text:
#include "envoy/http/codec.h"
#include "envoy/registry/registry.h"

#include "common/common/assert.h"
#include "common/common/logger.h"
#include "common/http/http3/quic_codec_factory.h"
#include "common/http/http3/well_known_names.h"

#include "extensions/quic_listeners/quiche/envoy_quic_client_session.h"
#include "extensions/quic_listeners/quiche/envoy_quic_server_session.h"

namespace Envoy {
namespace Quic {

// QuicHttpConnectionImplBase instance is a thin QUIC codec just providing quic interface to HCM.
// Owned by HCM and created during onNewConnection() if the network connection
// is a QUIC connection.
class QuicHttpConnectionImplBase : public virtual Http::Connection,
                                   protected Logger::Loggable<Logger::Id::quic> {
public:
  QuicHttpConnectionImplBase(QuicFilterManagerConnectionImpl& quic_session)
      : quic_session_(quic_session) {}

  // Http::Connection
  Http::Status dispatch(Buffer::Instance& /*data*/) override {
    // Bypassed. QUIC connection already hands all data to streams.
    NOT_REACHED_GCOVR_EXCL_LINE;
  }
  Http::Protocol protocol() override { return Http::Protocol::Http3; }
  // Returns true if the session has data to send but queued in connection or
  // stream send buffer.
  bool wantsToWrite() override;

  void runWatermarkCallbacksForEachStream(
      quic::QuicSmallMap<quic::QuicStreamId, std::unique_ptr<quic::QuicStream>, 10>& stream_map,
      bool high_watermark);

protected:
  QuicFilterManagerConnectionImpl& quic_session_;
};

class QuicHttpServerConnectionImpl : public QuicHttpConnectionImplBase,
                                     public Http::ServerConnection {
public:
  QuicHttpServerConnectionImpl(EnvoyQuicServerSession& quic_session,
                               Http::ServerConnectionCallbacks& callbacks);

  // Http::Connection
  void goAway() override;
  void shutdownNotice() override {
    // TODO(danzh): Add double-GOAWAY support in QUIC.
    ENVOY_CONN_LOG(error, "Shutdown notice is not propagated to QUIC.", quic_server_session_);
  }
  void onUnderlyingConnectionAboveWriteBufferHighWatermark() override;
  void onUnderlyingConnectionBelowWriteBufferLowWatermark() override;

private:
  EnvoyQuicServerSession& quic_server_session_;
};

class QuicHttpClientConnectionImpl : public QuicHttpConnectionImplBase,
                                     public Http::ClientConnection {
public:
  QuicHttpClientConnectionImpl(EnvoyQuicClientSession& session,
                               Http::ConnectionCallbacks& callbacks);

  // Http::ClientConnection
  Http::RequestEncoder& newStream(Http::ResponseDecoder& response_decoder) override;

  // Http::Connection
  void goAway() override { NOT_REACHED_GCOVR_EXCL_LINE; }
  void shutdownNotice() override { NOT_REACHED_GCOVR_EXCL_LINE; }
  void onUnderlyingConnectionAboveWriteBufferHighWatermark() override;
  void onUnderlyingConnectionBelowWriteBufferLowWatermark() override;

private:
  EnvoyQuicClientSession& quic_client_session_;
};

// A factory to create QuicHttpClientConnection.
class QuicHttpClientConnectionFactoryImpl : public Http::QuicHttpClientConnectionFactory {
public:
  std::unique_ptr<Http::ClientConnection>
  createQuicClientConnection(Network::Connection& connection,
                             Http::ConnectionCallbacks& callbacks) override;

  std::string name() const override { return Http::QuicCodecNames::get().Quiche; }
};

// A factory to create QuicHttpServerConnection.
class QuicHttpServerConnectionFactoryImpl : public Http::QuicHttpServerConnectionFactory {
public:
  std::unique_ptr<Http::ServerConnection>
  createQuicServerConnection(Network::Connection& connection,
                             Http::ConnectionCallbacks& callbacks) override;

  std::string name() const override { return Http::QuicCodecNames::get().Quiche; }
};

DECLARE_FACTORY(QuicHttpClientConnectionFactoryImpl);
DECLARE_FACTORY(QuicHttpServerConnectionFactoryImpl);

} // namespace Quic
} // namespace Envoy


text:
BuildingData::BuildingData()
{

}

void BuildingData::removeBuilding(const Building & b)
{
    const auto & building = std::find(_buildings.begin(), _buildings.end(), b);

    if (building != _buildings.end())
    {
        _buildings.erase(building);
    }
}

std::vector<Building> & BuildingData::getBuildings()
{
    return _buildings;
}

void BuildingData::addBuilding(const Building & b)
{
    _buildings.push_back(b);
}

bool BuildingData::isBeingBuilt(UnitType type)
{
    for (auto & b : _buildings)
    {
        if (b.type == type)
        {
            return true;
        }
    }

    return false;
}

void BuildingData::removeBuildings(const std::vector<Building> & buildings)
{
    for (const auto & b : buildings)
    {
        removeBuilding(b);
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Web.Mvc;
using Bonfire.Analytics.XdbPeek.Models;
using Bonfire.Analytics.XdbPeek.Repositories;

namespace Bonfire.Analytics.XdbPeek.Controllers
{
    public class XdbPeekController : Controller
    {
        public XdbPeekController()
        {
        }

        public ActionResult Details()
        {
            var model = new TrackerDto();
            try
            {
                var contactRepository = new ContactRepository(DependencyResolver.Current.GetService<IServiceProvider>());
                model = contactRepository.GetTrackerDto();
                return View(model);
            }
            catch
            {
                return View(model);
            }
        }
    }
}


text:
/**
 * Created by xz_liu on 2016/3/9.
 */
var app = angular.module('mobile', ['ngRoute', 'ngCookies']);

app.config(function ($routeProvider) {
    $routeProvider
        .when('/home', {
            controller: 'Home',
            templateUrl: 'pages/home.html'
        })
        .when('/category', {
            controller: 'Category',
            templateUrl: 'pages/category.html'
        })
        .when('/goods/:category', {
            controller: 'Goods',
            templateUrl: 'pages/goods.html'
        })
        .when('/cart', {
            controller: 'Cart',
            templateUrl: 'pages/cart.html'
        })
        .when('/account',{
            controller: 'Account',
            templateUrl: 'pages/account.html'
        })
        .otherwise({
            redirectTo: '/home'
        });
});


text:
package org.apache.hadoop.mapred.lib.aggregate;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;

/**
 * This class implements a value aggregator that dedupes a sequence of objects.
 *
 */
public class UniqValueCount implements ValueAggregator {

	private TreeMap<Object, Object> uniqItems = null;

	private long numItems = 0;

	private long maxNumItems = Long.MAX_VALUE;

	/**
	 * the default constructor
	 *
	 */
	public UniqValueCount() {
		this(Long.MAX_VALUE);
	}

	/**
	 * constructor
	 *
	 * @param maxNum
	 *            the limit in the number of unique values to keep.
	 *
	 */
	public UniqValueCount(long maxNum) {
		uniqItems = new TreeMap<Object, Object>();
		this.numItems = 0;
		maxNumItems = Long.MAX_VALUE;
		if (maxNum > 0) {
			this.maxNumItems = maxNum;
		}
	}

	/**
	 * Set the limit on the number of unique values
	 *
	 * @param n
	 *            the desired limit on the number of unique values
	 * @return the new limit on the number of unique values
	 */
	public long setMaxItems(long n) {
		if (n >= numItems) {
			this.maxNumItems = n;
		} else if (this.maxNumItems >= this.numItems) {
			this.maxNumItems = this.numItems;
		}
		return this.maxNumItems;
	}

	/**
	 * add a value to the aggregator
	 *
	 * @param val
	 *            an object.
	 *
	 */
	public void addNextValue(Object val) {
		if (this.numItems <= this.maxNumItems) {
			uniqItems.put(val.toString(), "1");
			this.numItems = this.uniqItems.size();
		}
	}

	/**
	 * @return return the number of unique objects aggregated
	 */
	public String getReport() {
		return "" + uniqItems.size();
	}

	/**
	 *
	 * @return the set of the unique objects
	 */
	public Set getUniqueItems() {
		return uniqItems.keySet();
	}

	/**
	 * reset the aggregator
	 */
	public void reset() {
		uniqItems = new TreeMap<Object, Object>();
	}

	/**
	 * @return return an array of the unique objects. The return value is
	 *         expected to be used by the a combiner.
	 */
	public ArrayList getCombinerOutput() {
		Object key = null;
		Iterator iter = uniqItems.keySet().iterator();
		ArrayList<Object> retv = new ArrayList<Object>();

		while (iter.hasNext()) {
			key = iter.next();
			retv.add(key);
		}
		return retv;
	}
}


text:
import { IParallelEnumerable, TypedData } from "../../types"
import { BasicParallelEnumerable } from "../BasicParallelEnumerable"
import { nextIterationAsync } from "./_nextIterationAsync"

export const eachAsync = <TSource>(
    source: IParallelEnumerable<TSource>,
    action: (x: TSource) => Promise<void>): IParallelEnumerable<TSource> => {

    const dataFunc: TypedData<TSource> = nextIterationAsync(source, async (x) => {
            await action(x)
            return x
    })

    return new BasicParallelEnumerable(dataFunc)
}


text:
<?php

/** @noinspection PhpComposerExtensionStubsInspection */

declare(strict_types=1);

namespace OpenTelemetry\Contrib\Grpc;

use function array_change_key_case;
use BadMethodCallException;
use Grpc\Call;
use Grpc\Channel;
use const Grpc\OP_RECV_INITIAL_METADATA;
use const Grpc\OP_RECV_MESSAGE;
use const Grpc\OP_RECV_STATUS_ON_CLIENT;
use const Grpc\OP_SEND_CLOSE_FROM_CLIENT;
use const Grpc\OP_SEND_INITIAL_METADATA;
use const Grpc\OP_SEND_MESSAGE;
use const Grpc\STATUS_OK;
use Grpc\Timeval;
use OpenTelemetry\SDK\Common\Export\TransportInterface;
use OpenTelemetry\SDK\Common\Future\CancellationInterface;
use OpenTelemetry\SDK\Common\Future\CompletedFuture;
use OpenTelemetry\SDK\Common\Future\ErrorFuture;
use OpenTelemetry\SDK\Common\Future\FutureInterface;
use OpenTelemetry\SDK\Common\Future\NullCancellation;
use RuntimeException;
use Throwable;

/**
 * @internal
 *
 * @template-implements TransportInterface<"application/x-protobuf">
 */
final class GrpcTransport implements TransportInterface
{
    private array $metadata;
    private Channel $channel;
    private string $method;
    private bool $closed = false;

    public function __construct(
        string $endpoint,
        array $opts,
        string $method,
        array $headers = []
    ) {
        $this->channel = new Channel($endpoint, $opts);
        $this->method = $method;
        $this->metadata = $this->formatMetadata(array_change_key_case($headers));
    }

    public function contentType(): string
    {
        return 'application/x-protobuf';
    }

    public function send(string $payload, ?CancellationInterface $cancellation = null): FutureInterface
    {
        if ($this->closed) {
            return new ErrorFuture(new BadMethodCallException('Transport closed'));
        }

        $call = new Call($this->channel, $this->method, Timeval::infFuture());

        $cancellation ??= new NullCancellation();
        $cancellationId = $cancellation->subscribe(static fn (Throwable $e) => $call->cancel());

        try {
            $event = $call->startBatch([
                OP_SEND_INITIAL_METADATA => $this->metadata,
                OP_SEND_MESSAGE => ['message' => $payload],
                OP_SEND_CLOSE_FROM_CLIENT => true,
                OP_RECV_INITIAL_METADATA => true,
                OP_RECV_STATUS_ON_CLIENT => true,
                OP_RECV_MESSAGE => true,
            ]);
        } catch (Throwable $e) {
            return new ErrorFuture($e);
        } finally {
            $cancellation->unsubscribe($cancellationId);
        }

        if ($event->status->code === STATUS_OK) {
            return new CompletedFuture($event->message);
        }

        return new ErrorFuture(new RuntimeException($event->status->details, $event->status->code));
    }

    public function shutdown(?CancellationInterface $cancellation = null): bool
    {
        if ($this->closed) {
            return false;
        }

        $this->closed = true;
        $this->channel->close();

        return true;
    }

    public function forceFlush(?CancellationInterface $cancellation = null): bool
    {
        return !$this->closed;
    }

    /**
     * @link https://github.com/grpc/grpc/blob/7e7a48f863218f39a1767e1c2b957ca8e4789272/src/php/tests/interop/interop_client.php#L525
     */
    private function formatMetadata(array $metadata): array
    {
        return array_map(fn ($value) => is_array($value) ? $value : [$value], $metadata);
    }
}


text:
//The MIT License
//
//Copyright(C) 2017 Roman Nix
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files(the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions :
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.

#pragma once

#include "GameFramework/Actor.h"
#include "DrawDebugHelpers.h"
#include "Runtime/Engine/Classes/Engine/World.h"
#include "Runtime/Engine/Classes/Components/BoxComponent.h"
#include "SpiderNavGridTracer.h"
#include "SpiderNavPoint.h"
#include "SpiderNavPointEdge.h"
#include "SpiderNavGridSaveGame.h"
#include "Kismet/GameplayStatics.h"
#include "SpiderNavGridBuilder.generated.h"

DECLARE_LOG_CATEGORY_EXTERN(SpiderNAVGRID_LOG, Log, All);

/** Provides settings to configure navigation builder. Builds navigation grid with relations, which can be saved to file */
UCLASS()
class ASpiderNavGridBuilder : public AActor
{
	GENERATED_BODY()

public:
	// Sets default values for this actor's properties
	ASpiderNavGridBuilder();

    /** Volume where to build navigation */
	UPROPERTY(VisibleAnywhere, Category="SpiderNavGridBuilder")
		UBoxComponent* VolumeBox;

	/** For debug. Blueprint class which will be used to spawn actors on scene in specified volume */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SpiderNavGridBuilder")
		TSubclassOf<ASpiderNavGridTracer> TracerActorBP;

	/** For debug. Blueprint class which will be used to spawn Navigation Points */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SpiderNavGridBuilder")
		TSubclassOf<ASpiderNavPoint> NavPointActorBP;

	/** For debug. Blueprint class which will be used to spawn Navigation Points on egdes when checking possible neightbors */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SpiderNavGridBuilder")
		TSubclassOf<ASpiderNavPointEdge> NavPointEdgeActorBP;

	/** The minimum distance between tracers to fill up scene */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SpiderNavGridBuilder")
	float GridStepSize;

	/** The list of actors which could have navigation points on them */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SpiderNavGridBuilder")
	TArray<AActor*> ActorsWhiteList;

	/** Whether to use ActorsWhiteList */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SpiderNavGridBuilder")
	bool bUseActorWhiteList;

	/** The list of actors which COULD NOT have navigation points on them */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SpiderNavGridBuilder")
	TArray<AActor*> ActorsBlackList;

	/** Whether to use ActorsBlackList */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SpiderNavGridBuilder")
	bool bUseActorBlackList;

	/** For debug. If false then all tracers remain on the scene after grid rebuild */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SpiderNavGridBuilder")
	bool bAutoRemoveTracers;

	/** Whether to save the navigation grid after rebuild */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SpiderNavGridBuilder")
	bool bAutoSaveGrid;

	/** How far put navigation point from a WorldStatic face */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SpiderNavGridBuilder")
	float BounceNavDistance;

	/** How far to trace from tracers. Multiplier of GridStepSize */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SpiderNavGridBuilder")
	float TraceDistanceModificator;

	/** How close navigation points can be to each other. Multiplier of GridStepSize */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SpiderNavGridBuilder")
	float ClosePointsFilterModificator;

	/** The radius of a sphere to find neighbors of each NavPoint. Multiplier of GridStepSize */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SpiderNavGridBuilder")
	float ConnectionSphereRadiusModificator;

	/** How far to trace from each NavPoint to find intersection through egdes of possible neightbors. Multiplier of GridStepSize */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SpiderNavGridBuilder")
	float TraceDistanceForEdgesModificator;

	/** How far can be one trace line from other trace line near the point of intersection when checking possible neightbors. Multiplier of GridStepSize */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SpiderNavGridBuilder")
	float EgdeDeviationModificator;

    /** Whether should try to remove tracers enclosed in volumes */
	//UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SpiderNavGridBuilder")
    bool bShouldTryToRemoveTracersEnclosedInVolumes;

    /** Distance threshold to remove tracers enclosed in volumes  */
	//UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SpiderNavGridBuilder")
    float TracersInVolumesCheckDistance;

protected:
	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

	TArray<ASpiderNavGridTracer*> Tracers;
	TArray<ASpiderNavPoint*> NavPoints;

	TArray<FVector> NavPointsLocations;
	TMap<int32, FVector> NavPointsNormals;

	void TraceFromAllTracers();

	void RemoveTracersClosedInVolumes();

	void AddNavPointByHitResult(FHitResult RV_Hit);

	void SpawnNavPoints();

	void BuildRelations();

	bool CheckNavPointsVisibility(ASpiderNavPoint* NavPoint1, ASpiderNavPoint* NavPoint2);

	bool CheckNavPointCanSeeLocation(ASpiderNavPoint* NavPoint, FVector Location);

	void BuildPossibleEdgeRelations();

	void RemoveNoConnected();

	void RemoveAllNavPoints();

	void EmptyAll();

	bool GetLineLineIntersection(FVector Start0, FVector End0, FVector Start1, FVector End1, FVector& Intersection);

	void CheckAndAddIntersectionNavPointEdge(FVector Intersection, ASpiderNavPoint* NavPoint1, ASpiderNavPoint* NavPoint2);

	float Dmnop(const TMap<int32, FVector> *v, int32 m, int32 n, int32 o, int32 p);

	void RemoveAllTracers();

	void SpawnTracers();

	int32 GetNavPointIndex(ASpiderNavPoint* NavPoint);

	float DebugThickness;

public:
	// Called every frame
	virtual void Tick(float DeltaTime) override;

    /** Builds navigation grid. Returs number of navigations points */
	UFUNCTION(BlueprintCallable, Category = "SpiderNavGridBuilder")
	int32 BuildGrid();

    /** Draws debug lines between connected navigation points */
	UFUNCTION(BlueprintCallable, Category = "SpiderNavGridBuilder")
	void DrawDebugRelations();

    /** Saves navigation grid to save file */
	UFUNCTION(BlueprintCallable, Category = "SpiderNavGridBuilder")
	void SaveGrid();
};


text:
import { CHANGE_DEMO } from './actionTypes';

export const changeDemo = (url) => {
    return {
        type: CHANGE_DEMO,
        url
    }
}


text:
// (C) Copyright 2006 Douglas Gregor <doug.gregor -at- gmail.com>

// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

//  Authors: Douglas Gregor

/** @file status.cpp
 *
 *  This file reflects the Boost.MPI @c status class into
 *  Python.
 */
#include <boost/python.hpp>
#include <boost/mpi.hpp>

using namespace boost::python;
using namespace boost::mpi;

namespace boost { namespace mpi { namespace python {

extern const char* status_docstring;
extern const char* status_source_docstring;
extern const char* status_tag_docstring;
extern const char* status_error_docstring;
extern const char* status_cancelled_docstring;

void export_status()
{
  using boost::python::arg;
  using boost::python::object;

  class_<status>("Status", status_docstring, no_init)
    .add_property("source", &status::source, status_source_docstring)
    .add_property("tag", &status::tag, status_tag_docstring)
    .add_property("error", &status::error, status_error_docstring)
    .add_property("cancelled", &status::cancelled, status_cancelled_docstring)
    ;
}

} } } // end namespace boost::mpi::python


text:
    log("11. Verifier is verifying proof from Prover")
    const verified = await indy.verifierVerifyProof(proofRequest, proof, schemas, credentialDefs, revocRegs, revRegs)

    logValue("Proof :")
    logValue(". Name="+proof['requested_proof']['revealed_attrs']['attr1_referent']['raw'])
    logValue(". Verified="+verified)

    // 12
    log("12. Closing both wallet_handles")
    await indy.closeWallet(issuerWalletHandle)
    await indy.closeWallet(proverWalletHandle)

    // 13
    log("13. Deleting created wallet_handles")
    await indy.deleteWallet(proverWalletName, proverWalletCredentials)
    await indy.deleteWallet(issuerWalletName, issuerWalletCredentials)


text:
package com.qloppy.qrscan.sample;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;

public class MainActivity extends ActionBarActivity {
    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);
        setContentView(R.layout.activity_main);
    }

    public void launchSimpleActivity(View v) {
        Intent intent = new Intent(this, SimpleScannerActivity.class);
        startActivity(intent);
    }

    public void launchSimpleFragmentActivity(View v) {
        Intent intent = new Intent(this, SimpleScannerFragmentActivity.class);
        startActivity(intent);
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ml.alternet.parser.visit Class Hierarchy (Alternet Libs 1.0 API)</title>
<meta name="date" content="2020-01-18">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package ml.alternet.parser.visit

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

ml.alternet.parser.visit.LogVisitor (implements ml.alternet.parser.visit.Visitor)

ml.alternet.parser.visit.Transform (implements java.util.function.Function<T,R>, ml.alternet.parser.visit.Visitor)

ml.alternet.parser.visit.TransformTrackingHost (implements ml.alternet.parser.visit.Visitor)

ml.alternet.parser.visit.Traverse (implements java.util.function.Consumer<T>, ml.alternet.parser.visit.Visitor)

ml.alternet.parser.visit.Dump (implements java.util.function.Supplier<T>, ml.alternet.parser.visit.Visitor)

Interface Hierarchy

ml.alternet.parser.util.ComposedRule<T>

ml.alternet.parser.visit.TraversableRule.CombinedRule (also extends ml.alternet.parser.visit.TraversableRule)

ml.alternet.parser.visit.TraversableRule.SimpleRule (also extends ml.alternet.parser.visit.TraversableRule)

ml.alternet.parser.visit.TraversableRule

ml.alternet.parser.visit.TraversableRule.CombinedRule (also extends ml.alternet.parser.util.ComposedRule<T>)

ml.alternet.parser.visit.TraversableRule.SimpleRule (also extends ml.alternet.parser.util.ComposedRule<T>)

ml.alternet.parser.visit.TraversableRule.StandaloneRule

ml.alternet.parser.visit.Visitor

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2020 Alternet. All rights reserved.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using OneDream.Models;

namespace OneDream.DAL
{
    public class AreaDAL : BaseDAL
    {
        /*
        public IList<OD_Province> GetAllProvince()
        {
            var list = entityInstance.OD_Province.OrderBy(m => m.Sort).ToList();
            return list;
        }
         * */

        public IList<KeyValuePairModel> GetAllProvince()
        {
            var list = entityInstance.OD_Province.OrderBy(m => m.Sort).Select(m => new KeyValuePairModel() { Key = m.ProvinceID, Value = m.ProvinceName }).ToList();
            return list;
        }

        public IList<OD_City> GetCityListByProvinceID(int pid)
        {
            var list = entityInstance.OD_City as IQueryable<OD_City>;
            if (pid != 0)
            {
                list = list.Where(m => m.ProvinceID == pid);
            }
            return list.ToList();
        }

        public IList<OD_District> GetDistrictListByCityID(int cid)
        {
            var list = entityInstance.OD_District as IQueryable<OD_District>;
            if (cid != 0)
            {
                list = list.Where(m => m.CityID == cid);
            }
            return list.ToList();
        }

    }
}


text:
 package com.indeed.lsmtree.core;

import com.google.common.base.Throwables;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.Maps;
import com.indeed.util.serialization.IntSerializer;
import com.indeed.util.serialization.LongSerializer;
import com.indeed.util.serialization.StringSerializer;
import junit.framework.TestCase;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author jplaisance
 */
public final class TestImmutableBTreeIndex extends TestCase {

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

    private static final int SMALL_TREE_SIZE = 1000;
    private static final int LARGE_TREE_SIZE = 100000000;

    File tmpDir;

    int treeSize = SMALL_TREE_SIZE;

    @Override
    public void setUp() throws Exception {
        tmpDir = File.createTempFile("tmp", "", new File("."));
        tmpDir.delete();
        tmpDir.mkdirs();
        String treeSizeStr = System.getProperty("lsmtree.test.size");
        treeSize = "large".equals(treeSizeStr) ? LARGE_TREE_SIZE : SMALL_TREE_SIZE;
    }

    @Override
    public void tearDown() throws Exception {
        FileUtils.deleteDirectory(tmpDir);
    }

    public int[] createTree() throws IOException, InstantiationException, IllegalAccessException {
        Random r = new Random(0);
        final int[] ints = new int[treeSize];
        int previous = 0;
        for (int i = 0; i < ints.length; i++) {
            ints[i] = previous+r.nextInt(10)+1;
            previous = ints[i];
        }
        Iterator<Generation.Entry<Integer, Long>> iterator = new Iterator<Generation.Entry<Integer, Long>>() {

            int index = 0;

            @Override
            public boolean hasNext() {
                return index < ints.length;
            }

            @Override
            public Generation.Entry<Integer, Long> next() {
                int ret = ints[index];
                index++;
                return Generation.Entry.create(ret, (long) ret);
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
        ImmutableBTreeIndex.Writer.write(tmpDir, iterator, new IntSerializer(), new LongSerializer(), 65536, false);
        return ints;
    }

    public void testSequential() throws Exception {
        int[] ints = createTree();
        ImmutableBTreeIndex.Reader<Integer, Long> reader = new ImmutableBTreeIndex.Reader(tmpDir, new IntSerializer(), new LongSerializer(), false);
        Iterator<Generation.Entry<Integer, Long>> iterator = reader.iterator();
        int index = 0;
        while (iterator.hasNext()) {
            Generation.Entry<Integer, Long> next = iterator.next();
            assertTrue(next.getKey() == ints[index]);
            assertTrue(next.getValue() == ints[index]);
            index++;
        }
        assertTrue(index == ints.length);
        for (final int i : ints) {
            Generation.Entry<Integer, Long> entry = reader.get(i);
            assertNotNull(entry);
            assertTrue(entry.getKey() == i);
            assertTrue(entry.getValue() == i);
            assertTrue(reader.get(i).getValue() == i);
        }
        assertNull(reader.get(ints[ints.length - 1] + 1));
    }

    public void testRandom() throws Exception {
        final int[] ints = createTree();
        final ImmutableBTreeIndex.Reader<Integer, Long> reader = new ImmutableBTreeIndex.Reader(tmpDir, new IntSerializer(), new LongSerializer(), false);
        final int max = ints[ints.length-1];
        final AtomicInteger done = new AtomicInteger(8);
        for (int i = 0; i < 8; i++) {
            final int index = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        final Random r = new Random(index);
                        for (int i = 0; i < treeSize; i++) {
                            int rand = r.nextInt(max+1);
                            int insertionindex = Arrays.binarySearch(ints, rand);
                            final Iterator<Generation.Entry<Integer, Long>> iterator = reader.iterator(rand, true);
                            try {
                                assertTrue(iterator.hasNext());
                            } catch (Throwable t) {
                                System.err.println("rand: "+rand);
                                throw Throwables.propagate(t);
                            }
                            Generation.Entry<Integer, Long> entry = iterator.next();
                            assertTrue("entry: "+entry+" rand: "+rand, entry.getKey() >= rand);
                            assertTrue(entry.getKey().longValue() == entry.getValue());
                            if (insertionindex >= 0) {
                                assertTrue(rand == ints[insertionindex]);
                                assertTrue(entry.getKey() == rand);
                                Generation.Entry<Integer, Long> result = reader.get(rand);
                                assertTrue(result.getValue() == rand);
                            } else {
                                if (insertionindex != -1) assertTrue(ints[(~insertionindex)-1] < rand);
                                assertTrue("insertionindex: "+insertionindex+" entry: "+entry+" ints[!insertionindex]"+ints[~insertionindex], ints[~insertionindex] == entry.getKey());
                                Generation.Entry<Integer, Long> result = reader.get(rand);
                                assertTrue(result == null);
                            }
                        }
                    } finally {
                        done.decrementAndGet();
                    }
                }
            }).start();
        }
        while (done.get() > 0) {
            Thread.yield();
        }
        reader.close();
    }

    public void testGaps() throws Exception {
        int[] ints = createTree();
        ImmutableBTreeIndex.Reader<Integer, Long> reader = new ImmutableBTreeIndex.Reader(tmpDir, new IntSerializer(), new LongSerializer(), false);
        int index = 0;
        for (int i = 0; i <= ints[ints.length-1]; i++) {
            int current = ints[index];
            if (i > current) {
                index++;
                current = ints[index];
            }
            Generation.Entry<Integer, Long> result = reader.get(i);
            if (i < current) {
                assertTrue(result == null);
            } else {
                assertTrue(result.getValue() == i);
            }
            Iterator<Generation.Entry<Integer, Long>> iterator = reader.iterator(i, true);
            assertTrue(iterator.hasNext());
            Generation.Entry<Integer, Long> entry = iterator.next();
            assertTrue(entry.getKey() == current);
            assertTrue(entry.getValue() == current);
        }
    }

    public void testSeekPrevious() throws Exception {
        final int[] ints = createTree();
        final ImmutableBTreeIndex.Reader<Integer, Long> reader = new ImmutableBTreeIndex.Reader(tmpDir, new IntSerializer(), new LongSerializer(), false);
        final int max = ints[ints.length-1];
        final AtomicInteger done = new AtomicInteger(8);
        for (int i = 0; i < 8; i++) {
            final int index = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        final Random r = new Random(index);
                        for (int i = 0; i < treeSize; i++) {
                            int rand = r.nextInt(max+10);
                            int insertionindex = Arrays.binarySearch(ints, rand);
                            final Iterator<Generation.Entry<Integer, Long>> iterator = reader.reverseIterator(rand, true);
                            final boolean hasPrevious = iterator.hasNext();
                            Generation.Entry<Integer, Long> entry = null;
                            assertEquals("rand: "+rand+" hasPrevious: "+hasPrevious+(hasPrevious ? " previous: "+(entry = iterator.next()) : ""), hasPrevious, insertionindex != -1);
                            if (hasPrevious) {
                                if (entry == null) entry = iterator.next();
                                assertTrue(entry.getKey() <= rand);
                                assertTrue(entry.getKey().longValue() == entry.getValue());
                            }
                            if (insertionindex >= 0) {
                                if (entry == null) entry = iterator.next();
                                assertTrue(rand == ints[insertionindex]);
                                assertTrue(entry.getKey() == rand);
                                Generation.Entry<Integer, Long> result = reader.get(rand);
                                assertTrue(result.getValue() == rand);
                            } else {
                                if (hasPrevious) {
                                    assertTrue(ints[(~insertionindex)-1] < rand);
                                    assertTrue(ints[(~insertionindex)-1] == entry.getKey());
                                }
                                Generation.Entry<Integer, Long> result = reader.get(rand);
                                assertTrue(result == null);
                            }
                        }
                    } finally {
                        done.decrementAndGet();
                    }
                }
            }).start();
        }
        while (done.get() > 0) {
            Thread.yield();
        }
        reader.close();
    }

    public void testLargeKeys() throws IOException {

        final TreeMap<String, Long> map = Maps.newTreeMap();
        final Random r = new Random(0);
        final String[] strings = new String[10000];
        for (int i = 0; i < strings.length; i++) {
            final byte[] bytes = new byte[16384];
            r.nextBytes(bytes);
            strings[i] = new String(Base64.encodeBase64(bytes));
        }
        Arrays.sort(strings);
        Iterator<Generation.Entry<String, Long>> iterator = new AbstractIterator<Generation.Entry<String, Long>>() {
            int index = 0;
            @Override
            protected Generation.Entry<String, Long> computeNext() {
                if (index >= strings.length) return endOfData();
                final String s = strings[index];
                final long l = r.nextLong();
                index++;
                map.put(s, l);
                return Generation.Entry.create(s, l);
            }
        };
        ImmutableBTreeIndex.Writer.write(tmpDir, iterator, new StringSerializer(), new LongSerializer(), 65536, false);
        ImmutableBTreeIndex.Reader<String, Long> index = new ImmutableBTreeIndex.Reader<String, Long>(tmpDir, new StringSerializer(), new LongSerializer(), false);
        Iterator<Generation.Entry<String, Long>> it1 = index.iterator();
        Iterator<Map.Entry<String, Long>> it2 = map.entrySet().iterator();
        int i = 0;
        while (it2.hasNext()) {
            i++;
            assertTrue(it1.hasNext());
            Generation.Entry<String, Long> next1 = it1.next();
            Map.Entry<String, Long> next2 = it2.next();
            assertEquals(next1.getKey(), next2.getKey());
            assertEquals(next1.getValue(), next2.getValue());
        }
        assertFalse(it1.hasNext());
    }
}


text:
// Type definitions for React Codemirror v0.2.6
// Project: https://github.com/JedWatson/react-codemirror
// Definitions by: Vicky Lai <https://github.com/velveret>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3

/// <reference types="react"/>
/// <reference types="codemirror"/>

declare namespace ReactCodeMirror {
    interface ReactCodeMirrorProps extends React.Props<ReactCodeMirror> {
        onChange?: (newValue: string) => any; // called when a change is made
        onFocusChange?: (focused: boolean) => any; // called when the editor is focused or loses focus
        onScroll?: (scrollInfo: CodeMirror.ScrollInfo) => any; // called when the editor is scrolled
        options?: CodeMirror.EditorConfiguration; // options passed to the CodeMirror instance
        path?: string; // the identifying name for the textarea
        value?: string; // the editor value
        className?: string; // CSS className for the outer element
        codeMirrorInstance?: CodeMirror.Editor; // the CodeMirror instance
    }

    interface ReactCodeMirror extends React.Component<ReactCodeMirrorProps> {
        /** Focuses the CodeMirror instance. */
        focus(): void;

        /** Returns the CodeMirror instance, if available. */
        getCodeMirror(): CodeMirror.Editor;
    }

    interface ReactCodeMirrorClass extends React.ComponentClass<ReactCodeMirrorProps> { }
}

declare module "react-codemirror" {
    const RCM: ReactCodeMirror.ReactCodeMirrorClass;
    export = RCM;
}


text:
<!DOCTYPE html>

  <form>
    <input id="foo">This should be green
    <input type="submit">This should be green
  </form>


text:
package com.spare.cointrade.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.spare.cointrade.actor.minitor.OkCoinTradeMonitor;
import com.spare.cointrade.model.AccountInfo;
import com.spare.cointrade.model.HuobiAccount;
import com.spare.cointrade.model.HuobiSubAccount;
import com.spare.cointrade.model.okcoin.OkCoinAccountFree;
import com.spare.cointrade.trade.huobi.HuobiTradeClient;
import com.spare.cointrade.trade.okcoin.OkCoinTradeClient;
import com.spare.cointrade.util.CoinTradeConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by dada on 2017/9/9.
 */
@Component
public class MonitorService implements Runnable {

    private static Logger logger = LoggerFactory.getLogger(MonitorService.class);

    @Autowired
    HuobiTradeClient huobiTradeClient;

    @Autowired
    OkCoinTradeClient okCoinTradeClient;

    private static ScheduledExecutorService scheduledExecutorService;

    private double totalMoney = 0.0;

    private double totalCoin = 0.0;

    private final int GAP = 20 * 1000;

    private long lastTs = 0;

    @PostConstruct
    private void start() {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleWithFixedDelay(this,5, 5, TimeUnit.SECONDS);
    }

    @Override
    public void run() {
        try {
            String user = okCoinTradeClient.queryUser();
            JSONObject jsonObject = JSON.parseObject(user);
            OkCoinAccountFree okCoinAccountFree = JSON.parseObject(jsonObject.getJSONObject("info").getJSONObject("funds").getString("free"), OkCoinAccountFree.class);
//            accountInfo.setCoinAmount(okCoinAccountFree.getEth());
//            accountInfo.setMoney(okCoinAccountFree.getCny());

            AccountInfo huobiAccountInfo = new AccountInfo();
            HuobiAccount huobiAccount = huobiTradeClient.queryBalance();
            for (HuobiSubAccount huobiSubAccount : huobiAccount.getList()) {
                if(huobiSubAccount.getCurrency().equals("cny") && huobiSubAccount.getType().equals("trade")) {
                    huobiAccountInfo.setMoney(Double.valueOf(huobiSubAccount.getBalance()));
                }
                if(huobiSubAccount.getCurrency().equals("eth") && huobiSubAccount.getType().equals("trade")) {
                    huobiAccountInfo.setCoinAmount(Double.valueOf(huobiSubAccount.getBalance()));
                }
            }

            boolean print = false;

            if(totalMoney != okCoinAccountFree.getCny() + huobiAccountInfo.getMoney()) {
                totalMoney = okCoinAccountFree.getCny() + huobiAccountInfo.getMoney();
                print = true;
            }
            if(totalCoin != okCoinAccountFree.getEth() + huobiAccountInfo.getCoinAmount()) {
                totalCoin = okCoinAccountFree.getEth() + huobiAccountInfo.getCoinAmount();
                print = true;
            }

            if(System.currentTimeMillis() - lastTs > GAP) {
                print = true;
                lastTs = System.currentTimeMillis();
            }

            if(print) {
                logger.info("[ okcoin {} {} ] [ huobi {} {} ] [ total {} {}]",
                        okCoinAccountFree.getCny(), okCoinAccountFree.getEth(),
                        huobiAccountInfo.getMoney(), huobiAccountInfo.getCoinAmount(),
                        okCoinAccountFree.getCny() + huobiAccountInfo.getMoney(),
                        okCoinAccountFree.getEth() + huobiAccountInfo.getCoinAmount());
            }

        } catch (Exception e) {
            logger.error("ERROR ", e);
        } catch (Throwable e) {
            logger.error("THROW ERROR ", e);
        }

    }
}


text:
package rdb

import (
	"bufio"
	"bytes"
	"encoding/binary"
	"fmt"
	"io"
	"math"
	"strconv"

	"github.com/cupcake/rdb/crc64"
)

// A Decoder must be implemented to parse a RDB file.
type Decoder interface {
	// StartRDB is called when parsing of a valid RDB file starts.
	StartRDB()
	// StartDatabase is called when database n starts.
	// Once a database starts, another database will not start until EndDatabase is called.
	StartDatabase(n int)
	// Set is called once for each string key.
	Set(key, value []byte, expiry int64)
	// StartHash is called at the beginning of a hash.
	// Hset will be called exactly length times before EndHash.
	StartHash(key []byte, length, expiry int64)
	// Hset is called once for each field=value pair in a hash.
	Hset(key, field, value []byte)
	// EndHash is called when there are no more fields in a hash.
	EndHash(key []byte)
	// StartSet is called at the beginning of a set.
	// Sadd will be called exactly cardinality times before EndSet.
	StartSet(key []byte, cardinality, expiry int64)
	// Sadd is called once for each member of a set.
	Sadd(key, member []byte)
	// EndSet is called when there are no more fields in a set.
	EndSet(key []byte)
	// StartList is called at the beginning of a list.
	// Rpush will be called exactly length times before EndList.
	StartList(key []byte, length, expiry int64)
	// Rpush is called once for each value in a list.
	Rpush(key, value []byte)
	// EndList is called when there are no more values in a list.
	EndList(key []byte)
	// StartZSet is called at the beginning of a sorted set.
	// Zadd will be called exactly cardinality times before EndZSet.
	StartZSet(key []byte, cardinality, expiry int64)
	// Zadd is called once for each member of a sorted set.
	Zadd(key []byte, score float64, member []byte)
	// EndZSet is called when there are no more members in a sorted set.
	EndZSet(key []byte)
	// EndDatabase is called at the end of a database.
	EndDatabase(n int)
	// EndRDB is called when parsing of the RDB file is complete.
	EndRDB()
}

// Decode parses a RDB file from r and calls the decode hooks on d.
func Decode(r io.Reader, d Decoder) error {
	decoder := &decode{d, make([]byte, 8), bufio.NewReader(r)}
	return decoder.decode()
}

// Decode a byte slice from the Redis DUMP command. The dump does not contain the
// database, key or expiry, so they must be included in the function call (but
// can be zero values).
func DecodeDump(dump []byte, db int, key []byte, expiry int64, d Decoder) error {
	err := verifyDump(dump)
	if err != nil {
		return err
	}

	decoder := &decode{d, make([]byte, 8), bytes.NewReader(dump[1:])}
	decoder.event.StartRDB()
	decoder.event.StartDatabase(db)

	err = decoder.readObject(key, ValueType(dump[0]), expiry)

	decoder.event.EndDatabase(db)
	decoder.event.EndRDB()
	return err
}

type byteReader interface {
	io.Reader
	io.ByteReader
}

type decode struct {
	event  Decoder
	intBuf []byte
	r      byteReader
}

type ValueType byte

const (
	TypeString ValueType = 0
	TypeList   ValueType = 1
	TypeSet    ValueType = 2
	TypeZSet   ValueType = 3
	TypeHash   ValueType = 4

	TypeHashZipmap  ValueType = 9
	TypeListZiplist ValueType = 10
	TypeSetIntset   ValueType = 11
	TypeZSetZiplist ValueType = 12
	TypeHashZiplist ValueType = 13
)

const (
	rdb6bitLen  = 0
	rdb14bitLen = 1
	rdb32bitLen = 2
	rdbEncVal   = 3

	rdbFlagExpiryMS = 0xfc
	rdbFlagExpiry   = 0xfd
	rdbFlagSelectDB = 0xfe
	rdbFlagEOF      = 0xff

	rdbEncInt8  = 0
	rdbEncInt16 = 1
	rdbEncInt32 = 2
	rdbEncLZF   = 3

	rdbZiplist6bitlenString  = 0
	rdbZiplist14bitlenString = 1
	rdbZiplist32bitlenString = 2

	rdbZiplistInt16 = 0xc0
	rdbZiplistInt32 = 0xd0
	rdbZiplistInt64 = 0xe0
	rdbZiplistInt24 = 0xf0
	rdbZiplistInt8  = 0xfe
	rdbZiplistInt4  = 15
)

func (d *decode) decode() error {
	err := d.checkHeader()
	if err != nil {
		return err
	}

	d.event.StartRDB()

	var db uint32
	var expiry int64
	firstDB := true
	for {
		objType, err := d.r.ReadByte()
		if err != nil {
			return err
		}
		switch objType {
		case rdbFlagExpiryMS:
			_, err := io.ReadFull(d.r, d.intBuf)
			if err != nil {
				return err
			}
			expiry = int64(binary.LittleEndian.Uint64(d.intBuf))
		case rdbFlagExpiry:
			_, err := io.ReadFull(d.r, d.intBuf[:4])
			if err != nil {
				return err
			}
			expiry = int64(binary.LittleEndian.Uint32(d.intBuf)) * 1000
		case rdbFlagSelectDB:
			if !firstDB {
				d.event.EndDatabase(int(db))
			}
			db, _, err = d.readLength()
			if err != nil {
				return err
			}
			d.event.StartDatabase(int(db))
		case rdbFlagEOF:
			d.event.EndDatabase(int(db))
			d.event.EndRDB()
			return nil
		default:
			key, err := d.readString()
			if err != nil {
				return err
			}
			err = d.readObject(key, ValueType(objType), expiry)
			if err != nil {
				return err
			}
		}
	}

	panic("not reached")
}

func (d *decode) readObject(key []byte, typ ValueType, expiry int64) error {
	switch typ {
	case TypeString:
		value, err := d.readString()
		if err != nil {
			return err
		}
		d.event.Set(key, value, expiry)
	case TypeList:
		length, _, err := d.readLength()
		if err != nil {
			return err
		}
		d.event.StartList(key, int64(length), expiry)
		for i := uint32(0); i < length; i++ {
			value, err := d.readString()
			if err != nil {
				return err
			}
			d.event.Rpush(key, value)
		}
		d.event.EndList(key)
	case TypeSet:
		cardinality, _, err := d.readLength()
		if err != nil {
			return err
		}
		d.event.StartSet(key, int64(cardinality), expiry)
		for i := uint32(0); i < cardinality; i++ {
			member, err := d.readString()
			if err != nil {
				return err
			}
			d.event.Sadd(key, member)
		}
		d.event.EndSet(key)
	case TypeZSet:
		cardinality, _, err := d.readLength()
		if err != nil {
			return err
		}
		d.event.StartZSet(key, int64(cardinality), expiry)
		for i := uint32(0); i < cardinality; i++ {
			member, err := d.readString()
			if err != nil {
				return err
			}
			score, err := d.readFloat64()
			if err != nil {
				return err
			}
			d.event.Zadd(key, score, member)
		}
		d.event.EndZSet(key)
	case TypeHash:
		length, _, err := d.readLength()
		if err != nil {
			return err
		}
		d.event.StartHash(key, int64(length), expiry)
		for i := uint32(0); i < length; i++ {
			field, err := d.readString()
			if err != nil {
				return err
			}
			value, err := d.readString()
			if err != nil {
				return err
			}
			d.event.Hset(key, field, value)
		}
		d.event.EndHash(key)
	case TypeHashZipmap:
		return d.readZipmap(key, expiry)
	case TypeListZiplist:
		return d.readZiplist(key, expiry)
	case TypeSetIntset:
		return d.readIntset(key, expiry)
	case TypeZSetZiplist:
		return d.readZiplistZset(key, expiry)
	case TypeHashZiplist:
		return d.readZiplistHash(key, expiry)
	default:
		return fmt.Errorf("rdb: unknown object type %d for key %s", typ, key)
	}
	return nil
}

func (d *decode) readZipmap(key []byte, expiry int64) error {
	var length int
	zipmap, err := d.readString()
	if err != nil {
		return err
	}
	buf := newSliceBuffer(zipmap)
	lenByte, err := buf.ReadByte()
	if err != nil {
		return err
	}
	if lenByte >= 254 { // we need to count the items manually
		length, err = countZipmapItems(buf)
		length /= 2
		if err != nil {
			return err
		}
	} else {
		length = int(lenByte)
	}
	d.event.StartHash(key, int64(length), expiry)
	for i := 0; i < length; i++ {
		field, err := readZipmapItem(buf, false)
		if err != nil {
			return err
		}
		value, err := readZipmapItem(buf, true)
		if err != nil {
			return err
		}
		d.event.Hset(key, field, value)
	}
	d.event.EndHash(key)
	return nil
}

func readZipmapItem(buf *sliceBuffer, readFree bool) ([]byte, error) {
	length, free, err := readZipmapItemLength(buf, readFree)
	if err != nil {
		return nil, err
	}
	if length == -1 {
		return nil, nil
	}
	value, err := buf.Slice(length)
	if err != nil {
		return nil, err
	}
	_, err = buf.Seek(int64(free), 1)
	return value, err
}

func countZipmapItems(buf *sliceBuffer) (int, error) {
	n := 0
	for {
		strLen, free, err := readZipmapItemLength(buf, n%2 != 0)
		if err != nil {
			return 0, err
		}
		if strLen == -1 {
			break
		}
		_, err = buf.Seek(int64(strLen)+int64(free), 1)
		if err != nil {
			return 0, err
		}
		n++
	}
	_, err := buf.Seek(0, 0)
	return n, err
}

func readZipmapItemLength(buf *sliceBuffer, readFree bool) (int, int, error) {
	b, err := buf.ReadByte()
	if err != nil {
		return 0, 0, err
	}
	switch b {
	case 253:
		s, err := buf.Slice(5)
		if err != nil {
			return 0, 0, err
		}
		return int(binary.BigEndian.Uint32(s)), int(s[4]), nil
	case 254:
		return 0, 0, fmt.Errorf("rdb: invalid zipmap item length")
	case 255:
		return -1, 0, nil
	}
	var free byte
	if readFree {
		free, err = buf.ReadByte()
	}
	return int(b), int(free), err
}

func (d *decode) readZiplist(key []byte, expiry int64) error {
	ziplist, err := d.readString()
	if err != nil {
		return err
	}
	buf := newSliceBuffer(ziplist)
	length, err := readZiplistLength(buf)
	if err != nil {
		return err
	}
	d.event.StartList(key, length, expiry)
	for i := int64(0); i < length; i++ {
		entry, err := readZiplistEntry(buf)
		if err != nil {
			return err
		}
		d.event.Rpush(key, entry)
	}
	d.event.EndList(key)
	return nil
}

func (d *decode) readZiplistZset(key []byte, expiry int64) error {
	ziplist, err := d.readString()
	if err != nil {
		return err
	}
	buf := newSliceBuffer(ziplist)
	cardinality, err := readZiplistLength(buf)
	if err != nil {
		return err
	}
	cardinality /= 2
	d.event.StartZSet(key, cardinality, expiry)
	for i := int64(0); i < cardinality; i++ {
		member, err := readZiplistEntry(buf)
		if err != nil {
			return err
		}
		scoreBytes, err := readZiplistEntry(buf)
		if err != nil {
			return err
		}
		score, err := strconv.ParseFloat(string(scoreBytes), 64)
		if err != nil {
			return err
		}
		d.event.Zadd(key, score, member)
	}
	d.event.EndZSet(key)
	return nil
}

func (d *decode) readZiplistHash(key []byte, expiry int64) error {
	ziplist, err := d.readString()
	if err != nil {
		return err
	}
	buf := newSliceBuffer(ziplist)
	length, err := readZiplistLength(buf)
	if err != nil {
		return err
	}
	length /= 2
	d.event.StartHash(key, length, expiry)
	for i := int64(0); i < length; i++ {
		field, err := readZiplistEntry(buf)
		if err != nil {
			return err
		}
		value, err := readZiplistEntry(buf)
		if err != nil {
			return err
		}
		d.event.Hset(key, field, value)
	}
	d.event.EndHash(key)
	return nil
}

func readZiplistLength(buf *sliceBuffer) (int64, error) {
	buf.Seek(8, 0) // skip the zlbytes and zltail
	lenBytes, err := buf.Slice(2)
	if err != nil {
		return 0, err
	}
	return int64(binary.LittleEndian.Uint16(lenBytes)), nil
}

func readZiplistEntry(buf *sliceBuffer) ([]byte, error) {
	prevLen, err := buf.ReadByte()
	if err != nil {
		return nil, err
	}
	if prevLen == 254 {
		buf.Seek(4, 1) // skip the 4-byte prevlen
	}

	header, err := buf.ReadByte()
	if err != nil {
		return nil, err
	}
	switch {
	case header>>6 == rdbZiplist6bitlenString:
		return buf.Slice(int(header & 0x3f))
	case header>>6 == rdbZiplist14bitlenString:
		b, err := buf.ReadByte()
		if err != nil {
			return nil, err
		}
		return buf.Slice((int(header&0x3f) << 8) | int(b))
	case header>>6 == rdbZiplist32bitlenString:
		lenBytes, err := buf.Slice(4)
		if err != nil {
			return nil, err
		}
		return buf.Slice(int(binary.BigEndian.Uint32(lenBytes)))
	case header == rdbZiplistInt16:
		intBytes, err := buf.Slice(2)
		if err != nil {
			return nil, err
		}
		return []byte(strconv.FormatInt(int64(int16(binary.LittleEndian.Uint16(intBytes))), 10)), nil
	case header == rdbZiplistInt32:
		intBytes, err := buf.Slice(4)
		if err != nil {
			return nil, err
		}
		return []byte(strconv.FormatInt(int64(int32(binary.LittleEndian.Uint32(intBytes))), 10)), nil
	case header == rdbZiplistInt64:
		intBytes, err := buf.Slice(8)
		if err != nil {
			return nil, err
		}
		return []byte(strconv.FormatInt(int64(binary.LittleEndian.Uint64(intBytes)), 10)), nil
	case header == rdbZiplistInt24:
		intBytes := make([]byte, 4)
		_, err := buf.Read(intBytes[1:])
		if err != nil {
			return nil, err
		}
		return []byte(strconv.FormatInt(int64(int32(binary.LittleEndian.Uint32(intBytes))>>8), 10)), nil
	case header == rdbZiplistInt8:
		b, err := buf.ReadByte()
		return []byte(strconv.FormatInt(int64(int8(b)), 10)), err
	case header>>4 == rdbZiplistInt4:
		return []byte(strconv.FormatInt(int64(header&0x0f)-1, 10)), nil
	}

	return nil, fmt.Errorf("rdb: unknown ziplist header byte: %d", header)
}

func (d *decode) readIntset(key []byte, expiry int64) error {
	intset, err := d.readString()
	if err != nil {
		return err
	}
	buf := newSliceBuffer(intset)
	intSizeBytes, err := buf.Slice(4)
	if err != nil {
		return err
	}
	intSize := binary.LittleEndian.Uint32(intSizeBytes)

	if intSize != 2 && intSize != 4 && intSize != 8 {
		return fmt.Errorf("rdb: unknown intset encoding: %d", intSize)
	}

	lenBytes, err := buf.Slice(4)
	if err != nil {
		return err
	}
	cardinality := binary.LittleEndian.Uint32(lenBytes)

	d.event.StartSet(key, int64(cardinality), expiry)
	for i := uint32(0); i < cardinality; i++ {
		intBytes, err := buf.Slice(int(intSize))
		if err != nil {
			return err
		}
		var intString string
		switch intSize {
		case 2:
			intString = strconv.FormatInt(int64(int16(binary.LittleEndian.Uint16(intBytes))), 10)
		case 4:
			intString = strconv.FormatInt(int64(int32(binary.LittleEndian.Uint32(intBytes))), 10)
		case 8:
			intString = strconv.FormatInt(int64(int64(binary.LittleEndian.Uint64(intBytes))), 10)
		}
		d.event.Sadd(key, []byte(intString))
	}
	d.event.EndSet(key)
	return nil
}

func (d *decode) checkHeader() error {
	header := make([]byte, 9)
	_, err := io.ReadFull(d.r, header)
	if err != nil {
		return err
	}

	if !bytes.Equal(header[:5], []byte("REDIS")) {
		return fmt.Errorf("rdb: invalid file format")
	}

	version, _ := strconv.ParseInt(string(header[5:]), 10, 64)
	if version < 1 || version > 6 {
		return fmt.Errorf("rdb: invalid RDB version number %d", version)
	}

	return nil
}

func (d *decode) readString() ([]byte, error) {
	length, encoded, err := d.readLength()
	if err != nil {
		return nil, err
	}
	if encoded {
		switch length {
		case rdbEncInt8:
			i, err := d.readUint8()
			return []byte(strconv.FormatInt(int64(int8(i)), 10)), err
		case rdbEncInt16:
			i, err := d.readUint16()
			return []byte(strconv.FormatInt(int64(int16(i)), 10)), err
		case rdbEncInt32:
			i, err := d.readUint32()
			return []byte(strconv.FormatInt(int64(int32(i)), 10)), err
		case rdbEncLZF:
			clen, _, err := d.readLength()
			if err != nil {
				return nil, err
			}
			ulen, _, err := d.readLength()
			if err != nil {
				return nil, err
			}
			compressed := make([]byte, clen)
			_, err = io.ReadFull(d.r, compressed)
			if err != nil {
				return nil, err
			}
			decompressed := lzfDecompress(compressed, int(ulen))
			if len(decompressed) != int(ulen) {
				return nil, fmt.Errorf("decompressed string length %d didn't match expected length %d", len(decompressed), ulen)
			}
			return decompressed, nil
		}
	}

	str := make([]byte, length)
	_, err = io.ReadFull(d.r, str)
	return str, err
}

func (d *decode) readUint8() (uint8, error) {
	b, err := d.r.ReadByte()
	return uint8(b), err
}

func (d *decode) readUint16() (uint16, error) {
	_, err := io.ReadFull(d.r, d.intBuf[:2])
	if err != nil {
		return 0, err
	}
	return binary.LittleEndian.Uint16(d.intBuf), nil
}

func (d *decode) readUint32() (uint32, error) {
	_, err := io.ReadFull(d.r, d.intBuf[:4])
	if err != nil {
		return 0, err
	}
	return binary.LittleEndian.Uint32(d.intBuf), nil
}

func (d *decode) readUint64() (uint64, error) {
	_, err := io.ReadFull(d.r, d.intBuf)
	if err != nil {
		return 0, err
	}
	return binary.LittleEndian.Uint64(d.intBuf), nil
}

func (d *decode) readUint32Big() (uint32, error) {
	_, err := io.ReadFull(d.r, d.intBuf[:4])
	if err != nil {
		return 0, err
	}
	return binary.BigEndian.Uint32(d.intBuf), nil
}

// Doubles are saved as strings prefixed by an unsigned
// 8 bit integer specifying the length of the representation.
// This 8 bit integer has special values in order to specify the following
// conditions:
// 253: not a number
// 254: + inf
// 255: - inf
func (d *decode) readFloat64() (float64, error) {
	length, err := d.readUint8()
	if err != nil {
		return 0, err
	}
	switch length {
	case 253:
		return math.NaN(), nil
	case 254:
		return math.Inf(0), nil
	case 255:
		return math.Inf(-1), nil
	default:
		floatBytes := make([]byte, length)
		_, err := io.ReadFull(d.r, floatBytes)
		if err != nil {
			return 0, err
		}
		f, err := strconv.ParseFloat(string(floatBytes), 64)
		return f, err
	}

	panic("not reached")
}

func (d *decode) readLength() (uint32, bool, error) {
	b, err := d.r.ReadByte()
	if err != nil {
		return 0, false, err
	}
	// The first two bits of the first byte are used to indicate the length encoding type
	switch (b & 0xc0) >> 6 {
	case rdb6bitLen:
		// When the first two bits are 00, the next 6 bits are the length.
		return uint32(b & 0x3f), false, nil
	case rdb14bitLen:
		// When the first two bits are 01, the next 14 bits are the length.
		bb, err := d.r.ReadByte()
		if err != nil {
			return 0, false, err
		}
		return (uint32(b&0x3f) << 8) | uint32(bb), false, nil
	case rdbEncVal:
		// When the first two bits are 11, the next object is encoded.
		// The next 6 bits indicate the encoding type.
		return uint32(b & 0x3f), true, nil
	default:
		// When the first two bits are 10, the next 6 bits are discarded.
		// The next 4 bytes are the length.
		length, err := d.readUint32Big()
		return length, false, err
	}

	panic("not reached")
}

func verifyDump(d []byte) error {
	if len(d) < 10 {
		return fmt.Errorf("rdb: invalid dump length")
	}
	version := binary.LittleEndian.Uint16(d[len(d)-10:])
	if version != uint16(Version) {
		return fmt.Errorf("rdb: invalid version %d, expecting %d", version, Version)
	}

	if binary.LittleEndian.Uint64(d[len(d)-8:]) != crc64.Digest(d[:len(d)-8]) {
		return fmt.Errorf("rdb: invalid CRC checksum")
	}

	return nil
}

func lzfDecompress(in []byte, outlen int) []byte {
	out := make([]byte, outlen)
	for i, o := 0, 0; i < len(in); {
		ctrl := int(in[i])
		i++
		if ctrl < 32 {
			for x := 0; x <= ctrl; x++ {
				out[o] = in[i]
				i++
				o++
			}
		} else {
			length := ctrl >> 5
			if length == 7 {
				length = length + int(in[i])
				i++
			}
			ref := o - ((ctrl & 0x1f) << 8) - int(in[i]) - 1
			i++
			for x := 0; x <= length+1; x++ {
				out[o] = out[ref]
				ref++
				o++
			}
		}
	}
	return out
}


text:
"""This file contains code for use with "Think Stats",
by Allen B. Downey, available from greenteapress.com

Copyright 2010 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""

from __future__ import print_function

from collections import defaultdict
import numpy as np
import sys

import thinkstats2

def ReadFemPreg(dct_file='2002FemPreg.dct',
                dat_file='2002FemPreg.dat.gz'):
    """Reads the NSFG pregnancy data.

    dct_file: string file name
    dat_file: string file name

    returns: DataFrame
    """
    dct = thinkstats2.ReadStataDct(dct_file)
    df = dct.ReadFixedWidth(dat_file, compression='gzip')
    CleanFemPreg(df)
    return df

def CleanFemPreg(df):
    """Recodes variables from the pregnancy frame.

    df: DataFrame
    """
    # mother's age is encoded in centiyears; convert to years
    df.agepreg /= 100.0

    # birthwgt_lb contains at least one bogus value (51 lbs)
    # replace with NaN
    df.birthwgt_lb[df.birthwgt_lb > 20] = np.nan

    # replace 'not ascertained', 'refused', 'don't know' with NaN
    na_vals = [97, 98, 99]
    df.birthwgt_lb.replace(na_vals, np.nan, inplace=True)
    df.birthwgt_oz.replace(na_vals, np.nan, inplace=True)
    df.hpagelb.replace(na_vals, np.nan, inplace=True)

    df.babysex.replace([7, 9], np.nan, inplace=True)
    df.nbrnaliv.replace([9], np.nan, inplace=True)

    # birthweight is stored in two columns, lbs and oz.
    # convert to a single column in lb
    # NOTE: creating a new column requires dictionary syntax,
    # not attribute assignment (like df.totalwgt_lb)
    df['totalwgt_lb'] = df.birthwgt_lb + df.birthwgt_oz / 16.0

    # due to a bug in ReadStataDct, the last variable gets clipped;
    # so for now set it to NaN
    df.cmintvw = np.nan

def MakePregMap(df):
    """Make a map from caseid to list of preg indices.

    df: DataFrame

    returns: dict that maps from caseid to list of indices into preg df
    """
    d = defaultdict(list)
    for index, caseid in df.caseid.iteritems():
        d[caseid].append(index)
    return d

def main(script):
    """Tests the functions in this module.

    script: string script name
    """
    df = ReadFemPreg()
    print(df.shape)

    assert len(df) == 13593

    assert df.caseid[13592] == 12571
    assert df.pregordr.value_counts()[1] == 5033
    assert df.nbrnaliv.value_counts()[1] == 8981
    assert df.babysex.value_counts()[1] == 4641
    assert df.birthwgt_lb.value_counts()[7] == 3049
    assert df.birthwgt_oz.value_counts()[0] == 1037
    assert df.prglngth.value_counts()[39] == 4744
    assert df.outcome.value_counts()[1] == 9148
    assert df.birthord.value_counts()[1] == 4413
    assert df.agepreg.value_counts()[22.75] == 100
    assert df.totalwgt_lb.value_counts()[7.5] == 302

    weights = df.finalwgt.value_counts()
    key = max(weights.keys())
    assert df.finalwgt.value_counts()[key] == 6

    print('%s: All tests passed.' % script)

if __name__ == '__main__':
    main(*sys.argv)


text:
package com.glaf.matrix.combination.domain;

import java.io.*;
import java.util.*;
import javax.persistence.*;
import com.alibaba.fastjson.*;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.glaf.core.base.*;
import com.glaf.core.util.DateUtils;
import com.glaf.matrix.combination.util.*;

/**
 *
 * 实体对象
 *
 */

@Entity
@Table(name = "SYS_COMBINATION_HISTORY")
public class CombinationHistory implements Serializable, JSONable {
	private static final long serialVersionUID = 1L;

	@Id
	@Column(name = "ID_", nullable = false)
	protected long id;

	/**
	 * 主数据编号
	 */
	@Column(name = "SYNCID_")
	protected long syncId;

	/**
	 * 部署编号
	 */
	@Column(name = "DEPLOYMENTID_", length = 50)
	protected String deploymentId;

	/**
	 * 执行数据库编号
	 */
	@Column(name = "DATABASEID_")
	protected long databaseId;

	/**
	 * 数据库名称
	 */
	@Column(name = "DATABASENAME_", length = 200)
	protected String databaseName;

	/**
	 * 执行状态
	 */
	@Column(name = "STATUS_")
	protected int status;

	/**
	 * 耗时(毫秒)
	 */
	@Column(name = "TOTALTIME_")
	protected int totalTime;

	/**
	 * 创建人
	 */
	@Column(name = "CREATEBY_", length = 50)
	protected String createBy;

	/**
	 * 创建时间
	 */
	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "CREATETIME_")
	protected Date createTime;

	public CombinationHistory() {

	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		CombinationHistory other = (CombinationHistory) obj;
		if (id != other.id)
			return false;
		return true;
	}

	public String getCreateBy() {
		return this.createBy;
	}

	public Date getCreateTime() {
		return this.createTime;
	}

	public String getCreateTimeString() {
		if (this.createTime != null) {
			return DateUtils.getDateTime(this.createTime);
		}
		return "";
	}

	public long getDatabaseId() {
		return this.databaseId;
	}

	public String getDatabaseName() {
		return databaseName;
	}

	public String getDeploymentId() {
		return this.deploymentId;
	}

	public long getId() {
		return this.id;
	}

	public int getStatus() {
		return this.status;
	}

	public long getSyncId() {
		return this.syncId;
	}

	public int getTotalTime() {
		return this.totalTime;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (int) (id ^ (id >>> 32));
		return result;
	}

	public CombinationHistory jsonToObject(JSONObject jsonObject) {
		return CombinationHistoryJsonFactory.jsonToObject(jsonObject);
	}

	public void setCreateBy(String createBy) {
		this.createBy = createBy;
	}

	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}

	public void setDatabaseId(long databaseId) {
		this.databaseId = databaseId;
	}

	public void setDatabaseName(String databaseName) {
		this.databaseName = databaseName;
	}

	public void setDeploymentId(String deploymentId) {
		this.deploymentId = deploymentId;
	}

	public void setId(long id) {
		this.id = id;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	public void setSyncId(long syncId) {
		this.syncId = syncId;
	}

	public void setTotalTime(int totalTime) {
		this.totalTime = totalTime;
	}

	public JSONObject toJsonObject() {
		return CombinationHistoryJsonFactory.toJsonObject(this);
	}

	public ObjectNode toObjectNode() {
		return CombinationHistoryJsonFactory.toObjectNode(this);
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
	}

}


text:
package org.uberfire.backend.server.config;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.inject.Qualifier;

@Qualifier
@Target({PARAMETER, FIELD})
@Retention(RUNTIME)
public @interface Added {

}


text:
import unittest

from os.path import dirname, join, realpath
from urllib import request

class IntegrationTest(unittest.TestCase):
    def test_get(self):
        response = request.urlopen('http://localhost:8000/golden/corn/')
        text = response.read()
        self.assertEqual(text.decode('utf-8'), 'Lets get the golden corn!')

        response = request.urlopen('http://localhost:8000/metal/silver/food/apple/')
        text = response.read()
        self.assertEqual(text.decode('utf-8'), 'Lets get the silver apple!')

    def test_post(self):
        response = request.urlopen('http://localhost:8000/golden/corn/', data=b"")
        text = response.read()
        self.assertEqual(text.decode('utf-8'), 'Lets post the golden corn!')

        response = request.urlopen('http://localhost:8000/metal/silver/food/apple/', data=b"")
        text = response.read()
        self.assertEqual(text.decode('utf-8'), 'Lets post the silver apple!')

    def test_redirect(self):
        response = request.urlopen('http://localhost:8000/golden/corn')
        text = response.read()
        self.assertEqual(text.decode('utf-8'), 'Lets get the golden corn!')

        response = request.urlopen('http://localhost:8000/metal/silver/food/apple')
        text = response.read()
        self.assertEqual(text.decode('utf-8'), 'Lets get the silver apple!')

    def test_not_found(self):
        self.assertRaises(request.HTTPError, request.urlopen, 'http://localhost:8000/')

    def test_static_files(self):
        with open(join(dirname(realpath(__file__)), 'src', 'static', 'pixel.png'), 'rb') as static_file:
            response = request.urlopen('http://localhost:8000/static/pixel.png')
            self.assertEqual(response.read(), static_file.read())

if __name__ == '__main__':
    unittest.main()


text:
package af_packet

import (
	"context"
	"fmt"
	"io"

	api "git.fd.io/govpp.git/api"
	vpe "go.ligato.io/vpp-agent/v3/plugins/vpp/binapi/vpp2106/vpe"
)

// RPCService defines RPC service af_packet.
type RPCService interface {
	AfPacketCreate(ctx context.Context, in *AfPacketCreate) (*AfPacketCreateReply, error)
	AfPacketDelete(ctx context.Context, in *AfPacketDelete) (*AfPacketDeleteReply, error)
	AfPacketDump(ctx context.Context, in *AfPacketDump) (RPCService_AfPacketDumpClient, error)
	AfPacketSetL4CksumOffload(ctx context.Context, in *AfPacketSetL4CksumOffload) (*AfPacketSetL4CksumOffloadReply, error)
}

type serviceClient struct {
	conn api.Connection
}

func NewServiceClient(conn api.Connection) RPCService {
	return &serviceClient{conn}
}

func (c *serviceClient) AfPacketCreate(ctx context.Context, in *AfPacketCreate) (*AfPacketCreateReply, error) {
	out := new(AfPacketCreateReply)
	err := c.conn.Invoke(ctx, in, out)
	if err != nil {
		return nil, err
	}
	return out, api.RetvalToVPPApiError(out.Retval)
}

func (c *serviceClient) AfPacketDelete(ctx context.Context, in *AfPacketDelete) (*AfPacketDeleteReply, error) {
	out := new(AfPacketDeleteReply)
	err := c.conn.Invoke(ctx, in, out)
	if err != nil {
		return nil, err
	}
	return out, api.RetvalToVPPApiError(out.Retval)
}

func (c *serviceClient) AfPacketDump(ctx context.Context, in *AfPacketDump) (RPCService_AfPacketDumpClient, error) {
	stream, err := c.conn.NewStream(ctx)
	if err != nil {
		return nil, err
	}
	x := &serviceClient_AfPacketDumpClient{stream}
	if err := x.Stream.SendMsg(in); err != nil {
		return nil, err
	}
	if err = x.Stream.SendMsg(&vpe.ControlPing{}); err != nil {
		return nil, err
	}
	return x, nil
}

type RPCService_AfPacketDumpClient interface {
	Recv() (*AfPacketDetails, error)
	api.Stream
}

type serviceClient_AfPacketDumpClient struct {
	api.Stream
}

func (c *serviceClient_AfPacketDumpClient) Recv() (*AfPacketDetails, error) {
	msg, err := c.Stream.RecvMsg()
	if err != nil {
		return nil, err
	}
	switch m := msg.(type) {
	case *AfPacketDetails:
		return m, nil
	case *vpe.ControlPingReply:
		return nil, io.EOF
	default:
		return nil, fmt.Errorf("unexpected message: %T %v", m, m)
	}
}

func (c *serviceClient) AfPacketSetL4CksumOffload(ctx context.Context, in *AfPacketSetL4CksumOffload) (*AfPacketSetL4CksumOffloadReply, error) {
	out := new(AfPacketSetL4CksumOffloadReply)
	err := c.conn.Invoke(ctx, in, out)
	if err != nil {
		return nil, err
	}
	return out, api.RetvalToVPPApiError(out.Retval)
}


text:
int fsl_diu_init(u16 xres, u16 yres, u32 pixel_format, int gamma_fix);

/* Prototypes for external board-specific functions */
int platform_diu_init(unsigned int xres, unsigned int yres, const char *port);
void diu_set_pixel_clock(unsigned int pixclock);


text:
package etcd

import (
	"fmt"
	"reflect"

	"k8s.io/kubernetes/pkg/api"
	kubeerr "k8s.io/kubernetes/pkg/api/errors"
	etcderr "k8s.io/kubernetes/pkg/api/errors/etcd"
	"k8s.io/kubernetes/pkg/api/meta"
	"k8s.io/kubernetes/pkg/api/rest"
	"k8s.io/kubernetes/pkg/api/unversioned"
	"k8s.io/kubernetes/pkg/api/validation"
	"k8s.io/kubernetes/pkg/fields"
	"k8s.io/kubernetes/pkg/labels"
	"k8s.io/kubernetes/pkg/registry/generic"
	"k8s.io/kubernetes/pkg/runtime"
	"k8s.io/kubernetes/pkg/storage"
	"k8s.io/kubernetes/pkg/util/validation/field"
	"k8s.io/kubernetes/pkg/watch"

	"github.com/golang/glog"
)

// Etcd implements generic.Registry, backing it with etcd storage.
// It's intended to be embeddable, so that you can implement any
// non-generic functions if needed.
// You must supply a value for every field below before use; these are
// left public as it's meant to be overridable if need be.
// This object is intended to be copyable so that it can be used in
// different ways but share the same underlying behavior.
//
// The intended use of this type is embedding within a Kind specific
// RESTStorage implementation. This type provides CRUD semantics on
// a Kubelike resource, handling details like conflict detection with
// ResourceVersion and semantics. The RESTCreateStrategy and
// RESTUpdateStrategy are generic across all backends, and encapsulate
// logic specific to the API.
//
// TODO: make the default exposed methods exactly match a generic RESTStorage
// TODO: because all aspects of etcd have been removed it should really
//       just be called a registry implementation.
type Etcd struct {
	// Called to make a new object, should return e.g., &api.Pod{}
	NewFunc func() runtime.Object

	// Called to make a new listing object, should return e.g., &api.PodList{}
	NewListFunc func() runtime.Object

	// Used for error reporting
	QualifiedResource unversioned.GroupResource

	// Used for listing/watching; should not include trailing "/"
	KeyRootFunc func(ctx api.Context) string

	// Called for Create/Update/Get/Delete. Note that 'namespace' can be
	// gotten from ctx.
	KeyFunc func(ctx api.Context, name string) (string, error)

	// Called to get the name of an object
	ObjectNameFunc func(obj runtime.Object) (string, error)

	// Return the TTL objects should be persisted with. Update is true if this
	// is an operation against an existing object. Existing is the current TTL
	// or the default for this operation.
	TTLFunc func(obj runtime.Object, existing uint64, update bool) (uint64, error)

	// Returns a matcher corresponding to the provided labels and fields.
	PredicateFunc func(label labels.Selector, field fields.Selector) generic.Matcher

	// Called on all objects returned from the underlying store, after
	// the exit hooks are invoked. Decorators are intended for integrations
	// that are above etcd and should only be used for specific cases where
	// storage of the value in etcd is not appropriate, since they cannot
	// be watched.
	Decorator rest.ObjectFunc
	// Allows extended behavior during creation, required
	CreateStrategy rest.RESTCreateStrategy
	// On create of an object, attempt to run a further operation.
	AfterCreate rest.ObjectFunc
	// Allows extended behavior during updates, required
	UpdateStrategy rest.RESTUpdateStrategy
	// On update of an object, attempt to run a further operation.
	AfterUpdate rest.ObjectFunc
	// Allows extended behavior during updates, optional
	DeleteStrategy rest.RESTDeleteStrategy
	// On deletion of an object, attempt to run a further operation.
	AfterDelete rest.ObjectFunc
	// If true, return the object that was deleted. Otherwise, return a generic
	// success status response.
	ReturnDeletedObject bool
	// Allows extended behavior during export, optional
	ExportStrategy rest.RESTExportStrategy

	// Used for all etcd access functions
	Storage storage.Interface
}

// NamespaceKeyRootFunc is the default function for constructing etcd paths to resource directories enforcing namespace rules.
func NamespaceKeyRootFunc(ctx api.Context, prefix string) string {
	key := prefix
	ns, ok := api.NamespaceFrom(ctx)
	if ok && len(ns) > 0 {
		key = key + "/" + ns
	}
	return key
}

// NamespaceKeyFunc is the default function for constructing etcd paths to a resource relative to prefix enforcing namespace rules.
// If no namespace is on context, it errors.
func NamespaceKeyFunc(ctx api.Context, prefix string, name string) (string, error) {
	key := NamespaceKeyRootFunc(ctx, prefix)
	ns, ok := api.NamespaceFrom(ctx)
	if !ok || len(ns) == 0 {
		return "", kubeerr.NewBadRequest("Namespace parameter required.")
	}
	if len(name) == 0 {
		return "", kubeerr.NewBadRequest("Name parameter required.")
	}
	if ok, msg := validation.IsValidPathSegmentName(name); !ok {
		return "", kubeerr.NewBadRequest(fmt.Sprintf("Name parameter invalid: %v.", msg))
	}
	key = key + "/" + name
	return key, nil
}

// NoNamespaceKeyFunc is the default function for constructing etcd paths to a resource relative to prefix without a namespace
func NoNamespaceKeyFunc(ctx api.Context, prefix string, name string) (string, error) {
	if len(name) == 0 {
		return "", kubeerr.NewBadRequest("Name parameter required.")
	}
	if ok, msg := validation.IsValidPathSegmentName(name); !ok {
		return "", kubeerr.NewBadRequest(fmt.Sprintf("Name parameter invalid: %v.", msg))
	}
	key := prefix + "/" + name
	return key, nil
}

// New implements RESTStorage
func (e *Etcd) New() runtime.Object {
	return e.NewFunc()
}

// NewList implements RESTLister
func (e *Etcd) NewList() runtime.Object {
	return e.NewListFunc()
}

// List returns a list of items matching labels and field
func (e *Etcd) List(ctx api.Context, options *api.ListOptions) (runtime.Object, error) {
	label := labels.Everything()
	if options != nil && options.LabelSelector != nil {
		label = options.LabelSelector
	}
	field := fields.Everything()
	if options != nil && options.FieldSelector != nil {
		field = options.FieldSelector
	}
	return e.ListPredicate(ctx, e.PredicateFunc(label, field), options)
}

// ListPredicate returns a list of all the items matching m.
func (e *Etcd) ListPredicate(ctx api.Context, m generic.Matcher, options *api.ListOptions) (runtime.Object, error) {
	list := e.NewListFunc()
	filterFunc := e.filterAndDecorateFunction(m)
	if name, ok := m.MatchesSingle(); ok {
		if key, err := e.KeyFunc(ctx, name); err == nil {
			err := e.Storage.GetToList(ctx, key, filterFunc, list)
			return list, etcderr.InterpretListError(err, e.QualifiedResource)
		}
		// if we cannot extract a key based on the current context, the optimization is skipped
	}

	if options == nil {
		options = &api.ListOptions{ResourceVersion: "0"}
	}
	err := e.Storage.List(ctx, e.KeyRootFunc(ctx), options.ResourceVersion, filterFunc, list)
	return list, etcderr.InterpretListError(err, e.QualifiedResource)
}

// Create inserts a new item according to the unique key from the object.
func (e *Etcd) Create(ctx api.Context, obj runtime.Object) (runtime.Object, error) {
	if err := rest.BeforeCreate(e.CreateStrategy, ctx, obj); err != nil {
		return nil, err
	}
	name, err := e.ObjectNameFunc(obj)
	if err != nil {
		return nil, err
	}
	key, err := e.KeyFunc(ctx, name)
	if err != nil {
		return nil, err
	}
	ttl, err := e.calculateTTL(obj, 0, false)
	if err != nil {
		return nil, err
	}
	out := e.NewFunc()
	if err := e.Storage.Create(ctx, key, obj, out, ttl); err != nil {
		err = etcderr.InterpretCreateError(err, e.QualifiedResource, name)
		err = rest.CheckGeneratedNameError(e.CreateStrategy, err, obj)
		return nil, err
	}
	if e.AfterCreate != nil {
		if err := e.AfterCreate(out); err != nil {
			return nil, err
		}
	}
	if e.Decorator != nil {
		if err := e.Decorator(obj); err != nil {
			return nil, err
		}
	}
	return out, nil
}

// Update performs an atomic update and set of the object. Returns the result of the update
// or an error. If the registry allows create-on-update, the create flow will be executed.
// A bool is returned along with the object and any errors, to indicate object creation.
func (e *Etcd) Update(ctx api.Context, obj runtime.Object) (runtime.Object, bool, error) {
	name, err := e.ObjectNameFunc(obj)
	if err != nil {
		return nil, false, err
	}
	key, err := e.KeyFunc(ctx, name)
	if err != nil {
		return nil, false, err
	}
	// If AllowUnconditionalUpdate() is true and the object specified by the user does not have a resource version,
	// then we populate it with the latest version.
	// Else, we check that the version specified by the user matches the version of latest etcd object.
	resourceVersion, err := e.Storage.Versioner().ObjectResourceVersion(obj)
	if err != nil {
		return nil, false, err
	}
	doUnconditionalUpdate := resourceVersion == 0 && e.UpdateStrategy.AllowUnconditionalUpdate()
	// TODO: expose TTL
	creating := false
	out := e.NewFunc()
	err = e.Storage.GuaranteedUpdate(ctx, key, out, true, func(existing runtime.Object, res storage.ResponseMeta) (runtime.Object, *uint64, error) {
		version, err := e.Storage.Versioner().ObjectResourceVersion(existing)
		if err != nil {
			return nil, nil, err
		}
		if version == 0 {
			if !e.UpdateStrategy.AllowCreateOnUpdate() {
				return nil, nil, kubeerr.NewNotFound(e.QualifiedResource, name)
			}
			creating = true
			if err := rest.BeforeCreate(e.CreateStrategy, ctx, obj); err != nil {
				return nil, nil, err
			}
			ttl, err := e.calculateTTL(obj, 0, false)
			if err != nil {
				return nil, nil, err
			}
			return obj, &ttl, nil
		}

		creating = false
		if doUnconditionalUpdate {
			// Update the object's resource version to match the latest etcd object's resource version.
			err = e.Storage.Versioner().UpdateObject(obj, res.Expiration, res.ResourceVersion)
			if err != nil {
				return nil, nil, err
			}
		} else {
			// Check if the object's resource version matches the latest resource version.
			newVersion, err := e.Storage.Versioner().ObjectResourceVersion(obj)
			if err != nil {
				return nil, nil, err
			}
			if newVersion == 0 {
				// TODO: The Invalid error should has a field for Resource.
				// After that field is added, we should fill the Resource and
				// leave the Kind field empty. See the discussion in #18526.
				qualifiedKind := unversioned.GroupKind{e.QualifiedResource.Group, e.QualifiedResource.Resource}
				fieldErrList := field.ErrorList{field.Invalid(field.NewPath("metadata").Child("resourceVersion"), newVersion, "must be specified for an update")}
				return nil, nil, kubeerr.NewInvalid(qualifiedKind, name, fieldErrList)
			}
			if newVersion != version {
				return nil, nil, kubeerr.NewConflict(e.QualifiedResource, name, fmt.Errorf("the object has been modified; please apply your changes to the latest version and try again"))
			}
		}
		if err := rest.BeforeUpdate(e.UpdateStrategy, ctx, obj, existing); err != nil {
			return nil, nil, err
		}
		ttl, err := e.calculateTTL(obj, res.TTL, true)
		if err != nil {
			return nil, nil, err
		}
		if int64(ttl) != res.TTL {
			return obj, &ttl, nil
		}
		return obj, nil, nil
	})

	if err != nil {
		if creating {
			err = etcderr.InterpretCreateError(err, e.QualifiedResource, name)
			err = rest.CheckGeneratedNameError(e.CreateStrategy, err, obj)
		} else {
			err = etcderr.InterpretUpdateError(err, e.QualifiedResource, name)
		}
		return nil, false, err
	}
	if creating {
		if e.AfterCreate != nil {
			if err := e.AfterCreate(out); err != nil {
				return nil, false, err
			}
		}
	} else {
		if e.AfterUpdate != nil {
			if err := e.AfterUpdate(out); err != nil {
				return nil, false, err
			}
		}
	}
	if e.Decorator != nil {
		if err := e.Decorator(obj); err != nil {
			return nil, false, err
		}
	}
	return out, creating, nil
}

// Get retrieves the item from etcd.
func (e *Etcd) Get(ctx api.Context, name string) (runtime.Object, error) {
	obj := e.NewFunc()
	key, err := e.KeyFunc(ctx, name)
	if err != nil {
		return nil, err
	}
	if err := e.Storage.Get(ctx, key, obj, false); err != nil {
		return nil, etcderr.InterpretGetError(err, e.QualifiedResource, name)
	}
	if e.Decorator != nil {
		if err := e.Decorator(obj); err != nil {
			return nil, err
		}
	}
	return obj, nil
}

var (
	errAlreadyDeleting = fmt.Errorf("abort delete")
	errDeleteNow       = fmt.Errorf("delete now")
)

// Delete removes the item from etcd.
func (e *Etcd) Delete(ctx api.Context, name string, options *api.DeleteOptions) (runtime.Object, error) {
	key, err := e.KeyFunc(ctx, name)
	if err != nil {
		return nil, err
	}

	obj := e.NewFunc()
	if err := e.Storage.Get(ctx, key, obj, false); err != nil {
		return nil, etcderr.InterpretDeleteError(err, e.QualifiedResource, name)
	}

	// support older consumers of delete by treating "nil" as delete immediately
	if options == nil {
		options = api.NewDeleteOptions(0)
	}
	graceful, pendingGraceful, err := rest.BeforeDelete(e.DeleteStrategy, ctx, obj, options)
	if err != nil {
		return nil, err
	}
	if pendingGraceful {
		return e.finalizeDelete(obj, false)
	}
	if graceful && *options.GracePeriodSeconds > 0 {
		out := e.NewFunc()
		lastGraceful := int64(0)
		err := e.Storage.GuaranteedUpdate(
			ctx, key, out, false,
			storage.SimpleUpdate(func(existing runtime.Object) (runtime.Object, error) {
				graceful, pendingGraceful, err := rest.BeforeDelete(e.DeleteStrategy, ctx, existing, options)
				if err != nil {
					return nil, err
				}
				if pendingGraceful {
					return nil, errAlreadyDeleting
				}
				if !graceful {
					return nil, errDeleteNow
				}
				lastGraceful = *options.GracePeriodSeconds
				return existing, nil
			}),
		)
		switch err {
		case nil:
			if lastGraceful > 0 {
				return out, nil
			}
			// fall through and delete immediately
		case errDeleteNow:
			// we've updated the object to have a zero grace period, or it's already at 0, so
			// we should fall through and truly delete the object.
		case errAlreadyDeleting:
			return e.finalizeDelete(obj, true)
		default:
			return nil, etcderr.InterpretUpdateError(err, e.QualifiedResource, name)
		}
	}

	// delete immediately, or no graceful deletion supported
	out := e.NewFunc()
	if err := e.Storage.Delete(ctx, key, out); err != nil {
		return nil, etcderr.InterpretDeleteError(err, e.QualifiedResource, name)
	}
	return e.finalizeDelete(out, true)
}

// DeleteCollection remove all items returned by List with a given ListOptions from etcd.
//
// DeleteCollection is currently NOT atomic. It can happen that only subset of objects
// will be deleted from etcd, and then an error will be returned.
// In case of success, the list of deleted objects will be returned.
//
// TODO: Currently, there is no easy way to remove 'directory' entry from etcd (if we
// are removing all objects of a given type) with the current API (it's technically
// possibly with etcd API, but watch is not delivered correctly then).
// It will be possible to fix it with v3 etcd API.
func (e *Etcd) DeleteCollection(ctx api.Context, options *api.DeleteOptions, listOptions *api.ListOptions) (runtime.Object, error) {
	listObj, err := e.List(ctx, listOptions)
	if err != nil {
		return nil, err
	}
	items, err := meta.ExtractList(listObj)
	if err != nil {
		return nil, err
	}
	for _, item := range items {
		accessor, err := meta.Accessor(item)
		if err != nil {
			return nil, err
		}
		if _, err := e.Delete(ctx, accessor.GetName(), options); err != nil && !kubeerr.IsNotFound(err) {
			return nil, err
		}
	}
	return listObj, nil
}

func (e *Etcd) finalizeDelete(obj runtime.Object, runHooks bool) (runtime.Object, error) {
	if runHooks && e.AfterDelete != nil {
		if err := e.AfterDelete(obj); err != nil {
			return nil, err
		}
	}
	if e.ReturnDeletedObject {
		if e.Decorator != nil {
			if err := e.Decorator(obj); err != nil {
				return nil, err
			}
		}
		return obj, nil
	}
	return &unversioned.Status{Status: unversioned.StatusSuccess}, nil
}

// Watch makes a matcher for the given label and field, and calls
// WatchPredicate. If possible, you should customize PredicateFunc to produre a
// matcher that matches by key. generic.SelectionPredicate does this for you
// automatically.
func (e *Etcd) Watch(ctx api.Context, options *api.ListOptions) (watch.Interface, error) {
	label := labels.Everything()
	if options != nil && options.LabelSelector != nil {
		label = options.LabelSelector
	}
	field := fields.Everything()
	if options != nil && options.FieldSelector != nil {
		field = options.FieldSelector
	}
	resourceVersion := ""
	if options != nil {
		resourceVersion = options.ResourceVersion
	}
	return e.WatchPredicate(ctx, e.PredicateFunc(label, field), resourceVersion)
}

// WatchPredicate starts a watch for the items that m matches.
func (e *Etcd) WatchPredicate(ctx api.Context, m generic.Matcher, resourceVersion string) (watch.Interface, error) {
	filterFunc := e.filterAndDecorateFunction(m)

	if name, ok := m.MatchesSingle(); ok {
		if key, err := e.KeyFunc(ctx, name); err == nil {
			if err != nil {
				return nil, err
			}
			return e.Storage.Watch(ctx, key, resourceVersion, filterFunc)
		}
		// if we cannot extract a key based on the current context, the optimization is skipped
	}

	return e.Storage.WatchList(ctx, e.KeyRootFunc(ctx), resourceVersion, filterFunc)
}

func (e *Etcd) filterAndDecorateFunction(m generic.Matcher) func(runtime.Object) bool {
	return func(obj runtime.Object) bool {
		matches, err := m.Matches(obj)
		if err != nil {
			glog.Errorf("unable to match watch: %v", err)
			return false
		}
		if matches && e.Decorator != nil {
			if err := e.Decorator(obj); err != nil {
				glog.Errorf("unable to decorate watch: %v", err)
				return false
			}
		}
		return matches
	}
}

// calculateTTL is a helper for retrieving the updated TTL for an object or returning an error
// if the TTL cannot be calculated. The defaultTTL is changed to 1 if less than zero. Zero means
// no TTL, not expire immediately.
func (e *Etcd) calculateTTL(obj runtime.Object, defaultTTL int64, update bool) (ttl uint64, err error) {
	// etcd may return a negative TTL for a node if the expiration has not occurred due
	// to server lag - we will ensure that the value is at least set.
	if defaultTTL < 0 {
		defaultTTL = 1
	}
	ttl = uint64(defaultTTL)
	if e.TTLFunc != nil {
		ttl, err = e.TTLFunc(obj, ttl, update)
	}
	return ttl, err
}

func exportObjectMeta(objMeta *api.ObjectMeta, exact bool) {
	objMeta.UID = ""
	if !exact {
		objMeta.Namespace = ""
	}
	objMeta.CreationTimestamp = unversioned.Time{}
	objMeta.DeletionTimestamp = nil
	objMeta.ResourceVersion = ""
	objMeta.SelfLink = ""
	if len(objMeta.GenerateName) > 0 && !exact {
		objMeta.Name = ""
	}
}

// Implements the rest.Exporter interface
func (e *Etcd) Export(ctx api.Context, name string, opts unversioned.ExportOptions) (runtime.Object, error) {
	obj, err := e.Get(ctx, name)
	if err != nil {
		return nil, err
	}
	if meta, err := api.ObjectMetaFor(obj); err == nil {
		exportObjectMeta(meta, opts.Exact)
	} else {
		glog.V(4).Infof("Object of type %v does not have ObjectMeta: %v", reflect.TypeOf(obj), err)
	}

	if e.ExportStrategy != nil {
		if err = e.ExportStrategy.Export(obj, opts.Exact); err != nil {
			return nil, err
		}
	} else {
		e.CreateStrategy.PrepareForCreate(obj)
	}
	return obj, nil
}


text:
package com.mobileobservinglog;

import com.mobileobservinglog.R;
import com.mobileobservinglog.R.id;
import com.mobileobservinglog.support.database.PersonalInfoDAO;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class PersonalInfoScreen extends ActivityBase {

	//gather resources
	LinearLayout body;

	Button editButton;
	TextView fullNameField;
	TextView addressField;
	TextView phoneField;
	TextView emailField;
	TextView clubField;

	String nameText;
	String addressText;
	String phoneText;
	String emailText;
	String clubText;

	@Override
    public void onCreate(Bundle icicle) {
		Log.d("JoeDebug", "PersonalInfo onCreate. Current session mode is " + settingsRef.getSessionMode());
        super.onCreate(icicle);

        customizeBrightness.setDimButtons(settingsRef.getButtonBrightness());

        //setup the layout
        setContentView(settingsRef.getPersonalInfoLayout());
        body = (LinearLayout)findViewById(R.id.personal_info_root);
	}

	@Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    //When we resume, we need to make sure we have the right layout set, in case the user has changed the session mode.
    @Override
    public void onResume() {
		Log.d("JoeDebug", "PersonalInfo onResume. Current session mode is " + settingsRef.getSessionMode());
        super.onResume();
        setLayout();
    }

    //Used by the Toggle Mode menu item method in ActivityBase. Reset the layout and force the redraw
	@Override
	public void setLayout(){
		setContentView(settingsRef.getPersonalInfoLayout());
		super.setLayout();
		findFields();
		findButtonSetListener();
		populateFields();
		body.postInvalidate();
	}

	private void findFields(){
		fullNameField = (TextView)findViewById(R.id.personal_info_top_label);
		addressField = (TextView)findViewById(R.id.view_personal_info_address);
		phoneField = (TextView)findViewById(R.id.view_personal_info_phone);
		emailField = (TextView)findViewById(id.view_personal_info_email);
		clubField = (TextView)findViewById(R.id.view_personal_info_club);
	}

	private void findButtonSetListener(){
		editButton = (Button)findViewById(R.id.view_personal_info_edit);
		editButton.setOnClickListener(editPersonalInfo);
	}

	private void populateFields(){
		PersonalInfoDAO db = new PersonalInfoDAO(this);
		Cursor personalInfo = db.getPersonalInfo();
		personalInfo.moveToFirst();

		nameText = personalInfo.getString(1);
		addressText = personalInfo.getString(2);
		phoneText = personalInfo.getString(3);
		emailText = personalInfo.getString(4);
		clubText = personalInfo.getString(5);
		personalInfo.close();

		if(!nameText.equals("")) {
			fullNameField.setText(nameText);
		} else {
			fullNameField.setText("Press \"Edit Information\" to change");
		}
		if(!addressText.equals("")) {
			addressField.setText(addressText);
		} else {
			addressField.setText("Press \"Edit Information\" to change");
		}
		if(!phoneText.equals("")) {
			phoneField.setText(phoneText);
		} else {
			phoneField.setText("Press \"Edit Information\" to change");
		}
		if(!emailText.equals("")) {
			emailField.setText(emailText);
		} else {
			emailField.setText("Press \"Edit Information\" to change");
		}
		if(!clubText.equals("")) {
			clubField.setText(clubText);
		} else {
			clubField.setText("Press \"Edit Information\" to change");
		}
	}

    protected final Button.OnClickListener editPersonalInfo = new Button.OnClickListener() {
		public void onClick(View view){
			//start new intent
			Intent intent = new Intent(PersonalInfoScreen.this.getApplication(), EditPersonalInfoScreen.class);
	        startActivity(intent);
        }
    };
}


text:
package io.moquette.spi.impl;

import java.util.Map;

import io.moquette.spi.impl.security.IAuthenticator;

/**
 * Test utility to implements authenticator instance.
 *
 * @author andrea
 */
public class MockAuthenticator implements IAuthenticator {

    private Map<String, byte[]> m_userPwds;

    public MockAuthenticator(Map<String, byte[]> userPwds) {
        m_userPwds = userPwds;
    }

    public boolean checkValid(String username, byte[] password, String clientId) {
        if (!m_userPwds.containsKey(username)) {
            return false;
        }
        return m_userPwds.get(username).equals(password);
    }

}


text:
export interface SendPasswordResetEmailResponse {
    sent?: boolean;
}


text:
ExpressionEngine3 plugin that adds string manipulation functionality to directly call PHP's string functions

This plugin takes 2 parameters, `functions` and `params`. Each is a pipe-delimited list (no pipes needed if only running one function). Functions will be called on the tag contents in the order provided. Add `parse="inward"` to parse contained EE tags first.

## Basic Example

```html
{exp:rd_string functions="substr" params="10"}
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse a ipsum
{/exp:rd_string}
```

returns:

```html
Lorem ipsu
```

## Multiple Example

```html
{exp:rd_string functions="substr|strtoupper" params="15|"}
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse a ipsum
{/exp:rd_string}
```

returns:

```html
LOREM IPSUM DOL
```

## Included PHP functions:

* **strip_tags** - Strip HTML and PHP tags from a string
* **strtolower** — Make a string lowercase
* **strtoupper** — Make a string uppercase
* **substr** — Return part of a string
* **substr_replace** — Replace text within a portion of a string
* **urlencode** — URL-encodes string


text:
'use strict';
var routes = require("./routes/routes.js");

module.exports = function (app){
    routes(app);
}