text:
#include <iostream>
#include <HFO.hpp>
#include <glog/logging.h>
#include <gflags/gflags.h>
#include "dqn.hpp"
#include "hfo_game.hpp"
#include <boost/filesystem.hpp>
#include <thread>
#include <mutex>
#include <algorithm>
#include <chrono>
#include <limits>
#include <stdlib.h>

using namespace boost::filesystem;
using namespace hfo;

DEFINE_bool(gpu, true, "Use GPU to brew Caffe");
DEFINE_bool(benchmark, false, "Benchmark the network and exit");
DEFINE_bool(learn_offline, false, "Just do updates on a fixed replaymemory.");
// Load/Save Args
DEFINE_string(save, "", "Prefix for saving snapshots");
DEFINE_string(resume, "", "Prefix for resuming from. Default=save_path");
DEFINE_string(actor_weights, "", "The actor pretrained weights load (*.caffemodel).");
DEFINE_string(critic_weights, "", "The critic pretrained weights load (*.caffemodel).");
DEFINE_string(actor_snapshot, "", "The actor solver state to load (*.solverstate).");
DEFINE_string(critic_snapshot, "", "The critic solver state to load (*.solverstate).");
DEFINE_string(memory_snapshot, "", "The replay memory to load (*.replaymemory).");
// Solver Args
DEFINE_string(solver, "Adam", "Solver Type.");
DEFINE_double(momentum, .95, "Solver momentum.");
DEFINE_double(momentum2, .999, "Solver momentum2.");
DEFINE_double(actor_lr, .00001, "Solver learning rate.");
DEFINE_double(critic_lr, .001, "Solver learning rate.");
DEFINE_double(clip_grad, 10, "Clip gradients.");
DEFINE_string(lr_policy, "fixed", "LR Policy.");
DEFINE_int32(max_iter, 10000000, "Custom max iter.");
// Epsilon-Greedy Args
DEFINE_int32(explore, 10000, "Iterations for epsilon to reach given value.");
DEFINE_double(epsilon, .1, "Value of epsilon after explore iterations.");
DEFINE_double(evaluate_with_epsilon, 0, "Epsilon value to be used in evaluation mode");
// Evaluation Args
DEFINE_bool(evaluate, false, "Evaluation mode: only playing a game, no updates");
DEFINE_int32(evaluate_freq, 10000, "Frequency (steps) between evaluations");
DEFINE_int32(repeat_games, 100, "Number of games played in evaluation mode");
// Misc Args
DEFINE_double(update_ratio, 0.1, "Ratio of new experiences to updates.");
// Sharing
DEFINE_int32(share_actor_layers, 0, "Share layers between actor networks.");
DEFINE_int32(share_critic_layers, 0, "Share layers between critic networks.");
DEFINE_bool(share_replay_memory, false, "Shares replay memory between agents.");
// Game configuration
DEFINE_int32(offense_agents, 1, "Number of agents playing offense");
DEFINE_int32(offense_npcs, 0, "Number of npcs playing offense");
DEFINE_int32(defense_agents, 0, "Number of agents playing defense");
DEFINE_int32(defense_npcs, 0, "Number of npcs playing defense");
DEFINE_int32(offense_dummies, 0, "Number of dummy npcs playing offense");
DEFINE_int32(defense_dummies, 0, "Number of dummy npcs playing defense");
DEFINE_int32(defense_chasers, 0, "Number of chasers playing defense");

// Global Variables Shared Between Threads
dqn::DQN* DQNS[12]; // Pointers to all DQNs. We will never have >12 players
std::mutex MTX;

double CalculateEpsilon(const int iter) {
  if (iter < FLAGS_explore) {
    return 1.0 - (1.0 - FLAGS_epsilon) * (static_cast<double>(iter) / FLAGS_explore);
  } else {
    return FLAGS_epsilon;
  }
}

std::string GetArg(std::string input, int indx) {
  std::istringstream ss(input);
  std::string token;
  int i = 0;
  while(std::getline(ss, token, ',')) {
    if (i++ == indx) {
      return token;
    }
  }
  return "";
}

// Busy sleep while suggesting that other threads run for a small amount of time
void little_sleep(std::chrono::microseconds us) {
  auto start = std::chrono::high_resolution_clock::now();
  auto end = start + us;
  do {
    std::this_thread::yield();
  } while (std::chrono::high_resolution_clock::now() < end);
}

/**
 * Play one episode and return the total score and number of steps
 */
std::tuple<double, int, status_t, double> PlayOneEpisode(HFOEnvironment& hfo,
                                                         dqn::DQN& dqn,
                                                         const double epsilon,
                                                         const bool update,
                                                         const int tid) {
  std::vector<dqn::Transition> episode;
  HFOGameState game(dqn.unum());
  hfo.act(DASH, 0, 0);
  game.update(hfo);
  CHECK(!game.episode_over) << "Episode should not be over at beginning!";
  std::deque<dqn::StateDataSp> past_states;
  while (!game.episode_over) {
    const std::vector<float>& current_state = hfo.getState();
    CHECK_EQ(current_state.size(), dqn.state_size());
    dqn::StateDataSp current_state_sp
        = std::make_shared<dqn::StateData>(dqn.state_size());
    std::copy(current_state.begin(), current_state.end(), current_state_sp->begin());
    past_states.push_back(current_state_sp);
    if (past_states.size() < dqn::kStateInputCount) {
      hfo.act(DASH, 0, 0);
    } else {
      while (past_states.size() > dqn::kStateInputCount) {
        past_states.pop_front();
      }
      dqn::InputStates input_states;
      std::copy(past_states.begin(), past_states.end(), input_states.begin());
      dqn::ActorOutput actor_output = dqn.SelectAction(input_states, epsilon);
      VLOG(1) << "Step " << game.steps;
      VLOG(1) << "Actor_output: " << dqn::PrintActorOutput(actor_output);
      Action action = dqn::GetAction(actor_output);
      VLOG(1) << "q_value: " << dqn.EvaluateAction(input_states, actor_output)
              << " Action: " << hfo::ActionToString(action.action);
      hfo.act(action.action, action.arg1, action.arg2);
      game.update(hfo);
      float reward = game.reward();
      if (update) {
        const std::vector<float>& next_state = hfo.getState();
        CHECK_EQ(next_state.size(), dqn.state_size());
        dqn::StateDataSp next_state_sp
            = std::make_shared<dqn::StateData>(dqn.state_size());
        std::copy(next_state.begin(), next_state.end(), next_state_sp->begin());
        const auto transition = (game.status == IN_GAME) ?
            dqn::Transition(input_states, actor_output, reward, 0, next_state_sp):
            dqn::Transition(input_states, actor_output, reward, 0, boost::none);
        episode.push_back(transition);
      }
    }
  }
  if (update) {
    if (FLAGS_share_replay_memory) { MTX.lock(); }
    dqn.LabelTransitions(episode);
    dqn.AddTransitions(episode);
    if (FLAGS_share_replay_memory) { MTX.unlock(); }
  }
  return std::make_tuple(game.total_reward, game.steps, game.status,
                         game.extrinsic_reward);
}

template <class T>
std::pair<double,double> get_avg_std(std::vector<T> data) {
  double sum = 0;
  for (int i = 0; i < data.size(); ++i) {
    sum += data[i];
  }
  double avg = sum / static_cast<double>(data.size());
  double std = 0;
  for (int i = 0; i < data.size(); ++i) {
    std += (data[i] - avg) * (data[i] - avg);
  }
  std = sqrt(std / static_cast<double>(data.size() - 1));
  return std::make_pair(avg, std);
}

double Evaluate(HFOEnvironment& hfo, dqn::DQN& dqn, int tid) {
  LOG(INFO) << "[Agent" << tid << "] Evaluating for " << FLAGS_repeat_games
            << " episodes with epsilon = " << FLAGS_evaluate_with_epsilon;
  std::vector<double> scores;
  std::vector<int> steps;
  std::vector<int> successful_trial_steps;
  int goals = 0;
  for (int i = 0; i < FLAGS_repeat_games; ++i) {
    auto result = PlayOneEpisode(hfo, dqn, FLAGS_evaluate_with_epsilon, false, tid);
    double trial_reward = std::get<0>(result);
    int trial_steps = std::get<1>(result);
    status_t trial_status = std::get<2>(result);
    scores.push_back(trial_reward);
    steps.push_back(trial_steps);
    if (trial_status == GOAL) {
      goals++;
      successful_trial_steps.push_back(trial_steps);
    }
  }
  std::pair<double, double> score_dist = get_avg_std(scores);
  std::pair<double, double> steps_dist = get_avg_std(steps);
  std::pair<double, double> succ_steps_dist = get_avg_std(successful_trial_steps);
  float goal_percent = goals / float(FLAGS_repeat_games);
  LOG(INFO) << "[Agent" << tid << "] Evaluation: "
            << "actor_iter = " << dqn.actor_iter()
            << ", avg_reward = " << score_dist.first
            << ", reward_std = " << score_dist.second
            << ", avg_steps = " << steps_dist.first
            << ", steps_std = " << steps_dist.second
            << ", success_steps = " << succ_steps_dist.first
            << ", success_std = " << succ_steps_dist.second
            << ", goal_perc = " << goal_percent;
  return goal_percent;
}

void KeepPlayingGames(int tid, std::string save_prefix, int port) {
  LOG(INFO) << "Thread " << tid << ", port=" << port << ", save_prefix=" << save_prefix;
  if (FLAGS_gpu) {
    caffe::Caffe::set_mode(caffe::Caffe::GPU);
  } else {
    caffe::Caffe::set_mode(caffe::Caffe::CPU);
  }
  // Look for a recent snapshot to resume
  std::string resume_path = FLAGS_resume.empty() ? save_prefix : FLAGS_resume;
  std::string last_actor_snapshot, last_critic_snapshot, last_memory_snapshot;
  dqn::FindLatestSnapshot(resume_path, last_actor_snapshot,
                          last_critic_snapshot, last_memory_snapshot);
  LOG(INFO) << "Found Resumable(s): [" << resume_path << "] "
            << last_actor_snapshot << ", " << last_critic_snapshot
            << ", " << last_memory_snapshot;
  CHECK((FLAGS_critic_snapshot.empty() || FLAGS_critic_weights.empty()) &&
        (FLAGS_actor_snapshot.empty() || FLAGS_actor_weights.empty()))
      << "Give a snapshot or weights but not both.";
  int num_players = FLAGS_offense_agents + FLAGS_offense_npcs
      + FLAGS_offense_dummies + FLAGS_defense_agents + FLAGS_defense_npcs
      + FLAGS_defense_dummies + FLAGS_defense_chasers;
  int num_features = NumStateFeatures(num_players);
  // Construct the solver
  caffe::SolverParameter actor_solver_param;
  caffe::SolverParameter critic_solver_param;
  caffe::NetParameter* actor_net_param = actor_solver_param.mutable_net_param();
  std::string actor_net_filename = save_prefix + "_actor.prototxt";
  if (boost::filesystem::is_regular_file(actor_net_filename)) {
    caffe::ReadProtoFromTextFileOrDie(actor_net_filename.c_str(), actor_net_param);
  } else {
    actor_net_param->CopyFrom(dqn::CreateActorNet(num_features));
    WriteProtoToTextFile(*actor_net_param, actor_net_filename.c_str());
  }
  caffe::NetParameter* critic_net_param = critic_solver_param.mutable_net_param();
  std::string critic_net_filename = save_prefix + "_critic.prototxt";
  if (boost::filesystem::is_regular_file(critic_net_filename)) {
    caffe::ReadProtoFromTextFileOrDie(critic_net_filename.c_str(), critic_net_param);
  } else {
    critic_net_param->CopyFrom(dqn::CreateCriticNet(num_features));
    WriteProtoToTextFile(*critic_net_param, critic_net_filename.c_str());
  }
  actor_solver_param.set_snapshot_prefix((save_prefix + "_actor").c_str());
  critic_solver_param.set_snapshot_prefix((save_prefix + "_critic").c_str());
  actor_solver_param.set_max_iter(FLAGS_max_iter);
  critic_solver_param.set_max_iter(FLAGS_max_iter);
  actor_solver_param.set_type(FLAGS_solver);
  critic_solver_param.set_type(FLAGS_solver);
  actor_solver_param.set_base_lr(FLAGS_actor_lr);
  critic_solver_param.set_base_lr(FLAGS_critic_lr);
  actor_solver_param.set_lr_policy(FLAGS_lr_policy);
  critic_solver_param.set_lr_policy(FLAGS_lr_policy);
  actor_solver_param.set_momentum(FLAGS_momentum);
  critic_solver_param.set_momentum(FLAGS_momentum);
  actor_solver_param.set_momentum2(FLAGS_momentum2);
  critic_solver_param.set_momentum2(FLAGS_momentum2);
  actor_solver_param.set_clip_gradients(FLAGS_clip_grad);
  critic_solver_param.set_clip_gradients(FLAGS_clip_grad);

  dqn::DQN* dqn = new dqn::DQN(actor_solver_param, critic_solver_param,
                               save_prefix, num_features, tid);
  // Load actor/critic/memory. Try to load from resumables
  // first. Otherwise load from the args.
  if (!last_actor_snapshot.empty()) {
    dqn->RestoreActorSolver(last_actor_snapshot);
  } else if (!GetArg(FLAGS_actor_snapshot, tid).empty()) {
    dqn->RestoreActorSolver(GetArg(FLAGS_actor_snapshot, tid));
  } else if (!GetArg(FLAGS_actor_weights, tid).empty()) {
    dqn->LoadActorWeights(GetArg(FLAGS_actor_weights, tid));
  }
  if (!last_critic_snapshot.empty()) {
    dqn->RestoreCriticSolver(last_critic_snapshot);
  } else if (!GetArg(FLAGS_critic_snapshot, tid).empty()) {
    dqn->RestoreCriticSolver(GetArg(FLAGS_critic_snapshot, tid));
  } else if (!GetArg(FLAGS_critic_weights, tid).empty()) {
    dqn->LoadCriticWeights(GetArg(FLAGS_critic_weights, 0));
  }
  if (!last_memory_snapshot.empty()) {
    dqn->LoadReplayMemory(last_memory_snapshot);
  } else if (!GetArg(FLAGS_memory_snapshot, tid).empty()) {
    dqn->LoadReplayMemory(GetArg(FLAGS_memory_snapshot, tid));
  }

  HFOEnvironment env;
  ConnectToServer(env, port);
  dqn->set_unum(env.getUnum());

  // Wait for all DQNs to connect and be ready
  DQNS[tid] = dqn;
  int target_id = tid == 0 ? 1 : 0;
  bool all_dqns_ready = false;
  while (!all_dqns_ready) {
    little_sleep(std::chrono::microseconds(100));
    all_dqns_ready = true;
    for (int i=0; i<FLAGS_offense_agents; ++i) {
      if (DQNS[i] == NULL) {
        all_dqns_ready = false;
      }
    }
  }
  // TID 0 is the Master and will do the sharing
  if (tid == 0) {
    if (FLAGS_share_actor_layers > 0 || FLAGS_share_critic_layers > 0) {
      for (int i=1; i<FLAGS_offense_agents; ++i) {
        dqn::DQN* teammate = DQNS[i];
        CHECK_NOTNULL(teammate);
        dqn->ShareParameters(*teammate,
                             FLAGS_share_actor_layers,
                             FLAGS_share_critic_layers);
      }
    }
    if (FLAGS_share_replay_memory) {
      for (int i=1; i<FLAGS_offense_agents; ++i) {
        dqn::DQN* teammate = DQNS[i];
        CHECK_NOTNULL(teammate);
        dqn->ShareReplayMemory(*teammate);
      }
    }
  }

  if (FLAGS_evaluate) {
    Evaluate(env, *dqn, tid);
    delete dqn;
    env.act(QUIT);
    env.step();
    return;
  }
  if (FLAGS_benchmark) {
    PlayOneEpisode(env, *dqn, FLAGS_evaluate_with_epsilon, true, tid);
    dqn->Benchmark(1000);
    delete dqn;
    env.act(QUIT);
    env.step();
    return;
  }
  if (FLAGS_learn_offline) {
    while (dqn->max_iter() < FLAGS_max_iter) {
      dqn->Update();
    }
    dqn->Snapshot();
    delete dqn;
    env.act(QUIT);
    env.step();
    return;
  }
  int last_eval_iter = dqn->max_iter();
  double best_score = std::numeric_limits<double>::min();
  for (int episode = 0; dqn->max_iter() < FLAGS_max_iter; ++episode) {
    double epsilon = CalculateEpsilon(dqn->max_iter());
    auto result = PlayOneEpisode(env, *dqn, epsilon, true, tid);
    LOG(INFO) << "[Agent" << tid <<"] Episode " << episode
              << " reward = " << std::get<0>(result);
    int steps = std::get<1>(result);
    int n_updates = int(steps * FLAGS_update_ratio);
    if (FLAGS_share_replay_memory) { MTX.lock(); }
    for (int i=0; i<n_updates; ++i) {
      dqn->Update();
    }
    if (FLAGS_share_replay_memory) { MTX.unlock(); }
    if (dqn->actor_iter() >= last_eval_iter + FLAGS_evaluate_freq) {
      double avg_score = Evaluate(env, *dqn, tid);
      if (avg_score > best_score) {
        LOG(INFO) << "[Agent " << tid << "] New High Score: " << avg_score
                  << ", actor_iter = " << dqn->actor_iter()
                  << ", critic_iter = " << dqn->critic_iter();
        best_score = avg_score;
        dqn::RemoveFilesMatchingRegexp(dqn->save_path() + "_HiScore.*");
        std::string fname = dqn->save_path() + "_HiScore" + std::to_string(avg_score);
        dqn->Snapshot(fname, false, false);
      }
      last_eval_iter = dqn->actor_iter();
    }
  }
  dqn->Snapshot();
  delete dqn;
  env.act(QUIT);
  env.step();
}

void SystemExecute(std::string cmd) {
  CHECK_EQ(system(cmd.c_str()), 0) << "Unable to execute command";
}

int main(int argc, char** argv) {
  std::string usage(argv[0]);
  usage.append(" -[evaluate|save [path]]");
  gflags::SetUsageMessage(usage);
  gflags::SetVersionString("0.1");
  gflags::ParseCommandLineFlags(&argc, &argv, true);
  google::InitGoogleLogging(argv[0]);
  google::InstallFailureSignalHandler();
  fLI::FLAGS_logbuflevel = -1;
  if (FLAGS_evaluate) {
    google::LogToStderr();
  }
  if (FLAGS_save.empty() && !FLAGS_evaluate) {
    LOG(ERROR) << "Save path (or evaluate) required but not set.";
    LOG(ERROR) << "Usage: " << gflags::ProgramUsage();
    exit(1);
  }
  path save_path(FLAGS_save);
  google::SetLogDestination(google::GLOG_INFO, (save_path.native() + "_INFO_").c_str());
  google::SetLogDestination(google::GLOG_WARNING, (save_path.native() + "_WARNING_").c_str());
  google::SetLogDestination(google::GLOG_ERROR, (save_path.native() + "_ERROR_").c_str());
  google::SetLogDestination(google::GLOG_FATAL, (save_path.native() + "_FATAL_").c_str());
  for (int i=0; i<12; ++i) { // Make the global pointers all null
    DQNS[i] = NULL;
  }
  srand(std::hash<std::string>()(save_path.native()));
  int port = rand() % 40000 + 20000;
  std::thread server_thread(
      StartHFOServer, port, FLAGS_offense_agents + FLAGS_offense_dummies,
      FLAGS_offense_npcs,
      FLAGS_defense_agents + FLAGS_defense_dummies + FLAGS_defense_chasers,
      FLAGS_defense_npcs);
  std::thread player_threads[10];
  int threadNum = 0;
  for (int i=0; i<FLAGS_offense_agents; ++i) {
    std::string save_prefix = save_path.native() + "_agent" + std::to_string(i);
    player_threads[threadNum++] = std::thread(KeepPlayingGames, i, save_prefix, port);
    sleep(10);
  }
  for (int i=0; i<FLAGS_offense_dummies; ++i) {
    player_threads[threadNum++] = std::thread(StartDummyTeammate, port);
  }
  for (int i=0; i<FLAGS_defense_dummies; ++i) {
    player_threads[threadNum++] = std::thread(StartDummyGoalie, port);
  }
  for (int i=0; i<FLAGS_defense_chasers; ++i) {
    player_threads[threadNum++] = std::thread(StartChaser, port, "base_right",
                                              i == 0 ? 1 : 0);
  }
  for (int i = 0; i < threadNum; ++i) {
    player_threads[i].join();
  }
  // StopHFOServer();
  server_thread.join();
};


text:
We follow the [Github flow](https://guides.github.com/introduction/flow/) development model.

### Fork the project, then clone your repo

First [fork and clone](https://help.github.com/articles/fork-a-repo) the project project.

### Create a feature branch

*Always* branch off master for new features.

```
git checkout -b mydescriptivebranchname
```

### Edit and build the code

The [developer guide](http://dev.px4.io/) explains how to set up the development environment on Mac OS, Linux or Windows. Please take note of our [coding style](http://px4.io/dev/code_style) when editing files.

### Commit your changes

Always write descriptive commit messages and add a fixes or relates note to them with an [issue number](https://github.com/px4/Firmware/issues) (Github will link these then conveniently)

**Example:**

```
Change how the attitude controller works

- Fixes rate feed forward
- Allows a local body rate override

Fixes issue #123
```

### Test your changes

Since we care about safety, we will regularly ask you for test results. Best is to do a test flight (or bench test where it applies) and upload the logfile from it (on the microSD card in the logs directory) to Google Drive or Dropbox and share the link.

### Push your changes

Push changes to your repo and send a [pull request](https://github.com/PX4/Firmware/compare/).

Make sure to provide some testing feedback and if possible the link to a flight log file. Upload flight log files to [Log Muncher](http://dash.oznet.ch) and link the resulting report.

redpajama_set_name: RedPajamaGithub


text:
NOTE: This repository has been retired.

The latest OpenTracing APIs can be found in the official repository: http://opentracing.io/apis/


text:
<?php

namespace CodeTool\ArtifactDownloader\EtcdClient\Error;

use CodeTool\ArtifactDownloader\Error\Error;
use CodeTool\ArtifactDownloader\Error\ErrorInterface;

use CodeTool\ArtifactDownloader\EtcdClient\Error\Details\EtcdClientErrorDetailsInterface;

class EtcdClientError extends Error implements EtcdClientErrorInterface
{
    /**
     * @var EtcdClientErrorDetailsInterface|null
     */
    private $details;

    /**
     * @param string                               $message
     * @param EtcdClientErrorDetailsInterface|null $details
     * @param mixed                                $context
     * @param ErrorInterface|null                  $prevError
     */
    public function __construct(
        $message,
        EtcdClientErrorDetailsInterface $details = null,
        $context = null,
        ErrorInterface $prevError = null
    ) {
        $this->details = $details;
        parent::__construct($message, $context, $prevError);
    }

    /**
     * @return EtcdClientErrorDetailsInterface|null
     */
    public function getDetails()
    {
        return $this->details;
    }
}


text:
/**
 * Created by Bell on 16/8/25.
 */

import mongoose from 'mongoose';
mongoose.Promise = global.Promise;

const Patch = new mongoose.Schema({
    project_id: {type: String, required: true, index: true},
    project_version: {type: String, required: true, index: true},
    patch_version: {type: Number, required: true, index: true},
    patch_url: {type: String, required: true},
    hash: {type: String, required: true}
});

export default mongoose.model('patch', Patch);


text:
package com.saradhi;

/**
 *
 * The proxy controlling access to WizardTower.
 *
 */
public class WizardTowerProxy extends WizardTower {

	private static final int NUM_WIZARDS_ALLOWED = 3;

	private int numWizards;

	@Override
	public void enter(Wizard wizard) {
		if (numWizards < NUM_WIZARDS_ALLOWED) {
			super.enter(wizard);
			numWizards++;
		} else {
			System.out.println(wizard + " is not allowed to enter!");
		}
	}
}


text:
using System;
using System.Linq;
using Orchard.Layouts.Framework.Display;
using Orchard.Layouts.Framework.Elements;

namespace Orchard.Layouts.Framework.Drivers {
    public abstract class ElementDriver<TElement> : Component, IElementDriver where TElement: Element {
        public virtual int Priority {
            get { return 0; }
        }

        public EditorResult BuildEditor(ElementEditorContext context) {
            return OnBuildEditor((TElement) context.Element, context);
        }

        public EditorResult UpdateEditor(ElementEditorContext context) {
            return OnUpdateEditor((TElement)context.Element, context);
        }

        public void Displaying(ElementDisplayContext context) {
            OnDisplaying((TElement) context.Element, context);
        }

        public void LayoutSaving(ElementSavingContext context) {
            OnLayoutSaving((TElement) context.Element, context);
        }

        public void Removing(ElementRemovingContext context) {
            OnRemoving((TElement) context.Element, context);
        }

        public void Exporting(ExportElementContext context) {
            OnExporting((TElement)context.Element, context);
        }

        public void Importing(ImportElementContext context) {
            OnImporting((TElement)context.Element, context);
        }

        protected virtual EditorResult OnBuildEditor(TElement element, ElementEditorContext context) {
            return null;
        }

        protected virtual EditorResult OnUpdateEditor(TElement element, ElementEditorContext context) {
            return OnBuildEditor(element, context);
        }

        protected virtual void OnDisplaying(TElement element, ElementDisplayContext context) {
        }

        protected virtual void OnLayoutSaving(TElement element, ElementSavingContext context) {
        }

        protected virtual void OnRemoving(TElement element, ElementRemovingContext context) {
        }

        protected virtual void OnExporting(TElement element, ExportElementContext context) {
        }

        protected virtual void OnImporting(TElement element, ImportElementContext context) {
        }

        protected EditorResult Editor(ElementEditorContext context, params dynamic[] editorShapes) {
            foreach (var editorShape in editorShapes) {
                if (String.IsNullOrWhiteSpace(editorShape.Metadata.Position)) {
                    editorShape.Metadata.Position = "Properties:0";
                }
            }

            var result = new EditorResult {
                Editors = editorShapes.ToList()
            };

            return result;
        }
    }
}


text:
import os
import sys

class Config(object):
    """Configuration variables for this test suite

    This creates a variable named CONFIG (${CONFIG} when included
    in a test as a variable file.

    Example:

    *** Settings ***
    | Variable | ../resources/config.py

    *** Test Cases ***
    | Example
    | | log | username: ${CONFIG}.username
    | | log | root url: ${CONFIG}.root_url

    """

    def __init__(self):
        _here = os.path.dirname(__file__)

        sys.path.insert(0, os.path.abspath(os.path.join(_here, "..", "..")))
        sys.path.insert(0, os.path.abspath(os.path.join(_here)))

        self.demo_root = os.path.abspath(os.path.join(_here, ".."))
        self.port = 8000
        self.root_url = "http://localhost:%s" % self.port
        self.username="test user"
        self.password="password"

    def __str__(self):
        return "<Config: %s>" % str(self.__dict__)

# This creates a variable that robot can see
CONFIG = Config()


text:
**********************************
rmgpy.molecule.draw.ReactionDrawer
**********************************

.. autoclass:: rmgpy.molecule.draw.ReactionDrawer


text:
@interface PDFKType3Font : PDFKSimpleFont {

}

@end


text:
package org.ovirt.engine.ui.common.widget.editor.generic;

import java.util.Arrays;

import org.ovirt.engine.ui.common.widget.VisibilityRenderer;
import org.ovirt.engine.ui.common.widget.parser.generic.ToIntEntityModelParser;
import org.ovirt.engine.ui.uicompat.ConstantsManager;

public class IntegerEntityModelTextBoxOnlyEditor extends NumberEntityModelTextBoxOnlyEditor<Integer> {

    public IntegerEntityModelTextBoxOnlyEditor(VisibilityRenderer visibilityRenderer) {
        super(new EntityModelTextBox<>(new ToStringEntityModelRenderer<Integer>(), new ToIntEntityModelParser()),
             visibilityRenderer);
    }

    public IntegerEntityModelTextBoxOnlyEditor() {
        super(new EntityModelTextBox<>(new ToStringEntityModelRenderer<Integer>(),
                new ToIntEntityModelParser()), new VisibilityRenderer.SimpleVisibilityRenderer());
    }

    @Override
    protected void handleInvalidState() {
        //Be sure to call super.handleInvalidstate to make sure the editor valid state is properly updated.
        super.handleInvalidState();
        markAsInvalid(Arrays.asList(ConstantsManager.getInstance().getConstants()
                .thisFieldMustContainIntegerNumberInvalidReason()));
    }

}


text:
package org.alfresco.jive.cmis.dao;

import com.jivesoftware.base.database.dao.DAOException;
import com.jivesoftware.community.impl.dao.DocumentBean;

public interface CmisDocumentDAO {
	/**
     * Retrieve a document's bean by documentID and version. If no document is found null will be
     * returned.
     *
     * @param documentID the document ID of the document to return
     * @param versionID the version ID of the document to return
     * @return a bean containing the document
     * @throws DAOException if an error occurs retrieving the document
     */
    DocumentBean getByDocumentCmisID(String cmisID) throws DAOException;
}


text:
'use strict';

module.exports = function(grunt) {

  grunt.initConfig({
    clean: ['test/**/*.gen.*'],

    jshint: {
      all: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'tasks/**/*.js'],
      options: {
        jshintrc: '.jshintrc',
      },
    },

    nodeunit: {
      all: ['test/**/*_test.js']
    },

    // tests runs csslint programmatically, this task is used only for debugging a failed test
    csslint: {
      options: {
        import: false
      },
      src: ['test/**/*.css']
    }
  });

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-nodeunit');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-csslint');

  grunt.registerTask('default', ['clean', 'jshint', 'nodeunit']);

};


text:
namespace arangodb {
class LocalDocumentId;
class SingleCollectionTransaction;

namespace aql {
struct AstNode;
struct Variable;
}

class RestEdgesHandler : public RestVocbaseBaseHandler {
 public:
  explicit RestEdgesHandler(GeneralRequest*, GeneralResponse*);

 public:
  RestStatus execute() override final;
  char const* name() const override final { return "RestEdgesHandler"; }

 protected:
  //////////////////////////////////////////////////////////////////////////////
  /// @brief reads all edges in given direction for given vertex
  //////////////////////////////////////////////////////////////////////////////

  bool readEdges();

  //////////////////////////////////////////////////////////////////////////////
  /// @brief reads all edges in given direction for a list of vertices
  //////////////////////////////////////////////////////////////////////////////

  bool readEdgesForMultipleVertices();

  //////////////////////////////////////////////////////////////////////////////
  /// @brief find the index and read it completely with the given callback
  //////////////////////////////////////////////////////////////////////////////

  void readCursor(aql::AstNode* condition, aql::Variable const* var,
                  std::string const& collectionName,
                  SingleCollectionTransaction& trx,
                  std::function<void(LocalDocumentId const&)> const& cb);

  //////////////////////////////////////////////////////////////////////////////
  /// @brief get all edges for a given vertex. Independent from the request
  //////////////////////////////////////////////////////////////////////////////

  bool getEdgesForVertex(
      std::string const& id, std::string const& collectionName,
      TRI_edge_direction_e direction, SingleCollectionTransaction& trx,
      std::function<void(LocalDocumentId const&)> const& cb);

  //////////////////////////////////////////////////////////////////////////////
  /// @brief Parse the direction parameter
  //////////////////////////////////////////////////////////////////////////////

  bool parseDirection(TRI_edge_direction_e& direction);

  //////////////////////////////////////////////////////////////////////////////
  /// @brief Validate that the collection exists and is an edge collection
  //////////////////////////////////////////////////////////////////////////////

  bool validateCollection(std::string const& name);
};
}

#endif


text:
package com.google.cloud.bigtable.config;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.util.List;

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.util.SecurityUtils;
import com.google.auth.Credentials;
import com.google.auth.oauth2.ComputeEngineCredentials;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.cloud.bigtable.config.CredentialOptions.JsonCredentialsOptions;
import com.google.cloud.bigtable.config.CredentialOptions.P12CredentialOptions;
import com.google.cloud.bigtable.config.CredentialOptions.UserSuppliedCredentialOptions;
import com.google.common.collect.ImmutableList;

/**
 * Simple factory for creating OAuth Credential objects for use with Bigtable.
 */
public class CredentialFactory {

  /**
   * The OAuth scope required to perform administrator actions such as creating tables.
   */
  public static final String CLOUD_BIGTABLE_ADMIN_SCOPE =
      "https://www.googleapis.com/auth/cloud-bigtable.admin";
  /**
   * The OAuth scope required to read data from tables.
   */
  public static final String CLOUD_BIGTABLE_READER_SCOPE =
      "https://www.googleapis.com/auth/cloud-bigtable.data.readonly";
  /**
   * The OAuth scope required to write data to tables.
   */
  public static final String CLOUD_BIGTABLE_WRITER_SCOPE =
      "https://www.googleapis.com/auth/cloud-bigtable.data";

  /**
   * Scopes required to read and write data from tables.
   */
  public static final List<String> CLOUD_BIGTABLE_READ_WRITE_SCOPES =
      ImmutableList.of(
          CLOUD_BIGTABLE_READER_SCOPE,
          CLOUD_BIGTABLE_WRITER_SCOPE);

  /**
   * Scopes required for full access to cloud bigtable.
   */
  public static final List<String> CLOUD_BIGTABLE_ALL_SCOPES =
      ImmutableList.of(
          CLOUD_BIGTABLE_READER_SCOPE,
          CLOUD_BIGTABLE_WRITER_SCOPE,
          CLOUD_BIGTABLE_ADMIN_SCOPE);

  // HTTP transport used for created credentials to perform token-refresh handshakes with remote
  // credential servers. Initialized lazily to move the possibility of throwing
  // GeneralSecurityException to the time a caller actually tries to get a credential.
  private static HttpTransport httpTransport = null;

  /**
   * Returns shared httpTransport instance; initializes httpTransport if it hasn't already been
   * initialized.
   */
  public static synchronized HttpTransport getHttpTransport()
      throws IOException, GeneralSecurityException {
    if (httpTransport == null) {
      httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    }
    return httpTransport;
  }

  /**
   * Look up a Credentials object based on a configuration of credentials described in a
   * {@link CredentialOptions}.
   */
  public static Credentials getCredentials(CredentialOptions options) throws IOException,
      GeneralSecurityException {
    switch (options.getCredentialType()) {
    case DefaultCredentials:
      return getApplicationDefaultCredential();
    case P12:
      P12CredentialOptions p12Options = (P12CredentialOptions) options;
      return getCredentialFromPrivateKeyServiceAccount(p12Options.getServiceAccount(),
        p12Options.getKeyFile());
    case SuppliedCredentials:
      return ((UserSuppliedCredentialOptions) options).getCredential();
    case SuppliedJson:
      return getInputStreamCredential(((JsonCredentialsOptions) options).getInputStream());
    case None:
      return null;
    default:
      throw new IllegalStateException("Cannot process Credential type: "
          + options.getCredentialType());
    }
  }

  /**
   * Initializes OAuth2 credential using preconfigured ServiceAccount settings on the local
   * GCE VM. See: Authenticating from Google Compute Engine.
   */
  public static Credentials getCredentialFromMetadataServiceAccount()
      throws IOException, GeneralSecurityException {
    return new ComputeEngineCredentials(getHttpTransport());
  }

  /**
   * Initializes OAuth2 credential from a private keyfile, as described in
   *  OAuth2 Service Accounts.
   *
   * @param serviceAccountEmail Email address of the service account associated with the keyfile.
   * @param privateKeyFile Full local path to private keyfile.
   */
  public static Credentials getCredentialFromPrivateKeyServiceAccount(
      String serviceAccountEmail, String privateKeyFile)
      throws IOException, GeneralSecurityException {
    return getCredentialFromPrivateKeyServiceAccount(
        serviceAccountEmail, privateKeyFile, CLOUD_BIGTABLE_ALL_SCOPES);
  }

  /**
   * Initializes OAuth2 credential from a private keyfile, as described in
   *  OAuth2 Service Accounts.
   *
   * @param serviceAccountEmail Email address of the service account associated with the keyfile.
   * @param privateKeyFile Full local path to private keyfile.
   * @param scopes List of well-formed desired scopes to use with the credential.
   */
  public static Credentials getCredentialFromPrivateKeyServiceAccount(
      String serviceAccountEmail, String privateKeyFile, List<String> scopes)
      throws IOException, GeneralSecurityException {
    String clientId = null;
    String privateKeyId = null;
    PrivateKey privateKey =
        SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(),
          new FileInputStream(privateKeyFile), "notasecret", "privatekey", "notasecret");
    return new ServiceAccountCredentials(clientId, serviceAccountEmail, privateKey, privateKeyId,
        scopes, getHttpTransport());
  }

  /**
   * Initializes OAuth2 application default credentials based on the environment the code is running
   * in. If a service account is to be used with JSON file, set the environment variable with name
   * "GOOGLE_APPLICATION_CREDENTIALS" to the JSON file path. For more details on application default
   * credentials:
   *
   * Application Default Credentials.
   */
  public static Credentials getApplicationDefaultCredential() throws IOException,
      GeneralSecurityException {
    return GoogleCredentials.getApplicationDefault(getHttpTransport()).createScoped(
      CLOUD_BIGTABLE_ALL_SCOPES);
  }

  /**
   * Initializes OAuth2 application default credentials based on an inputStream.
   */
  public static Credentials getInputStreamCredential(InputStream inputStream) throws IOException,
      GeneralSecurityException {
    return GoogleCredentials.fromStream(inputStream, getHttpTransport()).createScoped(
      CLOUD_BIGTABLE_ALL_SCOPES);
  }
}


text:
package aggregation

import (
	"bytes"
	"fmt"

	"github.com/juju/errors"
	"github.com/pingcap/tidb/mysql"
	"github.com/pingcap/tidb/sessionctx/variable"
	"github.com/pingcap/tidb/util/types"
)

type concatFunction struct {
	aggFunction
}

// Clone implements Aggregation interface.
func (cf *concatFunction) Clone() Aggregation {
	nf := *cf
	for i, arg := range cf.Args {
		nf.Args[i] = arg.Clone()
	}
	nf.resultMapper = make(aggCtxMapper)
	return &nf
}

// GetType implements Aggregation interface.
func (cf *concatFunction) GetType() *types.FieldType {
	return types.NewFieldType(mysql.TypeVarString)
}

func (cf *concatFunction) writeValue(ctx *aggEvaluateContext, val types.Datum) {
	if val.Kind() == types.KindBytes {
		ctx.Buffer.Write(val.GetBytes())
	} else {
		ctx.Buffer.WriteString(fmt.Sprintf("%v", val.GetValue()))
	}
}

// Update implements Aggregation interface.
func (cf *concatFunction) Update(row []types.Datum, groupKey []byte, sc *variable.StatementContext) error {
	ctx := cf.getContext(groupKey)
	cf.datumBuf = cf.datumBuf[:0]
	for _, a := range cf.Args {
		value, err := a.Eval(row)
		if err != nil {
			return errors.Trace(err)
		}
		if value.GetValue() == nil {
			return nil
		}
		cf.datumBuf = append(cf.datumBuf, value)
	}
	if cf.Distinct {
		d, err := ctx.DistinctChecker.Check(cf.datumBuf)
		if err != nil {
			return errors.Trace(err)
		}
		if !d {
			return nil
		}
	}
	if ctx.Buffer == nil {
		ctx.Buffer = &bytes.Buffer{}
	} else {
		// now use comma separator
		ctx.Buffer.WriteString(",")
	}
	for _, val := range cf.datumBuf {
		cf.writeValue(ctx, val)
	}
	// TODO: if total length is greater than global var group_concat_max_len, truncate it.
	return nil
}

// StreamUpdate implements Aggregation interface.
func (cf *concatFunction) StreamUpdate(row []types.Datum, sc *variable.StatementContext) error {
	ctx := cf.getStreamedContext()
	cf.datumBuf = cf.datumBuf[:0]
	for _, a := range cf.Args {
		value, err := a.Eval(row)
		if err != nil {
			return errors.Trace(err)
		}
		if value.GetValue() == nil {
			return nil
		}
		cf.datumBuf = append(cf.datumBuf, value)
	}
	if cf.Distinct {
		d, err := ctx.DistinctChecker.Check(cf.datumBuf)
		if err != nil {
			return errors.Trace(err)
		}
		if !d {
			return nil
		}
	}
	if ctx.Buffer == nil {
		ctx.Buffer = &bytes.Buffer{}
	} else {
		// now use comma separator
		ctx.Buffer.WriteString(",")
	}
	for _, val := range cf.datumBuf {
		cf.writeValue(ctx, val)
	}
	// TODO: if total length is greater than global var group_concat_max_len, truncate it.
	return nil
}

// GetGroupResult implements Aggregation interface.
func (cf *concatFunction) GetGroupResult(groupKey []byte) (d types.Datum) {
	ctx := cf.getContext(groupKey)
	if ctx.Buffer != nil {
		d.SetString(ctx.Buffer.String())
	} else {
		d.SetNull()
	}
	return d
}

// GetPartialResult implements Aggregation interface.
func (cf *concatFunction) GetPartialResult(groupKey []byte) []types.Datum {
	return []types.Datum{cf.GetGroupResult(groupKey)}
}

// GetStreamResult implements Aggregation interface.
func (cf *concatFunction) GetStreamResult() (d types.Datum) {
	if cf.streamCtx == nil {
		return
	}
	if cf.streamCtx.Buffer != nil {
		d.SetString(cf.streamCtx.Buffer.String())
	} else {
		d.SetNull()
	}
	cf.streamCtx = nil
	return
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.Fx.Portability.ObjectModel;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection;
using Xunit;

namespace Microsoft.Fx.Portability.Tests
{
    public class ReadWriteApiPortOptionsTests
    {
        [Fact]
        public static void AllPropertiesCopied()
        {
            var options = new TestOptions();
            var wrappedOptions = new ReadWriteApiPortOptions(options);

            foreach (var property in typeof(IApiPortOptions).GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                Assert.Equal(property.GetValue(options), property.GetValue(wrappedOptions));
            }
        }

        public class TestOptions : IApiPortOptions
        {
            public IEnumerable<string> BreakingChangeSuppressions { get; } = GenerateRandomList(5);

            public string Description { get; } = GetRandomString();

            public IEnumerable<string> IgnoredAssemblyFiles { get; } = GenerateRandomList(5);

            public ImmutableDictionary<IAssemblyFile, bool> InputAssemblies { get; } = ImmutableDictionary<IAssemblyFile, bool>.Empty.Add(new TestAssemblyFile(), false);

            public IEnumerable<string> InvalidInputFiles { get; } = GenerateRandomList(5);

            public string OutputFileName { get; } = GetRandomString();

            public IEnumerable<string> OutputFormats { get; } = GenerateRandomList(5);

            public AnalyzeRequestFlags RequestFlags { get; } = AnalyzeRequestFlags.ShowBreakingChanges | AnalyzeRequestFlags.ShowNonPortableApis;

            public string ServiceEndpoint { get; } = GetRandomString();

            public IEnumerable<string> Targets { get; } = GenerateRandomList(5);

            public bool OverwriteOutputFile { get; }

            public IEnumerable<string> ReferencedNuGetPackages { get; }

            private static IEnumerable<string> GenerateRandomList(int length)
            {
                return Enumerable.Range(0, length)
                    .Select(_ => GetRandomString())
                    .ToList();
            }

            private static string GetRandomString() => Guid.NewGuid().ToString();

            private class TestAssemblyFile : IAssemblyFile
            {
                public bool Exists { get; } = true;

                public string Name { get; } = Path.GetTempFileName();

                public string Version { get; } = string.Empty;

                public Stream OpenRead() => File.OpenRead(Name);
            }
        }
    }
}


text:
namespace Punch.Helpers
{
    public enum FieldType
    {
        Input,
        TextArea,
        Select
    }
}


text:
#region S# License

#endregion S# License
namespace StockSharp.Messages
{
	using System;
	using System.Runtime.Serialization;

	using Ecng.Common;

	/// <summary>
	/// Message security lookup for specified criteria.
	/// </summary>
	[DataContract]
	[Serializable]
	public class PortfolioLookupMessage : PortfolioMessage
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="PortfolioLookupMessage"/>.
		/// </summary>
		public PortfolioLookupMessage()
			: base(MessageTypes.PortfolioLookup)
		{
		}

		/// <summary>
		/// Create a copy of <see cref="PortfolioLookupMessage"/>.
		/// </summary>
		/// <returns>Copy.</returns>
		public override Message Clone()
		{
			return CopyTo(new PortfolioLookupMessage());
		}

		/// <summary>
		/// Returns a string that represents the current object.
		/// </summary>
		/// <returns>A string that represents the current object.</returns>
		public override string ToString()
		{
			return base.ToString() + ",TransId={0},Curr={1},Board={2},IsSubscribe={3}".Put(TransactionId, Currency, BoardCode, IsSubscribe);
		}
	}
}


text:
from tempest import config
from tempest.lib.common.utils import data_utils
import testtools
from testtools import testcase as tc

from manila_tempest_tests.common import constants
from manila_tempest_tests.tests.api import base

CONF = config.CONF

@testtools.skipUnless(
    CONF.share.run_share_group_tests, 'Share Group tests disabled.')
@base.skip_if_microversion_lt(constants.MIN_SHARE_GROUP_MICROVERSION)
class ShareGroupsTest(base.BaseSharesAdminTest):

    @classmethod
    def resource_setup(cls):
        super(ShareGroupsTest, cls).resource_setup()
        # Create 2 share_types
        name = data_utils.rand_name("tempest-manila")
        extra_specs = cls.add_extra_specs_to_dict()
        share_type = cls.create_share_type(name, extra_specs=extra_specs)
        cls.share_type = share_type['share_type']

        name = data_utils.rand_name("tempest-manila")
        share_type = cls.create_share_type(name, extra_specs=extra_specs)
        cls.share_type2 = share_type['share_type']

        cls.sg_type = cls.create_share_group_type(
            name=name,
            share_types=[cls.share_type['id'], cls.share_type2['id']],
            cleanup_in_class=True,
            version=constants.MIN_SHARE_GROUP_MICROVERSION)

    @tc.attr(base.TAG_POSITIVE, base.TAG_API)
    def test_create_share_group_with_single_share_type_min(self):
        share_group = self.create_share_group(
            share_group_type_id=self.sg_type['id'],
            cleanup_in_class=False,
            share_type_ids=[self.share_type['id']],
            version=constants.MIN_SHARE_GROUP_MICROVERSION)

        keys = set(share_group.keys())
        self.assertTrue(
            constants.SHARE_GROUP_DETAIL_REQUIRED_KEYS.issubset(keys),
            'At least one expected element missing from share group '
            'response. Expected %(expected)s, got %(actual)s.' % {
                "expected": constants.SHARE_GROUP_DETAIL_REQUIRED_KEYS,
                "actual": keys})

        actual_sg_type = share_group['share_group_type_id']
        expected_sg_type = self.sg_type['id']
        self.assertEqual(
            expected_sg_type, actual_sg_type,
            'Incorrect share group type applied to share group '
            '%s. Expected %s, got %s' % (
                share_group['id'], expected_sg_type, actual_sg_type))

        actual_share_types = share_group['share_types']
        expected_share_types = [self.share_type['id']]
        self.assertEqual(
            sorted(expected_share_types),
            sorted(actual_share_types),
            'Incorrect share types applied to share group %s. '
            'Expected %s, got %s' % (
                share_group['id'], expected_share_types, actual_share_types))

    @tc.attr(base.TAG_POSITIVE, base.TAG_API)
    def test_create_share_group_with_multiple_share_types_min(self):
        share_group = self.create_share_group(
            share_group_type_id=self.sg_type['id'],
            cleanup_in_class=False,
            share_type_ids=[self.share_type['id'], self.share_type2['id']],
            version=constants.MIN_SHARE_GROUP_MICROVERSION)

        keys = set(share_group.keys())
        self.assertTrue(
            constants.SHARE_GROUP_DETAIL_REQUIRED_KEYS.issubset(keys),
            'At least one expected element missing from share group '
            'response. Expected %(expected)s, got %(actual)s.' % {
                "expected": constants.SHARE_GROUP_DETAIL_REQUIRED_KEYS,
                "actual": keys})

        actual_sg_type = share_group['share_group_type_id']
        expected_sg_type = self.sg_type['id']
        self.assertEqual(
            expected_sg_type, actual_sg_type,
            'Incorrect share group type applied to share group %s. '
            'Expected %s, got %s' % (
                share_group['id'], expected_sg_type, actual_sg_type))

        actual_share_types = share_group['share_types']
        expected_share_types = [self.share_type['id'], self.share_type2['id']]
        self.assertEqual(
            sorted(expected_share_types),
            sorted(actual_share_types),
            'Incorrect share types applied to share group %s. '
            'Expected %s, got %s' % (
                share_group['id'], expected_share_types, actual_share_types))

    @tc.attr(base.TAG_POSITIVE, base.TAG_API)
    def test_default_share_group_type_applied(self):
        default_type = self.shares_v2_client.get_default_share_group_type()
        default_share_types = default_type['share_types']

        share_group = self.create_share_group(
            cleanup_in_class=False,
            share_type_ids=default_share_types,
            version=constants.MIN_SHARE_GROUP_MICROVERSION)

        keys = set(share_group.keys())
        self.assertTrue(
            constants.SHARE_GROUP_DETAIL_REQUIRED_KEYS.issubset(keys),
            'At least one expected element missing from share group '
            'response. Expected %(expected)s, got %(actual)s.' % {
                "expected": constants.SHARE_GROUP_DETAIL_REQUIRED_KEYS,
                "actual": keys})

        actual_sg_type = share_group['share_group_type_id']
        expected_sg_type = default_type['id']
        self.assertEqual(
            expected_sg_type, actual_sg_type,
            'Incorrect share group type applied to share group %s. '
            'Expected %s, got %s' % (
                share_group['id'], expected_sg_type, actual_sg_type))

    @testtools.skipUnless(
        CONF.share.multitenancy_enabled, "Only for multitenancy.")
    @tc.attr(base.TAG_POSITIVE, base.TAG_API)
    def test_create_sg_from_snapshot_verify_share_server_information_min(self):
        # Create a share group
        orig_sg = self.create_share_group(
            share_group_type_id=self.sg_type['id'],
            cleanup_in_class=False,
            share_type_ids=[self.share_type['id']],
            version=constants.MIN_SHARE_GROUP_MICROVERSION)

        # Get latest share group information
        orig_sg = self.shares_v2_client.get_share_group(
            orig_sg['id'], version=constants.MIN_SHARE_GROUP_MICROVERSION)

        # Assert share server information
        self.assertIsNotNone(orig_sg['share_network_id'])
        self.assertIsNotNone(orig_sg['share_server_id'])

        sg_snapshot = self.create_share_group_snapshot_wait_for_active(
            orig_sg['id'], cleanup_in_class=False,
            version=constants.MIN_SHARE_GROUP_MICROVERSION)
        new_sg = self.create_share_group(
            share_group_type_id=self.sg_type['id'],
            cleanup_in_class=False,
            version=constants.MIN_SHARE_GROUP_MICROVERSION,
            source_share_group_snapshot_id=sg_snapshot['id'])

        # Assert share server information
        self.assertEqual(
            orig_sg['share_network_id'], new_sg['share_network_id'])
        self.assertEqual(
            orig_sg['share_server_id'], new_sg['share_server_id'])


text:
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

using Microsoft.Win32.SafeHandles;
using System;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Security.AccessControl;
using System.Security.Principal;

namespace Thrift.Transport.Server
{
    // ReSharper disable once InconsistentNaming
    public class TNamedPipeServerTransport : TServerTransport
    {
        /// <summary>
        ///     This is the address of the Pipe on the localhost.
        /// </summary>
        private readonly string _pipeAddress;
        private bool _asyncMode = true;
        private volatile bool _isPending = true;
        private NamedPipeServerStream _stream = null;

        public TNamedPipeServerTransport(string pipeAddress)
        {
            _pipeAddress = pipeAddress;
        }

        public override void Listen()
        {
            // nothing to do here
        }

        public override void Close()
        {
            if (_stream != null)
            {
                try
                {
                    if (_stream.IsConnected)
                        _stream.Disconnect();
                    _stream.Dispose();
                }
                finally
                {
                    _stream = null;
                    _isPending = false;
                }
            }
        }

        public override bool IsClientPending()
        {
            return _isPending;
        }

        private void EnsurePipeInstance()
        {
            if (_stream == null)
            {
                const PipeDirection direction = PipeDirection.InOut;
                const int maxconn = NamedPipeServerStream.MaxAllowedServerInstances;
                const PipeTransmissionMode mode = PipeTransmissionMode.Byte;
                const int inbuf = 4096;
                const int outbuf = 4096;
                var options = _asyncMode ? PipeOptions.Asynchronous : PipeOptions.None;

                // TODO: "CreatePipeNative" ist only a workaround, and there are have basically two possible outcomes:
                // - once NamedPipeServerStream() gets a CTOR that supports pipesec, remove CreatePipeNative()
                // - if 31190 gets resolved before, use _stream.SetAccessControl(pipesec) instead of CreatePipeNative()
                // EITHER WAY,
                // - if CreatePipeNative() finally gets removed, also remove "allow unsafe code" from the project settings

                try
                {
                    var handle = CreatePipeNative(_pipeAddress, inbuf, outbuf);
                    if( (handle != null) && (!handle.IsInvalid))
                        _stream = new NamedPipeServerStream(PipeDirection.InOut, _asyncMode, false, handle);
                    else
                        _stream = new NamedPipeServerStream(_pipeAddress, direction, maxconn, mode, options, inbuf, outbuf/*, pipesec*/);
                }
                catch (NotImplementedException) // Mono still does not support async, fallback to sync
                {
                    if (_asyncMode)
                    {
                        options &= (~PipeOptions.Asynchronous);
                        _stream = new NamedPipeServerStream(_pipeAddress, direction, maxconn, mode, options, inbuf, outbuf);
                        _asyncMode = false;
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }

        #region CreatePipeNative workaround

        [StructLayout(LayoutKind.Sequential)]
        internal class SECURITY_ATTRIBUTES
        {
            internal int nLength = 0;
            internal IntPtr lpSecurityDescriptor = IntPtr.Zero;
            internal int bInheritHandle = 0;
        }

        private const string Kernel32 = "kernel32.dll";

        [DllImport(Kernel32, SetLastError = true)]
        internal static extern IntPtr CreateNamedPipe(
            string lpName, uint dwOpenMode, uint dwPipeMode,
            uint nMaxInstances, uint nOutBufferSize, uint nInBufferSize, uint nDefaultTimeOut,
            SECURITY_ATTRIBUTES pipeSecurityDescriptor
            );

        // Workaround: create the pipe via API call
        // we have to do it this way, since NamedPipeServerStream() for netstd still lacks a few CTORs
        // and _stream.SetAccessControl(pipesec); only keeps throwing ACCESS_DENIED errors at us
        // References:
        // - https://github.com/dotnet/corefx/issues/30170 (closed, continued in 31190)
        // - https://github.com/dotnet/corefx/issues/31190 System.IO.Pipes.AccessControl package does not work
        // - https://github.com/dotnet/corefx/issues/24040 NamedPipeServerStream: Provide support for WRITE_DAC
        // - https://github.com/dotnet/corefx/issues/34400 Have a mechanism for lower privileged user to connect to a privileged user's pipe
        private SafePipeHandle CreatePipeNative(string name, int inbuf, int outbuf)
        {
            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
                return null; // Windows only

            var pinningHandle = new GCHandle();
            try
            {
                // owner gets full access, everyone else read/write
                var pipesec = new PipeSecurity();
                using (var currentIdentity = WindowsIdentity.GetCurrent())
                {
                    var sidOwner = currentIdentity.Owner;
                    var sidWorld = new SecurityIdentifier(WellKnownSidType.WorldSid, null);

                    pipesec.SetOwner(sidOwner);
                    pipesec.AddAccessRule(new PipeAccessRule(sidOwner, PipeAccessRights.FullControl, AccessControlType.Allow));
                    pipesec.AddAccessRule(new PipeAccessRule(sidWorld, PipeAccessRights.ReadWrite, AccessControlType.Allow));
                }

                // create a security descriptor and assign it to the security attribs
                var secAttrs = new SECURITY_ATTRIBUTES();
                byte[] sdBytes = pipesec.GetSecurityDescriptorBinaryForm();
                pinningHandle = GCHandle.Alloc(sdBytes, GCHandleType.Pinned);
                unsafe {
                    fixed (byte* pSD = sdBytes) {
                        secAttrs.lpSecurityDescriptor = (IntPtr)pSD;
                    }
                }

                // a bunch of constants we will need shortly
                const int PIPE_ACCESS_DUPLEX = 0x00000003;
                const int FILE_FLAG_OVERLAPPED = 0x40000000;
                const int WRITE_DAC = 0x00040000;
                const int PIPE_TYPE_BYTE = 0x00000000;
                const int PIPE_READMODE_BYTE = 0x00000000;
                const int PIPE_UNLIMITED_INSTANCES = 255;

                // create the pipe via API call
                var rawHandle = CreateNamedPipe(
                    @"\\.\pipe\" + name,
                    PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | WRITE_DAC,
                    PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
                    PIPE_UNLIMITED_INSTANCES, (uint)inbuf, (uint)outbuf,
                    5 * 1000,
                    secAttrs
                    );

                // make a SafePipeHandle() from it
                var handle = new SafePipeHandle(rawHandle, true);
                if (handle.IsInvalid)
                    throw new Win32Exception(Marshal.GetLastWin32Error());

                // return it (to be packaged)
                return handle;
            }
            finally
            {
                if (pinningHandle.IsAllocated)
                    pinningHandle.Free();
            }
        }

        #endregion

        protected override async ValueTask<TTransport> AcceptImplementationAsync(CancellationToken cancellationToken)
        {
            try
            {
                EnsurePipeInstance();

                await _stream.WaitForConnectionAsync(cancellationToken);

                var trans = new ServerTransport(_stream);
                _stream = null; // pass ownership to ServerTransport

                //_isPending = false;

                return trans;
            }
            catch (TTransportException)
            {
                Close();
                throw;
            }
            catch (Exception e)
            {
                Close();
                throw new TTransportException(TTransportException.ExceptionType.NotOpen, e.Message);
            }
        }

        private class ServerTransport : TTransport
        {
            private readonly NamedPipeServerStream PipeStream;

            public ServerTransport(NamedPipeServerStream stream)
            {
                PipeStream = stream;
            }

            public override bool IsOpen => PipeStream != null && PipeStream.IsConnected;

            public override async Task OpenAsync(CancellationToken cancellationToken)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    await Task.FromCanceled(cancellationToken);
                }
            }

            public override void Close()
            {
                PipeStream?.Dispose();
            }

            public override async ValueTask<int> ReadAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken)
            {
                if (PipeStream == null)
                {
                    throw new TTransportException(TTransportException.ExceptionType.NotOpen);
                }

                return await PipeStream.ReadAsync(buffer, offset, length, cancellationToken);
            }

            public override async Task WriteAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken)
            {
                if (PipeStream == null)
                {
                    throw new TTransportException(TTransportException.ExceptionType.NotOpen);
                }

                // if necessary, send the data in chunks
                // there's a system limit around 0x10000 bytes that we hit otherwise
                // MSDN: "Pipe write operations across a network are limited to 65,535 bytes per write. For more information regarding pipes, see the Remarks section."
                var nBytes = Math.Min(15 * 4096, length); // 16 would exceed the limit
                while (nBytes > 0)
                {
                    await PipeStream.WriteAsync(buffer, offset, nBytes, cancellationToken);
                    offset += nBytes;
                    length -= nBytes;
                    nBytes = Math.Min(nBytes, length);
                }
            }

            public override async Task FlushAsync(CancellationToken cancellationToken)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    await Task.FromCanceled(cancellationToken);
                }
            }

            protected override void Dispose(bool disposing)
            {
                PipeStream?.Dispose();
            }
        }
    }
}


text:
package org.ovirt.engine.core.common.businessentities;

import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import org.ovirt.engine.core.common.businessentities.mapping.GuidType;
import org.ovirt.engine.core.common.validation.annotation.ValidName;
import org.ovirt.engine.core.common.validation.group.CreateEntity;
import org.ovirt.engine.core.common.validation.group.UpdateEntity;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.INotifyPropertyChanged;
import org.ovirt.engine.core.compat.NGuid;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.core.compat.Version;

@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = "storage_pool", namespace = "http://service.engine.ovirt.org")
@Entity
@Table(name = "storage_pool")
@TypeDef(name = "guid", typeClass = GuidType.class)
@NamedQueries(
        value = {
                @NamedQuery(
                        name = "all_storage_pools_for_storage_domain",
                        query = "from storage_pool p where (from storage_domain_static d where d.id = :storage_domain_id) in elements(p.domains)"),
                @NamedQuery(
                        name = "all_storage_pools_for_vds",
                        query = "select p from storage_pool p where p.id in (select g.storagePool from VDSGroup g where g.storagePool = p.id and g.id in (select v.vdsGroupId from VdsStatic v where v.vdsGroupId = g.id and v.id = :vds_id))"),

                @NamedQuery(
                        name = "all_storage_pools_for_vds_group",
                        query = "select p from storage_pool p, VDSGroup g where (g.id = :vds_group_id) and (g.storagePool = p.id)")
                        })
public class storage_pool extends IVdcQueryable implements INotifyPropertyChanged, BusinessEntity<Guid> {

    private static final long serialVersionUID = 8455998477522459262L;

    @XmlElement(name = "Id")
    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "org.ovirt.engine.core.dao.GuidGenerator")
    @Column(name = "id")
    @Type(type = "guid")
    private Guid id = new Guid();

    @ValidName(message = "VALIDATION.DATA_CENTER.NAME.INVALID", groups = { CreateEntity.class, UpdateEntity.class })
    @XmlElement(name = "name")
    @Size(min = 1, max = BusinessEntitiesDefinitions.DATACENTER_NAME_SIZE)
    @Column(name = "name")
    private String name = ""; // GREGM prevents NPE

    @XmlElement(name = "description")
    @Size(max = BusinessEntitiesDefinitions.GENERAL_MAX_SIZE)
    @Column(name = "description")
    private String description;

    @Column(name = "storage_pool_type")
    private int storagePoolType = StorageType.UNKNOWN.getValue();

    @XmlElement(name = "StoragePoolFormatType", nillable = true)
    @Column(name = "storage_pool_format_type")
    private StorageFormatType storagePoolFormatType = null;

    @XmlElement(name = "status")
    @Column(name = "status")
    private StoragePoolStatus status = StoragePoolStatus.Uninitialized;
    @XmlElement(name = "master_domain_version")
    @Column(name = "master_domain_version")
    private int masterDomainVersion;

    @XmlElement(name = "spm_vds_id")
    @Column(name = "spm_vds_id")
    @Type(type = "guid")
    private NGuid spmVdsId = new NGuid();

    @Size(max = BusinessEntitiesDefinitions.GENERAL_VERSION_SIZE)
    @Column(name = "compatibility_version")
    private String compatibilityVersion;

    @XmlElement(name = "LVER")
    @Transient
    private String LVER;

    @XmlElement(name = "recovery_mode")
    @Transient
    private RecoveryMode recovery_mode = RecoveryMode.forValue(0);

    // TODO this is a hack to get around how the old mappings were done
    // This will be redone in version 3.0 with proper relationship mapping
    @OneToMany(mappedBy = "storagePool", cascade = CascadeType.MERGE)
    private Set<VDSGroup> vdsGroups;

    @ManyToMany
    @JoinTable(name = "storage_pool_iso_map", joinColumns = @JoinColumn(name = "storage_pool_id"),
            inverseJoinColumns = @JoinColumn(name = "storage_id"))
    private List<storage_domain_static> domains;

    @Transient
    private Version version;

    public storage_pool() {
        description = "";
        masterDomainVersion = 0;
    }

    public storage_pool(String description, Guid id, String name, int storage_pool_type, int status) {
        this();
        this.description = description;
        this.id = id;
        this.name = name;
        setstorage_pool_type(StorageType.forValue(storage_pool_type));
        this.status = StoragePoolStatus.forValue(status);
    }

    public String getdescription() {
        if (description == null) {
            description = "";
        }
        return description;
    }

    public void setdescription(String value) {
        this.description = value;
    }

    @Override
    public Guid getId() {
        return this.id;
    }

    @Override
    public void setId(Guid id) {
        this.id = id;
    }

    public String getname() {
        return this.name;
    }

    public void setname(String value) {
        if (!StringHelper.EqOp(this.name, value)) {
            this.name = value;
        }
    }

    @XmlElement(name = "storage_pool_type")
    public StorageType getstorage_pool_type() {
        return StorageType.forValue(storagePoolType);

    }

    public void setstorage_pool_type(StorageType value) {
        storagePoolType = value.getValue();
    }

    public StorageFormatType getStoragePoolFormatType() {
        return storagePoolFormatType;
    }

    public void setStoragePoolFormatType(StorageFormatType value) {
        storagePoolFormatType = value;
    }

    public StoragePoolStatus getstatus() {
        return status;
    }

    public void setstatus(StoragePoolStatus value) {
        status = value;
    }

    public int getmaster_domain_version() {
        return this.masterDomainVersion;
    }

    public void setmaster_domain_version(int value) {
        this.masterDomainVersion = value;
    }

    @XmlElement(name = "compatibility_version")
    public Version getcompatibility_version() {
        if (version == null) {
            version = new Version(compatibilityVersion);
        }
        return version;
    }

    public void setcompatibility_version(Version value) {
        compatibilityVersion = value.toString();
        version = null;
    }

    @Override
    public Object getQueryableId() {
        return getId();
    }

    private static final java.util.ArrayList<String> _spProperties = new java.util.ArrayList<String>(
            java.util.Arrays.asList(new String[] { "name", "description", "status", "storage_pool_type",
                    "compatibility_version" }));

    @Override
    public java.util.ArrayList<String> getChangeablePropertiesList() {
        return _spProperties;
    }

    public String getLVER() {
        return LVER;
    }

    public void setLVER(String value) {
        LVER = value;
    }

    public RecoveryMode getrecovery_mode() {
        return recovery_mode;
    }

    public void setrecovery_mode(RecoveryMode value) {
        recovery_mode = value;
    }

    public NGuid getspm_vds_id() {
        return spmVdsId;
    }

    public void setspm_vds_id(NGuid value) {
        spmVdsId = value;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((LVER == null) ? 0 : LVER.hashCode());
        result = prime * result + ((compatibilityVersion == null) ? 0 : compatibilityVersion.hashCode());
        result = prime * result + ((description == null) ? 0 : description.hashCode());
        result = prime * result + ((domains == null) ? 0 : domains.hashCode());
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result + masterDomainVersion;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result + ((recovery_mode == null) ? 0 : recovery_mode.hashCode());
        result = prime * result + ((spmVdsId == null) ? 0 : spmVdsId.hashCode());
        result = prime * result + ((status == null) ? 0 : status.hashCode());
        result = prime * result + storagePoolType;
        result = prime * result + ((vdsGroups == null) ? 0 : vdsGroups.hashCode());
        result = prime * result + ((storagePoolFormatType == null) ? 0 : storagePoolFormatType.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        storage_pool other = (storage_pool) obj;
        if (LVER == null) {
            if (other.LVER != null)
                return false;
        } else if (!LVER.equals(other.LVER))
            return false;
        if (description == null) {
            if (other.description != null)
                return false;
        } else if (!description.equals(other.description))
            return false;
        if (getcompatibility_version() == null) {
            if (other.getcompatibility_version() != null)
                return false;
        } else if (!getcompatibility_version().equals(other.getcompatibility_version()))
            return false;
        if (domains == null) {
            if (other.domains != null)
                return false;
        } else if (!domains.equals(other.domains))
            return false;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        if (masterDomainVersion != other.masterDomainVersion)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (recovery_mode != other.recovery_mode)
            return false;
        if (spmVdsId == null) {
            if (other.spmVdsId != null)
                return false;
        } else if (!spmVdsId.equals(other.spmVdsId))
            return false;
        if (status != other.status)
            return false;
        if (storagePoolType != other.storagePoolType)
            return false;
        if (vdsGroups == null) {
            if (other.vdsGroups != null)
                return false;
        } else if (!vdsGroups.equals(other.vdsGroups))
            return false;
        if (storagePoolFormatType == null) {
            if (other.storagePoolFormatType != null)
                return false;
        } else if (storagePoolFormatType != other.storagePoolFormatType)
            return false;
        return true;
    }

}


text:
package com.billyyccc.bridgedemo.shape;

import com.billyyccc.bridgedemo.border.Border;
import com.billyyccc.bridgedemo.color.Color;

/**
 * Created by Billy Yuan on 2017/5/16.
 * Email: billy112487983@gmail.com
 */

public class Triangle extends Shape {
    public Triangle(Color color, Border border) {
        super(color, border);
    }

    @Override
    public void drawBorder() {
        System.out.println("Triangle drawing border...");
        border.applyBorder();
    }

    @Override
    public void color() {
        System.out.println("Triangle coloring...");
        color.applyColor();
    }
}


text:
def func():
    value = "not-none"

    if value is not None:  # Is not none
        print("Not none")
    else:
        print("None")


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>Web Speech API Test: the basics of SpeechGrammar and SpeechGrammarList</title>
<link rel="author" title="Intel" href="http://www.intel.com">
<link rel="help" href="http://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html">


text:
//======================================================================
using UnityEngine;
using System.Collections;
using DG.Tweening;
//======================================================================
public class LobbyCar : FSMSingleton<LobbyCar>, IFSMState<LobbyFSM>
{
    //--------------------------------------------
    public void Enter(LobbyFSM caller)
    {
        StartCoroutine(caller._uiLobbyCtrl._panelLobby.Show(false, 0f, 0.05f));

        caller._uiLobbyCtrl._panelCar.transform.DOLocalMoveY(0, 1);

        caller._uiLobbyCtrl._panelCar.SetCarInfo((int)GlobalData.Instance._eCurCar);

    }// public void Enter(LobbyFSM caller)
    //--------------------------------------------
    public void Execute(LobbyFSM caller) { }
    //--------------------------------------------
    public void Exit(LobbyFSM caller) { caller._uiLobbyCtrl._panelCar.transform.DOLocalMoveY(750, 1); }
    //--------------------------------------------
    public void Skip(LobbyFSM caller) { }
    //--------------------------------------------

}// public class LobbyCar : FSMSingleton<LobbyCar>, IFSMState<LobbyFSM>
//======================================================================


text:
package lx.easydb.dialect.function;

import java.util.List;

import lx.easydb.IConnectionFactory;
import lx.easydb.QueryException;

/**
 * Provides support routines for the functions as used
 * in the various SQL Dialects.
 */
public interface ISQLFunction {
	boolean hasArguments();
	boolean hasParenthesesIfNoArguments();
	int getReturnType(int firstArgumentType);
	String render(int firstArgumentType, @SuppressWarnings("rawtypes") List arguments, IConnectionFactory factory) throws QueryException;
}


text:
package com.github.willjgriff.skeleton.data.storage.realmupdaters.methods;

import io.realm.Realm;

/**
 * Created by Will on 11/09/2016.
 */

public interface RealmUpdateMethod<UPDATETYPE> {

	void updateRealm(Realm realm, UPDATETYPE updatedData);
}


text:
package org.apache.ode.bpel.obj;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.xml.namespace.QName;

import org.apache.ode.bpel.obj.OMessageVarType.Part;
import org.apache.ode.bpel.obj.OProcess.OPropertyAlias;
import org.apache.ode.bpel.obj.OScope.Variable;
import org.w3c.dom.Document;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;

public class OAssign extends OActivity  implements Serializable{
	public static final long serialVersionUID = -1L;
	private static final String COPY = "copy";

	@JsonCreator
	public OAssign(){
	}
	public OAssign(OProcess owner, OActivity parent) {
		super(owner, parent);
		setCopy(new ArrayList<Copy>());
	}

	@Override
	public void dehydrate() {
		super.dehydrate();
		for (Copy copy : getCopy()) {
			copy.dehydrate();
		}
	}

	@SuppressWarnings("unchecked")
	@JsonIgnore
	public List<Copy> getCopy() {
		Object o = fieldContainer.get(COPY);
		return o == null ? null : (List<Copy>)o;
	}

	public void setCopy(List<Copy> copy) {
		if (getCopy() == null){
			fieldContainer.put(COPY, copy);
		}
	}

	public String toString() {
		return "{OAssign : " + getName() + ", joinCondition="
				+ getJoinCondition() + "}";
	}

	/**
	 * Assignmenet copy entry, i.e. what the assignment consits of.
	 */
	public static class Copy extends OBase  implements Serializable{
	public static final long serialVersionUID = -1L;
		private static final String TO = "to";
		private static final String FROM = "from";
		private static final String KEEPSRCELEMENTNAME = "keepSrcElementName";
		private static final String IGNOREMISSINGFROMDATA = "ignoreMissingFromData";
		private static final String IGNOREUNINITIALIZEDFROMVARIABLE = "ignoreUninitializedFromVariable";
		private static final String INSERTMISSINGTODATA = "insertMissingToData";

		@JsonCreator
		public Copy(){
			initPrimitive();
		}
		public Copy(OProcess owner) {
			super(owner);
			initPrimitive();
		}
		private void initPrimitive(){
			setIgnoreMissingFromData(false);
			setIgnoreUninitializedFromVariable(false);
			setInsertMissingToData(false);
			setKeepSrcElementName(false);
		}

		@Override
		public void dehydrate() {
			super.dehydrate();
			setTo(null);
			setFrom(null);
		}

		@JsonIgnore
		public RValue getFrom() {
			Object o = fieldContainer.get(FROM);
		return o == null ? null : (RValue)o;
		}

		@JsonIgnore
		public boolean isIgnoreMissingFromData() {
			Object o = fieldContainer.get(IGNOREMISSINGFROMDATA);
		return o == null ? false : (Boolean)o;
		}

		@JsonIgnore
		public boolean isIgnoreUninitializedFromVariable() {
			return (Boolean) fieldContainer
					.get(IGNOREUNINITIALIZEDFROMVARIABLE);
		}

		@JsonIgnore
		public boolean isInsertMissingToData() {
			Object o = fieldContainer.get(INSERTMISSINGTODATA);
		return o == null ? false : (Boolean)o;
		}

		@JsonIgnore
		public boolean isKeepSrcElementName() {
			Object o = fieldContainer.get(KEEPSRCELEMENTNAME);
		return o == null ? false : (Boolean)o;
		}

		@JsonIgnore
		public LValue getTo() {
			Object o = fieldContainer.get(TO);
		return o == null ? null : (LValue)o;
		}

		public void setFrom(RValue from) {
			fieldContainer.put(FROM, from);
		}

		public void setIgnoreMissingFromData(boolean ignoreMissingFromData) {
			fieldContainer.put(IGNOREMISSINGFROMDATA, ignoreMissingFromData);
		}

		public void setIgnoreUninitializedFromVariable(
				boolean ignoreUninitializedFromVariable) {
			fieldContainer.put(IGNOREUNINITIALIZEDFROMVARIABLE,
					ignoreUninitializedFromVariable);
		}

		public void setInsertMissingToData(boolean insertMissingToData) {
			fieldContainer.put(INSERTMISSINGTODATA, insertMissingToData);
		}

		public void setKeepSrcElementName(boolean keepSrcElementName) {
			fieldContainer.put(KEEPSRCELEMENTNAME, keepSrcElementName);
		}

		public void setTo(LValue to) {
			fieldContainer.put(TO, to);
		}

		public String toString() {
			return "{OCopy " + getTo() + "=" + getFrom() + "}";
		}
	}

	/**
	 * Direct reference: selects named child of the message document element.
	 * This is used for access to extensions (SOAP headers for example).
	 * @author mszefler
	 */
	public static class DirectRef extends OBase implements RValue, LValue, Serializable{
	public static final long serialVersionUID = -1L;
		/** Referenced Variable */
		private static final String VARIABLE = "variable";

		/** Name of the element referenced. */
		private static final String ELNAME = "elName";

		@JsonCreator
		public DirectRef(){}

		public DirectRef(OProcess owner) {
			super(owner);
		}

		@JsonIgnore
		public QName getElName() {
			Object o = fieldContainer.get(ELNAME);
		return o == null ? null : (QName)o;
		}

		@JsonIgnore
		public OScope.Variable getVariable() {
			Object o = fieldContainer.get(VARIABLE);
		return o == null ? null : (OScope.Variable)o;
		}

		public void setElName(QName elName) {
			fieldContainer.put(ELNAME, elName);
		}

		public void setVariable(Variable variable) {
			fieldContainer.put(VARIABLE, variable);
		}
	}

	public static class Expression extends OBase implements RValue, Serializable{
	public static final long serialVersionUID = -1L;
		private static final String EXPRESSION = "expression";

		@JsonCreator
		public Expression(){}
		public Expression(OProcess owner, OExpression compiledExpression) {
			super(owner);
			setExpression(compiledExpression);
		}

		@JsonIgnore
		public OExpression getExpression() {
			Object o = fieldContainer.get(EXPRESSION);
		return o == null ? null : (OExpression)o;
		}

		public void setExpression(OExpression expression) {
			fieldContainer.put(EXPRESSION, expression);
		}

		public String toString() {
			return getExpression().toString();
		}
	}

	public static class Literal extends OBase implements RValue, Serializable{
	public static final long serialVersionUID = -1L;
		private static final String XMLLITERAL = "xmlLiteral";

		@JsonCreator
		public Literal(){}

		public Literal(OProcess owner, Document xmlLiteral) {
			super(owner);
			if (xmlLiteral == null)
				throw new IllegalArgumentException("null xmlLiteral!");
			setXmlLiteral(org.apache.ode.utils.DOMUtils.domToString(xmlLiteral));
		}

		@JsonIgnore
		public String getXmlLiteral() {
			Object o = fieldContainer.get(XMLLITERAL);
		return o == null ? null : (String)o;
		}

		public void setXmlLiteral(String xmlLiteral) {
			fieldContainer.put(XMLLITERAL, xmlLiteral);
		}

		public String toString() {
			return "{Literal " + getXmlLiteral() + "}";
		}
	}

	public interface LValue {
		OScope.Variable getVariable();
	}

	public static class LValueExpression extends OBase implements LValue, Serializable{
	public static final long serialVersionUID = -1L;
		private static final String EXPRESSION = "expression";

		@JsonCreator
		public LValueExpression(){}

		public LValueExpression(OProcess owner,
				OLValueExpression compiledExpression) {
			super(owner);
			setExpression(compiledExpression);
		}

		@JsonIgnore
		public OLValueExpression getExpression() {
			Object o = fieldContainer.get(EXPRESSION);
		return o == null ? null : (OLValueExpression)o;
		}

		/**
		 * @see org.apache.ode.bpel.obj.OAssign.LValue#getVariable()
		 */
		@JsonIgnore
		public Variable getVariable() {
			return getExpression().getVariable();
		}

		@JsonIgnore
		public boolean isInsertMissingToData() {
            return getExpression().isInsertMissingData();
		}

		public void setExpression(OLValueExpression expression) {
			fieldContainer.put(EXPRESSION, expression);
		}

		public void setInsertMissingToData(boolean insertMissingToData) {
			getExpression().setInsertMissingData(insertMissingToData);
		}

		public String toString() {
			return getExpression().toString();
		}

	}

	public static class PartnerLinkRef extends OBase implements RValue, LValue, Serializable{
	public static final long serialVersionUID = -1L;
		private static final String PARTNERLINK = "partnerLink";
		private static final String ISMYENDPOINTREFERENCE = "isMyEndpointReference";

		@JsonCreator
		public PartnerLinkRef(){
			setIsMyEndpointReference(false);
		}
		public PartnerLinkRef(OProcess owner) {
			super(owner);
			setIsMyEndpointReference(false);
		}

		@JsonIgnore
		public boolean isIsMyEndpointReference() {
			Object o = fieldContainer.get(ISMYENDPOINTREFERENCE);
		return o == null ? false : (Boolean)o;
		}

		@JsonIgnore
		public OPartnerLink getPartnerLink() {
			Object o = fieldContainer.get(PARTNERLINK);
		return o == null ? null : (OPartnerLink)o;
		}

		// Must fit in a LValue even if it's not variable based
		@JsonIgnore
		public Variable getVariable() {
			return null;
		}

		public void setIsMyEndpointReference(boolean isMyEndpointReference) {
			fieldContainer.put(ISMYENDPOINTREFERENCE, isMyEndpointReference);
		}

		public void setPartnerLink(OPartnerLink partnerLink) {
			fieldContainer.put(PARTNERLINK, partnerLink);
		}

		public String toString() {
			return "{PLinkRef " + getPartnerLink() + "!"
					+ isIsMyEndpointReference() + "}";
		}
	}

	public static class PropertyRef extends OBase implements RValue, LValue, Serializable{
	public static final long serialVersionUID = -1L;
		private static final String VARIABLE = "variable";
		private static final String PROPERTYALIAS = "propertyAlias";

		@JsonCreator
		public PropertyRef(){}
		public PropertyRef(OProcess owner) {
			super(owner);
		}

		@JsonIgnore
		public OPropertyAlias getPropertyAlias() {
			Object o = fieldContainer.get(PROPERTYALIAS);
		return o == null ? null : (OPropertyAlias)o;
		}

		@JsonIgnore
		public Variable getVariable() {
			Object o = fieldContainer.get(VARIABLE);
		return o == null ? null : (Variable)o;
		}

		public void setPropertyAlias(OPropertyAlias propertyAlias) {
			fieldContainer.put(PROPERTYALIAS, propertyAlias);
		}

		public void setVariable(Variable variable) {
			fieldContainer.put(VARIABLE, variable);
		}

		public String toString() {
			return "{PropRef " + getVariable() + "!" + getPropertyAlias() + "}";
		}
	}

	public interface RValue {
	}

	public static class VariableRef extends OBase implements RValue, LValue, Serializable{
	public static final long serialVersionUID = -1L;
		private static final String VARIABLE = "variable";
		private static final String PART = "part";
		private static final String HEADERPART = "headerPart";
		private static final String LOCATION = "location";

		@JsonCreator
		public VariableRef(){}

		public VariableRef(OProcess owner) {
			super(owner);
		}

		@JsonIgnore
		public Part getHeaderPart() {
			Object o = fieldContainer.get(HEADERPART);
		return o == null ? null : (Part)o;
		}

		@JsonIgnore
		public OExpression getLocation() {
			Object o = fieldContainer.get(LOCATION);
		return o == null ? null : (OExpression)o;
		}

		@JsonIgnore
		public Part getPart() {
			Object o = fieldContainer.get(PART);
		return o == null ? null : (Part)o;
		}

		@JsonIgnore
		public Variable getVariable() {
			Object o = fieldContainer.get(VARIABLE);
		return o == null ? null : (Variable)o;
		}

		@JsonIgnore
		public boolean isHeaderRef() {
			return getVariable().getType() instanceof OMessageVarType && getHeaderPart() != null && getLocation() == null;
        }

		/**
		 * Report whether this is a reference to a whole "message"
		 * @return true if whole-message reference
		 */
		@JsonIgnore
		public boolean isMessageRef() {
			return getVariable().getType() instanceof OMessageVarType && getPart() == null && getHeaderPart() == null && getLocation() == null;
        }

		/**
		 * Report whether this is a reference to a message part.
		 * @return true if reference to a message part
		 */
		@JsonIgnore
		public boolean isPartRef() {
			return getVariable().getType() instanceof OMessageVarType && getPart() != null && getLocation() == null;
        }

		public void setHeaderPart(Part headerPart) {
			fieldContainer.put(HEADERPART, headerPart);
		}

		public void setLocation(OExpression location) {
			fieldContainer.put(LOCATION, location);
		}

		public void setPart(Part part) {
			fieldContainer.put(PART, part);
		}

		public void setVariable(Variable variable) {
			fieldContainer.put(VARIABLE, variable);
		}

		public String toString() {
			return "{VarRef " + getVariable()
					+ (getPart() == null ? "" : "." + getPart().getName())
					+ (getLocation() == null ? "" : getLocation().toString())
					+ "}";
		}
	}
}


text:
using namespace thewizardplusplus::anna::sound;

PCMData::PCMData(void) :
	valid(false),
	data(NULL),
	size(0),
	type(PCMDataType::MONO),
	bits(PCMDataBits::BIT_16),
	frequency(0)
{}

PCMData::PCMData(const void* data, int size, PCMDataType::Types type,
	PCMDataBits::Types bits, int frequency)
:
	valid(true),
	data(data),
	size(size),
	type(type),
	bits(bits),
	frequency(frequency)
{}

bool PCMData::isValid(void) const {
	return valid;
}

const void* PCMData::getData(void) const {
	return data;
}

int PCMData::getSize(void) const {
	return size;
}

PCMDataType::Types PCMData::getType(void) const {
	return type;
}

PCMDataBits::Types PCMData::getBits(void) const {
	return bits;
}

int PCMData::getFrequency(void) const {
	return frequency;
}

void PCMData::reset(void) {
	*this = PCMData();
}


text:
package de.mbdevelopment.android.rbtvsendeplan;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.widget.RemoteViews;

public class OneDayScheduleWidgetProvider extends AppWidgetProvider {

    public static final int UPDATE_INTENT_ID = 0;

    /**
     * Use this action in intents to this provider to force a widget update
     */
    public static final String UPDATE_ACTION = "de.mbdevelopment.android.rbtvsendeplan.WIDGET_UPDATE_ACTION";

    @Override
    public void onEnabled(Context context) {
        super.onEnabled(context);

        // Start data service the first time this widget is added somewhere. This handles the case
        // in which the app is installed, but never started before adding the widget. In that case
        // there is no data yet, so the service is started this one time in order to fetch initial
        // data.
        Intent serviceIntent = new Intent(context, DataService.class);
        context.startService(serviceIntent);
    }

    @Override
    public void onReceive(@NonNull Context context, @NonNull Intent intent) {
        // Catch the manual update action
        if (intent.getAction().equals(UPDATE_ACTION)) {
            AppWidgetManager awm = AppWidgetManager.getInstance(context);
            int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
            for (int appWidgetId : appWidgetIds) {
                awm.notifyAppWidgetViewDataChanged(appWidgetId, R.id.one_day_schedule_widget_list);
            }
        }

        // Let the default implementations handle the rest
        super.onReceive(context, intent);
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // Update all widgets
        for (int appWidgetId : appWidgetIds) {
            // Set up the intent that starts the OneDayScheduleWidgetService, which will provide the
            // views for this collection.
            Intent intent = new Intent(context, OneDayScheduleWidgetService.class);
            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
            intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
            // Instantiate the RemoteViews object for the widget layout.
            RemoteViews remoteViews = new RemoteViews(context.getPackageName()
                    , R.layout.one_day_schedule_widget);
            // Set up the RemoteViews object to use a RemoteViews adapter.
            // This adapter connects to a RemoteViewsService through the specified intent.
            // This is how the data gets populated.
            remoteViews.setRemoteAdapter(R.id.one_day_schedule_widget_list, intent);

            // The empty view is displayed when the collection has no items.
            remoteViews.setEmptyView(R.id.one_day_schedule_widget_list
                    , R.id.one_day_schedule_widget_empty_view);

            // Set intent template to launch the activity when a list entry is clicked
            Intent activityIntent = new Intent(context, ScheduleActivity.class);
            activityIntent.setData(Uri.parse(activityIntent.toUri(Intent.URI_INTENT_SCHEME)));
            PendingIntent pendingActivityIntent = PendingIntent.getActivity(context, 0
                    , activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setPendingIntentTemplate(R.id.one_day_schedule_widget_list
                    , pendingActivityIntent);

            appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
        }

        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }

    /**
     * Notifies all widgets of changed data
     */
    public static void notifyWidgets(Context context) {
        int[] ids = AppWidgetManager.getInstance(context)
                .getAppWidgetIds(new ComponentName(context, OneDayScheduleWidgetProvider.class));
        Intent widgetIntent = new Intent(context, OneDayScheduleWidgetProvider.class);
        widgetIntent.setAction(UPDATE_ACTION);
        widgetIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
        PendingIntent pendingWidgetIntent = PendingIntent.getBroadcast(context, UPDATE_INTENT_ID,
                widgetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        // Schedule the update with two seconds delay to bundle multiple data changes to avoid
        // updating the widget too often in a short time frame.
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.ELAPSED_REALTIME,
                SystemClock.elapsedRealtime() + 2000,
                pendingWidgetIntent);
    }
}


text:
using System.Collections.Generic;
using System.Linq;
using Slp.Evi.Storage.Bootstrap;
using Slp.Evi.Storage.Relational.PostProcess;
using Slp.Evi.Storage.Relational.Query;
using Slp.Evi.Storage.Sparql.Algebra;
using Slp.Evi.Storage.Sparql.PostProcess;

namespace Slp.Evi.Storage.Query
{
    /// <summary>
    /// Class QueryPostProcess.
    /// </summary>
    public class QueryPostProcesses
    {
        /// <summary>
        /// The context
        /// </summary>
        private readonly IQueryContext _context;

        /// <summary>
        /// The relational optimizers
        /// </summary>
        private readonly List<IRelationalPostProcess> _relationalPostprocesses;

        /// <summary>
        /// The SPARQL optimizers
        /// </summary>
        private readonly List<ISparqlPostProcess> _sparqlPostprocesses;

        /// <summary>
        /// The relational optimizers to be used during join processing
        /// </summary>
        private readonly List<IRelationalPostProcess> _innerJoinProcesses;

        /// <summary>
        /// Initializes a new instance of the <see cref="QueryPostProcesses" /> class.
        /// </summary>
        /// <param name="factory">The factory.</param>
        /// <param name="context">The context.</param>
        public QueryPostProcesses(IEviQueryableStorageFactory factory, IQueryContext context)
        {
            _context = context;
            _relationalPostprocesses = new List<IRelationalPostProcess>(factory.GetRelationalPostProcesses());
            _sparqlPostprocesses = new List<ISparqlPostProcess>(factory.GetSparqlPostProcesses(context.Mapping));
            _innerJoinProcesses = new List<IRelationalPostProcess>(factory.GetRelationalInnerJoinProcesses());
        }

        /// <summary>
        /// Optimizes the algebra on the fly.
        /// </summary>
        /// <param name="algebra">The algebra.</param>
        /// <returns>The optimized algebra.</returns>
        public RelationalQuery PostProcess(RelationalQuery algebra)
        {
            return _relationalPostprocesses.Aggregate(algebra, (current, processor) => processor.Process(current, _context));
        }

        /// <summary>
        /// Optimizes the algebra.
        /// </summary>
        /// <param name="algebra">The SPARQL query.</param>
        /// <returns>The optimized SPARQL query.</returns>
        public ISparqlQuery PostProcess(ISparqlQuery algebra)
        {
            return _sparqlPostprocesses.Aggregate(algebra, (current, processor) => processor.Process(current, _context));
        }

        /// <summary>
        /// Optimizes the algebra on the fly (to be used during join processing).
        /// </summary>
        /// <param name="algebra">The algebra.</param>
        /// <returns>The optimized algebra.</returns>
        public RelationalQuery InnerJoinProcess(RelationalQuery algebra)
        {
            return _innerJoinProcesses.Aggregate(algebra, (current, processor) => processor.Process(current, _context));
        }
    }
}


text:
require "brewerytown/version"
require "brewerytown/brewable"

module Brewerytown
end