text:
package main

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"strconv"
	"strings"
	"syscall"

	"github.com/lxc/lxd/client"
	"github.com/lxc/lxd/lxc/config"
	"github.com/lxc/lxd/shared"
	"github.com/lxc/lxd/shared/gnuflag"
	"github.com/lxc/lxd/shared/i18n"
	"github.com/lxc/lxd/shared/logger"
	"github.com/lxc/lxd/shared/termios"
)

type fileCmd struct {
	uid  int
	gid  int
	mode string

	recursive bool

	mkdirs bool
}

func (c *fileCmd) showByDefault() bool {
	return true
}

func (c *fileCmd) usage() string {
	return i18n.G(
		`Usage: lxc file <subcommand> [options]

Manage files in containers.

lxc file pull [-r|--recursive] [<remote>:]<container>/<path> [[<remote>:]<container>/<path>...] <target path>
    Pull files from containers.

lxc file push [-r|--recursive] [-p|--create-dirs] [--uid=UID] [--gid=GID] [--mode=MODE] <source path> [<source path>...] [<remote>:]<container>/<path>
    Push files into containers.

lxc file delete [<remote>:]<container>/<path> [[<remote>:]<container>/<path>...]
    Delete files in containers.

lxc file edit [<remote>:]<container>/<path>
    Edit files in containers using the default text editor.

*Examples*
lxc file push /etc/hosts foo/etc/hosts
   To push /etc/hosts into the container "foo".

lxc file pull foo/etc/hosts .
   To pull /etc/hosts from the container and write it to the current directory.`)
}

func (c *fileCmd) flags() {
	gnuflag.IntVar(&c.uid, "uid", -1, i18n.G("Set the file's uid on push"))
	gnuflag.IntVar(&c.gid, "gid", -1, i18n.G("Set the file's gid on push"))
	gnuflag.StringVar(&c.mode, "mode", "", i18n.G("Set the file's perms on push"))
	gnuflag.BoolVar(&c.recursive, "recursive", false, i18n.G("Recursively push or pull files"))
	gnuflag.BoolVar(&c.recursive, "r", false, i18n.G("Recursively push or pull files"))
	gnuflag.BoolVar(&c.mkdirs, "create-dirs", false, i18n.G("Create any directories necessary"))
	gnuflag.BoolVar(&c.mkdirs, "p", false, i18n.G("Create any directories necessary"))
}

func (c *fileCmd) recursivePullFile(d lxd.ContainerServer, container string, p string, targetDir string) error {
	buf, resp, err := d.GetContainerFile(container, p)
	if err != nil {
		return err
	}

	target := filepath.Join(targetDir, filepath.Base(p))
	if resp.Type == "directory" {
		err := os.Mkdir(target, os.FileMode(resp.Mode))
		if err != nil {
			return err
		}

		for _, ent := range resp.Entries {
			nextP := path.Join(p, ent)

			err := c.recursivePullFile(d, container, nextP, target)
			if err != nil {
				return err
			}
		}
	} else if resp.Type == "file" {
		f, err := os.Create(target)
		if err != nil {
			return err
		}
		defer f.Close()

		err = os.Chmod(target, os.FileMode(resp.Mode))
		if err != nil {
			return err
		}

		_, err = io.Copy(f, buf)
		if err != nil {
			return err
		}
	} else {
		return fmt.Errorf(i18n.G("Unknown file type '%s'"), resp.Type)
	}

	return nil
}

func (c *fileCmd) recursivePushFile(d lxd.ContainerServer, container string, source string, target string) error {
	source = filepath.Clean(source)
	sourceDir, _ := filepath.Split(source)
	sourceLen := len(sourceDir)

	sendFile := func(p string, fInfo os.FileInfo, err error) error {
		if err != nil {
			return fmt.Errorf(i18n.G("Failed to walk path for %s: %s"), p, err)
		}

		// Detect unsupported files
		if !fInfo.Mode().IsRegular() && !fInfo.Mode().IsDir() && fInfo.Mode()&os.ModeSymlink != os.ModeSymlink {
			return fmt.Errorf(i18n.G("'%s' isn't a supported file type."), p)
		}

		// Prepare for file transfer
		targetPath := path.Join(target, filepath.ToSlash(p[sourceLen:]))
		mode, uid, gid := shared.GetOwnerMode(fInfo)
		args := lxd.ContainerFileArgs{
			UID:  int64(uid),
			GID:  int64(gid),
			Mode: int(mode.Perm()),
		}

		if fInfo.IsDir() {
			// Directory handling
			args.Type = "directory"
		} else if fInfo.Mode()&os.ModeSymlink == os.ModeSymlink {
			// Symlink handling
			symlinkTarget, err := os.Readlink(p)
			if err != nil {
				return err
			}

			args.Type = "symlink"
			args.Content = bytes.NewReader([]byte(symlinkTarget))
		} else {
			// File handling
			f, err := os.Open(p)
			if err != nil {
				return err
			}
			defer f.Close()

			args.Type = "file"
			args.Content = f
		}

		return d.CreateContainerFile(container, targetPath, args)
	}

	return filepath.Walk(source, sendFile)
}

func (c *fileCmd) recursiveMkdir(d lxd.ContainerServer, container string, p string, mode *os.FileMode, uid int64, gid int64) error {
	/* special case, every container has a /, we don't need to do anything */
	if p == "/" {
		return nil
	}

	// Remove trailing "/" e.g. /A/B/C/. Otherwise we will end up with an
	// empty array entry "" which will confuse the Mkdir() loop below.
	pclean := filepath.Clean(p)
	parts := strings.Split(pclean, "/")
	i := len(parts)

	for ; i >= 1; i-- {
		cur := filepath.Join(parts[:i]...)
		_, resp, err := d.GetContainerFile(container, cur)
		if err != nil {
			continue
		}

		if resp.Type != "directory" {
			return fmt.Errorf(i18n.G("%s is not a directory"), cur)
		}

		i++
		break
	}

	for ; i <= len(parts); i++ {
		cur := filepath.Join(parts[:i]...)
		if cur == "" {
			continue
		}

		modeArg := -1
		if mode != nil {
			modeArg = int(mode.Perm())
		}
		args := lxd.ContainerFileArgs{
			UID:  uid,
			GID:  gid,
			Mode: modeArg,
			Type: "directory",
		}

		err := d.CreateContainerFile(container, cur, args)
		if err != nil {
			return err
		}
	}

	return nil
}

func (c *fileCmd) push(conf *config.Config, send_file_perms bool, args []string) error {
	if len(args) < 2 {
		return errArgs
	}

	target := args[len(args)-1]
	pathSpec := strings.SplitN(target, "/", 2)

	if len(pathSpec) != 2 {
		return fmt.Errorf(i18n.G("Invalid target %s"), target)
	}

	remote, container, err := conf.ParseRemote(pathSpec[0])
	if err != nil {
		return err
	}

	targetIsDir := strings.HasSuffix(target, "/")
	// re-add leading / that got stripped by the SplitN
	targetPath := "/" + pathSpec[1]
	// clean various /./, /../, /////, etc. that users add (#2557)
	targetPath = path.Clean(targetPath)

	// normalization may reveal that path is still a dir, e.g. /.
	if strings.HasSuffix(targetPath, "/") {
		targetIsDir = true
	}

	logger.Debugf("Pushing to: %s  (isdir: %t)", targetPath, targetIsDir)

	d, err := conf.GetContainerServer(remote)
	if err != nil {
		return err
	}

	var sourcefilenames []string
	for _, fname := range args[:len(args)-1] {
		if !strings.HasPrefix(fname, "--") {
			sourcefilenames = append(sourcefilenames, fname)
		}
	}

	mode := os.FileMode(0755)
	if c.mode != "" {
		if len(c.mode) == 3 {
			c.mode = "0" + c.mode
		}

		m, err := strconv.ParseInt(c.mode, 0, 0)
		if err != nil {
			return err
		}
		mode = os.FileMode(m)
	}

	if c.recursive {
		if c.uid != -1 || c.gid != -1 || c.mode != "" {
			return fmt.Errorf(i18n.G("can't supply uid/gid/mode in recursive mode"))
		}

		if c.mkdirs {
			f, err := os.Open(args[0])
			if err != nil {
				return err
			}
			finfo, err := f.Stat()
			f.Close()
			if err != nil {
				return err
			}

			mode, uid, gid := shared.GetOwnerMode(finfo)

			err = c.recursiveMkdir(d, container, targetPath, &mode, int64(uid), int64(gid))
			if err != nil {
				return err
			}
		}

		for _, fname := range sourcefilenames {
			err := c.recursivePushFile(d, container, fname, targetPath)
			if err != nil {
				return err
			}
		}

		return nil
	}

	uid := 0
	if c.uid >= 0 {
		uid = c.uid
	}

	gid := 0
	if c.gid >= 0 {
		gid = c.gid
	}

	if (len(sourcefilenames) > 1) && !targetIsDir {
		return errArgs
	}

	/* Make sure all of the files are accessible by us before trying to
	 * push any of them. */
	var files []*os.File
	for _, f := range sourcefilenames {
		var file *os.File
		if f == "-" {
			file = os.Stdin
		} else {
			file, err = os.Open(f)
			if err != nil {
				return err
			}
		}

		defer file.Close()
		files = append(files, file)
	}

	for _, f := range files {
		fpath := targetPath
		if targetIsDir {
			fpath = path.Join(fpath, path.Base(f.Name()))
		}

		if c.mkdirs {
			finfo, err := f.Stat()
			if err != nil {
				return err
			}

			_, dUid, dGid := shared.GetOwnerMode(finfo)
			if c.uid == -1 || c.gid == -1 {
				if c.uid == -1 {
					uid = dUid
				}

				if c.gid == -1 {
					gid = dGid
				}
			}

			err = c.recursiveMkdir(d, container, path.Dir(fpath), nil, int64(uid), int64(gid))
			if err != nil {
				return err
			}
		}

		args := lxd.ContainerFileArgs{
			Content: f,
			UID:     -1,
			GID:     -1,
			Mode:    -1,
		}

		if send_file_perms {
			if c.mode == "" || c.uid == -1 || c.gid == -1 {
				finfo, err := f.Stat()
				if err != nil {
					return err
				}

				fMode, fUid, fGid := shared.GetOwnerMode(finfo)
				if err != nil {
					return err
				}

				if c.mode == "" {
					mode = fMode
				}

				if c.uid == -1 {
					uid = fUid
				}

				if c.gid == -1 {
					gid = fGid
				}
			}

			args.UID = int64(uid)
			args.GID = int64(gid)
			args.Mode = int(mode.Perm())
		}

		err = d.CreateContainerFile(container, fpath, args)
		if err != nil {
			return err
		}
	}

	return nil
}

func (c *fileCmd) pull(conf *config.Config, args []string) error {
	if len(args) < 2 {
		return errArgs
	}

	target := args[len(args)-1]
	targetIsDir := false
	sb, err := os.Stat(target)
	if err != nil && !os.IsNotExist(err) {
		return err
	}

	/*
	 * If the path exists, just use it. If it doesn't exist, it might be a
	 * directory in one of three cases:
	 *   1. Someone explicitly put "/" at the end
	 *   2. Someone provided more than one source. In this case the target
	 *      should be a directory so we can save all the files into it.
	 *   3. We are dealing with recursive copy
	 */
	if err == nil {
		targetIsDir = sb.IsDir()
		if !targetIsDir && len(args)-1 > 1 {
			return fmt.Errorf(i18n.G("More than one file to download, but target is not a directory"))
		}
	} else if strings.HasSuffix(target, string(os.PathSeparator)) || len(args)-1 > 1 || c.recursive {
		err := os.MkdirAll(target, 0755)
		if err != nil {
			return err
		}
		targetIsDir = true
	}

	for _, f := range args[:len(args)-1] {
		pathSpec := strings.SplitN(f, "/", 2)
		if len(pathSpec) != 2 {
			return fmt.Errorf(i18n.G("Invalid source %s"), f)
		}

		remote, container, err := conf.ParseRemote(pathSpec[0])
		if err != nil {
			return err
		}

		d, err := conf.GetContainerServer(remote)
		if err != nil {
			return err
		}

		if c.recursive {
			err := c.recursivePullFile(d, container, pathSpec[1], target)
			if err != nil {
				return err
			}

			continue
		}

		buf, resp, err := d.GetContainerFile(container, pathSpec[1])
		if err != nil {
			return err
		}

		if resp.Type == "directory" {
			return fmt.Errorf(i18n.G("Can't pull a directory without --recursive"))
		}

		var targetPath string
		if targetIsDir {
			targetPath = path.Join(target, path.Base(pathSpec[1]))
		} else {
			targetPath = target
		}

		var f *os.File
		if targetPath == "-" {
			f = os.Stdout
		} else {
			f, err = os.Create(targetPath)
			if err != nil {
				return err
			}
			defer f.Close()

			err = os.Chmod(targetPath, os.FileMode(resp.Mode))
			if err != nil {
				return err
			}
		}

		_, err = io.Copy(f, buf)
		if err != nil {
			return err
		}
	}

	return nil
}

func (c *fileCmd) delete(conf *config.Config, args []string) error {
	if len(args) < 1 {
		return errArgs
	}

	for _, f := range args[:] {
		pathSpec := strings.SplitN(f, "/", 2)
		if len(pathSpec) != 2 {
			return fmt.Errorf(i18n.G("Invalid path %s"), f)
		}

		remote, container, err := conf.ParseRemote(pathSpec[0])
		if err != nil {
			return err
		}

		d, err := conf.GetContainerServer(remote)
		if err != nil {
			return err
		}

		err = d.DeleteContainerFile(container, pathSpec[1])
		if err != nil {
			return err
		}
	}

	return nil
}

func (c *fileCmd) edit(conf *config.Config, args []string) error {
	if len(args) != 1 {
		return errArgs
	}

	if c.recursive {
		return fmt.Errorf(i18n.G("recursive edit doesn't make sense :("))
	}

	// If stdin isn't a terminal, read text from it
	if !termios.IsTerminal(int(syscall.Stdin)) {
		return c.push(conf, false, append([]string{os.Stdin.Name()}, args[0]))
	}

	// Create temp file
	f, err := ioutil.TempFile("", "lxd_file_edit_")
	fname := f.Name()
	f.Close()
	os.Remove(fname)
	defer os.Remove(fname)

	// Extract current value
	err = c.pull(conf, append([]string{args[0]}, fname))
	if err != nil {
		return err
	}

	_, err = shared.TextEditor(fname, []byte{})
	if err != nil {
		return err
	}

	err = c.push(conf, false, append([]string{fname}, args[0]))
	if err != nil {
		return err
	}

	return nil
}

func (c *fileCmd) run(conf *config.Config, args []string) error {
	if len(args) < 1 {
		return errUsage
	}

	switch args[0] {
	case "push":
		return c.push(conf, true, args[1:])
	case "pull":
		return c.pull(conf, args[1:])
	case "delete":
		return c.delete(conf, args[1:])
	case "edit":
		return c.edit(conf, args[1:])
	default:
		return errArgs
	}
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.wenzani</groupId>
    <artifactId>mongodb-maven-plugin</artifactId>
    <packaging>maven-plugin</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>mongodb-maven-plugin Maven Mojo</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-plugin-api</artifactId>
            <version>2.0</version>
        </dependency>

        <!-- Commons IO -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.0.1</version>
        </dependency>

        <!-- Commons IO -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>1.1</version>
        </dependency>

        <!-- Commons Lang -->
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>

        <!--httpcomponents-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.1.1</version>
        </dependency>

        <!-- MongoDB Driver -->
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>2.5.2</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-plugin-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <goalPrefix>mongodb</goalPrefix>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <developers>
        <developer>
            <id>stuartrexking</id>
            <name>Stuart King</name>
            <email>stuart@wenzani.com</email>
            <organization>Wenzani</organization>
            <roles>
                <role>CTO</role>
            </roles>
        </developer>
    </developers>
</project>

redpajama_set_name: RedPajamaGithub


text:
package automarker;

import automarker.Expr;
import java.util.HashMap;

class ExprWrapper {

    private static final Boolean TRUE = Boolean.TRUE;
    private static final Boolean FALSE = Boolean.FALSE;

    private static class EqualsVisitor implements Expr.VisitorP {

        EqualsVisitor(ExprWrapper param1) {
            this();
        }
        HashMap sym_map = new HashMap();

        public Object visitAbstract(Expr.Abstract paramAbstract, Object paramObject) {
            if (!(paramObject instanceof Expr.Abstract)) {
                return ExprWrapper.FALSE;
            }
            Expr.Abstract localAbstract = (Expr.Abstract) paramObject;
            this.sym_map.put(paramAbstract.sym, localAbstract.sym);
            Object localObject = paramAbstract.expr.visitP(this, localAbstract.expr);
            this.sym_map.remove(paramAbstract.sym);
            return localObject;
        }

        public Object visitApply(Expr.Apply paramApply, Object paramObject) {
            if (!(paramObject instanceof Expr.Apply)) {
                return ExprWrapper.FALSE;
            }
            Expr.Apply localApply = (Expr.Apply) paramObject;
            if (paramApply.left.visitP(this, localApply.left) == ExprWrapper.FALSE) {
                return ExprWrapper.FALSE;
            }
            if (paramApply.right.visitP(this, localApply.right) == ExprWrapper.FALSE) {
                return ExprWrapper.FALSE;
            }
            return ExprWrapper.TRUE;
        }

        public Object visitIdent(Expr.Ident paramIdent, Object paramObject) {
            if (!(paramObject instanceof Expr.Ident)) {
                return ExprWrapper.FALSE;
            }
            Expr.Ident localIdent = (Expr.Ident) paramObject;
            Symbol localSymbol = (Symbol) this.sym_map.get(paramIdent.sym);
            if (localSymbol == null) {
                if (paramIdent.sym.toString().equals(localIdent.sym.toString())) {
                    return ExprWrapper.TRUE;
                }
                return ExprWrapper.FALSE;
            }

            return localIdent.sym == localSymbol ? ExprWrapper.TRUE : ExprWrapper.FALSE;
        }

        private EqualsVisitor() {
        }
    }

    private final Expr expr;

    private static class HashCodeComputer implements Expr.Visitor {

        HashCodeComputer(ExprWrapper param1) {
            this();
        }
        private HashMap sym_map = new HashMap();
        int last_ident = 0;

        public Object visitAbstract(Expr.Abstract paramAbstract) {
            this.last_ident += 1;
            this.sym_map.put(paramAbstract.sym, new Integer(this.last_ident));
            Object localObject = paramAbstract.expr.visit(this);
            this.sym_map.remove(paramAbstract.sym);
            return localObject;
        }

        public Object visitApply(Expr.Apply paramApply) {
            int i = ((Integer) paramApply.left.visit(this)).intValue();
            int j = ((Integer) paramApply.right.visit(this)).intValue();
            return new Integer(i * 31 + j);
        }

        public Object visitIdent(Expr.Ident paramIdent) {
            Integer localInteger = (Integer) this.sym_map.get(paramIdent.sym);
            if (localInteger == null) {
                localInteger = new Integer(paramIdent.sym.toString().hashCode());
            }
            return localInteger;
        }

        private HashCodeComputer() {
        }
    }

    private boolean hash_code_known = false;
    private int hash_code_val;

    public ExprWrapper(Expr paramExpr) {
        this.expr = paramExpr;
    }

    public int hashCode() {
        if (!this.hash_code_known) {
            Integer localInteger = (Integer) this.expr.visit(new HashCodeComputer(null));
            this.hash_code_val = localInteger.intValue();
            this.hash_code_known = true;
        }
        return this.hash_code_val;
    }

    public boolean equals(Object paramObject) {
        if ((paramObject instanceof ExprWrapper)) {
            ExprWrapper localExprWrapper = (ExprWrapper) paramObject;
            if (localExprWrapper.hashCode() != hashCode()) {
                return false;
            }
            if (localExprWrapper.expr == this.expr) {
                return true;
            }
            return this.expr.visitP(new EqualsVisitor(null), localExprWrapper.expr) == TRUE;
        }
        if ((paramObject instanceof Expr)) {
            return equals(new ExprWrapper((Expr) paramObject));
        }
        return false;
    }
}


text:
namespace draco {

// Class for decoding a sequence of bits that were encoded with RAnsBitEncoder.
class RAnsBitDecoder {
  public:
    RAnsBitDecoder();
    ~RAnsBitDecoder();

    // Sets |source_buffer| as the buffer to decode bits from.
    // Returns false when the data is invalid.
    bool StartDecoding(DecoderBuffer *source_buffer);

    // Decode one bit. Returns true if the bit is a 1, otherwise false.
    bool DecodeNextBit();

    // Decode the next |nbits| and return the sequence in |value|. |nbits| must be
    // > 0 and <= 32.
    void DecodeLeastSignificantBits32(int nbits, uint32_t *value);

    void EndDecoding() {}

  private:
    void Clear();

    AnsDecoder ans_decoder_;
    uint8_t prob_zero_;
};

}  // namespace draco

#endif  // DRACO_CORE_BIT_CODERS_RANS_BIT_DECODER_H_


text:
from setuptools import setup

with open('README.rst') as readme_file:
    readme = readme_file.read()

with open('HISTORY.rst') as history_file:
    history = history_file.read()

requirements = [
    'Click>=6.0',
    # TODO: put package requirements here
]

test_requirements = [
    # TODO: put package test requirements here
]

setup(
    name='localhost',
    version='0.1.0',
    description="Arquivos para plotagem de áreas de abrangência dos projetos do GOC",
    long_description=readme + '\n\n' + history,
    author="GOC - Grupo de Oceanografia Costeira",
    author_email='arnaldorusso@gmail.com',
    url='https://github.com/arnaldorusso/localhost',
    packages=[
        'localhost',
    ],
    package_dir={'localhost':
                 'localhost'},
    entry_points={
        'console_scripts': [
            'localhost=localhost.cli:main'
        ]
    },
    include_package_data=True,
    install_requires=requirements,
    license="MIT license",
    zip_safe=False,
    keywords='localhost',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        "Programming Language :: Python :: 2",
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],
    test_suite='tests',
    tests_require=test_requirements
)


text:
#include "DataLog.h"

#include "FileUtils.h"

#include <folly/GroupVarint.h>

#include "BitUtil.h"
#include "GorillaStatsManager.h"

namespace facebook {
namespace gorilla {

DEFINE_int32(
    data_log_buffer_size,
    65536,
    "The size of the internal buffer when logging data. Buffer size of 64K "
    "equals roughly to 3 seconds of data before it's written to disk");
DEFINE_int32(
    max_allowed_timeseries_id,
    10000000,
    "This is the maximum allowed id for a time series in a shard. This is used "
    "for sanity checking that the file isn't corrupt and to avoid allocating "
    "too much memory");

// The algorithm for encoding data tries to take a full use of
// bytes. In the optimal case everything will fit 3 bytes. This is
// possible when the value doesn't change and the timestamp is the
// same as before. If timestamp is different, but value doesn't
// change, it's possible to use 4 bytes. If the value changes, a
// variable number of bytes will be used.

// 3 bytes with with three unused bits. One of the is used for the control bit.
const static int kShortIdBits = 21;

// 4 bytes with with three unused bits. One of the is used for the control bit.
const static int kLongIdBits = 29;
const static int kShortIdControlBit = 0;
const static int kLongIdControlBit = 1;

// 7 + 2 control bits -> 7 bits left in the byte.
const static int kShortDeltaBits = 7;
const static int kShortDeltaMin = -(1 << (kShortDeltaBits - 1)) + 1;
const static int kShortDeltaMax = (1 << (kShortDeltaBits - 1));

// 14 + 3 control bits -> 7 bits left in the byte.
const static int kMediumDeltaBits = 14;
const static int kMediumDeltaMin = -(1 << (kMediumDeltaBits - 1)) + 1;
const static int kMediumDeltaMax = (1 << (kMediumDeltaBits - 1));

const static int kLargeDeltaBits = 32;
const static int32_t kLargeDeltaMin = std::numeric_limits<int32_t>::min();

// Control bits for the timestamp type
const static int kZeroDeltaControlValue = 0; // 0
const static int kShortDeltaControlValue = 2; // 10
const static int kMediumDeltaControlValue = 6; // 110
const static int kLargeDeltaControlValue = 7; // 111

const static int kPreviousValuesVectorSizeIncrement = 1000;

const static int kBlockSizeBits = 6;
const static int kLeadingZerosBits = 5;
const static int kMinBytesNeeded = 3;

const static int kSameValueControlBit = 0;
const static int kDifferentValueControlBit = 1;

const static std::string kFailedCounter = ".failed_writes.log";

DataLogWriter::DataLogWriter(FileUtils::File&& out, int64_t baseTime)
    : out_(out),
      lastTimestamp_(baseTime),
      buffer_(new char[FLAGS_data_log_buffer_size]),
      bufferSize_(0) {
  GorillaStatsManager::addStatExportType(kFailedCounter, SUM);
}

DataLogWriter::~DataLogWriter() {
  if (out_.file) {
    flushBuffer();
    FileUtils::closeFile(out_.file);
  }
}

void DataLogWriter::append(uint32_t id, int64_t unixTime, double value) {
  folly::fbstring bits;
  uint32_t numBits = 0;

  if (id > FLAGS_max_allowed_timeseries_id) {
    LOG(ERROR) << "ID too large. Increase max_allowed_timeseries_id?";
    return;
  }

  // Leave two bits unused in the current byte after adding the id to
  // allow the best case scenario of time delta = 0 and value/xor = 0.
  if (id >= (1 << kShortIdBits)) {
    BitUtil::addValueToBitString(kLongIdControlBit, 1, bits, numBits);
    BitUtil::addValueToBitString(id, kLongIdBits, bits, numBits);
  } else {
    BitUtil::addValueToBitString(kShortIdControlBit, 1, bits, numBits);
    BitUtil::addValueToBitString(id, kShortIdBits, bits, numBits);
  }

  // Optimize for zero delta case and increase used bits 8 at a time
  // to fill bytes.
  int64_t delta = unixTime - lastTimestamp_;
  if (delta == 0) {
    BitUtil::addValueToBitString(kZeroDeltaControlValue, 1, bits, numBits);
  } else if (delta >= kShortDeltaMin && delta <= kShortDeltaMax) {
    delta -= kShortDeltaMin;
    CHECK_LT(delta, 1 << kShortDeltaBits);

    BitUtil::addValueToBitString(kShortDeltaControlValue, 2, bits, numBits);
    BitUtil::addValueToBitString(delta, kShortDeltaBits, bits, numBits);
  } else if (delta >= kMediumDeltaMin && delta <= kMediumDeltaMax) {
    delta -= kMediumDeltaMin;
    CHECK_LT(delta, 1 << kMediumDeltaBits);

    BitUtil::addValueToBitString(kMediumDeltaControlValue, 3, bits, numBits);
    BitUtil::addValueToBitString(delta, kMediumDeltaBits, bits, numBits);
  } else {
    delta -= kLargeDeltaMin;
    BitUtil::addValueToBitString(kLargeDeltaControlValue, 3, bits, numBits);
    BitUtil::addValueToBitString(delta, kLargeDeltaBits, bits, numBits);
  }

  if (id >= previousValues_.size()) {
    // If the value hasn't been seen before, assume that the previous
    // value is zero.
    previousValues_.resize(id + kPreviousValuesVectorSizeIncrement, 0);
  }

  uint64_t* v = (uint64_t*)&value;
  uint64_t* previousValue = (uint64_t*)&previousValues_[id];
  uint64_t xorWithPrevious = *v ^ *previousValue;
  if (xorWithPrevious == 0) {
    // Same as previous value, just store a single bit.
    BitUtil::addValueToBitString(kSameValueControlBit, 1, bits, numBits);
  } else {
    BitUtil::addValueToBitString(kDifferentValueControlBit, 1, bits, numBits);

    // Check TimeSeriesStream.cpp for more information about this
    // algorithm.
    int leadingZeros = __builtin_clzll(xorWithPrevious);
    int trailingZeros = __builtin_ctzll(xorWithPrevious);
    if (leadingZeros > 31) {
      leadingZeros = 31;
    }
    int blockSize = 64 - leadingZeros - trailingZeros;
    uint64_t blockValue = xorWithPrevious >> trailingZeros;

    BitUtil::addValueToBitString(
        leadingZeros, kLeadingZerosBits, bits, numBits);
    BitUtil::addValueToBitString(blockSize - 1, kBlockSizeBits, bits, numBits);
    BitUtil::addValueToBitString(blockValue, blockSize, bits, numBits);
  }

  previousValues_[id] = value;
  lastTimestamp_ = unixTime;

  if (bits.length() + bufferSize_ > FLAGS_data_log_buffer_size) {
    flushBuffer();
  }

  memcpy(buffer_.get() + bufferSize_, bits.data(), bits.length());
  bufferSize_ += bits.length();
}

bool DataLogWriter::flushBuffer() {
  bool success = true;
  if (bufferSize_ > 0) {
    int written = fwrite(buffer_.get(), sizeof(char), bufferSize_, out_.file);
    if (written != bufferSize_) {
      PLOG(ERROR) << "Flushing buffer failed! Wrote " << written << " of "
                  << bufferSize_ << " to " << out_.name;
      GorillaStatsManager::addStatValue(kFailedCounter, 1);
      success = false;
    }
    bufferSize_ = 0;
  }

  return success;
}

int DataLogReader::readLog(
    const FileUtils::File& file,
    int64_t baseTime,
    std::function<bool(uint32_t, int64_t, double)> out) {
  fseek(file.file, 0, SEEK_END);
  size_t len = ftell(file.file);
  if (len == 0) {
    return 0;
  }

  std::unique_ptr<char[]> buffer(new char[len]);
  fseek(file.file, 0, SEEK_SET);
  if (fread(buffer.get(), 1, len, file.file) != len) {
    PLOG(ERROR) << "Failed to read entire file " << file.name;
    return -1;
  }

  // Read out all the available points.
  int points = 0;
  int64_t prevTime = baseTime;
  std::vector<double> previousValues;
  uint64_t bitPos = 0;

  // Need at least three bytes for a complete value.
  while (bitPos <= len * 8 - kMinBytesNeeded * 8) {
    try {
      // Read the id of the time series.
      int idControlBit =
          BitUtil::readValueFromBitString(buffer.get(), len, bitPos, 1);
      uint32_t id;
      if (idControlBit == kShortIdControlBit) {
        id = BitUtil::readValueFromBitString(
            buffer.get(), len, bitPos, kShortIdBits);
      } else {
        id = BitUtil::readValueFromBitString(
            buffer.get(), len, bitPos, kLongIdBits);
      }

      if (id > FLAGS_max_allowed_timeseries_id) {
        LOG(ERROR) << "Corrupt file. ID is too large " << id;
        break;
      }

      // Read the time stamp delta based on the the number of bits in
      // the delta.
      uint32_t timeDeltaControlValue =
          BitUtil::readValueThroughFirstZero(buffer.get(), len, bitPos, 3);
      int64_t timeDelta = 0;
      switch (timeDeltaControlValue) {
        case kZeroDeltaControlValue:
          break;
        case kShortDeltaControlValue:
          timeDelta = BitUtil::readValueFromBitString(
                          buffer.get(), len, bitPos, kShortDeltaBits) +
              kShortDeltaMin;
          break;
        case kMediumDeltaControlValue:
          timeDelta = BitUtil::readValueFromBitString(
                          buffer.get(), len, bitPos, kMediumDeltaBits) +
              kMediumDeltaMin;
          break;
        case kLargeDeltaControlValue:
          timeDelta = BitUtil::readValueFromBitString(
                          buffer.get(), len, bitPos, kLargeDeltaBits) +
              kLargeDeltaMin;
          break;
        default:
          LOG(ERROR) << "Invalid time delta control value "
                     << timeDeltaControlValue;
          return points;
      }

      int64_t unixTime = prevTime + timeDelta;
      prevTime = unixTime;

      if (id >= previousValues.size()) {
        previousValues.resize(id + kPreviousValuesVectorSizeIncrement, 0);
      }

      // Finally read the value.
      double value;
      uint32_t sameValueControlBit =
          BitUtil::readValueFromBitString(buffer.get(), len, bitPos, 1);
      if (sameValueControlBit == kSameValueControlBit) {
        value = previousValues[id];
      } else {
        uint32_t leadingZeros = BitUtil::readValueFromBitString(
            buffer.get(), len, bitPos, kLeadingZerosBits);
        uint32_t blockSize = BitUtil::readValueFromBitString(
                                 buffer.get(), len, bitPos, kBlockSizeBits) +
            1;
        uint64_t blockValue = BitUtil::readValueFromBitString(
            buffer.get(), len, bitPos, blockSize);

        // Shift to left by the number of trailing zeros
        blockValue <<= (64 - blockSize - leadingZeros);

        uint64_t* previousValue = (uint64_t*)&previousValues[id];
        uint64_t xorredValue = blockValue ^ *previousValue;
        double* temp = (double*)&xorredValue;
        value = *temp;
      }

      previousValues[id] = value;

      // Each tuple (id, unixTime, value) in the file is byte aligned.
      if (bitPos % 8 != 0) {
        bitPos += 8 - (bitPos % 8);
      }

      if (!out(id, unixTime, value)) {
        // Callback doesn't accept more points.
        break;
      }
      points++;

    } catch (std::exception& e) {
      // Most likely too many bits were being read.
      LOG(ERROR) << e.what();
      break;
    }
  }

  return points;
}
}
} // facebook:gorilla


text:
package com.annimon.stream.operator;

import com.annimon.stream.function.IntPredicate;
import com.annimon.stream.iterator.PrimitiveExtIterator;
import com.annimon.stream.iterator.PrimitiveIterator;
import org.jetbrains.annotations.NotNull;

public class IntTakeUntil extends PrimitiveExtIterator.OfInt {

    private final PrimitiveIterator.OfInt iterator;
    private final IntPredicate stopPredicate;

    public IntTakeUntil(
            @NotNull PrimitiveIterator.OfInt iterator,
            @NotNull IntPredicate stopPredicate) {
        this.iterator = iterator;
        this.stopPredicate = stopPredicate;
    }

    @Override
    protected void nextIteration() {
        hasNext = iterator.hasNext() && !(isInit && stopPredicate.test(next));
        if (hasNext) {
            next = iterator.nextInt();
        }
    }
}


text:
<?php

namespace Google\Service\DatabaseMigrationService;

class SqlIpConfig extends \Google\Collection
{
  protected $collection_key = 'authorizedNetworks';
  protected $authorizedNetworksType = SqlAclEntry::class;
  protected $authorizedNetworksDataType = 'array';
  /**
   * @var bool
   */
  public $enableIpv4;
  /**
   * @var string
   */
  public $privateNetwork;
  /**
   * @var bool
   */
  public $requireSsl;

  /**
   * @param SqlAclEntry[]
   */
  public function setAuthorizedNetworks($authorizedNetworks)
  {
    $this->authorizedNetworks = $authorizedNetworks;
  }
  /**
   * @return SqlAclEntry[]
   */
  public function getAuthorizedNetworks()
  {
    return $this->authorizedNetworks;
  }
  /**
   * @param bool
   */
  public function setEnableIpv4($enableIpv4)
  {
    $this->enableIpv4 = $enableIpv4;
  }
  /**
   * @return bool
   */
  public function getEnableIpv4()
  {
    return $this->enableIpv4;
  }
  /**
   * @param string
   */
  public function setPrivateNetwork($privateNetwork)
  {
    $this->privateNetwork = $privateNetwork;
  }
  /**
   * @return string
   */
  public function getPrivateNetwork()
  {
    return $this->privateNetwork;
  }
  /**
   * @param bool
   */
  public function setRequireSsl($requireSsl)
  {
    $this->requireSsl = $requireSsl;
  }
  /**
   * @return bool
   */
  public function getRequireSsl()
  {
    return $this->requireSsl;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(SqlIpConfig::class, 'Google_Service_DatabaseMigrationService_SqlIpConfig');


text:
using System.Collections.Generic;
using Cresce.Models;

namespace Cresce.Datasources.Repositories
{
    public interface IServiceRepository : IResourceExistsQuery, IGetByIdQuery<Service>
    {
        IEnumerable<Service> GetServices();
        Service Save(Service service);
    }
}


text:
@interface BOXAPIJSONPatchOperation : BOXAPIJSONOperation

- (id)initWithURL:(NSURL *)URL HTTPMethod:(NSString *)HTTPMethod patchOperations:(NSArray *)patchOperations queryParams:(NSDictionary *)queryParams OAuth2Session:(BOXOAuth2Session *)OAuth2Session;

@end


text:
NS_ASSUME_NONNULL_BEGIN
@protocol SurfaceHandle <NSObject>
- (cairo_t *) cairo;
- (BOOL) finishWithError: (NSError **) error;
@end
NS_ASSUME_NONNULL_END


text:
module ArticleStructuresHelper
end


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/aiplatform/v1/tensorboard_service.proto

package com.google.cloud.aiplatform.v1;

public interface UpdateTensorboardTimeSeriesRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.aiplatform.v1.UpdateTensorboardTimeSeriesRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. Field mask is used to specify the fields to be overwritten in the
   * TensorboardTimeSeries resource by the update.
   * The fields specified in the update_mask are relative to the resource, not
   * the full request. A field will be overwritten if it is in the mask. If the
   * user does not provide a mask then all fields will be overwritten if new
   * values are specified.
   *

   *
   * .google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
   *
   *
   * @return Whether the updateMask field is set.
   */
  boolean hasUpdateMask();
  /**
   *
   *
   *

   * Required. Field mask is used to specify the fields to be overwritten in the
   * TensorboardTimeSeries resource by the update.
   * The fields specified in the update_mask are relative to the resource, not
   * the full request. A field will be overwritten if it is in the mask. If the
   * user does not provide a mask then all fields will be overwritten if new
   * values are specified.
   *

   *
   * .google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
   *
   *
   * @return The updateMask.
   */
  com.google.protobuf.FieldMask getUpdateMask();
  /**
   *
   *
   *

   * Required. Field mask is used to specify the fields to be overwritten in the
   * TensorboardTimeSeries resource by the update.
   * The fields specified in the update_mask are relative to the resource, not
   * the full request. A field will be overwritten if it is in the mask. If the
   * user does not provide a mask then all fields will be overwritten if new
   * values are specified.
   *

   *
   * .google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
   *
   */
  com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder();

  /**
   *
   *
   *

   * Required. The TensorboardTimeSeries' `name` field is used to identify the
   * TensorboardTimeSeries to be updated.
   * Format:
   * `projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}/runs/{run}/timeSeries/{time_series}`
   *

   *
   *
   * .google.cloud.aiplatform.v1.TensorboardTimeSeries tensorboard_time_series = 2 [(.google.api.field_behavior) = REQUIRED];
   *
   *
   * @return Whether the tensorboardTimeSeries field is set.
   */
  boolean hasTensorboardTimeSeries();
  /**
   *
   *
   *

   * Required. The TensorboardTimeSeries' `name` field is used to identify the
   * TensorboardTimeSeries to be updated.
   * Format:
   * `projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}/runs/{run}/timeSeries/{time_series}`
   *

   *
   *
   * .google.cloud.aiplatform.v1.TensorboardTimeSeries tensorboard_time_series = 2 [(.google.api.field_behavior) = REQUIRED];
   *
   *
   * @return The tensorboardTimeSeries.
   */
  com.google.cloud.aiplatform.v1.TensorboardTimeSeries getTensorboardTimeSeries();
  /**
   *
   *
   *

   * Required. The TensorboardTimeSeries' `name` field is used to identify the
   * TensorboardTimeSeries to be updated.
   * Format:
   * `projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}/runs/{run}/timeSeries/{time_series}`
   *

   *
   *
   * .google.cloud.aiplatform.v1.TensorboardTimeSeries tensorboard_time_series = 2 [(.google.api.field_behavior) = REQUIRED];
   *
   */
  com.google.cloud.aiplatform.v1.TensorboardTimeSeriesOrBuilder getTensorboardTimeSeriesOrBuilder();
}


text:
.. _glance-image-migration:

======================
Glance image migration
======================

Glance images have following attributes:

 - Private or public
     - Public images are accessible from ALL tenants, thus potentially any VM
       may be created from an image from another tenant.
 - Image memberships
     - Private images are allowed to have :dfn:`members` – other tenants
       which have access to an image.

With the above in mind and given that there is currently no support for
relationships between objects in CloudFerry (this is planned for future
releases), there are following ways of performing glance image migration:

 1. Copy all public images and images with memberships in other tenants, plus
    all associated tenants, or
 2. Copy only images which are specified in
    :ref:`filtering config <filter-configuration>`, that is either only
    images belonging to a tenant, or image IDs specified.

That behavior is controlled by
:dfn:`dont_include_public_and_members_from_other_tenants` option specified in
:ref:`filter file <filter-configuration>`.

Process
-------

 1. Download image from source cloud using glance APIs;
 2. Upload image to destination cloud using glance APIs;
 3. Glance image UUID will be kept in destination, unless an image with the
    same ID exists or existed previously.

.. note::

    Process above **does not** create extra copy of image anywhere, instead
    it redirects image from source cloud to destination using system streams.

Frequently Asked Questions
--------------------------

**Q**: I specified only 1 (one!) image in
:ref:`filter file <filter-configuration>`, but it tries to migrate all the
public images in the cloud! WTF???

**A**: This is happening because potentially VM may be booted from any public
image or image with membership in a migrated tenant. In case you're only
trying to migrate images, and no other resources (for example, you're using
:file:`3_get_and_transfer_images.yaml` as your scenario), than you can
override this behavior by making
:dfn:`dont_include_public_and_members_from_other_tenants` option
enabled in :ref:`filter file <filter-configuration>`. If it still tries to
migrate all the images - make sure you have :dfn:`act_get_filter` action
enabled in your scenario.

**Q**: Glance APIs allow specifying glance images IDs, but image I
migrated has different ID. WTF???

**A**: Glance image IDs are only kept if image with that ID does not exist or
existed previously in destination cloud. Glance keeps deleted images and their
IDs and does allow to create image with the ID already known to glance.


text:
# Using data providers

Simply put, data providers are the sources of data for your Elasticsearch indices.

By default, each index is assigned a default *self* data provider (`ElasticsearchProvider`), which retrieves the data from the Elasticsearch index itself. This is useful when you want to rebuild the index (like if you changed the mapping and want to update it).

In order to define your own custom data provider for a certain type, you have to create a service that implements `ProviderInterface` and tag it as `sfes.provider`, specifying the entity it is for in the `type` argument:

```
services:
    app.es.data_provider.product:
        class: AppBundle\ElasticSearch\Document\Provider\ProductProvider
        arguments:
            - AppBundle:Product
            - @doctrine.orm.entity_manager
        tags:
            - { name: sfes.provider, type: "AppBundle:Product" }
```

If your data is coming from Doctrine, you may extend the `AbstractDoctrineProvider` class, which provides you with the basic framework and you only need to extend a couple of methods in it, to make it work for your case:

```
    /**
     * Gets the query that will return all records from the DB
     *
     * @return Query
     */
    abstract public function getQuery();

    /**
     * Converts a Doctrine entity to Elasticsearch entity
     *
     * @param mixed $entity A doctrine entity object or data array
     * @return mixed An ES document entity object or document array
     */
    abstract protected function getAsDocument($entity);
```


text:
/*jshint node:true, mocha:true */

'use strict';

require('should');

var olsen = require('../src/olsen');

function isEven(x) {
  return x % 2 === 0;
}

function identity(x) {
  return x;
}

describe('olsen', function() {
  it('should validate two of a kind', function() {
    olsen(1, 1)(Number).should.be.exactly(true);
    olsen(1, 0.99999999999999999)(Number).should.be.true; // 0.999... becomes exactly 1
    olsen(1, '1.0')(Number).should.be.exactly(true);

    olsen(1, 3)(isEven).should.be.exactly(true); // both of kind "not even"
    olsen(2, 4)(isEven).should.be.exactly(true); // both of kind "even"

    olsen(Math.PI / 4, 7 / 4 * Math.PI)(function(x) {
      return Math.cos(x).toFixed(10);
    }).should.be.exactly(true);
  });

  it('should invalidate different kinds', function() {
    olsen(1, 2)(isEven).should.be.exactly(false);
    olsen(1, 0.9999999999999999)(Number).should.be.exactly(false);
    olsen(1, '1.0')(JSON.stringify).should.be.exactly(false);
    olsen(NaN, NaN)(identity).should.be.exactly(false); // NaN !== NaN
  });
});


text:
angular.module( 'orderCloud', [
        'ngSanitize',
        'ngAnimate',
        'ngMessages',
        'ngTouch',
        'ui.tree',
        'ui.router',
        'ui.bootstrap',
        'orderCloud.sdk',
	'LocalForageModule',
        'toastr',
        'jcs-autoValidate',
        'ordercloud-infinite-scroll',
        'ordercloud-buyer-select',
        'ordercloud-search',
        'ordercloud-assignment-helpers',
        'ordercloud-paging-helpers',
        'ordercloud-auto-id',
        'ordercloud-current-order',
        'ordercloud-address',
        'ordercloud-lineitems'
    ])

    .run( SetBuyerID )
    .config( Routing )
    .config( ErrorHandling )
    .config( Interceptor )
    .controller( 'AppCtrl', AppCtrl )
;

function SetBuyerID( OrderCloud, buyerid ) {
    OrderCloud.BuyerID.Get() ? angular.noop() : OrderCloud.BuyerID.Set(buyerid);
}

function Routing( $urlRouterProvider, $urlMatcherFactoryProvider, $locationProvider ) {
    $urlMatcherFactoryProvider.strictMode(false);
    $urlRouterProvider.otherwise( '/home' );
    $locationProvider.html5Mode(true);
}

function ErrorHandling( $provide ) {
    $provide.decorator('$exceptionHandler', handler);

    function handler( $delegate, $injector ) {
        return function( ex, cause ) {
            $delegate(ex, cause);
            $injector.get('toastr').error(ex.data ? (ex.data.error || (ex.data.Errors ? ex.data.Errors[0].Message : ex.data)) : ex.message, 'Error');
        };
    }
}

function AppCtrl( $rootScope, $state, appname, OrderCloud ) {
    var vm = this;
    vm.name = appname;
    vm.title = appname;
    vm.showLeftNav = true;
    vm.$state = $state;

    vm.toggleLeftNav = function() {
        vm.showLeftNav = !vm.showLeftNav;
    };

    vm.logout = function() {
        OrderCloud.Auth.RemoveToken();
        OrderCloud.Auth.RemoveImpersonationToken();
        OrderCloud.BuyerID.Set(null);
        $state.go('login');
    };

    $rootScope.$on('$stateChangeSuccess', function(e, toState) {
        if (toState.data && toState.data.componentName) {
            vm.title = appname + ' - ' + toState.data.componentName
        } else {
            vm.title = appname;
        }
    });

    $rootScope.$on('OC:AccessInvalidOrExpired', function() {
        vm.logout();
    });
}

function Interceptor( $httpProvider ) {
    $httpProvider.interceptors.push(function($q, $rootScope) {
        return {
            'responseError': function(rejection) {
                if (rejection.config.url.indexOf('ordercloud.io') > -1 && rejection.status == 401) {
                    $rootScope.$broadcast('OC:AccessInvalidOrExpired');
                }
                return $q.reject(rejection);
            }
        };
    });
}


text:
<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="android:Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/AppActionBar</item>
        <item name="android:windowContentOverlay">@null</item>
    </style>

    <style name="AppActionBar" parent="@android:style/Widget.Holo.Light.ActionBar.Solid">
        <item name="android:background">@color/actionbar_background</item>
        <item name="android:indeterminateProgressStyle">@style/IndeterminateProgressBar</item>
    </style>

    <style name="IndeterminateProgressBar" parent="@android:style/Widget.Holo.Light.ProgressBar.Large">
        <item name="android:minWidth">52dp</item>
        <item name="android:maxWidth">52dp</item>
        <item name="android:minHeight">32dp</item>
        <item name="android:maxHeight">32dp</item>
    </style>
</resources>


text:
using YuYan.Data.DbContext;
using YuYan.Data.Repository;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using YuYan.Domain.Database;
using System.Threading.Tasks;
using YuYan.Domain.DTO;
using System;

namespace YuYan.Test
{
    [TestClass]
    public class RepositoryTest
    {
        /*
        [TestMethod]
        public async void TestInitialize()
        {
            using (YuYanDBContext db = new YuYanDBContext())
            using (YuYanDBRepository repos = new YuYanDBRepository(db))
            {
                var surveys = await repos.GetAllActiveSurveys();
                foreach (var survey in surveys) {
                    survey.IsDeleted = false;
                    var questions = await repos.GetSurveyQuestionsBySurveyId(survey.SurveyId);
                    foreach (var question in questions) {
                        question.IsDeleted = false;
                        var items = await repos.GetQuestionItemsByQuestionId(question.QuestionId);
                        foreach (var item in items) {
                            item.IsDeleted = false;
                        }
                    }
                }
                await db.SaveChangesAsync();
            }
        }
         */

        [TestMethod]
        public void TestSelf()
        {
            int x = 1; int y = 1;
            int z = 2;

            Assert.AreEqual(z, x + y);
        }

        #region user
        [TestMethod]
        public async Task TestRepo_CreateUser()
        {
            using (YuYanDBContext db = new YuYanDBContext())
            using (YuYanDBRepository repos = new YuYanDBRepository(db))
            {
                dtoUser testuser = new dtoUser() { Email = "test001@test.com", Password = "qwerty" };

                tbUser userobj = await repos.CreateNewUser(testuser);
                Assert.IsNotNull(userobj);
                Assert.AreEqual("test001@test.com", userobj.Email, true);
            }
        }

        [TestMethod]
        public async Task TestRepo_SuccessLogin_User()
        {
            using (YuYanDBContext db = new YuYanDBContext())
            using (YuYanDBRepository repos = new YuYanDBRepository(db))
            {
                dtoUser testuser = new dtoUser() { Email = "test001@test.com", Password = "qwerty" };

                tbUser userobj = await repos.LoginUser(testuser);
                Assert.IsNotNull(userobj);
                Assert.AreEqual("test001@test.com", userobj.Email, true);
            }
        }

        [TestMethod]
        public async Task TestRepo_FailedLogin_UnknownUser()
        {
            using (YuYanDBContext db = new YuYanDBContext())
            using (YuYanDBRepository repos = new YuYanDBRepository(db))
            {
                dtoUser testuser = new dtoUser() { Email = "test001@unknown.com", Password = "qwerty" };

                tbUser userobj = await repos.LoginUser(testuser);
                Assert.IsNull(userobj); // is null means the user not existed in the database
            }
        }

        [TestMethod]
        public async Task TestRepo_FailedLogin_WrongPasswordUser()
        {
            using (YuYanDBContext db = new YuYanDBContext())
            using (YuYanDBRepository repos = new YuYanDBRepository(db))
            {
                dtoUser testuser = new dtoUser() { Email = "test001@test.com", Password = "12341234" };

                tbUser userobj = await repos.LoginUser(testuser);
                Assert.IsNotNull(userobj); // is new tbUser means the password not match
                Assert.AreEqual(Guid.Empty, userobj.UserId);
            }
        }

        #endregion

        #region survey
        [TestMethod]
        public async Task TestRepo_GetSurveyBySurveyId()
        {
            using (YuYanDBContext db = new YuYanDBContext())
            using (YuYanDBRepository repos = new YuYanDBRepository(db))
            {

                tbSurvey obj = await repos.GetSurveyBySurveyId(92);
                Assert.IsNotNull(obj);
                Assert.AreEqual("9292929292", obj.Title, true);
            }
        }
        #endregion

        #region question
        [TestMethod]
        public async Task TestRepo_GetSurveyQuestionBySurveyId()
        {

            using (YuYanDBContext db = new YuYanDBContext())
            using (YuYanDBRepository repos = new YuYanDBRepository(db))
            {

                var obj = await repos.GetSurveyQuestionsBySurveyId(1);
                Assert.IsNotNull(obj);
            }
        }
        #endregion

        #region item
        [TestMethod]
        public async Task TestRepo_GetQuestionItemsByQuestionId()
        {
            using (YuYanDBContext db = new YuYanDBContext())
            using (YuYanDBRepository repos = new YuYanDBRepository(db))
            {

                var obj = await repos.GetQuestionItemsByQuestionId(1);
                Assert.IsNotNull(obj);
            }
        }

        [TestMethod]
        public async Task TestRepo_CreateItem()
        {
            using (YuYanDBContext db = new YuYanDBContext())
            using (YuYanDBRepository repos = new YuYanDBRepository(db))
            {
                dtoSurveyQuestionItem newItem = new dtoSurveyQuestionItem();
                newItem.QuestionId = 1;
                newItem.ItemDescription = "The third choice";

                var obj = await repos.CreateNewItem(newItem);
                Assert.IsNotNull(obj);
            }
        }

        [TestMethod]
        public async Task TestRepo_UpdateItem()
        {
            using (YuYanDBContext db = new YuYanDBContext())
            using (YuYanDBRepository repos = new YuYanDBRepository(db))
            {
                dtoSurveyQuestionItem newItem = new dtoSurveyQuestionItem();
                newItem.QuestionItemId = 7;
                newItem.ItemDescription = "The ddddd chdfdsfsdsfoice";

                var obj = await repos.UpdateItem(newItem);
                Assert.IsNotNull(obj);
            }
        }

        [TestMethod]
        public async Task TestRepo_DeleteItem()
        {
            using (YuYanDBContext db = new YuYanDBContext())
            using (YuYanDBRepository repos = new YuYanDBRepository(db))
            {
                dtoSurveyQuestionItem newItem = new dtoSurveyQuestionItem();

                await repos.DeleteItem(4);

            }
        }

        #endregion

    }
}


text:
package io.github.kobakei.anago.usecase;

import javax.inject.Inject;

import io.github.kobakei.anago.repository.RepoRepository;
import io.github.kobakei.anago.repository.StarRepository;
import rx.Completable;

/**
 * スターをつけるユースケース
 * Created by keisuke on 2016/09/18.
 */

public class StarUseCase {

    private final StarRepository starRepository;
    private final RepoRepository repoRepository;

    @Inject
    public StarUseCase(StarRepository starRepository, RepoRepository repoRepository) {
        this.starRepository = starRepository;
        this.repoRepository = repoRepository;
    }

    public Completable run(String user, String repo) {
        return starRepository.put(user, repo)
                .doOnCompleted(repoRepository::clearCache);
    }
}


text:
.class Landroid/support/v7/app/AppCompatDelegateImplN;
.super Landroid/support/v7/app/AppCompatDelegateImplV23;
.source "AppCompatDelegateImplN.java"

# annotations
.annotation build Landroid/annotation/TargetApi;
    value = 0x18
.end annotation

.annotation build Landroid/support/annotation/RequiresApi;
    value = 0x18
.end annotation

.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/support/v7/app/AppCompatDelegateImplN$AppCompatWindowCallbackN;
    }
.end annotation

# direct methods
.method constructor <init>(Landroid/content/Context;Landroid/view/Window;Landroid/support/v7/app/AppCompatCallback;)V
    .locals 0
    .param p1, "context"    # Landroid/content/Context;
    .param p2, "window"    # Landroid/view/Window;
    .param p3, "callback"    # Landroid/support/v7/app/AppCompatCallback;

    .prologue
    .line 33
    invoke-direct {p0, p1, p2, p3}, Landroid/support/v7/app/AppCompatDelegateImplV23;-><init>(Landroid/content/Context;Landroid/view/Window;Landroid/support/v7/app/AppCompatCallback;)V

    .line 34
    return-void
.end method

# virtual methods
.method wrapWindowCallback(Landroid/view/Window$Callback;)Landroid/view/Window$Callback;
    .locals 1
    .param p1, "callback"    # Landroid/view/Window$Callback;

    .prologue
    .line 38
    new-instance v0, Landroid/support/v7/app/AppCompatDelegateImplN$AppCompatWindowCallbackN;

    invoke-direct {v0, p0, p1}, Landroid/support/v7/app/AppCompatDelegateImplN$AppCompatWindowCallbackN;-><init>(Landroid/support/v7/app/AppCompatDelegateImplN;Landroid/view/Window$Callback;)V

    return-object v0
.end method


text:
$:.push File.expand_path("../lib", __FILE__)
require 'readline-ng'

reader = ReadlineNG::Reader.new

loop do
  line = reader.get_line
  reader.puts_above("Got #{line}")
end


text:
package org.apache.hadoop.hive.ql.io.orc;

import org.iq80.snappy.Snappy;

import java.io.IOException;
import java.nio.ByteBuffer;

class SnappyCodec implements CompressionCodec {

  @Override
  public boolean compress(ByteBuffer in, ByteBuffer out,
                          ByteBuffer overflow) throws IOException {
    int inBytes = in.remaining();
    // I should work on a patch for Snappy to support an overflow buffer
    // to prevent the extra buffer copy.
    byte[] compressed = new byte[Snappy.maxCompressedLength(inBytes)];
    int outBytes =
        Snappy.compress(in.array(), in.arrayOffset() + in.position(), inBytes,
            compressed, 0);
    if (outBytes < inBytes) {
      int remaining = out.remaining();
      if (remaining >= outBytes) {
        System.arraycopy(compressed, 0, out.array(), out.arrayOffset() +
            out.position(), outBytes);
        out.position(out.position() + outBytes);
      } else {
        System.arraycopy(compressed, 0, out.array(), out.arrayOffset() +
            out.position(), remaining);
        out.position(out.limit());
        System.arraycopy(compressed, remaining, overflow.array(),
            overflow.arrayOffset(), outBytes - remaining);
        overflow.position(outBytes - remaining);
      }
      return true;
    } else {
      return false;
    }
  }

  @Override
  public void decompress(ByteBuffer in, ByteBuffer out) throws IOException {
    int inOffset = in.position();
    int uncompressLen =
        Snappy.uncompress(in.array(), in.arrayOffset() + inOffset,
        in.limit() - inOffset, out.array(), out.arrayOffset() + out.position());
    out.position(uncompressLen + out.position());
    out.flip();
  }
}


text:
package org.apache.pulsar.common.configuration;

import static org.apache.pulsar.common.configuration.PulsarConfigurationLoader.isComplete;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Properties;

import org.apache.pulsar.broker.ServiceConfiguration;
import org.apache.pulsar.common.configuration.FieldContext;
import org.apache.pulsar.common.configuration.PulsarConfigurationLoader;
import org.testng.annotations.Test;

public class PulsarConfigurationLoaderTest {

    @Test
    public void testPulsarConfiguraitonLoadingStream() throws Exception {
        File testConfigFile = new File("tmp." + System.currentTimeMillis() + ".properties");
        if (testConfigFile.exists()) {
            testConfigFile.delete();
        }
        final String zkServer = "z1.example.com,z2.example.com,z3.example.com";
        PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(testConfigFile)));
        printWriter.println("zookeeperServers=" + zkServer);
        printWriter.println("globalZookeeperServers=gz1.example.com,gz2.example.com,gz3.example.com/foo");
        printWriter.println("brokerDeleteInactiveTopicsEnabled=true");
        printWriter.println("statusFilePath=/tmp/status.html");
        printWriter.println("managedLedgerDefaultEnsembleSize=1");
        printWriter.println("backlogQuotaDefaultLimitGB=18");
        printWriter.println("clusterName=usc");
        printWriter.println("brokerClientAuthenticationPlugin=test.xyz.client.auth.plugin");
        printWriter.println("brokerClientAuthenticationParameters=role:my-role");
        printWriter.println("superUserRoles=appid1,appid2");
        printWriter.println("brokerServicePort=7777");
        printWriter.println("managedLedgerDefaultMarkDeleteRateLimit=5.0");
        printWriter.close();
        testConfigFile.deleteOnExit();
        InputStream stream = new FileInputStream(testConfigFile);
        final ServiceConfiguration serviceConfig = PulsarConfigurationLoader.create(stream, ServiceConfiguration.class);
        assertNotNull(serviceConfig);
        assertEquals(serviceConfig.getZookeeperServers(), zkServer);
        assertEquals(serviceConfig.isBrokerDeleteInactiveTopicsEnabled(), true);
        assertEquals(serviceConfig.getBacklogQuotaDefaultLimitGB(), 18);
        assertEquals(serviceConfig.getClusterName(), "usc");
        assertEquals(serviceConfig.getBrokerClientAuthenticationParameters(), "role:my-role");
        assertEquals(serviceConfig.getBrokerServicePort(), 7777);
    }

    @Test
    public void testPulsarConfiguraitonLoadingProp() throws Exception {
        final String zk = "localhost:2184";
        final Properties prop = new Properties();
        prop.setProperty("zookeeperServers", zk);
        final ServiceConfiguration serviceConfig = PulsarConfigurationLoader.create(prop, ServiceConfiguration.class);
        assertNotNull(serviceConfig);
        assertEquals(serviceConfig.getZookeeperServers(), zk);
    }

    @Test
    public void testPulsarConfiguraitonComplete() throws Exception {
        final String zk = "localhost:2184";
        final Properties prop = new Properties();
        prop.setProperty("zookeeperServers", zk);
        final ServiceConfiguration serviceConfig = PulsarConfigurationLoader.create(prop, ServiceConfiguration.class);
        try {
            isComplete(serviceConfig);
            fail("it should fail as config is not complete");
        } catch (IllegalArgumentException e) {
            // Ok
        }
    }

    @Test
    public void testComplete() throws Exception {
        TestCompleteObject complete = this.new TestCompleteObject();
        assertTrue(isComplete(complete));
    }

    @Test
    public void testInComplete() throws IllegalAccessException {

        try {
            isComplete(this.new TestInCompleteObjectRequired());
            fail("Should fail w/ illegal argument exception");
        } catch (IllegalArgumentException iae) {
            // OK, expected
        }

        try {
            isComplete(this.new TestInCompleteObjectMin());
            fail("Should fail w/ illegal argument exception");
        } catch (IllegalArgumentException iae) {
            // OK, expected
        }

        try {
            isComplete(this.new TestInCompleteObjectMax());
            fail("Should fail w/ illegal argument exception");
        } catch (IllegalArgumentException iae) {
            // OK, expected
        }

        try {
            isComplete(this.new TestInCompleteObjectMix());
            fail("Should fail w/ illegal argument exception");
        } catch (IllegalArgumentException iae) {
            // OK, expected
        }
    }

    class TestCompleteObject {
        @FieldContext(required = true)
        String required = "I am not null";
        @FieldContext(required = false)
        String optional;
        @FieldContext
        String optional2;
        @FieldContext(minValue = 1)
        int minValue = 2;
        @FieldContext(minValue = 1, maxValue = 3)
        int minMaxValue = 2;

    }

    class TestInCompleteObjectRequired {
        @FieldContext(required = true)
        String inValidRequired;
    }

    class TestInCompleteObjectMin {
        @FieldContext(minValue = 1, maxValue = 3)
        long inValidMin = 0;
    }

    class TestInCompleteObjectMax {
        @FieldContext(minValue = 1, maxValue = 3)
        long inValidMax = 4;
    }

    class TestInCompleteObjectMix {
        @FieldContext(required = true)
        String inValidRequired;
        @FieldContext(minValue = 1, maxValue = 3)
        long inValidMin = 0;
        @FieldContext(minValue = 1, maxValue = 3)
        long inValidMax = 4;
    }
}


text:
<?php

	class MY_URI extends CI_URI {

		private $uri_parameters = array();

		public function load_uri_parameters($uri)
		{
			$this->uri_parameters = Route::get_parameters($uri);
		}

		// Now the URI->segment Method also searchs for
		// named URIS in case we have declared them

		public function segment($n, $no_result = NULL)
		{
			if(!is_numeric($n))
			{
				if(array_key_exists($n, $this->uri_parameters))
				{
					$n = $this->uri_parameters[$n];
				}
				else
				{
					return $no_result;
				}
			}

			return parent::segment($n, $no_result);
		}

		public function rsegment($n, $no_result = NULL)
		{
			if(!is_numeric($n))
			{
				if(array_key_exists($n, $this->uri_parameters))
				{
					$n = $this->uri_parameters[$n];
				}
				else
				{
					return $no_result;
				}
			}

			return parent::rsegment($n, $no_result);
		}

	}


text:
import Post from 'src/models/PostModel';
import Subscriber from 'src/models/SubscriberModel';

export const publishedPosts = () => Post.find({
  lastPublished: { $ne: null },
  publishedMarkdown: { $ne: '' },
})
  .populate('country')
  .sort('-postDate');

export const post = id => Post.findOne({
  _id: id,
});

export const subscribers = () => Subscriber.find({});

export const nextPost = postDate => Post.findOne({
  postDate: { $gt: postDate },
})
  .sort('postDate');


text:
/**
 * ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
 * @version v20.1.0
 * @link http://www.ag-grid.com/
 * @license MIT
 */
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = require("./utils");
function defaultGroupComparator(valueA, valueB, nodeA, nodeB, accentedCompare) {
    if (accentedCompare === void 0) { accentedCompare = false; }
    console.warn('ag-Grid: Since ag-grid 11.0.0 defaultGroupComparator is not necessary. You can remove this from your colDef');
    var nodeAIsGroup = utils_1._.exists(nodeA) && nodeA.group;
    var nodeBIsGroup = utils_1._.exists(nodeB) && nodeB.group;
    var bothAreGroups = nodeAIsGroup && nodeBIsGroup;
    var bothAreNormal = !nodeAIsGroup && !nodeBIsGroup;
    if (bothAreGroups) {
        return utils_1._.defaultComparator(nodeA.key, nodeB.key, accentedCompare);
    }
    else if (bothAreNormal) {
        return utils_1._.defaultComparator(valueA, valueB, accentedCompare);
    }
    else if (nodeAIsGroup) {
        return 1;
    }
    else {
        return -1;
    }
}
exports.defaultGroupComparator = defaultGroupComparator;


text: module.exports = require('./lib/sqlite-promise.js');


text:
package org.apache.isis.applib.services.eventbus;

/**
 * Common interface for all Event Bus implementations.
 *
 *

 *     Defines an (non-pluggable, hard-coded) SPI to the {@link org.apache.isis.applib.services.eventbus.EventBusService},
 *     to allow alternativeimplementations of in-memory event bus to be used.
 *

 *
 *

 *     Currently, there are implementations based on Guava and on the Axon framework.
 *

 */
public interface EventBusImplementation {

    /**
     * For {@link org.apache.isis.applib.services.eventbus.EventBusService} to call on
     * {@link org.apache.isis.applib.services.eventbus.EventBusService#register(Object)}.
     */
    void register(Object domainService);

    /**
     * For {@link org.apache.isis.applib.services.eventbus.EventBusService} to call on
     * {@link org.apache.isis.applib.services.eventbus.EventBusService#unregister(Object)}.
     */
    void unregister(Object domainService);

    /**
     * For {@link org.apache.isis.applib.services.eventbus.EventBusService} to call on
     * {@link org.apache.isis.applib.services.eventbus.EventBusService#post(Object)}.
     */
    void post(Object event);

}


text:
/**
* SensorHolder.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from Sensor.idl
* Monday, November 25, 2013 3:41:52 PM BRST
*/

public final class SensorHolder implements org.omg.CORBA.portable.Streamable
{
  public Sensor value = null;

  public SensorHolder ()
  {
  }

  public SensorHolder (Sensor initialValue)
  {
    value = initialValue;
  }

  public void _read (org.omg.CORBA.portable.InputStream i)
  {
    value = SensorHelper.read (i);
  }

  public void _write (org.omg.CORBA.portable.OutputStream o)
  {
    SensorHelper.write (o, value);
  }

  public org.omg.CORBA.TypeCode _type ()
  {
    return SensorHelper.type ();
  }

}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>ArduinoDistanceSensorLibrary: DistanceGP2Y0A21YK Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

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

ArduinoDistanceSensorLibrary

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

 All Classes Functions Pages

Public Member Functions |
List of all members

DistanceGP2Y0A21YK Class Reference

Inheritance diagram for DistanceGP2Y0A21YK:

<map name="_distance_g_p2_y0_a21_y_k_inherit__map" id="_distance_g_p2_y0_a21_y_k_inherit__map">
<area shape="rect" id="node2" href="class_analog_distance_sensor.html" title="{AnalogDistanceSensor\n|# _refVoltage\l|+ AnalogDistanceSensor()\l+ begin()\l+ begin()\l+ getDistanceRaw()\l+ getDistanceVolt()\l+ setARefVoltage()\l}" alt="" coords="7,174,180,346"/><area shape="rect" id="node4" href="class_distance_sensor.html" title="{DistanceSensor\n|# _average\l|+ isCloser()\l+ isFarther()\l+ setAveraging()\l}" alt="" coords="35,5,152,125"/></map>

Collaboration diagram for DistanceGP2Y0A21YK:

<map name="_distance_g_p2_y0_a21_y_k_coll__map" id="_distance_g_p2_y0_a21_y_k_coll__map">
<area shape="rect" id="node2" href="class_analog_distance_sensor.html" title="{AnalogDistanceSensor\n|# _refVoltage\l|+ AnalogDistanceSensor()\l+ begin()\l+ begin()\l+ getDistanceRaw()\l+ getDistanceVolt()\l+ setARefVoltage()\l}" alt="" coords="7,174,180,346"/><area shape="rect" id="node4" href="class_distance_sensor.html" title="{DistanceSensor\n|# _average\l|+ isCloser()\l+ isFarther()\l+ setAveraging()\l}" alt="" coords="35,5,152,125"/></map>

Public Member Functions

 	DistanceGP2Y0A21YK ()

 	Constructor.

int 	getDistanceCentimeter ()

 	getDistanceCentimeter(): Returns the distance in centimeters

 Public Member Functions inherited from AnalogDistanceSensor

 	AnalogDistanceSensor ()

 	Constructor.

void 	begin ()

 	Begin function to set input pins: distancePin = A0.

void 	begin (int distancePin)

int 	getDistanceRaw ()

 	getDistanceRaw(): Returns the distance as a raw value: ADC output: 0 -> 1023

int 	getDistanceVolt ()

 	getDistanceVolt(): Returns the distance as a Voltage: ADC Input: 0V -> 5V (or 0V -> 3.3V)

void 	setARefVoltage (int _refV)

 	setARefVoltage:set the ADC reference voltage: (default value: 5V, set to 3 for external reference value, typically 3.3 on Arduino boards)

 Public Member Functions inherited from DistanceSensor

boolean 	isCloser (int threshold)

 	isCloser: check whether the distance to the detected object is smaller than a given threshold

boolean 	isFarther (int threshold)

 	isFarther: check whether the distance to the detected object is bigger than a given threshold

void 	setAveraging (int avg)

 	setAveraging(int avg): Sets how many samples have to be averaged in getDistanceCentimeter, default value is 1.

Additional Inherited Members

 Protected Attributes inherited from AnalogDistanceSensor

int 	_refVoltage

DistanceGP2Y0A21YK

Generated on Tue Dec 25 2012 03:39:34 for ArduinoDistanceSensorLibrary by

     1.8.1.2


text:
<?php

declare(strict_types=1);

namespace Phpml\Tests\Classification\DecisionTree;

use Phpml\Classification\DecisionTree\DecisionTreeLeaf;
use PHPUnit\Framework\TestCase;

class DecisionTreeLeafTest extends TestCase
{
    public function testHTMLOutput(): void
    {
        $leaf = new DecisionTreeLeaf();
        $leaf->value = 1;
        $leaf->columnIndex = 0;

        $rightLeaf = new DecisionTreeLeaf();
        $rightLeaf->value = '<= 2';
        $rightLeaf->columnIndex = 1;

        $leaf->rightLeaf = $rightLeaf;

        self::assertEquals(
            '

col_0 =1
Gini: 0.00

	 	No |

col_1 <= 2
Gini: 0.00

',
            $leaf->getHTML()
        );
    }

    public function testNodeImpurityDecreaseShouldBeZeroWhenLeafIsTerminal(): void
    {
        $leaf = new DecisionTreeLeaf();
        $leaf->isTerminal = true;

        self::assertEquals(0.0, $leaf->getNodeImpurityDecrease(1));
    }

    public function testNodeImpurityDecrease(): void
    {
        $leaf = new DecisionTreeLeaf();
        $leaf->giniIndex = 0.5;
        $leaf->records = [1, 2, 3];

        $leaf->leftLeaf = new DecisionTreeLeaf();
        $leaf->leftLeaf->records = [5, 2];

        $leaf->rightLeaf = new DecisionTreeLeaf();
        $leaf->rightLeaf->records = [];
        $leaf->rightLeaf->giniIndex = 0.3;

        self::assertSame(0.75, $leaf->getNodeImpurityDecrease(2));
    }
}


text:
package auth

import "github.com/google/wire"

// ProvideWebAuth is a wire set containing code necessary to manage auth sessions
var ProvideWebAuth = wire.NewSet()


text:
package org.hihan.girinoscope.comm;

import com.fazecast.jSerialComm.SerialPort;
import java.io.IOException;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Girino {

    private static final Logger LOGGER = Logger.getLogger(Girino.class.getName());

    public enum Parameter {

        BUFFER_SIZE(null),
        BAUD_RATE(null),
        PRESCALER("p"),
        VOLTAGE_REFERENCE("r"),
        TRIGGER_EVENT("e"),
        EXT_TRIGGER_EVENT("e"),
        WAIT_DURATION("w"),
        THRESHOLD("t"),
        CHANNEL_COMPOSITION("c");

        private final String command;

        Parameter(String command) {
            this.command = command;
        }

        public String getIdentifier() {
            if (this == WAIT_DURATION) {
                return "waitDuration";
            } else if (this == EXT_TRIGGER_EVENT) {
                return TRIGGER_EVENT.getIdentifier();
            } else if (this == CHANNEL_COMPOSITION) {
                return "channels";
            } else {
                return name().toLowerCase().replace('_', ' ');
            }
        }

        public String getDescription() {
            return name().charAt(0) + name().substring(1).toLowerCase().replace('_', ' ');
        }

        public static Parameter findByDescription(String description) {
            for (Parameter parameter : values()) {
                if (parameter.getDescription().equals(description)) {
                    return parameter;
                }
            }
            return null;
        }

        private static Map.Entry<Parameter, Integer> read(Serial serial, Device device) throws IOException, InterruptedException {
            String data = serial.readLine();
            if (device.getReadyMessage().equals(data)) {
                data = serial.readLine();
            }
            String[] items = data.split(":");
            String name = items[0].trim();
            int value = Integer.parseInt(items[1].trim());
            Parameter parameter = Parameter.findByDescription(name);
            return new AbstractMap.SimpleEntry<>(parameter, value);
        }

        private int apply(Serial serial, int newValue) throws IOException, InterruptedException {
            if (command != null) {
                serial.writeLine(command + newValue);
                String data = serial.readLine();
                String[] items = data.split(":");
                if (items.length > 1) {
                    String message = items[0].trim();
                    String identifier = getIdentifier();
                    if (message.equals(String.format("Setting %s to", identifier))) {
                        return Integer.parseInt(items[1].trim());
                    } else {
                        throw new IOException("Not matching returned parameter " + identifier);
                    }
                } else {
                    throw new IOException("Unknown parameter " + getDescription());
                }
            } else {
                throw new IllegalArgumentException("Read only parameter " + getDescription());
            }
        }
    }

    public static class PrescalerInfo {

        public final int value;
        public final double frequency;
        public final double timeframe;
        public final boolean tooFast;
        public final boolean reallyTooFast;

        public PrescalerInfo(
                int value,
                double frequency,
                double timeframe,
                boolean tooFast,
                boolean reallyTooFast) {
            this.value = value;
            this.frequency = frequency;
            this.timeframe = timeframe;
            this.tooFast = tooFast;
            this.reallyTooFast = reallyTooFast;
        }
    }

    public enum TriggerEventMode {

        TOGGLE(0, "Toggle"), //
        FALLING_EDGE(2, "Falling edge"), //
        RISING_EDGE(3, "Rising edge");

        public int value;
        public String description;

        TriggerEventMode(int value, String description) {
            this.value = value;
            this.description = description;
        }
    }

    public enum ExtTriggerEventMode {

        TOGGLE(0, "Toggle"), //
        FALLING_EDGE(2, "Falling edge"), //
        RISING_EDGE(3, "Rising edge"), //
        AUTO(4, "Automatic");

        public int value;
        public String description;

        ExtTriggerEventMode(int value, String description) {
            this.value = value;
            this.description = description;
        }
    }

    public enum ChannelCompositionMode {

        SINGLE(1, "Single"), //
        DUAL(2, "Dual"), //
        XY(3, "X-Y");

        public int value;
        public String description;

        ChannelCompositionMode(int value, String description) {
            this.value = value;
            this.description = description;
        }
    }

    public enum VoltageReference {

        AREF(0, "AREF, Internal Vref turned off"), //
        AVCC(1, "AVCC with external capacitor at AREF pin"), //
        /*
         * The value is misleading since it sets [REFS1, REFS0] to 11 (10 is
         * reserved). At least, the trigger event mode always uses the [ACI1,
         * ACI0] value (hence the gap since 2 is also a reserved value).
         */
        INTERNAL(2, "Internal 1.1V Vref with external capacitor at AREF pin");

        public int value;
        public String description;

        VoltageReference(int value, String description) {
            this.value = value;
            this.description = description;
        }
    }

    private static final String START_ACQUIRING_COMMAND = "s";

    private static final String STOP_ACQUIRING_COMMAND = "S";

    private static final String DUMP_COMMAND = "d";

    private Serial serial;

    private SerialPort port;

    private Device device = Device.createClassic();

    private final Map<Parameter, Integer> parameters = new HashMap<>();

    private void connect(SerialPort newPort) throws IOException, InterruptedException {
        if (newPort != null) {
            if (serial == null || !Objects.equals(port, newPort)) {
                port = newPort;
                if (serial != null) {
                    disconnect();
                }

                serial = new Serial(port);
                try {
                    /*
                     * The serial port is expected to reset the AVR each time a
                     * connection is etablished. The delay here is to give some
                     * time to the controller to set itself up. Since the Girino
                     * protocol only outputs its signature at startup, a lack of
                     * response could be an inappropriate serial adapter without
                     * the DTR/RTS wire (ie. it has only 4 wires) used to force
                     * a reset. It won't be the case with an Arduino, but if you
                     * have built your device from scratch, it could.
                     */
                    Thread.sleep(device.getSetupDelayOnReset());

                    String data;
                    do {
                        data = serial.readLine();
                    } while (data.isEmpty());
                    if (!data.endsWith(device.getReadyMessage())) {
                        throw new IOException("Expected a '" + device.getReadyMessage() + "' device but found a '" + data + "'");
                    }
                } catch (InterruptedException e) {
                    /*
                     * The underlying serial port library introduces a delay to
                     * avoid a rapid closing/opening on the part of the user.
                     * Interrupting it too fast will defeat this approach...
                     */
                    disconnect();
                }

                readParameters();
            }
        } else {
            throw new IllegalArgumentException("No serial port (see README.md file)");
        }
    }

    public void connect(Device device, SerialPort newPort, Map<Parameter, Integer> newParameters)
            throws Exception {
        this.device = Objects.requireNonNull(device);
        connect(newPort);
        if (serial != null) {
            applyParameters(newParameters);
        }
    }

    public void disconnect() throws IOException {
        if (serial != null) {
            serial.close();
            serial = null;
        }
    }

    private void readParameters() throws IOException, InterruptedException {
        if (serial != null) {
            serial.writeLine(DUMP_COMMAND);
            for (Parameter parameter : Parameter.values()) {
                if (device.isReadable(parameter)) {
                    Map.Entry<Parameter, Integer> entry = Parameter.read(serial, device);
                    if (entry.getKey() != null) {
                        parameters.put(entry.getKey(), entry.getValue());
                    }
                }
            }
        } else {
            throw new IllegalStateException("No serial connection");
        }
    }

    /**
     * @throws IOException Provided parameters shall be verified by the caller
     * since some parameters could have been set back to a different value than
     * asked.
     */
    private void applyParameters(Map<Parameter, Integer> newParameters) throws IOException, InterruptedException {
        if (serial != null) {
            for (Map.Entry<Parameter, Integer> entry : newParameters.entrySet()) {
                Parameter parameter = entry.getKey();
                Integer newValue = entry.getValue();

                // We only update modified parameters.
                if (!Objects.equals(newValue, parameters.get(parameter))) {
                    if (device.isWritable(parameter)) {
                        int returnedValue = parameter.apply(serial, newValue);
                        parameters.put(parameter, returnedValue);
                        if (!Objects.equals(newValue, parameters.get(parameter))) {
                            throw new IOException("Change has been rejected for parameter "
                                    + parameter.getDescription() + ": " + newValue + " =/= " + returnedValue);
                        }
                    }
                }
            }
        } else {
            throw new IllegalStateException("No serial connection");
        }
    }

    public byte[] acquireData() throws Exception {
        if (serial != null) {
            /*
             * When acquiring data in loop, give some time to the device between
             * a STOP and a START. This is the only place where two commands are
             * emitted in a row.
             */
            Thread.sleep(device.getChainedCommandDelay());
            serial.writeLine(START_ACQUIRING_COMMAND);
            /*
             * Note that the Girino reset its buffer (with zeros), meaning we won't
             * catch a lot of the signal before the trigger if it happens too fast.
             */
            try {
                FrameFormat frameFormat = device.getFrameFormat();
                byte[] buffer = new byte[frameFormat.sampleCount * frameFormat.sampleSizeInBit];
                int size = serial.readBytes(buffer);
                return size == buffer.length ? buffer : null;
            } finally {
                /*
                 * We can only acquire a single buffer and need to stop / start to
                 * get the next one. That's how the Girino code works, but it was
                 * probably a bit different during its development. In practise,
                 * this 'stop' is only required when we cancel a trigger waiting.
                 */
                serial.writeLine(STOP_ACQUIRING_COMMAND);
            }
        } else {
            throw new IllegalStateException("No serial connection");
        }
    }
}


text:
<?PHP

//require header.php;

ini_set('display_errors', '1');
//require 'HTML/BBCodeParser2.php';

/**
 *
 *  Get content from mysql database and create html results
 *
**/
$mysqli = new mysqli("localhost", "root", "", "TileInfoPage");
require './config.php';
$query = "SELECT * FROM index_pics WHERE sequence_no<7;";
$tile_result = $mysqli->query($query);
while ($line = $tile_result->fetch_array(MYSQLI_ASSOC)) {
    if ($line['name'] != ""){
        $content[$line['sequence_no']]  = "
\n";
        $content[$line['sequence_no']] .= "".$line['name']."
\n";
        $content[$line['sequence_no']] .= "
\n";
        $content[$line['sequence_no']] .= "".$line['description']."\n";
        $content[$line['sequence_no']] .= "
\n";
    }else{
        $content[$line['sequence_no']] = " ";
    }
    $images[$line['sequence_no']]['data'] = $line['image'];
    $images[$line['sequence_no']]['type'] = $line['image_type'];
    $images[$line['sequence_no']]['link'] = $line['link'];
    $images[$line['sequence_no']]['name'] = $line['name'];
    $images[$line['sequence_no']]['description'] = $line['description'];
}
$Impressum=$config_impressum;

/**
*
*   Use HTML_BBCodeParser2 here
*
**/
/* get options from the ini file */
//$config = parse_ini_file('BBCodeParser2.ini', true);
//$options = $config['HTML_BBCodeParser2'];
/* do yer stuff! */
//$parser = new HTML_BBCodeParser2($options);
//$parser->setText($Impressum);
//$parser->parse();
//$parsed = $parser->getParsed();
//$Impressum=$parsed;
?>
<!doctype html>

    <meta charset="utf-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?PHP echo $configArr_PageTitle['content'];?></title>
    <link rel="stylesheet" href="assets/css/app.css">

    <link rel="stylesheet" href="minified/themes/default.min.css" type="text/css" media="all" charset="UTF-8" />

      <form name="search" method="GET" action="Search.php">

                <img src="data:<?PHP echo $images[0]['type']?>;base64,<?PHP echo base64_encode($images[0]['data']) ?>"/>

                        <input type="text" name="search" class="prefix round" placeholder="Suchbegriff">

                        <input type="submit" class="radius button postfix" value="suchen">

                    </form>

Startseite

                <?PHP echo $Impressum;?>

			 Created by TLoebner licensed by   Apache License Version 2.0, January 2004

            Impressum

            Images by www.flaticon.com/ - Grafik-Lizenzen : CC BY 3.0

            Administration


text:
package org.innovateuk.ifs.testdata.builders;

import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.file.domain.FileEntry;
import org.innovateuk.ifs.finance.domain.ApplicationFinance;
import org.innovateuk.ifs.finance.resource.ApplicationFinanceResource;
import org.innovateuk.ifs.finance.resource.category.OtherFundingCostCategory;
import org.innovateuk.ifs.finance.resource.cost.*;
import org.innovateuk.ifs.organisation.resource.OrganisationResource;
import org.innovateuk.ifs.testdata.builders.data.AcademicCostData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

import static java.util.Collections.emptyList;
import static org.innovateuk.ifs.util.CollectionFunctions.simpleFilter;

/**
 * Generates Academic Finances for an Organisation on an Application
 */
public class AcademicCostDataBuilder extends BaseDataBuilder<AcademicCostData, AcademicCostDataBuilder> {

    private static final Logger LOG = LoggerFactory.getLogger(ApplicationDataBuilder.class);

    public AcademicCostDataBuilder withApplicationFinance(ApplicationFinanceResource applicationFinance) {
        return with(data -> data.setApplicationFinance(applicationFinance));
    }

    public AcademicCostDataBuilder withCompetition(CompetitionResource competitionResource) {
        return with(data -> data.setCompetition(competitionResource));
    }

    public AcademicCostDataBuilder withTsbReference(String value) {
        return addCostItem("Provide the project costs for '{organisationName}'", (finance) -> new AcademicCost(null, "tsb_reference", null, value, FinanceRowType.YOUR_FINANCE, finance.getId()));
    }

    public AcademicCostDataBuilder withDirectlyIncurredStaff(BigDecimal value) {
        return addCostItem("Labour", (finance) -> new AcademicCost(null, "incurred_staff", value, null, FinanceRowType.LABOUR, finance.getId()));
    }

    public AcademicCostDataBuilder withDirectlyIncurredTravelAndSubsistence(BigDecimal value) {
        return addCostItem("Travel and subsistence", (finance) -> new AcademicCost(null, "incurred_travel_subsistence", value, null, FinanceRowType.TRAVEL, finance.getId()));
    }

    public AcademicCostDataBuilder withDirectlyIncurredOtherCosts(BigDecimal value) {
        return addCostItem("Materials", (finance) -> new AcademicCost(null, "incurred_other_costs", value, null, FinanceRowType.MATERIALS, finance.getId()));
    }

    public AcademicCostDataBuilder withDirectlyAllocatedInvestigators(BigDecimal value) {
        return addCostItem("Labour", (finance) -> new AcademicCost(null, "allocated_investigators", value, null, FinanceRowType.LABOUR, finance.getId()));
    }

    public AcademicCostDataBuilder withDirectlyAllocatedEstateCosts(BigDecimal value) {
        return addCostItem("Other costs", (finance) -> new AcademicCost(null, "allocated_estates_costs", value, null, FinanceRowType.OTHER_COSTS, finance.getId()));
    }

    public AcademicCostDataBuilder withDirectlyAllocatedOtherCosts(BigDecimal value) {
        return addCostItem("Other costs", (finance) -> new AcademicCost(null, "allocated_other_costs", value, null, FinanceRowType.OTHER_COSTS, finance.getId()));
    }

    public AcademicCostDataBuilder withIndirectCosts(BigDecimal value) {
        return addCostItem("Overheads", (finance) -> new AcademicCost(null, "indirect_costs", value, null, FinanceRowType.OVERHEADS, finance.getId()));
    }

    public AcademicCostDataBuilder withExceptionsStaff(BigDecimal value) {
        return addCostItem("Labour", (finance) -> new AcademicCost(null, "exceptions_staff", value, null, FinanceRowType.LABOUR, finance.getId()));
    }

    public AcademicCostDataBuilder withExceptionsOtherCosts(BigDecimal value) {
        return addCostItem("Other costs", (finance) -> new AcademicCost(null, "exceptions_other_costs", value, null, FinanceRowType.OTHER_COSTS, finance.getId()));
    }

    public AcademicCostDataBuilder withOtherFunding(String fundingSource, LocalDate dateSecured, BigDecimal fundingAmount) {
        return updateCostItem(OtherFunding.class, FinanceRowType.OTHER_FUNDING, row -> OtherFundingCostCategory.OTHER_FUNDING.equals(row.getFundingSource()), existingCost -> {
            existingCost.setOtherPublicFunding("Yes");
            financeRowCostsService.update(existingCost.getId(), existingCost);
        }).addCostItem("Other funding", (finance) -> {
            OtherFunding otherFunding = new OtherFunding(finance.getId());
            otherFunding.setFundingAmount(fundingAmount);
            otherFunding.setFundingSource(fundingSource);
            otherFunding.setSecuredDate(dateSecured.format(DateTimeFormatter.ofPattern("MM-yyyy")));
            return otherFunding;
        });
    }

    public AcademicCostDataBuilder withGrantClaim(BigDecimal grantClaim) {
        return updateCostItem(GrantClaimPercentage.class, FinanceRowType.FINANCE, existingCost -> {
            existingCost.setPercentage(grantClaim);
            financeRowCostsService.update(existingCost.getId(), existingCost);
        });
    }

    public AcademicCostDataBuilder withUploadedJesForm() {
        return with(data -> {
            FileEntry fileEntry = fileEntryRepository.save(
                    new FileEntry(null, "jes-form.pdf", "application/pdf", 7945));

            ApplicationFinance finance = applicationFinanceRepository.findById(data.getApplicationFinance().getId()).get();
            finance.setFinanceFileEntry(fileEntry);
            applicationFinanceRepository.save(finance);
        });
    }

    public AcademicCostDataBuilder withLocation() {
        return with(data -> {

            ApplicationFinanceResource applicationFinance =
                    financeService.getApplicationFinanceById(data.getApplicationFinance().getId()).
                            getSuccess();
            OrganisationResource org = organisationService.findById(applicationFinance.getOrganisation()).getSuccess();

            if (org.isInternational()) {
                applicationFinance.setInternationalLocation("France");
            } else {
                applicationFinance.setWorkPostcode("AB12 3CD");
            }

            financeService.updateApplicationFinance(applicationFinance.getId(), applicationFinance);
        });
    }

    private AcademicCostDataBuilder addCostItem(String financeRowName, Function<ApplicationFinanceResource, FinanceRowItem> cost) {
        return with(data -> {

            FinanceRowItem newCostItem = cost.apply(data.getApplicationFinance());

            financeRowCostsService.create(newCostItem.getTargetId(), newCostItem).
                    getSuccess();
        });
    }

    private <T extends FinanceRowItem> AcademicCostDataBuilder updateCostItem(Class<T> clazz, FinanceRowType financeRowType, Consumer<T> updateFn) {
        return updateCostItem(clazz, financeRowType, c -> true, updateFn);
    }

    private <T extends FinanceRowItem> AcademicCostDataBuilder updateCostItem(Class<T> clazz, FinanceRowType financeRowType, Predicate<T> filterFn, Consumer<T> updateFn) {
        return with(data -> {
            List<FinanceRowItem> existingItems = getCostItems(data.getApplicationFinance().getId(), financeRowType);
            simpleFilter(existingItems, item -> filterFn.test((T) item)).forEach(item -> updateFn.accept((T) item));
        });
    }

    public static AcademicCostDataBuilder newAcademicCostData(ServiceLocator serviceLocator) {
        return new AcademicCostDataBuilder(emptyList(), serviceLocator);
    }

    private AcademicCostDataBuilder(List<BiConsumer<Integer, AcademicCostData>> multiActions,
                                    ServiceLocator serviceLocator) {

        super(multiActions, serviceLocator);
    }

    @Override
    protected AcademicCostDataBuilder createNewBuilderWithActions(List<BiConsumer<Integer, AcademicCostData>> actions) {
        return new AcademicCostDataBuilder(actions, serviceLocator);
    }

    @Override
    protected AcademicCostData createInitial() {
        return new AcademicCostData();
    }

    @Override
    protected void postProcess(int index, AcademicCostData instance) {
        super.postProcess(index, instance);
        OrganisationResource organisation = organisationService.findById(instance.getApplicationFinance().getOrganisation()).getSuccess();
        ApplicationResource application = applicationService.getApplicationById(instance.getApplicationFinance().getApplication()).getSuccess();
        LOG.info("Created Academic Costs for Application '{}', Organisation '{}'", application.getName(), organisation.getName());
    }
}