text:
<?php

class MlmDistPairingMapBuilder {

	const CLASS_NAME = 'lib.model.map.MlmDistPairingMapBuilder';

	private $dbMap;

	public function isBuilt()
	{
		return ($this->dbMap !== null);
	}

	public function getDatabaseMap()
	{
		return $this->dbMap;
	}

	public function doBuild()
	{
		$this->dbMap = Propel::getDatabaseMap('propel');

		$tMap = $this->dbMap->addTable('mlm_dist_pairing');
		$tMap->setPhpName('MlmDistPairing');

		$tMap->setUseIdGenerator(true);

		$tMap->addPrimaryKey('PAIRING_ID', 'PairingId', 'int', CreoleTypes::INTEGER, true, null);

		$tMap->addColumn('DIST_ID', 'DistId', 'int', CreoleTypes::INTEGER, true, null);

		$tMap->addColumn('LEFT_BALANCE', 'LeftBalance', 'int', CreoleTypes::INTEGER, true, null);

		$tMap->addColumn('RIGHT_BALANCE', 'RightBalance', 'int', CreoleTypes::INTEGER, true, null);

		$tMap->addColumn('FLUSH_LIMIT', 'FlushLimit', 'int', CreoleTypes::INTEGER, true, null);

		$tMap->addColumn('CREATED_BY', 'CreatedBy', 'int', CreoleTypes::INTEGER, true, null);

		$tMap->addColumn('CREATED_ON', 'CreatedOn', 'int', CreoleTypes::TIMESTAMP, true, null);

		$tMap->addColumn('UPDATED_BY', 'UpdatedBy', 'int', CreoleTypes::INTEGER, true, null);

		$tMap->addColumn('UPDATED_ON', 'UpdatedOn', 'int', CreoleTypes::TIMESTAMP, true, null);

	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>Apache log4cxx: SocketAppender Class Reference</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Modules

Namespaces

Classes

Files

Alphabetical List

Class List

Class Hierarchy

Class Members

log4cxx::net::SocketAppender

SocketAppender Class Reference
Inherits SocketAppenderSkeleton.

List of all members.

Detailed Description

Sends LoggingEvent objects to a remote a log server, usually Apache Chainsaw.

The SocketAppender has the following properties:

If sent to Apache Chainsaw, remote logging is non-intrusive as far as the log event is concerned. In other words, the event will be logged with the same time stamp, NDC, location info as if it were logged locally by the client.

SocketAppenders do not use a layout. They ship a serialized LoggingEvent object to the server side.

Remote logging uses the TCP protocol. Consequently, if the server is reachable, then log events will eventually arrive at the server.

If the remote server is down, the logging requests are simply dropped. However, if and when the server comes back up, then event transmission is resumed transparently. This transparent reconneciton is performed by a connector thread which periodically attempts to connect to the server.

Logging events are automatically buffered by the native TCP implementation. This means that if the link to server is slow but still faster than the rate of (log) event production by the client, the client will not be affected by the slow network connection. However, if the network connection is slower then the rate of event production, then the client can only progress at the network rate. In particular, if the network link to the the server is down, the client will be blocked.

 On the other hand, if the network link is up, but the server is down, the client will not be blocked when making log requests but the log events will be lost due to server unavailability.

Even if a SocketAppender is no longer attached to any logger, it will not be destroyed in the presence of a connector thread. A connector thread exists only if the connection to the server is down. To avoid this destruction problem, you should close the the SocketAppender explicitly. See also next item.

 Long lived applications which create/destroy many SocketAppender instances should be aware of this destruction problem. Most other applications can safely ignore it.

If the application hosting the SocketAppender exits before the SocketAppender is closed either explicitly or subsequent to destruction, then there might be untransmitted data in the pipe which might be lost.

 To avoid lost data, it is usually sufficient to close the SocketAppender either explicitly or by calling the LogManager::shutdown method before exiting the application.

Public Member Functions

 	SocketAppender ()

 	~SocketAppender ()

 	SocketAppender (helpers::InetAddressPtr &address, int port)

 	Connects to remote server at address and port.

 	SocketAppender (const LogString &host, int port)

 	Connects to remote server at host and port.

Static Public Attributes

static int 	DEFAULT_PORT

 	The default port number of remote logging server (4560).

static int 	DEFAULT_RECONNECTION_DELAY

 	The default reconnection delay (30000 milliseconds or 30 seconds).

Protected Member Functions

virtual void 	setSocket (log4cxx::helpers::SocketPtr &socket, log4cxx::helpers::Pool &p)

virtual void 	cleanUp (log4cxx::helpers::Pool &p)

virtual int 	getDefaultDelay () const

virtual int 	getDefaultPort () const

void 	append (const spi::LoggingEventPtr &event, log4cxx::helpers::Pool &pool)

 	Subclasses of AppenderSkeleton should implement this method to perform actual logging.

Constructor & Destructor Documentation

          SocketAppender
          (

           )

          ~SocketAppender
          (

           )

          SocketAppender
          (
          helpers::InetAddressPtr &
           address,

          int
           port

          )

Connects to remote server at address and port.

          SocketAppender
          (
          const LogString &
           host,

          int
           port

          )

Connects to remote server at host and port.

Member Function Documentation

          void append
          (
          const spi::LoggingEventPtr &
           event,

          log4cxx::helpers::Pool &
           pool

          )
           [protected, virtual]

Subclasses of AppenderSkeleton should implement this method to perform actual logging.

See also AppenderSkeleton::doAppend method.

Implements AppenderSkeleton.

          virtual void cleanUp
          (
          log4cxx::helpers::Pool &
           p
           )
           [protected, virtual]

Implements SocketAppenderSkeleton.

          virtual int getDefaultDelay
          (

           )
           const [protected, virtual]

Implements SocketAppenderSkeleton.

          virtual int getDefaultPort
          (

           )
           const [protected, virtual]

Implements SocketAppenderSkeleton.

          virtual void setSocket
          (
          log4cxx::helpers::SocketPtr &
           socket,

          log4cxx::helpers::Pool &
           p

          )
           [protected, virtual]

Implements SocketAppenderSkeleton.

Member Data Documentation

          int DEFAULT_PORT [static]

The default port number of remote logging server (4560).

          int DEFAULT_RECONNECTION_DELAY [static]

The default reconnection delay (30000 milliseconds or 30 seconds).

The documentation for this class was generated from the following file:

socketappender.h

redpajama_set_name: RedPajamaGithub


text:
namespace Microsoft.Azure.Management.DataLake.Analytics.Models
{
    using Analytics;
    using Azure;
    using DataLake;
    using Management;
    using Azure;
    using Management;
    using DataLake;
    using Analytics;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;
    using System.Runtime;
    using System.Runtime.Serialization;

    /// <summary>
    /// Defines values for CompileMode.
    /// </summary>
    [JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
    public enum CompileMode
    {
        [EnumMember(Value = "Semantic")]
        Semantic,
        [EnumMember(Value = "Full")]
        Full,
        [EnumMember(Value = "SingleBox")]
        SingleBox
    }
}


text:
package bulu.core

object MeasureType extends Enumeration {
	type MeasureType=Value
	val Count=Value("cnt")
	val Summary=Value("sum")
	val Average=Value("avg")
	val SquarSummary=Value("ssm")
	val Maximum=Value("max")
}


text:
BOARD_TAG    = nano328
PROJECT_DIR       = /home/vanell/Documents/Measure_Box/src
USER_LIB_PATH    :=  $(PROJECT_DIR)/libs
ARDUINO_LIBS = LiquidCrystal SoftwareSerial Bounce2 TinyGPS SD GPS pin
include /usr/share/Arduino-Makefile/Arduino.mk


text:
package ca.corefacility.bioinformatics.irida.model.workflow.execution;

/**
 * Defines acceptable file types for input to a workflow.
 *
 */
public enum InputFileType {

	/**
	 * The fastqsanger file type (quality scores are Phred+33).
	 */
	FASTQ_SANGER("fastqsanger"),

	/**
	 * The fastqsanger.gz (gzipped) file type (quality scores are Phred+33).
	 */
	FASTQ_SANGER_GZ("fastqsanger.gz"),

	/**
	 * A FASTA formatted file.
	 */
	FASTA("fasta");

	private String fileType;

	private InputFileType(String type) {
		this.fileType = type;
	}

	@Override
	public String toString() {
		return fileType;
	}
}


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\View\Compilers\Concerns\CompilesRawPhp;

class Pagamento extends Model
{

    protected $fillable = [
        'compra_id',
        'categoria_id',
        'pessoa_id',
        'vencimento',
        'pagamento',
        'total',
        'obs'
    ];

    protected $dates = [
        'vencimento',
        'pagamento'
    ];

    public function compra()
    {
        return $this->belongsto(Compra::class);
    }

    public function categoria()
    {
        return $this->belongsTo(FinanceiroCategoria::class, 'categoria_id');
    }

    public function pessoa()
    {
        return $this->belongsTo(Pessoa::class);
    }
}


text:
resource :package do
  ready!
  steps do |step|
    step.checks << "\\$(apt-cache policy #{self.name} | grep Installed | wc -l) -eq 1"
    step.checks << "\\$(apt-cache policy #{self.name} | grep Installed | grep '(none)' | wc -l) -eq 0"
    step.code = "apt-get install #{self.name} --yes"
  end
end


text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 3.0.8
 *
 * This file is not intended to be easily readable and contains a number of
 * coding conventions designed to improve portability and efficiency. Do not make
 * changes to this file unless you know what you are doing--modify the SWIG
 * interface file instead.
 * ----------------------------------------------------------------------------- */

// source: tmp.i

package tmp

/*
#define intgo swig_intgo
typedef void *swig_voidp;

#include <stdint.h>

typedef long long intgo;
typedef unsigned long long uintgo;

typedef struct { char *p; intgo n; } _gostring_;
typedef struct { void* array; intgo len; intgo cap; } _goslice_;

extern void _wrap_Swig_free_tmp_4231490e6333a8e7(uintptr_t arg1);
extern void _wrap_setMyString_tmp_4231490e6333a8e7(swig_voidp arg1);
#undef intgo

#cgo LDFLAGS: -L${SRCDIR}/cc -ltmp -lstdc++

*/
import "C"

import "unsafe"
import _ "runtime/cgo"
import "sync"

type _ unsafe.Pointer

var Swig_escape_always_false bool
var Swig_escape_val interface{}

type _swig_fnptr *byte
type _swig_memberptr *byte

type _ sync.Mutex

func Swig_free(arg1 uintptr) {
	_swig_i_0 := arg1
	C._wrap_Swig_free_tmp_4231490e6333a8e7(C.uintptr_t(_swig_i_0))
}

const X_GLIBCXX_STRING int = 1
func SetMyString(arg1 *string) {
	_swig_i_0 := arg1
	C._wrap_setMyString_tmp_4231490e6333a8e7(C.swig_voidp(_swig_i_0))
}


text:
package org.flowable.engine.common.impl.de.odysseus.el.tree.impl.ast;

import org.flowable.engine.common.impl.de.odysseus.el.misc.BooleanOperations;
import org.flowable.engine.common.impl.de.odysseus.el.misc.NumberOperations;
import org.flowable.engine.common.impl.de.odysseus.el.misc.TypeConverter;
import org.flowable.engine.common.impl.de.odysseus.el.tree.Bindings;
import org.flowable.engine.common.impl.javax.el.ELContext;

public class AstBinary extends AstRightValue {
	public interface Operator {
		public Object eval(Bindings bindings, ELContext context, AstNode left, AstNode right);
	}
	public abstract static class SimpleOperator implements Operator {
		public Object eval(Bindings bindings, ELContext context, AstNode left, AstNode right) {
			return apply(bindings, left.eval(bindings, context), right.eval(bindings, context));
		}

		protected abstract Object apply(TypeConverter converter, Object o1, Object o2);
	}
	public static final Operator ADD = new SimpleOperator() {
		@Override public Object apply(TypeConverter converter, Object o1, Object o2) { return NumberOperations.add(converter, o1, o2); }
		@Override public String toString() { return "+"; }
	};
	public static final Operator AND = new Operator() {
		public Object eval(Bindings bindings, ELContext context, AstNode left, AstNode right) {
			Boolean l = bindings.convert(left.eval(bindings, context), Boolean.class);
			return Boolean.TRUE.equals(l) ? bindings.convert(right.eval(bindings, context), Boolean.class) : Boolean.FALSE;
		}
		@Override public String toString() { return "&&"; }
	};
	public static final Operator DIV = new SimpleOperator() {
		@Override public Object apply(TypeConverter converter, Object o1, Object o2) { return NumberOperations.div(converter, o1, o2); }
		@Override public String toString() { return "/"; }
	};
	public static final Operator EQ = new SimpleOperator() {
		@Override public Object apply(TypeConverter converter, Object o1, Object o2) { return BooleanOperations.eq(converter, o1, o2); }
		@Override public String toString() { return "=="; }
	};
	public static final Operator GE = new SimpleOperator() {
		@Override public Object apply(TypeConverter converter, Object o1, Object o2) { return BooleanOperations.ge(converter, o1, o2); }
		@Override public String toString() { return ">="; }
	};
	public static final Operator GT = new SimpleOperator() {
		@Override public Object apply(TypeConverter converter, Object o1, Object o2) { return BooleanOperations.gt(converter, o1, o2); }
		@Override public String toString() { return ">"; }
	};
	public static final Operator LE = new SimpleOperator() {
		@Override public Object apply(TypeConverter converter, Object o1, Object o2) { return BooleanOperations.le(converter, o1, o2); }
		@Override public String toString() { return "<="; }
	};
	public static final Operator LT = new SimpleOperator() {
		@Override public Object apply(TypeConverter converter, Object o1, Object o2) { return BooleanOperations.lt(converter, o1, o2); }
		@Override public String toString() { return "<"; }
	};
	public static final Operator MOD = new SimpleOperator() {
		@Override public Object apply(TypeConverter converter, Object o1, Object o2) { return NumberOperations.mod(converter, o1, o2); }
		@Override public String toString() { return "%"; }
	};
	public static final Operator MUL = new SimpleOperator() {
		@Override public Object apply(TypeConverter converter, Object o1, Object o2) { return NumberOperations.mul(converter, o1, o2); }
		@Override public String toString() { return "*"; }
	};
	public static final Operator NE = new SimpleOperator() {
		@Override public Object apply(TypeConverter converter, Object o1, Object o2) { return BooleanOperations.ne(converter, o1, o2); }
		@Override public String toString() { return "!="; }
	};
	public static final Operator OR = new Operator() {
		public Object eval(Bindings bindings, ELContext context, AstNode left, AstNode right) {
			Boolean l = bindings.convert(left.eval(bindings, context), Boolean.class);
			return Boolean.TRUE.equals(l) ? Boolean.TRUE : bindings.convert(right.eval(bindings, context), Boolean.class);
		}
		@Override public String toString() { return "||"; }
	};
	public static final Operator SUB = new SimpleOperator() {
		@Override public Object apply(TypeConverter converter, Object o1, Object o2) { return NumberOperations.sub(converter, o1, o2); }
		@Override public String toString() { return "-"; }
	};

	private final Operator operator;
	private final AstNode left, right;

	public AstBinary(AstNode left, AstNode right, Operator operator) {
		this.left = left;
		this.right = right;
		this.operator = operator;
	}

	public Operator getOperator() {
		return operator;
	}

	@Override
	public Object eval(Bindings bindings, ELContext context) {
		return operator.eval(bindings, context, left, right);
	}

	@Override
	public String toString() {
		return "'" + operator.toString() + "'";
	}

	@Override
	public void appendStructure(StringBuilder b, Bindings bindings) {
		left.appendStructure(b, bindings);
		b.append(' ');
		b.append(operator);
		b.append(' ');
		right.appendStructure(b, bindings);
	}

	public int getCardinality() {
		return 2;
	}

	public AstNode getChild(int i) {
		return i == 0 ? left : i == 1 ? right : null;
	}
}


text:
package com.android.multidexlegacyandexception;

public class CaughtOnlyByIntermediateException extends RuntimeException {

}


text:
require('./Preloader.less');
var React = require('react');
var Preloader = React.createClass({
	displayName:'Preloader',
	getDefaultProps: function (){
		return {
			title: '正在加载中...'
		}
	},
	render: function(){
		return (

				{this.props.content||this.props.title}

		);
	}
});

module.exports = zn.preloader = zn.Class({
	static: true,
	methods: {
		init: function (){
			this._dom = zn.dom.createRootElement("div", { class: "zr-preloader-container" });
		},
		open: function (argv, overlay){
			zn.modal.open(<Preloader {...argv} />, { className: overlay?'overlay':'' });
		},
		close: function (){
			zn.modal.close();
		}
	}
});


text:
#ifndef _RAID0_H
#define _RAID0_H

struct strip_zone {
	sector_t zone_end;	/* Start of the next zone (in sectors) */
	sector_t dev_start;	/* Zone offset in real dev (in sectors) */
	int nb_dev;		/* # of devices attached to the zone */
};

struct r0conf {
	struct strip_zone *strip_zone;
	struct md_rdev **devlist; /* lists of rdevs, pointed to by strip_zone->dev */
	int nr_strip_zones;
};

#endif


text:
<?php

namespace Metabor\Observer;

/**
 * @author Oliver Tischlinger
 */
class CounterOberserverTest extends \PHPUnit_Framework_TestCase
{
    /**
     *
     */
    public function testCountsHowOftenTheObserverWasCalled()
    {
        $subject = $this->getMockForAbstractClass('\SplSubject');

        $observer = new CounterObserver();
        $this->assertEquals(0, $observer->getCount());
        $observer->update($subject);
        $observer->update($subject);
        $this->assertEquals(2, $observer->getCount());
    }

    /**
     *
     */
    public function testCanBeReset()
    {
        $subject = $this->getMockForAbstractClass('\SplSubject');

        $observer = new CounterObserver();
        $this->assertEquals(0, $observer->getCount());
        $observer->update($subject);
        $this->assertEquals(1, $observer->getCount());
        $observer->resetCount();
        $this->assertEquals(0, $observer->getCount());
    }
}


text:
package edu.ucsb.cs56.w15.drawings.weiers.advanced;
import java.awt.geom.GeneralPath;
import java.awt.geom.AffineTransform;
import java.awt.Shape;

import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.awt.Rectangle;
import java.awt.geom.PathIterator;
import java.awt.geom.AffineTransform;

import edu.ucsb.cs56.w15.drawings.utilities.ShapeTransforms;
import edu.ucsb.cs56.w15.drawings.utilities.GeneralPathWrapper;

/**
   A basic AC power outlet that implements
   the Shape interface, and so can be drawn,
   rotated, etc...

   @author William Eiers
   @version for CS56 Winter 15, UCSB

*/

public class PowerOutlet extends GeneralPathWrapper implements Shape {

    /**
       Constructor
       @param x x coord of lower left corner of power outlet
       @param y y coord of lower left corner of power outlet
       @param width width of outlet
       @param height height of outlet
    */

    public PowerOutlet(double x, double y, double width, double height) {
        // rectangular base for the outlet
        Rectangle2D.Double base = new Rectangle2D.Double(
            x,
            y + height,
            width,
            height);

        double plugRadius = width / 2;
        double socketX = x+width/4;
        double socketY = y+height;
        // topmost socket of the outlet
        Ellipse2D.Double topSocket = new Ellipse2D.Double(
            socketX, socketY+height/8, plugRadius, plugRadius);

        // bottommost socket of the outlet
        Ellipse2D.Double bottomSocket = new Ellipse2D.Double(
            socketX, socketY+height/2, plugRadius, plugRadius);

        // for the leftmost prong on top
        Line2D.Double topLeftHole = new Line2D.Double(
            socketX+plugRadius*2/6, // begin x
            socketY+plugRadius*7/8, // begin y
            socketX+plugRadius*2/6, // end x
            socketY+plugRadius*1/2); // end y

        // for the rightmost prong on top
        Line2D.Double topRightHole = new Line2D.Double(
            socketX+plugRadius*4/6, // begin x
            socketY+plugRadius*7/8, // begin y
            socketX+plugRadius*4/6, // end ex
            socketY+plugRadius*1/2); // end y

        // for the leftmost prong on bottom
        Line2D.Double bottomLeftHole = new Line2D.Double(
            socketX+plugRadius*2/6, // begin x
            socketY+height/2+plugRadius*1/2, // begin y
            socketX+plugRadius*2/6, // end x
            socketY+height/2+plugRadius*1/8); // end y

        // for the rightmost prong on bottom
        Line2D.Double bottomRightHole = new Line2D.Double(
            socketX+plugRadius*4/6, // begin x
            socketY+height/2+plugRadius*1/2, // begin y
            socketX+plugRadius*4/6, // end x
            socketY+height/2+plugRadius*1/8); // end y

        GeneralPath outlet = this.get();
        outlet.append(base, false);
        outlet.append(topSocket, false);
        outlet.append(bottomSocket, false);
        outlet.append(topLeftHole, false);
        outlet.append(topRightHole, false);
        outlet.append(bottomLeftHole, false);
        outlet.append(bottomRightHole, false);
    }

}


text:
<?php
namespace Concrete\Controller\Backend\UserInterface;

use Concrete\Controller\Backend\UserInterface;
use Concrete\Core\Legacy\TaskPermission;
use Concrete\Core\Marketplace\Marketplace;
use Concrete\Core\Marketplace\RemoteItem;

abstract class MarketplaceItem extends UserInterface
{

    protected $marketplace;
    protected $item;

    public function __construct()
    {
        parent::__construct();
        $this->marketplace = Marketplace::getInstance();
        $this->item = RemoteItem::getByID($this->request->query->get('mpID'));
    }

    protected function canAccess()
    {
        $tp = new TaskPermission();
        return $this->marketplace->isConnected() && $tp->canInstallPackages() && is_object($this->item);
    }

}


text:
layout: post
title: Python 常用资源
category: 资源
tags: Python
keywords: Python
description:
---

## 常用代码

### 遍历对象
    for key in a.__dict__:
        print key,':',a.__dict__[key]

### 调试方法
    assert False   //引发异常,观察错误界面
    import logging
    logging.info('')  //写日志

### 获得当前时间
    #时间戳
    time.time()
    #日期时间
    time.ctime()
    #iso时间
    datetime.fromtimestamp(time.time()).isoformat()
    #固定格式
    time.strftime('%Y-%m-%d',time.localtime(time.time()))
### 日期到时间戳
    dateC=datetime.datetime(2010,6,6,8,14,59)
    timestamp=time.mktime(dateC.timetuple())
### 时间戳到日期
    ltime=time.localtime(1237515355.0)
    timeStr=time.strftime("%Y-%m-%d %H:%M:%S", ltime)
### 之后的包从绝对位置导入
    from __future__ import absolute_import

### 3.5.0 Exceptions
    BaseException
     +-- SystemExit
     +-- KeyboardInterrupt
     +-- GeneratorExit
     +-- Exception
          +-- StopIteration
          +-- StopAsyncIteration
          +-- ArithmeticError
          |    +-- FloatingPointError
          |    +-- OverflowError
          |    +-- ZeroDivisionError
          +-- AssertionError
          +-- AttributeError
          +-- BufferError
          +-- EOFError
          +-- ImportError
          +-- LookupError
          |    +-- IndexError
          |    +-- KeyError
          +-- MemoryError
          +-- NameError
          |    +-- UnboundLocalError
          +-- OSError
          |    +-- BlockingIOError
          |    +-- ChildProcessError
          |    +-- ConnectionError
          |    |    +-- BrokenPipeError
          |    |    +-- ConnectionAbortedError
          |    |    +-- ConnectionRefusedError
          |    |    +-- ConnectionResetError
          |    +-- FileExistsError
          |    +-- FileNotFoundError
          |    +-- InterruptedError
          |    +-- IsADirectoryError
          |    +-- NotADirectoryError
          |    +-- PermissionError
          |    +-- ProcessLookupError
          |    +-- TimeoutError
          +-- ReferenceError
          +-- RuntimeError
          |    +-- NotImplementedError
          |    +-- RecursionError
          +-- SyntaxError
          |    +-- IndentationError
          |         +-- TabError
          +-- SystemError
          +-- TypeError
          +-- ValueError
          |    +-- UnicodeError
          |         +-- UnicodeDecodeError
          |         +-- UnicodeEncodeError
          |         +-- UnicodeTranslateError
          +-- Warning
               +-- DeprecationWarning
               +-- PendingDeprecationWarning
               +-- RuntimeWarning
               +-- SyntaxWarning
               +-- UserWarning
               +-- FutureWarning
               +-- ImportWarning
               +-- UnicodeWarning
               +-- BytesWarning
               +-- ResourceWarning


text:
'''
This is the setup script for cxfreeze

cxfreeze does not support pkg_resource, to compile,
please modify chainer to hardcode version name and remove pkg_resources

track cxfreeze branch https://github.com/grahamrjuk/cx_Freeze/tree/process_import
for process support

Process.pyc is to be renamed to process.pyc

cupy testing has to be modified to prevent pkg_resources require function
'''
#cx_freeze Dependencies
import sys

#Post-process
import os
import shutil

from cx_Freeze import setup, Executable
sys.path.append('./cgi-bin/paint_x2_unet')
sys.path.append('./cgi-bin/helpers')

# Dependencies fine tuning

MODS = [
    'cupy',
    'chainer',
    'numpy.core._methods', 'numpy.lib.format',
    'cgi_exe',
    'platformAdapter',
    "appdirs",
    "packaging.requirements"
]
BUILD_OPTIONS = {"packages": ["os"], "excludes": ["tkinter"], 'includes': MODS}

# GUI applications require a different base on Windows (the default is for a console application).
BASE = None
#if sys.platform == "win32":
#    base = "Win32GUI"

setup(
    name="PaintsChainer",
    version="0.1",
    description="PaintsChainer Executable Version!",
    options={"build_exe": BUILD_OPTIONS},
    executables=[Executable("server.py", base=BASE)]
)

#POST building patching
def copytree(src, dst, symlinks=False, ignore=None):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        if os.path.isdir(s):
            shutil.copytree(s, d, symlinks, ignore)
        else:
            shutil.copy2(s, d)

v = sys.version_info
os.chdir("./build/exe.win-amd64-"+str(v[0])+"."+str(v[1])+"/")
#todo: other platform path

undetected_dirs = ["wPaint", "models", "images","fonts","css"]
for directory in undetected_dirs:
    try:
        shutil.copytree(os.getcwd()+"/../../"+directory, os.getcwd()+"/"+directory)
    except:
        print("Folder is created before.")

undetected_files = [
    "index.html",
    "index_ja.html",
    "index_zh.html",
    "index_zh-TW.html",
    "howto.html",
    "howto_ja.html",
    "howto_zh.html",
    "howto_zh-TW.html",
    "paints_chainer.js",
    "manifest.json",
    "main.css",
    "LICENSE",
    "browserconfig.xml",
    "run_dependency_test.bat",
    "run_exe.bat"
]
for file in undetected_files:
    shutil.copyfile(os.getcwd()+"/../../"+file, os.getcwd()+"/"+file)

os.rename("multiprocessing/Process.pyc", "multiprocessing/process.pyc")

print("All Done.")


text:
package exnihilocreatio.util;

import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;

import javax.annotation.Nonnull;

public interface StackInfo {

    String toString();

    @Nonnull
    ItemStack getItemStack();

    boolean hasBlock();

    @Nonnull
    Block getBlock();

    int getMeta();

    @Nonnull
    IBlockState getBlockState();

    boolean isValid();

    NBTTagCompound writeToNBT(NBTTagCompound tag);

    int hashCode();

    /**
     * This is used to check if the contents equals the objects, based on what the object is
     * @param obj The object to check
     * @return Returns true if the output ItemStacks match
     */
    @Override
    boolean equals(Object obj);
}


text:
// Copyright 2022 The Oppia Authors. All Rights Reserved.
//
// 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.

/**
 * @fileoverview Component for state stats modal.
 */

import { Component, Input, OnInit } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { ConfirmOrCancelModal } from 'components/common-layout-directives/common-elements/confirm-or-cancel-modal.component';
import { InteractionCustomizationArgs } from 'interactions/customization-args-defs';
import { RouterService } from 'pages/exploration-editor-page/services/router.service';

import './state-stats-modal.component.css';

interface PieChartOpitons {
  chartAreaWidth: number;
  colors: string[];
  height: number;
  left: number;
  legendPosition: string;
  pieHole: number;
  pieSliceBorderColor: string;
  pieSliceTextStyleColor: string;
  title: string;
  width: number;
}

@Component({
  selector: 'oppia-state-stats-modal',
  templateUrl: './state-stats-modal.component.html'
})
export class StateStatsModalComponent
   extends ConfirmOrCancelModal implements OnInit {
  // These properties are initialized using Angular lifecycle hooks
  // and we need to do non-null assertion. For more information, see
  // https://github.com/oppia/oppia/wiki/Guide-on-defining-types#ts-7-1
  @Input() visualizationsInfo!: {
    data: string;
    options: string;
    id: string;
    addressed_info_is_supported: boolean;
  } [];

  @Input() interactionArgs!: InteractionCustomizationArgs;
  @Input() stateName!: string;
  @Input() stateStats!: {
    usefulFeedbackCount: number;
    totalAnswersCount: number;
    numTimesSolutionViewed: number;
    totalHitCount: number;
    numCompletions: number;
  };

  solutionUsagePieChartOptions!: PieChartOpitons;
  answerFeedbackPieChartOptions!: PieChartOpitons;
  answerFeedbackPieChartData!: (string[] | [string, number])[];
  solutionUsagePieChartData!: (string[] | [string, number])[];
  totalAnswersCount!: number;
  usefulFeedbackCount!: number;
  numTimesSolutionViewed!: number;
  numEnters!: number;
  numQuits!: number;
  hasExplorationBeenAnswered!: boolean;

  constructor(
     private ngbActiveModal: NgbActiveModal,
     private routerService: RouterService,
  ) {
    super(ngbActiveModal);
  }

  navigateToStateEditor(): void {
    this.cancel();
    this.routerService.navigateToMainTab(this.stateName);
  }

  makeCompletionRatePieChartOptions(title: string): PieChartOpitons {
    return {
      left: 20,
      pieHole: 0.6,
      pieSliceTextStyleColor: 'black',
      pieSliceBorderColor: 'black',
      chartAreaWidth: 240,
      colors: ['#d8d8d8', '#008808', 'blue'],
      height: 270,
      legendPosition: 'right',
      title: title,
      width: 240
    };
  }

  ngOnInit(): void {
    this.numTimesSolutionViewed = this.stateStats.numTimesSolutionViewed;
    this.totalAnswersCount = this.stateStats.totalAnswersCount;
    this.usefulFeedbackCount = this.stateStats.usefulFeedbackCount;

    this.hasExplorationBeenAnswered = this.totalAnswersCount > 0;
    this.numEnters = this.stateStats.totalHitCount;
    this.numQuits = (
      this.stateStats.totalHitCount - this.stateStats.numCompletions);

    this.answerFeedbackPieChartOptions = (
      this.makeCompletionRatePieChartOptions('Answer feedback statistics'));
    this.solutionUsagePieChartOptions = (
      this.makeCompletionRatePieChartOptions('Solution usage statistics'));

    this.answerFeedbackPieChartData = [
      ['Type', 'Number'],
      ['Default feedback', this.totalAnswersCount - this.usefulFeedbackCount],
      ['Specific feedback', this.usefulFeedbackCount],
    ];

    this.solutionUsagePieChartData = [
      ['Type', 'Number'],
      ['Solutions used to answer', this.numTimesSolutionViewed],
      ['Solutions not used',
        this.totalAnswersCount - this.numTimesSolutionViewed]
    ];
  }
}


text:
'use strict'

const keys = {
  kChildren: Symbol('fastify.children'),
  kBodyLimit: Symbol('fastify.bodyLimit'),
  kRoutePrefix: Symbol('fastify.routePrefix'),
  kLogLevel: Symbol('fastify.logLevel'),
  kLogSerializers: Symbol('fastify.logSerializers'),
  kHooks: Symbol('fastify.hooks'),
  kSchemas: Symbol('fastify.schemas'),
  kSchemaCompiler: Symbol('fastify.schemaCompiler'),
  kSchemaResolver: Symbol('fastify.schemaRefResolver'),
  kReplySerializerDefault: Symbol('fastify.replySerializerDefault'),
  kContentTypeParser: Symbol('fastify.contentTypeParser'),
  kReply: Symbol('fastify.Reply'),
  kRequest: Symbol('fastify.Request'),
  kMiddlewares: Symbol('fastify.middlewares'),
  kCanSetNotFoundHandler: Symbol('fastify.canSetNotFoundHandler'),
  kFourOhFour: Symbol('fastify.404'),
  kFourOhFourLevelInstance: Symbol('fastify.404LogLevelInstance'),
  kFourOhFourContext: Symbol('fastify.404ContextKey'),
  kDefaultJsonParse: Symbol('fastify.defaultJSONParse'),
  kReplySerializer: Symbol('fastify.reply.serializer'),
  kReplyIsError: Symbol('fastify.reply.isError'),
  kReplyHeaders: Symbol('fastify.reply.headers'),
  kReplyHasStatusCode: Symbol('fastify.reply.hasStatusCode'),
  kReplySent: Symbol('fastify.reply.sent'),
  kReplySentOverwritten: Symbol('fastify.reply.sentOverwritten'),
  kReplyStartTime: Symbol('fastify.reply.startTime'),
  kReplyErrorHandlerCalled: Symbol('fastify.reply.errorHandlerCalled'),
  kReplyIsRunningOnErrorHook: Symbol('fastify.reply.isRunningOnErrorHook'),
  kState: Symbol('fastify.state'),
  kOptions: Symbol('fastify.options'),
  kGlobalHooks: Symbol('fastify.globalHooks'),
  kDisableRequestLogging: Symbol('fastify.disableRequestLogging'),
  kPluginNameChain: Symbol('fastify.pluginNameChain')
}

module.exports = keys


text:
package com.gymnast.view.home.view;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import com.gymnast.R;
import com.gymnast.view.ImmersiveActivity;
import com.gymnast.view.home.HomeActivity;

/**
 * Created by Cymbi on 2016/9/7.
 */
public class WelcomeActivity extends ImmersiveActivity {
    private boolean isFirstIn = false;
    private static final int TIME = 2000;
    private static final int GO_HOME = 1000;
    private static final int GO_GUIDE = 1001;
    private Handler mHandler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case GO_HOME:
                    goHome();
                    break;
                case GO_GUIDE:
                    goGuide();
                    break;
            }
        };
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_boot);
        init();
    }
    private void init(){
        SharedPreferences perPreferences = getSharedPreferences("Welcome", MODE_PRIVATE);
        isFirstIn = perPreferences.getBoolean("isFirstIn", true);
        if (!isFirstIn) {
            mHandler.sendEmptyMessageDelayed(GO_HOME, TIME);
        }else{
            mHandler.sendEmptyMessageDelayed(GO_GUIDE, TIME);
            SharedPreferences.Editor editor = perPreferences.edit();
            editor.putBoolean("isFirstIn", false);
            editor.commit();
        }
    }
    private void goHome(){
        Intent i = new Intent(WelcomeActivity.this,HomeActivity.class);
        startActivity(i);
        finish();
    }
    private void goGuide(){
        Intent i = new Intent(WelcomeActivity.this,GuideActivity.class);
        startActivity(i);
        finish();
    }
}


text:
@startDocuBlock PutApiQueryCacheProperties
@brief changes the configuration for the AQL query results cache

@RESTHEADER{PUT /_api/query-cache/properties, Globally adjusts the AQL query results cache properties, replaceProperties:QueryCache}

@RESTDESCRIPTION
After the properties have been changed, the current set of properties will
be returned in the HTTP response.

Note: changing the properties may invalidate all results in the cache.
The global properties for AQL query cache.
The properties need to be passed in the attribute *properties* in the body
of the HTTP request. *properties* needs to be a JSON object with the following
properties:

@RESTBODYPARAM{mode,string,optional,string}
 the mode the AQL query cache should operate in. Possible values are *off*, *on* or *demand*.

@RESTBODYPARAM{maxResults,integer,optional,int64}
the maximum number of query results that will be stored per database-specific cache.

@RESTBODYPARAM{maxResultsSize,integer,optional,int64}
the maximum cumulated size of query results that will be stored per database-specific cache.

@RESTBODYPARAM{maxEntrySize,integer,optional,int64}
the maximum individual size of query results that will be stored per database-specific cache.

@RESTBODYPARAM{includeSystem,boolean,optional,}
whether or not to store results of queries that involve system collections.

@RESTRETURNCODES

@RESTRETURNCODE{200}
Is returned if the properties were changed successfully.

@RESTRETURNCODE{400}
The server will respond with *HTTP 400* in case of a malformed request,

@endDocuBlock


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows;

namespace LedBadgeLib
{
    public class WpfVisual: IBadgeVisual
    {
        public WpfVisual(BadgeCaps device, FrameworkElement element, int defaultWidth = -1, int defaultHeight = -1, bool dither = false, bool enableBlend = false)
        {
            if(defaultWidth <= 0) { defaultWidth = device.Width; }
            if(defaultHeight <= 0) { defaultHeight = device.Height; }

            Element = element;
            Element.Measure(new Size(defaultWidth, defaultHeight));
            Element.Arrange(new Rect(0, 0, defaultWidth, defaultHeight));

            ClipWidth = (int)Math.Ceiling(Element.ActualWidth);
            ClipHeight = (int)Math.Ceiling(Element.ActualHeight);

            Dither = dither;
            EnableBlend = enableBlend;

            m_cachedIntermediate = new BadgeRenderTarget(ClipWidth, ClipHeight, PixelFormat.TwoBits);
            m_renderTarget = new RenderTargetBitmap(ClipWidth, ClipHeight, 96, 96, PixelFormats.Pbgra32);

            Update(0); // To avoid remeasuring on a background thread
            UpdateCachedImage();
        }

        public int RenderX { get; set; }
        public int RenderY { get; set; }
        public int ClipX { get; set; }
        public int ClipY { get; set; }
        public int ClipWidth { get; set; }
        public int ClipHeight { get; set; }

        public bool Dither { get; set; }
        public bool EnableBlend { get; set; }

        public FrameworkElement Element
        {
            get { return m_element; }
            set
            {
                if(m_element != value)
                {
                    m_element = value;
                    DirtyVisual();
                }
            }
        }

        public void DirtyVisual()
        {
            m_visualLayoutDirty = true;
            m_visualRenderDirty = true;
        }

        public void Update(float dt)
        {
            if(m_visualLayoutDirty)
            {
                m_visualLayoutDirty = false;

                Element.Measure(new Size(ClipWidth, ClipHeight));
                Element.Arrange(new Rect(0, 0, ClipWidth, ClipHeight));
            }
        }

        public void Render(BadgeRenderTarget rt, int parentRenderX, int parentRenderY)
        {
            UpdateCachedImage();

            if(EnableBlend)
            {
                BadgeImage.Blit(
                    rt.IntermediateImage, rt.IntermediateStride, rt.WidthInPixels, rt.Height,
                    m_cachedIntermediate.IntermediateImage, m_alphaMask, m_cachedIntermediate.IntermediateStride, m_cachedIntermediate.WidthInPixels, m_cachedIntermediate.Height,
                    parentRenderX + RenderX, parentRenderY + RenderY, ClipX, ClipY, ClipWidth, ClipHeight);
            }
            else
            {
                BadgeImage.Blit(
                    rt.IntermediateImage, rt.IntermediateStride, rt.WidthInPixels, rt.Height,
                    m_cachedIntermediate.IntermediateImage, m_cachedIntermediate.IntermediateStride, m_cachedIntermediate.WidthInPixels, m_cachedIntermediate.Height,
                    parentRenderX + RenderX, parentRenderY + RenderY, ClipX, ClipY, ClipWidth, ClipHeight);
            }
        }

        private void UpdateCachedImage()
        {
            if(m_visualRenderDirty)
            {
                m_visualRenderDirty = false;

                m_renderTarget.Clear();
                m_renderTarget.Render(Element);

                if(EnableBlend)
                {
                    if(m_alphaMask == null)
                    {
                        m_alphaMask = new byte[m_cachedIntermediate.IntermediateImage.Length];
                    }
                    WPF.Read32BitImage(m_cachedIntermediate.IntermediateImage, m_alphaMask, m_renderTarget, 0, 0, m_cachedIntermediate.IntermediateStride, m_cachedIntermediate.WidthInPixels, m_cachedIntermediate.Height);
                }
                else
                {
                    m_alphaMask = null;
                    WPF.Read32BitImage(m_cachedIntermediate.IntermediateImage, m_renderTarget, 0, 0, m_cachedIntermediate.IntermediateStride, m_cachedIntermediate.WidthInPixels, m_cachedIntermediate.Height);
                    if(Dither)
                    {
                        m_cachedIntermediate.DitherImage();
                    }
                }
            }
        }

        bool m_visualRenderDirty;
        bool m_visualLayoutDirty;
        FrameworkElement m_element;
        RenderTargetBitmap m_renderTarget;
        BadgeRenderTarget m_cachedIntermediate;
        byte[] m_alphaMask;
    }
}


text:
Array Filler
------------

This is just a simple benchmark that I used to compare how a couple of languages
dealt with arrays. It fills an array in a couple of different ways and then
checks for the content of the array in a subsequent function call.

Versions for Dart and JavaScript can be found in the docs directory.


text:
"""
This provides connectivity to a message broker supporting the STOMP protocol. Both protocol
versions 1.0 and 1.1 are supported.

See the project page for more information.

Author: Jason R Briggs
License: http://www.apache.org/licenses/LICENSE-2.0
Project Page: http://code.google.com/p/stomppy
"""

import os
import sys
sys.path.insert(0, os.path.split(__file__)[0])

import connect, listener, exception

__version__ = (3, 1, 3)
Connection = connect.Connection
ConnectionListener = listener.ConnectionListener
StatsListener = listener.StatsListener


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.compute.model;

/**
 * Model definition for InstanceGroupManagerAutoHealingPolicyAutoHealingTriggers.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class InstanceGroupManagerAutoHealingPolicyAutoHealingTriggers extends com.google.api.client.json.GenericJson {

  /**
   * If you have configured an application-based health check for the group, this field controls
   * whether to trigger VM autohealing based on a failed health check. Valid values are: - ON
   * (default): The group recreates running VMs that fail the application-based health check. - OFF:
   * When set to OFF, you can still observe instance health state, but the group does not recreate
   * VMs that fail the application-based health check. This is useful for troubleshooting and
   * setting up your health check configuration.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String onHealthCheck;

  /**
   * If you have configured an application-based health check for the group, this field controls
   * whether to trigger VM autohealing based on a failed health check. Valid values are: - ON
   * (default): The group recreates running VMs that fail the application-based health check. - OFF:
   * When set to OFF, you can still observe instance health state, but the group does not recreate
   * VMs that fail the application-based health check. This is useful for troubleshooting and
   * setting up your health check configuration.
   * @return value or {@code null} for none
   */
  public java.lang.String getOnHealthCheck() {
    return onHealthCheck;
  }

  /**
   * If you have configured an application-based health check for the group, this field controls
   * whether to trigger VM autohealing based on a failed health check. Valid values are: - ON
   * (default): The group recreates running VMs that fail the application-based health check. - OFF:
   * When set to OFF, you can still observe instance health state, but the group does not recreate
   * VMs that fail the application-based health check. This is useful for troubleshooting and
   * setting up your health check configuration.
   * @param onHealthCheck onHealthCheck or {@code null} for none
   */
  public InstanceGroupManagerAutoHealingPolicyAutoHealingTriggers setOnHealthCheck(java.lang.String onHealthCheck) {
    this.onHealthCheck = onHealthCheck;
    return this;
  }

  @Override
  public InstanceGroupManagerAutoHealingPolicyAutoHealingTriggers set(String fieldName, Object value) {
    return (InstanceGroupManagerAutoHealingPolicyAutoHealingTriggers) super.set(fieldName, value);
  }

  @Override
  public InstanceGroupManagerAutoHealingPolicyAutoHealingTriggers clone() {
    return (InstanceGroupManagerAutoHealingPolicyAutoHealingTriggers) super.clone();
  }

}


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

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

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

# Distribution archive of Zeppelin project #

Zeppelin is distributed as a single gzip archive with the following structure:

```
zeppelin
 ├── bin
 │   ├── zeppelin.sh
 │   └── seppelin-deamon.sh
 ├── lib
 ├── conf
 ├── zan-repo
 │    ├── txt.wordcount
 │    ├── vis.bubble
 │    ├── vis.gchart
 │    ├── ml.something
 │    └── ...
 ├── zeppelin-server-<verion>.jar
 ├── zeppelin-web-<verion>.war
 └── zeppelin-cli-<verion>.jar

```

We use maven-assembly-pugin to build it, see distribution.xml for details

**IMPORTANT:** _/lib_ subdirectory contains all transitive dependencies of the zeppelin-distribution module,
automatically resolved by maven, except for explicitly excluded _server_, _web_ and _cli_ zeppelin sub-modules.


text:
#include "UGC.h"
#include "SMCDataSource.h"
#include "SMCDataset.h"

#include "SMCDsOperate.h"
#include "SMCStringHelper.h"

SMCDataSource::SMCDataSource()
{
	m_pDataSource = NULL;
}

SMCDataSource::~SMCDataSource()
{
	m_pDataSource = NULL;
}

_tstring SMCDataSource::GetSchema() const
{
	if(m_pDataSource != NULL)
	{
		UGC::UGDataSource* pDatasource = (UGC::UGDataSource*)m_pDataSource;
		return UNICODE_STRING(pDatasource->GetSchema().Cstr());
	}
	else
	{
		return _T("");
	}
}

bool SMCDataSource::IsOpen() const
{
	if(m_pDataSource != NULL)
	{
		UGC::UGDataSource* pDatasource = (UGC::UGDataSource*)m_pDataSource;
		return pDatasource->IsOpen();
	}
	else
	{
		return false;
	}
}

_tstring SMCDataSource::GetName() const
{
	if(m_pDataSource != NULL)
	{
		UGC::UGDataSource* pDatasource = (UGC::UGDataSource*)m_pDataSource;
		return UNICODE_STRING(pDatasource->GetName().Cstr());
	}
	else
	{
		return _T("");
	}
}

_tstring SMCDataSource::GetEngineName() const
{
	if(m_pDataSource != NULL)
	{
		UGC::UGDataSource* pDatasource = (UGC::UGDataSource*)m_pDataSource;
		return UNICODE_STRING(pDatasource->GetEngineName().Cstr());
	}
	else
	{
		return _T("");
	}
}

_tstring SMCDataSource::GetUnoccupiedDatasetName(const _tstring& strDatasetName)
{
	if(m_pDataSource != NULL)
	{
		UGC::UGDataSource* pDatasource = (UGC::UGDataSource*)m_pDataSource;
		_tstring strDatasetname = UNICODE_STRING((pDatasource->GetUnoccupiedDatasetName(ASCII_STRING(strDatasetName).c_str())).Cstr());
		return strDatasetname;
	}
	else
	{
		return _T("");
	}
}

bool SMCDataSource::IsModified()
{
	if(m_pDataSource != NULL)
	{
		UGC::UGDataSource* pDatasource = (UGC::UGDataSource*)m_pDataSource;
		return pDatasource->IsModified();
	}
	else
	{
		return false;
	}
}

void SMCDataSource::SetModifiedFlag(bool bModified)
{
	if(m_pDataSource != NULL)
	{
		UGC::UGDataSource* pDatasource = (UGC::UGDataSource*)m_pDataSource;
		return pDatasource->SetModifiedFlag(bModified);
	}
	else
	{
		return;
	}
}

int SMCDataSource::GetDatasetCount() const
{
	if(m_pDataSource != NULL)
	{
		UGC::UGDataSource* pDatasource = (UGC::UGDataSource*)m_pDataSource;
		return pDatasource->GetDatasetCount();
	}
	else
	{
		return -1;
	}
}

void SMCDataSource::SetConnection(const SMCDsConnection& dsconn)
{

	if(m_pDataSource != NULL)
	{
		UGC::UGDataSource* pDatasource =(UGC::UGDataSource*)m_pDataSource;
		UGC::UGDsConnection &conn		  =	pDatasource->GetConnectionInfo();

		conn.m_nEngineType  = (UGC::UGEngineType)conn.m_nEngineType;
		conn.m_bReadOnly    =	dsconn.m_bReadOnly;
		conn.m_bTransacted  =	dsconn.m_bTransacted;
		conn.m_bExclusive   =	dsconn.m_bExclusive;
		conn.m_bEncrypt     =	dsconn.m_bEncrypt;
		conn.m_strDatabase  =	ASCII_STRING(dsconn.m_strDatabase).c_str();
		conn.m_strDriver    =	ASCII_STRING(dsconn.m_strDriver).c_str();
		conn.m_strServer    =	ASCII_STRING(dsconn.m_strServer).c_str();
		conn.m_strUser      =	ASCII_STRING(dsconn.m_strUser).c_str();
		conn.m_strPassword  =	ASCII_STRING(dsconn.m_strPassword).c_str();
		conn.m_strAlias     =	ASCII_STRING(dsconn.m_strAlias).c_str();
		conn.m_bAutoConnect =	dsconn.m_bAutoConnect;
//		conn.m_nConnMaxNum  =	dsconn.m_nConnMaxNum;
//		conn.m_nConnMinNum  =	dsconn.m_nConnMinNum;
//		conn.m_nConnIncNum  =	dsconn.m_nConnIncNum;
	}
	else
	{
		return;
	}
}

bool SMCDataSource::CreateDataSource(SMCDsConnection::SMEngineType nEngineType)
{
	m_pDataSource = UGC::UGDataSourceManager::CreateDataSource((UGC::UGEngineType)nEngineType);
	if(m_pDataSource != NULL)
	{
		return true;
	}
	else
	{
		return false;
	}
}

bool SMCDataSource::GetDataset(int nIndex, SMCDataset *&pDdataset) const
{
	if(m_pDataSource != NULL)
	{
		UGC::UGDataSource* pDatasource = (UGC::UGDataSource*)m_pDataSource;
		(UGC::UGDataset*&)(pDdataset->m_pDataset) = pDatasource->GetDataset(nIndex);
		if(pDdataset->m_pDataset != NULL)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
}

bool SMCDataSource::GetDataset(const _tstring& strDatasetName, SMCDataset *&pDdataset) const
{
	if(m_pDataSource != NULL)
	{
		UGC::UGDataSource* pDatasource = (UGC::UGDataSource*)m_pDataSource;
		UGC::UGString strDtsetName = ASCII_STRING(strDatasetName).c_str();
		(UGC::UGDataset*&)(pDdataset->m_pDataset) = pDatasource->GetDataset(strDtsetName);
		if(pDdataset->m_pDataset != NULL)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
}

bool SMCDataSource::Create()
{
	if(m_pDataSource != NULL)
	{
		UGC::UGDataSource *pDatasource = (UGC::UGDataSource *)m_pDataSource;
		return pDatasource->Create();
	}
	else
	{
		return false;
	}
}

bool SMCDataSource::Open()
{
	if(m_pDataSource != NULL)
	{
		UGC::UGDataSource *pDatasource = (UGC::UGDataSource *)m_pDataSource;
		return pDatasource->Open();
	}
	else
	{
		return false;
	}
}

void SMCDataSource::Close()
{
	if(m_pDataSource != NULL)
	{
		UGC::UGDataSource *pDatasource = (UGC::UGDataSource *)m_pDataSource;
		return pDatasource->Close();
	}
	else
	{
		return;
	}
}

bool SMCDataSource::SaveInfo()
{
	if(m_pDataSource != NULL)
	{
		UGC::UGDataSource *pDatasource = (UGC::UGDataSource *)m_pDataSource;
		return pDatasource->SaveInfo();
	}
	else
	{
		return false;
	}
}

bool SMCDataSource::DeleteDataset(const _tstring& strName)
{
	if(m_pDataSource != NULL)
	{
		UGC::UGDataSource *pDatasource = (UGC::UGDataSource *)m_pDataSource;
		UGC::UGString strDsetName = ASCII_STRING(strName).c_str();
		return pDatasource->DeleteDataset(strDsetName);
	}
	else
	{
		return false;
	}
}

bool SMCDataSource::IsConnected()
{
	if(m_pDataSource != NULL)
	{
		UGC::UGDataSource *pDatasource = (UGC::UGDataSource *)m_pDataSource;
		return pDatasource->IsConnected();
	}
	else
	{
		return false;
	}
}

bool SMCDataSource::ChangePassword(const _tstring& strNewPassword)
{
	if(m_pDataSource != NULL)
	{
		UGC::UGDataSource *pDatasource = (UGC::UGDataSource *)m_pDataSource;
		UGC::UGString strNewPwd = UGC::UGString(ASCII_STRING(strNewPassword).c_str());
		return pDatasource->ChangePassword(strNewPwd);
	}
	else
	{
		return false;
	}
}

bool SMCDataSource::Connect()
{
	if(m_pDataSource != NULL)
	{
		UGC::UGDataSource *pDatasource = (UGC::UGDataSource *)m_pDataSource;
		return pDatasource->Connect();
	}
	else
	{
		return false;
	}
}

bool SMCDataSource::OpenDataSource(SMCDataSource &sdbDs, _tstring strConnection)
{
	std::vector<_tstring> strName = SMCStringHelper::Explode(strConnection, _T(";"));
	std::map<_tstring, _tstring> connInfo;
	SMCStringHelper::ProKeyAndVal(strName, connInfo);

	SMCDsConnection::SMEngineType nEngine;

	_tstring strEngineName = connInfo[SMC_CONNECTION_TYPE];
	nEngine = EngNameToEngType(strEngineName);

	//´´½¨Êý¾ÝÔ´
	bool bCreDs = sdbDs.CreateDataSource(nEngine);
	if(!bCreDs)
	{
		return false;
	}

	UGC::UGDsConnection &conn = ((UGC::UGDataSource *&)(sdbDs.m_pDataSource))->GetConnectionInfo();
	//Àà±ðÅжÏ
	if(strEngineName == _T("sdb"))
	{
		conn.m_strServer	  = ASCII_STRING(connInfo[SMC_CONNECTION_FILE]).c_str();
		conn.m_strUser		  = ASCII_STRING(connInfo[SMC_CONNECTION_USER]).c_str();
		conn.m_strPassword    = ASCII_STRING(connInfo[SMC_CONNECTION_PWD]).c_str();
	}
	else if(strEngineName == _T("ora") || strEngineName == _T("sql server"))
	{
		conn.m_strDatabase    = ASCII_STRING(connInfo[SMC_CONNECTION_SERVER]).c_str();
		conn.m_strDatabase    = ASCII_STRING(connInfo[SMC_CONNECTION_DATABASE]).c_str();
		conn.m_strUser		  = ASCII_STRING(connInfo[SMC_CONNECTION_USER]).c_str();
		conn.m_strPassword    = ASCII_STRING(connInfo[SMC_CONNECTION_PWD]).c_str();
	}
	else//Ä¿Ç°²»Ö§³ÖµÄÒýÇæÀàÐÍ
	{
		return false;
	}
	//¶ÔÊý¾ÝÔ´½øÐдò¿ª
	if(sdbDs.Open())
	{
		return true;
	}
	else
	{
		return false;
	}
}

bool SMCDataSource::OpenOraDS()
{
	UGC::UGDataSource *pds;
	pds = UGC::UGDataSourceManager::CreateDataSource(UGC::OraclePlus);

	UGC::UGDsConnection &conn = pds->GetConnectionInfo();
	conn.m_bAutoConnect = true;
	conn.m_strDatabase = "majun2";
	conn.m_strServer   = "UGCES";
	conn.m_strUser	   = "majun2";
	conn.m_strPassword = "majun2";
	bool bOpen = pds->Open();
	return true;
}


text:
package com.amazonaws.services.servicecatalog.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.servicecatalog.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * PrincipalMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class PrincipalMarshaller {

    private static final MarshallingInfo<String> PRINCIPALARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("PrincipalARN").build();
    private static final MarshallingInfo<String> PRINCIPALTYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("PrincipalType").build();

    private static final PrincipalMarshaller instance = new PrincipalMarshaller();

    public static PrincipalMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(Principal principal, ProtocolMarshaller protocolMarshaller) {

        if (principal == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(principal.getPrincipalARN(), PRINCIPALARN_BINDING);
            protocolMarshaller.marshall(principal.getPrincipalType(), PRINCIPALTYPE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
namespace ash {

namespace {

// Predefined padding for the icon used in this tray. These are to be set to the
// border of the icon, depending on the current |shelf_alignment()|.
const int kHorizontalShelfHorizontalPadding = 8;
const int kHorizontalShelfVerticalPadding = 4;
const int kVerticalShelfHorizontalPadding = 2;
const int kVerticalShelfVerticalPadding = 5;

// Width of the palette itself (dp).
const int kPaletteWidth = 332;

// Padding at the top/bottom of the palette (dp).
const int kPalettePaddingOnTop = 4;
const int kPalettePaddingOnBottom = 4;

// Size of icon in the shelf (dp).
const int kShelfIconSize = 18;

// Vertical margin around the title view elements so that the title view height
// matches kMenuButtonSize.
const int kVerticalMarginAroundTitleView = 1;

// Margins between the title view and the edges around it (dp).
const int kPaddingBetweenTitleAndLeftEdge = 12;
const int kPaddingBetweenTitleAndSeparator = 3;

// The distance between the title, help, and settings button in the title (dp).
const int kHorizontalPaddingBetweenTitleEntries = 2;

// Color of the separator.
const SkColor kPaletteSeparatorColor = SkColorSetARGB(0x1E, 0x00, 0x00, 0x00);

// Returns true if we are in a user session that can show the stylus tools.
bool IsInUserSession() {
  SessionStateDelegate* session_state_delegate =
      WmShell::Get()->GetSessionStateDelegate();
  return !session_state_delegate->IsUserSessionBlocked() &&
         session_state_delegate->GetSessionState() ==
             session_manager::SessionState::ACTIVE &&
         WmShell::Get()->system_tray_delegate()->GetUserLoginStatus() !=
             LoginStatus::KIOSK_APP;
}

// Returns the font used by the title view.
const gfx::FontList& GetTitleFont() {
  // TODO(tdanderson|jdufault): Use TrayPopupItemStyle instead.
  return ui::ResourceBundle::GetSharedInstance().GetFontListWithDelta(
      2, gfx::Font::FontStyle::NORMAL, gfx::Font::Weight::MEDIUM);
}

class TitleView : public views::View, public views::ButtonListener {
 public:
  explicit TitleView(PaletteTray* palette_tray) : palette_tray_(palette_tray) {
    auto* box_layout = new views::BoxLayout(
        views::BoxLayout::kHorizontal, 0, kVerticalMarginAroundTitleView,
        kHorizontalPaddingBetweenTitleEntries);
    SetLayoutManager(box_layout);

    views::Label* text_label =
        new views::Label(l10n_util::GetStringUTF16(IDS_ASH_STYLUS_TOOLS_TITLE));
    text_label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
    text_label->SetFontList(GetTitleFont());
    AddChildView(text_label);
    box_layout->SetFlexForView(text_label, 1);

    gfx::ImageSkia settings_icon =
        gfx::CreateVectorIcon(kSystemMenuSettingsIcon, kMenuIconColor);
    gfx::ImageSkia help_icon =
        gfx::CreateVectorIcon(kSystemMenuHelpIcon, kMenuIconColor);

    help_button_ = new ash::TrayPopupHeaderButton(this, help_icon,
                                                  IDS_ASH_STATUS_TRAY_HELP);
    help_button_->SetTooltipText(
        l10n_util::GetStringUTF16(IDS_ASH_STATUS_TRAY_HELP));
    AddChildView(help_button_);

    settings_button_ = new ash::TrayPopupHeaderButton(
        this, settings_icon, IDS_ASH_STATUS_TRAY_SETTINGS);
    settings_button_->SetTooltipText(
        l10n_util::GetStringUTF16(IDS_ASH_STATUS_TRAY_SETTINGS));
    AddChildView(settings_button_);
  }

  ~TitleView() override {}

 private:
  // views::ButtonListener:
  void ButtonPressed(views::Button* sender, const ui::Event& event) override {
    if (sender == settings_button_) {
      palette_tray_->RecordPaletteOptionsUsage(
          PaletteTrayOptions::PALETTE_SETTINGS_BUTTON);
      WmShell::Get()->system_tray_controller()->ShowPaletteSettings();
      palette_tray_->HidePalette();
    } else if (sender == help_button_) {
      palette_tray_->RecordPaletteOptionsUsage(
          PaletteTrayOptions::PALETTE_HELP_BUTTON);
      WmShell::Get()->system_tray_controller()->ShowPaletteHelp();
      palette_tray_->HidePalette();
    } else {
      NOTREACHED();
    }
  }

  // Unowned pointers to button views so we can determine which button was
  // clicked.
  ash::TrayPopupHeaderButton* settings_button_;
  ash::TrayPopupHeaderButton* help_button_;
  PaletteTray* palette_tray_;

  DISALLOW_COPY_AND_ASSIGN(TitleView);
};

}  // namespace

PaletteTray::PaletteTray(WmShelf* wm_shelf)
    : TrayBackgroundView(wm_shelf),
      palette_tool_manager_(new PaletteToolManager(this)),
      weak_factory_(this) {
  // PaletteTray should only be instantiated if the palette feature is enabled.
  DCHECK(IsPaletteFeatureEnabled());

  PaletteTool::RegisterToolInstances(palette_tool_manager_.get());

  if (MaterialDesignController::IsShelfMaterial()) {
    SetInkDropMode(InkDropMode::ON);
    SetContentsBackground(false);
  } else {
    SetContentsBackground(true);
  }

  SetLayoutManager(new views::FillLayout());
  icon_ = new views::ImageView();
  UpdateTrayIcon();

  SetIconBorderForShelfAlignment();
  tray_container()->AddChildView(icon_);

  WmShell::Get()->AddShellObserver(this);
  WmShell::Get()->GetSessionStateDelegate()->AddSessionStateObserver(this);
  if (WmShell::Get()->palette_delegate()) {
    WmShell::Get()->palette_delegate()->SetStylusStateChangedCallback(
        base::Bind(&PaletteTray::OnStylusStateChanged,
                   weak_factory_.GetWeakPtr()));
  }

  // OnPaletteEnabledPrefChanged will get called with the initial pref value,
  // which will take care of showing the palette.
  palette_enabled_subscription_ =
      WmShell::Get()->palette_delegate()->AddPaletteEnableListener(
          base::Bind(&PaletteTray::OnPaletteEnabledPrefChanged,
                     weak_factory_.GetWeakPtr()));
}

PaletteTray::~PaletteTray() {
  if (bubble_)
    bubble_->bubble_view()->reset_delegate();

  WmShell::Get()->RemoveShellObserver(this);
  WmShell::Get()->GetSessionStateDelegate()->RemoveSessionStateObserver(this);
}

bool PaletteTray::PerformAction(const ui::Event& event) {
  if (bubble_) {
    if (num_actions_in_bubble_ == 0)
      RecordPaletteOptionsUsage(PaletteTrayOptions::PALETTE_CLOSED_NO_ACTION);
    HidePalette();
    return true;
  }

  return ShowPalette();
}

bool PaletteTray::ShowPalette() {
  if (bubble_)
    return false;

  DCHECK(tray_container());

  views::TrayBubbleView::InitParams init_params(GetAnchorAlignment(),
                                                kPaletteWidth, kPaletteWidth);
  init_params.can_activate = true;
  init_params.close_on_deactivate = true;

  DCHECK(tray_container());

  // The views::TrayBubbleView ctor will cause a shelf auto hide update check.
  // Make sure to block auto hiding before that check happens.
  should_block_shelf_auto_hide_ = true;

  // TODO(tdanderson): Refactor into common row layout code.
  // TODO(tdanderson|jdufault): Add material design ripple effects to the menu
  // rows.

  // Create and customize bubble view.
  views::TrayBubbleView* bubble_view =
      views::TrayBubbleView::Create(GetBubbleAnchor(), this, &init_params);
  bubble_view->set_anchor_view_insets(GetBubbleAnchorInsets());
  bubble_view->set_margins(
      gfx::Insets(kPalettePaddingOnTop, 0, kPalettePaddingOnBottom, 0));

  // Add title.
  auto* title_view = new TitleView(this);
  title_view->SetBorder(views::CreateEmptyBorder(
      gfx::Insets(0, kPaddingBetweenTitleAndLeftEdge, 0, 0)));
  bubble_view->AddChildView(title_view);

  // Add horizontal separator.
  views::Separator* separator =
      new views::Separator(views::Separator::HORIZONTAL);
  separator->SetColor(kPaletteSeparatorColor);
  separator->SetBorder(views::CreateEmptyBorder(gfx::Insets(
      kPaddingBetweenTitleAndSeparator, 0, kMenuSeparatorVerticalPadding, 0)));
  bubble_view->AddChildView(separator);

  // Add palette tools.
  // TODO(tdanderson|jdufault): Use SystemMenuButton to get the material design
  // ripples.
  std::vector<PaletteToolView> views = palette_tool_manager_->CreateViews();
  for (const PaletteToolView& view : views)
    bubble_view->AddChildView(view.view);

  // Show the bubble.
  bubble_.reset(new ash::TrayBubbleWrapper(this, bubble_view));
  SetIsActive(true);
  return true;
}

bool PaletteTray::ContainsPointInScreen(const gfx::Point& point) {
  if (icon_ && icon_->GetBoundsInScreen().Contains(point))
    return true;

  return bubble_ && bubble_->bubble_view()->GetBoundsInScreen().Contains(point);
}

void PaletteTray::SessionStateChanged(session_manager::SessionState state) {
  UpdateIconVisibility();
}

void PaletteTray::OnLockStateChanged(bool locked) {
  UpdateIconVisibility();

  // The user can eject the stylus during the lock screen transition, which will
  // open the palette. Make sure to close it if that happens.
  if (locked)
    HidePalette();
}

void PaletteTray::ClickedOutsideBubble() {
  if (num_actions_in_bubble_ == 0)
    RecordPaletteOptionsUsage(PaletteTrayOptions::PALETTE_CLOSED_NO_ACTION);
  HidePalette();
}

base::string16 PaletteTray::GetAccessibleNameForTray() {
  return l10n_util::GetStringUTF16(IDS_ASH_STYLUS_TOOLS_TITLE);
}

void PaletteTray::HideBubbleWithView(const views::TrayBubbleView* bubble_view) {
  if (bubble_->bubble_view() == bubble_view)
    HidePalette();
}

void PaletteTray::BubbleViewDestroyed() {
  palette_tool_manager_->NotifyViewsDestroyed();
  SetIsActive(false);
}

void PaletteTray::OnMouseEnteredView() {}

void PaletteTray::OnMouseExitedView() {}

base::string16 PaletteTray::GetAccessibleNameForBubble() {
  return GetAccessibleNameForTray();
}

void PaletteTray::OnBeforeBubbleWidgetInit(
    views::Widget* anchor_widget,
    views::Widget* bubble_widget,
    views::Widget::InitParams* params) const {
  // Place the bubble in the same root window as |anchor_widget|.
  WmLookup::Get()
      ->GetWindowForWidget(anchor_widget)
      ->GetRootWindowController()
      ->ConfigureWidgetInitParamsForContainer(
          bubble_widget, kShellWindowId_SettingBubbleContainer, params);
}

void PaletteTray::HideBubble(const views::TrayBubbleView* bubble_view) {
  HideBubbleWithView(bubble_view);
}

void PaletteTray::HidePalette() {
  should_block_shelf_auto_hide_ = false;
  is_bubble_auto_opened_ = false;
  num_actions_in_bubble_ = 0;
  bubble_.reset();

  shelf()->UpdateAutoHideState();
}

void PaletteTray::HidePaletteImmediately() {
  if (bubble_)
    bubble_->bubble_widget()->SetVisibilityChangedAnimationsEnabled(false);
  HidePalette();
}

void PaletteTray::RecordPaletteOptionsUsage(PaletteTrayOptions option) {
  DCHECK_NE(option, PaletteTrayOptions::PALETTE_OPTIONS_COUNT);

  if (is_bubble_auto_opened_) {
    UMA_HISTOGRAM_ENUMERATION("Ash.Shelf.Palette.Usage.AutoOpened", option,
                              PaletteTrayOptions::PALETTE_OPTIONS_COUNT);
  } else {
    UMA_HISTOGRAM_ENUMERATION("Ash.Shelf.Palette.Usage", option,
                              PaletteTrayOptions::PALETTE_OPTIONS_COUNT);
  }
}

void PaletteTray::RecordPaletteModeCancellation(PaletteModeCancelType type) {
  if (type == PaletteModeCancelType::PALETTE_MODE_CANCEL_TYPE_COUNT)
    return;

  UMA_HISTOGRAM_ENUMERATION(
      "Ash.Shelf.Palette.ModeCancellation", type,
      PaletteModeCancelType::PALETTE_MODE_CANCEL_TYPE_COUNT);
}

bool PaletteTray::ShouldBlockShelfAutoHide() const {
  return should_block_shelf_auto_hide_;
}

void PaletteTray::OnActiveToolChanged() {
  ++num_actions_in_bubble_;
  UpdateTrayIcon();
}

WmWindow* PaletteTray::GetWindow() {
  return shelf()->GetWindow();
}

void PaletteTray::SetShelfAlignment(ShelfAlignment alignment) {
  if (alignment == shelf_alignment())
    return;

  TrayBackgroundView::SetShelfAlignment(alignment);
  SetIconBorderForShelfAlignment();
}

void PaletteTray::AnchorUpdated() {
  if (bubble_)
    bubble_->bubble_view()->UpdateBubble();
}

void PaletteTray::SetIconBorderForShelfAlignment() {
  // TODO(tdanderson): Ensure PaletteTray follows material design specs. See
  // crbug.com/630464.
  if (IsHorizontalAlignment(shelf_alignment())) {
    icon_->SetBorder(views::CreateEmptyBorder(gfx::Insets(
        kHorizontalShelfVerticalPadding, kHorizontalShelfHorizontalPadding)));
  } else {
    icon_->SetBorder(views::CreateEmptyBorder(gfx::Insets(
        kVerticalShelfVerticalPadding, kVerticalShelfHorizontalPadding)));
  }
}

void PaletteTray::UpdateTrayIcon() {
  icon_->SetImage(CreateVectorIcon(
      palette_tool_manager_->GetActiveTrayIcon(
          palette_tool_manager_->GetActiveTool(ash::PaletteGroup::MODE)),
      kShelfIconSize, kShelfIconColor));
}

void PaletteTray::OnStylusStateChanged(ui::StylusState stylus_state) {
  PaletteDelegate* palette_delegate = WmShell::Get()->palette_delegate();

  // Don't do anything if the palette should not be shown or if the user has
  // disabled it all-together.
  if (!IsInUserSession() || !palette_delegate->ShouldShowPalette())
    return;

  // Auto show/hide the palette if allowed by the user.
  if (palette_delegate->ShouldAutoOpenPalette()) {
    if (stylus_state == ui::StylusState::REMOVED && !bubble_) {
      is_bubble_auto_opened_ = true;
      ShowPalette();
    } else if (stylus_state == ui::StylusState::INSERTED && bubble_) {
      HidePalette();
    }
  }

  // Disable any active modes if the stylus has been inserted.
  if (stylus_state == ui::StylusState::INSERTED)
    palette_tool_manager_->DisableActiveTool(PaletteGroup::MODE);
}

void PaletteTray::OnPaletteEnabledPrefChanged(bool enabled) {
  if (!enabled) {
    SetVisible(false);
    palette_tool_manager_->DisableActiveTool(PaletteGroup::MODE);
  } else {
    UpdateIconVisibility();
  }
}

void PaletteTray::UpdateIconVisibility() {
  SetVisible(IsInUserSession());
}

}  // namespace ash


text:
package test

import (
	"log"
	"net/http"
	"net/http/httptest"
	"sort"

	"github.com/adams-sarah/test2doc/doc"
	"github.com/adams-sarah/test2doc/doc/parse"
)

// resources = map[uri]Resource
var resources = map[string]*doc.Resource{}

type Server struct {
	*httptest.Server
	doc *doc.Doc
}

// TODO: filter out 404 responses
func NewServer(handler http.Handler) (s *Server, err error) {
	// check if url var extractor func is set
	if parse.Extractor == nil {
		panic("please set a URLVarExtractor.")
	}

	outDoc, err := doc.NewDoc(".")
	if err != nil {
		return s, err
	}

	httptestServer := httptest.NewServer(handleAndRecord(handler, outDoc))

	return &Server{
		httptestServer,
		outDoc,
	}, nil
}

func (s *Server) Finish() {
	s.Close()

	// sort resources by path
	var uris []string
	for k := range resources {
		uris = append(uris, k)
	}
	sort.Strings(uris)
	for _, uri := range uris {
		s.doc.AddResource(resources[uri])
	}

	err := s.doc.Write()
	if err != nil {
		panic(err.Error())
	}
}

func handleAndRecord(handler http.Handler, outDoc *doc.Doc) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		// copy request body into Request object
		docReq, err := doc.NewRequest(req)
		if err != nil {
			log.Println("Error:", err.Error())
			return
		}

		// record response
		rw := httptest.NewRecorder()
		resp := NewResponseWriter(rw)

		handler.ServeHTTP(resp, req)

		// setup resource
		u := doc.NewURL(req)
		path := u.ParameterizedPath

		if resources[path] == nil {
			resources[path] = doc.NewResource(u)
		}

		// store response body in Response object
		docResp := doc.NewResponse(resp.W)

		// find action
		action := resources[path].FindAction(req.Method)
		if action == nil {
			// make new action
			action, err = doc.NewAction(req.Method, resp.HandlerInfo.FuncName)
			if err != nil {
				log.Println("Error:", err.Error())
				return
			}

			// add Action to Resource's list of Actions
			resources[path].AddAction(action)
		}

		// add request, response to action
		action.AddRequest(docReq, docResp)

		// copy response over to w
		doc.CopyHeader(w.Header(), resp.Header())
		w.WriteHeader(resp.W.Code)
		w.Write(resp.W.Body.Bytes())
	}
}


text:
In DayPicker, a **modifier** is added to a day when the day matches a specific condition, called [`Matcher`](/api/types/matcher). For example, selected days have the `selected` modifiers, disabled days the `disabled` modifier, the today's date matches the `today` modifier, etc.

```tsx
<DayPicker selected={new Date()} />
<DayPicker disabled={new Date()} />
<DayPicker hidden={new Date()} />
```

### Understanding modifiers

- Use modifiers to change the appearance of the days in the calendar or to inspect the days the user has interacted with (e.g. picking a day)
- DayPicker comes with some pre-built modifiers, such as `disabled`, `selected`, `hidden`, `today`, `range_start`, etc. designed to cover the most common use cases. See the [InternalModifiers enum](/api/enums/InternalModifier) for a list of the internal modifiers.
- It is possible to implement custom modifiers, extending the behavior of DayPicker: see [Custom Modifiers](#custom-modifiers) below for more details.

## The `selected` modifier

```tsx
<DayPicker selected={new Date()} />
```

When in selection mode, use the `selected` prop to add the `selected` modifier to the selected dates, and style them accordingly. To see how to implement the `selected` modifier, see the [Selecting days guide](/basics/selecting-days).

## Disabling days

When in selection mode, use the `disabled` modifier to disable one or more days. Pass a [`Matcher`](/api/types/matcher) or an array of `Matchers` to choose the disabled days:

```include-example
modifiers-disabled
```

## Hidden days

The `hidden` modifier removes the day from the calendar. Set the hidden days using the `hidden` prop.

```include-example
modifiers-hidden
```

## The `today` modifier

The `today` modifier is added to the current date:

```include-example
modifiers-today
```

:::info
You can change the current date using the `today` prop.
:::

## Custom modifiers

Add new modifiers according to your app's requirements. For example, a booking app may use a `booked` modifier to mark days as already booked.

Use the `modifiers` prop to pass an object with custom modifiers and their matcher. Change the inline-style of the cell with `modifiersStyles` or with `modifiersClassNames`.

```include-example
modifiers-custom
```

## Styling modifiers

A day can be styled according to its modifiers – using CSS or inline styles. See [Styling DayPicker](/basics/styling) for more details.


text:
package com.msi.tough.engine.resource;

/**
 * Interface to be implemented by all Resources
 *
 * @author raj
 *
 */
public interface Resource {
	/**
	 * Get value for attributes defined by the AWS CF for this resource
	 *
	 * @param key
	 *            attribute name
	 * @return attribute value
	 */
	public Object getAtt(String key);

	/**
	 * Ref value for the resource as defined by AWS CF documentation
	 *
	 * @return reference value
	 */
	public Object ref();
}


text:
var ImageDemo = (function( $ ) {

  var $shuffle = $('.shuffle--images'),
      sizer = document.getElementById('js-sizer'),

  init = function() {

    $shuffle.shuffle({
      sizer: sizer,
      itemSelector: '.js-item'
    });
  };

  return {
    init: init
  };
}( jQuery ));

$(document).ready(function() {
  ImageDemo.init();
});


text:
package com.redwoodsystems.android.apps;

import com.redwoodsystems.android.apps.db.LocationDBAdapter;
import com.redwoodsystems.android.apps.db.SettingsDBAdapter;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.OnEditorActionListener;

public class SettingsActivity extends Activity {

	private static final String TAG = SettingsActivity.class.getName();

	Activity mContext;
	SettingsDBAdapter mSettingsDbHelper;
	Cursor settingsModel=null;
	Settings settings;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, "SettingsActivity .. onCreate");
		setContentView(R.layout.settings_layout);

		EditText clusterNameEditText = (EditText) findViewById(R.id.clusterName);
		clusterNameEditText.setOnEditorActionListener(mClusterNameEditorActionListemer);

		EditText passwordEditText = (EditText) findViewById(R.id.password);
		passwordEditText.setOnEditorActionListener(mPasswordEditorActionListemer);

		mSettingsDbHelper = new SettingsDBAdapter(this);
		mSettingsDbHelper.open();

		settingsModel = mSettingsDbHelper.fetchAllSettings();
		startManagingCursor(settingsModel);

		if (settingsModel != null && settingsModel.getCount() > 0){
			Log.d(TAG, "SettingsActivity .. found db settings");
			settings = mSettingsDbHelper.getSettings(settingsModel);
			Log.d(TAG, "settings="+settings);
			clusterNameEditText.setText(settings.getClusterName());
			passwordEditText.setText(settings.getPassword());
		} else {
			settings = new Settings();
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.d(TAG, "In SettingsActivity..onDestroy");
		mSettingsDbHelper.close();

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		Log.d(TAG, "In SettingsActivity..onPause");
		//save values to the database
		EditText clusterNameEditText = (EditText) findViewById(R.id.clusterName);
		EditText passwordEditText = (EditText) findViewById(R.id.password);
		String clusterName = clusterNameEditText.getText().toString();
		String password = passwordEditText.getText().toString();

		saveSettings(clusterName, password);

	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		Log.d(TAG, "In SettingsActivity..onRestart");
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.d(TAG, "In SettingsActivity..onResume");

		if (settings.getClusterName() !=null && !settings.getClusterName().equals("")
				&& settings.getPassword() !=null && !settings.getPassword().equals("") ){
			//Ok
		} else {
			Toast.makeText(this, "Update Settings and add Locations to use this application", Toast.LENGTH_SHORT).show();
		}
	}

	OnEditorActionListener mClusterNameEditorActionListemer = new OnEditorActionListener() {
	    @Override
	    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
	    	Log.d(TAG, "onEditorAction called");
	        boolean handled = false;

	        String clusterName = v.getText().toString();
	        EditText editText = (EditText) findViewById(R.id.password);
	        String password = editText.getText().toString();

	        if (actionId == EditorInfo.IME_ACTION_NEXT) {
	        	saveSettings(clusterName,password);
	        	editText.requestFocus();
	            handled = true;
	        }
	        return handled;
	    }
	};

	OnEditorActionListener mPasswordEditorActionListemer = new OnEditorActionListener() {
	    @Override
	    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
	    	Log.d(TAG, "onEditorAction called");
	        boolean handled = false;

	        EditText editText = (EditText) findViewById(R.id.clusterName);
	        String clusterName = editText.getText().toString();
	        String password = v.getText().toString();

	        if (actionId == EditorInfo.IME_ACTION_DONE) {
	        	saveSettings(clusterName,password);
	        	dismissKeyboard();
	            handled = true;
	        }
	        return handled;
	    }
	};

	private void dismissKeyboard(){
		if (this.getCurrentFocus() != null && this.getCurrentFocus() instanceof EditText){
			InputMethodManager inputManager =
			        (InputMethodManager) this.
			            getSystemService(Context.INPUT_METHOD_SERVICE);
			inputManager.hideSoftInputFromWindow(
			        this.getCurrentFocus().getWindowToken(),
			        InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

	private Settings initSettings(){
    	if (settingsModel != null && settingsModel.getCount() > 0){
    		if (settings == null){
    			settings = mSettingsDbHelper.getSettings(settingsModel);
    		}
    	} else {
    		if (settings == null){
    			settings = new Settings();
    		}
    	}
    	return settings;
	}

	private void saveSettings(String clusterName, String password){
		Log.d(TAG, "saveSettings called");
    	//make sure settings points to latest values
    	initSettings();
    	settings.setClusterName(clusterName);
    	settings.setPassword(password);

    	Settings prevSettings = mSettingsDbHelper.getSettings(settingsModel);
    	if ((prevSettings.getClusterName().equals(settings.getClusterName()))
    			&& prevSettings.getPassword().equals(settings.getPassword())){
    		//no change
    		Log.d(TAG, "Settings unchanged from database.");
    	} else {

    		//erase lastLocationId
    		settings.setLastLocationId(-1);
        	//sync settings to DB
        	settingsModel = mSettingsDbHelper.createUpdateSettings(settings);
        	settings = mSettingsDbHelper.getSettings(settingsModel);

        	//delete locations
        	LocationDBAdapter locationsDbHelper = new LocationDBAdapter(this);
        	locationsDbHelper.open();

        	Cursor locModel = locationsDbHelper.fetchAllLocations();
        	if (locModel != null && locModel.getCount() >0){
        		Log.d(TAG, "Deleting all locations from database");
        		locationsDbHelper.deleteAllLocations();
        		Log.d(TAG, "locations db count ="+locationsDbHelper.fetchAllLocations().getCount());
        	}
        	locationsDbHelper.close();
    	}

    	Log.d(TAG, "settings="+settings);
	}

}


text:
import { Component, ViewEncapsulation } from '@angular/core';
import { marker } from '@biesbjerg/ngx-translate-extract-marker';
import { DatasetOptions, Timespan } from '@helgoland/core';
import { D3PlotOptions, HoveringStyle } from '@helgoland/d3';
import { FavoriteService, JsonFavoriteExporterService, SingleFavorite } from '@helgoland/favorite';

import { TimeseriesRouter } from '../services/timeseries-router.service';
import { TimeseriesService } from '../services/timeseries.service';

// add i18n fragments
marker('favorite.notifier.remove-favorite');
marker('favorite.notifier.add-favorite');

interface ExtendedSingleFavorite extends SingleFavorite {
  timespan: Timespan;
  option: Map<string, DatasetOptions>;
}

interface EditableExtendedSingleFavorite extends ExtendedSingleFavorite {
  editLabel: boolean;
  editedLabel: string;
  loading: boolean;
}

@Component({
  selector: 'n52-timeseries-favorites',
  templateUrl: './favorites.component.html',
  styleUrls: ['./favorites.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class TimeseriesFavoritesComponent {

  public favorites: EditableExtendedSingleFavorite[];

  public presenterOptions: D3PlotOptions = {
    hoverStyle: HoveringStyle.none,
    togglePanZoom: true,
    showTimeLabel: false
  };

  constructor(
    private favoriteSrvc: FavoriteService,
    private timeseriesService: TimeseriesService,
    private jsonExporter: JsonFavoriteExporterService,
    private router: TimeseriesRouter
  ) {
    this.loadFavorites();
  }

  public addToDiagram(favorite: ExtendedSingleFavorite) {
    this.timeseriesService.addDataset(favorite.favorite.internalId);
    this.router.navigateToDiagram();
  }

  public deleteFavorite(favorite: ExtendedSingleFavorite) {
    const idx = this.favorites.findIndex(entry => entry.id === favorite.id);
    this.favorites.splice(idx, 1);
    this.favoriteSrvc.removeFavorite(favorite.id);
  }

  public setLabel(favorite: ExtendedSingleFavorite, label: string) {
    this.favoriteSrvc.changeLabel(favorite, label);
  }

  public importFavorites(event: Event) {
    this.jsonExporter.importFavorites(event).subscribe(() => this.loadFavorites());
  }

  public exportFavorites() {
    this.jsonExporter.exportFavorites();
  }

  private loadFavorites() {
    this.favorites = [];
    this.favoriteSrvc.getFavorites().forEach((entry) => {
      const option = new DatasetOptions(entry.favorite.internalId, '#FF0000');
      option.generalize = true;
      const timespan = new Timespan(entry.favorite.lastValue.timestamp - 604800000, entry.favorite.lastValue.timestamp);
      this.favorites.push({
        id: entry.id,
        label: entry.label,
        favorite: entry.favorite,
        editLabel: false,
        editedLabel: entry.label,
        loading: false,
        timespan,
        options: option,
        option: new Map([[entry.favorite.internalId, option]])
      });
    });
  }
}