import * as React from 'react';
import {NULL_FUNCTION} from 'polar-shared/src/util/Functions';
import {RGBColor} from './ColorButton';
import {ColorSelectorBox} from './ColorSelectorBox';
import {MUIPopper} from "../../mui/menu/MUIPopper";
import PaletteIcon from "@material-ui/icons/Palette";
import {deepMemo} from "../../react/ReactUtils";

interface IProps {

    /**
     * The role if this selector whether it's to change or select a color.
     */
    readonly role: 'change' | 'select';

    readonly className?: string;

    readonly style?: React.CSSProperties;

    readonly size?: string;

    readonly color: RGBColor;

    readonly onSelected?: (color: string) => void;

}

export const ColorSelector = deepMemo((props: IProps) => {

    const onSelected = props.onSelected || NULL_FUNCTION;

    const [color, setColor] = React.useState<RGBColor>(props.color);

    function handleSelected(color: RGBColor) {
        setColor(color);
        onSelected(color);
    }

    return (
        // <Tooltip title={`Used to ${props.role} the color.`}>
            <MUIPopper size="small"
                       icon={<PaletteIcon/>}>

                <ColorSelectorBox selected={[color]}
                                  onSelected={handleSelected}/>

            </MUIPopper>
        // </Tooltip>
    );

});


Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Undoredo
Bundle-SymbolicName: de.vogella.rcp.undoredo; singleton:=true
Bundle-Version: 1.0.0.qualifier
Bundle-Activator: de.vogella.rcp.undoredo.Activator
Require-Bundle: org.eclipse.ui,
 org.eclipse.core.runtime
Bundle-ActivationPolicy: lazy
Bundle-RequiredExecutionEnvironment: JavaSE-1.6


.TH semanage_bool_set_local 3 "4 January 2006" "ivg2@cornell.edu" "Libsemanage API documentation"
.SH "NAME"
semanage_bool_set_active \- update an existing SELinux boolean in the currently active policy

.SH "SYNOPSIS"
.B #include <semanage/booleans_active.h>
.br
.sp
.B extern int semanage_bool_set_active (
.br
.BI "	semanage_handle_t *" handle ","
.br
.BI "	const semanage_bool_key_t *" key ","
.br
.BI "	const semanage_bool_t *" data ");"

.SH "DESCRIPTION"
.TP
.B Behavior:
The set function will fail if no matching key is found in the local store. Otherwise, the provided object will replace the current one. When
.BR semanage_commit "(3)"
is invoked, changes will be written permanently into the local store, and will be loaded into policy. Validity of the object being added is checked at commit time.

.TP
.B Parameters:
The
.I handle
is used to track persistent state across semanage calls, and for error reporting. The
.I key
identifies the
.I data
object, which will be written into the store. The key are data are properties of the caller, and are not stored or modified internally.

.TP
.B Requirements:
This function requires an semanage connection to be established (see
.BR semanage_connect "(3)"
), and must be executed in a transaction (see
.BR semanage_begin_transaction "(3)"
).

.SH "RETURN VALUE"
In case of failure, \-1 is returned, and the semanage error callback is invoked, describing the error.
Otherwise 0 is returned.

.SH "SEE ALSO"
.BR semanage_handle_create "(3), " semanage_begin_transaction "(3), " semanage_connect "(3), " semanage_commit "(3). "


#
# /
#
/.*				gen_context(system_u:object_r:default_t,s0)
/			-d	gen_context(system_u:object_r:root_t,s0)
/\.journal			<<none>>
/afs			-d	gen_context(system_u:object_r:mnt_t,s0)
/initrd\.img.*		-l	gen_context(system_u:object_r:boot_t,s0)
/vmlinuz.*		-l	gen_context(system_u:object_r:boot_t,s0)

ifdef(`distro_redhat',`
/\.autofsck		--	gen_context(system_u:object_r:etc_runtime_t,s0)
/\.autorelabel		--	gen_context(system_u:object_r:etc_runtime_t,s0)
/\.suspended		--	gen_context(system_u:object_r:etc_runtime_t,s0)
/fastboot 		--	gen_context(system_u:object_r:etc_runtime_t,s0)
/forcefsck 		--	gen_context(system_u:object_r:etc_runtime_t,s0)
/fsckoptions 		--	gen_context(system_u:object_r:etc_runtime_t,s0)
/halt			--	gen_context(system_u:object_r:etc_runtime_t,s0)
/poweroff		--	gen_context(system_u:object_r:etc_runtime_t,s0)
')

ifdef(`distro_suse',`
/success		--	gen_context(system_u:object_r:etc_runtime_t,s0)
')

#
# /boot
#
/boot			-d	gen_context(system_u:object_r:boot_t,s0)
/boot/.*			gen_context(system_u:object_r:boot_t,s0)
/boot/\.journal			<<none>>
/boot/efi(/.*)?/System\.map(-.*)? -- gen_context(system_u:object_r:system_map_t,s0)
/boot/lost\+found	-d	gen_context(system_u:object_r:lost_found_t,mls_systemhigh)
/boot/lost\+found/.*		<<none>>
/boot/System\.map(-.*)?	--	gen_context(system_u:object_r:system_map_t,s0)

#
# /emul
#
/emul			-d	gen_context(system_u:object_r:usr_t,s0)
/emul/.*			gen_context(system_u:object_r:usr_t,s0)

#
# /etc
#
/etc			-d	gen_context(system_u:object_r:etc_t,s0)
/etc/.*				gen_context(system_u:object_r:etc_t,s0)
/etc/\.fstab\.hal\..+	--	gen_context(system_u:object_r:etc_runtime_t,s0)
/etc/blkid(/.*)?		gen_context(system_u:object_r:etc_runtime_t,s0)
/etc/cmtab		--	gen_context(system_u:object_r:etc_runtime_t,s0)
/etc/fstab\.REVOKE	--	gen_context(system_u:object_r:etc_runtime_t,s0)
/etc/ioctl\.save	--	gen_context(system_u:object_r:etc_runtime_t,s0)
/etc/killpower		--	gen_context(system_u:object_r:etc_runtime_t,s0)
/etc/localtime		-l	gen_context(system_u:object_r:etc_t,s0)
/etc/mtab		--	gen_context(system_u:object_r:etc_runtime_t,s0)
/etc/mtab~[0-9]*	--	gen_context(system_u:object_r:etc_runtime_t,s0)
/etc/mtab\.tmp		--	gen_context(system_u:object_r:etc_runtime_t,s0)
/etc/mtab\.fuselock	--	gen_context(system_u:object_r:etc_runtime_t,s0)
/etc/nohotplug		--	gen_context(system_u:object_r:etc_runtime_t,s0)
/etc/nologin.*		--	gen_context(system_u:object_r:etc_runtime_t,s0)

/etc/cups/client\.conf	--	gen_context(system_u:object_r:etc_t,s0)

/etc/ipsec\.d/examples(/.*)?	gen_context(system_u:object_r:etc_t,s0)

/etc/network/ifstate	--	gen_context(system_u:object_r:etc_runtime_t,s0)

/etc/ptal/ptal-printd-like -- 	gen_context(system_u:object_r:etc_runtime_t,s0)

/etc/sysconfig/hwconf	--	gen_context(system_u:object_r:etc_runtime_t,s0)
/etc/sysconfig/iptables\.save -- gen_context(system_u:object_r:etc_runtime_t,s0)
/etc/sysconfig/firstboot --	gen_context(system_u:object_r:etc_runtime_t,s0)

/etc/zfs/zpool\.cache	--	gen_context(system_u:object_r:etc_runtime_t,s0)

ifdef(`distro_gentoo', `
/etc/profile\.env	--	gen_context(system_u:object_r:etc_runtime_t,s0)
/etc/csh\.env		--	gen_context(system_u:object_r:etc_runtime_t,s0)
/etc/env\.d/.*		--	gen_context(system_u:object_r:etc_runtime_t,s0)
')

ifdef(`distro_redhat',`
/etc/rhgb(/.*)?		-d	gen_context(system_u:object_r:mnt_t,s0)
')

ifdef(`distro_suse',`
/etc/defkeymap\.map	--	gen_context(system_u:object_r:etc_runtime_t,s0)
/etc/rc\.d/init\.d/\.depend.* -- gen_context(system_u:object_r:etc_runtime_t,s0)
')

#
# HOME_ROOT
# expanded by genhomedircon
#
HOME_ROOT		-d	gen_context(system_u:object_r:home_root_t,s0-mls_systemhigh)
HOME_ROOT		-l	gen_context(system_u:object_r:home_root_t,s0)
HOME_ROOT/\.journal		<<none>>
HOME_ROOT/lost\+found	-d	gen_context(system_u:object_r:lost_found_t,mls_systemhigh)
HOME_ROOT/lost\+found/.*	<<none>>

#
# /initrd
#
# initrd mount point, only used during boot
/initrd			-d	gen_context(system_u:object_r:root_t,s0)

#
# /lost+found
#
/lost\+found		-d	gen_context(system_u:object_r:lost_found_t,mls_systemhigh)
/lost\+found/.*			<<none>>

#
# /media
#
# Mount points; do not relabel subdirectories, since
# we don't want to change any removable media by default.
/media(/[^/]*)		-l	gen_context(system_u:object_r:mnt_t,s0)
/media(/[^/]*)?		-d	gen_context(system_u:object_r:mnt_t,s0)
/media/[^/]*/.*			<<none>>
/media/\.hal-.*		--	gen_context(system_u:object_r:mnt_t,s0)

#
# /misc
#
/misc			-d	gen_context(system_u:object_r:mnt_t,s0)

#
# /mnt
#
/mnt(/[^/]*)		-l	gen_context(system_u:object_r:mnt_t,s0)
/mnt(/[^/]*)?		-d	gen_context(system_u:object_r:mnt_t,s0)
/mnt/[^/]*/.*			<<none>>

#
# /net
#
/net			-d	gen_context(system_u:object_r:mnt_t,s0)

#
# /opt
#
/opt			-d	gen_context(system_u:object_r:usr_t,s0)
/opt/.*				gen_context(system_u:object_r:usr_t,s0)

/opt/(.*/)?var/lib(64)?(/.*)?	gen_context(system_u:object_r:var_lib_t,s0)

#
# /proc
#
/proc			-d	<<none>>
/proc/.*			<<none>>

#
# /run
#
/run			-d	gen_context(system_u:object_r:var_run_t,s0-mls_systemhigh)
/run			-l	gen_context(system_u:object_r:var_run_t,s0)
/run/shm		-l	gen_context(system_u:object_r:var_run_t,s0)
/run/.*				<<none>>

#
# /selinux
#
/selinux		-d	<<none>>
/selinux/.*			<<none>>

#
# /srv
#
/srv			-d	gen_context(system_u:object_r:var_t,s0)
/srv/.*				gen_context(system_u:object_r:var_t,s0)

#
# /tmp
#
/tmp			-d	gen_context(system_u:object_r:tmp_t,s0-mls_systemhigh)
/tmp/.*				<<none>>
/tmp/\.journal			<<none>>

/tmp/lost\+found	-d	gen_context(system_u:object_r:lost_found_t,mls_systemhigh)
/tmp/lost\+found/.*		<<none>>

/tmp/systemd-private-[^/]+	-d	gen_context(system_u:object_r:tmp_t,s0-mls_systemhigh)
/tmp/systemd-private-[^/]+/tmp	-d	gen_context(system_u:object_r:tmp_t,s0-mls_systemhigh)
/tmp/systemd-private-[^/]+/tmp/.*	<<none>>

#
# /usr
#
/usr			-d	gen_context(system_u:object_r:usr_t,s0)
/usr/.*				gen_context(system_u:object_r:usr_t,s0)
/usr/\.journal			<<none>>

/usr/doc(/.*)?/lib(/.*)?	gen_context(system_u:object_r:usr_t,s0)

/usr/etc(/.*)?			gen_context(system_u:object_r:etc_t,s0)

# Avoid calling m4's include by using en empty string
/usr/include`'(/.*)?		gen_context(system_u:object_r:usr_t,s0)

/usr/lib/modules(/.*)?		gen_context(system_u:object_r:modules_object_t,s0)

/usr/local/\.journal		<<none>>

/usr/local/etc(/.*)?		gen_context(system_u:object_r:etc_t,s0)

/usr/local/lost\+found	-d	gen_context(system_u:object_r:lost_found_t,mls_systemhigh)
/usr/local/lost\+found/.*	<<none>>

/usr/lost\+found	-d	gen_context(system_u:object_r:lost_found_t,mls_systemhigh)
/usr/lost\+found/.*		<<none>>

/usr/share/doc(/.*)?/README.*		gen_context(system_u:object_r:usr_t,s0)
/usr/share/docbook2X/xslt/man(/.*)?	gen_context(system_u:object_r:usr_t,s0)

/usr/tmp		-d	gen_context(system_u:object_r:tmp_t,s0-mls_systemhigh)
/usr/tmp/.*			<<none>>

ifdef(`distro_debian',`
# on Debian /lib/init/rw is a tmpfs used like /run
/usr/lib/init/rw(/.*)?		gen_context(system_u:object_r:var_run_t,s0-mls_systemhigh)
/run/resolvconf(/.*)? -d	gen_context(system_u:object_r:etc_t,s0)
')

ifndef(`distro_redhat',`
/usr/local/src(/.*)?		gen_context(system_u:object_r:src_t,s0)

/usr/src(/.*)?			gen_context(system_u:object_r:src_t,s0)
/usr/src/kernels/.+/lib(/.*)?	gen_context(system_u:object_r:usr_t,s0)
')

#
# /var
#
/var			-d	gen_context(system_u:object_r:var_t,s0)
/var/.*				gen_context(system_u:object_r:var_t,s0)
/var/\.journal			<<none>>

/var/db/.*\.db		--	gen_context(system_u:object_r:etc_t,s0)

/var/ftp/etc(/.*)?		gen_context(system_u:object_r:etc_t,s0)

/var/lib(/.*)?			gen_context(system_u:object_r:var_lib_t,s0)

/var/lib/nfs/rpc_pipefs(/.*)?	<<none>>

/var/lock		-d	gen_context(system_u:object_r:var_lock_t,s0-mls_systemhigh)
/var/lock		-l	gen_context(system_u:object_r:var_lock_t,s0)
/var/lock/subsys	-d	gen_context(system_u:object_r:var_lock_t,s0-mls_systemhigh)
/var/lock/.*			<<none>>

/var/log/lost\+found	-d	gen_context(system_u:object_r:lost_found_t,mls_systemhigh)
/var/log/lost\+found/.*		<<none>>

/var/log/audit/lost\+found -d	gen_context(system_u:object_r:lost_found_t,mls_systemhigh)
/var/log/audit/lost\+found/.*	<<none>>

/var/lost\+found	-d	gen_context(system_u:object_r:lost_found_t,mls_systemhigh)
/var/lost\+found/.*		<<none>>

/var/run		-l	gen_context(system_u:object_r:var_run_t,s0)

/var/spool(/.*)?		gen_context(system_u:object_r:var_spool_t,s0)
/var/spool/postfix/etc(/.*)?	gen_context(system_u:object_r:etc_t,s0)
/var/spool/postfix/pid	-d	gen_context(system_u:object_r:var_run_t,s0)

/var/tmp		-d	gen_context(system_u:object_r:tmp_t,s0-mls_systemhigh)
/var/tmp		-l	gen_context(system_u:object_r:tmp_t,s0)
/var/tmp/.*			<<none>>
/var/tmp/lost\+found	-d	gen_context(system_u:object_r:lost_found_t,mls_systemhigh)
/var/tmp/lost\+found/.*		<<none>>
/var/tmp/systemd-private-[^/]+	-d	gen_context(system_u:object_r:tmp_t,s0-mls_systemhigh)
/var/tmp/systemd-private-[^/]+/tmp	-d	gen_context(system_u:object_r:tmp_t,s0-mls_systemhigh)
/var/tmp/systemd-private-[^/]+/tmp/.*	<<none>>
/var/tmp/vi\.recover	-d	gen_context(system_u:object_r:tmp_t,s0)


// Copyright 2017 Prometheus Team
// 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.

package procfs

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

// XfrmStat models the contents of /proc/net/xfrm_stat.
type XfrmStat struct {
	// All errors which are not matched by other
	XfrmInError int
	// No buffer is left
	XfrmInBufferError int
	// Header Error
	XfrmInHdrError int
	// No state found
	// i.e. either inbound SPI, address, or IPSEC protocol at SA is wrong
	XfrmInNoStates int
	// Transformation protocol specific error
	// e.g. SA Key is wrong
	XfrmInStateProtoError int
	// Transformation mode specific error
	XfrmInStateModeError int
	// Sequence error
	// e.g. sequence number is out of window
	XfrmInStateSeqError int
	// State is expired
	XfrmInStateExpired int
	// State has mismatch option
	// e.g. UDP encapsulation type is mismatched
	XfrmInStateMismatch int
	// State is invalid
	XfrmInStateInvalid int
	// No matching template for states
	// e.g. Inbound SAs are correct but SP rule is wrong
	XfrmInTmplMismatch int
	// No policy is found for states
	// e.g. Inbound SAs are correct but no SP is found
	XfrmInNoPols int
	// Policy discards
	XfrmInPolBlock int
	// Policy error
	XfrmInPolError int
	// All errors which are not matched by others
	XfrmOutError int
	// Bundle generation error
	XfrmOutBundleGenError int
	// Bundle check error
	XfrmOutBundleCheckError int
	// No state was found
	XfrmOutNoStates int
	// Transformation protocol specific error
	XfrmOutStateProtoError int
	// Transportation mode specific error
	XfrmOutStateModeError int
	// Sequence error
	// i.e sequence number overflow
	XfrmOutStateSeqError int
	// State is expired
	XfrmOutStateExpired int
	// Policy discads
	XfrmOutPolBlock int
	// Policy is dead
	XfrmOutPolDead int
	// Policy Error
	XfrmOutPolError     int
	XfrmFwdHdrError     int
	XfrmOutStateInvalid int
	XfrmAcquireError    int
}

// NewXfrmStat reads the xfrm_stat statistics.
func NewXfrmStat() (XfrmStat, error) {
	fs, err := NewFS(DefaultMountPoint)
	if err != nil {
		return XfrmStat{}, err
	}

	return fs.NewXfrmStat()
}

// NewXfrmStat reads the xfrm_stat statistics from the 'proc' filesystem.
func (fs FS) NewXfrmStat() (XfrmStat, error) {
	file, err := os.Open(fs.proc.Path("net/xfrm_stat"))
	if err != nil {
		return XfrmStat{}, err
	}
	defer file.Close()

	var (
		x = XfrmStat{}
		s = bufio.NewScanner(file)
	)

	for s.Scan() {
		fields := strings.Fields(s.Text())

		if len(fields) != 2 {
			return XfrmStat{}, fmt.Errorf(
				"couldn't parse %s line %s", file.Name(), s.Text())
		}

		name := fields[0]
		value, err := strconv.Atoi(fields[1])
		if err != nil {
			return XfrmStat{}, err
		}

		switch name {
		case "XfrmInError":
			x.XfrmInError = value
		case "XfrmInBufferError":
			x.XfrmInBufferError = value
		case "XfrmInHdrError":
			x.XfrmInHdrError = value
		case "XfrmInNoStates":
			x.XfrmInNoStates = value
		case "XfrmInStateProtoError":
			x.XfrmInStateProtoError = value
		case "XfrmInStateModeError":
			x.XfrmInStateModeError = value
		case "XfrmInStateSeqError":
			x.XfrmInStateSeqError = value
		case "XfrmInStateExpired":
			x.XfrmInStateExpired = value
		case "XfrmInStateInvalid":
			x.XfrmInStateInvalid = value
		case "XfrmInTmplMismatch":
			x.XfrmInTmplMismatch = value
		case "XfrmInNoPols":
			x.XfrmInNoPols = value
		case "XfrmInPolBlock":
			x.XfrmInPolBlock = value
		case "XfrmInPolError":
			x.XfrmInPolError = value
		case "XfrmOutError":
			x.XfrmOutError = value
		case "XfrmInStateMismatch":
			x.XfrmInStateMismatch = value
		case "XfrmOutBundleGenError":
			x.XfrmOutBundleGenError = value
		case "XfrmOutBundleCheckError":
			x.XfrmOutBundleCheckError = value
		case "XfrmOutNoStates":
			x.XfrmOutNoStates = value
		case "XfrmOutStateProtoError":
			x.XfrmOutStateProtoError = value
		case "XfrmOutStateModeError":
			x.XfrmOutStateModeError = value
		case "XfrmOutStateSeqError":
			x.XfrmOutStateSeqError = value
		case "XfrmOutStateExpired":
			x.XfrmOutStateExpired = value
		case "XfrmOutPolBlock":
			x.XfrmOutPolBlock = value
		case "XfrmOutPolDead":
			x.XfrmOutPolDead = value
		case "XfrmOutPolError":
			x.XfrmOutPolError = value
		case "XfrmFwdHdrError":
			x.XfrmFwdHdrError = value
		case "XfrmOutStateInvalid":
			x.XfrmOutStateInvalid = value
		case "XfrmAcquireError":
			x.XfrmAcquireError = value
		}

	}

	return x, s.Err()
}


---
description: 유니온 타입을 이용해 “여러 경우 중 하나”인 타입을 표현할 수 있다.
---

# 3.7 유니온 타입

### **동기부여**

아래 함수를 한 번 살펴보자.

```typescript
function square(value: number, returnString: boolean = false): ??? {
  const squared = value * value;
  if (returnString) {
    return squared.toString();
  }
  return squared;
}
```

함수 `square`는 숫자 타입 인자를 하나 받고, 불리언 타입 인자를 하나 더 받아 그 값에 따라 문자열 또는 숫자 타입의 값을 반환한다. 이 함수의 반환 타입은 어떻게 표현할 수 있을까? 일단 이 경우 반환 타입이 **인자의 타입이 아닌 값에 의존한다**. 따라서 제너릭으로는 표현하기 까다롭다 짐작할 수 있다.

오버로딩을 이용하면 아래와 같이 표현은 가능하다. 하지만 하나의 타입을 제외하고 모든 부분이 똑같은데도 여러번 써야 해 비효율적이다. 게다가 오버로딩으로 함수를 정의한다 한들, 반환값을 할당하는 변수의 타입을 정의하기 어렵다는 문제가 남는다.

```typescript
function square(value: number, returnString: boolean): number;
function square(value: number, returnString: boolean): string;
function square(value, returnString = false) {
  /* 본문 동일 */
}
const mystery: ??? = square(randomNumber, randomBoolean);
```

**어떤 타입이 가질 수 있는 경우의 수를 나열**할 때 사용하는 **유니온 타입**으로 이 함수의 반환 타입을 표현할 수 있다.

### **문법**

유니온 타입은 가능한 모든 타입을 파이프\(`|`\) 기호로 이어서 표현한다. “`A` 또는 `B` 타입일 수 있는 타입”을 `A | B` 로 쓰는 식이다. `square` 함수의 타입은 아래와 같이 적을 수 있다.

```typescript
function square(value: number, returnString: boolean = false): string | number {
  /* 본문 동일 */
}
const stringOrNumber: string | number = square(randomNumber, randomBoolean);
```

타입 별칭 문법을 사용해 유니온 타입에 이름을 붙일 수 있다. 자주 사용되는 타입, 또는 인라인으로 작성하기에 너무 복잡한 타입의 경우 이 방식을 추천한다.

```typescript
type SquaredType = string | number;
function square(value: number, returnOnString: boolean = false): SquaredType {
  /* 본문 동일 */
}
```

유니온 타입이 가질 수 있는 타입의 수가 꼭 2개일 필요는 없다. 몇 개든 이어가며 정의할 수 있다.

```typescript
type Whatever = number | string | boolean;
```

### **여러 줄에 걸친 유니온 타입**

여러 줄에 걸쳐 유니온 타입을 적을 때에는 보통 아래와 같이 정렬을 맞춘다.

```typescript
type Fruits
  = Apple
  | Banana
  | Cherry;
```

추가로 유니온 타입의 맨 앞에도 파이프를 쓰는 것이 허용된다. 이렇게 하면 여러 줄에 걸쳐 유니온 타입을 정의할 때 각 라인의 형태를 통일할 수 있다. 실질적인 의미 차이는 없으니 선호대로 사용하면 된다.

```typescript
type Fruits =
  | Apple
  | Banana
  | Cherry;
```


/*
 * Copyright (c) 2013 Dave Collins <dave@davec.name>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
This test file is part of the spew package rather than than the spew_test
package because it needs access to internals to properly test certain cases
which are not possible via the public interface since they should never happen.
*/

package spew

import (
	"bytes"
	"reflect"
	"testing"
)

// dummyFmtState implements a fake fmt.State to use for testing invalid
// reflect.Value handling.  This is necessary because the fmt package catches
// invalid values before invoking the formatter on them.
type dummyFmtState struct {
	bytes.Buffer
}

func (dfs *dummyFmtState) Flag(f int) bool {
	if f == int('+') {
		return true
	}
	return false
}

func (dfs *dummyFmtState) Precision() (int, bool) {
	return 0, false
}

func (dfs *dummyFmtState) Width() (int, bool) {
	return 0, false
}

// TestInvalidReflectValue ensures the dump and formatter code handles an
// invalid reflect value properly.  This needs access to internal state since it
// should never happen in real code and therefore can't be tested via the public
// API.
func TestInvalidReflectValue(t *testing.T) {
	i := 1

	// Dump invalid reflect value.
	v := new(reflect.Value)
	buf := new(bytes.Buffer)
	d := dumpState{w: buf, cs: &Config}
	d.dump(*v)
	s := buf.String()
	want := "<invalid>"
	if s != want {
		t.Errorf("InvalidReflectValue #%d\n got: %s want: %s", i, s, want)
	}
	i++

	// Formatter invalid reflect value.
	buf2 := new(dummyFmtState)
	f := formatState{value: *v, cs: &Config, fs: buf2}
	f.format(*v)
	s = buf2.String()
	want = "<invalid>"
	if s != want {
		t.Errorf("InvalidReflectValue #%d got: %s want: %s", i, s, want)
	}
}

// SortValues makes the internal sortValues function available to the test
// package.
func SortValues(values []reflect.Value, cs *ConfigState) {
	sortValues(values, cs)
}


#!/bin/bash

pip3 install glog
pip3 install wordninja


/*
 * Marvell 88E6060 switch driver
 * Copyright (c) 2008 Felix Fietkau <nbd@nbd.name>
 *
 * This program is free software; you can redistribute  it and/or modify it
 * under  the terms of the GNU General Public License v2 as published by the
 * Free Software Foundation
 */
#ifndef __MVSWITCH_H
#define __MVSWITCH_H

#define MV_HEADER_SIZE	2
#define MV_HEADER_PORTS_M	0x001f
#define MV_HEADER_PORTS_S	0
#define MV_HEADER_VLAN_M	0xf000
#define MV_HEADER_VLAN_S	12

#define MV_TRAILER_SIZE	4
#define MV_TRAILER_PORTS_M	0x1f
#define MV_TRAILER_PORTS_S	16
#define MV_TRAILER_FLAGS_S	24
#define MV_TRAILER_OVERRIDE	0x80

#define MV_PORTS	5
#define MV_WANPORT	4
#define MV_CPUPORT	5

#define MV_BASE		0x10

#define MV_PHYPORT_BASE		(MV_BASE + 0x0)
#define MV_PHYPORT(_n)		(MV_PHYPORT_BASE + (_n))
#define MV_SWITCHPORT_BASE	(MV_BASE + 0x8)
#define MV_SWITCHPORT(_n)	(MV_SWITCHPORT_BASE + (_n))
#define MV_SWITCHREGS		(MV_BASE + 0xf)

enum {
	MV_PHY_CONTROL      = 0x00,
	MV_PHY_STATUS       = 0x01,
	MV_PHY_IDENT0       = 0x02,
	MV_PHY_IDENT1       = 0x03,
	MV_PHY_ANEG         = 0x04,
	MV_PHY_LINK_ABILITY = 0x05,
	MV_PHY_ANEG_EXPAND  = 0x06,
	MV_PHY_XMIT_NEXTP   = 0x07,
	MV_PHY_LINK_NEXTP   = 0x08,
	MV_PHY_CONTROL1     = 0x10,
	MV_PHY_STATUS1      = 0x11,
	MV_PHY_INTR_EN      = 0x12,
	MV_PHY_INTR_STATUS  = 0x13,
	MV_PHY_INTR_PORT    = 0x14,
	MV_PHY_RECV_COUNTER = 0x16,
	MV_PHY_LED_PARALLEL = 0x16,
	MV_PHY_LED_STREAM   = 0x17,
	MV_PHY_LED_CTRL     = 0x18,
	MV_PHY_LED_OVERRIDE = 0x19,
	MV_PHY_VCT_CTRL     = 0x1a,
	MV_PHY_VCT_STATUS   = 0x1b,
	MV_PHY_CONTROL2     = 0x1e
};
#define MV_PHYREG(_type, _port) MV_PHYPORT(_port), MV_PHY_##_type

enum {
	MV_PORT_STATUS      = 0x00,
	MV_PORT_IDENT       = 0x03,
	MV_PORT_CONTROL     = 0x04,
	MV_PORT_VLANMAP     = 0x06,
	MV_PORT_ASSOC       = 0x0b,
	MV_PORT_RXCOUNT     = 0x10,
	MV_PORT_TXCOUNT     = 0x11,
};
#define MV_PORTREG(_type, _port) MV_SWITCHPORT(_port), MV_PORT_##_type

enum {
	MV_PORTCTRL_BLOCK   =  (1 << 0),
	MV_PORTCTRL_LEARN   =  (2 << 0),
	MV_PORTCTRL_ENABLED =  (3 << 0),
	MV_PORTCTRL_VLANTUN =  (1 << 7),	/* Enforce VLANs on packets */
	MV_PORTCTRL_RXTR    =  (1 << 8),	/* Enable Marvell packet trailer for ingress */
	MV_PORTCTRL_HEADER	= (1 << 11),	/* Enable Marvell packet header mode for port */
	MV_PORTCTRL_TXTR    = (1 << 14),	/* Enable Marvell packet trailer for egress */
	MV_PORTCTRL_FORCEFL = (1 << 15),	/* force flow control */
};

#define MV_PORTVLAN_ID(_n) (((_n) & 0xf) << 12)
#define MV_PORTVLAN_PORTS(_n) ((_n) & 0x3f)

#define MV_PORTASSOC_PORTS(_n) ((_n) & 0x1f)
#define MV_PORTASSOC_MONITOR	(1 << 15)

enum {
	MV_SWITCH_MAC0      = 0x01,
	MV_SWITCH_MAC1      = 0x02,
	MV_SWITCH_MAC2      = 0x03,
	MV_SWITCH_CTRL      = 0x04,
	MV_SWITCH_ATU_CTRL  = 0x0a,
	MV_SWITCH_ATU_OP    = 0x0b,
	MV_SWITCH_ATU_DATA  = 0x0c,
	MV_SWITCH_ATU_MAC0  = 0x0d,
	MV_SWITCH_ATU_MAC1  = 0x0e,
	MV_SWITCH_ATU_MAC2  = 0x0f,
};
#define MV_SWITCHREG(_type) MV_SWITCHREGS, MV_SWITCH_##_type

enum {
	MV_SWITCHCTL_EEIE   =  (1 << 0),	/* EEPROM interrupt enable */
	MV_SWITCHCTL_PHYIE  =  (1 << 1),	/* PHY interrupt enable */
	MV_SWITCHCTL_ATUDONE=  (1 << 2),	/* ATU done interrupt enable */
	MV_SWITCHCTL_ATUIE  =  (1 << 3),	/* ATU interrupt enable */
	MV_SWITCHCTL_CTRMODE=  (1 << 8),	/* statistics for rx and tx errors */
	MV_SWITCHCTL_RELOAD =  (1 << 9),	/* reload registers from eeprom */
	MV_SWITCHCTL_MSIZE  = (1 << 10),	/* increase maximum frame size */
	MV_SWITCHCTL_DROP   = (1 << 13),	/* discard frames with excessive collisions */
};

enum {
#define MV_ATUCTL_AGETIME_MIN	16
#define MV_ATUCTL_AGETIME_MAX	4080
#define MV_ATUCTL_AGETIME(_n)	((((_n) / 16) & 0xff) << 4)
	MV_ATUCTL_ATU_256   = (0 << 12),
	MV_ATUCTL_ATU_512   = (1 << 12),
	MV_ATUCTL_ATU_1K	= (2 << 12),
	MV_ATUCTL_ATUMASK   = (3 << 12),
	MV_ATUCTL_NO_LEARN  = (1 << 14),
	MV_ATUCTL_RESET     = (1 << 15),
};

enum {
#define MV_ATUOP_DBNUM(_n)	((_n) & 0x0f)

	MV_ATUOP_NOOP       = (0 << 12),
	MV_ATUOP_FLUSH_ALL  = (1 << 12),
	MV_ATUOP_FLUSH_U    = (2 << 12),
	MV_ATUOP_LOAD_DB    = (3 << 12),
	MV_ATUOP_GET_NEXT   = (4 << 12),
	MV_ATUOP_FLUSH_DB   = (5 << 12),
	MV_ATUOP_FLUSH_DB_UU= (6 << 12),

	MV_ATUOP_INPROGRESS = (1 << 15),
};

#define MV_IDENT_MASK		0xfff0
#define MV_IDENT_VALUE		0x0600

#endif


<!DOCTYPE HTML>

<title>AbstractQueuedSynchronizer (Quasar 0.8.0)</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="dc.created" content="2018-11-03">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

All Classes

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Package co.paralleluniverse.strands.concurrent

Class AbstractQueuedSynchronizer

java.lang.Object

co.paralleluniverse.strands.concurrent.AbstractOwnableSynchronizer

co.paralleluniverse.strands.concurrent.AbstractQueuedSynchronizer

All Implemented Interfaces:

java.io.Serializable

public abstract class AbstractQueuedSynchronizer
extends AbstractOwnableSynchronizer
implements java.io.Serializable

Provides a framework for implementing blocking locks and related
 synchronizers (semaphores, events, etc) that rely on
 first-in-first-out (FIFO) wait queues.  This class is designed to
 be a useful basis for most kinds of synchronizers that rely on a
 single atomic int value to represent state. Subclasses
 must define the protected methods that change this state, and which
 define what that state means in terms of this object being acquired
 or released.  Given these, the other methods in this class carry
 out all queuing and blocking mechanics. Subclasses can maintain
 other state fields, but only the atomically updated int
 value manipulated using methods getState(), setState(int) and compareAndSetState(int, int) is tracked with respect
 to synchronization.

Subclasses should be defined as non-public internal helper
 classes that are used to implement the synchronization properties
 of their enclosing class.  Class
 AbstractQueuedSynchronizer does not implement any
 synchronization interface.  Instead it defines methods such as
 acquireInterruptibly(int) that can be invoked as
 appropriate by concrete locks and related synchronizers to
 implement their public methods.

This class supports either or both a default exclusive
 mode and a shared mode. When acquired in exclusive mode,
 attempted acquires by other strands cannot succeed. Shared mode
 acquires by multiple strands may (but need not) succeed. This class
 does not "understand" these differences except in the
 mechanical sense that when a shared mode acquire succeeds, the next
 waiting strand (if one exists) must also determine whether it can
 acquire as well. Strands waiting in the different modes share the
 same FIFO queue. Usually, implementation subclasses support only
 one of these modes, but both can come into play for example in a
 ReadWriteLock. Subclasses that support only exclusive or
 only shared modes need not define the methods supporting the unused mode.

This class defines a nested AbstractQueuedSynchronizer.ConditionObject class that
 can be used as a Condition implementation by subclasses
 supporting exclusive mode for which method isHeldExclusively() reports whether synchronization is exclusively
 held with respect to the current strand, method release(int)
 invoked with the current getState() value fully releases
 this object, and acquire(int), given this saved state value,
 eventually restores this object to its previous acquired state.  No
 AbstractQueuedSynchronizer method otherwise creates such a
 condition, so if this constraint cannot be met, do not use it.  The
 behavior of AbstractQueuedSynchronizer.ConditionObject depends of course on the
 semantics of its synchronizer implementation.

This class provides inspection, instrumentation, and monitoring
 methods for the internal queue, as well as similar methods for
 condition objects. These can be exported as desired into classes
 using an AbstractQueuedSynchronizer for their
 synchronization mechanics.

Serialization of this class stores only the underlying atomic
 integer maintaining state, so deserialized objects have empty
 strand queues. Typical subclasses requiring serializability will
 define a readObject method that restores this to a known
 initial state upon deserialization.

Usage

To use this class as the basis of a synchronizer, redefine the
 following methods, as applicable, by inspecting and/or modifying
 the synchronization state using getState(), setState(int) and/or compareAndSetState(int, int):

 tryAcquire(int)

 tryRelease(int)

 tryAcquireShared(int)

 tryReleaseShared(int)

 isHeldExclusively()

 Each of these methods by default throws UnsupportedOperationException.  Implementations of these methods
 must be internally strand-safe, and should in general be short and
 not block. Defining these methods is the only supported
 means of using this class. All other methods are declared
 final because they cannot be independently varied.

You may also find the inherited methods from AbstractOwnableSynchronizer useful to keep track of the strand
 owning an exclusive synchronizer.  You are encouraged to use them
 -- this enables monitoring and diagnostic tools to assist users in
 determining which strands hold locks.

Even though this class is based on an internal FIFO queue, it
 does not automatically enforce FIFO acquisition policies.  The core
 of exclusive synchronization takes the form:

 Acquire:
     while (!tryAcquire(arg)) {
        enqueue strand if it is not already queued;
        possibly block current strand;
     }

 Release:
     if (tryRelease(arg))
        unblock the first queued strand;

 (Shared mode is similar but may involve cascading signals.)

Because checks in acquire are invoked before
 enqueuing, a newly acquiring strand may barge ahead of
 others that are blocked and queued.  However, you can, if desired,
 define tryAcquire and/or tryAcquireShared to
 disable barging by internally invoking one or more of the inspection
 methods, thereby providing a fair FIFO acquisition order.
 In particular, most fair synchronizers can define tryAcquire
 to return false if hasQueuedPredecessors() (a method
 specifically designed to be used by fair synchronizers) returns
 true.  Other variations are possible.

Throughput and scalability are generally highest for the
 default barging (also known as greedy,
 renouncement, and convoy-avoidance) strategy.
 While this is not guaranteed to be fair or starvation-free, earlier
 queued strands are allowed to recontend before later queued
 strands, and each recontention has an unbiased chance to succeed
 against incoming strands.  Also, while acquires do not
 "spin" in the usual sense, they may perform multiple
 invocations of tryAcquire interspersed with other
 computations before blocking.  This gives most of the benefits of
 spins when exclusive synchronization is only briefly held, without
 most of the liabilities when it isn't. If so desired, you can
 augment this by preceding calls to acquire methods with
 "fast-path" checks, possibly prechecking hasContended()
 and/or hasQueuedStrands() to only do so if the synchronizer
 is likely not to be contended.

This class provides an efficient and scalable basis for
 synchronization in part by specializing its range of use to
 synchronizers that can rely on int state, acquire, and
 release parameters, and an internal FIFO wait queue. When this does
 not suffice, you can build synchronizers from a lower level using
 atomic classes, your own custom
 Queue classes, and LockSupport blocking
 support.

Usage Examples

Here is a non-reentrant mutual exclusion lock class that uses
 the value zero to represent the unlocked state, and one to
 represent the locked state. While a non-reentrant lock
 does not strictly require recording of the current owner
 strand, this class does so anyway to make usage easier to monitor.
 It also supports conditions and exposes
 one of the instrumentation methods:

 class Mutex implements Lock, java.io.Serializable {

   // Our internal helper class
   private static class Sync extends AbstractQueuedSynchronizer {
     // Reports whether in locked state
     protected boolean isHeldExclusively() {
       return getState() == 1;
     }

     // Acquires the lock if state is zero
     public boolean tryAcquire(int acquires) {
       assert acquires == 1; // Otherwise unused
       if (compareAndSetState(0, 1)) {
         setExclusiveOwnerStrand(Strand.currentStrand());
         return true;
       }
       return false;
     }

     // Releases the lock by setting state to zero
     protected boolean tryRelease(int releases) {
       assert releases == 1; // Otherwise unused
       if (getState() == 0) throw new IllegalMonitorStateException();
       setExclusiveOwnerStrand(null);
       setState(0);
       return true;
     }

     // Provides a Condition
     Condition newCondition() { return new ConditionObject(); }

     // Deserializes properly
     private void readObject(ObjectInputStream s)
         throws IOException, ClassNotFoundException {
       s.defaultReadObject();
       setState(0); // reset to unlocked state
     }
   }

   // The sync object does all the hard work. We just forward to it.
   private final Sync sync = new Sync();

   public void lock()                { sync.acquire(1); }
   public boolean tryLock()          { return sync.tryAcquire(1); }
   public void unlock()              { sync.release(1); }
   public Condition newCondition()   { return sync.newCondition(); }
   public boolean isLocked()         { return sync.isHeldExclusively(); }
   public boolean hasQueuedStrands() { return sync.hasQueuedStrands(); }
   public void lockInterruptibly() throws InterruptedException {
     sync.acquireInterruptibly(1);
   }
   public boolean tryLock(long timeout, TimeUnit unit)
       throws InterruptedException {
     return sync.tryAcquireNanos(1, unit.toNanos(timeout));
   }
 }

Here is a latch class that is like a
 CountDownLatch
 except that it only requires a single signal to
 fire. Because a latch is non-exclusive, it uses the shared
 acquire and release methods.

 class BooleanLatch {

   private static class Sync extends AbstractQueuedSynchronizer {
     boolean isSignalled() { return getState() != 0; }

     protected int tryAcquireShared(int ignore) {
       return isSignalled() ? 1 : -1;
     }

     protected boolean tryReleaseShared(int ignore) {
       setState(1);
       return true;
     }
   }

   private final Sync sync = new Sync();
   public boolean isSignalled() { return sync.isSignalled(); }
   public void signal()         { sync.releaseShared(1); }
   public void await() throws InterruptedException {
     sync.acquireSharedInterruptibly(1);
   }
 }

Since:

1.5

See Also:

Serialized Form

Nested Class Summary

Nested Classes

Modifier and Type
Class
Description

class
AbstractQueuedSynchronizer.ConditionObject

Condition implementation for a AbstractQueuedSynchronizer serving as the basis of a Lock implementation.

Constructor Summary

Constructors

Modifier
Constructor
Description

protected
AbstractQueuedSynchronizer()

Creates a new AbstractQueuedSynchronizer instance
 with initial synchronization state of zero.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method
Description

void
acquire(int arg)

Acquires in exclusive mode, ignoring interrupts.

void
acquireInterruptibly(int arg)

Acquires in exclusive mode, aborting if interrupted.

void
acquireShared(int arg)

Acquires in shared mode, ignoring interrupts.

void
acquireSharedInterruptibly(int arg)

Acquires in shared mode, aborting if interrupted.

protected boolean
compareAndSetState(int expect,
                  int update)

Atomically sets synchronization state to the given updated
 value if the current state value equals the expected value.

java.util.Collection<Strand>
getExclusiveQueuedStrands()

Returns a collection containing strands that may be waiting to
 acquire in exclusive mode.

Strand
getFirstQueuedStrand()

Returns the first (longest-waiting) strand in the queue, or
 null if no strands are currently queued.

java.util.Collection<Strand>
getQueuedStrands()

Returns a collection containing strands that may be waiting to
 acquire.

int
getQueueLength()

Returns an estimate of the number of strands waiting to
 acquire.

java.util.Collection<Strand>
getSharedQueuedStrands()

Returns a collection containing strands that may be waiting to
 acquire in shared mode.

protected int
getState()

Returns the current value of synchronization state.

java.util.Collection<Strand>
getWaitingStrands(AbstractQueuedSynchronizer.ConditionObject condition)

Returns a collection containing those strands that may be
 waiting on the given condition associated with this
 synchronizer.

int
getWaitQueueLength(AbstractQueuedSynchronizer.ConditionObject condition)

Returns an estimate of the number of strands waiting on the
 given condition associated with this synchronizer.

boolean
hasContended()

Queries whether any strands have ever contended to acquire this
 synchronizer; that is if an acquire method has ever blocked.

boolean
hasQueuedPredecessors()

Queries whether any strands have been waiting to acquire longer
 than the current strand.

boolean
hasQueuedStrands()

Queries whether any strands are waiting to acquire.

boolean
hasWaiters(AbstractQueuedSynchronizer.ConditionObject condition)

Queries whether any strands are waiting on the given condition
 associated with this synchronizer.

protected boolean
isHeldExclusively()

Returns true if synchronization is held exclusively with
 respect to the current (calling) strand.

boolean
isQueued(Strand strand)

Returns true if the given strand is currently queued.

boolean
owns(AbstractQueuedSynchronizer.ConditionObject condition)

Queries whether the given ConditionObject
 uses this synchronizer as its lock.

boolean
release(int arg)

Releases in exclusive mode.

boolean
releaseShared(int arg)

Releases in shared mode.

protected void
setState(int newState)

Sets the value of synchronization state.

java.lang.String
toString()

Returns a string identifying this synchronizer, as well as its state.

protected boolean
tryAcquire(int arg)

Attempts to acquire in exclusive mode.

boolean
tryAcquireNanos(int arg,
               long nanosTimeout)

Attempts to acquire in exclusive mode, aborting if interrupted,
 and failing if the given timeout elapses.

protected int
tryAcquireShared(int arg)

Attempts to acquire in shared mode.

boolean
tryAcquireSharedNanos(int arg,
                     long nanosTimeout)

Attempts to acquire in shared mode, aborting if interrupted, and
 failing if the given timeout elapses.

protected boolean
tryRelease(int arg)

Attempts to set the state to reflect a release in exclusive
 mode.

protected boolean
tryReleaseShared(int arg)

Attempts to set the state to reflect a release in shared mode.

Methods inherited from class co.paralleluniverse.strands.concurrent.AbstractOwnableSynchronizer

getExclusiveOwnerStrand, setExclusiveOwnerStrand

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

AbstractQueuedSynchronizer

protected AbstractQueuedSynchronizer()

Creates a new AbstractQueuedSynchronizer instance
 with initial synchronization state of zero.

Method Detail

getState

protected final int getState()

Returns the current value of synchronization state.
 This operation has memory semantics of a volatile read.

Returns:

current state value

setState

protected final void setState(int newState)

Sets the value of synchronization state.
 This operation has memory semantics of a volatile write.

Parameters:

newState - the new state value

compareAndSetState

protected final boolean compareAndSetState(int expect,
                                           int update)

Atomically sets synchronization state to the given updated
 value if the current state value equals the expected value.
 This operation has memory semantics of a volatile read
 and write.

Parameters:

expect - the expected value

update - the new value

Returns:

true if successful. False return indicates that the actual
         value was not equal to the expected value.

tryAcquire

protected boolean tryAcquire(int arg)

Attempts to acquire in exclusive mode. This method should query
 if the state of the object permits it to be acquired in the
 exclusive mode, and if so to acquire it.

This method is always invoked by the strand performing
 acquire.  If this method reports failure, the acquire method
 may queue the strand, if it is not already queued, until it is
 signalled by a release from some other strand. This can be used
 to implement method Lock.tryLock().

The default
 implementation throws UnsupportedOperationException.

Parameters:

arg - the acquire argument. This value is always the one
        passed to an acquire method, or is the value saved on entry
        to a condition wait.  The value is otherwise uninterpreted
        and can represent anything you like.

Returns:

true if successful. Upon success, this object has
         been acquired.

Throws:

java.lang.IllegalMonitorStateException - if acquiring would place this
         synchronizer in an illegal state. This exception must be
         thrown in a consistent fashion for synchronization to work
         correctly.

java.lang.UnsupportedOperationException - if exclusive mode is not supported

tryRelease

protected boolean tryRelease(int arg)

Attempts to set the state to reflect a release in exclusive
 mode.

This method is always invoked by the strand performing release.

The default implementation throws
 UnsupportedOperationException.

Parameters:

arg - the release argument. This value is always the one
        passed to a release method, or the current state value upon
        entry to a condition wait.  The value is otherwise
        uninterpreted and can represent anything you like.

Returns:

true if this object is now in a fully released
         state, so that any waiting strands may attempt to acquire;
         and false otherwise.

Throws:

java.lang.IllegalMonitorStateException - if releasing would place this
         synchronizer in an illegal state. This exception must be
         thrown in a consistent fashion for synchronization to work
         correctly.

java.lang.UnsupportedOperationException - if exclusive mode is not supported

tryAcquireShared

protected int tryAcquireShared(int arg)

Attempts to acquire in shared mode. This method should query if
 the state of the object permits it to be acquired in the shared
 mode, and if so to acquire it.

This method is always invoked by the strand performing
 acquire.  If this method reports failure, the acquire method
 may queue the strand, if it is not already queued, until it is
 signalled by a release from some other strand.

The default implementation throws UnsupportedOperationException.

Parameters:

arg - the acquire argument. This value is always the one
        passed to an acquire method, or is the value saved on entry
        to a condition wait.  The value is otherwise uninterpreted
        and can represent anything you like.

Returns:

a negative value on failure; zero if acquisition in shared
         mode succeeded but no subsequent shared-mode acquire can
         succeed; and a positive value if acquisition in shared
         mode succeeded and subsequent shared-mode acquires might
         also succeed, in which case a subsequent waiting strand
         must check availability. (Support for three different
         return values enables this method to be used in contexts
         where acquires only sometimes act exclusively.)  Upon
         success, this object has been acquired.

Throws:

java.lang.IllegalMonitorStateException - if acquiring would place this
         synchronizer in an illegal state. This exception must be
         thrown in a consistent fashion for synchronization to work
         correctly.

java.lang.UnsupportedOperationException - if shared mode is not supported

tryReleaseShared

protected boolean tryReleaseShared(int arg)

Attempts to set the state to reflect a release in shared mode.

This method is always invoked by the strand performing release.

The default implementation throws
 UnsupportedOperationException.

Parameters:

arg - the release argument. This value is always the one
        passed to a release method, or the current state value upon
        entry to a condition wait.  The value is otherwise
        uninterpreted and can represent anything you like.

Returns:

true if this release of shared mode may permit a
         waiting acquire (shared or exclusive) to succeed; and
         false otherwise

Throws:

java.lang.IllegalMonitorStateException - if releasing would place this
         synchronizer in an illegal state. This exception must be
         thrown in a consistent fashion for synchronization to work
         correctly.

java.lang.UnsupportedOperationException - if shared mode is not supported

isHeldExclusively

protected boolean isHeldExclusively()

Returns true if synchronization is held exclusively with
 respect to the current (calling) strand.  This method is invoked
 upon each call to a non-waiting AbstractQueuedSynchronizer.ConditionObject method.
 (Waiting methods instead invoke release(int).)

The default implementation throws UnsupportedOperationException. This method is invoked
 internally only within AbstractQueuedSynchronizer.ConditionObject methods, so need
 not be defined if conditions are not used.

Returns:

true if synchronization is held exclusively;
         false otherwise

Throws:

java.lang.UnsupportedOperationException - if conditions are not supported

acquire

@Suspendable
public final void acquire(int arg)

Acquires in exclusive mode, ignoring interrupts.  Implemented
 by invoking at least once tryAcquire(int),
 returning on success.  Otherwise the strand is queued, possibly
 repeatedly blocking and unblocking, invoking tryAcquire(int) until success.  This method can be used
 to implement method Lock.lock().

Parameters:

arg - the acquire argument.  This value is conveyed to
        tryAcquire(int) but is otherwise uninterpreted and
        can represent anything you like.

acquireInterruptibly

@Suspendable
public final void acquireInterruptibly(int arg)
                                throws java.lang.InterruptedException

Acquires in exclusive mode, aborting if interrupted.
 Implemented by first checking interrupt status, then invoking
 at least once tryAcquire(int), returning on
 success.  Otherwise the strand is queued, possibly repeatedly
 blocking and unblocking, invoking tryAcquire(int)
 until success or the strand is interrupted.  This method can be
 used to implement method Lock.lockInterruptibly().

Parameters:

arg - the acquire argument.  This value is conveyed to
        tryAcquire(int) but is otherwise uninterpreted and
        can represent anything you like.

Throws:

java.lang.InterruptedException - if the current strand is interrupted

tryAcquireNanos

@Suspendable
public final boolean tryAcquireNanos(int arg,
                                     long nanosTimeout)
                              throws java.lang.InterruptedException

Attempts to acquire in exclusive mode, aborting if interrupted,
 and failing if the given timeout elapses.  Implemented by first
 checking interrupt status, then invoking at least once tryAcquire(int), returning on success.  Otherwise, the strand is
 queued, possibly repeatedly blocking and unblocking, invoking
 tryAcquire(int) until success or the strand is interrupted
 or the timeout elapses.  This method can be used to implement
 method Lock.tryLock(long, TimeUnit).

Parameters:

arg - the acquire argument.  This value is conveyed to
        tryAcquire(int) but is otherwise uninterpreted and
        can represent anything you like.

nanosTimeout - the maximum number of nanoseconds to wait

Returns:

true if acquired; false if timed out

Throws:

java.lang.InterruptedException - if the current strand is interrupted

release

public final boolean release(int arg)

Releases in exclusive mode.  Implemented by unblocking one or
 more strands if tryRelease(int) returns true.
 This method can be used to implement method Lock.unlock().

Parameters:

arg - the release argument.  This value is conveyed to
        tryRelease(int) but is otherwise uninterpreted and
        can represent anything you like.

Returns:

the value returned from tryRelease(int)

acquireShared

@Suspendable
public final void acquireShared(int arg)

Acquires in shared mode, ignoring interrupts.  Implemented by
 first invoking at least once tryAcquireShared(int),
 returning on success.  Otherwise the strand is queued, possibly
 repeatedly blocking and unblocking, invoking tryAcquireShared(int) until success.

Parameters:

arg - the acquire argument.  This value is conveyed to
        tryAcquireShared(int) but is otherwise uninterpreted
        and can represent anything you like.

acquireSharedInterruptibly

@Suspendable
public final void acquireSharedInterruptibly(int arg)
                                      throws java.lang.InterruptedException

Acquires in shared mode, aborting if interrupted.  Implemented
 by first checking interrupt status, then invoking at least once
 tryAcquireShared(int), returning on success.  Otherwise the
 strand is queued, possibly repeatedly blocking and unblocking,
 invoking tryAcquireShared(int) until success or the strand
 is interrupted.

Parameters:

arg - the acquire argument.
 This value is conveyed to tryAcquireShared(int) but is
 otherwise uninterpreted and can represent anything
 you like.

Throws:

java.lang.InterruptedException - if the current strand is interrupted

tryAcquireSharedNanos

@Suspendable
public final boolean tryAcquireSharedNanos(int arg,
                                           long nanosTimeout)
                                    throws java.lang.InterruptedException

Attempts to acquire in shared mode, aborting if interrupted, and
 failing if the given timeout elapses.  Implemented by first
 checking interrupt status, then invoking at least once tryAcquireShared(int), returning on success.  Otherwise, the
 strand is queued, possibly repeatedly blocking and unblocking,
 invoking tryAcquireShared(int) until success or the strand
 is interrupted or the timeout elapses.

Parameters:

arg - the acquire argument.  This value is conveyed to
        tryAcquireShared(int) but is otherwise uninterpreted
        and can represent anything you like.

nanosTimeout - the maximum number of nanoseconds to wait

Returns:

true if acquired; false if timed out

Throws:

java.lang.InterruptedException - if the current strand is interrupted

releaseShared

public final boolean releaseShared(int arg)

Releases in shared mode.  Implemented by unblocking one or more
 strands if tryReleaseShared(int) returns true.

Parameters:

arg - the release argument.  This value is conveyed to
        tryReleaseShared(int) but is otherwise uninterpreted
        and can represent anything you like.

Returns:

the value returned from tryReleaseShared(int)

hasQueuedStrands

public final boolean hasQueuedStrands()

Queries whether any strands are waiting to acquire. Note that
 because cancellations due to interrupts and timeouts may occur
 at any time, a true return does not guarantee that any
 other strand will ever acquire.

In this implementation, this operation returns in
 constant time.

Returns:

true if there may be other strands waiting to acquire

hasContended

public final boolean hasContended()

Queries whether any strands have ever contended to acquire this
 synchronizer; that is if an acquire method has ever blocked.

In this implementation, this operation returns in
 constant time.

Returns:

true if there has ever been contention

getFirstQueuedStrand

public final Strand getFirstQueuedStrand()

Returns the first (longest-waiting) strand in the queue, or
 null if no strands are currently queued.

In this implementation, this operation normally returns in
 constant time, but may iterate upon contention if other strands are
 concurrently modifying the queue.

Returns:

the first (longest-waiting) strand in the queue, or
         null if no strands are currently queued

isQueued

public final boolean isQueued(Strand strand)

Returns true if the given strand is currently queued.

This implementation traverses the queue to determine
 presence of the given strand.

Parameters:

strand - the strand

Returns:

true if the given strand is on the queue

Throws:

java.lang.NullPointerException - if the strand is null

hasQueuedPredecessors

public final boolean hasQueuedPredecessors()

Queries whether any strands have been waiting to acquire longer
 than the current strand.

An invocation of this method is equivalent to (but may be
 more efficient than):

 getFirstQueuedStrand() != Strand.currentStrand() &&
 hasQueuedStrands()

Note that because cancellations due to interrupts and
 timeouts may occur at any time, a true return does not
 guarantee that some other strand will acquire before the current
 strand.  Likewise, it is possible for another strand to win a
 race to enqueue after this method has returned false,
 due to the queue being empty.

This method is designed to be used by a fair synchronizer to
 avoid barging.
 Such a synchronizer's tryAcquire(int) method should return
 false, and its tryAcquireShared(int) method should
 return a negative value, if this method returns true
 (unless this is a reentrant acquire).  For example, the
 tryAcquire method for a fair, reentrant, exclusive mode
 synchronizer might look like this:

 protected boolean tryAcquire(int arg) {
   if (isHeldExclusively()) {
     // A reentrant acquire; increment hold count
     return true;
   } else if (hasQueuedPredecessors()) {
     return false;
   } else {
     // try to acquire normally
   }
 }

Returns:

true if there is a queued strand preceding the
         current strand, and false if the current strand
         is at the head of the queue or the queue is empty

Since:

1.7

getQueueLength

public final int getQueueLength()

Returns an estimate of the number of strands waiting to
 acquire.  The value is only an estimate because the number of
 strands may change dynamically while this method traverses
 internal data structures.  This method is designed for use in
 monitoring system state, not for synchronization
 control.

Returns:

the estimated number of strands waiting to acquire

getQueuedStrands

public final java.util.Collection<Strand> getQueuedStrands()

Returns a collection containing strands that may be waiting to
 acquire.  Because the actual set of strands may change
 dynamically while constructing this result, the returned
 collection is only a best-effort estimate.  The elements of the
 returned collection are in no particular order.  This method is
 designed to facilitate construction of subclasses that provide
 more extensive monitoring facilities.

Returns:

the collection of strands

getExclusiveQueuedStrands

public final java.util.Collection<Strand> getExclusiveQueuedStrands()

Returns a collection containing strands that may be waiting to
 acquire in exclusive mode. This has the same properties
 as getQueuedStrands() except that it only returns
 those strands waiting due to an exclusive acquire.

Returns:

the collection of strands

getSharedQueuedStrands

public final java.util.Collection<Strand> getSharedQueuedStrands()

Returns a collection containing strands that may be waiting to
 acquire in shared mode. This has the same properties
 as getQueuedStrands() except that it only returns
 those strands waiting due to a shared acquire.

Returns:

the collection of strands

toString

public java.lang.String toString()

Returns a string identifying this synchronizer, as well as its state.
 The state, in brackets, includes the String "State ="
 followed by the current value of getState(), and either
 "nonempty" or "empty" depending on whether the
 queue is empty.

Overrides:

toString in class java.lang.Object

Returns:

a string identifying this synchronizer, as well as its state

owns

public final boolean owns(AbstractQueuedSynchronizer.ConditionObject condition)

Queries whether the given ConditionObject
 uses this synchronizer as its lock.

Parameters:

condition - the condition

Returns:

true if owned

Throws:

java.lang.NullPointerException - if the condition is null

hasWaiters

public final boolean hasWaiters(AbstractQueuedSynchronizer.ConditionObject condition)

Queries whether any strands are waiting on the given condition
 associated with this synchronizer. Note that because timeouts
 and interrupts may occur at any time, a true return
 does not guarantee that a future signal will awaken
 any strands.  This method is designed primarily for use in
 monitoring of the system state.

Parameters:

condition - the condition

Returns:

true if there are any waiting strands

Throws:

java.lang.IllegalMonitorStateException - if exclusive synchronization
         is not held

java.lang.IllegalArgumentException - if the given condition is
         not associated with this synchronizer

java.lang.NullPointerException - if the condition is null

getWaitQueueLength

public final int getWaitQueueLength(AbstractQueuedSynchronizer.ConditionObject condition)

Returns an estimate of the number of strands waiting on the
 given condition associated with this synchronizer. Note that
 because timeouts and interrupts may occur at any time, the
 estimate serves only as an upper bound on the actual number of
 waiters.  This method is designed for use in monitoring of the
 system state, not for synchronization control.

Parameters:

condition - the condition

Returns:

the estimated number of waiting strands

Throws:

java.lang.IllegalMonitorStateException - if exclusive synchronization
         is not held

java.lang.IllegalArgumentException - if the given condition is
         not associated with this synchronizer

java.lang.NullPointerException - if the condition is null

getWaitingStrands

public final java.util.Collection<Strand> getWaitingStrands(AbstractQueuedSynchronizer.ConditionObject condition)

Returns a collection containing those strands that may be
 waiting on the given condition associated with this
 synchronizer.  Because the actual set of strands may change
 dynamically while constructing this result, the returned
 collection is only a best-effort estimate. The elements of the
 returned collection are in no particular order.

Parameters:

condition - the condition

Returns:

the collection of strands

Throws:

java.lang.IllegalMonitorStateException - if exclusive synchronization
         is not held

java.lang.IllegalArgumentException - if the given condition is
         not associated with this synchronizer

java.lang.NullPointerException - if the condition is null

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

All Classes

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11134" systemVersion="15F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
    <dependencies>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11106"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--View Controller-->
        <scene sceneID="EHf-IW-A2E">
            <objects>
                <viewController id="01J-lp-oVM" sceneMemberID="viewController">
                    <layoutGuides>
                        <viewControllerLayoutGuide type="top" id="Llm-lL-Icb"/>
                        <viewControllerLayoutGuide type="bottom" id="xb3-aO-Qok"/>
                    </layoutGuides>
                    <view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                    </view>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="53" y="375"/>
        </scene>
    </scenes>
</document>


visionmedia-debug

Nathan Rajlich <nathan@tootallnate.net> (http://n8.io)

visionmedia-debug


package io.parallec.core.filter;

import io.parallec.core.FilterRegex;
import io.parallec.core.TestBase;
import io.parallec.core.util.PcConstants;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.junit.Test;

public class FilterRegexTest extends TestBase {

    @Test
    public void testFilterRegex() {
        String completeRegex = ".*\"progress\"\\s*:\\s*(100).*}";
        FilterRegex.stringMatcherByPattern(null, completeRegex);

        FilterRegex.stringMatcherByPattern(completeRegex, null);
    }

    @Test
    public void testRegex() {

        String completeRegex = ".*\"progress\"\\s*:\\s*(100).*}";
        Pattern patternMetric = Pattern.compile(completeRegex,
                Pattern.MULTILINE);
        String response = "{\"status\": \"/status/e40c0f1e-ddc2-4987-aaa7-b638a9978782\", \"progress\": 100,  \"error\": 300}";

        final Matcher matcher = patternMetric.matcher(response);
        String matchStr = PcConstants.NA;
        if (matcher.matches()) {
            matchStr = matcher.group(1);
        }
        logger.info(matchStr + "");
    }

}


import { connect } from 'react-redux'
import { buyEth, hideModal, showModal, hideWarning } from '../../../../store/actions'
import DepositEtherModal from './deposit-ether-modal.component'

function mapStateToProps (state) {
  return {
    network: state.metamask.network,
    address: state.metamask.selectedAddress,
  }
}

function mapDispatchToProps (dispatch) {
  return {
    toWyre: (address) => {
      dispatch(buyEth({ service: 'wyre', address }))
    },
    toCoinSwitch: (address) => {
      dispatch(buyEth({ service: 'coinswitch', address }))
    },
    hideModal: () => {
      dispatch(hideModal())
    },
    hideWarning: () => {
      dispatch(hideWarning())
    },
    showAccountDetailModal: () => {
      dispatch(showModal({ name: 'ACCOUNT_DETAILS' }))
    },
    toFaucet: (network) => dispatch(buyEth({ network })),
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(DepositEtherModal)


// The MIT License (MIT)
//
// Copyright (c) 2015 Arian Fornaris
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions: The above copyright notice and this permission
// notice shall be included in all copies or substantial portions of the
// Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
package phasereditor.assetpack.ui;

import java.util.List;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.IFontProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

import phasereditor.ui.FilteredTreeCanvas;
import phasereditor.ui.ImageProxy;
import phasereditor.ui.ImageProxyTreeCanvasItemRenderer;
import phasereditor.ui.TreeArrayContentProvider;
import phasereditor.ui.TreeCanvas;
import phasereditor.ui.TreeCanvasViewer;
import phasereditor.ui.TreeCanvas.TreeCanvasItem;

public class ImageResourceDialog extends Dialog {
	private TreeCanvasViewer _listViewer;
	private Object _selection;
	private Label _messageLabel;
	private TreeCanvas _treeCanvas;

	/**
	 * Create the dialog.
	 *
	 * @param parentShell
	 */
	public ImageResourceDialog(Shell parentShell) {
		super(parentShell);
		setShellStyle(SWT.DIALOG_TRIM | SWT.RESIZE);
	}

	/**
	 * Create contents of the dialog.
	 *
	 * @param parent
	 */
	@Override
	protected Control createDialogArea(Composite parent) {
		Composite container = (Composite) super.createDialogArea(parent);
		container.setLayout(new GridLayout(1, false));

		Composite composite_1 = new Composite(container, SWT.NONE);
		GridData gd_composite_1 = new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1);
		gd_composite_1.verticalIndent = 10;
		composite_1.setLayoutData(gd_composite_1);
		composite_1.setLayout(new GridLayout(1, false));

		_messageLabel = new Label(composite_1, SWT.NONE);
		_messageLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		_messageLabel.setText("Select the yyy image. Those in bold are not used in this pack.");

		Composite composite = new Composite(container, SWT.NONE);
		GridData gd_composite = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
		gd_composite.verticalIndent = 10;
		composite.setLayoutData(gd_composite);
		GridLayout gl_composite = new GridLayout(2, true);
		composite.setLayout(gl_composite);

		var filteredTree = new FilteredTreeCanvas(composite, SWT.BORDER);
		filteredTree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1));
		_treeCanvas = filteredTree.getTree();
		_listViewer = createViewer();

		_imagePreviewCanvas = new ImagePreviewComp(composite, SWT.BORDER);
		_imagePreviewCanvas.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		_listViewer.setContentProvider(new TreeArrayContentProvider());
		_listViewer.setLabelProvider(new LabelProvider());

		return container;
	}

	private TreeCanvasViewer createViewer() {
		return new TreeCanvasViewer(_treeCanvas) {
			@Override
			protected void setItemProperties(TreeCanvasItem item) {
				super.setItemProperties(item);

				var file = (IFile) item.getData();

				item.setRenderer(new ImageProxyTreeCanvasItemRenderer(item, ImageProxy.get(file, null)) {
					@Override
					public void render(PaintEvent e, int index, int x, int y) {
						var oldFont = e.gc.getFont();

						if (getLabelProvider() instanceof IFontProvider) {
							var font = ((IFontProvider) getLabelProvider()).getFont(_item.getData());
							if (font != null) {

								e.gc.setFont(font);
							}
						}

						super.render(e, index, x, y);

						e.gc.setFont(oldFont);
					}
				});
			}
		};
	}

	private LabelProvider _labelProvider;
	private Object _input;
	private ImagePreviewComp _imagePreviewCanvas;
	private IResource _initial;
	private String _objectName;
	private List<Object> _multiSelection;

	@Override
	protected Control createContents(Composite parent) {
		Control control = super.createContents(parent);

		if (_labelProvider != null) {
			_listViewer.setLabelProvider(_labelProvider);
		}

		if (_input != null) {
			_listViewer.setInput(_input);
		}

		_listViewer.getTree().addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDoubleClick(MouseEvent e) {
				okPressed();
			}
		});

		_listViewer.addSelectionChangedListener(new ISelectionChangedListener() {

			@Override
			public void selectionChanged(SelectionChangedEvent event) {
				getPreview().setImageFile((IFile) ((IStructuredSelection) event.getSelection()).getFirstElement());
			}
		});

		if (_initial != null) {
			_listViewer.setSelection(new StructuredSelection(_initial), true);
		}

		if (_objectName != null) {
			_messageLabel.setText("Select the " + _objectName + " image. Those in bold are not used in this pack.");
		}

		return control;
	}

	public void setObjectName(String objectName) {
		_objectName = objectName;
	}

	public void setLabelProvider(LabelProvider labelProvider) {
		_labelProvider = labelProvider;
	}

	public LabelProvider getLabelProvider() {
		return _labelProvider;
	}

	public void setInput(Object input) {
		_input = input;
	}

	public Object getInput() {
		return _input;
	}

	/**
	 * Create contents of the button bar.
	 *
	 * @param parent
	 */
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
		createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void okPressed() {
		_selection = ((IStructuredSelection) _listViewer.getSelection()).getFirstElement();
		_multiSelection = ((IStructuredSelection) _listViewer.getSelection()).toList();
		super.okPressed();
	}

	public Object getSelection() {
		return _selection;
	}

	public List<Object> getMultipleSelection() {
		return _multiSelection;
	}

	public ImagePreviewComp getPreview() {
		return _imagePreviewCanvas;
	}

	@Override
	protected Point getInitialSize() {
		return new Point(720, 600);
	}

	@Override
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText(_objectName == null ? "Image" : _objectName);
	}

	public void setInitial(IResource initial) {
		_initial = initial;
	}

}


/***
  Copyright (c) 2012 CommonsWare, LLC
  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.

  Covered in detail in the book _The Busy Coder's Guide to Android Development_
    https://commonsware.com/Android
 */

package com.commonsware.android.eventbus.greenrobot;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;

public class PollReceiver extends BroadcastReceiver {
  private static final int PERIOD=60000; // 1 minute
  private static final int INITIAL_DELAY=5000; // 5 seconds

  @Override
  public void onReceive(Context ctxt, Intent i) {
    if (i.getAction() == null) {
      ScheduledService.enqueueWork(ctxt);
    }
    else {
      scheduleAlarms(ctxt);
    }
  }

  static void scheduleAlarms(Context ctxt) {
    AlarmManager mgr=
        (AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
    Intent i=new Intent(ctxt, PollReceiver.class);
    PendingIntent pi=PendingIntent.getBroadcast(ctxt, 0, i, 0);

    mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                     SystemClock.elapsedRealtime() + INITIAL_DELAY,
                     PERIOD, pi);

  }
}


class CommentSweeper < ActionController::Caching::Sweeper
  include Mephisto::SweeperMethods
  observe Comment

  # only sweep updates, not creations
  # tagged 'lame hack'
  def before_save(record)
    @new = record.new_record?
  end

  def after_save(record)
    return if controller.nil? || (@new && !record.approved?)
    expire_overview_feed!
    expire_cache_for record
  end

  def after_destroy(record)
    return if controller.nil?
    expire_overview_feed!
    expire_cache_for record if record.approved?
  end

  protected
    def expire_cache_for(comment)
      pages = site.cached_pages.find_by_references(comment, comment.article)
      site.expire_cached_pages controller, "Expired pages referenced by #{comment.class} ##{comment.id}", pages
    end
end


.so man3/rtapi_prio.3rtapi


/***** includes *****/
#include "lfds700_ringbuffer_internal.h"

/***** private prototypes *****/
static void lfds700_ringbuffer_internal_queue_element_cleanup_callback( struct lfds700_queue_state *qs, struct lfds700_queue_element *qe, enum lfds700_misc_flag dummy_element_flag );
static void lfds700_ringbuffer_internal_freelist_element_cleanup_callback( struct lfds700_freelist_state *fs, struct lfds700_freelist_element *fe );

/****************************************************************************/
void lfds700_ringbuffer_cleanup( struct lfds700_ringbuffer_state *rs,
                                 void (*element_cleanup_callback)(struct lfds700_ringbuffer_state *rs, void *key, void *value, enum lfds700_misc_flag unread_flag) )
{
  LFDS700_PAL_ASSERT( rs != NULL );
  // TRD : element_cleanup_callback can be NULL

  if( element_cleanup_callback != NULL )
  {
    rs->element_cleanup_callback = element_cleanup_callback;
    lfds700_queue_cleanup( &rs->qs, lfds700_ringbuffer_internal_queue_element_cleanup_callback );
    lfds700_freelist_cleanup( &rs->fs, lfds700_ringbuffer_internal_freelist_element_cleanup_callback );
  }

  return;
}

/****************************************************************************/
#pragma warning( disable : 4100 )

static void lfds700_ringbuffer_internal_queue_element_cleanup_callback( struct lfds700_queue_state *qs, struct lfds700_queue_element *qe, enum lfds700_misc_flag dummy_element_flag )
{
  struct lfds700_ringbuffer_element
    *re;

  struct lfds700_ringbuffer_state
    *rs;

  LFDS700_PAL_ASSERT( qs != NULL );
  LFDS700_PAL_ASSERT( qe != NULL );
  // TRD : dummy_element can be any value in its range

  rs = (struct lfds700_ringbuffer_state *) LFDS700_QUEUE_GET_USER_STATE_FROM_STATE( *qs );
  re = (struct lfds700_ringbuffer_element *) LFDS700_QUEUE_GET_VALUE_FROM_ELEMENT( *qe );

  if( dummy_element_flag == LFDS700_MISC_FLAG_LOWERED )
    rs->element_cleanup_callback( rs, re->key, re->value, LFDS700_MISC_FLAG_RAISED );

  return;
}

#pragma warning( default : 4100 )

/****************************************************************************/
#pragma warning( disable : 4100 )

static void lfds700_ringbuffer_internal_freelist_element_cleanup_callback( struct lfds700_freelist_state *fs, struct lfds700_freelist_element *fe )
{
  struct lfds700_ringbuffer_element
    *re;

  struct lfds700_ringbuffer_state
    *rs;

  LFDS700_PAL_ASSERT( fs != NULL );
  LFDS700_PAL_ASSERT( fe != NULL );

  rs = (struct lfds700_ringbuffer_state *) LFDS700_FREELIST_GET_USER_STATE_FROM_STATE( *fs );
  re = (struct lfds700_ringbuffer_element *) LFDS700_FREELIST_GET_VALUE_FROM_ELEMENT( *fe );

  rs->element_cleanup_callback( rs, re->key, re->value, LFDS700_MISC_FLAG_LOWERED );

  return;
}

#pragma warning( default : 4100 )


/*
 * Copyright (c) 2018 THL A29 Limited, a Tencent company. 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.
 */
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace TencentCloud.Common
{
    public abstract class AbstractModel
    {
        internal abstract void ToMap(Dictionary<string, string> map, string prefix);

        protected void SetParamSimple<V>(Dictionary<string, string> map, String key, V value)
        {
            if ((value!= null) && !value.Equals(default(V)) )
            {
                key = key.Substring(0, 1).ToUpper() + key.Substring(1);
                key = key.Replace("_", ".");
                map.Add(key, value.ToString());
            }
        }

        protected void SetParamArraySimple<V>(Dictionary<string, string> map, string prefix, V[] array)
        {
            if (array != null)
            {
                for (int i = 0; i < array.Length; i++)
                {
                    this.SetParamSimple<V>(map, prefix + i, array[i]);
                }
            }
        }

        protected void SetParamObj<V>(Dictionary<string, string> map, String prefix, V obj)  where V: AbstractModel
        {
            if (obj != null)
            {
                obj.ToMap(map, prefix);
            }
        }

        protected  void SetParamArrayObj<V>(Dictionary<String, String> map, String prefix, V[] array) where V : AbstractModel
        {
            if (array != null)
            {
                for (int i = 0; i < array.Length; i++)
                {
                    this.SetParamObj<V>(map, prefix + i + ".", array[i]);
                }
            }
        }

        /// <summary>
        /// Serialize an obect of AbstractModel into JSON string.
        /// </summary>
        /// <typeparam name="V">A class inherited from AbstrctModel.</typeparam>
        /// <param name="obj">An object of the class.</param>
        /// <returns>JSON formatted string.</returns>
        public static string ToJsonString<V>(V obj) where V: AbstractModel
        {
            return JsonConvert.SerializeObject(obj);
        }

        /// <summary>
        /// Deserialize JSON formatted string into an object of a class inherited from AbstractModel.
        /// </summary>
        /// <typeparam name="V">A class inherited from AbstrctModel.</typeparam>
        /// <param name="json">JSON formatted string.</param>
        /// <returns>An object of the class.</returns>
        public static V FromJsonString<V>(string json)
        {
            return JsonConvert.DeserializeObject<V>(json);
        }
    }
}