text:
#include <stdio.h>
#include <limits.h>

#include "pm.h"
#include "fileio.h"

char
pm_getc(FILE * const file) {
    int ich;
    char ch;

    ich = getc(file);
    if (ich == EOF)
        pm_error("EOF / read error reading a byte");
    ch = (char) ich;

    if (ch == '#') {
        do {
	    ich = getc(file);
	    if (ich == EOF)
            pm_error("EOF / read error reading a byte");
	    ch = (char) ich;
	    } while (ch != '\n' && ch != '\r');
	}
    return ch;
}

/* This is useful for PBM files.  It used to be used for PGM and PPM files
   too, since the sample size was always one byte.  Now, use pbm_getrawsample()
   for PGM and PPM files.
*/

unsigned char
pm_getrawbyte(FILE * const file) {
    int iby;

    iby = getc(file);
    if (iby == EOF)
        pm_error("EOF / read error reading a one-byte sample");
    return (unsigned char) iby;
}

unsigned int
pm_getuint(FILE * const ifP) {
/*----------------------------------------------------------------------------
   Read an unsigned integer in ASCII decimal from the file stream
   represented by 'ifP' and return its value.

   If there is nothing at the current position in the file stream that
   can be interpreted as an unsigned integer, issue an error message
   to stderr and abort the program.

   If the number at the current position in the file stream is too
   great to be represented by an 'int' (Yes, I said 'int', not
   'unsigned int'), issue an error message to stderr and abort the
   program.
-----------------------------------------------------------------------------*/
    char ch;
    unsigned int i;

    do {
        ch = pm_getc(ifP);
	} while (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r');

    if (ch < '0' || ch > '9')
        pm_error("junk in file where an unsigned integer should be");

    i = 0;
    do {
        unsigned int const digitVal = ch - '0';

        if (i > INT_MAX/10 - digitVal)
            pm_error("ASCII decimal integer in file is "
                     "too large to be processed.  ");
        i = i * 10 + digitVal;
        ch = pm_getc(ifP);
    } while (ch >= '0' && ch <= '9');

    return i;
}

unsigned int
pm_getraw(FILE *       const file,
          unsigned int const bytes) {

    unsigned int value;  /* our return value */

    if (bytes == 1) {
        /* Here's a speedup for the common 1-byte sample case: */
        value = getc(file);
        if (value == EOF)
            pm_error("EOF/error reading 1 byte sample from file.");
    } else {
        /* This code works for bytes == 1..4 */
        /* We could speed this up by exploiting knowledge of the format of
           an unsigned integer (i.e. endianness).  Then we could just cast
           the value as an array of characters instead of shifting and
           masking.
           */
        int shift;
        unsigned char inval[4];
        int cursor;
        int n_read;

        n_read = fread(inval, bytes, 1, file);
        if (n_read < 1)
            pm_error("EOF/error reading %d byte sample from file.", bytes);
        value = 0;  /* initial value */
        cursor = 0;
        for (shift = (bytes-1)*8; shift >= 0; shift-=8)
            value += inval[cursor++] << shift;
    }
    return(value);
}

void
pm_putraw(FILE *       const file,
          unsigned int const value,
          unsigned int const bytes) {

    if (bytes == 1) {
        /* Here's a speedup for the common 1-byte sample case: */
        int rc;
        rc = fputc(value, file);
        if (rc == EOF)
            pm_error("Error writing 1 byte sample to file.");
    } else {
        /* This code works for bytes == 1..4 */
        /* We could speed this up by exploiting knowledge of the format of
           an unsigned integer (i.e. endianness).  Then we could just cast
           the value as an array of characters instead of shifting and
           masking.
           */
        int shift;
        unsigned char outval[4];
        int cursor;
        int n_written;

        cursor = 0;
        for (shift = (bytes-1)*8; shift >= 0; shift-=8) {
            outval[cursor++] = (value >> shift) & 0xFF;
        }
        n_written = fwrite(&outval, bytes, 1, file);
        if (n_written == 0)
            pm_error("Error writing %d byte sample to file.", bytes);
    }
}


text: public class GameActivateLaserEvent : GameEvent { }

redpajama_set_name: RedPajamaGithub


text:
layout: base
title:  'Statistics of NounType in UD_Erzya-JR'
udver: '2'
---

## Treebank Statistics: UD_Erzya-JR: Features: `NounType`

This feature is language-specific.
It occurs with 1 different values: `Relat`.

158 tokens (1%) have a non-empty value of `NounType`.
66 types (1%) occur at least once with a non-empty value of `NounType`.
20 lemmas (1%) occur at least once with a non-empty value of `NounType`.
The feature is used with 1 part-of-speech tags: <tt>NOUN</tt> (158; 1% instances).

### `NOUN`

158 <tt>NOUN</tt> tokens (3% of all `NOUN` tokens) have a non-empty value of `NounType`.

The most frequent other feature values with which `NOUN` and `NounType` co-occurred: <tt>Number</tt><tt>=Plur,Sing</tt> (140; 89%), <tt>Number[psor]</tt><tt>=EMPTY</tt> (133; 84%), <tt>Person[psor]</tt><tt>=EMPTY</tt> (133; 84%), <tt>Definite</tt><tt>=Ind</tt> (125; 79%).

`NOUN` tokens may have the following values of `NounType`:

* `Relat` (158; 100% of non-empty `NounType`): лангс, лангсо, ланга, юткс, пельде, ланкс, ёнов, пелев, ютксо, лангсто

`NounType` seems to be **lexical feature** of `NOUN`. 100% lemmas (20) occur only with one value of `NounType`.


text:
<?php

namespace ConsoleHelpers\SVNBuddy\Cache;

use ConsoleHelpers\ConsoleKit\ConsoleIO;
use ConsoleHelpers\SVNBuddy\Helper\SizeHelper;

class CacheManager
{

	/**
	 * Working directory.
	 *
	 * @var string
	 */
	private $_workingDirectory;

	/**
	 * Console IO.
	 *
	 * @var ConsoleIO
	 */
	private $_io;

	/**
	 * Size helper.
	 *
	 * @var SizeHelper
	 */
	private $_sizeHelper;

	/**
	 * Create cache manager.
	 *
	 * @param string     $working_directory Working directory.
	 * @param SizeHelper $size_helper       Size helper.
	 * @param ConsoleIO  $io                Console IO.
	 */
	public function __construct($working_directory, SizeHelper $size_helper, ConsoleIO $io = null)
	{
		$this->_workingDirectory = $working_directory;
		$this->_sizeHelper = $size_helper;
		$this->_io = $io;
	}

	/**
	 * Sets value in cache.
	 *
	 * @param string  $name        Name.
	 * @param mixed   $value       Value.
	 * @param mixed   $invalidator Invalidator.
	 * @param integer $duration    Duration in seconds.
	 *
	 * @return void
	 */
	public function setCache($name, $value, $invalidator = null, $duration = null)
	{
		$duration = $this->durationIntoSeconds($duration);

		$storage = $this->_getStorage($name, $duration);
		$storage->set(array(
			'name' => $name,
			'invalidator' => $invalidator,
			'duration' => $duration,
			'expiration' => $duration ? time() + $duration : null,
			'data' => $value,
		));
	}

	/**
	 * Gets value from cache.
	 *
	 * @param string  $name        Name.
	 * @param mixed   $invalidator Invalidator.
	 * @param integer $duration    Duration in seconds.
	 *
	 * @return mixed
	 */
	public function getCache($name, $invalidator = null, $duration = null)
	{
		$storage = $this->_getStorage($name, $this->durationIntoSeconds($duration));
		$cache = $storage->get();

		if ( !is_array($cache) || $cache['invalidator'] !== $invalidator ) {
			$storage->invalidate();

			return null;
		}

		if ( $cache['expiration'] && $cache['expiration'] < time() ) {
			$storage->invalidate();

			return null;
		}

		return $cache['data'];
	}

	/**
	 * Deletes value from cache.
	 *
	 * @param string  $name     Name.
	 * @param integer $duration Duration in seconds.
	 *
	 * @return void
	 */
	public function deleteCache($name, $duration = null)
	{
		$storage = $this->_getStorage($name, $this->durationIntoSeconds($duration));
		$storage->invalidate();
	}

	/**
	 * Converts duration into seconds.
	 *
	 * @param integer $duration Duration in seconds.
	 *
	 * @return integer|null
	 */
	protected function durationIntoSeconds($duration = null)
	{
		if ( !isset($duration) ) {
			return null;
		}

		if ( is_numeric($duration) ) {
			$duration .= ' seconds';
		}

		$now = time();

		return strtotime('+' . $duration, $now) - $now;
	}

	/**
	 * Returns file-based cache storage.
	 *
	 * @param string  $name     Cache name.
	 * @param integer $duration Duration in seconds.
	 *
	 * @return ICacheStorage
	 * @throws \InvalidArgumentException When namespace is missing in the name.
	 */
	private function _getStorage($name, $duration = null)
	{
		$name_parts = explode(':', $name, 2);

		if ( count($name_parts) != 2 ) {
			throw new \InvalidArgumentException('The $name parameter must be in "namespace:name" format.');
		}

		$filename_parts = array(
			$name_parts[0],
			substr(hash_hmac('sha1', $name_parts[1], 'svn-buddy'), 0, 8),
			'D' . (isset($duration) ? $duration : 'INF'),
		);

		$cache_filename = $this->_workingDirectory . DIRECTORY_SEPARATOR . implode('_', $filename_parts) . '.cache';

		if ( isset($this->_io) && $this->_io->isVerbose() ) {
			$message = $cache_filename;

			if ( file_exists($cache_filename) ) {
				$message .= ' (hit: ' . $this->_sizeHelper->formatSize(filesize($cache_filename)) . ')';
			}
			else {
				$message .= ' (miss)';
			}

			$this->_io->writeln(array(
				'',
				'<debug>[cache]: ' . $message . '</debug>',
			));
		}

		return new FileCacheStorage($cache_filename);
	}

}


text:
package commands

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"os"
	gopath "path"
	"strings"

	cmds "github.com/ipfs/go-ipfs/commands"
	core "github.com/ipfs/go-ipfs/core"
	e "github.com/ipfs/go-ipfs/core/commands/e"
	dag "github.com/ipfs/go-ipfs/merkledag"
	mfs "github.com/ipfs/go-ipfs/mfs"
	path "github.com/ipfs/go-ipfs/path"
	ft "github.com/ipfs/go-ipfs/unixfs"
	uio "github.com/ipfs/go-ipfs/unixfs/io"
	cmdkit "gx/ipfs/QmQp2a2Hhb7F6eK2A5hN8f9aJy4mtkEikL9Zj4cgB7d1dD/go-ipfs-cmdkit"

	node "gx/ipfs/QmNwUEK7QbwSqyKBu3mMtToo8SUc6wQJ7gdZq4gGGJqfnf/go-ipld-format"
	logging "gx/ipfs/QmSpJByNKFX1sCsHBEp3R73FL4NF6FnQTEGyNAXHm2GS52/go-log"
	mh "gx/ipfs/QmYeKnKpubCMRiq3PGZcTREErthbb5Q9cXsCoSkD9bjEBd/go-multihash"
	cid "gx/ipfs/QmeSrf6pzut73u6zLQkRFQ3ygt3k6XFT2kjdYP8Tnkwwyg/go-cid"
)

var log = logging.Logger("cmds/files")

var FilesCmd = &cmds.Command{
	Helptext: cmdkit.HelpText{
		Tagline: "Interact with unixfs files.",
		ShortDescription: `
Files is an API for manipulating IPFS objects as if they were a unix
filesystem.

NOTE:
Most of the subcommands of 'ipfs files' accept the '--flush' flag. It defaults
to true. Use caution when setting this flag to false. It will improve
performance for large numbers of file operations, but it does so at the cost
of consistency guarantees. If the daemon is unexpectedly killed before running
'ipfs files flush' on the files in question, then data may be lost. This also
applies to running 'ipfs repo gc' concurrently with '--flush=false'
operations.
`,
	},
	Options: []cmdkit.Option{
		cmdkit.BoolOption("f", "flush", "Flush target and ancestors after write.").WithDefault(true),
	},
	Subcommands: map[string]*cmds.Command{
		"read":  FilesReadCmd,
		"write": FilesWriteCmd,
		"mv":    FilesMvCmd,
		"cp":    FilesCpCmd,
		"ls":    FilesLsCmd,
		"mkdir": FilesMkdirCmd,
		"stat":  FilesStatCmd,
		"rm":    FilesRmCmd,
		"flush": FilesFlushCmd,
		"chcid": FilesChcidCmd,
	},
}

var cidVersionOption = cmdkit.IntOption("cid-version", "cid-ver", "Cid version to use. (experimental)")
var hashOption = cmdkit.StringOption("hash", "Hash function to use. Will set Cid version to 1 if used. (experimental)")

var formatError = errors.New("Format was set by multiple options. Only one format option is allowed")

var FilesStatCmd = &cmds.Command{
	Helptext: cmdkit.HelpText{
		Tagline: "Display file status.",
	},

	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("path", true, false, "Path to node to stat."),
	},
	Options: []cmdkit.Option{
		cmdkit.StringOption("format", "Print statistics in given format. Allowed tokens: "+
			"<hash> <size> <cumulsize> <type> <childs>. Conflicts with other format options.").WithDefault(
			`<hash>
Size: <size>
CumulativeSize: <cumulsize>
ChildBlocks: <childs>
Type: <type>`),
		cmdkit.BoolOption("hash", "Print only hash. Implies '--format=<hash>'. Conflicts with other format options."),
		cmdkit.BoolOption("size", "Print only size. Implies '--format=<cumulsize>'. Conflicts with other format options."),
	},
	Run: func(req cmds.Request, res cmds.Response) {

		_, err := statGetFormatOptions(req)
		if err != nil {
			res.SetError(err, cmdkit.ErrClient)
		}

		node, err := req.InvocContext().GetNode()
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		path, err := checkPath(req.Arguments()[0])
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		fsn, err := mfs.Lookup(node.FilesRoot, path)
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		o, err := statNode(node.DAG, fsn)
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		res.SetOutput(o)
	},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: func(res cmds.Response) (io.Reader, error) {
			v, err := unwrapOutput(res.Output())
			if err != nil {
				return nil, err
			}

			out, ok := v.(*Object)
			if !ok {
				return nil, e.TypeErr(out, v)
			}
			buf := new(bytes.Buffer)

			s, _ := statGetFormatOptions(res.Request())
			s = strings.Replace(s, "<hash>", out.Hash, -1)
			s = strings.Replace(s, "<size>", fmt.Sprintf("%d", out.Size), -1)
			s = strings.Replace(s, "<cumulsize>", fmt.Sprintf("%d", out.CumulativeSize), -1)
			s = strings.Replace(s, "<childs>", fmt.Sprintf("%d", out.Blocks), -1)
			s = strings.Replace(s, "<type>", out.Type, -1)

			fmt.Fprintln(buf, s)
			return buf, nil
		},
	},
	Type: Object{},
}

func moreThanOne(a, b, c bool) bool {
	return a && b || b && c || a && c
}

func statGetFormatOptions(req cmds.Request) (string, error) {

	hash, _, _ := req.Option("hash").Bool()
	size, _, _ := req.Option("size").Bool()
	format, found, _ := req.Option("format").String()

	if moreThanOne(hash, size, found) {
		return "", formatError
	}

	if hash {
		return "<hash>", nil
	} else if size {
		return "<cumulsize>", nil
	} else {
		return format, nil
	}
}

func statNode(ds dag.DAGService, fsn mfs.FSNode) (*Object, error) {
	nd, err := fsn.GetNode()
	if err != nil {
		return nil, err
	}

	c := nd.Cid()

	cumulsize, err := nd.Size()
	if err != nil {
		return nil, err
	}

	switch n := nd.(type) {
	case *dag.ProtoNode:
		d, err := ft.FromBytes(n.Data())
		if err != nil {
			return nil, err
		}

		var ndtype string
		switch fsn.Type() {
		case mfs.TDir:
			ndtype = "directory"
		case mfs.TFile:
			ndtype = "file"
		default:
			return nil, fmt.Errorf("unrecognized node type: %s", fsn.Type())
		}

		return &Object{
			Hash:           c.String(),
			Blocks:         len(nd.Links()),
			Size:           d.GetFilesize(),
			CumulativeSize: cumulsize,
			Type:           ndtype,
		}, nil
	case *dag.RawNode:
		return &Object{
			Hash:           c.String(),
			Blocks:         0,
			Size:           cumulsize,
			CumulativeSize: cumulsize,
			Type:           "file",
		}, nil
	default:
		return nil, fmt.Errorf("not unixfs node (proto or raw)")
	}
}

var FilesCpCmd = &cmds.Command{
	Helptext: cmdkit.HelpText{
		Tagline: "Copy files into mfs.",
	},
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("source", true, false, "Source object to copy."),
		cmdkit.StringArg("dest", true, false, "Destination to copy object to."),
	},
	Run: func(req cmds.Request, res cmds.Response) {
		node, err := req.InvocContext().GetNode()
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		flush, _, _ := req.Option("flush").Bool()

		src, err := checkPath(req.Arguments()[0])
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}
		src = strings.TrimRight(src, "/")

		dst, err := checkPath(req.Arguments()[1])
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		if dst[len(dst)-1] == '/' {
			dst += gopath.Base(src)
		}

		nd, err := getNodeFromPath(req.Context(), node, src)
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		err = mfs.PutNode(node.FilesRoot, dst, nd)
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		if flush {
			err := mfs.FlushPath(node.FilesRoot, dst)
			if err != nil {
				res.SetError(err, cmdkit.ErrNormal)
				return
			}
		}

		res.SetOutput(nil)
	},
}

func getNodeFromPath(ctx context.Context, node *core.IpfsNode, p string) (node.Node, error) {
	switch {
	case strings.HasPrefix(p, "/ipfs/"):
		np, err := path.ParsePath(p)
		if err != nil {
			return nil, err
		}

		resolver := &path.Resolver{
			DAG:         node.DAG,
			ResolveOnce: uio.ResolveUnixfsOnce,
		}

		return core.Resolve(ctx, node.Namesys, resolver, np)
	default:
		fsn, err := mfs.Lookup(node.FilesRoot, p)
		if err != nil {
			return nil, err
		}

		return fsn.GetNode()
	}
}

type Object struct {
	Hash           string
	Size           uint64
	CumulativeSize uint64
	Blocks         int
	Type           string
}

type FilesLsOutput struct {
	Entries []mfs.NodeListing
}

var FilesLsCmd = &cmds.Command{
	Helptext: cmdkit.HelpText{
		Tagline: "List directories in the local mutable namespace.",
		ShortDescription: `
List directories in the local mutable namespace.

Examples:

    $ ipfs files ls /welcome/docs/
    about
    contact
    help
    quick-start
    readme
    security-notes

    $ ipfs files ls /myfiles/a/b/c/d
    foo
    bar
`,
	},
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("path", false, false, "Path to show listing for. Defaults to '/'."),
	},
	Options: []cmdkit.Option{
		cmdkit.BoolOption("l", "Use long listing format."),
	},
	Run: func(req cmds.Request, res cmds.Response) {
		var arg string

		if len(req.Arguments()) == 0 {
			arg = "/"
		} else {
			arg = req.Arguments()[0]
		}

		path, err := checkPath(arg)
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		nd, err := req.InvocContext().GetNode()
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		fsn, err := mfs.Lookup(nd.FilesRoot, path)
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		long, _, _ := req.Option("l").Bool()

		switch fsn := fsn.(type) {
		case *mfs.Directory:
			if !long {
				var output []mfs.NodeListing
				names, err := fsn.ListNames(req.Context())
				if err != nil {
					res.SetError(err, cmdkit.ErrNormal)
					return
				}

				for _, name := range names {
					output = append(output, mfs.NodeListing{
						Name: name,
					})
				}
				res.SetOutput(&FilesLsOutput{output})
			} else {
				listing, err := fsn.List(req.Context())
				if err != nil {
					res.SetError(err, cmdkit.ErrNormal)
					return
				}
				res.SetOutput(&FilesLsOutput{listing})
			}
			return
		case *mfs.File:
			_, name := gopath.Split(path)
			out := &FilesLsOutput{[]mfs.NodeListing{mfs.NodeListing{Name: name, Type: 1}}}
			res.SetOutput(out)
			return
		default:
			res.SetError(errors.New("unrecognized type"), cmdkit.ErrNormal)
		}
	},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: func(res cmds.Response) (io.Reader, error) {
			v, err := unwrapOutput(res.Output())
			if err != nil {
				return nil, err
			}

			out, ok := v.(*FilesLsOutput)
			if !ok {
				return nil, e.TypeErr(out, v)
			}

			buf := new(bytes.Buffer)
			long, _, _ := res.Request().Option("l").Bool()

			for _, o := range out.Entries {
				if long {
					fmt.Fprintf(buf, "%s\t%s\t%d\n", o.Name, o.Hash, o.Size)
				} else {
					fmt.Fprintf(buf, "%s\n", o.Name)
				}
			}
			return buf, nil
		},
	},
	Type: FilesLsOutput{},
}

var FilesReadCmd = &cmds.Command{
	Helptext: cmdkit.HelpText{
		Tagline: "Read a file in a given mfs.",
		ShortDescription: `
Read a specified number of bytes from a file at a given offset. By default,
will read the entire file similar to unix cat.

Examples:

    $ ipfs files read /test/hello
    hello
        `,
	},

	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("path", true, false, "Path to file to be read."),
	},
	Options: []cmdkit.Option{
		cmdkit.IntOption("offset", "o", "Byte offset to begin reading from."),
		cmdkit.IntOption("count", "n", "Maximum number of bytes to read."),
	},
	Run: func(req cmds.Request, res cmds.Response) {
		n, err := req.InvocContext().GetNode()
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		path, err := checkPath(req.Arguments()[0])
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		fsn, err := mfs.Lookup(n.FilesRoot, path)
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		fi, ok := fsn.(*mfs.File)
		if !ok {
			res.SetError(fmt.Errorf("%s was not a file.", path), cmdkit.ErrNormal)
			return
		}

		rfd, err := fi.Open(mfs.OpenReadOnly, false)
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		defer rfd.Close()

		offset, _, err := req.Option("offset").Int()
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}
		if offset < 0 {
			res.SetError(fmt.Errorf("Cannot specify negative offset."), cmdkit.ErrNormal)
			return
		}

		filen, err := rfd.Size()
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		if int64(offset) > filen {
			res.SetError(fmt.Errorf("Offset was past end of file (%d > %d).", offset, filen), cmdkit.ErrNormal)
			return
		}

		_, err = rfd.Seek(int64(offset), io.SeekStart)
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		var r io.Reader = &contextReaderWrapper{R: rfd, ctx: req.Context()}
		count, found, err := req.Option("count").Int()
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}
		if found {
			if count < 0 {
				res.SetError(fmt.Errorf("Cannot specify negative 'count'."), cmdkit.ErrNormal)
				return
			}
			r = io.LimitReader(r, int64(count))
		}

		res.SetOutput(r)
	},
}

type contextReader interface {
	CtxReadFull(context.Context, []byte) (int, error)
}

type contextReaderWrapper struct {
	R   contextReader
	ctx context.Context
}

func (crw *contextReaderWrapper) Read(b []byte) (int, error) {
	return crw.R.CtxReadFull(crw.ctx, b)
}

var FilesMvCmd = &cmds.Command{
	Helptext: cmdkit.HelpText{
		Tagline: "Move files.",
		ShortDescription: `
Move files around. Just like traditional unix mv.

Example:

    $ ipfs files mv /myfs/a/b/c /myfs/foo/newc

`,
	},

	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("source", true, false, "Source file to move."),
		cmdkit.StringArg("dest", true, false, "Destination path for file to be moved to."),
	},
	Run: func(req cmds.Request, res cmds.Response) {
		n, err := req.InvocContext().GetNode()
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		src, err := checkPath(req.Arguments()[0])
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}
		dst, err := checkPath(req.Arguments()[1])
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		err = mfs.Mv(n.FilesRoot, src, dst)
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		res.SetOutput(nil)
	},
}

var FilesWriteCmd = &cmds.Command{
	Helptext: cmdkit.HelpText{
		Tagline: "Write to a mutable file in a given filesystem.",
		ShortDescription: `
Write data to a file in a given filesystem. This command allows you to specify
a beginning offset to write to. The entire length of the input will be
written.

If the '--create' option is specified, the file will be created if it does not
exist. Nonexistant intermediate directories will not be created.

Newly created files will have the same CID version and hash function of the
parent directory unless the --cid-version and --hash options are used.

Newly created leaves will be in the legacy format (Protobuf) if the
CID version is 0, or raw is the CID version is non-zero.  Use of the
--raw-leaves option will override this behavior.

If the '--flush' option is set to false, changes will not be propogated to the
merkledag root. This can make operations much faster when doing a large number
of writes to a deeper directory structure.

EXAMPLE:

    echo "hello world" | ipfs files write --create /myfs/a/b/file
    echo "hello world" | ipfs files write --truncate /myfs/a/b/file

WARNING:

Usage of the '--flush=false' option does not guarantee data durability until
the tree has been flushed. This can be accomplished by running 'ipfs files
stat' on the file or any of its ancestors.
`,
	},
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("path", true, false, "Path to write to."),
		cmdkit.FileArg("data", true, false, "Data to write.").EnableStdin(),
	},
	Options: []cmdkit.Option{
		cmdkit.IntOption("offset", "o", "Byte offset to begin writing at."),
		cmdkit.BoolOption("create", "e", "Create the file if it does not exist."),
		cmdkit.BoolOption("truncate", "t", "Truncate the file to size zero before writing."),
		cmdkit.IntOption("count", "n", "Maximum number of bytes to read."),
		cmdkit.BoolOption("raw-leaves", "Use raw blocks for newly created leaf nodes. (experimental)"),
		cidVersionOption,
		hashOption,
	},
	Run: func(req cmds.Request, res cmds.Response) {
		path, err := checkPath(req.Arguments()[0])
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		create, _, _ := req.Option("create").Bool()
		trunc, _, _ := req.Option("truncate").Bool()
		flush, _, _ := req.Option("flush").Bool()
		rawLeaves, rawLeavesDef, _ := req.Option("raw-leaves").Bool()

		prefix, err := getPrefix(req)
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		nd, err := req.InvocContext().GetNode()
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		offset, _, err := req.Option("offset").Int()
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}
		if offset < 0 {
			res.SetError(fmt.Errorf("cannot have negative write offset"), cmdkit.ErrNormal)
			return
		}

		fi, err := getFileHandle(nd.FilesRoot, path, create, prefix)
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}
		if rawLeavesDef {
			fi.RawLeaves = rawLeaves
		}

		wfd, err := fi.Open(mfs.OpenWriteOnly, flush)
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		defer func() {
			err := wfd.Close()
			if err != nil {
				res.SetError(err, cmdkit.ErrNormal)
			}
		}()

		if trunc {
			if err := wfd.Truncate(0); err != nil {
				res.SetError(err, cmdkit.ErrNormal)
				return
			}
		}

		count, countfound, err := req.Option("count").Int()
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}
		if countfound && count < 0 {
			res.SetError(fmt.Errorf("cannot have negative byte count"), cmdkit.ErrNormal)
			return
		}

		_, err = wfd.Seek(int64(offset), io.SeekStart)
		if err != nil {
			log.Error("seekfail: ", err)
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		input, err := req.Files().NextFile()
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		var r io.Reader = input
		if countfound {
			r = io.LimitReader(r, int64(count))
		}

		_, err = io.Copy(wfd, r)
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		res.SetOutput(nil)
	},
}

var FilesMkdirCmd = &cmds.Command{
	Helptext: cmdkit.HelpText{
		Tagline: "Make directories.",
		ShortDescription: `
Create the directory if it does not already exist.

The directory will have the same CID version and hash function of the
parent directory unless the --cid-version and --hash options are used.

NOTE: All paths must be absolute.

Examples:

    $ ipfs files mkdir /test/newdir
    $ ipfs files mkdir -p /test/does/not/exist/yet
`,
	},

	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("path", true, false, "Path to dir to make."),
	},
	Options: []cmdkit.Option{
		cmdkit.BoolOption("parents", "p", "No error if existing, make parent directories as needed."),
		cidVersionOption,
		hashOption,
	},
	Run: func(req cmds.Request, res cmds.Response) {
		n, err := req.InvocContext().GetNode()
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		dashp, _, _ := req.Option("parents").Bool()
		dirtomake, err := checkPath(req.Arguments()[0])
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		flush, _, _ := req.Option("flush").Bool()

		prefix, err := getPrefix(req)
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}
		root := n.FilesRoot

		err = mfs.Mkdir(root, dirtomake, mfs.MkdirOpts{
			Mkparents: dashp,
			Flush:     flush,
			Prefix:    prefix,
		})
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		res.SetOutput(nil)
	},
}

var FilesFlushCmd = &cmds.Command{
	Helptext: cmdkit.HelpText{
		Tagline: "Flush a given path's data to disk.",
		ShortDescription: `
Flush a given path to disk. This is only useful when other commands
are run with the '--flush=false'.
`,
	},
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("path", false, false, "Path to flush. Default: '/'."),
	},
	Run: func(req cmds.Request, res cmds.Response) {
		nd, err := req.InvocContext().GetNode()
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		path := "/"
		if len(req.Arguments()) > 0 {
			path = req.Arguments()[0]
		}

		err = mfs.FlushPath(nd.FilesRoot, path)
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		res.SetOutput(nil)
	},
}

var FilesChcidCmd = &cmds.Command{
	Helptext: cmdkit.HelpText{
		Tagline: "Change the cid version or hash function of the root node of a given path.",
		ShortDescription: `
Change the cid version or hash function of the root node of a given path.
`,
	},
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("path", false, false, "Path to change. Default: '/'."),
	},
	Options: []cmdkit.Option{
		cidVersionOption,
		hashOption,
	},
	Run: func(req cmds.Request, res cmds.Response) {
		nd, err := req.InvocContext().GetNode()
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		path := "/"
		if len(req.Arguments()) > 0 {
			path = req.Arguments()[0]
		}

		flush, _, _ := req.Option("flush").Bool()

		prefix, err := getPrefix(req)
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		err = updatePath(nd.FilesRoot, path, prefix, flush)
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		res.SetOutput(nil)
	},
}

func updatePath(rt *mfs.Root, pth string, prefix *cid.Prefix, flush bool) error {
	if prefix == nil {
		return nil
	}

	nd, err := mfs.Lookup(rt, pth)
	if err != nil {
		return err
	}

	switch n := nd.(type) {
	case *mfs.Directory:
		n.SetPrefix(prefix)
	default:
		return fmt.Errorf("can only update directories")
	}

	if flush {
		nd.Flush()
	}

	return nil
}

var FilesRmCmd = &cmds.Command{
	Helptext: cmdkit.HelpText{
		Tagline: "Remove a file.",
		ShortDescription: `
Remove files or directories.

    $ ipfs files rm /foo
    $ ipfs files ls /bar
    cat
    dog
    fish
    $ ipfs files rm -r /bar
`,
	},

	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("path", true, true, "File to remove."),
	},
	Options: []cmdkit.Option{
		cmdkit.BoolOption("recursive", "r", "Recursively remove directories."),
	},
	Run: func(req cmds.Request, res cmds.Response) {
		defer res.SetOutput(nil)

		nd, err := req.InvocContext().GetNode()
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		path, err := checkPath(req.Arguments()[0])
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		if path == "/" {
			res.SetError(fmt.Errorf("cannot delete root"), cmdkit.ErrNormal)
			return
		}

		// 'rm a/b/c/' will fail unless we trim the slash at the end
		if path[len(path)-1] == '/' {
			path = path[:len(path)-1]
		}

		dir, name := gopath.Split(path)
		parent, err := mfs.Lookup(nd.FilesRoot, dir)
		if err != nil {
			res.SetError(fmt.Errorf("parent lookup: %s", err), cmdkit.ErrNormal)
			return
		}

		pdir, ok := parent.(*mfs.Directory)
		if !ok {
			res.SetError(fmt.Errorf("No such file or directory: %s", path), cmdkit.ErrNormal)
			return
		}

		dashr, _, _ := req.Option("r").Bool()

		var success bool
		defer func() {
			if success {
				err := pdir.Flush()
				if err != nil {
					res.SetError(err, cmdkit.ErrNormal)
					return
				}
			}
		}()

		// if '-r' specified, don't check file type (in bad scenarios, the block may not exist)
		if dashr {
			err := pdir.Unlink(name)
			if err != nil {
				res.SetError(err, cmdkit.ErrNormal)
				return
			}

			success = true
			return
		}

		childi, err := pdir.Child(name)
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		switch childi.(type) {
		case *mfs.Directory:
			res.SetError(fmt.Errorf("%s is a directory, use -r to remove directories", path), cmdkit.ErrNormal)
			return
		default:
			err := pdir.Unlink(name)
			if err != nil {
				res.SetError(err, cmdkit.ErrNormal)
				return
			}

			success = true
		}
	},
}

func getPrefix(req cmds.Request) (*cid.Prefix, error) {
	cidVer, cidVerSet, _ := req.Option("cid-version").Int()
	hashFunStr, hashFunSet, _ := req.Option("hash").String()

	if !cidVerSet && !hashFunSet {
		return nil, nil
	}

	if hashFunSet && cidVer == 0 {
		cidVer = 1
	}

	prefix, err := dag.PrefixForCidVersion(cidVer)
	if err != nil {
		return nil, err
	}

	if hashFunSet {
		hashFunCode, ok := mh.Names[strings.ToLower(hashFunStr)]
		if !ok {
			return nil, fmt.Errorf("unrecognized hash function: %s", strings.ToLower(hashFunStr))
		}
		prefix.MhType = hashFunCode
		prefix.MhLength = -1
	}

	return &prefix, nil
}

func getFileHandle(r *mfs.Root, path string, create bool, prefix *cid.Prefix) (*mfs.File, error) {
	target, err := mfs.Lookup(r, path)
	switch err {
	case nil:
		fi, ok := target.(*mfs.File)
		if !ok {
			return nil, fmt.Errorf("%s was not a file", path)
		}
		return fi, nil

	case os.ErrNotExist:
		if !create {
			return nil, err
		}

		// if create is specified and the file doesnt exist, we create the file
		dirname, fname := gopath.Split(path)
		pdiri, err := mfs.Lookup(r, dirname)
		if err != nil {
			log.Error("lookupfail ", dirname)
			return nil, err
		}
		pdir, ok := pdiri.(*mfs.Directory)
		if !ok {
			return nil, fmt.Errorf("%s was not a directory", dirname)
		}
		if prefix == nil {
			prefix = pdir.GetPrefix()
		}

		nd := dag.NodeWithData(ft.FilePBData(nil, 0))
		nd.SetPrefix(prefix)
		err = pdir.AddChild(fname, nd)
		if err != nil {
			return nil, err
		}

		fsn, err := pdir.Child(fname)
		if err != nil {
			return nil, err
		}

		fi, ok := fsn.(*mfs.File)
		if !ok {
			return nil, errors.New("Expected *mfs.File, didnt get it. This is likely a race condition.")
		}
		return fi, nil

	default:
		return nil, err
	}
}

func checkPath(p string) (string, error) {
	if len(p) == 0 {
		return "", fmt.Errorf("Paths must not be empty.")
	}

	if p[0] != '/' {
		return "", fmt.Errorf("Paths must start with a leading slash.")
	}

	cleaned := gopath.Clean(p)
	if p[len(p)-1] == '/' && p != "/" {
		cleaned += "/"
	}
	return cleaned, nil
}

// copy+pasted from ../commands.go
func unwrapOutput(i interface{}) (interface{}, error) {
	var (
		ch <-chan interface{}
		ok bool
	)

	if ch, ok = i.(<-chan interface{}); !ok {
		return nil, e.TypeErr(ch, i)
	}

	return <-ch, nil
}


text:
#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_FUNCTION_BODY_H_
#define TENSORFLOW_CORE_COMMON_RUNTIME_FUNCTION_BODY_H_

#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/gtl/inlined_vector.h"

namespace tensorflow {

class Graph;
class Node;

// FunctionLibraryRuntime::GetFunctionBody returns a description of an
// instantiated function that is represented as a Graph with arg/ret
// nodes annotated.
struct FunctionBody {
  FunctionDef fdef;
  Graph* graph = nullptr;  // owned.
  DataTypeVector arg_types;
  DataTypeVector ret_types;
  // arg_nodes[i] contains the i'th function input. In other words,
  // GetNodeAttr(arg_nodes[i]->attrs(), "index") == i.
  gtl::InlinedVector<Node*, 4> arg_nodes;
  // ret_nodes[i] contains the i'th function output. In other words,
  // GetNodeAttr(ret_nodes[i]->attrs(), "index") == i.
  gtl::InlinedVector<Node*, 4> ret_nodes;
  gtl::InlinedVector<Node*, 4> control_ret_nodes;

  FunctionBody() {}
  FunctionBody(const FunctionDef& f, DataTypeSlice arg_types,
               DataTypeSlice ret_types, Graph* g);
  ~FunctionBody();
};

}  // end namespace tensorflow

#endif  // TENSORFLOW_CORE_COMMON_RUNTIME_FUNCTION_BODY_H_


text:
package com.google.android.gms.internal;

import android.os.Bundle;
import com.google.android.gms.common.data.DataHolder;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.metadata.internal.f;
import java.util.Arrays;

public class fj extends f<DriveId>
{
  public static final fj rN = new fj();

  private fj()
  {
    super("driveId", Arrays.asList(new String[] { "sqlId", "resourceId" }));
  }

  protected DriveId g(DataHolder paramDataHolder, int paramInt1, int paramInt2)
  {
    long l1 = paramDataHolder.getMetadata().getLong("dbInstanceId");
    String str1 = paramDataHolder.getString("resourceId", paramInt1, paramInt2);
    String str2 = str1;
    if ((str1 != null) && (str2.startsWith("generated-android-")))
      str2 = null;
    long l2 = Long.valueOf(paramDataHolder.getLong("sqlId", paramInt1, paramInt2)).longValue();
    return new DriveId(str2, l2, l1);
  }
}

/* Location:           /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
 * Qualified Name:     com.google.android.gms.internal.fj
 * JD-Core Version:    0.6.2
 */


text:
package org.deviceconnect.android.deviceplugin.host.recorder.camera;

import org.deviceconnect.android.deviceplugin.host.recorder.AbstractSRTPreviewServer;
import org.deviceconnect.android.libmedia.streaming.video.VideoEncoder;

public class Camera2SRTPreviewServer extends AbstractSRTPreviewServer {
    Camera2SRTPreviewServer(Camera2Recorder recorder, String encoderId) {
        super(recorder, encoderId);
    }

    @Override
    protected VideoEncoder createVideoEncoder() {
        Camera2Recorder recorder = (Camera2Recorder) getRecorder();
        switch (getEncoderSettings().getPreviewEncoderName()) {
            case H264:
            default:
                return new CameraVideoEncoder(recorder);
            case H265:
                return new CameraVideoEncoder(recorder, "video/hevc");
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<scanner domain="br.com.company" project="project">
	<structure>
		<package>org.wave.test.core</package>
		<package>br.com.company.project.empty</package>
	</structure>
</scanner>


text:
import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'

import { Message } from 'src'

const RadioTypesExamples = () => (
  <ExampleSection title='Types'>
    <ComponentExample
      title='Radio'
      description='A radio for checking.'
      examplePath='addons/Radio/Types/RadioExampleRadio'
    />
    <ComponentExample
      title='Toggle'
      description='A radio can toggle.'
      examplePath='addons/Radio/Types/RadioExampleToggle'
    />
    <ComponentExample
      title='Slider'
      description='A radio can look like a slider.'
      examplePath='addons/Radio/Types/RadioExampleSlider'
    />
    <ComponentExample
      title='Radio Group'
      description='Radios can be part of a group.'
      examplePath='addons/Radio/Types/RadioExampleRadioGroup'
    >
      <Message warning>
        Radios in a group must be
        <a
          href='https://facebook.github.io/react/docs/forms.html#controlled-components'
          rel='noopener noreferrer'
          target='_blank'
        >
           controlled components.
        </a>
      </Message>
    </ComponentExample>
  </ExampleSection>
)

export default RadioTypesExamples


text:
//#include <cmath>

#if GOOGLE_CUDA

#include "euclidean_dist_grad.h"

//#include "cuda/include/cuda.h"
#include "cuda.h"
//#include "tensorflow/core/platform/stream_executor.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"

namespace tensorflow {

template <typename T>
__global__ void EuclideanDistGrad(const T* in1, const T* in2, const T* in3, const T* in4, const int n, const int d, const int k, T* out1, T* out2) {
  for (int in = blockIdx.x; in < n; in += gridDim.x) {
    for (int id = threadIdx.x; id < d; id += blockDim.x) {
      out1[in*d+id] = 0;
    }
  }
  for (int id = blockIdx.x; id < d; id += gridDim.x) {
    for (int ik = threadIdx.x; ik < k; ik += blockDim.x) {
      out2[id*k+ik] = 0;
    }
  }
  for (int in = blockIdx.x; in < n; in += gridDim.x) {
    for (int ik = 0; ik < k; ik ++) {
      T tempMultiplicand = in4[in*k+ik]/in3[in*k+ik];
      for (int id = threadIdx.x; id < d; id += blockDim.x) {
        T temp = (in1[in*d+id] - in2[id*k+ik])*tempMultiplicand;
        out1[in*d+id]+=temp;
      }
    }
  }
  for (int in = 0; in < n; in ++) {
    for (int ik = threadIdx.x; ik < k; ik += blockDim.x) {
      T tempMultiplicand = in4[in*k+ik]/in3[in*k+ik];
      for (int id = blockIdx.x; id < d; id += gridDim.x) {
        T temp = (in1[in*d+id] - in2[id*k+ik])*tempMultiplicand;
        out2[id*k+ik]-=temp;
      }
    }
  }
}

/* // Not available to user kernels
namespace {
template <typename T>
perftools::gputools::DeviceMemory<T> AsDeviceMemory(const T* cuda_memory) {
  perftools::gputools::DeviceMemoryBase wrapped(const_cast<T*>(cuda_memory));
  perftools::gputools::DeviceMemory<T> typed(wrapped);
  return typed;
}
}  // namespace
*/

template <typename T>
void LaunchEuclideanDistGradGPU<T>::launch(
      OpKernelContext* ctx, OpKernel* kernel, const Tensor& a, const Tensor& b,
      const Tensor& d, const Tensor& g, Tensor* xout, Tensor* cout) {
  const uint64 r1 = a.dim_size(0);
  const uint64 c1 = a.dim_size(1);
  const uint64 c2 = b.dim_size(1);

  auto* stream = ctx->op_device_context()->stream();
  OP_REQUIRES(ctx, stream, errors::Internal("No GPU stream available."));

  //Not available to user kernels.
  //auto a_ptr = AsDeviceMemory(a.template flat<T>().data());
  //auto b_ptr = AsDeviceMemory(b.template flat<T>().data());
  //auto d_ptr = AsDeviceMemory(d.template flat<T>().data());
  //auto g_ptr = AsDeviceMemory(g.template flat<T>().data());
  //auto x_ptr = AsDeviceMemory(xout->template flat<T>().data());
  //auto c_ptr = AsDeviceMemory(out->template flat<T>().data());
  auto a_ptr = a.template flat<T>().data();
  auto b_ptr = b.template flat<T>().data();
  auto d_ptr = d.template flat<T>().data();
  auto g_ptr = g.template flat<T>().data();
  auto x_ptr = xout->template flat<T>().data();
  auto c_ptr = cout->template flat<T>().data();

  EuclideanDistGrad<T><<<32, 256>>>(a_ptr, b_ptr, d_ptr, g_ptr, r1, c1, c2, x_ptr, c_ptr);
}

template struct LaunchEuclideanDistGradGPU<double>;
template struct LaunchEuclideanDistGradGPU<float>;
template struct LaunchEuclideanDistGradGPU<int>;

}  // namespace tensorflow

#endif


text:
package com.ruesga.rview.fragments;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

import com.ruesga.rview.R;
import com.ruesga.rview.databinding.EditDialogBinding;

import java.util.regex.Pattern;

import androidx.annotation.Keep;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

public class EditDialogFragment extends RevealDialogFragment {

    public static final String TAG = "EditDialogFragment";

    private static final String EXTRA_TITLE = "title";
    private static final String EXTRA_SUBTITLE = "subtitle";
    private static final String EXTRA_VALUE = "value";
    private static final String EXTRA_HINT = "hint";
    private static final String EXTRA_ACTION = "action";
    private static final String EXTRA_ALLOW_EMPTY = "allow_empty";
    private static final String EXTRA_ALLOW_SUGGESTIONS = "allow_suggestions";
    private static final String EXTRA_USE_MULTI_LINE = "multi_line";
    private static final String EXTRA_REGEXP = "regexp";

    private static final String EXTRA_REQUEST_CODE = "request_code";
    private static final String EXTRA_REQUEST_DATA= "request_data";

    @Keep
    public static class Model {
        public String subtitle;
        public String value;
        public String hint;
        boolean allowEmpty;
        public boolean isMultiLine;
        public Pattern regexp;
    }

    public interface OnEditChanged {
        void onEditChanged(int requestCode, @Nullable Bundle requestData, String newValue);
    }

    private final TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            enabledOrDisableButtons(s.toString());
        }
    };

    public static EditDialogFragment newInstance(String title, String subtitle, String value,
            String action, String hint, boolean allowEmpty, boolean allowSuggestions,
            boolean multiLine, String regexp, View anchor, int requestCode,
            @Nullable Bundle data) {
        EditDialogFragment fragment = new EditDialogFragment();
        Bundle arguments = new Bundle();
        arguments.putString(EXTRA_TITLE, title);
        if (!TextUtils.isEmpty(subtitle)) {
            arguments.putString(EXTRA_SUBTITLE, subtitle);
        }
        arguments.putString(EXTRA_VALUE, value);
        arguments.putString(EXTRA_ACTION, action);
        arguments.putString(EXTRA_HINT, hint);
        arguments.putBoolean(EXTRA_ALLOW_EMPTY, allowEmpty);
        arguments.putBoolean(EXTRA_ALLOW_SUGGESTIONS, allowSuggestions);
        arguments.putBoolean(EXTRA_USE_MULTI_LINE, multiLine);
        if (!TextUtils.isEmpty(regexp)) {
            arguments.putString(EXTRA_REGEXP, regexp);
        }
        arguments.putParcelable(EXTRA_ANCHOR, computeViewOnScreen(anchor));
        arguments.putInt(EXTRA_REQUEST_CODE, requestCode);
        if (data != null) {
            arguments.putBundle(EXTRA_REQUEST_DATA, data);
        }
        fragment.setArguments(arguments);
        return fragment;
    }

    private int mRequestCode;
    private Bundle mRequestData;
    private Pattern mRegExp = null;

    protected EditDialogBinding mBinding;
    private final Model mModel = new Model();

    private String mOriginalValue;

    public EditDialogFragment() {
    }

    @Override
    public void buildDialog(AlertDialog.Builder builder, Bundle savedInstanceState) {
        //noinspection ConstantConditions
        String title = getArguments().getString(EXTRA_TITLE);
        String action = getArguments().getString(EXTRA_ACTION);
        if (TextUtils.isEmpty(action)) {
            action = getString(R.string.action_change);
        }

        boolean allowSuggestions = getArguments().getBoolean(EXTRA_ALLOW_SUGGESTIONS, false);
        int inputType = InputType.TYPE_CLASS_TEXT |
                (mModel.isMultiLine ? InputType.TYPE_TEXT_FLAG_MULTI_LINE : 0) |
                (allowSuggestions ? 0 : InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

        LayoutInflater inflater = LayoutInflater.from(builder.getContext());
        mBinding = DataBindingUtil.inflate(inflater, R.layout.edit_dialog, null, true);
        mBinding.edit.setInputType(inputType);
        mBinding.edit.addTextChangedListener(mTextWatcher);
        mBinding.setModel(mModel);

        builder.setTitle(title)
                .setView(mBinding.getRoot())
                .setNegativeButton(R.string.action_cancel, null)
                .setPositiveButton(action, (dialog, which) -> performEditChanged());
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //noinspection ConstantConditions
        mRequestCode = getArguments().getInt(EXTRA_REQUEST_CODE);
        if (getArguments().containsKey(EXTRA_REQUEST_DATA)) {
            mRequestData = getArguments().getBundle(EXTRA_REQUEST_DATA);
        }
        if (getArguments().containsKey(EXTRA_REGEXP)) {
            //noinspection ConstantConditions
            mRegExp = Pattern.compile(getArguments().getString(EXTRA_REGEXP));
        }

        mModel.subtitle = getArguments().getString(EXTRA_SUBTITLE);
        if (savedInstanceState != null) {
            mModel.value = savedInstanceState.getString(EXTRA_VALUE, null);
        } else {
            mModel.value = getArguments().getString(EXTRA_VALUE);
        }
        mModel.hint = getArguments().getString(EXTRA_HINT);
        mModel.allowEmpty = getArguments().getBoolean(EXTRA_ALLOW_EMPTY, false);
        mModel.isMultiLine = getArguments().getBoolean(EXTRA_USE_MULTI_LINE, false);
        mOriginalValue = "";
    }

    @Override
    public void onDialogReveled() {
        enabledOrDisableButtons(mModel.value == null ? "" : mModel.value);
        mBinding.edit.clearFocus();
        mBinding.edit.requestFocus();
        mBinding.edit.selectAll();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mBinding.unbind();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        String v = mBinding.edit.getText().toString();
        if (!TextUtils.isEmpty(v)) {
            outState.putString(EXTRA_VALUE, v);
        }
    }

    private void performEditChanged() {
        Activity a = getActivity();
        Fragment f = getParentFragment();
        if (f instanceof OnEditChanged) {
            ((OnEditChanged) f).onEditChanged(mRequestCode, mRequestData, mModel.value);
        } else if (a instanceof OnEditChanged) {
            ((OnEditChanged) a).onEditChanged(mRequestCode, mRequestData, mModel.value);
        }
    }

    private void enabledOrDisableButtons(String value) {
        if (getDialog() != null) {
            final AlertDialog dialog = ((AlertDialog) getDialog());
            Button button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
            if (button != null) {
                button.setEnabled(
                        (!value.equals(mOriginalValue) || (value.isEmpty() && mModel.allowEmpty))
                        && (!value.isEmpty() || (value.isEmpty() && mModel.allowEmpty))
                        && (mRegExp == null || mRegExp.matcher(value).matches()));
            }
        }
    }
}


text:
#ifndef itkBayesianClassifierInitializationImageFilter_h
#define itkBayesianClassifierInitializationImageFilter_h

#include "itkVectorImage.h"
#include "itkVectorContainer.h"
#include "itkImageToImageFilter.h"
#include "itkImageRegionIterator.h"
#include "itkMembershipFunctionBase.h"

namespace itk
{
/** \class BayesianClassifierInitializationImageFilter
 *
 * \brief This filter is intended to be used as a helper class to
 * initialize the BayesianClassifierImageFilter.
 *
 * \par
 * The goal of this filter is to generate a membership image that indicates
 * the membership of each pixel to each class. These membership images are fed
 * as input to the Bayesian classfier filter.
 *
 * \par Parameters
 * Number of classes: This defines the number of classes, which will determine
 * the number of membership images that will be generated. The user must specify
 * this.
 *
 * \par
 * Membership functions: The user can optionally plugin in any membership function.
 * The number of membership functions plugged in should be the
 * same as the number of classes. If the user does not supply membership
 * functions, the filter will generate membership functions for you. These
 * functions are Gaussian density functions centered around 'n' pixel intensity
 * values, \f$ I_k \f$. These 'n' values are obtained by running K-means on the
 * image. In other words, the default behaviour of the filter is to generate
 * Gaussian mixture model for the input image.
 *
 * \par Inputs and Outputs
 * The filter takes a scalar Image as input and generates a VectorImage, each
 * component \f$ c \f$ of which represents memberships of each pixel to the
 * class \f$ c \f$.
 *
 * \par Template parameters
 * This filter is templated over the input image type and the data type used
 * to represent the probabilities (defaults to float).
 *
 * \author John Melonakos, Georgia Tech
 *
 * \note
 * This work is part of the National Alliance for Medical Image Computing
 * (NAMIC), funded by the National Institutes of Health through the NIH Roadmap
 * for Medical Research, Grant U54 EB005149.
 *
 * \sa BayesianClassifierImageFilter
 * \sa VectorImage
 * \ingroup ClassificationFilters
 * \ingroup ITKClassifiers
 */
template< typename TInputImage, typename TProbabilityPrecisionType = float >
class BayesianClassifierInitializationImageFilter:
  public
  ImageToImageFilter< TInputImage, VectorImage< TProbabilityPrecisionType,
                                                TInputImage::ImageDimension > >
{
public:
  /** Standard class typedefs. */
  typedef BayesianClassifierInitializationImageFilter Self;
  typedef TInputImage                                 InputImageType;
  typedef TProbabilityPrecisionType                   ProbabilityPrecisionType;

  /** Dimension of the input image */
  itkStaticConstMacro(Dimension, unsigned int,
                       InputImageType ::ImageDimension);

  typedef VectorImage< ProbabilityPrecisionType,
                       itkGetStaticConstMacro(Dimension) >                   OutputImageType;
  typedef ImageToImageFilter< InputImageType, OutputImageType > Superclass;
  typedef SmartPointer< Self >                                  Pointer;
  typedef SmartPointer< const Self >                            ConstPointer;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(BayesianClassifierInitializationImageFilter, ImageToImageFilter);

  /** Input image iterators */
  typedef ImageRegionConstIterator< InputImageType > InputImageIteratorType;

  /** Pixel types. */
  typedef typename InputImageType::PixelType  InputPixelType;
  typedef typename OutputImageType::PixelType OutputPixelType;

  /** Image Type and Pixel type for the images representing the membership of a
   *  pixel to a particular class. This image has arrays as pixels, the number of
   *  elements in the array is the same as the number of classes to be used.    */
  typedef VectorImage< ProbabilityPrecisionType,
                       itkGetStaticConstMacro(Dimension) >             MembershipImageType;
  typedef typename MembershipImageType::PixelType    MembershipPixelType;
  typedef typename MembershipImageType::Pointer      MembershipImagePointer;
  typedef ImageRegionIterator< MembershipImageType > MembershipImageIteratorType;

  /** Type of the Measurement */
  typedef Vector< InputPixelType, 1 > MeasurementVectorType;

  /** Type of the density functions */
  typedef Statistics::MembershipFunctionBase< MeasurementVectorType > MembershipFunctionType;
  typedef typename MembershipFunctionType::Pointer                    MembershipFunctionPointer;

  /** Membership function container */
  typedef VectorContainer< unsigned int,
                           MembershipFunctionPointer >  MembershipFunctionContainerType;
  typedef typename MembershipFunctionContainerType::Pointer
  MembershipFunctionContainerPointer;

  /** Method to set/get the density functions. Here you can set a vector
   * container of density functions. If no density functions are specified,
   * the filter will create ones for you. These default density functions
   * are Gaussian density functions centered around the K-means of the
   * input image.  */
  virtual void SetMembershipFunctions(MembershipFunctionContainerType
                                      *densityFunctionContainer);
  itkGetModifiableObjectMacro(MembershipFunctionContainer, MembershipFunctionContainerType);

  /** Set/Get methods for the number of classes. The user must supply this. */
  itkSetMacro(NumberOfClasses, unsigned int);
  itkGetConstMacro(NumberOfClasses, unsigned int);

  virtual void GenerateOutputInformation() ITK_OVERRIDE;

#ifdef ITK_USE_CONCEPT_CHECKING
  // Begin concept checking
  itkConceptMacro( InputMultiplyOperatorCheck,
                   ( Concept::MultiplyOperator< InputPixelType > ) );
  itkConceptMacro( DoubleConvertibleToProbabilityCheck,
                   ( Concept::Convertible< double, TProbabilityPrecisionType > ) );
  itkConceptMacro( InputHasNumericTraitsCheck,
                   ( Concept::HasNumericTraits< InputPixelType > ) );
  itkConceptMacro( ProbabilityHasNumericTraitsCheck,
                   ( Concept::HasNumericTraits< TProbabilityPrecisionType > ) );
  itkConceptMacro( DoublePlusInputCheck,
                   ( Concept::AdditiveOperators< double, InputPixelType > ) );
  // End concept checking
#endif

protected:
  BayesianClassifierInitializationImageFilter();
  virtual ~BayesianClassifierInitializationImageFilter() {}
  void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE;

  /** Initialize the membership functions. This will be called only if the membership
   * function hasn't already been set. This method initializes membership functions
   * using Gaussian density functions centered around the means computed using
   * Kmeans.
   */
  virtual void InitializeMembershipFunctions();

  /** Here is where the prior and membership probability vector images are
    created.*/
  virtual void GenerateData() ITK_OVERRIDE;

private:
  ITK_DISALLOW_COPY_AND_ASSIGN(BayesianClassifierInitializationImageFilter);

  bool         m_UserSuppliesMembershipFunctions;
  unsigned int m_NumberOfClasses;

  typename MembershipFunctionContainerType::Pointer m_MembershipFunctionContainer;
};
} // end namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#include "itkBayesianClassifierInitializationImageFilter.hxx"
#endif

#endif


text:
var mongoose = require('mongoose');

var pageSchema = mongoose.Schema({
    name: String,
    href: String,
    body: String,
    nav: String
});

module.exports = mongoose.model('Page', pageSchema);


text:
using KeyWatcher.Messages;
using Microsoft.AspNet.SignalR;
using System;
using System.Threading.Tasks;

namespace KeyWatcher.Dependencies
{
	internal sealed class SignalRNotification
		: INotification
	{
		private readonly IHubContext hub;

		public SignalRNotification(IHubContext hub) =>
			this.hub = hub ?? throw new ArgumentNullException(nameof(hub));

		public Task SendAsync(string recipient, string title, string message)
		{
			this.hub.Clients.All.NotificationSent(
				new SignalRNotificationMessage(recipient, title, message));
			return Task.CompletedTask;
		}
	}
}


text:
<?php declare(strict_types=1);

namespace Granam\Tests\ExceptionsHierarchy\Exceptions\ExceptionsUsedInParentDirs\Exceptions;

interface Exception
{

}


text:
<?php

/**
* All requests have this file as endpoint. It simply pass all routes to the
* FrontController which process the routing work and call the right controller.
*/

use Symfony\Component\Yaml\Parser;
use Controller\Core\Route;

require __DIR__.'/Config/loader.php';

if (file_exists(__DIR__.'/Config/routing.yml')) {
	$yaml = new Parser();
	$raw = $yaml->parse(file_get_contents(__DIR__.'/Config/routing.yml'));
	$routes = array();
	foreach ($raw as $k => $v) {
		$https = $auth = false;
		$permissions = array();
		extract($v);

		if (is_null($v['url'])) {
			$v['url'] = '';
		}

		$routes[] = new Route((string) $k, (string) $v['url'], (string) $v['controller'], (string) $v['method'], $https, $auth, $permissions);
	}
} else {
	require __DIR__.'/Config/routing.php';
}

use Controller\Core as Core;

$router = new Core\Router($routes, ROOT_URL);

$frontController = new Core\FrontController($router);
$frontController->run();


text:
<!DOCTYPE html>

    <title>Bootstrap Admin Theme v3</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="css/styles.css" rel="stylesheet">

AGRUR

					<form action="signupCheck.php" method="post" class="box">

Inscription

			                Vous êtes :
			                <select class="form-control" id="select-1" name="typeUtilisateur">
								<option value="Producteur">Producteur</option>
								<option value="Client">Client</option>
							</select>
			                <input class="form-control" type="text" placeholder="Nom" name="nomClient">
			                <input class="form-control" type="text" placeholder="Adresse" name="adresseClient">
			                <input class="form-control" type="text" placeholder="Nom Responsable" name="nomResponsable">
			                <input class="form-control" type="text" placeholder="Prénom Responsable" name="prenomResponsable">
			                <input class="form-control" type="text" placeholder="Nom d'utilisateur" name="nomUtilisateur">
			                <input class="form-control" type="password" placeholder="Mot de passe" name="mdp">

			                    <input class="btn btn-primary signup" type="submit" value="S'inscrire" onclick="window.location='signupCheck.php'" />

			        </form>

Toujours pas de compte?

			            S'inscrire


text:
name: GCSFuse Bug report
about: Describe information users can provide to enable faster interaction
title: ''
labels: bug
assignees: ''

---

**Describe the bug**
Please provide a clear description of what you were trying to achieve along with the details of the flags that you passed.

**To Collect more Debug logs**
Steps to reproduce the behavior:
1. Please make sure you have no other security, monitoring, background processes which can offend the FUSE process running. Possibly reproduce under a fresh/clean installation.
2. Please rerun with --debug_fuse --debug_fs --debug_gcs --debug_http --foreground as additional flags to enable debug logs.
3. Monitor the logs and please capture screenshots or copy the relevant logs to a file (can use --log-format and --log-file as well).
4. Attach the screenshot or the logs file to the bug report here.
5. If you're using gcsfuse with any other library/tool/process please list out the steps you took to reproduce the issue.

**System (please complete the following information):**
 - OS: [e.g. Ubuntu 20.04]
 - Platform [VM, Kubernetes]
 - Version [e.g. 0.41]

**Additional context**
Add any other context about the problem here.


text:
""" Provides CalculusInfinity class.
"""
__docformat__ = "restructuredtext"
__all__ = ['CalculusInfinity', 'oo', 'moo', 'undefined', 'zoo']

from ..utils import str_PRODUCT, NUMBER, TERMS, FACTORS, SYMBOL
from ..heads import SPECIAL
from ..arithmetic import Infinity
from .algebra import Calculus

CalculusInfinity = Infinity

class _CalculusInfinity(Infinity):

    one = Calculus.one
    zero = Calculus.zero

    def __new__(cls, direction):
        if isinstance(direction, Calculus):
            head, data = direction.head, direction.data
            if head is NUMBER:
                return cls(data)
            elif head is TERMS:
                if len(data)==1:
                    t, c = data.items()[0]
                    if c > 0:
                        return cls(t)
            r = direction.get_direction()
            if r is not NotImplemented:
                return cls(r)
        return Infinity.__new__(cls, direction)

    def to_str_data(self, sort=True):
        return str_PRODUCT, str(self)

    def _get_symbols_data(self):
        return set()

    def subs(self, *args):
        d = self.data
        if isinstance(d, Calculus):
            return type(self)(d.subs(*args))
        return self

    @classmethod
    def IsUnbounded(cls, x):
        if isinstance(x, Calculus):
            head = x.head
            if head is NUMBER:
                return cls.IsUnbounded(x.data)
            f = x.is_bounded
            if f or f is not None:
                return Calculus.convert(not f)
        if isinstance(x, cls):
            return Calculus.one
        r = Infinity.IsUnbounded(x)
        if r is not NotImplemented:
            return Calculus.convert(r)
        x = Calculus.convert(x)
        return Calculus.Apply(cls.IsUnbounded, x)

    @classmethod
    def EqualArg(cls, x, y):
        if isinstance(x, Calculus):
            d = x.get_direction()
            if d is not NotImplemented:
                return cls.EqualArg(d, y)
        if isinstance(y, Calculus):
            d = y.get_direction()
            if d is not NotImplemented:
                return cls.EqualArg(x, d)
            if isinstance(x, Calculus):
                xy = x / y
                if xy.head is NUMBER:
                    return Calculus.convert(xy.data > 0)

        r = Infinity.EqualArg(x, y)
        if r is not NotImplemented:
            return Calculus.convert(r)
        x = Calculus.convert(x)
        y = Calculus.convert(y)
        return Calculus.Apply(cls.EqualArg, x,y)

    @classmethod
    def IsPositive(cls, x):
        if isinstance(x, Calculus):
            if x.head is NUMBER:
                return cls.IsPositive(x.data)
        r = Infinity.IsPositive(x)
        if r is not NotImplemented:
            return Calculus.convert(r)
        x = Calculus.convert(x)
        return Calculus.apply(cls.IsPositive, x)

    def __pow__(self, other):
        if isinstance(other, Calculus):
            head, data = other.head, other.data
            if head is NUMBER:
                other = data
        r = Infinity.__pow__(self, other)
        if r is not NotImplemented:
            if isinstance(r, type(self)):
                return r
            return Calculus.convert(r)
        x = Calculus.convert(other)
        return Calculus(FACTORS, {Calculus(SPECIAL, self): x})

    def __rpow__(self, other):
        if isinstance(other, Calculus):
            if other.head is SYMBOL:
                other = other.evalf(2)
            head, data = other.head, other.data
            if head is NUMBER:
                other = data
        r = Infinity.__rpow__(self, other)
        if r is not NotImplemented:
            if isinstance(r, type(self)):
                return r
            return Calculus.convert(r)
        x = Calculus.convert(other)
        return Calculus(FACTORS, {x: self})

oo = CalculusInfinity(1)
moo = CalculusInfinity(-1)
undefined = CalculusInfinity(0)
zoo = CalculusInfinity(undefined)

Calculus.oo = oo
Calculus.zoo = zoo
Calculus.undefined = undefined
Calculus.Infinity = CalculusInfinity


text:
package org.kuali.rice.krad.uif.util;

import org.apache.commons.lang.ArrayUtils;
import org.kuali.rice.core.api.exception.RiceRuntimeException;
import org.kuali.rice.krad.uif.component.ReferenceCopy;

import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Utility class for copying objects using reflection. Modified from the jCommon
 * library: http://www.matthicks.com/2008/05/fastest-deep-cloning.html
 *
 * @author Matt Hicks
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class CloneUtils {
    private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(CloneUtils.class);

    private static final Map<String, Field[]> fieldCache = new HashMap<String, Field[]>();
    private static final Map<String, Field> internalFields = new HashMap<String, Field>();

    public static final <O> O deepClone(O original) {
        try {
            return deepCloneReflection(original);
        } catch (Exception e) {
            throw new RiceRuntimeException(e);
        }
    }

    @SuppressWarnings("unchecked")
    public static final <O> O deepCloneReflection(O original) throws Exception {
        try {
            return (O) deepCloneReflectionInternal(original, new HashMap<Object, Object>(), false);
        } catch (Exception ex) {
            LOG.warn("Exception during clone (returning original): ", ex);
            return original;
        }
    }

    protected static final Object deepCloneReflectionInternal(Object original, Map<Object, Object> cache,
            boolean referenceCollectionCopy) throws Exception {
        if (original == null) { // No need to clone nulls
            return original;
        }
        else if (cache.containsKey(original)) {
            return cache.get(original);
        }

        // Deep clone
        Object clone = null;
        if (List.class.isAssignableFrom(original.getClass())) {
            clone = deepCloneList(original, cache, referenceCollectionCopy);
        }
        else if (Map.class.isAssignableFrom(original.getClass())) {
            clone = deepCloneMap(original, cache, referenceCollectionCopy);
        }
        else if ( original.getClass().isArray() ) {
            clone = deepCloneArray( original, cache);
        } else {
            clone = deepCloneObject(original, cache);
        }

        return clone;
    }

    protected static Object deepCloneArray(Object original,  Map<Object, Object> cache)
            throws Exception {
        // Instantiate a new instance
        Object[] clone = (Object[]) Array.newInstance(original.getClass().getComponentType(), ((Object[])original).length);

        // Populate data
        for ( int i = 0; i < ((Object[])original).length; i++ ) {
            clone[i] = deepCloneReflectionInternal(((Object[])original)[i], cache, false);
        }

        return clone;
    }

    protected static Object deepCloneObject(Object original, Map<Object, Object> cache) throws Exception {
        if (original instanceof Number) { // Numbers are immutable
            if (original instanceof AtomicInteger) {
                // AtomicIntegers are mutable
            }
            else if (original instanceof AtomicLong) {
                // AtomLongs are mutable
            }
            else {
                return original;
            }
        }
        else if (original instanceof String) { // Strings are immutable
            return original;
        }
        else if (original instanceof Character) { // Characters are immutable
            return original;
        }
        else if (original instanceof Class) { // Classes are immutable
            return original;
        }
        else if (original instanceof Boolean) {
            return new Boolean(((Boolean) original).booleanValue());
        }
        else if (original instanceof Enum) {
            return original;
        }

        // To our understanding, this is a mutable object, so clone it
        Class<?> c = original.getClass();
        Field[] fields = getFields(c, false);
        //try {
            Object copy = instantiate(original);

            // Put into cache
            cache.put(original, copy);

            // iterate through and copy fields
            for (Field f : fields) {
                Object object = f.get(original);
                try {
                    boolean referenceCopy = false;
                    boolean referenceCollectionCopy = false;
                    ReferenceCopy copyAnnotation = f.getAnnotation(ReferenceCopy.class);
                    if (copyAnnotation != null) {
                        referenceCopy = true;
                        referenceCollectionCopy = copyAnnotation.newCollectionInstance();
                    }

                    if (!referenceCopy || referenceCollectionCopy) {
                        object = CloneUtils.deepCloneReflectionInternal(object, cache, referenceCollectionCopy);
                    }
                    f.set(copy, object);
                } catch ( Exception ex ) {
                    LOG.warn("Exception during field cloning (using original object value). Field: " + original.getClass() + "." + f.getName() + "(" + f.getType() + ")", ex);
                    f.set(copy, object);
                }
            }

            return copy;
//        }
//        catch (Exception ex) {
//            LOG.warn("Exception during clone (returning original): ", ex);
//            return original;
//        }
    }

    @SuppressWarnings("unchecked")
    protected static Object deepCloneMap(Object original, Map<Object, Object> cache, boolean referenceCollectionCopy)
            throws Exception {
        // Instantiate a new instance
        Map<Object, Object> clone = null;
        try {
            clone = (Map<Object, Object>) instantiate(original);
        } catch (Exception e) {
            // check for collections empty map which cannot be instantiated
            if ((original != null) && ((Map) original).isEmpty()) {
                return Collections.emptyMap();
            } else {
                throw new RuntimeException(e);
            }
        }

        // Populate data
        for (Entry<Object, Object> entry : ((Map<Object, Object>) original).entrySet()) {
            if (referenceCollectionCopy) {
                clone.put(entry.getKey(), entry.getValue());
            }
            else {
                clone.put(deepCloneReflectionInternal(entry.getKey(), cache, false),
                        deepCloneReflectionInternal(entry.getValue(), cache, false));
            }
        }

        return clone;
    }

    @SuppressWarnings("unchecked")
    protected static Object deepCloneList(Object original, Map<Object, Object> cache, boolean referenceCollectionCopy)
            throws Exception {
        // Instantiate a new instance
        List<Object> clone = null;
        try {
            clone = (List<Object>) instantiate(original);
        } catch (Exception e) {
            // check for collections empty list which cannot be instantiated
            if ((original != null) && ((Collection) original).isEmpty()) {
                return Collections.emptyList();
            }
            else {
                throw new RuntimeException(e);
            }
        }

        // Populate data
        for (Iterator<Object> iterator = ((List<Object>) original).iterator(); iterator.hasNext();) {
            Object object = iterator.next();
            if (referenceCollectionCopy) {
                clone.add(object);
            }
            else {
                clone.add(deepCloneReflectionInternal(object, cache, false));
            }
        }

        return clone;

    }

    /**
     * Retrieves all field names for the given class that have the given annotation
     *
     * @param clazz class to find field annotations for
     * @param annotationClass class for annotation to find
     * @return map containing the field name that has the annotation as a key and the
     *         annotation instance as a value
     */
    public static Map<String, Annotation> getFieldsWithAnnotation(Class<?> clazz,
            Class<? extends Annotation> annotationClass) {
        Map<String, Annotation> annotationFields = new HashMap<String, Annotation>();

        Field[] fields = getFields(clazz, false);
        for (Field f : fields) {
            Annotation fieldAnnotation = f.getAnnotation(annotationClass);
            if (fieldAnnotation != null) {
                annotationFields.put(f.getName(), fieldAnnotation);
            }
        }

        return annotationFields;
    }

    /**
     * Determines whether the property of the given class has the given annotation specified
     *
     * @param clazz class containing the property to check
     * @param propertyName name of the property to check
     * @param annotationClass class for the annotation to look for
     * @return true if the field associated with the property name has the given annotation, false if not
     */
    public static boolean fieldHasAnnotation(Class<?> clazz, String propertyName,
            Class<? extends Annotation> annotationClass) {
        Field[] fields = getFields(clazz, false);
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            if (field.getName().equals(propertyName)) {
                Annotation fieldAnnotation = field.getAnnotation(annotationClass);
                if (fieldAnnotation != null) {
                    return true;
                } else {
                    return false;
                }
            }
        }

        return false;
    }

    protected static final Object instantiate(Object original) throws InstantiationException, IllegalAccessException {
        return original.getClass().newInstance();
    }

    public static Field[] getFields(Object object, boolean includeStatic) {
        return getFields(object, includeStatic, true);
    }

    public static Field[] getFields(Object object, boolean includeStatic, boolean includeTransient) {
        Class<?> c = object.getClass();
        return getFields(c, includeStatic, includeTransient);
    }

    public static Field[] getFields(Class<?> c, boolean includeStatic) {
        return getFields(c, includeStatic, true);
    }

    public static Field[] getFields(Class<?> c, boolean includeStatic, boolean includeTransient) {
        String cacheKey = c.getName() + ":" + includeStatic;
        Field[] array = fieldCache.get(cacheKey);

        if (array == null) {
            ArrayList<Field> fields = new ArrayList<Field>();

            List<Class<?>> classes = getClassHierarchy(c, false);

            // Reverse order so we make sure we maintain consistent order
            Collections.reverse(classes);

            for (Class<?> clazz : classes) {
                Field[] allFields = clazz.getDeclaredFields();
                for (Field f : allFields) {
                    if ((!includeTransient) && ((f.getModifiers() & Modifier.TRANSIENT) == Modifier.TRANSIENT)) {
                        continue;
                    }
                    else if (f.isSynthetic()) {
                        // Synthetic fields are bad!!!
                        continue;
                    }
                    boolean isStatic = (f.getModifiers() & Modifier.STATIC) == Modifier.STATIC;
                    if ((isStatic) && (!includeStatic)) {
                        continue;
                    }
                    if (f.getName().equalsIgnoreCase("serialVersionUID")) {
                        continue;
                    }
                    f.setAccessible(true);
                    fields.add(f);
                }
            }

            array = fields.toArray(new Field[fields.size()]);
            fieldCache.put(cacheKey, array);
        }
        return array;
    }

    protected static final Field internalField(Object object, String fieldName) {
        if (object == null) {
            System.out.println("Internal Field: " + object + ", " + fieldName);
            return null;
        }

        String key = object.getClass().getName() + "." + fieldName;
        Field field = internalFields.get(key);
        if (field == null) {
            Field[] fields = getFields(object.getClass(), false);

            for (Field f : fields) {
                String name = f.getName();
                if (name.equals(fieldName)) {
                    field = f;
                    internalFields.put(key, field);
                    break;
                }
            }
        }

        return field;
    }

    protected static List<Class<?>> getClassHierarchy(Class<?> c, boolean includeInterfaces) {
        List<Class<?>> classes = new ArrayList<Class<?>>();
        while (c != Object.class) {
            classes.add(c);
            if (includeInterfaces) {
                Class<?>[] interfaces = c.getInterfaces();
                for (Class<?> i : interfaces) {
                    classes.add(i);
                }
            }
            c = c.getSuperclass();
            if (c == null) {
                break;
            }
        }

        return classes;
    }

}


text:
layout: post
title: "xjn Hello World"
description: ""
category: cat1
tags: []
---
{% include JB/setup %}

xjn test

Directly following the intro we'll learn exactly _how_ Jekyll does what it does.

![local picture](../res/aa.png)

asdfadf

![github picture](https://github.com/igiantpanda/igiantpanda.github.io/blob/master/_posts/res/aa.png?raw=true)

{% highlight java linenos %}
```java
private void makeDefault(NetworkAgentInfo newNetwork) {
    if (DBG) log("Switching to new default network: " + newNetwork);
    setupDataActivityTracking(newNetwork);
    try {
        mNetd.setDefaultNetId(newNetwork.network.netId);
    } catch (Exception e) {
        loge("Exception setting default network :" + e);
    }
    notifyLockdownVpn(newNetwork);
    handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
    updateTcpBufferSizes(newNetwork);
    setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
}
```
{% endhighlight %}

```java
private void makeDefault(NetworkAgentInfo newNetwork) {
    if (DBG) log("Switching to new default network: " + newNetwork);
    setupDataActivityTracking(newNetwork);
    try {
        mNetd.setDefaultNetId(newNetwork.network.netId);
    } catch (Exception e) {
        loge("Exception setting default network :" + e);
    }
    notifyLockdownVpn(newNetwork);
    handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
    updateTcpBufferSizes(newNetwork);
    setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
}
```


text:
'use strict';

let React = require('react');
let ReactRouter = require('react-router');
let Link = ReactRouter.Link;

let classNames = require('classNames');
let PubSub = require('pubsub-js');

let FeedsList = require('../components/FeedsList.js');
let AppStore = require('../AppStore.js');
let AppUtils = require('../AppUtils.js');
let AppMessages = require('./../AppMessages.js');

let FoldersList = React.createClass({
    getInitialState: function() {
        return {
            foldersUnreadCount: AppStore.foldersUnreadCount ? AppStore.foldersUnreadCount : {}
        };
    },

    componentDidMount: function() {
        this.folderUnreadCountChanged = PubSub.subscribe(AppMessages.FOLDERS_UNREAD_COUNT_CHANGED, function( msg, data ) {
            this.setState({
                foldersUnreadCount: AppStore.foldersUnreadCount
            });
        }.bind(this));
    },

    componentWillUnmount: function() {
        PubSub.unsubscribe( this.folderUnreadCountChanged );
    },

    folderClick: function(e) {
        AppUtils.morphElementToHeader(e);
    },

    render: function() {
        let feeds, folders;

        if (!this.props.userData) {
            return (
);
        }

        folders = Object.keys(this.props.userData.bloglist);
        folders = folders.filter(function(element){
            return element !== 'root';
        }).map(function (folder) {
            let linkToFolder = '/' + folder;
            let folderUnreadCount = '';
            if (this.state.foldersUnreadCount && this.state.foldersUnreadCount[folder]) {
                if (this.state.foldersUnreadCount[folder] <= 0) {
                    folderUnreadCount = '';
                } else if (this.state.foldersUnreadCount[folder] > 999) {
                    folderUnreadCount = '999';
                } else {
                    folderUnreadCount = this.state.foldersUnreadCount[folder];
                }
            }

            // get all folder feeds
            let unreadFeeds = this.props.userData.bloglist[folder];

            // get unread
            unreadFeeds = unreadFeeds.filter(function(feed, i) {
                let unreadData, unreadCount;
                unreadData = AppStore.readData[feed.url];
                if (typeof unreadData !== 'undefined') {
                    unreadCount = AppStore.readData[feed.url].totalCount - AppStore.readData[feed.url].readCount;
                    if (unreadCount > 0) {
                        feed.unreadCount = unreadCount;
                        return feed;
                    }
                }
            });

            // get first 5, todo sort them before
            unreadFeeds = unreadFeeds.slice(0, 5).map(function(feed) {
                let url = linkToFolder + '/' + encodeURIComponent(feed.url);
                return

                            <Link to={url} onClick={this.folderClick} >
                                {feed.title}
                                ({feed.unreadCount})
                            </Link>

;
            }.bind(this));

            let unreadFeedsString = '';
            if (unreadFeeds.length > 0) {
                unreadFeedsString =
{unreadFeeds}
;
            } else {
                unreadFeedsString =

;
            }

            let unreadCountClassName = classNames({
                unreadCountMultipleView: true
            });

            return (

                    <Link to={linkToFolder} onClick={this.folderClick} >

                            {folderUnreadCount !== '' ? folderUnreadCount : String.fromCharCode(183)}

                            {folder}

                    </Link>
                    {unreadFeedsString}

            );
        }.bind(this));

        if (this.props.isRoot === 'True') {
            feeds = <FeedsList userData={this.props.userData} multipleFeedsView={false}/>;
        }

        return (

                {folders}
                {feeds}

        );
    }
});

module.exports = FoldersList;


text:
'use strict'

const OSX = process.platform === 'darwin'
const WIN32 = process.platform === 'win32'
let mapper = null

if (OSX) mapper = require('./mapOSX')
if (WIN32) mapper = require('./mapWIN')

const hget = action => fetch(`http://localhost:14004${action}`)
  .then(res => res.json())

module.exports = {

  getWindows: m => hget('/windows').then(mapper.map),
  focusWindow: id => hget(`/windows/${id}/focus`)

}