text:
{% extends "templates/layout.html" %}

{% block page_title %}
  Venlafaxine - NHS Medicines alpha
{% endblock %}

{% block content %}

Venlafaxine

Venlafaxine contents

          Toggle navigation

Key facts

How and when to take

Side effects

Who can take it

Common questions

Taking with other medicines

More

Pregnancy advice

More about

Venlafaxine is a type of antidepressant that is often used to treat depression. It is also sometimes used to treat anxiety and panic attacks.

Venlafaxine helps many people recover from depression, and has fewer unwanted effects than older antidepressants.

It comes as tablets and capsules which are available only on prescription.

Venlafaxine is not suitable for children.

Venlafaxine has lots of different brand names including Efexor XL.

Key facts

It usually takes four to six weeks for venlafaxine to work.

Side effects such as feeling sick, headache, sweating, and dry mouth are common. They are usually mild and go away after a couple of weeks.

Venlafaxine can affect an unborn baby. Tell your doctor straight away if you're trying to get pregnant or become pregnant while taking it.

Venlafaxine can cause withdrawal symptoms so don't stop taking it without talking to your doctor.

You can drink alcohol while taking venlafaxine but it may make you feel sleepy.

        Info:

Check the leaflet inside your medicine packet for specific information about the brand that you are taking.

How and when to take

Take venlafaxine once or twice a day as recommended by your doctor.

The usual dose of venlafaxine is a total of 75mg a day.

It's best to take venlafaxine with food so it doesn't make you feel sick.

          More information

Venlafaxine tablets and capsules can be either immediate release or extended release. How you take them depends on the type you've been prescribed.

Immediate release tablets release the venlafaxine into your system as soon as you swallow them. Take them twice a day, once in the morning and once in the evening.

The usual dose of immediate release tablets is 37.5mg twice a day.

Extended release tablets and capsules are released into your system gradually so you only need to take them once a day. You can choose to take them at any time as long as you stick to the same time every day. If you have trouble sleeping, it's best to take it in the morning. Venlafaxine capsules are all extended release.

The usual dose of extended release tablets and capsules is 75mg once a day.

Will my dose go up or down?

The usual starting dose of venlafaxine is 75mg a day. This might be gradually increased to a maximum dose of 375mg once a day.

If you have problems with your liver or kidneys your doctor might prescribe a lower dose of venlafaxine for you.

What if I forget to take it?

If you forget to take a dose, don't worry. Take your next dose at the usual time. Never take two doses at the same time to make up for a forgotten one.

What if I take too much?

Ask your doctor for advice straight away as overdose can lead to potentially serious symptoms such as:

feeling sleepy

vomiting

a racing heart

seizures

Side effects

Not everyone will get side effects with venlafaxine, but common ones include feeling sick, headaches, sweating, and dry mouth.

          More information

Common side effects

Like all medicines, venlafaxine can cause side effects in some people, but many people have no side effects or only minor ones.

These very common side effects affect more than one in 10 people. Keep taking the medicine, but tell your doctor if they bother you or don't go away:

feeling sick

headache

sweating

dry mouth

trouble sleeping

dizziness

feeling sleepy

constipation

Serious side effects

It happens rarely (in fewer than one in 1,000 people), but some people may have serious side effects when taking venlafaxine.

Tell a doctor straight away if you develop:

low sodium levels - warning signs include headache, trouble focusing, memory problems, not thinking clearly, weakness, seizures, or losing your balance

thoughts about harming yourself or ending your life

chest pain or pressure, shortness of breath, or a fast or irregular heart beat

severe dizziness or passing out

feelings of euphoria, excessive enthusiasm or excitement, or a feeling of restlessness that means you can't sit or stand still

unexplained muscle pain or weakness

unexplained itchiness, or yellow skin or eyes

any changes in your eyesight, like blurred vision or dilated pupils

putting on or losing weight without trying to

changes in your periods such as heavy bleeding, spotting, or bleeding between periods

Or, if you get any signs of abnormal bleeding including:

bleeding from the gut: warning signs include vomiting blood or dark vomit; coughing up blood; blood in your urine; black or red poo

bleeding from the gums or bruises that appear without a reason or that get bigger

any bleeding that is very bad or that you cannot stop

Serious allergic reaction

It's rare to have an allergic reaction to venlafaxine but if this happens to you, stop taking the medicine and contact a doctor straight away.

The warning signs of a serious allergic reaction are:

getting a skin rash that may include itchy, red, swollen, blistered or peeling skin

wheezing

tightness in the chest or throat

having trouble breathing or talking

swelling of the mouth, face, lips, tongue or throat

            Info:

These are not all the side effects of venlafaxine. For a full list see the leaflet inside your medicine packet.

Coping with side effects

Some of the common side effects of venlafaxine will gradually improve as your body gets used to it.

What to do about feeling sick

Try taking venlafaxine with or after food to see if that eases feelings of sickness. It may also help if you avoid rich or spicy food while you're taking this medicine.

What to do about feeling sleepy

Cut down the amount of alcohol you drink.

What to do if you're unable to sleep

Take venlafaxine first thing in the morning.

What to do if you have a dry mouth

Chew sugar-free gum or sugar-free sweets.

You can lessen the chance of having a side effect if you take venlafaxine in the evening so that you're asleep when the level of medicine in your body is highest.

            Info:

If you have a side effect from any medicine, including venlafaxine, you can report it using the Yellow Card Scheme.

Who can take venlafaxine

Check with your doctor before starting to take venlafaxine if you:

have an allergy to venlafaxine or any of its ingredients

have a heart problem as venlafaxine can speed up or change your heartbeat

have ever taken any other medicines for depression. Some rarely used antidepressants can interact with venlafaxine to cause very high blood pressure even when they have been stopped for a few weeks

are trying to become pregnant, are already pregnant or breastfeeding. Venlafaxine is not recommended in pregnancy or while breastfeeding

have an eye condition called glaucoma because venlafaxine can increase the pressure in your eye.

If you have diabetes, venlafaxine can make it more difficult to keep your blood sugar stable. Monitor your blood sugar more often for the first few weeks of treatment with venlafaxine and adjust your diabetes treatment if necessary.

Common questions

What will happen when I come off it?

Don't stop taking venlafaxine unless your doctor tells you to.

If you stop taking venlafaxine suddenly you may get unpleasant withdrawal symptoms. These include:

dizziness

feeling sick

numbness or tingling in the hands or feet

trouble sleeping

feeling agitated or anxious

headaches

shaking

Withdrawal symptoms are usually harmless and over within a few days but it's possible to prevent them by reducing the dose gradually when you stop taking this medicine.

Can I drink alcohol?

You can drink alcohol while taking venlafaxine but it may make you feel sleepy. It might be best to stop drinking alcohol during the first few days of treatment until you see how this medicine affects you.

Will I gain or lose weight?

Venlafaxine can make you feel less hungry than usual, so you may lose weight when you start taking it. Some people might find they gain weight.

If you start to have problems with your weight while taking venlafaxine, talk to your doctor or pharmacist.

Will it affect my sex life?

The good effects of venlafaxine may, after a while, enhance your sex life as your mood lifts and you become interested in life and relationships again.

Some of the possible negative effects include:

men might have problems with getting an erection, or with ejaculating

women might have some vaginal bleeding

both men and women might find they don't reach orgasm the same way as before

you may have a lower sex drive

Any mild sexual side effects might pass after the first couple of weeks. If they don't, and this a problem for you, go back to your doctor to see if there's an alternative antidepressant for you to try.

Will street drugs affect it?

It can be potentially dangerous (even fatal) to take venlafaxine with:

stimulants like MDMA (ecstasy) or cocaine

hallucinogens like LSD

some legal highs like mephedrone

The sleep-inducing effects of cannabis can add to those of venlafaxine, especially in people who have just started taking it.

Methadone can increase the risk of side effects in people taking venlafaxine.

Venlafaxine has not been properly tested with street drugs. Talk to your doctor if you think you might use any street drugs while taking venlafaxine.

Can I drive or ride a bike while I'm taking it?

Most people drive as normal while taking venlafaxine. Taking venlafaxine may, though, reduce your concentration. It might be best to stop driving and cycling for the first few days of treatment until you know how this medicine affects you.

Will it affect my contraception?

For women, venlafaxine will not affect contraceptive pills or the morning after pill.

Taking venlafaxine with other medicines

Some medicines and venlafaxine can interfere with each other and increase the chances of you having side effects.

Tell your doctor or pharmacist if you're taking any other medicines, including herbal remedies and supplements, before starting venlafaxine.

          More information

Tell your doctor if you're taking these medicines before you start venlaxafine:

any medicines that affect your heartbeat - as venlafaxine can speed up or change your heartbeat

any other medicines for depression. Some rarely used antidepressants can interact with venlafaxine to cause very high blood pressure even when they have been stopped for a few weeks

Mixing venlafaxine with complementary remedies

Don't take the herbal remedy for depression, St John's wort, at the same time as venlafaxine as this will increase your risk of side effects.

Pregnancy and breastfeeding

No antidepressants are considered completely safe to take in pregnancy or while breastfeeding, but your doctor will want to prescribe venlafaxine when the benefits to you outweigh the risks.

          More information

Taking venlafaxine in pregnancy

Venlafaxine and similar antidepressants have been linked with a small risk of problems for the unborn baby when they're taken in early or late pregnancy.

Tell your doctor immediately if you're trying to get pregnant or become pregnant while taking this medicine.

Venlafaxine and breastfeeding

Venlafaxine passes into breast milk and has been linked with side effects in breastfed babies.

Talk to your doctor, as there may be other antidepressants that are more suitable for you while you are breastfeeding.

More about venlafaxine

How venlafaxine works

Venlafaxine is one of a group of antidepressants called serotonin and noradrenaline reuptake inhibitors, or SNRIs. These medicines are thought to work by increasing the levels of mood-enhancing chemicals called serotonin and noradrenaline in the brain.

How will it make me feel?

Antidepressants like venlafaxine help to jump start your mood so you feel better. You may notice that you sleep better and get on with people more easily because you're less anxious. You will hopefully take in your stride little things that used to worry you.

Venlafaxine won't change your personality or make you feel euphorically happy. It will simply help you feel like yourself again.

Don't expect to feel better overnight, though. Some people feel worse during the first few weeks of treatment before they begin to feel better.

When will I feel better?

You may see an improvement in your symptoms after a week or two although it usually takes between four and six weeks before you feel the full benefits. That's because it takes around a week for venlafaxine levels to build up in your body, and then a few weeks longer for your body to adapt and get used to it.

Don't stop taking venlafaxine after a week or two just because you feel it is not helping your symptoms. Give the medicine at least six weeks to work.

How long will I take venlafaxine for?

Once your condition is under control it is likely that you will continue to take venlafaxine for several more months to prevent the symptoms returning.

You will need to discuss with your doctor the pros and cons of continuing to take venlafaxine for longer than a few months. The decision will depend on the type and severity of your initial symptoms, whether it's a one-off or recurring problem, how well venlafaxine works for you, and whether you have had any serious side effects.

Is venlafaxine better than other antidepressants?

Venlafaxine isn't any better or worse than other antidepressants. However, sometimes people respond better to one antidepressant than to another. If you aren't feeling any better after six weeks, talk to your doctor.

Food and drinks to avoid

There are no food or drinks you need to avoid while taking venlafaxine.

Non-medical treatment options

Antidepressants, including venlafaxine, are just one of several approaches to treating depression. Other potential treatments include:

talking therapy (such as cognitive behavioural therapy)

exercise programmes

help to get a good night's sleep

Choosing a treatment that's most suitable for you depends on how long you have had depression, your symptoms, whether you have had any previous bouts of depression, whether previous treatment has worked, how likely you are to stick with your treatment, the potential side effects and your preferences and priorities.

Related conditions

Depression

Anxiety

Social anxiety

Panic attacks

Useful resources (external links)

Antidepressants: patient stories

Depression: patient stories

Depression and anxiety: patient stories

Action on depression: forum

Anxiety support: forum

Depression Alliance

Depression UK

Mental Health Foundation: depression

Mind: depression

{% endblock %}


text:
package entity;

import entity.chess.Chess;

//Author 在线疯狂
//Homepage http://bookshadow.com
public class Board {

	public static final char SELF = 's';
	public static final char OPPONENT = 'o';

	public static final int UP = 0;
	public static final int DOWN = 1;

	public Board() {
	}

	public Board(Chess[][] board, char upColor) {
		this.board = board;
		this.upColor = upColor;
	}

	private Chess[][] board;
	private char upColor; // Chess color in upper board

	public Chess[][] getBoard() {
		return board;
	}

	public void setBoard(Chess[][] board) {
		this.board = board;
	}

	public char getUpColor() {
		// System.out.println("upColor = " + upColor);
		return upColor;
	}

	public void setUpColor(char upColor) {
		this.upColor = upColor;
	}

	public static Chess findGeneral(Chess board[][], char color) {
		for (int i = 0; i < 10; i++) {
			for (int j = 0; j < 9; j++) {
				if (board[i][j] != null && board[i][j].getCode() == Chess.GENERAL && board[i][j].getColor() == color) {
					return board[i][j];
				}
			}
		}
		return null;
	}

	public Chess findGeneral(char color) {
		return findGeneral(this.board, color);
	}

	public int countChess(Coordinate start, Coordinate end) {
		return countChess(start, end, Chess.RED) + countChess(start, end, Chess.BLACK);
	}

	public static int countChess(Chess board[][], Coordinate start, Coordinate end) {
		return countChess(board, start, end, Chess.RED) + countChess(board, start, end, Chess.BLACK);
	}

	public int countChess(Coordinate start, Coordinate end, char color) {
		return countChess(board, start, end, color);
	}

	public static int countChess(Chess board[][], Coordinate start, Coordinate end, char color) {
		int sx = start.getX();
		int sy = start.getY();
		int ex = end.getX();
		int ey = end.getY();
		int minX = Math.min(sx, ex);
		int maxX = Math.max(sx, ex);
		int minY = Math.min(sy, ey);
		int maxY = Math.max(sy, ey);
		int cnt = 0;
		for (int i = minX; i <= maxX; i++) {
			for (int j = minY; j <= maxY; j++) {
				if (board[i][j] != null && board[i][j].getColor() == color)
					cnt++;
			}
		}
		return cnt;
	}

	public int getBottom(char color) {
		return color == upColor ? 0 : 9;
	}

	public int getRiver(char color) {
		return color == upColor ? 4 : 5;
	}

	public static boolean isEdge(int y) {
		return y == 0 || y == 8;
	}
}

redpajama_set_name: RedPajamaGithub


text:
package apiserver

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"path"
	rt "runtime"
	"strconv"
	"strings"
	"time"

	"k8s.io/kubernetes/pkg/admission"
	"k8s.io/kubernetes/pkg/api"
	apierrors "k8s.io/kubernetes/pkg/api/errors"
	"k8s.io/kubernetes/pkg/api/meta"
	"k8s.io/kubernetes/pkg/api/rest"
	"k8s.io/kubernetes/pkg/api/unversioned"
	"k8s.io/kubernetes/pkg/apiserver/metrics"
	"k8s.io/kubernetes/pkg/runtime"
	utilerrors "k8s.io/kubernetes/pkg/util/errors"
	"k8s.io/kubernetes/pkg/util/flushwriter"
	utilruntime "k8s.io/kubernetes/pkg/util/runtime"
	"k8s.io/kubernetes/pkg/util/wsstream"
	"k8s.io/kubernetes/pkg/version"

	"github.com/emicklei/go-restful"
	"github.com/golang/glog"
)

func init() {
	metrics.Register()
}

// mux is an object that can register http handlers.
type Mux interface {
	Handle(pattern string, handler http.Handler)
	HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))
}

// APIGroupVersion is a helper for exposing rest.Storage objects as http.Handlers via go-restful
// It handles URLs of the form:
// /${storage_key}[/${object_name}]
// Where 'storage_key' points to a rest.Storage object stored in storage.
// This object should contain all parameterization necessary for running a particular API version
type APIGroupVersion struct {
	Storage map[string]rest.Storage

	Root string

	// GroupVersion is the external group version
	GroupVersion unversioned.GroupVersion

	// RequestInfoResolver is used to parse URLs for the legacy proxy handler.  Don't use this for anything else
	// TODO: refactor proxy handler to use sub resources
	RequestInfoResolver *RequestInfoResolver

	// OptionsExternalVersion controls the Kubernetes APIVersion used for common objects in the apiserver
	// schema like api.Status, api.DeleteOptions, and api.ListOptions. Other implementors may
	// define a version "v1beta1" but want to use the Kubernetes "v1" internal objects. If
	// empty, defaults to GroupVersion.
	OptionsExternalVersion *unversioned.GroupVersion

	Mapper meta.RESTMapper

	// Serializer is used to determine how to convert responses from API methods into bytes to send over
	// the wire.
	Serializer     runtime.NegotiatedSerializer
	ParameterCodec runtime.ParameterCodec

	Typer     runtime.ObjectTyper
	Creater   runtime.ObjectCreater
	Convertor runtime.ObjectConvertor
	Copier    runtime.ObjectCopier
	Linker    runtime.SelfLinker

	Admit   admission.Interface
	Context api.RequestContextMapper

	MinRequestTimeout time.Duration

	// SubresourceGroupVersionKind contains the GroupVersionKind overrides for each subresource that is
	// accessible from this API group version. The GroupVersionKind is that of the external version of
	// the subresource. The key of this map should be the path of the subresource. The keys here should
	// match the keys in the Storage map above for subresources.
	SubresourceGroupVersionKind map[string]unversioned.GroupVersionKind
}

type ProxyDialerFunc func(network, addr string) (net.Conn, error)

// TODO: Pipe these in through the apiserver cmd line
const (
	// Minimum duration before timing out read/write requests
	MinTimeoutSecs = 300
	// Maximum duration before timing out read/write requests
	MaxTimeoutSecs = 600
)

// InstallREST registers the REST handlers (storage, watch, proxy and redirect) into a restful Container.
// It is expected that the provided path root prefix will serve all operations. Root MUST NOT end
// in a slash.
func (g *APIGroupVersion) InstallREST(container *restful.Container) error {
	installer := g.newInstaller()
	ws := installer.NewWebService()
	apiResources, registrationErrors := installer.Install(ws)
	AddSupportedResourcesWebService(g.Serializer, ws, g.GroupVersion, apiResources)
	container.Add(ws)
	return utilerrors.NewAggregate(registrationErrors)
}

// UpdateREST registers the REST handlers for this APIGroupVersion to an existing web service
// in the restful Container.  It will use the prefix (root/version) to find the existing
// web service.  If a web service does not exist within the container to support the prefix
// this method will return an error.
func (g *APIGroupVersion) UpdateREST(container *restful.Container) error {
	installer := g.newInstaller()
	var ws *restful.WebService = nil

	for i, s := range container.RegisteredWebServices() {
		if s.RootPath() == installer.prefix {
			ws = container.RegisteredWebServices()[i]
			break
		}
	}

	if ws == nil {
		return apierrors.NewInternalError(fmt.Errorf("unable to find an existing webservice for prefix %s", installer.prefix))
	}
	apiResources, registrationErrors := installer.Install(ws)
	AddSupportedResourcesWebService(g.Serializer, ws, g.GroupVersion, apiResources)
	return utilerrors.NewAggregate(registrationErrors)
}

// newInstaller is a helper to create the installer.  Used by InstallREST and UpdateREST.
func (g *APIGroupVersion) newInstaller() *APIInstaller {
	prefix := path.Join(g.Root, g.GroupVersion.Group, g.GroupVersion.Version)
	installer := &APIInstaller{
		group:             g,
		info:              g.RequestInfoResolver,
		prefix:            prefix,
		minRequestTimeout: g.MinRequestTimeout,
	}
	return installer
}

// TODO: document all handlers
// InstallVersionHandler registers the APIServer's `/version` handler
func InstallVersionHandler(mux Mux, container *restful.Container) {

	// Set up a service to return the git code version.
	versionWS := new(restful.WebService)
	versionWS.Path("/version")
	versionWS.Doc("git code version from which this is built")
	versionWS.Route(
		versionWS.GET("/").To(handleVersion).
			Doc("get the code version").
			Operation("getCodeVersion").
			Produces(restful.MIME_JSON).
			Consumes(restful.MIME_JSON).
			Writes(version.Info{}))

	container.Add(versionWS)
}

// InstallLogsSupport registers the APIServer log support function into a mux.
func InstallLogsSupport(mux Mux) {
	// TODO: use restful: ws.Route(ws.GET("/logs/{logpath:*}").To(fileHandler))
	// See github.com/emicklei/go-restful/blob/master/examples/restful-serve-static.go
	mux.Handle("/logs/", http.StripPrefix("/logs/", http.FileServer(http.Dir("/var/log/"))))
}

// TODO: needs to perform response type negotiation, this is probably the wrong way to recover panics
func InstallRecoverHandler(s runtime.NegotiatedSerializer, container *restful.Container) {
	container.RecoverHandler(func(panicReason interface{}, httpWriter http.ResponseWriter) {
		logStackOnRecover(s, panicReason, httpWriter)
	})
}

//TODO: Unify with RecoverPanics?
func logStackOnRecover(s runtime.NegotiatedSerializer, panicReason interface{}, w http.ResponseWriter) {
	var buffer bytes.Buffer
	buffer.WriteString(fmt.Sprintf("recover from panic situation: - %v\r\n", panicReason))
	for i := 2; ; i += 1 {
		_, file, line, ok := rt.Caller(i)
		if !ok {
			break
		}
		buffer.WriteString(fmt.Sprintf("    %s:%d\r\n", file, line))
	}
	glog.Errorln(buffer.String())

	headers := http.Header{}
	if ct := w.Header().Get("Content-Type"); len(ct) > 0 {
		headers.Set("Accept", ct)
	}
	errorNegotiated(apierrors.NewGenericServerResponse(http.StatusInternalServerError, "", api.Resource(""), "", "", 0, false), s, unversioned.GroupVersion{}, w, &http.Request{Header: headers})
}

func InstallServiceErrorHandler(s runtime.NegotiatedSerializer, container *restful.Container, requestResolver *RequestInfoResolver, apiVersions []string) {
	container.ServiceErrorHandler(func(serviceErr restful.ServiceError, request *restful.Request, response *restful.Response) {
		serviceErrorHandler(s, requestResolver, apiVersions, serviceErr, request, response)
	})
}

func serviceErrorHandler(s runtime.NegotiatedSerializer, requestResolver *RequestInfoResolver, apiVersions []string, serviceErr restful.ServiceError, request *restful.Request, response *restful.Response) {
	errorNegotiated(apierrors.NewGenericServerResponse(serviceErr.Code, "", api.Resource(""), "", "", 0, false), s, unversioned.GroupVersion{}, response.ResponseWriter, request.Request)
}

// Adds a service to return the supported api versions at the legacy /api.
func AddApiWebService(s runtime.NegotiatedSerializer, container *restful.Container, apiPrefix string, getAPIVersionsFunc func(req *restful.Request) *unversioned.APIVersions) {
	// TODO: InstallREST should register each version automatically

	// Because in release 1.1, /api returns response with empty APIVersion, we
	// use StripVersionNegotiatedSerializer to keep the response backwards
	// compatible.
	ss := StripVersionNegotiatedSerializer{s}
	versionHandler := APIVersionHandler(ss, getAPIVersionsFunc)
	ws := new(restful.WebService)
	ws.Path(apiPrefix)
	ws.Doc("get available API versions")
	ws.Route(ws.GET("/").To(versionHandler).
		Doc("get available API versions").
		Operation("getAPIVersions").
		Produces(s.SupportedMediaTypes()...).
		Consumes(s.SupportedMediaTypes()...).
		Writes(unversioned.APIVersions{}))
	container.Add(ws)
}

// stripVersionEncoder strips APIVersion field from the encoding output. It's
// used to keep the responses at the discovery endpoints backward compatible
// with release-1.1, when the responses have empty APIVersion.
type stripVersionEncoder struct {
	encoder    runtime.Encoder
	serializer runtime.Serializer
}

func (c stripVersionEncoder) EncodeToStream(obj runtime.Object, w io.Writer, overrides ...unversioned.GroupVersion) error {
	buf := bytes.NewBuffer([]byte{})
	err := c.encoder.EncodeToStream(obj, buf, overrides...)
	if err != nil {
		return err
	}
	roundTrippedObj, gvk, err := c.serializer.Decode(buf.Bytes(), nil, nil)
	if err != nil {
		return err
	}
	gvk.Group = ""
	gvk.Version = ""
	roundTrippedObj.GetObjectKind().SetGroupVersionKind(*gvk)
	return c.serializer.EncodeToStream(roundTrippedObj, w)
}

// StripVersionNegotiatedSerializer will return stripVersionEncoder when
// EncoderForVersion is called. See comments for stripVersionEncoder.
type StripVersionNegotiatedSerializer struct {
	runtime.NegotiatedSerializer
}

func (n StripVersionNegotiatedSerializer) EncoderForVersion(encoder runtime.Encoder, gv unversioned.GroupVersion) runtime.Encoder {
	serializer, ok := encoder.(runtime.Serializer)
	if !ok {
		// The stripVersionEncoder needs both an encoder and decoder, but is called from a context that doesn't have access to the
		// decoder. We do a best effort cast here (since this code path is only for backwards compatibility) to get access to the caller's
		// decoder.
		panic(fmt.Sprintf("Unable to extract serializer from %#v", encoder))
	}
	versioned := n.NegotiatedSerializer.EncoderForVersion(encoder, gv)
	return stripVersionEncoder{versioned, serializer}
}

func keepUnversioned(group string) bool {
	return group == "" || group == "extensions"
}

// Adds a service to return the supported api versions at /apis.
func AddApisWebService(s runtime.NegotiatedSerializer, container *restful.Container, apiPrefix string, f func(req *restful.Request) []unversioned.APIGroup) {
	// Because in release 1.1, /apis returns response with empty APIVersion, we
	// use StripVersionNegotiatedSerializer to keep the response backwards
	// compatible.
	ss := StripVersionNegotiatedSerializer{s}
	rootAPIHandler := RootAPIHandler(ss, f)
	ws := new(restful.WebService)
	ws.Path(apiPrefix)
	ws.Doc("get available API versions")
	ws.Route(ws.GET("/").To(rootAPIHandler).
		Doc("get available API versions").
		Operation("getAPIVersions").
		Produces(s.SupportedMediaTypes()...).
		Consumes(s.SupportedMediaTypes()...).
		Writes(unversioned.APIGroupList{}))
	container.Add(ws)
}

// Adds a service to return the supported versions, preferred version, and name
// of a group. E.g., a such web service will be registered at /apis/extensions.
func AddGroupWebService(s runtime.NegotiatedSerializer, container *restful.Container, path string, group unversioned.APIGroup) {
	ss := s
	if keepUnversioned(group.Name) {
		// Because in release 1.1, /apis/extensions returns response with empty
		// APIVersion, we use StripVersionNegotiatedSerializer to keep the
		// response backwards compatible.
		ss = StripVersionNegotiatedSerializer{s}
	}
	groupHandler := GroupHandler(ss, group)
	ws := new(restful.WebService)
	ws.Path(path)
	ws.Doc("get information of a group")
	ws.Route(ws.GET("/").To(groupHandler).
		Doc("get information of a group").
		Operation("getAPIGroup").
		Produces(s.SupportedMediaTypes()...).
		Consumes(s.SupportedMediaTypes()...).
		Writes(unversioned.APIGroup{}))
	container.Add(ws)
}

// Adds a service to return the supported resources, E.g., a such web service
// will be registered at /apis/extensions/v1.
func AddSupportedResourcesWebService(s runtime.NegotiatedSerializer, ws *restful.WebService, groupVersion unversioned.GroupVersion, apiResources []unversioned.APIResource) {
	ss := s
	if keepUnversioned(groupVersion.Group) {
		// Because in release 1.1, /apis/extensions/v1beta1 returns response
		// with empty APIVersion, we use StripVersionNegotiatedSerializer to
		// keep the response backwards compatible.
		ss = StripVersionNegotiatedSerializer{s}
	}
	resourceHandler := SupportedResourcesHandler(ss, groupVersion, apiResources)
	ws.Route(ws.GET("/").To(resourceHandler).
		Doc("get available resources").
		Operation("getAPIResources").
		Produces(s.SupportedMediaTypes()...).
		Consumes(s.SupportedMediaTypes()...).
		Writes(unversioned.APIResourceList{}))
}

// handleVersion writes the server's version information.
func handleVersion(req *restful.Request, resp *restful.Response) {
	writeRawJSON(http.StatusOK, version.Get(), resp.ResponseWriter)
}

// APIVersionHandler returns a handler which will list the provided versions as available.
func APIVersionHandler(s runtime.NegotiatedSerializer, getAPIVersionsFunc func(req *restful.Request) *unversioned.APIVersions) restful.RouteFunction {
	return func(req *restful.Request, resp *restful.Response) {
		writeNegotiated(s, unversioned.GroupVersion{}, resp.ResponseWriter, req.Request, http.StatusOK, getAPIVersionsFunc(req))
	}
}

// RootAPIHandler returns a handler which will list the provided groups and versions as available.
func RootAPIHandler(s runtime.NegotiatedSerializer, f func(req *restful.Request) []unversioned.APIGroup) restful.RouteFunction {
	return func(req *restful.Request, resp *restful.Response) {
		writeNegotiated(s, unversioned.GroupVersion{}, resp.ResponseWriter, req.Request, http.StatusOK, &unversioned.APIGroupList{Groups: f(req)})
	}
}

// GroupHandler returns a handler which will return the api.GroupAndVersion of
// the group.
func GroupHandler(s runtime.NegotiatedSerializer, group unversioned.APIGroup) restful.RouteFunction {
	return func(req *restful.Request, resp *restful.Response) {
		writeNegotiated(s, unversioned.GroupVersion{}, resp.ResponseWriter, req.Request, http.StatusOK, &group)
	}
}

// SupportedResourcesHandler returns a handler which will list the provided resources as available.
func SupportedResourcesHandler(s runtime.NegotiatedSerializer, groupVersion unversioned.GroupVersion, apiResources []unversioned.APIResource) restful.RouteFunction {
	return func(req *restful.Request, resp *restful.Response) {
		writeNegotiated(s, unversioned.GroupVersion{}, resp.ResponseWriter, req.Request, http.StatusOK, &unversioned.APIResourceList{GroupVersion: groupVersion.String(), APIResources: apiResources})
	}
}

// write renders a returned runtime.Object to the response as a stream or an encoded object. If the object
// returned by the response implements rest.ResourceStreamer that interface will be used to render the
// response. The Accept header and current API version will be passed in, and the output will be copied
// directly to the response body. If content type is returned it is used, otherwise the content type will
// be "application/octet-stream". All other objects are sent to standard JSON serialization.
func write(statusCode int, gv unversioned.GroupVersion, s runtime.NegotiatedSerializer, object runtime.Object, w http.ResponseWriter, req *http.Request) {
	if stream, ok := object.(rest.ResourceStreamer); ok {
		out, flush, contentType, err := stream.InputStream(gv.String(), req.Header.Get("Accept"))
		if err != nil {
			errorNegotiated(err, s, gv, w, req)
			return
		}
		if out == nil {
			// No output provided - return StatusNoContent
			w.WriteHeader(http.StatusNoContent)
			return
		}
		defer out.Close()

		if wsstream.IsWebSocketRequest(req) {
			r := wsstream.NewReader(out, true)
			if err := r.Copy(w, req); err != nil {
				utilruntime.HandleError(fmt.Errorf("error encountered while streaming results via websocket: %v", err))
			}
			return
		}

		if len(contentType) == 0 {
			contentType = "application/octet-stream"
		}
		w.Header().Set("Content-Type", contentType)
		w.WriteHeader(statusCode)
		writer := w.(io.Writer)
		if flush {
			writer = flushwriter.Wrap(w)
		}
		io.Copy(writer, out)
		return
	}
	writeNegotiated(s, gv, w, req, statusCode, object)
}

// writeNegotiated renders an object in the content type negotiated by the client
func writeNegotiated(s runtime.NegotiatedSerializer, gv unversioned.GroupVersion, w http.ResponseWriter, req *http.Request, statusCode int, object runtime.Object) {
	serializer, err := negotiateOutputSerializer(req, s)
	if err != nil {
		status := errToAPIStatus(err)
		writeRawJSON(int(status.Code), status, w)
		return
	}

	w.Header().Set("Content-Type", serializer.MediaType)
	w.WriteHeader(statusCode)

	encoder := s.EncoderForVersion(serializer, gv)
	if err := encoder.EncodeToStream(object, w); err != nil {
		errorJSONFatal(err, encoder, w)
	}
}

// errorNegotiated renders an error to the response. Returns the HTTP status code of the error.
func errorNegotiated(err error, s runtime.NegotiatedSerializer, gv unversioned.GroupVersion, w http.ResponseWriter, req *http.Request) int {
	status := errToAPIStatus(err)
	code := int(status.Code)
	// when writing an error, check to see if the status indicates a retry after period
	if status.Details != nil && status.Details.RetryAfterSeconds > 0 {
		delay := strconv.Itoa(int(status.Details.RetryAfterSeconds))
		w.Header().Set("Retry-After", delay)
	}
	writeNegotiated(s, gv, w, req, code, status)
	return code
}

// errorJSONFatal renders an error to the response, and if codec fails will render plaintext.
// Returns the HTTP status code of the error.
func errorJSONFatal(err error, codec runtime.Encoder, w http.ResponseWriter) int {
	utilruntime.HandleError(fmt.Errorf("apiserver was unable to write a JSON response: %v", err))
	status := errToAPIStatus(err)
	code := int(status.Code)
	output, err := runtime.Encode(codec, status)
	if err != nil {
		w.WriteHeader(code)
		fmt.Fprintf(w, "%s: %s", status.Reason, status.Message)
		return code
	}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	w.Write(output)
	return code
}

// writeRawJSON writes a non-API object in JSON.
func writeRawJSON(statusCode int, object interface{}, w http.ResponseWriter) {
	output, err := json.MarshalIndent(object, "", "  ")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(statusCode)
	w.Write(output)
}

func parseTimeout(str string) time.Duration {
	if str != "" {
		timeout, err := time.ParseDuration(str)
		if err == nil {
			return timeout
		}
		glog.Errorf("Failed to parse %q: %v", str, err)
	}
	return 30 * time.Second
}

func readBody(req *http.Request) ([]byte, error) {
	defer req.Body.Close()
	return ioutil.ReadAll(req.Body)
}

// splitPath returns the segments for a URL path.
func splitPath(path string) []string {
	path = strings.Trim(path, "/")
	if path == "" {
		return []string{}
	}
	return strings.Split(path, "/")
}


text:
package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Update migration item input.
 */
public class UpdateMigrationItemInput {
    /**
     * Update migration item input properties.
     */
    @JsonProperty(value = "properties")
    private UpdateMigrationItemInputProperties properties;

    /**
     * Get update migration item input properties.
     *
     * @return the properties value
     */
    public UpdateMigrationItemInputProperties properties() {
        return this.properties;
    }

    /**
     * Set update migration item input properties.
     *
     * @param properties the properties value to set
     * @return the UpdateMigrationItemInput object itself.
     */
    public UpdateMigrationItemInput withProperties(UpdateMigrationItemInputProperties properties) {
        this.properties = properties;
        return this;
    }

}


text:
#ifndef ISPL_XCALIGN_H__
#define ISPL_XCALIGN_H__ 1
#include <stdbool.h>
#include "ispl/utils.h"

struct xcAlignCSRMatrix_struct
{
    double *A;    /*!< Contains the sparse matrix from VanDecar and
                       Crosson 1990 - Eqn 5a + 5b.  This is an array
                       of dimension [nnz]. */
    int *rowPtr;  /*!< Maps from the ir'th row to the start index of
                       colPtr and A.  This is an array of dimension
                       [mrows+1]. */
    int *colPtr;  /*!< Maps from the inz'th non-zero to the column index.
                       This is an array of dimension [nnz]. */
    int mrows;    /*!< Number of rows in sparse matrix. */
    int ncols;    /*!< Number of columns in sparse matrix. */
    int nnz;      /*!< Number of non-zeros in sparse matrices. */
    char pad[4];
};

struct xcAlign_struct
{
    struct xcAlignCSRMatrix_struct csrMat; /*!< Contains the CSR matrix. */
    double *test;     /*!< Optimized travel-times.  This is an array of
                           dimension [nsignals]. */
    double *signals;  /*!< Contains the signals to cross-correlate.  This
                           is an array of dimension [lds x nsignals]
                           with leading dimension lds. */
    double *xcs;      /*!< Cross-correlograms.  This is an array of dimension
                           [ldxc x nxc] with leading dimension ldxc. */
    double *xnorm;    /*!< Two-norm in each waveform for normalization.  This
                           is an array of dimension [nsignals]. */
    double *tp;       /*!< Pick times relative to trace start in seconds.
                           This is an array of [nsignals]. */
    double *xcdt;     /*!< These are the cross-correlation derived differential
                           travel times (seconds).  This is an array of
                           dimension [nxc+1]. */
    double *phi;      /*!< Normalized cross-correlation value at optimal
                           lag.  This is an array of dimension [nxc+1]. */
    double *var;      /*!< Variance in the signal.  This is an array of
                           dimension [nsignals]. */
    bool *lskip;      /*!< If true then skip this observation.  This is
                           an array of dimension [nsignals]. */
    double t0;        /*!< Seconds before pick time to begin correlation
                           window. */
    double xcWinLen;  /*!< Length of cross-correlation window in seconds. */
    double dt;        /*!< Sampling period (seconds). */
    int nsignals;     /*!< Number of signals. */
    int ndecim;       /*!< Decimation factor in cross-correlation. */
    int npts;         /*!< Number of points in data windows. */
    int lds;          /*!< Leading dimension of signals. */
    int nptsXC;       /*!< Number of points in cross-correlations. */
    int nxc;          /*!< Number of cross-correlations. */
    int ldxc;         /*!< Leading dimension of cross-correlations. */
    int verbose;      /*!< Controls verbosity. \n
                           0 is quiet. \n
                           1 reports on errors only. \n
                           2 reports on warnings and errors. \n
                           3 reports on everything. */
    bool linit;       /*!< If true then the structure is initialized. */
    bool lhaveData;   /*!< If true then the data has been set. */
    bool luseAbs;     /*!< If true then take the max absolute value from the
                           cross-correlograms.  Otherwise, just choose the
                           max. */
    char pad[6];
};

#ifdef __cplusplus
extern "C"
{
#endif

/* Initialize the XC align structure */
int ispl_xcAlign_initialize(const int nsignals,
                            const int ndecim,
                            const int verbose,
                            const bool luseAbs,
                            const double dt,
                            const double t0,
                            const double xcWinLen,
                            struct xcAlign_struct *xcStruct);
/* Free the the xcAlign structure */
int ispl_xcAlign_free(struct xcAlign_struct *xcStruct);
/* Optimize the travel picks */
int ispl_xcAlign_optimizeTimeLags(struct xcAlign_struct *xcStruct);
/* Get the new pick times */
int ispl_xcAlign_getNewPickTimes(const int nsignals,
                                 const struct xcAlign_struct xcStruct,
                                 double *tp);
/* Internal function for populating RHS from time lags. */
int ispl_xcAlign_timeLagsFromXCsToRHS(struct xcAlign_struct *xcStruct);
/* Compute the cross-correlation */
int ispl_xcAlign_computeCorrelograms(struct xcAlign_struct *xcStruct);
/* Sets the xcAlign data */
int ispl_xcAlign_setData64f(const int nsignals,
                            const int signalPtr[],
                            const double tp[],
                            const double signals[],
                            struct xcAlign_struct *xcStruct);

#ifdef __cplusplus
}
#endif
#endif


text:
#define __OODUCK_HASHMAP_PRIV_H
#include <ooduck/hashmap.h>
#include <ooduck/_defs/hashmap.h>
#include <ooduck/_priv/hashmap.h>

OODUCK_DEFINE_CLASS (
    Hashmap,
    new (
        Class (), "Hashmap",
        Iterable (), sizeof (struct Hashmap),
        "__constructor__", Hashmap_constructor,
        "__destructor__", Hashmap_destructor,
        "contains", Hashmap_contains,
        "clear", Hashmap_clear,
        "next", Hashmap_next,
        "get", Hashmap_get,
        "set", Hashmap_set,
        "del", Hashmap_del,
        "keys", Hashmap_keys,
        "values", Hashmap_values,
        NULL
    )
)

/* implementation */

static void *Hashmap_constructor (void *_self, va_list *app)
{
    Class_constructor_m ctor = method (super (Hashmap ()), "__constructor__");
    struct Hashmap *self = ctor (_self, app);

    self->keys = new (Collection ());
    self->values = new (Collection ());

    return self;
}

static void *Hashmap_destructor (void *_self)
{
    struct Hashmap *self = cast (Hashmap (), _self);
    Class_destructor_m dtor = method (super (Hashmap ()), "__destructor__");

    delete (self->keys);
    delete (self->values);

    return dtor (self);
}

static bool Hashmap_contains (const void *_self, const void *key)
{
    struct Hashmap *self = cast (Hashmap (), _self);
    Iterable_contains_m contains = method (classOf (self->keys), "contains");

    return contains (self->keys, key);
}

static void Hashmap_clear (void *_self)
{
    struct Hashmap *self = cast (Hashmap (), _self);
    Iterable_clear_m clearkeys = method (classOf (self->keys), "clear");
    Iterable_clear_m clearvalues = method (classOf (self->values), "clear");

    clearkeys (self->keys);
    clearvalues (self->values);
}

static void *Hashmap_next (const void *_self, const void *iterator)
{
    struct Hashmap *self = cast (Hashmap (), _self);
    Iterable_next_m next = method (classOf (self->keys), "next");

    return next (self->keys, iterator);
}

static void *Hashmap_get (const void *_self, const void *key)
{
    struct Hashmap *self = cast (Hashmap (), _self);
    void *item = NULL;
    int i = 0;

    void *it = new (Iterator (), self);
    Iterator_next_m next = method (classOf (it), "next");

    /* look for the key */
    Object_equal_m equal = method (classOf (key), "equal");

    for (; (item = next (it)) != NULL && !equal (key, item); ++i);

    delete (it);

    /* the value is at the same position */
    it = new (Iterator (), self->values);

    for (; i >= 0; --i)
    {
        item = next (it);
    }

    delete (it);

    /* return value */
    return ref (item);
}

static void Hashmap_set (void *_self, const void *key, void *value)
{
    struct Hashmap *self = cast (Hashmap (), _self);

    Iterable_contains_m contains = method (classOf (self), "contains");
    Collection_add_m addkey = method (classOf (self->keys), "add");
    Collection_add_m addval = method (classOf (self->values), "add");

    if (contains (self, key))
    {
        Hashmap_del_m del = method (classOf (self), "del");
        del (self, key);
    }

    addkey (self->keys, key);
    addval (self->values, value);
}

static void Hashmap_del (void *_self, const void *key)
{
    struct Hashmap *self = cast (Hashmap (), _self);

    Iterable_contains_m contains = method (classOf (self), "contains");

    if (contains (self, key))
    {
        Hashmap_get_m get = method (classOf (self), "get");
        Collection_del_m delkey = method (classOf (self->keys), "del");
        Collection_del_m delval = method (classOf (self->values), "del");

        void *oldvalue = get (self, key);
        delkey (self->keys, key);
        delval (self->values, oldvalue);
    }
}

static void *Hashmap_keys (const void *_self)
{
    struct Hashmap *self = cast (Hashmap (), _self);
    return self->keys;
}

static void *Hashmap_values (const void *_self)
{
    struct Hashmap *self = cast (Hashmap (), _self);
    return self->values;
}


text:
<!DOCTYPE html>

<title>How do I reply to a forum post (i.e. conversation)?</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta content="sakai.forums" name="description">
<meta content="Forum, Topic, Conversation, post message, reply" name="search">
<link href="/library/skin/tool_base.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/skin/morpheus-default/tool.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/skin/morpheus-default/help.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/js/jquery/featherlight/0.4.0/featherlight.min.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">

How do I reply to a forum post (i.e. conversation)?

Go to Forums.

Select the Forums tool from Tool Menu in your site.

Choose a topic within a forum.

Click on the title of the topic to enter the topic.

Note: The message indicator text next to the topic title will tell you how many messages have been posted within that topic, and how many of them are new or unread.

Click on the title of an existing post to view the conversation.

              Zoom

Click reply.

              Zoom

You have two different options for replying to the post within the Forums tool.

Click Reply to Initial Message at the top of the conversation to reply to the first message in the conversation or thread.

Click the Reply link within the message itself to reply to the item you are currently viewing. This is the option you want to use if you would like to reply to someone else's reply.

Compose your message.

              Zoom

The message you are replying to will be displayed at the top. You can hide the message by clicking on the small downward arrow next to "Hide the message you are replying to".

Edit the reply title. (Optional)

              Zoom

The title will be taken from the initial message and prefilled for you, but you may modify it if you wish.

Enter your message.

              Zoom

Use the Rich Text Editor to compose your response.

Note: You may optionally click on the Insert original text link above the editor area to include the original message along with your reply.

Add attachment. (Optional)

              Zoom

Click the Add attachments button if you would like to browse for and attach a file.

Click Post.

After you have finished your reply, click Post to add your message to the conversation.


text:
module.exports.run = async (client, message, args) => {
    const Discord = require('discord.js')
    var baseUptime = client.uptime;
    var minutes = Math.round((baseUptime / 1000 / 60) % 60);
    var hours = Math.round((minutes / 60) % 60);
    var days = Math.round((hours / 24) % 24);
    var baseString = `I've been up for ${hours}:${minutes} hours. (Day count is ${days})`;

    if (minutes <= 9) {
        baseString = `I've been up for ${hours}:0${minutes} hours. (Day count is ${days})`;
    }
    else if (hours <= 9) {
        baseString = `I've been up for 0${hours}:${minutes} hours. (Day count is ${days})`;
    }
    try {
        let embed = new Discord.RichEmbed()
        .setTitle("PrecipitationJS Uptime")
        .setDescription(baseString)
        .setFooter(`PrecipitationJS 0.1.2 | Requested by ${message.author.username} at ${new Date()}`, message.author.avatarURL)
    message.channel.send({ embed })
    } catch(e) {
        console.log(e);
    }
}

module.exports.help = {
    name: 'uptime',
    args: '[none]',
    notes: 'Sends the uptime of PrecipitationJS.'
}


text:
const bp = require('../constants/mediaTypes');

module.exports = {
    '--media-phone-small': `screen and (max-width: ${bp.PHONE_SMALL}px)`,
    '--media-phone': `screen and (max-width: ${bp.PHONE}px)`,
    '--media-phone-gigant': `screen and (min-width: ${bp.TABLETS}px) and (max-width: ${bp.PHONE_GIANT}px)`,
    '--media-tablets': `screen and (min-width: ${bp.TABLETS}px)`,
    '--media-mobile': `screen and (max-width: ${bp.MOBILE}px)`,
    '--media-desktop': `screen and (min-width: ${bp.DESKTOP}px)`,
    '--media-desktop-large': `screen and (min-width: ${bp.DESKTOP_LARGE}px)`,
    '--media-desktop-dambo': `screen and (min-width: ${bp.DESKTOP_DAMBO}px)`,
    '--media-desktop-extra-large': `screen and (min-width: ${bp.DESKTOP_EXTRA_LARGE}px)`,
    '--media-desktop-gigant': `screen and (min-width: ${bp.DESKTOP_GIANT}px)`,
    '--media-retina': '(-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi)'
};


text:
Ti=Article 96 -Relationship with previously concluded Agreements

sec=International agreements involving the transfer of personal data to third countries or international organisations which were concluded by Member States prior to … [the date of entry into force of this Regulation], and which are in accordance with Union law applicable prior to … [the date of entry into force of this Regulation], shall remain in force until amended, replaced or revoked.

=[Z/ol/0]


text:
namespace mojo {
namespace dart {
namespace {

static bool generateEntropy(uint8_t* buffer, intptr_t length) {
  base::RandBytes(reinterpret_cast<void*>(buffer), length);
  return true;
}

static void exceptionCallback(bool* exception, Dart_Handle error) {
  *exception = true;
}

static void RunTest(const std::string& test,
                    bool compile_all,
                    const char** extra_args,
                    int num_extra_args) {
  base::FilePath path;
  PathService::Get(base::DIR_SOURCE_ROOT, &path);
  path = path.AppendASCII("mojo")
             .AppendASCII("dart")
             .AppendASCII("test")
             .AppendASCII(test);

  // Read in the source.
  std::string source;
  EXPECT_TRUE(ReadFileToString(path, &source)) << "Failed to read test file";

  // Setup the package root.
  base::FilePath package_root;
  PathService::Get(base::DIR_EXE, &package_root);
  package_root = package_root.AppendASCII("gen")
                             .AppendASCII("dart-pkg")
                             .AppendASCII("packages");

  char* error = NULL;
  bool unhandled_exception = false;
  DartControllerConfig config;
  // Run with strict compilation even in Release mode so that ASAN testing gets
  // coverage of Dart asserts, type-checking, etc.
  config.strict_compilation = true;
  config.script = source;
  config.script_uri = path.AsUTF8Unsafe();
  config.package_root = package_root.AsUTF8Unsafe();
  config.application_data = nullptr;
  config.callbacks.exception =
      base::Bind(&exceptionCallback, &unhandled_exception);
  config.entropy = generateEntropy;
  config.arguments = extra_args;
  config.arguments_count = num_extra_args;
  config.handle = MOJO_HANDLE_INVALID;
  config.compile_all = compile_all;
  config.error = &error;

  bool success = DartController::RunSingleDartScript(config);
  EXPECT_TRUE(success) << error;
  EXPECT_FALSE(unhandled_exception);
}

// TODO(zra): instead of listing all these tests, search //mojo/dart/test for
// _test.dart files.

TEST(DartTest, hello_mojo) {
  RunTest("hello_mojo.dart", false, nullptr, 0);
}

TEST(DartTest, core_types_test) {
  RunTest("core_types_test.dart", false, nullptr, 0);
}

TEST(DartTest, async_test) {
  RunTest("async_test.dart", false, nullptr, 0);
}

TEST(DartTest, isolate_test) {
  RunTest("isolate_test.dart", false, nullptr, 0);
}

TEST(DartTest, import_mojo) {
  RunTest("import_mojo.dart", false, nullptr, 0);
}

TEST(DartTest, simple_handle_watcher_test) {
  RunTest("simple_handle_watcher_test.dart", false, nullptr, 0);
}

TEST(DartTest, ping_pong_test) {
  RunTest("ping_pong_test.dart", false, nullptr, 0);
}

TEST(DartTest, timer_test) {
  RunTest("timer_test.dart", false, nullptr, 0);
}

TEST(DartTest, async_await_test) {
  RunTest("async_await_test.dart", false, nullptr, 0);
}

TEST(DartTest, core_test) {
  RunTest("core_test.dart", false, nullptr, 0);
}

TEST(DartTest, codec_test) {
  RunTest("codec_test.dart", false, nullptr, 0);
}

TEST(DartTest, handle_watcher_test) {
  RunTest("handle_watcher_test.dart", false, nullptr, 0);
}

TEST(DartTest, bindings_generation_test) {
  RunTest("bindings_generation_test.dart", false, nullptr, 0);
}

TEST(DartTest, compile_all_interfaces_test) {
  RunTest("compile_all_interfaces_test.dart", true, nullptr, 0);
}

TEST(DartTest, uri_base_test) {
  RunTest("uri_base_test.dart", false, nullptr, 0);
}

TEST(DartTest, exception_test) {
  RunTest("exception_test.dart", false, nullptr, 0);
}

TEST(DartTest, control_messages_test) {
  RunTest("control_messages_test.dart", false, nullptr, 0);
}

TEST(DartTest, handle_finalizer_test) {
  const int kNumArgs = 2;
  const char* args[kNumArgs];
  args[0] = "--new-gen-semi-max-size=1";
  args[1] = "--old_gen_growth_rate=1";
  RunTest("handle_finalizer_test.dart", false, args, kNumArgs);
}

}  // namespace
}  // namespace dart
}  // namespace mojo


text:
package com.epam.catgenome.controller;

import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.ResultActions;

import com.epam.catgenome.common.AbstractControllerTest;
import com.epam.catgenome.common.ResponseResult;
import com.epam.catgenome.controller.vo.externaldb.UniprotEntryVO;
import com.epam.catgenome.controller.vo.externaldb.ensemblevo.EnsemblEntryVO;
import com.epam.catgenome.manager.externaldb.HttpDataManager;
import com.epam.catgenome.manager.externaldb.ParameterNameValue;

/**
 * Source:      ExternalDBControllerTest
 * Created:     30.09.16, 13:10
 * Project:     CATGenome Browser
 * Make:        IntelliJ IDEA 14.1.4, JDK 1.8
 *
 * @author Mikhail Miroliubov
 */

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration()
@ContextConfiguration({"classpath:applicationContext-test.xml", "classpath:catgenome-servlet-test.xml"})
public class ExternalDBControllerTest extends AbstractControllerTest {
    private static final String URL_FETCH_ENSEMBL_DATA = "/restapi/externaldb/ensembl/%s/get";
    private static final String URL_FETCH_UNIPROT_DATA = "/restapi/externaldb/uniprot/%s/get";

    private static final long GENE_START = 74082933L;
    private static final long END = 74122525L;

    @MockBean(name = "httpDataManager")
    private HttpDataManager httpDataManager;

    @Autowired
    private ApplicationContext context;

    @Before
    public void setup() throws Exception {
        super.setup();
    }

    @Test
    public void testFetchEnsemblData() throws Exception {
        // arrange
        String fetchRes = readFile("ensembl_lookup_id_ENSG00000106683.json");

        when(
                httpDataManager.fetchData(Mockito.anyString(), Mockito.any(ParameterNameValue[].class))
        ).thenReturn(fetchRes);

        // act
        ResultActions actions = mvc()
                .perform(get(String.format(URL_FETCH_ENSEMBL_DATA, "rs7412"))
                        .contentType(EXPECTED_CONTENT_TYPE))
                .andExpect(status().isOk())
                .andExpect(content().contentType(EXPECTED_CONTENT_TYPE))
                .andExpect(jsonPath(JPATH_PAYLOAD).exists())
                .andExpect(jsonPath(JPATH_STATUS).value(ResultStatus.OK.name()));

        ResponseResult<EnsemblEntryVO> res = getObjectMapper().readValue(actions.andReturn().getResponse()
                .getContentAsByteArray(), getTypeFactory().constructParametricType(ResponseResult.class,
                EnsemblEntryVO.class));

        EnsemblEntryVO ensemblEntryVO = res.getPayload();

        // assert
        Assert.assertNotNull(ensemblEntryVO);
        Assert.assertEquals("ENSG00000106683", ensemblEntryVO.getId());
        Assert.assertTrue(ensemblEntryVO.getStart().equals(GENE_START));
        Assert.assertTrue(ensemblEntryVO.getEnd().equals(END));
        Assert.assertEquals("GRCh38", ensemblEntryVO.getAssemblyName());
        Assert.assertEquals("LIMK1", ensemblEntryVO.getDisplayName());
        Assert.assertEquals("LIM domain kinase 1 [Source:HGNC Symbol;Acc:HGNC:6613]", ensemblEntryVO.getDescription());
    }

    @Test
    public void testFetchUniprotData() throws Exception {
        // arrange
        String fetchRes = readFile("uniprot_fetch_gene_ENSG00000106683.xml");

        when(
                httpDataManager.fetchData(Mockito.any(), Mockito.any(ParameterNameValue[].class))
        ).thenReturn(fetchRes);

        // act
        ResultActions actions = mvc()
                .perform(get(String.format(URL_FETCH_UNIPROT_DATA, "ENSG00000106683"))
                        .contentType(EXPECTED_CONTENT_TYPE))
                .andExpect(status().isOk())
                .andExpect(content().contentType(EXPECTED_CONTENT_TYPE))
                .andExpect(jsonPath(JPATH_PAYLOAD).exists())
                .andExpect(jsonPath(JPATH_STATUS).value(ResultStatus.OK.name()));

        ResponseResult<List<UniprotEntryVO>> res = getObjectMapper().readValue(actions.andReturn().getResponse()
                .getContentAsByteArray(), getTypeFactory().constructParametricType(ResponseResult.class,
                getTypeFactory().constructParametricType(List.class, UniprotEntryVO.class)));

        List<UniprotEntryVO> entryList = res.getPayload();

        // assert
        Assert.assertNotNull(entryList);
        Assert.assertEquals(2, entryList.size());

        UniprotEntryVO entryVO = entryList.get(0);
        Assert.assertNotNull(entryVO);
        Assert.assertEquals("LIMK1_HUMAN", entryVO.getName());
        Assert.assertEquals("LIMK1", entryVO.getGeneNames().get(0));
    }

    private String readFile(String filename) throws IOException {
        Resource resource = context.getResource("classpath:externaldb//data//" + filename);
        String pathStr = resource.getFile().getPath();
        String content = new String(Files.readAllBytes(Paths.get(pathStr)), Charset.defaultCharset());
        return content;
    }
}


text:
import format from 'date-fns/format';
import parseISO from 'date-fns/parseISO';
import React from 'react';
import Article from './Article';
import Link from './Link';
import PostContainer from './PostContainer';
import Timestamp from './Timestamp';

interface PostProps {
  children: string;
  date: string;
}

function Post({ children, date }: PostProps) {
  return (
    <PostContainer>
      <Link href={`/posts/${date}`}>
        <Article>{children}</Article>
        <Timestamp>{format(parseISO(date), 'MMMM do, yyyy')}</Timestamp>
      </Link>
    </PostContainer>
  );
}

export default Post;


text:
//
// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// 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.
//

// Module dependencies.
var _ = require('underscore');

var azureCommon = require('azure-common');
var azureutil = azureCommon.util;
var Constants = azureCommon.Constants;
var HeaderConstants = Constants.HeaderConstants;

function BlobResult(container, blob) {
  if (container) {
    this.container = container;
  }

  if (blob) {
    this.blob = blob;
  }
}

BlobResult.parse = function (blobXml) {
  var blobResult = new BlobResult();
  for (var propertyName in blobXml) {
    if (propertyName === 'Properties' || propertyName === 'Metadata') {
      blobResult[propertyName.toLowerCase()] = { };
      for (var subPropertyName in blobXml[propertyName]) {
        if (blobXml[propertyName].hasOwnProperty(subPropertyName)) {
          blobResult[propertyName.toLowerCase()][subPropertyName.toLowerCase()] = blobXml[propertyName][subPropertyName];
        }
      }
    } else {
      blobResult[propertyName.toLowerCase()] = blobXml[propertyName];
    }
  }

  return blobResult;
};

var headersForProperties = {
  'etag': 'ETAG',
  'lastModified': 'LAST_MODIFIED',

  'contentType': 'CONTENT_TYPE',
  'contentEncoding': 'CONTENT_ENCODING',
  'contentLanguage': 'CONTENT_LANGUAGE',
  'contentMD5': 'CONTENT_MD5',
  'cacheControl': 'CACHE_CONTROL',
  'contentRange': 'CONTENT_RANGE',
  'contentTypeHeader': 'CONTENT_TYPE_HEADER',
  'contentEncodingHeader': 'CONTENT_ENCODING_HEADER',
  'contentLanguageHeader': 'CONTENT_LANGUAGE_HEADER',
  'contentMD5Header': 'BLOB_CONTENT_MD5_HEADER',
  'cacheControlHeader': 'CACHE_CONTROL_HEADER',

  'contentLength': 'CONTENT_LENGTH',
  'contentLengthHeader': 'CONTENT_LENGTH_HEADER',

  'range': 'RANGE',
  'rangeHeader': 'STORAGE_RANGE_HEADER',

  'getContentMd5': 'RANGE_GET_CONTENT_MD5',
  'acceptRanges': 'ACCEPT_RANGES',

  'blobType': 'BLOB_TYPE_HEADER',
  'leaseStatus': 'LEASE_STATUS',
  'leaseId': 'LEASE_ID_HEADER',
  'leaseDuration': 'LEASE_DURATION',
  'leaseState': 'LEASE_STATE',

  'sequenceNumberHeader': 'SEQUENCE_NUMBER',

  'copyStatus': 'COPY_STATUS',
  'copyCompletionTime': 'COPY_COMPLETION_TIME',
  'copyStatusDescription': 'COPY_STATUS_DESCRIPTION',
  'copyId': 'COPY_ID',
  'copyProgress': 'COPY_PROGRESS',

  'requestId': 'REQUEST_ID_HEADER'
};

BlobResult.prototype.getPropertiesFromHeaders = function (headers) {
  var self = this;

  var setBlobPropertyFromHeaders = function (blobProperty, headerProperty) {
    if (!self[blobProperty] && headers[headerProperty.toLowerCase()]) {
      self[blobProperty] = headers[headerProperty.toLowerCase()];
    }
  };

  _.chain(headersForProperties).pairs().each(function (pair) {
    var property = pair[0];
    var header = HeaderConstants[pair[1]];
    setBlobPropertyFromHeaders(property, header);
  });
};

BlobResult.setHeadersFromBlob = function (webResource, blob) {
  var setHeaderPropertyFromBlob = function (headerProperty, blobProperty) {
    if (blob[blobProperty]) {
      webResource.withHeader(headerProperty, blob[blobProperty]);
    }
  };

  if (blob) {
    // Content-Type
    setHeaderPropertyFromBlob(HeaderConstants.CONTENT_TYPE_HEADER, 'contentTypeHeader');
    setHeaderPropertyFromBlob(HeaderConstants.CONTENT_TYPE_HEADER, 'contentType');
    setHeaderPropertyFromBlob(HeaderConstants.CONTENT_TYPE, 'contentType');

    // Content-Encoding
    setHeaderPropertyFromBlob(HeaderConstants.CONTENT_ENCODING_HEADER, 'contentEncodingHeader');
    setHeaderPropertyFromBlob(HeaderConstants.CONTENT_ENCODING_HEADER, 'contentEncoding');
    setHeaderPropertyFromBlob(HeaderConstants.CONTENT_ENCODING, 'contentEncoding');

    // Content-MD5
    setHeaderPropertyFromBlob(HeaderConstants.BLOB_CONTENT_MD5_HEADER, 'contentMD5Header');
    setHeaderPropertyFromBlob(HeaderConstants.BLOB_CONTENT_MD5_HEADER, 'contentMD5');
    setHeaderPropertyFromBlob(HeaderConstants.CONTENT_MD5, 'contentMD5');

    // Content-Language
    setHeaderPropertyFromBlob(HeaderConstants.CONTENT_LANGUAGE_HEADER, 'contentLanguageHeader');
    setHeaderPropertyFromBlob(HeaderConstants.CONTENT_LANGUAGE_HEADER, 'contentLanguage');
    setHeaderPropertyFromBlob(HeaderConstants.CONTENT_LANGUAGE, 'contentLanguage');

    // Cache-Control
    setHeaderPropertyFromBlob(HeaderConstants.CACHE_CONTROL_HEADER, 'cacheControlHeader');
    setHeaderPropertyFromBlob(HeaderConstants.CACHE_CONTROL_HEADER, 'cacheControl');
    setHeaderPropertyFromBlob(HeaderConstants.CACHE_CONTROL, 'cacheControl');

    // Content-Length
    setHeaderPropertyFromBlob(HeaderConstants.CONTENT_LENGTH_HEADER, 'contentLengthHeader');
    setHeaderPropertyFromBlob(HeaderConstants.CONTENT_LENGTH_HEADER, 'contentLength');
    setHeaderPropertyFromBlob(HeaderConstants.CONTENT_LENGTH, 'contentLength');

    // Range
    if (!azureutil.objectIsNull(blob.rangeStart)) {
      var range = 'bytes=' + blob.rangeStart + '-';

      if (!azureutil.objectIsNull(blob.rangeEnd)) {
        range += blob.rangeEnd;
      }

      webResource.withHeader(HeaderConstants.RANGE, range);
    }

    if (!azureutil.objectIsNull(blob.rangeStartHeader)) {
      var rangeHeader = 'bytes=' + blob.rangeStartHeader + '-';

      if (!azureutil.objectIsNull(blob.rangeEndHeader)) {
        rangeHeader += blob.rangeEndHeader;
      }

      webResource.withHeader(HeaderConstants.STORAGE_RANGE_HEADER, rangeHeader);
    }

    // Range get content-md5
    setHeaderPropertyFromBlob(HeaderConstants.RANGE_GET_CONTENT_MD5, 'rangeGetContentMd5');

    // Blob Type
    setHeaderPropertyFromBlob(HeaderConstants.BLOB_TYPE_HEADER, 'blobTypeHeader');
    setHeaderPropertyFromBlob(HeaderConstants.BLOB_TYPE_HEADER, 'blobType');

    // Lease id
    setHeaderPropertyFromBlob(HeaderConstants.LEASE_ID_HEADER, 'leaseId');

    // Sequence number
    setHeaderPropertyFromBlob(HeaderConstants.SEQUENCE_NUMBER, 'sequenceNumberHeader');
    setHeaderPropertyFromBlob('x-ms-sequence-number-action', 'sequenceNumberActionHeader');

    if (blob.metadata) {
      webResource.addOptionalMetadataHeaders(blob.metadata);
    }
  }
};

module.exports = BlobResult;


text:
export declare function compile(parts: string[]): (entry: any, value?: any) => any;
export declare function compileGet(path: string): (entry: any) => any;
export declare function compileSet(path: string): (entry: any, value: any) => void;


text:
package android.orm.remote.watch.executor;

import android.content.ContentResolver;
import android.net.Uri;
import android.orm.remote.Route;
import android.orm.remote.watch.Dispatcher;
import android.orm.remote.watch.Executor;
import android.orm.remote.watch.Observer;
import android.orm.util.Cancelable;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import org.jetbrains.annotations.NonNls;

import java.lang.annotation.Retention;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static java.lang.annotation.RetentionPolicy.SOURCE;

public abstract class DispatcherExecutor implements Executor {

    private static final long DEFAULT_REMOVAL_DELAY = 60;
    private static final TimeUnit DEFAULT_REMOVAL_DELAY_UNIT = TimeUnit.SECONDS;

    private final long mRemovalDelay;
    @NonNull
    private final TimeUnit mRemovalDelayUnit;

    protected DispatcherExecutor() {
        this(DEFAULT_REMOVAL_DELAY, DEFAULT_REMOVAL_DELAY_UNIT);
    }

    protected DispatcherExecutor(final long removalDelay,
                                 @NonNull final TimeUnit removalDelayUnit) {
        super();

        mRemovalDelay = removalDelay;
        mRemovalDelayUnit = removalDelayUnit;
    }

    @NonNull
    protected abstract Dispatcher get(@NonNull final ContentResolver resolver,
                                      @NonNull final Route route,
                                      @NonNull final Uri uri);

    protected abstract void stop(@NonNull final Dispatcher dispatcher,
                                 @NonNull final Route route,
                                 @NonNull final Uri uri);

    @NonNull
    @Override
    public final android.orm.remote.watch.Session session(@NonNull final ContentResolver resolver) {
        return new Session(this, resolver);
    }

    @NonNull
    private Cancelable submit(@NonNull final ContentResolver resolver,
                              @NonNull final Route route,
                              @NonNull final Uri uri,
                              @NonNull final Observer observer) {
        final Dispatcher dispatcher = get(resolver, route, uri);
        final Cancelable submission = dispatcher.submit(route, uri, observer);
        return new Cancelable() {
            @Override
            public void cancel() {
                submission.cancel();
                if (dispatcher.isEmpty()) {
                    scheduleRemoval(dispatcher, route, uri);
                }
            }
        };
    }

    private void scheduleRemoval(@NonNull final Dispatcher dispatcher,
                                 @NonNull final Route route,
                                 @NonNull final Uri uri) {
        dispatcher.schedule(mRemovalDelay, mRemovalDelayUnit, new Runnable() {
            @Override
            public void run() {
                if (dispatcher.isEmpty()) {
                    stop(dispatcher, route, uri);
                }
            }
        });
    }

    private static class Session implements android.orm.remote.watch.Session {

        @NonNls
        private static final String UNKNOWN_STATE = "Unknown state: ";

        @NonNull
        private final DispatcherExecutor mExecutor;
        @NonNull
        private final ContentResolver mResolver;

        private final Lock mLock = new ReentrantLock();
        private final Collection<Registration> mRegistrations = new ArrayList<>();
        @State
        private int mState = State.INITIALIZED;

        private Session(@NonNull final DispatcherExecutor executor,
                        @NonNull final ContentResolver resolver) {
            super();

            mExecutor = executor;
            mResolver = resolver;
        }

        @Override
        public final boolean isStarted() {
            final boolean result;

            mLock.lock();
            try {
                result = mState == State.STARTED;
            } finally {
                mLock.unlock();
            }

            return result;
        }

        @Override
        public final void start() {
            mLock.lock();
            try {
                switch (mState) {
                    case State.INITIALIZED:
                    case State.PAUSED:
                    case State.STOPPED:
                        for (final Registration registration : mRegistrations) {
                            registration.start();
                        }
                        mState = State.STARTED;
                        break;
                    case State.STARTED:
                            /* do nothing */
                        break;
                    default:
                        throw new UnsupportedOperationException(UNKNOWN_STATE + mState);
                }
            } finally {
                mLock.unlock();
            }
        }

        @Override
        public final void pause() {
            mLock.lock();
            try {
                switch (mState) {
                    case State.STARTED:
                        for (final Registration registration : mRegistrations) {
                            registration.stop();
                        }
                        mState = State.PAUSED;
                        break;
                    case State.INITIALIZED:
                    case State.PAUSED:
                    case State.STOPPED:
                            /* do nothing */
                        break;
                    default:
                        throw new UnsupportedOperationException(UNKNOWN_STATE + mState);
                }
            } finally {
                mLock.unlock();
            }
        }

        @Override
        public final void stop() {
            mLock.lock();
            try {
                switch (mState) {
                    case State.STARTED:
                    case State.INITIALIZED:
                    case State.PAUSED:
                        for (final Registration registration : mRegistrations) {
                            registration.stop();
                        }
                        mRegistrations.clear();
                        mState = State.STOPPED;
                        break;
                    case State.STOPPED:
                            /* do nothing */
                        break;
                    default:
                        throw new UnsupportedOperationException(UNKNOWN_STATE + mState);
                }
            } finally {
                mLock.unlock();
            }
        }

        @NonNull
        @Override
        public final Cancelable submit(@NonNull final Route route,
                                       @NonNull final Uri uri,
                                       @NonNull final Observer observer) {
            final Cancelable cancelable;

            mLock.lock();
            try {
                final Registration registration = new Registration(mExecutor, mResolver, route, uri, observer);
                if (mState == State.STARTED) {
                    registration.start();
                }
                mRegistrations.add(registration);

                cancelable = new Cancelable() {
                    @Override
                    public void cancel() {
                        mLock.lock();
                        try {
                            registration.stop();
                            mRegistrations.remove(registration);
                        } finally {
                            mLock.unlock();
                        }
                    }
                };
            } finally {
                mLock.unlock();
            }

            return cancelable;
        }

        @Retention(SOURCE)
        @IntDef({State.INITIALIZED, State.STARTED, State.PAUSED, State.STOPPED})
        private @interface State {
            int INITIALIZED = 0;
            int STARTED = 1;
            int PAUSED = 2;
            int STOPPED = 3;
        }
    }

    private static class Registration {

        @NonNull
        private final DispatcherExecutor mExecutor;
        @NonNull
        private final ContentResolver mResolver;
        @NonNull
        private final Route mRoute;
        @NonNull
        private final Uri mUri;
        @NonNull
        private final Observer mObserver;

        @Nullable
        private Cancelable mCancelable;

        private Registration(@NonNull final DispatcherExecutor executor,
                             @NonNull final ContentResolver resolver,
                             @NonNull final Route route,
                             @NonNull final Uri uri,
                             @NonNull final Observer observer) {
            super();

            mExecutor = executor;
            mResolver = resolver;
            mRoute = route;
            mUri = uri;
            mObserver = observer;
        }

        public final void start() {
            if (mCancelable != null) {
                mCancelable.cancel();
            }

            mCancelable = mExecutor.submit(mResolver, mRoute, mUri, mObserver);
        }

        public final void stop() {
            if (mCancelable != null) {
                mCancelable.cancel();
                mCancelable = null;
            }
        }
    }
}


text:
/*	$NetBSD: profileio.h,v 1.1 2002/02/10 01:57:37 thorpej Exp $	*/

/*
 * Copyright 1997
 * Digital Equipment Corporation. All rights reserved.
 *
 * This software is furnished under license and may be used and
 * copied only in accordance with the following terms and conditions.
 * Subject to these conditions, you may download, copy, install,
 * use, modify and distribute this software in source and/or binary
 * form. No title or ownership is transferred hereby.
 *
 * 1) Any source code used, modified or distributed must reproduce
 *    and retain this copyright notice and list of conditions as
 *    they appear in the source file.
 *
 * 2) No right is granted to use any trade name, trademark, or logo of
 *    Digital Equipment Corporation. Neither the "Digital Equipment
 *    Corporation" name nor any trademark or logo of Digital Equipment
 *    Corporation may be used to endorse or promote products derived
 *    from this software without the prior written permission of
 *    Digital Equipment Corporation.
 *
 * 3) This software is provided "AS-IS" and any express or implied
 *    warranties, including but not limited to, any implied warranties
 *    of merchantability, fitness for a particular purpose, or
 *    non-infringement are disclaimed. In no event shall DIGITAL be
 *    liable for any damages whatsoever, and in particular, DIGITAL
 *    shall not be liable for special, indirect, consequential, or
 *    incidental damages or damages for lost profits, loss of
 *    revenue or loss of use, whether such damages arise in contract,
 *    negligence, tort, under statute, in equity, at law or otherwise,
 *    even if advised of the possibility of such damage.
 */

/*
 * Remote profiler structures used to communicate between the
 * target (SHARK) and the host (GUI'd) machine.
 * Also has stuff used to talk between the profiling driver and
 * profiling server function.
 *
 */

#ifndef __PROFILE_IO_H__
#define __PROFILE_IO_H__

#include <sys/types.h>

/* I have no idea what the 'P' group id means,
 * I presume it isn't used for much.??
 */
#define PROFIOSTART	_IOWR('P', 0, struct profStartInfo) /* start profiling */
#define PROFIOSTOP	_IO('P', 1)	/* stop profiling  */

/* hash table stuff.
 */
#define TABLE_ENTRY_SIZE (sizeof(struct hashEntry))
#define REDUNDANT_BITS   0x02
#define COUNT_BITS       0x02
#define COUNT_BIT_MASK   0x03

/* sample mode flags.
 */
#define SAMPLE_MODE_MASK 0x03
#define SAMPLE_PROC      0x01
#define SAMPLE_KERN      0x02

/* an actual entry
 */
struct profHashEntry
{
    unsigned int pc;          /* the pc, minus any redundant bits. */
    unsigned int next;        /* the next pointer as an entry index */
    unsigned short counts[4]; /* the counts */
};

/* table header.
 */
struct profHashHeader
{
    unsigned int tableSize;     /* total table size in entries */
    unsigned int entries;       /* first level table size, in entries */
    unsigned int samples;       /* the number of samples in the table. */
    unsigned int missed;        /* the number of samples missed. */
    unsigned int fiqs;          /* the number of fiqs. */
    unsigned int last;          /* last entry in the overflow area */
    pid_t pid;                  /* The pid being sampled */
    int mode;                   /* kernel or user mode */
}
__attribute__ ((packed));

/* actual table
 */
struct profHashTable
{
    struct profHashHeader hdr;
    struct profHashEntry *entries;
};

/* information passed to the start/stop ioctl.
 */
struct profStartInfo
{
    pid_t pid;                  /* if this is -1 sample no processes */
    unsigned int tableSize;     /* the total table size in entries */
    unsigned int entries;       /* number of entries to hash */
    unsigned int mode;          /* if set profile the kernel */
    int status;                 /* status of command returned by driver. */
};

/* Communications Protocol stuff
 * defines the messages that the host and
 * target will use to communicate.
 */

struct packetHeader
{
    int code;        /* this will either be a command or a
				* data specifier.
				*/
    unsigned int size;         /* size of data to follow,
				* quantity depends on code.
				*/
}
__attribute__ ((packed));

struct startSamplingCommand
{
    pid_t pid;              /* the pid to sample */
    unsigned int tableSize; /* the total table size in entries */
    unsigned int entries;   /* number of entries to hash */
    unsigned int mode;     /* if set profile kernel also. */
}
__attribute__ ((packed));

struct startSamplingResponse
{
    int status;          /* identifies the status of the command. */
    int count;           /* number of shared lib entries following. */
}
__attribute__ ((packed));

struct stopSamplingCommand
{
    int alert;          /* if set then the daemon sends a SIGINT to
			 * the process.
			 */
}
__attribute__ ((packed));

struct disassemble
{
    unsigned int offset; /* offset into file to begin disassembling */
    unsigned int length; /* length in arm words ie 32bits. */
}
__attribute__ ((packed));

struct profStatus
{
    unsigned int status;    /* identifies the status. */
}
__attribute__ ((packed));

/* Command/Data Types
 * Only one bit may be set for any one command.
 * so these are not masks but distinct values.
 */
#define START_SAMPLING 0x01
#define STOP_SAMPLING  0x02
#define READ_TABLE     0x03
#define DISASSEMBLY    0x04
#define SYMBOL_INFO    0x05
#define PROCESS_INFO   0x06

/* Data Types */
#define TABLE_DATA     0x07
#define SYMBOL_DATA    0x08
#define DISAS_DATA     0x09
#define PROC_DATA      0x0a
#define STATUS_DATA    0x0b
#define START_DATA     0x0c

/* Status Codes */
#define CMD_OK           0x00
#define ALREADY_SAMPLING 0x01
#define NOT_SAMPLING     0x02
#define NO_MEMORY        0x03
#define BAD_TABLE_SIZE   0x04
#define ILLEGAL_PACKET   0x05
#define ILLEGAL_COMMAND  0x06
#define BAD_OPTION       0x07

#endif


text:
<?php

namespace app\modules\user\controllers\frontend;

use app\modules\user\forms\frontend\EmailConfirmForm;
use app\modules\user\forms\LoginForm;
use app\modules\user\models\User;
use app\modules\user\forms\frontend\PasswordResetRequestForm;
use app\modules\user\forms\frontend\PasswordResetForm;
use app\modules\user\forms\frontend\SignupForm;
use yii\base\InvalidParamException;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use Yii;

class DefaultController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['signup'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    public function actions()
    {
        return [
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public function actionIndex()
    {
        return $this->redirect(['profile/index'], 301);
    }

    public function actionLogin()
    {
        $this->layout = "@app/modules/main/views/layouts/frontend/main";
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->redirect(['/user/profile/index']);
            // return $this->goBack();
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    public function actionSignup()
    {
        $this->layout = "@app/modules/main/views/layouts/frontend/main";
        $model = new SignupForm($this->module->defaultRole);
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                Yii::$app->getSession()->setFlash('success', Yii::t('app', 'FLASH_EMAIL_CONFIRM_REQUEST'));
                return $this->goHome();
            }
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }

    public function actionEmailConfirm($token)
    {
        try {
            $model = new EmailConfirmForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->confirmEmail()) {
            Yii::$app->getSession()->setFlash('success', Yii::t('app', 'EMAIL_SUBMIT_SUCCESS'));
        } else {
            Yii::$app->getSession()->setFlash('error', Yii::t('app', 'EMAIL_SUBMIT_ERROR'));
        }

        return $this->goHome();
    }

    public function actionPasswordResetRequest()
    {
        $this->layout = "@app/modules/main/views/layouts/frontend/main";
        $model = new PasswordResetRequestForm($this->module->passwordResetTokenExpire);
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->getSession()->setFlash('success', Yii::t('app', 'FLASH_PASSWORD_RESET_REQUEST'));
                return $this->goHome();
            } else {
                Yii::$app->getSession()->setFlash('error', Yii::t('app', 'FLASH_PASSWORD_RESET_ERROR'));
            }
        }
        return $this->render('passwordResetRequest', [
            'model' => $model,
        ]);
    }

    public function actionPasswordReset($token)
    {
        try {
            $model = new PasswordResetForm($token, $this->module->passwordResetTokenExpire);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->getSession()->setFlash('success', Yii::t('app', 'FLASH_PASSWORD_RESET_SUCCESS'));
            return $this->goHome();
        }
        return $this->render('passwordReset', [
            'model' => $model,
        ]);
    }
}


text:
{% extends "../layout.html" %} {% block content %}

      BETA
      This is a new service – your feedback will help us to improve it.

      {% include "includes/validation-error-messages.html" %}

      <form class="form" method="post">

Sign in

Sign in using your username and password

          Username
          <input class="form-control" id="customer-reference" type="text" name="reference">

          Password
          <input class="form-control" id="password" type="password" name="password">

          <button class="button" type="submit">Continue</button>

      </form>

{% endblock %}