text:
"""
SECURITY ENDPOINTS CHECK
Add auth checks called /checklogged and /testadmin
"""

import abc
import jwt
import hmac
import hashlib
import base64
import pytz
import socket

from rapydo.utils.uuid import getUUID
from datetime import datetime, timedelta
from flask import current_app, request
from rapydo.services.detect import Detector
from rapydo.confs import PRODUCTION
from rapydo.utils.globals import mem
from rapydo.utils import htmlcodes as hcodes
from rapydo.utils.logs import get_logger

log = get_logger(__name__)

class BaseAuthentication(metaclass=abc.ABCMeta):

    """
    An almost abstract class with methods
    to be implemented with a new service
    that aims to store credentials of users and roles.
    """

    ##########################
    # This string will be replaced with a proper secret file
    JWT_SECRET = 'top secret!'
    JWT_ALGO = 'HS256'
    # TO FIX: already defined in auth.py HTTPAUTH_DEFAULT_SCHEME
    token_type = 'Bearer'

    ##########################
    _oauth2 = {}

    longTTL = 2592000     # 1 month in seconds
    shortTTL = 604800     # 1 week in seconds

    def __init__(self):
        # TODO: myinit is a class method for unittest could it be fixed?
        self.myinit()
        # Create variables to be fulfilled by the authentication decorator
        self._token = None
        self._user = None

    @classmethod
    def myinit(cls):
        """
        Note: converted as a classmethod to use inside unittests
        # TODO: check if still necessary
        """

        credentials = mem.customizer._configurations \
            .get('variables', {}) \
            .get('python', {}) \
            .get('backend', {}) \
            .get('credentials', {})

        cls.default_user = credentials.get('username', None)
        cls.default_password = credentials.get('password', None)
        if cls.default_user is None or cls.default_password is None:
            raise AttributeError("Default credentials unavailable!")

        roles = credentials.get('roles', {})
        cls.default_role = roles.get('default')
        cls.role_admin = roles.get('admin')
        cls.default_roles = [
            roles.get('user'),
            roles.get('internal'),
            cls.role_admin
        ]
        if cls.default_role is None or None in cls.default_roles:
            raise AttributeError("Default roles are not available!")

    # @abc.abstractmethod
    # def __init__(self, services=None):
    #     """
    #     Make sure you can create an instance/connection,
    #     or reuse one service from `server.py` operations.
    #     """
    #     return

    def make_login(self, username, password):
        """ The method which will check if credentials are good to go """

        try:
            user = self.get_user_object(username=username)
        except BaseException as e:
            log.error("Broken auth backend:\n[%s] %s" % (type(e), e))
            log.critical("Please reinitialize backend tables")
            from rapydo.exceptions import RestApiException
            raise RestApiException(
                "Server authentication misconfiguration",
                status_code=hcodes.HTTP_SERVER_ERROR
            )

        if user is None:
            return None, None

        try:
            # Check if Oauth2 is enabled
            if user.authmethod != 'credentials':
                return None, None
        except BaseException:
            # Missing authmethod as requested for authentication
            log.critical("Current authentication db models are broken!")
            return None, None

        if self.check_passwords(user.password, password):
            return self.create_token(self.fill_payload(user))

        return None, None

    # ########################
    # # Configure Secret Key #
    # ########################
    def import_secret(self, abs_filename):
        """
        Configure the JWT_SECRET from a file

        If the file does not exist, print instructions
        to create it from a shell with a random key
        and continues with default key
        """

        try:
            self.JWT_SECRET = open(abs_filename, 'rb').read()
        except IOError:
            log.warning("Jwt secret file %s not found, using default "
                        % abs_filename)
            log.info("To create your own secret file:\n" +
                     "head -c 24 /dev/urandom > %s" % abs_filename)

        return self.JWT_SECRET

    def set_oauth2_services(self, services):
        self._oauth2 = services

    # #####################
    # # Password handling #
    # #####################
    @staticmethod
    def encode_string(string):
        """ Encodes a string to bytes, if it isn't already. """
        if isinstance(string, str):
            string = string.encode('utf-8')
        return string

    @staticmethod
    def hash_password(password):
        """ Original source:
        # https://github.com/mattupstate/flask-security
        #    /blob/develop/flask_security/utils.py#L110
        """

        salt = "Unknown"

        h = hmac.new(
            BaseAuthentication.encode_string(salt),
            BaseAuthentication.encode_string(password),
            hashlib.sha512)
        return base64.b64encode(h.digest()).decode('ascii')

    @staticmethod
    def check_passwords(hashed_password, password):
        proposed_password = BaseAuthentication.hash_password(password)
        return hashed_password == proposed_password

    # ########################
    # # Retrieve information #
    # ########################

    def get_user(self):
        """
            Current user, obtained by the authentication decorator
            inside the same Request (which is the same object instance)
        """
        return self._user

    def get_token(self):
        """
            Current token obtained by the authentication decorator
        """
        return self._token

    @abc.abstractmethod
    def get_user_object(self, username=None, payload=None):
        """
        How to retrieve the user from the current service,
        based on the unique username given, or from the content of the token
        """
        return

    @abc.abstractmethod
    def get_tokens(self, user=None, token_jti=None):
        """
            Return the list of all active tokens
        """
        return

    @staticmethod
    def get_host_info():

        ###############
        # Note: timeout do not work on dns lookup...
        # also read:
        # http://depier.re/attempts_to_speed_up_gethostbyaddr/

        # # if getting slow when network is unreachable
        # timer = 1
        # if hasattr(socket, 'setdefaulttimeout'):
        #     socket.setdefaulttimeout(timer)
        # # socket.socket.settimeout(timer)

        ###############
        hostname = ""

        if 'X-Forwarded-For' in request.headers:
            forwarded_ips = request.headers['X-Forwarded-For']
            ip = current_app.wsgi_app.get_remote_addr([forwarded_ips])
        else:
            ip = request.remote_addr
            if PRODUCTION:
                log.warning(
                    "Server in production X-Forwarded-For header is missing")

        if current_app.config['TESTING'] and ip is None:
            pass
        elif PRODUCTION:
            try:
                # note: this will return the ip if hostname is not available
                hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip)
            except Exception as e:
                log.warning(
                    "Error solving '%s': '%s'" % (ip, e))
        return ip, hostname

    # ###################
    # # Tokens handling #
    # ###################
    def create_token(self, payload):
        """ Generate a byte token with JWT library to encrypt the payload """
        self._user = self.get_user_object(payload=payload)
        encode = jwt.encode(
            payload, self.JWT_SECRET, algorithm=self.JWT_ALGO).decode('ascii')

        return encode, payload['jti']

    # TO FIX: this method is not used
    def create_temporary_token(self, user):
        # expiration = timedelta(seconds=300)
        expiration = timedelta(seconds=10)
        payload = self.fill_payload(user, expiration=expiration)
        return self.create_token(payload)

    @abc.abstractmethod
    def verify_token_custom(self, jti, user, payload):
        """
            This method MUST be implemented by specific Authentication Methods
            to add more specific validation contraints
        """
        return

    @abc.abstractmethod
    def refresh_token(self, jti):
        """
            Verify shortTTL to refresh token if not expired
            Invalidate token otherwise
        """
        return

    def unpack_token(self, token):

        payload = None
        try:
            payload = jwt.decode(
                token, self.JWT_SECRET, algorithms=[self.JWT_ALGO])
        # now > exp
        except jwt.exceptions.ExpiredSignatureError as e:
            # should this token be invalidated into the DB?
            log.warning("Unable to decode JWT token. %s" % e)
        # now < nbf
        except jwt.exceptions.ImmatureSignatureError as e:
            log.warning("Unable to decode JWT token. %s" % e)
        except Exception as e:
            log.warning("Unable to decode JWT token. %s" % e)

        return payload

    def verify_token(self, token):

        # Force token cleaning
        payload = {}
        self._user = None

        if token is None:
            return False

        # Decode the current token
        tmp_payload = self.unpack_token(token)
        if tmp_payload is None:
            return False
        else:
            payload = tmp_payload

        # Get the user from payload
        self._user = self.get_user_object(payload=payload)
        if self._user is None:
            return False

        if not self.verify_token_custom(
           user=self._user,
           jti=payload['jti'], payload=payload):
            return False
        # e.g. for graph: verify the (token <- user) link

        if not self.refresh_token(payload['jti']):
            return False

        logfunc = log.verbose
        if current_app.config['TESTING']:
            logfunc = log.very_verbose
        logfunc("User authorized")

        self._token = token
        return True

    def save_token(self, user, token, jti):
        log.debug("Token is not saved in base authentication")

    @abc.abstractmethod
    def invalidate_all_tokens(self, user=None):
        """
            With this method all token emitted for this user must be
            invalidated (no longer valid starting from now)
        """
        return

    @abc.abstractmethod
    def invalidate_token(self, token, user=None):
        """
            With this method the specified token must be invalidated
            as expected after a user logout
        """
        return

# TO FIX payload should be some basic part + custom payload from the developer
    def fill_custom_payload(self, userobj, payload):
        """
            This method can be implemented by specific Authentication Methods
            to add more specific payload content
        """
        return payload

    def fill_payload(self, userobj, expiration=None):
        """ Informations to store inside the JWT token,
        starting from the user obtained from the current service

        Claim attributes listed here:
        http://blog.apcelent.com/json-web-token-tutorial-example-python.html

        TTL is measured in seconds
        """

        if expiration is None:
            expiration = timedelta(seconds=self.longTTL)

        payload = {
            'user_id': userobj.uuid,
            'jti': getUUID()
        }

        short_jwt = \
            Detector.get_global_var('AUTH_FULL_JWT_PAYLOAD', '') \
            .lower() == 'false'

        if not short_jwt:
            now = datetime.now(pytz.utc)
            nbf = now   # you can add a timedelta
            exp = now + expiration
            payload['iat'] = now
            payload['nbf'] = nbf
            payload['exp'] = exp

        return self.fill_custom_payload(userobj, payload)

    # ##################
    # # Roles handling #
    # ##################
    def verify_roles(self, roles, warnings=True):

        current_roles = self.get_roles_from_user()
        for role in roles:
            if role not in current_roles:
                if warnings:
                    log.warning("Auth role '%s' missing for request" % role)
                return False
        return True

    def verify_admin(self):
        """ Check if current user has administration role """
        return self.verify_roles([self.role_admin], warnings=False)

    @abc.abstractmethod
    def get_roles_from_user(self, userobj=None):
        """
        How to retrieve the role of a user from the current service,
        based on a user object.
        If not provided, uses the current user obj stored in self._user.
        """
        return

    # #################
    # # Database init #
    # #################
    def avoid_defaults(self):
        """
        Check in production if using the default user...
        """

        user = self.get_user_object(username=self.default_user)
        if user is not None and user.email == self.default_user:
            if user.password == self.hash_password(self.default_password):
                return True
        return False

    @abc.abstractmethod
    def init_users_and_roles(self):
        """
        Create roles and a user if no one exists.
        A possible algorithm:

        if not exist_one_role():
            for role in self.DEFAULT_ROLES:
                create_role(role)
        if not exist_one_user():
            create_user(
                email=self.DEFAULT_USER,
                name="Whatever", surname="YouLike",
                name_surname="Whatever#_#YouLike",
                password=self.DEFAULT_PASSWORD,
                roles=DEFAULT_ROLES)
        """
        return

    # ################
    # # Create Users #
    # ################
    # @abc.abstractmethod
    def create_user(self, userdata, roles=[]):
        """
        A method to create a new user following some standards.
        - The user should be at least associated to the default (basic) role
        - More to come
        """
        return

    @abc.abstractmethod
    def store_oauth2_user(self, current_user, token):
        """
        Allow external accounts (oauth2 credentials)
        to be connected to internal local user.

        (requires an ExternalAccounts model defined for current service)
        """
        return ('internal_user', 'external_user')

    @abc.abstractmethod
    def store_proxy_cert(self, external_user, proxy):
        """ Save the proxy certificate name into oauth2 account """
        return

    # ###########################
    # # Login attempts handling #
    # ###########################

    def register_failed_login(self, username):
        log.critical("auth.register_failed_login: not implemented")
        return True

    def get_failed_login(self, username):
        log.critical("auth.get_failed_login: not implemented")
        return 0


text:
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"regexp"
	"time"

	"github.com/mh-cbon/emd/cli"
	"github.com/mh-cbon/emd/deprecated"
	"github.com/mh-cbon/emd/emd"
	gostd "github.com/mh-cbon/emd/go"
	gononstd "github.com/mh-cbon/emd/go-nonstd"
	"github.com/mh-cbon/emd/provider"
	"github.com/mh-cbon/emd/std"
)

// VERSION defines the running build id.
var VERSION = "0.0.0"

var program = cli.NewProgram("emd", VERSION)

var verbose bool

func logMsg(f string, args ...interface{}) {
	if verbose {
		log.Printf(f+"\n", args...)
	}
}

func main() {
	program.Bind()
	if err := program.Run(os.Args); err != nil {
		log.Println(err)
		os.Exit(1)
	}
}

// gen sub command
type gencommand struct {
	*cli.Command
	in        string
	out       string
	data      string
	help      bool
	shortHelp bool
}

// init sub command
type initcommand struct {
	*cli.Command
	help      bool
	shortHelp bool
	out       string
	force     bool
}

func init() {
	gen := &gencommand{Command: cli.NewCommand("gen", "Process an emd file.", Generate)}
	gen.Set.StringVar(&gen.in, "in", "", "Input src file")
	gen.Set.StringVar(&gen.out, "out", "-", "Output destination, defaults to stdout")
	gen.Set.StringVar(&gen.data, "data", "", "JSON map of data")
	gen.Set.BoolVar(&gen.help, "help", false, "Show help")
	gen.Set.BoolVar(&gen.shortHelp, "h", false, "Show help")
	program.Add(gen)

	ini := &initcommand{Command: cli.NewCommand("init", "Init a basic emd file.", InitFile)}
	ini.Set.BoolVar(&ini.help, "help", false, "Show help")
	ini.Set.BoolVar(&ini.shortHelp, "h", false, "Show help")
	ini.Set.BoolVar(&ini.force, "force", false, "Force write")
	ini.Set.StringVar(&ini.out, "out", "README.e.md", "Out file")
	program.Add(ini)

	verbose = os.Getenv("VERBOSE") != ""
}

// Generate is the cli command implementation of gen.
func Generate(s cli.Commander) error {

	cmd, ok := s.(*gencommand)
	if ok == false {
		return fmt.Errorf("Invalid command type %T", s)
	}

	if cmd.help || cmd.shortHelp {
		return program.ShowCmdUsage(cmd)
	}

	out, err := getStdout(cmd.out)
	if err != nil {
		return err
	}
	if x, ok := out.(io.Closer); ok {
		defer x.Close()
	}

	projectPath, err := getProjectPath()
	if err != nil {
		return err
	}
	logMsg("projectPath %q", projectPath)

	plugins := getPlugins()
	data, err := getData(projectPath)
	if err != nil {
		return err
	}

	gen := emd.NewGenerator()

	gen.SetDataMap(data)

	if cmd.in != "" {
		if err := gen.AddFileTemplate(cmd.in); err != nil {
			return err
		}
	} else {
		b := tryReadOsStdin()
		if b != nil && b.Len() > 0 {
			gen.AddTemplate(b.String())

		} else {
			if s, err := os.Stat("README.e.md"); !os.IsNotExist(err) && s.IsDir() == false {
				err := gen.AddFileTemplate("README.e.md")
				if err != nil {
					return err
				}
			} else {
				gen.AddTemplate(defTemplate)
			}
		}
	}

	for name, plugin := range plugins {
		if err := plugin(gen); err != nil {
			return fmt.Errorf("Failed to register %v package: %v", name, err)
		}
	}

	if cmd.data != "" {
		jData := map[string]interface{}{}
		if err := json.Unmarshal([]byte(cmd.data), &jData); err != nil {
			return fmt.Errorf("Cannot decode JSON data string: %v", err)
		}
		gen.SetDataMap(jData)
	}

	if err := gen.Execute(out); err != nil {
		return fmt.Errorf("Generator failed: %v", err)
	}

	return nil
}

func tryReadOsStdin() *bytes.Buffer {
	copied := make(chan bool)
	timedout := make(chan bool)
	var ret bytes.Buffer
	go func() {
		io.Copy(&ret, os.Stdin)
		copied <- true
	}()
	go func() {
		<-time.After(time.Millisecond * 10)
		timedout <- ret.Len() == 0
	}()
	select {
	case empty := <-timedout:
		if empty {
			return nil
		}
		<-copied
	case <-copied:
	}
	return &ret
}

func getProjectPath() (string, error) {
	originalCwd, err := os.Getwd()
	if err != nil {
		return "", err
	}
	logMsg("cwd %q", originalCwd)

	// regular go package
	{
		projectPath, err := matchProjectPath(originalCwd)
		if err == nil {
			return projectPath, nil
		}
	}

	// symlinked go package
	{
		cwd, err := filepath.EvalSymlinks(originalCwd)
		if err == nil {
			projectPath, err := matchProjectPath(cwd)
			if err == nil {
				return projectPath, nil
			}
		}
	}

	// all other cases
	return originalCwd, nil
}

var re = regexp.MustCompile("(src/[^/]+[.](com|org|net)/.+)")

func matchProjectPath(p string) (string, error) {
	res := re.FindAllString(p, -1)
	if len(res) > 0 {
		return res[0][3:], nil
	}
	return "", fmt.Errorf("Invalid working directory %q", p)
}

func getData(cwd string) (map[string]interface{}, error) {
	p := provider.Default(cwd)
	return map[string]interface{}{
		"Name":         p.GetProjectName(),
		"User":         p.GetUserName(),
		"ProviderURL":  p.GetProviderURL(),
		"ProviderName": p.GetProviderID(),
		"URL":          p.GetURL(),
		"ProjectURL":   p.GetProjectURL(),
		"Branch":       "master",
	}, nil
}

func getPlugins() map[string]func(*emd.Generator) error {
	return map[string]func(*emd.Generator) error{
		"std":        std.Register,
		"gostd":      gostd.Register,
		"gononstd":   gononstd.Register,
		"deprecated": deprecated.Register,
	}
}

func getStdout(out string) (io.Writer, error) {
	ret := os.Stdout

	if out != "-" {
		f, err := os.Create(out)
		if err != nil {
			f, err = os.Open(out)
			if err != nil {
				return nil, fmt.Errorf("Cannot open out destination: %v", err)
			}
		}
		ret = f
	}
	return ret, nil
}

// InitFile creates a basic emd file if none exists.
func InitFile(s cli.Commander) error {

	cmd, ok := s.(*initcommand)
	if ok == false {
		return fmt.Errorf("Invalid command type %T", s)
	}

	if cmd.help || cmd.shortHelp {
		return program.ShowCmdUsage(cmd)
	}

	out := cmd.out
	if cmd.out == "" {
		out = "README.e.md"
	}
	if _, err := os.Stat(out); !cmd.force && !os.IsNotExist(err) {
		return fmt.Errorf("File exists at %q", out)
	}
	return ioutil.WriteFile(out, []byte(defTemplate), os.ModePerm)
}

var defTemplate = `# {{.Name}}

{{template "badge/goreport" .}} {{template "badge/godoc" .}}

{{pkgdoc}}

# {{toc 5}}

# Install

{{template "gh/releases" .}}

#### go
{{template "go/install" .}}
`

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net.Mail;

public partial class Main_PasswordRecovery : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

}


text:
<link rel="stylesheet" type="text/css" href="style.css">

Matrix analysieren

Analysieren sie die Matrix mit Hilfe verschiedener Visualisierungen.
Mit einem rechtsklick auf eines der Diagramme können Sie weitere Optionen aufrufen und so beispielsweise das Diagramm als Bild abspeichern.
Mit der linken Maustaste können Sie einen Bereich aufziehen und den entsprechenden Bereich vergrössern.

Gewisse Visualisierungen stehen nur für Datenmengen mit bis zu 500 Elementen zur Verfügung, da ansonsten die Berechnungen zu lange dauern.

Histogramm

Die zeigt die Häufigkeitsverteilung aller berechneten Distanzen.

Einzelnes Histogramm

Mit dem

Multidimensionale Skalierung


text:
RailsPortal::Application.configure do
  # Settings specified here will take precedence over those in config/application.rb

  # The production environment is meant for finished, "live" apps.
  # Code is not reloaded between requests
  config.cache_classes = true

  # Eager loads all registered config.eager_load_namespaces. This includes your application, engines, Rails frameworks, and any other registered namespace.
  config.eager_load = true

  # this will fall back to autoloading to files outside the app folder
  config.enable_dependency_loading = true

  # Full error reports are disabled and caching is turned on
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true

  # Specifies the header that your server uses for sending files
  # config.action_dispatch.x_sendfile_header = "X-Sendfile"

  # For nginx:
  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'

  # If you have no front-end server that supports something like X-Sendfile,
  # just comment this out and Rails will serve the files

  # See info messages and above in the log (default is :debug in Rails 5)
  config.log_level = :info

  # Use a different logger for distributed setups
  # config.logger = SyslogLogger.new
  if BoolENV['RAILS_STDOUT_LOGGING']
    config.logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
  end

  # Use a different cache store in production
  # config.cache_store = :mem_cache_store

  # Disable Rails's static asset server
  # In production, Apache or nginx will already do this
  config.serve_static_assets = true

  # Enable serving of images, stylesheets, and javascripts from an asset server
  # config.action_controller.asset_host = "http://assets.example.com"

  # Disable delivery errors, bad email addresses will be ignored
  # config.action_mailer.raise_delivery_errors = false

  # Enable threaded mode
  # config.threadsafe!

  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation can not be found)
  config.i18n.default_locale = 'en'
  config.i18n.fallbacks = true

  # Send deprecation notices to registered listeners
  config.active_support.deprecation = :notify

  #### Asset Pipeline:  #####
  # Production servers may not compile missing assets. (missed by precompile)
  # Requires asset helper gems in production bundle
  config.assets.compile = true

  # Minify/uglify/compress assets from the pipeline
  config.assets.js_compressor = Uglifier.new(harmony: true)
  config.assets.css_compressor = :yui

  # Generate digests for assets' URLs.
  config.assets.digest = true
  config.action_mailer.default_url_options = {:protocol => APP_CONFIG[:protocol], :host => APP_CONFIG[:host] }
  config.action_mailer.asset_host = APP_CONFIG[:protocol] + '://' + APP_CONFIG[:host]

  # START OF RAILS 5 OPTIONS
  #
  # The following are new Rails 5 config options with their default option set
  # We may want to change these options in the future.  More info here:
  #
  # https://guides.rubyonrails.org/upgrading_ruby_on_rails.html#new-framework-defaults
  #
  config.active_record.belongs_to_required_by_default = false
  config.action_controller.per_form_csrf_tokens = false
  config.action_controller.forgery_protection_origin_check = false
  config.action_mailer.perform_caching = false
  config.ssl_options = { hsts: { subdomains: false } }
  # The following are commented out due to different reasons
  # 1. We don't want to rename the queue
  # config.action_mailer.deliver_later_queue_name = :new_queue_name
  # 2. This only is valid for PostgreSQL
  # config.active_record.dump_schemas = :all
  # 3. Commented out because this needs Ruby 2.4 to work
  # ActiveSupport.to_time_preserves_timezone = false
  #
  # END OF RAILS 5 OPTIONS

  # Rails 5 defaults to disable submit
  config.action_view.automatically_disable_submit_tag = false

end


text:
public class RearrangementTest21
{
    int v, u;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycologia 45: 895 (1953)

#### Original name
Galerina camarinoides A.H. Sm.

### Remarks
null


text:
var Baobab = require('baobab');
var LocalStorage = require('local-storage');

var StateTree = new Baobab({
  loggedIn: {
    user: null
  }
});

StateTree.commit();

/**
 * Cursor is initialized with data from local storage (if any) and future updates are saved back.
 */
function cacheInLocalStorage(cursor, attachListener) {
  var c = StateTree.select(cursor);
  if (!Array.isArray(cursor)) cursor = [cursor];
  var key = "state-tree:" + cursor.join('/');

  var object;
  try {
    object = LocalStorage.get(key);
  } catch (error) {
    console.error("Bad values stored in local storage for ", cursor, error);
  }
  if (object) {
    if (cursor[0] != "views") object._fromCache = true;
    c.set(object);
  }

  c.on('update', () => {
    try {
      LocalStorage.set(key, c.get())
    } catch (error) {
      console.error("Problem setting local storage for", cursor, error);
    }
  });

  // if this is true attach a listener on local storage so that these changes will be shared across tabs
  if (attachListener) {
    LocalStorage.on(key, (value) => {
      c.set(value);
    });
  }
}

cacheInLocalStorage(['loggedIn', 'user'], true);

module.exports = StateTree;


text:
namespace Americommerce4Net.Clients
{
    public class ClientGiftCertificates : BaseNestedClient
    {
        protected internal ClientGiftCertificates(IRestEngine restEngine)
            : base(restEngine) {
            base.ResourceName = "gift_certificates";
        }
    }
}


text:
import {mapObjIndexed} from 'ramda';

function setDataIdFromKey(data){
  return mapObjIndexed(
    (item, id)=>{
      return {...item, id};
    }
  , data);
}

export function eventsNormalizr(data){
  return setDataIdFromKey(data);
}


text:
using ApacheOrcDotNet.Compression;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace ApacheOrcDotNet.Infrastructure
{
    public static class OrcCompressedBufferFactoryExtensions
    {
		public static void SerializeAndCompressTo(this OrcCompressedBufferFactory bufferFactory, Stream outputStream, object instance, out long length)
		{
			var buffer = bufferFactory.CreateBuffer();
			StaticProtoBuf.Serializer.Serialize(buffer, instance);
			buffer.CopyTo(outputStream);
			length = buffer.Length;
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="ca.ualberta.trinkettrader.Inventory.Trinket.AddOrEditTrinketActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:weightSum="60">

        <EditText
            android:id="@+id/name_text"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="26"
            android:hint="@string/activity_add_or_edit_trinket_name_hint"/>

        <EditText
            android:id="@+id/quantity_text"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="17"
            android:hint="@string/activity_add_or_edit_trinket_quantity_hint"/>

        <CheckBox
            android:id="@+id/accessibility_checkbox"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="17"
            android:checked="true"
            android:text="@string/activity_add_or_edit_trinket_accessibility_checkbox"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:weightSum="60">

        <EditText
            android:id="@+id/description_text"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="60"
            android:hint="@string/activity_add_or_edit_trinket_description_hint"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:weightSum="60">

        <EditText
            android:id="@+id/latitude"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="30"
            android:ems="10"
            android:hint="@string/activity_add_or_edit_trinket_latitude"
            android:inputType="numberDecimal"/>

        <EditText
            android:id="@+id/longitude"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="30"
            android:ems="10"
            android:hint="@string/activity_add_or_edit_trinket_longitude"
            android:inputType="numberDecimal"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:weightSum="60">

        <Spinner
            android:id="@+id/category_spinner"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="30"
            android:entries="@array/spinner_categories"
            android:prompt="@string/activity_add_or_edit_trinket_spinner_categories_prompt"
            android:spinnerMode="dropdown"/>

        <Spinner
            android:id="@+id/quality_spinner"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="30"
            android:entries="@array/spinner_qualities"
            android:prompt="@string/activity_add_or_edit_trinket_spinner_qualities_prompt"
            android:spinnerMode="dropdown"/>
    </LinearLayout>

    <LinearLayout
        style="?android:buttonBarStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:weightSum="60">

        <Button
            android:id="@+id/picture_library_button"
            style="?android:buttonBarButtonStyle"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:layout_weight="20"
            android:onClick="pictureLibraryClick"
            android:text="@string/activity_add_or_edit_trinket_picture_library_button_text"/>

        <Button
            android:id="@+id/take_picture_button"
            style="?android:buttonBarButtonStyle"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:layout_weight="20"
            android:onClick="takePictureClick"
            android:text="@string/activity_add_or_edit_trinket_take_picture_button_text"/>

        <Button
            android:id="@+id/save_button"
            style="?android:buttonBarButtonStyle"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:layout_weight="20"
            android:text="@string/activity_add_or_edit_trinket_save_button_text"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:weightSum="60">

        <!-- Bill Donahue; https://github.com/MeetMe/Android-HorizontalListView; 2015-11-20 -->
        <com.meetme.android.horizontallistview.HorizontalListView
            android:id="@+id/gallery"
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:widget="http://schemas.android.com/apk/res-auto"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="60"
            widget:dividerWidth="10dp"/>
    </LinearLayout>
</LinearLayout>


text:
package org.nd4j.python4j;

import org.bytedeco.cpython.PyObject;
import org.bytedeco.javacpp.Pointer;

import java.util.*;

import static org.bytedeco.cpython.global.python.*;

public class PythonObject {

    static {
        new PythonExecutioner();
    }

    private boolean owned = true;
    private PyObject nativePythonObject;

    public PythonObject(PyObject nativePythonObject, boolean owned) {
        PythonGIL.assertThreadSafe();
        this.nativePythonObject = nativePythonObject;
        this.owned = owned;
        if (owned && nativePythonObject != null) {
            PythonGC.register(this);
        }
    }

    public PythonObject(PyObject nativePythonObject) {
        PythonGIL.assertThreadSafe();
        this.nativePythonObject = nativePythonObject;
        if (nativePythonObject != null) {
            PythonGC.register(this);
        }

    }

    public PyObject getNativePythonObject() {
        return nativePythonObject;
    }

    public String toString() {
        return PythonTypes.STR.toJava(this);

    }

    public boolean isNone() {
        if (nativePythonObject == null || Pointer.isNull(nativePythonObject)) {
            return true;
        }
        try (PythonGC gc = PythonGC.pause()) {
            PythonObject type = Python.type(this);
            boolean ret = Python.type(this).toString().equals("<class 'NoneType'>") && toString().equals("None");
            Py_DecRef(type.nativePythonObject);
            return ret;
        }
    }

    public void del() {
        PythonGIL.assertThreadSafe();
        if (owned && nativePythonObject != null && !PythonGC.isWatching()) {
            Py_DecRef(nativePythonObject);
            nativePythonObject = null;
        }
    }

    public PythonObject callWithArgs(PythonObject args) {
        return callWithArgsAndKwargs(args, null);
    }

    public PythonObject callWithKwargs(PythonObject kwargs) {
        if (!Python.callable(this)) {
            throw new PythonException("Object is not callable: " + toString());
        }
        PyObject tuple = PyTuple_New(0);
        PyObject dict = kwargs.nativePythonObject;
        if (PyObject_IsInstance(dict, new PyObject(PyDict_Type())) != 1) {
            throw new PythonException("Expected kwargs to be dict. Received: " + kwargs.toString());
        }
        PythonObject ret = new PythonObject(PyObject_Call(nativePythonObject, tuple, dict));
        Py_DecRef(tuple);
        return ret;
    }

    public PythonObject callWithArgsAndKwargs(PythonObject args, PythonObject kwargs) {
        PythonGIL.assertThreadSafe();
        PyObject tuple = null;
        boolean ownsTuple = false;
        try {
            if (!Python.callable(this)) {
                throw new PythonException("Object is not callable: " + toString());
            }

            if (PyObject_IsInstance(args.nativePythonObject, new PyObject(PyTuple_Type())) == 1) {
                tuple = args.nativePythonObject;
            } else if (PyObject_IsInstance(args.nativePythonObject, new PyObject(PyList_Type())) == 1) {
                tuple = PyList_AsTuple(args.nativePythonObject);
                ownsTuple = true;
            } else {
                throw new PythonException("Expected args to be tuple or list. Received: " + args.toString());
            }
            if (kwargs != null && PyObject_IsInstance(kwargs.nativePythonObject, new PyObject(PyDict_Type())) != 1) {
                throw new PythonException("Expected kwargs to be dict. Received: " + kwargs.toString());
            }
            return new PythonObject(PyObject_Call(nativePythonObject, tuple, kwargs == null ? null : kwargs.nativePythonObject));
        } finally {
            if (ownsTuple) Py_DecRef(tuple);
        }

    }

    public PythonObject call(Object... args) {
        return callWithArgsAndKwargs(Arrays.asList(args), null);
    }

    public PythonObject callWithArgs(List args) {
        return call(args, null);
    }

    public PythonObject callWithKwargs(Map kwargs) {
        return call(null, kwargs);
    }

    public PythonObject callWithArgsAndKwargs(List args, Map kwargs) {
        PythonGIL.assertThreadSafe();
        try (PythonGC gc = PythonGC.watch()) {
            if (!Python.callable(this)) {
                throw new PythonException("Object is not callable: " + toString());
            }
            PythonObject pyArgs;
            PythonObject pyKwargs;

            if (args == null || args.isEmpty()) {
                pyArgs = new PythonObject(PyTuple_New(0));
            } else {
                PythonObject argsList = PythonTypes.convert(args);
                pyArgs = new PythonObject(PyList_AsTuple(argsList.getNativePythonObject()));
            }
            if (kwargs == null) {
                pyKwargs = null;
            } else {
                pyKwargs = PythonTypes.convert(kwargs);
            }

            PythonObject ret = new PythonObject(
                    PyObject_Call(
                            nativePythonObject,
                            pyArgs.nativePythonObject,
                            pyKwargs == null ? null : pyKwargs.nativePythonObject
                    )
            );

            PythonGC.keep(ret);

            return ret;
        }

    }

    public PythonObject attr(String attrName) {
        PythonGIL.assertThreadSafe();
        return new PythonObject(PyObject_GetAttrString(nativePythonObject, attrName));
    }

    public PythonObject(Object javaObject) {
        PythonGIL.assertThreadSafe();
        if (javaObject instanceof PythonObject) {
            owned = false;
            nativePythonObject = ((PythonObject) javaObject).nativePythonObject;
        } else {
            try (PythonGC gc = PythonGC.pause()) {
                nativePythonObject = PythonTypes.convert(javaObject).getNativePythonObject();
            }
            PythonGC.register(this);
        }

    }

    public int toInt() {
        return PythonTypes.INT.toJava(this).intValue();
    }

    public long toLong() {
        return PythonTypes.INT.toJava(this);
    }

    public float toFloat() {
        return PythonTypes.FLOAT.toJava(this).floatValue();
    }

    public double toDouble() {
        return PythonTypes.FLOAT.toJava(this);
    }

    public boolean toBoolean() {
        return PythonTypes.BOOL.toJava(this);

    }

    public List toList() {
        return PythonTypes.LIST.toJava(this);
    }

    public Map toMap() {
        return PythonTypes.DICT.toJava(this);
    }

    public PythonObject get(int key) {
        PythonGIL.assertThreadSafe();
        return new PythonObject(PyObject_GetItem(nativePythonObject, PyLong_FromLong(key)));
    }

    public PythonObject get(String key) {
        PythonGIL.assertThreadSafe();
        return new PythonObject(PyObject_GetItem(nativePythonObject, PyUnicode_FromString(key)));
    }

    public PythonObject get(PythonObject key) {
        PythonGIL.assertThreadSafe();
        return new PythonObject(PyObject_GetItem(nativePythonObject, key.nativePythonObject));
    }

    public void set(PythonObject key, PythonObject value) {
        PythonGIL.assertThreadSafe();
        PyObject_SetItem(nativePythonObject, key.nativePythonObject, value.nativePythonObject);
    }

    public PythonObject abs(){
        return new PythonObject(PyNumber_Absolute(nativePythonObject));
    }
    public PythonObject add(PythonObject pythonObject){
        return new PythonObject(PyNumber_Add(nativePythonObject, pythonObject.nativePythonObject));
    }
    public PythonObject sub(PythonObject pythonObject){
        return new PythonObject(PyNumber_Subtract(nativePythonObject, pythonObject.nativePythonObject));
    }
    public PythonObject mod(PythonObject pythonObject){
        return new PythonObject(PyNumber_Divmod(nativePythonObject, pythonObject.nativePythonObject));
    }
    public PythonObject mul(PythonObject pythonObject){
        return new PythonObject(PyNumber_Multiply(nativePythonObject, pythonObject.nativePythonObject));
    }
    public PythonObject trueDiv(PythonObject pythonObject){
        return new PythonObject(PyNumber_TrueDivide(nativePythonObject, pythonObject.nativePythonObject));
    }
    public PythonObject floorDiv(PythonObject pythonObject){
        return new PythonObject(PyNumber_FloorDivide(nativePythonObject, pythonObject.nativePythonObject));
    }
    public PythonObject matMul(PythonObject pythonObject){
        return new PythonObject(PyNumber_MatrixMultiply(nativePythonObject, pythonObject.nativePythonObject));
    }

    public void addi(PythonObject pythonObject){
        PyNumber_InPlaceAdd(nativePythonObject, pythonObject.nativePythonObject);
    }
    public void subi(PythonObject pythonObject){
        PyNumber_InPlaceSubtract(nativePythonObject, pythonObject.nativePythonObject);
    }
    public void muli(PythonObject pythonObject){
        PyNumber_InPlaceMultiply(nativePythonObject, pythonObject.nativePythonObject);
    }
    public void trueDivi(PythonObject pythonObject){
        PyNumber_InPlaceTrueDivide(nativePythonObject, pythonObject.nativePythonObject);
    }
    public void floorDivi(PythonObject pythonObject){
        PyNumber_InPlaceFloorDivide(nativePythonObject, pythonObject.nativePythonObject);
    }
    public void matMuli(PythonObject pythonObject){
        PyNumber_InPlaceMatrixMultiply(nativePythonObject, pythonObject.nativePythonObject);
    }
}


text:
@interface TGMoreController : UITableViewController

@end


text:
package org.apache.camel.component.seda;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.ResolveEndpointFailedException;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Test;

public class SedaBlockWhenFullInvalidConfigurationTest extends ContextTestSupport {

    @Override
    public boolean isUseRouteBuilder() {
        return false;
    }

    @Test
    public void testInvalidConfiguration() throws Exception {
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start")
                    .to("seda:foo?blockWhenFull=true&blockWhenFull=true");
            }
        });
        try {
            context.start();
            fail("Should fail");
        } catch (Exception e) {
            ResolveEndpointFailedException refe = assertIsInstanceOf(ResolveEndpointFailedException.class, e.getCause());
            assertEquals("Value [true, true] converted to java.lang.Boolean cannot be null", refe.getCause().getMessage());
        }

    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using MessageVault.Cloud;
using Newtonsoft.Json;

namespace MessageVault.Api {

	public sealed class Client : IClient, IDisposable {
		readonly HttpClient _client;

		public static Func<Stream> StreamFactory = () => new MemoryStream();

		public Client(string url, string username, string password) {
			_client = new HttpClient {
				BaseAddress = new Uri(url)
			};

			SetupBasicAuth(username, password);
		}

		void SetupBasicAuth(string username, string password) {
			var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);
			_client.DefaultRequestHeaders.Authorization =
				new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
		}

		public async Task<PostMessagesResponse> PostMessagesAsync(string stream, ICollection<Message> messages) {

			using (var mem = StreamFactory()) {

				TransferFormat.WriteMessages(messages, mem);

				mem.Seek(0, SeekOrigin.Begin);

				using (var sc = new StreamContent(mem)) {
					var result = await _client.PostAsync("/streams/" + stream, sc);
					result.EnsureSuccessStatusCode();
					var content = await result.Content.ReadAsStringAsync();
					return JsonConvert.DeserializeObject<PostMessagesResponse>(content);
				}
			}
		}

		public async Task<MessageReader> GetMessageReaderAsync(string stream) {
			var result = await _client.GetAsync("/streams/" + stream);
			result.EnsureSuccessStatusCode();
			var content = await result.Content.ReadAsStringAsync();
			var response = JsonConvert.DeserializeObject<GetStreamResponse>(content);

			return CloudSetup.GetReader(response.Signature);
		}

		public void Dispose() {
			_client.Dispose();
		}
	}
}


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

namespace P03_FootballBetting.Data.Models
{
    public class Country
    {
        public int CountryId { get; set; }

        public string Name { get; set; }

        public ICollection<Town> Towns { get; set; }
    }
}


text:
#import "DDMessageEntity.h"
#import "DDUserModule.h"
#import "EmotionsModule.h"
#import "ChattingModule.h"
#import "DDMessageModule.h"
#import "RuntimeStatus.h"
@interface DDMessageEntity(private)

- (NSString*)getNewMessageContentFromContent:(NSString*)content;

@end
@implementation DDMessageEntity

- (DDMessageEntity*)initWithMsgID:(NSUInteger)ID msgType:(DDMessageType)msgType msgTime:(NSUInteger)msgTime sessionID:(NSString*)sessionID senderID:(NSString*)senderID msgContent:(NSString*)msgContent toUserID:(NSString*)toUserID
{
    self = [super init];
    if (self)
    {
        if (msgType == DDMessageTypeImage)
        {
            NSLog(@"asd");
        }
        _msgID = ID;
        _msgType = msgType;
        _msgTime = msgTime;
        _sessionId = [sessionID copy];
        _senderId = [senderID copy];
        _msgContent = [self getNewMessageContentFromContent:msgContent];
        _toUserID = [toUserID copy];
        _info = [[NSMutableDictionary alloc] init];
    }
    return self;
}
- (id)copyWithZone:(NSZone *)zone
{
    DDMessageEntity *ddmentity =[[[self class] allocWithZone:zone] initWithMsgID:_msgID msgType:_msgType msgTime:_msgTime sessionID:_sessionId senderID:_senderId msgContent:_msgContent toUserID:_toUserID];
    return ddmentity;
}

#pragma mark -
#pragma mark - privateAPI
- (NSString*)getNewMessageContentFromContent:(NSString*)content
{

    NSMutableString *msgContent = [NSMutableString stringWithString:content];
    NSMutableString *resultContent = [NSMutableString string];
    NSRange startRange;
    NSDictionary* emotionDic = [EmotionsModule shareInstance].emotionUnicodeDic;
    while ((startRange = [msgContent rangeOfString:@"["]).location != NSNotFound) {
        if (startRange.location > 0)
        {
            NSString *str = [msgContent substringWithRange:NSMakeRange(0, startRange.location)];
            DDLog(@"[前文本内容:%@",str);
            [msgContent deleteCharactersInRange:NSMakeRange(0, startRange.location)];
            startRange.location=0;
            [resultContent appendString:str];
        }

        NSRange endRange = [msgContent rangeOfString:@"]"];
        if (endRange.location != NSNotFound) {
            NSRange range;
            range.location = 0;
            range.length = endRange.location + endRange.length;
            NSString *emotionText = [msgContent substringWithRange:range];
            [msgContent deleteCharactersInRange:
             NSMakeRange(0, endRange.location + endRange.length)];

            DDLog(@"类似表情字串:%@",emotionText);
            NSString *emotion = emotionDic[emotionText];
            if (emotion) {
                // 表情
                [resultContent appendString:emotion];
            } else
            {
                [resultContent appendString:emotionText];
            }
        } else {
            DDLog(@"没有[匹配的后缀");
            break;
        }
    }

    if ([msgContent length] > 0)
    {
        [resultContent appendString:msgContent];
    }
    return resultContent;
}
+(DDMessageEntity *)makeMessage:(NSString *)content Module:(ChattingModule *)module MsgType:(DDMessageType )type
{
    NSUInteger msgTime = [[NSDate date] timeIntervalSince1970];
    NSString* senderID = [RuntimeStatus instance].user.userId;
    NSUInteger messageID = [DDMessageModule getMessageID];
    DDMessageEntity* message = [[DDMessageEntity alloc] initWithMsgID:messageID msgType:type msgTime:msgTime sessionID:module.sessionEntity.sessionID senderID:senderID msgContent:content toUserID:module.sessionEntity.sessionID];
    message.state = DDMessageSending;
    message.msgType=type;
    [module addShowMessage:message];
    [module updateSessionUpdateTime:message.msgTime];
    return message;
}
@end


text:
' | Version 1.17.2018
' | Copyright 2018 Esri
' |
' | 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.

Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.IO
Imports ESRI.ArcGIS.Display
Imports ESRI.ArcGIS.Carto
Imports ESRI.ArcGIS.Geodatabase
Imports ESRI.ArcGIS.Editor
Imports ESRI.ArcGIS.Framework
Imports ESRI.ArcGIS.esriSystem
Imports ESRI.ArcGIS.SystemUI
Imports ESRI.ArcGIS.Desktop.AddIns
Imports ESRI.ArcGIS.ADF.CATIDs
Imports ESRI.ArcGIS.ADF.BaseClasses

Imports ESRI.ArcGIS.Geometry

Public Class CostEstimatingExtension
    Inherits ESRI.ArcGIS.Desktop.AddIns.Extension

    Private Shared s_dockWindow As ESRI.ArcGIS.Framework.IDockableWindow
    Private Shared s_extension As CostEstimatingExtension
    Private Shared s_SelectAssetTool As ICommandItem
    Private Shared s_SelectPrj As ICommandItem
    Private Shared s_SelectCostedAsset As ICommandItem

    'Shared Events
    Friend Shared Event ChangeCIPToolStatus(ByVal enable As Boolean)

    Public Sub New()

    End Sub

    ' Overrides

    Protected Overrides Sub OnStartup()
        s_extension = Me

        ' Wire up events
        AddHandler My.ArcMap.Events.NewDocument, AddressOf ArcMap_NewDocument
        AddHandler My.ArcMap.Events.OpenDocument, AddressOf ArcMap_OpenDocument

        Dim pID As New UID

        pID.Value = "esriEditor.Editor"

        My.Globals.Variables.v_Editor = TryCast(My.ArcMap.Application.FindExtensionByCLSID(pID), IEditor2)

        If My.Globals.Variables.v_Editor Is Nothing Then Return

        My.Globals.Variables.v_EditorEvents = TryCast(My.Globals.Variables.v_Editor, Editor)

        pID = Nothing
        'If Me.State = ExtensionState.Enabled Then
        '    Initialize()

        'End If

    End Sub

    Protected Overrides Function OnSetState(ByVal state As ExtensionState) As Boolean
        ' Optionally check for a license here
        Me.State = state
        If state = ExtensionState.Enabled Then
            Initialize()
            initAddin()
        Else
            Uninitialize()
        End If

        Return MyBase.OnSetState(state)
    End Function

    Protected Overrides Function OnGetState() As ExtensionState
        Return Me.State
    End Function

    Protected Overrides Sub OnShutdown()

    End Sub
    ' Privates
    Private Sub initAddin()
        If State = ExtensionState.Enabled Then
            GetCostEstimatingWindow()

            If CheckForCIPLayers() Then
                If My.Globals.Variables.v_CIPWindowsValid = True Then Return

                initCIPLayers()
                CostEstimatingWindow.EnableWindowControls(True)
                CostEstimatingWindow.LoadControlsToDetailForm()
                My.Globals.Variables.v_CIPWindowsValid = True

            Else
                CostEstimatingWindow.EnableWindowControls(False)
                My.Globals.Variables.v_CIPWindowsValid = False

            End If
            CostEstimatingWindow.EnableSavePrj()
        Else

            CostEstimatingWindow.EnableWindowControls(False)
            My.Globals.Variables.v_CIPWindowsValid = False

        End If

    End Sub
    Private Sub Initialize()
        If s_extension Is Nothing Or Me.State <> ExtensionState.Enabled Then
            Return
        End If

        ' Reset event handlers
        Dim avEvent As IActiveViewEvents_Event = TryCast(My.ArcMap.Document.FocusMap, IActiveViewEvents_Event)
        AddHandler avEvent.ItemAdded, AddressOf AvEvent_ItemAdded
        AddHandler avEvent.ItemDeleted, AddressOf AvEvent_ItemDeleted
        'AddHandler avEvent.SelectionChanged, AddressOf UpdateSelCountDockWin
        'AddHandler avEvent.ContentsChanged, AddressOf avEvent_ContentsChanged

        ' If the dockview hasn't been created yet

        If (Not CostEstimatingWindow.Exists) Then
            Return
        End If

        CostEstimatingWindow.ResetControls(True)

        If CheckForCIPLayers() Then
            initCIPLayers()
            CostEstimatingWindow.EnableWindowControls(True)
            RaiseEvent ChangeCIPToolStatus(True)

            CostEstimatingWindow.LoadControlsToDetailForm()

        Else
            CostEstimatingWindow.EnableWindowControls(False)
            RaiseEvent ChangeCIPToolStatus(False)

        End If
        CostEstimatingWindow.EnableSavePrj()
        CostEstimatingWindow.SetEnabled(True)

    End Sub

    Friend Shared Sub raiseEventInExt(ByVal bVal As Boolean)
        RaiseEvent ChangeCIPToolStatus(bVal)

    End Sub

    Friend Shared Function CheckForCIPLayers() As Boolean
        Try
           If My.ArcMap.Document Is Nothing Then Return False
            If My.ArcMap.Document.FocusMap Is Nothing Then Return False
            If My.ArcMap.Document.FocusMap.LayerCount = 0 Then Return False

            If My.Globals.Functions.LayerExist(My.Globals.Constants.c_CIPProjectPointLayName) = False Then Return False
            If My.Globals.Functions.LayerExist(My.Globals.Constants.c_CIPProjectPolygonLayName) = False Then Return False
            If My.Globals.Functions.LayerExist(My.Globals.Constants.c_CIPProjectPolylineLayName) = False Then Return False
            If My.Globals.Functions.LayerExist(My.Globals.Constants.c_CIPProjectLayName) = False Then Return False
            If My.Globals.Functions.LayerExist(My.Globals.Constants.c_CIPOverviewLayName) = False Then Return False
            If My.Globals.Functions.LayerExist(My.Globals.Constants.c_CIPOverviewPointLayName) = False Then Return False
            If My.Globals.Functions.TableExist(My.Globals.Constants.c_CIPDefTableName) = False Then Return False
            If My.Globals.Functions.TableExist(My.Globals.Constants.c_CIPCostTableName) = False Then Return False
            If My.Globals.Functions.TableExist(My.Globals.Constants.c_CIPReplaceTableName) = False Then Return False
            ' If  my.Globals.Functions.TableExist(my.Globals.Constants.c_CIPInvLayName, pMap) = False Then Return False
            Return True

        Catch ex As Exception
            If Not ex.ToString().Contains("COM object") Then

                MsgBox("Error in the Costing Tools - CIPProjectWindow: CheckForCIPLayers" & vbCrLf & ex.ToString())

            End If

        End Try

    End Function
    Friend Shared Function initCIPLayers() As Boolean
        Try

            My.Globals.Variables.v_CIPLayerPoint = TryCast(My.Globals.Functions.FindLayer(My.Globals.Constants.c_CIPProjectPointLayName), IFeatureLayer)
            My.Globals.Variables.v_CIPLayerPolygon = TryCast(My.Globals.Functions.FindLayer(My.Globals.Constants.c_CIPProjectPolygonLayName), IFeatureLayer)
            My.Globals.Variables.v_CIPLayerPolyline = TryCast(My.Globals.Functions.FindLayer(My.Globals.Constants.c_CIPProjectPolylineLayName), IFeatureLayer)
            My.Globals.Variables.v_CIPLayerPrj = TryCast(My.Globals.Functions.FindLayer(My.Globals.Constants.c_CIPProjectLayName), IFeatureLayer)
            My.Globals.Variables.v_CIPLayerOver = TryCast(My.Globals.Functions.FindLayer(My.Globals.Constants.c_CIPOverviewLayName), IFeatureLayer)
            My.Globals.Variables.v_CIPLayerOverPoint = TryCast(My.Globals.Functions.FindLayer(My.Globals.Constants.c_CIPOverviewPointLayName), IFeatureLayer)
            My.Globals.Variables.v_CIPTableDef = TryCast(My.Globals.Functions.FindTable(My.Globals.Constants.c_CIPDefTableName), ITable)
            My.Globals.Variables.v_CIPTableCost = TryCast(My.Globals.Functions.FindTable(My.Globals.Constants.c_CIPCostTableName), ITable)
            My.Globals.Variables.v_CIPTableReplace = TryCast(My.Globals.Functions.FindTable(My.Globals.Constants.c_CIPReplaceTableName), ITable)

            'Dim pConfFiles() As String = My.Globals.Functions.GetConfigFiles
            'If pConfFiles.Length = 0 Then Return False
            My.Globals.Variables.v_CIPReplaceValue = My.Globals.Functions.GetConfigValue("CIPReplacementValue")
            My.Globals.Variables.v_CIPAbandonValue = My.Globals.Functions.GetConfigValue("CIPAbandonValue")
            Return True

        Catch ex As Exception
            MsgBox("Error in the Costing Tools - CIPProjectWindow: initCIPLayers" & vbCrLf & ex.ToString())
            Return False

        End Try

    End Function
    Private Sub Uninitialize()
        If s_extension Is Nothing Then
            Return
        End If

        ' Detach event handlers
        Dim avEvent As IActiveViewEvents_Event = TryCast(My.ArcMap.Document.FocusMap, IActiveViewEvents_Event)
        RemoveHandler avEvent.ItemAdded, AddressOf AvEvent_ItemAdded
        RemoveHandler avEvent.ItemDeleted, AddressOf AvEvent_ItemDeleted
        ' RemoveHandler avEvent.SelectionChanged, AddressOf UpdateSelCountDockWin
        ' RemoveHandler avEvent.ContentsChanged, AddressOf avEvent_ContentsChanged
        avEvent = Nothing

        ' Update UI
        'Dim selCombo As SelectionTargetComboBox = SelectionTargetComboBox.GetSelectionComboBox()
        'If selCombo IsNot Nothing Then
        'selCombo.ClearAll()
        ' End If

        'SelCountDockWin.SetEnabled(False)
        CostEstimatingWindow.SetEnabled(False)
        My.Globals.Variables.v_CIPWindowsValid = False

    End Sub

    ' Event handlers

    Private Sub ArcMap_NewDocument()
        Dim pageLayoutEvent As IActiveViewEvents_Event = TryCast(My.ArcMap.Document.PageLayout, IActiveViewEvents_Event)
        Try
            AddHandler pageLayoutEvent.FocusMapChanged, AddressOf AVEvents_FocusMapChanged
        Catch ex As Exception

        End Try

        '  Initialize()
        initAddin()

    End Sub
    Private Sub ArcMap_OpenDocument()
        Dim pageLayoutEvent As IActiveViewEvents_Event = TryCast(My.ArcMap.Document.PageLayout, IActiveViewEvents_Event)
        AddHandler pageLayoutEvent.FocusMapChanged, AddressOf AVEvents_FocusMapChanged

        Initialize()
        initAddin()

    End Sub

    Private Sub avEvent_ContentsChanged()
        Initialize()
        initAddin()

    End Sub

    Private Sub AvEvent_ItemAdded(ByVal Item As Object)
        Try

            initAddin()

        Catch ex As Exception
            MsgBox("Error in the Costing Tools - CIPProjectWindow: layerAdded" & vbCrLf & ex.ToString())

        End Try

    End Sub
    Private Sub AvEvent_ItemDeleted(ByVal Item As Object)
        Try
            initAddin()
        Catch ex As Exception
            MsgBox("Error in the Costing Tools - CIPProjectWindow: layerAdded" & vbCrLf & ex.ToString())

        End Try

    End Sub
    Private Sub AVEvents_FocusMapChanged()
        initAddin()
    End Sub
    'Private Function onActiveViewChanged() As Boolean
    '    Try
    '        ResetControls(True)
    '        m_actViewEvents = CType(m_pMxDoc.FocusMap, IActiveViewEvents_Event)
    '        If m_actViewEvents Is Nothing Then Return False
    '        If m_pMxDoc.FocusMap Is Nothing Then Return False

    '        AddHandler m_actViewEvents.ItemAdded, AddressOf layerAdded
    '        AddHandler m_actViewEvents.ItemDeleted, AddressOf layerAdded
    '        If CheckForCIPLayers(m_pMxDoc.FocusMap) Then
    '            EnableCIPTools(True)
    '            LoadControlsFromLayers()
    '            EnableSavePrj()
    '        Else
    '            EnableCIPTools(False)
    '            EnableSavePrj()
    '        End If

    '    Catch ex As Exception
    '        MsgBox("Error in the Costing Tools - CIPProjectWindow: onActiveViewChanged" & vbCrLf & ex.ToString())

    '    End Try
    'End Function
    ' Statics
    Friend Shared Sub ToggleCIPTools(ByVal enable As Boolean)
        GetSelectAssetTool()
        'RaiseEvent ChangeCIPToolStatus(enable)
    End Sub
    Friend Shared Function GetCostEstimatingWindow() As ESRI.ArcGIS.Framework.IDockableWindow
        If s_extension Is Nothing Then
            GetExtension()
        End If

        ' Only get/create the dockable window if they ask for it
        If s_dockWindow Is Nothing Then
            Dim dockWinID As UID = New UID()
            dockWinID.Value = "ArcGIS4LocalGovernment_CostEstimatingWindow"
            s_dockWindow = My.ArcMap.DockableWindowManager.GetDockableWindow(dockWinID)
            's_extension.UpdateSelCountDockWin()
        End If

        Return s_dockWindow
    End Function
    Friend Shared Function GetSelectAssetTool() As ICommandItem
        If s_extension Is Nothing Then
            GetExtension()
        End If
        If s_SelectAssetTool Is Nothing Then
            s_SelectAssetTool = My.Globals.Functions.GetCommand("ArcGIS4LocalGovernment_SelectAssetForGrid")

        End If

        Return s_SelectAssetTool
    End Function
    Friend Shared Function GetSelectPrjTool() As ICommandItem
        If s_extension Is Nothing Then
            GetExtension()
        End If
        If s_SelectPrj Is Nothing Then
            s_SelectPrj = My.Globals.Functions.GetCommand("ArcGIS4LocalGovernment_SelectExistingProject")

        End If

        Return s_SelectPrj
    End Function
    Friend Shared Function GetSelectCostedAssetTool() As ICommandItem
        If s_extension Is Nothing Then
            GetExtension()
        End If
        If s_SelectCostedAsset Is Nothing Then
            s_SelectCostedAsset = My.Globals.Functions.GetCommand("ArcGIS4LocalGovernment_SelectCostedAsset")

        End If

        Return s_SelectCostedAsset
    End Function
    Friend Shared Function IsExtensionEnabled() As Boolean
        If s_extension Is Nothing Then
            GetExtension()
        End If

        If s_extension Is Nothing Then
            Return False
        End If

        Return s_extension.State = ExtensionState.Enabled
    End Function
    Friend Shared Function HasSelectableLayer() As Boolean
        'If s_extension Is Nothing Then
        '    GetExtension()
        'End If

        'If s_extension Is Nothing Then
        '    Return False
        'End If

        'Return s_extension.m_hasSelectableLayer
    End Function

    Private Shared Function GetExtension() As CostEstimatingExtension
        If s_extension Is Nothing Then
            Dim extID As UID = New UIDClass()
            extID.Value = "ArcGIS4LocalGovernment_ArcGISProjectCostEstimatingExtension"
            ' Call FindExtension to load this just-in-time extension.
            My.ArcMap.Application.FindExtensionByCLSID(extID)
        End If
        Return s_extension
    End Function
End Class


text:
# See http://api.opensuse.org
#

module Obs

class Definition

  # content of .product
  attr_reader :vendor, :name, :version, :patchlevel, :summary

  #
  # Obs::Definition.new product (Obs::Product)
  def initialize(product)
    @product = product # Obs::Product
    @xml = @product.api.get "/source/#{self.origin}/_product/#{self.productname}.product"
    case @xml
    when String
      @xml = Nokogiri::XML(@xml)
    end
    product = @xml.xpath("//products/product").first
    @vendor = product.xpath("vendor").text
    @name = product.xpath("name").text
    @version = product.xpath("version").text
    @patchlevel = product.xpath("patchlevel").text
    @summary = product.xpath("summary").text
  end
  def to_xml
    @xml
  end
  def to_s
    "#{@vendor};#{@name};#{@version};#{@patchlevel} : #{@summary}"
  end

  # keys to access .product file
  # -> /source/#{origin}/_product/#{productname}.product
  def origin
    @product.origin
  end
  def productname
    @product.name
  end

end # class Product

end #Module Obs


text:
namespace auto_warehousing
{

static const char GETWAREHOUSECONFIG[] = "auto_warehousing/GetWarehouseConfig";

  class GetWarehouseConfigRequest : public ros::Msg
  {
    public:

    GetWarehouseConfigRequest()
    {
    }

    virtual int serialize(unsigned char *outbuffer) const
    {
      int offset = 0;
      return offset;
    }

    virtual int deserialize(unsigned char *inbuffer)
    {
      int offset = 0;
     return offset;
    }

    const char * getType(){ return GETWAREHOUSECONFIG; };
    const char * getMD5(){ return "d41d8cd98f00b204e9800998ecf8427e"; };

  };

  class GetWarehouseConfigResponse : public ros::Msg
  {
    public:
      typedef auto_warehousing::WarehouseConfiguration _warehouse_configuration_type;
      _warehouse_configuration_type warehouse_configuration;

    GetWarehouseConfigResponse():
      warehouse_configuration()
    {
    }

    virtual int serialize(unsigned char *outbuffer) const
    {
      int offset = 0;
      offset += this->warehouse_configuration.serialize(outbuffer + offset);
      return offset;
    }

    virtual int deserialize(unsigned char *inbuffer)
    {
      int offset = 0;
      offset += this->warehouse_configuration.deserialize(inbuffer + offset);
     return offset;
    }

    const char * getType(){ return GETWAREHOUSECONFIG; };
    const char * getMD5(){ return "8e7a6b6ded628f457b11b476368a8509"; };

  };

  class GetWarehouseConfig {
    public:
    typedef GetWarehouseConfigRequest Request;
    typedef GetWarehouseConfigResponse Response;
  };

}
#endif


text:
package kr.pe.kingori.ihatecolor.ui.view;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
import kr.pe.kingori.ihatecolor.util.FontManager;

public class CustomFontTextView extends TextView {
    public CustomFontTextView(Context context) {
        super(context);
        applyTypeFace();
    }

    public CustomFontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        applyTypeFace();

    }

    public CustomFontTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        applyTypeFace();
    }

    private void applyTypeFace() {
        FontManager.applyTypeface(this);
    }
}


text:
.spinnerContainer {
  margin: 25px auto 0;
}


text:
using System;
using System.IO;
using System.Reflection;
using System.Windows;

namespace Vlc.DotNet.Wpf.Samples
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            setpath();
            myControl.EndInit();
            this.DataContext = myControl;

            //myControl.Source = @"r:\[UHA-Wing] [Nyanbo!][26][1080p][BIG5].mp4";
            myControl.Source = @"r:\1.mp4";
        }

        WpfVlc.VlcControl myControl = new WpfVlc.VlcControl();

        private void setpath()
        {
            var currentAssembly = Assembly.GetEntryAssembly();
            var currentDirectory = new FileInfo(currentAssembly.Location).DirectoryName;
            if (currentDirectory == null)
                return;
            if (AssemblyName.GetAssemblyName(currentAssembly.Location).ProcessorArchitecture == ProcessorArchitecture.X86)
                myControl.LibVlcPath = Path.Combine(currentDirectory, @"..\..\..\lib\x86\");
            else
                myControl.LibVlcPath = Path.Combine(currentDirectory, @"..\..\..\lib\x64\");
        }

        private void OnPlayButtonClick(object sender, RoutedEventArgs e)
        {
            //myControl.MediaPlayer.Play(new Uri("http://download.blender.org/peach/bigbuckbunny_movies/big_buck_bunny_480p_surround-fix.avi"));

            myControl.IsPlay = !myControl.IsPlay;
        }

        private void OnForwardButtonClick(object sender, RoutedEventArgs e)
        {
            myControl.Rate = 2;
        }

        private void GetLength_Click(object sender, RoutedEventArgs e)
        {
            myControl.SubFile= null;
        }

        private void GetCurrentTime_Click(object sender, RoutedEventArgs e)
        {

            myControl.SubFile = @"r:\[UHA-Wing] [Nyanbo!][26][1080p][BIG5].ass";
        }

    }
}


text:
/**
 * RemarketingSettings.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
 */

package com.google.api.ads.adwords.axis.v201502.mcm;

/**
 * Customer-wide settings related to AdWords remarketing.
 */
public class RemarketingSettings  implements java.io.Serializable {
    /* The Adwords remarketing tag snippet for the customer.
     *                 This field is read
     * only and will be ignored when sent to the API. */
    private java.lang.String snippet;

    public RemarketingSettings() {
    }

    public RemarketingSettings(
           java.lang.String snippet) {
           this.snippet = snippet;
    }

    /**
     * Gets the snippet value for this RemarketingSettings.
     *
     * @return snippet   * The Adwords remarketing tag snippet for the customer.
     *                 This field is read
     * only and will be ignored when sent to the API.
     */
    public java.lang.String getSnippet() {
        return snippet;
    }

    /**
     * Sets the snippet value for this RemarketingSettings.
     *
     * @param snippet   * The Adwords remarketing tag snippet for the customer.
     *                 This field is read
     * only and will be ignored when sent to the API.
     */
    public void setSnippet(java.lang.String snippet) {
        this.snippet = snippet;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof RemarketingSettings)) return false;
        RemarketingSettings other = (RemarketingSettings) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = true &&
            ((this.snippet==null && other.getSnippet()==null) ||
             (this.snippet!=null &&
              this.snippet.equals(other.getSnippet())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = 1;
        if (getSnippet() != null) {
            _hashCode += getSnippet().hashCode();
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(RemarketingSettings.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/mcm/v201502", "RemarketingSettings"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("snippet");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/mcm/v201502", "snippet"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
{% extends "registration/base.html" %}

{% block title %}Activation complete{% endblock %}

{% block content %}

Congratulations!

Your registration is now complete. Go to the site and start having fun!

{% endblock %}


text:
// -*- c++ -*-
// Generated by gtkmmproc -- DO NOT MODIFY!
#ifndef _GTKMM_PRINTUNIXDIALOG_H
#define _GTKMM_PRINTUNIXDIALOG_H

#include <glibmm.h>

#include <gtkmm/dialog.h>
#include <gtkmm/pagesetup.h>
#include <gtkmm/printer.h>
#include <gtkmm/printjob.h>
#include <gtkmm/printsettings.h>

#ifndef DOXYGEN_SHOULD_SKIP_THIS
typedef struct _GtkPrintUnixDialog GtkPrintUnixDialog;
typedef struct _GtkPrintUnixDialogClass GtkPrintUnixDialogClass;
#endif /* DOXYGEN_SHOULD_SKIP_THIS */

namespace Gtk
{ class PrintUnixDialog_Class; } // namespace Gtk
namespace Gtk
{

/** PrintUnixDialog implements a print dialog for platforms
 * which don't provide a native print dialog, like Unix. It can
 * be used very much like any other GTK+ dialog, at the cost of
 * the portability offered by the high-level printing API exposed
 * through PrintOperation.
 *
 * In order to print something with PrintUnixDialog, you need
 * to use get_selected_printer() to obtain a Printer object and
 * use it to construct a PrintJob using PrintJob::create().
 *
 * PrintUnixDialog uses the following response values:
 * - RESPONSE_OK for the "Print" button
 * - RESPONSE_APPLY for the "Preview" button
 * - RESPONSE_CANCEL for the "Cancel" button
 *
 * @newin{2,10}
 *
 * @ingroup Printing
 */

class PrintUnixDialog : public Dialog
{
  public:
#ifndef DOXYGEN_SHOULD_SKIP_THIS
  typedef PrintUnixDialog CppObjectType;
  typedef PrintUnixDialog_Class CppClassType;
  typedef GtkPrintUnixDialog BaseObjectType;
  typedef GtkPrintUnixDialogClass BaseClassType;
#endif /* DOXYGEN_SHOULD_SKIP_THIS */

  virtual ~PrintUnixDialog();

#ifndef DOXYGEN_SHOULD_SKIP_THIS

private:
  friend class PrintUnixDialog_Class;
  static CppClassType printunixdialog_class_;

  // noncopyable
  PrintUnixDialog(const PrintUnixDialog&);
  PrintUnixDialog& operator=(const PrintUnixDialog&);

protected:
  explicit PrintUnixDialog(const Glib::ConstructParams& construct_params);
  explicit PrintUnixDialog(GtkPrintUnixDialog* castitem);

#endif /* DOXYGEN_SHOULD_SKIP_THIS */

public:
#ifndef DOXYGEN_SHOULD_SKIP_THIS
  static GType get_type()      G_GNUC_CONST;

  static GType get_base_type() G_GNUC_CONST;
#endif

  ///Provides access to the underlying C GtkObject.
  GtkPrintUnixDialog*       gobj()       { return reinterpret_cast<GtkPrintUnixDialog*>(gobject_); }

  ///Provides access to the underlying C GtkObject.
  const GtkPrintUnixDialog* gobj() const { return reinterpret_cast<GtkPrintUnixDialog*>(gobject_); }

public:
  //C++ methods used to invoke GTK+ virtual functions:

protected:
  //GTK+ Virtual Functions (override these to change behaviour):

  //Default Signal Handlers::

private:

  //This is not available in on Win32.
//This source file will not be compiled,
//and the class will not be registered in wrap_init.h or wrap_init.cc

public:
  explicit PrintUnixDialog(Gtk::Window& parent, const Glib::ustring& title);
  explicit PrintUnixDialog(const Glib::ustring& title);

  /** Sets the page setup of the Gtk::PrintUnixDialog.
   *
   * @newin{2,10}
   * @param page_setup A Gtk::PageSetup.
   */
  void set_page_setup(const Glib::RefPtr<PageSetup>& page_setup);

  /** Gets the page setup that is used by the Gtk::PrintUnixDialog.
   *
   * @newin{2,10}
   * @return The page setup of @a dialog.
   */
  Glib::RefPtr<PageSetup> get_page_setup();

  /** Gets the page setup that is used by the Gtk::PrintUnixDialog.
   *
   * @newin{2,10}
   * @return The page setup of @a dialog.
   */
  Glib::RefPtr<const PageSetup> get_page_setup() const;

  /** Sets the current page number. If @a current_page is not -1, this enables
   * the current page choice for the range of pages to print.
   *
   * @newin{2,10}
   * @param current_page The current page number.
   */
  void set_current_page(int current_page);

  /** Gets the current page of the Gtk::PrintDialog.
   *
   * @newin{2,10}
   * @return The current page of @a dialog.
   */
  int get_current_page() const;

  /** Sets the Gtk::PrintSettings for the Gtk::PrintUnixDialog. Typically,
   * this is used to restore saved print settings from a previous print
   * operation before the print dialog is shown.
   *
   * @newin{2,10}
   * @param settings A Gtk::PrintSettings, or <tt>0</tt>.
   */
  void set_settings(const Glib::RefPtr<PrintSettings>& print_settings);

  /** Gets a new Gtk::PrintSettings object that represents the
   * current values in the print dialog. Note that this creates a
   * <emphasis>new object</emphasis>, and you need to unref it
   * if don't want to keep it.
   *
   * @newin{2,10}
   * @return A new Gtk::PrintSettings object with the values from @a dialog.
   */
  Glib::RefPtr<PrintSettings> get_settings();

  /** Gets a new Gtk::PrintSettings object that represents the
   * current values in the print dialog. Note that this creates a
   * <emphasis>new object</emphasis>, and you need to unref it
   * if don't want to keep it.
   *
   * @newin{2,10}
   * @return A new Gtk::PrintSettings object with the values from @a dialog.
   */
  Glib::RefPtr<const PrintSettings> get_settings() const;

  /** Gets the currently selected printer.
   *
   * @newin{2,10}
   * @return The currently selected printer.
   */
  Glib::RefPtr<Printer> get_selected_printer();

  /** Gets the currently selected printer.
   *
   * @newin{2,10}
   * @return The currently selected printer.
   */
  Glib::RefPtr<const Printer> get_selected_printer() const;

  void add_custom_tab(const Widget& child, const Glib::ustring& tab_label);

  /** Adds a custom tab to the print dialog.
   *
   * @newin{2,10}
   * @param child The widget to put in the custom tab.
   * @param tab_label The widget to use as tab label.
   */
  void add_custom_tab(const Widget& child, const Widget& tab_label);

  /** This lets you specify the printing capabilities your application
   * supports. For instance, if you can handle scaling the output then
   * you pass Gtk::PRINT_CAPABILITY_SCALE. If you don't pass that, then
   * the dialog will only let you select the scale if the printing
   * system automatically handles scaling.
   *
   * @newin{2,10}
   * @param capabilities The printing capabilities of your application.
   */
  void set_manual_capabilities(PrintCapabilities capabilities);

  /** Gets the value of Gtk::PrintUnixDialog::manual-capabilities property.
   *
   * @newin{2,18}
   * @return The printing capabilities.
   */
  PrintCapabilities get_manual_capabilities() const;

  /** Sets whether the print dialog allows user to print a selection.
   *
   * @newin{2,18}
   * @param support_selection <tt>true</tt> to allow print selection.
   */
  void get_support_selection(bool support_selection = true);

  /** Gets the value of Gtk::PrintUnixDialog::support-selection property.
   *
   * @newin{2,18}
   * @return Whether the application supports print of selection.
   */
  bool get_support_selection() const;

  /** Sets whether a selection exists.
   *
   * @newin{2,18}
   * @param has_selection <tt>true</tt> indicates that a selection exists.
   */
  void set_has_selection(bool has_selection = true);

  /** Gets the value of Gtk::PrintUnixDialog::has-selection property.
   *
   * @newin{2,18}
   * @return Whether there is a selection.
   */
  bool get_has_selection() const;

  /** Embed page size combo box and orientation combo box into page setup page.
   *
   * @newin{2,18}
   * @param embed Embed page setup selection.
   */
  void set_embed_page_setup(bool embed = true);

  /** Gets the value of Gtk::PrintUnixDialog::embed-page-setup property.
   *
   * @newin{2,18}
   * @return Whether there is a selection.
   */
  bool get_embed_page_setup() const;

  /** Gets the page setup that is used by the Gtk::PrintUnixDialog.
   *
   * @newin{2,18}
   * @return Whether a page setup was set by user.
   */
  bool get_page_setup_set() const;

  #ifdef GLIBMM_PROPERTIES_ENABLED
/** The GtkPageSetup to use.
   *
   * You rarely need to use properties because there are get_ and set_ methods for almost all of them.
   * @return A PropertyProxy that allows you to get or set the property of the value, or receive notification when
   * the value of the property changes.
   */
  Glib::PropertyProxy< Glib::RefPtr<PageSetup> > property_page_setup() ;
#endif //#GLIBMM_PROPERTIES_ENABLED

#ifdef GLIBMM_PROPERTIES_ENABLED
/** The GtkPageSetup to use.
   *
   * You rarely need to use properties because there are get_ and set_ methods for almost all of them.
   * @return A PropertyProxy that allows you to get or set the property of the value, or receive notification when
   * the value of the property changes.
   */
  Glib::PropertyProxy_ReadOnly< Glib::RefPtr<PageSetup> > property_page_setup() const;
#endif //#GLIBMM_PROPERTIES_ENABLED

  #ifdef GLIBMM_PROPERTIES_ENABLED
/** The current page in the document.
   *
   * You rarely need to use properties because there are get_ and set_ methods for almost all of them.
   * @return A PropertyProxy that allows you to get or set the property of the value, or receive notification when
   * the value of the property changes.
   */
  Glib::PropertyProxy<int> property_current_page() ;
#endif //#GLIBMM_PROPERTIES_ENABLED

#ifdef GLIBMM_PROPERTIES_ENABLED
/** The current page in the document.
   *
   * You rarely need to use properties because there are get_ and set_ methods for almost all of them.
   * @return A PropertyProxy that allows you to get or set the property of the value, or receive notification when
   * the value of the property changes.
   */
  Glib::PropertyProxy_ReadOnly<int> property_current_page() const;
#endif //#GLIBMM_PROPERTIES_ENABLED

  #ifdef GLIBMM_PROPERTIES_ENABLED
/** The GtkPrintSettings used for initializing the dialog.
   *
   * You rarely need to use properties because there are get_ and set_ methods for almost all of them.
   * @return A PropertyProxy that allows you to get or set the property of the value, or receive notification when
   * the value of the property changes.
   */
  Glib::PropertyProxy< Glib::RefPtr<PrintSettings> > property_print_settings() ;
#endif //#GLIBMM_PROPERTIES_ENABLED

#ifdef GLIBMM_PROPERTIES_ENABLED
/** The GtkPrintSettings used for initializing the dialog.
   *
   * You rarely need to use properties because there are get_ and set_ methods for almost all of them.
   * @return A PropertyProxy that allows you to get or set the property of the value, or receive notification when
   * the value of the property changes.
   */
  Glib::PropertyProxy_ReadOnly< Glib::RefPtr<PrintSettings> > property_print_settings() const;
#endif //#GLIBMM_PROPERTIES_ENABLED

  #ifdef GLIBMM_PROPERTIES_ENABLED
/** The GtkPrinter which is selected.
   *
   * You rarely need to use properties because there are get_ and set_ methods for almost all of them.
   * @return A PropertyProxy that allows you to get or set the property of the value, or receive notification when
   * the value of the property changes.
   */
  Glib::PropertyProxy_ReadOnly< Glib::RefPtr<Printer> > property_selected_printer() const;
#endif //#GLIBMM_PROPERTIES_ENABLED

  #ifdef GLIBMM_PROPERTIES_ENABLED
/** Capabilities the application can handle.
   *
   * You rarely need to use properties because there are get_ and set_ methods for almost all of them.
   * @return A PropertyProxy that allows you to get or set the property of the value, or receive notification when
   * the value of the property changes.
   */
  Glib::PropertyProxy<bool> property_manual_capabilities() ;
#endif //#GLIBMM_PROPERTIES_ENABLED

#ifdef GLIBMM_PROPERTIES_ENABLED
/** Capabilities the application can handle.
   *
   * You rarely need to use properties because there are get_ and set_ methods for almost all of them.
   * @return A PropertyProxy that allows you to get or set the property of the value, or receive notification when
   * the value of the property changes.
   */
  Glib::PropertyProxy_ReadOnly<bool> property_manual_capabilities() const;
#endif //#GLIBMM_PROPERTIES_ENABLED

  #ifdef GLIBMM_PROPERTIES_ENABLED
/** Whether the dialog supports selection.
   *
   * You rarely need to use properties because there are get_ and set_ methods for almost all of them.
   * @return A PropertyProxy that allows you to get or set the property of the value, or receive notification when
   * the value of the property changes.
   */
  Glib::PropertyProxy<bool> property_support_selection() ;
#endif //#GLIBMM_PROPERTIES_ENABLED

#ifdef GLIBMM_PROPERTIES_ENABLED
/** Whether the dialog supports selection.
   *
   * You rarely need to use properties because there are get_ and set_ methods for almost all of them.
   * @return A PropertyProxy that allows you to get or set the property of the value, or receive notification when
   * the value of the property changes.
   */
  Glib::PropertyProxy_ReadOnly<bool> property_support_selection() const;
#endif //#GLIBMM_PROPERTIES_ENABLED

  #ifdef GLIBMM_PROPERTIES_ENABLED
/** Whether the application has a selection.
   *
   * You rarely need to use properties because there are get_ and set_ methods for almost all of them.
   * @return A PropertyProxy that allows you to get or set the property of the value, or receive notification when
   * the value of the property changes.
   */
  Glib::PropertyProxy<bool> property_has_selection() ;
#endif //#GLIBMM_PROPERTIES_ENABLED

#ifdef GLIBMM_PROPERTIES_ENABLED
/** Whether the application has a selection.
   *
   * You rarely need to use properties because there are get_ and set_ methods for almost all of them.
   * @return A PropertyProxy that allows you to get or set the property of the value, or receive notification when
   * the value of the property changes.
   */
  Glib::PropertyProxy_ReadOnly<bool> property_has_selection() const;
#endif //#GLIBMM_PROPERTIES_ENABLED

  #ifdef GLIBMM_PROPERTIES_ENABLED
/** TRUE if page setup combos are embedded in GtkPrintUnixDialog.
   *
   * You rarely need to use properties because there are get_ and set_ methods for almost all of them.
   * @return A PropertyProxy that allows you to get or set the property of the value, or receive notification when
   * the value of the property changes.
   */
  Glib::PropertyProxy<bool> property_embed_page_setup() ;
#endif //#GLIBMM_PROPERTIES_ENABLED

#ifdef GLIBMM_PROPERTIES_ENABLED
/** TRUE if page setup combos are embedded in GtkPrintUnixDialog.
   *
   * You rarely need to use properties because there are get_ and set_ methods for almost all of them.
   * @return A PropertyProxy that allows you to get or set the property of the value, or receive notification when
   * the value of the property changes.
   */
  Glib::PropertyProxy_ReadOnly<bool> property_embed_page_setup() const;
#endif //#GLIBMM_PROPERTIES_ENABLED

};

} // namespace Gtk

namespace Glib
{
  /** A Glib::wrap() method for this object.
   *
   * @param object The C instance.
   * @param take_copy False if the result should take ownership of the C instance. True if it should take a new copy or ref.
   * @result A C++ instance that wraps this C instance.
   *
   * @relates Gtk::PrintUnixDialog
   */
  Gtk::PrintUnixDialog* wrap(GtkPrintUnixDialog* object, bool take_copy = false);
} //namespace Glib

#endif /* _GTKMM_PRINTUNIXDIALOG_H */


text:
#ifndef CPPCAT_CLIENT_H
#define CPPCAT_CLIENT_H

#include <string>

namespace cat {

    using namespace std;

    const string SUCCESS = "0";
    const string FAIL = "-1";
    const string ERROR = "ERROR";

    const int ENCODER_TEXT = 0;
    const int ENCODER_BINARY  = 1;

    class Config {
    public:
        int encoderType = ENCODER_BINARY;
        bool enableHeartbeat = true;
        bool enableSampling = true;
        bool enableMultiprocessing = false;
        bool enableDebugLog = false;
    };

    class Transaction {
    private:
        void* trans;
    public:
        Transaction(const string& type, const string& name);

        void Complete();

        unsigned long GetDurationMs();

        string GetType();

        string GetName();

        string GetStatus();

        void SetStatus(const string& status);

        void SetDurationStart(unsigned long ms);

        void SetDurationInMillis(unsigned long ms);

        void SetTimestamp(unsigned long timestamp);

        void AddData(const string& key, const string& val);

        void AddData(const string& data);
    };

    class Event {
    private:
        void* event;
    public:
        Event(const string& type, const string& name);

        void Complete();

        string GetType();

        string GetName();

        string GetStatus();

        void SetStatus(const string& status);

        void SetTimestamp(unsigned long timestamp);

        void AddData(const string& key, const string& val);

        void AddData(const string& data);
    };

    void init(const string& domain);

    void init(const string& domain, const Config& config);

    string version();

    void destroy();

    void logEvent(const string& type, const string& name, const string& status = SUCCESS, const string& data = "");

    void logMetricForCount(const string& key, unsigned int count = 1);

    void logMetricForDuration(const string& key, unsigned long ms);
};

#endif // CPPCAT_CLIENT_H