text:
package cli

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"io"
	"net"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/gorilla/mux"
	"github.com/pkg/errors"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	htpasswd "github.com/tg123/go-htpasswd"

	"github.com/kopia/kopia/internal/auth"
	"github.com/kopia/kopia/internal/ctxutil"
	"github.com/kopia/kopia/internal/server"
	"github.com/kopia/kopia/repo"
)

const serverRandomPasswordLength = 32

type commandServerStart struct {
	co connectOptions

	serverStartHTMLPath string

	serverStartUI                  bool
	serverStartLegacyRepositoryAPI bool
	serverStartGRPC                bool
	serverStartControlAPI          bool

	serverStartRefreshInterval time.Duration
	serverStartInsecure        bool
	serverStartMaxConcurrency  int

	serverStartWithoutPassword bool
	serverStartRandomPassword  bool
	serverStartHtpasswdFile    string

	randomServerControlPassword bool
	serverControlUsername       string
	serverControlPassword       string

	serverAuthCookieSingingKey string

	serverStartShutdownWhenStdinClosed bool

	serverStartTLSGenerateCert          bool
	serverStartTLSCertFile              string
	serverStartTLSKeyFile               string
	serverStartTLSGenerateRSAKeySize    int
	serverStartTLSGenerateCertValidDays int
	serverStartTLSGenerateCertNames     []string
	serverStartTLSPrintFullServerCert   bool
	uiTitlePrefix                       string
	uiPreferencesFile                   string
	asyncRepoConnect                    bool

	logServerRequests bool

	disableCSRFTokenChecks bool // disable CSRF token checks - used for development/debugging only

	sf  serverFlags
	svc advancedAppServices
	out textOutput
}

func (c *commandServerStart) setup(svc advancedAppServices, parent commandParent) {
	cmd := parent.Command("start", "Start Kopia server").Default()
	cmd.Flag("html", "Server the provided HTML at the root URL").ExistingDirVar(&c.serverStartHTMLPath)
	cmd.Flag("ui", "Start the server with HTML UI").Default("true").BoolVar(&c.serverStartUI)

	cmd.Flag("legacy-api", "Start the legacy server API").Default("true").BoolVar(&c.serverStartLegacyRepositoryAPI)
	cmd.Flag("grpc", "Start the GRPC server").Default("true").BoolVar(&c.serverStartGRPC)
	cmd.Flag("control-api", "Start the control API").Default("true").BoolVar(&c.serverStartControlAPI)

	cmd.Flag("refresh-interval", "Frequency for refreshing repository status").Default("300s").DurationVar(&c.serverStartRefreshInterval)
	cmd.Flag("insecure", "Allow insecure configurations (do not use in production)").Hidden().BoolVar(&c.serverStartInsecure)
	cmd.Flag("max-concurrency", "Maximum number of server goroutines").Default("0").IntVar(&c.serverStartMaxConcurrency)

	cmd.Flag("without-password", "Start the server without a password").Hidden().BoolVar(&c.serverStartWithoutPassword)
	cmd.Flag("random-password", "Generate random password and print to stderr").Hidden().BoolVar(&c.serverStartRandomPassword)
	cmd.Flag("htpasswd-file", "Path to htpasswd file that contains allowed user@hostname entries").Hidden().ExistingFileVar(&c.serverStartHtpasswdFile)

	cmd.Flag("random-server-control-password", "Generate random server control password and print to stderr").Hidden().BoolVar(&c.randomServerControlPassword)
	cmd.Flag("server-control-username", "Server control username").Default("server-control").Envar(svc.EnvName("KOPIA_SERVER_CONTROL_USER")).StringVar(&c.serverControlUsername)
	cmd.Flag("server-control-password", "Server control password").PlaceHolder("PASSWORD").Envar(svc.EnvName("KOPIA_SERVER_CONTROL_PASSWORD")).StringVar(&c.serverControlPassword)

	cmd.Flag("auth-cookie-signing-key", "Force particular auth cookie signing key").Envar(svc.EnvName("KOPIA_AUTH_COOKIE_SIGNING_KEY")).Hidden().StringVar(&c.serverAuthCookieSingingKey)

	cmd.Flag("shutdown-on-stdin", "Shut down the server when stdin handle has closed.").Hidden().BoolVar(&c.serverStartShutdownWhenStdinClosed)

	cmd.Flag("tls-generate-cert", "Generate TLS certificate").Hidden().BoolVar(&c.serverStartTLSGenerateCert)
	cmd.Flag("tls-cert-file", "TLS certificate PEM").StringVar(&c.serverStartTLSCertFile)
	cmd.Flag("tls-key-file", "TLS key PEM file").StringVar(&c.serverStartTLSKeyFile)
	cmd.Flag("tls-generate-rsa-key-size", "TLS RSA Key size (bits)").Hidden().Default("4096").IntVar(&c.serverStartTLSGenerateRSAKeySize)
	cmd.Flag("tls-generate-cert-valid-days", "How long should the TLS certificate be valid").Default("3650").Hidden().IntVar(&c.serverStartTLSGenerateCertValidDays)
	cmd.Flag("tls-generate-cert-name", "Host names/IP addresses to generate TLS certificate for").Default("127.0.0.1").Hidden().StringsVar(&c.serverStartTLSGenerateCertNames)
	cmd.Flag("tls-print-server-cert", "Print server certificate").Hidden().BoolVar(&c.serverStartTLSPrintFullServerCert)

	cmd.Flag("async-repo-connect", "Connect to repository asynchronously").Hidden().BoolVar(&c.asyncRepoConnect)
	cmd.Flag("ui-title-prefix", "UI title prefix").Hidden().Envar(svc.EnvName("KOPIA_UI_TITLE_PREFIX")).StringVar(&c.uiTitlePrefix)
	cmd.Flag("ui-preferences-file", "Path to JSON file storing UI preferences").StringVar(&c.uiPreferencesFile)

	cmd.Flag("log-server-requests", "Log server requests").Hidden().BoolVar(&c.logServerRequests)
	cmd.Flag("disable-csrf-token-checks", "Disable CSRF token").Hidden().BoolVar(&c.disableCSRFTokenChecks)

	c.sf.setup(svc, cmd)
	c.co.setup(svc, cmd)
	c.svc = svc
	c.out.setup(svc)

	cmd.Action(svc.baseActionWithContext(c.run))
}

func (c *commandServerStart) serverStartOptions(ctx context.Context) (*server.Options, error) {
	authn, err := c.getAuthenticator(ctx)
	if err != nil {
		return nil, errors.Wrap(err, "unable to initialize authentication")
	}

	uiPreferencesFile := c.uiPreferencesFile
	if uiPreferencesFile == "" {
		uiPreferencesFile = filepath.Join(filepath.Dir(c.svc.repositoryConfigFileName()), "ui-preferences.json")
	}

	return &server.Options{
		ConfigFile:           c.svc.repositoryConfigFileName(),
		ConnectOptions:       c.co.toRepoConnectOptions(),
		RefreshInterval:      c.serverStartRefreshInterval,
		MaxConcurrency:       c.serverStartMaxConcurrency,
		Authenticator:        authn,
		Authorizer:           auth.DefaultAuthorizer(),
		AuthCookieSigningKey: c.serverAuthCookieSingingKey,
		UIUser:               c.sf.serverUsername,
		ServerControlUser:    c.serverControlUsername,
		LogRequests:          c.logServerRequests,
		PasswordPersist:      c.svc.passwordPersistenceStrategy(),
		UIPreferencesFile:    uiPreferencesFile,
		UITitlePrefix:        c.uiTitlePrefix,

		DisableCSRFTokenChecks: c.disableCSRFTokenChecks,
	}, nil
}

func (c *commandServerStart) initRepositoryPossiblyAsync(ctx context.Context, srv *server.Server) error {
	initialize := func(ctx context.Context) (repo.Repository, error) {
		//nolint:wrapcheck
		return c.svc.openRepository(ctx, false)
	}

	if c.asyncRepoConnect {
		// retry initialization indefinitely
		initialize = server.RetryInitRepository(initialize)
	}

	if _, err := srv.InitRepositoryAsync(ctx, "Open", initialize, !c.asyncRepoConnect); err != nil {
		return errors.Wrap(err, "unable to initialize repository")
	}

	return nil
}

func (c *commandServerStart) run(ctx context.Context) error {
	opts, err := c.serverStartOptions(ctx)
	if err != nil {
		return err
	}

	srv, err := server.New(ctx, opts)
	if err != nil {
		return errors.Wrap(err, "unable to initialize server")
	}

	if err = c.initRepositoryPossiblyAsync(ctx, srv); err != nil {
		return errors.Wrap(err, "unable to initialize repository")
	}

	httpServer := &http.Server{
		ReadHeaderTimeout: 15 * time.Second, //nolint:gomnd
		Addr:              stripProtocol(c.sf.serverAddress),
		BaseContext: func(l net.Listener) context.Context {
			return ctx
		},
	}

	srv.OnShutdown = httpServer.Shutdown

	c.svc.onCtrlC(func() {
		log(ctx).Infof("Shutting down...")

		if serr := httpServer.Shutdown(ctx); serr != nil {
			log(ctx).Debugf("unable to shut down: %v", serr)
		}
	})

	c.svc.onRepositoryFatalError(func(_ error) {
		if serr := httpServer.Shutdown(ctx); serr != nil {
			log(ctx).Debugf("unable to shut down: %v", serr)
		}
	})

	m := mux.NewRouter()

	c.setupHandlers(srv, m)

	// init prometheus after adding interceptors that require credentials, so that this
	// handler can be called without auth
	initPrometheus(m)

	var handler http.Handler = m

	if c.serverStartGRPC {
		handler = srv.GRPCRouterHandler(handler)
	}

	httpServer.Handler = handler

	if c.serverStartShutdownWhenStdinClosed {
		log(ctx).Infof("Server will close when stdin is closed...")

		ctxutil.GoDetached(ctx, func(ctx context.Context) {
			// consume all stdin and close the server when it closes
			io.ReadAll(os.Stdin) //nolint:errcheck
			log(ctx).Infof("Shutting down server...")
			httpServer.Shutdown(ctx) //nolint:errcheck
		})
	}

	onExternalConfigReloadRequest(func() {
		if rerr := srv.Refresh(ctx); rerr != nil {
			log(ctx).Errorf("refresh failed: %v", rerr)
		}
	})

	err = c.startServerWithOptionalTLS(ctx, httpServer)
	if !errors.Is(err, http.ErrServerClosed) {
		return err
	}

	return errors.Wrap(srv.SetRepository(ctx, nil), "error setting active repository")
}

func (c *commandServerStart) setupHandlers(srv *server.Server, m *mux.Router) {
	if c.serverStartLegacyRepositoryAPI {
		srv.SetupRepositoryAPIHandlers(m)
	}

	if c.serverStartControlAPI {
		srv.SetupControlAPIHandlers(m)
	}

	if c.serverStartUI {
		srv.SetupHTMLUIAPIHandlers(m)

		if c.serverStartHTMLPath != "" {
			srv.ServeStaticFiles(m, http.Dir(c.serverStartHTMLPath))
		} else {
			srv.ServeStaticFiles(m, server.AssetFile())
		}
	}
}

func initPrometheus(m *mux.Router) {
	m.Handle("/metrics", promhttp.Handler())
}

func stripProtocol(addr string) string {
	return strings.TrimPrefix(strings.TrimPrefix(addr, "https://"), "http://")
}

func (c *commandServerStart) getAuthenticator(ctx context.Context) (auth.Authenticator, error) {
	var authenticators []auth.Authenticator

	// handle passwords (UI and remote) from htpasswd file.
	if c.serverStartHtpasswdFile != "" {
		f, err := htpasswd.New(c.serverStartHtpasswdFile, htpasswd.DefaultSystems, nil)
		if err != nil {
			return nil, errors.Wrap(err, "error initializing htpasswd")
		}

		authenticators = append(authenticators, auth.AuthenticateHtpasswdFile(f))
	}

	// handle UI password (--without-password, --password or --random-password)
	switch {
	case c.serverStartWithoutPassword:
		if !c.serverStartInsecure {
			return nil, errors.Errorf("--without-password specified without --insecure, refusing to start server")
		}

		return nil, nil

	case c.sf.serverPassword != "":
		authenticators = append(authenticators, auth.AuthenticateSingleUser(c.sf.serverUsername, c.sf.serverPassword))

	case c.serverStartRandomPassword:
		// generate very long random one-time password
		b := make([]byte, serverRandomPasswordLength)
		io.ReadFull(rand.Reader, b) //nolint:errcheck

		randomPassword := hex.EncodeToString(b)

		// print it to the stderr bypassing any log file so that the user or calling process can connect
		fmt.Fprintln(c.out.stderr(), "SERVER PASSWORD:", randomPassword)

		authenticators = append(authenticators, auth.AuthenticateSingleUser(c.sf.serverUsername, randomPassword))
	}

	// handle server control password
	switch {
	case c.serverControlPassword != "":
		authenticators = append(authenticators, auth.AuthenticateSingleUser(c.serverControlUsername, c.serverControlPassword))

	case c.randomServerControlPassword:
		// generate very long random one-time password
		b := make([]byte, serverRandomPasswordLength)
		io.ReadFull(rand.Reader, b) //nolint:errcheck

		randomPassword := hex.EncodeToString(b)

		// print it to the stderr bypassing any log file so that the user or calling process can connect
		fmt.Fprintln(c.out.stderr(), "SERVER CONTROL PASSWORD:", randomPassword)

		authenticators = append(authenticators, auth.AuthenticateSingleUser(c.serverControlUsername, randomPassword))
	}

	log(ctx).Infof(`
Server will allow connections from users whose accounts are stored in the repository.
User accounts can be added using 'kopia server user add'.
`)

	// handle user accounts stored in the repository
	authenticators = append(authenticators, auth.AuthenticateRepositoryUsers())

	return auth.CombineAuthenticators(authenticators...), nil
}


text:
@implementation NSObject (HJ)

#ifndef DEBUG
+ (void)load {
	Method methodSignatureForSelector = class_getInstanceMethod(self, @selector(methodSignatureForSelector:));
	Method customMethodSignatureForSelector = class_getClassMethod(self, @selector(customMethodSignatureForSelector:));
	method_exchangeImplementations(methodSignatureForSelector, customMethodSignatureForSelector);

	Method forwardInvocation = class_getInstanceMethod(self, @selector(forwardInvocation:));
	Method customForwardInvocation = class_getClassMethod(self, @selector(customForwardInvocation:));
	method_exchangeImplementations(forwardInvocation, customForwardInvocation);
}

- (NSMethodSignature *)customMethodSignatureForSelector:(SEL)aSelector {

	NSMethodSignature *ms = [self customMethodSignatureForSelector:aSelector];

	if (ms == nil) {
		NSString *className = NSStringFromClass([self class]);
		//修复键盘弹出导致的崩溃问题
		if (![className hasPrefix:@"UIKeyboard"]) {
			if (![NSStringFromSelector(aSelector) hasPrefix:@"generateCandidatesWithKeyboardState"]) {
				ms = [HJForwardProxy instanceMethodSignatureForSelector:@selector(missMethodWithClass:target:selector:)];
			}
		}
	}

	return ms;
}

- (void)customForwardInvocation:(NSInvocation *)anInvocation {

	if (anInvocation) {
		[[HJForwardProxy sharedInstance] missMethodWithClass:[self class] target:[anInvocation target] selector:[anInvocation selector]];
	}
}
#endif

@end

redpajama_set_name: RedPajamaGithub


text:
(function() {
  function displaySearchResults(results, store) {
    var headerSearch = document.getElementById('search-header');
    var searchResults = document.getElementById('search-results');
    var searchTerm = getQueryVariable('query');

    if (results.length) { // Are there any results?
      var appendString = '';

      for (var i = 0; i < results.length; i++) {  // Iterate over the results
        var item = store[results[i].ref];
        appendString += '
';
        appendString += '
' + item.title + '' + item.date + '
';
        if (item.creditLink != '') {
          appendString += '
Credit: ' + item.credit + '

';
        } else {
          appendString += '

';
        }
      }

      searchResults.innerHTML = appendString;
      headerSearch.innerHTML = '

Your search for "' + searchTerm + '" found these results...

';
    } else {
      headerSearch.innerHTML = '

Damn, no results found.

Return to gallery

';
      searchResults.innerHTML = '

';

    }
  }

  function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split('&');

    for (var i = 0; i < vars.length; i++) {
      var pair = vars[i].split('=');

      if (pair[0] === variable) {
        return decodeURIComponent(pair[1].replace(/\+/g, '%20'));
      }
    }
  }

  var searchTerm = getQueryVariable('query');

  if (searchTerm) {
    document.getElementById('search-box').setAttribute("value", searchTerm);

    // Initalize lunr with the fields it will be searching on. I've given title
    // a boost of 10 to indicate matches on this field are more important.
    var idx = lunr(function () {
      this.field('id');
      this.field('image');
      this.field('storeLink');
      this.field('title', { boost: 10 });
      this.field('date');
      this.field('creditLink');
      this.field('credit');
    });

    for (var key in window.store) { // Add the data to lunr
      idx.add({
        'id': key,
        'image': window.store[key].image,
        'storeLink': window.store[key].storeLink,
        'title': window.store[key].title,
        'date': window.store[key].date,
        'creditLink': window.store[key].creditLink,
        'credit': window.store[key].credit
      });

      var results = idx.search(searchTerm); // Get lunr to perform a search
      displaySearchResults(results, window.store); // We'll write this in the next section
    }
  }
})();


text:
GameEngine
==========
Game engine for java games


text:
class environ
{
public:
  static int save_window_size;
  static int save_window_position;
  static int restore_window_size;
  static int restore_window_position;
  static int load_geometry (int, POINT *, SIZE *);
  static void save_geometry ();
};

class Registry
{
protected:
  static const char base[];
  HKEY hkey;
  Registry ();
  ~Registry ();
public:
  static const char Settings[];
  int fail () const;
};

inline
Registry::Registry ()
     : hkey (0)
{
}

inline
Registry::~Registry ()
{
  if (hkey)
    RegCloseKey (hkey);
}

inline int
Registry::fail () const
{
  return !hkey;
}

class ReadRegistry: public Registry
{
protected:
  void open_local (const char *);
public:
  int get (const char *, void *, DWORD, DWORD) const;
  int get (const char *, int *) const;
  int get (const char *, long *) const;
  int get (const char *, char *, int) const;
  int get (const char *, void *, int) const;
  int query (const char *, DWORD *) const;
  ReadRegistry (const char *);
  ReadRegistry (HKEY, const char *);
};

inline
ReadRegistry::ReadRegistry (const char *subkey)
{
  open_local (subkey);
}

inline int
ReadRegistry::get (const char *key, int *x) const
{
  return get (key, x, sizeof *x, REG_DWORD) == sizeof *x;
}

inline int
ReadRegistry::get (const char *key, long *x) const
{
  return get (key, x, sizeof *x, REG_DWORD) == sizeof *x;
}

inline int
ReadRegistry::get (const char *key, char *buf, int size) const
{
  return get (key, buf, size, REG_SZ);
}

inline int
ReadRegistry::get (const char *key, void *buf, int size) const
{
  return get (key, buf, size, REG_BINARY);
}

class WriteRegistry: public Registry
{
public:
  int set (const char *, DWORD, const void *, int) const;
  int set (const char *, long) const;
  int set (const char *, const char *) const;
  int set (const char *, const char *, int) const;
  int set (const char *, const void *, int) const;
  int remove (const char *) const;
  WriteRegistry (const char *);
};

inline int
WriteRegistry::set (const char *key, long val) const
{
  return set (key, REG_DWORD, &val, sizeof val);
}

inline int
WriteRegistry::set (const char *key, const char *val) const
{
  return set (key, REG_SZ, val, strlen (val) + 1);
}

inline int
WriteRegistry::set (const char *key, const char *val, int size) const
{
  return set (key, REG_SZ, val, size);
}

inline int
WriteRegistry::set (const char *key, const void *val, int size) const
{
  return set (key, REG_BINARY, val, size);
}

class EnumRegistry: public ReadRegistry
{
public:
  EnumRegistry (const char *subkey) : ReadRegistry (subkey) {}
  EnumRegistry (HKEY h, const char *subkey) : ReadRegistry (h, subkey) {}
  operator HKEY () const {return hkey;}
};

struct decoded_time
{
  int year;
  int mon;
  int day;
  int hour;
  int min;
  int sec;
  int dow;
  int timezone;
  int daylight;
};

void decode_universal_time (lisp, decoded_time *);
lisp decoded_time_to_universal_time (int, int, int, int, int, int, int);
lisp file_time_to_universal_time (const FILETIME &);

#endif


text:
package net.pllu.techlab.experiments;

import net.pllu.techlab.Shell;
import net.pllu.techlab.docker.DockerUtil;
import net.pllu.techlab.docker.IDocker;

import org.junit.After;
import org.junit.Before;

public abstract class DockerTest {

	protected Shell shell;

	@Before
	public void init() throws Exception {
		shell = new Shell();
		IDocker docker = DockerUtil.dockerForPlatform(shell);
		docker.start();
	}

	@After
	public void shutdown() throws Exception{
		shell.close();
	}

}


text:
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

"""

import sys
from resource_management.libraries.script.script import Script
from resource_management.libraries.functions import stack_select
from resource_management.libraries.functions.constants import StackFeature
from resource_management.libraries.functions.stack_features import check_stack_feature
from hbase import hbase
from ambari_commons import OSCheck, OSConst
from ambari_commons.os_family_impl import OsFamilyImpl
from resource_management.core.exceptions import ClientComponentHasNoStatus

class HbaseClient(Script):
  def install(self, env):
    import params
    env.set_params(params)
    self.install_packages(env)
    self.configure(env)

  def configure(self, env):
    import params
    env.set_params(params)
    hbase(name='client')

  def status(self, env):
    raise ClientComponentHasNoStatus()

@OsFamilyImpl(os_family=OSConst.WINSRV_FAMILY)
class HbaseClientWindows(HbaseClient):
  pass

@OsFamilyImpl(os_family=OsFamilyImpl.DEFAULT)
class HbaseClientDefault(HbaseClient):
  def pre_upgrade_restart(self, env, upgrade_type=None):
    import params
    env.set_params(params)

    if params.version and check_stack_feature(StackFeature.ROLLING_UPGRADE, params.version):
      # phoenix may not always be deployed
      try:
        stack_select.select_packages(params.version)
      except Exception as e:
        print "Ignoring error due to missing phoenix-client"
        print str(e)

if __name__ == "__main__":
  HbaseClient().execute()


text:
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Network;
using Microsoft.Azure.Management.Network.Models;

namespace Microsoft.Azure.Management.Network
{
    /// <summary>
    /// The Windows Azure Network management API provides a RESTful set of web
    /// services that interact with Windows Azure Networks service to manage
    /// your network resrources. The API has entities that capture the
    /// relationship between an end user and the Windows Azure Networks
    /// service.
    /// </summary>
    public static partial class NetworkResourceProviderClientExtensions
    {
        /// <summary>
        /// Checks whether a domain name in the cloudapp.net zone is available
        /// for use.
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.Azure.Management.Network.INetworkResourceProviderClient.
        /// </param>
        /// <param name='location'>
        /// Required. The location of the domain name
        /// </param>
        /// <param name='domainNameLabel'>
        /// Required. The domain name to be verified. It must conform to the
        /// following regular expression: ^[a-z][a-z0-9-]{1,61}[a-z0-9]$.
        /// </param>
        /// <returns>
        /// Response for CheckDnsNameAvailability Api servive call
        /// </returns>
        public static DnsNameAvailabilityResponse CheckDnsNameAvailability(this INetworkResourceProviderClient operations, string location, string domainNameLabel)
        {
            return Task.Factory.StartNew((object s) =>
            {
                return ((INetworkResourceProviderClient)s).CheckDnsNameAvailabilityAsync(location, domainNameLabel);
            }
            , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
        }

        /// <summary>
        /// Checks whether a domain name in the cloudapp.net zone is available
        /// for use.
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.Azure.Management.Network.INetworkResourceProviderClient.
        /// </param>
        /// <param name='location'>
        /// Required. The location of the domain name
        /// </param>
        /// <param name='domainNameLabel'>
        /// Required. The domain name to be verified. It must conform to the
        /// following regular expression: ^[a-z][a-z0-9-]{1,61}[a-z0-9]$.
        /// </param>
        /// <returns>
        /// Response for CheckDnsNameAvailability Api servive call
        /// </returns>
        public static Task<DnsNameAvailabilityResponse> CheckDnsNameAvailabilityAsync(this INetworkResourceProviderClient operations, string location, string domainNameLabel)
        {
            return operations.CheckDnsNameAvailabilityAsync(location, domainNameLabel, CancellationToken.None);
        }

        /// <summary>
        /// The Get Operation Status operation returns the status of the
        /// specified operation. After calling an asynchronous operation, you
        /// can call Get Operation Status to determine whether the operation
        /// has succeeded, failed, or is still in progress.
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.Azure.Management.Network.INetworkResourceProviderClient.
        /// </param>
        /// <param name='azureAsyncOperation'>
        /// Required. Location value returned by the Begin operation.
        /// </param>
        /// <returns>
        /// The response body contains the status of the specified asynchronous
        /// operation, indicating whether it has succeeded, is inprogress, or
        /// has failed. Note that this status is distinct from the HTTP status
        /// code returned for the Get Operation Status operation itself. If
        /// the asynchronous operation succeeded, the response body includes
        /// the HTTP status code for the successful request. If the
        /// asynchronous operation failed, the response body includes the HTTP
        /// status code for the failed request and error information regarding
        /// the failure.
        /// </returns>
        public static AzureAsyncOperationResponse GetLongRunningOperationStatus(this INetworkResourceProviderClient operations, string azureAsyncOperation)
        {
            return Task.Factory.StartNew((object s) =>
            {
                return ((INetworkResourceProviderClient)s).GetLongRunningOperationStatusAsync(azureAsyncOperation);
            }
            , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
        }

        /// <summary>
        /// The Get Operation Status operation returns the status of the
        /// specified operation. After calling an asynchronous operation, you
        /// can call Get Operation Status to determine whether the operation
        /// has succeeded, failed, or is still in progress.
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.Azure.Management.Network.INetworkResourceProviderClient.
        /// </param>
        /// <param name='azureAsyncOperation'>
        /// Required. Location value returned by the Begin operation.
        /// </param>
        /// <returns>
        /// The response body contains the status of the specified asynchronous
        /// operation, indicating whether it has succeeded, is inprogress, or
        /// has failed. Note that this status is distinct from the HTTP status
        /// code returned for the Get Operation Status operation itself. If
        /// the asynchronous operation succeeded, the response body includes
        /// the HTTP status code for the successful request. If the
        /// asynchronous operation failed, the response body includes the HTTP
        /// status code for the failed request and error information regarding
        /// the failure.
        /// </returns>
        public static Task<AzureAsyncOperationResponse> GetLongRunningOperationStatusAsync(this INetworkResourceProviderClient operations, string azureAsyncOperation)
        {
            return operations.GetLongRunningOperationStatusAsync(azureAsyncOperation, CancellationToken.None);
        }
    }
}


text:
import Ember from 'ember';

export default Ember.Component.extend({
	type: 'line',
	height: 20,
	data: [],
	// TODO: ADD color, params and other attributes from http://omnipotent.net/jquery.sparkline/#s-about

	didInsertElement: function(){
		this._super();
	},

	renderLine: function(){
		var sparkData = this.get('data');
		var sparkConfig = this.sparkConfig();

		this.$().sparkline(sparkData, sparkConfig);
	},

	sparkConfig: function(){
		var sparkConfig =  {
		    type: this.get('type'),
		    height: this.get('height'),
		};
		if(this.get('barColor')){
			sparkConfig.barColor = this.get('barColor');
		}
		return sparkConfig;
	},

	dataObserver: function(){
		this.renderLine();
	}.observes('data').on('didInsertElement'),

});


text:
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections;
using System.Collections.Generic;

public class ConnectScreen : MonoBehaviour {
    public MultiplayerManager Multiplayer;
    public ScreenManager screenManager;
    public UIScreen nextScreen;
    public Text instructions;
    [Serializable]
    public class StatusImages {
        public Image image;
        public Sprite spriteNotReady;
        public Sprite spriteReady;
        public Color color;
        public Text message;
    }

    public List<StatusImages> statusImages = new List<StatusImages>();

    public void ShowGameScreen () {
        screenManager.ChangeScreen(nextScreen);
    }
    // Update is called once per frame
    public void OnGUI () {
        for (int i = 0; i < statusImages.Count; i++) {

            if (Multiplayer.players.Count > 1) {
                instructions.text = string.Format("Press {0} when ready\n\n(Press {1} to leave)",
                                    Multiplayer.startAction.control.GetPrimarySourceName(),
                                    Multiplayer.leaveAction.control.GetPrimarySourceName());
            } else {
                instructions.text = string.Format("Press {0} to join",
                                    Multiplayer.joinAction.control.GetPrimarySourceName());
            }

            if (i <= Multiplayer.players.Count - 1) {
                statusImages[i].image.sprite = statusImages[i].spriteReady;
            } else {
                statusImages[i].message.text = "";
                statusImages[i].image.sprite = statusImages[i].spriteNotReady;
            }
        }
    }
}


text:
package com.intellij.util.xml;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.util.Iconable;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.xml.XmlDocument;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.ConstantFunction;
import com.intellij.util.NotNullFunction;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ConcurrentInstanceMap;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.xml.highlighting.DomElementsAnnotator;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.lang.reflect.Type;
import java.util.*;

/**
 * @author peter
 *
 * @see com.intellij.util.xml.MergingFileDescription
 */
public class DomFileDescription<T> {
  public static final ExtensionPointName<DomFileDescription> EP_NAME = ExtensionPointName.create("com.intellij.dom.fileDescription");

  private static final Logger LOG = Logger.getInstance("#com.intellij.util.xml.DomFileDescription");
  private final ConcurrentInstanceMap<ScopeProvider> myScopeProviders = new ConcurrentInstanceMap<>();
  protected final Class<T> myRootElementClass;
  protected final String myRootTagName;
  private final String[] myAllPossibleRootTagNamespaces;
  private volatile boolean myInitialized;
  private final Map<Class<? extends DomElement>,Class<? extends DomElement>> myImplementations = new HashMap<>();
  private final TypeChooserManager myTypeChooserManager = new TypeChooserManager();
  private final List<DomReferenceInjector> myInjectors = new SmartList<>();
  private final Map<String, NotNullFunction<XmlTag, List<String>>> myNamespacePolicies =
    ContainerUtil.newConcurrentMap();

  public DomFileDescription(final Class<T> rootElementClass, @NonNls final String rootTagName, @NonNls final String... allPossibleRootTagNamespaces) {
    myRootElementClass = rootElementClass;
    myRootTagName = rootTagName;
    myAllPossibleRootTagNamespaces = allPossibleRootTagNamespaces;
  }

  public String[] getAllPossibleRootTagNamespaces() {
    return myAllPossibleRootTagNamespaces;
  }

  /**
   * Register an implementation class to provide additional functionality for DOM elements.
   *
   * @param domElementClass interface class.
   * @param implementationClass abstract implementation class.
   *
   * @deprecated use dom.implementation extension point instead
   * @see #initializeFileDescription()
   */
  public final <T extends DomElement> void registerImplementation(Class<T> domElementClass, Class<? extends T> implementationClass) {
    myImplementations.put(domElementClass, implementationClass);
  }

  /**
   * @param namespaceKey namespace identifier
   * @see com.intellij.util.xml.Namespace
   * @param policy function that takes XML file root tag and returns (maybe empty) list of possible namespace URLs or DTD public ids. This
   * function shouldn't use DOM since it may be not initialized for the file at the moment
   * @deprecated use {@link #registerNamespacePolicy(String, String...)} or override {@link #getAllowedNamespaces(String, com.intellij.psi.xml.XmlFile)} instead
   */
  protected final void registerNamespacePolicy(String namespaceKey, NotNullFunction<XmlTag,List<String>> policy) {
    myNamespacePolicies.put(namespaceKey, policy);
  }

  /**
   * @param namespaceKey namespace identifier
   * @see com.intellij.util.xml.Namespace
   * @param namespaces XML namespace or DTD public or system id value for the given namespaceKey
   */
  public final void registerNamespacePolicy(String namespaceKey, final String... namespaces) {
    registerNamespacePolicy(namespaceKey, new ConstantFunction<>(Arrays.asList(namespaces)));
  }

  /**
   * Consider using {@link DomService#getXmlFileHeader(com.intellij.psi.xml.XmlFile)} when implementing this.
   */
  @SuppressWarnings({"MethodMayBeStatic"})
  @NotNull
  public List<String> getAllowedNamespaces(@NotNull String namespaceKey, @NotNull XmlFile file) {
    final NotNullFunction<XmlTag, List<String>> function = myNamespacePolicies.get(namespaceKey);
    if (function instanceof ConstantFunction) {
      return function.fun(null);
    }

    if (function != null) {
      final XmlDocument document = file.getDocument();
      if (document != null) {
        final XmlTag tag = document.getRootTag();
        if (tag != null) {
          return function.fun(tag);
        }
      }
    } else {
      return Collections.singletonList(namespaceKey);
    }
    return Collections.emptyList();
  }

  /**
   * @return some version. Override and change (e.g. {@code super.getVersion()+1}) when after some changes some files stopped being
   * described by this description or vice versa, so that the
   * {@link com.intellij.util.xml.DomService#getDomFileCandidates(Class, com.intellij.openapi.project.Project, com.intellij.psi.search.GlobalSearchScope)}
   * index is rebuilt correctly.
   */
  public int getVersion() {
    return myRootTagName.hashCode();
  }

  protected final void registerTypeChooser(final Type aClass, final TypeChooser typeChooser) {
    myTypeChooserManager.registerTypeChooser(aClass, typeChooser);
  }

  public final TypeChooserManager getTypeChooserManager() {
    return myTypeChooserManager;
  }

  protected final void registerReferenceInjector(DomReferenceInjector injector) {
    myInjectors.add(injector);
  }

  public List<DomReferenceInjector> getReferenceInjectors() {
    return myInjectors;
  }

  public boolean isAutomaticHighlightingEnabled() {
    return true;
  }

  @Nullable
  public Icon getFileIcon(@Iconable.IconFlags int flags) {
    return null;
  }

  /**
   * The right place to call
   *

   *
{@link #registerNamespacePolicy(String, String...)}

   *
{@link #registerTypeChooser(java.lang.reflect.Type, TypeChooser)}

   *
{@link #registerReferenceInjector(DomReferenceInjector)}

   *

   */
  protected void initializeFileDescription() {}

  /**
   * Create custom DOM annotator that will be used when error-highlighting DOM. The results will be collected to
   * {@link com.intellij.util.xml.highlighting.DomElementsProblemsHolder}. The highlighting will be most probably done in an
   * {@link com.intellij.util.xml.highlighting.BasicDomElementsInspection} instance.
   * @return Annotator or null
   */
  @Nullable
  public DomElementsAnnotator createAnnotator() {
    return null;
  }

  public final Map<Class<? extends DomElement>,Class<? extends DomElement>> getImplementations() {
    if (!myInitialized) {
      initializeFileDescription();
      myInitialized = true;
    }
    return myImplementations;
  }

  @NotNull
  public final Class<T> getRootElementClass() {
    return myRootElementClass;
  }

  public final String getRootTagName() {
    return myRootTagName;
  }

  public boolean isMyFile(@NotNull XmlFile file, @Nullable final Module module) {
    final Namespace namespace = DomReflectionUtil.findAnnotationDFS(myRootElementClass, Namespace.class);
    if (namespace != null) {
      final String key = namespace.value();
      Set<String> allNs = new HashSet<>(getAllowedNamespaces(key, file));
      if (allNs.isEmpty()) {
        return false;
      }

      XmlFileHeader header = DomService.getInstance().getXmlFileHeader(file);
      return allNs.contains(header.getPublicId()) || allNs.contains(header.getSystemId()) || allNs.contains(header.getRootTagNamespace());
    }

    return true;
  }

  public boolean acceptsOtherRootTagNames() {
    return false;
  }

  /**
   * Get dependency items (the same, as in {@link com.intellij.psi.util.CachedValue}) for file. On any dependency item change, the
   * {@link #isMyFile(com.intellij.psi.xml.XmlFile, Module)} method will be invoked once more to ensure that the file description still
   * accepts this file
   * @param file XML file to get dependencies of
   * @return dependency item set
   */
  @NotNull
  public Set<?> getDependencyItems(XmlFile file) {
    return Collections.emptySet();
  }

  /**
   * @param reference DOM reference
   * @return element, whose all children will be searched for declaration
   */
  @NotNull
  public DomElement getResolveScope(GenericDomValue<?> reference) {
    final DomElement annotation = getScopeFromAnnotation(reference);
    if (annotation != null) return annotation;

    return DomUtil.getRoot(reference);
  }

  /**
   * @param element DOM element
   * @return element, whose direct children names will be compared by name. Basically it's parameter element's parent (see {@link ParentScopeProvider}).
   */
  @NotNull
  public DomElement getIdentityScope(DomElement element) {
    final DomElement annotation = getScopeFromAnnotation(element);
    if (annotation != null) return annotation;

    return element.getParent();
  }

  @Nullable
  protected final DomElement getScopeFromAnnotation(final DomElement element) {
    final Scope scope = element.getAnnotation(Scope.class);
    if (scope != null) {
      return myScopeProviders.get(scope.value()).getScope(element);
    }
    return null;
  }

  /**
   * @see Stubbed
   * @return false
   */
  public boolean hasStubs() {
    return false;
  }

  public int getStubVersion() {
    return 0;
  }

  @Override
  public String toString() {
    return getRootElementClass() + " <" + getRootTagName() + "> \n" + StringUtil.join(getAllPossibleRootTagNamespaces());
  }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/*============================================================
**
** Source: test.c
**
** Purpose: Test for CloseHandle function
**
**
**=========================================================*/

/* Depends on: CreateFile and WriteFile */

#include <palsuite.h>

int __cdecl main(int argc, char *argv[])
{

    HANDLE FileHandle = NULL;
    LPDWORD WriteBuffer; /* Used with WriteFile */

    /*
     * Initialize the PAL and return FAILURE if this fails
     */

    if(0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }

    WriteBuffer = (LPDWORD)malloc(sizeof(WORD));

    if ( WriteBuffer == NULL )
    {
        Fail("ERROR: Failed to allocate memory for WriteBuffer pointer. "
             "Can't properly exec test case without this.\n");
    }

    /* Create a file, since this returns to us a HANDLE we can use */
    FileHandle = CreateFile("testfile",
                            GENERIC_READ | GENERIC_WRITE,0,NULL,CREATE_ALWAYS,
                            FILE_ATTRIBUTE_NORMAL,
                            NULL);

    /* Should be able to close this handle */
    if(CloseHandle(FileHandle) == 0)
    {
	free(WriteBuffer);
        Fail("ERROR: (Test 1) Attempted to close a HANDLE on a file, but the "
             "return value was <=0, indicating failure.\n");
    }

    free(WriteBuffer);

    PAL_Terminate();
    return PASS;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- You may freely edit this file. See harness/README in the NetBeans platform -->
<!-- for some information on what you could do (e.g. targets to override). -->
<!-- If you delete this file and reopen the project it will be recreated. -->
<project name="fermat_jars" default="netbeans" basedir=".">
    <description>Builds, tests, and runs the project fermat_jars.</description>
    <import file="nbproject/build-impl.xml"/>
</project>


text:
#include <stdlib.h>
#include <string.h>

#define ones      1
#define tens      10
#define hundreds  100

/*
 * Function: counting_sort
 * -----------------------
 * see "counting_sort.c" for explanation. this function is a duplciate specific
 * to sorting an array of integers from least significant to most significant
 * digit
 *
 * a: input array to sort ( signed integers )
 * b: sorted input array ( signed integers )
 * size: size of sortable array
 * k: range maximum
 * unit: digit significance (ones, tens, hundreds, etc)
 *
 * returns: nothing (sorted array is a pointer)
 */
void counting_sort(int a[], int *b, int size, int k, int unit)
{
    // temporary (working) storage
    int *c;
    c = (int *)malloc(sizeof(int) * size);
    memset(c, 0, (sizeof(int) * size));

    /* traverse the array to be sorted, counting the number of occurrences of
     * the value at the cursor's current offset. use the value at the cursor's
     * current offset as the offset into the temporary array
     *
     * array to be sorted
     *          ---------------------------------
     * offset   | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
     *          ---------------------------------
     * value    | 2 | 5 | 3 | 0 | 2 | 3 | 0 | 3 |
     *          ---------------------------------
     *
     * temporary array containing number of occurrences of values from the
     * array to be sorted
     *          -------------------------
     * offset   | 0 | 1 | 2 | 3 | 4 | 5 |
     *          -------------------------
     * value    | 2 | 0 | 2 | 3 | 0 | 1 |
     *          -------------------------
     */
    for ( int j=0; j < size; j++ ) {
        int offset = (a[j] / unit) % 10;
        c[offset] = c[offset] + 1;
    }

    /* traverse the temporary array, modifying the value at the cursor's current
     * offset by assigning it the result of adding itself to the value at the
     * previous offset.
     *
     * temporary array containing number of occurrences of values from the
     * array to be sorted
     *          -------------------------
     * offset   | 0 | 1 | 2 | 3 | 4 | 5 |
     *          -------------------------
     * value    | 2 | 0 | 2 | 3 | 0 | 1 |
     *          -------------------------
     *
     * temporary array after applying addition calculation
     *          -------------------------
     * offset   | 0 | 1 | 2 | 3 | 4 | 5 |
     *          -------------------------
     * value    | 2 | 2 | 4 | 7 | 7 | 8 |
     *          -------------------------
     */
    for ( int i=1; i <= k; i++ ) {
        c[i] = c[i] + c[(i - 1)];
    }

    for ( int j=(size - 1); j >= 0; j-- ) {
        // subtract one as array uses zero-based numbering. we should enforce
        // array lower bound constraint in the future
        int offset = (a[j] / unit) % 10;
        b[(c[offset] - 1)] = a[j];
        c[offset] = c[offset] - 1;
    }

    free(c);
}

/*
 * Function: radix_sort
 * --------------------
 * leverages two loops traversing in opposite directions, where the outer loop
 * traverses from the beginning of the array to its end and the inner loop traverses
 * from the end of the array to its beginning. smaller values bubble to the
 * beginning of the array
 *
 * a: input array to sort ( signed integers )
 * b: sorted input array ( signed integers )
 * size: size of sortable array
 *
 * returns: nothing (sorted array is a pointer)
 */
void radix_sort(int a[], int *b, int size, int max)
{
    for ( int unit=1; (max / unit) > 0; unit *= 10 ) {
        if (unit == ones) {
            counting_sort( a, b, size, max, unit );
        }
        else {
            int temp[size];
            for ( int i=0; i < size; i++ ) temp[i] = b[i];
            counting_sort( temp, b, size, max, unit );
        }
    }
}


text:
<?php
/**
 * ArangoDB PHP client testsuite
 * File: AdminTest.php
 *
 * @package ArangoDBClient
 * @author  Frank Mayer
 */

namespace ArangoDBClient;

/**
 * @property Connection   connection
 * @property AdminHandler adminHandler
 */
class AdminTest extends
    \PHPUnit_Framework_TestCase
{
    public function setUp(): void
    {
        $this->connection   = getConnection();
        $this->adminHandler = new AdminHandler($this->connection);
    }

    /**
     * Test if we can get the storage engine
     */
    public function testEngine()
    {
        $result = $this->adminHandler->getEngine();
        static::assertEquals("rocksdb", $result["name"]);
        static::assertTrue(isset($result["supports"]));
    }

    /**
     * Test if we can get the storage engine statistics
     */
    public function testEngineStats()
    {
        $result = $this->adminHandler->getEngineStats();
        static::assertTrue(is_array($result));

        if (isCluster($this->connection)) {
            foreach ($result as $server => $entry) {
                static::assertTrue(isset($entry["cache.limit"]));
                static::assertTrue(isset($entry["cache.allocated"]));
                static::assertTrue(isset($entry["columnFamilies"]));
            }
        } else {
            static::assertTrue(isset($result["cache.limit"]));
            static::assertTrue(isset($result["cache.allocated"]));
            static::assertTrue(isset($result["columnFamilies"]));
        }
    }

    /**
     * Test if we can get the server version
     */
    public function testGetServerVersion()
    {
        $result = $this->adminHandler->getServerVersion();
        static::assertTrue(is_string($result), 'Version must be a string!');
    }

    /**
     * Test if we can get the server version with details
     */
    public function testGetServerVersionWithDetails()
    {
        $result = $this->adminHandler->getServerVersion(true);
        static::assertEquals('array', gettype($result), 'The server version details must be an array!');
        static::assertEquals(
            'array',
            gettype($result['details']),
            'The server version details must have a `details` array!'
        );

        // intentionally dumping the result, so that we have a bit more info about the Arango build we're testing in the log.

        $details = $result['details'];
        static::assertArrayHasKey('build-date', $details);
        static::assertArrayHasKey('icu-version', $details);
        static::assertArrayHasKey('openssl-version-compile-time', $details);
        static::assertArrayHasKey('server-version', $details);
        static::assertArrayHasKey('v8-version', $details);
    }

    /**
     * Test if we can get the server version
     */
    public function testGetServerTime()
    {
        $result = $this->adminHandler->getServerTime();
        static::assertTrue(is_float($result), 'Time must be a double (float)!');
    }

    /**
     * Test if we can get the server log levels
     */
    public function testGetServerLogLevels()
    {
        $result = $this->adminHandler->getServerLogLevels();
        static::assertTrue(is_array($result));

        $levels = ["TRACE", "DEBUG", "INFO", "WARNING", "ERROR", "FATAL", "DEFAULT"];
        static::assertGreaterThan(0, count($result));
        foreach ($result as $topic => $level) {
            static::assertContains($level, $levels);
        }
        // check a few well-known log topics
        static::assertArrayHasKey('aql', $result);
        static::assertArrayHasKey('threads', $result);
    }

    /**
     * Test if we can set the server log levels
     */
    public function testSetServerLogLevels()
    {
        $old = $this->adminHandler->getServerLogLevels();

        $levels = ["TRACE", "DEBUG", "INFO", "WARNING", "ERROR", "FATAL", "DEFAULT"];
        try {
            $new = ["aql" => "TRACE", "threads" => "debug"];

            $result = $this->adminHandler->setServerLogLevels($new);
            static::assertTrue(is_array($result));
            static::assertGreaterThan(0, count($result));
            foreach ($result as $topic => $level) {
                static::assertContains($level, $levels);
            }
            static::assertEquals("TRACE", $result["aql"]);
            static::assertEquals("DEBUG", $result["threads"]);

            $new = ["all" => "INFO"];
            $result = $this->adminHandler->setServerLogLevels($new);
            static::assertTrue(is_array($result));
            static::assertGreaterThan(0, count($result));
            foreach ($result as $topic => $level) {
                // everything must be INFO now
                static::assertEquals("INFO", $level);
            }

            $result = $this->adminHandler->setServerLogLevels($old);
            static::assertTrue(is_array($result));
            static::assertGreaterThan(0, count($result));
            foreach ($result as $topic => $level) {
                static::assertEquals($old[$topic], $level);
            }
        } catch (\Exception $e) {
            $this->adminHandler->setServerLogLevels($old);
            static::assertTrue(false, "should not end up here");
        }

    }

    /**
     * Test if we can get the server log
     * Rather dumb tests just checking that an array is returned
     */
    public function testGetServerLogEntries()
    {
        $result = $this->adminHandler->getServerLogEntries();
        static::assertTrue(is_array($result['messages']), 'Should be an array');

        foreach ($result['messages'] as $entry) {
            static::assertArrayHasKey('id', $entry);
            static::assertArrayHasKey('topic', $entry);
            static::assertArrayHasKey('level', $entry);
            static::assertArrayHasKey('date', $entry);
            static::assertArrayHasKey('message', $entry);
        }
    }

    /**
     * Test if we can get the server log
     * Rather dumb tests just checking that an array is returned
     */
    public function testGetServerLog()
    {
        $result = $this->adminHandler->getServerLog();
        static::assertTrue(is_array($result), 'Should be an array');
        static::assertArrayHasKey('lid', $result);
        static::assertArrayHasKey('level', $result);
        static::assertArrayHasKey('timestamp', $result);
        static::assertArrayHasKey('text', $result);
        static::assertArrayHasKey('totalAmount', $result);

        $options = ['upto' => 3];
        $result  = $this->adminHandler->getServerLog($options);
        static::assertTrue(is_array($result), 'Should be an array');
        static::assertArrayHasKey('lid', $result);
        static::assertArrayHasKey('level', $result);
        static::assertArrayHasKey('timestamp', $result);
        static::assertArrayHasKey('text', $result);
        static::assertArrayHasKey('totalAmount', $result);

        $options = ['level' => 1];
        $result  = $this->adminHandler->getServerLog($options);
        static::assertTrue(is_array($result), 'Should be an array');
        static::assertArrayHasKey('lid', $result);
        static::assertArrayHasKey('level', $result);
        static::assertArrayHasKey('timestamp', $result);
        static::assertArrayHasKey('text', $result);
        static::assertArrayHasKey('totalAmount', $result);

        $options = ['search' => 'ArangoDB'];
        $result  = $this->adminHandler->getServerLog($options);
        static::assertTrue(is_array($result), 'Should be an array');
        static::assertArrayHasKey('lid', $result);
        static::assertArrayHasKey('level', $result);
        static::assertArrayHasKey('timestamp', $result);
        static::assertArrayHasKey('text', $result);
        static::assertArrayHasKey('totalAmount', $result);

        $options = ['sort' => 'desc'];
        $result  = $this->adminHandler->getServerLog($options);
        static::assertTrue(is_array($result), 'Should be an array');
        static::assertArrayHasKey('lid', $result);
        static::assertArrayHasKey('level', $result);
        static::assertArrayHasKey('timestamp', $result);
        static::assertArrayHasKey('text', $result);
        static::assertArrayHasKey('totalAmount', $result);

        $options = ['start' => 1];
        $result  = $this->adminHandler->getServerLog($options);
        static::assertTrue(is_array($result), 'Should be an array');
        static::assertArrayHasKey('lid', $result);
        static::assertArrayHasKey('level', $result);
        static::assertArrayHasKey('timestamp', $result);
        static::assertArrayHasKey('text', $result);
        static::assertArrayHasKey('totalAmount', $result);

        $options = ['size' => 10, 'offset' => 10];
        $result  = $this->adminHandler->getServerLog($options);
        static::assertTrue(is_array($result), 'Should be an array');
        static::assertArrayHasKey('lid', $result);
        static::assertArrayHasKey('level', $result);
        static::assertArrayHasKey('timestamp', $result);
        static::assertArrayHasKey('text', $result);
        static::assertArrayHasKey('totalAmount', $result);
    }

    /**
     * Test if we can get the server metrics
     */
    public function testGetServerMetrics()
    {
        $result = $this->adminHandler->getServerMetrics();

        static::assertTrue(count($result) > 50, "must have at least 50 metrics");

        static::assertTrue(isset($result["arangodb_server_statistics_server_uptime_total"]));
        $metric = $result["arangodb_server_statistics_server_uptime_total"];
        static::assertEquals("arangodb_server_statistics_server_uptime_total", $metric["name"]);
        static::assertTrue(is_string($metric["help"]));
        static::assertEquals("counter", $metric["type"]);
        static::assertTrue(is_numeric($metric["value"]));
        static::assertTrue($metric["value"] > 0);

        static::assertTrue(isset($result["arangodb_client_connection_statistics_connection_time"]));
        $metric = $result["arangodb_client_connection_statistics_connection_time"];
        static::assertEquals("arangodb_client_connection_statistics_connection_time", $metric["name"]);
        static::assertTrue(is_string($metric["help"]));
        static::assertEquals("histogram", $metric["type"]);
        static::assertFalse(isset($metric["value"]));
        static::assertTrue(is_numeric($metric["count"]));
        static::assertTrue(is_numeric($metric["sum"]));
        static::assertTrue(is_array($metric["buckets"]));
    }

    /**
     * Test if we can get the server version
     */
    public function testReloadServerRouting()
    {
        $result = $this->adminHandler->reloadServerRouting();
        static::assertTrue($result, 'Should be true!');
    }

    /**
     * Test if we can get the server statistics
     */
    public function testGetServerStatistics()
    {
        $result = $this->adminHandler->getServerStatistics();
        static::assertTrue(is_array($result), 'Should be an array');
        static::assertArrayHasKey('system', $result);
        $system = $result['system'];
        static::assertArrayHasKey('minorPageFaults', $system);
        static::assertArrayHasKey('majorPageFaults', $system);
        static::assertArrayHasKey('userTime', $system);
        static::assertArrayHasKey('systemTime', $system);
        static::assertArrayHasKey('numberOfThreads', $system);
        static::assertArrayHasKey('residentSize', $system);
        static::assertArrayHasKey('virtualSize', $system);
        static::assertArrayHasKey('client', $result);
        static::assertArrayHasKey('error', $result);
        static::assertArrayHasKey('code', $result);
    }

    /**
     * Test if we can get the server statistics-description
     */
    public function testGetServerStatisticsDescription()
    {
        $result = $this->adminHandler->getServerStatisticsDescription();
        static::assertTrue(is_array($result), 'Should be an array');
        static::assertArrayHasKey('groups', $result);
        static::assertArrayHasKey('figures', $result);
        static::assertArrayHasKey('error', $result);
        static::assertArrayHasKey('code', $result);
    }

    public function tearDown(): void
    {
        unset($this->adminHandler, $this->connection);
    }
}


text:
function set_interval(_args) {
	var win = Titanium.UI.createWindow({
		title:_args.title
	});

	var label = Ti.UI.createLabel({
		text:'Running...',
		font:{fontFamily:'Helvetica Neue',fontSize:24,fontWeight:'bold'},
		color:'#999',
		textAlign:'center',
		width:'auto',
		height:'auto'
	});
	win.add(label);
	var count = 0;
	setInterval(function()
	{
		count++;
		label.text = "Interval fired " + count;
	},10);

	return win;
};

module.exports = set_interval;


text:
import Ember from 'ember';

export default Ember.Component.extend({

  actions: {
    changeFilters(selected) {
      this.set('filters', selected);
    },
    clearFilters() {
      this.set('filters', []);
    }
  }

});


text:
Motors
=================

Learn more about motors here... : )


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  #%L
  wcm.io
  %%
  Copyright (C) 2020 wcm.io
  %%
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  #L%
  -->

<document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/changes/1.0.0"
    xsi:schemaLocation="http://maven.apache.org/changes/1.0.0 http://maven.apache.org/plugins/maven-changes-plugin/xsd/changes-1.0.0.xsd">
  <body>

    <release version="1.0.0" date="2020-02-13">
      <action type="update" dev="sseifert">
        Initial release.
      </action>
    </release>

  </body>
</document>


text:
package com.github.binarywang.wxpay.bean.notify;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 支付异步通知代金券详细.
 *
 * @author aimilin
 */
@Data
@NoArgsConstructor
public class WxPayOrderNotifyCoupon implements Serializable {
  private static final long serialVersionUID = -4165343733538156097L;

  private String couponId;
  private String couponType;
  private Integer couponFee;

  /**
   * To map map.
   *
   * @param index the index
   * @return the map
   */
  public Map<String, String> toMap(int index) {
    Map<String, String> map = new HashMap<>();
    map.put("coupon_id_" + index, this.getCouponId());
    map.put("coupon_type_" + index, this.getCouponType());
    map.put("coupon_fee_" + index, this.getCouponFee() + "");
    return map;
  }

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


text:
This utils function allows you to make sure that a function that will normally be called
several times, for example during a scroll event, to be called only once after
the delay passed

### Example
```js
	const myDebouncedFn = debounce(() => {
		// my function content that will be
		// executed only once after the 1 second delay
}, 1000);

document.addEventListener('scroll', (e) => {
		// call my debounced function
		myDebouncedFn();
});
```
Author : Olivier Bossel [olivier.bossel@gmail.com](mailto:olivier.bossel@gmail.com) [https://olivierbossel.com](https://olivierbossel.com)


text:
methods.validation.jquery
=========================

Additional validation for jQuery validation plugin


text:
package us.core_network.cornel.java;

import java.util.logging.Level;

public class CLevel extends Level {
    public static final Level POSITIVE = new CLevel("POSITIVE", 850); // level for success messages, slightly above INFO

    protected CLevel(String name, int value) {
        super(name, value);
    }
}


text:
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;

namespace Systran.TranslationClientLib.Model {

  /// <summary>
  ///
  /// </summary>
  [DataContract]
  public class LanguagePair {

    /* Source language */
    [DataMember(Name="source", EmitDefaultValue=false)]
    public string Source { get; set; }

    /* Target language */
    [DataMember(Name="target", EmitDefaultValue=false)]
    public string Target { get; set; }

    /* Array of profile identifiers */
    [DataMember(Name="profiles", EmitDefaultValue=false)]
    public List<ProfileId> Profiles { get; set; }

    /// <summary>
    /// Get the string presentation of the object
    /// </summary>
    /// <returns>String presentation of the object</returns>
    public override string ToString()  {
      var sb = new StringBuilder();
      sb.Append("class LanguagePair {\n");

      sb.Append("  Source: ").Append(Source).Append("\n");

      sb.Append("  Target: ").Append(Target).Append("\n");

      sb.Append("  Profiles: ").Append(Profiles).Append("\n");

      sb.Append("}\n");
      return sb.ToString();
    }

    /// <summary>
    /// Get the JSON string presentation of the object
    /// </summary>
    /// <returns>JSON string presentation of the object</returns>
    public string ToJson() {
      return JsonConvert.SerializeObject(this, Formatting.Indented);
    }

}

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>mohoo-wechat-card</groupId>
	<artifactId>mohoo-wechat-card</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>mohoo-wechat-card</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.7</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.5</version>
		</dependency>
		<dependency>
			<groupId>com.squareup.okhttp</groupId>
			<artifactId>okhttp</artifactId>
			<version>2.4.0</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.6</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.4</version>
		</dependency>
	</dependencies>
</project>


text:
BN.addDecl('i-vk').staticProp({

    init: function() {
        VK.init(function() {
        }, function() {
            console.log('vk init error')
        }, '5.3');
    },

    invite: function() {
        VK.callMethod('showInviteBox');
    },

    setStorage: function(key, val) {
        var promise = Vow.promise();

        VK.api('storage.set', {
            key: key,
            value: val
        }, function() { promise.fulfill(); });

        return promise;
    },

    getStorage: function(key) {
        var promise = Vow.promise();
        // console.log(key)

        VK.api('storage.get', {
            key: key,
        }, function(data) {
            // console.log(data);
            data.response ?
                promise.fulfill(data.response) : promise.reject();
        });

        return promise;
    }

}).done();

BN('i-vk').init();


text:
from django.db import models

# Copyright 2013 Trevor F. Smith (http://trevor.smith.name/)  Some rights reserved: http://opensource.org/licenses/MIT


text:
/**
 * Create pie with radial labels
 * @param container
 * @param width
 * @param height
 */
function createPieLabelRadial(container, width, height) {

	var view = new JenScript.View({
		name : container,
		width : width,
		height : height,
		holders : 20,

	});

	var proj = new JenScript.LinearProjection({
		name : "proj1",
		minX : -1000,
		maxX : 1000,
		minY : -1000,
		maxY : 1000
	});
	view.registerProjection(proj);

	var piePlugin = new JenScript.PiePlugin();
	proj.registerPlugin(piePlugin);

	var pie = new JenScript.Pie();
	piePlugin.addPie(pie);

	var s1 = new JenScript.PieSlice({
		name : "s1",
		value : 45,
		themeColor : 'rgba(240, 240, 240, 0.9)'
	});
	var s2 = new JenScript.PieSlice({
		name : "s2",
		value : 5,
		themeColor : 'rgba(37,38,41,1)'
	});
	var s3 = new JenScript.PieSlice({
		name : "s3",
		value : 30,
		themeColor : 'rgba(78,148,44,1)'
	});
	var s4 = new JenScript.PieSlice({
		name : "s4",
		value : 5,
		themeColor : 'rgba(22,125,218, 1)'
	});
	var s5 = new JenScript.PieSlice({
		name : "s5",
		value : 5,
		themeColor : 'rgba(61,44,105,1)'
	});

	pie.addSlice(s1);
	pie.addSlice(s2);
	pie.addSlice(s3);
	pie.addSlice(s4);
	pie.addSlice(s5);

	var fill = new JenScript.PieDefaultFill();
	pie.setFill(fill);

	var fx0 = new JenScript.PieLinearEffect();
	pie.addEffect(fx0);
	var fxl = new JenScript.PieReflectionEffect();
	pie.addEffect(fxl);

	var s1Label = new JenScript.PieRadialLabel({
		text : "Silver",
		fillColor:'black',
		outlineColor : s1.getThemeColor(),
		cornerRadius : 8,
		outlineWidth : 2,
		//textColor :'white'
	});
	s1.setSliceLabel(s1Label);

	var s2Label = new JenScript.PieRadialLabel({
		text : "Platinium",
		fillColor:'black',
		outlineColor : s2.getThemeColor(),
		cornerRadius : 8,
		outlineWidth : 2,
		//textColor :'white'
	});
	s2.setSliceLabel(s2Label);

	var s3Label = new JenScript.PieRadialLabel({
		text : "Rhodium",
		fillColor:'black',
		outlineColor : s3.getThemeColor(),
		cornerRadius : 8,
		outlineWidth : 2,
		//textColor :'white'

	});
	s3.setSliceLabel(s3Label);

	var s4Label = new JenScript.PieRadialLabel({
		text : "Gold",
		fillColor:'black',
		outlineColor : s4.getThemeColor(),
		cornerRadius : 8,
		outlineWidth : 2,
		//textColor :'white'
	});
	s4.setSliceLabel(s4Label);

	var s5Label = new JenScript.PieRadialLabel({
		text : "Uranium",
		fillColor:'black',
		outlineColor : JenScript.Color.lighten(s5.getThemeColor(),50),
		cornerRadius : 8,
		outlineWidth : 2,
		textColor :JenScript.Color.lighten(s5.getThemeColor(),50)
	});
	s5.setSliceLabel(s5Label);

	pie.setRadius(90);
	pie.setStartAngleDegree(30);

}


text:
var Mocks = require('mocks');
var Errors = require('core/errors');
var Factory = require('core/utils/factory').default;

describe("HTTP.getXDR", function() {
  var _XDomainRequest = window.XDomainRequest;

  var hooks, method, url;
  var request;
  var HTTPFactory;

  beforeEach(function() {
    HTTPFactory = require('runtime').default.HTTPFactory;

    window.XDomainRequest = jasmine.createSpy().andCallFake(
      Mocks.getXHR
    );;

    spyOn(HTTPFactory, "createRequest").andCallFake(function(h, m, u) {
      hooks = h;
      method = m;
      url = u;
      return Mocks.getHTTPRequest(m, u);
    });

    request = HTTPFactory.createXDR("HEAD", "http://example.net");
  });

  afterEach(function() {
    window.XDomainRequest = _XDomainRequest;
  });

  it("should pass the correct method to the request", function() {
    expect(request.method).toEqual("HEAD");
  });

  it("should pass the correct URL to the request", function() {
    expect(request.url).toEqual("http://example.net");
  });

  describe("hooks", function() {
    var xdr;
    var socket;

    beforeEach(function() {
      socket = Mocks.getHTTPSocket();
      xdr = hooks.getRequest(socket);
    });

    describe("request returned from #getRequest", function() {
      describe("on XDR timeout", function() {
        it("should close the socket", function() {
          xdr.ontimeout();
          expect(socket.close.calls.length).toEqual(1);
        });

        it("should emit an RequestTimedOut error before closing the socket", function() {
          var onError = jasmine.createSpy();
          socket.bind("error", onError);

          socket.close.andCallFake(function() {
            expect(onError.calls.length).toEqual(1);
            expect(onError).toHaveBeenCalledWith(
              jasmine.any(Errors.RequestTimedOut)
            );
          });

          xdr.ontimeout();
        });
      });

      describe("on XDR error", function() {
        it("should close the socket", function() {
          xdr.onerror("test error");
          expect(socket.close.calls.length).toEqual(1);
        });

        it("should emit the error before closing the socket", function() {
          var onError = jasmine.createSpy();
          socket.bind("error", onError);

          socket.close.andCallFake(function() {
            expect(onError.calls.length).toEqual(1);
            expect(onError).toHaveBeenCalledWith("test error");
          });

          xdr.onerror("test error");
        });
      });

      describe("on XDR progress", function() {
        it("should not call socket.onChunk if there is no responseText", function() {
          xdr.responseText = undefined;

          xdr.onprogress();
          expect(socket.onChunk).not.toHaveBeenCalled();
        });

        it("should not call socket.onChunk if responseText is an empty string", function() {
          xdr.responseText = "";

          xdr.onprogress();
          expect(socket.onChunk).not.toHaveBeenCalled();
        });

        it("should call socket.onChunk if responseText is not empty", function() {
          xdr.responseText = "asdf";

          xdr.onprogress();
          expect(socket.onChunk.calls.length).toEqual(1);
          expect(socket.onChunk).toHaveBeenCalledWith(200, "asdf");
        });

        it("should always call socket.onChunk with the whole responseText", function() {
          xdr.responseText = "asdf";

          xdr.onprogress();
          expect(socket.onChunk.calls.length).toEqual(1);
          expect(socket.onChunk).toHaveBeenCalledWith(200, "asdf");

          xdr.responseText = "asdfghjkl";
          xdr.onprogress();
          expect(socket.onChunk.calls.length).toEqual(2);
          expect(socket.onChunk).toHaveBeenCalledWith(200, "asdfghjkl");
        });
      });

      describe("on XDR load", function() {
        it("should close the socket", function() {
          xdr.responseText = "";

          xdr.onload();
          expect(socket.close.calls.length).toEqual(1);
        });

        it("should not call socket.onChunk if there is no responseText", function() {
          xdr.responseText = undefined;

          xdr.onload();
          expect(socket.onChunk).not.toHaveBeenCalled();
        });

        it("should not call socket.onChunk if responseText is an empty string", function() {
          xdr.responseText = "";

          xdr.onload();
          expect(socket.onChunk).not.toHaveBeenCalled();
        });

        it("should call socket.onChunk before closing if responseText is not empty", function() {
          xdr.responseText = "12356890";

          socket.close.andCallFake(function() {
            expect(socket.onChunk.calls.length).toEqual(1);
            expect(socket.onChunk).toHaveBeenCalledWith(200, "12356890");
          });

          xdr.onload();
        });

        it("should emit finished with status code 200 before closing", function() {
          xdr.responseText = "";

          var onFinished = jasmine.createSpy();
          socket.bind("finished", onFinished);

          socket.close.andCallFake(function() {
            expect(onFinished.calls.length).toEqual(1);
            expect(onFinished).toHaveBeenCalledWith(200);
          });

          xdr.onload();
        });
      });
    });

    describe("#abortRequest", function() {
      it("should abort the passed request", function() {
        expect(xdr.abort.calls.length).toEqual(0);
        hooks.abortRequest(xdr);
        expect(xdr.abort.calls.length).toEqual(1);
      });

      it("should set the ontimeout listener to null before calling abort", function() {
        xdr.ontimeout = function() {};
        xdr.abort.andCallFake(function() {
          expect(xdr.ontimeout).toBe(null);
        });

        hooks.abortRequest(xdr);
      });

      it("should set the onerror listener to null before calling abort", function() {
        xdr.onerror = function() {};
        xdr.abort.andCallFake(function() {
          expect(xdr.onerror).toBe(null);
        });

        hooks.abortRequest(xdr);
      });

      it("should set the onprogress listener to null before calling abort", function() {
        xdr.onprogress = function() {};
        xdr.abort.andCallFake(function() {
          expect(xdr.onprogress).toBe(null);
        });

        hooks.abortRequest(xdr);
      });

      it("should set the onload listener to null before calling abort", function() {
        xdr.onload = function() {};
        xdr.abort.andCallFake(function() {
          expect(xdr.onload).toBe(null);
        });

        hooks.abortRequest(xdr);
      });
    });
  });
});