text:
var GOOGLE_API_URL = 'https://ampcid.google.com/v1/publisher:getClientId?key=';
var AMP_TOKEN = 'AMP_TOKEN';

var TokenStatus = {
  RETRIEVING: '$RETRIEVING',
  OPT_OUT: '$OPT_OUT',
  NOT_FOUND: '$NOT_FOUND',
  ERROR: '$ERROR'
};

var TIMEOUT = 30000;
var HOUR = 60 * 60 * 1000;
var DAY = 24 * HOUR;
var YEAR = 365 * DAY;

var PROXY_ORIGIN_URL_REGEX =
    /^https:\/\/([a-zA-Z0-9_-]+\.)?cdn\.ampproject\.org/;

var scopedCidCallbacks = {};

/**
 * Gets scoped CID (client ID).
 *
 * @param {string} scope
 * @param {string} apiKey
 * @param {function()} callback
 */
function getScopedCid(scope, apiKey, callback) {
  if (scopedCidCallbacks[scope]) {
    scopedCidCallbacks[scope].push(callback);
    return;
  }
  scopedCidCallbacks[scope] = [callback];
  var cb = wrapCallbacks(scopedCidCallbacks[scope]);
  var token;
  // Block the request if a previous request is on flight
  // Poll every 200ms. Longer interval means longer latency for the 2nd CID.
  poll(200, function () {
    token = getCookie(AMP_TOKEN);
    return token !== TokenStatus.RETRIEVING;
  }, function () {
    // If the page referrer is proxy origin, we force to use API even the
    // token indicates a previous fetch returned nothing
    var forceFetch =
        token === TokenStatus.NOT_FOUND && isReferrerProxyOrigin();

    // Token is in a special state
    if (!forceFetch && isStatusToken(token)) {
      if (token === TokenStatus.OPT_OUT) {
        cb(null, TokenStatus.OPT_OUT);
      } else if (token === TokenStatus.NOT_FOUND) {
        cb(null, null);
      } else if (token === TokenStatus.ERROR) {
        cb(new Error('There was an error in previous request. Try later.'));
      } else {
        cb(new Error('Invalid token state: ' + token));
      }
      return;
    }

    if (!token || isStatusToken(token)) {
      persistToken(TokenStatus.RETRIEVING, TIMEOUT);
    }
    fetchCid(apiKey, scope, token, cb)
  });
}

/**
 * Fetches CID remotely
 *
 * @param {string} apiKey
 * @param {string} scope
 * @param {?string} token
 * @param {function()} callback
 */
function fetchCid(apiKey, scope, token, callback) {
  var payload = {'originScope': scope};
  if (token) {
    payload['securityToken'] = token;
  }
  const url = GOOGLE_API_URL + apiKey;
  fetchJson(url, payload, TIMEOUT, function (err, res) {
    if (!err && res['alternateUrl']) {
      // Try again with alternateUrl
      const altUrl = `${res['alternateUrl']}?key=${apiKey}`;
      fetchJson(altUrl, payload, TIMEOUT, function (err, res) {
        handleResponse(err, res, callback);
      });
    } else {
      handleResponse(err, res, callback);
    }
  });
}

/**
 *
 * @param {?Error} err
 * @param {!JsonObject} res
 * @param {function()} callback
 */
function handleResponse(err, res, callback) {
  if (err) {
    persistToken(TokenStatus.ERROR, TIMEOUT);
    callback(err);
  } else if (res['optOut']) {
    persistToken(TokenStatus.OPT_OUT, YEAR);
    callback(null, TokenStatus.OPT_OUT);
  } else if (res['clientId']) {
    persistToken(res['securityToken'], YEAR);
    callback(null, res['clientId']);
  } else {
    persistToken(TokenStatus.NOT_FOUND, HOUR);
    callback(null, null);
  }
}

/**
 * Wraps an array of callback functions, so that all of them are invoked
 * together.
 *
 * @param {Array<function()>} callbacks
 * @returns {function()}
 */
function wrapCallbacks(callbacks) {
  return function () {
    var args = arguments;
    callbacks.forEach(function (callback) {
      callback.apply(null, args);
    })
  };
}

/**
 * Stores the given token value into a cookie with name of `AMP_TOKEN`.
 *
 * @param {string} tokenValue
 * @param {number} expires
 */
function persistToken(tokenValue, expires) {
  if (tokenValue) {
    setCookie(AMP_TOKEN, tokenValue, Date.now() + expires);
  }
}

/**
 * Checks if the document referrer is proxy origin.
 *
 * @returns {boolean}
 */
function isReferrerProxyOrigin() {
  return PROXY_ORIGIN_URL_REGEX.test(self.document.referrer);
}

/**
 * Returns if the AMP_TOKEN contains a value that indicates a special state.
 *
 * @param {string} token
 * @returns {boolean}
 */
function isStatusToken(token) {
  return !!token && (token[0] === '$');
}

/**
 * Polls with the given time interval until the provided `predicate` is `true`.
 *
 * @param {number} delay
 * @param {function} predicate
 * @param {function} callback
 */
function poll(delay, predicate, callback) {
  var interval = self.setInterval(function () {
    if (predicate()) {
      self.clearInterval(interval);
      callback();
    }
  }, delay);
}

/**
 * Gets cookie value. Returns `null` if not exists.
 *
 * @param {string} name
 * @returns {?string}
 */
function getCookie(name) {
  var cookies = self.document.cookie.split(';');
  for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i].trim();
    var values = cookie.split('=', 2);
    if (values.length !== 2) {
      continue;
    }
    if (decodeURIComponent(values[0]) === name) {
      return decodeURIComponent(values[1]);
    }
  }
  return null;
}

/**
 * Sets cookie.
 *
 * @param {string} name
 * @param {string} value
 * @param {number} expirationTime
 */
function setCookie(name, value, expirationTime) {
  self.document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) +
      '; path=/; expires=' + new Date(expirationTime).toUTCString();
}

/**
 * Fetch a JSON object from a remote endpoint using a POST XHR request.
 *
 * @param {string} url
 * @param {Object} payload
 * @param {number} timeout
 * @param {function} callback
 */
function fetchJson(url, payload, timeout, callback) {
  var oneTimeCallback = oneTime(callback);
  self.setTimeout(function () {
    oneTimeCallback(new Error('Request timed out'));
  }, timeout);

  var xhr = createPostXhrRequest(url);
  xhr.onreadystatechange = function () {
    if (xhr.readyState < /* STATUS_RECEIVED */ 2) {
      return;
    }
    if (xhr.status < 100 || xhr.status > 599) {
      xhr.onreadystatechange = null;
      oneTimeCallback(new Error('Unknown HTTP status' + xhr.status));
      return;
    }
    if (xhr.readyState === /* COMPLETE */ 4) {
      try {
        var json = JSON.parse(xhr.responseText);
        if (xhr.status >= 400) {
          oneTimeCallback(new Error(json.error ?
              json.error.message : ('Invalid response: ' + xhr.responseText)));
        } else {
          oneTimeCallback(null, json);
        }
      } catch (e) {
        oneTimeCallback(new Error('Invalid response: ' + xhr.responseText));
      }
    }
  };
  xhr.onerror = function () {
    oneTimeCallback(new Error('Network failure'));
  };
  xhr.onabort = function () {
    oneTimeCallback(new Error('Request aborted'));
  };
  xhr.send(JSON.stringify(payload));
}

/**
 * Creates a POST XHR.
 *
 * @param {string} url
 * @returns {XMLHttpRequest|XDomainRequest}
 */
function createPostXhrRequest(url) {
  var xhr = new self.XMLHttpRequest();
  if ('withCredentials' in xhr) {
    xhr.open('POST', url, true);
  } else if (typeof self.XDomainRequest !== 'undefined') {
    // IE-specific object.
    xhr = new self.XDomainRequest();
    xhr.open('POST', url);
  } else {
    throw new Error('CORS is not supported');
  }
  xhr.withCredentials = true;
  xhr.setRequestHeader('Content-Type', 'text/plain;charset=utf-8');
  xhr.setRequestHeader('Accept', 'application/json');
  return xhr;
}

/**
 * Wraps a callback so that it will only be invoked once.
 *
 * @param {function} callback
 * @returns {function}
 */
function oneTime(callback) {
  var called = false;
  return function () {
    if (!called) {
      callback.apply(null, arguments);
      called = true;
    }
  }
}

self.GoogleAmpCidApi = {
  getScopedCid: getScopedCid
};

if (Object.prototype.toString.call(self.googleAmpCidApiOnload) === '[object Array]') {
  self.googleAmpCidApiOnload.forEach(function (listener) {
    listener(self.GoogleAmpCidApi);
  });
}

self.googleAmpCidApiOnload = {
  push: function (listener) {
    listener(self.GoogleAmpCidApi);
  }
};


text:
package pad;

import java.io.IOException;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Reducer;

/** Combiner task of the \see StarDriver Job. */
public class StarCombiner extends Reducer<NodesPairWritable, IntWritable, NodesPairWritable, IntWritable>
{
	/**
	* Reduce method of the this StarCombiner class.
	* It reduce the number of duplicates that are emit by the \see StarMapper.
	* @param pair			pair of nodes.
	* @param neighbourhood	list of neighbours.
	* @param context		context of this Job.
	* @throws IOException, InterruptedException
	*/
	public void reduce( NodesPairWritable pair, Iterable<IntWritable> neighbourhood, Context context ) throws IOException, InterruptedException
	{
		// Do not exists a node with ID equal to minus two ( minus one already used to indicate loneliness )
		int lastNodeSeen = -2;
		for ( IntWritable neighbour : neighbourhood )
		{
			// Skip the duplicate nodes.
			if ( neighbour.get() == lastNodeSeen )
				continue;

			// Emit the pair
			pair.NeighbourID = neighbour.get();
			context.write( pair, neighbour );

			// Store the last neighbourId that we have processed.
			lastNodeSeen = neighbour.get();
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Control from '../Control';
import Label from '../Label';

import './range-input.scss';

const fieldId = id => `param-${id}`;

const range = (lowEnd, highEnd) => {
  const list = [];
  for (let i = lowEnd; i <= highEnd; i += 1) {
    list.push(i);
  }
  return list;
};

const RangeInput = ({
  id,
  label,
  min,
  max,
  value,
  onChange,
}) => (
  <Control>
    {label}

      <input
        id={fieldId(id)}
        styleName="range-input"
        type="range"
        value={value}
        onChange={e => onChange(parseInt(e.target.value, 10))}
        min={min}
        max={max}
      />

        {range(min, max).map((n) => {
          const styles = classNames({
            'range-label': true,
            'range-label-active': n === value,
          });

          return (
            <span
              key={n}
              styleName={styles}
              style={{ left: `${(100 / (max - min)) * (n - 1)}%` }}
              onClick={() => onChange(n)}
            >
              {n}

          );
        })}

  </Control>
);

RangeInput.propTypes = {
  value: PropTypes.number.isRequired,
  onChange: PropTypes.func.isRequired,
};

export default RangeInput;


text:
kern_return_t ___PACKAGENAMEASIDENTIFIER____start(kmod_info_t * ki, void *d);
kern_return_t ___PACKAGENAMEASIDENTIFIER____stop(kmod_info_t *ki, void *d);

kern_return_t ___PACKAGENAMEASIDENTIFIER____start(kmod_info_t * ki, void *d)
{
    return KERN_SUCCESS;
}

kern_return_t ___PACKAGENAMEASIDENTIFIER____stop(kmod_info_t *ki, void *d)
{
    return KERN_SUCCESS;
}


text:
package main

import (
	"context"
	"flag"
	"fmt"
	"io"
	golog "log"
	"math/rand"
	"net"
	"net/http"
	"os"
	"os/signal"
	"path/filepath"
	"time"

	snapshotsapi "github.com/containerd/containerd/api/services/snapshots/v1"
	"github.com/containerd/containerd/contrib/snapshotservice"
	"github.com/containerd/containerd/defaults"
	"github.com/containerd/containerd/log"
	"github.com/containerd/containerd/pkg/dialer"
	"github.com/containerd/containerd/snapshots"
	"github.com/containerd/containerd/sys"
	dbmetadata "github.com/containerd/stargz-snapshotter/cmd/containerd-stargz-grpc/db"
	ipfs "github.com/containerd/stargz-snapshotter/cmd/containerd-stargz-grpc/ipfs"
	"github.com/containerd/stargz-snapshotter/fs"
	"github.com/containerd/stargz-snapshotter/metadata"
	memorymetadata "github.com/containerd/stargz-snapshotter/metadata/memory"
	"github.com/containerd/stargz-snapshotter/service"
	"github.com/containerd/stargz-snapshotter/service/keychain/cri"
	"github.com/containerd/stargz-snapshotter/service/keychain/dockerconfig"
	"github.com/containerd/stargz-snapshotter/service/keychain/kubeconfig"
	"github.com/containerd/stargz-snapshotter/service/resolver"
	"github.com/containerd/stargz-snapshotter/version"
	sddaemon "github.com/coreos/go-systemd/v22/daemon"
	metrics "github.com/docker/go-metrics"
	"github.com/pelletier/go-toml"
	"github.com/sirupsen/logrus"
	bolt "go.etcd.io/bbolt"
	"golang.org/x/sys/unix"
	"google.golang.org/grpc"
	"google.golang.org/grpc/backoff"
	"google.golang.org/grpc/credentials/insecure"
	runtime "k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
)

const (
	defaultAddress             = "/run/containerd-stargz-grpc/containerd-stargz-grpc.sock"
	defaultConfigPath          = "/etc/containerd-stargz-grpc/config.toml"
	defaultLogLevel            = logrus.InfoLevel
	defaultRootDir             = "/var/lib/containerd-stargz-grpc"
	defaultImageServiceAddress = "/run/containerd/containerd.sock"
)

var (
	address      = flag.String("address", defaultAddress, "address for the snapshotter's GRPC server")
	configPath   = flag.String("config", defaultConfigPath, "path to the configuration file")
	logLevel     = flag.String("log-level", defaultLogLevel.String(), "set the logging level [trace, debug, info, warn, error, fatal, panic]")
	rootDir      = flag.String("root", defaultRootDir, "path to the root directory for this snapshotter")
	printVersion = flag.Bool("version", false, "print the version")
)

type snapshotterConfig struct {
	service.Config

	// MetricsAddress is address for the metrics API
	MetricsAddress string `toml:"metrics_address"`

	// NoPrometheus is a flag to disable the emission of the metrics
	NoPrometheus bool `toml:"no_prometheus"`

	// DebugAddress is a Unix domain socket address where the snapshotter exposes /debug/ endpoints.
	DebugAddress string `toml:"debug_address"`

	// IPFS is a flag to enbale lazy pulling from IPFS.
	IPFS bool `toml:"ipfs"`

	// MetadataStore is the type of the metadata store to use.
	MetadataStore string `toml:"metadata_store" default:"memory"`
}

func main() {
	rand.Seed(time.Now().UnixNano())
	flag.Parse()
	lvl, err := logrus.ParseLevel(*logLevel)
	if err != nil {
		log.L.WithError(err).Fatal("failed to prepare logger")
	}
	if *printVersion {
		fmt.Println("containerd-stargz-grpc", version.Version, version.Revision)
		return
	}
	logrus.SetLevel(lvl)
	logrus.SetFormatter(&logrus.JSONFormatter{
		TimestampFormat: log.RFC3339NanoFixed,
	})

	var (
		ctx    = log.WithLogger(context.Background(), log.L)
		config snapshotterConfig
	)
	// Streams log of standard lib (go-fuse uses this) into debug log
	// Snapshotter should use "github.com/containerd/containerd/log" otherwize
	// logs are always printed as "debug" mode.
	golog.SetOutput(log.G(ctx).WriterLevel(logrus.DebugLevel))

	// Get configuration from specified file
	tree, err := toml.LoadFile(*configPath)
	if err != nil && !(os.IsNotExist(err) && *configPath == defaultConfigPath) {
		log.G(ctx).WithError(err).Fatalf("failed to load config file %q", *configPath)
	}
	if err := tree.Unmarshal(&config); err != nil {
		log.G(ctx).WithError(err).Fatalf("failed to unmarshal config file %q", *configPath)
	}

	if err := service.Supported(*rootDir); err != nil {
		log.G(ctx).WithError(err).Fatalf("snapshotter is not supported")
	}

	// Create a gRPC server
	rpc := grpc.NewServer()

	// Configure keychain
	credsFuncs := []resolver.Credential{dockerconfig.NewDockerconfigKeychain(ctx)}
	if config.Config.KubeconfigKeychainConfig.EnableKeychain {
		var opts []kubeconfig.Option
		if kcp := config.Config.KubeconfigKeychainConfig.KubeconfigPath; kcp != "" {
			opts = append(opts, kubeconfig.WithKubeconfigPath(kcp))
		}
		credsFuncs = append(credsFuncs, kubeconfig.NewKubeconfigKeychain(ctx, opts...))
	}
	if config.Config.CRIKeychainConfig.EnableKeychain {
		// connects to the backend CRI service (defaults to containerd socket)
		criAddr := defaultImageServiceAddress
		if cp := config.CRIKeychainConfig.ImageServicePath; cp != "" {
			criAddr = cp
		}
		connectCRI := func() (runtime.ImageServiceClient, error) {
			// TODO: make gRPC options configurable from config.toml
			backoffConfig := backoff.DefaultConfig
			backoffConfig.MaxDelay = 3 * time.Second
			connParams := grpc.ConnectParams{
				Backoff: backoffConfig,
			}
			gopts := []grpc.DialOption{
				grpc.WithTransportCredentials(insecure.NewCredentials()),
				grpc.WithConnectParams(connParams),
				grpc.WithContextDialer(dialer.ContextDialer),
				grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(defaults.DefaultMaxRecvMsgSize)),
				grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(defaults.DefaultMaxSendMsgSize)),
			}
			conn, err := grpc.Dial(dialer.DialAddress(criAddr), gopts...)
			if err != nil {
				return nil, err
			}
			return runtime.NewImageServiceClient(conn), nil
		}
		f, criServer := cri.NewCRIKeychain(ctx, connectCRI)
		runtime.RegisterImageServiceServer(rpc, criServer)
		credsFuncs = append(credsFuncs, f)
	}
	fsOpts := []fs.Option{fs.WithMetricsLogLevel(logrus.InfoLevel)}
	if config.IPFS {
		fsOpts = append(fsOpts, fs.WithResolveHandler("ipfs", new(ipfs.ResolveHandler)))
	}
	mt, err := getMetadataStore(*rootDir, config)
	if err != nil {
		log.G(ctx).WithError(err).Fatalf("failed to configure metadata store")
	}
	fsOpts = append(fsOpts, fs.WithMetadataStore(mt))
	rs, err := service.NewStargzSnapshotterService(ctx, *rootDir, &config.Config,
		service.WithCredsFuncs(credsFuncs...), service.WithFilesystemOptions(fsOpts...))
	if err != nil {
		log.G(ctx).WithError(err).Fatalf("failed to configure snapshotter")
	}

	cleanup, err := serve(ctx, rpc, *address, rs, config)
	if err != nil {
		log.G(ctx).WithError(err).Fatalf("failed to serve snapshotter")
	}

	if cleanup {
		log.G(ctx).Debug("Closing the snapshotter")
		rs.Close()
	}
	log.G(ctx).Info("Exiting")
}

func serve(ctx context.Context, rpc *grpc.Server, addr string, rs snapshots.Snapshotter, config snapshotterConfig) (bool, error) {
	// Convert the snapshotter to a gRPC service,
	snsvc := snapshotservice.FromSnapshotter(rs)

	// Register the service with the gRPC server
	snapshotsapi.RegisterSnapshotsServer(rpc, snsvc)

	// Prepare the directory for the socket
	if err := os.MkdirAll(filepath.Dir(addr), 0700); err != nil {
		return false, fmt.Errorf("failed to create directory %q: %w", filepath.Dir(addr), err)
	}

	// Try to remove the socket file to avoid EADDRINUSE
	if err := os.RemoveAll(addr); err != nil {
		return false, fmt.Errorf("failed to remove %q: %w", addr, err)
	}

	errCh := make(chan error, 1)

	// We need to consider both the existence of MetricsAddress as well as NoPrometheus flag not set
	if config.MetricsAddress != "" && !config.NoPrometheus {
		l, err := net.Listen("tcp", config.MetricsAddress)
		if err != nil {
			return false, fmt.Errorf("failed to get listener for metrics endpoint: %w", err)
		}
		m := http.NewServeMux()
		m.Handle("/metrics", metrics.Handler())
		go func() {
			if err := http.Serve(l, m); err != nil {
				errCh <- fmt.Errorf("error on serving metrics via socket %q: %w", addr, err)
			}
		}()
	}

	if config.DebugAddress != "" {
		log.G(ctx).Infof("listen %q for debugging", config.DebugAddress)
		l, err := sys.GetLocalListener(config.DebugAddress, 0, 0)
		if err != nil {
			return false, fmt.Errorf("failed to listen %q: %w", config.DebugAddress, err)
		}
		go func() {
			if err := http.Serve(l, debugServerMux()); err != nil {
				errCh <- fmt.Errorf("error on serving a debug endpoint via socket %q: %w", addr, err)
			}
		}()
	}

	// Listen and serve
	l, err := net.Listen("unix", addr)
	if err != nil {
		return false, fmt.Errorf("error on listen socket %q: %w", addr, err)
	}
	go func() {
		if err := rpc.Serve(l); err != nil {
			errCh <- fmt.Errorf("error on serving via socket %q: %w", addr, err)
		}
	}()

	if os.Getenv("NOTIFY_SOCKET") != "" {
		notified, notifyErr := sddaemon.SdNotify(false, sddaemon.SdNotifyReady)
		log.G(ctx).Debugf("SdNotifyReady notified=%v, err=%v", notified, notifyErr)
	}
	defer func() {
		if os.Getenv("NOTIFY_SOCKET") != "" {
			notified, notifyErr := sddaemon.SdNotify(false, sddaemon.SdNotifyStopping)
			log.G(ctx).Debugf("SdNotifyStopping notified=%v, err=%v", notified, notifyErr)
		}
	}()

	var s os.Signal
	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, unix.SIGINT, unix.SIGTERM)
	select {
	case s = <-sigCh:
		log.G(ctx).Infof("Got %v", s)
	case err := <-errCh:
		return false, err
	}
	if s == unix.SIGINT {
		return true, nil // do cleanup on SIGINT
	}
	return false, nil
}

const (
	memoryMetadataType = "memory"
	dbMetadataType     = "db"
)

func getMetadataStore(rootDir string, config snapshotterConfig) (metadata.Store, error) {
	switch config.MetadataStore {
	case "", memoryMetadataType:
		return memorymetadata.NewReader, nil
	case dbMetadataType:
		bOpts := bolt.Options{
			NoFreelistSync:  true,
			InitialMmapSize: 64 * 1024 * 1024,
			FreelistType:    bolt.FreelistMapType,
		}
		db, err := bolt.Open(filepath.Join(rootDir, "metadata.db"), 0600, &bOpts)
		if err != nil {
			return nil, err
		}
		return func(sr *io.SectionReader, opts ...metadata.Option) (metadata.Reader, error) {
			return dbmetadata.NewReader(db, sr, opts...)
		}, nil
	default:
		return nil, fmt.Errorf("unknown metadata store type: %v; must be %v or %v",
			config.MetadataStore, memoryMetadataType, dbMetadataType)
	}
}


text:
require 'yaml'
require 'ostruct'
require 'rubygems'
require 'facet/hash/to_ostruct_recurse'

ostruct = YAML.load(File.open("example.yaml")).to_ostruct_recurse


text:
@interface ThumbnailView : REPhotoThumbnailView {
    EGOImageButton *imageButton;
}

- (void)setPhoto:(NSObject <REPhotoObjectProtocol> *)photo;

@end


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

namespace WebAddressbookTests
{
    public class GroupTestBase : AuthTestBase
    {
        [TearDown]
        public void CompareGroupsUI_DB()
        {
            if (PERFORM_LONG_UI_CHECKS)
            {
                List<GroupData> fromUI = app.Groups.GetGroupList();
                List<GroupData> fromDB = GroupData.GetAllFromDB();
                fromUI.Sort();
                fromDB.Sort();
                Assert.AreEqual(fromUI, fromDB);
            }
        }
    }
}


text:
0.sec=within any country/location

1.sec=within specified countries/locations

2.sec=within any country/location other than those specified

=[G/Z/ol/s2]


text:
import 'jest-styled-components'
import '@testing-library/jest-dom/extend-expect'
import { renderWithTheme } from '@looker/components-test-utils'
import React from 'react'
import { fireEvent, screen, act } from '@testing-library/react'
import { ButtonTransparent } from './ButtonTransparent'

beforeEach(() => {
  jest.useFakeTimers()
})
afterEach(() => {
  jest.runOnlyPendingTimers()
  jest.useRealTimers()
})
const runTimers = () =>
  act(() => {
    jest.runOnlyPendingTimers()
  })

describe('ButtonTransparent', () => {
  test('ripple effect default', () => {
    renderWithTheme(<ButtonTransparent>Test</ButtonTransparent>)

    const button = screen.getByRole('button')
    expect(button).not.toHaveClass('bg-on fg-in')
    expect(button).toHaveStyle({
      '--ripple-color': '#6C43E0',
      '--ripple-scale-end': '1',
      '--ripple-scale-start': '0.1',
      '--ripple-size': '100%',
      '--ripple-translate': '0, 0',
    })

    fireEvent.focus(button)
    expect(button).toHaveClass('bg-on')

    fireEvent.mouseDown(button)
    expect(button).toHaveClass('bg-on fg-in')

    // foreground is locked for a minimum time to animate the ripple
    fireEvent.mouseUp(button)
    runTimers()
    expect(button).toHaveClass('bg-on fg-out')
    runTimers()
    expect(button).toHaveClass('bg-on')

    fireEvent.blur(button)
    expect(button).not.toHaveClass('bg-on fg-in')
  })

  test('Color critical', () => {
    renderWithTheme(
      <ButtonTransparent color="critical">Test</ButtonTransparent>
    )

    const button = screen.getByRole('button')
    expect(button).toHaveStyle({ '--ripple-color': '#CC1F36' })
  })
})


text:
// This file is automatically generated.

package adila.db;

/*
 * Acer Liquid S2
 *
 * DEVICE: a12
 * MODEL: S520
 */
final class a12 {
    public static final String DATA = "Acer|Liquid S2|";
}


text:
/*----------------------------------------------------------------------------
 SigmaTel Inc
 $Archive: /Fatfs/FileSystem/Fat32/handle/Handle.c $
 $Revision: 18 $
 $Date: 9/27/03 5:32p $
 Description: Handle.c
 Notes:
----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------
		File Includes
----------------------------------------------------------------------------*/
#include <types.h>
#include "fstypes.h"
#include "fat_internal.h"
#include "filesystem/fsapi.h"

/*----------------------------------------------------------------------------
>  Function Name:  RtStatus_t Freehandle(int32_t HandleNumber)

   FunctionType:   Reentrant

   Inputs:         1)Handle number

   Outputs:        Returns 0 or an ERROR CODE if HandleNumber exceeds maxhandles

   Description:    marks the given handle number in the handle table as free
<
----------------------------------------------------------------------------*/
RtStatus_t Freehandle(int32_t HandleNumber)
{

    // Ensure the handle table pointer is not NULL.
    assert(Handle);

    // Check whether the passed handle number is within range
    if ((HandleNumber < 0) || (HandleNumber >= maxhandles))
        return ERROR_OS_FILESYSTEM_MAX_HANDLES_EXCEEDED;

    Handle[HandleNumber].HandleActive = 0;
    Handle[HandleNumber].ErrorCode = 0;

    return SUCCESS;
}

/*----------------------------------------------------------------------------
>  Function Name: RtStatus_t Updatehandlemode(int32_t HandleNumber,int32_t Mode)

   FunctionType:  Reentrant

   Inputs:        1) Handle number
                  2) Mode

   Outputs:       Returns SUCCESS or Error if the mode can not be updated.

   Description:   Updates the mode field of the given handle number with
                  the specified mode.
<
----------------------------------------------------------------------------*/
RtStatus_t Updatehandlemode(int32_t HandleNumber, int32_t Mode)
{
    // Ensure the handle table pointer is not NULL.
    assert(Handle);

    // Check whether the passed handle number is within range
    if ((HandleNumber < 0) || (HandleNumber >= maxhandles))
        return ERROR_OS_FILESYSTEM_MAX_HANDLES_EXCEEDED;

    Handle[HandleNumber].Mode = (FileSystemModeTypes_t) Mode;
    return SUCCESS;
}

/*----------------------------------------------------------------------------
>  Function Name: RtStatus_t Gethandlemode(int32_t HandleNumber,int32_t Mode)

   FunctionType:  Reentrant

   Inputs:        1) Handle number
                  2) Mode

   Outputs:       Returns HandleMode or an Error.

   Description:   Updates the mode field of the given handle number with
                  the specified mode.
<
----------------------------------------------------------------------------*/
int32_t Gethandlemode(int32_t HandleNumber)
{
    // Ensure the handle table pointer is not NULL.
    assert(Handle);

    // Check whether the passed handle number is within range
    if ((HandleNumber < 0) || (HandleNumber >= maxhandles))
        return ERROR_OS_FILESYSTEM_MAX_HANDLES_EXCEEDED;
    return Handle[HandleNumber].Mode;
}

/*----------------------------------------------------------------------------
>  Function Name: RtStatus_t IsHandleWriteAllocated(int32_t HandleNumber)

   FunctionType:  Reentrant

   Inputs:        1) Handle number

   Outputs:       Returns WRITE_MODE if Handle is allocated for Write,
                  if not then returns NOT_WRITE_MODE (0)

   Description:   Checks whether the file associated with the given
                  handle number is already opened for write mode or not.
<
----------------------------------------------------------------------------*/
FileSystemModeTypes_t IsHandleWriteAllocated(int32_t HandleNumber)
{
    int32_t i;

    // Ensure the handle table pointer is not NULL.
    assert(Handle);

    EnterNonReentrantSection();
    // Check whether the passed handle number is within range
    if ((HandleNumber < 0) || (HandleNumber >= maxhandles)) {
        LeaveNonReentrantSection();
        // Cast to FileSystem mode to prevent errors.
        return (FileSystemModeTypes_t) ERROR_OS_FILESYSTEM_MAX_HANDLES_EXCEEDED;
    }

    for (i = FIRST_VALID_HANDLE; i < maxhandles; i++) {
        if (i != HandleNumber) {
            if (Handle[i].HandleActive == 1) {
                if (Handle[HandleNumber].Device == Handle[i].Device) {
                    if (Handle[HandleNumber].DirSector == Handle[i].DirSector) {
                        if (Handle[HandleNumber].diroffset == Handle[i].diroffset)
                            if (Handle[i].Mode & WRITE_MODE) {
                                LeaveNonReentrantSection();
                                return WRITE_MODE;
                            }
                    }
                }
            }
        }
    }
    LeaveNonReentrantSection();
    return NOT_WRITE_MODE;
}

/*----------------------------------------------------------------------------
>  Function Name: int32_t Searchfreehandleallocate(void)

   FunctionType:  Reentrant

   Inputs:        Nil

   Outputs:       Handle number of free handle or error(NofreeHandle) if no
                  free handle is available

   Description:   Searches in the handle table for free handle. If free handle is found
                  then mark this handle  as active in the handle table
<
----------------------------------------------------------------------------*/
int32_t Searchfreehandleallocate(void)
{
    int32_t i;

    // Ensure the handle table pointer is not NULL.
    assert(Handle);

    EnterNonReentrantSection();
    for (i = FIRST_VALID_HANDLE; i < maxhandles; i++) {
        if (Handle[i].HandleActive == 0) {
            Handle[i].HandleActive = 1;
            Handle[i].ErrorCode = 0;
            Handle[i].FileSize = 0;
            Handle[i].Mode = 0;
            Handle[i].DirSector = 0;
            Handle[i].diroffset = 0;
            SeekPoint_InitializeBuffer(i);
            LeaveNonReentrantSection();
            return i;
        }
    }

    LeaveNonReentrantSection();
    return ERROR_OS_FILESYSTEM_NO_FREE_HANDLE;
}

/*----------------------------------------------------------------------------
>  Function Name: RtStatus_t Isfileopen(int32_t HandleNumber)

   FunctionType:  Reentrant

   Inputs:        1) Handle number

   Outputs:       Returns ERROR_OS_FILESYSTEM_FILE_OPEN if file is opened else SUCCESS

   Description:   Checks whether the file associated with the given
                  handle number is already opened or not.
<
----------------------------------------------------------------------------*/
RtStatus_t Isfileopen(int32_t HandleNumber)
{
    int32_t i;

    // Ensure the handle table pointer is not NULL.
    assert(Handle);

    // Check whether the passed handle number is within range
    // To Fix -> stmp00014483.
    if ((HandleNumber < FIRST_VALID_HANDLE - 1) || (HandleNumber >= maxhandles))
        return ERROR_OS_FILESYSTEM_MAX_HANDLES_EXCEEDED;

    for (i = FIRST_VALID_HANDLE - 1; i < maxhandles; i++) {
        if (i != HandleNumber) {
            if (Handle[HandleNumber].Device == Handle[i].Device) {
                if (Handle[i].HandleActive == 1) {
                    if (Handle[HandleNumber].CurrentSector == Handle[i].DirSector) {
                        if (Handle[HandleNumber].BytePosInSector == Handle[i].diroffset)
                            return ERROR_OS_FILESYSTEM_FILE_OPEN;
                    }
                }
            }
        }
    }
    return SUCCESS;
}

/*----------------------------------------------------------------------------
>  Function Name: RtStatus_t IsCurrWorkDir(int32_t HandleNumber)

   FunctionType:  Reentrant

   Inputs:        1) Handle number

   Outputs:       Returns ERROR_OS_FILESYSTEM_CURRENT_WORK_DIR if given directory is current working
                  directory else SUCCESS

   Description:   Checks whether the directory associated with the given
                  handle number is current working directory.
<
----------------------------------------------------------------------------*/
RtStatus_t IsCurrWorkDir(int32_t HandleNumber)
{
    // Ensure the handle table pointer is not NULL.
    assert(Handle);

    EnterNonReentrantSection();
    if ((HandleNumber < 0) || (HandleNumber >= maxhandles)) {
        LeaveNonReentrantSection();
        return ERROR_OS_FILESYSTEM_MAX_HANDLES_EXCEEDED;
    }

    if (Handle[HandleNumber].Device == Handle[CWD_HANDLE].Device) {
        if (Handle[HandleNumber].DirSector == Handle[CWD_HANDLE].DirSector) {
            if (Handle[HandleNumber].diroffset == Handle[CWD_HANDLE].diroffset) {
                LeaveNonReentrantSection();
                return ERROR_OS_FILESYSTEM_CURRENT_WORK_DIR;
            }
        }
    }

    LeaveNonReentrantSection();
    return SUCCESS;
}

/*----------------------------------------------------------------------------
>  Function Name: int32_t GetCWDHandle(void)

   FunctionType:  Reentrant

   Inputs:        None

   Outputs:       Returns Handle Number of the new free hnadle found or error if function fails

   Description:   Finds a free handle and copies the handle 0 (CWD handle) to this new handle.
<----------------------------------------------------------------------------*/
int32_t GetCWDHandle(void)
{
    int32_t HandleNumber;

    // Ensure the handle table pointer is not NULL.
    assert(Handle);

    if ((HandleNumber = Searchfreehandleallocate()) < 0)
        return (ERROR_OS_FILESYSTEM_NO_FREE_HANDLE);

    EnterNonReentrantSection();

    /* copy the handle 0 (CWD handle) to this new handle found */
    Handle[HandleNumber] = Handle[CWD_HANDLE];

    LeaveNonReentrantSection();

    /* Remove Handle Write Mode */
    Handle[HandleNumber].Mode = (FileSystemModeTypes_t) (DIRECTORY_MODE + READ_MODE);

    return HandleNumber;
}

/*----------------------------------------------------------------------------
>  Function Name:  RtStatus_t GetDeviceFromHandle(int32_t HandleNumber, int32_t *pDeviceNumber)

   FunctionType:   Reentrant

   Inputs:         1) Handle number
				   2) Device number pointer

   Outputs:        Writes the device handle to the device number pointer address

   Description:    Reads the handle's device number
<
----------------------------------------------------------------------------*/
RtStatus_t GetDeviceFromHandle(int32_t HandleNumber, int32_t * pDeviceNumber)
{
    // Ensure the handle table pointer is not NULL.
    assert(Handle);

    // Check whether the passed handle number is within range
    if ((HandleNumber < 0) || (HandleNumber >= maxhandles))
        return ERROR_OS_FILESYSTEM_MAX_HANDLES_EXCEEDED;

    if (HandleNumber == 0)
        return ERROR_OS_FILESYSTEM_HANDLE_NOT_ACTIVE;

    if (Handle[HandleNumber].HandleActive != 0)
        return ERROR_OS_FILESYSTEM_HANDLE_NOT_ACTIVE;
    else {
        *pDeviceNumber = Handle[HandleNumber].Device;
        return SUCCESS;
    }
}

/*----------------------------------------------------------------------------
>  Function Name: RtStatus_t UpdateHandle(int32_t HandleNumber,int32_t clusterno)

   FunctionType:  Reentrant

   Inputs:        1) Handle Number
                  2) Cluster Number

   Outputs:       Returns 0

   Description:   Updates the handle entries according to the cluster number

<
----------------------------------------------------------------------------*/
RtStatus_t UpdateHandle(int32_t HandleNumber, int32_t clusterno)
{
    // Ensure the handle table pointer is not NULL.
    assert(Handle);

    if ((HandleNumber < 0) || (HandleNumber >= maxhandles))
        return ERROR_OS_FILESYSTEM_MAX_HANDLES_EXCEEDED;

    Handle[HandleNumber].diroffset = Handle[HandleNumber].BytePosInSector;
    Handle[HandleNumber].DirSector = Handle[HandleNumber].CurrentSector;
    Handle[HandleNumber].StartingCluster = clusterno;
    Handle[HandleNumber].CurrentCluster = clusterno;
    Handle[HandleNumber].CurrentSector =
        Firstsectorofcluster(Handle[HandleNumber].Device, clusterno);
    Handle[HandleNumber].CurrentOffset = 0;
    Handle[HandleNumber].BytePosInSector = 0;
    Handle[HandleNumber].SectorPosInCluster = 0;

    return SUCCESS;
}

/*----------------------------------------------------------------------------
>  Function Name:  RtStatus_t Handleactive(int32_t HandleNumber)

   FunctionType:   Reentrant

   Inputs:         1) Handle number

   Outputs:        Returns 0 if Handle is active else an ERROR CODE

   Description:    Checks the handle active field of the given handle number.
<
----------------------------------------------------------------------------*/
RtStatus_t Handleactive(int32_t HandleNumber)
{
    // Check whether the passed handle number is within range
    if ((HandleNumber < 0) || (HandleNumber >= maxhandles))
        return ERROR_OS_FILESYSTEM_MAX_HANDLES_EXCEEDED;

    if (HandleNumber == 0)
        return ERROR_OS_FILESYSTEM_HANDLE_NOT_ACTIVE;

    if (Handle == NULL)
        return ERROR_OS_FILESYSTEM_HANDLE_NOT_ACTIVE;

    if (Handle[HandleNumber].HandleActive == 1)
        return SUCCESS;

    else
        return ERROR_OS_FILESYSTEM_HANDLE_NOT_ACTIVE;
}

/*----------------------------------------------------------------------------
>  Function Name: uint8_t CheckMode(uint32_t HandleNumber)

   FunctionType:  Non-Reentrant

   Inputs:        1)HandleNumber

   Outputs:       Returns Mode field of the given HandleNumber

   Description:   Finds the Mode field of the given HandleNumber
<
----------------------------------------------------------------------------*/
uint8_t CheckMode(uint32_t HandleNumber)
{
    return Handle[HandleNumber].Mode;
}

/*----------------------------------------------------------------------------
>  Function Name:  RtStatus_t Ferror(int32_t HandleNumber)

   FunctionType:  Reentrant

   Inputs:        1) Handle Number

   Outputs:       Returns Error code for handle

   Description:   Finds the error code in the handle table
<
----------------------------------------------------------------------------*/
int32_t Ferror(int32_t HandleNumber)
{
    RtStatus_t RetValue;        // Don't init to save memory.

    EnterNonReentrantSection();

    // Check whether the passed handle number is within range
    if ((HandleNumber < 0) || (HandleNumber >= maxhandles)) {
        LeaveNonReentrantSection();
        return ERROR_OS_FILESYSTEM_MAX_HANDLES_EXCEEDED;
    }

    if ((RetValue = Handleactive(HandleNumber)) < 0) {
        LeaveNonReentrantSection();
        return RetValue;
    }
    LeaveNonReentrantSection();
    return Handle[HandleNumber].ErrorCode;
}


text:
import template from "./companion-data-type-rules-section.html"
import {initialiseData} from "../../../common";

import CompanionDataTypeRulesPanel from "../svelte/CompanionDataTypeRulesPanel.svelte";

const bindings = {
    parentEntityRef: "<"
};

const initialState = {
    CompanionDataTypeRulesPanel
};

function controller() {

    const vm = initialiseData(this, initialState);

}

const component ={
    template,
    bindings,
    controller
}

export default {
    id: "waltzCompanionDataTypeRulesSection",
    component
}


text:
docker_gogs
===========

Testing phusion/baseimage:0.9.12 with gogits/gogs:0.4.2

### Simple test :

```
git clone https://github.com/Paulmicha/docker_gogs.git
cd docker_gogs/
docker build -t="paulmicha/docker_gogs" .
```

### Run :
```
docker run --name="gogs" -d -p 3000:3000 paulmicha/docker_gogs
```

### Run + allow ssh-ing inside container :
```
docker run --name="gogs" -d -p 3000:3000 paulmicha/docker_gogs /sbin/my_init --enable-insecure-key
```


text:
package org.codehaus.groovy.tools.javac;

import java.util.List;

import org.codehaus.groovy.control.CompilationUnit;

/**
 * @author Alex.Tkachman
 */
public interface JavaCompiler {
    void compile(List<String> files, CompilationUnit cu);
}


text:
'use strict'

const expect = require('chai').expect
const Field = require(__dirname + '/../src/field')

describe('Field', () => {
  describe('Parsing', () => {
    /*
    it('Prefix', () => {
      // arrange / act
      let p_require = parser.getPrefix('*string')
      let p_hidden = parser.getPrefix('-string')
      let p_unique = parser.getPrefix('!string')
      let p_mixed_urh = parser.getPrefix('!*-string')
      // assert
      expect(p_require.size).to.equal(1)
      expect(p_require.has('*')).to.equal(true)
      expect(p_hidden.size).to.equal(1)
      expect(p_hidden.has('-')).to.equal(true)
      expect(p_unique.size).to.equal(1)
      expect(p_unique.has('!')).to.equal(true)
      expect(p_mixed_urh.size).to.equal(3)
      expect(p_mixed_urh.has('*')).to.equal(true)
      expect(p_mixed_urh.has('-')).to.equal(true)
      expect(p_mixed_urh.has('!')).to.equal(true)
    })
    */

    it('Type / Namespace', () => {
      // arrange
      let d_string = '*string'
      let d_int = '-!int>0'
      let d_bool = '*!-mynamespace.bool'
      // act
      let f_string = Field.create(d_string)
      let f_int = Field.create(d_int)
      let f_bool = Field.create(d_bool)
      // assert
      expect(f_string.type).to.equal('string')
      expect(f_string.namespace).to.equal(undefined)
      expect(f_int.type).to.equal('int')
      expect(f_int.namespace).to.equal(undefined)
      expect(f_bool.type).to.equal('bool')
      expect(f_bool.namespace).to.equal('mynamespace')
    })

    it('Min / Max', () => {
      // arrange
      let d_none = 'int'
      let d_min = 'int>1'
      let d_max = 'int<10'
      let d_both_a = 'int>1<10'
      let d_both_b = 'int<10>1'
      // act
      let f_none = Field.create(d_none)
      let f_min = Field.create(d_min)
      let f_max = Field.create(d_max)
      let f_both_a = Field.create(d_both_a)
      let f_both_b = Field.create(d_both_b)
      // arrange
      expect(f_none.max).to.equal(undefined)
      expect(f_none.min).to.equal(undefined)
      expect(f_min.max).to.equal(undefined)
      expect(f_min.min).to.equal(1)
      expect(f_max.max).to.equal(10)
      expect(f_max.min).to.equal(undefined)
      expect(f_both_a.max).to.equal(10)
      expect(f_both_a.min).to.equal(1)
      expect(f_both_b.max).to.equal(10)
      expect(f_both_b.min).to.equal(1)
    })

    it('array', () => {
      let f_regular = Field.create('string')
      let f_array = Field.create('string[]')
      let f_array_max = Field.create('string[]<10')

      // assert
      expect(f_regular.isArray).to.equal(false)
      expect(f_array.isArray).to.equal(true)
      expect(f_array_max.isArray).to.equal(true)
      expect(f_array_max.max).to.equal(10)

    })
  })

  describe('Validation', () => {
    it('validation', () => {
      // arrange
      let f = Field.create("*string>3")
      // act
      let result1 = f.validate(undefined)
      let result2 = f.validate('123')
      let result3 = f.validate('this is long enough')
      // assert
      expect(result1.isValid).to.equal(false)
      expect(result2.isValid).to.equal(false)
      expect(result3.isValid).to.equal(true)
    })
  })

})


text:
package edu.mit.cci.wikilanguage.main

import edu.mit.cci.wikilanguage.db.DAO
import edu.mit.cci.wikilanguage.wiki.{TopNPeopleRetrieverByYear, BetweennessByYearCalculator}
import java.util.concurrent.Executors

/**
 * @author pdeboer
 *         First created on 14/01/14 at 18:45
 */
object BetweennessCalculator extends App {
	println("started..")

	val calculator = new BetweennessByYearCalculator()

	val exec = Executors.newFixedThreadPool(1)

	DAO.getYears().foreach(year => {
		exec.submit(new Runnable {
			def run() {
				try {
					calculator.process(year)
				}
				catch {
					case e: Exception => {
						println("couldnt process " + year)
						e.printStackTrace(System.err)
					}
				}
			}
		})
	})
	exec.shutdown()

	println("finished.")
}


text:
[PyPI History][1]

[1]: https://pypi.org/project/google-cloud-build/#history

## 0.1.0

11-07-2019 10:48 PST

**Note**:  This library is incompatible with `google-cloud-containeranalysis<0.3.1`. Please upgrade to `google-cloud-containeranalysis>=0.3.1` to use this library.

### New Features
- Initial generation of Cloud Build v1 ([#9510](https://github.com/googleapis/google-cloud-python/pull/9510)).


text:
#pragma once
#include <aws/mq/MQ_EXPORTS.h>
#include <aws/mq/MQRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace MQ
{
namespace Model
{

  /**
   */
  class AWS_MQ_API DescribeBrokerRequest : public MQRequest
  {
  public:
    DescribeBrokerRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "DescribeBroker"; }

    Aws::String SerializePayload() const override;

    /**
     *
The unique ID that Amazon MQ generates for the broker.

     */
    inline const Aws::String& GetBrokerId() const{ return m_brokerId; }

    /**
     *
The unique ID that Amazon MQ generates for the broker.

     */
    inline bool BrokerIdHasBeenSet() const { return m_brokerIdHasBeenSet; }

    /**
     *
The unique ID that Amazon MQ generates for the broker.

     */
    inline void SetBrokerId(const Aws::String& value) { m_brokerIdHasBeenSet = true; m_brokerId = value; }

    /**
     *
The unique ID that Amazon MQ generates for the broker.

     */
    inline void SetBrokerId(Aws::String&& value) { m_brokerIdHasBeenSet = true; m_brokerId = std::move(value); }

    /**
     *
The unique ID that Amazon MQ generates for the broker.

     */
    inline void SetBrokerId(const char* value) { m_brokerIdHasBeenSet = true; m_brokerId.assign(value); }

    /**
     *
The unique ID that Amazon MQ generates for the broker.

     */
    inline DescribeBrokerRequest& WithBrokerId(const Aws::String& value) { SetBrokerId(value); return *this;}

    /**
     *
The unique ID that Amazon MQ generates for the broker.

     */
    inline DescribeBrokerRequest& WithBrokerId(Aws::String&& value) { SetBrokerId(std::move(value)); return *this;}

    /**
     *
The unique ID that Amazon MQ generates for the broker.

     */
    inline DescribeBrokerRequest& WithBrokerId(const char* value) { SetBrokerId(value); return *this;}

  private:

    Aws::String m_brokerId;
    bool m_brokerIdHasBeenSet;
  };

} // namespace Model
} // namespace MQ
} // namespace Aws


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

namespace bfp4f_sharp_api.vos
{
    class GetLoadoutVO
    {
        public string result { get; set; }
        public string status { get; set; }
        public GetLoadoutDataVO data { get; set; }
    }

    class GetLoadoutDataVO
    {
        public List<GetLoadoutDataApparelItemVO> apparel { get; set; }
        public List<GetLoadoutDataAttachmentItemVO> attachments { get; set; }
        public List<GetLoadoutDataEquipmentItemVO> equipment { get; set; }
    }

    class GetLoadoutDataApparelItemVO
    {
        public bool buyable { get; set; }
        public string category { get; set; }
        public string categoryname { get; set; }
        public string description { get; set; }
        public int equippedSlot { get; set; } // @todo: is it bugged too?
        public bool expireTS { get; set; }
        public bool expired { get; set; }
        public string expiredate { get; set; }
        public string id { get; set; }
        public bool isDefault { get; set; }
        public bool isLocked { get; set; }
        public bool isnew { get; set; }
        public string lockCriteria { get; set; }
        public string lockType { get; set; }
        public int maxNumPockets { get; set; }
        public int minNumPockets { get; set; }
        public string name { get; set; }
        public int numberOfPockets { get; set; }
        public bool owned { get; set; }
        public string ownedPermanent { set; get; }
        public List<string> prices { set; get; }
        public string promotionType { set; get; }
        public string type { set; get; }
        public List<string> upgrades { set; get; }
        public string usecount { set; get; }
        public string validationGroup { set; get; }
    }

    class GetLoadoutDataAttachmentItemVO
    {
        public bool buyable { get; set; }
        public string category { get; set; }
        public string categoryname { get; set; }
        public string description { get; set; }
        //public int equippedSlot { get; set; } // @todo: it is equal "false" if not set so throws an exception because we have int here :( Solution: make something dynamic
        public bool expireTS { get; set; }
        public bool expired { get; set; }
        public string expiredate { get; set; }
        public string fitsSlot { get; set; }
        public string id { get; set; }
        public bool isDefault { get; set; }
        public bool isLocked { get; set; }
        public bool isnew { get; set; }
        public string lockCriteria { get; set; }
        public string lockType { get; set; }
        public string name { get; set; }
        public bool owned { get; set; }
        public string ownedPermanent { set; get; }
        public List<int> parentItems { set; get; }
        public List<string> prices { set; get; }
        public string promotionType { set; get; }
        public string reticleImage { set; get; }
        //public Dictionary<string, GetLoadoutDataAttachmentItemStatsVO> stats { get; set; } // @todo: There is a bug, when it is empty List. Solution: replace Dictionary with Class
        public string type { set; get; }
        public string usecount { set; get; } // @todo: test it. Why does it show null.
        public string validationGroup { set; get; }
    }

    /// <summary>
    /// Such as Accuracy, AccControl, AccPrecision, Damage, MagSizeIncrease, Zoom etc. etc.
    /// </summary>
    class GetLoadoutDataAttachmentItemStatsVO
    {
        public bool isPenalty { get; set; }
        public int value { get; set; }
    }

    class GetLoadoutDataEquipmentItemVO
    {
        public bool buyable { get; set; }
        public string category { get; set; }
        public string categoryname { get; set; }
        public string description { get; set; }
        public int equippedSlot { get; set; }
        public bool expireTS { get; set; }
        public bool expired { get; set; }
        public string expiredate { get; set; }
        public string id { get; set; }
        public bool isLocked { get; set; }
        public bool isnew { get; set; }
        public string lockCriteria { get; set; }
        public string lockType { get; set; }
        public string name { get; set; }
        public bool owned { get; set; }
        public string ownedPermanent { set; get; }
        public List<string> prices { set; get; }
        public string promotionType { set; get; }
        [JsonIgnore]
        public Dictionary<string, GetLoadoutDataWeaponItemStatsVO> stats { get; set; } // @todo: It is buggy when is empty.
        public string type { set; get; }
        public string usecount { set; get; }
        public string validationGroup { set; get; }
    }
    class GetLoadoutDataWeaponItemStatsVO
    {
        public bool isBestInClass { get; set; }
        public int value { get; set; }
    }
}


text:
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { TransitionGroup } from 'react-transition-group'

import Donut from './Donut'
import Fade from './Fade'
import '../css/DonutViewer.css'

class DonutViewer extends Component {
  constructor (...args) {
    super(...args)
    this.state = {
      donuts: [],
      donutQueue: []
    }
  }

  /**
   * Handle new donuts via dispatched props.
   *
   * @param {Object} newProps
   * @param {Array[]} newProps.donuts
   */
  componentWillReceiveProps ({ donuts }) {
    const delay = 500
    const lifespan = 3000
    const nextQueue = [
      ...this.state.donutQueue,
      ...donuts.map(([id, donut]) => ({
        id,
        donut,
        isScheduled: false
      }))
    ].slice(0, 10)
    let toSchedule = nextQueue.filter(({ isScheduled }) => !isScheduled)

    this.setState({
      donuts: this.state.donuts,
      donutQueue: nextQueue.map(item => ({ ...item, isScheduled: true }))
    })

    toSchedule
      .forEach((obj, index) => {
        // Add donuts to state:
        setTimeout(() => {
          console.log('before', this.state.donuts.length, this.state.donutQueue.length)
          console.log('adding this ID', obj.id)
          this.setState({
            donuts: [...this.state.donuts, [obj.id, obj.donut, index]],
            donutQueue: this.state.donutQueue.map(o1 => {
              if (o1.id === obj.id) {
                return Object.assign(o1, { isScheduled: true })
              }
              return o1
            })
          })
        }, delay * index)

        // Remove donut from state:
        setTimeout(() => {
          console.log('after', this.state.donuts.length, this.state.donutQueue.length)
          this.setState({
            donuts: this.state.donuts.filter(([_id]) => _id !== obj.id),
            donutQueue: this.state.donutQueue.filter(({ id }) => id !== obj.id)
          })
        }, lifespan + delay * index)
      })
  }

  render () {
    return (

        <TransitionGroup className='DonutViewer-TransitionGroup'>
          {this.state.donuts.map(([id, donut, index]) => (
            <Fade key={id}>

                <div className={`DonutViewer-item ${index % 2 ? 'DonutViewer-item-odd' : ''}`}>
                  <Donut {...donut} />

            </Fade>
          ))}
        </TransitionGroup>

    )
  }
}

DonutViewer.defaultProps = {
  donuts: []
}

DonutViewer.propTypes = {
  donuts: PropTypes.arrayOf(PropTypes.arrayOf(PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.shape({
      DONUT_FROSTING_COVERAGE: PropTypes.number.isRequired,
      DONUT_FROSTING_THICKNESS: PropTypes.number.isRequired,
      DONUT_INNER_RADIUS: PropTypes.number.isRequired,
      DONUT_OUTER_RADIUS: PropTypes.number.isRequired,
      DONUT_SPRINKLE_COVERAGE: PropTypes.number.isRequired
    })
  ])))
}

export default DonutViewer


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
utils.selectNamespace('utils.files', function(files) {

    files.loaded_js = [];
    files.rpath = RESOURCE_PATH || "res";
    files.context = CONTEXT_PATH || "";
    files.setContext = function(context){
    	this.context = context;
    };
    files.setResourcePath = function(path){
    	this.rpath = path;
    };
    files.loadJs = function(js){
    	files.load(this.context + this.rpath  + js);
    };
    files.load = function(js){
        $('body').append('<jscript class="client" src="' + js + '"></jscript>');
        $('head').append('<script src="' + js + '" type="text/javascript"></script>');
    };
    utils.require = function() {
        for (var i = 0; i < arguments.length; i++) {
            var js = arguments[i];
            if (!files.loaded_js[js]){
            	files.loadJs(js);
            }
            files.loaded_js[js] = js;
        }
    };

});


text:
[Harbor](https://goharbor.io/) is used as the default package repository for Lagoon when deploying to Kubernetes infrastructure. Harbor provides a docker registry and a container security scanning solution provided by [Clair](https://coreos.com/clair/docs/latest/).

**Note** When running Lagoon locally, the configuration for Harbor is handled entirely automagically.

If you are running Lagoon locally, you can access that UI at [localhost:8084](https://localhost:8084/). The username is `admin` and the password is `admin`

**Note:** If you are hosting a site with amazee.io, we do not allow customer access to the Harbor UI within amazee.io's Lagoon.

Once logged in, the first screen is a list of all repositories your user has access to. Each "repository" in Harbor correlates to a project in Lagoon.

![Harbor Projects Overview](projects_overview.png)

Within each Harbor repository, you'll see a list of container images from all environments with a single Lagoon project.

![Harbor Repositories Overview](repositories_overview.png)

From here, you can drill down into an individual container in order to see its details, including an overview of its security scan results.

![Harbor Container Overview](container_overview.png)

## How Harbor interacts with the Problems Database

Lagoon can respond to Harbor webhook scan events and, if the result set matches a Project environment, will use the results and generate entries in the Problems system.

By default, Lagoon tries to parse out the incoming Harbor repo to match the pattern `PROJECT/ENVIRONMENT/SERVICE` - so if we had a project FOO, with environments PROD and DEV, and each of these environments had services `nodejs` and `mariadb` - an incoming Harbor repo name of `FOO/DEV/mariadb` will tell us precisely which service this image scan corresponds to.

In the case where the Harbor repo name does not correspond to this schema, we need some way of mapping scans to the right Project/environment/service. To allow this, we introduce an object called a Harbor Scan Matcher. This is essentially a regex that is meant to match against incoming Harbor repo names that associates the scan with existing projects and environments (or a range of them).We make use named capture groups in our regexes to match Project, Environment, and Service names. If the name of an environment, project, or service is not present in your regex, you can assign a default name for each of these that will be used instead. This is best illustrated by an example.

Below we create a Harbor Scan Matcher that matches an incoming repo name for the FOO project - let's assume that the incoming repo name from Harbor does not contain anything corresponding to the environment name, so we'll by default assume that this is going to go to an environment named PROD.If the harbor repo name is something like `MY_ENTERPRISE_PROJECT-<ENVIRONMENT NAME>` we could match with by creating the following Harbor Scan Matcher:

```graphql
mutation addProblemHarborScan {
  addProblemHarborScanMatch(input: {name: "EnterpriseProjectMatcher", description:"Matches incoming Harbor Scans for FOO",
    defaultLagoonProject: "FOO"
    defaultLagoonService: "nodejs"
    regex: "^MY_ENTERPRISE_PROJECT-(?<lagoonEnvironmentName>.+)$"
  }) {
    id
    name
    description
    regex
  }
}
```

This will now match any incoming string of the form `MY_ENTERPRISE_PROJECT-<ENVIRONMENT Name>` - assign it to the FOO project and attach any vulnerabilities found to the `nodejs` service.This is an ADMIN ONLY function since the Harbor Scan Matchers need to be set across the entire Lagoon instance. If non-admin users could set these then it would be possible to reroute Harbor scans from one project to another.


text:
'use strict';

var times = {};
var message;
var but;

if (localStorage.times) { // Local Storage exists
  times = JSON.parse(localStorage.times);

  message = document.getElementById('personal_message');
  message.textContent = 'Greetings ' + times.userName + '! Here is your summary:';

  var pElement;
  var divElement;
  var solvedProblems = document.getElementById('solved');
  var unsolvedProblems = document.getElementById('unsolved');

  // Display solved problems
  for(var key in times.goal) {
    divElement = document.createElement('div');
    but = document.createElement('button');
    but.textContent = 'X';
    but.addEventListener('click', removeItemSolved);
    divElement.appendChild(but);
    divElement.id = times.goal[key];
    pElement = document.createElement('p');
    pElement.textContent = 'Problem: ' + key;
    divElement.appendChild(pElement);
    pElement = document.createElement('p');
    pElement.textContent = 'Solution: ' + times.goal[key];
    divElement.appendChild(pElement);
    solvedProblems.appendChild(divElement);
  }

  // Display unsolved problems
  for(key in times.unsolved) {
    divElement = document.createElement('div');
    but = document.createElement('button');
    but.textContent = 'X';
    but.addEventListener('click', removeItemUnsolved);
    divElement.appendChild(but);
    divElement.id = times.unsolved[key];
    pElement = document.createElement('p');
    pElement.textContent = 'Problem: ' + key;
    divElement.appendChild(pElement);
    pElement = document.createElement('p');
    pElement.textContent = 'Comment: ' + times.unsolved[key];
    divElement.appendChild(pElement);
    unsolvedProblems.appendChild(divElement);
  }

} else {
  // no local storage
  message = document.getElementById('personal_message');
  message.textContent = 'You have no Duck-Timer summary.';
}

function handleBack() {
  window.location.href = 'main.html';
}

function removeItemSolved (event) {
  var button = event.target;
  for(var key in times.goal) {
    if(button.parentNode.id === times.goal[key]){
      console.log('Found match!');
      delete times.goal[key];
      localStorage.times = JSON.stringify(times);
    }
  }
  button.parentNode.parentNode.removeChild(button.parentNode);
}

function removeItemUnsolved (event) {
  var button = event.target;
  for(var key in times.unsolved) {
    if(button.parentNode.id === times.unsolved[key]){
      delete times.unsolved[key];
      localStorage.times = JSON.stringify(times);
    }
  }
  button.parentNode.parentNode.removeChild(button.parentNode);
}


text:
import React from "react";
import { shallow, mount } from "enzyme";
import { message } from "@src/index";
import {
  Type,
  TRANSITION_DURATION,
  Message
} from "@components/Message/lib/Message";
import { getStatusIcon } from "@components/Icon";
import { overrideError } from "@src/utils";

let recoverError: null | Function = null;
beforeAll(() => {
  recoverError = overrideError();
  jest.useFakeTimers();
});
afterAll(() => {
  if (typeof recoverError === "function") {
    recoverError();
  }
  jest.useRealTimers();
});

describe("Message", () => {
  test("handle 'type' properly", () => {
    const acceptableTypes: Type[] = ["info", "success", "warning", "error"];
    acceptableTypes.forEach(type => {
      const wrapper = shallow(<Message type={type}>test</Message>);
      expect(wrapper.contains(getStatusIcon(type))).toBe(true);
    });
  });
  test("won't add additional class for incorrect 'type'", () => {
    const type: string = "whatever";
    // @ts-ignore
    const wrapper = shallow(<Message type={type}>test</Message>);
    // @ts-ignore
    expect(wrapper.contains(getStatusIcon(type))).toBe(false);
  });

  test("duration config works", () => {
    const duration: number = 100;
    message({ message: "duration", duration });
    jest.advanceTimersByTime(TRANSITION_DURATION);
    expect(document.querySelectorAll(".c-message").length).toEqual(1);
    jest.advanceTimersByTime(duration + TRANSITION_DURATION + 1);
    expect(document.querySelectorAll(".c-message").length).toEqual(0);
  });

  test("close all works", () => {
    const messageCount: number = 10;
    new Array(messageCount).fill(0).forEach(() => {
      message({
        message: "message"
      });
    });
    expect(document.querySelectorAll(".c-message").length).toBe(messageCount);
    message.closeAll();
    expect(document.querySelectorAll(".c-message").length).toBe(0);
  });

  test("render message correctly", () => {
    const text = "this is message";
    const TextNode = {text};
    const duration: number = 100;
    message({
      message: TextNode,
      duration
    });
    jest.advanceTimersByTime(TRANSITION_DURATION);
    const span = document.querySelector(".c-message span") as HTMLElement;
    expect(span.textContent).toEqual(text);
    message.closeAll();
  });

  test("support syntax sugar", () => {
    const duration: number = 100;
    const types: Type[] = ["success", "error", "info", "warning"];
    types.forEach(type => {
      message[type]({
        message: type,
        duration
      });
    });
    jest.advanceTimersByTime(TRANSITION_DURATION);
    for (let i = 0; i < types.length; i++) {
      const type = types[i];
      const icon = document.querySelectorAll("i[class*='icon']")[
        i
      ] as HTMLElement;
      const className = `c-icon--${type}`;
      expect(icon.classList.contains(className)).toBe(true);
    }

    jest.advanceTimersByTime(duration + TRANSITION_DURATION);
    expect(document.querySelectorAll(".c-message").length).toBeFalsy();
  });

  test("delay disappear accordingly", () => {
    const duration: number = 100;
    const onClose = jest.fn();
    const Component = () => {
      return (

          <Message duration={duration} onClose={onClose}>
            message
          </Message>

      );
    };
    const wrapper = mount(<Component />);
    const messageComponent = wrapper.find(".c-message");
    messageComponent.simulate("mouseenter");
    expect(onClose).toHaveBeenCalledTimes(0);
    jest.advanceTimersByTime(duration + TRANSITION_DURATION);
    messageComponent.simulate("mouseenter");
    expect(onClose).toHaveBeenCalledTimes(0);
    messageComponent.simulate("mouseleave");
    jest.advanceTimersByTime(
      duration + TRANSITION_DURATION + TRANSITION_DURATION
    );
    expect(onClose).toHaveBeenCalledTimes(1);
    message.closeAll();
  });

  test("config api works", () => {
    const duration: number = 100;
    message.config({
      top: "1px",
      duration
    });
    message({
      message: "top 1px"
    });
    const container = document.querySelector(
      ".c-message-container"
    ) as HTMLElement;
    expect(document.querySelectorAll(".c-message-container").length).toBe(1);
    expect(container.style.top).toBe("1px");
    message.closeAll();
  });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/spring-context.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <filter>
        <filter-name>charsetFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>charsetFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>themostcd</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/admin-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>themostcd</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>/index.jsp</welcome-file>
    </welcome-file-list>
</web-app>


text:
title: sqlalchemy.ext.automap automap_base Example Code
category: page
slug: sqlalchemy-ext-automap-automap-base-examples
sortorder: 500031046
toc: False
sidebartitle: sqlalchemy.ext.automap automap_base
meta: Python example code that shows how to use the automap_base callable from the sqlalchemy.ext.automap module of the SQLAlchemy project.

`automap_base` is a callable within the `sqlalchemy.ext.automap` module of the SQLAlchemy project.

## Example 1 from SQLAthanor
[SQLAthanor](https://github.com/insightindustry/sqlathanor)
([PyPI package information](https://pypi.org/project/sqlathanor/)
and
[project documentation](https://sqlathanor.readthedocs.io/en/latest/index.html))
is a [SQLAlchemy](/sqlalchemy.html) extension that provides serialization and
deserialization support for JSON, CSV, YAML and Python dictionaries.
This project is similar to [Marshmallow](https://marshmallow.readthedocs.io/en/stable/)
with one major difference: SQLAthanor works through SQLAlchemy models
while Marshmallow is less coupled to SQLAlchemy because it requires
separate representations of the serialization objects. Both libraries
have their uses depending on whether the project plans to use SQLAlchemy
for object representations or would prefer to avoid that couping.
SQLAthanor is open sourced under the
[MIT license](https://github.com/insightindustry/sqlathanor/blob/master/LICENSE).

[**SQLAthanor / sqlathanor / automap.py**](https://github.com/insightindustry/sqlathanor/blob/master/sqlathanor/./automap.py)

```python
# automap.py

import sqlalchemy

try:
~~    from sqlalchemy.ext.automap import automap_base as SA_automap_base
    SUPPORTS_AUTOMAP = True
except ImportError:
    SUPPORTS_AUTOMAP = False
    SA_automap_base = bool

from validator_collection import checkers

from sqlathanor import BaseModel
from sqlathanor.errors import SQLAlchemySupportError

~~def automap_base(declarative_base = None,
                 **kwargs):

    if not SUPPORTS_AUTOMAP:
        raise SQLAlchemySupportError(
            'automap is only available in SQLAlchemy v.0.9.1 and higher, ' + \
            'but you are using %s. Please upgrade.' % sqlalchemy.__version__
        )

    if declarative_base is None:
        cls = BaseModel
    elif isinstance(declarative_base, BaseModel) or declarative_base == BaseModel:
        cls = declarative_base
    elif isinstance(declarative_base, tuple):
        for item in declarative_base:
            if item == BaseModel or isinstance(item, BaseModel):
                cls = declarative_base
                break
    else:
        cls = kwargs.pop('cls', None)
        if cls is None and checkers.is_iterable(declarative_base):
            class_list = [BaseModel]
            class_list.extend([x for x in declarative_base])
        elif cls is None and not checkers.is_iterable(declarative_base):
            class_list = [BaseModel, declarative_base]

## ... source file continues with no further automap_base examples...

```

## Example 2 from sandman2
[sandman2](https://github.com/jeffknupp/sandman2)
([project documentation](https://sandman2.readthedocs.io/en/latest/)
and
[PyPI package information](https://pypi.org/project/sandman2/))
is a code library for automatically generating
[RESTful APIs](/application-programming-interfaces.html) from
existing database schemas. This approach is handy for solving
straightforward situations where you want to put an abstraction
layer between one or more applications and your
[relational database](/databases.html) to prevent or reduce
direct database access.

The sandman2 project is provided under the
[Apache License 2.0](https://github.com/jeffknupp/sandman2/blob/master/LICENSE).

[**sandman2 / sandman2 / model.py**](https://github.com/jeffknupp/sandman2/blob/master/sandman2/./model.py)

```python
# model.py

import datetime
from decimal import Decimal

from sqlalchemy.inspection import inspect
from flask_sqlalchemy import SQLAlchemy  # pylint: disable=import-error,no-name-in-module
~~from sqlalchemy.ext.automap import automap_base
from sqlalchemy.ext.declarative import declarative_base

db = SQLAlchemy()

class Model(object):

    __url__ = None

    __version__ = '1'

    __methods__ = {
        'GET',
        'POST',
        'PUT',
        'PATCH',
        'DELETE',
        'HEAD',
        'OPTIONS'
        }

    @classmethod
    def required(cls):
        columns = []

## ... source file abbreviated to get to automap_base examples ...

                instance = getattr(self, relationship.key)
                if instance:
                    link_dict[str(relationship.key)] = instance.resource_uri()
        return link_dict

    def resource_uri(self):
        return self.__url__ + '/' + str(getattr(self, self.primary_key()))

    def update(self, attributes):
        for attribute in attributes:
            setattr(self, attribute, attributes[attribute])
        return self

    @classmethod
    def description(cls):

        description = {}
        for column in cls.__table__.columns:  # pylint: disable=no-member
            column_description = str(column.type)
            if not column.nullable:
                column_description += ' (required)'
            description[column.name] = column_description
        return description

DeclarativeModel = declarative_base(cls=(db.Model, Model))
~~AutomapModel = automap_base(DeclarativeModel)

## ... source file continues with no further automap_base examples...

```


text:
package com.github.aureliano.achmed.client.resources.properties;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.util.Arrays;
import java.util.Set;

import org.junit.Test;

import com.github.aureliano.achmed.client.types.DebianConfigFilesStatus;
import com.github.aureliano.achmed.client.types.PackageProvider;
import com.github.aureliano.achmed.client.validation.ConstraintViolation;
import com.github.aureliano.achmed.client.validation.ObjectValidator;

public class PackagePropertiesTest {

	@Test
	public void testDefaultValues() {
		PackageProperties pkg = new PackageProperties();

		assertEquals("installed", pkg.getEnsure());
		assertEquals(DebianConfigFilesStatus.KEEP, pkg.getConfigFiles());
		assertTrue(pkg.getInstallOptions().isEmpty());
		assertTrue(pkg.getUninstallOptions().isEmpty());
	}

	@Test
	public void testConfigureAttributes() {
		PackageProperties pkg = (PackageProperties) new PackageProperties()
			.put("name", "pkg")
			.put("provider", PackageProvider.APT)
			.put("configFiles", DebianConfigFilesStatus.REPLACE)
			.put("ensure", "latest")
			.put("installOptions", Arrays.asList("-i test"))
			.put("uninstallOptions", Arrays.asList("-u test"))
			.put("source", "src")
			.configureAttributes();

		assertEquals("pkg", pkg.getName());
		assertEquals(PackageProvider.APT, pkg.getProvider());
		assertEquals(DebianConfigFilesStatus.REPLACE, pkg.getConfigFiles());
		assertEquals("latest", pkg.getEnsure());
		assertEquals(Arrays.asList("-i test"), pkg.getInstallOptions());
		assertEquals(Arrays.asList("-u test"), pkg.getUninstallOptions());
		assertEquals("src", pkg.getSource());

		pkg.setProvider(null);
		assertNull(pkg.getProvider());

		pkg.put("provider", "apt").configureAttributes();
		assertEquals(PackageProvider.APT, pkg.getProvider());

		pkg.setConfigFiles(null);
		assertNull(pkg.getConfigFiles());

		pkg.put("configfiles", "replace").configureAttributes();
		assertEquals(DebianConfigFilesStatus.REPLACE, pkg.getConfigFiles());
	}

	@Test
	public void testHashCode() {
		PackageProperties p1 = new PackageProperties();
		PackageProperties p2 = new PackageProperties();

		assertEquals(p1.hashCode(), p2.hashCode());

		p1.setName("pkg");
		assertFalse(p1.hashCode() == p2.hashCode());

		p2.setName("pkg");
		assertTrue(p1.hashCode() == p2.hashCode());

		p1.setProvider(PackageProvider.APT);
		assertFalse(p1.hashCode() == p2.hashCode());

		p2.setProvider(PackageProvider.APT);
		assertTrue(p1.hashCode() == p2.hashCode());
	}

	@Test
	public void testEquals() {
		PackageProperties p1 = new PackageProperties();
		PackageProperties p2 = new PackageProperties();

		assertEquals(p1, p2);

		p1.setName("pkg");
		assertFalse(p1.equals(p2));

		p2.setName("pkg");
		assertTrue(p1.equals(p2));

		p1.setProvider(PackageProvider.APT);
		assertFalse(p1.equals(p2));

		p2.setProvider(PackageProvider.APT);
		assertTrue(p1.equals(p2));
	}

	@Test
	public void testValidation() {
		PackageProperties p = new PackageProperties();
		p.setName(null);
		p.setEnsure("present");

		Set<ConstraintViolation> violations = ObjectValidator.instance().validate(p);
		assertEquals(1, violations.size());
		assertEquals(
			"Expected to find a not empty text for field name.",
			violations.iterator().next().getMessage()
		);

		p.setName("");
		violations = ObjectValidator.instance().validate(p);
		assertEquals(1, violations.size());
		assertEquals(
			"Expected to find a not empty text for field name.",
			violations.iterator().next().getMessage()
		);

		p.setName("pkg_name");
		p.setEnsure(null);
		violations = ObjectValidator.instance().validate(p);
		assertEquals(1, violations.size());
		assertEquals(
			"Expected to find a not null value for field ensure. Accept only [ INSTALLED, PRESENT, ABSENT, LATEST, version-value ]",
			violations.iterator().next().getMessage()
		);
	}
}


text:
{{define "title"}}Murder Hobos{{end}} {{define "content"}}

Here's Your Profile, {{.Claims.Username}}

We will have some stuff for you here in the future!

For now, try hovering over your name in the navigation bar to have a look at your spells and characters.

{{end}}{{define "scripts"}}{{end}}


text:
bool CefSchemeRegistrarCToCpp::AddCustomScheme(const CefString& scheme_name,
    bool is_standard, bool is_local, bool is_display_isolated) {
  cef_scheme_registrar_t* _struct = GetStruct();
  if (CEF_MEMBER_MISSING(_struct, add_custom_scheme))
    return false;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Verify param: scheme_name; type: string_byref_const
  DCHECK(!scheme_name.empty());
  if (scheme_name.empty())
    return false;

  // Execute
  int _retval = _struct->add_custom_scheme(_struct,
      scheme_name.GetStruct(),
      is_standard,
      is_local,
      is_display_isolated);

  // Return type: bool
  return _retval?true:false;
}

// CONSTRUCTOR - Do not edit by hand.

CefSchemeRegistrarCToCpp::CefSchemeRegistrarCToCpp() {
}

template<> cef_scheme_registrar_t* CefCToCpp<CefSchemeRegistrarCToCpp,
    CefSchemeRegistrar, cef_scheme_registrar_t>::UnwrapDerived(
    CefWrapperType type, CefSchemeRegistrar* c) {
  NOTREACHED() << "Unexpected class type: " << type;
  return NULL;
}

#ifndef NDEBUG
template<> base::AtomicRefCount CefCToCpp<CefSchemeRegistrarCToCpp,
    CefSchemeRegistrar, cef_scheme_registrar_t>::DebugObjCt = 0;
#endif

template<> CefWrapperType CefCToCpp<CefSchemeRegistrarCToCpp,
    CefSchemeRegistrar, cef_scheme_registrar_t>::kWrapperType =
    WT_SCHEME_REGISTRAR;


text:
order: 26
title:
  en-US: Drag sorting
  zh-CN: 拖拽排序
---

## zh-CN

使用自定义元素,我们可以集成 [react-dnd](https://github.com/react-dnd/react-dnd) 来实现拖拽排序。

## en-US

By using `components`, we can integrate table with [react-dnd](https://github.com/react-dnd/react-dnd) to implement drag sorting function.

```tsx
import { Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import update from 'immutability-helper';
import React, { useCallback, useRef, useState } from 'react';
import { DndProvider, useDrag, useDrop } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';

interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
}

interface DraggableBodyRowProps extends React.HTMLAttributes<HTMLTableRowElement> {
  index: number;
  moveRow: (dragIndex: number, hoverIndex: number) => void;
}

const type = 'DraggableBodyRow';

const DraggableBodyRow = ({
  index,
  moveRow,
  className,
  style,
  ...restProps
}: DraggableBodyRowProps) => {
  const ref = useRef<HTMLTableRowElement>(null);
  const [{ isOver, dropClassName }, drop] = useDrop({
    accept: type,
    collect: monitor => {
      const { index: dragIndex } = monitor.getItem() || {};
      if (dragIndex === index) {
        return {};
      }
      return {
        isOver: monitor.isOver(),
        dropClassName: dragIndex < index ? ' drop-over-downward' : ' drop-over-upward',
      };
    },
    drop: (item: { index: number }) => {
      moveRow(item.index, index);
    },
  });
  const [, drag] = useDrag({
    type,
    item: { index },
    collect: monitor => ({
      isDragging: monitor.isDragging(),
    }),
  });
  drop(drag(ref));

  return (
    <tr
      ref={ref}
      className={`${className}${isOver ? dropClassName : ''}`}
      style={{ cursor: 'move', ...style }}
      {...restProps}
    />
  );
};

const columns: ColumnsType<DataType> = [
  {
    title: 'Name',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: 'Age',
    dataIndex: 'age',
    key: 'age',
  },
  {
    title: 'Address',
    dataIndex: 'address',
    key: 'address',
  },
];

const App: React.FC = () => {
  const [data, setData] = useState([
    {
      key: '1',
      name: 'John Brown',
      age: 32,
      address: 'New York No. 1 Lake Park',
    },
    {
      key: '2',
      name: 'Jim Green',
      age: 42,
      address: 'London No. 1 Lake Park',
    },
    {
      key: '3',
      name: 'Joe Black',
      age: 32,
      address: 'Sidney No. 1 Lake Park',
    },
  ]);

  const components = {
    body: {
      row: DraggableBodyRow,
    },
  };

  const moveRow = useCallback(
    (dragIndex: number, hoverIndex: number) => {
      const dragRow = data[dragIndex];
      setData(
        update(data, {
          $splice: [
            [dragIndex, 1],
            [hoverIndex, 0, dragRow],
          ],
        }),
      );
    },
    [data],
  );

  return (
    <DndProvider backend={HTML5Backend}>
      <Table
        columns={columns}
        dataSource={data}
        components={components}
        onRow={(_, index) => {
          const attr = {
            index,
            moveRow,
          };
          return attr as React.HTMLAttributes<any>;
        }}
      />
    </DndProvider>
  );
};

export default App;
```

```css
#components-table-demo-drag-sorting tr.drop-over-downward td {
  border-bottom: 2px dashed #1890ff;
}

#components-table-demo-drag-sorting tr.drop-over-upward td {
  border-top: 2px dashed #1890ff;
}
```


text:
export default function then(callback, delay = 100) {
  setTimeout(callback, jasmine.THEN_DELAY);
  jasmine.THEN_DELAY += delay;
}

beforeEach(() => (jasmine.THEN_DELAY = 0));


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <title>MDInsider ♥ Open Source / 404 / Page Not Found</title>

    <meta name="author" content="MDInsider, Inc.">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="shortcut icon" href="/assets/themes/gilt/img/favicon.ico">
    <link href="/atom.xml" type="application/atom+xml" rel="alternate" title="Sitewide ATOM Feed">
    <link href="/rss.xml" type="application/rss+xml" rel="alternate" title="Sitewide RSS Feed">

    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="/assets/themes/gilt/css/github-light.css">
    <link rel="stylesheet/less" href="/assets/themes/gilt/css/style.less">

    Join MD Insider Tech
    MDInsider.com

            Categories

              <input type="search" placeholder="Search …" title="Search for:" />

            <menu id="categories-menu">

              <menuitem>
                blog
              </menuitem>

              <menuitem>
                tech
              </menuitem>

            </menu>
            <menu id="search-results">
            </menu>

Tech Blog

404 / Page Not Found

Our Apologies

    The page you're looking for doesn't exist. Please don't let this keep you from
    getting the most out of Gilt. There's a lot more to explore!

    Categories •
    Tags •
    Archives

    Join MD Insider Tech
    MDInsider.com

          © 2015 MDInsider, Inc. • Archives


text:
package reuseport

import "syscall"

var reusePort = syscall.SO_REUSEPORT


text:
<?php

namespace Jadu\Pulsar\Twig\Extension;

class HelperOptionsModifierExtension extends \Twig_Extension
{
    /**
     * Name of this extension
     *
     * @return string
     */
    public function getName()
    {
        return 'modify_options';
    }

    /**
     * Register the `modify_options()` function with Twig.
     *
     * @return array The Twig function
     */
    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('modify_options', array($this, 'modifyOptions'))
        );
    }

    /**
     * Returns a modified options array including error flag, error and help guids
     *
     * @param  array    $options    The form helper options
     * @return array|boolean
     */
    public function modifyOptions($options)
    {
        // If we don't have $options, abandon ship
        if ($options === null) {
            return false;
        }

        // Check if errors are present in options
        if (array_key_exists('error', $options) && !empty($options['error'])) {
            $errors = is_array($options['error']) ?  $options['error'] : [$options['error']];

            $numberOfErrors = count($errors);
            $errorGuids = array();

            // Set has_error for aria-invalid use
            $options['has_error'] = true;

            // Build guids for errors
            for ($i = 0; $i < $numberOfErrors; $i++) {
                $errorGuids[] = 'guid-' . rand();
            }

            $options['error_ids'] = $errorGuids;
        }

        // Check if errors are present in options
        if (array_key_exists('help', $options) and !empty($options['help']) ) {
            $options['help_id'] = 'guid-' . rand();
        }

        return $options;
    }
}


text:
package org.wso2.carbon.automation.extensions.servers.jmsserver.client;

import org.wso2.carbon.automation.extensions.servers.jmsserver.controller.config.JMSBrokerConfiguration;

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

public class JMSQueueMessageConsumer {
    private Connection connection = null;
    private Session session = null;
    private QueueConnectionFactory connectionFactory = null;
    private Destination destination = null;
    private MessageConsumer consumer = null;

    public JMSQueueMessageConsumer(JMSBrokerConfiguration brokerConfiguration)
            throws NamingException {
        // Create a ConnectionFactory
        Properties props = new Properties();
        props.setProperty(Context.INITIAL_CONTEXT_FACTORY, brokerConfiguration.
                getInitialNamingFactory());
        if (brokerConfiguration.getProviderURL().startsWith("amqp://")) {
            //setting property for Qpid running on WSO2 MB
            props.put("connectionfactory.QueueConnectionFactory",
                    brokerConfiguration.getProviderURL());
        } else {
            //setting property for ActiveMQ
            props.setProperty(Context.PROVIDER_URL, brokerConfiguration.getProviderURL());
        }
        Context ctx = new InitialContext(props);
        connectionFactory = (QueueConnectionFactory) ctx.lookup("QueueConnectionFactory");
    }

    /**
     * This will establish  the connection with the given Queue. T
     * his must be called before calling popMessage() to get messages
     *
     * @param queueName Queue name trying to consume
     * @throws JMSException
     * @throws javax.naming.NamingException
     */
    public void connect(String queueName) throws JMSException, NamingException {
        // Create a Connection
        connection = connectionFactory.createConnection();
        connection.start();
        // Create a Session
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // Create a MessageConsumer from the Session to the Topic or Queue
        destination = session.createQueue(queueName);
        consumer = session.createConsumer(destination);
    }

    /**
     * This will disconnect  the connection with the given Queue.
     * This must be called after consuming the messages to release
     * the connection
     */
    public void disconnect() {
        if (consumer != null) {
            try {
                consumer.close();
            } catch (JMSException e) {
                //ignore
            }
        }
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
                //ignore
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                //ignore
            }
        }
    }

    /**
     * this will get the first message from the Queue and dequeue the message from the queue
     *
     * @return the message text
     * @throws Exception
     */
    public String popMessage() throws Exception {
        if (consumer == null) {
            throw new Exception("No Consumer with Queue. Please connect");
        }
        Message message = consumer.receive(10000);
        if (message != null) {
            if (message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                return textMessage.getText();
            } else {
                throw new Exception("Test Framework Exception. Message Type is not a TextMessage");
            }
        } else {
            return null;
        }
    }

    /**
     * @param clzz
     * @param <T>
     * @return
     * @throws Exception
     */
    public <T> T popMessage(Class<T> clzz) throws Exception {
        if (consumer == null) {
            throw new Exception("No Consumer with Queue. Please connect");
        }
        Message message = consumer.receive(10000);
        if (message != null) {
            if (clzz.isInstance(message)) {
                return clzz.cast(message);
            } else {
                throw new Exception("Test Framework Exception. Unexpected Message Type to cast");
            }
        } else {
            return null;
        }
    }

    /**
     * this will get the first message from the Queue and dequeue the message from the queue
     *
     * @return JMS Message object
     * @throws Exception
     */
    public Message popRawMessage() throws Exception {
        if (consumer == null) {
            throw new Exception("No Consumer with Queue. Please connect");
        }
        return consumer.receive(10000);
    }

    /**
     * Returns all the messages in the Queue and dequeue messages from the queue
     *
     * @return messages list
     * @throws Exception
     */
    public List<String> getMessages() throws Exception {
        if (session == null) {
            throw new Exception("No Connection with Queue. Please connect");
        }
        QueueBrowser browser;
        List<String> list = new ArrayList<String>();
        browser = session.createBrowser((Queue) destination);
        Enumeration enu = browser.getEnumeration();
        while (enu.hasMoreElements()) {
            TextMessage message = (TextMessage) enu.nextElement();
            list.add(message.getText());
        }
        browser.close();
        return list;
    }
}