text:
namespace extensions {

namespace {

// This video encoder implements hardware accelerated H.264 video encoding
// using media::VideoEncodeAccelerator.
class WiFiDisplayVideoEncoderVEA final
    : public WiFiDisplayVideoEncoder,
      public media::VideoEncodeAccelerator::Client {
 public:
  static void Create(
      const InitParameters& params,
      const VideoEncoderCallback& encoder_callback,
      scoped_refptr<base::SingleThreadTaskRunner> media_task_runner,
      std::unique_ptr<media::VideoEncodeAccelerator> vea);

 private:
  WiFiDisplayVideoEncoderVEA(
      scoped_refptr<base::SingleThreadTaskRunner> media_task_runner,
      media::VideoEncodeAccelerator* vea,
      const CreateEncodeMemoryCallback& create_memory_callback);
  ~WiFiDisplayVideoEncoderVEA() override;

  // media::VideoEncodeAccelerator::Client
  void RequireBitstreamBuffers(unsigned int input_count,
                               const gfx::Size& input_coded_size,
                               size_t output_buffer_size) override;

  void BitstreamBufferReady(int32_t bitstream_buffer_id,
                            size_t payload_size,
                            bool key_frame,
                            base::TimeDelta timestamp) override;
  void NotifyError(media::VideoEncodeAccelerator::Error error) override;

  scoped_refptr<WiFiDisplayVideoEncoder> InitOnMediaThread(
      const InitParameters& params);
  void InsertFrameOnMediaThread(scoped_refptr<media::VideoFrame> video_frame,
                                base::TimeTicks reference_time,
                                bool send_idr) override;
  void OnCreateSharedMemory(std::unique_ptr<base::SharedMemory> memory);
  void OnReceivedSharedMemory(std::unique_ptr<base::SharedMemory> memory);

 private:
  struct InProgressFrameEncode {
    InProgressFrameEncode(scoped_refptr<media::VideoFrame> video_frame,
                          base::TimeTicks reference_time);
    ~InProgressFrameEncode();
    // The source content to encode.
    const scoped_refptr<media::VideoFrame> video_frame;

    // The reference time for this frame.
    const base::TimeTicks reference_time;
  };
  // FIFO list.
  std::list<InProgressFrameEncode> in_progress_frame_encodes_;
  media::VideoEncodeAccelerator* vea_;  // Owned on media thread.
  ScopedVector<base::SharedMemory> output_buffers_;
  size_t output_buffers_count_;
  CreateEncodeMemoryCallback create_video_encode_memory_cb_;
};

WiFiDisplayVideoEncoderVEA::InProgressFrameEncode::InProgressFrameEncode(
    scoped_refptr<media::VideoFrame> video_frame,
    base::TimeTicks reference_time)
    : video_frame(std::move(video_frame)), reference_time(reference_time) {}

WiFiDisplayVideoEncoderVEA::InProgressFrameEncode::~InProgressFrameEncode() =
    default;

// static
void WiFiDisplayVideoEncoderVEA::Create(
    const InitParameters& params,
    const VideoEncoderCallback& encoder_callback,
    scoped_refptr<base::SingleThreadTaskRunner> media_task_runner,
    std::unique_ptr<media::VideoEncodeAccelerator> vea) {
  if (!vea || !media_task_runner) {
    encoder_callback.Run(nullptr);
    return;
  }

  base::PostTaskAndReplyWithResult(
      media_task_runner.get(), FROM_HERE,
      base::Bind(&WiFiDisplayVideoEncoderVEA::InitOnMediaThread,
                 make_scoped_refptr(new WiFiDisplayVideoEncoderVEA(
                     std::move(media_task_runner), vea.release(),
                     params.create_memory_callback)),
                 params),
      encoder_callback);
}

WiFiDisplayVideoEncoderVEA::WiFiDisplayVideoEncoderVEA(
    scoped_refptr<base::SingleThreadTaskRunner> media_task_runner,
    media::VideoEncodeAccelerator* vea,
    const CreateEncodeMemoryCallback& create_video_encode_memory_cb)
    : WiFiDisplayVideoEncoder(std::move(media_task_runner)),
      vea_(vea),
      output_buffers_count_(0),
      create_video_encode_memory_cb_(create_video_encode_memory_cb) {}

WiFiDisplayVideoEncoderVEA::~WiFiDisplayVideoEncoderVEA() {
  media_task_runner_->PostTask(
      FROM_HERE, base::Bind(&media::VideoEncodeAccelerator::Destroy,
                            base::Unretained(vea_)));
}

scoped_refptr<WiFiDisplayVideoEncoder>
WiFiDisplayVideoEncoderVEA::InitOnMediaThread(const InitParameters& params) {
  media::VideoCodecProfile profile = (params.profile == wds::CHP)
      ? media::H264PROFILE_HIGH : media::H264PROFILE_BASELINE;
  bool success =
      vea_->Initialize(media::PIXEL_FORMAT_I420, params.frame_size,
                       profile, params.bit_rate, this);
  if (success)
    return this;

  DVLOG(1) << "Failed to init VEA";
  return nullptr;
}

// Called to allocate the input and output buffers.
void WiFiDisplayVideoEncoderVEA::RequireBitstreamBuffers(
    unsigned int input_count,
    const gfx::Size& input_coded_size,
    size_t output_buffer_size) {
  DCHECK(media_task_runner_->BelongsToCurrentThread());
  output_buffers_count_ = input_count;
  for (size_t i = 0; i < input_count; ++i) {
    create_video_encode_memory_cb_.Run(
        output_buffer_size,
        base::Bind(&WiFiDisplayVideoEncoderVEA::OnCreateSharedMemory, this));
  }
}

// Note: This method can be called on any thread.
void WiFiDisplayVideoEncoderVEA::OnCreateSharedMemory(
    std::unique_ptr<base::SharedMemory> memory) {
  media_task_runner_->PostTask(
      FROM_HERE, base::Bind(&WiFiDisplayVideoEncoderVEA::OnReceivedSharedMemory,
                            this, base::Passed(&memory)));
}

void WiFiDisplayVideoEncoderVEA::OnReceivedSharedMemory(
    std::unique_ptr<base::SharedMemory> memory) {
  DCHECK(media_task_runner_->BelongsToCurrentThread());

  output_buffers_.push_back(std::move(memory));

  // Wait until all requested buffers are received.
  if (output_buffers_.size() < output_buffers_count_)
    return;

  // Immediately provide all output buffers to the VEA.
  for (size_t i = 0; i < output_buffers_.size(); ++i) {
    vea_->UseOutputBitstreamBuffer(media::BitstreamBuffer(
        static_cast<int32_t>(i), output_buffers_[i]->handle(),
        output_buffers_[i]->mapped_size()));
  }
}

void WiFiDisplayVideoEncoderVEA::InsertFrameOnMediaThread(
    scoped_refptr<media::VideoFrame> video_frame,
    base::TimeTicks reference_time,
    bool send_idr) {
  in_progress_frame_encodes_.emplace_back(video_frame, reference_time);
  DCHECK(vea_);
  vea_->Encode(video_frame, send_idr);
}

void WiFiDisplayVideoEncoderVEA::BitstreamBufferReady(
    int32_t bitstream_buffer_id,
    size_t payload_size,
    bool key_frame,
    base::TimeDelta timestamp) {
  if (bitstream_buffer_id >= static_cast<int>(output_buffers_.size())) {
    DVLOG(1) << "WiFiDisplayVideoEncoderVEA::BitstreamBufferReady()"
             << ": invalid bitstream_buffer_id=" << bitstream_buffer_id;
    return;
  }
  base::SharedMemory* output_buffer = output_buffers_[bitstream_buffer_id];
  if (payload_size > output_buffer->mapped_size()) {
    DVLOG(1) << "WiFiDisplayVideoEncoderVEA::BitstreamBufferReady()"
             << ": invalid payload_size=" << payload_size;
    return;
  }
  if (in_progress_frame_encodes_.empty()) {
    DVLOG(1) << "WiFiDisplayVideoEncoderVEA::BitstreamBufferReady()"
             << ": unexpected frame";
    return;
  }
  const InProgressFrameEncode& request = in_progress_frame_encodes_.front();

  if (!encoded_callback_.is_null()) {
    encoded_callback_.Run(
        std::unique_ptr<WiFiDisplayEncodedFrame>(new WiFiDisplayEncodedFrame(
            std::string(reinterpret_cast<const char*>(output_buffer->memory()),
                        payload_size),
            request.reference_time, base::TimeTicks::Now(), key_frame)));
  }
  DCHECK(vea_);
  vea_->UseOutputBitstreamBuffer(
      media::BitstreamBuffer(bitstream_buffer_id, output_buffer->handle(),
                             output_buffer->mapped_size()));

  in_progress_frame_encodes_.pop_front();
}

void WiFiDisplayVideoEncoderVEA::NotifyError(
    media::VideoEncodeAccelerator::Error error) {
  if (!error_callback_.is_null())
    error_callback_.Run();
}

}  // namespace

// static
void WiFiDisplayVideoEncoder::CreateVEA(
    const InitParameters& params,
    const VideoEncoderCallback& encoder_callback) {
  auto on_vea_cb =
      base::Bind(&WiFiDisplayVideoEncoderVEA::Create, params, encoder_callback);
  params.vea_create_callback.Run(media::BindToCurrentLoop(on_vea_cb));
}

}  // namespace extensions


text:
title: "Torstaiksi 10.9"
tags: läksyt rub1.1
---

Lue teksti 4 (huomaa että teksti on kolmessa osassa, A, B ja C). Tee sitten työvihkosta tekstiin 4 liittyvät aukkosuomennokset ja B-teksti käy läpi suomennoksen kera (3 sivua).

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

	<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=utf-8">
	<TITLE>PTHREAD_MUTEXATTR_SETPSHARED(3) manual page</TITLE>

POSIX Threads for Windows – REFERENCE - Pthreads4W

Reference Index

Table of Contents

Name

pthread_mutexattr_getpshared, pthread_mutexattr_setpshared - get
and set the process-shared attribute

Synopsis

#include <pthread.h>

int pthread_mutexattr_getpshared(const pthread_mutexattr_t *
restrict attr, int *restrict pshared);

int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr,
int pshared);

Description

The pthread_mutexattr_getpshared function shall obtain the
value of the process-shared attribute from the attributes
object referenced by attr. The pthread_mutexattr_setpshared
function shall set the process-shared attribute in an
initialized attributes object referenced by attr.

The process-shared attribute is set to
PTHREAD_PROCESS_SHARED to permit a mutex to be operated upon
by any thread that has access to the memory where the mutex is
allocated, even if the mutex is allocated in memory that is shared by
multiple processes. If the process-shared attribute is
PTHREAD_PROCESS_PRIVATE, the mutex shall only be operated upon
by threads created within the same process as the thread that
initialized the mutex; if threads of differing processes attempt to
operate on such a mutex, the behavior is undefined. The default value
of the attribute shall be PTHREAD_PROCESS_PRIVATE.

PThreads4W defines _POSIX_THREAD_PROCESS_SHARED in
pthread.h as -1 to indicate that these routines are implemented but
the process shared option is not supported.

Return Value

Upon successful completion, pthread_mutexattr_setpshared
shall return zero; otherwise, an error number shall be returned to
indicate the error.

Upon successful completion, pthread_mutexattr_getpshared
shall return zero and store the value of the process-shared
attribute of attr into the object referenced by the pshared
parameter. Otherwise, an error number shall be returned to indicate
the error.

Errors

The pthread_mutexattr_getpshared and
pthread_mutexattr_setpshared functions may fail if:

EINVAL

	The value specified by attr is invalid.

The pthread_mutexattr_setpshared function may fail if:

EINVAL

	The new value specified for the attribute is outside the range of
	legal values for that attribute.

	ENOTSUP

	The new value specified for the attribute is PTHREAD_PROCESS_SHARED.

These functions shall not return an error code of [EINTR].

The following sections are informative.

Examples

None.

Application Usage

None.

Rationale

None.

Future Directions

None.

See Also

pthread_cond_destroy(3)
, pthread_create(3) ,
pthread_mutex_destroy(3)
, pthread_mutexattr_destroy(3)
, the Base Definitions volume of IEEE Std 1003.1-2001,
<pthread.h>

Copyright

Portions of this text are reprinted and reproduced in electronic
form from IEEE Std 1003.1, 2003 Edition, Standard for Information
Technology -- Portable Operating System Interface (POSIX), The Open
Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the
Institute of Electrical and Electronics Engineers, Inc and The Open
Group. In the event of any discrepancy between this version and the
original IEEE and The Open Group Standard, the original IEEE and The
Open Group Standard is the referee document. The original Standard
can be obtained online at http://www.opengroup.org/unix/online.html
.

Modified by Ross Johnson for use with Pthreads4W.

Table of Contents

Name

Synopsis

Description

Return
	Value

Errors

Examples

Application
	Usage

Rationale

Future
	Directions

See
	Also

Copyright


text:
'use strict';

import { module } from 'angular';

import { AccountService, Registry } from '@spinnaker/core';

export const ECS_PIPELINE_STAGES_SHRINKCLUSTER_ECSSHRINKCLUSTERSTAGE =
  'spinnaker.ecs.pipeline.stage.ecs.shrinkClusterStage';
export const name = ECS_PIPELINE_STAGES_SHRINKCLUSTER_ECSSHRINKCLUSTERSTAGE; // for backwards compatibility
module(ECS_PIPELINE_STAGES_SHRINKCLUSTER_ECSSHRINKCLUSTERSTAGE, [])
  .config(function () {
    Registry.pipeline.registerStage({
      provides: 'shrinkCluster',
      cloudProvider: 'ecs',
      templateUrl: require('./shrinkClusterStage.html'),
      accountExtractor: (stage) => [stage.context.credentials],
      configAccountExtractor: (stage) => [stage.credentials],
      validators: [
        { type: 'requiredField', fieldName: 'cluster' },
        { type: 'requiredField', fieldName: 'shrinkToSize', fieldLabel: 'shrink to [X] Server Groups' },
        { type: 'requiredField', fieldName: 'regions' },
        { type: 'requiredField', fieldName: 'credentials', fieldLabel: 'account' },
      ],
    });
  })
  .controller('ecsShrinkClusterStageCtrl', [
    '$scope',
    function ($scope) {
      const ctrl = this;

      const stage = $scope.stage;

      $scope.state = {
        accounts: false,
        regionsLoaded: false,
      };

      AccountService.listAccounts('ecs').then(function (accounts) {
        $scope.accounts = accounts;
        $scope.state.accounts = true;
      });

      stage.regions = stage.regions || [];
      stage.cloudProvider = 'ecs';

      if (!stage.credentials && $scope.application.defaultCredentials.ecs) {
        stage.credentials = $scope.application.defaultCredentials.ecs;
      }
      if (!stage.regions.length && $scope.application.defaultRegions.ecs) {
        stage.regions.push($scope.application.defaultRegions.ecs);
      }

      if (stage.shrinkToSize === undefined) {
        stage.shrinkToSize = 1;
      }

      if (stage.allowDeleteActive === undefined) {
        stage.allowDeleteActive = false;
      }

      ctrl.pluralize = function (str, val) {
        if (val === 1) {
          return str;
        }
        return str + 's';
      };

      if (stage.retainLargerOverNewer === undefined) {
        stage.retainLargerOverNewer = 'false';
      }
      stage.retainLargerOverNewer = stage.retainLargerOverNewer.toString();
    },
  ]);


text:
<?xml version="1.0" encoding="UTF-8" ?>
<ldml>
	<identity>
		<version number="$Revision: 1.54 $"/>
		<generation date="$Date: 2009/06/15 04:15:33 $"/>
		<language type="dv"/>
	</identity>
	<localeDisplayNames>
		<languages>
			<language type="dv">ދިވެހިބަސް</language>
		</languages>
		<territories>
			<territory type="MV">ދިވެހި ރާއްޖެ</territory>
		</territories>
	</localeDisplayNames>
	<layout>
		<orientation characters="right-to-left"/>
	</layout>
	<characters>
		<exemplarCharacters>[ހ-ޗ \u07A6-\u07B0]</exemplarCharacters>
		<exemplarCharacters type="auxiliary">[\u200C \u200D ޙ ޚ ޜ ޢ ޣ ޥ ޛ ޘ ޠ ޡ ޤ ޝ-ޟ ޱ]</exemplarCharacters>
	</characters>
	<dates>
		<calendars>
			<calendar type="gregorian">
				<months>
					<monthContext type="format">
						<monthWidth type="abbreviated">
							<month type="1">1</month>
							<month type="2">2</month>
							<month type="3">3</month>
							<month type="4">4</month>
							<month type="5">5</month>
							<month type="6">6</month>
							<month type="7">7</month>
							<month type="8">8</month>
							<month type="9">9</month>
							<month type="10">10</month>
							<month type="11">11</month>
							<month type="12">12</month>
						</monthWidth>
						<monthWidth type="wide">
							<month type="1">1</month>
							<month type="2">2</month>
							<month type="3">3</month>
							<month type="4">4</month>
							<month type="5">5</month>
							<month type="6">6</month>
							<month type="7">7</month>
							<month type="8">8</month>
							<month type="9">9</month>
							<month type="10">10</month>
							<month type="11">11</month>
							<month type="12">12</month>
						</monthWidth>
					</monthContext>
					<monthContext type="stand-alone">
						<monthWidth type="narrow">
							<month type="1">1</month>
							<month type="2">2</month>
							<month type="3">3</month>
							<month type="4">4</month>
							<month type="5">5</month>
							<month type="6">6</month>
							<month type="7">7</month>
							<month type="8">8</month>
							<month type="9">9</month>
							<month type="10">10</month>
							<month type="11">11</month>
							<month type="12">12</month>
						</monthWidth>
					</monthContext>
				</months>
				<days>
					<dayContext type="format">
						<dayWidth type="abbreviated">
							<day type="sun">1</day>
							<day type="mon">2</day>
							<day type="tue">3</day>
							<day type="wed">4</day>
							<day type="thu">5</day>
							<day type="fri">6</day>
							<day type="sat">7</day>
						</dayWidth>
						<dayWidth type="wide">
							<day type="sun">1</day>
							<day type="mon">2</day>
							<day type="tue">3</day>
							<day type="wed">4</day>
							<day type="thu">5</day>
							<day type="fri">6</day>
							<day type="sat">7</day>
						</dayWidth>
					</dayContext>
					<dayContext type="stand-alone">
						<dayWidth type="narrow">
							<day type="sun">1</day>
							<day type="mon">2</day>
							<day type="tue">3</day>
							<day type="wed">4</day>
							<day type="thu">5</day>
							<day type="fri">6</day>
							<day type="sat">7</day>
						</dayWidth>
					</dayContext>
				</days>
				<quarters>
					<quarterContext type="format">
						<quarterWidth type="abbreviated">
							<quarter type="1">Q1</quarter>
							<quarter type="2">Q2</quarter>
							<quarter type="3">Q3</quarter>
							<quarter type="4">Q4</quarter>
						</quarterWidth>
						<quarterWidth type="wide">
							<quarter type="1">Q1</quarter>
							<quarter type="2">Q2</quarter>
							<quarter type="3">Q3</quarter>
							<quarter type="4">Q4</quarter>
						</quarterWidth>
					</quarterContext>
				</quarters>
				<am>AM</am>
				<pm>PM</pm>
				<eras>
					<eraAbbr>
						<era type="0">BCE</era>
						<era type="1">CE</era>
					</eraAbbr>
				</eras>
				<dateFormats>
					<dateFormatLength type="full">
						<dateFormat>
							<pattern>EEEE d MMMM y</pattern>
						</dateFormat>
					</dateFormatLength>
					<dateFormatLength type="long">
						<dateFormat>
							<pattern>d MMMM y</pattern>
						</dateFormat>
					</dateFormatLength>
					<dateFormatLength type="medium">
						<dateFormat>
							<pattern>dd-MM-yyyy</pattern>
						</dateFormat>
					</dateFormatLength>
					<dateFormatLength type="short">
						<dateFormat>
							<pattern>d-M-yy</pattern>
						</dateFormat>
					</dateFormatLength>
				</dateFormats>
				<timeFormats>
					<timeFormatLength type="full">
						<timeFormat>
							<pattern>hh:mm:ss a zzzz</pattern>
						</timeFormat>
					</timeFormatLength>
					<timeFormatLength type="long">
						<timeFormat>
							<pattern>hh:mm:ss a z</pattern>
						</timeFormat>
					</timeFormatLength>
					<timeFormatLength type="medium">
						<timeFormat>
							<pattern>hh:mm:ss a</pattern>
						</timeFormat>
					</timeFormatLength>
					<timeFormatLength type="short">
						<timeFormat>
							<pattern>hh:mm a</pattern>
						</timeFormat>
					</timeFormatLength>
				</timeFormats>
				<dateTimeFormats>
					<availableFormats>
						<dateFormatItem id="MMdd">dd-MM</dateFormatItem>
						<dateFormatItem id="MMMMd">d MMMM</dateFormatItem>
						<dateFormatItem id="yyQ">Q yy</dateFormatItem>
						<dateFormatItem id="yyyyMM">MM-yyyy</dateFormatItem>
						<dateFormatItem id="yyyyMMMM">MMMM y</dateFormatItem>
					</availableFormats>
				</dateTimeFormats>
			</calendar>
		</calendars>
		<timeZoneNames>
			<hourFormat>+HH:mm;-HH:mm</hourFormat>
			<gmtFormat>GMT{0}</gmtFormat>
			<regionFormat>{0}</regionFormat>
		</timeZoneNames>
	</dates>
	<numbers>
		<symbols>
			<list>,</list>
			<nativeZeroDigit>0</nativeZeroDigit>
		</symbols>
		<decimalFormats>
			<decimalFormatLength>
				<decimalFormat>
					<pattern>#,##,##0.###</pattern>
				</decimalFormat>
			</decimalFormatLength>
		</decimalFormats>
		<percentFormats>
			<percentFormatLength>
				<percentFormat>
					<pattern>#,##,##0%</pattern>
				</percentFormat>
			</percentFormatLength>
		</percentFormats>
		<currencyFormats>
			<currencyFormatLength>
				<currencyFormat>
					<pattern>¤ #,##,##0.00</pattern>
				</currencyFormat>
			</currencyFormatLength>
		</currencyFormats>
		<currencies>
			<currency type="MVR">
				<symbol>ރ.</symbol>
			</currency>
		</currencies>
	</numbers>
</ldml>


text:
using System.Collections.Generic;
using NFleet.Data;

namespace NFleet
{
    public class ResponseData : IResponseData
    {
        public Link Location { get { return Meta.Find( l => l.Rel == "location" ); } }

        public ResponseData()
        {
            Meta = new List<Link>();
            Items = new List<ErrorData>();
        }

        public List<Link> Meta { get; set; }
        public List<ErrorData> Items { get; set; }

        #region Implementation of IVersioned

        public int VersionNumber { get; set; }

        #endregion
    }
}


text:
extern "C" {
#endif
#include "ffmpeg-1.1\rtsp.h"
#include "ffmpeg-1.1\rtspcodes.h"
	int ffio_open_dyn_packet_buf(AVIOContext **, int );
#ifdef __cplusplus__
}
#endif

#include "../VideoUtility/rtspconf.h"

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#define HOLE_PUNCHING  // enable self-implemented hole-punching
#define RTSP_CHANNEL_MAX 8
#define RTSP_CHANNEL_MAXx2 16

#define IMAGE_SOURCE_CHANNEL_MAX 4 // temp define here
#define SHARE_ENCODER

#define MULTI_CHANNEL

// this definition is a flag to identify the rtsp context support multi-sourced video or not
#define MULTI_SOURCE_SUPPORT

#ifndef NIPQUAD
#define NIPQUAD(x) ((unsigned char *)&(x))[0], \
	((unsigned char *)&(x))[1], \
	((unsigned char *)&(x))[2], \
	((unsigned char *)&(x))[3]
#endif
namespace cg{
	namespace rtsp{
		enum RTSPServerState{
			SERVER_STATE_IDLE = 0,
			SERVER_STATE_READY,
			SERVER_STATE_PLAYING,
			SERVER_STATE_PAUSE,
			SERVER_STATE_TEARDOWN
		};

		struct RTSPContext{
			int channels;
			int id;  // combine the source with rtsp context
			char object[RTSPCONF_OBJECT_SIZE];    // the rtsp service name
			unsigned char tag;

			bool initialized; //
			bool enableGen;
			SOCKET fd;
			struct sockaddr_in client;

			int state;
			int hasVideo;

			int height, width;
			/// RTSP
			//internal read buffer
			char * rBuffer;
			int rBufHead;
			int rBufTail;
			int rBufSize;

			// for creating SDP
			AVFormatContext *sdpFmtCtx;
			AVStream *sdpVStream[IMAGE_SOURCE_CHANNEL_MAX];
			AVStream *sdpAStream;
			AVCodecContext * sdpVEncoder[IMAGE_SOURCE_CHANNEL_MAX];
			AVCodecContext * sdpAEncoder;
			// for real audio / video encoding
			//
			int seq;
			char *sessionId;
			enum RTSPLowerTransport lowerTransport[RTSP_CHANNEL_MAX];
			AVFormatContext * fmtCtx[RTSP_CHANNEL_MAX];
			AVStream * stream[RTSP_CHANNEL_MAX];
			AVCodecContext * encoder[RTSP_CHANNEL_MAX];
			// streaming
			int mtu;
			URLContext * rtp[RTSP_CHANNEL_MAX]; // RTP over UDP
			HANDLE rtspWriteMutex; // RTP over RTSP/ TCP

			RTSPConf * rtspConf;
#ifdef HOLE_PUNCHING
			int streamCount;
			SOCKET rtpSocket[RTSP_CHANNEL_MAXx2];

			unsigned short rtpLocalPort[RTSP_CHANNEL_MAXx2];
			unsigned short rtpPeerPort[RTSP_CHANNEL_MAXx2];
			char rtpPortChecked[RTSP_CHANNEL_MAXx2];
#endif

		public:
			void setConf(RTSPConf * conf){ rtspConf = conf; }
			void rtspCleanUp(int retCode);
			int rtspWriteBinData(int streamId, uint8_t *buf, int bufLen);

			// tool functions
			int clientInit(int channels, int width, int height);
			int rtspWrite(const void* buf, size_t count);
			int rtspPrintf(const char* fmt, ...);
#ifdef HOLE_PUNCHING
			int rtpOpenPorts(int streamId);
			int rtpClosePorts(int streamId);
			int rtpWriteBinData(int streamId, uint8_t* buf, int bufLen);

#endif

			int rtpNewAVStream(struct sockaddr_in * sin, int streamid, enum AVCodecID codecid);
			int rtspReadInternal();
			int rtspReadText(char* buf, size_t count);
			int rtspReadBinary(char* buf, size_t count);
			int rtspGetNext(char* buf, size_t count);

			void closeAV(AVFormatContext* fctx, AVStream* st, AVCodecContext* cctx,enum RTSPLowerTransport transport );
			void clientDeinit();
			void rtspReplyHeader(enum RTSPStatusCode error_number);
			void rtspReplyError(enum RTSPStatusCode error_number);
			int prepareSdpDescription(char* buf, int bufsize);
			void rtspCmdDescribe(const char* url);
			void rtspCmdOptions(const char* url);
			RTSPTransportField * findTransport(RTSPMessageHeader* h, enum RTSPLowerTransport lower_transport );

			void rtspCmdSetup(const char* url, RTSPMessageHeader* h, int streamId);
			void rtspCmdPlay(const char* url, RTSPMessageHeader* h);
			void rtspCmdPause(const char * rul, RTSPMessageHeader * h);
			void rtspCmdTeardown(const char * rul, RTSPMessageHeader * h, int bruteforce);

			// constructor and destructor
			RTSPContext();
			~RTSPContext();
			RTSPContext & operator=(const RTSPContext &); /// copy constructor

			inline RTSPConf * getRTSPConf(){
				if (NULL == rtspConf)
					rtspConf = RTSPConf::GetRTSPConf();
				return rtspConf;
			}

			inline void setId(int _id){ id = _id;}
			inline int getId(){ return id; }
			bool setClientSocket(SOCKET s);
		};

		DWORD WINAPI RtspServerThreadProc(LPVOID arg);// this is the thread procedure for the rtsp thread
	}
}
#endif


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

package com.google.gerrit.httpd;

import com.google.gerrit.common.data.GitWebType;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.config.SitePaths;
import com.google.inject.Inject;

import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

public class GitWebConfig {
  private static final Logger log = LoggerFactory.getLogger(GitWebConfig.class);

  private final String url;
  private final File gitweb_cgi;
  private final File gitweb_css;
  private final File gitweb_js;
  private final File git_logo_png;
  private GitWebType type;

  @Inject
  GitWebConfig(final SitePaths sitePaths, @GerritServerConfig final Config cfg) {
    final String cfgUrl = cfg.getString("gitweb", null, "url");
    final String cfgCgi = cfg.getString("gitweb", null, "cgi");

    type = GitWebType.fromName(cfg.getString("gitweb", null, "type"));
    type.setBranch(cfg.getString("gitweb", null, "branch"));
    type.setProject(cfg.getString("gitweb", null, "project"));
    type.setRevision(cfg.getString("gitweb", null, "revision"));

    if (type.getBranch() == null) {
      log.warn("No Pattern specified for gitweb.branch, disabling.");
      type = null;
    } else if (type.getProject() == null) {
      log.warn("No Pattern specified for gitweb.project, disabling.");
      type = null;
    } else if (type.getRevision() == null) {
      log.warn("No Pattern specified for gitweb.revision, disabling.");
      type = null;
    }

    if ((cfgUrl != null && cfgUrl.isEmpty())
        || (cfgCgi != null && cfgCgi.isEmpty()) || type == null) {
      // Either setting was explicitly set to the empty string disabling
      // gitweb for this server. Disable the configuration.
      //
      url = null;
      gitweb_cgi = null;
      gitweb_css = null;
      gitweb_js = null;
      git_logo_png = null;
      return;
    }

    if ((cfgUrl != null) && (cfgCgi == null || cfgCgi.isEmpty())) {
      // Use an externally managed gitweb instance, and not an internal one.
      //
      url = cfgUrl;
      gitweb_cgi = null;
      gitweb_css = null;
      gitweb_js = null;
      git_logo_png = null;
      return;
    }

    final File pkgCgi = new File("/usr/lib/cgi-bin/gitweb.cgi");
    String[] resourcePaths = {"/usr/share/gitweb/static", "/usr/share/gitweb",
        "/var/www/static", "/var/www"};
    File cgi;

    if (cfgCgi != null) {
      // Use the CGI script configured by the administrator, failing if it
      // cannot be used as specified.
      //
      cgi = sitePaths.resolve(cfgCgi);
      if (!cgi.isFile()) {
        throw new IllegalStateException("Cannot find gitweb.cgi: " + cgi);
      }
      if (!cgi.canExecute()) {
        throw new IllegalStateException("Cannot execute gitweb.cgi: " + cgi);
      }

      if (!cgi.equals(pkgCgi)) {
        // Assume the administrator pointed us to the distribution,
        // which also has the corresponding CSS and logo file.
        //
        String absPath = cgi.getParentFile().getAbsolutePath();
        resourcePaths = new String[] {absPath + "/static", absPath};
      }

    } else if (pkgCgi.isFile() && pkgCgi.canExecute()) {
      // Use the OS packaged CGI.
      //
      log.debug("Assuming gitweb at " + pkgCgi);
      cgi = pkgCgi;

    } else {
      log.warn("gitweb not installed (no " + pkgCgi + " found)");
      cgi = null;
      resourcePaths = new String[] {};
    }

    File css = null, js = null, logo = null;
    for (String path : resourcePaths) {
      File dir = new File(path);
      css = new File(dir, "gitweb.css");
      js = new File(dir, "gitweb.js");
      logo = new File(dir, "git-logo.png");
      if (css.isFile() && logo.isFile()) {
        break;
      }
    }

    if (cfgUrl == null || cfgUrl.isEmpty()) {
      url = cgi != null ? "gitweb" : null;
    } else {
      url = cgi != null ? cfgUrl : null;
    }
    gitweb_cgi = cgi;
    gitweb_css = css;
    gitweb_js = js;
    git_logo_png = logo;
  }

  /** @return GitWebType for gitweb viewer. */
  public GitWebType getGitWebType() {
    return type;
  }

  /**
   * @return URL of the entry point into gitweb. This URL may be relative to our
   *         context if gitweb is hosted by ourselves; or absolute if its hosted
   *         elsewhere; or null if gitweb has not been configured.
   */
  public String getUrl() {
    return url;
  }

  /** @return local path to the CGI executable; null if we shouldn't execute. */
  public File getGitwebCGI() {
    return gitweb_cgi;
  }

  /** @return local path of the {@code gitweb.css} matching the CGI. */
  public File getGitwebCSS() {
    return gitweb_css;
  }

  /** @return local path of the {@code gitweb.js} for the CGI. */
  public File getGitwebJS() {
    return gitweb_js;
  }

  /** @return local path of the {@code git-logo.png} for the CGI. */
  public File getGitLogoPNG() {
    return git_logo_png;
  }
}


text:
/**
 * <body>
 * XQuery utility classes.
 * </body>
 */
package org.basex.query.util;


text:
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * Get the login username to be used by the controller.
     * Overirden as you allow both username and email during login.
     *
     * @return string
     */
    public function username()
    {
        return 'login';
    }

    /**
     * Get the needed authorization credentials from the request.
     * Overirden as you allow both username and email during login.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return array
     */
    protected function credentials(Request $request)
    {
        $login = $request->get('login');
        $field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

        return [
            $field => $login,
            'password' => $request->get('password'),
        ];
    }
}


text:
<?php

namespace Core\Service;

use Zend\Authentication\AuthenticationService;

class AuthorizationService extends BaseService
{

    /**
     * @param $moduleName
     * @param $controllerName
     * @param $actionName
     * @return bool
     */
    public function grantAccess($moduleName, $controllerName, $actionName)
    {
        $flashmessenger = $this->getServiceManager()->get('ControllerPluginManager')->get('flashmessenger');

        $enabledPermissions = $this->getServiceManager()->get('Config');
        $enabledPermissions = $enabledPermissions['access_control'];

        $preLoginOpenActions = $enabledPermissions['preloginopenactions'];
        $postLoginOpenActions = $enabledPermissions['postloginopenactions'];

        if($this->checkPrePostAccess($preLoginOpenActions, $moduleName, $controllerName, $actionName)) {
            return true;
        }

        $auth = $this->getService('Core\Service\AuthService');
        if ( $auth->isLogged() ) {
            if($this->checkPrePostAccess($postLoginOpenActions, $moduleName, $controllerName, $actionName)) {
                return true;
            } else if ($this->checkPermission($moduleName, $controllerName, $actionName)) {
                return true;
            }
            $flashmessenger->setNamespace('danger')->addMessage('Acesso proibido!');
        }

        return false;
    }

    /**
     * @param $modulename
     * @param $controllerName
     * @param $actionName
     * @return bool
     */
    private function checkPermission($modulename, $controllerName, $actionName)
    {
        return true;
        $session = $this->getServiceManager()->get('Session');
        $user = $session->offsetGet('zf2base_loggeduser');

        $repository = $this->getDbalConnection();
        $sql = "SELECT prm_id, prm_nome FROM seg_permissoes p
                INNER JOIN seg_perfis_permissoes pp ON prp_prm_id = prm_id
                INNER JOIN seg_recursos r ON rcs_id = prm_rcs_id
                INNER JOIN seg_modulos m ON mod_id = rcs_mod_id
                WHERE mod_nome = ?
                  AND rcs_nome = ?
                  AND prm_nome = ?
                  AND prp_prf_id = (
                    SELECT prf_id FROM seg_perfis
                    INNER JOIN seg_modulos ON mod_id = prf_mod_id
                    INNER JOIN seg_perfis_usuarios ON pru_prf_id = prf_id
                    WHERE pru_usr_id = ? AND mod_nome = ?
                  )";
        $data = array($modulename, $controllerName, $actionName, $user->usr_id, $modulename);
        $res = $repository->executeQuery($sql, $data)->fetchAll();

        if (sizeof($res)) {
            return true;
        }
        return false;
    }

    /**
     * @param $openActions
     * @param $moduleName
     * @param $controllerName
     * @param $actionName
     * @return bool
     */
    private function checkPrePostAccess($openActions, $moduleName, $controllerName, $actionName)
    {
        $openModules = array_keys($openActions);
        if (in_array($moduleName, $openModules))
        {
            $openControllers = array_keys($openActions[$moduleName]);
            if (in_array($controllerName, $openControllers)) {
                if(in_array($actionName, $openActions[$moduleName][$controllerName])) {
                    return true;
                }
            }
        }
        return false;
    }
}


text:
set +x

# only run on tags
if [[ "$CIRCLE_TAG" = "" ]]; then exit 0; fi

if [ -f ~/.npmrc ]; then mv ~/.npmrc ~/.npmrc.bak; fi
echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > ~/.npmrc

echo "Publishing flow-parser-bin";
npm publish ./dist/npm-flow-parser-bin.tgz;

echo "Publishing flow-parser";
npm publish ./dist/npm-flow-parser.tgz;

echo "Publishing flow-remove-types";
npm publish ./dist/npm-flow-remove-types.tgz;

echo "Publishing flow-node";
npm publish ./dist/npm-flow-node.tgz;

if [ -f ~/.npmrc.bak ]; then mv ~/.npmrc.bak ~/.npmrc; fi


text:
export class Good {
    id: number;
    title: String;
    sellPoint: String;
    price: number;
    num: number;
    barcode: String;
    cid: number;
    status: number;
    created: String;
    updated: String;
}

export class CatParameter {
    id: number;
    itemCatId: number;
    paramData: String;
    created: String;
    updated: String;
}

export class Parameter {
    group:String;
    params:String[];
}


text:
<?php

namespace ProxyManager\ProxyGenerator\RemoteObject\MethodGenerator;

use ProxyManager\Generator\MagicMethodGenerator;
use ReflectionClass;
use ProxyManager\Generator\ParameterGenerator;
use Zend\Code\Generator\PropertyGenerator;

/**
 * Magic `__get` for remote objects
 *
 * @author Vincent Blanchon <blanchon.vincent@gmail.com>
 * @license MIT
 */
class MagicGet extends MagicMethodGenerator
{
    /**
     * Constructor
     * @param ReflectionClass                        $originalClass
     * @param \Zend\Code\Generator\PropertyGenerator $adapterProperty
     */
    public function __construct(ReflectionClass $originalClass, PropertyGenerator $adapterProperty)
    {
        parent::__construct($originalClass, '__get', array(new ParameterGenerator('name')));

        $this->setDocblock('@param string $name');
        $this->setBody(
            '$return = $this->' . $adapterProperty->getName() . '->call(' . var_export($originalClass->getName(), true)
            . ', \'__get\', array($name));' . "\n\n" . 'return $return;'
        );
    }
}


text:
Get file information using the VMRay integration.

## Dependencies
This playbook uses the following sub-playbooks, integrations, and scripts.

### Sub-playbooks
This playbook does not use any sub-playbooks.

### Integrations
* VMRay

### Scripts
* IsIntegrationAvailable

### Commands
* vmray-get-sample-by-hash

## Playbook Inputs
---

| **Name** | **Description** | **Default Value** | **Required** |
| --- | --- | --- | --- |
| MD5 | File MD5 to enrich | File.MD5 | Optional |
| SHA256 | File SHA256 to enrich | File.SHA256 | Optional |
| SHA1 | File SHA1 to enrich | File.SHA1 | Optional |

## Playbook Outputs
---

| **Path** | **Description** | **Type** |
| --- | --- | --- |
| File.Name | The full file name \(including file extension\). | String |
| File.MD5 | The MD5 hash of the file. | String |
| File.SHA1 | The SHA1 hash of the file. | String |
| File.SHA256 | The SHA256 hash of the file. | String |
| File.SSDeep | The SSDeep hash of the file. | String |
| DBotScore.Indicator | The indicator that was tested. | String |
| DBotScore.Type | The indicator type. | String |
| DBotScore.Vendor | The vendor used to calculate the score. | String |
| DBotScore.Score | The actual score. | Number |
| DBotScore.Reliability | String | Reliability of the source providing the intelligence data. |
| VMRay.Sample.SampleID | ID of the sample. | Number |
| VMRay.Sample.SampleURL | URL to sample page. | String |
| VMRay.Sample.FileName | File name of the sample. | String |
| VMRay.Sample.MD5 | MD5 hash of the sample. | String |
| VMRay.Sample.SHA1 | SHA1 hash of the sample. | String |
| VMRay.Sample.SHA256 | SHA256 hash of the sample. | String |
| VMRay.Sample.SSDeep | ssdeep hash of the sample. | String |
| VMRay.Sample.Verdict | Verdict for the sample \(Malicious, Suspicious, Clean, Not Available\). | String |
| VMRay.Sample.VerdictReason | Description of the Verdict Reason. | String |
| VMRay.Sample.Severity | Severity of the sample in the submission \(Malicious, Suspicious, Good, Blacklisted, Whitelisted, Unknown\). Deprecated. | String |
| VMRay.Sample.Type | File type. | String |
| VMRay.Sample.Created | Timestamp of sample creation. | Date |
| VMRay.Sample.Classifications | Classifications of the sample. | String |
| VMRay.Sample.ChildSampleIDs | List of child sample IDs. | Number |
| VMRay.Sample.ParentSampleIDs | List of parent sample IDs. | Number |

## Playbook Image
---
![File Enrichment - VMRay](https://raw.githubusercontent.com/demisto/content/60e253f2612941a5868c069dac05a06d9eed8360/docs/images/playbooks/File_Enrichment_VMRay.png)


text:
var $ = require('jquery');
var _ = require('underscore');
var Backbone = require('backbone');
var React = require('react');
var list = require('./warrior-list');
var Warrior = require('./warrior');

var warriorCollection = Backbone.Collection.extend({
        					comparator : function (a,b) {
								return b.get('honor') - a.get('honor');
							}
						});

var App = React.createClass({displayName: 'App',
	getInitialState : function () {
        	return { collection : new warriorCollection() };
	},
	componentDidMount : function () {
		list.forEach(function (value) {
			$.ajax({
				type : 'GET',
				url : 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22codewars.com%2Fusers%2F'+ value + '%22%20and%20xpath%3D%27%2F%2F*%5B%40id%3D%22shell_content%22%5D%2Fdiv%5B3%5D%2Fsection%27&format=json'
			}).done(function (data){
				this.state.collection.add({
					username : data.query.results.section.div.figure.img.title,
					name : data.query.results.section.div.figcaption.h1.content,
					clan : data.query.results.section.div.figcaption.div[2].content,
					skills : data.query.results.section.div.figcaption.div[3].content,
					honor : data.query.results.section.div.figcaption.div[4].content.split('#')[0],
					img : data.query.results.section.div.figure.img.src
				});
				this.state.collection.sort();
				this.forceUpdate();
			}.bind(this)).fail( function () {
				console.log('FATAL ERROR: request fail...');
			});
		}.bind(this));
	},
	render : function () {
		var ranking = this.state.collection.map(function (model,index) {
			return React.createElement(Warrior, {model: model, key: index });

		});
	    return (
	    	React.createElement("div", {className: "small-12 large-8 large-centered columns container"},
		      	React.createElement("div", {className: "box"},
		      		React.createElement("h1", {className: "title"}, "REVELEX CODEWARS RANKING"),
		      		React.createElement("div", {className: "row rank-list"},
		      			ranking
		      		)
		      	)
		    )
	    );
	}
});

$(document).ready(function () {

    React.render(
		React.createElement(App, null),
	   	document.getElementById('app')
	);

});


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

These release notes cover new developer and user-facing incompatibilities, features, and major improvements.

---

* [HADOOP-10371](https://issues.apache.org/jira/browse/HADOOP-10371) | *Minor* | **The eclipse-plugin cannot work  in my environment**

fixed

---

* [MAPREDUCE-3859](https://issues.apache.org/jira/browse/MAPREDUCE-3859) | *Major* | **CapacityScheduler incorrectly utilizes extra-resources of queue for high-memory jobs**

Fixed wrong CapacityScheduler resource allocation for high memory consumption jobs


text:
AWS Batch Backend Architecture
==============================

Overview
--------

The architecture of the code base follows very closely to the Google version.
Probably a little too closely, and lots of code was lifted from the Google
backend originally, then modified to work with AWS.

Fundamentally, Google Pipelines API (a.k.a. PAPI) works pretty differently from
AWS Batch. In Pipelines, all the infrastructure is completely managed by Google,
while AWS Batch exposes that infrastructure to a large degree so that customers
can fine tune it as necessary. An implementation that uses Fargate might be an
alternative that is closer or an implementation that uses Step Functions although
that would be a separate backend.

From a Cromwell perspective, this means that unlike Pipelines, where
infrastructure details are defined in the configuration or the WDL, in AWS
Batch, these configuration details are handled outside. All the AWS Batch
backend needs to know is "what is the ARN for the job Queue"?

A good example of the difference can be seen in the 'disks' configuration. In
Pipelines, you need to specify the type of disk and size. In AWS, this will
be defined instead when you setup your environment (more on that later), so
all the AWS backend really needs to know is what mount points you need
defined.

This infrastructure and all the associated configuration still exists; however,
it is moved out of the Cromwell configuration.

AWS Batch
---------

Because AWS Batch is so different from PAPI, those familiar only with PAPI
would be best off with an overview of AWS Batch. If you are familiar with
the workings of Batch, feel free to skip this section, and move on.

[AWS Batch](https://aws.amazon.com/batch/) fundamentally is a service to allow batch jobs to run easily and
efficiently. To use it effectively, however, you need to understand its own
technical stack. To create a job, you need a "Job Queue". That job queue allows
jobs to be scheduled onto one or more "Compute Environments". This can
be managed through AWS Batch, but when AWS Batch sets up a compute environment,
it's simply setting up an Elastic Container Service (ECS) Cluster. The ECS
cluster, in turn is just a few managed CloudFormation templates, that is
controlling an AutoScaling group of EC2 instances.

What really makes an ECS instance an ECS instance is the presence of a configured
[Amazon ECS agent](https://github.com/aws/amazon-ecs-agent). This agent polls
the ECS service to determine if there are any tasks to run. An AWS Batch Job
will be turned into an ECS task. From there, the agent will pick it up and
manage it, sending updates back to ECS (and from there AWS Batch) on a regular
basis.

There are some limits that will impact the design of the AWS Batch backend, and
will be discussed later. These are:

* [AWS Batch Limits](https://docs.aws.amazon.com/batch/latest/userguide/service_limits.html)
* [8k container overrides limit.](https://docs.aws.amazon.com/cli/latest/reference/ecs/run-task.html)

The ECS workers used by the AWS Batch backend can be any instance type and should
be based on an AMI running the ECS agent and docker. An ECS optimized AMI is recommended.
An EC2 LaunchTemplate is used to provide some additional "on first boot" configuration that:
1. Installs AWS CLI v2,
1. Installs a script to mount an EBS as a `btrfs` file system that will auto-expand,
1. Configures docker to use that file system so that the "filesystem" of the container
will auto-expand,
1. Installs a `fetch_and_run.sh` script that allows the container to download
generated shell scripts from S3 that contain the instructions of the workflow
task

```text
                  +-------------+
                  |             |
                  |  AWS Batch  |
                  |             |
                  +------+------+
                         |
                         |
                         |
                         |
                         |
        +----------------v------------------+
        |                                   |
        |  Elastic Container Service (ECS)  |
        |                                   |
        +----------------+------------------+
                         |
                         |
                         |
                         |
                         |
+------------------------v-------------------------+
|                                                  |
|  AutoScaling Group                               |
|                                                  |
| +---------------------------------+              |
| |                                 |              |
| |  EC2 Instance                   |              |
| |                                 |              |
| |  +--------------------+         |              |
| |  |                    |         |              |
| |  |  Docker Container  |         |              |
| |  |                    |         |              |
| |  +--------------------+  ...    |              |
| |                                 |              |
| +---------------------------------+     ...      |
|                                                  |
+--------------------------------------------------+

```

Cromwell AWS Batch Backend
--------------------------

There are several scala classes as part of the AWS Batch Backend, but
the primary classes involved in running the backend are shown below. The
arrows represent the flow of job submission.

```text
    +----------------------------------------+
    |                                        |
    |  AwsBatchBackendLifecycleActorFactory  |
    |                                        |
    +------------------+---------------------+
                       |
                       |
                       |
                       |
                       |
    +------------------v----------------------+
    |                                         |
    |  AwsBatchAsyncBackendJobExecutionActor  |
    |                                         |
    +------------------+----------------------+
                       |
                       |
                       |
                       |
                       |
               +-------v-------+                 +-------------------------+
               |               |                 |                         |
               |  AwsBatchJob  +----------------->  AwsBatchJobDefinition  |
               |               |                 |                         |
               +---------------+                 +-------------------------+
```

1. The `AwsBatchBackendLifecycleActorFactory` class is configured by the user
   as the Cromwell backend. This factory provides an object from the
   `AwsBatchAsyncBackendJobExecutionActor` class to create and manage the job.
2. The `AwsBatchAsyncBackendJobExecutionActor` creates and manages the job.
   The job itself is encapsulated by the functionality in `AwsBatchJob`.
3. `AwsBatchJob` is the primary interface to AWS Batch. It creates the
   necessary `AwsBatchJobDefinition`, then submits the job using the SubmitJob
   API.
4. `AwsBatchJobDefinition` is responsible for the creation of the job definition.
   In AWS Batch, every job must have a definition. Note that the job definition
   can be overridden by the `SubmitJob`, so the `JobDefinition` contains core information such
   as the docker image type while the `SubmitJob` contains details that are more related to
   the actual task.

AWS Batch Job Instantiation
---------------------------
```text
             +--------------------+
             |                    |
             |  Cromwell Backend  |
             |                    |
             +---------+----------+
                       |
                       |
                   SubmitJob
                       |
                       |
                +------v------+
                |             |
                |  AWS Batch  |
                |             |
                +------^------+
                       |
                       |
                     Polls
                       |
                       |
                +------+------+
                |             |
                |  ECS Agent  |
                |             |
                +------+------+
                       |
           Creates, Launches and Monitors
                       |
              +--------v---------+
              |                  |
              |  Task Container  |
              |                  |
              +------------------+

```

When a Cromwell task begins, the Cromwell backend will call the SubmitJob
API of AWS Batch. From there, the backend will call the AWS Batch `DescribeJobs`
API to provide status to the Cromwell engine as requested.

Once the job is Submitted in AWS Batch, one of the EC2 instances assigned
to the compute environment (a.k.a. ECS Cluster) with a running agent will
pick up the Cromwell Job/AWS Batch Job/ECS Task and run it. Importantly,
AWS Batch calls ECS' `RunTask` API when submitting the job. It uses the
task definition, and overrides both the command text and the environment
variables.

Input files are read into the container from S3 and output files are copied back to
S3. Three additional files are also written to the S3 bucket using the names of these
environment variables:

* AWS_CROMWELL_RC_FILE (the return code of the task)
* AWS_CROMWELL_STDOUT_FILE (STDOUT of the task)
* AWS_CROMWELL_STDERR_FILE (STDERR of the task)

These files are placed in the correct location in S3 after task execution. In addition
STDOUT and STDERR are fed to the tasks cloudwatch log.

Input and Command Compression
-----------------------------

NOTE: All limits in this section are subject to change

In testing, specifically with large fan-in operations such as the MergeVCFs
task of the Haplotype caller test, that the container overrides length limit
of 8k was being exceeded. There are several limits described on AWS Batch,
and a limit for container overrides on ECS, all of which should be considered.

* Maximum payload size for RegisterJobDefinition calls: 24KiB
* Maximum payload size for SubmitJob calls: 30KiB
* Maximum JSON payload for ECS RunTask containerOverrides values: 8KiB

Effective limits, however, are much, much smaller. While both AWS Batch and
ECS have command and environment as part of their Job/Task definitions
respectively, AWS Batch passes both command and environment through to ECS
based solely on RunTask. While a lot of effort was initially placed on
balancing payloads between RegisterJobDefinition and SubmitJob, because
everything is passed as an override to RunTask, we're gated by the ECS
RunTask 8KiB limit.

Dependencies
------------

Two dependencies were added to Cromwell as part of this project, though
existing Cromwell dependencies were also leveraged. These two are:

* AWS Java SDK v2
* elerch/S3 Filesystem

The Java SDK version two carries with it a significant amount of additional
dependencies. These had a significant effect on the ability of Cromwell to
compile, but ultimately the overlapping dependencies came down to:

* com.fasterxml.jackson.core (jackson-annotations):
    Jackson version was bumped to accomodate throughput
* org.slf4j (jcl-over-slf4j):
    Ignored by aws sdk in favor of the version bundled in Cromwell
* nettyHandler:
    Version bumped to accomodate AWS SDK
* sttpV:
    Version bumped to accomodate AWS SDK

While the AWS SDK v2 has nio capabilities, it does not include
a FileSystemProvider to allow Cromwell to operate seamlessly with AWS S3.
This was found later in the project, and as such, the filesystem provider
is not integrated with the Cromwell configuration system. The S3 FS was
forked from Udacity's provider, which was based on AWS SDK for Java version 1.
Of particular note is the fact that all API configuration for the provider
is performed through environment variables. As such, configuration is possible,
but currently disjoint from Cromwell proper.

Authentication
--------------

Authentication is required for both the Cromwell AWS Backend and the S3
Filesystem provider. By default, in both cases, the default credential provider
chain is followed. AWS tools all follow the same prioritized set of
checks for access key/secret key (and optionally token), with the exception
of #2 below.

[Default credential provider chain](https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html)
1. Configured permissions (environment)
2. (NOTE BELOW) Java properties
3. Access key/secret key as defined in $HOME/.aws/credentials and config
4. Container role
5. EC2 Instance role

NOTE: The Java properties check is specific and unique to the Java SDK. This
      does not apply to other SDKs or tools (e.g. the CLI).

Normally customers will be using an EC2 Instance role (recommended) or file configuration
as described in #3 (not recommended in production).

Permissions
-----------

Within AWS, everything must be authorized. This is a consistent rule, and as
such, AWS Services themselves are not immune to the rule. Therefore, customers
of AWS are responsible for granting services access to APIs within their account.
The flow described below represents the permissions needed by each stage, from
Cromwell server through the task running. This includes the permissions needed for
the AWS Services involved in the processing of the work.

```text
+----------------------------+
|                            |  s3:GetObject on bucket for workflow and script bucket
|                            |  s3:ListObjects on script bucket
|                            |  s3:PutObject on script bucket
|          Cromwell          |  batch:RegisterTaskDefinition
|                            |  batch:SubmitJob
|                            |  batch:DescribeJobs
|                            |  batch:DescribeJobDefinitions
+-------------+--------------+
              |
              |
              |
+-------------v--------------+
|                            |  AWSBatchServiceRole managed policy - described at:
|          AWS Batch         |
|                            |     https://docs.aws.amazon.com/batch/latest/userguide/service_IAM_role.html
+-------------+--------------+
              |
              |
              |
+-------------v--------------+
|                            |  AWSServiceRoleForECS Service-linked role, documented at:
|                            |
| Elastic Container Service  |     https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using-service-linked-roles.html
|                            |
|  (See discussion #1 below) |  AmazonEC2ContainerServiceAutoscaleRole managed policy - described at:
|                            |
|                            |     https://docs.aws.amazon.com/AmazonECS/latest/developerguide/autoscale_IAM_role.html
+-------------+--------------+
              |
              |
              |
+-------------v--------------+
|                            |
|                            |  AmazonEC2ContainerServiceforEC2Role managed policy, described at:
| ECS Agent (running on EC2) |     https://docs.aws.amazon.com/AmazonECS/latest/developerguide/instance_IAM_role.html (EC2)
|                            |    OR
|                            |  AmazonECSTaskExecutionRolePolicy managed policy, described at:
|                            |     https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_execution_IAM_role.html (Fargate)
+-------------+--------------+
              |
              |
              |
+-------------v--------------+
|                            |  Task Role permissions. These are user defined, but ecs-tasks.amazon.com must have sts:AssumeRole trust relationship defined. Documentation:
|       Task Container       |
|                            |     https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_IAM_role.html
|                            |  s3:GetObject, s3:PutObject, s3:ListObjects
+----------------------------+
```

1. ECS has several sets of permissions for various items. AWS Batch, however,
   does not take advantage of certain features of ECS, most importantly
   ECS Services are out of scope of AWS Batch. ECS services require things
   like load balancing registration and DNS updates. While there is
   documentation regarding roles related to ECS services, these are
   irrelevant to the Cromwell use case.
2. Other than access to the main Cromwell bucket, the task container itself
   does not need additional permissions unless
   the task in the WDL has been defined with a command that interfaces
   with AWS directly. This may include access to additional s3 buckets containing
   things like reference genome files.

   Task container permissions are currently supported through ECS and AWS
   Batch, but there is no configuration currently wired for the Cromwell
   AWS Backend to pass these settings to AWS. As such, the task container
   permissions must be managed by attaching a role to the EC2 Instance
   with permissions necessary for both the ECS Agent and the task container.

NOTE: ECS Agent permissions currently must use the permissions as outlined
      in the AmazonEC2ContainerServiceForEC2Role managed policy.

Future considerations
---------------------

AWS Batch Backend

* Should the 'disks' configuration be renamed to mount points or maybe
  ignored? This might make the wdl configuration more portable between backends
* The intent is to be able to override the queueArn between the
  default-runtime-attributes and the runtime attributes in the WDL. This
  appears broken at the moment.
* Job caching appears to be broken at the moment. Identical tasks need not be repeated
  if the results of a previous run of the task are still available.
* Retrying failed jobs is not currently attempted. Adding this would be beneficial
  especially in conjunction with result caching
* Some S3 FS stuff can be removed: It looks like there's a bunch of leftover
  unused code here from before having the nio implementation
  [here](https://github.com/broadinstitute/cromwell/tree/develop/filesystems/s3/src/main/scala/cromwell/filesystems/s3/batch)
  Also, I recommend adding another case for S3
  [here](https://github.com/broadinstitute/cromwell/blob/7a830a7fceaab9e7eaaa6802e58fe3cfd5d411a8/engine/src/main/scala/cromwell/engine/io/nio/NioFlow.scala#L95)
  otherwise files will be pulled down to be hashed instead of looking up the
  hash from S3 metadata. You might need to add the s3 Cromwell fs as a dependency
  to the engine to be able to do that.
* S3 Filesystem should be an official AWS thing (e.g. upplication or awslabs account)
* 8k container overrides limit should be bigger (ECS)
* We should understand why AWS Batch is putting everything in container overrides
* Authentication configuration consistency between S3FS and AWS Batch backend
* Full configuration of jobs in AWS Batch

Cromwell

* The style of integration with backends requires a lot of boilerplate code
  that I believe can be significantly reduced via heavier use of traits and
  supporting libraries
* There is a lot of data available within the backend if you know where
  to look, but if you don't, there is a lot of looking at inherited classes
  etc. to try to find them. Often, lack of code comments, etc and very similarly
  named variables can be confusing for folks confronting the code base for the
  first time. Workflow root vs call root is a great example. Adding additional
  comments and potentially context objects to encapsulate state would make
  the codebase more approachable.
* There is a significant amount of dependent libraries (with more added by
  the introduction of the S3 filesystem and the AWS SDK). Dependency management
  is challenging as a result. Adding significant new functionality is relatively
  painful when new dependencies are needed.


text:
package com.umeng.analytics;

public class ReportPolicy
{

    public static final int BATCH_AT_LAUNCH = 1;
    public static final int BATCH_BY_INTERVAL = 6;
    public static final int BATCH_BY_SIZE = 7;
    public static final int DAILY = 4;
    public static final int REALTIME = 0;
    public static final int WIFIONLY = 5;
    static final int a = 2;
    static final int b = 3;

    public ReportPolicy()
    {
    }
}


text:
.class Lcom/android/gallery3d/gadget/WidgetService$EmptySource;
.super Ljava/lang/Object;
.source "WidgetService.java"

# interfaces
.implements Lcom/android/gallery3d/gadget/WidgetSource;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/gallery3d/gadget/WidgetService;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "EmptySource"
.end annotation

# direct methods
.method private constructor <init>()V
    .locals 0

    .prologue
    .line 55
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method synthetic constructor <init>(Lcom/android/gallery3d/gadget/WidgetService$1;)V
    .locals 0
    .parameter "x0"

    .prologue
    .line 55
    invoke-direct {p0}, Lcom/android/gallery3d/gadget/WidgetService$EmptySource;-><init>()V

    return-void
.end method

# virtual methods
.method public close()V
    .locals 0

    .prologue
    .line 79
    return-void
.end method

.method public getContentUri(I)Landroid/net/Uri;
    .locals 1
    .parameter "index"

    .prologue
    .line 69
    new-instance v0, Ljava/lang/UnsupportedOperationException;

    invoke-direct {v0}, Ljava/lang/UnsupportedOperationException;-><init>()V

    throw v0
.end method

.method public getImage(I)Landroid/graphics/Bitmap;
    .locals 1
    .parameter "index"

    .prologue
    .line 64
    new-instance v0, Ljava/lang/UnsupportedOperationException;

    invoke-direct {v0}, Ljava/lang/UnsupportedOperationException;-><init>()V

    throw v0
.end method

.method public reload()V
    .locals 0

    .prologue
    .line 76
    return-void
.end method

.method public setContentListener(Lcom/android/gallery3d/data/ContentListener;)V
    .locals 0
    .parameter "listener"

    .prologue
    .line 73
    return-void
.end method

.method public size()I
    .locals 1

    .prologue
    .line 59
    const/4 v0, 0x0

    return v0
.end method


text:
<?php

namespace Drupal\Tests\toolbar\Functional;

use Drupal\Tests\BrowserTestBase;

/**
 * Tests the implementation of hook_toolbar() by a module.
 *
 * @group toolbar
 */
class ToolbarHookToolbarTest extends BrowserTestBase {

  /**
   * A user with permission to access the administrative toolbar.
   *
   * @var \Drupal\user\UserInterface
   */
  protected $adminUser;

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = ['toolbar', 'toolbar_test', 'test_page_test'];

  protected function setUp() {
    parent::setUp();

    // Create an administrative user and log it in.
    $this->adminUser = $this->drupalCreateUser(['access toolbar']);
    $this->drupalLogin($this->adminUser);
  }

  /**
   * Tests for a tab and tray provided by a module implementing hook_toolbar().
   */
  public function testHookToolbar() {
    $this->drupalGet('test-page');
    $this->assertResponse(200);

    // Assert that the toolbar is present in the HTML.
    $this->assertRaw('id="toolbar-administration"');

    // Assert that the tab registered by toolbar_test is present.
    $this->assertRaw('id="toolbar-tab-testing"');

    // Assert that the tab item descriptions are present.
    $this->assertRaw('title="Test tab"');

    // Assert that the tray registered by toolbar_test is present.
    $this->assertRaw('id="toolbar-tray-testing"');

    // Assert that tray item descriptions are present.
    $this->assertRaw('title="Test link 1 title"');
  }

}


text:
#ifndef NamedFlowCollection_h
#define NamedFlowCollection_h

#include "core/dom/DocumentLifecycleObserver.h"
#include "core/dom/NamedFlow.h"
#include "wtf/Forward.h"
#include "wtf/ListHashSet.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/Vector.h"

namespace WebCore {

class Document;
class DOMNamedFlowCollection;

class NamedFlowCollection : public RefCounted<NamedFlowCollection>, public DocumentLifecycleObserver {
public:
    static PassRefPtr<NamedFlowCollection> create(Document* doc) { return adoptRef(new NamedFlowCollection(doc)); }

    Vector<RefPtr<NamedFlow> > namedFlows();
    NamedFlow* flowByName(const String&);
    PassRefPtr<NamedFlow> ensureFlowWithName(const String&);

    void discardNamedFlow(NamedFlow*);

    Document* document() const;

    virtual ~NamedFlowCollection() { }

    PassRefPtr<DOMNamedFlowCollection> createCSSOMSnapshot();

private:
    struct NamedFlowHashFunctions;
    struct NamedFlowHashTranslator;

    typedef ListHashSet<NamedFlow*, 1, NamedFlowHashFunctions> NamedFlowSet;

    explicit NamedFlowCollection(Document*);

    NamedFlowSet m_namedFlows;
};

} // namespace WebCore

#endif // NamedFlowCollection_h


text:
const RepresentationList = require('./representationList');

class LinkeduserList extends RepresentationList {
  constructor(client, parent) {
    super(client, parent);
    this.type = 'linkeduserList';
    this.itemType = 'linkeduser';
  }
}

module.exports = LinkeduserList;


text:
package net.kbrz.pokedroid.models.pokemon;

import com.google.gson.annotations.SerializedName;

import net.kbrz.pokedroid.models.PokeDroidModel;
import net.kbrz.pokedroid.models.commons.Effect;
import net.kbrz.pokedroid.models.commons.NamedApiResource;

import java.util.List;

/**
 * @author Konrad Brzykcy.
 */

@SuppressWarnings("unused")
public class AbilityEffectChange extends PokeDroidModel {

    @SerializedName("effect_entries")
    private List<Effect> effectEntries;
    @SerializedName("version_group")
    private NamedApiResource versionGroup;

    public List<Effect> getEffectEntries() {
        return effectEntries;
    }

    public void setEffectEntries(List<Effect> effectEntries) {
        this.effectEntries = effectEntries;
    }

    public NamedApiResource getVersionGroup() {
        return versionGroup;
    }

    public void setVersionGroup(NamedApiResource versionGroup) {
        this.versionGroup = versionGroup;
    }
}


text:
HeroTracker implements the turn sequence of the Hero Games system.  The Hero Games system utilizes a segment chart with 12 phases.  A character's speed determines how many and on which phases he/she gets to act.  HeroTracker will add a token to the Roll20 tracker multiple times to simulate this mechanic.

### Syntax

```!herotracker <parms>```

```!ht <parms>```

### Parameters:

* **--help**
* **--add**
* **--remove**
* **--id** <_token_id_>
* **--tag** <_label_>
* **--speed** <_number_>
* **--dex** <_number_>
* **--segment** <_number_>
* **--speed_field** <_name_>
* **--dex_field** <_name_>
* **--back**

---
To add tokens to the initiative tracker, select one or more tokens and then enter the chat command.

```!ht --add```

---
To remove entries, select one or more tokens and enter the chat command:

```!ht --remove```

---
Alternately, you can specify a single token by its ID rather than selecting it. For example, to add a specific token, selected or not, enter this chat command:

```!ht --add --id -L9sBx-soK0CQzQYCiFA --speed 5```

---
You can also add a static label to the tracker by entering this chat command:

```!ht --tag GAS-EFFECT --speed 4```

---
When adding a token, the speed and dex will be automatically derived from the token's attributes. However, you can override this by specifying your own speed and dex:

```!ht --add --speed 6 --dex 18```

---
You can add a token or label to just one segment by using this chat command:

```!ht --add --tag POST --segment 13```

---
Because the tracker can end up with a great many entries, it would normally create a cumbersome problem to cycle through the entire list should you accidentally move past a turn that isn't complete. As such, HeroTracker includes an option to rollback the tracker one turn:

```!ht --back```

---
Hero System begins a turn at segment 12. You can sort the tracker, with segment 12 at the top of the order, by using this command:

```!ht --start```

---
HeroTracker uses dex to break ties by appending a decimal value to the token's speed. The value is just the dex subtracted from 100. If you do not want to use this feature, you can specify a dex of zero using this command:

```!ht --add --dex 0```

---
By default, HeroTracker uses the character sheet fields **SPD** and **DEX** to derive the speed and dex values. You can override and choose your own field names using the parameters **--speed_field** and **--dex_field**. This can also be used for characters that use a different attribute to break ties, such as ego based characters. The command would look like this:

```!ht --add --dex_field EGO```

---
### Notes

The speed and dex of a selected token will be derived from the token's attributes **SPD** and **DEX** respectively.

If you specify a single token using the **--id** parameter, or create a custom label using the **--tag** parameter, you must also provide a speed or segment, and optionally a dex.

Entries are added (collated) into the existing initiative order without resorting.  So if you were just starting segment 5 and a new character enters the combat, you can add the new character normally and the turn order will still be at the start of segment 5.  This also makes it easy to change a token's speed or dex in the middle of a turn if needed.  So, for example, if a character was effected by a Drain SPD attack that reduced his SPD to 2, you would select the character's token and enter the following command:

```!ht --add --speed 2```

The following macro can be used to initiate combat with all selected tokens, beginning with segment 12:

```
!ht --add --tag SEGMENT --speed 12
!ht --add --tag POST_RECOVERY --segment 13
!ht --add --start
```


text:
import CardView from './card.view.js';

//material ui
  //theme provider
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

class CardController extends React.Component {
    constructor(...args) {
        super(...args);

        this.state = {
            data: this.props.data
        };
    }

    render() {
        return <MuiThemeProvider>
            <CardView
                data={this.state.data}
            />
        </MuiThemeProvider>;
    }
}

export default CardController;


text:
"""
Script for importing labels from wikidata into the sqlite synonym table so
they can be resolved by the resolved keyword annotator.
Currently only animal diseases and hand selected human diseases are imported.
"""
from __future__ import absolute_import
from __future__ import print_function
from ..get_database_connection import get_database_connection
import six
from six.moves.urllib.request import urlopen
from six.moves.urllib.parse import urlencode
from six.moves.urllib.error import URLError
import json
import datetime
from ..utils import normalize_disease_name

def import_wikidata(drop_previous=False):
    connection = get_database_connection(create_database=True)
    cur = connection.cursor()
    if drop_previous:
        print("Dropping previous data...")
        cur.execute("""
        DELETE FROM synonyms WHERE entity_id IN (
            SELECT id FROM entities WHERE source = 'Wikidata'
        )""")
        cur.execute("DELETE FROM entities WHERE source = 'Wikidata'")
        cur.execute("DELETE FROM metadata WHERE property = 'wikidata_retrieval_date'")
    wikidata_retrieval_date = next(cur.execute("""
    SELECT value FROM metadata WHERE property = 'wikidata_retrieval_date'
    """), None)
    if wikidata_retrieval_date:
        print("Wikidata data has already been imported. Run this again with --drop-previous to re-import it.")
        return
    cur.execute("INSERT INTO metadata VALUES ('wikidata_retrieval_date', ?)",
                (datetime.date.today().isoformat(),))
    try:
        response = urlopen("https://query.wikidata.org/sparql", str.encode(urlencode({
            "format": "json",
            "query": """
            SELECT ?item ?itemLabel WHERE {
              ?item wdt:P31 wd:Q9190427.
              SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
            }
            """
        })))
    except URLError:
        print("If you are operating behind a firewall, try setting the HTTP_PROXY/HTTPS_PROXY environment variables.")
        raise
    results = json.loads(six.text_type(response.read(), 'utf-8'))['results']['bindings']
    print("Importing %s wikidata entities..." % len(results))
    cur.executemany("INSERT INTO entities VALUES (?, ?, 'disease', 'Wikidata')", [
        (result['item']['value'], result['itemLabel']['value'])
        for result in results])
    cur.executemany("INSERT INTO synonyms VALUES (?, ?, 1)", [
        (normalize_disease_name(result['itemLabel']['value']), result['item']['value'])
        for result in results])
    print("Importing manually added diseases not in disease ontology...")
    # Wikidata entities are used in place of those from the disease ontology.
    additional_diseases = [
        ('https://www.wikidata.org/wiki/Q16654806', 'Middle East respiratory syndrome',),
        ('https://www.wikidata.org/wiki/Q6946', 'Cytomegalovirus'),
        ('https://www.wikidata.org/wiki/Q1142751', 'Norovirus',),
        ('https://www.wikidata.org/wiki/Q15928531', 'Nipah virus',),
        ('https://www.wikidata.org/wiki/Q18350119', 'Acute flaccid myelitis',),
        ('https://www.wikidata.org/wiki/Q6163830', 'Seoul virus',),
        ('https://www.wikidata.org/wiki/Q101896', 'Gonorrhoea'),
        ('https://www.wikidata.org/wiki/Q62658688', 'Rotavirus Disease'),
        ('https://www.wikidata.org/wiki/Q2600216', 'Yersiniosis'),
        ('https://www.wikidata.org/wiki/Q19000403', 'Enterovirus infectious disease'),
        ('https://www.wikidata.org/wiki/Q837054', 'Adenovirus infection'),
    ]
    cur.executemany("INSERT INTO entities VALUES (?, ?, 'disease', 'Wikidata')", additional_diseases)
    cur.executemany("INSERT INTO synonyms VALUES (?, ?, 3)", [
        (normalize_disease_name(disease_name), uri,) for uri, disease_name in additional_diseases])
    MERS_synonyms = ['MERS', 'Middle East respiratory syndrome coronavirus', 'MERS-CoV', 'MERS Coronavirus']
    cur.executemany("INSERT INTO synonyms VALUES (?, ?, ?)", [
        (normalize_disease_name(synonym), 'https://www.wikidata.org/wiki/Q16654806', 3)
        for synonym in MERS_synonyms
    ])
    connection.commit()
    connection.close()

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--drop-previous", dest='drop_previous', action='store_true')
    parser.set_defaults(drop_previous=False)
    args = parser.parse_args()
    import_wikidata(args.drop_previous)


text:
package ensemble

import (
	"github.com/sjwhitworth/golearn/base"
	"github.com/sjwhitworth/golearn/evaluation"
	. "github.com/smartystreets/goconvey/convey"
	"io/ioutil"
	"testing"
)

func TestMultiSVMUnweighted(t *testing.T) {
	Convey("Loading data...", t, func() {
		inst, err := base.ParseCSVToInstances("../examples/datasets/articles.csv", false)
		So(err, ShouldBeNil)
		X, Y := base.InstancesTrainTestSplit(inst, 0.4)

		m := NewMultiLinearSVC("l1", "l2", true, 1.0, 1e-4, nil)
		m.Fit(X)

		Convey("Predictions should work...", func() {
			predictions, err := m.Predict(Y)
			cf, err := evaluation.GetConfusionMatrix(Y, predictions)
			So(err, ShouldEqual, nil)
			So(evaluation.GetAccuracy(cf), ShouldBeGreaterThan, 0.70)
		})

		Convey("Saving should work...", func() {
			f, err := ioutil.TempFile("", "tree")
			So(err, ShouldBeNil)
			err = m.Save(f.Name())
			So(err, ShouldBeNil)

			Convey("Loading should work...", func() {
				mLoaded := NewMultiLinearSVC("l1", "l2", true, 1.00, 1e-8, nil)
				err := mLoaded.Load(f.Name())
				So(err, ShouldBeNil)

				Convey("Predictions should be the same...", func() {
					originalPredictions, err := m.Predict(Y)
					So(err, ShouldBeNil)
					newPredictions, err := mLoaded.Predict(Y)
					So(err, ShouldBeNil)
					So(base.InstancesAreEqual(originalPredictions, newPredictions), ShouldBeTrue)
				})

			})

		})

	})
}

func TestMultiSVMWeighted(t *testing.T) {
	Convey("Loading data...", t, func() {
		weights := make(map[string]float64)
		weights["Finance"] = 0.1739
		weights["Tech"] = 0.0750
		weights["Politics"] = 0.4928

		inst, err := base.ParseCSVToInstances("../examples/datasets/articles.csv", false)
		So(err, ShouldBeNil)
		X, Y := base.InstancesTrainTestSplit(inst, 0.4)

		m := NewMultiLinearSVC("l1", "l2", true, 0.62, 1e-4, weights)
		m.Fit(X)

		Convey("Predictions should work...", func() {
			predictions, err := m.Predict(Y)
			cf, err := evaluation.GetConfusionMatrix(Y, predictions)
			So(err, ShouldEqual, nil)
			So(evaluation.GetAccuracy(cf), ShouldBeGreaterThan, 0.60)

			Convey("Saving should work...", func() {
				f, err := ioutil.TempFile("", "tree")
				So(err, ShouldBeNil)
				err = m.Save(f.Name())
				So(err, ShouldBeNil)

				Convey("Loading should work...", func() {
					mLoaded := NewMultiLinearSVC("l1", "l2", true, 1.00, 1e-8, weights)
					err := mLoaded.Load(f.Name())
					So(err, ShouldBeNil)

					Convey("Predictions should be the same...", func() {
						originalPredictions, err := m.Predict(Y)
						So(err, ShouldBeNil)
						newPredictions, err := mLoaded.Predict(Y)
						So(err, ShouldBeNil)
						So(base.InstancesAreEqual(originalPredictions, newPredictions), ShouldBeTrue)
					})

				})
			})

		})
	})
}

func TestMultiSVMSaved(t *testing.T) {
	Convey("Loading data...", t, func() {

	})
}


text:
using System;
using System.Diagnostics.CodeAnalysis;

namespace WindowsFormsAero.InteropServices
{
    [Serializable]
    internal enum MarginType : int
    {
        Sizing = 3601,
        Content = 3602,
        Caption = 3603
    }

    [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")]
    internal enum MenuPart : int
    {
        MENU_MENUITEM_TMSCHEMA = 1,
        MENU_MENUDROPDOWN_TMSCHEMA = 2,
        MENU_MENUBARITEM_TMSCHEMA = 3,
        MENU_MENUBARDROPDOWN_TMSCHEMA = 4,
        MENU_CHEVRON_TMSCHEMA = 5,
        MENU_SEPARATOR_TMSCHEMA = 6,
        BarBackground = 7,
        BarItem = 8,
        PopupBackground = 9,
        PopupBorders = 10,
        PopupCheck = 11,
        PopupCheckBackground = 12,
        PopupGutter = 13,
        PopupItem = 14,
        PopupSeparator = 15,
        PopupSubmenu = 16,
        MENU_SYSTEMCLOSE = 17,
        MENU_SYSTEMMAXIMIZE = 18,
        MENU_SYSTEMMINIMIZE = 19,
        MENU_SYSTEMRESTORE = 20
    }

    internal static class MenuBarState
    {
        internal const int Active = 1;
        internal const int Inactive = 2;
    }

    internal static class MenuBarItemStates
    {
        internal const int Normal = 1;
        internal const int Hot = 2;
        internal const int Pushed = 3;
        internal const int Disabled = 4;
        internal const int DisabledHot = 5;
        internal const int DisabledPushed = 6;
    }

    internal static class MenuPopupItemStates
    {
        internal const int Normal = 1;
        internal const int Hot = 2;
        internal const int Disabled = 3;
        internal const int DisabledHot = 4;
    }

    internal static class MenuPopupCheckState
    {
        internal const int CheckmarkNormal = 1;
        internal const int CheckmarkDisabled = 2;
        internal const int BulletNormal = 3;
        internal const int BulletDisabled = 4;
    }

    internal static class MenuPopupCheckBackgroundState
    {
        internal const int Disabled = 1;
        internal const int Normal = 2;
        internal const int Bitmap = 3;
    }

    internal static class MenuPopupSubmenuState
    {
        internal const int Normal = 1;
        internal const int Disabled = 2;
    }

}


text:
#ifndef WEEX_PROJECT_JNI_TYPE_H
#define WEEX_PROJECT_JNI_TYPE_H

#include <jni.h>
#include "base/android/jni/scoped_java_ref.h"

namespace base {
namespace android {
class JNIType {
 public:
  static jdouble DoubleValue(JNIEnv* env, jobject value);
  static ScopedLocalJavaRef<jfloatArray> NewFloatArray(JNIEnv* env, int length,
                                                       float* array = nullptr);

  static bool RegisterJNIUtils(JNIEnv* env);
};
}  // namespace android
}  // namespace base

#endif  // WEEX_PROJECT_JNI_TYPE_H


text:
module Api::JobsControllerHelper
end


text:
package nl.gogognome.textsearch.string;

import java.util.function.*;
import nl.gogognome.textsearch.criteria.*;

/**
 *
This class checks whether a {@link Criterion} matches a specified String.

 *
 *
Typical usage:

 *
 *

 *   Criterion criterion = new Parser().parse("foo AND bar");
 *   CriterionMatcher matcher = new StringSearchFactory().caseInsensitiveCriterionMatcher(searchCriterion);
 *   boolean matches = matcher.matches("Barefoot is a movie directed by Andrew Flemming.");
 *   // matches == true
 *

 *
 *
A special use case is that the {@link Criterion} must be matched against a number of attributes of an object.
 * For example, you want to match the {@link Criterion} against the first name, last name, street and city of
 * relations.
 * This could be implemented by joining these attributes' values to a single string, separated by a character
 * that does not occur in the `Criterion`, and then matching
 * the {@link Criterion} against this resulting string. This approach however would require a lot of string copying
 * which is time consuming and produces a lot of garbage on the heap. To overcome this problem
 * the method {@link CriterionMatcher#matches(String...)} has a varargs string parameter.
 * The strings passed to the method are treated as if they were all joined together to a single string, separated
 * by a character that does not occur in the {@link Criterion}.
 *

 *
 *

 *   Criterion criterion = new Parser().parse("foo AND bar");
 *   CriterionMatcher matcher = new StringSearchFactory().caseInsensitiveCriterionMatcher(criterion);
 *   boolean matches1 = matcher.matches("Bart", "food");
 *   // matches1 == true
 *   boolean matches2 = matcher.matches("ba", "rt food");
 *   // matches2 == false because "bar" is not found
 *

 *
 */
public class CriterionMatcher {

    private final MatchingCriterion matchingCriterion;

    private CriterionMatcher(Criterion criterion, Function<String, Predicate<String>> buildStringMatcher) {
        matchingCriterion = new MatchingCriterionBuilder(buildStringMatcher).getMatchingCriterionFor(criterion);
        if (matchingCriterion == null) {
            throw new IllegalArgumentException("The criterion could not be converted to a CriterionMatcher");
        }
    }

    public boolean matches(String text) {
        return matchingCriterion.matches(text);
    }

    public boolean matches(String... texts) {
        return matchingCriterion.matchesAny(texts);
    }

    private static class MatchingCriterionBuilder implements CriterionVisitor {

        private final Function<String, Predicate<String>> buildStringMatcher;
        private MatchingCriterion matchingCriterion;

        private MatchingCriterionBuilder(Function<String, Predicate<String>> buildStringMatcher) {
            this.buildStringMatcher = buildStringMatcher;
        }

        private MatchingCriterion getMatchingCriterion() {
            return matchingCriterion;
        }

        @Override
        public void visit(And and) {
            this.matchingCriterion = new MatchingAnd(
                    getMatchingCriterionFor(and.getLeft()),
                    getMatchingCriterionFor(and.getRight()));
        }

        @Override
        public void visit(Or or) {
            matchingCriterion = new MatchingOr(
                    getMatchingCriterionFor(or.getLeft()),
                    getMatchingCriterionFor(or.getRight()));
        }

        @Override
        public void visit(Not not) {
            matchingCriterion = new MatchingNot(
                    getMatchingCriterionFor(not.getCriterion()));
        }

        @Override
        public void visit(StringLiteral stringLiteral) {
            matchingCriterion = new MatchingStringLiteral(buildStringMatcher.apply(stringLiteral.getLiteral()));
        }

        private MatchingCriterion getMatchingCriterionFor(Criterion criterion) {
            criterion.accept(this);
            return getMatchingCriterion();
        }
    }

    private interface MatchingCriterion {
        boolean matches(String text);
        boolean matchesAny(String... texts);
    }

    private static class MatchingStringLiteral implements MatchingCriterion {

        private final Predicate<String> stringMatcher;

        private MatchingStringLiteral(Predicate<String> stringMatcher) {
            this.stringMatcher = stringMatcher;
        }

        @Override
        public boolean matches(String text) {
            return stringMatcher.test(text);
        }

        @Override
        public boolean matchesAny(String... texts) {
            for (String text : texts) {
                if (matches(text)) {
                    return true;
                }
            }
            return false;
        }
    }

    private static class MatchingAnd implements MatchingCriterion {

        private final MatchingCriterion left;
        private final MatchingCriterion right;

        private MatchingAnd(MatchingCriterion left, MatchingCriterion right) {
            this.left = left;
            this.right = right;
        }

        @Override
        public boolean matches(String text) {
            return left.matches(text) && right.matches(text);
        }

        @Override
        public boolean matchesAny(String... texts) {
            return left.matchesAny(texts) && right.matchesAny(texts);
        }
    }

    private static class MatchingOr implements MatchingCriterion {

        private final MatchingCriterion left;
        private final MatchingCriterion right;

        private MatchingOr(MatchingCriterion left, MatchingCriterion right) {
            this.left = left;
            this.right = right;
        }

        @Override
        public boolean matches(String text) {
            return left.matches(text) || right.matches(text);
        }

        @Override
        public boolean matchesAny(String... texts) {
            return left.matchesAny(texts) || right.matchesAny(texts);
        }
    }

    private static class MatchingNot implements MatchingCriterion {

        private final MatchingCriterion matchingCriterion;

        private MatchingNot(MatchingCriterion matchingCriterion) {
            this.matchingCriterion = matchingCriterion;
        }

        @Override
        public boolean matches(String text) {
            return !matchingCriterion.matches(text);
        }

        @Override
        public boolean matchesAny(String... texts) {
            return !matchingCriterion.matchesAny(texts);
        }
    }

    public static class Builder {

        private Function<String, Predicate<String>> buildStringMatcher;

        Builder(Function<String, Predicate<String>> buildStringMatcher) {
            this.buildStringMatcher = buildStringMatcher;
        }

        public CriterionMatcher build(Criterion criterion) {
            return new CriterionMatcher(criterion, buildStringMatcher);
        }
    }

}


text:
package com.netflix.spinnaker.orca.api.pipeline.models;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

/**
 * Execution Status enumerations used for executions and stages.
 *
 * <p>Note: we implement CharSequence to allow simple SpEL expressions such as: {#stage('s1').status
 * == 'SUCCEEDED'}
 */
public enum ExecutionStatus implements CharSequence {
  /** The task has yet to start. */
  NOT_STARTED(false, false),

  /** The task is still running and the {@code Task} may be re-executed in order to continue. */
  RUNNING(false, false),

  /** The task is still running and the {@code Task} may be resumed in order to continue. */
  PAUSED(false, false),

  /** The task is complete but the pipeline should now be stopped pending a trigger of some kind. */
  SUSPENDED(false, false),

  /** The task executed successfully and the pipeline may now proceed to the next task. */
  SUCCEEDED(true, false),

  /** The task execution failed, but the pipeline may proceed to the next task. */
  FAILED_CONTINUE(true, false),

  /** The task failed and the failure was terminal. The pipeline will not progress any further. */
  TERMINAL(true, true),

  /** The task was canceled. The pipeline will not progress any further. */
  CANCELED(true, true),

  /**
   * The step completed but is indicating that a decision path should be followed, not the default
   * path.
   */
  REDIRECT(false, false),

  /** The task was stopped. The pipeline will not progress any further. */
  STOPPED(true, true),

  /** The task was skipped and the pipeline will proceed to the next task. */
  SKIPPED(true, false),

  /** The task is not started and must be transitioned to NOT_STARTED. */
  BUFFERED(false, false);

  /** Indicates that the task/stage/pipeline has finished its work (successfully or not). */
  public final boolean isComplete() {
    return complete;
  }

  public final boolean isSkipped() {
    return SKIPPED.equals(this);
  }

  /** Indicates an abnormal completion so nothing downstream should run afterward. */
  public final boolean isHalt() {
    return halt;
  }

  public static final Collection<ExecutionStatus> COMPLETED =
      Collections.unmodifiableList(
          Arrays.asList(CANCELED, SUCCEEDED, STOPPED, SKIPPED, TERMINAL, FAILED_CONTINUE));

  private static final Collection<ExecutionStatus> SUCCESSFUL =
      Collections.unmodifiableList(Arrays.asList(SUCCEEDED, STOPPED, SKIPPED));
  private static final Collection<ExecutionStatus> FAILURE =
      Collections.unmodifiableList(Arrays.asList(TERMINAL, STOPPED, FAILED_CONTINUE));
  private final boolean complete;
  private final boolean halt;

  ExecutionStatus(boolean complete, boolean halt) {
    this.complete = complete;
    this.halt = halt;
  }

  public boolean isSuccessful() {
    return SUCCESSFUL.contains(this);
  }

  public boolean isFailure() {
    return FAILURE.contains(this);
  }

  @Override
  public int length() {
    return toString().length();
  }

  @Override
  public char charAt(int index) {
    return toString().charAt(index);
  }

  @Override
  public CharSequence subSequence(int start, int end) {
    return toString().subSequence(start, end);
  }
}