text:
/*
Smile Incorporated (additional IE styles)
Ian Yates
December 2011
Tuts+ Premium
*/

.social .skype a {
	background: url(../img/sprite.png) -450px -50px no-repeat transparent;
	}

.social .twitter a {
	background: url(../img/sprite.png) -500px -50px no-repeat transparent;
	}

.social .facebook a {
	background: url(../img/sprite.png) -550px -50px no-repeat transparent;
	}

.social .skype a:hover {
	background: url(../img/sprite.png) -450px -100px no-repeat transparent;
	}

.social .twitter a:hover {
	background: url(../img/sprite.png) -500px -100px no-repeat transparent;
	}

.social .facebook a:hover {
	background: url(../img/sprite.png) -550px -100px no-repeat transparent;
	}

/*button*/
.contact-form button {
	width: 52px;
	height: 52px;
	line-height: 52px;
	background: url(../img/sprite.png) -373px -23px no-repeat transparent;
	}

.contact-form button:hover {
	background: url(../img/sprite.png) -373px -123px no-repeat transparent;
	}

/*get rid of white testimonial bg*/
.testimonial .slide {
	background: url("../img/subtle_freckles.png") repeat;
	}

/*fix broken clearing floats*/
section,
footer {
	float: left;
	width: 100%;
	}


text:
![Office 365 Developer Patterns and Practices](https://camo.githubusercontent.com/a732087ed949b0f2f84f5f02b8c79f1a9dd96f65/687474703a2f2f692e696d6775722e636f6d2f6c3031686876452e706e67)

Please use [http://aka.ms/OfficeDevPnP](http://aka.ms/OfficeDevPnP) for getting latest information around the whole *Office 365 Developer Patterns and Practices program*.

This sample is a set of interactive demos for using the [Patterns and Practices JavaScript Core Library](https://github.com/OfficeDev/PnP-JS-Core/). They are implemented as a SharePoint hosted Add-In so you can try them out in your site easily and see live results. Additional documentation and instructions are included when you launch the add-in.

## Getting Started ##

1. Pull down the sample project, which is a SharePoint hosted add-in
2. Update the deployment URL to a development tenant
3. Hit F5 to run the sample

## Resources ##

### Contributing ###

We always welcome new samples! If you have an idea for a good scenario please create it and submit a pull request. You can use the existing samples as a template for adding your own.

### Yammer Group ###
We have an active [Yammer Group](http://aka.ms/OfficeDevPnPSIGJavaScriptYammer) dedicated to the library upon which these samples are built, please join the conversation.

#### Disclaimer ####
**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**

###"Sharing is Caring"###

redpajama_set_name: RedPajamaGithub


text:
package com.huawei.streaming.cql.semanticanalyzer.parser.visitor;

import org.antlr.v4.runtime.misc.NotNull;

import com.huawei.streaming.cql.semanticanalyzer.parser.CQLParser;
import com.huawei.streaming.cql.semanticanalyzer.parser.context.ExpressionPreviousContext;

/**
 * previous表达式遍历
 *
 */
public class ExpressionPreviousVisitor extends AbsCQLParserBaseVisitor<ExpressionPreviousContext>
{
    private ExpressionPreviousContext context = null;

    /**
     * <默认构造函数>
     */
    public ExpressionPreviousVisitor()
    {
        context = new ExpressionPreviousContext();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected ExpressionPreviousContext defaultResult()
    {
        return context;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ExpressionPreviousContext visitExpression(@NotNull CQLParser.ExpressionContext ctx)
    {
        ExpressionVisitor visitor = new ExpressionVisitor();
        context.getExpressions().add(visitor.visit(ctx));
        return context;
    }

}


text:
package rust

import (
	"fmt"

	"github.com/pelletier/go-toml"

	"github.com/anchore/syft/syft/artifact"
	"github.com/anchore/syft/syft/pkg"
	"github.com/anchore/syft/syft/pkg/cataloger/generic"
	"github.com/anchore/syft/syft/source"
)

var _ generic.Parser = parseCargoLock

type cargoLockFile struct {
	Packages []pkg.CargoPackageMetadata `toml:"package"`
}

// parseCargoLock is a parser function for Cargo.lock contents, returning all rust cargo crates discovered.
func parseCargoLock(_ source.FileResolver, _ *generic.Environment, reader source.LocationReadCloser) ([]pkg.Package, []artifact.Relationship, error) {
	tree, err := toml.LoadReader(reader)
	if err != nil {
		return nil, nil, fmt.Errorf("unable to load Cargo.lock for parsing: %w", err)
	}

	m := cargoLockFile{}
	err = tree.Unmarshal(&m)
	if err != nil {
		return nil, nil, fmt.Errorf("unable to parse Cargo.lock: %w", err)
	}

	var pkgs []pkg.Package

	for _, p := range m.Packages {
		if p.Dependencies == nil {
			p.Dependencies = make([]string, 0)
		}
		pkgs = append(pkgs, newPackageFromCargoMetadata(p, reader.Location))
	}

	return pkgs, nil, nil
}


text:
// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.

package libcmdline

import (
	"fmt"
	"io"
	"strings"
	"time"

	"github.com/keybase/cli"
	"github.com/keybase/client/go/libkb"
)

type Command interface {
	libkb.Command
	ParseArgv(*cli.Context) error // A command-specific parse-args
	Run() error                   // Run in client mode
}

type ForkCmd int
type LogForward int

const (
	NormalFork ForkCmd = iota
	NoFork
	ForceFork
)

const (
	LogForwardNormal LogForward = iota
	LogForwardNone
)

type CommandLine struct {
	app                   *cli.App
	ctx                   *cli.Context
	cmd                   Command
	name                  string     // the name of the chosen command
	service               bool       // The server is a special command
	fork                  ForkCmd    // If the command is to stop (then don't start the server)
	noStandalone          bool       // On if this command can't run in standalone mode
	logForward            LogForward // What do to about log forwarding
	skipOutOfDateCheck    bool       // don't try to check for service being out of date
	skipAccountResetCheck bool       // don't check if our account is scheduled for rest
	defaultCmd            string
}

func (p CommandLine) IsService() bool             { return p.service }
func (p CommandLine) SkipOutOfDateCheck() bool    { return p.skipOutOfDateCheck }
func (p CommandLine) SkipAccountResetCheck() bool { return p.skipAccountResetCheck }
func (p *CommandLine) SetService()                { p.service = true }
func (p CommandLine) GetForkCmd() ForkCmd         { return p.fork }
func (p *CommandLine) SetForkCmd(v ForkCmd)       { p.fork = v }
func (p *CommandLine) SetNoStandalone()           { p.noStandalone = true }
func (p CommandLine) IsNoStandalone() bool        { return p.noStandalone }
func (p *CommandLine) SetLogForward(f LogForward) { p.logForward = f }
func (p *CommandLine) GetLogForward() LogForward  { return p.logForward }
func (p *CommandLine) SetSkipOutOfDateCheck()     { p.skipOutOfDateCheck = true }
func (p *CommandLine) SetSkipAccountResetCheck()  { p.skipAccountResetCheck = true }

func (p CommandLine) GetNoAutoFork() (bool, bool) {
	return p.GetBool("no-auto-fork", true)
}
func (p CommandLine) GetAutoFork() (bool, bool) {
	return p.GetBool("auto-fork", true)
}
func (p CommandLine) GetHome() string {
	return p.GetGString("home")
}
func (p CommandLine) GetMobileSharedHome() string {
	return p.GetGString("mobile-shared-home")
}
func (p CommandLine) GetServerURI() (string, error) {
	return p.GetGString("server"), nil
}
func (p CommandLine) GetConfigFilename() string {
	return p.GetGString("config-file")
}
func (p CommandLine) GetGUIConfigFilename() string {
	return p.GetGString("gui-config-file")
}
func (p CommandLine) GetUpdaterConfigFilename() string {
	return p.GetGString("updater-config-file")
}
func (p CommandLine) GetDeviceCloneStateFilename() string {
	return p.GetGString("device-clone-state-file")
}
func (p CommandLine) GetSessionFilename() string {
	return p.GetGString("session-file")
}
func (p CommandLine) GetDbFilename() string {
	return p.GetGString("db")
}
func (p CommandLine) GetChatDbFilename() string {
	return p.GetGString("chat-db")
}
func (p CommandLine) GetPvlKitFilename() string {
	return p.GetGString("pvl-kit")
}
func (p CommandLine) GetParamProofKitFilename() string {
	return p.GetGString("paramproof-kit")
}
func (p CommandLine) GetExternalURLKitFilename() string {
	return p.GetGString("externalurl-kit")
}
func (p CommandLine) GetProveBypass() (bool, bool) {
	return p.GetBool("prove-bypass", true)
}
func (p CommandLine) GetDebug() (bool, bool) {
	// --no-debug suppresses --debug. Note that although we don't define a
	// separate GetNoDebug() accessor, fork_server.go still looks for
	// --no-debug by name, to pass it along to an autoforked daemon.
	if noDebug, _ := p.GetBool("no-debug", true); noDebug {
		return false /* val */, true /* isSet */
	}
	return p.GetBool("debug", true)
}
func (p CommandLine) GetDebugJourneycard() (bool, bool) {
	return p.GetBool("debug-journeycard", true)
}
func (p CommandLine) GetDisplayRawUntrustedOutput() (bool, bool) {
	return p.GetBool("display-raw-untrusted-output", true)
}
func (p CommandLine) GetVDebugSetting() string {
	return p.GetGString("vdebug")
}
func (p CommandLine) GetPGPFingerprint() *libkb.PGPFingerprint {
	return libkb.PGPFingerprintFromHexNoError(p.GetGString("fingerprint"))
}
func (p CommandLine) GetProxy() string {
	return p.GetGString("proxy")
}
func (p CommandLine) GetLogFile() string {
	return p.GetGString("log-file")
}
func (p CommandLine) GetEKLogFile() string {
	return p.GetGString("ek-log-file")
}
func (p CommandLine) GetPerfLogFile() string {
	return p.GetGString("perf-log-file")
}
func (p CommandLine) GetGUILogFile() string {
	return p.GetGString("gui-log-file")
}
func (p CommandLine) GetUseDefaultLogFile() (bool, bool) {
	return p.GetBool("use-default-log-file", true)
}
func (p CommandLine) GetUseRootConfigFile() (bool, bool) {
	return p.GetBool("use-root-config-file", true)
}
func (p CommandLine) GetLogPrefix() string {
	return p.GetGString("log-prefix")
}

func (p CommandLine) GetLogFormat() string {
	return p.GetGString("log-format")
}
func (p CommandLine) GetGpgHome() string {
	return p.GetGString("gpg-home")
}
func (p CommandLine) GetAPIDump() (bool, bool) {
	return p.GetBool("api-dump-unsafe", true)
}
func (p CommandLine) GetGregorSaveInterval() (time.Duration, bool) {
	ret, err := p.GetGDuration("push-save-interval")
	if err != nil {
		return 0, false
	}
	return ret, true
}
func (p CommandLine) GetGregorDisabled() (bool, bool) {
	return p.GetBool("push-disabled", true)
}
func (p CommandLine) GetSecretStorePrimingDisabled() (bool, bool) {
	// SecretStorePrimingDisabled is only for tests
	return false, false
}
func (p CommandLine) GetBGIdentifierDisabled() (bool, bool) {
	return p.GetBool("bg-identifier-disabled", true)
}

func (p CommandLine) GetGregorURI() string {
	return p.GetGString("push-server-uri")
}
func (p CommandLine) GetGregorPingInterval() (time.Duration, bool) {
	ret, err := p.GetGDuration("push-ping-interval")
	if err != nil {
		return 0, false
	}
	return ret, true
}
func (p CommandLine) GetGregorPingTimeout() (time.Duration, bool) {
	ret, err := p.GetGDuration("push-ping-timeout")
	if err != nil {
		return 0, false
	}
	return ret, true
}

func (p CommandLine) GetChatDelivererInterval() (time.Duration, bool) {
	ret, err := p.GetGDuration("chat-deliverer-interval")
	if err != nil {
		return 0, false
	}
	return ret, true
}

func (p CommandLine) GetRunMode() (libkb.RunMode, error) {
	return libkb.StringToRunMode(p.GetGString("run-mode"))
}
func (p CommandLine) GetFeatureFlags() (libkb.FeatureFlags, error) {
	return libkb.StringToFeatureFlags(p.GetGString("features")), nil
}
func (p CommandLine) GetPinentry() string {
	return p.GetGString("pinentry")
}
func (p CommandLine) GetAppType() libkb.AppType {
	return libkb.DesktopAppType
}
func (p CommandLine) IsMobileExtension() (bool, bool) {
	return false, false
}
func (p CommandLine) GetSlowGregorConn() (bool, bool) {
	return p.GetBool("slow-gregor-conn", true)
}
func (p CommandLine) GetReadDeletedSigChain() (bool, bool) {
	return p.GetBool("read-deleted-sigchain", true)
}
func (p CommandLine) GetGString(s string) string {
	return p.ctx.GlobalString(s)
}
func (p CommandLine) GetString(s string) string {
	return p.ctx.String(s)
}
func (p CommandLine) GetGInt(s string) int {
	return p.ctx.GlobalInt(s)
}
func (p CommandLine) GetGDuration(s string) (time.Duration, error) {
	return time.ParseDuration(p.GetGString(s))
}
func (p CommandLine) GetGpg() string {
	return p.GetGString("gpg")
}
func (p CommandLine) GetSecretKeyringTemplate() string {
	return p.GetGString("secret-keyring")
}
func (p CommandLine) GetSocketFile() string {
	return p.GetGString("socket-file")
}
func (p CommandLine) GetPidFile() string {
	return p.GetGString("pid-file")
}
func (p CommandLine) GetScraperTimeout() (time.Duration, bool) {
	ret, err := p.GetGDuration("scraper-timeout")
	if err != nil {
		return 0, false
	}
	return ret, true
}
func (p CommandLine) GetAPITimeout() (time.Duration, bool) {
	ret, err := p.GetGDuration("api-timeout")
	if err != nil {
		return 0, false
	}
	return ret, true
}
func (p CommandLine) GetGpgOptions() []string {
	var ret []string
	s := p.GetGString("gpg-options")
	if len(s) > 0 {
		ret = strings.Fields(s)
	}
	return ret
}

func (p CommandLine) getKIDs(name string) []string {
	s := p.GetGString(name)
	if len(s) == 0 {
		return nil
	}
	return strings.Split(s, ":")
}

func (p CommandLine) GetMerkleKIDs() []string {
	return p.getKIDs("merkle-kids")
}

func (p CommandLine) GetCodeSigningKIDs() []string {
	return p.getKIDs("code-signing-kids")
}

func (p CommandLine) GetUserCacheMaxAge() (time.Duration, bool) {
	ret, err := p.GetGDuration("user-cache-maxage")
	if err != nil {
		return 0, false
	}
	return ret, true
}

func (p CommandLine) GetProofCacheSize() (int, bool) {
	ret := p.GetGInt("proof-cache-size")
	if ret != 0 {
		return ret, true
	}
	return 0, false
}

func (p CommandLine) GetLevelDBNumFiles() (int, bool) {
	ret := p.GetGInt("leveldb-num-files")
	if ret != 0 {
		return ret, true
	}
	return 0, false
}

func (p CommandLine) GetLevelDBWriteBufferMB() (int, bool) {
	ret := p.GetGInt("leveldb-write-buffer-mb")
	if ret != 0 {
		return ret, true
	}
	return 0, false
}

func (p CommandLine) GetChatInboxSourceLocalizeThreads() (int, bool) {
	ret := p.GetGInt("chat-inboxsource-localizethreads")
	if ret != 0 {
		return ret, true
	}
	return 0, false
}

func (p CommandLine) GetLinkCacheSize() (int, bool) {
	ret := p.GetGInt("link-cache-size")
	if ret != 0 {
		return ret, true
	}
	return 0, false
}

func (p CommandLine) GetUPAKCacheSize() (int, bool) {
	ret := p.GetGInt("upak-cache-size")
	if ret != 0 {
		return ret, true
	}
	return 0, false
}

func (p CommandLine) GetUIDMapFullNameCacheSize() (int, bool) {
	ret := p.GetGInt("uid-map-full-name-cache-size")
	if ret != 0 {
		return ret, true
	}
	return 0, false
}

func (p CommandLine) GetPayloadCacheSize() (int, bool) {
	ret := p.GetGInt("payload-cache-size")
	if ret != 0 {
		return ret, true
	}
	return 0, false
}

func (p CommandLine) GetLocalTrackMaxAge() (time.Duration, bool) {
	ret, err := p.GetGDuration("local-track-maxage")
	if err != nil {
		return 0, false
	}
	return ret, true
}

func (p CommandLine) GetStandalone() (bool, bool) {
	return p.GetBool("standalone", true)
}

func (p CommandLine) GetLocalRPCDebug() string {
	return p.GetGString("local-rpc-debug-unsafe")
}

func (p CommandLine) GetTimers() string {
	return p.GetGString("timers")
}

func (p CommandLine) GetTorMode() (ret libkb.TorMode, err error) {
	if s := p.GetGString("tor-mode"); s != "" {
		ret, err = libkb.StringToTorMode(s)
	}
	return ret, err
}

func (p CommandLine) GetTorHiddenAddress() string {
	return p.GetGString("tor-hidden-address")
}
func (p CommandLine) GetTorProxy() string {
	return p.GetGString("tor-proxy")
}

func (p CommandLine) GetProxyType() string {
	return p.GetGString("proxy-type")
}

func (p CommandLine) IsCertPinningEnabled() bool {
	r1, _ := p.GetBool("disable-cert-pinning", true)
	// Defaults to false since it is a boolean flag, so just invert it
	return !r1
}

func (p CommandLine) GetMountDir() string {
	return p.GetGString("mountdir")
}

func (p CommandLine) GetMountDirDefault() string {
	return p.GetGString("mountdirdefault")
}

func (p CommandLine) GetRememberPassphrase(libkb.NormalizedUsername) (bool, bool) {
	return p.GetBool("remember-passphrase", true)
}

func (p CommandLine) GetAttachmentDisableMulti() (bool, bool) {
	return p.GetBool("attachment-disable-multi", true)
}

func (p CommandLine) GetDisableTeamAuditor() (bool, bool) {
	return p.GetBool("disable-team-auditor", true)
}

func (p CommandLine) GetDisableTeamBoxAuditor() (bool, bool) {
	return p.GetBool("disable-team-box-auditor", true)
}

func (p CommandLine) GetDisableEKBackgroundKeygen() (bool, bool) {
	return p.GetBool("disable-ek-backgorund-keygen", true)
}

func (p CommandLine) GetDisableMerkleAuditor() (bool, bool) {
	return p.GetBool("disable-merkle-auditor", true)
}

func (p CommandLine) GetDisableSearchIndexer() (bool, bool) {
	return p.GetBool("disable-search-indexer", true)
}

func (p CommandLine) GetDisableBgConvLoader() (bool, bool) {
	return p.GetBool("disable-bg-conv-loader", true)
}

func (p CommandLine) GetEnableBotLiteMode() (bool, bool) {
	return p.GetBool("enable-bot-lite-mode", true)
}

func (p CommandLine) GetExtraNetLogging() (bool, bool) {
	return p.GetBool("extra-net-logging", true)
}

func (p CommandLine) GetForceLinuxKeyring() (bool, bool) {
	return p.GetBool("force-linux-keyring", true)
}

func (p CommandLine) GetForceSecretStoreFile() (bool, bool) {
	return false, false // not configurable via command line flags
}

func (p CommandLine) GetRuntimeStatsEnabled() (bool, bool) {
	return false, false
}

func (p CommandLine) GetAttachmentHTTPStartPort() (int, bool) {
	ret := p.GetGInt("attachment-httpsrv-port")
	if ret != 0 {
		return ret, true
	}
	return 0, false
}

func (p CommandLine) GetBool(s string, glbl bool) (bool, bool) {
	var v bool
	if glbl {
		v = p.ctx.GlobalBool(s)
	} else {
		v = p.ctx.Bool(s)
	}
	return v, v
}

type CmdBaseHelp struct {
	ctx *cli.Context
}

func (c *CmdBaseHelp) GetUsage() libkb.Usage {
	return libkb.Usage{}
}
func (c *CmdBaseHelp) ParseArgv(*cli.Context) error { return nil }

type CmdGeneralHelp struct {
	CmdBaseHelp
}

func (c *CmdBaseHelp) RunClient() error { return c.Run() }

func (c *CmdBaseHelp) Run() error {
	cli.ShowAppHelp(c.ctx)
	return nil
}

type CmdSpecificHelp struct {
	CmdBaseHelp
	name string
}

func (c CmdSpecificHelp) Run() error {
	cli.ShowCommandHelp(c.ctx, c.name)
	return nil
}

func NewCommandLine(addHelp bool, extraFlags []cli.Flag) *CommandLine {
	app := cli.NewApp()
	ret := &CommandLine{app: app, fork: NormalFork}
	ret.PopulateApp(addHelp, extraFlags)
	return ret
}

func (p *CommandLine) PopulateApp(addHelp bool, extraFlags []cli.Flag) {
	app := p.app
	app.Name = "keybase"
	app.EnableBashCompletion = true
	app.Version = libkb.VersionString()
	app.Usage = "Keybase command line client."

	app.Flags = []cli.Flag{
		cli.BoolFlag{
			Name:  "api-dump-unsafe",
			Usage: "Dump API call internals (may leak secrets).",
		},
		cli.StringFlag{
			Name:  "api-timeout",
			Usage: "set the HTTP timeout for API calls to the keybase API server",
		},
		cli.StringFlag{
			Name:  "api-uri-path-prefix",
			Usage: "Specify an alternate API URI path prefix.",
		},
		cli.StringFlag{
			Name:  "app-start-mode",
			Usage: "Specify 'service' to auto-start UI app, or anything else to disable",
		},
		cli.BoolFlag{
			Name:  "bg-identifier-disabled",
			Usage: "supply to disable the BG identifier loop",
		},
		cli.StringFlag{
			Name:  "chat-db",
			Usage: "Specify an alternate local Chat DB location.",
		},
		cli.StringFlag{
			Name:  "code-signing-kids",
			Usage: "Set of code signing key IDs (colon-separated).",
		},
		cli.StringFlag{
			Name:  "config-file, c",
			Usage: "Specify an (alternate) master config file.",
		},
		cli.BoolFlag{
			Name:  "use-root-config-file",
			Usage: "Use the default root config on Linux only.",
		},
		cli.StringFlag{
			Name:  "db",
			Usage: "Specify an alternate local DB location.",
		},
		cli.BoolFlag{
			Name:  "debug, d",
			Usage: "Enable debugging mode.",
		},
		cli.BoolFlag{
			Name: "disable-cert-pinning",
			Usage: "Disable certificate pinning within the app. WARNING: This reduces the security of the app. Do not use " +
				"unless necessary! This should only be used if you are running keybase behind a proxy that does TLS interception.",
		},
		cli.BoolFlag{
			Name:  "display-raw-untrusted-output",
			Usage: "Display output from users (messages, chats, ...) in the terminal without escaping terminal codes. WARNING: maliciously crafted unescaped outputs can overwrite anything you see on the terminal.",
		},
		cli.StringFlag{
			Name:  "features",
			Usage: "specify experimental feature flags",
		},
		cli.StringFlag{
			Name:  "gpg",
			Usage: "Path to GPG client (optional for exporting keys).",
		},
		cli.StringFlag{
			Name:  "gpg-options",
			Usage: "Options to use when calling GPG.",
		},
		cli.StringFlag{
			Name:  "home, H",
			Usage: "Specify an (alternate) home directory.",
		},
		cli.IntFlag{
			Name:  "leveldb-num-files",
			Usage: "Specify the max number of files LevelDB may open",
		},
		cli.StringFlag{
			Name:  "local-rpc-debug-unsafe",
			Usage: "Use to debug local RPC (may leak secrets).",
		},
		cli.StringFlag{
			Name:  "log-file",
			Usage: "Specify a log file for the keybase service.",
		},
		cli.StringFlag{
			Name:  "ek-log-file",
			Usage: "Specify a log file for the keybase ephemeral key log.",
		},
		cli.StringFlag{
			Name:  "log-format",
			Usage: "Log format (default, plain, file, fancy).",
		},
		cli.StringFlag{
			Name:  "log-prefix",
			Usage: "Specify a prefix for a unique log file name.",
		},
		cli.StringFlag{
			Name:  "merkle-kids",
			Usage: "Set of admissible Merkle Tree fingerprints (colon-separated).",
		},
		cli.BoolFlag{
			Name:  "no-debug",
			Usage: "Suppress debugging mode; takes precedence over --debug.",
		},
		cli.StringFlag{
			Name:  "pgpdir, gpgdir",
			Usage: "Specify a PGP directory (default is ~/.gnupg).",
		},
		cli.StringFlag{
			Name:  "pid-file",
			Usage: "Location of the keybased pid-file (to ensure only one running daemon).",
		},
		cli.StringFlag{
			Name:  "pinentry",
			Usage: "Specify a path to find a pinentry program.",
		},
		cli.IntFlag{
			Name:  "proof-cache-size",
			Usage: "Number of proof entries to cache.",
		},
		cli.StringFlag{
			Name:  "proxy",
			Usage: "Specify a proxy to ship all Web requests over; Must be used with --proxy-type; Example: localhost:8080",
		},
		cli.StringFlag{
			Name:  "proxy-type",
			Usage: fmt.Sprintf("set the proxy type; One of: %s", libkb.GetCommaSeparatedListOfProxyTypes()),
		},
		cli.BoolFlag{
			Name:  "push-disabled",
			Usage: "Disable push server connection (which is on by default)",
		},
		cli.IntFlag{
			Name:  "push-save-interval",
			Usage: "Set the interval between saves of the push cache (in seconds)",
		},
		cli.StringFlag{
			Name:  "push-server-uri",
			Usage: "Specify a URI for contacting the Keybase push server",
		},
		cli.StringFlag{
			Name:  "pvl-kit",
			Usage: "Specify an alternate local PVL kit file location.",
		},
		cli.StringFlag{
			Name:  "paramproof-kit",
			Usage: "Specify an alternate local parameterized proof kit file location.",
		},
		cli.BoolFlag{
			Name:  "prove-bypass",
			Usage: "Prove even disabled proof services",
		},
		cli.BoolFlag{
			Name:  "remember-passphrase",
			Usage: "Remember keybase passphrase",
		},
		cli.StringFlag{
			Name:  "run-mode",
			Usage: "Run mode (devel, staging, prod).", // These are defined in libkb/constants.go
		},
		cli.StringFlag{
			Name:  "scraper-timeout",
			Usage: "set the HTTP timeout for external proof scrapers",
		},
		cli.StringFlag{
			Name:  "secret-keyring",
			Usage: "Location of the Keybase secret-keyring (P3SKB-encoded).",
		},
		cli.StringFlag{
			Name:  "server, s",
			Usage: "Specify server API.",
		},
		cli.StringFlag{
			Name:  "session-file",
			Usage: "Specify an alternate session data file.",
		},
		cli.BoolFlag{
			Name:  "slow-gregor-conn",
			Usage: "Slow responses from gregor for testing",
		},
		cli.BoolFlag{
			Name:  "read-deleted-sigchain",
			Usage: "Allow admins to read deleted sigchains for debugging.",
		},
		cli.StringFlag{
			Name:  "socket-file",
			Usage: "Location of the keybased socket-file.",
		},
		cli.BoolFlag{
			Name:  "standalone",
			Usage: "Use the client without any daemon support.",
		},
		cli.StringFlag{
			Name:  "timers",
			Usage: "Specify 'a' for API; 'r' for RPCs; and 'x' for eXternal API calls",
		},
		cli.StringFlag{
			Name:  "tor-hidden-address",
			Usage: fmt.Sprintf("set TOR address of keybase server; defaults to %s", libkb.TorServerURI),
		},
		cli.StringFlag{
			Name:  "tor-mode",
			Usage: "set TOR mode to be 'leaky', 'none', or 'strict'. 'none' by default. See 'help tor' for more details.",
		},
		cli.StringFlag{
			Name:  "tor-proxy",
			Usage: fmt.Sprintf("set TOR proxy; when Tor mode is on; defaults to %s when TOR is enabled", libkb.TorProxy),
		},
		cli.StringFlag{
			Name:  "updater-config-file",
			Usage: "Specify a path to the updater config file",
		},
		cli.StringFlag{
			Name:  "gui-config-file",
			Usage: "Specify a path to the GUI config file",
		},
		cli.BoolFlag{
			Name:  "use-default-log-file",
			Usage: "Log to the default log file in $XDG_CACHE_HOME, or ~/.cache if unset.",
		},
		cli.IntFlag{
			Name:  "user-cache-size",
			Usage: "Number of User entries to cache.",
		},
		cli.StringFlag{
			Name:  "vdebug",
			Usage: "Verbose debugging; takes a comma-joined list of levels and tags",
		},
		cli.BoolFlag{
			Name:  "debug-journeycard",
			Usage: "Enable experimental journey cards",
		},
		cli.BoolFlag{
			Name:  "disable-team-auditor",
			Usage: "Disable auditing of teams",
		},
		cli.BoolFlag{
			Name:  "disable-team-box-auditor",
			Usage: "Disable box auditing of teams",
		},
		cli.BoolFlag{
			Name:  "disable-merkle-auditor",
			Usage: "Disable background probabilistic merkle audit",
		},
		cli.BoolFlag{
			Name:  "disable-search-indexer",
			Usage: "Disable chat search background indexer",
		},
		cli.BoolFlag{
			Name:  "disable-bg-conv-loader",
			Usage: "Disable background conversation loading",
		},
		cli.BoolFlag{
			Name:  "enable-bot-lite-mode",
			Usage: "Enable bot lite mode. Disables non-critical background services for bot performance.",
		},
		cli.BoolFlag{
			Name:  "force-linux-keyring",
			Usage: "Require the use of the OS keyring (Gnome Keyring or KWallet) and fail if not available rather than falling back to file-based secret store.",
		},
		cli.BoolFlag{
			Name:  "extra-net-logging",
			Usage: "Do additional debug logging during network requests.",
		},
	}
	if extraFlags != nil {
		app.Flags = append(app.Flags, extraFlags...)
	}

	app.Commands = []cli.Command{}
}

func filter(cmds []cli.Command, fn func(cli.Command) bool) []cli.Command {
	var filter []cli.Command
	for _, cmd := range cmds {
		if fn(cmd) {
			filter = append(filter, cmd)
		}
	}
	return filter
}

func (p *CommandLine) AddCommands(cmds []cli.Command) {
	cmds = filter(cmds, func(c cli.Command) bool {
		return c.Name != ""
	})
	p.app.Commands = append(p.app.Commands, cmds...)
}

func (p *CommandLine) SetDefaultCommand(name string, cmd Command) {
	p.defaultCmd = name
	p.app.Action = func(c *cli.Context) {
		p.cmd = cmd
		p.ctx = c
		p.name = name
	}
}

// Called back from inside our subcommands, when they're picked...
func (p *CommandLine) ChooseCommand(cmd Command, name string, ctx *cli.Context) {
	p.cmd = cmd
	p.name = name
	p.ctx = ctx
}

func (p *CommandLine) Parse(args []string) (cmd Command, err error) {
	// This is suboptimal, but the default help action when there are
	// no args crashes.
	// (cli sets HelpPrinter to nil when p.app.Run(...) returns.)
	if len(args) == 1 && p.defaultCmd == "help" {
		args = append(args, p.defaultCmd)
	}

	// Actually pick a command
	err = p.app.Run(args)

	// Should not be populated
	cmd = p.cmd

	if err != nil || cmd == nil {
		return
	}

	// cli.HelpPrinter is nil here...anything that needs it will panic.

	// If we failed to parse arguments properly, switch to the help command
	if err = p.cmd.ParseArgv(p.ctx); err == nil {
		_, err = p.GetRunMode()
	}
	if err != nil {
		cmd = &CmdSpecificHelp{CmdBaseHelp{p.ctx}, p.name}
	}

	return
}

func (p *CommandLine) SetOutputWriter(w io.Writer) {
	p.app.Writer = w
}

// AddHelpTopics appends topics to the list of help topics for
// this app.
func (p *CommandLine) AddHelpTopics(topics []cli.HelpTopic) {
	p.app.HelpTopics = append(p.app.HelpTopics, topics...)
}


text:
const _ = require('lodash');
const rewiremock = require('rewiremock').default;
const { addPlugin, plugins } = require('rewiremock');

addPlugin(plugins.relative);
addPlugin(plugins.usedByDefault);

const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised);

const assert = chai.assert;

describe('Testing FB reply', () => {
  it('fb reply', async () => {
    let rpData = null;

    rewiremock('request-promise').with(async (data) => {
      rpData = data;
      return null;
    });

    rewiremock('../multiconf').with(() => ({
      getEnv: envName => '123',
      getFacebookPageTokenByPageID: envName => '123'
    }));

    rewiremock.enable();
    rewiremock.isolation();

    const fbInstance = require(rewiremock.resolve('../src/fb/reply'));
    const fbMsg = require(rewiremock.resolve('../src/fb/message_types'));
    const senderID = '1234567890';
    let fb = fbInstance(null);
    await fb.reply(fbMsg.textMessage('hello'), senderID);

    rewiremock.disable();
    rewiremock.clear();

    assert.equal(_.get(rpData, 'method'), 'POST');
    assert.equal(_.get(rpData, 'json.recipient.id'), senderID);
    assert.equal(_.get(rpData, 'json.message.text'), 'hello');
    assert.isOk(_.has(rpData, 'qs.access_token'));
    assert.isOk(_.has(rpData, 'url'));
    assert.equal(_.get(rpData, 'qs.access_token'), '123');
  });
});


text:
'use strict';

var _supertest = require('supertest');

var _supertest2 = _interopRequireDefault(_supertest);

var _chai = require('chai');

var _chai2 = _interopRequireDefault(_chai);

var _chaiHttp = require('chai-http');

var _chaiHttp2 = _interopRequireDefault(_chaiHttp);

var _models = require('../models');

var _app = require('../app');

var _app2 = _interopRequireDefault(_app);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

// During the test the env variable is set to test
process.env.NODE_ENV = 'test'; // Require the dev-dependencies

var server = _supertest2.default.agent(_app2.default);
var should = _chai2.default.should();

_chai2.default.use(_chaiHttp2.default);

describe('Users', function () {
  before(function (done) {
    // Before each test we empty the database
    _models.Users.sync({ force: true }).then(function () {
      done();
    }).catch(function (error) {
      done(error);
    });
  });

  describe('API Route Tests: ', function () {
    describe('Signup', function () {
      it('should create a new user account when all conditions are met', function (done) {
        server.post('/api/v1/users/signup').send({
          username: 'kene',
          email: 'kene@gmail.com',
          phone: '07038550515',
          password: 'kene' }).end(function (err, res) {
          res.should.have.status(201);
          res.body.should.be.a('object');
          res.should.have.status(201);
          res.body.should.have.property('message').eql('User Created successfully');
          done();
        });
      });
      it('should another a new user account', function (done) {
        server.post('/api/v1/users/signup').send({
          username: 'Mike',
          email: 'mike@gmail.com',
          phone: '07038550515',
          password: 'kene' }).end(function (err, res) {
          res.should.have.status(201);
          res.body.should.be.a('object');
          res.should.have.status(201);
          res.body.should.have.property('message').eql('User Created successfully');
          done();
        });
      });
      it('should throw 409 error when a duplicate account wants to be created', function (done) {
        server.post('/api/v1/users/signup').send({
          username: 'kene',
          email: 'kene@gmail.com',
          phone: '07038550515',
          password: 'kene' }).end(function (err, res) {
          res.should.have.status(409);
          res.body.should.have.property('message').eql('User already exist');
          done();
        });
      });
      it('should not allow user to be created when any field is invalid', function (done) {
        server.post('/api/v1/users/signup').send({
          username: 'Miene',
          email: 'email',
          phone: '07038550515',
          password: 'kene' }).end(function (err, res) {
          res.should.have.status(400);
          res.body.should.have.property('message').eql('Email is invalid');
          done();
        });
      });
      it('should not create a new user when all field is not available', function (done) {
        server.post('/api/v1/users/signup').send({
          // username: 'kene', // ie if the validate input fails
          email: 'kene@gmail.com',
          phone: '07038550515',
          password: 'kene' }).end(function (err, res) {
          res.should.have.status(400);
          res.body.should.have.property('message').eql('Invalid request. Some column(s) are missing');
          done();
        });
      });
      it('should not create a new user when any field is empty', function (done) {
        server.post('/api/v1/users/signup').send({
          username: '',
          email: 'kene@gmail.com',
          phone: '07038550515',
          password: 'kene' }).end(function (err, res) {
          res.should.have.status(400);
          res.body.should.have.property('message').eql('Invalid request. Some column(s) are missing');
          done();
        });
      });
    });
  });
  describe('Signin', function () {
    var token = '';
    it('should not signin when any field is missing', function (done) {
      server.post('/api/v1/users/signin').send({
        // username: 'kene',
        password: 'kene' }).end(function (err, res) {
        token = res.body.token;
        res.should.have.status(400);
        res.body.should.be.a('object');
        res.body.should.have.property('message').eql('Invalid request. Some column(s) are missing');
        done();
      });
    });
    it('should not signin when any field is empty', function (done) {
      server.post('/api/v1/users/signin').send({
        username: '',
        password: 'kene' }).end(function (err, res) {
        token = res.body.token;
        res.should.have.status(400);
        res.body.should.be.a('object');
        res.body.should.have.property('message').eql('Invalid request. Some column(s) are missing');
        done();
      });
    });
    it('should expect parameter of object returned on successful signin', function (done) {
      server.post('/api/v1/users/signin').send({
        username: 'kene',
        password: 'kene' }).end(function (err, res) {
        res.should.have.status(202);
        res.body.should.have.property('token');
        res.body.should.have.property('message').eql('Successfully logged in');
        res.body.should.have.property('username').eql('kene');
        done();
      });
    });
    it('should signin a user with correct credentials', function (done) {
      server.post('/api/v1/users/signin').send({
        username: 'kene',
        password: 'kene' }).end(function (err, res) {
        token = res.body.token;
        res.should.have.status(202);
        res.body.should.be.a('object');
        res.body.should.have.property('message').eql('Successfully logged in');
        done();
      });
    });
    it('should return 404 if a user is not found', function (done) {
      server.post('/api/v1/users/signin').send({
        username: 'paul',
        password: 'kene' }).end(function (err, res) {
        res.should.have.status(404);
        res.body.should.have.property('message').eql('Username not found, please register');
        done();
      });
    });
    it('should return user details when searched by username', function (done) {
      server.post('/api/v1/users/username').send({
        token: token,
        username: 'kene' }).end(function (err, res) {
        res.should.have.status(200);
        res.body.should.have.property('userid');
        res.body.should.have.property('username');
        res.body.should.have.property('phone');
        res.body.should.have.property('email');
        done();
      });
    });
    it('should return 404 error when user\n        details is not found when searched by username', function (done) {
      server.post('/api/v1/users/username').send({
        token: token,
        username: 'keneM' }).end(function (err, res) {
        res.should.have.status(404);
        res.body.should.have.property('message').eql('User not found');
        done();
      });
    });
    it('should return 403 error when search user by\n        username query errored', function (done) {
      server.post('/api/v1/users/username').send({
        // token, // when token is not available
        username: 'kene' }).end(function (err, res) {
        res.should.have.status(403);
        done();
      });
    });
    it('should not search a user by username if username is not supplied', function (done) {
      server.post('/api/v1/users/username').send({
        token: token
        // username: 'kene'
      }).end(function (err, res) {
        res.should.have.status(400);
        res.body.should.have.property('message').eql('Invalid request. Username column is missing');
        done();
      });
    });
    it('should not search a user by username if username is empty', function (done) {
      server.post('/api/v1/users/username').send({
        token: token,
        username: ''
      }).end(function (err, res) {
        res.should.have.status(400);
        res.body.should.have.property('message').eql('Invalid request. Username column is missing');
        done();
      });
    });
  });
  describe('Update Password', function () {
    var token = 'thisisagibrishtoken';
    it('should not update password if new password is not available', function (done) {
      server.post('/api/v1/users/resetpassword/' + token).send({
        // password: 'kene',
        email: 'kene@gmail.com' }).end(function (err, res) {
        res.should.have.status(400);
        res.body.should.be.a('object');
        res.body.should.have.property('message').eql('Invalid request. Some column(s) are missing');
        done();
      });
    });
    it('should not update password if any parameter violates validation rules', function (done) {
      server.post('/api/v1/users/resetpassword/' + token).send({
        password: 'kene',
        confirmPassword: 'kene',
        email: 'kene' }).end(function (err, res) {
        res.should.have.status(400);
        res.body.should.be.a('object');
        res.body.should.have.property('message').eql('Email is invalid');
        done();
      });
    });
    it('should update password when all conditions are met', function (done) {
      server.post('/api/v1/users/resetpassword/' + token).send({
        password: 'kene',
        confirmPassword: 'kene',
        email: 'kene@gmail.com' }).end(function (err, res) {
        res.should.have.status(200);
        res.body.should.be.a('object');
        res.body.should.have.property('message').eql('Password reset successfully!');
        done();
      });
    });
    it('should 404 when token does not exists', function (done) {
      var inValidToken = 'thisisaninvalidtoken';
      server.get('/api/v1/users/resetpassword/' + inValidToken).end(function (err, res) {
        res.should.have.status(404);
        res.body.should.be.a('object');
        res.body.should.have.property('message').eql('Token not found');
        done();
      });
    });
  });
  describe('Valid Token', function () {
    var token = 'thisisagibrishtoken';
    it('should check if token exist', function (done) {
      server.get('/api/v1/users/resetpassword/' + token).set({ 'x-access-token': token }).end(function (err, res) {
        res.should.have.status(404);
        res.body.should.be.a('object');
        res.body.should.have.property('message').eql('Token not found');
        done();
      });
    });
  });
  describe('Reset password', function () {
    it('should not reset password if any parameter violates validation rules', function (done) {
      server.post('/api/v1/users/resetpassword').send({
        password: 'kene',
        confirmPassword: 'kene',
        email: 'kene' }).end(function (err, res) {
        res.should.have.status(400);
        res.body.should.be.a('object');
        res.body.should.have.property('message').eql('Email is invalid');
        done();
      });
    });
    it('should not update password when any field is empty', function (done) {
      server.post('/api/v1/users/resetpassword').send({
        password: 'kene',
        confirmPassword: 'kene',
        email: '' }).end(function (err, res) {
        res.should.have.status(400);
        res.body.should.be.a('object');
        res.body.should.have.property('message').eql('Invalid request. Email column is missing');
        done();
      });
    });
  });
});


text:
/*
 * Implementation of MCS ticket spinlock
 */

#include <stddef.h>
#include <atomics_x86.h>
#include <mcs_ticket_lock.h>

void ticket_lock(ticketlock_t *lock) {
	// atomically fetch and increment ticket
	//uint64_t ticket = lock_xadd_64(&lock->ticket, 1);
	uint64_t ticket = __sync_fetch_and_add(&lock->ticket, 1);

	// wait for turn to match this thread's ticket
	uint64_t turn, cnt;
	while ((turn = lock->turn) != ticket) {
		// proportional back-off
		for (cnt = ticket; cnt < turn; cnt++);
	}
}

void ticket_unlock(ticketlock_t *lock) {
	// increment turn
	lock->turn++;
}


text:
/**
 * @file ThunderTimer Class implementation. ThunderTimer creates a timer that can be managed with methods like ThunderTimer.start(),
 * ThunderTimer.pause(), ThunderTimer.stop(), among others.
 * @author Tomás Castro
 * @version 0.0.1
 */
import EventEmitter from 'events';

const TIME = {
  SECOND_TENTHS_PER_SECOND: 10,
  SECONDS_PER_MINUTE: 60,
  SECOND_TENTHS_PER_MINUTE: 600,
  MINUTES_PER_HOUR: 60,
  SECONDS_PER_HOUR: 3600,
  SECOND_TENTHS_PER_HOUR: 36000,
  HOURS_PER_DAY: 24,

  SECOND_TENTHS_POSITION: 0,
  SECONDS_POSITION: 1,
  MINUTES_POSITION: 2,
  HOURS_POSITION: 3,
  DAYS_POSITION: 4,

  SECOND_TENTHS: 'secondTenths',
  SECONDS: 'seconds',
  MINUTES: 'minutes',
  HOURS: 'hours',
  DAYS: 'days',

  unitsInMilliseconds: {
    secondTenths: 100,
    seconds: 1000,
    minutes: 60000,
    hours: 3600000,
    days: 86400000,
  },

};

const STATUS = {
  NOT_STARTED: 'not started',
  RUNNING: 'running',
  PAUSED: 'paused',
  STOPPED: 'stopped',
};

/**
 * ThunderTimer Class.
 *
 * @extends EventEmitter
 * @class
 * @property {number[]} timeArray=[0, 0, 0, 0, 0] - Array of length 5 representing the current time of a timer.
 * @property {boolean}  isCountDown=false         - Sets if the timer is a countdown.
 * @property {Object}   thunder=null              - Holds the setInterval function.
 * @property {boolean}  isRunning=false           - Represents the running status of a timer.
 * @property {Object}   separator=:               - Sets the type of separator for the prettified time.
 * @property {string}   status=Not started.       - Descriptor of the current status of the timer.
 * @property {Object}   metaTimes                 - Helper time variables for in timer calculations.
 * @public
 *
 */
class ThunderTimer extends EventEmitter {

  /**
   * ThunderTimer Constructor.
   * @constructor
   * @param {Object}   [options={}]                        - Timer options.
   * @param {number[]} [options.timeArray=[0, 0, 0, 0, 0]] - Array of length 5 representing the current time of a timer.
   * @param {boolean}  [options.isCountDown=false]         - Sets if the timer is a countdown.
   * @param {Object}   [options.separator=:]               - Sets the type of separator for the prettified time.
   */
  constructor(options = {}) {
    super();

    if (options.separator && options.separator === '.') {
      throw new Error('Separator can not be a dot.');
    }

    this.timeArray = options.initialTime || [0, 0, 0, 0, 0];
    this.isCountDown = options.isCountDown || false;
    this.separator = options.separator || ':';
    this.thunder = null;
    this.isRunning = false;
    this.status = STATUS.NOT_STARTED;
    this.metaTimes = {
      initialTime: null,
      endTime: null,
      currentTime: 0,
      realTime: 0,
      onRestartTime: 0,
      onPauseTime: 0,
      leisureTime: 0,
    };
  }

  /**
   * Starts a timer.
   * @param {number} [updateTimeInterval=TIME.unitsInMilliseconds.secondTenths] - Interval at which the timer is updated. (in milliseconds)
   */
  start(updateTimeInterval = TIME.unitsInMilliseconds.secondTenths) {
    if (this.status === STATUS.STOPPED) return;
    !this.thunder ? this.metaTimes.initialTime = Date.now() : noop();
    this.metaTimes.onPauseTime ? (() => {
      this.metaTimes.onRestartTime = Date.now();
      this.metaTimes.leisureTime += (this.metaTimes.onRestartTime - this.metaTimes.onPauseTime);
    })() : noop();

    this.thunder = setInterval(this._updateTime.bind(this), updateTimeInterval);
    this._updateStatus(STATUS.RUNNING);
  }

  /**
   * Pauses a timer.
   * @returns {string}
   */
  pause() {
    if (this.status !== STATUS.RUNNING) return;
    this.metaTimes.onPauseTime = Date.now();
    clearInterval(this.thunder);
    this._updateStatus(STATUS.PAUSED);
    return this.getTime();
  }

  /**
   * Stops a timer.
   */
  stop() {
    if (this.status !== STATUS.RUNNING && this.status !== STATUS.PAUSED) return;
    this.metaTimes.endTime = Date.now();
    clearInterval(this.thunder);
    this._updateStatus(STATUS.STOPPED);
  }

  /**
   * Returns a representation of the arrayTime of timer.
   * @param {boolean} [pretty=false] - If set to true timer is prettified and returned as String.
   * @returns {string}
   */
  getTime(pretty = false) {
    return pretty ? this._prettify() : this.timeArray.slice().reverse().join(this.separator);
  }

  /**
   * Returns the current status descriptor of timer.
   * @returns {string}
   */
  getStatus() {
    return this.status;
  }

  static getStatuses() {
    return STATUS;
  }

  /**
   * Sets the value for isRunning of timer.
   * @param {boolean} isRunning - Represents the running state of the timer.
   * @private
   */
  _setIsRunning(isRunning) {
    this.isRunning = isRunning;
  }

  /**
   * Returns the current running status of timer.
   * @returns {boolean}
   * @private
   */
  _getIsRunning() {
    return this.isRunning;
  }

  /**
   * Sets the status of timer.
   * @param {string} status - Status descriptor of timer.
   * @private
   */
  _setStatus(status) {
    this.status = status;
  }

  /**
   * Updates arrayTime.
   * @private
   */
  _updateTime() {
    this.metaTimes.realTime = Date.now() - this.metaTimes.initialTime;
    this.metaTimes.currentTime = this.metaTimes.realTime - this.metaTimes.leisureTime;

    this.timeArray[4] = Math.floor(this.metaTimes.currentTime / TIME.unitsInMilliseconds.days);
    this.timeArray[3] = Math.floor((this.metaTimes.currentTime % TIME.unitsInMilliseconds.days) / TIME.unitsInMilliseconds.hours);
    this.timeArray[2] = Math.floor((this.metaTimes.currentTime % TIME.unitsInMilliseconds.hours) / TIME.unitsInMilliseconds.minutes);
    this.timeArray[1] = Math.floor((this.metaTimes.currentTime % TIME.unitsInMilliseconds.minutes) / TIME.unitsInMilliseconds.seconds);
    this.timeArray[0] = (this.metaTimes.currentTime % TIME.unitsInMilliseconds.seconds) / TIME.unitsInMilliseconds.secondTenths;
  }

  /**
   * Updates general status of timer.
   * @param {string} status - New status descriptor for timer.
   * @private
   */
  _updateStatus(status) {
    status === STATUS.RUNNING ? this._setIsRunning(true) : this._setIsRunning(false);
    this._setStatus(status);
    this.emit(status, this._getTimerData());
  }

  /**
   * Returns general data of the timer.
   * @returns {Object}
   * @private
   */
  _getTimerData() {
    return {
      initialTime: this.metaTimes.initialTime,
      endTime: this.metaTimes.endTime,
    };
  }

  /**
   * Prettifies timer.
   * @returns {string}
   * @private
   */
  _prettify() {
    return this.timeArray[TIME.DAYS_POSITION] + ' ' + TIME.DAYS + ', ' +
            this.timeArray[TIME.HOURS_POSITION] + ' ' + TIME.HOURS + ', ' +
            this.timeArray[TIME.MINUTES_POSITION] + ' ' + TIME.MINUTES + ', ' +
            this.timeArray[TIME.SECONDS_POSITION] + ' ' + TIME.SECONDS;
  }

}

function noop() {}

module.exports = ThunderTimer;


text:
package net.runelite.client.plugins.pyramidplunder;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import net.runelite.api.Client;
import net.runelite.api.Varbits;
import net.runelite.client.ui.overlay.infobox.Timer;

class PyramidPlunderTimer extends Timer
{
	private final PyramidPlunderConfig config;
	private final Client client;

	public PyramidPlunderTimer(
		Duration duration,
		BufferedImage image,
		PyramidPlunderPlugin plugin,
		PyramidPlunderConfig config,
		Client client
	)
	{
		super(duration.toMillis(), ChronoUnit.MILLIS, image, plugin);
		this.config = config;
		this.client = client;
	}

	@Override
	public Color getTextColor()
	{
		long secondsLeft = Duration.between(Instant.now(), getEndTime()).getSeconds();
		return secondsLeft < config.timerLowWarning() ? Color.RED.brighter() : Color.white;
	}

	@Override
	public String getTooltip()
	{
		int floor = client.getVarbitValue(Varbits.PYRAMID_PLUNDER_ROOM);
		int thievingLevel = client.getVarbitValue(Varbits.PYRAMID_PLUNDER_THIEVING_LEVEL);
		return String.format("Time remaining. Floor: %d. Thieving level: %d", floor, thievingLevel);
	}

	@Override
	public boolean render()
	{
		return config.showExactTimer();
	}
}


text:
module Azure::CDN::Mgmt::V2020_09_01
  module Models
    #
    # Defines the origin group override action for the delivery rule.
    #
    class OriginGroupOverrideAction < DeliveryRuleAction

      include MsRestAzure

      def initialize
        @name = "OriginGroupOverride"
      end

      attr_accessor :name

      # @return [OriginGroupOverrideActionParameters] Defines the parameters
      # for the action.
      attr_accessor :parameters

      #
      # Mapper for OriginGroupOverrideAction class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'OriginGroupOverride',
          type: {
            name: 'Composite',
            class_name: 'OriginGroupOverrideAction',
            model_properties: {
              name: {
                client_side_validation: true,
                required: true,
                serialized_name: 'name',
                type: {
                  name: 'String'
                }
              },
              parameters: {
                client_side_validation: true,
                required: true,
                serialized_name: 'parameters',
                default_value: {},
                type: {
                  name: 'Composite',
                  class_name: 'OriginGroupOverrideActionParameters'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
namespace views {

class NativeViewHost;

class WEBVIEW_EXPORT WebView : public View,
                               public content::WebContentsDelegate,
                               public content::WebContentsObserver {
 public:
  static const char kViewClassName[];

  explicit WebView(content::BrowserContext* browser_context);
  virtual ~WebView();

  // This creates a WebContents if none is yet associated with this WebView. The
  // WebView owns this implicitly created WebContents.
  content::WebContents* GetWebContents();

  // WebView does not assume ownership of WebContents set via this method, only
  // those it implicitly creates via GetWebContents() above.
  void SetWebContents(content::WebContents* web_contents);

  // If |mode| is true, WebView will register itself with WebContents as a
  // WebContentsObserver, monitor for the showing/destruction of fullscreen
  // render widgets, and alter its child view hierarchy to embed the fullscreen
  // widget or restore the normal WebContentsView.
  void SetEmbedFullscreenWidgetMode(bool mode);

  content::WebContents* web_contents() const {
    return content::WebContentsObserver::web_contents();
  }

  content::BrowserContext* browser_context() { return browser_context_; }

  // Loads the initial URL to display in the attached WebContents. Creates the
  // WebContents if none is attached yet. Note that this is intended as a
  // convenience for loading the initial URL, and so URLs are navigated with
  // PAGE_TRANSITION_AUTO_TOPLEVEL, so this is not intended as a general purpose
  // navigation method - use WebContents' API directly.
  void LoadInitialURL(const GURL& url);

  // Controls how the attached WebContents is resized.
  // false = WebContents' views' bounds are updated continuously as the
  //         WebView's bounds change (default).
  // true  = WebContents' views' position is updated continuously but its size
  //         is not (which may result in some clipping or under-painting) until
  //         a continuous size operation completes. This allows for smoother
  //         resizing performance during interactive resizes and animations.
  void SetFastResize(bool fast_resize);

  // Called when the WebContents is focused.
  // TODO(beng): This view should become a WebContentsViewObserver when a
  //             WebContents is attached, and not rely on the delegate to
  //             forward this notification.
  void OnWebContentsFocused(content::WebContents* web_contents);

  // When used to host UI, we need to explicitly allow accelerators to be
  // processed. Default is false.
  void set_allow_accelerators(bool allow_accelerators) {
    allow_accelerators_ = allow_accelerators;
  }

  // Sets the preferred size. If empty, View's implementation of
  // GetPreferredSize() is used.
  void SetPreferredSize(const gfx::Size& preferred_size);

  // Overridden from View:
  virtual const char* GetClassName() const OVERRIDE;

 private:
  // Overridden from View:
  virtual void OnBoundsChanged(const gfx::Rect& previous_bounds) OVERRIDE;
  virtual void ViewHierarchyChanged(
      const ViewHierarchyChangedDetails& details) OVERRIDE;
  virtual bool SkipDefaultKeyEventProcessing(
      const ui::KeyEvent& event) OVERRIDE;
  virtual bool IsFocusable() const OVERRIDE;
  virtual void OnFocus() OVERRIDE;
  virtual void AboutToRequestFocusFromTabTraversal(bool reverse) OVERRIDE;
  virtual void GetAccessibleState(ui::AXViewState* state) OVERRIDE;
  virtual gfx::NativeViewAccessible GetNativeViewAccessible() OVERRIDE;
  virtual gfx::Size GetPreferredSize() OVERRIDE;

  // Overridden from content::WebContentsDelegate:
  virtual void WebContentsFocused(content::WebContents* web_contents) OVERRIDE;
  virtual bool EmbedsFullscreenWidget() const OVERRIDE;

  // Overridden from content::WebContentsObserver:
  virtual void RenderViewHostChanged(
      content::RenderViewHost* old_host,
      content::RenderViewHost* new_host) OVERRIDE;
  virtual void WebContentsDestroyed(
      content::WebContents* web_contents) OVERRIDE;
  virtual void DidShowFullscreenWidget(int routing_id) OVERRIDE;
  virtual void DidDestroyFullscreenWidget(int routing_id) OVERRIDE;
  // Workaround for MSVC++ linker bug/feature that requires
  // instantiation of the inline IPC::Listener methods in all translation units.
  virtual void OnChannelConnected(int32 peer_id) OVERRIDE {}
  virtual void OnChannelError() OVERRIDE {}

  void AttachWebContents();
  void DetachWebContents();
  void ReattachForFullscreenChange(bool enter_fullscreen);

  // Create a regular or test web contents (based on whether we're running
  // in a unit test or not).
  content::WebContents* CreateWebContents(
      content::BrowserContext* browser_context);

  NativeViewHost* wcv_holder_;
  // Non-NULL if |web_contents()| was created and is owned by this WebView.
  scoped_ptr<content::WebContents> wc_owner_;
  // When true, WebView auto-embeds fullscreen widgets as a child view.
  bool embed_fullscreen_widget_mode_enabled_;
  // Set to true while WebView is embedding a fullscreen widget view as a child
  // view instead of the normal WebContentsView render view.
  bool is_embedding_fullscreen_widget_;
  content::BrowserContext* browser_context_;
  bool allow_accelerators_;
  gfx::Size preferred_size_;

  DISALLOW_COPY_AND_ASSIGN(WebView);
};

}  // namespace views

#endif  // UI_VIEWS_CONTROLS_WEBVIEW_WEBVIEW_H_


text:
namespace Microsoft.AspNetCore.Mvc.ViewFeatures;

/// <summary>
/// Specifies that a controller property should be set with the current
/// <see cref="ViewDataDictionary"/> when creating the controller. The property must have a public
/// set method.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class ViewDataDictionaryAttribute : Attribute
{
}


text:
/* */
var $export = require("./_export");
$export($export.S + $export.F * !require("./_descriptors"), 'Object', {defineProperties: require("./_object-dps")});


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:drawable="@color/transparent_black" />
    <item android:state_focused="true" android:drawable="@color/transparent_black" />
    <item android:state_pressed="true" android:drawable="@color/transparent_black" />
    <item android:drawable="@android:color/transparent" />
</selector>


text:
#include "./../server.h"
#include "./../Game/postgresqlstruct.h"
#include "./../PlayerLogin/playerlogin.h"
#include "./../Game/cmdparse.h"
#include "./../Game/session.hpp"

#include "tcpconnection.h"

TCPConnection::TCPConnection(boost::asio::io_service &io)
    :m_socket(io),m_dataPos(0),m_LoginStatus(PlayerNotLoginUser)
{

}

TCPConnection::~TCPConnection()
{
    Logger::GetLogger()->Info("Release Memory of TCPConnection");
}

void TCPConnection::Start()
{
    ReadSome();
}

int TCPConnection::Write_all(void *buff, int size)
{
    if(size >= CHUNK_SIZE)  //test
    {
        STR_PackHead t_packHead;
        memcpy(&t_packHead, buff, sizeof(STR_PackHead));
        Logger::GetLogger()->Error("send data :%u,flag:%u,len:%u\n",size, t_packHead.Flag, t_packHead.Len);
        return 0;
    }
//    STR_PackHead t_packHead;
//    memcpy(&t_packHead, buff, sizeof(STR_PackHead));
//    Logger::GetLogger()->Error("send data :%u,flag:%u,len:%u\n",size, t_packHead.Flag, t_packHead.Len);

    m_write_lock.lock();

    //将要发送的数据拷贝至发送缓冲区,防止数据丢失
    memcpy(m_send_buf,buff,size);
    boost::asio::async_write( m_socket,boost::asio::buffer((char*)buff,size),boost::asio::transfer_all(),boost::bind(
                              &TCPConnection::CallBack_Write,shared_from_this(),boost::asio::placeholders::error(),
                              boost::asio::placeholders::bytes_transferred()
                              )
                            );
    return 0;
}

void TCPConnection::ReadSome()
{
        m_socket.async_read_some(boost::asio::buffer(m_buf + m_dataPos,TCP_BUFFER_SIZE - m_dataPos),
                                boost::bind(&TCPConnection::CallBack_Read_Some,
                                            shared_from_this(),
                                            boost::asio::placeholders::error(),
                                            boost::asio::placeholders::bytes_transferred()));
}

void TCPConnection::CallBack_Read_Some(const boost::system::error_code &ec, hf_uint16 size)
{
    if ( !ec )
    {
//        Logger::GetLogger()->Debug("size:%u",size);

        m_dataPos += size;
        hf_uint16 currentPos = 0;
        STR_PackHead head;
        SessionMgr::SessionPointer smap =  SessionMgr::Instance()->GetSession();
        while(currentPos < m_dataPos)
        {
            if(m_dataPos < sizeof(STR_PackHead))
            {
                Logger::GetLogger()->Debug("datalen:%u",m_dataPos);
                break;
            }
            memcpy(&head, m_buf + currentPos, sizeof(STR_PackHead));
            if(head.Len > 512)
            {
                Logger::GetLogger()->Debug("Client head.len > 512 Disconnected");
                Server::GetInstance()->GetPlayerLogin()->SavePlayerOfflineData(shared_from_this() );
            }
            if(currentPos + sizeof(STR_PackHead) + head.Len == m_dataPos) //最后一个包
            {
                memcpy(m_pack.data, m_buf + currentPos, sizeof(STR_PackHead) + head.Len);
                hf_uint8 value = JudgePlayerLogin(head.Flag);
                if(value == 2)
                {
                   m_pack.roleid = (*smap)[shared_from_this()].m_roleid;
                   Server::GetInstance()->PushPackage(m_pack);
                }
                else if(value == 1)//未登录角色
                {
                   CommandParseLogin(shared_from_this(), m_pack.data);
                }
                m_dataPos = 0;
                break;
            }
            else if(currentPos + sizeof(STR_PackHead) + head.Len < m_dataPos)  //未处理的数据长度多于一个包
            {
                memcpy(m_pack.data, m_buf + currentPos, sizeof(STR_PackHead) + head.Len);
                hf_uint8 value = JudgePlayerLogin(head.Flag);
                if(value == 2)
                {
                   m_pack.roleid = (*smap)[shared_from_this()].m_roleid;
                   Server::GetInstance()->PushPackage(m_pack);
                }
                else if(value == 1)//未登录角色
                {
                   CommandParseLogin(shared_from_this(), m_pack.data);
                }
                currentPos += sizeof(STR_PackHead) + head.Len;
                continue;
            }
            else //不够一个包的长度
            {
                Logger::GetLogger()->Debug("you wei jie xi de bao currentPos:%u,m_dataPos:%u,head.len:%u,head.flag:%u",currentPos,m_dataPos,head.Len, head.Flag);
                hf_char buff[TCP_BUFFER_SIZE] = { 0 };
                memcpy(buff, m_buf + currentPos, m_dataPos - currentPos);
                memcpy(m_buf, buff, TCP_BUFFER_SIZE);
                m_dataPos -= currentPos;
                break;
            }
        }
        ReadSome();
      }
    else if ( size == 0 || ec == boost::asio::error::eof || ec == boost::asio::error::shut_down)
    {
        Logger::GetLogger()->Debug("Client head Disconnected");
        Server::GetInstance()->GetPlayerLogin()->SavePlayerOfflineData(shared_from_this());
    }
}

void TCPConnection::CallBack_Write(const boost::system::error_code &code, hf_uint16 transfferd)
{

    if ( code ||  transfferd == 0 )
      {
        Logger::GetLogger()->Debug("Send Data to Player Error");
        Server::GetInstance()->GetPlayerLogin()->SavePlayerOfflineData(shared_from_this() );
      }
    m_write_lock.unlock();
}

//判断玩家是否登录角色
hf_uint8 TCPConnection::JudgePlayerLogin(hf_uint8 flag)
{
    if(m_LoginStatus == PlayerNotLoginUser) //未登录用户名,只能登录或注册用户
    {
        if(flag == FLAG_PlayerLoginUserId || flag == FLAG_PlayerRegisterUserId)
            return 1;
        else
            return 0;
    }
    else if(m_LoginStatus == PlayerLoginUser)//未登录角色,只能登录或注册或删除角色
    {
        if(flag == FLAG_PlayerLoginRole || flag == FLAG_PlayerRegisterRole || flag == FLAG_UserDeleteRole)
            return 1;
        else
            return 0;
    }
    else
    {
        return 2;
    }
}


text:
namespace Iyzipay.Request.V2.Subscription
{
    public class UpdateCardRequest : BaseRequestV2
    {
        public string CustomerReferenceCode { get; set; }
        public string CallbackUrl { get; set; }
    }
}


text:
**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public TermGroup[] TermGroup { get; set; }
```

### Property Value
Type: [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508.TermGroup[]](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508.TermGroup.md)

## See also
- [TermStore](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508.TermStore.md)
- [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508.md)


text:
use ControlMessage;
use bip_handshake::InfoHash;
use bip_peer::PeerInfo;
use bip_peer::messages::BitFieldMessage;
use bip_peer::messages::HaveMessage;

pub mod error;

mod honest;

pub use self::honest::HonestRevealModule;

/// Enumeration of revelation messages that can be sent to a revelation module.
pub enum IRevealMessage {
    /// Control message.
    Control(ControlMessage),
    /// Good piece for the given `InfoHash` was found.
    FoundGoodPiece(InfoHash, u64),
    /// Received a `BitFieldMessage`.
    ReceivedBitField(PeerInfo, BitFieldMessage),
    /// Received a `HaveMessage`.
    ReceivedHave(PeerInfo, HaveMessage),
}

/// Enumeration of revelation messages that can be received from a revelation module.
pub enum ORevealMessage {
    /// Send a `BitFieldMessage`.
    SendBitField(PeerInfo, BitFieldMessage),
    /// Send a `HaveMessage`.
    SendHave(PeerInfo, HaveMessage),
}


text:
namespace Alimer
{
    static constexpr uint32_t kConversionBufferLength = 128u;
    static constexpr uint32_t kMatrixConversionBufferLength = 256u;

    ALIMER_API extern const std::string kEmptyString;
    ALIMER_API extern const char kWhitespaceASCII[];

    enum class WhitespaceHandling
    {
        KeepWhitespace,
        TrimWhitespace
    };

    enum class SplitResult
    {
        All,
        NonEmpty,
    };

    uint32_t FormatStringIntoVector(const char* fmt, va_list args, std::vector<char>& buffer);

    /// Return a formatted string.
    ALIMER_API std::string ToString(const char* format, ...);

    ALIMER_API std::string TrimString(const std::string& input, const std::string& trimChars);

    ALIMER_API std::vector<std::string> SplitString(const std::string& input, const std::string& delimiters, WhitespaceHandling whitespace,
                                                    SplitResult resultType);

#ifdef _WIN32
    ALIMER_API std::string ToUtf8(const wchar_t* wstr, size_t len);
    ALIMER_API std::string ToUtf8(const std::wstring& str);

    ALIMER_API std::wstring ToUtf16(const char* str, size_t len);
    ALIMER_API std::wstring ToUtf16(const std::string& str);
#endif
}


text:
project_path: /web/_project.yaml
book_path: /web/fundamentals/_book.yaml
description: Обработчики ввода потенциально являются источниками проблем с производительностью в приложениях, поскольку они могут заблокировать завершение кадров, а также вызывать дополнительную (и совершенно ненужную) работу по пересчету макета

{# wf_updated_on: 2015-03-19 #}
{# wf_published_on: 2000-01-01 #}

# Оптимизация обработчиков ввода {: .page-title }

{% include "web/_shared/contributors/paullewis.html" %}

Обработчики ввода потенциально являются источниками проблем с производительностью в приложениях, поскольку они могут заблокировать завершение кадров, а также вызывать дополнительную (и совершенно ненужную) работу по пересчету макета

### TL;DR {: .hide-from-toc }
- "Не используйте обработчики ввода с длительным рабочим циклом\_– они могут заблокировать прокрутку."
- Не изменяйте стили в обработчиках ввода.
- Оптимизируйте обработчики; запоминайте значения событий и реализуйте изменения стилей при следующем обратном вызове функции requestAnimationFrame.

## Не используйте обработчики ввода с длительным рабочим циклом

В самом быстром варианте, когда пользователь вводит данные на страницу, поток компоновки страницы может принять касание пользователя и просто переместить контент. Основной поток, в котором выполняется код JavaScript, перерисовка, рассчитывается макет и применяются стили, при этом задействован не будет вообще.

Однако, если прикрепить обработчик ввода, например `touchstart`, `touchmove` или `touchend`, поток компоновщика должен будет подождать завершения выполнения рабочего цикла этого обработчика, поскольку может быть вызвана функция `preventDefault()` и прокрутка будет остановлена. Даже если функция `preventDefault()` не вызывается, компоновщик должен ждать, а выполняемая пользователем прокрутка будет заблокирована, что может привести к подвисанию или пропуску кадров.

Короче говоря, рабочий цикл любых используемых обработчиков ввода должен выполняться быстро, чтобы компоновщик мог делать свою работу.

## Не изменяйте стили в обработчиках ввода

Рабочий цикл обработчиков ввода, например прокрутки и касаний, выполняется перед тем, как будут выполняться обратные вызовы функции `requestAnimationFrame`.

Если внутри одного из таких обработчиков вносится визуальное изменение, то в начале выполнения обратного вызова `requestAnimationFrame` необходимо будет применить изменение стиля. Если _после этого_ выполнить чтение визуальных свойств в начале обратного вызова requestAnimationFrame, как рекомендуется в статье "[Не используйте большие, сложные макеты и избегайте подтормаживания макетов](avoid-large-complex-layouts-and-layout-thrashing)", вы вызовите принудительный синхронный перерасчет макета!

## Оптимизируйте обработчики прокрутки

Обе описанные выше неполадки имеют одно решение: следует всегда откладывать внесение визуальных изменений до следующего обратного вызова `requestAnimationFrame`:

    function onScroll (evt) {

      // Store the scroll value for laterz.
      lastScrollY = window.scrollY;

      // Prevent multiple rAF callbacks.
      if (scheduledAnimationFrame)
        return;

      scheduledAnimationFrame = true;
      requestAnimationFrame(readAndUpdatePage);
    }

    window.addEventListener('scroll', onScroll);

Кроме того, обработчики ввода при этом останутся необременительными, а это отлично, поскольку теперь прокрутка или касания при выполнении кода с большим объемом вычислений не будут блокироваться!


text:
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.math.BigDecimal;

import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.Writable;

/**
 * Writable representing a stock's price on a given day
 *
 */
public class StockWritable implements Writable {
	/** The stock's price */
	public BigDecimal price;

	/** The date of the stock price */
	public String date;

	/**
	 * Empty constructor - required for serialization.
	 */
	public StockWritable() {

	}

	/**
	 * Constructor
	 */
	public StockWritable(String date, BigDecimal price) {
		this.date = date;
		this.price = price;
	}

	/**
	 * Serializes the fields of this object to out.
	 */
	public void write(DataOutput out) throws IOException {
		out.writeUTF(date);

		byte[] priceArray = Bytes.toBytes(price);

		out.writeInt(priceArray.length);
		out.write(priceArray);
	}

	/**
	 * Deserializes the fields of this object from in.
	 */
	public void readFields(DataInput in) throws IOException {
		date = in.readUTF();

		int byteSize = in.readInt();
		byte[] priceArray = new byte[byteSize];
		in.readFully(priceArray);

		price = Bytes.toBigDecimal(priceArray);
	}

	@Override
	public String toString() {
		return date + " " + price;
	}

	@Override
	public Object clone() {
		return new StockWritable(date, price);
	}

	/**
	 * The hashCode method generates a hash code for a StockWritable object. The equals and hashCode methods have been
	 * automatically generated by Eclipse by right-clicking on an empty line, selecting Source, and then selecting the
	 * Generate hashCode() and equals() option.
	 */
	@Override
	public int hashCode() {
		return date.hashCode();
	}
}


text:
import os
import re
import subprocess
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
from numpy import get_include

cwd = os.path.abspath(os.path.dirname(__file__))
cdir = os.path.join(cwd, "shenfun", "optimization", "cython")

def has_flag(compiler, flagname):
    """Return a boolean indicating whether a flag name is supported on
    the specified compiler.
    """
    devnull = open(os.devnull, "w")
    p = subprocess.Popen([compiler.compiler[0], '-E', '-'] + [flagname],
                         stdin=subprocess.PIPE, stdout=devnull, stderr=devnull)
    p.communicate("")
    return True if p.returncode == 0 else False

class build_ext_subclass(build_ext):
    def build_extensions(self):
        extra_compile_args = ['-g0']
        if os.environ.get("READTHEDOCS", None) == "True":
            extra_compile_args.append('-O0')
        else:
            extra_compile_args.append('-O3')
            if not os.environ.get('CONDA_BUILD', 0):
                for c in ['-w', '-Ofast', '-ffast-math', '-march=native']:
                    if has_flag(self.compiler, c):
                        extra_compile_args.append(c)

        for e in self.extensions:
            e.extra_compile_args += extra_compile_args
            e.include_dirs.extend([get_include()])
        build_ext.build_extensions(self)

def get_extensions():
    ext = []
    for s in ("Matvec", "la", "evaluate", "transforms"):
        ext.append(Extension("shenfun.optimization.cython.{0}".format(s),
                             libraries=['m'],
                             sources=[os.path.join(cdir, '{0}.pyx'.format(s))],
                             language="c++"))  # , define_macros=define_macros
    ext.append(Extension("shenfun.legendre.fastgl.fastgl_wrap",
                         libraries=['m'],
                         language='c++',
                         sources=[os.path.join(cwd, "shenfun", "legendre", "fastgl", "fastgl_wrap.pyx")]))
    [e.extra_link_args.extend(["-std=c++11"]) for e in ext]
    #[e.extra_link_args.extend(["-std=c++11", "-fopenmp"]) for e in ext]
    for s in ("Cheb", "convolve", "outer", "applymask", "cross"):
        ext.append(Extension("shenfun.optimization.cython.{0}".format(s),
                             libraries=['m'],
                             sources=[os.path.join(cdir, '{0}.pyx'.format(s))]))

    return ext

def version():
    srcdir = os.path.join(cwd, 'shenfun')
    with open(os.path.join(srcdir, '__init__.py')) as f:
        m = re.search(r"__version__\s*=\s*'(.*)'", f.read())
        return m.groups()[0]

with open("README.rst", "r") as fh:
    long_description = fh.read()

if __name__ == '__main__':
    setup(name="shenfun",
          version=version(),
          description="Shenfun -- Automated Spectral-Galerkin framework",
          long_description=long_description,
          author="Mikael Mortensen",
          author_email="mikaem@math.uio.no",
          url='https://github.com/spectralDNS/shenfun',
          classifiers=[
              'Development Status :: 4 - Beta',
              'Environment :: Console',
              'Intended Audience :: Developers',
              'Intended Audience :: Science/Research',
              'Intended Audience :: Education',
              'Programming Language :: Python',
              'Programming Language :: Python :: 3',
              'Programming Language :: Cython',
              'License :: OSI Approved :: BSD License',
              'Topic :: Scientific/Engineering :: Mathematics',
              'Topic :: Software Development :: Libraries :: Python Modules',
              ],
          packages=["shenfun",
                    "shenfun.optimization",
                    "shenfun.optimization.cython",
                    "shenfun.optimization.numba",
                    "shenfun.legendre",
                    "shenfun.legendre.fastgl",
                    "shenfun.laguerre",
                    "shenfun.hermite",
                    "shenfun.chebyshev",
                    "shenfun.chebyshevu",
                    "shenfun.ultraspherical",
                    "shenfun.fourier",
                    "shenfun.jacobi",
                    "shenfun.forms",
                    "shenfun.utilities",
                    "shenfun.io"
                   ],
          package_dir={"shenfun": "shenfun"},
          install_requires=["mpi4py-fft", "mpi4py", "cython", "numpy", "scipy"],
          setup_requires=["numpy>=1.9",
                          "cython>=0.25",
                          "setuptools>=18.0"],
          ext_modules=get_extensions(),
          cmdclass={"build_ext": build_ext_subclass}
         )


text:
/* global describe, it, expect */

var aja = window.aja;

describe('aja()', function(){

    //test basic module behavior
    it('should be a function', function(){
        expect(aja).to.be.a('function');
    });

    it('should return an object', function(){
        expect(aja()).to.be.an('object');
        aja().url();
    });

    describe('method', function(){

        describe('on/off/trigger', function(){

            it('should be methods', function(){
                expect(aja().on).to.be.a('function');
                expect(aja().off).to.be.a('function');
                expect(aja().trigger).to.be.a('function');
            });

            it('should register an handler', function(done){
                aja().on('foo', function(){
                    done();
                }).trigger('foo');
            });

            it('should register multiple handlers', function(done){
                var counter = 0;
                aja()
                .on('foo', function(){
                    counter++;
                })
                .on('foo', function(){
                    counter++;
                })
                .on('foo', function(){
                    expect(counter).to.equal(2);
                    done();
                })
                .trigger('foo');
            });

            it('should register multiple handlers', function(done){
                var counter = 0;
                aja()
                .on('foo', function(){
                    counter++;
                })
                .off('foo')
                .trigger('foo');
                setTimeout(function(){
                    expect(counter).to.equal(0);
                    done();
                }, 10);
            });

            it('should send parameters', function(done){
                aja()
                .on('foo', function(bar){
                    expect(bar).to.equal('bar');
                    done();
                })
                .trigger('foo', 'bar');
            });

        });

    });
});


text:
title: 'MVP Marketing + Design'
project_img_laptop: mvp-homepage-800px-min.png
project_img_phone: mvp-work-mobile-cut-min.png
project_intro_background_image: office-8-min.jpg
date: '01-09-2016 00:00'
---


text:
package de.oglimmer.game.logic.turnprocessing;

import java.util.HashSet;
import java.util.Set;

import org.atmosphere.cpr.Broadcaster;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.oglimmer.game.logic.Game;
import de.oglimmer.game.logic.board.Field;
import de.oglimmer.game.logic.unit.Unit;

public class MeleeBattle extends Battle {

	private static final Logger log = LoggerFactory.getLogger(MeleeBattle.class);

	public MeleeBattle(Game game, Set<Unit> updatedUnits) {
		super(game, updatedUnits);
	}

	public void doMeleeBattles(Broadcaster bc) {
		for (Field field : getAllBattlegrounds()) {
			Unit u1 = field.getUnit(0);
			Unit u2 = field.getUnit(1);

			log.debug("Battleground " + field + ", Unit_1:" + u1 + "/Unit_2:"
					+ u2);

			fight(u1, u2, Type.MELEE, bc);
			fight(u2, u1, Type.MELEE, bc);

		}
		processDeath();
	}

	public Set<Field> getAllBattlegrounds() {
		Set<Field> retSet = new HashSet<Field>();
		for (Field field : game.getBoard().getFields()) {
			if (field.getUnit(0) != null && field.getUnit(1) != null) {
				retSet.add(field);
			}
		}
		return retSet;
	}
}


text:
#pragma once
#include <aws/cognito-identity/CognitoIdentity_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/DateTime.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace CognitoIdentity
{
namespace Model
{

  /**
   *
Credentials for the provided identity ID.

See Also:
   AWS
   * API Reference

   */
  class AWS_COGNITOIDENTITY_API Credentials
  {
  public:
    Credentials();
    Credentials(Aws::Utils::Json::JsonView jsonValue);
    Credentials& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The Access Key portion of the credentials.

     */
    inline const Aws::String& GetAccessKeyId() const{ return m_accessKeyId; }

    /**
     *
The Access Key portion of the credentials.

     */
    inline bool AccessKeyIdHasBeenSet() const { return m_accessKeyIdHasBeenSet; }

    /**
     *
The Access Key portion of the credentials.

     */
    inline void SetAccessKeyId(const Aws::String& value) { m_accessKeyIdHasBeenSet = true; m_accessKeyId = value; }

    /**
     *
The Access Key portion of the credentials.

     */
    inline void SetAccessKeyId(Aws::String&& value) { m_accessKeyIdHasBeenSet = true; m_accessKeyId = std::move(value); }

    /**
     *
The Access Key portion of the credentials.

     */
    inline void SetAccessKeyId(const char* value) { m_accessKeyIdHasBeenSet = true; m_accessKeyId.assign(value); }

    /**
     *
The Access Key portion of the credentials.

     */
    inline Credentials& WithAccessKeyId(const Aws::String& value) { SetAccessKeyId(value); return *this;}

    /**
     *
The Access Key portion of the credentials.

     */
    inline Credentials& WithAccessKeyId(Aws::String&& value) { SetAccessKeyId(std::move(value)); return *this;}

    /**
     *
The Access Key portion of the credentials.

     */
    inline Credentials& WithAccessKeyId(const char* value) { SetAccessKeyId(value); return *this;}

    /**
     *
The Secret Access Key portion of the credentials

     */
    inline const Aws::String& GetSecretKey() const{ return m_secretKey; }

    /**
     *
The Secret Access Key portion of the credentials

     */
    inline bool SecretKeyHasBeenSet() const { return m_secretKeyHasBeenSet; }

    /**
     *
The Secret Access Key portion of the credentials

     */
    inline void SetSecretKey(const Aws::String& value) { m_secretKeyHasBeenSet = true; m_secretKey = value; }

    /**
     *
The Secret Access Key portion of the credentials

     */
    inline void SetSecretKey(Aws::String&& value) { m_secretKeyHasBeenSet = true; m_secretKey = std::move(value); }

    /**
     *
The Secret Access Key portion of the credentials

     */
    inline void SetSecretKey(const char* value) { m_secretKeyHasBeenSet = true; m_secretKey.assign(value); }

    /**
     *
The Secret Access Key portion of the credentials

     */
    inline Credentials& WithSecretKey(const Aws::String& value) { SetSecretKey(value); return *this;}

    /**
     *
The Secret Access Key portion of the credentials

     */
    inline Credentials& WithSecretKey(Aws::String&& value) { SetSecretKey(std::move(value)); return *this;}

    /**
     *
The Secret Access Key portion of the credentials

     */
    inline Credentials& WithSecretKey(const char* value) { SetSecretKey(value); return *this;}

    /**
     *
The Session Token portion of the credentials

     */
    inline const Aws::String& GetSessionToken() const{ return m_sessionToken; }

    /**
     *
The Session Token portion of the credentials

     */
    inline bool SessionTokenHasBeenSet() const { return m_sessionTokenHasBeenSet; }

    /**
     *
The Session Token portion of the credentials

     */
    inline void SetSessionToken(const Aws::String& value) { m_sessionTokenHasBeenSet = true; m_sessionToken = value; }

    /**
     *
The Session Token portion of the credentials

     */
    inline void SetSessionToken(Aws::String&& value) { m_sessionTokenHasBeenSet = true; m_sessionToken = std::move(value); }

    /**
     *
The Session Token portion of the credentials

     */
    inline void SetSessionToken(const char* value) { m_sessionTokenHasBeenSet = true; m_sessionToken.assign(value); }

    /**
     *
The Session Token portion of the credentials

     */
    inline Credentials& WithSessionToken(const Aws::String& value) { SetSessionToken(value); return *this;}

    /**
     *
The Session Token portion of the credentials

     */
    inline Credentials& WithSessionToken(Aws::String&& value) { SetSessionToken(std::move(value)); return *this;}

    /**
     *
The Session Token portion of the credentials

     */
    inline Credentials& WithSessionToken(const char* value) { SetSessionToken(value); return *this;}

    /**
     *
The date at which these credentials will expire.

     */
    inline const Aws::Utils::DateTime& GetExpiration() const{ return m_expiration; }

    /**
     *
The date at which these credentials will expire.

     */
    inline bool ExpirationHasBeenSet() const { return m_expirationHasBeenSet; }

    /**
     *
The date at which these credentials will expire.

     */
    inline void SetExpiration(const Aws::Utils::DateTime& value) { m_expirationHasBeenSet = true; m_expiration = value; }

    /**
     *
The date at which these credentials will expire.

     */
    inline void SetExpiration(Aws::Utils::DateTime&& value) { m_expirationHasBeenSet = true; m_expiration = std::move(value); }

    /**
     *
The date at which these credentials will expire.

     */
    inline Credentials& WithExpiration(const Aws::Utils::DateTime& value) { SetExpiration(value); return *this;}

    /**
     *
The date at which these credentials will expire.

     */
    inline Credentials& WithExpiration(Aws::Utils::DateTime&& value) { SetExpiration(std::move(value)); return *this;}

  private:

    Aws::String m_accessKeyId;
    bool m_accessKeyIdHasBeenSet;

    Aws::String m_secretKey;
    bool m_secretKeyHasBeenSet;

    Aws::String m_sessionToken;
    bool m_sessionTokenHasBeenSet;

    Aws::Utils::DateTime m_expiration;
    bool m_expirationHasBeenSet;
  };

} // namespace Model
} // namespace CognitoIdentity
} // namespace Aws


text:
package vgrechka.phizdetsidea.phizdets.testing.tox;

import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.ConfigurationType;
import icons.PhizdetsIcons;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

/**
 * @author Ilya.Kazakevich
 */
public class PyToxConfigurationType implements ConfigurationType {

  public static final String ID = "Tox";
  public static final ConfigurationType INSTANCE = new PyToxConfigurationType();

  @Override
  public ConfigurationFactory[] getConfigurationFactories() {
    return new ConfigurationFactory[]{new PyToxConfigurationFactory(this)};
  }

  @Override
  public String getDisplayName() {
    return ID;
  }

  @Override
  public String getConfigurationTypeDescription() {
    return "Tox runner";
  }

  @Override
  public Icon getIcon() {
    return PhizdetsIcons.Phizdets.PhizdetsTests;
  }

  @NotNull
  @Override
  public String getId() {
    return ID;
  }
}


text:
import add from './add.js';
import reduce from './reduce.js';

/**
 * Adds together all the elements of a list.
 *
 * @func
 * @memberOf R
 * @since v0.1.0
 * @category Math
 * @sig [Number] -> Number
 * @param {Array} list An array of numbers
 * @return {Number} The sum of all the numbers in the list.
 * @see R.reduce
 * @example
 *
 *      R.sum([2,4,6,8,100,1]); //=> 121
 */
var sum = reduce(add, 0);
export default sum;


text:
const dice = require("./dice.js");

var exports = module.exports = {};

exports.attack = function (character) {
	var response = character.name + " attacks with ";
	if (character.gender === "Female") {
		response += "her ";
	} else if (character.gender === "Male") {
		response += "his ";
	} else {
		response += "their ";
	}

	response += character.weapons[0].name + ":\n";

	var attackBonus = parseInt(character.bab) + parseInt(character.weapons[0].hitbonus);

	if (this.hasFeat(character, "weapon finesse") && character.weapons[0].special.indexOf("Light") !== -1) {
		attackBonus += this.getAbilityModifier(character.abilities.dexterity);
	} else {
		attackBonus += this.getAbilityModifier(character.abilities.strength);
	}

	var damageBonus = this.getAbilityModifier(character.abilities.strength);

	response += "Attack roll: ";
	var attackRoll;

	if (attackBonus >= 0) {
		attackRoll = dice.parseRoll("1d20 + " + attackBonus);
	} else {
		attackRoll = dice.parseRoll("1d20 - " + attackBonus);
	}

	console.log("attackRoll = " + attackRoll);

	response += dice.formatRoll(attackRoll) + "\n";

	response += "Damage roll: ";

	var damageRoll;

	if (damageBonus >= 0) {
		damageRoll = dice.parseRoll(character.weapons[0].damage + " + " + damageBonus);
	} else {
		damageRoll = dice.parseRoll(character.weapons[0].damage + " - " + damageBonus);
	}

	response += dice.formatRoll(damageRoll);

	return response;
};

exports.getAC = function (character) {
	return 10 + this.getAbilityModifier(character.abilities.dexterity) + character.armour.bonus;
};

exports.getAbilityModifier = function (ability) {
	return Math.floor((ability - 10) / 2);
};

exports.hasFeat = function (character, feat) {
	console.log("Looking for feat " + feat);
	for (var i = 0; i < character.feats.length; i++) {
		console.log("Checking feat " + character.feats[i]);
		if (character.feats[i].toLowerCase() === feat.toLowerCase()) {
			return true;
		}
	}

	return false;
}

exports.skillCheck = function (character, skill) {
	var normSkill = skill.toLowerCase();

	console.log("Checking skill: " + normSkill);

	if (typeof character.skills[normSkill] != 'undefined') {
		return dice.parseRoll("1d20 + " + character.skills[normSkill]);
	}
}

exports.savingThrow = function (character, save) {
	var normSave = save.toLowerCase();

	console.log("Rolling saving throw: " + normSave);

	if (typeof character.saves[normSave] != 'undefined') {
		return dice.parseRoll("1d20 + " + character.saves[normSave]);
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<notification>
  <type>webhook</type>
  <details>
    <url>https://systems.example.org/new_alert</url>
  </details>
</notification>


text:
/*************************************************************************/
/*
 * GeekOS master source distribution and/or project solution
 * Copyright (c) 2001,2003,2004 David H. Hovemeyer <daveho@cs.umd.edu>
 * Copyright (c) 2003 Jeffrey K. Hollingsworth <hollings@cs.umd.edu>
 *
 * This file is not distributed under the standard GeekOS license.
 * Publication or redistribution of this file without permission of
 * the author(s) is prohibited.
 */
/*************************************************************************/
/*
 * Signals
 * Copyright (c) 2005, Michael Hicks <mwh@cs.umd.edu>
 * $Rev$
 *
 * This is free software.  You are permitted to use,
 * redistribute, and modify it as specified in the file "COPYING".
 */

#include <geekos/syscall.h>
#include <geekos/signal.h>
#include <fmtout.h>
#include <process.h>
#include <conio.h>

/* System call wrappers */
DEF_SYSCALL(Kill,SYS_KILL,int,(int pid, int sig),int arg0 = pid; int arg1 = sig;,SYSCALL_REGS_2)
DEF_SYSCALL(Signal,SYS_SIGNAL,int,(signal_handler h,int sig),signal_handler arg0 = h; int arg1 = sig;,SYSCALL_REGS_2)
DEF_SYSCALL(RegDeliver,SYS_REGDELIVER,int,(void (*deliver)(void),signal_handler def, signal_handler ign),void (*arg0)(void) = deliver; signal_handler arg1 = def; signal_handler arg2 = ign;,SYSCALL_REGS_3)

/* Trampoline for completing a signal handler
*/
extern void Return_Signal(void);

/* Called when the process has not set a different handler; terminates
   the process. */
static void Def_Handler(void) {
	Print("Terminated.\n");
	Exit(1);
}

static void Ign_Handler(void) {
	Print("Ign_Handler\n");
	//*((ulong_t *)0x7fffef80) = Return_Signal;
	//Print("%x, %x\n", 0x7fffef80, *((ulong_t *)0x7fffef80));
	#if 0
	int addr = 0;
	Print("%x : %x, %x : %x \n", &addr, *(&addr), &addr+1, *(&addr + 1));
	Print("%x : %x, %x : %x \n", &addr+2, *(&addr + 2), &addr+3, *(&addr + 3));
	Print("%x : %x, %x : %x \n", &addr+4, *(&addr + 4), &addr+5, *(&addr + 5));
	#endif
	return;
}

void Def_Child_Handler(void) {
	int status;
	while (WaitNoPID(&status) >= 0);
	return;
}

/* Should be called when the program starts up */
int Sig_Init(void) {
 	return RegDeliver(Return_Signal,Def_Handler,Ign_Handler);
}