text:
<!doctype html>

		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<title>reveal.js</title>

		<link rel="stylesheet" href="css/reveal.css">
		<link rel="stylesheet" href="css/gitgraph.css">

		<link rel="stylesheet" href="css/theme/solarized.css">

		<link rel="stylesheet" href="lib/css/zenburn.css">

Advanced Git

Understanding the graph, commits and other mysteries you never knew you wanted to know - in a format for massive nerds.

Matt Hooks / Greg Bowser

Describe Git using at least 3 buzzwords

Git is an open source, distributed source control management tool,
							designed to be fast, flexible, and secure.

What is "distributed" SCM?

Every checkout works independetly and contains the full history of the project.

How is it "fast and flexible"?

Committing, branching and history are all local operations (in constant time!)

Users and teams can independently define their own workflows

2-minute Git crash course

Getting a repository

$ git clone url

Committing changes

$ git add filename.txt; git commit

Receiving changes

$ git pull

Sharing changes

$ git push

Making a new branch

$ git branch name-of-branch

Switching branches

$ git checkout name-of-branch

Both at the same time

$ git checkout -b name-of-branch

What happens if I _____?

Almost every operation in Git is local.

committing is local

branching is local

checking history is local

reverting is local

Your changes become public (and effectively permanent) when you push.

97f341d10392085d981353457def1f4dc06b9d93

Every commit in Git is identified by a sha1 hash.

Making hashes easier

Instead of remembering sha1 hashes, we can use pointers, which
							Git calls "references", or more often, "refs".

Hashes vs refs

Git generally doesn't care if you
							provide a raw sha1 or a ref. In most cases, they imply the same meaning.

Branches and tags are all refs in Git.

Remote refs

In additional to local refs (such as local branches), cloning a
							repo provides a copy of the remote repo's refs, under a different
							"remotes" namespace.

Gone but not forgotten

In fact, after cloning a repo, Git
								maintains knowledge of the source url and tracks that repo as a
								"remote".

When you collaborate on a branch, your local branch has
									metadata associating it with the remote ref.

Git uses the remote when
								running git push or git pull
								commands.

When you create a new branch to share, setup tracking with

$ git push --set-upstream name-of-remote name-of-branch

Checking out a remote branch automatically creates the tracking metadata.

The Art of War Committing

In Git, you stage files before committing them.

HEAD and INDEX

There are three "active" versions of every file in
							Git:

The file in the working directory (your unsaved changes)

The file added to the INDEX (files you've staged for commit)

The file committed to HEAD (the file as it was last comitted)

The INDEX is simply what your next commit will contain.

HEAD is whatever commit will be the parent of your next commit,
							the last commit you checkout out, and the branch your next
							commit will be added to.

The Git workflow

Files move from your working directory, to the INDEX,
							then become your new HEAD.

You can inspect your INDEX any time with

$ git status

$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        new file:   file1.py

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   file1.py

Changes to be committed:

The difference between the index and HEAD

Changes not staged for commit:

The difference between the working tree and the INDEX

What Git reset resets

You can change HEAD and INDEX at will with

$ git reset

git reset --soft will leave both the INDEX and working directory alone.

git reset --mixed (default) will clear your INDEX,
								but leave your working directory alone.

git reset --hard will clear your INDEX,
								and match your working directory to HEAD

Git Graph Theory 101

Git is a big graph

Every commit in a Git repo can be thought of as a node in a graph (because they all are).

<canvas id="graph-example"></canvas>

Specifically, a Directed Acyclic Graph

<canvas id="graph-example-parents"></canvas>

Let's break that down...

directed

									Parents commits are indicated by the direction of the edges.

acyclic

									Commits reference their ancestors, not their descendents.

Every time you commit, you add a new point to the graph, and that point references your last commit.

A branch is just a pointer to a commit

master and C2 are the exact same thing.

A merge is just a commit with multiple parents

master (C6) has two parents.

Note: New branches are not new commits

If you start a new branch from master called
							feature1, then feature1 has not
							diverged from master until you commit to one of
							them.

Why do I want abstract math in my version control?

Because commits are nodes on a graph, you can "move" those
								nodes when you want to reorganize your work, and better
								organize your patch before sharing it with the team.

When branches are just pointers, they can be created instantly,
							which is great (assuming you like branches).

Once you understand the Git graph,
							 the tool becomes simple and intuitive.

Understanding merge vs rebase

In Git, there are two ways to
							combine branches:

							merge and rebase

I've seen this trick before

Git merge is simple:
							combine the changes from one branch with another using a commit
							with multiple parents.

Wibbly-wobbly Git history

Git rebase
							 allows you to move branches from one part of the graph to another.

For example, move feature1

<canvas id="graph-example-rebase-start"></canvas>

somewhere else

<canvas id="graph-example-rebase-end"></canvas>

But wait...

Git commits are immutable,
							and they encode their parent's sha1...

aka, you can't change a commit's parent,

aka, you can't actually move a branch.

Rebase actually creates new commits

When you rebase, you replicate the diffs ontop of a different commit

<canvas id="graph-example-rebased"></canvas>

$ git checkout feature1
$ git rebase master

The old commits still exist

<canvas id="graph-example-rebased-hidden"></canvas>

Where do the old commits go?

Commits not pointed to by any refs are automatically hidden and eventually garbage collected.

The special case

Merging a direct decendent of your HEAD neither rebases nor
							creates a new merge commit.

<canvas id="graph-example-fast-forward-start"></canvas>

Fast-forward

Instead, it simply updates the ref (by default).

<canvas id="graph-example-fast-forward-end"></canvas>

master has been fast-forwarded to feature1

Fast-forward only moves forward through linear history.

<canvas id="graph-example-fast-forward-impossible"></canvas>

master cannot be fast forwarded to feature2

Basics revisited

Remember git pull and git push

git pull simply retrieves a remote repo's graph
							and merges your local changes.

git push simply pushes your graph, and updates
								the remote refs to reflect your new commits.

All changes to the graph are done by addition.

git commit, git commit --amend
							both create new commits.

Git Internals

Many Git commands are implemented as shell scripts that call out to other git commands.

Some used to be shell scripts but have been ported to C.

Shell scripts: stash, rebase,
							submodule, filter-branch,
							bisect

The Git internals are easily accessible via commands

Internal commands are referred to as "plumbing commands"

Example: git commit (not a shell script)

git write-tree
# Prompt the user for a commit message
git commit-tree

The database, objects and you

Every object Git stores gets put in the Git database, including:

commits

blobs (files)

trees

annotated tags

Exception: LFS (stores pointers)

Git's database is a simple
							key-value filesystem identified by a sha1 hashes.

.git/objects: each subdirectory is the
							first byte of a sha1.

Each file in the subdirectories is the remainder of the sha1.

Exception: packed objects are stored as deltas in a packfile.

Every object is stored using the same basic format:

zlib_compress([type of object][space][size of object][NUL][object content])

Header is all ASCII strings

Hash is the SHA1 of the content before compression

Useful Git Commands

Interactive Add

git add -p

Git prompts you to stage each chunk individually.

If the chunk cannot be split any further, you can edit the patch.

The Git Reflog

Git commits are never deleted immediately.

If you lose changes in a branch, the reflog records the branch's previous HEAD

$ git reflog
34d257b HEAD@{0}: merge master: Fast-forward
3ec67f7 HEAD@{1}: checkout: moving from master to stable
34d257b HEAD@{2}: commit (amend): [bootstrap] Update changelog and bump version to 1.11.4.
4fb697b HEAD@{3}: commit: [bootstrap] Update changelog and bump version to 11.1.4.
13d40fc HEAD@{4}: commit (amend): [bootstrap] Detect if virtualenv actually exists.

Interactive Rebase

When rebasing, interactive allows you to arbitrarily reorder, squash, or delete commits.

git rebase -i master

Cherry Pick

Similar to rebasing a single commit: one commit can be copied to another branch.

git checkout master
git cherry-pick feature-branch

Question time


text:
<?php

	namespace UserApp;

	use \json_encode;

	use \InvalidArgumentException;
	use \BadMethodCallException;

	use \UserApp\Exceptions\UserAppException;
	use \UserApp\Exceptions\ServiceException;
	use \UserApp\Exceptions\TransportException;
	use \UserApp\Exceptions\InvalidConfigurationException;

	class Client extends ClientBase {
		const CLIENT_VERSION = "0.1";

		public function __construct(){
			parent::__construct($this);

			$arguments = func_get_args();
			$options = $this->getOptions();

			for($i=0;$i<count($arguments);++$i){
				$argument = $arguments[$i];
				if($i == count($arguments)-1 && is_array($argument)){
					$options->set($argument);
				}else if($i == 0){
					if($argument != null && is_string($argument)){
						$options->app_id = $argument;
					}
				}else if($i == 1){
					if($argument != null && is_string($argument)){
						$options->token = $argument;
					}
				}
			}
		}

		// Call

		public function call($version, $service, $method, $arguments){
			$logs = null;
			$generated_exception = null;

			$this->assertConfiguration();
			$this->assertArguments($version, $service, $method, $arguments);

			$protocol = $this->_options->secure ? 'https' : 'http';
			$service_url = sprintf("%s://%s/v%s/%s.%s", $protocol, $this->_options->base_address, $version, $service, $method);

			if($this->debugMode()){
				$service_url .= "?\$debug";
			}

			$headers = array(
				'Content-Type' => 'application/json',
				'User-Agent' => sprintf("UserApp/%s PHP/%s", self::CLIENT_VERSION, PHP_VERSION),
				'Authorization' => sprintf("Basic %s", base64_encode(sprintf("%s:%s", $this->_options->app_id, $this->_options->token)))
			);

			if($this->debugMode()){
				$this->log(sprintf("Sending POST Request to '%s' with headers '%s' and body '%s'.",
					$service_url, json_encode($headers), json_encode($arguments)));
			}

			$response = $this->getTransport()->request('POST', $service_url, $headers, json_encode($arguments));
			$this->assertResponse($response);

			if($response->status->code != 200){
				throw new TransportException(sprintf("Expected 200 OK response. Received %s %s.",
					$response->status->code, $response->status->message));
			}

			if($this->debugMode()){
				$this->log(sprintf("Received response with status '%s' and headers '%s'.",
					json_encode($response->status), json_encode($response->headers)));
			}

			$result = $this->processContentType($response->headers["Content-Type"], $response->body);

			if(is_object($result)){
				if(isset($result->error_code)){
					switch($result->error_code){
						case 'INVALID_SERVICE':
							throw new BadMethodCallException("Call to invalid service '$service'.");
							break;
						case 'INVALID_METHOD':
							throw new BadMethodCallException("Call to invalid method '$method()'.");
							break;
						default:
							if($this->_options->throw_errors){
								$generated_exception = new ServiceException($result->error_code, $result->message);
							}
							break;
					}
				}else{
					if($service == 'user' && $method == 'login'){
						if(isset($result->token) && $this->_options->token == null){
							$this->_options->token = $result->token;
						}
					}
				}
				if(isset($result->__logs)){
					$logs = $result->__logs;
					unset($result->__logs);
				}
			}elseif(is_array($result)){
				foreach($result as $key => $item){
					if(is_object($item)){
						if(isset($item->__logs)){
							$logs = $item->__logs;
							unset($result[$key]);
						}
					}
				}
			}

			if($this->debugMode()){
				$this->log("Request result '" . json_encode($result) . "'.");
			}

			if($logs != null){
				foreach($logs as $log){
					$this->log($log->message, $log->type, $log->created_at);
				}
			}

			if($generated_exception != null){
				throw $generated_exception;
			}

			return $result;
		}

		private function processContentType($content_type, $body){
			switch($content_type){
				case 'application/json':
					return json_decode($body);
					break;
				default:
					return $body;
					break;
			}
		}

		private function log($message){
			$logger = $this->getLogger();
			if($logger != null){
				$logger->log($message);
			}
		}

		// Assertion

		private function assertConfiguration(){
			if(!is_string($this->_options->base_address) || strlen($this->_options->base_address) == 0){
				throw new InvalidConfigurationException("Base Address cannot be empty.");
			}

			if(!is_string($this->_options->app_id) || strlen($this->_options->app_id) == 0){
				throw new InvalidConfigurationException("App Id cannot be empty.");
			}
		}

		private function assertArguments($version, $service, $method, $arguments){
			if(!is_integer($version)){
				throw new InvalidArgumentException("Version must be an an integer value.");
			}

			if(!is_string($service) || strlen($service) == 0){
				throw new InvalidArgumentException("Service must be a string value with at least 1 character.");
			}

			if(!is_string($method) || strlen($method) == 0){
				throw new InvalidArgumentException("Method must be a string value with at least 1 character.");
			}

			if(!is_array($arguments)){
				throw new InvalidArgumentException("Arguments must be an array of arguments.");
			}
		}

		private function assertResponse($response){
			if($response == null){
				throw new InvalidArgumentException("Response cannot be null.");
			}

			if($response->status == null){
				throw new InvalidArgumentException("Response status cannot be null.");
			}

			if(!is_integer($response->status->code)){
				throw new InvalidArgumentException("Response status code must be an integer value.");
			}

			if(!is_array($response->headers)){
				throw new InvalidArgumentException("Response headers must be an array.");
			}
		}
	}

?>

redpajama_set_name: RedPajamaGithub


text:
package im.AfriChat.runtime;

import im.AfriChat.runtime.js.JsEngineProvider;

public class EnginesRuntimeProvider extends JsEngineProvider {

}


text:
@class IOBluetoothDevice;
@class NSArray;
@class NSDate;

namespace base {

class SequencedTaskRunner;

}  // namespace base

@class BluetoothLowEnergyCentralManagerDelegate;

namespace device {

class DEVICE_BLUETOOTH_EXPORT BluetoothAdapterMac
    : public BluetoothAdapter,
      public BluetoothDiscoveryManagerMac::Observer,
      public BluetoothLowEnergyDiscoveryManagerMac::Observer {
 public:
  static base::WeakPtr<BluetoothAdapterMac> CreateAdapter();
  static base::WeakPtr<BluetoothAdapterMac> CreateAdapterForTest(
      std::string name,
      std::string address,
      scoped_refptr<base::SequencedTaskRunner> ui_task_runner);

  // BluetoothAdapter overrides:
  std::string GetAddress() const override;
  std::string GetName() const override;
  void SetName(const std::string& name,
               const base::Closure& callback,
               const ErrorCallback& error_callback) override;
  bool IsInitialized() const override;
  bool IsPresent() const override;
  bool IsPowered() const override;
  void SetPowered(bool powered,
                  const base::Closure& callback,
                  const ErrorCallback& error_callback) override;
  bool IsDiscoverable() const override;
  void SetDiscoverable(bool discoverable,
                       const base::Closure& callback,
                       const ErrorCallback& error_callback) override;
  bool IsDiscovering() const override;
  void CreateRfcommService(
      const BluetoothUUID& uuid,
      const ServiceOptions& options,
      const CreateServiceCallback& callback,
      const CreateServiceErrorCallback& error_callback) override;
  void CreateL2capService(
      const BluetoothUUID& uuid,
      const ServiceOptions& options,
      const CreateServiceCallback& callback,
      const CreateServiceErrorCallback& error_callback) override;
  void RegisterAudioSink(
      const BluetoothAudioSink::Options& options,
      const AcquiredCallback& callback,
      const BluetoothAudioSink::ErrorCallback& error_callback) override;
  void RegisterAdvertisement(
      scoped_ptr<BluetoothAdvertisement::Data> advertisement_data,
      const CreateAdvertisementCallback& callback,
      const CreateAdvertisementErrorCallback& error_callback) override;

  // BluetoothDiscoveryManagerMac::Observer overrides:
  void ClassicDeviceFound(IOBluetoothDevice* device) override;
  void ClassicDiscoveryStopped(bool unexpected) override;

  // Registers that a new |device| has connected to the local host.
  void DeviceConnected(IOBluetoothDevice* device);

  // We only use CoreBluetooth when OS X >= 10.10. This because the
  // CBCentralManager destructor was found to crash on the mac_chromium_rel_ng
  // builder running 10.9.5. May also cause blued to crash on OS X 10.9.5
  // (crbug.com/506287).
  static bool IsLowEnergyAvailable();

  // Resets |low_energy_central_manager_| to |central_manager| and sets
  // |low_energy_central_manager_delegate_| as the manager's delegate. Should
  // be called only when |IsLowEnergyAvailable()|.
  void SetCentralManagerForTesting(CBCentralManager* central_manager);

 protected:
  // BluetoothAdapter override:
  void RemovePairingDelegateInternal(
      device::BluetoothDevice::PairingDelegate* pairing_delegate) override;

 private:
  // The length of time that must elapse since the last Inquiry response (on
  // Classic devices) or call to BluetoothLowEnergyDevice::Update() (on Low
  // Energy) before a discovered device is considered to be no longer available.
  const static NSTimeInterval kDiscoveryTimeoutSec;

  friend class BluetoothTestMac;
  friend class BluetoothAdapterMacTest;
  friend class BluetoothLowEnergyCentralManagerBridge;

  BluetoothAdapterMac();
  ~BluetoothAdapterMac() override;

  // BluetoothAdapter overrides:
  void AddDiscoverySession(BluetoothDiscoveryFilter* discovery_filter,
                           const base::Closure& callback,
                           const ErrorCallback& error_callback) override;
  void RemoveDiscoverySession(BluetoothDiscoveryFilter* discovery_filter,
                              const base::Closure& callback,
                              const ErrorCallback& error_callback) override;
  void SetDiscoveryFilter(scoped_ptr<BluetoothDiscoveryFilter> discovery_filter,
                          const base::Closure& callback,
                          const ErrorCallback& error_callback) override;

  // Start classic and/or low energy discovery sessions, according to the
  // filter.  If a discovery session is already running the filter is updated.
  bool StartDiscovery(BluetoothDiscoveryFilter* discovery_filter);

  void Init();
  void InitForTest(scoped_refptr<base::SequencedTaskRunner> ui_task_runner);
  void PollAdapter();

  // Registers that a new |device| has replied to an Inquiry, is paired, or has
  // connected to the local host.
  void ClassicDeviceAdded(IOBluetoothDevice* device);

  // BluetoothLowEnergyDiscoveryManagerMac::Observer override:
  void LowEnergyDeviceUpdated(CBPeripheral* peripheral,
                              NSDictionary* advertisement_data,
                              int rssi) override;

  // Updates |devices_| when there is a change to the CBCentralManager's state.
  void LowEnergyCentralManagerUpdatedState();

  // Removes from |devices_| any previously paired, connected or seen devices
  // which are no longer present. Notifies observers.
  void RemoveTimedOutDevices();

  // Updates |devices_| to include the currently paired devices and notifies
  // observers.
  void AddPairedDevices();

  std::string address_;
  std::string name_;
  bool classic_powered_;
  int num_discovery_sessions_;

  // Discovery manager for Bluetooth Classic.
  scoped_ptr<BluetoothDiscoveryManagerMac> classic_discovery_manager_;

  // Discovery manager for Bluetooth Low Energy.
  scoped_ptr<BluetoothLowEnergyDiscoveryManagerMac>
      low_energy_discovery_manager_;

  // Underlying CoreBluetooth CBCentralManager and its delegate.
  base::scoped_nsobject<CBCentralManager> low_energy_central_manager_;
  base::scoped_nsobject<BluetoothLowEnergyCentralManagerDelegate>
      low_energy_central_manager_delegate_;

  scoped_refptr<base::SequencedTaskRunner> ui_task_runner_;

  base::WeakPtrFactory<BluetoothAdapterMac> weak_ptr_factory_;

  DISALLOW_COPY_AND_ASSIGN(BluetoothAdapterMac);
};

}  // namespace device

#endif  // DEVICE_BLUETOOTH_BLUETOOTH_ADAPTER_MAC_H_


text:
/*
   Writers/Readers of stats

   We are attempting to mimic the Graphite API json blobs throughout the process here
   such that we can hook this in directly to either graphite-api/web

   NOTE: this is not a full graphite DSL, just paths and metrics, we leave the fancy functions inside
   graphite-api/web to work their magic .. one day we'll implement the full DSL, but until then ..

   Currently just implementing /find /expand and /render (json only) for graphite-api
*/

package metrics

import (
	sindexer "cadent/server/schemas/indexer"
	"cadent/server/schemas/metrics"
	smetrics "cadent/server/schemas/metrics"
	"cadent/server/schemas/repr"
	sseries "cadent/server/schemas/series"
	"cadent/server/series"
	"cadent/server/utils"
	"cadent/server/utils/options"
	"cadent/server/writers/indexer"
	"github.com/opentracing/opentracing-go"
	"golang.org/x/net/context"
	logging "gopkg.in/op/go-logging.v1"
	"math"
	"time"
)

var log = logging.MustGetLogger("metrics")

type WritersNeeded int

const (
	AllResolutions  WritersNeeded = iota // all of them
	FirstResolution                      // just one
)

type CacheTypeNeeded int

const (
	Chunked CacheTypeNeeded = iota // time based log chunks
	Single                         // single byte sized based
)

// Writer interface ..
type Metrics interface {
	// SetTracer set the tracer object, will be used in API/get calls
	SetTracer(t opentracing.Tracer)

	// GetSpan start a tracer named span from context
	GetSpan(name string, ctx context.Context) (opentracing.Span, func())

	// the name of the driver
	Driver() string

	// Name of the writer, for the registry
	Name() string

	// SetResolutions need to able to set what our resolutions are for ease of resolution picking
	// the INT return tells the agg loop if we need to have MULTI writers
	// i.e. for items that DO NOT self rollup (DBs) we need as many writers as resolutions
	// for Whisper (or 'other' things) we only need the Lowest time for the writers
	// as the whisper file rolls up internally
	SetResolutions([][]int) int

	// GetResolutions get the resolutions
	GetResolutions() [][]int

	// SetCurrentResolution we can have a writer per resolution, so this just sets the one we are currently on
	SetCurrentResolution(int)

	// IsPrimaryWriter this writer is responsible for also sending things to the indexer
	// if there are multiple writers, we pick one to be the index sender
	IsPrimaryWriter() bool

	// ShouldWrite should this writer write anything
	ShouldWrite() bool

	// ShouldWriteIndex is true only for the lowest resolution writer
	ShouldWriteIndex() bool

	// Cache the main cache object
	Cache() Cacher

	// CachePrefix prefix of the name in the registry of cache objects
	CachePrefix() string

	// Config configure the writer
	Config(*options.Options) error

	// need an Indexer 99% of the time to deal with render
	SetIndexer(indexer.Indexer) error

	// Write add a metric to the writer (the writer can do many things with this)
	Write(*repr.StatRepr) error

	// WriteWithOffset same as Write expect add a kafka offset marker as well
	WriteWithOffset(*repr.StatRepr, *metrics.OffsetInSeries) error

	RawRender(ctx context.Context, path string, from int64, to int64, tags repr.SortingTags, resample uint32) ([]*metrics.RawRenderItem, error)

	// just get data in the write-back caches
	CacheRender(ctx context.Context, path string, from int64, to int64, tags repr.SortingTags) ([]*metrics.RawRenderItem, error)

	// InCache is the target in this nodes cache?
	InCache(path string, tags repr.SortingTags) (bool, error)

	// CacheList list of all the names in the cache
	CacheList() ([]*repr.StatName, error)

	// return the cached data as the raw binary series
	// note for now only ONE metric can be returned using this method
	CachedSeries(path string, from int64, to int64, tags repr.SortingTags) (*metrics.TotalTimeSeries, error)

	// TurnOnWriteNotify initialize the notify write channel .. note not every writer has this
	TurnOnWriteNotify() <-chan *sseries.MetricWritten

	// OnWriteNotify the channel with a series.MetricWritten message will only be active if
	// the config options `return_write_notifications` is true
	OnWriteNotify() <-chan *sseries.MetricWritten

	// Stop stop the writer and cleanup
	Stop()

	// Start start the writer and associated parts, this needs to be called before anything will happen
	Start()
}

// for those writers that are "blob" writers, we need them to match this interface
// so that we can do resolution rollups
type DBMetrics interface {

	// Driver the name of the driver
	Driver() string

	// GetLatestFromDB gets the latest point(s) written
	GetLatestFromDB(name *repr.StatName, resolution uint32) (metrics.DBSeriesList, error)

	// GetRangeFromDB get the series that fit in a window
	GetRangeFromDB(name *repr.StatName, start uint32, end uint32, resolution uint32) (metrics.DBSeriesList, error)

	// UpdateDBSeries update a db row
	UpdateDBSeries(dbs *metrics.DBSeries, ts series.TimeSeries) error

	// InsertDBSeries add a new row
	InsertDBSeries(name *repr.StatName, timeseries series.TimeSeries, resolution uint32) (int, error)
}

/**** a "common" object we need prepped for almost every "query" we do ****/
type commonQueryGet struct {
	metric        *sindexer.MetricFindItem
	rawd          *smetrics.RawRenderItem
	realStart     uint32
	realEnd       uint32
	uStart        uint32
	uEnd          uint32
	start         int64
	end           int64
	dbResolution  uint32
	outResolution uint32
	doResample    bool
}

// WriterBase is the "parent" object for all writers
type WriterBase struct {
	TracerMetrics

	indexer           indexer.Indexer
	resolutions       [][]int
	currentResolution int
	staticTags        *repr.SortingTags
	options           *options.Options // incoming opts
	name              string           // assigned name

	// this is for Render where we may have several caches, but only "one"
	// cacher get picked for the default render (things share the cache from writers
	// and the api render, but not all the caches, so we need to be able to get the
	// the cache singleton keys
	// `cache:series:seriesMaxMetrics:seriesEncoding:seriesMaxBytes:maxTimeInCache`
	cacherPrefix string
	cacher       Cacher
	isPrimary    bool // is this the primary writer to the cache?
	shouldWrite  bool // default true, if false, the writer will simply act as a cache and do no DB writing

	renderTimeout time.Duration // a timeout on queries

	shutitdown bool
	startstop  utils.StartStop

	writeNotifySubscribe bool
	writeNotify          chan *sseries.MetricWritten
}

// Name the name assigned to this writer
func (wc *WriterBase) Name() string {
	return wc.name
}

// SetResolutions should be of the form
// [BinTime, TTL]
// we select the BinTime based on the TTL
func (wb *WriterBase) SetResolutions(res [][]int) int {
	wb.resolutions = res
	return len(res) // need as many writers as bins
}

// GetResolutions return the [ [BinTime, TTL] ... ] items
func (wb *WriterBase) GetResolutions() [][]int {
	return wb.resolutions
}

// MinResolution the smallest resolution in the set
func (wb *WriterBase) MinResolution() int {
	return wb.resolutions[0][0]
}

// SetCurrentResolution set the current resolution a writer is treating
func (wb *WriterBase) SetCurrentResolution(res int) {
	wb.currentResolution = res
}

// SetIndexer sets the indexer for the metrics writer, all index writes pass through the metrics writer first
func (wb *WriterBase) SetIndexer(idx indexer.Indexer) error {
	wb.indexer = idx
	return nil
}

// IsPrimaryWriter writers that use triggered rollups use the same cache backend, but we only want
// one writer acctually writing, which will then trigger the sub resolutions to get written
func (wc *WriterBase) IsPrimaryWriter() bool {
	return wc.isPrimary
}

// ShouldWrite if false, the actual writing of metrics will not occur, but the cache will
// be used only, good for "cache slave/replicas" this can ONLY be false if
// the Writer object is using the Log-Series based caches, otherwise caches will eat all ram.
// This option is useful for replication, where we want to have a hot standby
// that has all it's read caches full, and still maintains its log state
// (so yes the Log items will still get written, and purged accordingly to
// flushes, just no series or rollups occur)
func (wc *WriterBase) ShouldWrite() bool {

	_, ok := wc.Cache().(*CacherChunk)
	if ok {
		return wc.shouldWrite
	}
	return true
}

// ShouldWriteIndex only write to the indexer if the current writer is the lowest resolution one
func (wc *WriterBase) ShouldWriteIndex() bool {
	return wc.currentResolution == wc.resolutions[0][0] || len(wc.resolutions) == 1
}

// Cache the cache item for the writer
func (wc *WriterBase) Cache() Cacher {
	return wc.cacher
}

// CachePrefix a name for the current cacher to allow easy lookup and for metrics emission
func (wc *WriterBase) CachePrefix() string {
	return wc.cacherPrefix
}

// OnWriteNotify the channel with a series.MetricWritten message will only be active if
// the config options `return_write_notifications` is true
func (wc *WriterBase) OnWriteNotify() <-chan *sseries.MetricWritten {
	return wc.writeNotify
}

// TurnOnWriteNotify will default to nil unless a subclass has this functionality
func (wc *WriterBase) TurnOnWriteNotify() <-chan *sseries.MetricWritten {
	return nil
}

// GetResolution based on the from/to in seconds get the best resolution
// from and to should be SECONDS not nano-seconds
// from and to needs to be > then the TTL as well
func (wc *WriterBase) GetResolution(from int64, to int64) uint32 {
	redux := 3
	diff := int(math.Abs(float64(to-from))) / redux // still get a lower res if w/i 3x the diff
	n := int(time.Now().Unix())
	backF := n - int(from)
	backT := n - int(to)
	for _, res := range wc.resolutions {
		if diff <= res[1] && backF <= res[1] && backT <= res[1] {
			return uint32(res[0])
		}
	}
	return uint32(wc.resolutions[len(wc.resolutions)-1][0])
}

// InCache default is false
func (wc *WriterBase) InCache(path string, tags repr.SortingTags) (bool, error) {
	return false, nil
}

// CacheList list of things in the cache
func (wc *WriterBase) CacheList() ([]*repr.StatName, error) {
	return nil, ErrNotYetimplemented
}

// CacheRender render data only from the cache
func (cass *WriterBase) CacheRender(ctx context.Context, path string, from int64, to int64, tags repr.SortingTags) ([]*metrics.RawRenderItem, error) {
	return nil, ErrNotYetimplemented
}

// CachedSeries get the time series from the cache
func (cass *WriterBase) CachedSeries(path string, from int64, to int64, tags repr.SortingTags) (*metrics.TotalTimeSeries, error) {
	return nil, ErrNotYetimplemented
}

// a helper to aid with queries
func (cass *WriterBase) newGetPrep(metric *sindexer.MetricFindItem, start int64, end int64, resample uint32) *commonQueryGet {
	rawd := new(smetrics.RawRenderItem)

	out := new(commonQueryGet)
	out.metric = metric

	//figure out the best res
	out.dbResolution = cass.GetResolution(start, end)
	out.outResolution = out.dbResolution

	//obey the bigger
	if resample > out.dbResolution {
		out.outResolution = resample
	}

	out.doResample = resample > 0 && resample > out.dbResolution

	start = TruncateTimeTo(start, int(out.dbResolution))
	end = TruncateTimeTo(end, int(out.dbResolution))

	out.uStart = uint32(start)
	out.uEnd = uint32(end)

	statName := metric.StatName()

	rawd.Step = out.outResolution
	rawd.Metric = metric.Path
	rawd.Id = metric.UniqueId
	rawd.RealEnd = out.uEnd
	rawd.RealStart = out.uStart
	rawd.Start = rawd.RealStart
	rawd.End = rawd.RealEnd
	rawd.Tags = metric.Tags
	rawd.MetaTags = metric.MetaTags
	rawd.AggFunc = statName.AggType()
	out.rawd = rawd
	return out
}


text:
<?php

namespace App\Traits;

/**
 * Support for basic LIKE '%foo%' search clauses against a `name` column
 *
 * Class Searchable
 * @package App\Traits
 */
trait Searchable
{
    /**
     * records matching keywords
     *
     * @param $query
     * @param string $keywords
     * @return mixed
     */
    public function scopeKeywords($query, $keywords)
    {
        if ($keywords) {
            return $query->where('name', 'like', '%' . $keywords . '%');
        }

        return $query;
    }
}


text:
<link rel="import" href="../paper-material/paper-material.html" />
<link rel="import" href="../paper-fab/paper-fab.html" />
<link rel="import" href="../paper-icon-button/paper-icon-button.html" />
<link rel="import" href="../paper-button/paper-button.html" />
<link rel="import" href="../iron-icons/iron-icons.html" />
<link rel="import" href="../iron-icons/av-icons.html" />
<link rel="import" href="../neon-animation/neon-shared-element-animatable-behavior.html">
<link rel="import" href="../paper-progress/paper-progress.html" />
<link rel="import" href="../neon-animation/neon-animated-pages.html" />
<link rel="import" href="../neon-animation/neon-animations.html" />
<link rel="import" href="../paper-toast/paper-toast.html" />

<dom-module id="song-file-player">

	<template>
		<paper-progress id="loadmeter" value="{{loadingval}}"></paper-progress>
		<paper-material id="container" elevation="0">
			<paper-material id="wavecontainer" elevation="0">

			</paper-material>

				<paper-icon-button class="flex" id='replaybutton' icon="av:replay-30" on-tap="replay"></paper-icon-button>
				<paper-icon-button class="flex"  id='pausebutton' icon="av:pause" on-tap="togglePlay"></paper-icon-button>
				<paper-icon-button class="flex"  id='mutebutton' icon="av:volume-off" on-tap="mute" toggles></paper-icon-button>

		</paper-material>
		<paper-toast id="error" duration="3000" text="An error occured while downloading the file"></paper-toast>
	</template>
</dom-module>


text:
<TITLE>Review for Midnight in the Garden of Good and Evil (1997)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Midnight in the Garden of Good and Evil (1997)

reviewed by
Ben Hoffman

                  MIDNIGHT IN THE GARDEN OF GOOD AND EVIL

Do not let the title fool you.   It could lead you to believe  this
was going to be one of the surreal films with corpses rising out of
graves.   Not at all . . . or at least only occasionally spooky.
Instead this is a tensely entertaining film about a murder and a
trial.   The acting by everyone is absolutely superb.   Good story
and great acting; what else could one ask for?

Based quite loosely on John Berendt's recounting of a murder in
Savannah, it will hold you in its grip from beginning to end.   John
Kelso (John Cusack) is a journalist who is sent by TOWN AND COUNTRY
magazine to cover a Christmas party given at the beautiful Savannah
home of wealthy, famous Jim Williams (Kevin Spacey) who is a
collector, an antique dealer, a restorer of 18th and 19th Century
homes.

What should have been a routine assignment for Kelso who would just
have to take notes on the lavishness of  the party, record who in
Georgia society attended, and other such trivia finds himself in a
room with Williams discussing the party.   Into  this room bursts
Billy Hanson (Jude Law), an obvious hustler who shouts at Williams,
knocks over an expensive antique grandfather clock and hurls threats
before he leaves in a state of drunkenness or excessive drugs.
All this is witnessed by the  journalist to whom it is obvious that
Billy lives with Williams as his lover.

When, a short while later, Williams shoots and kills Billy, (in
self-defense, he claims) the movie turns dark.   Williams is
arrested but because he is a prestigious member of Savannah society
he expects to be released at once on his own recognizance.  That
does not happen that quickly because the investigators have lots of
questions about Williams' version of what happened.

In a nice twist of irony, the film concludes exactly right.

Just about everyone in the cast is superb, from Cusack as the young
journalist, to Spacey, haughty, dignified, self-assured.   An
exceptionally able performance is given by Jack Thompson who plays
Sonny Seiler, Williams' defense attorney.

Special mention must be made of the transvestite known as The Lady
Chablis who is played by Chablis Deveau (a transvestite in real
life)  who provides both humor and pathos to the film, dominating
many of the scenes.  Add to the cast, Minerva, (Irma P. Hall) like a
one-woman Greek oracle who keeps popping up every now and then with
some pithy remark.  It was she who stole the film A FAMILY THING
with her performance in 1996.    Lastly, there is the entirely
unnecessary "love interest" played by Alison Eastwood who just
happens to be Clint Eastwood's daughter.

Do not expect the film to be faithful to the book.  See it on its
own merits which are plentiful.

                     Directed by Clint Eastwood.

3.5 bytes

4 Bytes = Superb
3 Bytes = Too good to miss
2 Bytes = Average
1 Byte  = Save your money

               Copyright 1997               Ben Hoffman

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>My Project: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

My Project

TUResenha Member List

This is the complete list of members for TUResenha, including all inherited members.

FALHA	TUResenha	static

run()	TUResenha

SUCESSO	TUResenha	static

<address class="footer">
Generated by

 1.8.13
</address>


text:
require 'spec_helper'

RSpec.describe Protobuf::Field::Int64Field do

  it_behaves_like :packable_field, described_class

end


text:
cask 'objectivesharpie' do
  version '3.0.8'
  sha256 'f5deb879d0f5f379eb5ccc6d78bedf99007386d102720639cf7a5f3dc8be04cc'

  url "https://files.xamarin.com/~abock/ObjectiveSharpie/ObjectiveSharpie-#{version}.pkg"
  name 'Objective Sharpie'
  homepage 'https://developer.xamarin.com/guides/cross-platform/macios/binding/objective-sharpie/'

  pkg "ObjectiveSharpie-#{version}.pkg"

  uninstall pkgutil: 'com.xamarin.ObjectiveSharpie'
end


text:
package ru.istolbov.list;

import org.junit.Assert;
import org.junit.Test;

import java.util.ArrayList;

import static org.hamcrest.CoreMatchers.is;

/**
 * StackTest.
 * Created by istolbov on 20.04.2017.
 */
public class StackTest {
    /**
     * whenWeManipulateWithStack.
     */
    @Test
    public void whenWeManipulateWithStack() {
        int[] target = new int[]{1, 2};
        Stack<Integer> stack = new Stack<>();

        stack.push(1);
        stack.push(2);
        stack.push(3);

        int value = stack.pop();

        ArrayList<Integer> result = new ArrayList<>();
        for (Integer i : stack) {
            result.add(i);
        }

        Assert.assertThat(value, is(3));
        Assert.assertThat(result.toArray(), is(target));
    }
}


text:
package lite.erp.system.service;

import java.util.List;

import lite.erp.system.entity.Origanization;
import lite.erp.system.vo.OriganizationVO;

public interface IOriganizationService extends IBaseService<Origanization,Long>{

	public List<OriganizationVO> findAllVOs();

	public OriganizationVO findVO(Long id);

	public OriganizationVO insert(OriganizationVO vo);

	public OriganizationVO update(OriganizationVO vo);

}


text:
package com.belteshazzar.jquery;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import com.belteshazzar.jquery.functions.PromiseBooleanVoidFunction;
import com.belteshazzar.jquery.functions.PromiseIntIntVoidFunction;
import com.belteshazzar.jquery.functions.PromiseVoidFunction;

import java.util.Set;

import netscape.javascript.JSObject;

public class PlainObject {

	private Map<String,Object> values;

	public PlainObject() {
		values = new HashMap<String,Object>();
	}

	public PlainObject(JSObject js) {
		this();
		final JSObject names = (JSObject)js.eval("(function (obj) { var names = []; for (var name in obj) names.push(name); return names; })(this)");
		final int count = (int)names.getMember("length");
		for (int i=0 ; i<count ; i++) {
			String name = (String)names.getSlot(i);
			values.put(name, js.getMember(name));
		}
	}

	public PlainObject set(String key, Object value) {
		values.put(key, value);
		return this;
	}

	public Object get(String key) {
		return values.get(key);
	}

	public Set<String> keys() {
		return values.keySet();
	}

	public Collection<Object> values() {
		return values.values();
	}

	public Set<Map.Entry<String,Object>> entries() {
		return values.entrySet();
	}

	public PlainObject remove(String key) {
		values.remove(key);
		return this;
	}

	public PlainObject empty() {
		values.clear();
		return this;
	}

	public JSObject toJSObject() {
		JSObject js = JQuery.createObject();
		for (Map.Entry<String,Object> entry : values.entrySet()) {
			String name = entry.getKey();
			Object value = entry.getValue();
			if (value instanceof PromiseVoidFunction) {
				js.setMember(name, JQuery.createFunction((PromiseVoidFunction)value));
			} else if (value instanceof PromiseBooleanVoidFunction) {
				js.setMember(name, JQuery.createFunction((PromiseBooleanVoidFunction)value));
			} else if (value instanceof PromiseIntIntVoidFunction) {
				js.setMember(name, JQuery.createFunction((PromiseIntIntVoidFunction)value));
			} else {
				js.setMember(name, value);
			}
		}
		return js;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("PlainObject[");
		Iterator<Entry<String, Object>> entries = entries().iterator();
		if (entries.hasNext()) {
			Entry<String,Object> entry = entries.next();
			sb.append(entry.getKey());
			sb.append("=");
			sb.append(entry.getValue());
			while (entries.hasNext()) {
				entry = entries.next();
				sb.append(",");
				sb.append(entry.getKey());
				sb.append("=");
				sb.append(entry.getValue());
			}
		}
		sb.append("]");
		return sb.toString();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((values == null) ? 0 : values.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;
		PlainObject other = (PlainObject) obj;
		if (values == null) {
			if (other.values != null)
				return false;
		} else if (!values.equals(other.values))
			return false;
		return true;
	}
}


text:
#define WINDOWS_PHONE
#define SILVERLIGHT

// ===============================================================================
// TruecolorReader.cs
// .NET Image Tools
// ===============================================================================
// Copyright (c) .NET Image Tools Development Group.
// All rights reserved.
// ===============================================================================

using System;
using ImageTools.Helpers;

namespace ImageTools.IO.Png
{
    /// <summary>
    /// Color reader for reading truecolors from a PNG file. Only colors
    /// with 24 or 32 bit (3 or 4 bytes) per pixel are supported at the moment.
    /// </summary>
    sealed class TrueColorReader : IColorReader
    {
        #region Fields

        private int _row;
        private bool _useAlpha;

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="TrueColorReader"/> class.
        /// </summary>
        /// <param name="useAlpha">if set to <c>true</c> the color reader will also read the
        /// alpha channel from the scanline.</param>
        public TrueColorReader(bool useAlpha)
        {
            _useAlpha = useAlpha;
        }

        #endregion

        #region IPngFormatHandler Members

        /// <summary>
        /// Reads the specified scanline.
        /// </summary>
        /// <param name="scanline">The scanline.</param>
        /// <param name="pixels">The pixels, where the colors should be stored in RGBA format.</param>
        /// <param name="header">The header, which contains information about the png file, like
        /// the width of the image and the height.</param>
        public void ReadScanline(byte[] scanline, byte[] pixels, PngHeader header)
        {
            int offset = 0;

            byte[] newScanline = scanline.ToArrayByBitsLength(header.BitDepth);

            if (_useAlpha)
            {
                Array.Copy(newScanline, 0, pixels, _row * header.Width * 4, newScanline.Length);
            }
            else
            {
                for (int x = 0; x < newScanline.Length / 3; x++)
                {
                    offset = (_row * header.Width + x) * 4;

                    pixels[offset + 0] = newScanline[x * 3];
                    pixels[offset + 1] = newScanline[x * 3 + 1];
                    pixels[offset + 2] = newScanline[x * 3 + 2];
                    pixels[offset + 3] = (byte)255;
                }
            }

            _row++;
        }

        #endregion
    }
}


text:
package com.sdw.soft.socket.sample;

import java.io.IOException;
import java.io.InputStream;

/**
 *
 * @author syd
 */
public class Request {

	private InputStream inputStream;
	private String uri;

	public Request(InputStream inputStream){
		this.inputStream = inputStream;
	}

	public void parse(){
		StringBuffer sb = new StringBuffer(2048);
		int i = 0;
		byte[] buffer = new byte[2048];
		try {
			i = inputStream.read(buffer);
		} catch (Exception e) {
			e.printStackTrace();
			i = -1;
		}
		for(int n = 0;n < i;n++){
			sb.append((char)buffer[n]);
		}
		System.out.println("请求信息:");
		System.out.println(sb.toString());
		uri = parseUri(sb.toString());
	}

	private String parseUri(String requestString){
		int index_first = requestString.indexOf(' ');
		int index_second = requestString.indexOf(' ',index_first + 1);
		if(index_second > index_first){
			return requestString.substring(index_first + 1, index_second);
		}
		return null;
	}

	public String getUri(){
		return this.uri;
	}
}


text:
package ru.job4j.security.controller.admin;

import org.junit.Test;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static org.junit.Assert.assertThat;
import static org.hamcrest.core.Is.is;
import org.mockito.Mockito;
import ru.job4j.security.controller.authorization.MockHttpSession;
import ru.job4j.security.controller.authorization.UserIdentification;
import ru.job4j.security.model.AdvancedUser;
import ru.job4j.security.model.AdvancedUserSecurityStore;

/**
 * Class DeleteUserControllerTest содержит тест для DeleteUserController.
 * @author Timur Kpakaev (timur.kap@yandex.ru)
 * @version $ID$
 * @since 20.11.2017
 */
public class DeleteUserControllerTest {

    /**
     * Тест для метода doPost.
     * @throws Exception - ошибка удаления элемента
     * */
    @Test
    public void whenDoPostThenDeleteElementFromDatabase() throws Exception {

        /* подготовка базы данных. */
        AdvancedUserSecurityStore.getInstance().clearUsers();
        String loginOfDeletedElement = "test";
        AdvancedUser deletedUser = new AdvancedUser.AdvancedUserBuilder().addLogin(loginOfDeletedElement).addName("Test").
                addEmail("test@mail.ru").addRole("admin").addPassword("test_password").build();
        AdvancedUserSecurityStore.getInstance().insert(deletedUser);

        /* подготовка теста */
        HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
        HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class);
        Mockito.when(mockRequest.getParameter("login")).thenReturn(loginOfDeletedElement);

        HttpSession session = new MockHttpSession();
        session.setAttribute("identification", new UserIdentification("admin", "login"));
        Mockito.when(mockRequest.getSession()).thenReturn(session);

        /* Тест операции удаления */
        DeleteUserController deleteServlet = new DeleteUserController();
        deleteServlet.doPost(mockRequest, mockResponse);

        AdvancedUser user = AdvancedUserSecurityStore.getInstance().searchByPrimaryKey(new AdvancedUser.Key(loginOfDeletedElement));

        assertThat(user == null, is(true));

    }
}


text:
const bool TEST=1;
#include<iostream>
#include<cctype>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<vector>
#include<map>
#include<queue>
#include<set>
#include<cctype>
#include<cstring>
#include<utility>
#include<cmath>
#include<sstream>
#include<stack>
const int inf=0x7fffffff;
#define IF if(TEST)
#define FI if(!TEST)
#define gts(s) fgets((s),sizeof(s),stdin)
#define ALL(s) (s).begin(),(s).end()
#define MK(a,b) make_pair((a),(b))
typedef long long int LL;
typedef unsigned int U;
typedef unsigned long long ULL;
using namespace std;
typedef pair<int,int> Point;
template <typename T>
void pA(T *begin,int n){ for(int i=0;i<n;i++){ cout<<*(begin++); } printf("\n"); }
void sol(){
	int x;
	cin>>x;
	if(x<1200)cout<<"ABC";
	else cout<<"ARC";
	cout<<endl;
}
int main()
{
	sol();
	return 0;
}
//A.cc
//generated automatically at Sat Jan 28 20:06:00 2017
//by xsthunder


text:
mkdir -p /var/tmp/deploy/
cd /var/tmp/deploy/
forever stopall
rm -r KV004/
git clone https://github.com/ITsvetkoFF/KV004.git
cd KV004/frontend/
bower install --allow-root
npm install
grunt distOn
grunt
cd ../backend
npm install
mysql -u root -proot < EnviromapDB.sql
nodejs filldb.js
forever start -a -l /var/log/forever.log -o /var/log/out.log -e /var/log/err.log api.js


text:
package model

import (
	"fmt"
	"github.com/kubernetes-incubator/kube-aws/credential"
	"github.com/kubernetes-incubator/kube-aws/logger"
	"github.com/kubernetes-incubator/kube-aws/pkg/api"
	"github.com/kubernetes-incubator/kube-aws/plugin/clusterextension"
)

func newStack(stackName string, conf *Config, opts api.StackTemplateOptions, assetsConfig *credential.CompactAssets, tmplCtx func(stack *Stack) (interface{}, error), init func(stack *Stack) error) (*Stack, error) {
	logger.Debugf("Called newStack")

	stack := &Stack{
		StackName:            stackName,
		StackTemplateOptions: opts,
		ClusterName:          conf.ClusterName,
		S3URI:                conf.S3URI,
		Region:               conf.Region,
		AssetsConfig:         assetsConfig,
		Config:               conf,
	}

	ctx, err := tmplCtx(stack)
	if err != nil {
		return nil, err
	}
	stack.tmplCtx = ctx

	if err := init(stack); err != nil {
		return nil, err
	}

	assets, err := stack.buildAssets()
	if err != nil {
		return nil, err
	}
	stack.assets = assets

	return stack, nil
}

// NewControlPlaneStack reads the specified cluster spec along with all the referenced files into memory.
// Any configuration error like a reference to a missing file results in kube-aws existing with an error.
func NewControlPlaneStack(conf *Config, opts api.StackTemplateOptions, extras clusterextension.ClusterExtension, assetsConfig *credential.CompactAssets) (*Stack, error) {
	return newStack(
		conf.ControlPlaneStackName(),
		conf,
		opts,
		assetsConfig,
		func(stack *Stack) (interface{}, error) {
			// Import all the managed subnets from the network stack
			subnets, err := stack.Config.Subnets.ImportFromNetworkStackRetainingNames()
			if err != nil {
				return nil, fmt.Errorf("failed to import subnets from network stack: %v", err)
			}
			vpc := stack.Config.VPC.ImportFromNetworkStack()

			return ControllerTmplCtx{
				Stack:   stack,
				Config:  conf,
				VPC:     vpc,
				Subnets: subnets,
			}, nil
		},
		func(stack *Stack) error {
			extraStack, err := extras.ControlPlaneStack(stack)
			if err != nil {
				return fmt.Errorf("failed to load control-plane stack extras from plugins: %v", err)
			}
			stack.ExtraCfnResources = extraStack.Resources

			extraController, err := extras.Controller(conf)
			if err != nil {
				return fmt.Errorf("failed to load controller node extras from plugins: %v", err)
			}

			if len(conf.Kubelet.Kubeconfig) == 0 {
				conf.Kubelet.Kubeconfig = extraController.Kubeconfig
			}
			conf.Kubelet.Mounts = append(conf.Kubelet.Mounts, extraController.KubeletVolumeMounts...)
			conf.APIServerFlags = append(conf.APIServerFlags, extraController.APIServerFlags...)
			conf.ControllerFlags = append(conf.ControllerFlags, extraController.ControllerFlags...)
			conf.APIServerVolumes = append(conf.APIServerVolumes, extraController.APIServerVolumes...)
			conf.Controller.CustomSystemdUnits = append(conf.Controller.CustomSystemdUnits, extraController.SystemdUnits...)
			conf.Controller.CustomFiles = append(conf.Controller.CustomFiles, extraController.Files...)
			conf.Controller.IAMConfig.Policy.Statements = append(conf.Controller.IAMConfig.Policy.Statements, extraController.IAMPolicyStatements...)
			conf.KubeAWSVersion = VERSION
			for k, v := range extraController.NodeLabels {
				conf.Controller.NodeLabels[k] = v
			}
			conf.HelmReleaseFilesets = extraController.HelmReleaseFilesets
			conf.KubernetesManifestFiles = extraController.KubernetesManifestFiles

			if len(conf.StackTags) == 0 {
				conf.StackTags = make(map[string]string, 1)
			}
			conf.StackTags["kube-aws:version"] = VERSION

			stack.archivedFiles = extraController.ArchivedFiles
			stack.CfnInitConfigSets = extraController.CfnInitConfigSets

			return stack.RenderAddControllerUserdata(opts)
		},
	)
}

func NewNetworkStack(conf *Config, nodePools []*Stack, opts api.StackTemplateOptions, extras clusterextension.ClusterExtension, assetsConfig *credential.CompactAssets) (*Stack, error) {
	return newStack(
		conf.NetworkStackName(),
		conf,
		opts,
		assetsConfig,
		func(stack *Stack) (interface{}, error) {
			nps := []WorkerTmplCtx{}
			for _, s := range nodePools {
				nps = append(nps, s.tmplCtx.(WorkerTmplCtx))
			}

			return NetworkTmplCtx{
				Stack:           stack,
				Config:          conf,
				WorkerNodePools: nps,
			}, nil
		},
		func(stack *Stack) error {
			return nil
		},
	)
}

func NewEtcdStack(conf *Config, opts api.StackTemplateOptions, extras clusterextension.ClusterExtension, assetsConfig *credential.CompactAssets, s *Context) (*Stack, error) {
	return newStack(
		conf.EtcdStackName(),
		conf,
		opts,
		assetsConfig,
		func(stack *Stack) (interface{}, error) {
			// create the context that will be used to build the assets (combination of config + existing state)
			existingState, err := s.InspectEtcdExistingState(conf)
			if err != nil {
				return nil, fmt.Errorf("Could not inspect existing etcd state: %v", err)
			}

			// Import all the managed subnets from the network stack
			subnets, err := stack.Config.Subnets.ImportFromNetworkStackRetainingNames()
			if err != nil {
				return nil, fmt.Errorf("failed to import subnets from network stack: %v", err)
			}

			nodes := []EtcdNode{}
			for i, n := range stack.Config.EtcdNodes {
				n2 := n
				n2.subnet = subnets[i%len(subnets)]
				nodes = append(nodes, n2)
			}

			return EtcdTmplCtx{
				Stack:             stack,
				Config:            conf,
				EtcdExistingState: existingState,
				EtcdNodes:         nodes,
			}, nil
		}, func(stack *Stack) error {
			extraStack, err := extras.EtcdStack(stack)
			if err != nil {
				return fmt.Errorf("failed to load etcd stack extras from plugins: %v", err)
			}
			stack.ExtraCfnResources = extraStack.Resources

			extraEtcd, err := extras.Etcd()
			if err != nil {
				return fmt.Errorf("failed to load etcd node extras from plugins: %v", err)
			}

			conf.Etcd.CustomSystemdUnits = append(conf.Etcd.CustomSystemdUnits, extraEtcd.SystemdUnits...)
			conf.Etcd.CustomFiles = append(conf.Etcd.CustomFiles, extraEtcd.Files...)
			conf.Etcd.IAMConfig.Policy.Statements = append(conf.Etcd.IAMConfig.Policy.Statements, extraEtcd.IAMPolicyStatements...)
			// TODO Not implemented yet
			//stack.archivedFiles = extraEtcd.ArchivedFiles
			//stack.CfnInitConfigSets = extraEtcd.CfnInitConfigSets

			return stack.RenderAddEtcdUserdata(opts)
		},
	)
}

func NewWorkerStack(conf *Config, npconf *NodePoolConfig, opts api.StackTemplateOptions, extras clusterextension.ClusterExtension, assetsConfig *credential.CompactAssets) (*Stack, error) {
	return newStack(
		npconf.StackName(),
		conf,
		opts,
		assetsConfig,
		func(stack *Stack) (interface{}, error) {
			return WorkerTmplCtx{
				Stack:          stack,
				NodePoolConfig: npconf,
			}, nil
		},
		func(stack *Stack) error {
			stack.NodePoolConfig = npconf

			extraStack, err := extras.NodePoolStack(conf)
			if err != nil {
				return fmt.Errorf("failed to load node pool stack extras from plugins: %v", err)
			}
			stack.ExtraCfnResources = extraStack.Resources

			extraWorker, err := extras.Worker(conf)
			if err != nil {
				return fmt.Errorf("failed to load worker node extras from plugins: %v", err)
			}
			if len(npconf.Kubelet.Kubeconfig) == 0 {
				npconf.Kubelet.Kubeconfig = extraWorker.Kubeconfig
			}
			npconf.Kubelet.Mounts = append(conf.Kubelet.Mounts, extraWorker.KubeletVolumeMounts...)
			npconf.CustomSystemdUnits = append(npconf.CustomSystemdUnits, extraWorker.SystemdUnits...)
			npconf.CustomFiles = append(npconf.CustomFiles, extraWorker.Files...)
			npconf.IAMConfig.Policy.Statements = append(npconf.IAMConfig.Policy.Statements, extraWorker.IAMPolicyStatements...)
			npconf.KubeAWSVersion = VERSION
			if len(npconf.StackTags) == 0 {
				npconf.StackTags = make(map[string]string, 1)
			}
			npconf.StackTags["kube-aws:version"] = VERSION

			for k, v := range extraWorker.NodeLabels {
				npconf.NodeSettings.NodeLabels[k] = v
			}
			for k, v := range extraWorker.FeatureGates {
				npconf.NodeSettings.FeatureGates[k] = v
			}

			stack.archivedFiles = extraWorker.ArchivedFiles
			stack.CfnInitConfigSets = extraWorker.CfnInitConfigSets

			return stack.RenderAddWorkerUserdata(opts)
		},
	)
}


text:
import {Component, OnInit, OnDestroy} from '@angular/core';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit, OnDestroy {

  constructor() {
  }

  ngOnInit() {
  }

  ngOnDestroy(): void {
    console.log('用户组件已经被销毁ngOnDestroy!!!');
  }

}


text:
<html>
  <head>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <title>Angular 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">

    <!-- 1. Load libraries -->
     <!-- Polyfill(s) for older browsers -->
    <script src="libs/core-js/client/shim.min.js"></script>
    <script src="libs/zone.js/dist/zone.js"></script>
    <script src="libs/reflect-metadata/Reflect.js"></script>
    <script src="libs/systemjs/dist/system.src.js"></script>

    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>

  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>
  </body>

</html>


text:
#include <gtest/gtest.h>

#include "folly/Benchmark.h"

// for backward compatibility with gflags
namespace gflags { }
namespace google { using namespace gflags; }

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);
  int result = RUN_ALL_TESTS();
  google::ParseCommandLineFlags(&argc, &argv, true);
  google::SetCommandLineOptionWithMode(
    "bm_min_iters", "100000", google::SET_FLAG_IF_DEFAULT
  );
  folly::runBenchmarksOnFlag();
  return result;
}


text:
package job

import (
	"context"
	"errors"
	"fmt"
	"strconv"
	"testing"
	"time"

	"github.com/google/go-cmp/cmp"
	batchv1 "k8s.io/api/batch/v1"
	"k8s.io/api/core/v1"
	eventsv1 "k8s.io/api/events/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/apimachinery/pkg/util/sets"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/apimachinery/pkg/watch"
	"k8s.io/apiserver/pkg/util/feature"
	"k8s.io/client-go/informers"
	clientset "k8s.io/client-go/kubernetes"
	restclient "k8s.io/client-go/rest"
	featuregatetesting "k8s.io/component-base/featuregate/testing"
	jobcontroller "k8s.io/kubernetes/pkg/controller/job"
	"k8s.io/kubernetes/pkg/features"
	"k8s.io/kubernetes/test/integration/framework"
	"k8s.io/utils/pointer"
)

// TestNonParallelJob tests that a Job that only executes one Pod. The test
// recreates the Job controller at some points to make sure a new controller
// is able to pickup.
func TestNonParallelJob(t *testing.T) {
	closeFn, restConfig, clientSet, ns := setup(t, "simple")
	defer closeFn()
	ctx, cancel := startJobController(restConfig, clientSet)
	defer func() {
		cancel()
	}()

	jobObj, err := createJobWithDefaults(ctx, clientSet, ns.Name, &batchv1.Job{})
	if err != nil {
		t.Fatalf("Failed to create Job: %v", err)
	}
	validateJobPodsStatus(ctx, t, clientSet, jobObj, podsByStatus{
		Active: 1,
	})

	// Restarting controller.
	cancel()
	ctx, cancel = startJobController(restConfig, clientSet)

	// Failed Pod is replaced.
	if err := setJobPodsPhase(ctx, clientSet, jobObj, v1.PodFailed, 1); err != nil {
		t.Fatalf("Failed setting phase %s on Job Pod: %v", v1.PodFailed, err)
	}
	validateJobPodsStatus(ctx, t, clientSet, jobObj, podsByStatus{
		Active: 1,
		Failed: 1,
	})

	// Restarting controller.
	cancel()
	ctx, cancel = startJobController(restConfig, clientSet)

	// No more Pods are created after the Pod succeeds.
	if err := setJobPodsPhase(ctx, clientSet, jobObj, v1.PodSucceeded, 1); err != nil {
		t.Fatalf("Failed setting phase %s on Job Pod: %v", v1.PodSucceeded, err)
	}
	validateJobSucceeded(ctx, t, clientSet, jobObj)
	validateJobPodsStatus(ctx, t, clientSet, jobObj, podsByStatus{
		Failed:    1,
		Succeeded: 1,
	})
}

func TestParallelJob(t *testing.T) {
	closeFn, restConfig, clientSet, ns := setup(t, "parallel")
	defer closeFn()
	ctx, cancel := startJobController(restConfig, clientSet)
	defer cancel()

	jobObj, err := createJobWithDefaults(ctx, clientSet, ns.Name, &batchv1.Job{
		Spec: batchv1.JobSpec{
			Parallelism: pointer.Int32Ptr(5),
		},
	})
	if err != nil {
		t.Fatalf("Failed to create Job: %v", err)
	}
	validateJobPodsStatus(ctx, t, clientSet, jobObj, podsByStatus{
		Active: 5,
	})
	// Failed Pods are replaced.
	if err := setJobPodsPhase(ctx, clientSet, jobObj, v1.PodFailed, 2); err != nil {
		t.Fatalf("Failed setting phase %s on Job Pods: %v", v1.PodFailed, err)
	}
	validateJobPodsStatus(ctx, t, clientSet, jobObj, podsByStatus{
		Active: 5,
		Failed: 2,
	})
	// Once one Pod succeeds, no more Pods are created, even if some fail.
	if err := setJobPodsPhase(ctx, clientSet, jobObj, v1.PodSucceeded, 1); err != nil {
		t.Fatalf("Failed setting phase %s on Job Pod: %v", v1.PodSucceeded, err)
	}
	validateJobPodsStatus(ctx, t, clientSet, jobObj, podsByStatus{
		Failed:    2,
		Succeeded: 1,
		Active:    4,
	})
	if err := setJobPodsPhase(ctx, clientSet, jobObj, v1.PodFailed, 2); err != nil {
		t.Fatalf("Failed setting phase %s on Job Pods: %v", v1.PodFailed, err)
	}
	validateJobPodsStatus(ctx, t, clientSet, jobObj, podsByStatus{
		Failed:    4,
		Succeeded: 1,
		Active:    2,
	})
	// No more Pods are created after remaining Pods succeed.
	if err := setJobPodsPhase(ctx, clientSet, jobObj, v1.PodSucceeded, 2); err != nil {
		t.Fatalf("Failed setting phase %s on Job Pods: %v", v1.PodSucceeded, err)
	}
	validateJobSucceeded(ctx, t, clientSet, jobObj)
	validateJobPodsStatus(ctx, t, clientSet, jobObj, podsByStatus{
		Failed:    4,
		Succeeded: 3,
	})
}

func TestParallelJobWithCompletions(t *testing.T) {
	closeFn, restConfig, clientSet, ns := setup(t, "completions")
	defer closeFn()
	ctx, cancel := startJobController(restConfig, clientSet)
	defer cancel()

	jobObj, err := createJobWithDefaults(ctx, clientSet, ns.Name, &batchv1.Job{
		Spec: batchv1.JobSpec{
			Parallelism: pointer.Int32Ptr(4),
			Completions: pointer.Int32Ptr(6),
		},
	})
	if err != nil {
		t.Fatalf("Failed to create Job: %v", err)
	}
	validateJobPodsStatus(ctx, t, clientSet, jobObj, podsByStatus{
		Active: 4,
	})
	// Failed Pods are replaced.
	if err := setJobPodsPhase(ctx, clientSet, jobObj, v1.PodFailed, 2); err != nil {
		t.Fatalf("Failed setting phase %s on Job Pods: %v", v1.PodFailed, err)
	}
	validateJobPodsStatus(ctx, t, clientSet, jobObj, podsByStatus{
		Active: 4,
		Failed: 2,
	})
	// Pods are created until the number of succeeded Pods equals completions.
	if err := setJobPodsPhase(ctx, clientSet, jobObj, v1.PodSucceeded, 3); err != nil {
		t.Fatalf("Failed setting phase %s on Job Pod: %v", v1.PodSucceeded, err)
	}
	validateJobPodsStatus(ctx, t, clientSet, jobObj, podsByStatus{
		Failed:    2,
		Succeeded: 3,
		Active:    3,
	})
	// No more Pods are created after the Job completes.
	if err := setJobPodsPhase(ctx, clientSet, jobObj, v1.PodSucceeded, 3); err != nil {
		t.Fatalf("Failed setting phase %s on Job Pods: %v", v1.PodSucceeded, err)
	}
	validateJobSucceeded(ctx, t, clientSet, jobObj)
	validateJobPodsStatus(ctx, t, clientSet, jobObj, podsByStatus{
		Failed:    2,
		Succeeded: 6,
	})
}

func TestIndexedJob(t *testing.T) {
	defer featuregatetesting.SetFeatureGateDuringTest(t, feature.DefaultFeatureGate, features.IndexedJob, true)()

	closeFn, restConfig, clientSet, ns := setup(t, "indexed")
	defer closeFn()
	ctx, cancel := startJobController(restConfig, clientSet)
	defer func() {
		cancel()
	}()

	mode := batchv1.IndexedCompletion
	jobObj, err := createJobWithDefaults(ctx, clientSet, ns.Name, &batchv1.Job{
		Spec: batchv1.JobSpec{
			Parallelism:    pointer.Int32Ptr(3),
			Completions:    pointer.Int32Ptr(4),
			CompletionMode: &mode,
		},
	})
	if err != nil {
		t.Fatalf("Failed to create Job: %v", err)
	}
	validateJobPodsStatus(ctx, t, clientSet, jobObj, podsByStatus{
		Active: 3,
	})
	validateJobPodsIndexes(ctx, t, clientSet, jobObj, sets.NewInt(0, 1, 2), "")

	// One Pod succeeds.
	if err := setJobPhaseForIndex(ctx, clientSet, jobObj, v1.PodSucceeded, 1); err != nil {
		t.Fatal("Failed trying to succeed pod with index 1")
	}
	validateJobPodsStatus(ctx, t, clientSet, jobObj, podsByStatus{
		Active:    3,
		Succeeded: 1,
	})
	validateJobPodsIndexes(ctx, t, clientSet, jobObj, sets.NewInt(0, 2, 3), "1")

	// Disable feature gate and restart controller.
	defer featuregatetesting.SetFeatureGateDuringTest(t, feature.DefaultFeatureGate, features.IndexedJob, false)()
	cancel()
	ctx, cancel = startJobController(restConfig, clientSet)
	events, err := clientSet.EventsV1().Events(ns.Name).Watch(ctx, metav1.ListOptions{})
	if err != nil {
		t.Fatal(err)
	}
	defer events.Stop()

	// One Pod fails, but no recreations happen because feature is disabled.
	if err := setJobPhaseForIndex(ctx, clientSet, jobObj, v1.PodFailed, 2); err != nil {
		t.Fatal("Failed trying to succeed pod with index 2")
	}
	if err := waitForEvent(events, jobObj.UID, "IndexedJobDisabled"); err != nil {
		t.Errorf("Waiting for an event for IndexedJobDisabled: %v", err)
	}
	validateJobPodsIndexes(ctx, t, clientSet, jobObj, sets.NewInt(0, 3), "1")

	// Re-enable feature gate and restart controller. Failed Pod should be recreated now.
	defer featuregatetesting.SetFeatureGateDuringTest(t, feature.DefaultFeatureGate, features.IndexedJob, true)()
	cancel()
	ctx, cancel = startJobController(restConfig, clientSet)

	validateJobPodsStatus(ctx, t, clientSet, jobObj, podsByStatus{
		Active:    3,
		Failed:    1,
		Succeeded: 1,
	})
	validateJobPodsIndexes(ctx, t, clientSet, jobObj, sets.NewInt(0, 2, 3), "1")

	// Remaining Pods succeed.
	if err := setJobPodsPhase(ctx, clientSet, jobObj, v1.PodSucceeded, 3); err != nil {
		t.Fatal("Failed trying to succeed remaining pods")
	}
	validateJobPodsStatus(ctx, t, clientSet, jobObj, podsByStatus{
		Active:    0,
		Failed:    1,
		Succeeded: 4,
	})
	validateJobPodsIndexes(ctx, t, clientSet, jobObj, nil, "0-3")
	validateJobSucceeded(ctx, t, clientSet, jobObj)
}

func TestSuspendJob(t *testing.T) {
	type step struct {
		flag       bool
		wantActive int
		wantStatus v1.ConditionStatus
		wantReason string
	}
	testCases := []struct {
		featureGate bool
		create      step
		update      step
	}{
		// Exhaustively test all combinations other than trivial true->true and
		// false->false cases.
		{
			featureGate: true,
			create:      step{flag: false, wantActive: 2},
			update:      step{flag: true, wantActive: 0, wantStatus: v1.ConditionTrue, wantReason: "Suspended"},
		},
		{
			featureGate: true,
			create:      step{flag: true, wantActive: 0, wantStatus: v1.ConditionTrue, wantReason: "Suspended"},
			update:      step{flag: false, wantActive: 2, wantStatus: v1.ConditionFalse, wantReason: "Resumed"},
		},
		{
			featureGate: false,
			create:      step{flag: false, wantActive: 2},
			update:      step{flag: true, wantActive: 2},
		},
		{
			featureGate: false,
			create:      step{flag: true, wantActive: 2},
			update:      step{flag: false, wantActive: 2},
		},
	}

	for _, tc := range testCases {
		name := fmt.Sprintf("feature=%v,create=%v,update=%v", tc.featureGate, tc.create.flag, tc.update.flag)
		t.Run(name, func(t *testing.T) {
			defer featuregatetesting.SetFeatureGateDuringTest(t, feature.DefaultFeatureGate, features.SuspendJob, tc.featureGate)()

			closeFn, restConfig, clientSet, ns := setup(t, "suspend")
			defer closeFn()
			ctx, cancel := startJobController(restConfig, clientSet)
			defer cancel()
			events, err := clientSet.EventsV1().Events(ns.Name).Watch(ctx, metav1.ListOptions{})
			if err != nil {
				t.Fatal(err)
			}
			defer events.Stop()

			parallelism := int32(2)
			job, err := createJobWithDefaults(ctx, clientSet, ns.Name, &batchv1.Job{
				Spec: batchv1.JobSpec{
					Parallelism: pointer.Int32Ptr(parallelism),
					Completions: pointer.Int32Ptr(4),
					Suspend:     pointer.BoolPtr(tc.create.flag),
				},
			})
			if err != nil {
				t.Fatalf("Failed to create Job: %v", err)
			}

			validate := func(s string, active int, status v1.ConditionStatus, reason string) {
				validateJobPodsStatus(ctx, t, clientSet, job, podsByStatus{
					Active: active,
				})
				job, err = clientSet.BatchV1().Jobs(ns.Name).Get(ctx, job.Name, metav1.GetOptions{})
				if err != nil {
					t.Fatalf("Failed to get Job after %s: %v", s, err)
				}
				if got, want := getJobConditionStatus(ctx, job, batchv1.JobSuspended), status; got != want {
					t.Errorf("Unexpected Job condition %q status after %s: got %q, want %q", batchv1.JobSuspended, s, got, want)
				}
				if err := waitForEvent(events, job.UID, reason); err != nil {
					t.Errorf("Waiting for event with reason %q after %s: %v", reason, s, err)
				}
			}
			validate("create", tc.create.wantActive, tc.create.wantStatus, tc.create.wantReason)

			job.Spec.Suspend = pointer.BoolPtr(tc.update.flag)
			job, err = clientSet.BatchV1().Jobs(ns.Name).Update(ctx, job, metav1.UpdateOptions{})
			if err != nil {
				t.Fatalf("Failed to update Job: %v", err)
			}
			validate("update", tc.update.wantActive, tc.update.wantStatus, tc.update.wantReason)
		})
	}
}

func TestSuspendJobControllerRestart(t *testing.T) {
	defer featuregatetesting.SetFeatureGateDuringTest(t, feature.DefaultFeatureGate, features.SuspendJob, true)()

	closeFn, restConfig, clientSet, ns := setup(t, "suspend")
	defer closeFn()
	ctx, cancel := startJobController(restConfig, clientSet)
	defer func() {
		cancel()
	}()

	job, err := createJobWithDefaults(ctx, clientSet, ns.Name, &batchv1.Job{
		Spec: batchv1.JobSpec{
			Parallelism: pointer.Int32Ptr(2),
			Completions: pointer.Int32Ptr(4),
			Suspend:     pointer.BoolPtr(true),
		},
	})
	if err != nil {
		t.Fatalf("Failed to create Job: %v", err)
	}
	validateJobPodsStatus(ctx, t, clientSet, job, podsByStatus{
		Active: 0,
	})

	// Disable feature gate and restart controller to test that pods get created.
	defer featuregatetesting.SetFeatureGateDuringTest(t, feature.DefaultFeatureGate, features.SuspendJob, false)()
	cancel()
	ctx, cancel = startJobController(restConfig, clientSet)
	job, err = clientSet.BatchV1().Jobs(ns.Name).Get(ctx, job.Name, metav1.GetOptions{})
	if err != nil {
		t.Fatalf("Failed to get Job: %v", err)
	}
	validateJobPodsStatus(ctx, t, clientSet, job, podsByStatus{
		Active: 2,
	})
}

type podsByStatus struct {
	Active    int
	Failed    int
	Succeeded int
}

func validateJobPodsStatus(ctx context.Context, t *testing.T, clientSet clientset.Interface, jobObj *batchv1.Job, desired podsByStatus) {
	t.Helper()
	var actualCounts podsByStatus
	if err := wait.Poll(time.Second, wait.ForeverTestTimeout, func() (bool, error) {
		updatedJob, err := clientSet.BatchV1().Jobs(jobObj.Namespace).Get(ctx, jobObj.Name, metav1.GetOptions{})
		if err != nil {
			t.Fatalf("Failed to get updated Job: %v", err)
		}
		actualCounts = podsByStatus{
			Active:    int(updatedJob.Status.Active),
			Succeeded: int(updatedJob.Status.Succeeded),
			Failed:    int(updatedJob.Status.Failed),
		}
		return cmp.Equal(actualCounts, desired), nil
	}); err != nil {
		diff := cmp.Diff(desired, actualCounts)
		t.Errorf("Waiting for Job Pods: %v\nPods (-want,+got):\n%s", err, diff)
	}
	// Verify active Pods. No need for another wait.Poll.
	pods, err := clientSet.CoreV1().Pods(jobObj.Namespace).List(ctx, metav1.ListOptions{})
	if err != nil {
		t.Fatalf("Failed to list Job Pods: %v", err)
	}
	active := 0
	for _, pod := range pods.Items {
		if isPodOwnedByJob(&pod, jobObj) {
			if pod.Status.Phase == v1.PodPending || pod.Status.Phase == v1.PodRunning {
				active++
			}
		}
	}
	if active != desired.Active {
		t.Errorf("Found %d active Pods, want %d", active, desired.Active)
	}
}

// validateJobPodsIndexes validates indexes of active and completed Pods of an
// Indexed Job. Call after validateJobPodsStatus
func validateJobPodsIndexes(ctx context.Context, t *testing.T, clientSet clientset.Interface, jobObj *batchv1.Job, wantActive sets.Int, gotCompleted string) {
	t.Helper()
	updatedJob, err := clientSet.BatchV1().Jobs(jobObj.Namespace).Get(ctx, jobObj.Name, metav1.GetOptions{})
	if err != nil {
		t.Fatalf("Failed to get updated Job: %v", err)
	}
	if updatedJob.Status.CompletedIndexes != gotCompleted {
		t.Errorf("Got completed indexes %q, want %q", updatedJob.Status.CompletedIndexes, gotCompleted)
	}
	pods, err := clientSet.CoreV1().Pods(jobObj.Namespace).List(ctx, metav1.ListOptions{})
	if err != nil {
		t.Fatalf("Failed to list Job Pods: %v", err)
	}
	gotActive := sets.NewInt()
	for _, pod := range pods.Items {
		if isPodOwnedByJob(&pod, jobObj) {
			if pod.Status.Phase == v1.PodPending || pod.Status.Phase == v1.PodRunning {
				if ix, err := getCompletionIndex(&pod); err != nil {
					t.Errorf("Failed getting completion index for pod %s: %v", pod.Name, err)
				} else {
					gotActive.Insert(ix)
				}
			}
		}
	}
	if wantActive == nil {
		wantActive = sets.NewInt()
	}
	if diff := cmp.Diff(wantActive.List(), gotActive.List()); diff != "" {
		t.Errorf("Unexpected active indexes (-want,+got):\n%s", diff)
	}
}

func waitForEvent(events watch.Interface, uid types.UID, reason string) error {
	if reason == "" {
		return nil
	}
	return wait.Poll(time.Second, wait.ForeverTestTimeout, func() (bool, error) {
		for {
			var ev watch.Event
			select {
			case ev = <-events.ResultChan():
			default:
				return false, nil
			}
			e, ok := ev.Object.(*eventsv1.Event)
			if !ok {
				continue
			}
			ctrl := "job-controller"
			if (e.ReportingController == ctrl || e.DeprecatedSource.Component == ctrl) && e.Reason == reason && e.Regarding.UID == uid {
				return true, nil
			}
		}
	})
}

func getJobConditionStatus(ctx context.Context, job *batchv1.Job, cType batchv1.JobConditionType) v1.ConditionStatus {
	for _, cond := range job.Status.Conditions {
		if cond.Type == cType {
			return cond.Status
		}
	}
	return ""
}

func validateJobSucceeded(ctx context.Context, t *testing.T, clientSet clientset.Interface, jobObj *batchv1.Job) {
	t.Helper()
	if err := wait.Poll(time.Second, wait.ForeverTestTimeout, func() (bool, error) {
		j, err := clientSet.BatchV1().Jobs(jobObj.Namespace).Get(ctx, jobObj.Name, metav1.GetOptions{})
		if err != nil {
			t.Fatalf("Failed to obtain updated Job: %v", err)
		}
		return getJobConditionStatus(ctx, j, batchv1.JobComplete) == v1.ConditionTrue, nil
	}); err != nil {
		t.Errorf("Waiting for Job to succeed: %v", err)
	}
}

func setJobPodsPhase(ctx context.Context, clientSet clientset.Interface, jobObj *batchv1.Job, phase v1.PodPhase, cnt int) error {
	pods, err := clientSet.CoreV1().Pods(jobObj.Namespace).List(ctx, metav1.ListOptions{})
	if err != nil {
		return fmt.Errorf("listing Job Pods: %w", err)
	}
	for _, pod := range pods.Items {
		if cnt == 0 {
			break
		}
		if p := pod.Status.Phase; isPodOwnedByJob(&pod, jobObj) && p != v1.PodFailed && p != v1.PodSucceeded {
			pod.Status.Phase = phase
			_, err := clientSet.CoreV1().Pods(pod.Namespace).UpdateStatus(ctx, &pod, metav1.UpdateOptions{})
			if err != nil {
				return fmt.Errorf("updating Pod status: %w", err)
			}
			cnt--
		}
	}
	if cnt != 0 {
		return fmt.Errorf("couldn't set phase on %d Job Pods", cnt)
	}
	return nil
}

func setJobPhaseForIndex(ctx context.Context, clientSet clientset.Interface, jobObj *batchv1.Job, phase v1.PodPhase, ix int) error {
	pods, err := clientSet.CoreV1().Pods(jobObj.Namespace).List(ctx, metav1.ListOptions{})
	if err != nil {
		return fmt.Errorf("listing Job Pods: %w", err)
	}
	for _, pod := range pods.Items {
		if p := pod.Status.Phase; !isPodOwnedByJob(&pod, jobObj) || p == v1.PodFailed || p == v1.PodSucceeded {
			continue
		}
		if pix, err := getCompletionIndex(&pod); err == nil && pix == ix {
			pod.Status.Phase = phase
			_, err := clientSet.CoreV1().Pods(pod.Namespace).UpdateStatus(ctx, &pod, metav1.UpdateOptions{})
			if err != nil {
				return fmt.Errorf("updating pod %s status: %w", pod.Name, err)
			}
			return nil
		}
	}
	return errors.New("no pod matching index found")
}

func getCompletionIndex(p *v1.Pod) (int, error) {
	if p.Annotations == nil {
		return 0, errors.New("no annotations found")
	}
	v, ok := p.Annotations[batchv1.JobCompletionIndexAnnotationAlpha]
	if !ok {
		return 0, fmt.Errorf("annotation %s not found", batchv1.JobCompletionIndexAnnotationAlpha)
	}
	return strconv.Atoi(v)
}

func isPodOwnedByJob(p *v1.Pod, j *batchv1.Job) bool {
	for _, owner := range p.ObjectMeta.OwnerReferences {
		if owner.Kind == "Job" && owner.UID == j.UID {
			return true
		}
	}
	return false
}

func createJobWithDefaults(ctx context.Context, clientSet clientset.Interface, ns string, jobObj *batchv1.Job) (*batchv1.Job, error) {
	if jobObj.Name == "" {
		jobObj.Name = "test-job"
	}
	if len(jobObj.Spec.Template.Spec.Containers) == 0 {
		jobObj.Spec.Template.Spec.Containers = []v1.Container{
			{Name: "foo", Image: "bar"},
		}
	}
	if jobObj.Spec.Template.Spec.RestartPolicy == "" {
		jobObj.Spec.Template.Spec.RestartPolicy = v1.RestartPolicyNever
	}
	return clientSet.BatchV1().Jobs(ns).Create(ctx, jobObj, metav1.CreateOptions{})
}

func setup(t *testing.T, nsBaseName string) (framework.CloseFunc, *restclient.Config, clientset.Interface, *v1.Namespace) {
	masterConfig := framework.NewIntegrationTestMasterConfig()
	_, server, masterCloseFn := framework.RunAMaster(masterConfig)

	config := restclient.Config{Host: server.URL}
	clientSet, err := clientset.NewForConfig(&config)
	if err != nil {
		t.Fatalf("Error creating clientset: %v", err)
	}
	ns := framework.CreateTestingNamespace(nsBaseName, server, t)
	closeFn := func() {
		framework.DeleteTestingNamespace(ns, server, t)
		masterCloseFn()
	}
	return closeFn, &config, clientSet, ns
}

func startJobController(restConfig *restclient.Config, clientSet clientset.Interface) (context.Context, context.CancelFunc) {
	ctx, cancel := context.WithCancel(context.Background())
	resyncPeriod := 12 * time.Hour
	informerSet := informers.NewSharedInformerFactory(clientset.NewForConfigOrDie(restclient.AddUserAgent(restConfig, "cronjob-informers")), resyncPeriod)
	jc := jobcontroller.NewController(informerSet.Core().V1().Pods(), informerSet.Batch().V1().Jobs(), clientSet)
	informerSet.Start(ctx.Done())
	go jc.Run(1, ctx.Done())
	return ctx, cancel
}


text:
package com.lambdaworks.redis.commands.transactional;

import com.lambdaworks.redis.api.sync.RedisCommands;
import com.lambdaworks.redis.commands.BitCommandTest;

/**
 * @author Mark Paluch
 */
public class BitTxCommandTest extends BitCommandTest {

    @Override
    protected RedisCommands<String, String> connect() {
        bitstring = TxSyncInvocationHandler.sync(client.connect(new BitStringCodec()));
        return TxSyncInvocationHandler.sync(client.connect());
    }
}


text:
shared_context 'rack attack cache store' do
  around do |example|
    # Instead of test environment's :null_store so the throttles can increment
    Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new

    # Make time-dependent tests deterministic
    Timecop.freeze { example.run }

    Rack::Attack.cache.store = Rails.cache
  end
end


text:
<?php
/**
ALTER TABLE  `pos_cost_temp` ADD PRIMARY KEY (  `ID` );
 */

class pos_cost_temp extends feed {
	public static $table = 'pos_cost_temp';
	public static $feed_file = '';

	public static function table_name() {
		return self::$table;
	}
//Equivalent:  pricing_del_pos_cost_temp
	public static function delete_table() {
		$sql = "DELETE  FROM " . self::table_name();
 		mysql_query($sql) or sql_error($sql);
	}
//Equivalent:  pricing_insert_pos_cost_temp
////changed from si.store_sku = CHAR(q.ID) to q.ID
	public static function pricing_insert_pos_cost_temp() {
		$sql = "INSERT INTO pos_cost_temp ( ID, cost )
						SELECT qs.`Item Number`, xf.bot_cost
						FROM (pos AS qs INNER JOIN item_store2 AS si ON si.store_sku = qs.`Item Number` and si.store_id = 1)
						INNER JOIN (select x.item_id, min(x.cost_per_bottle + IF(cost_per_bottle > ps.SWE_cost_threshold or COALESCE(i.bot_per_case,x.bot_per_case) > ps.SWE_min_qty_under_cost_threshold,x.split_case_charge,0)) as bot_cost
						FROM (item_xref x INNER JOIN item i on x.item_id = i.ID)
						INNER JOIN hub_price_settings ps on x.store_id = ps.store_id
						WHERE x.store_id = 1 group by x.item_id) AS xf ON si.item_id = xf.item_id";
 		mysql_query($sql) or sql_error($sql);
	}

}//end class


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Odachi.Gettext.Internal.Expressions
{
	internal class CExpressionSymbol
	{
		public CExpressionSymbol(CExpressionSymbolKind kind, string text)
		{
			Kind = kind;
			Text = text;
		}

		public CExpressionSymbolKind Kind { get; set; }

		public string Text { get; set; }

		public override string ToString()
		{
			return "Symbol '" + Text + "' (" + Kind + ")";
		}
	}
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Giansalex
 * Date: 05/10/2017
 * Time: 08:23
 */

declare(strict_types=1);

namespace Tests\Greenter\Xml\Parser;

use Greenter\Model\Sale\Invoice;
use Greenter\Xml\Parser\InvoiceParser;
use PHPUnit\Framework\TestCase;

class InvoiceParserTest extends TestCase
{
    /**
     * @dataProvider providerSolDocs
     * @param string $filename
     */
    public function testParseSunatSOL($filename)
    {
        $parser = new InvoiceParser();

        $xml = file_get_contents($filename);
        /**@var $obj Invoice */
        $obj = $parser->parse($xml);

        $this->assertRegExp('/^0\d{1}/', $obj->getTipoDoc());
        $this->assertRegExp('/^E\w{3}/', $obj->getSerie());
        $this->assertLessThanOrEqual(8, strlen($obj->getCorrelativo()));
        $this->assertNotEmpty($obj->getFechaEmision());
        $this->assertGreaterThanOrEqual(1, count($obj->getDetails()));
        $this->assertGreaterThanOrEqual(1, count($obj->getLegends()));
        $this->assertNotNull($obj->getCompany());
        $this->assertNotNull($obj->getCompany()->getAddress());
        $this->assertNotEmpty($obj->getCompany()->getAddress()->getDireccion());
        $this->assertNotEmpty($obj->getCompany()->getAddress()->getUbigueo());
    }

    /**
     * @dataProvider providerDocs
     * @param string $filename
     */
    public function testFacParse($filename)
    {
        $parser = new InvoiceParser();

        $xml = file_get_contents($filename);
        /**@var $obj Invoice */
        $obj = $parser->parse($xml);

        $this->assertRegExp('/^0\d{1}/', $obj->getTipoDoc());
        $this->assertRegExp('/^[FB]\w{3}/', $obj->getSerie());
        $this->assertLessThanOrEqual(8, strlen($obj->getCorrelativo()));
        $this->assertNotEmpty($obj->getFechaEmision());
        $this->assertGreaterThanOrEqual(1, count($obj->getDetails()));
        $this->assertGreaterThanOrEqual(1, count($obj->getLegends()));
        $this->assertTrue(is_float($obj->getMtoImpVenta()));
    }

    public function testFacParseFromDoc()
    {
        $parser = new InvoiceParser();

        $xml = file_get_contents($this->providerDocs()[0][0]);
        $doc = new \DOMDocument();
        @$doc->loadXML($xml);
        /**@var $obj Invoice */
        $obj = $parser->parse($doc);

        $this->assertRegExp('/^0\d{1}/', $obj->getTipoDoc());
        $this->assertRegExp('/^[FB]\w{3}/', $obj->getSerie());
        $this->assertLessThanOrEqual(8, strlen($obj->getCorrelativo()));
        $this->assertNotEmpty($obj->getFechaEmision());
        $this->assertGreaterThanOrEqual(1, count($obj->getDetails()));
        $this->assertGreaterThanOrEqual(1, count($obj->getLegends()));
    }

    public function providerDocs()
    {
        $files = glob(__DIR__.'/../../Resources/invoice/*.xml');

        return array_map(function ($file) {
            return [$file];
        }, $files);
    }

    public function providerSolDocs()
    {
        $files = glob(__DIR__.'/../../Resources/clavesol/*.xml');

        return array_map(function ($file) {
            return [$file];
        }, $files);
    }
}


text:
"use strict";

const Base = require("./Base");

/**
* Represents a channel. You also probably want to look at GroupChannel, GuildChannel, and PrivateChannel
* @prop {String} id The ID of the channel
* @prop {Number} createdAt Timestamp of the channel's creation
*/
class Channel extends Base {
    constructor(data) {
        super(data.id);
        this.type = data.type;
    }

    /**
    * Send typing status in a text channel
    * @returns {Promise}
    */
    sendTyping() {
        return (this._client || this.guild.shard.client).sendChannelTyping.call((this._client || this.guild.shard.client), this.id);
    }

    /**
    * Get a previous message in a text channel
    * @arg {String} messageID The ID of the message
    * @returns {Promise<Message>}
    */
    getMessage(messageID) {
        return (this._client || this.guild.shard.client).getMessage.call((this._client || this.guild.shard.client), this.id, messageID);
    }

    /**
    * Get a previous message in a text channel
    * @arg {Number} [limit=50] The max number of messages to get
    * @arg {String} [before] Get messages before this message ID
    * @arg {String} [after] Get messages after this message ID
    * @arg {String} [around] Get messages around this message ID (does not work with limit > 100)
    * @returns {Promise<Message[]>}
    */
    getMessages(limit, before, after, around) {
        return (this._client || this.guild.shard.client).getMessages.call((this._client || this.guild.shard.client), this.id, limit, before, after, around);
    }

    /**
    * Get all the pins in a text channel
    * @returns {Promise<Message[]>}
    */
    getPins() {
        return (this._client || this.guild.shard.client).getPins.call((this._client || this.guild.shard.client), this.id);
    }

    /**
    * Create a message in a text channel
    * Note: If you want to DM someone, the user ID is **not** the DM channel ID. use Client.getDMChannel() to get the DM channel ID for a user
    * @arg {String | Object} content A string or object. If an object is passed:
    * @arg {String} content.content A content string
    * @arg {Boolean} [content.tts] Set the message TTS flag
    * @arg {Boolean} [content.disableEveryone] Whether to filter @everyone/@here or not (overrides default)
    * @arg {Object} [content.embed] An embed object. See [the official Discord API documentation entry](https://discordapp.com/developers/docs/resources/channel#embed-object) for object structure
    * @arg {Object} [file] A file object
    * @arg {String} file.file A buffer containing file data
    * @arg {String} file.name What to name the file
    * @returns {Promise<Message>}
    */
    createMessage(content, file) {
        return (this._client || this.guild.shard.client).createMessage.call((this._client || this.guild.shard.client), this.id, content, file);
    }

    /**
    * Edit a message
    * @arg {String} messageID The ID of the message
    * @arg {String | Array | Object} content A string, array of strings, or object. If an object is passed:
    * @arg {String} content.content A content string
    * @arg {Boolean} [content.disableEveryone] Whether to filter @everyone/@here or not (overrides default)
    * @arg {Object} [content.embed] An embed object. See [the official Discord API documentation entry](https://discordapp.com/developers/docs/resources/channel#embed-object) for object structure
    * @returns {Promise<Message>}
    */
    editMessage(messageID, content) {
        return (this._client || this.guild.shard.client).editMessage.call((this._client || this.guild.shard.client), this.id, messageID, content);
    }

    /**
    * Pin a message
    * @arg {String} messageID The ID of the message
    * @returns {Promise}
    */
    pinMessage(messageID) {
        return (this._client || this.guild.shard.client).pinMessage.call((this._client || this.guild.shard.client), this.id, messageID);
    }

    /**
    * Unpin a message
    * @arg {String} messageID The ID of the message
    * @returns {Promise}
    */
    unpinMessage(messageID) {
        return (this._client || this.guild.shard.client).unpinMessage.call((this._client || this.guild.shard.client), this.id, messageID);
    }

    /**
    * Get a list of users who reacted with a specific reaction
    * @arg {String} messageID The ID of the message
    * @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji)
    * @arg {Number} [limit=100] The maximum number of users to get
    * @returns {Promise<User[]>}
    */
    getMessageReaction(messageID, reaction, limit) {
        return (this._client || this.guild.shard.client).getMessageReaction.call((this._client || this.guild.shard.client), this.id, messageID, reaction, limit);
    }

    /**
    * Add a reaction to a message
    * @arg {String} messageID The ID of the message
    * @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji)
    * @arg {String} [userID="@me"] The ID of the user to react as
    * @returns {Promise}
    */
    addMessageReaction(messageID, reaction, userID) {
        return (this._client || this.guild.shard.client).addMessageReaction.call((this._client || this.guild.shard.client), this.id, messageID, reaction, userID);
    }

    /**
    * Remove a reaction from a message
    * @arg {String} messageID The ID of the message
    * @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji)
    * @arg {String} [userID="@me"] The ID of the user to remove the reaction for
    * @returns {Promise}
    */
    removeMessageReaction(messageID, reaction, userID) {
        return (this._client || this.guild.shard.client).removeMessageReaction.call((this._client || this.guild.shard.client), this.id, messageID, reaction, userID);
    }

    /**
    * Remove all reactions from a message
    * @arg {String} messageID The ID of the message
    * @returns {Promise}
    */
    removeMessageReactions(messageID) {
        return (this._client || this.guild.shard.client).removeMessageReactions.call((this._client || this.guild.shard.client), this.id, messageID);
    }

    /**
    * Delete a message
    * @arg {String} messageID The ID of the message
    * @arg {String} [reason] The reason to be displayed in audit logs
    * @returns {Promise}
    */
    deleteMessage(messageID, reason) {
        return (this._client || this.guild.shard.client).deleteMessage.call((this._client || this.guild.shard.client), this.id, messageID, reason);
    }

    /**
    * Un-send a message. You're welcome Programmix
    * @arg {String} messageID The ID of the message
    * @returns {Promise}
    */
    unsendMessage(messageID) {
        return (this._client || this.guild.shard.client).deleteMessage.call((this._client || this.guild.shard.client), this.id, messageID);
    }
}

module.exports = Channel;