text:
#ifndef TALK_MEDIA_BASE_MEDIAENGINE_H_
#define TALK_MEDIA_BASE_MEDIAENGINE_H_

#ifdef OSX
#include <CoreAudio/CoreAudio.h>
#endif

#include <limits.h>

#include <string>
#include <vector>

#include "talk/media/base/codec.h"
#include "talk/media/base/mediachannel.h"
#include "talk/media/base/mediacommon.h"
#include "talk/media/base/videocapturer.h"
#include "talk/media/base/videocommon.h"
#include "talk/media/base/videoprocessor.h"
#include "talk/media/base/voiceprocessor.h"
#include "talk/media/devices/devicemanager.h"
#include "webrtc/base/fileutils.h"
#include "webrtc/base/sigslotrepeater.h"

#if defined(GOOGLE_CHROME_BUILD) || defined(CHROMIUM_BUILD)
#define DISABLE_MEDIA_ENGINE_FACTORY
#endif

namespace cricket {

class VideoCapturer;

// MediaEngineInterface is an abstraction of a media engine which can be
// subclassed to support different media componentry backends.
// It supports voice and video operations in the same class to facilitate
// proper synchronization between both media types.
class MediaEngineInterface {
 public:
  // Default value to be used for SetAudioDelayOffset().
  static const int kDefaultAudioDelayOffset;

  virtual ~MediaEngineInterface() {}

  // Initialization
  // Starts the engine.
  virtual bool Init(rtc::Thread* worker_thread) = 0;
  // Shuts down the engine.
  virtual void Terminate() = 0;
  // Returns what the engine is capable of, as a set of Capabilities, above.
  virtual int GetCapabilities() = 0;

  // MediaChannel creation
  // Creates a voice media channel. Returns NULL on failure.
  virtual VoiceMediaChannel *CreateChannel() = 0;
  // Creates a video media channel, paired with the specified voice channel.
  // Returns NULL on failure.
  virtual VideoMediaChannel* CreateVideoChannel(
      const VideoOptions& options,
      VoiceMediaChannel* voice_media_channel) = 0;

  // Creates a soundclip object for playing sounds on. Returns NULL on failure.
  virtual SoundclipMedia *CreateSoundclip() = 0;

  // Configuration
  // Gets global audio options.
  virtual AudioOptions GetAudioOptions() const = 0;
  // Sets global audio options. "options" are from AudioOptions, above.
  virtual bool SetAudioOptions(const AudioOptions& options) = 0;
  // Sets the value used by the echo canceller to offset delay values obtained
  // from the OS.
  virtual bool SetAudioDelayOffset(int offset) = 0;
  // Sets the default (maximum) codec/resolution and encoder option to capture
  // and encode video.
  virtual bool SetDefaultVideoEncoderConfig(const VideoEncoderConfig& config)
      = 0;

  // Device selection
  // TODO(tschmelcher): Add method for selecting the soundclip device.
  virtual bool SetSoundDevices(const Device* in_device,
                               const Device* out_device) = 0;

  // Device configuration
  // Gets the current speaker volume, as a value between 0 and 255.
  virtual bool GetOutputVolume(int* level) = 0;
  // Sets the current speaker volume, as a value between 0 and 255.
  virtual bool SetOutputVolume(int level) = 0;

  // Local monitoring
  // Gets the current microphone level, as a value between 0 and 10.
  virtual int GetInputLevel() = 0;
  // Starts or stops the local microphone. Useful if local mic info is needed
  // prior to a call being connected; the mic will be started automatically
  // when a VoiceMediaChannel starts sending.
  virtual bool SetLocalMonitor(bool enable) = 0;
  // Installs a callback for raw frames from the local camera.

  virtual const std::vector<AudioCodec>& audio_codecs() = 0;
  virtual const std::vector<RtpHeaderExtension>&
      audio_rtp_header_extensions() = 0;
  virtual const std::vector<VideoCodec>& video_codecs() = 0;
  virtual const std::vector<RtpHeaderExtension>&
      video_rtp_header_extensions() = 0;

  // Logging control
  virtual void SetVoiceLogging(int min_sev, const char* filter) = 0;
  virtual void SetVideoLogging(int min_sev, const char* filter) = 0;

  // Starts AEC dump using existing file.
  virtual bool StartAecDump(rtc::PlatformFile file) = 0;

  // Voice processors for effects.
  virtual bool RegisterVoiceProcessor(uint32 ssrc,
                                      VoiceProcessor* video_processor,
                                      MediaProcessorDirection direction) = 0;
  virtual bool UnregisterVoiceProcessor(uint32 ssrc,
                                        VoiceProcessor* video_processor,
                                        MediaProcessorDirection direction) = 0;
};

#if !defined(DISABLE_MEDIA_ENGINE_FACTORY)
class MediaEngineFactory {
 public:
  typedef cricket::MediaEngineInterface* (*MediaEngineCreateFunction)();
  // Creates a media engine, using either the compiled system default or the
  // creation function specified in SetCreateFunction, if specified.
  static MediaEngineInterface* Create();
  // Sets the function used when calling Create. If unset, the compiled system
  // default will be used. Returns the old create function, or NULL if one
  // wasn't set. Likewise, NULL can be used as the |function| parameter to
  // reset to the default behavior.
  static MediaEngineCreateFunction SetCreateFunction(
      MediaEngineCreateFunction function);
 private:
  static MediaEngineCreateFunction create_function_;
};
#endif

// CompositeMediaEngine constructs a MediaEngine from separate
// voice and video engine classes.
template<class VOICE, class VIDEO>
class CompositeMediaEngine : public MediaEngineInterface {
 public:
  CompositeMediaEngine() : video_(&voice_) {}
  virtual ~CompositeMediaEngine() {}
  virtual bool Init(rtc::Thread* worker_thread) {
    if (!voice_.Init(worker_thread))
      return false;
    if (!video_.Init(worker_thread)) {
      voice_.Terminate();
      return false;
    }
    return true;
  }
  virtual void Terminate() {
    video_.Terminate();
    voice_.Terminate();
  }

  virtual int GetCapabilities() {
    return (voice_.GetCapabilities() | video_.GetCapabilities());
  }
  virtual VoiceMediaChannel *CreateChannel() {
    return voice_.CreateChannel();
  }
  virtual VideoMediaChannel* CreateVideoChannel(const VideoOptions& options,
                                                VoiceMediaChannel* channel) {
    return video_.CreateChannel(options, channel);
  }
  virtual SoundclipMedia *CreateSoundclip() {
    return voice_.CreateSoundclip();
  }

  virtual AudioOptions GetAudioOptions() const {
    return voice_.GetOptions();
  }
  virtual bool SetAudioOptions(const AudioOptions& options) {
    return voice_.SetOptions(options);
  }
  virtual bool SetAudioDelayOffset(int offset) {
    return voice_.SetDelayOffset(offset);
  }
  virtual bool SetDefaultVideoEncoderConfig(const VideoEncoderConfig& config) {
    return video_.SetDefaultEncoderConfig(config);
  }

  virtual bool SetSoundDevices(const Device* in_device,
                               const Device* out_device) {
    return voice_.SetDevices(in_device, out_device);
  }

  virtual bool GetOutputVolume(int* level) {
    return voice_.GetOutputVolume(level);
  }
  virtual bool SetOutputVolume(int level) {
    return voice_.SetOutputVolume(level);
  }

  virtual int GetInputLevel() {
    return voice_.GetInputLevel();
  }
  virtual bool SetLocalMonitor(bool enable) {
    return voice_.SetLocalMonitor(enable);
  }
  virtual const std::vector<AudioCodec>& audio_codecs() {
    return voice_.codecs();
  }
  virtual const std::vector<RtpHeaderExtension>& audio_rtp_header_extensions() {
    return voice_.rtp_header_extensions();
  }
  virtual const std::vector<VideoCodec>& video_codecs() {
    return video_.codecs();
  }
  virtual const std::vector<RtpHeaderExtension>& video_rtp_header_extensions() {
    return video_.rtp_header_extensions();
  }

  virtual void SetVoiceLogging(int min_sev, const char* filter) {
    voice_.SetLogging(min_sev, filter);
  }
  virtual void SetVideoLogging(int min_sev, const char* filter) {
    video_.SetLogging(min_sev, filter);
  }

  virtual bool StartAecDump(rtc::PlatformFile file) {
    return voice_.StartAecDump(file);
  }

  virtual bool RegisterVoiceProcessor(uint32 ssrc,
                                      VoiceProcessor* processor,
                                      MediaProcessorDirection direction) {
    return voice_.RegisterProcessor(ssrc, processor, direction);
  }
  virtual bool UnregisterVoiceProcessor(uint32 ssrc,
                                        VoiceProcessor* processor,
                                        MediaProcessorDirection direction) {
    return voice_.UnregisterProcessor(ssrc, processor, direction);
  }

 protected:
  VOICE voice_;
  VIDEO video_;
};

// NullVoiceEngine can be used with CompositeMediaEngine in the case where only
// a video engine is desired.
class NullVoiceEngine {
 public:
  bool Init(rtc::Thread* worker_thread) { return true; }
  void Terminate() {}
  int GetCapabilities() { return 0; }
  // If you need this to return an actual channel, use FakeMediaEngine instead.
  VoiceMediaChannel* CreateChannel() {
    return NULL;
  }
  SoundclipMedia* CreateSoundclip() {
    return NULL;
  }
  bool SetDelayOffset(int offset) { return true; }
  AudioOptions GetOptions() const { return AudioOptions(); }
  bool SetOptions(const AudioOptions& options) { return true; }
  bool SetDevices(const Device* in_device, const Device* out_device) {
    return true;
  }
  bool GetOutputVolume(int* level) {
    *level = 0;
    return true;
  }
  bool SetOutputVolume(int level) { return true; }
  int GetInputLevel() { return 0; }
  bool SetLocalMonitor(bool enable) { return true; }
  const std::vector<AudioCodec>& codecs() { return codecs_; }
  const std::vector<RtpHeaderExtension>& rtp_header_extensions() {
    return rtp_header_extensions_;
  }
  void SetLogging(int min_sev, const char* filter) {}
  bool StartAecDump(rtc::PlatformFile file) { return false; }
  bool RegisterProcessor(uint32 ssrc,
                         VoiceProcessor* voice_processor,
                         MediaProcessorDirection direction) { return true; }
  bool UnregisterProcessor(uint32 ssrc,
                           VoiceProcessor* voice_processor,
                           MediaProcessorDirection direction) { return true; }

 private:
  std::vector<AudioCodec> codecs_;
  std::vector<RtpHeaderExtension> rtp_header_extensions_;
};

// NullVideoEngine can be used with CompositeMediaEngine in the case where only
// a voice engine is desired.
class NullVideoEngine {
 public:
  bool Init(rtc::Thread* worker_thread) { return true; }
  void Terminate() {}
  int GetCapabilities() { return 0; }
  // If you need this to return an actual channel, use FakeMediaEngine instead.
  VideoMediaChannel* CreateChannel(
      const VideoOptions& options,
      VoiceMediaChannel* voice_media_channel) {
    return NULL;
  }
  bool SetOptions(const VideoOptions& options) { return true; }
  bool SetDefaultEncoderConfig(const VideoEncoderConfig& config) {
    return true;
  }
  const std::vector<VideoCodec>& codecs() { return codecs_; }
  const std::vector<RtpHeaderExtension>& rtp_header_extensions() {
    return rtp_header_extensions_;
  }
  void SetLogging(int min_sev, const char* filter) {}

 private:
  std::vector<VideoCodec> codecs_;
  std::vector<RtpHeaderExtension> rtp_header_extensions_;
};

typedef CompositeMediaEngine<NullVoiceEngine, NullVideoEngine> NullMediaEngine;

enum DataChannelType {
  DCT_NONE = 0,
  DCT_RTP = 1,
  DCT_SCTP = 2
};

class DataEngineInterface {
 public:
  virtual ~DataEngineInterface() {}
  virtual DataMediaChannel* CreateChannel(DataChannelType type) = 0;
  virtual const std::vector<DataCodec>& data_codecs() = 0;
};

}  // namespace cricket

#endif  // TALK_MEDIA_BASE_MEDIAENGINE_H_


text:
using Microsoft.Extensions.DependencyInjection;
using Networker.Client.Abstractions;
using Networker.Common.Abstractions;
using Networker.Server.Abstractions;

namespace Networker.Extensions.ProtobufNet
{
	public static class ProtoBufNetBuilderExtension
	{
		public static IServerBuilder UseProtobufNet(this IServerBuilder serverBuilder)
		{
			var serviceCollection = serverBuilder.GetServiceCollection();
			serviceCollection.AddSingleton<IPacketSerialiser, ProtoBufNetSerialiser>();

			return serverBuilder;
		}

		public static IClientBuilder UseProtobufNet(this IClientBuilder clientBuilder)
		{
			var serviceCollection = clientBuilder.GetServiceCollection();
			serviceCollection.AddSingleton<IPacketSerialiser, ProtoBufNetSerialiser>();
			return clientBuilder;
		}
	}
}

redpajama_set_name: RedPajamaGithub


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

// Example for how to use file_based_test_driver to run tests that support test
// modes. The operation being tested is to sum a bunch of comma separated
// numbers (similar to example_test.cc). We use mode_a_results/mode_b_results to
// overwrite the results for different test modes.

#include <string>
#include <vector>

#include "file_based_test_driver/base/path.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/container/node_hash_map.h"
#include "absl/functional/bind_front.h"
#include "absl/status/status.h"
#include "absl/strings/match.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "file_based_test_driver/base/status_matchers.h"
#include "file_based_test_driver/file_based_test_driver.h"
#include "file_based_test_driver/test_case_mode.h"
#include "file_based_test_driver/test_case_options.h"
#include "file_based_test_driver/base/status.h"
#include "file_based_test_driver/base/status_macros.h"

namespace {

using file_based_test_driver::RunTestCaseWithModesResult;
using file_based_test_driver::TestCaseMode;

// The test fixture
class ExampleTestWithModes : public ::testing::Test {
 public:
  //
  // OPTION NAMES
  //
  // String Prefix to print before the result.
  static inline constexpr absl::string_view kResultPrefixOption =
      "result_prefix";

  // If set, flags the test suite to ignore the result.
  static inline constexpr absl::string_view kIgnoreThisTestOption =
      "ignore_this_test";

  // If set, return the specified results for the test mode. The format is
  // <result type1>:<output1>,<result type2>:<output2>,...
  static inline constexpr absl::string_view kModeAResultOption =
      "mode_a_results";
  static inline constexpr absl::string_view kModeBResultOption =
      "mode_b_results";

  ExampleTestWithModes() {
    options_.RegisterString(kResultPrefixOption, "The result is: ");
    options_.RegisterBool(kIgnoreThisTestOption, false);
    options_.RegisterString(kModeAResultOption, "");
    options_.RegisterString(kModeBResultOption, "");
  }

  // Callback for running a single test case. This example sums a series of
  // comma separated integers, and applies some transformations on it based on
  // test options. Test inputs that start with an empty line are copied to the
  // output with an added *second* line saying "INSERTED SECOND LINE".
  void RunExampleTestCase(const TestCaseMode& test_mode,
                          absl::string_view test_mode_option_name,
                          absl::string_view test_case,
                          RunTestCaseWithModesResult* test_result) {
    // Parse and strip off the test case's options.
    std::string test_case_without_options = std::string(test_case);
    const absl::Status options_status =
        options_.ParseTestCaseOptions(&test_case_without_options);
    if (!options_status.ok()) {
      // For bad test cases, prefer to return an error in the output instead
      // of crashing.
      FILE_BASED_TEST_DRIVER_CHECK_OK(test_result->mutable_test_case_outputs()->RecordOutput(
          TestCaseMode(test_mode), "ERROR",
          absl::StrCat("Failed to parse options: ",
                       options_status.ToString())));
      return;
    }

    // Ignore? Then return straight away. The test driver will copy the entire
    // test case verbatim.
    if (options_.GetBool(kIgnoreThisTestOption)) {
      test_result->set_ignore_test_output(true);
      return;
    }

    // Special case: anything starting with \n gets special treatment. (This is
    // used to show how blank lines are handled using escaping.)
    if (absl::StartsWith(test_case, "\n")) {
      // Return the test output through <test_result>.
      FILE_BASED_TEST_DRIVER_CHECK_OK(test_result->mutable_test_case_outputs()->RecordOutput(
          TestCaseMode(test_mode), "" /* result_type */,
          absl::StrCat("\nINSERTED SECOND LINE\n", test_case.substr(1))));
      return;
    }

    // The actual test. A real test would of course call into some other
    // function that is to be tested.
    const std::vector<std::string> number_strings =
        absl::StrSplit(test_case_without_options, ",", absl::SkipEmpty());
    int64_t sum = 0;
    for (const std::string& number_string : number_strings) {
      int64_t number = 0;
      if (!absl::SimpleAtoi(number_string, &number)) {
        // For bad test cases, prefer to return an error in the output instead
        // of crashing.
        FILE_BASED_TEST_DRIVER_CHECK_OK(test_result->mutable_test_case_outputs()->RecordOutput(
            TestCaseMode(test_mode), "ERROR",
            absl::StrCat("Failed to parse ", number_string)));
        return;
      }
      sum += number;
    }

    const std::string mode_result = options_.GetString(test_mode_option_name);

    // Return the outputs specified in the options.
    const absl::node_hash_map<std::string, std::string> mode_results =
        ExtractOutputs(mode_result);
    for (const auto& result : mode_results) {
      FILE_BASED_TEST_DRIVER_CHECK_OK(test_result->mutable_test_case_outputs()->RecordOutput(
                   TestCaseMode(test_mode), result.first, result.second));
    }
    // Return the default main output (the sum) if it's not specified in the
    // options.
    if (!file_based_test_driver_base::ContainsKey(mode_results, "")) {
      const std::string result_string =
          absl::StrCat(options_.GetString(kResultPrefixOption), sum);
      FILE_BASED_TEST_DRIVER_CHECK_OK(test_result->mutable_test_case_outputs()->RecordOutput(
                   TestCaseMode(test_mode), "", result_string));
    }
  }

 protected:
  file_based_test_driver::TestCaseOptions options_;
  std::string test_dir_;

 private:
  // Extracts the outputs from the option.
  absl::node_hash_map<std::string, std::string> ExtractOutputs(
      const std::string& result_str) {
    absl::node_hash_map<std::string, std::string> result_type_to_output_map;
    const std::vector<std::string> result_list =
        absl::StrSplit(result_str, ",", absl::SkipEmpty());
    for (const std::string& result : result_list) {
      const std::vector<std::string> output =
          absl::StrSplit(result, ":", absl::SkipEmpty());
      if (output.size() == 1) {
        file_based_test_driver_base::InsertIfNotPresent(&result_type_to_output_map, "", output[0]);
      } else if (output.size() == 2) {
        file_based_test_driver_base::InsertIfNotPresent(&result_type_to_output_map, output[0],
                                output[1]);
      }
    }
    return result_type_to_output_map;
  }
};

inline std::string TestDir() {
  return file_based_test_driver_base::AddSlash(
      file_based_test_driver_base::JoinPath(
          getenv("TEST_SRCDIR"),
          "com_google_file_based_test_driver/file_based_test_driver"));
}

// Run test cases from example_with_modes.test.
TEST_F(ExampleTestWithModes, RunExampleTestModeA) {
  const std::string filespec =
      file_based_test_driver_base::JoinPath(TestDir(), "example_with_modes.test");
  FILE_BASED_TEST_DRIVER_ASSERT_OK_AND_ASSIGN(
      TestCaseMode mode,
      TestCaseMode::Create(std::vector<std::string>({"MODE", "A"})));
  EXPECT_TRUE(RunTestCasesWithModesFromFiles(
      filespec, absl::bind_front(&ExampleTestWithModes::RunExampleTestCase,
                                 this, mode, kModeAResultOption)));
}

TEST_F(ExampleTestWithModes, RunExampleTestModeB) {
  const std::string filespec =
      file_based_test_driver_base::JoinPath(TestDir(), "example_with_modes.test");
  FILE_BASED_TEST_DRIVER_ASSERT_OK_AND_ASSIGN(
      TestCaseMode mode,
      TestCaseMode::Create(std::vector<std::string>({"MODE", "B"})));
  EXPECT_TRUE(RunTestCasesWithModesFromFiles(
      filespec, absl::bind_front(&ExampleTestWithModes::RunExampleTestCase,
                                 this, mode, kModeBResultOption)));
}

TEST_F(ExampleTestWithModes, CountTestCasesInFiles) {
  const std::string filespec =
      file_based_test_driver_base::JoinPath(TestDir(), "example_with_modes.test");
  EXPECT_EQ(file_based_test_driver::CountTestCasesInFiles(filespec), 13);
}

}  // anonymous namespace


text:
package crypto

import (
	"bytes"
	"encoding/base64"
	"errors"
	"fmt"
	"io"

	"crypto/elliptic"
	"crypto/hmac"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha1"
	"crypto/sha256"
	"crypto/sha512"
	"hash"

	pb "gx/ipfs/QmPGxZ1DP2w45WcogpW1h43BvseXbfke9N91qotpoQcUeS/go-libp2p-crypto/pb"
	mh "gx/ipfs/QmbZ6Cee2uHjG7hf19qLHppgKDRtaG4CVtMzdmK9VCVqLu/go-multihash"

	proto "gx/ipfs/QmZ4Qi3GaRbjcx28Sme5eMH7RQjGkt8wHxt2a65oLaeFEV/gogo-protobuf/proto"
)

var ErrBadKeyType = errors.New("invalid or unsupported key type")

const (
	RSA = iota
	Ed25519
	Secp256k1
)

// Key represents a crypto key that can be compared to another key
type Key interface {
	// Bytes returns a serialized, storeable representation of this key
	Bytes() ([]byte, error)

	// Hash returns the hash of this key
	Hash() ([]byte, error)

	// Equals checks whether two PubKeys are the same
	Equals(Key) bool
}

// PrivKey represents a private key that can be used to generate a public key,
// sign data, and decrypt data that was encrypted with a public key
type PrivKey interface {
	Key

	// Cryptographically sign the given bytes
	Sign([]byte) ([]byte, error)

	// Return a public key paired with this private key
	GetPublic() PubKey
}

type PubKey interface {
	Key

	// Verify that 'sig' is the signed hash of 'data'
	Verify(data []byte, sig []byte) (bool, error)
}

// Given a public key, generates the shared key.
type GenSharedKey func([]byte) ([]byte, error)

func GenerateKeyPair(typ, bits int) (PrivKey, PubKey, error) {
	return GenerateKeyPairWithReader(typ, bits, rand.Reader)
}

// Generates a keypair of the given type and bitsize
func GenerateKeyPairWithReader(typ, bits int, src io.Reader) (PrivKey, PubKey, error) {
	switch typ {
	case RSA:
		priv, err := rsa.GenerateKey(src, bits)
		if err != nil {
			return nil, nil, err
		}
		pk := &priv.PublicKey
		return &RsaPrivateKey{sk: priv}, &RsaPublicKey{pk}, nil
	case Ed25519:
		return GenerateEd25519Key(src)
	case Secp256k1:
		return GenerateSecp256k1Key(src)
	default:
		return nil, nil, ErrBadKeyType
	}
}

// Generates an ephemeral public key and returns a function that will compute
// the shared secret key.  Used in the identify module.
//
// Focuses only on ECDH now, but can be made more general in the future.
func GenerateEKeyPair(curveName string) ([]byte, GenSharedKey, error) {
	var curve elliptic.Curve

	switch curveName {
	case "P-256":
		curve = elliptic.P256()
	case "P-384":
		curve = elliptic.P384()
	case "P-521":
		curve = elliptic.P521()
	}

	priv, x, y, err := elliptic.GenerateKey(curve, rand.Reader)
	if err != nil {
		return nil, nil, err
	}

	pubKey := elliptic.Marshal(curve, x, y)

	done := func(theirPub []byte) ([]byte, error) {
		// Verify and unpack node's public key.
		x, y := elliptic.Unmarshal(curve, theirPub)
		if x == nil {
			return nil, fmt.Errorf("Malformed public key: %d %v", len(theirPub), theirPub)
		}

		if !curve.IsOnCurve(x, y) {
			return nil, errors.New("Invalid public key.")
		}

		// Generate shared secret.
		secret, _ := curve.ScalarMult(x, y, priv)

		return secret.Bytes(), nil
	}

	return pubKey, done, nil
}

type StretchedKeys struct {
	IV        []byte
	MacKey    []byte
	CipherKey []byte
}

// Generates a set of keys for each party by stretching the shared key.
// (myIV, theirIV, myCipherKey, theirCipherKey, myMACKey, theirMACKey)
func KeyStretcher(cipherType string, hashType string, secret []byte) (StretchedKeys, StretchedKeys) {
	var cipherKeySize int
	var ivSize int
	switch cipherType {
	case "AES-128":
		ivSize = 16
		cipherKeySize = 16
	case "AES-256":
		ivSize = 16
		cipherKeySize = 32
	case "Blowfish":
		ivSize = 8
		// Note: 24 arbitrarily selected, needs more thought
		cipherKeySize = 32
	}

	hmacKeySize := 20

	seed := []byte("key expansion")

	result := make([]byte, 2*(ivSize+cipherKeySize+hmacKeySize))

	var h func() hash.Hash

	switch hashType {
	case "SHA1":
		h = sha1.New
	case "SHA256":
		h = sha256.New
	case "SHA512":
		h = sha512.New
	default:
		panic("Unrecognized hash function, programmer error?")
	}

	m := hmac.New(h, secret)
	m.Write(seed)

	a := m.Sum(nil)

	j := 0
	for j < len(result) {
		m.Reset()
		m.Write(a)
		m.Write(seed)
		b := m.Sum(nil)

		todo := len(b)

		if j+todo > len(result) {
			todo = len(result) - j
		}

		copy(result[j:j+todo], b)

		j += todo

		m.Reset()
		m.Write(a)
		a = m.Sum(nil)
	}

	half := len(result) / 2
	r1 := result[:half]
	r2 := result[half:]

	var k1 StretchedKeys
	var k2 StretchedKeys

	k1.IV = r1[0:ivSize]
	k1.CipherKey = r1[ivSize : ivSize+cipherKeySize]
	k1.MacKey = r1[ivSize+cipherKeySize:]

	k2.IV = r2[0:ivSize]
	k2.CipherKey = r2[ivSize : ivSize+cipherKeySize]
	k2.MacKey = r2[ivSize+cipherKeySize:]

	return k1, k2
}

// UnmarshalPublicKey converts a protobuf serialized public key into its
// representative object
func UnmarshalPublicKey(data []byte) (PubKey, error) {
	pmes := new(pb.PublicKey)
	err := proto.Unmarshal(data, pmes)
	if err != nil {
		return nil, err
	}

	switch pmes.GetType() {
	case pb.KeyType_RSA:
		return UnmarshalRsaPublicKey(pmes.GetData())
	case pb.KeyType_Ed25519:
		var pubk [32]byte
		copy(pubk[:], pmes.Data)
		return &Ed25519PublicKey{&pubk}, nil
	case pb.KeyType_Secp256k1:
		return UnmarshalSecp256k1PublicKey(pmes.GetData())
	default:
		return nil, ErrBadKeyType
	}
}

// MarshalPublicKey converts a public key object into a protobuf serialized
// public key
func MarshalPublicKey(k PubKey) ([]byte, error) {
	return k.Bytes()
}

// UnmarshalPrivateKey converts a protobuf serialized private key into its
// representative object
func UnmarshalPrivateKey(data []byte) (PrivKey, error) {
	pmes := new(pb.PrivateKey)
	err := proto.Unmarshal(data, pmes)
	if err != nil {
		return nil, err
	}

	switch pmes.GetType() {
	case pb.KeyType_RSA:
		return UnmarshalRsaPrivateKey(pmes.GetData())
	case pb.KeyType_Ed25519:
		return UnmarshalEd25519PrivateKey(pmes.GetData())
	case pb.KeyType_Secp256k1:
		return UnmarshalSecp256k1PrivateKey(pmes.GetData())
	default:
		return nil, ErrBadKeyType
	}
}

// MarshalPrivateKey converts a key object into its protobuf serialized form.
func MarshalPrivateKey(k PrivKey) ([]byte, error) {

	switch k.(type) {
	case *Ed25519PrivateKey:
		return k.Bytes()
	case *RsaPrivateKey:
		return k.Bytes()
	default:
		return nil, ErrBadKeyType
	}
}

// ConfigDecodeKey decodes from b64 (for config file), and unmarshals.
func ConfigDecodeKey(b string) ([]byte, error) {
	return base64.StdEncoding.DecodeString(b)
}

// ConfigEncodeKey encodes to b64 (for config file), and marshals.
func ConfigEncodeKey(b []byte) string {
	return base64.StdEncoding.EncodeToString(b)
}

// KeyEqual checks whether two
func KeyEqual(k1, k2 Key) bool {
	if k1 == k2 {
		return true
	}

	b1, err1 := k1.Bytes()
	b2, err2 := k2.Bytes()
	return bytes.Equal(b1, b2) && err1 == err2
}

// KeyHash hashes a key.
func KeyHash(k Key) ([]byte, error) {
	kb, err := k.Bytes()
	if err != nil {
		return nil, err
	}

	h, _ := mh.Sum(kb, mh.SHA2_256, -1)
	return []byte(h), nil
}


text:
namespace SQLServerSearcher
{
    partial class FrmChangelog
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmChangelog));
            this.txtChangelog = new System.Windows.Forms.TextBox();
            this.btnClose = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // txtChangelog
            //
            this.txtChangelog.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.txtChangelog.BackColor = System.Drawing.SystemColors.Control;
            this.txtChangelog.BorderStyle = System.Windows.Forms.BorderStyle.None;
            this.txtChangelog.Location = new System.Drawing.Point(13, 13);
            this.txtChangelog.Multiline = true;
            this.txtChangelog.Name = "txtChangelog";
            this.txtChangelog.ReadOnly = true;
            this.txtChangelog.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.txtChangelog.Size = new System.Drawing.Size(539, 305);
            this.txtChangelog.TabIndex = 0;
            //
            // btnClose
            //
            this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.btnClose.Location = new System.Drawing.Point(469, 324);
            this.btnClose.Name = "btnClose";
            this.btnClose.Size = new System.Drawing.Size(86, 33);
            this.btnClose.TabIndex = 1;
            this.btnClose.Text = "&Close";
            this.btnClose.UseVisualStyleBackColor = true;
            //
            // FrmChangelog
            //
            this.AcceptButton = this.btnClose;
            this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.CancelButton = this.btnClose;
            this.ClientSize = new System.Drawing.Size(564, 369);
            this.Controls.Add(this.btnClose);
            this.Controls.Add(this.txtChangelog);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "FrmChangelog";
            this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
            this.Text = "Changelog";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FrmChangelog_FormClosing);
            this.Load += new System.EventHandler(this.FrmChangelog_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox txtChangelog;
        private System.Windows.Forms.Button btnClose;
    }
}


text:
package sk.svantner.idea.doctrineplugin.config.annotation;

import com.intellij.codeInsight.completion.CompletionParameters;
import com.intellij.codeInsight.completion.CompletionProvider;
import com.intellij.codeInsight.completion.CompletionResultSet;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.util.ProcessingContext;
import com.jetbrains.php.lang.documentation.phpdoc.parser.PhpDocElementTypes;
import com.jetbrains.php.lang.parser.PhpElementTypes;
import com.jetbrains.php.lang.psi.elements.PhpPsiElement;
import org.jetbrains.annotations.NotNull;
import sk.svantner.idea.doctrineplugin.config.doctrine.DoctrineStaticTypeLookupBuilder;

/**
 * Provides keywords to be auto-completed
 * @author Ing. Jan Svantner <posta.janci@gmail.com>
 */
public class KeywordCompletionProvider extends CompletionProvider<CompletionParameters> {

    @Override
    protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {

        PsiElement element = completionParameters.getPosition().getOriginalElement();
        PsiElement nextSibling = element.getParent().getNextSibling();

        PhpPsiElement nextNextSibling = null;
        if(nextSibling != null && nextSibling.getNextSibling() != null){
            nextNextSibling = (PhpPsiElement) nextSibling.getNextSibling();
            ASTNode siblingNode = (nextNextSibling !=null)? nextNextSibling.getNode():null;

            if ( siblingNode!=null && nextNextSibling.getNode().getElementType() == PhpElementTypes.CLASS_FIELDS ){
                handleFieldComment(element, completionResultSet);
            }

            if ( siblingNode!=null && nextNextSibling.getNode().getElementType() == PhpDocElementTypes.phpDocTagValue){
                handleFieldCommentValue(element.getParent().getParent(), completionResultSet);
            }

        }
    }

    private void handleFieldComment(PsiElement element, CompletionResultSet completionResultSet){
        completionResultSet.addAllElements(
            new DoctrineStaticTypeLookupBuilder(DoctrineStaticTypeLookupBuilder.InsertHandler.Annotations).getOrmFieldAnnotations());
    }

    private void handleFieldCommentValue(PsiElement element, CompletionResultSet completionResultSet){
        String text = element.getNode().getText();

        if(text.startsWith("@ORM\\OneToOne"))
            completionResultSet.addAllElements( new DoctrineStaticTypeLookupBuilder(DoctrineStaticTypeLookupBuilder.InsertHandler.Annotations)
                    .getAssociationMapping(DoctrineStaticTypeLookupBuilder.Association.oneToOne));
        if(text.startsWith("@ORM\\OneToMany"))
            completionResultSet.addAllElements( new DoctrineStaticTypeLookupBuilder(DoctrineStaticTypeLookupBuilder.InsertHandler.Annotations)
                    .getAssociationMapping(DoctrineStaticTypeLookupBuilder.Association.oneToMany));
        if(text.startsWith("@ORM\\ManyToOne"))
            completionResultSet.addAllElements( new DoctrineStaticTypeLookupBuilder(DoctrineStaticTypeLookupBuilder.InsertHandler.Annotations)
                    .getAssociationMapping(DoctrineStaticTypeLookupBuilder.Association.manyToOne));
        if(text.startsWith("@ORM\\ManyToMany"))
            completionResultSet.addAllElements( new DoctrineStaticTypeLookupBuilder(DoctrineStaticTypeLookupBuilder.InsertHandler.Annotations)
                    .getAssociationMapping(DoctrineStaticTypeLookupBuilder.Association.manyToMany));
        if(text.startsWith("@ORM\\Column"))
            completionResultSet.addAllElements( new DoctrineStaticTypeLookupBuilder(DoctrineStaticTypeLookupBuilder.InsertHandler.Annotations)
                    .getPropertyMappings());
    }
}


text:
from . import formats
from . import messages
from grow.common import utils
from grow.pods import locales
from grow.pods import urls
import datetime
import json
import logging
import os
import re

class Error(Exception):
    pass

class PathFormatError(Error, ValueError):
    pass

class DocumentDoesNotExistError(Error, ValueError):
    pass

class DocumentExistsError(Error, ValueError):
    pass

class BadLocalesError(Error, ValueError):
    pass

class Document(object):

    def __init__(self, pod_path, _pod, locale=None, _collection=None):
        self._locale_kwarg = locale
        utils.validate_name(pod_path)
        self.pod_path = pod_path
        self.root_pod_path = pod_path  # For multi-file localization.
        self.basename = Document._clean_basename(pod_path)
        self.base, self.ext = os.path.splitext(self.basename)
        self.pod = _pod
        self.collection = _collection
        self.locale = self._init_locale(locale, pod_path)

    def __repr__(self):
        if self.locale:
            return "<Document({}, locale='{}')>".format(self.pod_path, self.locale)
        return "<Document({})>".format(self.pod_path)

    def __cmp__(self, other):
        return self.pod_path == other.pod_path and self.pod == other.pod

    def __ne__(self, other):
        return self.pod_path != other.pod_path or self.pod != other.pod

    def _init_locale(self, locale, pod_path):
        try:
            self.root_pod_path, locale_from_path = \
                formats.Format.parse_localized_path(pod_path)
            if locale_from_path:
                locale = locale_from_path
            return self.pod.normalize_locale(
                locale, default=self.default_locale)
        except IOError as exc:  # Document does not exist.
            if '[Errno 2] No such file or directory' in str(exc):
                return None
            else:
                raise

    def __eq__(self, other):
        return (isinstance(self, Document)
                and isinstance(other, Document)
                and self.pod_path == other.pod_path)

    def __getattr__(self, name):
        if name == 'locale':
            return self._locale_kwarg
        try:
            return self.fields[name]
        except KeyError:
            return object.__getattribute__(self, name)

    @classmethod
    def _clean_basename(cls, pod_path):
        pod_path, _ = formats.Format.parse_localized_path(pod_path)
        return os.path.basename(pod_path)

    @utils.cached_property
    def default_locale(self):
        if ('$localization' in self.fields
            and 'default_locale' in self.fields['$localization']):
            locale = self.fields['$localization']['default_locale']
        elif (self.collection.localization
              and 'default_locale' in self.collection.localization):
            locale = self.collection.localization['default_locale']
        else:
            locale = self.pod.podspec.default_locale
        locale = locales.Locale.parse(locale)
        if locale:
            locale.set_alias(self.pod)
        return locale

    @utils.cached_property
    def fields(self):
        tagged_fields = self.get_tagged_fields()
        fields = utils.untag_fields(tagged_fields)
        return {} if not fields else fields

    def get_tagged_fields(self):
        format = formats.Format.get(self)
        return format.fields

    @utils.cached_property
    def format(self):
        return formats.Format.get(self)

    @property
    def url(self):
        path = self.get_serving_path()
        if path:
            return urls.Url(
                path=path,
                host=self.pod.env.host,
                port=self.pod.env.port,
                scheme=self.pod.env.scheme)

    @property
    def slug(self):
        if '$slug' in self.fields:
            return self.fields['$slug']
        return utils.slugify(self.title) if self.title is not None else None

    @property
    def order(self):
        return self.fields.get('$order')

    @property
    def sitemap(self):
        return self.fields.get('$sitemap')

    @property
    def title(self):
        return self.fields.get('$title')

    def titles(self, title_name=None):
        if title_name is None:
            return self.title
        titles = self.fields.get('$titles', {})
        return titles.get(title_name, self.title)

    @property
    def category(self):
        return self.fields.get('$category')

    @property
    def date(self):
        return self.fields.get('$date')

    @property
    def view(self):
        view_format = self.fields.get('$view', self.collection.view)
        if view_format is not None:
            return self._format_path(view_format)

    def dates(self, date_name=None):
        if date_name is None:
            return self.date
        dates = self.fields.get('$dates', {})
        return dates.get(date_name, self.date)

    def delete(self):
        self.pod.delete_file(self.pod_path)

    @property
    def exists(self):
        return self.pod.file_exists(self.pod_path)

    def localize(self, locale):
        return self.collection.get_doc(self.root_pod_path, locale=locale)

    @property
    @utils.memoize
    def path_format(self):
        val = None
        if (self.locale
            and self.default_locale
            and self.locale != self.default_locale):
            if ('$localization' in self.fields
                and 'path' in self.fields['$localization']):
                val = self.fields['$localization']['path']
            elif self.collection.localization:
                val = self.collection.localization['path']
        if val is None:
            return self.fields.get('$path', self.collection.path_format)
        return val

    @property
    @utils.memoize
    def parent(self):
        if '$parent' not in self.fields:
            return None
        parent_pod_path = self.fields['$parent']
        return self.collection.get_doc(parent_pod_path, locale=self.locale)

    @utils.memoize
    def has_serving_path(self):
        return bool(self.path_format)

    @utils.memoize
    def get_serving_path(self):
        # Get root path.
        locale = str(self.locale)
        config = self.pod.get_podspec().get_config()
        root_path = config.get('flags', {}).get('root_path', '')
        if locale == self.default_locale:
            root_path = config.get('localization', {}).get('root_path', root_path)
        path_format = self.path_format
        if path_format is None:
            raise PathFormatError(
                'No path format found for {}. You must specify a path '
                'format in either the blueprint or the document.'.format(self))
        path_format = (path_format
                       .replace('<grow:locale>', '{locale}')
                       .replace('<grow:slug>', '{slug}'))

        # Prevent double slashes when combining root path and path format.
        if path_format.startswith('/') and root_path.endswith('/'):
            root_path = root_path[0:len(root_path) - 1]
        path_format = root_path + path_format

        # Handle default date formatting in the url.
        while '{date|' in path_format:
            re_date = r'({date\|(?P<date_format>[a-zA-Z0-9_%-]+)})'
            match = re.search(re_date, path_format)
            if match:
                formatted_date = self.date
                formatted_date = formatted_date.strftime(match.group('date_format'))
                path_format = (path_format[:match.start()] + formatted_date +
                               path_format[match.end():])
            else:
                # Does not match expected format, let the normal format attempt it.
                break

        # Handle the special formatting of dates in the url.
        while '{dates.' in path_format:
            re_dates = r'({dates\.(?P<date_name>\w+)(\|(?P<date_format>[a-zA-Z0-9_%-]+))?})'
            match = re.search(re_dates, path_format)
            if match:
                formatted_date = self.dates(match.group('date_name'))
                date_format = match.group('date_format') or '%Y-%m-%d'
                formatted_date = formatted_date.strftime(date_format)
                path_format = (path_format[:match.start()] + formatted_date +
                               path_format[match.end():])
            else:
                # Does not match expected format, let the normal format attempt it.
                break

        try:
            return self._format_path(path_format)
        except KeyError:
            logging.error('Error with path format: {}'.format(path_format))
            raise

    def _format_path(self, path_format):
        podspec = self.pod.get_podspec()
        locale = self.locale.alias if self.locale is not None else self.locale
        formatters = {
            'base': self.base,
            'category': self.category,
            'collection.basename': self.collection.basename,
            'collection.root': self.collection.root,
            'env.fingerpint': self.pod.env.fingerprint,
            'locale': locale,
            'parent': self.parent if self.parent else utils.DummyDict(),
            'root': podspec.root,
            'slug': self.slug,
        }
        if '{date' in path_format:
            if isinstance(self.date, datetime.datetime):
                formatters['date'] = self.date.date()
            else:
                formatters['date'] = self.date
        if '|lower' in path_format:
            for key, value in formatters.items():
                if isinstance(value, basestring):
                    formatters['{}|lower'.format(key)] = value.lower()
        return path_format.format(**formatters).replace('//', '/')

    @utils.cached_property
    def locales(self):
        localized = '$localization' in self.fields
        if localized and 'locales' in self.fields['$localization']:
            codes = self.fields['$localization']['locales']
            if codes is None:
                return []
            return locales.Locale.parse_codes(codes)
        if self.format.has_localized_parts:
            document_codes = self.format._locales_from_parts
            diff = set(document_codes) - set(self.collection.locales)
            if diff:
                text = '{} specified content for unconfigured locales: {}'
                text = text.format(self, diff)
                raise BadLocalesError(text)
        return self.collection.locales

    @property
    @utils.memoize
    def body(self):
        return self.format.body.decode('utf-8') if self.format.body else None

    @property
    def content(self):
        return self.format.content.decode('utf-8')

    @property
    def html(self):
        return self.format.html

    @property
    def hidden(self):
        return self.fields.get('$hidden', False)

    def next(self, docs=None):
        if docs is None:
            docs = self.collection.list_docs()
        for i, doc in enumerate(docs):
            if type(doc) != self.__class__:
                raise ValueError('Usage: {{doc.next(<docs>)}}.')
            if doc == self:
                n = i + 1
                if n == len(docs):
                    return None
                return docs[i + 1]

    def prev(self, docs=None):
        if docs is None:
            docs = self.collection.list_docs()
        for i, doc in enumerate(docs):
            if type(doc) != self.__class__:
                raise ValueError('Usage: {{doc.prev(<docs>)}}.')
            if doc == self:
                n = i - 1
                if n < 0:
                    return None
                return docs[i - 1]

    def to_message(self):
        message = messages.DocumentMessage()
        message.basename = self.basename
        message.pod_path = self.pod_path
        message.collection_path = self.collection.collection_path
        message.body = self.body
        message.content = self.content
        message.fields = json.dumps(self.fields, cls=utils.JsonEncoder)
        message.serving_path = self.get_serving_path()
        return message

    def write(self, fields=utils.SENTINEL, body=utils.SENTINEL):
        content = self.content if self.exists else ''
        new_content = formats.Format.update(content, fields=fields, body=body)
        self.pod.write_file(self.pod_path, new_content)

    def inject(self, fields=utils.SENTINEL, body=utils.SENTINEL):
        """Injects without updating the copy on the filesystem."""
        if fields != utils.SENTINEL:
            self.fields.update(fields)
        if body != utils.SENTINEL:
            self.format.body = body
        self.pod.logger.info('Injected -> {}'.format(self.pod_path))


text:
using System;
using System.Threading;
using System.Threading.Tasks;

namespace FBCore.Concurrency
{
    /// <summary>
    /// An <see cref="IExecutorService"/> that can schedule commands to run after
    /// a given delay, or to execute periodically.
    /// </summary>
    public interface IScheduledExecutorService : IExecutorService
    {
        /// <summary>
        /// Creates and executes a one-shot action that becomes enabled after the
        /// given delay.
        /// </summary>
        /// <remarks>
        /// The action will be submitted to the end of the event queue
        /// even if it is being submitted from the same queue Thread.
        /// </remarks>
        /// <param name="action">The action.</param>
        /// <param name="delay">The delay in milliseconds.</param>
        Task Schedule(Action action, long delay);

        /// <summary>
        /// Creates and executes a one-shot action that becomes enabled after
        /// the given delay.
        /// </summary>
        /// <remarks>
        /// The action will be submitted to the end of the event queue
        /// even if it is being submitted from the same queue Thread.
        /// </remarks>
        /// <param name="action">The action.</param>
        /// <param name="delay">The delay in milliseconds.</param>
        /// <param name="token">The cancellation token.</param>
        Task Schedule(Action action, long delay, CancellationToken token);

        /// <summary>
        /// Creates and executes a one-shot function that becomes enabled after
        /// the given delay.
        /// </summary>
        /// <remarks>
        /// The function will be submitted to the end of the event queue
        /// even if it is being submitted from the same queue Thread.
        /// </remarks>
        /// <typeparam name="T">Type of response.</typeparam>
        /// <param name="func">The action.</param>
        /// <param name="delay">The delay in milliseconds.</param>
        Task<T> Schedule<T>(Func<T> func, long delay);

        /// <summary>
        /// Creates and executes a one-shot function that becomes enabled after
        /// the given delay.
        /// </summary>
        /// <remarks>
        /// The function will be submitted to the end of the event queue
        /// even if it is being submitted from the same queue Thread.
        /// </remarks>
        /// <typeparam name="T">Type of response.</typeparam>
        /// <param name="func">The function.</param>
        /// <param name="delay">The delay in milliseconds.</param>
        /// <param name="token">The cancellation token.</param>
        Task<T> Schedule<T>(Func<T> func, long delay, CancellationToken token);
    }
}


text:
/*
 * OrderNewSingleRequest.h
 *
 * The new order message.
 */

#ifndef _OrderNewSingleRequest_H_
#define _OrderNewSingleRequest_H_

#include <string>
#include "Date.h"
#include "OrdSide.h"
#include "OrdType.h"
#include "TimeInForce.h"
#include <list>
#include "Object.h"

/** \defgroup Models Data Structures for API
 *  Classes containing all the Data Structures needed for calling/returned by API endpoints
 *
 */

namespace Tizen {
namespace ArtikCloud {

/*! \brief The new order message.
 *
 *  \ingroup Models
 *
 */

class OrderNewSingleRequest : public Object {
public:
	/*! \brief Constructor.
	 */
	OrderNewSingleRequest();
	OrderNewSingleRequest(char* str);

	/*! \brief Destructor.
	 */
	virtual ~OrderNewSingleRequest();

	/*! \brief Retrieve a string JSON representation of this class.
	 */
	char* toJson();

	/*! \brief Fills in members of this class from JSON string representing it.
	 */
	void fromJson(char* jsonStr);

	/*! \brief Get Exchange identifier used to identify the routing destination.
	 */
	std::string getExchangeId();

	/*! \brief Set Exchange identifier used to identify the routing destination.
	 */
	void setExchangeId(std::string  exchange_id);
	/*! \brief Get The unique identifier of the order assigned by the client.
	 */
	std::string getClientOrderId();

	/*! \brief Set The unique identifier of the order assigned by the client.
	 */
	void setClientOrderId(std::string  client_order_id);
	/*! \brief Get Exchange symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order.
	 */
	std::string getSymbolIdExchange();

	/*! \brief Set Exchange symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order.
	 */
	void setSymbolIdExchange(std::string  symbol_id_exchange);
	/*! \brief Get CoinAPI symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order.
	 */
	std::string getSymbolIdCoinapi();

	/*! \brief Set CoinAPI symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order.
	 */
	void setSymbolIdCoinapi(std::string  symbol_id_coinapi);
	/*! \brief Get Order quantity.
	 */
	long long getAmountOrder();

	/*! \brief Set Order quantity.
	 */
	void setAmountOrder(long long  amount_order);
	/*! \brief Get Order price.
	 */
	long long getPrice();

	/*! \brief Set Order price.
	 */
	void setPrice(long long  price);
	/*! \brief Get
	 */
	OrdSide getSide();

	/*! \brief Set
	 */
	void setSide(OrdSide  side);
	/*! \brief Get
	 */
	OrdType getOrderType();

	/*! \brief Set
	 */
	void setOrderType(OrdType  order_type);
	/*! \brief Get
	 */
	TimeInForce getTimeInForce();

	/*! \brief Set
	 */
	void setTimeInForce(TimeInForce  time_in_force);
	/*! \brief Get Expiration time. Conditionaly required for orders with time_in_force = `GOOD_TILL_TIME_EXCHANGE` or `GOOD_TILL_TIME_OEML`.
	 */
	Date getExpireTime();

	/*! \brief Set Expiration time. Conditionaly required for orders with time_in_force = `GOOD_TILL_TIME_EXCHANGE` or `GOOD_TILL_TIME_OEML`.
	 */
	void setExpireTime(Date  expire_time);
	/*! \brief Get Order execution instructions are documented in the separate section: EMS / Starter Guide / Order parameters / Execution instructions
	 */
	std::list<std::string> getExecInst();

	/*! \brief Set Order execution instructions are documented in the separate section: EMS / Starter Guide / Order parameters / Execution instructions
	 */
	void setExecInst(std::list <std::string> exec_inst);

private:
	std::string exchange_id;
	std::string client_order_id;
	std::string symbol_id_exchange;
	std::string symbol_id_coinapi;
	long long amount_order;
	long long price;
	OrdSide side;
	OrdType order_type;
	TimeInForce time_in_force;
	Date expire_time;
	std::list <std::string>exec_inst;
	void __init();
	void __cleanup();

};
}
}

#endif /* _OrderNewSingleRequest_H_ */


text:
from unittest import TestCase

from pyreport.reporter import Report

class TestUnicode(TestCase):
    def test_unicode_msg(self):
        report = Report()
        report.create_report()
        report.info(u'ñiet')
        assert report.finalize_report()


text:
``helper.datetime.time`` --- Manipulate time
============================================

.. warning::
   This package is not documented yet.

.. automodule:: dp_tornado.helper.datetime.time
    :members:
    :undoc-members:
    :show-inheritance:


text:
namespace clipr
{
    /// <summary>
    /// Indicates the range of argument values
    /// that may be parsed by the argument.
    /// </summary>
    public enum NumArgsConstraint
    {
        /// <summary>
        /// The parameter must provide exactly this number of arguments.
        /// </summary>
        Exactly = 0,

        /// <summary>
        /// The parameter allows either zero or one arguments. When specifying
        /// this constraint, you cannot also set NumArgs.
        /// </summary>
        Optional,

        /// <summary>
        /// The parameter must provide at least this number of arguments.
        /// </summary>
        AtLeast,

        /// <summary>
        /// The parameter must provide at most this number of arguments.
        /// </summary>
        AtMost
    }
}


text:
Subject: meta-sama5d4-xplained
URL: https://github.com/rzr/meta-sama5d4-xplained
Contact: https://dockr.eurogiciel.fr/blogs/embedded/qtwayland-sama5d4-xplained/

## USAGE ##

  url="https://github.com/rzr/meta-sama5d4-xplained"
  branch="dizzy"
  basename=$(basename -- "$url")
  git clone "$url" -b "$branch" && make demo V=1 -C "${basename}"


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

  angular.module('pnc.builds').component('pncBuildLink', {
    bindings: {
      build: '<',
      shortLink: '@'
    },
    transclude: true,
    templateUrl: 'builds/directives/pnc-build-link/pnc-build-link.html',
    controller: [Controller]
  });

  function Controller() {
    const $ctrl = this;

    // -- Controller API --

    // --------------------

    $ctrl.$onInit = function () {
      $ctrl.linkText = getLinkText();
    };

    function getLinkText() {
      if ($ctrl.shortLink === 'true') {
        return '#' + $ctrl.build.id;
      } else {
        return $ctrl.build.$canonicalName();
      }
    }
  }

})();


text:
package de.opitz.consulting.camunda.cockpit.plugin.bpmnstats.resources;

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

import org.camunda.bpm.cockpit.db.QueryParameters;
import org.camunda.bpm.cockpit.plugin.resource.AbstractCockpitPluginResource;

import de.opitz.consulting.camunda.cockpit.plugin.bpmnstats.dto.StatsContainerDto;

public class BpmnStatsEngineSpecificResource extends AbstractCockpitPluginResource {

	public BpmnStatsEngineSpecificResource(String engineName) {
		super(engineName);
	}

	@GET
	@Path("process-definition/{id}/taskstats")
	public List<StatsContainerDto> getTaskActitityStats(
			@PathParam("id") String processDefinitionId) {

		QueryParameters<StatsContainerDto> parameter = new QueryParameters<StatsContainerDto>();
		parameter.setParameter(processDefinitionId);
		return getQueryService().executeQuery(
				"cockpit.bpmn-stats.selectStatsForTaskActitvity",
				parameter);

	}

	@GET
	@Path("process-definition/{id}/stats")
	public StatsContainerDto getProcessInstanceStats(
			@PathParam("id") String processDefinitionId) {
		return getQueryService().executeQuery(
				"cockpit.bpmn-stats.selectStatsForProcessInstances",
				processDefinitionId, StatsContainerDto.class);
	}

}


text:
package cop5555sp15;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

import java.io.PrintWriter;

import org.junit.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.util.TraceClassVisitor;

import cop5555sp15.ast.ASTNode;
import cop5555sp15.ast.CodeGenVisitor;
import cop5555sp15.ast.Program;
import cop5555sp15.ast.TypeCheckVisitor;
import cop5555sp15.ast.TypeCheckVisitor.TypeCheckException;
import cop5555sp15.symbolTable.SymbolTable;

public class Assignment4Tests {

    public static class DynamicClassLoader extends ClassLoader {
        public DynamicClassLoader(ClassLoader parent) {
            super(parent);
        }

        public Class<?> define(String className, byte[] bytecode) {
            return super.defineClass(className, bytecode, 0, bytecode.length);
        }
    };

 public void dumpBytecode(byte[] bytecode){
    int flags = ClassReader.SKIP_DEBUG;
    ClassReader cr;
    cr = new ClassReader(bytecode);
    cr.accept(new TraceClassVisitor(new PrintWriter(System.out)), flags);
}

	private ASTNode parseCorrectInput(String input) throws Exception {
		TokenStream stream = new TokenStream(input);
		Scanner scanner = new Scanner(stream);
		scanner.scan();
		Parser parser = new Parser(stream);
		System.out.println();
		ASTNode ast = parser.parse();
		if (ast == null) {
			System.out.println("errors " + parser.getErrors());
		}
		assertNotNull(ast);
		return ast;
	}

	private ASTNode typeCheckCorrectAST(ASTNode ast) throws Exception {
		SymbolTable symbolTable = new SymbolTable();
		TypeCheckVisitor v = new TypeCheckVisitor(symbolTable);
		try {
			ast.visit(v, null);
		} catch (TypeCheckException e) {
			System.out.println(e.getMessage());
			fail("no errors expected");
		}
		return ast;
	}

	private void typeCheckIncorrectAST(ASTNode ast) throws Exception {
		SymbolTable symbolTable = new SymbolTable();
		TypeCheckVisitor v = new TypeCheckVisitor(symbolTable);
		try {
			ast.visit(v, null);
			fail("expected error");
		} catch (TypeCheckException e) {
			System.out.println(e.getMessage());
		}
	}

	private byte[] generateByteCode(ASTNode ast) throws Exception {
		CodeGenVisitor v = new CodeGenVisitor();
			byte[] bytecode = (byte[]) ast.visit(v, null);
			dumpBytecode(bytecode);
			return bytecode;
	}

    public void executeByteCode(String name, byte[] bytecode) throws InstantiationException, IllegalAccessException{
        DynamicClassLoader loader = new DynamicClassLoader(Thread
                .currentThread().getContextClassLoader());
        Class<?> testClass = loader.define(name, bytecode);
        Codelet codelet = (Codelet) testClass.newInstance();
        codelet.execute();
    }

@Test
/**
 * generates and executes code to prints an int literal
 * The TypeCheckVisitor should set the type of the IntLitExpression to intType
 * intType is a constant defined in TypeConstants.java
 *
 * This test should pass in the assignment as givin.
 *
 * @throws Exception
 *
 * output:
 * 3
 */
public void printIntLiteral() throws Exception{
	System.out.println("***********printIntLiteral");
	String input = "class A {\n print 3; \n}";
	System.out.println(input);
	Program program = (Program) parseCorrectInput(input);
	assertNotNull(program);
	typeCheckCorrectAST(program);
	byte[] bytecode = generateByteCode(program);
	assertNotNull(bytecode);
	System.out.println("\nexecuting bytecode:");
	executeByteCode(program.JVMName, bytecode);
}

@Test
/**
 * generates and executes code to print a boolean literal
 * The TypeCheckVisitor should set the type of the BooleanLitExpression to booleanType
 * booleanType is a constant defined in TypeConstants.java
 * @throws Exception
 *
 * output:
 * true
 */
public void printBooleanLiteral() throws Exception{
	System.out.println("***********printIntLiteral");
	String input = "class A {\n print true; \n}";
	System.out.println(input);
	Program program = (Program) parseCorrectInput(input);
	assertNotNull(program);
	typeCheckCorrectAST(program);
	byte[] bytecode = generateByteCode(program);
	assertNotNull(bytecode);
	System.out.println("\nexecuting bytecode:");
	executeByteCode(program.JVMName, bytecode);
}

@Test
/**
 * generates and executes code to print a String literal
 * The TypeCheckVisitor should set the type of the StringLitExpression to stringType
 * stringType is a constant defined in TypeConstants.java
 * @throws Exception
 *
 * output:
 * go gators
 */
public void printStringLiteral() throws Exception{
	System.out.println("***********printIntLiteral");
	String input = "class A {\n print \"go gators\" ; \n}";
	System.out.println(input);
	Program program = (Program) parseCorrectInput(input);
	assertNotNull(program);
	typeCheckCorrectAST(program);
	byte[] bytecode = generateByteCode(program);
	assertNotNull(bytecode);
	System.out.println("\nexecuting bytecode:");
	executeByteCode(program.JVMName, bytecode);
}

/**
 * The following set of tests have to do with binary expressions.  The type checker
 * should ensure that both operand expressions are the same type, and set the type
 * of the result expression appropriately.  It is convenient to use the JVM type
 * as the representation for types.  It is also convenient for the visit method of
 * Expressions (and subclasses) to return the type.
 *
 * Legal combinations of types  and operators and the
 * result types are given below.  List and map types will be treated later.
 *
 *      int (+ | - | * | /) int 				-> int
 *      string + string         				-> string
 *      int (== | != | < | <= | >= | >) int     -> boolean
 *      string (== | !=) string       			-> boolean
 *
 */

@Test
/**
 * Generates and executes code to print the value of several integer expressions
 * The type checker should set the type of each expression to intType
 * @throws Exception
 *
 * output:
 * 8
 * 14
 * 1
 * 3
 */
public void intBinaryOps() throws Exception{
	System.out.println("***********intBinaryOps");
	String input = "class A {\n print 3+5;\n print 7*2;\n  print 5-4;\n  print 6/2;\n}";
	System.out.println(input);
	Program program = (Program) parseCorrectInput(input);
	assertNotNull(program);
	typeCheckCorrectAST(program);
	byte[] bytecode = generateByteCode(program);
	assertNotNull(bytecode);
	System.out.println("\nexecuting bytecode:");
	executeByteCode(program.JVMName, bytecode);
}

@Test
/**
 * Generates and executes code to print the value of several integer expressions with nested expressions
 * @throws Exception
 *
 * output:
 * 4
 * 16
 * -5
 * 2
 */
public void intBinaryOps2() throws Exception{
	System.out.println("***********intBinaryOps2");
	String input = "class A {\n print (3+5)/2;\n print (7*2)+(6/3);\n  print 5-4-6;\n  print 6/(2+1);\n}";
	System.out.println(input);
	Program program = (Program) parseCorrectInput(input);
	assertNotNull(program);
	typeCheckCorrectAST(program);
	byte[] bytecode = generateByteCode(program);
	assertNotNull(bytecode);
	System.out.println("\nexecuting bytecode:");
	executeByteCode(program.JVMName, bytecode);
}

@Test
/**
 * Generates and executes code to concatenate two strings and print the result
 * The type checker should set the type of each expression to stringType.  Note
 * that plus is overloaded.  You code generator needs to check the type to know
 * what kind of code to generate.
 *
 * @throws Exception
 *
 * output:
 * go**gators
 *
 * Hint: One way to do this is to generate the calls to
 * create a StringBuilder object, invoke append, and then toString
 * The other is to write a little java method to concatenate
 * two strings and return the result and invoke that.  You
 * might want to create a class called RuntimeSupport or similar
 * to hold all the static methods you use this way.
*/
public void stringConcat() throws Exception{
	System.out.println("***********stringConcat");
	String input = "class A {\n print \"go\" + \"***\" + \"gators\";\n}";
	System.out.println(input);
	Program program = (Program) parseCorrectInput(input);
	assertNotNull(program);
	typeCheckCorrectAST(program);
	byte[] bytecode = generateByteCode(program);
	assertNotNull(bytecode);
	System.out.println("\nexecuting bytecode:");
	executeByteCode(program.JVMName, bytecode);
}

@Test
/**
 * boolean binary op  &
 *
 * The type checker should ensure that both arguments are boolean and
 * set the result type to boolean.
 *
 * These are equivalent to && and || in c and java.  Probably the
 * easiest way to do this is to invoke a static Java method, but I'll
 * go ahead and explain how to use asmifier to figure this out.
 *
 * I wrote a little program containing 		boolean e = x && y;
 * where x and y are static booleans. The corresponding asmified bytecode
 * is as follows:
 *
mv.visitFieldInsn(GETSTATIC, "asm_tests/TestClass", "x", "Z");
Label l1 = new Label();
mv.visitJumpInsn(IFEQ, l1);
mv.visitFieldInsn(GETSTATIC, "asm_tests/TestClass", "y", "Z");
mv.visitJumpInsn(IFEQ, l1);
mv.visitInsn(ICONST_1);
Label l2 = new Label();
mv.visitJumpInsn(GOTO, l2);
mv.visitLabel(l1);
mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
mv.visitInsn(ICONST_0);
mv.visitLabel(l2);
mv.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] {Opcodes.INTEGER});
mv.visitVarInsn(ISTORE, 1);
 *
 * The non-asmified code is
    GETSTATIC asm_tests/EmptyClass.x : Z
    IFEQ L1
    GETSTATIC asm_tests/EmptyClass.y : Z
    IFEQ L1
    ICONST_1
    GOTO L2
   L1
   FRAME SAME
    ICONST_0
   L2
   FRAME SAME1 I
    ISTORE 1

 * In this code, the mv.visitFieldInsn instructions load the value
 * of the arguments on the stack.  In our code generation we will
 * visit the expressions to generate the necessary code to leave the
 * value of the expressions on the stack.  The ISTORE 1 at the
 * end implements the assignment.  Since our goal is to generate code
 * to leave the value on top of the stack, we will omit this, too.
 *
 *  ASM makes it convenient to handle labels.
 *  Before you refer to a label, create a label object
 *  Label l1 = new Label();
 *  Now you can use that in instructions.  For example
 *  mv.visitJumpInsn(IFEQ, l1);
 *  Immediately before the instruction where the label should go,
 *  visit the label
 *  mv.visitLabel(l1);
 *
 * Make sure to create a new Label object for each label in your code.
 *
 * The FRAME SAME, FRAME SAME1 I  instructions provide information to
 * the JVM about what should be on the stack at the target of a jump.
 * Although you see visitFrame instructions in the asmified code, you
 * can omit these from your code generation.  Because we created our
 * ClassWriter with the COMPUTE_FRAMES flag, asm will automatically
 * handle this for us.
 *
 * Getting back to the problem:  We see that the implementation of &&
 * in java is
 *  evaluate the left expression and leave its value on the stack
    IFEQ L1
    evaluate the right expression and leave its value on the stack
    IFEQ L1
    ICONST_1
    GOTO L2
   L1
    ICONST_0
   L2
   .....

 *  So what happens is evaluate left expression.  If it is  0, jump
 *  to L1 which loads 0 onto the stack.  Otherwise, evaluate the
 *  right expression.  If it is 0, jump to L1, which loads 0 onto the
 *  stack.  Otherwise load 1 onto the stack and jump to L2, which is
 *  past the load 0 instruction.
 *
 *  In your code generator, you will want something like
 *
 *  	public Object visitBinaryExpression(BinaryExpression binaryExpression,
			Object arg) throws Exception {
		MethodVisitor mv = ((Argument) arg).mv;
		Kind op = binaryExpression.op.kind;
		switch (op) {
		case AND: {
			binaryExpression.expression0.visit(this, arg);
			Label l1 = new Label();
			mv.visitJumpInsn(IFEQ, l1);
			binaryExpression.expression1.visit(this,arg);
			mv.visitJumpInsn(IFEQ, l1);
			mv.visitInsn(ICONST_1);
			Label l2 = new Label();
			mv.visitJumpInsn(GOTO, l2);
			mv.visitLabel(l1);
			mv.visitInsn(ICONST_0);
			mv.visitLabel(l2);
		}
		break;
		.....

*
*  output:
*  false
*  false
*  false
*  true
 */
public void and() throws Exception{
	System.out.println("***********and");
	String input = "class A {\n print false & false;\n print false & true;\n  print true & false;\n  print true & true;\n}";
	System.out.println(input);
	Program program = (Program) parseCorrectInput(input);
	assertNotNull(program);
	typeCheckCorrectAST(program);
	byte[] bytecode = generateByteCode(program);
	assertNotNull(bytecode);
	System.out.println("\nexecuting bytecode:");
	executeByteCode(program.JVMName, bytecode);
}

@Test
/**
 * boolean binary op  |
 *
 * Similar to previous test.  The type checking rules are the same.
 *
 * output:
 * false
 * true
 * true
 * true
 *
 */
public void or() throws Exception{
	System.out.println("***********or");
	String input = "class A {\n print false | false;\n print false | true;\n  print true | false;\n  print true | true;\n}";
	System.out.println(input);
	Program program = (Program) parseCorrectInput(input);
	assertNotNull(program);
	typeCheckCorrectAST(program);
	byte[] bytecode = generateByteCode(program);
	assertNotNull(bytecode);
	System.out.println("\nexecuting bytecode:");
	executeByteCode(program.JVMName, bytecode);
}
@Test
/**
 * The next set of tests involves relational expressions.
 *
 * This tests == for ints.  The type checker should ensure that both operands are ints
 * and set the result to boolean.
 *
 * output:
 * true
 * false
 */
public void intEqual() throws Exception{
	System.out.println("***********intEqual");
	String input = "class A {\n print 3 == (1+2); print 3 == 4; \n}";
	System.out.println(input);
	Program program = (Program) parseCorrectInput(input);
	assertNotNull(program);
	typeCheckCorrectAST(program);
	byte[] bytecode = generateByteCode(program);
	assertNotNull(bytecode);
	System.out.println("\nexecuting bytecode:");
	executeByteCode(program.JVMName, bytecode);
}

@Test
/**
 *
 * This tests != for ints.  The type checker should ensure that both operands are ints
 * and set the result to boolean.
 *
 * output:
 * false
 * true
 */
public void intNotEqual() throws Exception{
	System.out.println("***********intEqual");
	String input = "class A {\n print 3 != (1+2); print 3 != 4; \n}";
	System.out.println(input);
	Program program = (Program) parseCorrectInput(input);
	assertNotNull(program);
	typeCheckCorrectAST(program);
	byte[] bytecode = generateByteCode(program);
	assertNotNull(bytecode);
	System.out.println("\nexecuting bytecode:");
	executeByteCode(program.JVMName, bytecode);
}

@Test
/** equal and notequal for booleans.
 *
 * output:
 * false
 * true
 * false
 * true
 */
public void booleanRelational() throws Exception{
	System.out.println("***********booleanRelational");
	String input = "class A {\n print false != false; print false != true; print false == true; print true == true; \n}";
	System.out.println(input);
	Program program = (Program) parseCorrectInput(input);
	assertNotNull(program);
	typeCheckCorrectAST(program);
	byte[] bytecode = generateByteCode(program);
	assertNotNull(bytecode);
	System.out.println("\nexecuting bytecode:");
	executeByteCode(program.JVMName, bytecode);
}

@Test
/** equal and not equal for strings.
 * This requires using the equals method rather than comparing values
 *
 * output:
 * false
 * true
 * true
 * false
 */
public void stringRelational() throws Exception{
	System.out.println("***********stringRelational");
	String input = "class A {\n print \"hello\" != \"hello\";\n   print \"hello\" != \"goodbye\";\n   print \"good\" == \"good\";\n    print \"bad\" == \"good\"; \n }" ;
	System.out.println(input);
	Program program = (Program) parseCorrectInput(input);
	assertNotNull(program);
	typeCheckCorrectAST(program);
	byte[] bytecode = generateByteCode(program);
	assertNotNull(bytecode);
	System.out.println("\nexecuting bytecode:");
	executeByteCode(program.JVMName, bytecode);
}

@Test
/** relational expressions on ints
 * The easiest way is to write a little java program and use
 * asmifier to see how to do this.  But note that if you try to
 * compiler 3<3, the compiler will optimize that out and just
 * store 0.
 *
 * output:
 * false
 * true
 * false
 * true
 */
public void intRelational1() throws Exception{
	System.out.println("***********intRelational1");
	String input = "class A {\n print 3 < 3;\n   print 3 <= 3;\n   print 3>3;\n    print 3>=3; \n }" ;
	System.out.println(input);
	Program program = (Program) parseCorrectInput(input);
	assertNotNull(program);
	typeCheckCorrectAST(program);
	byte[] bytecode = generateByteCode(program);
	assertNotNull(bytecode);
	System.out.println("\nexecuting bytecode:");
	executeByteCode(program.JVMName, bytecode);
}

@Test
/**
 * output:
 * true
 * false
 * true
 * false
 */
public void intRelational2() throws Exception{
	System.out.println("***********intRelational2");
	String input = "class A {\n print 2 < 3;\n   print 4 <= 3;\n   print 4>3;\n    print 2>=3; \n }" ;
	System.out.println(input);
	Program program = (Program) parseCorrectInput(input);
	assertNotNull(program);
	typeCheckCorrectAST(program);
	byte[] bytecode = generateByteCode(program);
	assertNotNull(bytecode);
	System.out.println("\nexecuting bytecode:");
	executeByteCode(program.JVMName, bytecode);
}

/** The next (incomplete) set of tests have typing errors and
 * are expected to throw a type check error.  They should work
 * without extra coding if you have properly implemented type
 * checking for the features of the previous cases.
 */

@Test
/** This test is expected to throw a TypeCheckException
 *
 * @throws Exception
 */
public void binaryExpressionFail1() throws Exception{
	System.out.println("***********binaryExpressionFail1");
	String input = "class A {\n  print true + 1;}";
	System.out.println(input);
	Program program = (Program) parseCorrectInput(input);
	typeCheckIncorrectAST(program);
}
@Test
/** This test is expected to throw a TypeCheckException
 *
 * @throws Exception
 */
public void binaryExpressionFail2() throws Exception{
	System.out.println("***********binaryExpressionFail2");
	String input = "class A {\n  print true + \"hello\";}";
	System.out.println(input);
	Program program = (Program) parseCorrectInput(input);
	typeCheckIncorrectAST(program);
}

@Test
/** This test is expected to throw a TypeCheckException
 *
 * @throws Exception
 */
public void binaryExpressionFail3() throws Exception{
	System.out.println("***********binaryExpressionFail2");
	String input = "class A {\n  print 2 & 3;}";
	System.out.println(input);
	Program program = (Program) parseCorrectInput(input);
	typeCheckIncorrectAST(program);
}

@Test
/** outer scope variables for simple types mapped into fields
 * with assignments.
 *
 * Type checking:
 *
 * Declaration:  insert variable and its declaration in to the  symbol
 *    table making sure to check that it has not already been defined
 *    in this scope.
 *
 * Use:  lookup variable in symbol table, make sure it has been declared
 *    in the current scope, and get its type.
 *
 * When an expression is visited, determine its type and store the
 * type in the field in the Expression
 *
 * In assignment statement, ensure that both sides have compatible types.
 *
 * Code generation:
 *
 * Declaration:
 *   For now, we will only declare variables in the outer scope and
 *   implement them as fields.
 *
 *   call cw.visitField to add a field for the variable to the class
 *   fv = cw.visitField(0, varName, type, null, null);
 *     fv.visitEnd();
 *
 *
 * Assignment Statement
 * 	 only do the simple types for now (lValue instance of IdentLValue)
 *       gen code to load "this" reference on the stack
 *       visit the expression (which gens code to put value on stack)
 *       gen putfield
 *
 *   If the expression is an IdentExpression
 *       gen code to load "this" reference onto stack
 *       gen getfield
 *   this code leaves the value of the ident on the stack
 *
 *
 *   output:
 *   3
 */
public void intVariable() throws Exception{
	System.out.println("***********intVariable");
	String input = "class A {def x: int; \n x = 3;\n  print x;}";
	System.out.println(input);
	Program program = (Program) parseCorrectInput(input);
	assertNotNull(program);
	typeCheckCorrectAST(program);
	byte[] bytecode = generateByteCode(program);
	assertNotNull(bytecode);
	System.out.println("\nexecuting bytecode:");
	executeByteCode(program.JVMName, bytecode);
}

@Test
/*  similar to above except with a boolean.
 *
 * output:
 * false
 */
public void booleanVariable() throws Exception{
	System.out.println("***********intVariable");
	String input = "class A {def x: boolean; \n x = false;\n  print x;}";
	System.out.println(input);
	Program program = (Program) parseCorrectInput(input);
	assertNotNull(program);
	typeCheckCorrectAST(program);
	byte[] bytecode = generateByteCode(program);
	assertNotNull(bytecode);
	System.out.println("\nexecuting bytecode:");
	executeByteCode(program.JVMName, bytecode);
}

@Test
/* A more complicated program.  This should pass if the previous
 * steps have been done correctly.
 *
 * output:
x=
43
b=
true
 */
public void expressonsAndVars() throws Exception{
	System.out.println("***********expressonsAndVars");
	String input = "class A {def x: int; \n def b: boolean;";
	input = input + "x = 42;\n   x = x + 1;\n   b = (x > 100) | (x == 43);\n  ";
			input = input + "print \"x=\";\n  print x;\n print \"b=\"; print b;}";
	System.out.println(input);
	Program program = (Program) parseCorrectInput(input);
	assertNotNull(program);
	typeCheckCorrectAST(program);
	byte[] bytecode = generateByteCode(program);
	assertNotNull(bytecode);
	System.out.println("\nexecuting bytecode:");
	executeByteCode(program.JVMName, bytecode);
}

}


text:
package org.apache.tiles.request.portlet.extractor;

import static org.easymock.EasyMock.*;
import static org.easymock.classextension.EasyMock.*;
import static org.junit.Assert.*;

import java.util.Enumeration;

import javax.portlet.PortletRequest;
import javax.portlet.PortletSession;

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

/**
 * Tests {@link SessionScopeExtractor}.
 *
 * @version $Rev$ $Date$
 */
public class SessionScopeExtractorTest {

    /**
     * The request.
     */
    private PortletRequest request;

    /**
     * The session.
     */
    private PortletSession session;

    /**
     * The scope to test.
     */
    private SessionScopeExtractor extractor;

    /**
     * Sets up the test.
     */
    @Before
    public void setUp() {
        request = createMock(PortletRequest.class);
        session = createMock(PortletSession.class);
        extractor = new SessionScopeExtractor(request, PortletSession.PORTLET_SCOPE);
    }

    /**
     * Tests {@link SessionScopeExtractor#SessionScopeExtractor(PortletRequest, int)}.
     */
    @Test(expected = IllegalArgumentException.class)
    public void testIllegalScope() {
        replay(request, session);
        new SessionScopeExtractor(request, 0);
        verify(request, session);
    }

    /**
     * Test method for {@link SessionScopeExtractor#setValue(java.lang.String, java.lang.Object)}.
     */
    @Test
    public void testSetValue() {
        expect(request.getPortletSession()).andReturn(session);
        session.setAttribute("name", "value", PortletSession.PORTLET_SCOPE);

        replay(request, session);
        extractor.setValue("name", "value");
        verify(request, session);
    }

    /**
     * Test method for {@link SessionScopeExtractor#removeValue(java.lang.String)}.
     */
    @Test
    public void testRemoveValue() {
        expect(request.getPortletSession(false)).andReturn(session);
        session.removeAttribute("name", PortletSession.PORTLET_SCOPE);

        replay(request, session);
        extractor.removeValue("name");
        verify(request, session);
    }

    /**
     * Test method for {@link SessionScopeExtractor#getKeys()}.
     */
    @SuppressWarnings("unchecked")
    @Test
    public void testGetKeys() {
        Enumeration<String> keys = createMock(Enumeration.class);

        expect(request.getPortletSession(false)).andReturn(session);
        expect(session.getAttributeNames(PortletSession.PORTLET_SCOPE)).andReturn(keys);

        replay(request, session, keys);
        assertEquals(keys, extractor.getKeys());
        verify(request, session, keys);
    }

    /**
     * Test method for {@link SessionScopeExtractor#getKeys()}.
     */
    @Test
    public void testGetKeysNoSession() {
        expect(request.getPortletSession(false)).andReturn(null);

        replay(request, session);
        assertNull(extractor.getKeys());
        verify(request, session);
    }

    /**
     * Test method for {@link SessionScopeExtractor#getValue(java.lang.String)}.
     */
    @Test
    public void testGetValue() {
        expect(request.getPortletSession(false)).andReturn(session);
        expect(session.getAttribute("name", PortletSession.PORTLET_SCOPE)).andReturn("value");

        replay(request, session);
        assertEquals("value", extractor.getValue("name"));
        verify(request, session);
    }

    /**
     * Test method for {@link SessionScopeExtractor#getValue(java.lang.String)}.
     */
    @Test
    public void testGetValueNoSession() {
        expect(request.getPortletSession(false)).andReturn(null);

        replay(request, session);
        assertNull(extractor.getValue("name"));
        verify(request, session);
    }

}


text:
namespace IdentityServer3.Admin.MongoDb.Powershell
{
    public enum HashType
    {
        SHA256,
        SHA512
    }
}