text:
namespace TaskManager
{
    using System;
    using System.Diagnostics;
    using System.ServiceProcess;

    /// <summary>
    /// Implements the Windows service interface for the Task Manager.
    /// </summary>
    public partial class TaskManagerService : ServiceBase
    {
        /// <summary>
        /// The name used in the Windows Event Log.
        /// </summary>
        internal static readonly string LogName = TaskManagerInstaller.SERVICE_DESCRIPTION;

        /// <summary>
        /// The source name used in the Windows Event Log.
        /// </summary>
        internal static readonly string LogSource = "TaskManager Service";

        /// <summary>
        /// The EventLog instance.
        /// </summary>
        private static EventLog _eventLog;

        /// <summary>
        /// The logger instance.
        /// </summary>
        private static ILogger _logger;

        /// <summary>
        /// Initializes static members of the <see cref="TaskManagerService"/> class.
        /// </summary>
        static TaskManagerService()
        {
            _eventLog = new EventLog(TaskManagerService.LogName, ".", TaskManagerService.LogSource);

            _logger = new Logger();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="TaskManagerService"/> class.
        /// </summary>
        public TaskManagerService()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Gets the logger instance.
        /// </summary>
        public static ILogger Logger
        {
            get
            {
                return TaskManagerService._logger;
            }
        }

        /// <summary>
        /// Logs an information message.
        /// </summary>
        /// <param name="message">The message.</param>
        public static void LogInfo(string message)
        {
            if (null == _eventLog)
            {
                Console.WriteLine("    " + message);
            }
            else
            {
                lock (_eventLog)
                {
                    _eventLog.WriteEntry(message, EventLogEntryType.Information);
                }
            }
        }

        /// <summary>
        /// Logs an error.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="ex">An exception.</param>
        public static void LogError(string message, Exception ex)
        {
            if (null == _eventLog)
            {
                Console.WriteLine(string.Format("*** {0}: {2} ({1})", message, ex.GetType().Name, ex.Message));
            }
            else
            {
                lock (_eventLog)
                {
                    EventLogEntryType logEntryType = EventLogEntryType.Error;
                    string log = null;

                    if (ex is System.Threading.ThreadAbortException)
                    {
                        log = "Task scheduling and execution aborted.";
                        logEntryType = EventLogEntryType.Warning;
                    }
                    else
                    {
                        log = string.Format("An error ocurred during task execution:\r\n\r\n{0}\r\n\r\n{1}: {2}\r\n\r\nStacktrace:\r\n{3}", message, ex.GetType().Name, ex.Message, ex.StackTrace);
                    }

                    _eventLog.WriteEntry(log, logEntryType);
                }
            }
        }

        /// <summary>
        /// Called when the service is being started by the SCM.
        /// </summary>
        /// <param name="args">The arguments.</param>
        protected override void OnStart(string[] args)
        {
            ////#if DEBUG
            ////            System.Threading.Thread.Sleep(10000);
            ////#endif

            LogInfo("Starting service...");
            try
            {
                TaskSupervisor.Initialize();
                ModuleSupervisor.Initialize();
                LogInfo("Service successfully started...");

                ModuleSupervisor.Execute();
            }
            catch (Exception e)
            {
                LogError("Unable to start service.", e);
                throw;
            }
        }

        /// <summary>
        /// Called when the service is being stopped by the SCM.
        /// </summary>
        protected override void OnStop()
        {
            LogInfo("Stopping service...");
            try
            {
                ModuleSupervisor.Shutdown();
                TaskSupervisor.Shutdown();
                LogInfo("Service successfully stopped...");
            }
            catch (Exception e)
            {
                LogError("Unable to stop service.", e);
                throw;
            }

            lock (_eventLog)
            {
                _eventLog.Close();
                _eventLog = null;
            }
        }
    }
}


text:
package rpm4s.data

import rpm4s.data.SenseFlags.Sense

class SenseFlags(val value: Int) extends AnyVal {
  def &(other: SenseFlags) = SenseFlags(value & other.value)
  def |(other: SenseFlags) = SenseFlags(value | other.value)
  def ^(other: SenseFlags) = SenseFlags(value ^ other.value)
  def union(other: SenseFlags) = this | other
  def intersection(other: SenseFlags) = this & other
  def diff(other: SenseFlags) = this ^ other
  def inverse: SenseFlags = this ^ SenseFlags.All
  def -(other: SenseFlags) = this & other.inverse

  def sense: Sense = {
    this & SenseFlags.SenseMask match {
      case SenseFlags.Any => Sense.Any
      case SenseFlags.Equal => Sense.EQ
      case SenseFlags.Greater => Sense.GT
      case SenseFlags.GreaterEqual => Sense.GE
      case SenseFlags.Less => Sense.LT
      case SenseFlags.LessEqual => Sense.LE
      case _ =>
        throw new RuntimeException(
          "This should not happen if SenseMask is correct")
    }
  }

  /**
    * @see https://github.com/rpm-software-management/yum/blob/8bbb3a9b79aed25815986d87f41902dae397814c/yum/packages.py#L1621
    * @return
    */
  def isPreReq: Boolean = containsAny(SenseFlags.PreReqMask)

  def containsAll(attributes: SenseFlags): Boolean =
    (value & attributes.value) == attributes.value
  def containsAny(attributes: SenseFlags): Boolean =
    (value & attributes.value) != 0
  override def toString: String = {
    import SenseFlags._
    if (this == Any) {
      "SenseFlags(Any)"
    } else {
      val flags: String = List(
        if (containsAny(Less)) List("Less") else List.empty,
        if (containsAny(Greater)) List("Greater") else List.empty,
        if (containsAny(Equal)) List("Equal") else List.empty,
        if (containsAny(PostTrans)) List("PostTrans") else List.empty,
        if (containsAny(PreReq)) List("PreReq") else List.empty,
        if (containsAny(PreTrans)) List("PreTrans") else List.empty,
        if (containsAny(Interp)) List("Interp") else List.empty,
        if (containsAny(ScriptPre)) List("ScriptPre") else List.empty,
        if (containsAny(ScriptPost)) List("ScriptPost") else List.empty,
        if (containsAny(ScriptPreUn)) List("ScriptPreUn") else List.empty,
        if (containsAny(ScriptPostUn)) List("ScriptPostUn") else List.empty,
        if (containsAny(ScriptVerify)) List("ScriptVerify") else List.empty,
        if (containsAny(FindRequires)) List("FindRequires") else List.empty,
        if (containsAny(FindProvides)) List("FindProvides") else List.empty,
        if (containsAny(TriggerIn)) List("TriggerIn") else List.empty,
        if (containsAny(TriggerUn)) List("TriggerUn") else List.empty,
        if (containsAny(TriggerPostUn)) List("TriggerPostUn") else List.empty,
        if (containsAny(MissingOk)) List("MissingOk") else List.empty,
        if (containsAny(SenseFlags.RpmLib)) List("RpmLib") else List.empty,
        if (containsAny(TriggerPreIn)) List("TriggerPreIn") else List.empty,
        if (containsAny(Keyring)) List("Keyring") else List.empty,
        if (containsAny(Config)) List("Config") else List.empty
      ).flatten.mkString("|")
      s"SenseFlags($flags)"
    }
  }
}

object SenseFlags {

  sealed trait Sense extends Product with Serializable
  object Sense {
    case object Any extends Sense
    case object GT extends Sense
    case object GE extends Sense
    case object LT extends Sense
    case object LE extends Sense
    case object EQ extends Sense
  }

  case class Provides(sense: Sense, findProvides: Boolean)
  case class Trigger(
      sense: Sense,
      in: Boolean,
      un: Boolean,
      preIn: Boolean,
      preUn: Boolean)
  case class Requires(
      sense: Sense,
      interp: Boolean,
      pre: Boolean,
      post: Boolean,
      preUn: Boolean,
      postUn: Boolean,
      verify: Boolean,
      findRequires: Boolean,
      rpmlib: Boolean,
      keyring: Boolean,
      preTrans: Boolean,
      postTrans: Boolean,
      preReq: Boolean,
      missingOk: Boolean
  )

  def apply(int: Int): SenseFlags = new SenseFlags(int)

  val Any = SenseFlags(0)
  val Less = SenseFlags(1 << 1)
  val Greater = SenseFlags(1 << 2)
  val Equal = SenseFlags(1 << 3)

  val GreaterEqual: SenseFlags = Greater | Equal
  val LessEqual: SenseFlags = Less | Equal

  val PostTrans = SenseFlags(1 << 5) /*!< %posttrans dependency */
  val PreReq = SenseFlags(1 << 6) /* legacy prereq dependency */
  val PreTrans = SenseFlags(1 << 7) /*!< Pre-transaction dependency. */
  val Interp = SenseFlags(1 << 8) /*!< Interpreter used by scriptlet. */
  val ScriptPre = SenseFlags(1 << 9) /*!< %pre dependency. */
  val ScriptPost = SenseFlags(1 << 10) /*!< %post dependency. */
  val ScriptPreUn = SenseFlags(1 << 11) /*!< %preun dependency. */
  val ScriptPostUn = SenseFlags(1 << 12) /*!< %postun dependency. */
  val ScriptVerify = SenseFlags(1 << 13) /*!< %verify dependency. */
  val FindRequires = SenseFlags(1 << 14) /*!< find-requires generated dependency. */
  val FindProvides = SenseFlags(1 << 15) /*!< find-provides generated dependency. */

  val TriggerIn = SenseFlags(1 << 16) /*!< %triggerin dependency. */
  val TriggerUn = SenseFlags(1 << 17) /*!< %triggerun dependency. */
  val TriggerPostUn = SenseFlags(1 << 18) /*!< %triggerpostun dependency. */
  val MissingOk = SenseFlags(1 << 19) /*!< suggests/enhances hint. */
  val RpmLib = SenseFlags(1 << 24) /*!< rpmlib(feature) dependency. */
  val TriggerPreIn = SenseFlags(1 << 25) /*!< %triggerprein dependency. */
  val Keyring = SenseFlags(1 << 26)
  val Config = SenseFlags(1 << 28)

  val SenseMask: SenseFlags =
    Less | Equal | Greater | Any

  val TriggerMask: SenseFlags =
    TriggerPreIn | TriggerIn | TriggerUn | TriggerPostUn

  val PreReqMask =
    PreReq | ScriptPre | ScriptPost

  val AllRequiresMask: SenseFlags =
    Interp | ScriptPre | ScriptPost | ScriptPreUn | ScriptPostUn
  ScriptVerify | FindRequires | RpmLib | Keyring | PreTrans
  PostTrans | PreReq | MissingOk

  val All: SenseFlags = Any | Less | Greater | Equal |
    PostTrans | PreReq | PreTrans | Interp |
    ScriptPre | ScriptPost | ScriptPreUn | ScriptPostUn |
    ScriptVerify | FindRequires | FindProvides |
    TriggerIn | TriggerUn | TriggerPostUn |
    MissingOk | RpmLib | TriggerPreIn |
    Keyring | Config

}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Thelebolus nanus Heimerl, 1889

### Remarks
null


text:
package kr.ac.kumoh.railroApplication.classes;

public class Item {
	public String title;
	public String imageUrl;
	public String address;
	public String newAddress;
	public String zipcode;
	public String phone;
	public double longitude;
	public double latitude;
	public double distance;
	public String category;
	public String id;
	public String placeUrl;
	public String direction;
	public String addressBCode;
}


text:
/* jslint maxlen:80, es6:true, white:true */

/* jshint bitwise:true, camelcase:true, curly:true, eqeqeq:true, forin:true,
   freeze:true, futurehostile:true, latedef:true, newcap:true, nocomma:true,
   nonbsp:true, singleGroups:true, strict:true, undef:true, unused:true,
   es3:false, esnext:true, plusplus:true, maxparams:1, maxdepth:1,
   maxstatements:3, maxcomplexity:2 */

/* eslint strict: 1, max-statements: 1 */

/* global module */

;(function () { // eslint-disable-line no-extra-semi

  'use strict';

  var pToString = Object.prototype.toString;
  var isNull = require('lodash.isnull');
  var isUndefined = require('validate.io-undefined');
  var nullTag = '[object Null]';
  var undefTag = '[object Undefined]';

  /**
   * The `toStringTag` method returns "[object type]", where type is the
   * object type.
   *
   * @param {*} value The object of which to get the object type string.
   * @return {string} The object type string.
   * @example
   * var o = new Object();
   *
   * toStringTag(o); // returns '[object Object]'
   */
  module.exports = function toStringTag(value) {
    if (isNull(value)) {
      return nullTag;
    }
    if (isUndefined(value)) {
      return undefTag;
    }
    return pToString.call(value);
  };
}());


text:
package org.xdi.oxauth.uma.ws.rs;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.log.Log;
import org.xdi.oxauth.model.config.Configuration;
import org.xdi.oxauth.model.config.ConfigurationFactory;
import org.xdi.oxauth.model.error.ErrorResponseFactory;
import org.xdi.oxauth.model.uma.UmaConfiguration;
import org.xdi.oxauth.model.uma.UmaConstants;
import org.xdi.oxauth.model.uma.UmaErrorResponseType;
import org.xdi.oxauth.util.ServerUtil;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;

/**
 * The endpoint at which the requester can obtain UMA metadata configuration.
 *
 * @author Yuriy Movchan Date: 10/25/2012
 * @author Yuriy Zabrovarnyy Date: 03/12/2015
 */
@Name("umaMetaDataConfigurationRestWebService")
@Path("/oxauth/uma-configuration")
@Api(value = "/.well-known/uma-configuration", description = "The authorization server endpoint that provides configuration data in a JSON [RFC4627] document that resides in at /.well-known/uma-configuration directory at its hostmeta [hostmeta] location. The configuration data documents conformance options and endpoints supported by the authorization server. ")
public class UmaConfigurationWS {

    public static final String UMA_SCOPES_SUFFIX = "/uma/scopes";

    @Logger
    private Log log;
    @In
    private ErrorResponseFactory errorResponseFactory;

    @GET
    @Produces({UmaConstants.JSON_MEDIA_TYPE})
    @ApiOperation(
            value = "Provides configuration data as json document. It contains options and endpoints supported by the authorization server.",
            response = UmaConfiguration.class
    )
    @ApiResponses(value = {
            @ApiResponse(code = 500, message = "Failed to build Uma configuration json object.")
    })
    public Response getConfiguration() {
        try {
            final Configuration configuration = ConfigurationFactory.instance().getConfiguration();
            final String baseEndpointUri = configuration.getBaseEndpoint();

            final UmaConfiguration c = new UmaConfiguration();
            c.setVersion("1.0");
            c.setIssuer(configuration.getIssuer());
            c.setPatProfilesSupported(new String[]{"bearer"});
            c.setAatProfilesSupported(new String[]{"bearer"});
            c.setRptProfilesSupported(new String[]{"https://docs.kantarainitiative.org/uma/profiles/uma-token-bearer-1.0"});
            c.setPatGrantTypesSupported(new String[]{"authorization_code"});
            c.setAatGrantTypesSupported(new String[]{"authorization_code"});
            c.setClaimTokenProfilesSupported(new String[]{"openid"});
            c.setDynamicClientEndpoint(baseEndpointUri + "/oxauth/register");
            c.setTokenEndpoint(baseEndpointUri + "/oxauth/token");
            c.setAuthorizationEndpoint(baseEndpointUri + "/requester/perm");
            c.setRequestingPartyClaimsEndpoint("");
            c.setResourceSetRegistrationEndpoint(baseEndpointUri + "/host/rsrc/resource_set");
            c.setIntrospectionEndpoint(baseEndpointUri + "/rpt/status");
            c.setPermissionRegistrationEndpoint(baseEndpointUri + "/host/rsrc_pr");
            c.setRptEndpoint(baseEndpointUri + "/requester/rpt");
            c.setScopeEndpoint(baseEndpointUri + UMA_SCOPES_SUFFIX);
            c.setUserEndpoint(baseEndpointUri + "/oxauth/authorize");

            // convert manually to avoid possible conflicts between resteasy providers, e.g. jettison, jackson
            final String entity = ServerUtil.asPrettyJson(c);
            log.trace("Uma configuration: {0}", entity);

            return Response.ok(entity).build();
        } catch (Throwable ex) {
            log.error(ex.getMessage(), ex);
            throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                    .entity(errorResponseFactory.getUmaJsonErrorResponse(UmaErrorResponseType.SERVER_ERROR)).build());
        }
    }

}


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

namespace BlatantShopping.Sales
{
	class AboveThresholdSale : ISale
	{
		public int threshold;
		public decimal priceEachAfterThreshold;
		public String customReason = null;

		/// <summary>
		/// If threshold or more items are purchased, get a deal
		/// </summary>
		/// <param name="threshold">Deal is applied if the quantity purchased is greater than or equal to the threshold</param>
		/// <param name="priceEachAfterThreshold">Price each after threshold is met or exceeded</param>
		public AboveThresholdSale(int threshold, decimal priceEachAfterThreshold)
		{
			this.threshold = threshold;
			this.priceEachAfterThreshold = priceEachAfterThreshold;
		}

		public decimal GetSalePrice(int quantity)
		{
			return QuantityAppliedTo(quantity) * priceEachAfterThreshold;
		}

		public int QuantityAppliedTo(int quantity)
		{
			return (quantity >= threshold) ? quantity : 0;
		}

		public string GetReasoning(int quantity)
		{
			if (String.IsNullOrEmpty(customReason))
			{
				return String.Format("{0}@ Buy min {1} for {2:C}ea = {3:C}", QuantityAppliedTo(quantity), threshold, priceEachAfterThreshold, GetSalePrice(quantity));
			}
			else
			{
				return String.Format("{0}@ {1} = {2:C}", QuantityAppliedTo(quantity), customReason, GetSalePrice(quantity));
			}
		}
	}
}


text:
package docker

import (
	"context"
	"net/http"
	"net/url"
	"path"
	"strconv"
	"strings"

	"github.com/containerd/containerd/errdefs"
	"github.com/containerd/containerd/images"
	"github.com/containerd/containerd/log"
	"github.com/containerd/containerd/reference"
	"github.com/containerd/containerd/remotes"
	"github.com/containerd/containerd/version"
	digest "github.com/opencontainers/go-digest"
	ocispec "github.com/opencontainers/image-spec/specs-go/v1"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"golang.org/x/net/context/ctxhttp"
)

var (
	// ErrNoToken is returned if a request is successful but the body does not
	// contain an authorization token.
	ErrNoToken = errors.New("authorization server did not include a token in the response")

	// ErrInvalidAuthorization is used when credentials are passed to a server but
	// those credentials are rejected.
	ErrInvalidAuthorization = errors.New("authorization failed")
)

// Authorizer is used to authorize HTTP requests based on 401 HTTP responses.
// An Authorizer is responsible for caching tokens or credentials used by
// requests.
type Authorizer interface {
	// Authorize sets the appropriate `Authorization` header on the given
	// request.
	//
	// If no authorization is found for the request, the request remains
	// unmodified. It may also add an `Authorization` header as
	//  "bearer <some bearer token>"
	//  "basic <base64 encoded credentials>"
	Authorize(context.Context, *http.Request) error

	// AddResponses adds a 401 response for the authorizer to consider when
	// authorizing requests. The last response should be unauthorized and
	// the previous requests are used to consider redirects and retries
	// that may have led to the 401.
	//
	// If response is not handled, returns `ErrNotImplemented`
	AddResponses(context.Context, []*http.Response) error
}

// ResolverOptions are used to configured a new Docker register resolver
type ResolverOptions struct {
	// Authorizer is used to authorize registry requests
	Authorizer Authorizer

	// Credentials provides username and secret given a host.
	// If username is empty but a secret is given, that secret
	// is interpreted as a long lived token.
	// Deprecated: use Authorizer
	Credentials func(string) (string, string, error)

	// Host provides the hostname given a namespace.
	Host func(string) (string, error)

	// Headers are the HTTP request header fields sent by the resolver
	Headers http.Header

	// PlainHTTP specifies to use plain http and not https
	PlainHTTP bool

	// Client is the http client to used when making registry requests
	Client *http.Client

	// Tracker is used to track uploads to the registry. This is used
	// since the registry does not have upload tracking and the existing
	// mechanism for getting blob upload status is expensive.
	Tracker StatusTracker
}

// DefaultHost is the default host function.
func DefaultHost(ns string) (string, error) {
	if ns == "docker.io" {
		return "registry-1.docker.io", nil
	}
	return ns, nil
}

type dockerResolver struct {
	auth      Authorizer
	host      func(string) (string, error)
	headers   http.Header
	plainHTTP bool
	client    *http.Client
	tracker   StatusTracker
}

// NewResolver returns a new resolver to a Docker registry
func NewResolver(options ResolverOptions) remotes.Resolver {
	if options.Tracker == nil {
		options.Tracker = NewInMemoryTracker()
	}
	if options.Host == nil {
		options.Host = DefaultHost
	}
	if options.Headers == nil {
		options.Headers = make(http.Header)
	}
	if _, ok := options.Headers["Accept"]; !ok {
		// set headers for all the types we support for resolution.
		options.Headers.Set("Accept", strings.Join([]string{
			images.MediaTypeDockerSchema2Manifest,
			images.MediaTypeDockerSchema2ManifestList,
			ocispec.MediaTypeImageManifest,
			ocispec.MediaTypeImageIndex, "*"}, ", "))
	}
	if _, ok := options.Headers["User-Agent"]; !ok {
		options.Headers.Set("User-Agent", "containerd/"+version.Version)
	}
	if options.Authorizer == nil {
		options.Authorizer = NewAuthorizer(options.Client, options.Credentials)
	}
	return &dockerResolver{
		auth:      options.Authorizer,
		host:      options.Host,
		headers:   options.Headers,
		plainHTTP: options.PlainHTTP,
		client:    options.Client,
		tracker:   options.Tracker,
	}
}

var _ remotes.Resolver = &dockerResolver{}

func (r *dockerResolver) Resolve(ctx context.Context, ref string) (string, ocispec.Descriptor, error) {
	refspec, err := reference.Parse(ref)
	if err != nil {
		return "", ocispec.Descriptor{}, err
	}

	if refspec.Object == "" {
		return "", ocispec.Descriptor{}, reference.ErrObjectRequired
	}

	base, err := r.base(refspec)
	if err != nil {
		return "", ocispec.Descriptor{}, err
	}

	fetcher := dockerFetcher{
		dockerBase: base,
	}

	var (
		urls []string
		dgst = refspec.Digest()
	)

	if dgst != "" {
		if err := dgst.Validate(); err != nil {
			// need to fail here, since we can't actually resolve the invalid
			// digest.
			return "", ocispec.Descriptor{}, err
		}

		// turns out, we have a valid digest, make a url.
		urls = append(urls, fetcher.url("manifests", dgst.String()))

		// fallback to blobs on not found.
		urls = append(urls, fetcher.url("blobs", dgst.String()))
	} else {
		urls = append(urls, fetcher.url("manifests", refspec.Object))
	}

	ctx, err = contextWithRepositoryScope(ctx, refspec, false)
	if err != nil {
		return "", ocispec.Descriptor{}, err
	}
	for _, u := range urls {
		req, err := http.NewRequest(http.MethodHead, u, nil)
		if err != nil {
			return "", ocispec.Descriptor{}, err
		}

		req.Header = r.headers

		log.G(ctx).Debug("resolving")
		resp, err := fetcher.doRequestWithRetries(ctx, req, nil)
		if err != nil {
			if errors.Cause(err) == ErrInvalidAuthorization {
				err = errors.Wrapf(err, "pull access denied, repository does not exist or may require authorization")
			}
			return "", ocispec.Descriptor{}, err
		}
		resp.Body.Close() // don't care about body contents.

		if resp.StatusCode > 299 {
			if resp.StatusCode == http.StatusNotFound {
				continue
			}
			return "", ocispec.Descriptor{}, errors.Errorf("unexpected status code %v: %v", u, resp.Status)
		}

		// this is the only point at which we trust the registry. we use the
		// content headers to assemble a descriptor for the name. when this becomes
		// more robust, we mostly get this information from a secure trust store.
		dgstHeader := digest.Digest(resp.Header.Get("Docker-Content-Digest"))

		if dgstHeader != "" {
			if err := dgstHeader.Validate(); err != nil {
				return "", ocispec.Descriptor{}, errors.Wrapf(err, "%q in header not a valid digest", dgstHeader)
			}
			dgst = dgstHeader
		}

		if dgst == "" {
			return "", ocispec.Descriptor{}, errors.Errorf("could not resolve digest for %v", ref)
		}

		var (
			size       int64
			sizeHeader = resp.Header.Get("Content-Length")
		)

		size, err = strconv.ParseInt(sizeHeader, 10, 64)
		if err != nil {

			return "", ocispec.Descriptor{}, errors.Wrapf(err, "invalid size header: %q", sizeHeader)
		}
		if size < 0 {
			return "", ocispec.Descriptor{}, errors.Errorf("%q in header not a valid size", sizeHeader)
		}

		desc := ocispec.Descriptor{
			Digest:    dgst,
			MediaType: resp.Header.Get("Content-Type"), // need to strip disposition?
			Size:      size,
		}

		log.G(ctx).WithField("desc.digest", desc.Digest).Debug("resolved")
		return ref, desc, nil
	}

	return "", ocispec.Descriptor{}, errors.Errorf("%v not found", ref)
}

func (r *dockerResolver) Fetcher(ctx context.Context, ref string) (remotes.Fetcher, error) {
	refspec, err := reference.Parse(ref)
	if err != nil {
		return nil, err
	}

	base, err := r.base(refspec)
	if err != nil {
		return nil, err
	}

	return dockerFetcher{
		dockerBase: base,
	}, nil
}

func (r *dockerResolver) Pusher(ctx context.Context, ref string) (remotes.Pusher, error) {
	refspec, err := reference.Parse(ref)
	if err != nil {
		return nil, err
	}

	// Manifests can be pushed by digest like any other object, but the passed in
	// reference cannot take a digest without the associated content. A tag is allowed
	// and will be used to tag pushed manifests.
	if refspec.Object != "" && strings.Contains(refspec.Object, "@") {
		return nil, errors.New("cannot use digest reference for push locator")
	}

	base, err := r.base(refspec)
	if err != nil {
		return nil, err
	}

	return dockerPusher{
		dockerBase: base,
		tag:        refspec.Object,
		tracker:    r.tracker,
	}, nil
}

type dockerBase struct {
	refspec reference.Spec
	base    url.URL

	client *http.Client
	auth   Authorizer
}

func (r *dockerResolver) base(refspec reference.Spec) (*dockerBase, error) {
	var (
		err  error
		base url.URL
	)

	host := refspec.Hostname()
	base.Host = host
	if r.host != nil {
		base.Host, err = r.host(host)
		if err != nil {
			return nil, err
		}
	}

	base.Scheme = "https"
	if r.plainHTTP || strings.HasPrefix(base.Host, "localhost:") {
		base.Scheme = "http"
	}

	prefix := strings.TrimPrefix(refspec.Locator, host+"/")
	base.Path = path.Join("/v2", prefix)

	return &dockerBase{
		refspec: refspec,
		base:    base,
		client:  r.client,
		auth:    r.auth,
	}, nil
}

func (r *dockerBase) url(ps ...string) string {
	url := r.base
	url.Path = path.Join(url.Path, path.Join(ps...))
	return url.String()
}

func (r *dockerBase) authorize(ctx context.Context, req *http.Request) error {
	// Check if has header for host
	if r.auth != nil {
		if err := r.auth.Authorize(ctx, req); err != nil {
			return err
		}
	}

	return nil
}

func (r *dockerBase) doRequest(ctx context.Context, req *http.Request) (*http.Response, error) {
	ctx = log.WithLogger(ctx, log.G(ctx).WithField("url", req.URL.String()))
	log.G(ctx).WithField("request.headers", req.Header).WithField("request.method", req.Method).Debug("do request")
	if err := r.authorize(ctx, req); err != nil {
		return nil, errors.Wrap(err, "failed to authorize")
	}
	resp, err := ctxhttp.Do(ctx, r.client, req)
	if err != nil {
		return nil, errors.Wrap(err, "failed to do request")
	}
	log.G(ctx).WithFields(logrus.Fields{
		"status":           resp.Status,
		"response.headers": resp.Header,
	}).Debug("fetch response received")
	return resp, nil
}

func (r *dockerBase) doRequestWithRetries(ctx context.Context, req *http.Request, responses []*http.Response) (*http.Response, error) {
	resp, err := r.doRequest(ctx, req)
	if err != nil {
		return nil, err
	}

	responses = append(responses, resp)
	req, err = r.retryRequest(ctx, req, responses)
	if err != nil {
		resp.Body.Close()
		return nil, err
	}
	if req != nil {
		resp.Body.Close()
		return r.doRequestWithRetries(ctx, req, responses)
	}
	return resp, err
}

func (r *dockerBase) retryRequest(ctx context.Context, req *http.Request, responses []*http.Response) (*http.Request, error) {
	if len(responses) > 5 {
		return nil, nil
	}
	last := responses[len(responses)-1]
	if last.StatusCode == http.StatusUnauthorized {
		log.G(ctx).WithField("header", last.Header.Get("WWW-Authenticate")).Debug("Unauthorized")
		if r.auth != nil {
			if err := r.auth.AddResponses(ctx, responses); err == nil {
				return copyRequest(req)
			} else if !errdefs.IsNotImplemented(err) {
				return nil, err
			}
		}

		return nil, nil
	} else if last.StatusCode == http.StatusMethodNotAllowed && req.Method == http.MethodHead {
		// Support registries which have not properly implemented the HEAD method for
		// manifests endpoint
		if strings.Contains(req.URL.Path, "/manifests/") {
			// TODO: copy request?
			req.Method = http.MethodGet
			return copyRequest(req)
		}
	}

	// TODO: Handle 50x errors accounting for attempt history
	return nil, nil
}

func copyRequest(req *http.Request) (*http.Request, error) {
	ireq := *req
	if ireq.GetBody != nil {
		var err error
		ireq.Body, err = ireq.GetBody()
		if err != nil {
			return nil, err
		}
	}
	return &ireq, nil
}


text:
\chapter{The \acl{LHC}}
\label{chap:intro:lhc}

As high-energy particle physics has progressed over the last century, the
meaning of `high energy' has continuously evolved.
Today, high energy refers to the \acl{LHC}~\cite{Bruning:2004ej}, a circular
collider which began operating at a proton-proton centre of mass energy of
\sqrtseq{7} in 2010, and in 2015 reached \sqrtseq{13}.
This section will describe the machine, the experiments which it services, and
the changes in operation throughout its lifetime so far.

In order to produce collisions, bunches of \num{1.2e11} protons are obtained
through the ionisation of hydrogen gas, and are then accelerated through a
chain of progressively larger, more powerful accelerators before being injected
into the \ac{LHC}.
During nominal operation, a single \ac{LHC} `fill' consists of injecting 2808
bunches into the machine, each of which is about \SI{10}{\centi\metre} long,
separated from the surrounding bunches by about \SI{7}{\metre}, completing a
full revolution of the ring at a rate of \SI{11.246}{\kilo\hertz}.

The beams are steered around the ring by superconducting dipole magnets, cooled
to \SI{1.9}{\kelvin}, and are focused by quadrupole and other, higher-order,
magnets.
The beams are made to collide at four \acp{LHCIP}, before which they are
focused further, from the usual circulating bunch diameter of
\SI{0.2}{\milli\metre} to a width on the order of microns, such that they can
collide.

For a collision experiment, the rate $N$ at which a particular process occurs
per second is given by
\begin{equation}
  N = \lumi\xsec,
  \label{eqn:intro:lhc:lumi_xsec}
\end{equation}
where \lumi\ is the instantaneous luminosity of the accelerator and \xsec\ is
the cross-section of the process.
At $\sqrts = \SI{13}{\TeV}$, the visible proton-proton interaction
cross-section is around $\xsecppvis =
\SI{70}{\milli\barn}$~\cite{Aaboud:2016mmw,CMS:2016ael}.
Given that this number is fixed by the beam energy and colliding particle type,
the \ac{LHC} is designed to maximise the luminosity \lumi, which can be
expressed as
\begin{equation}
  \lumi = \frac{N_{\text{p}}^{2}N_{\text{b}}\revfreq\gamma}{4\pi\epsilon\beta^{*}}F,
  \label{eqn:intro:lhc:inst_lumi}
\end{equation}
where $N_{\text{p}}$ is the number of particles per bunch; $N_{\text{b}}$ is
the number of bunches per beam; \revfreq\ is the bunch revolution frequency;
$\gamma$ is the Lorentz factor; $\epsilon$ is the beam emittance during
circulation, a measure of the beam size transverse to the beam direction;
$\beta^{*}$ is a measure of the transverse beam size at a particular
\ac{LHCIP}; and $F$ accounts for non-zero crossing angles between the two beams
at an \ac{LHCIP}.
Depending on the experiment, the \betastar\ parameter can be tuned to provide a
specific average number $\nu$ of collisions per bunch crossing.
The design luminosity at the \atlas\ and \cms\ \acp{LHCIP} is
\SI{1e34}{\per\square\centi\metre\per\second}, which results in a rate of
visible proton-proton interactions of \SI{700}{\mega\hertz}.

\subsection{Running periods}

The \ac{LHC} first began running in 2010 at a proton-proton centre-of-mass
energy of $\sqrts = \SI{7}{\TeV}$, and this continued until the end of 2011.
In 2012, the centre-of-mass energy was increased to $\sqrts = \SI{8}{\TeV}$,
before the machine was shut down at the end of 2012.
This marked the end of \runone\ and the beginning of \acf{LS1}, during which
the accelerator was upgraded in order to prepare the machine for running at
$\sqrts = \SI{13}{\TeV}$.
This new phase of operation, \runtwo, began in mid-2015, and is expected to
continue until the end of 2018.


text:
package gameofking;

public class Card {

}


text:
<resources>

    <!--
        Base application theme for API 11+. This theme completely replaces
        AppBaseTheme from res/values/styles.xml on API 11+ devices.
    -->
    <style name="AppBaseTheme" parent="android:Theme.Holo.Light">
        <!-- API 11 theme customizations can go here. -->
        <item name="colorAccent">@color/nga_primary_light</item>
    </style>

</resources>


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.kevdez.imageviewer.ViewPhotoActivity">

    <!--<android.support.design.widget.AppBarLayout-->
        <!--android:layout_width="match_parent"-->
        <!--android:layout_height="wrap_content"-->
        <!--android:theme="@style/Theme.Custom.AppBarOverlay">-->

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/Theme.Custom.PopupOverlay" />

    <include layout="@layout/content_view_photo" />

</android.support.design.widget.CoordinatorLayout>


text:
<?php namespace Devise\Pages\Models;

use Devise\Support\Framework;

class ModelsResponseHandler
{
	/**
	 * Model Manager
	 *
	 * @var ModelManager
	 */
	protected $ModelManager;

	/**
	 * Create a new model manager
	 *
	 * @param ModelManager $ModelManager
	 */
	public function __construct(ModelManager $ModelManager, Framework $Framework)
	{
		$this->ModelManager = $ModelManager;
		$this->Response = $Framework->Response;
	}

	/**
	 * Updates a single model field for this model (attribute)
	 *
	 * @param  integer $modelFieldId
	 * @param  array   $input
	 * @return array
	 */
	public function executeModelFieldUpdate($modelFieldId, $input)
	{
		try
		{
			$field = $this->ModelManager->updateField($input['field'], $input['page']);
		}

		catch (ModelFieldValidationFailedException $e)
		{
			return $this->Response->json([
				'errors' => $e->getErrors()
			], 403);
		}

		return array('field' => $field);
	}

	/**
	 * Loops over all fields for this model and updates
	 * the model with new values (model)
	 *
	 * @param  array $input
	 * @return array
	 */
	public function executeModelFieldsUpdate($input)
	{
		try {
			$fields = $this->ModelManager->updateFields($input['fields'], $input['page']);
		} catch (ModelFieldValidationFailedException $e) {
			return $this->Response->json(['errors' => $e->getErrors()], 403);
		}

		return array('fields' => $fields);
	}

	/**
	 * Model creators use this to create new model fields
	 * for a model (model creator)
	 *
	 * @param  array $input
	 * @return array
	 */
	public function executeModelFieldsCreate($input)
	{
		try {
			list($fields, $model) = $this->ModelManager->createFieldsAndModel($input['fields'], $input['page']);
		} catch (ModelFieldValidationFailedException $e) {
			return $this->Response->json(['errors' => $e->getErrors()], 403);
		}

		return array('model' => $model, 'fields' => $fields);
	}
}


text:
from distutils.core import Command
import json
import re
import time
import pkg_resources

# Note, the last time I coded python daily was at Google, so it's entirely
# possible some of my techniques below are outdated or bad.
# If you have fixes, let me know.

class get_metadata(Command):
  description = "get package metadata"
  user_options = []

  def initialize_options(self):
    pass
  # def initialize_options

  def finalize_options(self):
    pass
  # def finalize_options

  def run(self):
    #print type(self.distribution)
    #for i in sorted(dir(self.distribution)):
      #if i.startswith("_"):
        #continue
      ###print "%s: %r" % (i, self.__getattr__(i))
      #print "%s" % i

    data = {
      "name": self.distribution.get_name(),
      "version": self.distribution.get_version(),
      "author": "%s <%s>" % (self.distribution.get_author(),
        self.distribution.get_author_email()),
      "description": self.distribution.get_description(),
      "license": self.distribution.get_license(),
      "url": self.distribution.get_url(),
    }

    # If there are python C/extension modules, we'll want to build a native
    # arch package.
    if self.distribution.has_ext_modules():
      data["architecture"] = "native"
    else:
      data["architecture"] = "all"
    # end if

    final_deps = []
    if getattr(self.distribution, 'install_requires', None):
        for dep in pkg_resources.parse_requirements(self.distribution.install_requires):
            # add all defined specs to the dependecy list separately.
            if dep.specs:
                for operator, version in dep.specs:
                    final_deps.append("%s %s %s" % (
                        dep.project_name,
                        "=" if operator == "==" else operator,
                        version
                    ))
            else:
                final_deps.append(dep.project_name)

    data["dependencies"] = final_deps

    #print json.dumps(data, indent=2)
    try:
      print(json.dumps(data, indent=2))
    except AttributeError as e:
      # For Python 2.5 and Debian's python-json
      print(json.write(data))
  # def run
# class list_dependencies


text:
layout:    more
title:     BlazeDS Cheat Sheet
---

Resource

Online

Official Website

Wikipedia BlazeDS

Download

Getting Started with BlazeDS by Shashank Tiwari [.pdf]

Related

Adobe

Flex

Java


text:
{% extends 'index.html' %}
{% load static %}
{% load i18n %}
{% block title %} - {% trans 'Help' %}{% endblock %}
{% block content %}
	{% trans 'Score -> Score: Your own total scores' %}

	{% trans 'Score -> Basic scoring: Add a new score, view all your scores' %}

	{% trans 'Ranking: Show all available players and their statistics, click on one player to view all his scores' %}
{% endblock %}


text:
using UnrealBuildTool;

public class AttackOnPotato : ModuleRules
{
	public AttackOnPotato(TargetInfo Target)
	{
		PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore" });
	}
}


text:
using System;
using UnityEngine;
using LuaInterface;
using Object = UnityEngine.Object;

public class AssetBundleWrap
{
	public static void Register(IntPtr L)
	{
		LuaMethod[] regs = new LuaMethod[]
		{
			new LuaMethod("LoadFromFileAsync", LoadFromFileAsync),
			new LuaMethod("LoadFromFile", LoadFromFile),
			new LuaMethod("LoadFromMemoryAsync", LoadFromMemoryAsync),
			new LuaMethod("LoadFromMemory", LoadFromMemory),
			new LuaMethod("Contains", Contains),
			new LuaMethod("LoadAsset", LoadAsset),
			new LuaMethod("LoadAssetAsync", LoadAssetAsync),
			new LuaMethod("LoadAssetWithSubAssets", LoadAssetWithSubAssets),
			new LuaMethod("LoadAssetWithSubAssetsAsync", LoadAssetWithSubAssetsAsync),
			new LuaMethod("LoadAllAssets", LoadAllAssets),
			new LuaMethod("LoadAllAssetsAsync", LoadAllAssetsAsync),
			new LuaMethod("Unload", Unload),
			new LuaMethod("GetAllAssetNames", GetAllAssetNames),
			new LuaMethod("GetAllScenePaths", GetAllScenePaths),
			new LuaMethod("New", _CreateAssetBundle),
			new LuaMethod("GetClassType", GetClassType),
			new LuaMethod("__eq", Lua_Eq),
		};

		LuaField[] fields = new LuaField[]
		{
			new LuaField("mainAsset", get_mainAsset, null),
		};

		LuaScriptMgr.RegisterLib(L, "UnityEngine.AssetBundle", typeof(AssetBundle), regs, fields, typeof(Object));
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int _CreateAssetBundle(IntPtr L)
	{
		int count = LuaDLL.lua_gettop(L);

		if (count == 0)
		{
			AssetBundle obj = new AssetBundle();
			LuaScriptMgr.Push(L, obj);
			return 1;
		}
		else
		{
			LuaDLL.luaL_error(L, "invalid arguments to method: AssetBundle.New");
		}

		return 0;
	}

	static Type classType = typeof(AssetBundle);

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int GetClassType(IntPtr L)
	{
		LuaScriptMgr.Push(L, classType);
		return 1;
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int get_mainAsset(IntPtr L)
	{
		object o = LuaScriptMgr.GetLuaObject(L, 1);
		AssetBundle obj = (AssetBundle)o;

		if (obj == null)
		{
			LuaTypes types = LuaDLL.lua_type(L, 1);

			if (types == LuaTypes.LUA_TTABLE)
			{
				LuaDLL.luaL_error(L, "unknown member name mainAsset");
			}
			else
			{
				LuaDLL.luaL_error(L, "attempt to index mainAsset on a nil value");
			}
		}

		LuaScriptMgr.Push(L, obj.mainAsset);
		return 1;
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int LoadFromFileAsync(IntPtr L)
	{
		int count = LuaDLL.lua_gettop(L);

		if (count == 1)
		{
			string arg0 = LuaScriptMgr.GetLuaString(L, 1);
			AssetBundleCreateRequest o = AssetBundle.LoadFromFileAsync(arg0);
			LuaScriptMgr.PushObject(L, o);
			return 1;
		}
		else if (count == 2)
		{
			string arg0 = LuaScriptMgr.GetLuaString(L, 1);
			uint arg1 = (uint)LuaScriptMgr.GetNumber(L, 2);
			AssetBundleCreateRequest o = AssetBundle.LoadFromFileAsync(arg0,arg1);
			LuaScriptMgr.PushObject(L, o);
			return 1;
		}
		else
		{
			LuaDLL.luaL_error(L, "invalid arguments to method: AssetBundle.LoadFromFileAsync");
		}

		return 0;
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int LoadFromFile(IntPtr L)
	{
		int count = LuaDLL.lua_gettop(L);

		if (count == 1)
		{
			string arg0 = LuaScriptMgr.GetLuaString(L, 1);
			AssetBundle o = AssetBundle.LoadFromFile(arg0);
			LuaScriptMgr.Push(L, o);
			return 1;
		}
		else if (count == 2)
		{
			string arg0 = LuaScriptMgr.GetLuaString(L, 1);
			uint arg1 = (uint)LuaScriptMgr.GetNumber(L, 2);
			AssetBundle o = AssetBundle.LoadFromFile(arg0,arg1);
			LuaScriptMgr.Push(L, o);
			return 1;
		}
		else
		{
			LuaDLL.luaL_error(L, "invalid arguments to method: AssetBundle.LoadFromFile");
		}

		return 0;
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int LoadFromMemoryAsync(IntPtr L)
	{
		int count = LuaDLL.lua_gettop(L);

		if (count == 1)
		{
			byte[] objs0 = LuaScriptMgr.GetArrayNumber<byte>(L, 1);
			AssetBundleCreateRequest o = AssetBundle.LoadFromMemoryAsync(objs0);
			LuaScriptMgr.PushObject(L, o);
			return 1;
		}
		else if (count == 2)
		{
			byte[] objs0 = LuaScriptMgr.GetArrayNumber<byte>(L, 1);
			uint arg1 = (uint)LuaScriptMgr.GetNumber(L, 2);
			AssetBundleCreateRequest o = AssetBundle.LoadFromMemoryAsync(objs0,arg1);
			LuaScriptMgr.PushObject(L, o);
			return 1;
		}
		else
		{
			LuaDLL.luaL_error(L, "invalid arguments to method: AssetBundle.LoadFromMemoryAsync");
		}

		return 0;
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int LoadFromMemory(IntPtr L)
	{
		int count = LuaDLL.lua_gettop(L);

		if (count == 1)
		{
			byte[] objs0 = LuaScriptMgr.GetArrayNumber<byte>(L, 1);
			AssetBundle o = AssetBundle.LoadFromMemory(objs0);
			LuaScriptMgr.Push(L, o);
			return 1;
		}
		else if (count == 2)
		{
			byte[] objs0 = LuaScriptMgr.GetArrayNumber<byte>(L, 1);
			uint arg1 = (uint)LuaScriptMgr.GetNumber(L, 2);
			AssetBundle o = AssetBundle.LoadFromMemory(objs0,arg1);
			LuaScriptMgr.Push(L, o);
			return 1;
		}
		else
		{
			LuaDLL.luaL_error(L, "invalid arguments to method: AssetBundle.LoadFromMemory");
		}

		return 0;
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int Contains(IntPtr L)
	{
		LuaScriptMgr.CheckArgsCount(L, 2);
		AssetBundle obj = (AssetBundle)LuaScriptMgr.GetUnityObjectSelf(L, 1, "AssetBundle");
		string arg0 = LuaScriptMgr.GetLuaString(L, 2);
		bool o = obj.Contains(arg0);
		LuaScriptMgr.Push(L, o);
		return 1;
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int LoadAsset(IntPtr L)
	{
		int count = LuaDLL.lua_gettop(L);

		if (count == 2)
		{
			AssetBundle obj = (AssetBundle)LuaScriptMgr.GetUnityObjectSelf(L, 1, "AssetBundle");
			string arg0 = LuaScriptMgr.GetLuaString(L, 2);
			Object o = obj.LoadAsset(arg0);
			LuaScriptMgr.Push(L, o);
			return 1;
		}
		else if (count == 3)
		{
			AssetBundle obj = (AssetBundle)LuaScriptMgr.GetUnityObjectSelf(L, 1, "AssetBundle");
			string arg0 = LuaScriptMgr.GetLuaString(L, 2);
			Type arg1 = LuaScriptMgr.GetTypeObject(L, 3);
			Object o = obj.LoadAsset(arg0,arg1);
			LuaScriptMgr.Push(L, o);
			return 1;
		}
		else
		{
			LuaDLL.luaL_error(L, "invalid arguments to method: AssetBundle.LoadAsset");
		}

		return 0;
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int LoadAssetAsync(IntPtr L)
	{
		int count = LuaDLL.lua_gettop(L);

		if (count == 2)
		{
			AssetBundle obj = (AssetBundle)LuaScriptMgr.GetUnityObjectSelf(L, 1, "AssetBundle");
			string arg0 = LuaScriptMgr.GetLuaString(L, 2);
			AssetBundleRequest o = obj.LoadAssetAsync(arg0);
			LuaScriptMgr.PushObject(L, o);
			return 1;
		}
		else if (count == 3)
		{
			AssetBundle obj = (AssetBundle)LuaScriptMgr.GetUnityObjectSelf(L, 1, "AssetBundle");
			string arg0 = LuaScriptMgr.GetLuaString(L, 2);
			Type arg1 = LuaScriptMgr.GetTypeObject(L, 3);
			AssetBundleRequest o = obj.LoadAssetAsync(arg0,arg1);
			LuaScriptMgr.PushObject(L, o);
			return 1;
		}
		else
		{
			LuaDLL.luaL_error(L, "invalid arguments to method: AssetBundle.LoadAssetAsync");
		}

		return 0;
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int LoadAssetWithSubAssets(IntPtr L)
	{
		int count = LuaDLL.lua_gettop(L);

		if (count == 2)
		{
			AssetBundle obj = (AssetBundle)LuaScriptMgr.GetUnityObjectSelf(L, 1, "AssetBundle");
			string arg0 = LuaScriptMgr.GetLuaString(L, 2);
			Object[] o = obj.LoadAssetWithSubAssets(arg0);
			LuaScriptMgr.PushArray(L, o);
			return 1;
		}
		else if (count == 3)
		{
			AssetBundle obj = (AssetBundle)LuaScriptMgr.GetUnityObjectSelf(L, 1, "AssetBundle");
			string arg0 = LuaScriptMgr.GetLuaString(L, 2);
			Type arg1 = LuaScriptMgr.GetTypeObject(L, 3);
			Object[] o = obj.LoadAssetWithSubAssets(arg0,arg1);
			LuaScriptMgr.PushArray(L, o);
			return 1;
		}
		else
		{
			LuaDLL.luaL_error(L, "invalid arguments to method: AssetBundle.LoadAssetWithSubAssets");
		}

		return 0;
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int LoadAssetWithSubAssetsAsync(IntPtr L)
	{
		int count = LuaDLL.lua_gettop(L);

		if (count == 2)
		{
			AssetBundle obj = (AssetBundle)LuaScriptMgr.GetUnityObjectSelf(L, 1, "AssetBundle");
			string arg0 = LuaScriptMgr.GetLuaString(L, 2);
			AssetBundleRequest o = obj.LoadAssetWithSubAssetsAsync(arg0);
			LuaScriptMgr.PushObject(L, o);
			return 1;
		}
		else if (count == 3)
		{
			AssetBundle obj = (AssetBundle)LuaScriptMgr.GetUnityObjectSelf(L, 1, "AssetBundle");
			string arg0 = LuaScriptMgr.GetLuaString(L, 2);
			Type arg1 = LuaScriptMgr.GetTypeObject(L, 3);
			AssetBundleRequest o = obj.LoadAssetWithSubAssetsAsync(arg0,arg1);
			LuaScriptMgr.PushObject(L, o);
			return 1;
		}
		else
		{
			LuaDLL.luaL_error(L, "invalid arguments to method: AssetBundle.LoadAssetWithSubAssetsAsync");
		}

		return 0;
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int LoadAllAssets(IntPtr L)
	{
		int count = LuaDLL.lua_gettop(L);

		if (count == 1)
		{
			AssetBundle obj = (AssetBundle)LuaScriptMgr.GetUnityObjectSelf(L, 1, "AssetBundle");
			Object[] o = obj.LoadAllAssets();
			LuaScriptMgr.PushArray(L, o);
			return 1;
		}
		else if (count == 2)
		{
			AssetBundle obj = (AssetBundle)LuaScriptMgr.GetUnityObjectSelf(L, 1, "AssetBundle");
			Type arg0 = LuaScriptMgr.GetTypeObject(L, 2);
			Object[] o = obj.LoadAllAssets(arg0);
			LuaScriptMgr.PushArray(L, o);
			return 1;
		}
		else
		{
			LuaDLL.luaL_error(L, "invalid arguments to method: AssetBundle.LoadAllAssets");
		}

		return 0;
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int LoadAllAssetsAsync(IntPtr L)
	{
		int count = LuaDLL.lua_gettop(L);

		if (count == 1)
		{
			AssetBundle obj = (AssetBundle)LuaScriptMgr.GetUnityObjectSelf(L, 1, "AssetBundle");
			AssetBundleRequest o = obj.LoadAllAssetsAsync();
			LuaScriptMgr.PushObject(L, o);
			return 1;
		}
		else if (count == 2)
		{
			AssetBundle obj = (AssetBundle)LuaScriptMgr.GetUnityObjectSelf(L, 1, "AssetBundle");
			Type arg0 = LuaScriptMgr.GetTypeObject(L, 2);
			AssetBundleRequest o = obj.LoadAllAssetsAsync(arg0);
			LuaScriptMgr.PushObject(L, o);
			return 1;
		}
		else
		{
			LuaDLL.luaL_error(L, "invalid arguments to method: AssetBundle.LoadAllAssetsAsync");
		}

		return 0;
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int Unload(IntPtr L)
	{
		LuaScriptMgr.CheckArgsCount(L, 2);
		AssetBundle obj = (AssetBundle)LuaScriptMgr.GetUnityObjectSelf(L, 1, "AssetBundle");
		bool arg0 = LuaScriptMgr.GetBoolean(L, 2);
		obj.Unload(arg0);
		return 0;
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int GetAllAssetNames(IntPtr L)
	{
		LuaScriptMgr.CheckArgsCount(L, 1);
		AssetBundle obj = (AssetBundle)LuaScriptMgr.GetUnityObjectSelf(L, 1, "AssetBundle");
		string[] o = obj.GetAllAssetNames();
		LuaScriptMgr.PushArray(L, o);
		return 1;
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int GetAllScenePaths(IntPtr L)
	{
		LuaScriptMgr.CheckArgsCount(L, 1);
		AssetBundle obj = (AssetBundle)LuaScriptMgr.GetUnityObjectSelf(L, 1, "AssetBundle");
		string[] o = obj.GetAllScenePaths();
		LuaScriptMgr.PushArray(L, o);
		return 1;
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int Lua_Eq(IntPtr L)
	{
		LuaScriptMgr.CheckArgsCount(L, 2);
		Object arg0 = LuaScriptMgr.GetLuaObject(L, 1) as Object;
		Object arg1 = LuaScriptMgr.GetLuaObject(L, 2) as Object;
		bool o = arg0 == arg1;
		LuaScriptMgr.Push(L, o);
		return 1;
	}
}


text:
<?php

namespace Enqueue\Consumption;

use Enqueue\Consumption\Context\End;
use Enqueue\Consumption\Context\InitLogger;
use Enqueue\Consumption\Context\MessageReceived;
use Enqueue\Consumption\Context\MessageResult;
use Enqueue\Consumption\Context\PostConsume;
use Enqueue\Consumption\Context\PostMessageReceived;
use Enqueue\Consumption\Context\PreConsume;
use Enqueue\Consumption\Context\PreSubscribe;
use Enqueue\Consumption\Context\ProcessorException;
use Enqueue\Consumption\Context\Start;

class ChainExtension implements ExtensionInterface
{
    private $startExtensions;
    private $initLoggerExtensions;
    private $preSubscribeExtensions;
    private $preConsumeExtensions;
    private $messageReceivedExtensions;
    private $messageResultExtensions;
    private $postMessageReceivedExtensions;
    private $processorExceptionExtensions;
    private $postConsumeExtensions;
    private $endExtensions;

    public function __construct(array $extensions)
    {
        $this->startExtensions = [];
        $this->initLoggerExtensions = [];
        $this->preSubscribeExtensions = [];
        $this->preConsumeExtensions = [];
        $this->messageReceivedExtensions = [];
        $this->messageResultExtensions = [];
        $this->postMessageReceivedExtensions = [];
        $this->processorExceptionExtensions = [];
        $this->postConsumeExtensions = [];
        $this->endExtensions = [];

        array_walk($extensions, function ($extension) {
            if ($extension instanceof ExtensionInterface) {
                $this->startExtensions[] = $extension;
                $this->initLoggerExtensions[] = $extension;
                $this->preSubscribeExtensions[] = $extension;
                $this->preConsumeExtensions[] = $extension;
                $this->messageReceivedExtensions[] = $extension;
                $this->messageResultExtensions[] = $extension;
                $this->postMessageReceivedExtensions[] = $extension;
                $this->processorExceptionExtensions[] = $extension;
                $this->postConsumeExtensions[] = $extension;
                $this->endExtensions[] = $extension;

                return;
            }

            $extensionValid = false;
            if ($extension instanceof StartExtensionInterface) {
                $this->startExtensions[] = $extension;

                $extensionValid = true;
            }

            if ($extension instanceof InitLoggerExtensionInterface) {
                $this->initLoggerExtensions[] = $extension;

                $extensionValid = true;
            }

            if ($extension instanceof PreSubscribeExtensionInterface) {
                $this->preSubscribeExtensions[] = $extension;

                $extensionValid = true;
            }

            if ($extension instanceof PreConsumeExtensionInterface) {
                $this->preConsumeExtensions[] = $extension;

                $extensionValid = true;
            }

            if ($extension instanceof MessageReceivedExtensionInterface) {
                $this->messageReceivedExtensions[] = $extension;

                $extensionValid = true;
            }

            if ($extension instanceof MessageResultExtensionInterface) {
                $this->messageResultExtensions[] = $extension;

                $extensionValid = true;
            }

            if ($extension instanceof ProcessorExceptionExtensionInterface) {
                $this->processorExceptionExtensions[] = $extension;

                $extensionValid = true;
            }

            if ($extension instanceof PostMessageReceivedExtensionInterface) {
                $this->postMessageReceivedExtensions[] = $extension;

                $extensionValid = true;
            }

            if ($extension instanceof PostConsumeExtensionInterface) {
                $this->postConsumeExtensions[] = $extension;

                $extensionValid = true;
            }

            if ($extension instanceof EndExtensionInterface) {
                $this->endExtensions[] = $extension;

                $extensionValid = true;
            }

            if (false == $extensionValid) {
                throw new \LogicException(sprintf('Invalid extension given %s', get_class($extension)));
            }
        });
    }

    public function onInitLogger(InitLogger $context): void
    {
        foreach ($this->initLoggerExtensions as $extension) {
            $extension->onInitLogger($context);
        }
    }

    public function onStart(Start $context): void
    {
        foreach ($this->startExtensions as $extension) {
            $extension->onStart($context);
        }
    }

    public function onPreSubscribe(PreSubscribe $context): void
    {
        foreach ($this->preSubscribeExtensions as $extension) {
            $extension->onPreSubscribe($context);
        }
    }

    public function onPreConsume(PreConsume $context): void
    {
        foreach ($this->preConsumeExtensions as $extension) {
            $extension->onPreConsume($context);
        }
    }

    public function onMessageReceived(MessageReceived $context): void
    {
        foreach ($this->messageReceivedExtensions as $extension) {
            $extension->onMessageReceived($context);
        }
    }

    public function onResult(MessageResult $context): void
    {
        foreach ($this->messageResultExtensions as $extension) {
            $extension->onResult($context);
        }
    }

    public function onProcessorException(ProcessorException $context): void
    {
        foreach ($this->processorExceptionExtensions as $extension) {
            $extension->onProcessorException($context);
        }
    }

    public function onPostMessageReceived(PostMessageReceived $context): void
    {
        foreach ($this->postMessageReceivedExtensions as $extension) {
            $extension->onPostMessageReceived($context);
        }
    }

    public function onPostConsume(PostConsume $context): void
    {
        foreach ($this->postConsumeExtensions as $extension) {
            $extension->onPostConsume($context);
        }
    }

    public function onEnd(End $context): void
    {
        foreach ($this->endExtensions as $extension) {
            $extension->onEnd($context);
        }
    }
}


text:
package kubemark

import (
	"fmt"
	"time"

	"k8s.io/klog/v2"
	"k8s.io/utils/mount"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	clientset "k8s.io/client-go/kubernetes"
	internalapi "k8s.io/cri-api/pkg/apis"
	kubeletapp "k8s.io/kubernetes/cmd/kubelet/app"
	"k8s.io/kubernetes/cmd/kubelet/app/options"
	"k8s.io/kubernetes/pkg/kubelet"
	kubeletconfig "k8s.io/kubernetes/pkg/kubelet/apis/config"
	"k8s.io/kubernetes/pkg/kubelet/cadvisor"
	"k8s.io/kubernetes/pkg/kubelet/cm"
	containertest "k8s.io/kubernetes/pkg/kubelet/container/testing"
	kubetypes "k8s.io/kubernetes/pkg/kubelet/types"
	"k8s.io/kubernetes/pkg/util/oom"
	"k8s.io/kubernetes/pkg/volume"
	"k8s.io/kubernetes/pkg/volume/cephfs"
	"k8s.io/kubernetes/pkg/volume/configmap"
	"k8s.io/kubernetes/pkg/volume/csi"
	"k8s.io/kubernetes/pkg/volume/downwardapi"
	"k8s.io/kubernetes/pkg/volume/emptydir"
	"k8s.io/kubernetes/pkg/volume/fc"
	"k8s.io/kubernetes/pkg/volume/flocker"
	"k8s.io/kubernetes/pkg/volume/git_repo"
	"k8s.io/kubernetes/pkg/volume/glusterfs"
	"k8s.io/kubernetes/pkg/volume/hostpath"
	"k8s.io/kubernetes/pkg/volume/iscsi"
	"k8s.io/kubernetes/pkg/volume/local"
	"k8s.io/kubernetes/pkg/volume/nfs"
	"k8s.io/kubernetes/pkg/volume/portworx"
	"k8s.io/kubernetes/pkg/volume/projected"
	"k8s.io/kubernetes/pkg/volume/quobyte"
	"k8s.io/kubernetes/pkg/volume/rbd"
	"k8s.io/kubernetes/pkg/volume/scaleio"
	"k8s.io/kubernetes/pkg/volume/secret"
	"k8s.io/kubernetes/pkg/volume/storageos"
	"k8s.io/kubernetes/pkg/volume/util/hostutil"
	"k8s.io/kubernetes/pkg/volume/util/subpath"
	"k8s.io/kubernetes/test/utils"
)

type HollowKubelet struct {
	KubeletFlags         *options.KubeletFlags
	KubeletConfiguration *kubeletconfig.KubeletConfiguration
	KubeletDeps          *kubelet.Dependencies
}

func volumePlugins() []volume.VolumePlugin {
	allPlugins := []volume.VolumePlugin{}
	allPlugins = append(allPlugins, emptydir.ProbeVolumePlugins()...)
	allPlugins = append(allPlugins, git_repo.ProbeVolumePlugins()...)
	allPlugins = append(allPlugins, hostpath.ProbeVolumePlugins(volume.VolumeConfig{})...)
	allPlugins = append(allPlugins, nfs.ProbeVolumePlugins(volume.VolumeConfig{})...)
	allPlugins = append(allPlugins, secret.ProbeVolumePlugins()...)
	allPlugins = append(allPlugins, iscsi.ProbeVolumePlugins()...)
	allPlugins = append(allPlugins, glusterfs.ProbeVolumePlugins()...)
	allPlugins = append(allPlugins, rbd.ProbeVolumePlugins()...)
	allPlugins = append(allPlugins, quobyte.ProbeVolumePlugins()...)
	allPlugins = append(allPlugins, cephfs.ProbeVolumePlugins()...)
	allPlugins = append(allPlugins, downwardapi.ProbeVolumePlugins()...)
	allPlugins = append(allPlugins, fc.ProbeVolumePlugins()...)
	allPlugins = append(allPlugins, flocker.ProbeVolumePlugins()...)
	allPlugins = append(allPlugins, configmap.ProbeVolumePlugins()...)
	allPlugins = append(allPlugins, projected.ProbeVolumePlugins()...)
	allPlugins = append(allPlugins, portworx.ProbeVolumePlugins()...)
	allPlugins = append(allPlugins, scaleio.ProbeVolumePlugins()...)
	allPlugins = append(allPlugins, local.ProbeVolumePlugins()...)
	allPlugins = append(allPlugins, storageos.ProbeVolumePlugins()...)
	allPlugins = append(allPlugins, csi.ProbeVolumePlugins()...)
	return allPlugins
}

func NewHollowKubelet(
	flags *options.KubeletFlags,
	config *kubeletconfig.KubeletConfiguration,
	client *clientset.Clientset,
	heartbeatClient *clientset.Clientset,
	cadvisorInterface cadvisor.Interface,
	imageService internalapi.ImageManagerService,
	runtimeService internalapi.RuntimeService,
	containerManager cm.ContainerManager) *HollowKubelet {
	d := &kubelet.Dependencies{
		KubeClient:           client,
		HeartbeatClient:      heartbeatClient,
		RemoteRuntimeService: runtimeService,
		RemoteImageService:   imageService,
		CAdvisorInterface:    cadvisorInterface,
		Cloud:                nil,
		OSInterface:          &containertest.FakeOS{},
		ContainerManager:     containerManager,
		VolumePlugins:        volumePlugins(),
		TLSOptions:           nil,
		OOMAdjuster:          oom.NewFakeOOMAdjuster(),
		Mounter:              &mount.FakeMounter{},
		Subpather:            &subpath.FakeSubpath{},
		HostUtil:             hostutil.NewFakeHostUtil(nil),
	}

	return &HollowKubelet{
		KubeletFlags:         flags,
		KubeletConfiguration: config,
		KubeletDeps:          d,
	}
}

// Starts this HollowKubelet and blocks.
func (hk *HollowKubelet) Run() {
	if err := kubeletapp.RunKubelet(&options.KubeletServer{
		KubeletFlags:         *hk.KubeletFlags,
		KubeletConfiguration: *hk.KubeletConfiguration,
	}, hk.KubeletDeps, false); err != nil {
		klog.Fatalf("Failed to run HollowKubelet: %v. Exiting.", err)
	}
	select {}
}

// HollowKubletOptions contains settable parameters for hollow kubelet.
type HollowKubletOptions struct {
	NodeName            string
	KubeletPort         int
	KubeletReadOnlyPort int
	MaxPods             int
	PodsPerCore         int
	NodeLabels          map[string]string
}

// Builds a KubeletConfiguration for the HollowKubelet, ensuring that the
// usual defaults are applied for fields we do not override.
func GetHollowKubeletConfig(opt *HollowKubletOptions) (*options.KubeletFlags, *kubeletconfig.KubeletConfiguration) {
	testRootDir := utils.MakeTempDirOrDie("hollow-kubelet.", "")
	podFilePath := utils.MakeTempDirOrDie("static-pods", testRootDir)
	klog.Infof("Using %s as root dir for hollow-kubelet", testRootDir)

	// Flags struct
	f := options.NewKubeletFlags()
	f.RootDirectory = testRootDir
	f.HostnameOverride = opt.NodeName
	f.MinimumGCAge = metav1.Duration{Duration: 1 * time.Minute}
	f.MaxContainerCount = 100
	f.MaxPerPodContainerCount = 2
	f.NodeLabels = opt.NodeLabels
	f.ContainerRuntimeOptions.ContainerRuntime = kubetypes.RemoteContainerRuntime
	f.RegisterNode = true
	f.RegisterSchedulable = true

	// Config struct
	c, err := options.NewKubeletConfiguration()
	if err != nil {
		panic(err)
	}

	c.StaticPodURL = ""
	c.EnableServer = true
	c.Address = "0.0.0.0" /* bind address */
	c.Port = int32(opt.KubeletPort)
	c.ReadOnlyPort = int32(opt.KubeletReadOnlyPort)
	c.StaticPodPath = podFilePath
	c.FileCheckFrequency.Duration = 20 * time.Second
	c.HTTPCheckFrequency.Duration = 20 * time.Second
	c.NodeStatusUpdateFrequency.Duration = 10 * time.Second
	c.NodeStatusReportFrequency.Duration = 5 * time.Minute
	c.SyncFrequency.Duration = 10 * time.Second
	c.EvictionPressureTransitionPeriod.Duration = 5 * time.Minute
	c.MaxPods = int32(opt.MaxPods)
	c.PodsPerCore = int32(opt.PodsPerCore)
	c.ClusterDNS = []string{}
	c.ImageGCHighThresholdPercent = 90
	c.ImageGCLowThresholdPercent = 80
	c.ProviderID = fmt.Sprintf("kubemark://%v", opt.NodeName)
	c.VolumeStatsAggPeriod.Duration = time.Minute
	c.CgroupRoot = ""
	c.CPUCFSQuota = true
	c.EnableControllerAttachDetach = false
	c.EnableDebuggingHandlers = true
	c.CgroupsPerQOS = false
	// hairpin-veth is used to allow hairpin packets. Note that this deviates from
	// what the "real" kubelet currently does, because there's no way to
	// set promiscuous mode on docker0.
	c.HairpinMode = kubeletconfig.HairpinVeth
	c.MaxOpenFiles = 1024
	c.RegistryBurst = 10
	c.RegistryPullQPS = 5.0
	c.ResolverConfig = kubetypes.ResolvConfDefault
	c.KubeletCgroups = "/kubelet"
	c.SerializeImagePulls = true
	c.SystemCgroups = ""
	c.ProtectKernelDefaults = false

	return f, c
}


text:
'use strict'

var fs = require('graceful-fs')
var path = require('path')
var Component = require('./compolib.Component')

var filetreeToJson = function filetreeToJSON (opts, dir, buildComponentsList) {
  buildComponentsList = typeof buildComponentsList !== 'undefined' ? buildComponentsList : false
  var output = []        // variable which later will be returned.

  fs.readdirSync(dir).filter(function (file) {
    if (file.charAt(0) === '.') return // ignore hidden files
    if ( /^.*\.demo\.[^.\n]+$/.test(file) ) return // ignore *.demo.* files
    var whitelisted = false
    var item = {}
    item.title = file                                    // filename.twig
    item.folder = dir.split(opts.location.src)[1]
    item.type = (path.extname(file) === '') ? 'folder' : path.extname(file).toLowerCase()  // folder || .json/.md/.twig..
    item.basename = path.basename(file, item.type)                     // filename
    if (item.type !== 'folder') {
      item.src = path.join('/components/' + item.folder, item.basename + opts.extensions.output)
    } else {
      item.src = path.join(dir, file)
    }

    if (item.type === 'folder') {
      // if directory call function on new path
      item.children = filetreeToJSON(opts, item.src, buildComponentsList)
      whitelisted = true
    } else {
      // if file, make sure it's whitelisted
      if (opts.extensions.template === item.type) {
        whitelisted = true
        // assamble Component
        if (buildComponentsList) {
          var component = new Component(opts, path.join(dir, file))
          component.assemble(opts)
        }
      }
    }
    if (whitelisted) output.push(item)
  })
  return output
}

module.exports = filetreeToJson


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/' debug="false">

    <appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
        <param name="target" value="System.out"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1} - %m%n"/>
        </layout>
    </appender>

    <category name="edu.javacourse">
        <priority value="debug"/>
        <appender-ref ref="consoleAppender"/>
    </category>

</log4j:configuration>


text:
'use strict'

import Orbit from 'orbit_'
import Reflux from 'reflux'
import AppActions from 'actions/AppActions'
import IpfsDaemonStore from 'stores/IpfsDaemonStore'
import IpfsDaemonActions from 'actions/IpfsDaemonActions'
import path from 'path'
import Logger from 'logplease'

const logger = Logger.create('OrbitStore', { color: Logger.Colors.Blue })
const isElectron = window.remote
const ipcRenderer = window.ipcRenderer

const OrbitStore = Reflux.createStore({
  listenables: [AppActions, IpfsDaemonActions],
  init: function() {
    this.orbit = null
    this.trigger(this.orbit)
  },
  onDisconnect: function() {
    this.orbit.disconnect()
  },
  onDaemonStarted: function(ipfs) {
    const options = {
      // path where to keep generates keys
      keystorePath: path.join(IpfsDaemonStore.getIpfsSettings().OrbitDataDir, "/data/keys"),
      // path to orbit-db cache file
      cachePath: path.join(IpfsDaemonStore.getIpfsSettings().OrbitDataDir, "/data/orbit-db"),
      // how many messages to retrieve from history on joining a channel
      maxHistory: isElectron ? 64 : 64,
    }

    this.orbit = new Orbit(ipfs, options)

    this.orbit.events.on('connected', (network, user) => {
      if(ipcRenderer)
        ipcRenderer.send('connected', network, user)
    })

    this.orbit.events.on('disconnected', () => {
      if(ipcRenderer)
        ipcRenderer.send('disconnected')
    })

    AppActions.initialize(this.orbit)
    this.trigger(this.orbit)
  },
})

export default OrbitStore


text:
class SubtractionModel : public MathOperationDataModel
{
public:

  virtual
  ~SubtractionModel() {}

public:

  QString
  caption() const override
  { return QStringLiteral("Subtraction"); }

  virtual bool
  portCaptionVisible(PortType portType, PortIndex portIndex) const override
  { return true; }

  virtual QString
  portCaption(PortType portType, PortIndex portIndex) const override
  {
    switch (portType)
    {
      case PortType::In:
        if (portIndex == 0)
          return QStringLiteral("Minuend");
        else if (portIndex == 1)
          return QStringLiteral("Subtrahend");

        break;

      case PortType::Out:
        return QStringLiteral("Result");

      default:
        break;
    }
    return QString();
  }

  QString
  name() const override
  { return QStringLiteral("Subtraction"); }

  std::unique_ptr<NodeDataModel>
  clone() const override
  { return std::make_unique<SubtractionModel>(); }

private:

  void
  compute() override
  {
    PortIndex const outPortIndex = 0;

    auto n1 = _number1.lock();
    auto n2 = _number2.lock();

    if (n1 && n2)
    {
      modelValidationState = NodeValidationState::Valid;
      modelValidationError = QString();
      _result = std::make_shared<DecimalData>(n1->number() -
                                              n2->number());
    }
    else
    {
      modelValidationState = NodeValidationState::Warning;
      modelValidationError = QStringLiteral("Missing or incorrect inputs");
      _result.reset();
    }

    emit dataUpdated(outPortIndex);
  }
};


text:
class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table(:users) do |t|
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      ## Rememberable
      t.datetime :remember_created_at

      t.timestamps
    end

    add_index :users, :email,                unique: true
  end
end


text:
import { helper } from '@ember/component/helper';

/**
 * Executes `Math.log2` on the number passed to the helper.
 *
 * ```hbs
 * {{log2 a}}
 * ```
 *
 * @param {number} number The number to pass to `Math.log2`
 * @return {number} The log2 of the passed number
 */
export function log2([number]) {
  return Math.log2(number);
}

export default helper(log2);


text:
package org.orienteer.core.component.widget.oclass;

import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.record.impl.ODocument;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.ResourceModel;
import org.orienteer.core.component.widget.AbstractSchemaLocalizationWidget;
import org.orienteer.core.widget.Widget;

/**
 * Widget to show and modify {@link com.orientechnologies.orient.core.metadata.schema.OClass} localization.
 */
@Widget(id="class-localization", domain="class", tab="localization", order=20, autoEnable=true)
public class OClassLocalizationWidget extends AbstractSchemaLocalizationWidget<OClass> {

    public OClassLocalizationWidget(String id, IModel<OClass> model, final IModel<ODocument> widgetDocumentModel) {
        super(id, model, widgetDocumentModel);

    }

    @Override
    protected String getLocalizationKey(OClass oProperty) {
        return getModelObject().getName();
    }

    @Override
    protected IModel<String> getDefaultTitleModel() {
        return new ResourceModel("class.localization");
    }
}


text:
g_Types = { Mouse: ["All", "List", "List_Background", "Tree", "Tabs", "Tabs_Background"] };

const src = await ReadTextFile("addons\\" + Addon_Id + "\\options.html");
const ar = [];
const s = "CSA";
for (let i = s.length; i--;) {
	ar.unshift('<input type="button" value="', await MainWindow.g_.KeyState[i][0], '" title="', s.charAt(i), '" onclick="AddMouse(this)">');
}
await SetTabContents(4, "", src.replace("%s", ar.join("")));

AddMouse = function (o) {
	document.E.MouseMouse.value += o.title;
	ChangeX("Mouse");
}

SaveLocation = async function () {
	SetChanged(null, document.E);
	await SaveX("Mouse", document.E);
}

LoadX("Mouse", null, document.E);


text:
var Application = require('../../../index').Application;
var util        = require('util');

function DemoApp() {
    DemoApp.super_.call(this);

    this.setConfig({
        component: __dirname + '/components',
        config: __dirname + '/config'
    });
}

util.inherits(DemoApp, Application);

module.exports = DemoApp;


text:
module Puppet::Parser::Functions
  newfunction(:upcase, :type => :rvalue, :doc => <<-DOC
    Converts a string or an array of strings to uppercase.

    *Examples:*

        upcase("abcd")

    Will return:

        ABCD

    Note: from Puppet 6.0.0, the compatible function with the same name in Puppet core
    will be used instead of this function.
  DOC
             ) do |arguments|

    raise(Puppet::ParseError, "upcase(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1

    value = arguments[0]

    unless value.is_a?(Array) || value.is_a?(Hash) || value.respond_to?(:upcase)
      raise(Puppet::ParseError, 'upcase(): Requires an array, hash or object that responds to upcase in order to work')
    end

    if value.is_a?(Array)
      # Numbers in Puppet are often string-encoded which is troublesome ...
      result = value.map { |i| function_upcase([i]) }
    elsif value.is_a?(Hash)
      result = {}
      value.each_pair do |k, v|
        result[function_upcase([k])] = function_upcase([v])
      end
    else
      result = value.upcase
    end

    return result
  end
end

# vim: set ts=2 sw=2 et :


text:
using System.Diagnostics.CodeAnalysis;

namespace PrtgAPI.Parameters
{
    [ExcludeFromCodeCoverage]
    class GetObjectPropertyParameters : BaseActionParameters, IHtmlParameters
    {
        HtmlFunction IHtmlParameters.Function => HtmlFunction.ObjectData;

        public GetObjectPropertyParameters(Either<IPrtgObject, int> objectOrId, object objectType) : base(objectOrId)
        {
            if (objectType != null)
                ObjectType = objectType;
        }

        public object ObjectType
        {
            get { return this[Parameter.ObjectType]; }
            set { this[Parameter.ObjectType] = value; }
        }
    }
}


text:
package org.apache.sftp.protocol.packetdata.openssh;

import org.apache.sftp.protocol.packetdata.Status;

/**
 * Implements the hardlink operation:
 *
 *

 * 10. sftp: Extension request "hardlink@openssh.com"
 *
 * This request is for creating a hard link to a regular file. This
 * request is implemented as a SSH_FXP_EXTENDED request with the
 * following format:
 *
 *         uint32          id
 *         string          "hardlink@openssh.com"
 *         string          oldpath
 *         string          newpath
 *
 * On receiving this request the server will perform the operation
 * link(oldpath, newpath) and will respond with a SSH_FXP_STATUS message.
 * This extension is advertised in the SSH_FXP_VERSION hello with version
 * "1".
 *

 *
 * @author Lucas Theisen
 * @see OpenSSH's deviations and extensions to the published SSH protocol
 */
public interface HardLink extends BaseExtendedPath<HardLink, Status> {
    public String getTargetPath();

    public HardLink setTargetPath( String targetPath );
}


text:
'use strict';

var TESTHELPER = require('./helper');
var assert = require('assert');

module.exports = {
  run: function(cb){
    TESTHELPER({
      list: require('./mocks/list-one-page'),
      final: require('./mocks/final-multiple-links'),
      testedMethod: 'getOne',
      options: {},
      assert: function(data){
        assert.equal(data.length, 5);
      },
      cb: cb
    });
  }
};


text:
import { Component, Input, OnInit, OnDestroy } from '@angular/core';

import { Observable }         from 'rxjs/Observable'
import { Subscription }       from 'rxjs/Subscription'

import { Config }             from '../config';
import { DeltaTimeAdjuster }  from '../models/delta-time-adjuster'

@Component({
  selector: 'uhunt-timer',
  template: '{{text}}',
})
export class TimerComponent implements OnInit, OnDestroy {
  // To ensure non negative elapsed time.
  private static local_adjuster = new DeltaTimeAdjuster(0);

  // Observables for updating the elements for each unit.
  // There are 4 units: 0: seconds, 1: minutes, 2: hours, 3: days.
  private static intervals = [
    Observable.interval(1000),
    Observable.interval(60 * 1000),
    Observable.interval(60 * 60 * 1000),
    Observable.interval(24 * 60 * 60 * 1000)
  ];

  @Input() timestamp: number;
  @Input() adjuster = TimerComponent.local_adjuster;
  text: string;

  private unit = -1;
  private subscription: Subscription;

  ngOnInit() {
    if (!isNaN(this.timestamp) && this.timestamp > 0) {
      this.update_text();
    }
  }

  private update_text() {
    if (this.adjuster == TimerComponent.local_adjuster) {
      TimerComponent.local_adjuster.set_now(this.timestamp);
    }
    let elapsed = this.adjuster.get_elapsed(this.timestamp);
    let new_unit = TimerComponent.get_unit(elapsed);
    if (new_unit > this.unit) {
      this.subscription && this.subscription.unsubscribe();
      this.unit = new_unit;
      this.subscription = (this.unit < 4 || elapsed < 0)
        ? TimerComponent.intervals[Math.min(3, this.unit)]
            .subscribe(() => this.update_text())
        : null;
    }
    this.text = TimerComponent.get_text(this.timestamp, this.unit, elapsed);
  }

  ngOnDestroy() {
    this.subscription && this.subscription.unsubscribe();
  }

  private static get_text(timestamp: number, unit: number, elapsed: number) {
    let suffix = elapsed < 0 ? '' : ' ago';
    elapsed = Math.abs(elapsed);
    switch (unit) {
      case 0: return Math.floor(elapsed) + ' secs' + suffix;
      case 1: return Math.floor(elapsed / 60) + ' mins' + suffix;
      case 2: return Math.floor(elapsed / 60 / 60) + ' hours' + suffix;
      case 3: return Math.floor(elapsed / 60 / 60 / 24) + ' days' + suffix;
      default: return TimerComponent.full_date(timestamp);
    }
  }

  public static full_date(timestamp: number): string {
    var d = new Date(timestamp * 1000);
    return this.addZeroPrefix(d.getFullYear(), 4) + '-' +
      this.addZeroPrefix(d.getMonth() + 1, 2) + '-' +
      this.addZeroPrefix(d.getDate(), 2) + ' ' +
      this.addZeroPrefix(d.getHours(), 2) + ':' +
      this.addZeroPrefix(d.getMinutes(), 2);
  }

  private static get_unit(elapsed: number): number {
    let w = Math.abs(elapsed);
    if (w <= 60) return 0;
    if (w <= 60 * 60) return 1;
    if (w <= 24 * 60 * 60) return 2;
    if (w <= 30 * 24 * 60 * 60) return 3;
    return 4;
  }

  private static addZeroPrefix(num: number, len: number): string {
    let v = '' + num;
    while (v.length < len) {
      v = '0' + v;
    }
    return v;
  }
}


text:
/**
 * @Author Lars Harmsen
 */

#pragma once

#include "ros/ros.h"
#include <geometry_msgs/PoseStamped.h>
#include "std_msgs/Int8.h"

#define TOPIC_ORIENTATION_IN "orientation/out"
#define TOPIC_ORIENTATION_OUT "orientation/in"
#define TOPIC_GO_SIGNAL "measure/go"

class ReplyOrientation
{
public:

	ReplyOrientation(void);
	~ReplyOrientation(void);

	void init();

	void publish(geometry_msgs::PoseStamped msg);

	void publishGoSignal();

	// --------------- Callbacks ---------------
	void orientationCallback(const geometry_msgs::PoseStamped& msg);

private:
	ros::NodeHandle node;
	ros::Subscriber orientationSub;
	ros::Publisher goSignalPub;
	ros::Publisher orientationPub;
};


text:
package placetracking.api.endpoint.reporting;

import java.util.ArrayList;
import java.util.List;

import placetracking.WebsiteRequest;
import placetracking.api.ApiResponse;
import placetracking.api.endpoint.Endpoint;
import placetracking.api.endpoint.EndpointManager;
import placetracking.util.slack.SlackPayload;
import placetracking.util.slack.SlackWebHook;

public class ReportingEndpoint extends Endpoint {

    public static final List<Endpoint> endpoints = getAvailableEndpoints();

    @Override
    public String getEndpointPath() {
        return EndpointManager.ENDPOINT_REPORTING;
    }

    @Override
    public ApiResponse processRequest(WebsiteRequest request) {
        Endpoint endpoint = EndpointManager.getEndpointForRequest(request, endpoints);
        if (endpoint != null) {
            ApiResponse response = endpoint.processRequest(request);

            String slackWebHookUrl = request.getParameter("slackWebHookUrl");
            if (slackWebHookUrl != null) {
                SlackPayload slackPayload = response.generateSlackPayload(request);
                SlackWebHook slackWebHook = new SlackWebHook(slackWebHookUrl);
                slackWebHook.setPayload(slackPayload);
                slackWebHook.post();
            }

            return response;
        } else {
            return super.processRequest(request);
        }
    }

    private static List<Endpoint> getAvailableEndpoints() {
        List<Endpoint> endpoints = new ArrayList<Endpoint>();
        endpoints.add(new DeltaReportingEndpoint());
        endpoints.add(new BinReportingEndpoint());
        return endpoints;
    }

}


text:
import { DEAD, CHECKING, READY, PLAYING, Player  } from './player.js';
import { Renderer } from './renderer.js';
import { AudioEngine, JUMP, DEATH } from './audio-engine.js';
import { Box } from './box.js';

const SPEED = 0.005;
const GRAVITY = 0.00035;
const PIPE_WIDTH = 1.0 / 15.0;
const MAX_HOLE_SIZE = 0.5;
const MIN_HOLE_SIZE = 0.35;
const TICKS_TO_NEXT_PIPE = 90;
const TIME_TO_WAIT_FOR_PLAYER_TO_BE_READY = 5000;
const SECONDS_TO_START = 5;
const SECONDS_TO_RESPAWN = 3;
const TICKS_TO_EXPIRE_PLAYER = 60;

export class Game {
  constructor(canvas, options) {
    options = options || {};
    this.state = {
      tick: 0,
      timeToNextBlock: 50,
      gravity: GRAVITY,
      speed: SPEED,
      players: [],
      boxes: [],
      stars: [],
      particles: [],
      highestScore: {
        name: null,
        score: 0
      }
    };

    this.players = {};
    this.renderer = new Renderer(canvas, {
      kinect: options.kinect
    });
    this.audioEngine = new AudioEngine();

    this.availableSlots = [-0.3, 0.3, -0.2, 0.2, -0.1, 0.1, 0.0];
    this.availableColors = [0, 1, 2, 3, 4, 5, 6];

    this.state.stars = [];

    for (let i = 0; i < 20; i++) {
      this.state.stars.push({
        x: Math.random() - 0.5,
        y: Math.random() - 0.5,
        speed: (0.4 + i * 0.05) * this.state.speed
      });
    }

    this.events = {};
  }

  init() {
  }

  update(frameData) {
    this.updatePlayers(frameData);
    this.updateState();

    this.renderScene();
  }

  updatePlayers(frameData) {
    let self = this;

    _.forEach(frameData, function (data) {
      if (data.bodyId === 0 || !data.active) {
        return;
      }

      let player = self.players[data.bodyId];

      if (!player) {
        player = self.createPlayer(data);
      }

      if (player.state !== DEAD) {
        player.updateDataWith(data);
      }
    });

    var i = self.state.players.length;
    while (i--) {
      let player = self.state.players[i];

      if (player.state !== DEAD) {
        player.age += 1;

        if (player.state !== CHECKING) {
          let oldVel = player.velocityY;
          player.restingPeriod += 1;

          player.stepTime(self.state.gravity);

          if (player.state === PLAYING) {
            player.livingPeriod += 1;
            player.currentScore = Math.floor(player.livingPeriod / 30);
          }

          if (oldVel < 0.0 && player.velocityY > 0.0) {
            self.audioEngine.play(JUMP[i % 6]);
          }
        }

        if (player.age > TICKS_TO_EXPIRE_PLAYER) {
          self.removePlayer(player);
        }
      }
    }
  }

  createPlayer(data) {
    let self = this,
        position = this.availableSlots.pop(),
        player = new Player(data, {
          x: position,
          y: 0.0
        }, 0.05, this.availableColors.pop());

    player.state = CHECKING;

    this.state.players.push(player);
    this.players[player.id] = player;

    this.scheduleEventForPlayer(player, function () {
      if (self.players[player.id]) {
        self.prepareGameFor(player);
      }
    }, TIME_TO_WAIT_FOR_PLAYER_TO_BE_READY);

    return player;
  }

  updateState() {
    let self = this,
        state = self.state;
    state.tick = state.tick + 1;

    if (self.shouldMakeANewObstacle()) {
      self.generateNewObstacle();
    }

    let toRemoveList = [];
    for (let i = 0; i < state.boxes.length; i++) {
      let box = state.boxes[i];
      if (box.position.x + box.halfWidth < -0.5) {
        toRemoveList.push(i);
      }

      box.position.x = box.position.x - state.speed;
    }

    _.forEach(state.stars, function (star, index) {
      star.x -= star.speed;

      if (star.x < -0.5) {
        star.x = 0.5;
        star.y = Math.random() - 0.5;
        star.speed = (0.4 + index * 0.05) * self.state.speed;
      }
    });

    let toRemove = toRemoveList.pop();
    while (toRemove) {
      state.boxes.splice(toRemove - 1, 1);
      toRemove = toRemoveList.pop();
    }

    _.forEach(state.players, function (player) {
      if (player.state !== DEAD && (player.position.y < player.halfSize - 0.5 ||
            player.position.y > 0.5 - player.halfSize ||
            player.position.x < player.halfSize - 0.5 ||
            player.position.x > 0.5 - player.halfSize)) {
        self.killPlayer(player);
        return;
      }

      if (player.state === PLAYING) {
        _.any(state.boxes, function (box) {
          if (box.didCollideWith(player)) {
            self.killPlayer(player);
            return true;
          }

          return false;
        });
      }
    });

    let i = state.particles.length;
    while (i--) {
      let particle = state.particles[i];

      particle.vy -= 3.5 * state.gravity;
      particle.x += particle.vx;
      particle.y += particle.vy;
      if (particle.y < -0.5) {
        state.particles.splice(i, 1);
      }
    }
  }

  killPlayer(player) {
    var self = this;

    player.state = DEAD;
    self.audioEngine.play(DEATH[self.state.players.indexOf(player) % 6]);
    if (player.currentScore > player.highScore) {
      player.highScore = player.currentScore;
    }

    let numParticles = Math.round(3 * Math.random() + 4);
    for (let i = 0; i < numParticles; i++) {
      let vx = Math.random() - 0.5,
          vy = 2.0 * Math.random(),
          v = 50 * Math.sqrt(vx*vx + vy*vy);

      self.state.particles.push({
        x: player.position.x + player.halfSize * (Math.random() - 0.5),
        y: player.position.y + player.halfSize * (Math.random() - 0.5),
        vx: vx / v,
        vy: vy / v,
        halfSize: player.halfSize / Math.sqrt(numParticles / 2),
        color: player.color
      });
    }

    if (player.currentScore > self.state.highestScore.score) {
      self.state.highestScore.name = player.name;
      self.state.highestScore.score = player.currentScore;
    }

    self.scheduleEventForPlayer(player, function () {
      self.prepareGameFor(player);
    }, 1000 * SECONDS_TO_RESPAWN);
  }

  removePlayer(player) {
    this.state.players.splice(this.state.players.indexOf(player), 1);
    delete this.players[player.id];

    this.availableSlots.push(player.position.x);
    this.availableColors.push(player.color);
  }

  prepareGameFor(player) {
    let self = this;
    player.state = READY;
    player.overheadText = SECONDS_TO_START;
    player.reset();

    var callback = function () {
      if (self.players[player.id] && player.state !== DEAD) {
        if (--player.overheadText) {
          self.scheduleEventForPlayer(player, callback, 1000);
        } else {
          player.state = PLAYING;
          player.overheadText = 'GO';

          self.scheduleEventForPlayer(player, function () {
            player.overheadText = null;
          }, 1000);
        }
      }
    };

    self.scheduleEventForPlayer(player, callback, 1000);
  }

  shouldMakeANewObstacle() {
    return this.state.tick % this.state.timeToNextBlock === 0;
  }

  generateNewObstacle() {
    var state = this.state;

    state.tick = 0;
    state.timeToNextBlock = Math.round(TICKS_TO_NEXT_PIPE * Math.random() / 3.3 + TICKS_TO_NEXT_PIPE);

    let size = (MAX_HOLE_SIZE - MIN_HOLE_SIZE) * Math.random() + MIN_HOLE_SIZE,
        pos = {
          x: 0.5 + PIPE_WIDTH,
          y: (1.0 - size) * Math.random() + size/2.0
        },
        heights = [
          Math.max(1.0 - size/2.0 - pos.y, 0.0),
          pos.y - size/2.0
        ];

    state.boxes.push(
      new Box({ x: pos.x, y: pos.y - 0.5 + size/2.0 + heights[0]/2.0 }, PIPE_WIDTH, heights[0])
    );
    state.boxes.push(
      new Box({ x: pos.x, y: pos.y - 0.5 - size/2.0 - heights[1]/2.0 }, PIPE_WIDTH, heights[1])
    );
  }

  renderScene() {
    this.renderer.render(this.state);
  }

  scheduleEventForPlayer(player, callback, time) {
    var self = this,
        event = this.events[player.id];
    if (event) {
      clearTimeout(event);
    }

    self.events[player.id] = setTimeout(function () {
      delete self.events[player.id];
      callback(player);
    }, time);
  }
}


text:
.. _qemu_leon3:

LEON3 Emulation (QEMU)
######################

Overview
********

The LEON3 QEMU board configuration is used to emulate the LEON3 processor.

.. figure:: qemu_leon3.png
   :width: 600px
   :align: center
   :alt: Qemu

   Qemu (Credit: qemu.org)

Programming and Debugging
*************************

Applications for the ``qemu_leon3`` board configuration can be built and run in
the usual way for emulated boards (see :ref:`build_an_application` and
:ref:`application_run` for more details).

Flashing
========

While this board is emulated and you can't "flash" it, you can use this
configuration to run basic Zephyr applications and kernel tests in the QEMU
emulated environment. For example, with the :ref:`synchronization_sample`:

.. zephyr-app-commands::
   :zephyr-app: samples/synchronization
   :host-os: unix
   :board: qemu_leon3
   :goals: run

This will build an image with the synchronization sample app, boot it using
QEMU, and display the following console output:

.. code-block:: console

        *** Booting Zephyr OS build zephyr-v2.4.0-27-g7b37fdd5303b  ***
        threadA: Hello World from qemu_leon3!
        threadB: Hello World from qemu_leon3!
        threadA: Hello World from qemu_leon3!
        threadB: Hello World from qemu_leon3!
        threadA: Hello World from qemu_leon3!
        threadB: Hello World from qemu_leon3!
        threadA: Hello World from qemu_leon3!
        threadB: Hello World from qemu_leon3!
        threadA: Hello World from qemu_leon3!
        threadB: Hello World from qemu_leon3!

Exit QEMU by pressing :kbd:`CTRL+A` :kbd:`x`.

Debugging
=========

Refer to the detailed overview about :ref:`application_debugging`.


text:
package org.elasticsearch.client;

import java.io.IOException;

import org.apache.http.client.methods.HttpGet;
import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsRequest;
import org.elasticsearch.common.Strings;

/**
 * RequestConverters扩展
 *
 * @author rewerma 2019-08-01
 * @version 1.0.0
 */
public class RequestConvertersExt {

    /**
     * 修改 getMappings 去掉request参数
     *
     * @param getMappingsRequest
     * @return
     * @throws IOException
     */
    static Request getMappings(GetMappingsRequest getMappingsRequest) throws IOException {
        String[] indices = getMappingsRequest.indices() == null ? Strings.EMPTY_ARRAY : getMappingsRequest.indices();
        String[] types = getMappingsRequest.types() == null ? Strings.EMPTY_ARRAY : getMappingsRequest.types();

        return new Request(HttpGet.METHOD_NAME, RequestConverters.endpoint(indices, "_mapping", types));
    }
}


text:
#include "OpenSLESUtilities.h"

namespace oboe {

/*
 * OSLES Helpers
 */

const char *getSLErrStr(SLresult code) {
    switch (code) {
        case SL_RESULT_SUCCESS:
            return "SL_RESULT_SUCCESS";
        case SL_RESULT_PRECONDITIONS_VIOLATED:
            return "SL_RESULT_PRECONDITIONS_VIOLATED";
        case SL_RESULT_PARAMETER_INVALID:
            return "SL_RESULT_PARAMETER_INVALID";
        case SL_RESULT_MEMORY_FAILURE:
            return "SL_RESULT_MEMORY_FAILURE";
        case SL_RESULT_RESOURCE_ERROR:
            return "SL_RESULT_RESOURCE_ERROR";
        case SL_RESULT_RESOURCE_LOST:
            return "SL_RESULT_RESOURCE_LOST";
        case SL_RESULT_IO_ERROR:
            return "SL_RESULT_IO_ERROR";
        case SL_RESULT_BUFFER_INSUFFICIENT:
            return "SL_RESULT_BUFFER_INSUFFICIENT";
        case SL_RESULT_CONTENT_CORRUPTED:
            return "SL_RESULT_CONTENT_CORRUPTED";
        case SL_RESULT_CONTENT_UNSUPPORTED:
            return "SL_RESULT_CONTENT_UNSUPPORTED";
        case SL_RESULT_CONTENT_NOT_FOUND:
            return "SL_RESULT_CONTENT_NOT_FOUND";
        case SL_RESULT_PERMISSION_DENIED:
            return "SL_RESULT_PERMISSION_DENIED";
        case SL_RESULT_FEATURE_UNSUPPORTED:
            return "SL_RESULT_FEATURE_UNSUPPORTED";
        case SL_RESULT_INTERNAL_ERROR:
            return "SL_RESULT_INTERNAL_ERROR";
        case SL_RESULT_UNKNOWN_ERROR:
            return "SL_RESULT_UNKNOWN_ERROR";
        case SL_RESULT_OPERATION_ABORTED:
            return "SL_RESULT_OPERATION_ABORTED";
        case SL_RESULT_CONTROL_LOST:
            return "SL_RESULT_CONTROL_LOST";
        default:
            return "Unknown SL error";
    }
}

SLAndroidDataFormat_PCM_EX OpenSLES_createExtendedFormat(
        SLDataFormat_PCM format, SLuint32 representation) {
    SLAndroidDataFormat_PCM_EX format_pcm_ex;
    format_pcm_ex.formatType = SL_ANDROID_DATAFORMAT_PCM_EX;
    format_pcm_ex.numChannels = format.numChannels;
    format_pcm_ex.sampleRate = format.samplesPerSec;
    format_pcm_ex.bitsPerSample = format.bitsPerSample;
    format_pcm_ex.containerSize = format.containerSize;
    format_pcm_ex.channelMask = format.channelMask;
    format_pcm_ex.endianness = format.endianness;
    format_pcm_ex.representation = representation;
    return format_pcm_ex;
}

SLuint32 OpenSLES_ConvertFormatToRepresentation(AudioFormat format) {
    switch(format) {
        case AudioFormat::I16:
            return SL_ANDROID_PCM_REPRESENTATION_SIGNED_INT;
        case AudioFormat::Float:
            return SL_ANDROID_PCM_REPRESENTATION_FLOAT;
        case AudioFormat::I24:
        case AudioFormat::I32:
        case AudioFormat::Invalid:
        case AudioFormat::Unspecified:
        default:
            return 0;
    }
}

} // namespace oboe


text:
vk

f

ru

en


text:
import os
import logging

from pegasus.models import TargetPlatform, Architecture, ProductType

from pegasus.targets.macosx_common import (process_params_for_driver,
	link_product_dependency, get_full_product_name, get_full_product_path,
	get_full_symbols_path, get_product_install_name, check_source_compiles,
	check_source_runs)

class iPhoneSimulator(TargetPlatform):
	def default_compiler(self):
		return "clang"

	def default_driver(self):
		return "xcode"

	def default_architectures(self):
		return [
			Architecture.x86
		]

	def prevalidate_driver_data(self, data):
		data.sdkroot = "iphonesimulator"

	def supports_fat_binaries(self):
		return True

	def process_params_for_driver(self, layoutparams, driver, driver_name):
		return process_params_for_driver(layoutparams, driver, driver_name)

	def link_product_dependency(self, toplevel, dependent):
		return link_product_dependency(self, toplevel, dependent)

	def get_full_product_name(self, product):
		return get_full_product_name(self, product)

	def get_full_product_path(self, product):
		return get_full_product_path(self, product)

	def get_full_symbols_path(self, product):
		return get_full_symbols_path(self, product)

	def get_product_install_name(self, product):
		return get_product_install_name(self, product)

	def product_supported(self, product, driver_instance, driver_name):
		unsupported = [ProductType.DynamicLibrary]
		if product.output in unsupported:
			logging.warn("Product type \"%s\" is not supported with the current platform/driver configuration." % product.output)
			return False

		return True

	def check_source_compiles(self, source, **kwargs):
		return check_source_compiles(source, **kwargs)

	def check_source_runs(self, source, **kwargs):
		return check_source_runs(source, **kwargs)