text:
package main

import (
	"bytes"
	"context"
	"crypto/tls"
	"flag"
	"fmt"
	"hash/crc32"
	"image"
	"image/jpeg"
	"io"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"path"
	"regexp"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"time"

	"cloud.google.com/go/storage"
	"go4.org/syncutil/singleflight"
	"golang.org/x/build/autocertcache"
	"golang.org/x/crypto/acme/autocert"
	"golang.org/x/net/http2"
)

var (
	prod = flag.Bool("prod", false, "Whether to configure itself to be the production http2.golang.org server.")

	httpsAddr = flag.String("https_addr", "localhost:4430", "TLS address to listen on ('host:port' or ':port'). Required.")
	httpAddr  = flag.String("http_addr", "", "Plain HTTP address to listen on ('host:port', or ':port'). Empty means no HTTP.")

	hostHTTP  = flag.String("http_host", "", "Optional host or host:port to use for http:// links to this service. By default, this is implied from -http_addr.")
	hostHTTPS = flag.String("https_host", "", "Optional host or host:port to use for http:// links to this service. By default, this is implied from -https_addr.")
)

func homeOldHTTP(w http.ResponseWriter, r *http.Request) {
	if r.Host == "http1.golang.org" {
		http.Redirect(w, r, "https://http2.golang.org/", http.StatusFound)
		return
	}
	io.WriteString(w, `

Go + HTTP/2

Welcome to the Go language's HTTP/2 demo & interop server.

Unfortunately, you're not using HTTP/2 right now. To do so:

Use Firefox Nightly or go to about:config and enable "network.http.spdy.enabled.http2draft"

Use Google Chrome Canary and/or go to chrome://flags/#enable-spdy4 to Enable SPDY/4 (Chrome's name for HTTP/2)

See code & instructions for connecting at https://github.com/golang/net/tree/master/http2.

`)
}

func home(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}
	io.WriteString(w, `

Go + HTTP/2

Welcome to the Go language's HTTP/2 demo & interop server.

Congratulations, you're using HTTP/2 right now.

This server exists for others in the HTTP/2 community to test their HTTP/2 client implementations and point out flaws in our server.

The code is at golang.org/x/net/http2 and
is used transparently by the Go standard library from Go 1.6 and later.

Contact info: bradfitz@golang.org, or file a bug.

Handlers for testing

GET /reqinfo to dump the request + headers received

GET /clockstream streams the current time every second

GET /gophertiles to see a page with a bunch of images

GET /serverpush to see a page with server push

GET /file/gopher.png for a small file (does If-Modified-Since, Content-Range, etc)

GET /file/go.src.tar.gz for a larger file (~10 MB)

GET /redirect to redirect back to / (this page)

GET /goroutines to see all active goroutines in this server

PUT something to /crc32 to get a count of number of bytes and its CRC-32

PUT something to /ECHO and it will be streamed back to you capitalized

`)
}

func reqInfoHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain")
	fmt.Fprintf(w, "Method: %s\n", r.Method)
	fmt.Fprintf(w, "Protocol: %s\n", r.Proto)
	fmt.Fprintf(w, "Host: %s\n", r.Host)
	fmt.Fprintf(w, "RemoteAddr: %s\n", r.RemoteAddr)
	fmt.Fprintf(w, "RequestURI: %q\n", r.RequestURI)
	fmt.Fprintf(w, "URL: %#v\n", r.URL)
	fmt.Fprintf(w, "Body.ContentLength: %d (-1 means unknown)\n", r.ContentLength)
	fmt.Fprintf(w, "Close: %v (relevant for HTTP/1 only)\n", r.Close)
	fmt.Fprintf(w, "TLS: %#v\n", r.TLS)
	fmt.Fprintf(w, "\nHeaders:\n")
	r.Header.Write(w)
}

func crcHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "PUT" {
		http.Error(w, "PUT required.", 400)
		return
	}
	crc := crc32.NewIEEE()
	n, err := io.Copy(crc, r.Body)
	if err == nil {
		w.Header().Set("Content-Type", "text/plain")
		fmt.Fprintf(w, "bytes=%d, CRC32=%x", n, crc.Sum(nil))
	}
}

type capitalizeReader struct {
	r io.Reader
}

func (cr capitalizeReader) Read(p []byte) (n int, err error) {
	n, err = cr.r.Read(p)
	for i, b := range p[:n] {
		if b >= 'a' && b <= 'z' {
			p[i] = b - ('a' - 'A')
		}
	}
	return
}

type flushWriter struct {
	w io.Writer
}

func (fw flushWriter) Write(p []byte) (n int, err error) {
	n, err = fw.w.Write(p)
	if f, ok := fw.w.(http.Flusher); ok {
		f.Flush()
	}
	return
}

func echoCapitalHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "PUT" {
		http.Error(w, "PUT required.", 400)
		return
	}
	if f, ok := w.(http.Flusher); ok {
		f.Flush()
	}
	io.Copy(flushWriter{w}, capitalizeReader{r.Body})
}

var (
	fsGrp   singleflight.Group
	fsMu    sync.Mutex // guards fsCache
	fsCache = map[string]http.Handler{}
)

// fileServer returns a file-serving handler that proxies URL.
// It lazily fetches URL on the first access and caches its contents forever.
func fileServer(url string, latency time.Duration) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if latency > 0 {
			time.Sleep(latency)
		}
		hi, err := fsGrp.Do(url, func() (interface{}, error) {
			fsMu.Lock()
			if h, ok := fsCache[url]; ok {
				fsMu.Unlock()
				return h, nil
			}
			fsMu.Unlock()

			res, err := http.Get(url)
			if err != nil {
				return nil, err
			}
			defer res.Body.Close()
			slurp, err := ioutil.ReadAll(res.Body)
			if err != nil {
				return nil, err
			}

			modTime := time.Now()
			var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				http.ServeContent(w, r, path.Base(url), modTime, bytes.NewReader(slurp))
			})
			fsMu.Lock()
			fsCache[url] = h
			fsMu.Unlock()
			return h, nil
		})
		if err != nil {
			http.Error(w, err.Error(), 500)
			return
		}
		hi.(http.Handler).ServeHTTP(w, r)
	})
}

func clockStreamHandler(w http.ResponseWriter, r *http.Request) {
	clientGone := w.(http.CloseNotifier).CloseNotify()
	w.Header().Set("Content-Type", "text/plain")
	ticker := time.NewTicker(1 * time.Second)
	defer ticker.Stop()
	fmt.Fprintf(w, "# ~1KB of junk to force browsers to start rendering immediately: \n")
	io.WriteString(w, strings.Repeat("# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n", 13))

	for {
		fmt.Fprintf(w, "%v\n", time.Now())
		w.(http.Flusher).Flush()
		select {
		case <-ticker.C:
		case <-clientGone:
			log.Printf("Client %v disconnected from the clock", r.RemoteAddr)
			return
		}
	}
}

func registerHandlers() {
	tiles := newGopherTilesHandler()
	push := newPushHandler()

	mux2 := http.NewServeMux()
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.URL.Path == "/gophertiles":
			tiles.ServeHTTP(w, r) // allow HTTP/2 + HTTP/1.x
			return
		case strings.HasPrefix(r.URL.Path, "/serverpush"):
			push.ServeHTTP(w, r) // allow HTTP/2 + HTTP/1.x
			return
		case r.TLS == nil: // do not allow HTTP/1.x for anything else
			http.Redirect(w, r, "https://"+httpsHost()+"/", http.StatusFound)
			return
		}
		if r.ProtoMajor == 1 {
			if r.URL.Path == "/reqinfo" {
				reqInfoHandler(w, r)
				return
			}
			homeOldHTTP(w, r)
			return
		}
		mux2.ServeHTTP(w, r)
	})
	mux2.HandleFunc("/", home)
	mux2.Handle("/file/gopher.png", fileServer("https://golang.org/doc/gopher/frontpage.png", 0))
	mux2.Handle("/file/go.src.tar.gz", fileServer("https://storage.googleapis.com/golang/go1.4.1.src.tar.gz", 0))
	mux2.HandleFunc("/reqinfo", reqInfoHandler)
	mux2.HandleFunc("/crc32", crcHandler)
	mux2.HandleFunc("/ECHO", echoCapitalHandler)
	mux2.HandleFunc("/clockstream", clockStreamHandler)
	mux2.Handle("/gophertiles", tiles)
	mux2.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) {
		http.Redirect(w, r, "/", http.StatusFound)
	})
	stripHomedir := regexp.MustCompile(`/(Users|home)/\w+`)
	mux2.HandleFunc("/goroutines", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		buf := make([]byte, 2<<20)
		w.Write(stripHomedir.ReplaceAll(buf[:runtime.Stack(buf, true)], nil))
	})
}

var pushResources = map[string]http.Handler{
	"/serverpush/static/jquery.min.js": fileServer("https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js", 100*time.Millisecond),
	"/serverpush/static/godocs.js":     fileServer("https://golang.org/lib/godoc/godocs.js", 100*time.Millisecond),
	"/serverpush/static/playground.js": fileServer("https://golang.org/lib/godoc/playground.js", 100*time.Millisecond),
	"/serverpush/static/style.css":     fileServer("https://golang.org/lib/godoc/style.css", 100*time.Millisecond),
}

func newPushHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		for path, handler := range pushResources {
			if r.URL.Path == path {
				handler.ServeHTTP(w, r)
				return
			}
		}

		cacheBust := time.Now().UnixNano()
		if pusher, ok := w.(http.Pusher); ok {
			for path := range pushResources {
				url := fmt.Sprintf("%s?%d", path, cacheBust)
				if err := pusher.Push(url, nil); err != nil {
					log.Printf("Failed to push %v: %v", path, err)
				}
			}
		}
		time.Sleep(100 * time.Millisecond) // fake network latency + parsing time
		if err := pushTmpl.Execute(w, struct {
			CacheBust   int64
			HTTPSHost   string
			HTTP1Prefix string
		}{
			CacheBust:   cacheBust,
			HTTPSHost:   httpsHost(),
			HTTP1Prefix: http1Prefix(),
		}); err != nil {
			log.Printf("Executing server push template: %v", err)
		}
	})
}

func newGopherTilesHandler() http.Handler {
	const gopherURL = "https://blog.golang.org/go-programming-language-turns-two_gophers.jpg"
	res, err := http.Get(gopherURL)
	if err != nil {
		log.Fatal(err)
	}
	if res.StatusCode != 200 {
		log.Fatalf("Error fetching %s: %v", gopherURL, res.Status)
	}
	slurp, err := ioutil.ReadAll(res.Body)
	res.Body.Close()
	if err != nil {
		log.Fatal(err)
	}
	im, err := jpeg.Decode(bytes.NewReader(slurp))
	if err != nil {
		if len(slurp) > 1024 {
			slurp = slurp[:1024]
		}
		log.Fatalf("Failed to decode gopher image: %v (got %q)", err, slurp)
	}

	type subImager interface {
		SubImage(image.Rectangle) image.Image
	}
	const tileSize = 32
	xt := im.Bounds().Max.X / tileSize
	yt := im.Bounds().Max.Y / tileSize
	var tile [][][]byte // y -> x -> jpeg bytes
	for yi := 0; yi < yt; yi++ {
		var row [][]byte
		for xi := 0; xi < xt; xi++ {
			si := im.(subImager).SubImage(image.Rectangle{
				Min: image.Point{xi * tileSize, yi * tileSize},
				Max: image.Point{(xi + 1) * tileSize, (yi + 1) * tileSize},
			})
			buf := new(bytes.Buffer)
			if err := jpeg.Encode(buf, si, &jpeg.Options{Quality: 90}); err != nil {
				log.Fatal(err)
			}
			row = append(row, buf.Bytes())
		}
		tile = append(tile, row)
	}
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ms, _ := strconv.Atoi(r.FormValue("latency"))
		const nanosPerMilli = 1e6
		if r.FormValue("x") != "" {
			x, _ := strconv.Atoi(r.FormValue("x"))
			y, _ := strconv.Atoi(r.FormValue("y"))
			if ms <= 1000 {
				time.Sleep(time.Duration(ms) * nanosPerMilli)
			}
			if x >= 0 && x < xt && y >= 0 && y < yt {
				http.ServeContent(w, r, "", time.Time{}, bytes.NewReader(tile[y][x]))
				return
			}
		}
		io.WriteString(w, "")
		fmt.Fprintf(w, "A grid of %d tiled images is below. Compare:
", xt*yt)
		for _, ms := range []int{0, 30, 200, 1000} {
			d := time.Duration(ms) * nanosPerMilli
			fmt.Fprintf(w, "[HTTP/2, %v latency] [HTTP/1, %v latency]
\n",
				httpsHost(), ms, d,
				http1Prefix(), ms, d,
			)
		}
		io.WriteString(w, "
\n")
		cacheBust := time.Now().UnixNano()
		for y := 0; y < yt; y++ {
			for x := 0; x < xt; x++ {
				fmt.Fprintf(w, "",
					tileSize, tileSize, x, y, cacheBust, ms)
			}
			io.WriteString(w, "
\n")
		}
		io.WriteString(w, `

<&lt Back to Go HTTP/2 demo server`)
	})
}

func httpsHost() string {
	if *hostHTTPS != "" {
		return *hostHTTPS
	}
	if v := *httpsAddr; strings.HasPrefix(v, ":") {
		return "localhost" + v
	} else {
		return v
	}
}

func http1Prefix() string {
	if *prod {
		return "https://http1.golang.org"
	}
	return "http://" + httpHost()
}

func httpHost() string {
	if *hostHTTP != "" {
		return *hostHTTP
	}
	if v := *httpAddr; strings.HasPrefix(v, ":") {
		return "localhost" + v
	} else {
		return v
	}
}

func serveProdTLS(autocertManager *autocert.Manager) error {
	srv := &http.Server{
		TLSConfig: &tls.Config{
			GetCertificate: autocertManager.GetCertificate,
			GetConfigForClient: func(hello *tls.ClientHelloInfo) (*tls.Config, error) {
				if hello.ServerName == "http1.golang.org" {
					return &tls.Config{
						GetCertificate: autocertManager.GetCertificate,
					}, nil
				}
				return nil, nil // fallback to other methods
			},
		},
	}
	http2.ConfigureServer(srv, &http2.Server{
		NewWriteScheduler: func() http2.WriteScheduler {
			return http2.NewPriorityWriteScheduler(nil)
		},
	})
	ln, err := net.Listen("tcp", ":443")
	if err != nil {
		return err
	}
	return srv.Serve(tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, srv.TLSConfig))
}

type tcpKeepAliveListener struct {
	*net.TCPListener
}

func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
	tc, err := ln.AcceptTCP()
	if err != nil {
		return
	}
	tc.SetKeepAlive(true)
	tc.SetKeepAlivePeriod(3 * time.Minute)
	return tc, nil
}

func serveProd() error {
	log.Printf("running in production mode.")

	storageClient, err := storage.NewClient(context.Background())
	if err != nil {
		log.Fatalf("storage.NewClient: %v", err)
	}
	autocertManager := &autocert.Manager{
		Prompt:     autocert.AcceptTOS,
		HostPolicy: autocert.HostWhitelist("http1.golang.org", "http2.golang.org"),
		Cache:      autocertcache.NewGoogleCloudStorageCache(storageClient, "golang-h2demo-autocert"),
	}

	errc := make(chan error, 2)
	go func() { errc <- http.ListenAndServe(":80", autocertManager.HTTPHandler(http.DefaultServeMux)) }()
	go func() { errc <- serveProdTLS(autocertManager) }()
	return <-errc
}

const idleTimeout = 5 * time.Minute
const activeTimeout = 10 * time.Minute

// TODO: put this into the standard library and actually send
// PING frames and GOAWAY, etc: golang.org/issue/14204
func idleTimeoutHook() func(net.Conn, http.ConnState) {
	var mu sync.Mutex
	m := map[net.Conn]*time.Timer{}
	return func(c net.Conn, cs http.ConnState) {
		mu.Lock()
		defer mu.Unlock()
		if t, ok := m[c]; ok {
			delete(m, c)
			t.Stop()
		}
		var d time.Duration
		switch cs {
		case http.StateNew, http.StateIdle:
			d = idleTimeout
		case http.StateActive:
			d = activeTimeout
		default:
			return
		}
		m[c] = time.AfterFunc(d, func() {
			log.Printf("closing idle conn %v after %v", c.RemoteAddr(), d)
			go c.Close()
		})
	}
}

func main() {
	var srv http.Server
	flag.BoolVar(&http2.VerboseLogs, "verbose", false, "Verbose HTTP/2 debugging.")
	flag.Parse()
	srv.Addr = *httpsAddr
	srv.ConnState = idleTimeoutHook()

	registerHandlers()

	if *prod {
		*hostHTTP = "http2.golang.org"
		*hostHTTPS = "http2.golang.org"
		log.Fatal(serveProd())
	}

	url := "https://" + httpsHost() + "/"
	log.Printf("Listening on " + url)
	http2.ConfigureServer(&srv, &http2.Server{})

	if *httpAddr != "" {
		go func() {
			log.Printf("Listening on http://" + httpHost() + "/ (for unencrypted HTTP/1)")
			log.Fatal(http.ListenAndServe(*httpAddr, nil))
		}()
	}

	go func() {
		log.Fatal(srv.ListenAndServeTLS("server.crt", "server.key"))
	}()
	select {}
}


text:
namespace ozonewayland {

const int kCursorNull = 0;
const int kCursorPointer = 1;
const int kCursorCross = 2;
const int kCursorHand = 3;
const int kCursorIBeam = 4;
const int kCursorWait = 5;
const int kCursorHelp = 6;
const int kCursorEastResize = 7;
const int kCursorNorthResize = 8;
const int kCursorNorthEastResize = 9;
const int kCursorNorthWestResize = 10;
const int kCursorSouthResize = 11;
const int kCursorSouthEastResize = 12;
const int kCursorSouthWestResize = 13;
const int kCursorWestResize = 14;
const int kCursorNorthSouthResize = 15;
const int kCursorEastWestResize = 16;
const int kCursorNorthEastSouthWestResize = 17;
const int kCursorNorthWestSouthEastResize = 18;
const int kCursorColumnResize = 19;
const int kCursorRowResize = 20;
const int kCursorMiddlePanning = 21;
const int kCursorEastPanning = 22;
const int kCursorNorthPanning = 23;
const int kCursorNorthEastPanning = 24;
const int kCursorNorthWestPanning = 25;
const int kCursorSouthPanning = 26;
const int kCursorSouthEastPanning = 27;
const int kCursorSouthWestPanning = 28;
const int kCursorWestPanning = 29;
const int kCursorMove = 30;
const int kCursorVerticalText = 31;
const int kCursorCell = 32;
const int kCursorContextMenu = 33;
const int kCursorAlias = 34;
const int kCursorProgress = 35;
const int kCursorNoDrop = 36;
const int kCursorCopy = 37;
const int kCursorNone = 38;
const int kCursorNotAllowed = 39;
const int kCursorZoomIn = 40;
const int kCursorZoomOut = 41;
const int kCursorGrab = 42;
const int kCursorGrabbing = 43;
const int kCursorCustom = 44;

// Returns Wayland font cursor shape from an Aura cursor.
WaylandCursor::CursorType CursorShapeFromNative(unsigned cursor_type) {
  switch (cursor_type) {
    case kCursorMiddlePanning:
    case kCursorMove:
      return WaylandCursor::CURSOR_FLEUR;
    case kCursorEastPanning:
      return WaylandCursor::CURSOR_RIGHT;
    case kCursorNorthPanning:
      return WaylandCursor::CURSOR_UP_ARROW;
    case kCursorNorthEastPanning:
      return WaylandCursor::CURSOR_TOP_RIGHT;
    case kCursorNorthWestPanning:
      return WaylandCursor::CURSOR_TOP_LEFT;
    case kCursorSouthPanning:
      return WaylandCursor::CURSOR_BOTTOM;
    case kCursorSouthEastPanning:
    case kCursorSouthEastResize:
      return WaylandCursor::CURSOR_BOTTOM_RIGHT;
    case kCursorSouthWestPanning:
    case kCursorSouthWestResize:
      return WaylandCursor::CURSOR_BOTTOM_LEFT;
    case kCursorWestPanning:
      return WaylandCursor::CURSOR_LEFT_ARROW;
    case kCursorNone:
    case kCursorNull:
    case kCursorPointer:
    // TODO(kalyan): Choose right cursor types.
    case kCursorGrab:
    case kCursorGrabbing:
      return WaylandCursor::CURSOR_LEFT_PTR;
    case kCursorCross:
      return WaylandCursor::CURSOR_CROSS;
    case kCursorHand:
      return WaylandCursor::CURSOR_HAND1;
    case kCursorIBeam:
      return WaylandCursor::CURSOR_IBEAM;
    case kCursorProgress:
      return WaylandCursor::CURSOR_WATCH;
    case kCursorWait:
      return WaylandCursor::CURSOR_WAIT;
    case kCursorHelp:
      return WaylandCursor::CURSOR_QUESTION_ARROW;
    case kCursorEastResize:
      return WaylandCursor::CURSOR_RIGHT;
    case kCursorNorthResize:
      return WaylandCursor::CURSOR_TOP;
    case kCursorNorthEastResize:
      return WaylandCursor::CURSOR_TOP_RIGHT;
    case kCursorNorthWestResize:
      return WaylandCursor::CURSOR_TOP_LEFT_ARROW;
    case kCursorSouthResize:
      return WaylandCursor::CURSOR_BOTTOM;
    case kCursorWestResize:
      return WaylandCursor::CURSOR_LEFT;
    case kCursorNorthSouthResize:
    case kCursorRowResize:
      return WaylandCursor::CURSOR_V_DOUBLE_ARROW;
    case kCursorEastWestResize:
    case kCursorColumnResize:
      return WaylandCursor::CURSOR_H_DOUBLE_ARROW;
    case kCursorCustom:
      NOTREACHED();
      return WaylandCursor::CURSOR_DEFAULT;
  }
  NOTREACHED() << "Case not handled for " << cursor_type;
  return WaylandCursor::CURSOR_LEFT_PTR;
}

WaylandInputDevice::WaylandInputDevice(WaylandDisplay* display,
                                       uint32_t id)
    : focused_window_handle_(0),
      grab_window_handle_(0),
      grab_button_(0),
      input_seat_(NULL),
      input_keyboard_(NULL),
      input_pointer_(NULL),
      input_touch_(NULL),
      text_input_(NULL) {
  ui::IMEStateChangeHandler::SetInstance(this);
  static const struct wl_seat_listener kInputSeatListener = {
    WaylandInputDevice::OnSeatCapabilities,
  };

  input_seat_ = static_cast<wl_seat*>(
      wl_registry_bind(display->registry(), id, &wl_seat_interface, 1));
  DCHECK(input_seat_);
  wl_seat_add_listener(input_seat_, &kInputSeatListener, this);
  wl_seat_set_user_data(input_seat_, this);
  text_input_ = new WaylandTextInput(this);
}

WaylandInputDevice::~WaylandInputDevice() {
  delete input_keyboard_;
  delete input_pointer_;
  delete text_input_;
  if (input_touch_ != NULL) {
    delete input_touch_;
  }
  wl_seat_destroy(input_seat_);
}

void WaylandInputDevice::OnSeatCapabilities(void *data,
                                            wl_seat *seat,
                                            uint32_t caps) {
  WaylandInputDevice* device = static_cast<WaylandInputDevice*>(data);
  if ((caps & WL_SEAT_CAPABILITY_KEYBOARD) && !device->input_keyboard_) {
    device->input_keyboard_ = new WaylandKeyboard();
    device->input_keyboard_->OnSeatCapabilities(seat, caps);
  } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD) && device->input_keyboard_) {
    device->input_keyboard_->OnSeatCapabilities(seat, caps);
    delete device->input_keyboard_;
    device->input_keyboard_ = NULL;
  }

  if ((caps & WL_SEAT_CAPABILITY_POINTER) && !device->input_pointer_) {
    device->input_pointer_ = new WaylandPointer();
    device->input_pointer_->OnSeatCapabilities(seat, caps);
  } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && device->input_pointer_) {
    device->input_pointer_->OnSeatCapabilities(seat, caps);
    delete device->input_pointer_;
    device->input_pointer_ = NULL;
  }

  if ((caps & WL_SEAT_CAPABILITY_TOUCH) && !device->input_touch_) {
    device->input_touch_ = new WaylandTouchscreen();
    device->input_touch_->OnSeatCapabilities(seat, caps);
  } else if (!(caps & WL_SEAT_CAPABILITY_TOUCH) && device->input_touch_) {
    delete device->input_touch_;
    device->input_touch_ = NULL;
  }
}

void WaylandInputDevice::SetFocusWindowHandle(unsigned windowhandle) {
  focused_window_handle_ = windowhandle;
  WaylandWindow* window = NULL;
  if (windowhandle)
    window = WaylandDisplay::GetInstance()->GetWindow(windowhandle);
  text_input_->SetActiveWindow(window);
}

void WaylandInputDevice::SetGrabWindowHandle(unsigned windowhandle,
                                             uint32_t button) {
  grab_window_handle_ = windowhandle;
  grab_button_ = button;
}

void WaylandInputDevice::SetCursorType(int cursor_type) {
  if (!input_pointer_) {
    LOG(WARNING) << "Tried to change cursor without input configured";
    return;
  }
  input_pointer_->Cursor()->Update(CursorShapeFromNative(cursor_type),
                                   WaylandDisplay::GetInstance()->GetSerial());
}

void WaylandInputDevice::ResetIme() {
  text_input_->ResetIme();
}

void WaylandInputDevice::ImeCaretBoundsChanged(gfx::Rect rect) {
  NOTIMPLEMENTED();
}

void WaylandInputDevice::ShowInputPanel() {
  text_input_->ShowInputPanel(input_seat_);
}

void WaylandInputDevice::HideInputPanel() {
  text_input_->HideInputPanel(input_seat_);
}

}  // namespace ozonewayland

redpajama_set_name: RedPajamaGithub


text:
Grid Extension
==============

Overview
--------

Filter bundle provides extension for data grid with ORM datasource.
Filters could be added to datagrid in the datagrid.yml file for specified datagrid under `filters` node.
Definition of any filter has required option `data_name` that should be reference to column in query and type - filter type.
For example:

```
    SOME_DATAGRID:
        source:
            type: orm
            query:
                select:
                    - g.id
                    - g.label
                from:
                    - { table: OroCRMContactBundle:Group, alias: g }

        filters:
            SOME_FITLER_NAME: # uses for query param, and for setting default filters
                type: string  # Filter type, list of available types described below
                data_name: g.id

```

## Additional params

 - `filter_condition` - use OR or AND operator in expression
 - `filter_by_having` - filter expression should be added to HAVING clause
 - `options` - pass form options directly to filter form type (for additional info [see](./filter_form_types.md)

Filters
-------

### String filter

Provides filtering using string comparison.

`type: string`
Validated by TextFilterType on backend and rendered by [Oro.Filter.ChoiceFilter](./javascript_widgets.md#orofilterchoicefilter)

### Select Row filter

Provides filtering by selected/not selected records

`type: string`
Validated by [SelectRowFilterType](./filter_form_types.md#oro_type_selectrow) on backend.

### Number and percent filter

Provides filtering by numbers comparison.

**Note**: _value from frontend will automatically transform to percentage for "percent" filter_

`type: number` - integer/decimal filter

`type: percent` - percent filter

Validated by [NumberFilterType](./filter_form_types.md#oro_type_number_filter-form-type) on backend
and rendered by [Oro.Filter.NumberFilter](./javascript_widgets.md#orofilternumberfilter)

### Boolean filter

Provides filtering for boolean values.

`type: boolean`

Validated by [BooleanFilterType](./filter_form_types.md#oro_type_boolean_filter-form-type) on backend
and rendered by [Oro.Filter.ChoiceFilter](./javascript_widgets.md#orofilterchoicefilter) with predefined set of option (yes/no)

**Additional params:**

`nullable: true|false` - is boolean column nullable or no

### Choice filter

Provides filtering data using list of predefined choices

`type: choice`

Validated by [ChoiceFilterType](./filter_form_types.md#oro_type_choice_filter-form-type) on backend
and rendered by [Oro.Filter.ChoiceFilter](./javascript_widgets.md#orofilterchoicefilter)

### Entity filter

Provides filtering data using list of choices that extracted from database.

`type: entity`

Validated by [EntityFilterType](./filter_form_types.md#oro_type_entity_filter-form-type) on backend
and rendered by [Oro.Filter.ChoiceFilter](./javascript_widgets.md#orofilterchoicefilter)

**Note**: _`query_builder` option could be passed from yml configuration to `field_options` using [method call link](./../../link.md)._

### Date filter

Provides filtering data by date values

`type: date`

Validated by [DateRangeFilterType](./filter_form_types.md#oro_type_date_range_filter-form-type)
Rendered by [Oro.Filter.DateFilter](./javascript_widgets.md#orofilterdatefilter)

### DateTime filter

Provides filtering data by datetime values

`type: datetime`

Validated by [DateTimeRangeFilterType](./filter_form_types.md#oro_type_datetime_range_filter-form-type)
Rendered by [Oro.Filter.DateTimeFilter](./javascript_widgets.md#orofilterdatetimefilter)

Customization
-------------
To implement your filter you have to do following:

 - Develop class that implements Oro\Bundle\FilterBundle\Filter\FilterInterface (also there is basic implementation in AbstractFilter class)
 - Register you filter as service with tag { name: oro\_filter.extension.orm\_filter.filter, type: YOUR\_FILTER\_TYPE }


text:
namespace quiche {

inline std::string QuicheStackTraceImpl() {
  return base::debug::StackTrace().ToString();
}

}  // namespace quiche

#endif  // NET_THIRD_PARTY_QUICHE_OVERRIDES_QUICHE_PLATFORM_IMPL_QUICHE_STACK_TRACE_IMPL_H_


text:
//
//  categoryHeader.h
//  myOrgForum
//
//  Created by SkyAndSea on 16/4/28.
//  Copyright © 2016年 SkyAndSea. All rights reserved.
//

#ifndef categoryHeader_h
#define categoryHeader_h
#import "UIWindow+Extension.h"
#import "UIView+Extension.h"
#import "UIBarButtonItem+Extension.h"
#import "LQSAppDelegate.h"
#import "LQSAppDelegate+HUD.h"
#import "UIImage+Extension.h"
#import "NSDate+MJ.h"
#import "NSString+Timestamp.h"
#import "UIButton+ImageTitleStyle.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "UIColor+Hex.h"
#endif /* categoryHeader_h */


text:
namespace CrystalQuartz.Core.Quartz3.Tests.Stubs
{
    using Quartz.Impl.Triggers;

    public class TriggerStub : SimpleTriggerImpl
    {
        public TriggerStub(string name) : base(name)
        {
        }

        public TriggerStub(string name, string @group) : base(name, @group)
        {
        }
    }
}


text:
import sys

with open(sys.argv[1], 'r') as f:
    lines = [line.strip() for line in f.readlines() if line.strip()]

for l in lines:
    print int(int(l) % 2 == 0)


text:
====================
lcm.sitecontent
====================

Sitecontent package containing folderish content pages

* `Source code @ GitHub <https://github.com/a25kk/lcm.sitecontent>`_
* `Releases @ PyPI <http://pypi.python.org/pypi/lcm.sitecontent>`_
* `Documentation @ ReadTheDocs <http://lcmsitecontent.readthedocs.org>`_
* `Continuous Integration @ Travis-CI <http://travis-ci.org/a25kk/lcm.sitecontent>`_

How it works
============

...

Installation
============

To install `lcm.sitecontent` you simply add ``lcm.sitecontent``
to the list of eggs in your buildout, run buildout and restart Plone.
Then, install `lcm.sitecontent` using the Add-ons control panel.

Configuration
=============

...


text:
'use strict';

var PLUGIN_NAME = 'gulp-watch-less';

var gulp = require('gulp'),
	gutil = require('gulp-util'),
	watch = require('gulp-watch'),
	mergeDefaults = require('lodash.defaults'),
	through = require('through2'),
	less = require('less');

// Generates list of @import paths for a given Vinyl file
function getLessFileImports(file, options, cb) {
	var imports = [];

	// Support (file, cb) signature
	if(typeof options === 'function') {
		cb = options; options = null;
	}

	// Parse the filepath, using file path as `filename` option
	less.parse(file.contents.toString('utf8'), mergeDefaults({
		filename: file.path
	},
	options || {}),
	function(err, root, imports, options) {
		// Add a better error message / properties
		if (err) {
			err.lineNumber = err.line;
			err.fileName = err.filename;
			err.message = err.message + ' in file ' + err.fileName + ' line no. ' + err.lineNumber;
		}

		// Generate imports list from the files hash (sorted)
		var imports = Object.keys(imports.files).sort();

		cb(err, imports);
	});
};

// Tracks watch streams e.g. `{filepath}: stream`
var _streams = Object.create(null);

// Name of the event fired when @imports cause file to change
// (Overwrites the current file.event set by gulp-watch/gaze)
var changeEvent = 'changed:by:import';

// Import generator
function watchLessImports(file, options, cb, done) {
	var filePath = file.path,
		watchStream = _streams[filePath];

	// Generate an @import list via LESS...
	getLessFileImports(file, options.less, function(err, imports) {
		var oldImports;

		// Emit the error if one was returned
		if (err) { cb(new gutil.PluginError(PLUGIN_NAME, err)); }

		// If a previous watch stream is active...
		if(watchStream) {
			oldImports = watchStream._imports;

			// Check to ensure the @import arrays are identical.
			if(oldImports.length && oldImports.join() === imports.join()) {
				done(); return; // Don't do anything further!
			}

			// Clean up previous watch stream
			watchStream.end();
			watchStream.unpipe();
			watchStream.close();
			delete _streams[filePath];
		}

		// If we found some imports...
		if(imports.length) {
			// Generate new watch stream
			watchStream = _streams[filePath] = watch(imports, options, cb);

			// Expose @import list on the stream
			watchStream._imports = imports;
		}

		done();
	});
}

module.exports = function (glob, options, callback) {
	// No-op callback if not given
	if(!options) { options = {}; }
	if(!callback) { callback = function() {}; }

	// Merge defaults
	options = mergeDefaults(options, {
		name: 'LESS', // Use LESS name by default
		less: {} // No LESS options by default
	});

	// Generate a basic `gulp-watch` stream
	var watchStream = watch(glob, options, callback)

	function watchImportStream(file, enc, cb) {
		var filePath = file.path;

		// Passthrough the file
		this.push(file);

		// Make sure we only execute the logic on external events
		// and not when our own internal changeEvent triggers it
		if(file.event !== changeEvent) {
			watchLessImports(file, options, function(importFile) {
				watchStream._gaze.emit('all', changeEvent, filePath);
			},
			cb);
		}

		// Otherwise exeute the callback logic immediately
		else { cb(); }

	}

	// Close all import watch streams when the watchStream ends
	watchStream.on('end', function() { Object.keys(_streams).forEach(closeStream); });

	// Immediately apply the globs and watch all imports, since otherwise we'd
	// have to edit the files once before any @import watching would activate
	gulp.src(glob).pipe(through.obj(watchImportStream));

	// Pipe the watch stream into the imports watcher so whenever any of the
	// files change, we re-generate our @import watcher so removals/additions
	// are detected
	return watchStream.pipe(through.obj(watchImportStream));
};


text:
namespace EFSM.Designer.Interfaces
{
    public interface INamedItem
    {
        string Name { get; }
    }
}


text:
package org.openbel.framework.common.cfg;

import static java.lang.System.*;
import static org.openbel.framework.common.BELUtilities.asPath;
import static org.openbel.framework.common.PathConstants.*;
import static org.openbel.framework.common.Strings.*;
import static org.openbel.framework.common.enums.ExitCode.MISSING_SYSTEM_CONFIGURATION;
import static org.openbel.framework.common.enums.ExitCode.UNRECOVERABLE_ERROR;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.openbel.framework.common.BELRuntimeException;
import org.openbel.framework.common.PathConstants;

/**
 * Provides system configuration capabilities.
 *

 * Two types of configuration exist within the BEL framework, system
 * configuration and {@link RuntimeConfiguration runtime configuration}. System
 * configuration allows access and modification of settings that affect the
 * system's behavior, i.e., the installation of the BEL framework.
 *

 *
 * @version 3.0.0
 */
public final class SystemConfiguration extends Configuration {

    private static SystemConfiguration self;

    /**
     * KAM URL setting name: {@value #KAMSTORE_URL_DESC}
     */
    public static final String KAMSTORE_URL_DESC = "kamstore_url";

    /**
     * KAM user setting name: {@value #KAMSTORE_USER_DESC}
     */
    public static final String KAMSTORE_USER_DESC = "kamstore_user";

    /**
     * KAM password setting name: {@value #KAMSTORE_PASSWORD_DESC}
     */
    public static final String KAMSTORE_PASSWORD_DESC = "kamstore_password";

    /**
     * KAM password setting name: {@value #SYSTEM_MANAGED_SCHEMAS}
     */
    public static final String SYSTEM_MANAGED_SCHEMAS =
            "system_managed_schemas";

    /**
     * KamStore catalog schema setting name:
     * {@value #KAMSTORE_CATALOG_SCHEMA_DESC}
     */
    public static final String KAMSTORE_CATALOG_SCHEMA_DESC =
            "kamstore_catalog_schema";

    /**
     * KamStore KAM schema prefix setting name:
     * {@value #KAMSTORE_SCHEMA_PREFIX_DESC}
     */
    public static final String KAMSTORE_SCHEMA_PREFIX_DESC =
            "kamstore_schema_prefix";

    /**
     * Framework working area: {@value #FRAMEWORK_WORKING_AREA_DESC}
     */
    public static final String FRAMEWORK_WORKING_AREA_DESC =
            "belframework_work";

    /**
     * Framework cache directory setting name:
     * {@value #FRAMEWORK_CACHE_DIRECTORY_DESC}
     */
    public static final String FRAMEWORK_CACHE_DIRECTORY_DESC =
            "belframework_cache";

    /**
     * Application log path: {@value #APPLICATION_LOG_PATH_DESC}
     */
    public static final String APPLICATION_LOG_PATH_DESC =
            "application_log_path";

    /**
     * URL to the BELFramework resource index: {@value #RESOURCE_INDEX_URL_DESC}
     */
    public static final String RESOURCE_INDEX_URL_DESC =
            "resource_index_url";

    /**
     * Location of BEL Templates (for BELWorkbench document creation):
     * {@value #BEL_TEMPLATE_LOCATION}
     *
     * @deprecated Deprecated as of version 3.0.0; no equivalent replacement
     */
    @Deprecated
    public static final String BEL_TEMPLATE_LOCATION = "beltemplate_path";

    /**
     * Defines the default value, {@value} , for the
     * {@value #KAMSTORE_CATALOG_SCHEMA_DESC} setting.
     */
    public static final String DEFAULT_KAM_CATALOG_SCHEMA = "kam_catalog";

    /**
     * Defines the default value, {@value} , for the
     * {@value #KAMSTORE_SCHEMA_PREFIX_DESC} setting.
     */
    private static final String DEFAULT_KAM_SCHEMA_PREFIX = "kam";

    /**
     * Defines the default value, {@value} , for the
     * {@value #SYSTEM_MANAGED_SCHEMAS} setting.
     */
    private static final String DEFAULT_SYSTEM_MANAGED_SCHEMAS = "1";

    private String kamURL;
    private String kamUser;
    private String kamPassword;
    private String kamCatalogSchema;
    private String kamSchemaPrefix;
    private String systemManagedSchemas;
    private File configurationFile;
    private File workingDirectory;
    private File cacheDirectory;
    private File applicationLogPath;
    private String resourceIndexURL;
    private File belTemplateDirectory;

    /**
     * Creates a system configuration instance.
     *

     * The configuration file to be used is
     * {@link PathConstants#SYSCONFIG_FILENAME} in
     * {@link PathConstants#SYS_PATH}.
     *

     *
     * @throws IOException Thrown if an I/O error occurs
     */
    private SystemConfiguration() throws IOException {
        super(defaultSysCfg());
        init();
    }

    /**
     * Creates a system configuration instance, using {@code file} as the
     * configuration source.
     *
     * @param file Configuration file
     * @throws IOException Thrown if an I/O error occurs
     */
    private SystemConfiguration(final File file) throws IOException {
        super(file);
        this.configurationFile = file;
        init();
    }

    /**
     * Creates a system configuration instance, using {@code map} as the
     * configuration source.
     *
     * @param map Map of string name-values
     */
    private SystemConfiguration(final Map<String, String> map) {
        super(map);
        init();
    }

    /**
     * Creates the system configuration as defined by the environment.
     *
     * @return {@link SystemConfiguration}
     * @throws IOException Thrown if an I/O error occurs
     */
    public static synchronized SystemConfiguration createSystemConfiguration()
            throws IOException {
        if (self == null) {
            if (getenv(BELFRAMEWORK_HOME_ENV_VAR) == null) {
                String err = MISSING_SYSCFG;
                err = err.concat(": environment variable not set ");
                err = err.concat(BELFRAMEWORK_HOME_ENV_VAR);
                throw new IOException(err);
            }
            self = new SystemConfiguration();
        }
        return self;
    }

    /**
     * Creates the system configuration from the provided file, which may be
     * null.
     *
     * @param file System configuration file, which may be null
     * @return {@link SystemConfiguration}
     * @throws IOException Thrown if an I/O error occurs
     */
    public static synchronized SystemConfiguration createSystemConfiguration(
            final File file) throws IOException {
        if (self == null) {
            if (file == null) {
                if (getenv(BELFRAMEWORK_HOME_ENV_VAR) == null) {
                    String err = MISSING_SYSCFG;
                    err = err.concat(": environment variable not set ");
                    err = err.concat(BELFRAMEWORK_HOME_ENV_VAR);
                    throw new IOException(err);
                }
                self = new SystemConfiguration();
            } else {
                self = new SystemConfiguration(file);
            }
        }
        return self;
    }

    /**
     * Creates the system configuration from the provided map.
     *

     *
     *

     *
     * map.put(KAMSTORE_URL_DESC, "mysql://...");
     * map.put(FRAMEWORK_WORKING_AREA_DESC, "{home}/BEL_Framework");
     * createSystemConfiguration(map);
     *
     *

     *
     *

     *
     * @param map Map of string name-values
     * @return {@link SystemConfiguration}
     * @see #APPLICATION_LOG_PATH_DESC
     * @see #FRAMEWORK_CACHE_DIRECTORY_DESC
     * @see #FRAMEWORK_WORKING_AREA_DESC
     * @see #KAMSTORE_CATALOG_SCHEMA_DESC
     * @see #KAMSTORE_PASSWORD_DESC
     * @see #KAMSTORE_SCHEMA_PREFIX_DESC
     * @see #KAMSTORE_URL_DESC
     * @see #KAMSTORE_USER_DESC
     * @see #RESOURCE_INDEX_URL_DESC
     * @see #SYSTEM_MANAGED_SCHEMAS
     */
    public static synchronized SystemConfiguration createSystemConfiguration(
            final Map<String, String> map) {
        if (self == null) {
            self = new SystemConfiguration(map);
        }
        return self;
    }

    /**
     * Returns the system configuration.
     *

     * It is an error to access the system configuration before it has been
     * created. As a result, this method throws {@link IllegalStateException} to
     * indicate this has occurred.
     *

     *
     * @return {@link SystemConfiguration}
     * @see #createSystemConfiguration(File)
     * @throws IllegalStateException Thrown if no system configuration has been
     * created
     */
    public static synchronized SystemConfiguration getSystemConfiguration() {
        if (self == null) {
            throw new IllegalStateException(
                    "System configuration has not been created.");
        }
        return self;
    }

    /**
     * Destroys the system configuration.
     *

     * It is an error to destroy the system configuration before it has been
     * created. As a result, this method throws {@link IllegalStateException} to
     * indicate this has occurred.
     *

     *
     * @see #createSystemConfiguration(File)
     */
    protected static synchronized void destroySystemConfiguration() {
        if (self == null) {
            throw new IllegalStateException(
                    "System configuration has not been created.");
        }
        self = null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void processSetting(String name, String value) {
        if (KAMSTORE_URL_DESC.equals(name)) {
            kamURL = value;
        } else if (KAMSTORE_USER_DESC.equals(name)) {
            kamUser = value;
        } else if (KAMSTORE_PASSWORD_DESC.equals(name)) {
            kamPassword = value;
        } else if (KAMSTORE_CATALOG_SCHEMA_DESC.equals(name)) {
            kamCatalogSchema = value;
        } else if (KAMSTORE_SCHEMA_PREFIX_DESC.equals(name)) {
            kamSchemaPrefix = value;
        } else if (FRAMEWORK_WORKING_AREA_DESC.equals(name)) {
            final String workingPath = asPath(value, NESTED_OUTPUT_DIRECTORY);
            workingDirectory = new File(workingPath);
        } else if (FRAMEWORK_CACHE_DIRECTORY_DESC.equals(name)) {
            cacheDirectory = new File(value);
        } else if (APPLICATION_LOG_PATH_DESC.equals(name)) {
            applicationLogPath = new File(value);
        } else if (RESOURCE_INDEX_URL_DESC.equals(name)) {
            resourceIndexURL = value;
        } else if (BEL_TEMPLATE_LOCATION.equals(name)) {
            belTemplateDirectory = new File(value);
        } else if (SYSTEM_MANAGED_SCHEMAS.equals(name)) {
            systemManagedSchemas = value;
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void initializeDefaults() {
        String err = "A BEL Framework system configuration must be present";
        if (configurationFile != null) {
            err += " (using " + configurationFile + ")";
        }
        throw new BELRuntimeException(err, MISSING_SYSTEM_CONFIGURATION);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void readComplete() {
        Set<String> unsetStrings = new HashSet<String>();

        if (kamURL == null || kamURL.isEmpty()) {
            unsetStrings.add(KAMSTORE_URL_DESC);
        }

        if (resourceIndexURL == null || resourceIndexURL.isEmpty()) {
            unsetStrings.add(RESOURCE_INDEX_URL_DESC);
        }

        if (workingDirectory == null) {
            String value = getProperty("java.io.tmpdir");
            String pathel2 = DEFAULT_OUTPUT_DIRECTORY;
            String pathel3 = NESTED_OUTPUT_DIRECTORY;
            value = asPath(value, pathel2, pathel3);
            workingDirectory = new File(value);
        }
        validateOutputPath(workingDirectory);

        if (cacheDirectory == null) {
            String value = getProperty("user.home");
            value = asPath(value, DEFAULT_CACHE_DIRECTORY);
            cacheDirectory = new File(value);
        }
        validateOutputPath(cacheDirectory);

        if (applicationLogPath == null) {
            String outputPath = workingDirectory.getAbsolutePath();
            applicationLogPath = new File(outputPath);
        }
        validateOutputPath(applicationLogPath);

        if (kamCatalogSchema == null) {
            kamCatalogSchema = DEFAULT_KAM_CATALOG_SCHEMA;
        }

        if (kamSchemaPrefix == null) {
            kamSchemaPrefix = DEFAULT_KAM_SCHEMA_PREFIX;
        }

        if (systemManagedSchemas == null) {
            systemManagedSchemas = DEFAULT_SYSTEM_MANAGED_SCHEMAS;
        }

        if (belTemplateDirectory == null) {
            String value = getProperty("user.home");
            value = asPath(value, DEFAULT_BEL_TEMPLATE_DIRECTORY);
            belTemplateDirectory = new File(value);
        }
        validateOutputPath(belTemplateDirectory);

        if (!unsetStrings.isEmpty()) {
            final StringBuilder bldr = new StringBuilder();
            bldr.append("The configuration file is not complete.");
            bldr.append("\n(missing");
            for (final String setting : unsetStrings) {
                bldr.append(" ");
                bldr.append(setting);
            }
            bldr.append(")");
            final String err = bldr.toString();
            throw new BELRuntimeException(err, UNRECOVERABLE_ERROR);
        }

        // Five-by-five.
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Map<String, String> defaults() {
        Map<String, String> ret = new HashMap<String, String>();

        String value = getProperty("java.io.tmpdir");
        value = asPath(value, DEFAULT_OUTPUT_DIRECTORY);
        ret.put(FRAMEWORK_WORKING_AREA_DESC, value);

        value = getProperty("user.home");
        value = asPath(value, DEFAULT_CACHE_DIRECTORY);
        ret.put(FRAMEWORK_CACHE_DIRECTORY_DESC, value);

        value = getProperty("java.io.tmpdir");
        value = asPath(value, DEFAULT_OUTPUT_DIRECTORY);
        ret.put(APPLICATION_LOG_PATH_DESC, value);

        return ret;
    }

    /**
     * Returns the KAM URL system configuration setting.
     *
     * @return {@link String}, the KAM store database URL, which cannot be null
     */
    public final String getKamURL() {
        return kamURL;
    }

    /**
     * Returns the KAM user system configuration setting.
     *
     * @return {@link String}, the KAM database username, which can be null
     */
    public final String getKamUser() {
        return kamUser;
    }

    /**
     * Returns the KAM password configuration setting.
     *
     * @return {@link String}, the KAM database password, which can be null
     */
    public final String getKamPassword() {
        return kamPassword;
    }

    /**
     * Returns the KAM catalog schema name.
     *
     * @return {@link String}, the KAM catalog schema name
     */
    public final String getKamCatalogSchema() {
        return kamCatalogSchema;
    }

    /**
     * Returns the KAM schema prefix.
     *
     * @return {@link String}, the KAM schema prefix
     */
    public final String getKamSchemaPrefix() {
        return kamSchemaPrefix;
    }

    /**
     * Returns the framework working directory system configuration setting.
     *
     * @return Non-null, writable directory
     */
    public final File getWorkingDirectory() {
        return workingDirectory;
    }

    /**
     * Returns the framework cache directory system configuration setting.
     *
     * @return Non-null, writable directory
     */
    public final File getCacheDirectory() {
        return cacheDirectory;
    }

    /**
     * Returns true if the OpenBEL Framework is managing the KAMStore schemas
     * false otherwise.
     *
     * @return Non-null, writable directory
     */
    public final boolean getSystemManagedSchemas() {
        if ("1".equals(systemManagedSchemas)) {
            return true;
        }
        return false;
    }

    /**
     * Returns the application log path system configuration setting.
     *
     * @return Non-null, writable directory
     */
    public final File getApplicationLogPath() {
        return applicationLogPath;
    }

    /**
     * Returns the URL to the OpenBEL Framework resource index.
     *
     * @return Non-null, string
     */
    public String getResourceIndexURL() {
        return resourceIndexURL;
    }

    /**
     * Returns the BEL Template directory system configuration setting.
     *
     * @return Non-null, writable directory
     * @deprecated Deprecated as of version 3.0.0; no equivalent replacement
     */
    @Deprecated
    public final File getBELTemplateDirectory() {
        return belTemplateDirectory;
    }

    private static File defaultSysCfg() {
        if (SYS_PATH == null) return null;
        return new File(asPath(SYS_PATH.getAbsolutePath(), SYSCONFIG_FILENAME));
    }

    /**
     * Prints the default system configuration.
     *
     * @param args Ignored command-line arguments
     */
    public static void main(String... args) {
        final String cfgpath = "../docs/configuration/belframework.cfg";
        final File cfgfile = new File(cfgpath);
        try {
            SystemConfiguration syscfg = createSystemConfiguration(cfgfile);
            out.println(syscfg.defaultConfiguration());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Throws a system configuration error if the {@code path} cannot be written
     * to. If {@code path} does not exist, an attempt to create it will be made.
     *
     * @param path Path for validation
     */
    private void validateOutputPath(final File path) {
        if (path.canWrite()) return;

        // If the path doesn't exist...
        if (!path.exists()) {
            // ... try creating it...
            if (!path.mkdirs()) {
                // ... or die trying.
                String err = DIRECTORY_CREATION_FAILED.concat(path.toString());
                throw new BELRuntimeException(err, UNRECOVERABLE_ERROR);
            }
            return;
        }

        // ... can't write to it.
        String err = CANT_WRITE_TO_PATH.concat(path.toString());
        throw new BELRuntimeException(err, UNRECOVERABLE_ERROR);
    }
}


text:
package com.github.weisj.darklaf.components.tooltip;

import javax.swing.*;

import com.github.weisj.darklaf.ui.tooltip.DarkToolTipUI;
import com.github.weisj.darklaf.util.Alignment;
import com.github.weisj.darklaf.util.LazyValue;

public class TooltipAwareButton extends JButton implements ToolTipAware {

    private final LazyValue<ToolTipContext> context =
            new LazyValue<>(() -> new ToolTipContext().setAlignment(Alignment.SOUTH).setCenterAlignment(Alignment.SOUTH)
                    .setAlignInside(false).setIgnoreBorder(true));

    public TooltipAwareButton() {
        this(null, null);
    }

    public TooltipAwareButton(final String text, final Icon icon) {
        super(text, icon);
        init();
    }

    public TooltipAwareButton(final Icon icon) {
        this(null, icon);
    }

    public TooltipAwareButton(final String text) {
        this(text, null);
    }

    public TooltipAwareButton(final Action a) {
        super(a);
        init();
    }

    private void init() {
        putClientProperty(DarkToolTipUI.KEY_CONTEXT, getToolTipContext());
        putClientProperty(DarkToolTipUI.KEY_STYLE, ToolTipStyle.BALLOON);
    }

    @Override
    public ToolTipContext getToolTipContext() {
        return context.get();
    }
}


text:
var info = document.getElementById('info')
info.addEventListener('touchstart',function(){
	location.href = '../../login_information/login.html'
})
var infoButton = document.getElementById('info_button');
infoButton.addEventListener('touchstart',function(){
	location.href = '../../info/settings.html'
})


text:
{-|
Module      : Idris.Core.Typecheck
Description : Idris' type checker.
Copyright   :
License     : BSD3
Maintainer  : The Idris Community.
-}

{-# LANGUAGE DeriveFunctor, FlexibleInstances, MultiParamTypeClasses,
             PatternGuards #-}

module Idris.Core.Typecheck where

import Idris.Core.Evaluate
import Idris.Core.TT

import Control.Monad.State
import qualified Data.Vector.Unboxed as V (length)
import Debug.Trace

-- To check conversion, normalise each term wrt the current environment.
-- Since we haven't converted everything to de Bruijn indices yet, we'll have to
-- deal with alpha conversion - we do this by making each inner term de Bruijn
-- indexed with 'finalise'

convertsC :: Context -> Env -> Term -> Term -> StateT UCs TC ()
convertsC ctxt env x y =
    do let hs = map fst (filter isHole env)
       c1 <- convEq ctxt hs x y
       if c1 then return ()
         else
            do c2 <- convEq ctxt hs (finalise (normalise ctxt env x))
                         (finalise (normalise ctxt env y))
               if c2 then return ()
                 else lift $ tfail (CantConvert
                             (finalise (normalise ctxt env x))
                             (finalise (normalise ctxt env y)) (errEnv env))

converts :: Context -> Env -> Term -> Term -> TC ()
converts ctxt env x y
     = let hs = map fst (filter isHole env) in
       case convEq' ctxt hs x y of
          OK True -> return ()
          _ -> case convEq' ctxt hs (finalise (normalise ctxt env x))
                                    (finalise (normalise ctxt env y)) of
                OK True -> return ()
                _ -> tfail (CantConvert
                           (finalise (normalise ctxt env x))
                           (finalise (normalise ctxt env y)) (errEnv env))

isHole (n, Hole _) = True
isHole _ = False

errEnv = map (\(x, b) -> (x, binderTy b))

isType :: Context -> Env -> Term -> TC ()
isType ctxt env tm = isType' (normalise ctxt env tm)
    where isType' tm | isUniverse tm = return ()
                     | otherwise = fail (showEnv env tm ++ " is not a Type")

convType :: String -> Context -> Env -> Term -> StateT UCs TC ()
convType tcns ctxt env tm =
    do (v, cs) <- get
       put (v + 1, cs)
       case normalise ctxt env tm of
            UType _ -> return ()
            _ -> convertsC ctxt env tm (TType (UVar tcns v))

recheck :: String -> Context -> Env -> Raw -> Term -> TC (Term, Type, UCs)
recheck = recheck_borrowing False []

recheck_borrowing :: Bool -> [Name] -> String -> Context -> Env -> Raw -> Term ->
                     TC (Term, Type, UCs)
recheck_borrowing uniq_check bs tcns ctxt env tm orig
   = let v = next_tvar ctxt in
       case runStateT (check' False tcns ctxt env tm) (v, []) of -- holes banned
          Error (IncompleteTerm _) -> Error $ IncompleteTerm orig
          Error e -> Error e
          OK ((tm, ty), constraints) ->
              do when uniq_check $ checkUnique bs ctxt env tm
                 return (tm, ty, constraints)

check :: Context -> Env -> Raw -> TC (Term, Type)
check ctxt env tm
     -- Holes allowed, so constraint namespace doesn't matter
     = evalStateT (check' True [] ctxt env tm) (0, [])

check' :: Bool -> String -> Context -> Env -> Raw -> StateT UCs TC (Term, Type)
check' holes tcns ctxt env top = chk (TType (UVar tcns (-5))) Nothing env top where

  smaller (UType NullType) _ = UType NullType
  smaller _ (UType NullType) = UType NullType
  smaller (UType u)        _ = UType u
  smaller _        (UType u) = UType u
  smaller x        _         = x

  astate | holes = MaybeHoles
         | otherwise = Complete

  chk :: Type -> -- uniqueness level
         Maybe UExp -> -- universe for kind
         Env -> Raw -> StateT UCs TC (Term, Type)
  chk u lvl env (Var n)
      | Just (i, ty) <- lookupTyEnv n env = return (P Bound n ty, ty)
      -- If we're elaborating, we don't want the private names; if we're
      -- checking an already elaborated term, we do
      | [P nt n' ty] <- lookupP_all (not holes) False n ctxt
             = return (P nt n' ty, ty)
      -- If the names are ambiguous, require it to be fully qualified
      | [P nt n' ty] <- lookupP_all (not holes) True n ctxt
             = return (P nt n' ty, ty)
      | otherwise = do lift $ tfail $ NoSuchVariable n
  chk u lvl env ap@(RApp f RType) | not holes
    -- special case to reduce constraintss
      = do (fv, fty) <- chk u Nothing env f
           let fty' = case uniqueBinders (map fst env) (finalise fty) of
                        ty@(Bind x (Pi i s k) t) -> ty
                        _ -> uniqueBinders (map fst env)
                                 $ case normalise ctxt env fty of
                                     ty@(Bind x (Pi i s k) t) -> ty
                                     _ -> normalise ctxt env fty
           case fty' of
             Bind x (Pi i (TType v') k) t ->
               do (v, cs) <- get
                  put (v+1, ULT (UVar tcns v) v' : cs)
                  let apty = simplify initContext env
                                 (Bind x (Let (TType v') (TType (UVar tcns v))) t)
                  return (App Complete fv (TType (UVar tcns v)), apty)
             Bind x (Pi i s k) t ->
                 do (av, aty) <- chk u Nothing env RType
                    convertsC ctxt env aty s
                    let apty = simplify initContext env
                                        (Bind x (Let aty av) t)
                    return (App astate fv av, apty)
             t -> lift $ tfail $ NonFunctionType fv fty
  chk u lvl env ap@(RApp f a)
      = do (fv, fty) <- chk u Nothing env f
           let fty' = case uniqueBinders (map fst env) (finalise fty) of
                        ty@(Bind x (Pi i s k) t) -> ty
                        _ -> uniqueBinders (map fst env)
                                 $ case normalise ctxt env fty of
                                     ty@(Bind x (Pi i s k) t) -> ty
                                     _ -> normalise ctxt env fty
           (av, aty) <- chk u Nothing env a
           case fty' of
             Bind x (Pi i s k) t ->
                 do convertsC ctxt env aty s
                    let apty = simplify initContext env
                                        (Bind x (Let aty av) t)
                    return (App astate fv av, apty)
             t -> lift $ tfail $ NonFunctionType fv fty
  chk u lvl env RType
    | holes = return (TType (UVal 0), TType (UVal 0))
    | otherwise = do (v, cs) <- get
                     let c = ULT (UVar tcns v) (UVar tcns (v+1))
                     put (v+2, (c:cs))
                     return (TType (UVar tcns v), TType (UVar tcns (v+1)))
  chk u lvl env (RUType un)
    | holes = return (UType un, TType (UVal 0))
    | otherwise = do -- TODO! Issue #1715 on the issue tracker.
                     -- https://github.com/idris-lang/Idris-dev/issues/1715
                     -- (v, cs) <- get
                     -- let c = ULT (UVar v) (UVar (v+1))
                     -- put (v+2, (c:cs))
                     -- return (TType (UVar v), TType (UVar (v+1)))
                     return (UType un, TType (UVal 0))
  chk u lvl env (RConstant Forgot) = return (Erased, Erased)
  chk u lvl env (RConstant c) = return (Constant c, constType c)
    where constType (I _)   = Constant (AType (ATInt ITNative))
          constType (BI _)  = Constant (AType (ATInt ITBig))
          constType (Fl _)  = Constant (AType ATFloat)
          constType (Ch _)  = Constant (AType (ATInt ITChar))
          constType (Str _) = Constant StrType
          constType (B8 _)  = Constant (AType (ATInt (ITFixed IT8)))
          constType (B16 _) = Constant (AType (ATInt (ITFixed IT16)))
          constType (B32 _) = Constant (AType (ATInt (ITFixed IT32)))
          constType (B64 _) = Constant (AType (ATInt (ITFixed IT64)))
          constType TheWorld = Constant WorldType
          constType Forgot  = Erased
          constType _       = TType (UVal 0)
  chk u lvl env (RBind n (Pi i s k) t)
      = do (sv, st) <- chk u Nothing env s
           (v, cs) <- get
           (kv, kt) <- chk u Nothing env k -- no need to validate these constraints, they are independent
           put (v+1, cs)
           let maxu = case lvl of
                           Nothing -> UVar tcns v
                           Just v' -> v'
           (tv, tt) <- chk st (Just maxu) ((n, Pi i sv kv) : env) t

--            convertsC ctxt env st (TType maxu)
--            convertsC ctxt env tt (TType maxu)
--            when holes $ put (v, cs)
--            return (Bind n (Pi i (uniqueBinders (map fst env) sv) (TType maxu))
--                      (pToV n tv), TType maxu)

           case (normalise ctxt env st, normalise ctxt env tt) of
                (TType su, TType tu) -> do
                    when (not holes) $ do (v, cs) <- get
                                          put (v, ULE su maxu :
                                                  ULE tu maxu : cs)
                    let k' = TType (UVar tcns v) `smaller` st `smaller` kv `smaller` u
                    return (Bind n (Pi i (uniqueBinders (map fst env) sv) k')
                              (pToV n tv), k')
                (un, un') ->
                   let k' = st `smaller` kv `smaller` un `smaller` un' `smaller` u in
                    return (Bind n (Pi i (uniqueBinders (map fst env) sv) k')
                                (pToV n tv), k')

      where mkUniquePi kv (Bind n (Pi i s k) sc)
                    = let k' = smaller kv k in
                          Bind n (Pi i s k') (mkUniquePi k' sc)
            mkUniquePi kv (Bind n (Lam t) sc)
                    = Bind n (Lam (mkUniquePi kv t)) (mkUniquePi kv sc)
            mkUniquePi kv (Bind n (Let t v) sc)
                    = Bind n (Let (mkUniquePi kv t) v) (mkUniquePi kv sc)
            mkUniquePi kv t = t

            -- Kind of the whole thing is the kind of the most unique thing
            -- in the environment (because uniqueness taints everything...)
            mostUnique [] k = k
            mostUnique (Pi _ _ pk : es) k = mostUnique es (smaller pk k)
            mostUnique (_ : es) k = mostUnique es k

  chk u lvl env (RBind n b sc)
      = do (b', bt') <- checkBinder b
           (scv, sct) <- chk (smaller bt' u) Nothing ((n, b'):env) sc
           discharge n b' bt' (pToV n scv) (pToV n sct)
    where checkBinder (Lam t)
            = do (tv, tt) <- chk u Nothing env t
                 let tv' = normalise ctxt env tv
                 convType tcns ctxt env tt
                 return (Lam tv, tt)
          checkBinder (Let t v)
            = do (tv, tt) <- chk u Nothing env t
                 (vv, vt) <- chk u Nothing env v
                 let tv' = normalise ctxt env tv
                 convertsC ctxt env vt tv
                 convType tcns ctxt env tt
                 return (Let tv vv, tt)
          checkBinder (NLet t v)
            = do (tv, tt) <- chk u Nothing env t
                 (vv, vt) <- chk u Nothing env v
                 let tv' = normalise ctxt env tv
                 convertsC ctxt env vt tv
                 convType tcns ctxt env tt
                 return (NLet tv vv, tt)
          checkBinder (Hole t)
            | not holes = lift $ tfail (IncompleteTerm undefined)
            | otherwise
                   = do (tv, tt) <- chk u Nothing env t
                        let tv' = normalise ctxt env tv
                        convType tcns ctxt env tt
                        return (Hole tv, tt)
          checkBinder (GHole i ns t)
            = do (tv, tt) <- chk u Nothing env t
                 let tv' = normalise ctxt env tv
                 convType tcns ctxt env tt
                 return (GHole i ns tv, tt)
          checkBinder (Guess t v)
            | not holes = lift $ tfail (IncompleteTerm undefined)
            | otherwise
                   = do (tv, tt) <- chk u Nothing env t
                        (vv, vt) <- chk u Nothing env v
                        let tv' = normalise ctxt env tv
                        convertsC ctxt env vt tv
                        convType tcns ctxt env tt
                        return (Guess tv vv, tt)
          checkBinder (PVar t)
            = do (tv, tt) <- chk u Nothing env t
                 let tv' = normalise ctxt env tv
                 convType tcns ctxt env tt
                 -- Normalised version, for erasure purposes (it's easier
                 -- to tell if it's a collapsible variable)
                 return (PVar tv, tt)
          checkBinder (PVTy t)
            = do (tv, tt) <- chk u Nothing env t
                 let tv' = normalise ctxt env tv
                 convType tcns ctxt env tt
                 return (PVTy tv, tt)

          discharge n (Lam t) bt scv sct
            = return (Bind n (Lam t) scv, Bind n (Pi Nothing t bt) sct)
          discharge n (Pi i t k) bt scv sct
            = return (Bind n (Pi i t k) scv, sct)
          discharge n (Let t v) bt scv sct
            = return (Bind n (Let t v) scv, Bind n (Let t v) sct)
          discharge n (NLet t v) bt scv sct
            = return (Bind n (NLet t v) scv, Bind n (Let t v) sct)
          discharge n (Hole t) bt scv sct
            = return (Bind n (Hole t) scv, sct)
          discharge n (GHole i ns t) bt scv sct
            = return (Bind n (GHole i ns t) scv, sct)
          discharge n (Guess t v) bt scv sct
            = return (Bind n (Guess t v) scv, sct)
          discharge n (PVar t) bt scv sct
            = return (Bind n (PVar t) scv, Bind n (PVTy t) sct)
          discharge n (PVTy t) bt scv sct
            = return (Bind n (PVTy t) scv, sct)

-- Number of times a name can be used
data UniqueUse = Never -- no more times
               | Once -- at most once more
               | LendOnly -- only under 'lend'
               | Many -- unlimited
  deriving Eq

-- If any binders are of kind 'UniqueType' or 'AllTypes' and the name appears
-- in the scope more than once, this is an error.
checkUnique :: [Name] -> Context -> Env -> Term -> TC ()
checkUnique borrowed ctxt env tm
         = evalStateT (chkBinders env (explicitNames tm)) []
  where
    isVar (P _ _ _) = True
    isVar (V _) = True
    isVar _ = False

    chkBinders :: Env -> Term -> StateT [(Name, (UniqueUse, Universe))] TC ()
    chkBinders env (V i) | length env > i = chkName (fst (env!!i))
    chkBinders env (P _ n _) = chkName n
    -- 'lending' a unique or nulltype variable doesn't count as a use,
    -- but we still can't lend something that's already been used.
    chkBinders env (App _ (App _ (P _ (NS (UN lend) [owner]) _) t) a)
       | isVar a && owner == txt "Ownership" &&
         (lend == txt "lend" || lend == txt "Read")
            = do chkBinders env t -- Check the type normally
                 st <- get
                 -- Remove the 'LendOnly' names from the unusable set
                 put (filter (\(n, (ok, _)) -> ok /= LendOnly) st)
                 chkBinders env a
                 put st -- Reset the old state after checking the argument
    chkBinders env (App _ f a) = do chkBinders env f; chkBinders env a
    chkBinders env (Bind n b t)
       = do chkBinderName env n b
            st <- get
            case b of
                 Let t v -> chkBinders env v
                 _ -> return ()
            chkBinders ((n, b) : env) t
    chkBinders env t = return ()

    chkBinderName :: Env -> Name -> Binder Term ->
                     StateT [(Name, (UniqueUse, Universe))] TC ()
    chkBinderName env n b
       = do let rawty = forgetEnv (map fst env) (binderTy b)
            (_, kind) <- lift $ check ctxt env rawty
            case kind of
                 UType UniqueType -> do ns <- get
                                        if n `elem` borrowed
                                           then put ((n, (LendOnly, NullType)) : ns)
                                           else put ((n, (Once, UniqueType)) : ns)
                 UType NullType -> do ns <- get
                                      put ((n, (Many, NullType)) : ns)
                 UType AllTypes -> do ns <- get
                                      put ((n, (Once, AllTypes)) : ns)
                 _ -> return ()

    chkName n
       = do ns <- get
            case lookup n ns of
                 Nothing -> return ()
                 Just (Many, k) -> return ()
                 Just (Never, k) -> lift $ tfail (UniqueError k n)
                 Just (LendOnly, k) -> lift $ tfail (UniqueError k n)
                 Just (Once, k) -> put ((n, (Never, k)) :
                                              filter (\x -> fst x /= n) ns)


text:
package mock_client

import (
	gomock "github.com/golang/mock/gomock"
	zapcore "go.uber.org/zap/zapcore"
)

// MockLogger is a mock of Logger interface
type MockLogger struct {
	ctrl     *gomock.Controller
	recorder *MockLoggerMockRecorder
}

// MockLoggerMockRecorder is the mock recorder for MockLogger
type MockLoggerMockRecorder struct {
	mock *MockLogger
}

// NewMockLogger creates a new mock instance
func NewMockLogger(ctrl *gomock.Controller) *MockLogger {
	mock := &MockLogger{ctrl: ctrl}
	mock.recorder = &MockLoggerMockRecorder{mock}
	return mock
}

// EXPECT returns an object that allows the caller to indicate expected use
func (_m *MockLogger) EXPECT() *MockLoggerMockRecorder {
	return _m.recorder
}

// Debug mocks base method
func (_m *MockLogger) Debug(msg string, fields ...zapcore.Field) {
	_s := []interface{}{msg}
	for _, _x := range fields {
		_s = append(_s, _x)
	}
	_m.ctrl.Call(_m, "Debug", _s...)
}

// Debug indicates an expected call of Debug
func (_mr *MockLoggerMockRecorder) Debug(arg0 interface{}, arg1 ...interface{}) *gomock.Call {
	_s := append([]interface{}{arg0}, arg1...)
	return _mr.mock.ctrl.RecordCall(_mr.mock, "Debug", _s...)
}

// Warn mocks base method
func (_m *MockLogger) Warn(msg string, fields ...zapcore.Field) {
	_s := []interface{}{msg}
	for _, _x := range fields {
		_s = append(_s, _x)
	}
	_m.ctrl.Call(_m, "Warn", _s...)
}

// Warn indicates an expected call of Warn
func (_mr *MockLoggerMockRecorder) Warn(arg0 interface{}, arg1 ...interface{}) *gomock.Call {
	_s := append([]interface{}{arg0}, arg1...)
	return _mr.mock.ctrl.RecordCall(_mr.mock, "Warn", _s...)
}

// Error mocks base method
func (_m *MockLogger) Error(msg string, fields ...zapcore.Field) error {
	_s := []interface{}{msg}
	for _, _x := range fields {
		_s = append(_s, _x)
	}
	ret := _m.ctrl.Call(_m, "Error", _s...)
	ret0, _ := ret[0].(error)
	return ret0
}

// Error indicates an expected call of Error
func (_mr *MockLoggerMockRecorder) Error(arg0 interface{}, arg1 ...interface{}) *gomock.Call {
	_s := append([]interface{}{arg0}, arg1...)
	return _mr.mock.ctrl.RecordCall(_mr.mock, "Error", _s...)
}


text:
"""

Perceptron: with no inner layers
        synapse(with weight)
(Input) -----------> (Neuron) ---> (output)
  x               {x1w1 + ... + xNwN}

### Training Process
* take inputs from training example and put through formula to get neuron's output
* calculate error which is difference between output we got and actual output
* depending on severeness of error, adjust weights accordingly
* repeat process N00000 times

### Error Weighted Derivative
* adjust weights by = error.input.0'(output)
`Error = output - actual_output`
* Input either 1 or 0

Backpropagation

numpy uses here
exp—for generating the natural exponential
array—for generating a matrix
dot—for multiplying matrices
random—for generating random numbers

"""

import numpy as np

training_inputs = np.array([
    [1, 0, 0],
    [1, 1, 0],
    [1, 0, 1],
    [0, 0, 0],
    [1, 0, 0],
    [1, 1, 0],
    [1, 0, 1],
    [0, 1, 0],
    [0, 1, 1],
    [0, 0, 1],
    [1, 0, 0],
    [1, 1, 0],
    [1, 0, 1],
    [0, 0, 0],
    [1, 0, 0],
    [1, 1, 0],
    [1, 0, 1],
    [0, 1, 0],
    [0, 1, 1],
    [0, 0, 1]
])

training_outputs = np.array([ [1,1,1,0,1,1,1,0,0,0,1,1,1,0,1,1,1,0,0,0] ]).T

np.random.seed(10)

synaptic_weights = 2 * np.random.random((3, 1)) - 1

print("Random starting synaptic weight", synaptic_weights)

def sigmoid(x):
    return 1 / ( 1 + np.exp(-x) )

def sigmoid_derivative(x):
    return x * ( 1 - x)

"""
For sigmoid:
https://stackoverflow.com/questions/10626134/derivative-of-sigmoid
https://gist.github.com/jovianlin/805189d4b19332f8b8a79bbd07e3f598
"""

def think(iteration_input):
    required_input = iteration_input.astype(float)
    return sigmoid(
        np.dot(required_input, synaptic_weights)
    )

def train():
    global training_inputs
    global training_outputs
    global synaptic_weights
    iterations = 500 # 100000
    for iteration in range(iterations):
        input_layer = training_inputs
        outputs = think(input_layer)
        error = training_outputs - outputs
        adjustments = error * sigmoid_derivative(outputs)
        synaptic_weights += np.dot(input_layer.T, adjustments)

    print('Synaptic weights after training: ',synaptic_weights)
    print('Outputs after training: ',outputs)

def ask_now():
    item1 = str(input('enter 0 or 1: '))
    item2 = str(input('enter 0 or 1: '))
    item3 = str(input('enter 0 or 1: '))
    neural_input = np.array([item1, item2, item3])
    print("Your result is: ", think(neural_input))

if __name__ == "__main__":
    train()
    ask_now()


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. N. Y. St. Mus. 266: 82 (1925)

#### Original name
Phyllosticta cyanococci Dearn. & House

### Remarks
null


text:
#include <memory>

#import <ABI43_0_0React/ABI43_0_0RCTBridgeDelegate.h>

namespace ABI43_0_0facebook {
namespace ABI43_0_0React {

class JSExecutorFactory;

}
}

// This is a separate class so non-C++ implementations don't need to
// take a C++ dependency.

@protocol ABI43_0_0RCTCxxBridgeDelegate <ABI43_0_0RCTBridgeDelegate>

/**
 * In the ABI43_0_0RCTCxxBridge, if this method is implemented, return a
 * ExecutorFactory instance which can be used to create the executor.
 * If not implemented, or returns an empty pointer, JSIExecutorFactory
 * will be used with a JSCRuntime.
 */
- (void *)jsExecutorFactoryForBridge:(ABI43_0_0RCTBridge *)bridge;

@end

@protocol ABI43_0_0RCTCxxBridgeTurboModuleDelegate <ABI43_0_0RCTBridgeDelegate>

/**
 * The ABI43_0_0RCTCxxBridgeDelegate used outside of the Expo Go.
 */
- (std::unique_ptr<ABI43_0_0facebook::ABI43_0_0React::JSExecutorFactory>)jsExecutorFactoryForBridge:(ABI43_0_0RCTBridge *)bridge;

@end


text:
class ProfileSyncService;

// This class provides some common functionality for StatusChangeCheckers that
// observe many ProfileSyncServices.  This class is abstract.  Its descendants
// are expected to provide additional functionality.
class MultiClientStatusChangeChecker : public StatusChangeChecker,
                                       public sync_driver::SyncServiceObserver {
 public:
  explicit MultiClientStatusChangeChecker(
      std::vector<ProfileSyncService*> services);
  ~MultiClientStatusChangeChecker() override;

  // Called when waiting times out.
  void OnTimeout();

  // Blocks until the exit condition is satisfied or a timeout occurs.
  void Wait();

  // sync_driver::SyncServiceObserver implementation.
  void OnStateChanged() override;

  // StatusChangeChecker implementations and stubs.
  bool IsExitConditionSatisfied() override = 0;
  std::string GetDebugMessage() const override = 0;

 protected:
  const std::vector<ProfileSyncService*>& services() { return services_; }

 private:
  std::vector<ProfileSyncService*> services_;
};

#endif  // CHROME_BROWSER_SYNC_TEST_INTEGRATION_MULTI_CLIENT_STATUS_CHANGE_CHECKER_H_


text:
import mock
import pytest
from lxml import html

from ...helpers import LoggedInApplicationTest

class TestServiceUpdates(LoggedInApplicationTest):
    user_role = 'admin-ccs-category'

    def setup_method(self, method):
        super().setup_method(method)
        self.data_api_client_patch = mock.patch('app.main.views.service_updates.data_api_client', autospec=True)
        self.data_api_client = self.data_api_client_patch.start()

    def teardown_method(self, method):
        self.data_api_client_patch.stop()
        super().teardown_method(method)

    @pytest.mark.parametrize("role,expected_code", [
        ("admin", 403),
        ("admin-ccs-category", 200),
        ("admin-ccs-sourcing", 403),
        ("admin-manager", 403),
    ])
    def test_view_service_updates_only_for_allowed_user_roles(self, role, expected_code):
        self.user_role = role
        response = self.client.get('/admin/services/updates/unapproved')
        actual_code = response.status_code
        assert actual_code == expected_code, "Unexpected response {} for role {}".format(actual_code, role)

    @pytest.mark.parametrize('audit_events,expected_table_contents,expected_count', (
        (
            (
                ('2012-07-15T18:03:43.061077Z', '1123456789012351', u'Company name', '240697', '240680'),
                ('2016-03-05T10:42:16.061077Z', '1123456789012348', u'Testing Ltd', '240699', '240682'),
                ('2017-04-25T14:43:46.061077Z', '597637931594387', u'Making £ Inc', '240701', '240684'),
            ),
            (
                ('Company name', '1123456789012351', 'Sunday 15 July 2012 at 18:03:43', '/admin/services/1123456789012351/updates'),  # noqa
                ('Testing Ltd', '1123456789012348', 'Saturday 5 March 2016 at 10:42:16', '/admin/services/1123456789012348/updates'),  # noqa
                ('Making £ Inc', '597637931594387', 'Tuesday 25 April 2017 at 14:43:46', '/admin/services/597637931594387/updates'),  # noqa
            ),
            '3 edited services',
        ),
        (
            (
                ('2012-07-15T18:03:43.061077Z', '597637931590002', 'Company name', '240697', '240680'),
                ('2016-03-05T10:42:16.061077Z', '597637931590001', 'Ideal Health', '240699', '240682'),
            ),
            (
                ('Company name', '597637931590002', 'Sunday 15 July 2012 at 18:03:43', '/admin/services/597637931590002/updates'),  # noqa
                ('Ideal Health', '597637931590001', 'Saturday 5 March 2016 at 10:42:16', '/admin/services/597637931590001/updates'),  # noqa
            ),
            '2 edited services',
        ),
        (
            (),
            (),
            '0 edited services',
        ),
        (
            (
                ('2012-07-15T18:03:43.061077Z', '597637931590002', 'Company name', '240697', '240680'),
            ),
            (
                ('Company name', '597637931590002', 'Sunday 15 July 2012 at 18:03:43', '/admin/services/597637931590002/updates'),  # noqa
            ),
            '1 edited service',
        ),
    ))
    def test_should_show_unacknowledged_services(self, audit_events, expected_table_contents, expected_count):
        self.data_api_client.find_audit_events.return_value = {
            "auditEvents": [
                {
                    "data": {
                        "oldArchivedServiceId": old_archived_service_id,
                        "newArchivedServiceId": new_archived_service_id,
                        "serviceId": service_id,
                        "supplierName": supplier_name,
                    },
                    "createdAt": date_string
                } for (
                    date_string, service_id, supplier_name, old_archived_service_id, new_archived_service_id
                ) in audit_events
            ],
            "links": {},
        }

        response = self.client.get('/admin/services/updates/unapproved')

        assert response.status_code == 200
        document = html.fromstring(response.get_data(as_text=True))

        assert tuple(
            tuple(
                td.xpath('normalize-space(string())') for td in tr.xpath('./td')[:-1]
            ) + (tr.xpath('./td[last()]//a/@href')[0],)
            for tr in document.xpath('//table[@class="summary-item-body"]/tbody/tr')
        ) == expected_table_contents

        assert len(document.cssselect(f'p.govuk-body.search-summary:contains("{expected_count}")')) == 1

        if audit_events != ():
            assert tuple(
                tuple(th.xpath('normalize-space(string())') for th in tr.xpath('./th'))
                for tr in document.xpath('//table[@class="summary-item-body"]/thead/tr')
            ) == (('Supplier', 'Service ID', 'Edited', 'Changes'),)

    def test_acknowledge_audit_event_happy_path(self):
        audit_event = {
            'auditEvents': {
                'acknowledged': False,
                'links': {
                    'self': 'http://localhost:5000/services/updates/unapproved'
                },
                'data': {
                    'serviceName': 'new name',
                    'supplierId': 93518,
                    'supplierName': 'Clouded Networks',
                    'serviceId': '321',
                },
                'user': 'joeblogs',
                'type': 'update_service',
                'id': 123,
                'createdAt': '2015-06-17T08:49:22.999Z'
            },
            'links': {}
        }

        self.data_api_client.get_audit_event.side_effect = lambda audit_event_id: {123: audit_event}[audit_event_id]
        response = self.client.post('/admin/services/321/updates/123/approve')
        assert response.status_code == 302
        self.assert_flashes("The changes to service 321 were approved.")
        assert response.location == 'http://localhost/admin/services/updates/unapproved'

        self.data_api_client.acknowledge_service_update_including_previous.assert_called_with(
            u'321',
            123,
            'test@example.com'
        )

    def test_should_404_wrong_service_id(self):
        response = self.client.post('/admin/services/123/updates/321/approve')
        assert response.status_code == 404

    @pytest.mark.parametrize("role_not_allowed", ["admin", "admin-ccs-sourcing", "admin-manager"])
    def test_post_should_403_forbidden_user_roles(self, role_not_allowed):
        self.user_role = role_not_allowed
        response = self.client.post('/admin/services/123/updates/321/approve')
        assert response.status_code == 403

    def test_should_410_already_acknowledged_event(self):
        audit_event = {
            'auditEvents': {
                'acknowledged': True,
                'links': {
                    'self': 'http://localhost:5000/audit-events'
                },
                'data': {
                    'serviceName': 'new name',
                    'supplierId': 93518,
                    'supplierName': 'Clouded Networks',
                    'serviceId': '321',
                },
                'user': 'joeblogs',
                'type': 'update_service',
                'id': 123,
                'createdAt': '2015-06-17T08:49:22.999Z'
            },
            'links': {}
        }

        self.data_api_client.get_audit_event.side_effect = lambda audit_event_id: {123: audit_event}[audit_event_id]
        response = self.client.post('/admin/services/321/updates/123/approve')
        assert response.status_code == 410

    def test_should_404_wrong_audit_event_type(self):
        audit_event = {
            'auditEvents': {
                'acknowledged': False,
                'links': {
                    'self': 'http://localhost:5000/audit-events'
                },
                'data': {
                    'serviceName': 'new name',
                    'supplierId': 93518,
                    'supplierName': 'Clouded Networks',
                    'serviceId': '321',
                },
                'user': 'joeblogs',
                'type': 'not_the_right_type',
                'id': 123,
                'createdAt': '2015-06-17T08:49:22.999Z'
            },
            'links': {}
        }

        self.data_api_client.get_audit_event.side_effect = lambda audit_event_id: {123: audit_event}[audit_event_id]
        response = self.client.post('/admin/services/321/updates/123/approve')
        assert response.status_code == 404


text:
/**
 * @author Joshua Kissoon
 * @desc Interface for all Robot Tour Optimization Algorithms
 */
package chapter1.exercise26;

public interface RobotTourOptimizationAlgorithm
{
    /**
     * @desc Executes the algorithm
     */
    public void executeAlgorithm();

    /**
     * @desc Method that computes the total distance traveled
     * @return double The total distance traveled
     */
    public double getTotalDistanceTraveled();

    /**
     * @return The graph plotted by the Algorithm for the tour
     */
    public Graph getTourGraph();
}


text:
'use strict'

const logger = require('./lib/logger')

let __singleton

const setupDefaultLogger = function(key, opts) {
  if (!(__singleton instanceof logger.Logger)) {
    __singleton = logger.createLogger(key, opts)
  }
  return __singleton
}

module.exports = {
  cleanUpAll: logger.cleanUpAll
, createLogger: logger.createLogger
, flushAll: logger.flushAll
, Logger: logger.Logger
, setupDefaultLogger
}


text:
/*Tatiana Smidi
Hector Fuentes
May 27. 2015
Classwork 2

This program reads and displays data from a text file.*/
#include<iostream> //needed for cin/cout
#include<iomanip>  //needed for setw and setprecision
#include<string>	 //needed to use string data type
#include<fstream>  //needed for reading/writing files
using namespace std;

int main()
{

	//Declare/intialize variables
	string make1, make2, make3, model1, model2, model3;
	int year1 = 0, year2 = 0 ,year3 = 0;

	//Declare File Pointer
	ifstream infile;

	//Intro
	cout<<"Welcome to the Car Info Collector!\n";

	//Open the file cars.txt
	infile.open("cars.txt", ios::in);

	//Check if File exists
	if(!infile)
		{
			cout<<"File does not exist!\n";
		}
	//read in data line by line
	infile>>year1>>make1>>model1;
	infile>>year2>>make2>>model2;

	//Close the file
	infile.close();

	//Display Results
	cout<<"\nYear\tMake\tModel\n";
	cout<<"-----------------------\n";
	cout<<year1<<"\t"<<make1<<"\t"<<model1<<endl;
	cout<<year2<<"\t"<<make2<<"\t"<<model2<<endl;

	//Prompt user for year3, make3 and model3 of car
	cout<<"Enter year: ";
	cin>>year3;
	cout<<"Enter make: ";
	cin>>make3;
	cout<<"Enter model: ";
	cin>>model3;

	//Write raw data to the file
	//declare a file pointer for output
	ofstream outfile;
	//Open cars.txt
	outfile.open("cars.txt", ios::app);

	//Append the data
	outfile<<year3<<"\t"<<make3<<"\t"<<model3<<endl;
	//close file
	outfile.close();

 return 0;
}


text:
//
//  QNUploadSystemClient.m
//  QiniuSDK_Mac
//
//  Created by yangsen on 2020/5/6.
//  Copyright © 2020 Qiniu. All rights reserved.
//

#import "QNUploadSystemClient.h"
#import "QNUserAgent.h"
#import "NSURLRequest+QNRequest.h"

@interface QNUploadSystemClient()<NSURLSessionDelegate>

@property(nonatomic, strong)NSURLRequest *request;
@property(nonatomic, strong)QNUploadSingleRequestMetrics *requestMetrics;
@property(nonatomic, strong)NSURLSessionDataTask *uploadTask;
@property(nonatomic, strong)NSMutableData *responseData;
@property(nonatomic,  copy)void(^progress)(long long totalBytesWritten, long long totalBytesExpectedToWrite);
@property(nonatomic,  copy)QNRequestClientCompleteHandler complete;

@end
@implementation QNUploadSystemClient

- (NSString *)clientId {
    return @"NSURLSession";
}

- (void)request:(NSURLRequest *)request
         server:(id <QNUploadServer>)server
connectionProxy:(NSDictionary *)connectionProxy
       progress:(void (^)(long long, long long))progress
       complete:(QNRequestClientCompleteHandler)complete {

    // 非 https 方可使用 IP
    if (!request.qn_isHttps && server && server.ip.length > 0 && server.host.length > 0) {
        NSString *urlString = request.URL.absoluteString;
        urlString = [urlString stringByReplacingOccurrencesOfString:server.host withString:server.ip];
        NSMutableURLRequest *requestNew = [request mutableCopy];
        requestNew.URL = [NSURL URLWithString:urlString];
        requestNew.qn_domain = server.host;
        self.request = [requestNew copy];
    } else {
        self.request = request;
    }

    self.requestMetrics = [QNUploadSingleRequestMetrics emptyMetrics];
    self.requestMetrics.remoteAddress = self.request.qn_isHttps ? nil : server.ip;
    self.requestMetrics.remotePort = self.request.qn_isHttps ? @443 : @80;
    [self.requestMetrics start];

    self.responseData = [NSMutableData data];
    self.progress = progress;
    self.complete = complete;

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    if (connectionProxy) {
        configuration.connectionProxyDictionary = connectionProxy;
    }
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration
                                                          delegate:self
                                                     delegateQueue:nil];
    NSURLSessionDataTask *uploadTask = [session dataTaskWithRequest:self.request];
    [uploadTask resume];

    self.uploadTask = uploadTask;
}

- (void)cancel{
    [self.uploadTask cancel];
}

//MARK:-- NSURLSessionDelegate
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
    completionHandler(NSURLSessionResponseAllow);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    [self.responseData appendData:data];
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error {
    [self.requestMetrics end];
    self.requestMetrics.request = task.currentRequest;
    self.requestMetrics.response = task.response;
    self.requestMetrics.error = error;
    self.complete(task.response, self.requestMetrics,self.responseData, error);

    [session finishTasksAndInvalidate];
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didFinishCollectingMetrics:(NSURLSessionTaskMetrics *)metrics  API_AVAILABLE(ios(10.0)) {
    NSURLSessionTaskTransactionMetrics *transactionMetrics = metrics.transactionMetrics.lastObject;

    self.requestMetrics.domainLookupStartDate = transactionMetrics.domainLookupStartDate;
    self.requestMetrics.domainLookupEndDate = transactionMetrics.domainLookupEndDate;
    self.requestMetrics.connectStartDate = transactionMetrics.connectStartDate;
    self.requestMetrics.secureConnectionStartDate = transactionMetrics.secureConnectionStartDate;
    self.requestMetrics.secureConnectionEndDate = transactionMetrics.secureConnectionEndDate;
    self.requestMetrics.connectEndDate = transactionMetrics.connectEndDate;

    self.requestMetrics.requestStartDate = transactionMetrics.requestStartDate;
    self.requestMetrics.requestEndDate = transactionMetrics.requestEndDate;
    self.requestMetrics.responseStartDate = transactionMetrics.responseStartDate;
    self.requestMetrics.responseEndDate = transactionMetrics.responseEndDate;

    if ([transactionMetrics.networkProtocolName isEqualToString:@"http/1.0"]) {
        self.requestMetrics.httpVersion = @"1.0";
    } else if ([transactionMetrics.networkProtocolName isEqualToString:@"http/1.1"]) {
        self.requestMetrics.httpVersion = @"1.1";
    } else if ([transactionMetrics.networkProtocolName isEqualToString:@"h2"]) {
        self.requestMetrics.httpVersion = @"2";
    } else if ([transactionMetrics.networkProtocolName isEqualToString:@"h3"]) {
        self.requestMetrics.httpVersion = @"3";
    } else {
        self.requestMetrics.httpVersion = transactionMetrics.networkProtocolName;
    }

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
    if (@available(iOS 13.0, macOS 10.15, *)) {
        if (transactionMetrics.remoteAddress) {
            self.requestMetrics.remoteAddress = transactionMetrics.remoteAddress;
            self.requestMetrics.remotePort = transactionMetrics.remotePort;
        }
        if (transactionMetrics.countOfRequestHeaderBytesSent > 0) {
            self.requestMetrics.countOfRequestHeaderBytesSent = transactionMetrics.countOfRequestHeaderBytesSent;
        }
        if (transactionMetrics.countOfResponseHeaderBytesReceived > 0) {
            self.requestMetrics.countOfResponseHeaderBytesReceived = transactionMetrics.countOfResponseHeaderBytesReceived;
        }
        if (transactionMetrics.countOfResponseBodyBytesReceived > 0) {
            self.requestMetrics.countOfResponseBodyBytesReceived = transactionMetrics.countOfResponseBodyBytesReceived;
        }
    }
#endif

}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
             didSendBodyData:(int64_t)bytesSent
              totalBytesSent:(int64_t)totalBytesSent
    totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {

    self.requestMetrics.countOfRequestBodyBytesSent = totalBytesSent;
    if (self.progress) {
        self.progress(totalBytesSent, totalBytesExpectedToSend);
    }
}

/*
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
                  forDomain:(NSString *)domain {

    NSMutableArray *policies = [NSMutableArray array];
    if (domain) {
        [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)];
    } else {
        [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()];
    }

    SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);

    if (@available(iOS 13.0, macOS 10.14, *)) {
        CFErrorRef error = NULL;
        BOOL ret = SecTrustEvaluateWithError(serverTrust, &error);
        return ret && (error == nil);
    } else {
        SecTrustResultType result;
        SecTrustEvaluate(serverTrust, &result);
        return (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
    }
}

- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler {
    if (!challenge) {
        return;
    }
    NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
    NSURLCredential *credential = nil;

    NSString* host = [[self.request allHTTPHeaderFields] objectForKey:@"host"];
    if (!host) {
        host = self.request.URL.host;
    }
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        if ([self evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:host]) {
            disposition = NSURLSessionAuthChallengeUseCredential;
            credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        } else {
            disposition = NSURLSessionAuthChallengePerformDefaultHandling;
        }
    } else {
        disposition = NSURLSessionAuthChallengePerformDefaultHandling;
    }

    completionHandler(disposition,credential);
}
*/
@end


text:
package org.caleydo.core.data.datadomain.graph;

import org.caleydo.core.data.datadomain.IDataDomain;
import org.caleydo.core.id.IDCategory;

public final class Edge {
	// String vertex1;
	// String vertex2;
	private final IDataDomain vertex1;
	private final IDataDomain vertex2;
	private final IDCategory idCategory;
	private String infoVertex1;
	private String infoVertex2;

	public Edge(IDataDomain vertex1, IDataDomain vertex2) {
		this(vertex1, vertex1, null);
	}

	public Edge(IDataDomain vertex1, IDataDomain vertex2, IDCategory idCategory) {
		this.vertex1 = vertex1;
		this.vertex2 = vertex2;
		this.idCategory = idCategory;
	}

	public IDataDomain getOtherSideOf(IDataDomain vertex) {
		if (vertex.equals(vertex1))
			return vertex2;
		else if (vertex.equals(vertex2))
			return vertex1;
		else
			return null;
	}

	public String getInfoVertex1() {
		return infoVertex1;
	}

	public void setInfoVertex1(String infoVertex1) {
		this.infoVertex1 = infoVertex1;
	}

	public IDCategory getIdCategory() {
		return idCategory;
	}

	public String getInfoVertex2() {
		return infoVertex2;
	}

	public void setInfoVertex2(String infoVertex2) {
		this.infoVertex2 = infoVertex2;
	}

}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;

class CreatePasswordResetTable extends Migration
{
    /**
     * Run the migrations
     */
    public function up()
    {
        Schema::create(config('laranixauth.password.table'), function (Blueprint $table) {
            $table->unsignedInteger('user_id')->unique();
            $table->string('email');
            $table->string('token');
            $table->timestamps();

            $table->index('token');
            $table->unique('email');

            $table->foreign('user_id')
                ->references('id')
                ->on(config('laranixauth.user.table'))
                ->onUpdate('cascade')
                ->onDelete('cascade');
        });
    }

    /**
     * Reverse migrations
     */
    public function down()
    {
        $table = config('laranixauth.password.table');

        $userKey = "{$table}_user_id_foreign";

        Schema::table($table, function (Blueprint $table) use ($userKey) {
            $table->dropForeign($userKey);
        });

        Schema::dropIfExists($table);
    }
}


text:
package com.gemstone.gemfire.internal.cache.versions;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import com.gemstone.gemfire.distributed.internal.DM;
import com.gemstone.gemfire.distributed.internal.membership.InternalDistributedMember;
import com.gemstone.gemfire.internal.Version;

/**
 * The version tag class for version tags for non-persistent regions. The
 * VersionSource held in these tags is an InternalDistributedMember.
 *
 * @author dsmith
 *
 */
public class VMVersionTag extends VersionTag<InternalDistributedMember> {

  public VMVersionTag() {
    super();
  }

  @Override
  public void writeMember(InternalDistributedMember member, DataOutput out) throws IOException {
    member.writeEssentialData(out);

  }

  @Override
  public void setCanonicalIDs(DM dm) {
    InternalDistributedMember id = getMemberID();
    if (id != null) {
      setMemberID(dm.getCanonicalId(getMemberID()));
      id = getPreviousMemberID();
      if (id != null) {
        setPreviousMemberID(dm.getCanonicalId(id));
      }
    }
  }

  @Override
  public InternalDistributedMember readMember(DataInput in) throws IOException, ClassNotFoundException {
    return InternalDistributedMember.readEssentialData(in);
  }

  @Override
  public int getDSFID() {
    return VERSION_TAG;
  }

  @Override
  public Version[] getSerializationVersions() {
    return null;
  }

}