repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
Bridg/hydra-1
warden/warden_http.go
2295
package warden import ( "net/http" "net/url" "github.com/ory-am/fosite" "github.com/ory-am/hydra/firewall" "github.com/ory-am/hydra/pkg" "github.com/pkg/errors" "golang.org/x/net/context" "golang.org/x/oauth2" "golang.org/x/oauth2/clientcredentials" ) type HTTPWarden struct { Client *http.Client Dry bool Endpoint *url.URL } func (w *HTTPWarden) TokenFromRequest(r *http.Request) string { return fosite.AccessTokenFromRequest(r) } func (w *HTTPWarden) SetClient(c *clientcredentials.Config) { w.Client = c.Client(oauth2.NoContext) } // TokenAllowed checks if a token is valid and if the token owner is allowed to perform an action on a resource. // This endpoint requires a token, a scope, a resource name, an action name and a context. // // The HTTP API is documented at http://docs.hydra13.apiary.io/#reference/warden:-access-control-for-resource-providers/check-if-an-access-tokens-subject-is-allowed-to-do-something func (w *HTTPWarden) TokenAllowed(ctx context.Context, token string, a *firewall.TokenAccessRequest, scopes ...string) (*firewall.Context, error) { var resp = struct { *firewall.Context Allowed bool `json:"allowed"` }{} var ep = *w.Endpoint ep.Path = TokenAllowedHandlerPath agent := &pkg.SuperAgent{URL: ep.String(), Client: w.Client} if err := agent.POST(&wardenAccessRequest{ wardenAuthorizedRequest: &wardenAuthorizedRequest{ Token: token, Scopes: scopes, }, TokenAccessRequest: a, }, &resp); err != nil { return nil, err } else if !resp.Allowed { return nil, errors.New("Token is not valid") } return resp.Context, nil } // IsAllowed checks if an arbitrary subject is allowed to perform an action on a resource. // // The HTTP API is documented at http://docs.hydra13.apiary.io/#reference/warden:-access-control-for-resource-providers/check-if-a-subject-is-allowed-to-do-something func (w *HTTPWarden) IsAllowed(ctx context.Context, a *firewall.AccessRequest) error { var allowed = struct { Allowed bool `json:"allowed"` }{} var ep = *w.Endpoint ep.Path = AllowedHandlerPath agent := &pkg.SuperAgent{URL: ep.String(), Client: w.Client} if err := agent.POST(a, &allowed); err != nil { return err } else if !allowed.Allowed { return errors.Wrap(fosite.ErrRequestForbidden, "") } return nil }
apache-2.0
escapin/ElectionManager
ElectionHandler/refreshConfig.sh
348
#!/bin/bash node ../sElect/tools/config2js.js config.json > webapp/js/config.js configRaw node ../sElect/tools/config2js.js ../_configFiles_/handlerConfigFile.json > webapp/js/ElectionConfigFile.js electionConfigRaw node ../sElect/tools/config2js.js ../_configFiles_/serverAddresses.json > webapp/js/serverAddresses.js sAddressesRaw 2>/dev/null
apache-2.0
qingyuancloud/qingyuan
release-0.19.0/docs/getting-started-guides/coreos/bare_metal_offline.md
26138
# Bare Metal CoreOS with QingYuan (OFFLINE) Deploy a CoreOS running QingYuan environment. This particular guild is made to help those in an OFFLINE system, wither for testing a POC before the real deal, or you are restricted to be totally offline for your applications. ## High Level Design 1. Manage the tftp directory * /tftpboot/(coreos)(centos)(RHEL) * /tftpboot/pxelinux.0/(MAC) -> linked to Linux image config file 2. Update per install the link for pxelinux 3. Update the DHCP config to reflect the host needing deployment 4. Setup nodes to deploy CoreOS creating a etcd cluster. 5. Have no access to the public [etcd discovery tool](https://discovery.etcd.io/). 6. Installing the CoreOS slaves to become QingYuan minions. ## Pre-requisites 1. Installed *CentOS 6* for PXE server 2. At least two bare metal nodes to work with ## This Guides variables | Node Description | MAC | IP | | :---------------------------- | :---------------: | :---------: | | CoreOS/etcd/QingYuan Master | d0:00:67:13:0d:00 | 10.20.30.40 | | CoreOS Slave 1 | d0:00:67:13:0d:01 | 10.20.30.41 | | CoreOS Slave 2 | d0:00:67:13:0d:02 | 10.20.30.42 | ## Setup PXELINUX CentOS To setup CentOS PXELINUX environment there is a complete [guide here](http://docs.fedoraproject.org/en-US/Fedora/7/html/Installation_Guide/ap-pxe-server.html). This section is the abbreviated version. 1. Install packages needed on CentOS sudo yum install tftp-server dhcp syslinux 2. ```vi /etc/xinetd.d/tftp``` to enable tftp service and change disable to 'no' disable = no 3. Copy over the syslinux images we will need. su - mkdir -p /tftpboot cd /tftpboot cp /usr/share/syslinux/pxelinux.0 /tftpboot cp /usr/share/syslinux/menu.c32 /tftpboot cp /usr/share/syslinux/memdisk /tftpboot cp /usr/share/syslinux/mboot.c32 /tftpboot cp /usr/share/syslinux/chain.c32 /tftpboot /sbin/service dhcpd start /sbin/service xinetd start /sbin/chkconfig tftp on 4. Setup default boot menu mkdir /tftpboot/pxelinux.cfg touch /tftpboot/pxelinux.cfg/default 5. Edit the menu ```vi /tftpboot/pxelinux.cfg/default``` default menu.c32 prompt 0 timeout 15 ONTIMEOUT local display boot.msg MENU TITLE Main Menu LABEL local MENU LABEL Boot local hard drive LOCALBOOT 0 Now you should have a working PXELINUX setup to image CoreOS nodes. You can verify the services by using VirtualBox locally or with bare metal servers. ## Adding CoreOS to PXE This section describes how to setup the CoreOS images to live alongside a pre-existing PXELINUX environment. 1. Find or create the TFTP root directory that everything will be based off of. * For this document we will assume ```/tftpboot/``` is our root directory. 2. Once we know and have our tftp root directory we will create a new directory structure for our CoreOS images. 3. Download the CoreOS PXE files provided by the CoreOS team. MY_TFTPROOT_DIR=/tftpboot mkdir -p $MY_TFTPROOT_DIR/images/coreos/ cd $MY_TFTPROOT_DIR/images/coreos/ wget http://stable.release.core-os.net/amd64-usr/current/coreos_production_pxe.vmlinuz wget http://stable.release.core-os.net/amd64-usr/current/coreos_production_pxe.vmlinuz.sig wget http://stable.release.core-os.net/amd64-usr/current/coreos_production_pxe_image.cpio.gz wget http://stable.release.core-os.net/amd64-usr/current/coreos_production_pxe_image.cpio.gz.sig gpg --verify coreos_production_pxe.vmlinuz.sig gpg --verify coreos_production_pxe_image.cpio.gz.sig 4. Edit the menu ```vi /tftpboot/pxelinux.cfg/default``` again default menu.c32 prompt 0 timeout 300 ONTIMEOUT local display boot.msg MENU TITLE Main Menu LABEL local MENU LABEL Boot local hard drive LOCALBOOT 0 MENU BEGIN CoreOS Menu LABEL coreos-master MENU LABEL CoreOS Master KERNEL images/coreos/coreos_production_pxe.vmlinuz APPEND initrd=images/coreos/coreos_production_pxe_image.cpio.gz cloud-config-url=http://<xxx.xxx.xxx.xxx>/pxe-cloud-config-single-master.yml LABEL coreos-slave MENU LABEL CoreOS Slave KERNEL images/coreos/coreos_production_pxe.vmlinuz APPEND initrd=images/coreos/coreos_production_pxe_image.cpio.gz cloud-config-url=http://<xxx.xxx.xxx.xxx>/pxe-cloud-config-slave.yml MENU END This configuration file will now boot from local drive but have the option to PXE image CoreOS. ## DHCP configuration This section covers configuring the DHCP server to hand out our new images. In this case we are assuming that there are other servers that will boot alongside other images. 1. Add the ```filename``` to the _host_ or _subnet_ sections. filename "/tftpboot/pxelinux.0"; 2. At this point we want to make pxelinux configuration files that will be the templates for the different CoreOS deployments. subnet 10.20.30.0 netmask 255.255.255.0 { next-server 10.20.30.242; option broadcast-address 10.20.30.255; filename "<other default image>"; ... # http://www.syslinux.org/wiki/index.php/PXELINUX host core_os_master { hardware ethernet d0:00:67:13:0d:00; option routers 10.20.30.1; fixed-address 10.20.30.40; option domain-name-servers 10.20.30.242; filename "/pxelinux.0"; } host core_os_slave { hardware ethernet d0:00:67:13:0d:01; option routers 10.20.30.1; fixed-address 10.20.30.41; option domain-name-servers 10.20.30.242; filename "/pxelinux.0"; } host core_os_slave2 { hardware ethernet d0:00:67:13:0d:02; option routers 10.20.30.1; fixed-address 10.20.30.42; option domain-name-servers 10.20.30.242; filename "/pxelinux.0"; } ... } We will be specifying the node configuration later in the guide. # QingYuan To deploy our configuration we need to create an ```etcd``` master. To do so we want to pxe CoreOS with a specific cloud-config.yml. There are two options we have here. 1. Is to template the cloud config file and programmatically create new static configs for different cluster setups. 2. Have a service discovery protocol running in our stack to do auto discovery. This demo we just make a static single ```etcd``` server to host our QingYuan and ```etcd``` master servers. Since we are OFFLINE here most of the helping processes in CoreOS and QingYuan are then limited. To do our setup we will then have to download and serve up our binaries for QingYuan in our local environment. An easy solution is to host a small web server on the DHCP/TFTP host for all our binaries to make them available to the local CoreOS PXE machines. To get this up and running we are going to setup a simple ```apache``` server to serve our binaries needed to bootstrap QingYuan. This is on the PXE server from the previous section: rm /etc/httpd/conf.d/welcome.conf cd /var/www/html/ wget -O qing-register https://github.com/kelseyhightower/qing-register/releases/download/v0.0.2/qing-register-0.0.2-linux-amd64 wget -O setup-network-environment https://github.com/kelseyhightower/setup-network-environment/releases/download/v1.0.0/setup-network-environment wget https://storage.googleapis.com/kubernetes-release/release/v0.15.0/bin/linux/amd64/qingyuan --no-check-certificate wget https://storage.googleapis.com/kubernetes-release/release/v0.15.0/bin/linux/amd64/qing-apiserver --no-check-certificate wget https://storage.googleapis.com/kubernetes-release/release/v0.15.0/bin/linux/amd64/qing-controller-manager --no-check-certificate wget https://storage.googleapis.com/kubernetes-release/release/v0.15.0/bin/linux/amd64/qing-scheduler --no-check-certificate wget https://storage.googleapis.com/kubernetes-release/release/v0.15.0/bin/linux/amd64/qingctl --no-check-certificate wget https://storage.googleapis.com/kubernetes-release/release/v0.15.0/bin/linux/amd64/qingcfg --no-check-certificate wget https://storage.googleapis.com/kubernetes-release/release/v0.15.0/bin/linux/amd64/qinglet --no-check-certificate wget https://storage.googleapis.com/kubernetes-release/release/v0.15.0/bin/linux/amd64/qing-proxy --no-check-certificate wget -O flanneld https://storage.googleapis.com/k8s/flanneld --no-check-certificate This sets up our binaries we need to run QingYuan. This would need to be enhanced to download from the Internet for updates in the future. Now for the good stuff! ## Cloud Configs The following config files are tailored for the OFFLINE version of a QingYuan deployment. These are based on the work found here: [master.yml](http://docs.k8s.io/getting-started-guides/coreos/cloud-configs/master.yaml), [node.yml](http://docs.k8s.io/getting-started-guides/coreos/cloud-configs/node.yaml) To make the setup work, you need to replace a few placeholders: - Replace `<PXE_SERVER_IP>` with your PXE server ip address (e.g. 10.20.30.242) - Replace `<MASTER_SERVER_IP>` with the qingyuan master ip address (e.g. 10.20.30.40) - If you run a private docker registry, replace `rdocker.example.com` with your docker registry dns name. - If you use a proxy, replace `rproxy.example.com` with your proxy server (and port) - Add your own SSH public key(s) to the cloud config at the end ### master.yml On the PXE server make and fill in the variables ```vi /var/www/html/coreos/pxe-cloud-config-master.yml```. #cloud-config --- write_files: - path: /opt/bin/waiter.sh owner: root content: | #! /usr/bin/bash until curl http://127.0.0.1:4001/v2/machines; do sleep 2; done - path: /opt/bin/qingyuan-download.sh owner: root permissions: 0755 content: | #! /usr/bin/bash /usr/bin/wget -N -P "/opt/bin" "http://<PXE_SERVER_IP>/qingctl" /usr/bin/wget -N -P "/opt/bin" "http://<PXE_SERVER_IP>/qingyuan" /usr/bin/wget -N -P "/opt/bin" "http://<PXE_SERVER_IP>/qingcfg" chmod +x /opt/bin/* - path: /etc/profile.d/opt-path.sh owner: root permissions: 0755 content: | #! /usr/bin/bash PATH=$PATH/opt/bin coreos: units: - name: 10-eno1.network runtime: true content: | [Match] Name=eno1 [Network] DHCP=yes - name: 20-nodhcp.network runtime: true content: | [Match] Name=en* [Network] DHCP=none - name: get-qing-tools.service runtime: true command: start content: | [Service] ExecStartPre=-/usr/bin/mkdir -p /opt/bin ExecStart=/opt/bin/qingyuan-download.sh RemainAfterExit=yes Type=oneshot - name: setup-network-environment.service command: start content: | [Unit] Description=Setup Network Environment Documentation=https://github.com/kelseyhightower/setup-network-environment Requires=network-online.target After=network-online.target [Service] ExecStartPre=-/usr/bin/mkdir -p /opt/bin ExecStartPre=/usr/bin/wget -N -P /opt/bin http://<PXE_SERVER_IP>/setup-network-environment ExecStartPre=/usr/bin/chmod +x /opt/bin/setup-network-environment ExecStart=/opt/bin/setup-network-environment RemainAfterExit=yes Type=oneshot - name: etcd.service command: start content: | [Unit] Description=etcd Requires=setup-network-environment.service After=setup-network-environment.service [Service] EnvironmentFile=/etc/network-environment User=etcd PermissionsStartOnly=true ExecStart=/usr/bin/etcd \ --name ${DEFAULT_IPV4} \ --addr ${DEFAULT_IPV4}:4001 \ --bind-addr 0.0.0.0 \ --cluster-active-size 1 \ --data-dir /var/lib/etcd \ --http-read-timeout 86400 \ --peer-addr ${DEFAULT_IPV4}:7001 \ --snapshot true Restart=always RestartSec=10s - name: fleet.socket command: start content: | [Socket] ListenStream=/var/run/fleet.sock - name: fleet.service command: start content: | [Unit] Description=fleet daemon Wants=etcd.service After=etcd.service Wants=fleet.socket After=fleet.socket [Service] Environment="FLEET_ETCD_SERVERS=http://127.0.0.1:4001" Environment="FLEET_METADATA=role=master" ExecStart=/usr/bin/fleetd Restart=always RestartSec=10s - name: etcd-waiter.service command: start content: | [Unit] Description=etcd waiter Wants=network-online.target Wants=etcd.service After=etcd.service After=network-online.target Before=flannel.service Before=setup-network-environment.service [Service] ExecStartPre=/usr/bin/chmod +x /opt/bin/waiter.sh ExecStart=/usr/bin/bash /opt/bin/waiter.sh RemainAfterExit=true Type=oneshot - name: flannel.service command: start content: | [Unit] Wants=etcd-waiter.service After=etcd-waiter.service Requires=etcd.service After=etcd.service After=network-online.target Wants=network-online.target Description=flannel is an etcd backed overlay network for containers [Service] Type=notify ExecStartPre=-/usr/bin/mkdir -p /opt/bin ExecStartPre=/usr/bin/wget -N -P /opt/bin http://<PXE_SERVER_IP>/flanneld ExecStartPre=/usr/bin/chmod +x /opt/bin/flanneld ExecStartPre=-/usr/bin/etcdctl mk /coreos.com/network/config '{"Network":"10.100.0.0/16", "Backend": {"Type": "vxlan"}}' ExecStart=/opt/bin/flanneld - name: qing-apiserver.service command: start content: | [Unit] Description=QingYuan API Server Documentation=https://github.com/qingyuancloud/QingYuan Requires=etcd.service After=etcd.service [Service] ExecStartPre=-/usr/bin/mkdir -p /opt/bin ExecStartPre=/usr/bin/wget -N -P /opt/bin http://<PXE_SERVER_IP>/qing-apiserver ExecStartPre=/usr/bin/chmod +x /opt/bin/qing-apiserver ExecStart=/opt/bin/qing-apiserver \ --address=0.0.0.0 \ --port=8080 \ --service-cluster-ip-range=10.100.0.0/16 \ --etcd_servers=http://127.0.0.1:4001 \ --logtostderr=true Restart=always RestartSec=10 - name: qing-controller-manager.service command: start content: | [Unit] Description=QingYuan Controller Manager Documentation=https://github.com/qingyuancloud/QingYuan Requires=qing-apiserver.service After=qing-apiserver.service [Service] ExecStartPre=/usr/bin/wget -N -P /opt/bin http://<PXE_SERVER_IP>/qing-controller-manager ExecStartPre=/usr/bin/chmod +x /opt/bin/qing-controller-manager ExecStart=/opt/bin/qing-controller-manager \ --master=127.0.0.1:8080 \ --logtostderr=true Restart=always RestartSec=10 - name: qing-scheduler.service command: start content: | [Unit] Description=QingYuan Scheduler Documentation=https://github.com/qingyuancloud/QingYuan Requires=qing-apiserver.service After=qing-apiserver.service [Service] ExecStartPre=/usr/bin/wget -N -P /opt/bin http://<PXE_SERVER_IP>/qing-scheduler ExecStartPre=/usr/bin/chmod +x /opt/bin/qing-scheduler ExecStart=/opt/bin/qing-scheduler --master=127.0.0.1:8080 Restart=always RestartSec=10 - name: qing-register.service command: start content: | [Unit] Description=QingYuan Registration Service Documentation=https://github.com/kelseyhightower/qing-register Requires=qing-apiserver.service After=qing-apiserver.service Requires=fleet.service After=fleet.service [Service] ExecStartPre=/usr/bin/wget -N -P /opt/bin http://<PXE_SERVER_IP>/qing-register ExecStartPre=/usr/bin/chmod +x /opt/bin/qing-register ExecStart=/opt/bin/qing-register \ --metadata=role=node \ --fleet-endpoint=unix:///var/run/fleet.sock \ --healthz-port=10248 \ --api-endpoint=http://127.0.0.1:8080 Restart=always RestartSec=10 update: group: stable reboot-strategy: off ssh_authorized_keys: - ssh-rsa AAAAB3NzaC1yc2EAAAAD... ### node.yml On the PXE server make and fill in the variables ```vi /var/www/html/coreos/pxe-cloud-config-slave.yml```. #cloud-config --- write_files: - path: /etc/default/docker content: | DOCKER_EXTRA_OPTS='--insecure-registry="rdocker.example.com:5000"' coreos: units: - name: 10-eno1.network runtime: true content: | [Match] Name=eno1 [Network] DHCP=yes - name: 20-nodhcp.network runtime: true content: | [Match] Name=en* [Network] DHCP=none - name: etcd.service mask: true - name: docker.service drop-ins: - name: 50-insecure-registry.conf content: | [Service] Environment="HTTP_PROXY=http://rproxy.example.com:3128/" "NO_PROXY=localhost,127.0.0.0/8,rdocker.example.com" - name: fleet.service command: start content: | [Unit] Description=fleet daemon Wants=fleet.socket After=fleet.socket [Service] Environment="FLEET_ETCD_SERVERS=http://<MASTER_SERVER_IP>:4001" Environment="FLEET_METADATA=role=node" ExecStart=/usr/bin/fleetd Restart=always RestartSec=10s - name: flannel.service command: start content: | [Unit] After=network-online.target Wants=network-online.target Description=flannel is an etcd backed overlay network for containers [Service] Type=notify ExecStartPre=-/usr/bin/mkdir -p /opt/bin ExecStartPre=/usr/bin/wget -N -P /opt/bin http://<PXE_SERVER_IP>/flanneld ExecStartPre=/usr/bin/chmod +x /opt/bin/flanneld ExecStart=/opt/bin/flanneld -etcd-endpoints http://<MASTER_SERVER_IP>:4001 - name: docker.service command: start content: | [Unit] After=flannel.service Wants=flannel.service Description=Docker Application Container Engine Documentation=http://docs.docker.io [Service] EnvironmentFile=-/etc/default/docker EnvironmentFile=/run/flannel/subnet.env ExecStartPre=/bin/mount --make-rprivate / ExecStart=/usr/bin/docker -d --bip=${FLANNEL_SUBNET} --mtu=${FLANNEL_MTU} -s=overlay -H fd:// ${DOCKER_EXTRA_OPTS} [Install] WantedBy=multi-user.target - name: setup-network-environment.service command: start content: | [Unit] Description=Setup Network Environment Documentation=https://github.com/kelseyhightower/setup-network-environment Requires=network-online.target After=network-online.target [Service] ExecStartPre=-/usr/bin/mkdir -p /opt/bin ExecStartPre=/usr/bin/wget -N -P /opt/bin http://<PXE_SERVER_IP>/setup-network-environment ExecStartPre=/usr/bin/chmod +x /opt/bin/setup-network-environment ExecStart=/opt/bin/setup-network-environment RemainAfterExit=yes Type=oneshot - name: qing-proxy.service command: start content: | [Unit] Description=QingYuan Proxy Documentation=https://github.com/qingyuancloud/QingYuan Requires=setup-network-environment.service After=setup-network-environment.service [Service] ExecStartPre=/usr/bin/wget -N -P /opt/bin http://<PXE_SERVER_IP>/qing-proxy ExecStartPre=/usr/bin/chmod +x /opt/bin/qing-proxy ExecStart=/opt/bin/qing-proxy \ --etcd_servers=http://<MASTER_SERVER_IP>:4001 \ --logtostderr=true Restart=always RestartSec=10 - name: qing-qinglet.service command: start content: | [Unit] Description=QingYuan Qinglet Documentation=https://github.com/qingyuancloud/QingYuan Requires=setup-network-environment.service After=setup-network-environment.service [Service] EnvironmentFile=/etc/network-environment ExecStartPre=/usr/bin/wget -N -P /opt/bin http://<PXE_SERVER_IP>/qinglet ExecStartPre=/usr/bin/chmod +x /opt/bin/qinglet ExecStart=/opt/bin/qinglet \ --address=0.0.0.0 \ --port=10250 \ --hostname_override=${DEFAULT_IPV4} \ --api_servers=<MASTER_SERVER_IP>:8080 \ --healthz_bind_address=0.0.0.0 \ --healthz_port=10248 \ --logtostderr=true Restart=always RestartSec=10 update: group: stable reboot-strategy: off ssh_authorized_keys: - ssh-rsa AAAAB3NzaC1yc2EAAAAD... ## New pxelinux.cfg file Create a pxelinux target file for a _slave_ node: ```vi /tftpboot/pxelinux.cfg/coreos-node-slave``` default coreos prompt 1 timeout 15 display boot.msg label coreos menu default kernel images/coreos/coreos_production_pxe.vmlinuz append initrd=images/coreos/coreos_production_pxe_image.cpio.gz cloud-config-url=http://<pxe-host-ip>/coreos/pxe-cloud-config-slave.yml console=tty0 console=ttyS0 coreos.autologin=tty1 coreos.autologin=ttyS0 And one for the _master_ node: ```vi /tftpboot/pxelinux.cfg/coreos-node-master``` default coreos prompt 1 timeout 15 display boot.msg label coreos menu default kernel images/coreos/coreos_production_pxe.vmlinuz append initrd=images/coreos/coreos_production_pxe_image.cpio.gz cloud-config-url=http://<pxe-host-ip>/coreos/pxe-cloud-config-master.yml console=tty0 console=ttyS0 coreos.autologin=tty1 coreos.autologin=ttyS0 ## Specify the pxelinux targets Now that we have our new targets setup for master and slave we want to configure the specific hosts to those targets. We will do this by using the pxelinux mechanism of setting a specific MAC addresses to a specific pxelinux.cfg file. Refer to the MAC address table in the beginning of this guide. Documentation for more details can be found [here](http://www.syslinux.org/wiki/index.php/PXELINUX). cd /tftpboot/pxelinux.cfg ln -s coreos-node-master 01-d0-00-67-13-0d-00 ln -s coreos-node-slave 01-d0-00-67-13-0d-01 ln -s coreos-node-slave 01-d0-00-67-13-0d-02 Reboot these servers to get the images PXEd and ready for running containers! ## Creating test pod Now that the CoreOS with QingYuan installed is up and running lets spin up some QingYuan pods to demonstrate the system. See [a simple nginx example](../../../examples/simple-nginx.md) to try out your new cluster. For more complete applications, please look in the [examples directory](../../../examples). ## Helping commands for debugging List all keys in etcd: etcdctl ls --recursive List fleet machines fleetctl list-machines Check system status of services on master node: systemctl status qing-apiserver systemctl status qing-controller-manager systemctl status qing-scheduler systemctl status qing-register Check system status of services on a minion node: systemctl status qing-qinglet systemctl status docker.service List QingYuan qingctl get pods qingctl get minions Kill all pods: for i in `qingctl get pods | awk '{print $1}'`; do qingctl stop pod $i; done [![Analytics](https://qingyuan-site.appspot.com/UA-36037335-10/GitHub/docs/getting-started-guides/coreos/bare_metal_offline.md?pixel)]() [![Analytics](https://qingyuan-site.appspot.com/UA-36037335-10/GitHub/release-0.19.0/docs/getting-started-guides/coreos/bare_metal_offline.md?pixel)]()
apache-2.0
JoyIfBam5/aws-sdk-cpp
aws-cpp-sdk-sagemaker-runtime/include/aws/sagemaker-runtime/SageMakerRuntimeClient.h
9323
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/sagemaker-runtime/SageMakerRuntime_EXPORTS.h> #include <aws/sagemaker-runtime/SageMakerRuntimeErrors.h> #include <aws/core/client/AWSError.h> #include <aws/core/client/ClientConfiguration.h> #include <aws/core/client/AWSClient.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/sagemaker-runtime/model/InvokeEndpointResult.h> #include <aws/core/client/AsyncCallerContext.h> #include <aws/core/http/HttpTypes.h> #include <future> #include <functional> namespace Aws { namespace Http { class HttpClient; class HttpClientFactory; } // namespace Http namespace Utils { template< typename R, typename E> class Outcome; namespace Threading { class Executor; } // namespace Threading } // namespace Utils namespace Auth { class AWSCredentials; class AWSCredentialsProvider; } // namespace Auth namespace Client { class RetryStrategy; } // namespace Client namespace SageMakerRuntime { namespace Model { class InvokeEndpointRequest; typedef Aws::Utils::Outcome<InvokeEndpointResult, Aws::Client::AWSError<SageMakerRuntimeErrors>> InvokeEndpointOutcome; typedef std::future<InvokeEndpointOutcome> InvokeEndpointOutcomeCallable; } // namespace Model class SageMakerRuntimeClient; typedef std::function<void(const SageMakerRuntimeClient*, const Model::InvokeEndpointRequest&, const Model::InvokeEndpointOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > InvokeEndpointResponseReceivedHandler; /** * <p> The Amazon SageMaker runtime API. </p> */ class AWS_SAGEMAKERRUNTIME_API SageMakerRuntimeClient : public Aws::Client::AWSJsonClient { public: typedef Aws::Client::AWSJsonClient BASECLASS; /** * Initializes client to use DefaultCredentialProviderChain, with default http client factory, and optional client config. If client config * is not specified, it will be initialized to default values. */ SageMakerRuntimeClient(const Aws::Client::ClientConfiguration& clientConfiguration = Aws::Client::ClientConfiguration()); /** * Initializes client to use SimpleAWSCredentialsProvider, with default http client factory, and optional client config. If client config * is not specified, it will be initialized to default values. */ SageMakerRuntimeClient(const Aws::Auth::AWSCredentials& credentials, const Aws::Client::ClientConfiguration& clientConfiguration = Aws::Client::ClientConfiguration()); /** * Initializes client to use specified credentials provider with specified client config. If http client factory is not supplied, * the default http client factory will be used */ SageMakerRuntimeClient(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider>& credentialsProvider, const Aws::Client::ClientConfiguration& clientConfiguration = Aws::Client::ClientConfiguration()); virtual ~SageMakerRuntimeClient(); inline virtual const char* GetServiceClientName() const override { return "SageMaker Runtime"; } /** * <p>After you deploy a model into production using Amazon SageMaker hosting * services, your client applications use this API to get inferences from the model * hosted at the specified endpoint. </p> <p>For an overview of Amazon SageMaker, * see <a * href="http://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works.html">How It * Works</a>. </p> <p>Amazon SageMaker strips all POST headers except those * supported by the API. Amazon SageMaker might add additional headers. You should * not rely on the behavior of headers outside those enumerated in the request * syntax. </p> <p>Cals to <code>InvokeEndpoint</code> are authenticated by using * AWS Signature Version 4. For information, see <a * href="http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html">Authenticating * Requests (AWS Signature Version 4)</a> in the <i>Amazon S3 API * Reference</i>.</p> <note> <p>Endpoints are scoped to an individual account, and * are not public. The URL does not contain the account ID, but Amazon SageMaker * determines the account ID from the authentication token that is supplied by the * caller.</p> </note><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/runtime.sagemaker-2017-05-13/InvokeEndpoint">AWS * API Reference</a></p> */ virtual Model::InvokeEndpointOutcome InvokeEndpoint(const Model::InvokeEndpointRequest& request) const; /** * <p>After you deploy a model into production using Amazon SageMaker hosting * services, your client applications use this API to get inferences from the model * hosted at the specified endpoint. </p> <p>For an overview of Amazon SageMaker, * see <a * href="http://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works.html">How It * Works</a>. </p> <p>Amazon SageMaker strips all POST headers except those * supported by the API. Amazon SageMaker might add additional headers. You should * not rely on the behavior of headers outside those enumerated in the request * syntax. </p> <p>Cals to <code>InvokeEndpoint</code> are authenticated by using * AWS Signature Version 4. For information, see <a * href="http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html">Authenticating * Requests (AWS Signature Version 4)</a> in the <i>Amazon S3 API * Reference</i>.</p> <note> <p>Endpoints are scoped to an individual account, and * are not public. The URL does not contain the account ID, but Amazon SageMaker * determines the account ID from the authentication token that is supplied by the * caller.</p> </note><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/runtime.sagemaker-2017-05-13/InvokeEndpoint">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::InvokeEndpointOutcomeCallable InvokeEndpointCallable(const Model::InvokeEndpointRequest& request) const; /** * <p>After you deploy a model into production using Amazon SageMaker hosting * services, your client applications use this API to get inferences from the model * hosted at the specified endpoint. </p> <p>For an overview of Amazon SageMaker, * see <a * href="http://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works.html">How It * Works</a>. </p> <p>Amazon SageMaker strips all POST headers except those * supported by the API. Amazon SageMaker might add additional headers. You should * not rely on the behavior of headers outside those enumerated in the request * syntax. </p> <p>Cals to <code>InvokeEndpoint</code> are authenticated by using * AWS Signature Version 4. For information, see <a * href="http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html">Authenticating * Requests (AWS Signature Version 4)</a> in the <i>Amazon S3 API * Reference</i>.</p> <note> <p>Endpoints are scoped to an individual account, and * are not public. The URL does not contain the account ID, but Amazon SageMaker * determines the account ID from the authentication token that is supplied by the * caller.</p> </note><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/runtime.sagemaker-2017-05-13/InvokeEndpoint">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void InvokeEndpointAsync(const Model::InvokeEndpointRequest& request, const InvokeEndpointResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; private: void init(const Aws::Client::ClientConfiguration& clientConfiguration); /**Async helpers**/ void InvokeEndpointAsyncHelper(const Model::InvokeEndpointRequest& request, const InvokeEndpointResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; Aws::String m_uri; std::shared_ptr<Aws::Utils::Threading::Executor> m_executor; }; } // namespace SageMakerRuntime } // namespace Aws
apache-2.0
XuSihan/gumtree-spoon-ast-diff
src/main/java/gumtree/spoon/diff/operations/MoveOperation.java
211
package gumtree.spoon.diff.operations; import com.github.gumtreediff.actions.model.Move; public class MoveOperation extends AdditionOperation<Move> { public MoveOperation(Move action) { super(action); } }
apache-2.0
babajon/babajon.github.io
_site/_site/salg/2014/07/15/project-4/index.html
22466
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Trondheimsveien 69</title> <meta name="viewport" content="width=device-width"> <meta name="description" content="Irfan Mirza eiendomsmegler hos DNB Eindom Rodeløkka"> <link rel="canonical" href="/salg/2014/07/15/project-4/"> <!-- Custom CSS & Bootstrap Core CSS - Uses Bootswatch Flatly Theme: http://bootswatch.com/flatly/ --> <link rel="stylesheet" href="/style.css"> <!-- Custom Fonts --> <link rel="stylesheet" href="/css/font-awesome/css/font-awesome.min.css"> <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href='http://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'> <link href="http://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css"> <link href='http://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body id="page-top" class="index"> <!-- Navigation --> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header page-scroll"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <!-- Irfan Mirza er tittel til siden i header --> <a class="navbar-brand page-scroll" href="#page-top"><!--Irfan Mirza--></a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li class="hidden"> <a href="#page-top"></a> </li> <li> <a class="page-scroll" href="#about">Om</a> </li> <li> <a class="page-scroll" href="#services">Tjenester</a> </li> <li> <a class="page-scroll" href="#portfolio">Portefølje</a> </li> <!-- <li> <a class="page-scroll" href="#team">Team</a> </li> --> <li> <a class="page-scroll" href="#contact">Kontakt</a> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav> <!-- Header --> <header> <div class="container"> <div class="intro-text"> <div class="intro-lead-in">Irfan Mirza</div> <div class="intro-heading">Eiendomsmegler <br> hos DNB Eiendom Rodeløkka</div> <a href="#about" class="page-scroll btn btn-xl">Fortell mer</a> </div> </div> </header> <!-- --> <!-- About Section --> <section id="about"> <div class="container"> <div class="row"> <div class="col-lg-13 text-center"> <h2 class="section-heading">Om meg</h2> <h3 class="section-subheading text-muted">Jeg er en entusiastisk megler med mye energi! <br> <br>For meg er det viktigste at du som selger skal føle deg trygg og ivaretatt gjennom hele salgsprosessen og at vi sammen skal få den beste prisen for din bolig! <br> <br>Fra første møte skal du føle at du og boligen din er i trygge hender og at prosessen går effektivt og riktig for seg. <br> <br>Jeg gjør mitt aller ytterste i alle ledd i hvert enste oppdrag. Fornøyde kunder er min beste referanse!</h3> </div> </div> <div class="row"> <div class="col-lg-12"> <ul class="timeline"> <li> <div class="timeline-image"> <img class="img-circle img-responsive" src="img/about/bi.jpg" alt=""> </div> <div class="timeline-panel"> <div class="timeline-heading"> <h4>2009-2011</h4> <h4 class="subheading">Meglerutdanning på BI</h4> </div> <div class="timeline-body"> <p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt ut voluptatum eius sapiente, totam reiciendis temporibus qui quibusdam, recusandae sit vero unde, sed, incidunt et ea quo dolore laudantium consectetur!</p> </div> </div> </li> <li class="timeline-inverted"> <div class="timeline-image"> <img class="img-circle img-responsive" src="img/about/dnb.jpg" alt=""> </div> <div class="timeline-panel"> <div class="timeline-heading"> <h4>March 2011</h4> <h4 class="subheading">Begynnte å jobbe hos DNB Eindom</h4> </div> <div class="timeline-body"> <p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt ut voluptatum eius sapiente, totam reiciendis temporibus qui quibusdam, recusandae sit vero unde, sed, incidunt et ea quo dolore laudantium consectetur!</p> </div> </div> </li> <li> <div class="timeline-image"> <img class="img-circle img-responsive" src="img/about/3.jpg" alt=""> </div> <div class="timeline-panel"> <div class="timeline-heading"> <h4>December 2012</h4> <h4 class="subheading">Årets team DNB Rodeløkka</h4> </div> <div class="timeline-body"> <p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt ut voluptatum eius sapiente, totam reiciendis temporibus qui quibusdam, recusandae sit vero unde, sed, incidunt et ea quo dolore laudantium consectetur!</p> </div> </div> </li> <li class="timeline-inverted"> <div class="timeline-image"> <h4>Vil du <br>være med <br>videre?</h4> </div> </li> </ul> </div> </div> </div> </section> <!-- Services Section --> <section id="services"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">Tjenester</h2> <h3 class="section-subheading text-muted">Dette kan jeg hjelpe deg med.</h3> </div> </div> <div class="row text-center"> <div class="col-md-4"> <span class="fa-stack fa-4x"> <i class="fa fa-circle fa-stack-2x text-primary"></i> <i class="fa fa-shopping-cart fa-stack-1x fa-inverse"></i> </span> <h4 class="service-heading">Kjøp av bolig</h4> <p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.</p> </div> <div class="col-md-4"> <span class="fa-stack fa-4x"> <i class="fa fa-circle fa-stack-2x text-primary"></i> <i class="fa fa-key fa-stack-1x fa-inverse"></i> </span> <h4 class="service-heading">Salg av bolig</h4> <p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.</p> </div> <div class="col-md-4"> <span class="fa-stack fa-4x"> <i class="fa fa-circle fa-stack-2x text-primary"></i> <!-- <i class="fa fa-lock fa-stack-1x fa-inverse"></i>--> <i class="fa fa-usd fa-stack-1x fa-inverse"></i> </span> <h4 class="service-heading">Eiendomsvurdering</h4> <p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.</p> </div> </div> </div> </section> <!-- Portfolio Grid Section --> <section id="portfolio" class="bg-light-gray"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">Portefølje</h2> <h3 class="section-subheading text-muted">På følgende eiendommer har jeg bidratt med min tjenester.</h3> </div> </div> <div class="row"> <div class="col-md-4 col-sm-6 portfolio-item"> <a href="#portfolioModal4" class="portfolio-link" data-toggle="modal"> <div class="portfolio-hover"> <div class="portfolio-hover-content"> <i class="fa fa-plus fa-3x"></i> </div> </div> <img src="img/portfolio/trondheimsveien69.png" class="img-responsive" alt=""> </a> <div class="portfolio-caption"> <h4>Trondheimsveien 69</h4> <p class="text-muted">Salg av bolig</p> </div> </div> <div class="col-md-4 col-sm-6 portfolio-item"> <a href="#portfolioModal6" class="portfolio-link" data-toggle="modal"> <div class="portfolio-hover"> <div class="portfolio-hover-content"> <i class="fa fa-plus fa-3x"></i> </div> </div> <img src="img/portfolio/naakkvesvei3.png" class="img-responsive" alt=""> </a> <div class="portfolio-caption"> <h4>Nåkkves vei 3</h4> <p class="text-muted">Salg av bolig</p> </div> </div> <div class="col-md-4 col-sm-6 portfolio-item"> <a href="#portfolioModal5" class="portfolio-link" data-toggle="modal"> <div class="portfolio-hover"> <div class="portfolio-hover-content"> <i class="fa fa-plus fa-3x"></i> </div> </div> <img src="img/portfolio/bergljotsvei7c.png" class="img-responsive" alt=""> </a> <div class="portfolio-caption"> <h4>Bergljotsvei 7C</h4> <p class="text-muted">Salg av bolig</p> </div> </div> </div> </div> </section> <section id="contact"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">Kontakt Meg</h2> <h3 class="section-subheading text-muted">Her kommer kontakt informasjon.</h3> </div> </div> <div class="row"> <div class="col-lg-12"> <form name="sentMessage" id="contactForm" novalidate> <div class="row"> </div> </form> </div> </div> </div> </section> <footer> <div class="container"> <div class="row"> <div class="col-md-4"> <span class="copyright">Copyright &copy; Irfan Mirza 2015</span> </div> <div class="col-md-4"> <ul class="list-inline social-buttons"> <li><a href="http://twitter.com/jekyllrb"><i class="fa fa-twitter"></i></a> </li> <li><a href=""><i class="fa fa-facebook"></i></a> </li> <li><a href="http://stackoverflow.com/questions/tagged/jekyll"><i class="fa fa-stack-overflow"></i></a> </li> <li><a href="http://bitbucket.org/jekyll"><i class="fa fa-bitbucket"></i></a> </li> <li><a href="http://github.com/jekyll"><i class="fa fa-github"></i></a> </li> </ul> </div> <div class="col-md-4"> <ul class="list-inline quicklinks"> <li><a href="#">Privacy Policy</a> </li> <li><a href="#">Terms of Use</a> </li> </ul> </div> </div> </div> </footer> <!-- Portfolio Modals --> <div class="portfolio-modal modal fade" id="portfolioModal4" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-content"> <div class="close-modal" data-dismiss="modal"> <div class="lr"> <div class="rl"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <div class="modal-body"> <h2>Trondheimsveien 69</h2> <hr class="star-primary"> <img src="img/portfolio/trondheimsveien69.png" class="img-responsive img-centered" alt="image-alt"> <p>Lorem ipsum dolor sit amet, usu cu alterum nominavi lobortis. At duo novum diceret. Tantas apeirian vix et, usu sanctus postulant inciderint ut, populo diceret necessitatibus in vim. Cu eum dicam feugiat noluisse.</p> <ul class="list-inline item-details"> <li>Client: <strong><a href="http://startbootstrap.com">Privat</a> </strong> </li> <li>Date: <strong><a href="http://startbootstrap.com">April 2014</a> </strong> </li> <li>Service: <strong><a href="http://startbootstrap.com">Salg</a> </strong> </li> </ul> <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button> </div> </div> </div> </div> </div> </div> <div class="portfolio-modal modal fade" id="portfolioModal6" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-content"> <div class="close-modal" data-dismiss="modal"> <div class="lr"> <div class="rl"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <div class="modal-body"> <h2>Nåkkves vei 3</h2> <hr class="star-primary"> <img src="img/portfolio/naakkvesvei3.png" class="img-responsive img-centered" alt="image-alt"> <p>Lorem ipsum dolor sit amet, usu cu alterum nominavi lobortis. At duo novum diceret. Tantas apeirian vix et, usu sanctus postulant inciderint ut, populo diceret necessitatibus in vim. Cu eum dicam feugiat noluisse.</p> <ul class="list-inline item-details"> <li>Client: <strong><a href="http://startbootstrap.com">Privat</a> </strong> </li> <li>Date: <strong><a href="http://startbootstrap.com">April 2014</a> </strong> </li> <li>Service: <strong><a href="http://startbootstrap.com">Salg</a> </strong> </li> </ul> <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button> </div> </div> </div> </div> </div> </div> <div class="portfolio-modal modal fade" id="portfolioModal5" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-content"> <div class="close-modal" data-dismiss="modal"> <div class="lr"> <div class="rl"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <div class="modal-body"> <h2>Bergljotsvei 7C</h2> <hr class="star-primary"> <img src="img/portfolio/naakkvesvei3.png" class="img-responsive img-centered" alt="image-alt"> <p>Lorem ipsum dolor sit amet, usu cu alterum nominavi lobortis. At duo novum diceret. Tantas apeirian vix et, usu sanctus postulant inciderint ut, populo diceret necessitatibus in vim. Cu eum dicam feugiat noluisse.</p> <ul class="list-inline item-details"> <li>Client: <strong><a href="http://startbootstrap.com">Privat</a> </strong> </li> <li>Date: <strong><a href="http://startbootstrap.com">April 2014</a> </strong> </li> <li>Service: <strong><a href="http://startbootstrap.com">Salg</a> </strong> </li> </ul> <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button> </div> </div> </div> </div> </div> </div> <!-- jQuery Version 1.11.0 --> <script src="/js/jquery-1.11.0.js"></script> <!-- Bootstrap Core JavaScript --> <script src="/js/bootstrap.min.js"></script> <!-- Plugin JavaScript --> <script src="/js/jquery.easing.min.js"></script> <script src="/js/classie.js"></script> <script src="/js/cbpAnimatedHeader.js"></script> <!-- Contact Form JavaScript --> <script src="/js/jqBootstrapValidation.js"></script> <script src="/js/contact_me.js"></script> <!-- Custom Theme JavaScript --> <script src="/js/agency.js"></script> </body> </html>
apache-2.0
gsantovena/mesos
src/slave/flags.hpp
7795
// 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. #ifndef __SLAVE_FLAGS_HPP__ #define __SLAVE_FLAGS_HPP__ #include <cstdint> #include <string> #include <stout/bytes.hpp> #include <stout/duration.hpp> #include <stout/json.hpp> #include <stout/option.hpp> #include <stout/path.hpp> #include <mesos/module/module.hpp> #include "logging/flags.hpp" #include "messages/flags.hpp" namespace mesos { namespace internal { namespace slave { class Flags : public virtual logging::Flags { public: Flags(); bool version; Option<std::string> hostname; bool hostname_lookup; Option<std::string> resources; Option<std::string> resource_provider_config_dir; Option<std::string> disk_profile_adaptor; std::string isolation; std::string launcher; Option<std::string> image_providers; Option<std::string> image_provisioner_backend; Option<ImageGcConfig> image_gc_config; std::string appc_simple_discovery_uri_prefix; std::string appc_store_dir; std::string docker_registry; std::string docker_store_dir; std::string docker_volume_checkpoint_dir; bool docker_ignore_runtime; std::string default_role; Option<std::string> attributes; Bytes fetcher_cache_size; std::string fetcher_cache_dir; Duration fetcher_stall_timeout; std::string work_dir; std::string runtime_dir; std::string launcher_dir; Option<std::string> hadoop_home; size_t max_completed_executors_per_framework; #ifndef __WINDOWS__ bool switch_user; Option<std::string> volume_gid_range; #endif // __WINDOWS__ Duration http_heartbeat_interval; std::string frameworks_home; // TODO(benh): Make an Option. Duration registration_backoff_factor; Duration authentication_backoff_factor; Duration authentication_timeout_min; Duration authentication_timeout_max; Option<JSON::Object> executor_environment_variables; Duration executor_registration_timeout; Duration executor_reregistration_timeout; Option<Duration> executor_reregistration_retry_interval; Duration executor_shutdown_grace_period; #ifdef USE_SSL_SOCKET Option<Path> jwt_secret_key; #endif // USE_SSL_SOCKET Duration gc_delay; double gc_disk_headroom; bool gc_non_executor_container_sandboxes; Duration disk_watch_interval; Option<std::string> container_logger; std::string reconfiguration_policy; std::string recover; Duration recovery_timeout; bool strict; Duration register_retry_interval_min; #ifdef __linux__ Duration cgroups_destroy_timeout; std::string cgroups_hierarchy; std::string cgroups_root; bool cgroups_enable_cfs; bool cgroups_limit_swap; bool cgroups_cpu_enable_pids_and_tids_count; Option<std::string> cgroups_net_cls_primary_handle; Option<std::string> cgroups_net_cls_secondary_handles; Option<DeviceWhitelist> allowed_devices; Option<std::string> agent_subsystems; Option<std::string> host_path_volume_force_creation; Option<std::vector<unsigned int>> nvidia_gpu_devices; Option<std::string> perf_events; Duration perf_interval; Duration perf_duration; bool revocable_cpu_low_priority; bool systemd_enable_support; std::string systemd_runtime_directory; Option<CapabilityInfo> effective_capabilities; Option<CapabilityInfo> bounding_capabilities; Option<Bytes> default_shm_size; bool disallow_sharing_agent_ipc_namespace; bool disallow_sharing_agent_pid_namespace; #endif Option<Firewall> firewall_rules; Option<Path> credential; Option<ACLs> acls; std::string containerizers; std::string docker; Option<std::string> docker_mesos_image; Duration docker_remove_delay; std::string sandbox_directory; Option<ContainerDNSInfo> default_container_dns; Option<ContainerInfo> default_container_info; // TODO(alexr): Remove this after the deprecation cycle (started in 1.0). Duration docker_stop_timeout; bool docker_kill_orphans; std::string docker_socket; Option<JSON::Object> docker_config; #ifdef ENABLE_PORT_MAPPING_ISOLATOR uint16_t ephemeral_ports_per_container; Option<std::string> eth0_name; Option<std::string> lo_name; Option<Bytes> egress_rate_limit_per_container; bool egress_unique_flow_per_container; std::string egress_flow_classifier_parent; bool network_enable_socket_statistics_summary; bool network_enable_socket_statistics_details; bool network_enable_snmp_statistics; #endif // ENABLE_PORT_MAPPING_ISOLATOR #ifdef ENABLE_NETWORK_PORTS_ISOLATOR Duration container_ports_watch_interval; bool check_agent_port_range_only; bool enforce_container_ports; Option<std::string> container_ports_isolated_range; #endif // ENABLE_NETWORK_PORTS_ISOLATOR Option<std::string> network_cni_plugins_dir; Option<std::string> network_cni_config_dir; bool network_cni_root_dir_persist; bool network_cni_metrics; Duration container_disk_watch_interval; bool enforce_container_disk_quota; Option<Modules> modules; Option<std::string> modulesDir; std::string authenticatee; std::string authorizer; Option<std::string> http_authenticators; bool authenticate_http_readonly; bool authenticate_http_readwrite; #ifdef USE_SSL_SOCKET bool authenticate_http_executors; #endif // USE_SSL_SOCKET Option<Path> http_credentials; Option<std::string> hooks; Option<std::string> secret_resolver; Option<std::string> resource_estimator; Option<std::string> qos_controller; Duration qos_correction_interval_min; Duration oversubscribed_resources_interval; Option<std::string> master_detector; #if ENABLE_XFS_DISK_ISOLATOR std::string xfs_project_range; bool xfs_kill_containers; #endif #if ENABLE_SECCOMP_ISOLATOR Option<std::string> seccomp_config_dir; Option<std::string> seccomp_profile_name; #endif bool http_command_executor; Option<SlaveCapabilities> agent_features; Option<DomainInfo> domain; // The following flags are executable specific (e.g., since we only // have one instance of libprocess per execution, we only want to // advertise the IP and port option once, here). Option<std::string> ip; uint16_t port; Option<std::string> advertise_ip; Option<std::string> advertise_port; Option<flags::SecurePathOrValue> master; bool memory_profiling; Duration zk_session_timeout; // Optional IP discover script that will set the slave's IP. // If set, its output is expected to be a valid parseable IP string. Option<std::string> ip_discovery_command; // IPv6 flags. // // NOTE: These IPv6 flags are currently input mechanisms // for the operator to specify v6 addresses on which containers // running on host network can listen. Mesos itself doesn't listen // or communicate over v6 addresses at this point. Option<std::string> ip6; // Similar to the `ip_discovery_command` this optional discover // script is expected to output a valid IPv6 string. Only one of the // two options `ip6` or `ip6_discovery_command` can be set at any // given point of time. Option<std::string> ip6_discovery_command; }; } // namespace slave { } // namespace internal { } // namespace mesos { #endif // __SLAVE_FLAGS_HPP__
apache-2.0
taohungyang/cloud-custodian
tools/c7n_azure/tests/test_networksecuritygroup.py
6524
# Copyright 2015-2018 Capital One Services, 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. from __future__ import absolute_import, division, print_function, unicode_literals from azure_common import BaseTest, arm_template class NetworkSecurityGroupTest(BaseTest): def setUp(self): super(NetworkSecurityGroupTest, self).setUp() @arm_template('networksecuritygroup.json') def test_find_by_name(self): p = self.load_policy({ 'name': 'test-azure-nsg', 'resource': 'azure.networksecuritygroup', 'filters': [ {'type': 'value', 'key': 'name', 'op': 'eq', 'value_type': 'normalize', 'value': 'c7n-nsg'}], }) resources = p.run() self.assertEqual(len(resources), 1) @arm_template('networksecuritygroup.json') def test_allow_single_port(self): p = self.load_policy({ 'name': 'test-azure-nsg', 'resource': 'azure.networksecuritygroup', 'filters': [ {'type': 'value', 'key': 'name', 'op': 'eq', 'value_type': 'normalize', 'value': 'c7n-nsg'}, {'type': 'ingress', 'ports': '80', 'access': 'Allow'}], }) resources = p.run() self.assertEqual(len(resources), 1) @arm_template('networksecuritygroup.json') def test_allow_multiple_ports(self): p = self.load_policy({ 'name': 'test-azure-nsg', 'resource': 'azure.networksecuritygroup', 'filters': [ {'type': 'value', 'key': 'name', 'op': 'eq', 'value_type': 'normalize', 'value': 'c7n-nsg'}, {'type': 'ingress', 'ports': '80,8080-8084,88-90', 'match': 'all', 'access': 'Allow'}], }) resources = p.run() self.assertEqual(len(resources), 1) @arm_template('networksecuritygroup.json') def test_allow_ports_range_any(self): p = self.load_policy({ 'name': 'test-azure-nsg', 'resource': 'azure.networksecuritygroup', 'filters': [ {'type': 'value', 'key': 'name', 'op': 'eq', 'value_type': 'normalize', 'value': 'c7n-nsg'}, {'type': 'ingress', 'ports': '40-100', 'match': 'any', 'access': 'Allow'}] }) resources = p.run() self.assertEqual(len(resources), 1) @arm_template('networksecuritygroup.json') def test_deny_port(self): p = self.load_policy({ 'name': 'test-azure-nsg', 'resource': 'azure.networksecuritygroup', 'filters': [ {'type': 'value', 'key': 'name', 'op': 'eq', 'value_type': 'normalize', 'value': 'c7n-nsg'}, {'type': 'ingress', 'ports': '8086', 'access': 'Deny'}], }) resources = p.run() self.assertEqual(len(resources), 1) @arm_template('networksecuritygroup.json') def test_egress_policy_protocols(self): p = self.load_policy({ 'name': 'test-azure-nsg', 'resource': 'azure.networksecuritygroup', 'filters': [ {'type': 'value', 'key': 'name', 'op': 'eq', 'value_type': 'normalize', 'value': 'c7n-nsg'}, {'type': 'egress', 'ports': '22', 'ipProtocol': 'TCP', 'access': 'Allow'}], }) resources = p.run() self.assertEqual(len(resources), 1) p = self.load_policy({ 'name': 'test-azure-nsg', 'resource': 'azure.networksecuritygroup', 'filters': [ {'type': 'value', 'key': 'name', 'op': 'eq', 'value_type': 'normalize', 'value': 'c7n-nsg'}, {'type': 'egress', 'ports': '22', 'ipProtocol': 'UDP', 'access': 'Allow'}], }) resources = p.run() self.assertEqual(len(resources), 0) @arm_template('networksecuritygroup.json') def test_open_ports(self): p = self.load_policy({ 'name': 'test-azure-nsg', 'resource': 'azure.networksecuritygroup', 'filters': [ {'type': 'value', 'key': 'name', 'op': 'eq', 'value_type': 'normalize', 'value': 'c7n-nsg'}, {'type': 'ingress', 'ports': '1000-1100', 'match': 'any', 'access': 'Deny'}], 'actions': [ { 'type': 'open', 'ports': '1000-1100', 'direction': 'Inbound'} ] }) resources = p.run() self.assertEqual(len(resources), 1) p = self.load_policy({ 'name': 'test-azure-nsg', 'resource': 'azure.networksecuritygroup', 'filters': [ {'type': 'value', 'key': 'name', 'op': 'eq', 'value_type': 'normalize', 'value': 'c7n-nsg'}, {'type': 'ingress', 'ports': '1000-1100', 'match': 'any', 'access': 'Deny'}], 'actions': [ {'type': 'open', 'ports': '1000-1100', 'direction': 'Inbound'}] }) resources = p.run() self.assertEqual(len(resources), 0)
apache-2.0
tcrognon/google-cloud-node
scripts/helpers.js
10052
/*! * Copyright 2016 Google Inc. 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. */ 'use strict'; var path = require('path'); var uniq = require('array-uniq'); var globby = require('globby'); var spawn = require('child_process').spawnSync; require('shelljs/global'); /** * google-cloud-node root directory.. useful in case we need to cd */ var ROOT_DIR = path.join(__dirname, '..'); module.exports.ROOT_DIR = ROOT_DIR; /** * Helper class to make install dependencies + running tests easier to read * and less error prone. * * @class Module * @param {string} name - The module name (e.g. common, bigquery, etc.) */ function Module(name) { if (!(this instanceof Module)) { return new Module(name); } this.name = name; this.directory = path.join(ROOT_DIR, 'packages', name); var pkgJson = require(path.join(this.directory, 'package.json')); this.packageName = pkgJson.name; this.dependencies = Object.keys(pkgJson.devDependencies || {}); } /** * Umbrella module name. * * @static */ Module.UMBRELLA = 'google-cloud'; /** * Retrieves a list of modules that are ahead of origin/master. We do this by * creating a temporary remote branch that points official master branch. * We then do a git diff against the two to get a list of files. From there we * only care about either JS or JSON files being changed. * * @static * @return {Module[]} modules - The updated modules. */ Module.getUpdated = function() { var command = 'git'; var args = ['diff']; if (!isPushToMaster()) { run([ 'git remote add temp', 'https://github.com/GoogleCloudPlatform/google-cloud-node.git' ]); run('git fetch -q temp'); args.push('HEAD', 'temp/master'); } else { args.push('HEAD^'); } args.push('--name-only'); console.log(command, args.join(' ')); // There's a Windows bug where child_process.exec exits early on `git diff` // which in turn does not return all of the files that have changed. This can // cause a false positive when checking for package changes on AppVeyor var output = spawn(command, args, { cwd: ROOT_DIR, stdio: null }); if (output.status || output.error) { console.error(output.error || output.stderr.toString()); exit(output.status || 1); } var files = output.stdout.toString(); console.log(files); var modules = files .trim() .split('\n') .filter(function(file) { return /^packages\/.+\.js/.test(file); }) .map(function(file) { return file.split('/')[1]; }); return uniq(modules).map(Module); }; /** * Builds docs for all modules * * @static */ Module.buildDocs = function() { run('npm run docs', { cwd: ROOT_DIR }); }; /** * Returns a list containing ALL the modules. * * @static * @return {Module[]} modules - All of em'! */ Module.getAll = function() { cd(ROOT_DIR); return globby .sync('*', { cwd: 'packages' }) .map(Module); }; /** * Returns a list of modules that are dependent on one or more of the modules * specified. * * @static * @param {Module[]} modules - The dependency modules. * @return {Module[]} modules - The dependent modules. */ Module.getDependents = function(modules) { return Module.getAll().filter(function(mod) { return mod.hasDeps(modules); }); }; /** * Installs dependencies for all the modules! * * @static */ Module.installAll = function() { run('npm run postinstall', { cwd: ROOT_DIR }); }; /** * Generates an lcov coverage report for the specified modules. * * @static */ Module.runCoveralls = function() { run('npm run coveralls', { cwd: ROOT_DIR }); }; /** * Installs this modules dependencies via `npm install` */ Module.prototype.install = function() { run('npm install', { cwd: this.directory }); }; /** * Creates/uses symlink for a module (depending on if module was provided) * via `npm link` * * @param {Module=} mod - The module to use with `npm link ${mod.packageName}` */ Module.prototype.link = function(mod) { run(['npm link', mod && mod.packageName || ''], { cwd: this.directory }); }; /** * Runs unit tests for this module via `npm run test` */ Module.prototype.runUnitTests = function() { run('npm run test', { cwd: this.directory }); }; /** * Runs snippet tests for this module. */ Module.prototype.runSnippetTests = function() { process.env.TEST_MODULE = this.name; run('npm run snippet-test', { cwd: ROOT_DIR }); delete process.env.TEST_MODULE; }; /** * Runs system tests for this module via `npm run system-test` */ Module.prototype.runSystemTests = function() { run('npm run system-test', { cwd: this.directory }); }; /** * Checks to see if this module has one or more of the supplied modules * as a dev dependency. * * @param {Module[]} modules - The modules to check for. * @return {boolean} */ Module.prototype.hasDeps = function(modules) { var packageName; for (var i = 0; i < modules.length; i++) { packageName = modules[i].packageName; if (this.dependencies.indexOf(packageName) > -1) { return true; } } return false; }; module.exports.Module = Module; /** * Exec's command via child_process.spawnSync. * By default all output will be piped to the console unless `stdio` * is overridden. * * @param {string} command - The command to run. * @param {object=} options - Options to pass to `spawnSync`. * @return {string|null} */ function run(command, options) { options = options || {}; if (Array.isArray(command)) { command = command.join(' '); } console.log(command); var response = exec(command, options); if (response.code) { exit(response.code); } return response.stdout; } module.exports.run = run; /** * Used to make committing to git easier/etc.. * * @param {string=} cwd - Directory to commit/add/push from. */ function Git(cwd) { this.cwd = cwd || ROOT_DIR; } // We'll use this for cloning/submoduling/pushing purposes on CI Git.REPO = 'https://${GH_OAUTH_TOKEN}@github.com/${GH_OWNER}/${GH_PROJECT_NAME}'; /** * Creates a submodule in the root directory in quiet mode. * * @param {string} branch - The branch to use. * @param {string=} alias - Name of the folder that contains submodule. * @return {Git} */ Git.prototype.submodule = function(branch, alias) { alias = alias || branch; run(['git submodule add -q -b', branch, Git.REPO, alias], { cwd: this.cwd }); return new Git(path.join(this.cwd, alias)); }; /** * Check to see if git has any files it can commit. * * @return {boolean} */ Git.prototype.hasUpdates = function() { var output = run('git status --porcelain', { cwd: this.cwd }); return !!output && output.trim().length > 0; }; /** * Sets git user * * @param {string} name - User name * @param {string} email - User email */ Git.prototype.setUser = function(name, email) { run(['git config --global user.name', name], { cwd: this.cwd }); run(['git config --global user.email', email], { cwd: this.cwd }); }; /** * Adds all files passed in via git add * * @param {...string} file - File to add */ Git.prototype.add = function() { var files = [].slice.call(arguments); var command = ['git add'].concat(files); run(command, { cwd: this.cwd }); }; /** * Commits to git via commit message. * * @param {string} message - The commit message. */ Git.prototype.commit = function(message) { run(['git commit -m', '"' + message + ' [ci skip]"'], { cwd: this.cwd }); }; /** * Runs git status and pushes changes in quiet mode. * * @param {string} branch - The branch to push to. */ Git.prototype.push = function(branch) { run('git status', { cwd: this.cwd }); run(['git push -q', Git.REPO, branch], { cwd: this.cwd }); }; module.exports.git = new Git(); /** * The name of the branch currently being tested. * * @alias ci.BRANCH */ var BRANCH = process.env.TRAVIS_BRANCH || process.env.APPVEYOR_REPO_BRANCH; /** * The pull request number. * * @alias ci.PR_NUMBER; */ var PR_NUMBER = process.env.TRAVIS_PULL_REQUEST || process.env.APPVEYOR_PULL_REQUEST_NUMBER; /** * Checks to see if this is a pull request or not. * * @alias ci.IS_PR */ var IS_PR = !isNaN(parseInt(PR_NUMBER, 10)); /** * Returns the tag name (assuming this is a release) * * @alias ci.getTagName * @return {string|null} */ function getTagName() { return process.env.TRAVIS_TAG || process.env.APPVEYOR_REPO_TAG_NAME; } /** * Let's us know whether or not this is a release. * * @alias ci.isReleaseBuild * @return {string|null} */ function isReleaseBuild() { return !!getTagName(); } /** * Returns name/version of release. * * @alias ci.getRelease * @return {object|null} */ function getRelease() { var tag = getTagName(); if (!tag) { return null; } var parts = tag.split('-'); return { version: parts.pop(), name: parts.pop() || Module.UMBRELLA }; } /** * Checks to see if this is a push to master. * * @alias ci.isPushToMaster * @return {boolean} */ function isPushToMaster() { return BRANCH === 'master' && !IS_PR; } /** * Checks to see if this the CI's first pass (Travis only) * * @alias ci.isFirstPass * @return {boolean} */ function isFirstPass() { return /\.1$/.test(process.env.TRAVIS_JOB_NUMBER); } module.exports.ci = { BRANCH: BRANCH, IS_PR: IS_PR, PR_NUMBER: PR_NUMBER, getTagName: getTagName, isReleaseBuild: isReleaseBuild, getRelease: getRelease, isPushToMaster: isPushToMaster, isFirstPass: isFirstPass };
apache-2.0
akhr/java
Spring/jars/spring-framework-5.1.18.RELEASE/docs/javadoc-api/org/springframework/http/package-tree.html
15357
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_232) on Tue Sep 15 08:52:47 UTC 2020 --> <title>org.springframework.http Class Hierarchy (Spring Framework 5.1.18.RELEASE API)</title> <meta name="date" content="2020-09-15"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.springframework.http Class Hierarchy (Spring Framework 5.1.18.RELEASE API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Spring Framework</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../org/springframework/format/support/package-tree.html">Prev</a></li> <li><a href="../../../org/springframework/http/client/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/springframework/http/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">Hierarchy For Package org.springframework.http</h1> <span class="packageHierarchyLabel">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a> <ul> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/CacheControl.html" title="class in org.springframework.http"><span class="typeNameLink">CacheControl</span></a></li> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/ContentDisposition.html" title="class in org.springframework.http"><span class="typeNameLink">ContentDisposition</span></a></li> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/HttpCookie.html" title="class in org.springframework.http"><span class="typeNameLink">HttpCookie</span></a> <ul> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/ResponseCookie.html" title="class in org.springframework.http"><span class="typeNameLink">ResponseCookie</span></a></li> </ul> </li> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/HttpEntity.html" title="class in org.springframework.http"><span class="typeNameLink">HttpEntity</span></a>&lt;T&gt; <ul> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/RequestEntity.html" title="class in org.springframework.http"><span class="typeNameLink">RequestEntity</span></a>&lt;T&gt;</li> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/ResponseEntity.html" title="class in org.springframework.http"><span class="typeNameLink">ResponseEntity</span></a>&lt;T&gt;</li> </ul> </li> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/HttpHeaders.html" title="class in org.springframework.http"><span class="typeNameLink">HttpHeaders</span></a> (implements org.springframework.util.<a href="../../../org/springframework/util/MultiValueMap.html" title="interface in org.springframework.util">MultiValueMap</a>&lt;K,V&gt;, java.io.<a href="https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a>)</li> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/HttpLogging.html" title="class in org.springframework.http"><span class="typeNameLink">HttpLogging</span></a></li> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/HttpRange.html" title="class in org.springframework.http"><span class="typeNameLink">HttpRange</span></a></li> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/MediaTypeFactory.html" title="class in org.springframework.http"><span class="typeNameLink">MediaTypeFactory</span></a></li> <li type="circle">org.springframework.util.<a href="../../../org/springframework/util/MimeType.html" title="class in org.springframework.util"><span class="typeNameLink">MimeType</span></a> (implements java.lang.<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html?is-external=true" title="class or interface in java.lang">Comparable</a>&lt;T&gt;, java.io.<a href="https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a>) <ul> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/MediaType.html" title="class in org.springframework.http"><span class="typeNameLink">MediaType</span></a> (implements java.io.<a href="https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a>)</li> </ul> </li> <li type="circle">java.beans.<a href="https://docs.oracle.com/javase/8/docs/api/java/beans/PropertyEditorSupport.html?is-external=true" title="class or interface in java.beans"><span class="typeNameLink">PropertyEditorSupport</span></a> (implements java.beans.<a href="https://docs.oracle.com/javase/8/docs/api/java/beans/PropertyEditor.html?is-external=true" title="class or interface in java.beans">PropertyEditor</a>) <ul> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/MediaTypeEditor.html" title="class in org.springframework.http"><span class="typeNameLink">MediaTypeEditor</span></a></li> </ul> </li> <li type="circle">java.lang.<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Throwable</span></a> (implements java.io.<a href="https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a>) <ul> <li type="circle">java.lang.<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Exception.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Exception</span></a> <ul> <li type="circle">java.lang.<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/RuntimeException.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">RuntimeException</span></a> <ul> <li type="circle">java.lang.<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalArgumentException.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">IllegalArgumentException</span></a> <ul> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/InvalidMediaTypeException.html" title="class in org.springframework.http"><span class="typeNameLink">InvalidMediaTypeException</span></a></li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> <h2 title="Interface Hierarchy">Interface Hierarchy</h2> <ul> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/ContentDisposition.Builder.html" title="interface in org.springframework.http"><span class="typeNameLink">ContentDisposition.Builder</span></a></li> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/HttpMessage.html" title="interface in org.springframework.http"><span class="typeNameLink">HttpMessage</span></a> <ul> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/HttpInputMessage.html" title="interface in org.springframework.http"><span class="typeNameLink">HttpInputMessage</span></a></li> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/HttpOutputMessage.html" title="interface in org.springframework.http"><span class="typeNameLink">HttpOutputMessage</span></a> <ul> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/StreamingHttpOutputMessage.html" title="interface in org.springframework.http"><span class="typeNameLink">StreamingHttpOutputMessage</span></a></li> </ul> </li> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/HttpRequest.html" title="interface in org.springframework.http"><span class="typeNameLink">HttpRequest</span></a></li> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/ReactiveHttpInputMessage.html" title="interface in org.springframework.http"><span class="typeNameLink">ReactiveHttpInputMessage</span></a></li> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/ReactiveHttpOutputMessage.html" title="interface in org.springframework.http"><span class="typeNameLink">ReactiveHttpOutputMessage</span></a> <ul> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/ZeroCopyHttpOutputMessage.html" title="interface in org.springframework.http"><span class="typeNameLink">ZeroCopyHttpOutputMessage</span></a></li> </ul> </li> </ul> </li> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/RequestEntity.HeadersBuilder.html" title="interface in org.springframework.http"><span class="typeNameLink">RequestEntity.HeadersBuilder</span></a>&lt;B&gt; <ul> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/RequestEntity.BodyBuilder.html" title="interface in org.springframework.http"><span class="typeNameLink">RequestEntity.BodyBuilder</span></a></li> </ul> </li> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/ResponseCookie.ResponseCookieBuilder.html" title="interface in org.springframework.http"><span class="typeNameLink">ResponseCookie.ResponseCookieBuilder</span></a></li> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/ResponseEntity.HeadersBuilder.html" title="interface in org.springframework.http"><span class="typeNameLink">ResponseEntity.HeadersBuilder</span></a>&lt;B&gt; <ul> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/ResponseEntity.BodyBuilder.html" title="interface in org.springframework.http"><span class="typeNameLink">ResponseEntity.BodyBuilder</span></a></li> </ul> </li> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/StreamingHttpOutputMessage.Body.html" title="interface in org.springframework.http"><span class="typeNameLink">StreamingHttpOutputMessage.Body</span></a></li> </ul> <h2 title="Enum Hierarchy">Enum Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a> <ul> <li type="circle">java.lang.<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Enum</span></a>&lt;E&gt; (implements java.lang.<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html?is-external=true" title="class or interface in java.lang">Comparable</a>&lt;T&gt;, java.io.<a href="https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a>) <ul> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/HttpMethod.html" title="enum in org.springframework.http"><span class="typeNameLink">HttpMethod</span></a></li> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/HttpStatus.Series.html" title="enum in org.springframework.http"><span class="typeNameLink">HttpStatus.Series</span></a></li> <li type="circle">org.springframework.http.<a href="../../../org/springframework/http/HttpStatus.html" title="enum in org.springframework.http"><span class="typeNameLink">HttpStatus</span></a></li> </ul> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Spring Framework</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../org/springframework/format/support/package-tree.html">Prev</a></li> <li><a href="../../../org/springframework/http/client/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/springframework/http/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
apache-2.0
dump247/aws-sdk-java
aws-java-sdk-directconnect/src/main/java/com/amazonaws/services/directconnect/model/transform/DescribeConnectionsOnInterconnectResultJsonUnmarshaller.java
3202
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.directconnect.model.transform; import java.util.Map; import java.util.Map.Entry; import com.amazonaws.services.directconnect.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * DescribeConnectionsOnInterconnectResult JSON Unmarshaller */ public class DescribeConnectionsOnInterconnectResultJsonUnmarshaller implements Unmarshaller<DescribeConnectionsOnInterconnectResult, JsonUnmarshallerContext> { public DescribeConnectionsOnInterconnectResult unmarshall( JsonUnmarshallerContext context) throws Exception { DescribeConnectionsOnInterconnectResult describeConnectionsOnInterconnectResult = new DescribeConnectionsOnInterconnectResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) return null; while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("connections", targetDepth)) { context.nextToken(); describeConnectionsOnInterconnectResult .setConnections(new ListUnmarshaller<Connection>( ConnectionJsonUnmarshaller.getInstance()) .unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals( currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return describeConnectionsOnInterconnectResult; } private static DescribeConnectionsOnInterconnectResultJsonUnmarshaller instance; public static DescribeConnectionsOnInterconnectResultJsonUnmarshaller getInstance() { if (instance == null) instance = new DescribeConnectionsOnInterconnectResultJsonUnmarshaller(); return instance; } }
apache-2.0
Laimiux/RxActivity
rxactivity/src/main/java/com/laimiux/rxactivity/LifecycleEvent.java
495
package com.laimiux.rxactivity; import android.app.Activity; public abstract class LifecycleEvent { private final Kind kind; private final Activity activity; public LifecycleEvent(Kind kind, Activity activity) { this.kind = kind; this.activity = activity; } public Activity activity() { return activity; } public Kind kind() { return kind; } public enum Kind { CREATE, START, RESUME, PAUSE, SAVE_INSTANCE, STOP, DESTROY } }
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Piperales/Piperaceae/Pothomorphe/Pothomorphe alleni/README.md
174
# Pothomorphe alleni Trel. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
apache-2.0
kfmaster/cicdlab
modules/docker-roundcubemail/plugins/enigma/lib/enigma_engine.php
26398
<?php /* +-------------------------------------------------------------------------+ | Engine of the Enigma Plugin | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License version 2 | | as published by the Free Software Foundation. | | | | This program is distributed in the hope that it will be useful, | | but WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | | GNU General Public License for more details. | | | | You should have received a copy of the GNU General Public License along | | with this program; if not, write to the Free Software Foundation, Inc., | | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. | | | +-------------------------------------------------------------------------+ | Author: Aleksander Machniak <[email protected]> | +-------------------------------------------------------------------------+ */ /* RFC2440: OpenPGP Message Format RFC3156: MIME Security with OpenPGP RFC3851: S/MIME */ class enigma_engine { private $rc; private $enigma; private $pgp_driver; private $smime_driver; public $decryptions = array(); public $signatures = array(); public $signed_parts = array(); const PASSWORD_TIME = 120; /** * Plugin initialization. */ function __construct($enigma) { $this->rc = rcmail::get_instance(); $this->enigma = $enigma; // this will remove passwords from session after some time $this->get_passwords(); } /** * PGP driver initialization. */ function load_pgp_driver() { if ($this->pgp_driver) { return; } $driver = 'enigma_driver_' . $this->rc->config->get('enigma_pgp_driver', 'gnupg'); $username = $this->rc->user->get_username(); // Load driver $this->pgp_driver = new $driver($username); if (!$this->pgp_driver) { rcube::raise_error(array( 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Enigma plugin: Unable to load PGP driver: $driver" ), true, true); } // Initialise driver $result = $this->pgp_driver->init(); if ($result instanceof enigma_error) { rcube::raise_error(array( 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Enigma plugin: ".$result->getMessage() ), true, true); } } /** * S/MIME driver initialization. */ function load_smime_driver() { if ($this->smime_driver) { return; } $driver = 'enigma_driver_' . $this->rc->config->get('enigma_smime_driver', 'phpssl'); $username = $this->rc->user->get_username(); // Load driver $this->smime_driver = new $driver($username); if (!$this->smime_driver) { rcube::raise_error(array( 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Enigma plugin: Unable to load S/MIME driver: $driver" ), true, true); } // Initialise driver $result = $this->smime_driver->init(); if ($result instanceof enigma_error) { rcube::raise_error(array( 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Enigma plugin: ".$result->getMessage() ), true, true); } } /** * Handler for message_part_structure hook. * Called for every part of the message. * * @param array Original parameters * * @return array Modified parameters */ function part_structure($p) { if ($p['mimetype'] == 'text/plain' || $p['mimetype'] == 'application/pgp') { $this->parse_plain($p); } else if ($p['mimetype'] == 'multipart/signed') { $this->parse_signed($p); } else if ($p['mimetype'] == 'multipart/encrypted') { $this->parse_encrypted($p); } else if ($p['mimetype'] == 'application/pkcs7-mime') { $this->parse_encrypted($p); } return $p; } /** * Handler for message_part_body hook. * * @param array Original parameters * * @return array Modified parameters */ function part_body($p) { // encrypted attachment, see parse_plain_encrypted() if ($p['part']->need_decryption && $p['part']->body === null) { $storage = $this->rc->get_storage(); $body = $storage->get_message_part($p['object']->uid, $p['part']->mime_id, $p['part'], null, null, true, 0, false); $result = $this->pgp_decrypt($body); // @TODO: what to do on error? if ($result === true) { $p['part']->body = $body; $p['part']->size = strlen($body); $p['part']->body_modified = true; } } return $p; } /** * Handler for plain/text message. * * @param array Reference to hook's parameters */ function parse_plain(&$p) { $part = $p['structure']; // exit, if we're already inside a decrypted message if ($part->encrypted) { return; } // Get message body from IMAP server $body = $this->get_part_body($p['object'], $part->mime_id); // @TODO: big message body could be a file resource // PGP signed message if (preg_match('/^-----BEGIN PGP SIGNED MESSAGE-----/', $body)) { $this->parse_plain_signed($p, $body); } // PGP encrypted message else if (preg_match('/^-----BEGIN PGP MESSAGE-----/', $body)) { $this->parse_plain_encrypted($p, $body); } } /** * Handler for multipart/signed message. * * @param array Reference to hook's parameters */ function parse_signed(&$p) { $struct = $p['structure']; // S/MIME if ($struct->parts[1] && $struct->parts[1]->mimetype == 'application/pkcs7-signature') { $this->parse_smime_signed($p); } // PGP/MIME: RFC3156 // The multipart/signed body MUST consist of exactly two parts. // The first part contains the signed data in MIME canonical format, // including a set of appropriate content headers describing the data. // The second body MUST contain the PGP digital signature. It MUST be // labeled with a content type of "application/pgp-signature". else if ($struct->ctype_parameters['protocol'] == 'application/pgp-signature' && count($struct->parts) == 2 && $struct->parts[1] && $struct->parts[1]->mimetype == 'application/pgp-signature' ) { $this->parse_pgp_signed($p); } } /** * Handler for multipart/encrypted message. * * @param array Reference to hook's parameters */ function parse_encrypted(&$p) { $struct = $p['structure']; // S/MIME if ($struct->mimetype == 'application/pkcs7-mime') { $this->parse_smime_encrypted($p); } // PGP/MIME: RFC3156 // The multipart/encrypted MUST consist of exactly two parts. The first // MIME body part must have a content type of "application/pgp-encrypted". // This body contains the control information. // The second MIME body part MUST contain the actual encrypted data. It // must be labeled with a content type of "application/octet-stream". else if ($struct->ctype_parameters['protocol'] == 'application/pgp-encrypted' && count($struct->parts) == 2 && $struct->parts[0] && $struct->parts[0]->mimetype == 'application/pgp-encrypted' && $struct->parts[1] && $struct->parts[1]->mimetype == 'application/octet-stream' ) { $this->parse_pgp_encrypted($p); } } /** * Handler for plain signed message. * Excludes message and signature bodies and verifies signature. * * @param array Reference to hook's parameters * @param string Message (part) body */ private function parse_plain_signed(&$p, $body) { $this->load_pgp_driver(); $part = $p['structure']; // Verify signature if ($this->rc->action == 'show' || $this->rc->action == 'preview') { $sig = $this->pgp_verify($body); } // @TODO: Handle big bodies using (temp) files // In this way we can use fgets on string as on file handle $fh = fopen('php://memory', 'br+'); // @TODO: fopen/fwrite errors handling if ($fh) { fwrite($fh, $body); rewind($fh); } $body = $part->body = null; $part->body_modified = true; // Extract body (and signature?) while (!feof($fh)) { $line = fgets($fh, 1024); if ($part->body === null) $part->body = ''; else if (preg_match('/^-----BEGIN PGP SIGNATURE-----/', $line)) break; else $part->body .= $line; } // Remove "Hash" Armor Headers $part->body = preg_replace('/^.*\r*\n\r*\n/', '', $part->body); // de-Dash-Escape (RFC2440) $part->body = preg_replace('/(^|\n)- -/', '\\1-', $part->body); // Store signature data for display if (!empty($sig)) { $this->signed_parts[$part->mime_id] = $part->mime_id; $this->signatures[$part->mime_id] = $sig; } fclose($fh); } /** * Handler for PGP/MIME signed message. * Verifies signature. * * @param array Reference to hook's parameters */ private function parse_pgp_signed(&$p) { // Verify signature if ($this->rc->action == 'show' || $this->rc->action == 'preview') { $this->load_pgp_driver(); $struct = $p['structure']; $msg_part = $struct->parts[0]; $sig_part = $struct->parts[1]; // Get bodies // Note: The first part body need to be full part body with headers // it also cannot be decoded $msg_body = $this->get_part_body($p['object'], $msg_part->mime_id, true); $sig_body = $this->get_part_body($p['object'], $sig_part->mime_id); // Verify $sig = $this->pgp_verify($msg_body, $sig_body); // Store signature data for display $this->signatures[$struct->mime_id] = $sig; // Message can be multipart (assign signature to each subpart) if (!empty($msg_part->parts)) { foreach ($msg_part->parts as $part) $this->signed_parts[$part->mime_id] = $struct->mime_id; } else { $this->signed_parts[$msg_part->mime_id] = $struct->mime_id; } // Remove signature file from attachments list (?) unset($struct->parts[1]); } } /** * Handler for S/MIME signed message. * Verifies signature. * * @param array Reference to hook's parameters */ private function parse_smime_signed(&$p) { return; // @TODO // Verify signature if ($this->rc->action == 'show' || $this->rc->action == 'preview') { $this->load_smime_driver(); $struct = $p['structure']; $msg_part = $struct->parts[0]; // Verify $sig = $this->smime_driver->verify($struct, $p['object']); // Store signature data for display $this->signatures[$struct->mime_id] = $sig; // Message can be multipart (assign signature to each subpart) if (!empty($msg_part->parts)) { foreach ($msg_part->parts as $part) $this->signed_parts[$part->mime_id] = $struct->mime_id; } else { $this->signed_parts[$msg_part->mime_id] = $struct->mime_id; } // Remove signature file from attachments list unset($struct->parts[1]); } } /** * Handler for plain encrypted message. * * @param array Reference to hook's parameters * @param string Message (part) body */ private function parse_plain_encrypted(&$p, $body) { $this->load_pgp_driver(); $part = $p['structure']; // Decrypt $result = $this->pgp_decrypt($body); // Store decryption status $this->decryptions[$part->mime_id] = $result; // Parse decrypted message if ($result === true) { $part->body = $body; $part->body_modified = true; $part->encrypted = true; // Encrypted plain message may contain encrypted attachments // in such case attachments have .pgp extension and application/octet-stream. // This is what happens when you select "Encrypt each attachment separately // and send the message using inline PGP" in Thunderbird's Enigmail. // find parent part ID if (strpos($part->mime_id, '.')) { $items = explode('.', $part->mime_id); array_pop($items); $parent = implode('.', $items); } else { $parent = 0; } if ($p['object']->mime_parts[$parent]) { foreach ((array)$p['object']->mime_parts[$parent]->parts as $p) { if ($p->disposition == 'attachment' && $p->mimetype == 'application/octet-stream' && preg_match('/^(.*)\.pgp$/i', $p->filename, $m) ) { // modify filename $p->filename = $m[1]; // flag the part, it will be decrypted when needed $p->need_decryption = true; // disable caching $p->body_modified = true; } } } } } /** * Handler for PGP/MIME encrypted message. * * @param array Reference to hook's parameters */ private function parse_pgp_encrypted(&$p) { $this->load_pgp_driver(); $struct = $p['structure']; $part = $struct->parts[1]; // Get body $body = $this->get_part_body($p['object'], $part->mime_id); // Decrypt $result = $this->pgp_decrypt($body); if ($result === true) { // Parse decrypted message $struct = $this->parse_body($body); // Modify original message structure $this->modify_structure($p, $struct); // Attach the decryption message to all parts $this->decryptions[$struct->mime_id] = $result; foreach ((array) $struct->parts as $sp) { $this->decryptions[$sp->mime_id] = $result; } } else { $this->decryptions[$part->mime_id] = $result; // Make sure decryption status message will be displayed $part->type = 'content'; $p['object']->parts[] = $part; } } /** * Handler for S/MIME encrypted message. * * @param array Reference to hook's parameters */ private function parse_smime_encrypted(&$p) { // $this->load_smime_driver(); } /** * PGP signature verification. * * @param mixed Message body * @param mixed Signature body (for MIME messages) * * @return mixed enigma_signature or enigma_error */ private function pgp_verify(&$msg_body, $sig_body=null) { // @TODO: Handle big bodies using (temp) files // @TODO: caching of verification result $sig = $this->pgp_driver->verify($msg_body, $sig_body); if (($sig instanceof enigma_error) && $sig->getCode() != enigma_error::E_KEYNOTFOUND) rcube::raise_error(array( 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Enigma plugin: " . $sig->getMessage() ), true, false); return $sig; } /** * PGP message decryption. * * @param mixed Message body * * @return mixed True or enigma_error */ private function pgp_decrypt(&$msg_body) { // @TODO: Handle big bodies using (temp) files // @TODO: caching of verification result $keys = $this->get_passwords(); $result = $this->pgp_driver->decrypt($msg_body, $keys); if ($result instanceof enigma_error) { $err_code = $result->getCode(); if (!in_array($err_code, array(enigma_error::E_KEYNOTFOUND, enigma_error::E_BADPASS))) rcube::raise_error(array( 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Enigma plugin: " . $result->getMessage() ), true, false); return $result; } $msg_body = $result; return true; } /** * PGP keys listing. * * @param mixed Key ID/Name pattern * * @return mixed Array of keys or enigma_error */ function list_keys($pattern = '') { $this->load_pgp_driver(); $result = $this->pgp_driver->list_keys($pattern); if ($result instanceof enigma_error) { rcube::raise_error(array( 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Enigma plugin: " . $result->getMessage() ), true, false); } return $result; } /** * PGP key details. * * @param mixed Key ID * * @return mixed enigma_key or enigma_error */ function get_key($keyid) { $this->load_pgp_driver(); $result = $this->pgp_driver->get_key($keyid); if ($result instanceof enigma_error) { rcube::raise_error(array( 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Enigma plugin: " . $result->getMessage() ), true, false); } return $result; } /** * PGP key delete. * * @param string Key ID * * @return enigma_error|bool True on success */ function delete_key($keyid) { $this->load_pgp_driver(); $result = $this->pgp_driver->delete_key($keyid); if ($result instanceof enigma_error) { rcube::raise_error(array( 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Enigma plugin: " . $result->getMessage() ), true, false); } return $result; } /** * PGP keys/certs importing. * * @param mixed Import file name or content * @param boolean True if first argument is a filename * * @return mixed Import status data array or enigma_error */ function import_key($content, $isfile=false) { $this->load_pgp_driver(); $result = $this->pgp_driver->import($content, $isfile); if ($result instanceof enigma_error) { rcube::raise_error(array( 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Enigma plugin: " . $result->getMessage() ), true, false); } else { $result['imported'] = $result['public_imported'] + $result['private_imported']; $result['unchanged'] = $result['public_unchanged'] + $result['private_unchanged']; } return $result; } /** * Handler for keys/certs import request action */ function import_file() { $uid = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_POST); $mbox = rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_POST); $mime_id = rcube_utils::get_input_value('_part', rcube_utils::INPUT_POST); $storage = $this->rc->get_storage(); if ($uid && $mime_id) { $storage->set_folder($mbox); $part = $storage->get_message_part($uid, $mime_id); } if ($part && is_array($result = $this->import_key($part))) { $this->rc->output->show_message('enigma.keysimportsuccess', 'confirmation', array('new' => $result['imported'], 'old' => $result['unchanged'])); } else $this->rc->output->show_message('enigma.keysimportfailed', 'error'); $this->rc->output->send(); } function password_handler() { $keyid = rcube_utils::get_input_value('_keyid', rcube_utils::INPUT_POST); $passwd = rcube_utils::get_input_value('_passwd', rcube_utils::INPUT_POST, true); if ($keyid && $passwd !== null && strlen($passwd)) { $this->save_password($keyid, $passwd); } } function save_password($keyid, $password) { // we store passwords in session for specified time if ($config = $_SESSION['enigma_pass']) { $config = $this->rc->decrypt($config); $config = @unserialize($config); } $config[$keyid] = array($password, time()); $_SESSION['enigma_pass'] = $this->rc->encrypt(serialize($config)); } function get_passwords() { if ($config = $_SESSION['enigma_pass']) { $config = $this->rc->decrypt($config); $config = @unserialize($config); } $threshold = time() - self::PASSWORD_TIME; $keys = array(); // delete expired passwords foreach ((array) $config as $key => $value) { if ($value[1] < $threshold) { unset($config[$key]); $modified = true; } else { $keys[$key] = $value[0]; } } if ($modified) { $_SESSION['enigma_pass'] = $this->rc->encrypt(serialize($config)); } return $keys; } /** * Get message part body. * * @param rcube_message Message object * @param string Message part ID * @param bool Return raw body with headers */ private function get_part_body($msg, $part_id, $full = false) { // @TODO: Handle big bodies using file handles if ($full) { $storage = $this->rc->get_storage(); $body = $storage->get_raw_headers($msg->uid, $part_id); $body .= $storage->get_raw_body($msg->uid, null, $part_id); } else { $body = $msg->get_part_body($part_id, false); } return $body; } /** * Parse decrypted message body into structure * * @param string Message body * * @return array Message structure */ private function parse_body(&$body) { // Mail_mimeDecode need \r\n end-line, but gpg may return \n $body = preg_replace('/\r?\n/', "\r\n", $body); // parse the body into structure $struct = rcube_mime::parse_message($body); return $struct; } /** * Replace message encrypted structure with decrypted message structure * * @param array * @param rcube_message_part */ private function modify_structure(&$p, $struct) { // modify mime_parts property of the message object $old_id = $p['structure']->mime_id; foreach (array_keys($p['object']->mime_parts) as $idx) { if (!$old_id || $idx == $old_id || strpos($idx, $old_id . '.') === 0) { unset($p['object']->mime_parts[$idx]); } } // modify the new structure to be correctly handled by Roundcube $this->modify_structure_part($struct, $p['object'], $old_id); // replace old structure with the new one $p['structure'] = $struct; $p['mimetype'] = $struct->mimetype; } /** * Modify decrypted message part * * @param rcube_message_part * @param rcube_message */ private function modify_structure_part($part, $msg, $old_id) { // never cache the body $part->body_modified = true; $part->encoding = 'stream'; // Cache the fact it was decrypted $part->encrypted = true; // modify part identifier if ($old_id) { $part->mime_id = !$part->mime_id ? $old_id : ($old_id . '.' . $part->mime_id); } $msg->mime_parts[$part->mime_id] = $part; // modify sub-parts foreach ((array) $part->parts as $p) { $this->modify_structure_part($p, $msg, $old_id); } } /** * Checks if specified message part is a PGP-key or S/MIME cert data * * @param rcube_message_part Part object * * @return boolean True if part is a key/cert */ public function is_keys_part($part) { // @TODO: S/MIME return ( // Content-Type: application/pgp-keys $part->mimetype == 'application/pgp-keys' ); } }
apache-2.0
quantumlib/Cirq
cirq-rigetti/cirq_rigetti/sampler.py
5548
# Copyright 2021 The Cirq Developers # # 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 # # https://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. from typing import Optional, Sequence from pyquil import get_qc from pyquil.api import QuantumComputer import cirq from cirq_rigetti import circuit_transformers as transformers from cirq_rigetti import circuit_sweep_executors as executors _default_executor = executors.with_quilc_compilation_and_cirq_parameter_resolution class RigettiQCSSampler(cirq.Sampler): """This class supports running circuits on QCS quantum hardware as well as pyQuil's quantum virtual machine (QVM). It implements the `cirq.Sampler` interface and thereby supports sampling parameterized circuits across parameter sweeps. """ def __init__( self, quantum_computer: QuantumComputer, executor: executors.CircuitSweepExecutor = _default_executor, transformer: transformers.CircuitTransformer = transformers.default, ): """Initializes a `RigettiQCSSampler`. Args: quantum_computer: A `pyquil.api.QuantumComputer` against which to run the `cirq.Circuit`s. executor: A callable that first uses the below `transformer` on `cirq.Circuit` s and then executes the transformed circuit on the `quantum_computer`. You may pass your own callable or any static method on `CircuitSweepExecutors`. transformer: A callable that transforms the `cirq.Circuit` into a `pyquil.Program`. You may pass your own callable or any static method on `CircuitTransformers`. """ self._quantum_computer = quantum_computer self.executor = executor self.transformer = transformer def run_sweep( self, program: cirq.AbstractCircuit, params: cirq.Sweepable, repetitions: int = 1, ) -> Sequence[cirq.Result]: """This will evaluate results on the circuit for every set of parameters in `params`. Args: program: Circuit to evaluate for each set of parameters in `params`. params: `cirq.Sweepable` of parameters which this function passes to `cirq.protocols.resolve_parameters` for evaluating the circuit. repetitions: Number of times to run each iteration through the `params`. For a given set of parameters, the `cirq.Result` will include a measurement for each repetition. Returns: A list of `cirq.Result` s. """ resolvers = [r for r in cirq.to_resolvers(params)] return self.executor( quantum_computer=self._quantum_computer, circuit=program.unfreeze(copy=False), resolvers=resolvers, repetitions=repetitions, transformer=self.transformer, ) def get_rigetti_qcs_sampler( quantum_processor_id: str, *, as_qvm: Optional[bool] = None, noisy: Optional[bool] = None, executor: executors.CircuitSweepExecutor = _default_executor, transformer: transformers.CircuitTransformer = transformers.default, ) -> RigettiQCSSampler: """Calls `pyquil.get_qc` to initialize a `pyquil.api.QuantumComputer` and uses this to initialize `RigettiQCSSampler`. Args: quantum_processor_id: The name of the desired quantum computer. This should correspond to a name returned by `pyquil.api.list_quantum_computers`. Names ending in "-qvm" will return a QVM. Names ending in "-pyqvm" will return a `pyquil.PyQVM`. Otherwise, we will return a Rigetti QCS QPU if one exists with the requested name. as_qvm: An optional flag to force construction of a QVM (instead of a QPU). If specified and set to `True`, a QVM-backed quantum computer will be returned regardless of the name's suffix noisy: An optional flag to force inclusion of a noise model. If specified and set to `True`, a quantum computer with a noise model will be returned. The generic QVM noise model is simple T1 and T2 noise plus readout error. At the time of this writing, this has no effect on a QVM initialized based on a Rigetti QCS `qcs_api_client.models.InstructionSetArchitecture`. executor: A callable that first uses the below transformer on cirq.Circuit s and then executes the transformed circuit on the quantum_computer. You may pass your own callable or any static method on CircuitSweepExecutors. transformer: A callable that transforms the cirq.Circuit into a pyquil.Program. You may pass your own callable or any static method on CircuitTransformers. Returns: A `RigettiQCSSampler` with the specified quantum processor, executor, and transformer. """ qc = get_qc( quantum_processor_id, as_qvm=as_qvm, noisy=noisy, ) return RigettiQCSSampler( quantum_computer=qc, executor=executor, transformer=transformer, )
apache-2.0
JohnSnowLabs/spark-nlp
docs/_posts/HashamUlHaq/2021-02-03-hindi_cc_300d_hi.md
2029
--- layout: model title: Word Embeddings for Hindi (hindi_cc_300d) author: John Snow Labs name: hindi_cc_300d date: 2021-02-03 task: Embeddings language: hi edition: Spark NLP 2.7.2 spark_version: 2.4 tags: [embeddings, open_source, hi] supported: true article_header: type: cover use_language_switcher: "Python-Scala-Java" --- ## Description This model is trained on Common Crawl and Wikipedia using fastText. It is trained using CBOW with position-weights, in dimension 300, with character n-grams of length 5, a window of size 5 and 10 negatives. The model gives 300 dimensional vector outputs per token. The output vectors map words into a meaningful space where the distance between the vectors is related to semantic similarity of words. These embeddings can be used in multiple tasks like semantic word similarity, named entity recognition, sentiment analysis, and classification. {:.btn-box} <button class="button button-orange" disabled>Live Demo</button> <button class="button button-orange" disabled>Open in Colab</button> [Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/models/hindi_cc_300d_hi_2.7.2_2.4_1612362695785.zip){:.button.button-orange.button-orange-trans.arr.button-icon} ## How to use Use as part of a pipeline after tokenization. <div class="tabs-box" markdown="1"> {% include programmingLanguageSelectScalaPythonNLU.html %} ```python embeddings = WordEmbeddingsModel.pretrained("hindi_cc_300d", "hi") \ .setInputCols(["sentence", "token"]) \ .setOutputCol("embeddings") ``` </div> ## Results ```bash The model gives 300 dimensional feature vector output per token. ``` {:.model-param} ## Model Information {:.table-model} |---|---| |Model Name:|hindi_cc_300d| |Type:|embeddings| |Compatibility:|Spark NLP 2.7.2+| |License:|Open Source| |Input Labels:|[document, token]| |Output Labels:|[word_embeddings]| |Language:|hi| |Case sensitive:|false| |Dimension:|300| ## Data Source This model is imported from https://fasttext.cc/docs/en/crawl-vectors.html
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Salicaceae/Populus/Populus inopina/README.md
181
# Populus inopina Eckenw. SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
vesteraas/primeng
showcase/demo/responsive/responsivedemo.html
36238
<div> <style type="text/css"> /** Demo **/ .ui-grid-row .ui-grid-col-2, .ui-grid-row .ui-grid-col-10 { padding: 0.5em 0; } .ui-datagrid .ui-datagrid-column { text-align: center; } </style> <div class="ContentSideSections"> <div> <span class="fontSize30 TextShadow orange marginBottom20 dispBlock">Responsive</span> <span class="defaultText">.ui-fluid style class provides fluid width to components for efficient use of space in screen. This example demonstrates ui-fluid in combination with Grid CSS and the components having built-in responsive modes like datatable. Note that Grid CSS is not mandatory, any grid system can be used with ui-fluid.</span> </div> </div> <div class="ContentSideSections Implementation ui-fluid"> <div class="ui-grid ui-grid-responsive ui-grid-pad"> <div class="ui-grid-row"> <div class="ui-grid-col-6"> <div class="ui-grid-col-4"> InputText </div> <div class="ui-grid-col-8"> <input pInputText type="text" /> </div> </div> <div class="ui-grid-col-6"> <div class="ui-grid-col-4"> Textarea </div> <div class="ui-grid-col-8"> <textarea pInputTextarea type="text"></textarea> </div> </div> </div> <div class="ui-grid-row"> <div class="ui-grid-col-6"> <div class="ui-grid-col-4"> Calendar </div> <div class="ui-grid-col-8"> <p-calendar [(ngModel)]="date"></p-calendar> </div> </div> <div class="ui-grid-col-6"> <div class="ui-grid-col-4"> AutoComplete </div> <div class="ui-grid-col-8"> <p-autoComplete [(ngModel)]="country" [suggestions]="filteredCountriesSingle" (completeMethod)="filterCountrySingle($event)" field="name" [size]="30" placeholder="Countries" [minLength]="1"></p-autoComplete> </div> </div> </div> <div class="ui-grid-row"> <div class="ui-grid-col-6"> <div class="ui-grid-col-4"> Button </div> <div class="ui-grid-col-8"> <button pButton label="Save"type="button"></button> </div> </div> <div class="ui-grid-col-6"> <div class="ui-grid-col-4"> SplitButton </div> <div class="ui-grid-col-8"> <p-splitButton label="Save" icon="fa-check"> <p-splitButtonItem icon="fa-close" label="Delete"></p-splitButtonItem> <p-splitButtonItem icon="fa-refresh" label="Update"></p-splitButtonItem> <p-splitButtonItem icon="fa-link" label="Angular.io" url="http://angular.io"></p-splitButtonItem> </p-splitButton> </div> </div> </div> <div class="ui-grid-row"> <div class="ui-grid-col-6"> <div class="ui-grid-col-4"> Dropdown </div> <div class="ui-grid-col-8"> <p-dropdown [options]="cities" [(ngModel)]="selectedCity" [autoWidth]="false"></p-dropdown> </div> </div> <div class="ui-grid-col-6"> <div class="ui-grid-col-4"> Password </div> <div class="ui-grid-col-8"> <input type="text" pPassword /> </div> </div> </div> <div class="ui-grid-row"> <div class="ui-grid-col-6"> <div class="ui-grid-col-4"> Listbox </div> <div class="ui-grid-col-8"> <p-listbox [options]="options" [(ngModel)]="selectedOptions"></p-listbox> </div> </div> <div class="ui-grid-col-6"> <div class="ui-grid-col-4"> RadioButton </div> <div class="ui-grid-col-8"> <div class="ui-grid ui-grid-responsive"> <div class="ui-grid-row"> <div class="ui-grid-col-1"><p-radioButton name="group1" value="Option 1" [(ngModel)]="val"></p-radioButton></div> <div class="ui-grid-col-11"><label class="ui-widget">Option 1</label></div> </div> <div class="ui-grid-row"> <div class="ui-grid-col-1"><p-radioButton name="group1" value="Option 2" [(ngModel)]="val"></p-radioButton></div> <div class="ui-grid-col-11"><label class="ui-widget">Option 2</label></div> </div> <div class="ui-grid-row"> <div class="ui-grid-col-1"><p-radioButton name="group1" value="Option 3" [(ngModel)]="val"></p-radioButton></div> <div class="ui-grid-col-11"><label class="ui-widget">Option 3</label></div> </div> <div class="ui-grid-row"> <div class="ui-grid-col-1"><p-radioButton name="group1" value="Option 4" [(ngModel)]="val"></p-radioButton></div> <div class="ui-grid-col-11"><label class="ui-widget">Option 4</label></div> </div> </div> </div> </div> </div> <div class="ui-grid-row"> <div class="ui-grid-col-2"> Dialog </div> <div class="ui-grid-col-10"> <button pButton label="Show" type="button" icon='fa-external-link' (click)="showDialog()"></button> </div> </div> </div> <p-dialog header="Godfather 1" [(visible)]="display" [responsive]="true" [resizable]="false"> <p>The story begins as Don Vito Corleone, the head of a New York Mafia family, oversees his daughter's wedding. His beloved son Michael has just come home from the war, but does not intend to become part of his father's business. Through Michael's life the nature of the family business becomes clear. The business of the family is just like the head of the family, kind and benevolent to those who give respect, but given to ruthless violence whenever anything stands against the good of the family.</p> </p-dialog> <p-panel header="Panel" style="margin-top:20px"> The story begins as Don Vito Corleone, the head of a New York Mafia family, oversees his daughter's wedding. His beloved son Michael has just come home from the war, but does not intend to become part of his father's business. Through Michael's life the nature of the family business becomes clear. The business of the family is just like the head of the family, kind and benevolent to those who give respect, but given to ruthless violence whenever anything stands against the good of the family. </p-panel> <p-dataTable style="margin-top:20px" [value]="cars" [rows]="10" [paginator]="true" [pageLinks]="3" [responsive]="true"> <header>Cars</header> <p-column field="vin" header="Vin"></p-column> <p-column field="year" header="Year"></p-column> <p-column field="brand" header="Brand"></p-column> <p-column field="color" header="Color"></p-column> </p-dataTable> <p-dataGrid style="margin-top:20px;margin-bottom:20px" [value]="cars" [columns]="5" [paginator]="true" [rows]="20"> <header> Datagrid </header> <template let-car> <div style="padding:3px"> <p-panel [header]="car.vin" [paginator]="true" style="text-align:center"> <img src="showcase/resources/demo/images/car/{{car.brand}}.gif"> <div class="car-detail">{{car.year}} - {{car.color}}</div> <hr class="ui-widget-content" style="border-top:0"> </p-panel> </div> </template> </p-dataGrid> <p-tree [value]="files" style="margin-top:20px;margin-bottom:20px"></p-tree> <p-orderList [value]="cars" listStyle="height:250px" style="margin-top:20px;margin-bottom:20px" [responsive]="true" header="Responsive Cars"> <template let-car> <li class="ui-orderlist-item ui-helper-clearfix"> <img src="showcase/resources/demo/images/car/{{car.brand}}.gif" style="display:inline-block;margin:2px 0 2px 2px"/> <div style="font-size:14px;float:right;margin:15px 5px 0 0">{{car.brand}} - {{car.year}} - {{car.color}}</div> </li> </template> </p-orderList> <p-carousel headerText="Cars" [value]="cars2" style="margin-top:20px;margin-bottom:20px"> <template let-car> <li> <div class="ui-grid ui-grid-responsive ui-grid-pad" style="text-align:center"> <div class="ui-grid-row"> <div class="ui-grid-col-12" style="text-align:center"><img src="showcase/resources/demo/images/car/{{car.brand}}.gif" /></div> </div> <div class="ui-grid-row"> <div class="ui-grid-col-6">Vin</div> <div class="ui-grid-col-6">{{car.vin}}</div> </div> <div class="ui-grid-row"> <div class="ui-grid-col-6">Year</div> <div class="ui-grid-col-6">{{car.year}}</div> </div> <div class="ui-grid-row"> <div class="ui-grid-col-6">Color</div> <div class="ui-grid-col-6">{{car.color}}</div> </div> </div> </li> </template> </p-carousel> <p-pickList [source]="sourceCars" [target]="targetCars" sourceHeader="Available" targetHeader="Selected" [responsive]="true" sourceStyle="height:300px" targetStyle="height:300px" style="margin-top:20px;margin-bottom:20px"> <template let-car> <li class="ui-picklist-item ui-helper-clearfix"> <img src="showcase/resources/demo/images/car/{{car.brand}}.gif" style="display:inline-block;margin:2px 0 2px 2px"/> <div style="font-size:14px;float:right;margin:15px 5px 0 0">{{car.brand}} - {{car.year}} - {{car.color}}</div> </li> </template> </p-pickList> <div class="ui-grid ui-grid-responsive ui-grid-pad"> <div class="ui-grid-row"> <div class="ui-grid-col-6"> <p-menu> <ul> <li><h3>File</h3></li> <li><a data-icon="fa-plus"><span>New</span></a></li> <li><a data-icon="fa-download"><span>Open</span></a></li> <li><h3>Edit</h3></li> <li><a data-icon="fa-refresh"><span>Undo</span></a></li> <li><a data-icon="fa-repeat"><span>Redo</span></a></li> </ul> </p-menu> </div> <div class="ui-grid-col-6"> <p-panelMenu> <div> <div><a data-icon="fa-file-o"><span>File</span></a></div> <div> <ul> <li><a data-icon="fa-plus"><span>New</span></a> <ul> <li><a><span>Project</span></a></li> <li><a><span>Other</span></a></li> </ul> </li> <li><a><span>Open</span></a></li> <li><a><span>Quit</span></a></li> </ul> </div> </div> <div> <div><a data-icon="fa-edit"><span>Edit</span></a></div> <div> <ul> <li><a data-icon="fa-mail-forward"><span>Undo</span></a></li> <li><a data-icon="fa-mail-reply"><span>Redo</span></a></li> </ul> </div> </div> <div> <div><a data-icon="fa-question"><span>Help</span></a></div> <div> <ul> <li><a><span>Contents</span></a></li> <li><a data-icon="fa-search"><span>Search</span></a> <ul> <li><a><span>Text</span></a> <ul> <li><a><span>Workspace</span></a></li> </ul> </li> <li><a><span>File</span></a></li> </ul> </li> </ul> </div> </div> <div> <div><a data-icon="fa-gear"><span>Actions</span></a></div> <div> <ul> <li><a data-icon="fa-pencil"><span>Edit</span></a> <ul> <li><a data-icon="fa-save"><span>Save</span></a></li> <li><a data-icon="fa-save"><span>Update</span></a></li> </ul> </li> <li><a data-icon="fa-phone"><span>Other</span></a> <ul> <li><a data-icon="fa-minus"><span>Delete</span></a></li> </ul> </li> </ul> </div> </div> </p-panelMenu> </div> </div> </div> </div> </div> <div class="ContentSideSections Source"> <p-tabView effect="fade"> <p-tabPanel header="Source"> <pre> <code class="language-markup" pCode ngNonBindable> &lt;div class="ui-grid ui-grid-responsive ui-grid-pad"&gt; &lt;div class="ui-grid-row"&gt; &lt;div class="ui-grid-col-6"&gt; &lt;div class="ui-grid-col-4"&gt; InputText &lt;/div&gt; &lt;div class="ui-grid-col-8"&gt; &lt;input pInputText type="text" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="ui-grid-col-6"&gt; &lt;div class="ui-grid-col-4"&gt; Textarea &lt;/div&gt; &lt;div class="ui-grid-col-8"&gt; &lt;textarea pInputTextarea type="text"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="ui-grid-row"&gt; &lt;div class="ui-grid-col-6"&gt; &lt;div class="ui-grid-col-4"&gt; Calendar &lt;/div&gt; &lt;div class="ui-grid-col-8"&gt; &lt;p-calendar [(ngModel)]="date"&gt;&lt;/p-calendar&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="ui-grid-col-6"&gt; &lt;div class="ui-grid-col-4"&gt; AutoComplete &lt;/div&gt; &lt;div class="ui-grid-col-8"&gt; &lt;p-autoComplete [(ngModel)]="country" [suggestions]="filteredCountriesSingle" (completeMethod)="filterCountrySingle($event)" field="name" [size]="30" placeholder="Countries" [minLength]="1"&gt;&lt;/p-autoComplete&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="ui-grid-row"&gt; &lt;div class="ui-grid-col-6"&gt; &lt;div class="ui-grid-col-4"&gt; Button &lt;/div&gt; &lt;div class="ui-grid-col-8"&gt; &lt;button pButton label="Save"type="button"&gt;&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="ui-grid-col-6"&gt; &lt;div class="ui-grid-col-4"&gt; SplitButton &lt;/div&gt; &lt;div class="ui-grid-col-8"&gt; &lt;p-splitButton label="Save" icon="fa-check" (onClick)="save()"&gt; &lt;p-splitButtonItem icon="fa-close" label="Delete" (onClick)="delete()"&gt;&lt;/p-splitButtonItem&gt; &lt;p-splitButtonItem icon="fa-refresh" label="Update" (onClick)="update()"&gt;&lt;/p-splitButtonItem&gt; &lt;p-splitButtonItem icon="fa-link" label="Angular.io" url="http://angular.io"&gt;&lt;/p-splitButtonItem&gt; &lt;/p-splitButton&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="ui-grid-row"&gt; &lt;div class="ui-grid-col-6"&gt; &lt;div class="ui-grid-col-4"&gt; Dropdown &lt;/div&gt; &lt;div class="ui-grid-col-8"&gt; &lt;p-dropdown [options]="cities" [(ngModel)]="selectedCity" [autoWidth]="false"&gt;&lt;/p-dropdown&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="ui-grid-col-6"&gt; &lt;div class="ui-grid-col-4"&gt; Password &lt;/div&gt; &lt;div class="ui-grid-col-8"&gt; &lt;input type="text" pPassword /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="ui-grid-row"&gt; &lt;div class="ui-grid-col-6"&gt; &lt;div class="ui-grid-col-4"&gt; Listbox &lt;/div&gt; &lt;div class="ui-grid-col-8"&gt; &lt;p-listbox [options]="options" [(ngModel)]="selectedOptions"&gt;&lt;/p-listbox&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="ui-grid-col-6"&gt; &lt;div class="ui-grid-col-4"&gt; RadioButton &lt;/div&gt; &lt;div class="ui-grid-col-8"&gt; &lt;div class="ui-grid ui-grid-responsive"&gt; &lt;div class="ui-grid-row"&gt; &lt;div class="ui-grid-col-1"&gt;&lt;p-radioButton name="group1" value="Option 1" [(ngModel)]="val"&gt;&lt;/p-radioButton&gt;&lt;/div&gt; &lt;div class="ui-grid-col-11"&gt;&lt;label class="ui-widget"&gt;Option 1&lt;/label&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="ui-grid-row"&gt; &lt;div class="ui-grid-col-1"&gt;&lt;p-radioButton name="group1" value="Option 2" [(ngModel)]="val"&gt;&lt;/p-radioButton&gt;&lt;/div&gt; &lt;div class="ui-grid-col-11"&gt;&lt;label class="ui-widget"&gt;Option 2&lt;/label&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="ui-grid-row"&gt; &lt;div class="ui-grid-col-1"&gt;&lt;p-radioButton name="group1" value="Option 3" [(ngModel)]="val"&gt;&lt;/p-radioButton&gt;&lt;/div&gt; &lt;div class="ui-grid-col-11"&gt;&lt;label class="ui-widget"&gt;Option 3&lt;/label&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="ui-grid-row"&gt; &lt;div class="ui-grid-col-1"&gt;&lt;p-radioButton name="group1" value="Option 4" [(ngModel)]="val"&gt;&lt;/p-radioButton&gt;&lt;/div&gt; &lt;div class="ui-grid-col-11"&gt;&lt;label class="ui-widget"&gt;Option 4&lt;/label&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="ui-grid-row"&gt; &lt;div class="ui-grid-col-2"&gt; Dialog &lt;/div&gt; &lt;div class="ui-grid-col-10"&gt; &lt;button pButton label="Show" type="button" icon='fa-external-link' (click)="showDialog()"&gt;&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;p-dialog header="Godfather 1" [(visible)]="display" [responsive]="true" [resizable]="false"&gt; &lt;p&gt;The story begins as Don Vito Corleone, the head of a New York Mafia family, oversees his daughter's wedding. His beloved son Michael has just come home from the war, but does not intend to become part of his father's business. Through Michael's life the nature of the family business becomes clear. The business of the family is just like the head of the family, kind and benevolent to those who give respect, but given to ruthless violence whenever anything stands against the good of the family.&lt;/p&gt; &lt;/p-dialog&gt; &lt;p-panel header="Panel" style="margin-top:20px"&gt; The story begins as Don Vito Corleone, the head of a New York Mafia family, oversees his daughter's wedding. His beloved son Michael has just come home from the war, but does not intend to become part of his father's business. Through Michael's life the nature of the family business becomes clear. The business of the family is just like the head of the family, kind and benevolent to those who give respect, but given to ruthless violence whenever anything stands against the good of the family. &lt;/p-panel&gt; &lt;p-dataTable style="margin-top:20px" [value]="cars" [rows]="10" [paginator]="true" [pageLinks]="3" [responsive]="true"&gt; &lt;header&gt;Cars&lt;/header&gt; &lt;p-column field="vin" header="Vin"&gt;&lt;/p-column&gt; &lt;p-column field="year" header="Year"&gt;&lt;/p-column&gt; &lt;p-column field="brand" header="Brand"&gt;&lt;/p-column&gt; &lt;p-column field="color" header="Color"&gt;&lt;/p-column&gt; &lt;/p-dataTable&gt; &lt;p-dataGrid style="margin-top:20px;margin-bottom:20px" [value]="cars" [columns]="5" [paginator]="true" [rows]="20"&gt; &lt;header&gt; Datagrid &lt;/header&gt; &lt;template let-car&gt; &lt;div style="padding:3px"&gt; &lt;p-panel [header]="car.vin" [paginator]="true" style="text-align:center"&gt; &lt;img src="showcase/resources/demo/images/car/{{car.brand}}.gif"&gt; &lt;div class="car-detail"&gt;{{car.year}} - {{car.color}}&lt;/div&gt; &lt;hr class="ui-widget-content" style="border-top:0"&gt; &lt;/p-panel&gt; &lt;/div&gt; &lt;/template&gt; &lt;/p-dataGrid&gt; &lt;p-tree [value]="files" style="margin-top:20px;margin-bottom:20px"&gt;&lt;/p-tree&gt; &lt;p-orderList [value]="cars" listStyle="height:250px" style="margin-top:20px;margin-bottom:20px" [responsive]="true" header="Responsive Cars"&gt; &lt;template let-car&gt; &lt;li class="ui-orderlist-item ui-helper-clearfix"&gt; &lt;img src="showcase/resources/demo/images/car/{{car.brand}}.gif" style="display:inline-block;margin:2px 0 2px 2px"/&gt; &lt;div style="font-size:14px;float:right;margin:15px 5px 0 0"&gt;{{car.brand}} - {{car.year}} - {{car.color}}&lt;/div&gt; &lt;/li&gt; &lt;/template&gt; &lt;/p-orderList&gt; &lt;p-carousel headerText="Cars" [value]="cars2" style="margin-top:20px;margin-bottom:20px"&gt; &lt;template let-car&gt; &lt;li&gt; &lt;div class="ui-grid ui-grid-responsive ui-grid-pad" style="text-align:center"&gt; &lt;div class="ui-grid-row"&gt; &lt;div class="ui-grid-col-12" style="text-align:center"&gt;&lt;img src="showcase/resources/demo/images/car/{{car.brand}}.gif" /&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="ui-grid-row"&gt; &lt;div class="ui-grid-col-6"&gt;Vin&lt;/div&gt; &lt;div class="ui-grid-col-6"&gt;{{car.vin}}&lt;/div&gt; &lt;/div&gt; &lt;div class="ui-grid-row"&gt; &lt;div class="ui-grid-col-6"&gt;Year&lt;/div&gt; &lt;div class="ui-grid-col-6"&gt;{{car.year}}&lt;/div&gt; &lt;/div&gt; &lt;div class="ui-grid-row"&gt; &lt;div class="ui-grid-col-6"&gt;Color&lt;/div&gt; &lt;div class="ui-grid-col-6"&gt;{{car.color}}&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/li&gt; &lt;/template&gt; &lt;/p-carousel&gt; &lt;p-pickList [source]="sourceCars" [target]="targetCars" sourceHeader="Available" targetHeader="Selected" [responsive]="true" sourceStyle="height:300px" targetStyle="height:300px" style="margin-top:20px;margin-bottom:20px"&gt; &lt;template let-car&gt; &lt;li class="ui-picklist-item ui-helper-clearfix"&gt; &lt;img src="showcase/resources/demo/images/car/{{car.brand}}.gif" style="display:inline-block;margin:2px 0 2px 2px"/&gt; &lt;div style="font-size:14px;float:right;margin:15px 5px 0 0"&gt;{{car.brand}} - {{car.year}} - {{car.color}}&lt;/div&gt; &lt;/li&gt; &lt;/template&gt; &lt;/p-pickList&gt; &lt;div class="ui-grid ui-grid-responsive ui-grid-pad"&gt; &lt;div class="ui-grid-row"&gt; &lt;div class="ui-grid-col-6"&gt; &lt;p-menu&gt; &lt;ul&gt; &lt;li&gt;&lt;h3&gt;File&lt;/h3&gt;&lt;/li&gt; &lt;li&gt;&lt;a data-icon="fa-plus"&gt;&lt;span&gt;New&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a data-icon="fa-download"&gt;&lt;span&gt;Open&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;h3&gt;Edit&lt;/h3&gt;&lt;/li&gt; &lt;li&gt;&lt;a data-icon="fa-refresh"&gt;&lt;span&gt;Undo&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a data-icon="fa-repeat"&gt;&lt;span&gt;Redo&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/p-menu&gt; &lt;/div&gt; &lt;div class="ui-grid-col-6"&gt; &lt;p-panelMenu&gt; &lt;div&gt; &lt;div&gt;&lt;a data-icon="fa-file-o"&gt;&lt;span&gt;File&lt;/span&gt;&lt;/a&gt;&lt;/div&gt; &lt;div&gt; &lt;ul&gt; &lt;li&gt;&lt;a data-icon="fa-plus"&gt;&lt;span&gt;New&lt;/span&gt;&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a&gt;&lt;span&gt;Project&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a&gt;&lt;span&gt;Other&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a&gt;&lt;span&gt;Open&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a&gt;&lt;span&gt;Quit&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;div&gt;&lt;a data-icon="fa-edit"&gt;&lt;span&gt;Edit&lt;/span&gt;&lt;/a&gt;&lt;/div&gt; &lt;div&gt; &lt;ul&gt; &lt;li&gt;&lt;a data-icon="fa-mail-forward"&gt;&lt;span&gt;Undo&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a data-icon="fa-mail-reply"&gt;&lt;span&gt;Redo&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;div&gt;&lt;a data-icon="fa-question"&gt;&lt;span&gt;Help&lt;/span&gt;&lt;/a&gt;&lt;/div&gt; &lt;div&gt; &lt;ul&gt; &lt;li&gt;&lt;a&gt;&lt;span&gt;Contents&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a data-icon="fa-search"&gt;&lt;span&gt;Search&lt;/span&gt;&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a&gt;&lt;span&gt;Text&lt;/span&gt;&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a&gt;&lt;span&gt;Workspace&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a&gt;&lt;span&gt;File&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;div&gt;&lt;a data-icon="fa-gear"&gt;&lt;span&gt;Actions&lt;/span&gt;&lt;/a&gt;&lt;/div&gt; &lt;div&gt; &lt;ul&gt; &lt;li&gt;&lt;a data-icon="fa-pencil"&gt;&lt;span&gt;Edit&lt;/span&gt;&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a data-icon="fa-save"&gt;&lt;span&gt;Save&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a data-icon="fa-save"&gt;&lt;span&gt;Update&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a data-icon="fa-phone"&gt;&lt;span&gt;Other&lt;/span&gt;&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a data-icon="fa-minus"&gt;&lt;span&gt;Delete&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/p-panelMenu&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code> </pre> <pre> <code class="language-typescript" pCode> export class ResponsiveDemo implements OnInit { cities: SelectItem[]; files: TreeNode[]; sourceCars: Car[]; targetCars: Car[]; data: any; selectedCity: string; val: string; options: SelectItem[]; selectedOption: string; display: boolean = false; cars: Car[]; cars1: Car[]; cars2: Car[]; cars3: Car[]; date: string; text: string; filteredCountriesSingle: any[]; showDialog() { this.display = true; } constructor(private carService: CarService, private countryService: CountryService, private nodeService: NodeService) { this.cars2 = [ {vin: 'r3278r2', year: 2010, brand: 'Audi', color: 'Black'}, {vin: 'jhto2g2', year: 2015, brand: 'BMW', color: 'White'}, {vin: 'h453w54', year: 2012, brand: 'Honda', color: 'Blue'}, {vin: 'g43gwwg', year: 1998, brand: 'Renault', color: 'White'}, {vin: 'gf45wg5', year: 2011, brand: 'VW', color: 'Red'}, {vin: 'bhv5y5w', year: 2015, brand: 'Jaguar', color: 'Blue'}, {vin: 'ybw5fsd', year: 2012, brand: 'Ford', color: 'Yellow'}, {vin: '45665e5', year: 2011, brand: 'Mercedes', color: 'Brown'}, {vin: 'he6sb5v', year: 2015, brand: 'Ford', color: 'Black'} ]; this.cities = []; this.cities.push({label:'Select Cities', value:'Select Cities'}); this.cities.push({label:'New York', value:'New York'}); this.cities.push({label:'Rome', value:'Rome'}); this.cities.push({label:'London', value:'London'}); this.cities.push({label:'Istanbul', value:'Istanbul'}); this.cities.push({label:'Paris', value:'Paris'}); this.options = []; this.options.push({label:'Option 1', value:'Option 1'}); this.options.push({label:'Option 2', value:'Option 2'}); this.options.push({label:'Option 3', value:'Option 3'}); this.options.push({label:'Option 4', value:'Option 4'}); this.options.push({label:'Option 5', value:'Option 5'}); this.data = { labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'], datasets: [ { label: 'My First dataset', fillColor: 'rgba(220,220,220,0.2)', strokeColor: 'rgba(220,220,220,1)', pointColor: 'rgba(220,220,220,1)', pointStrokeColor: '#fff', pointHighlightFill: '#fff', pointHighlightStroke: 'rgba(220,220,220,1)', data: [65, 59, 80, 81, 56, 55, 40] }, { label: 'My Second dataset', fillColor: 'rgba(151,187,205,0.2)', strokeColor: 'rgba(151,187,205,1)', pointColor: 'rgba(151,187,205,1)', pointStrokeColor: '#fff', pointHighlightFill: '#fff', pointHighlightStroke: 'rgba(151,187,205,1)', data: [28, 48, 40, 19, 86, 27, 90] } ] } } ngOnInit() { this.carService.getCarsMedium().then(cars => this.cars = cars); this.nodeService.getFiles().then(files => this.files = files); this.carService.getCarsSmall().then(cars1 => this.cars1 = cars1); this.carService.getCarsSmall().then(cars3 => this.sourceCars = cars3); this.targetCars = []; } filterCountrySingle(event) { let query = event.query; this.countryService.getCountries().then(countries => { this.filteredCountriesSingle = this.filterCountry(query, countries); }); } filterCountry(query, countries: any[]):any[] { //in a real application, make a request to a remote url with the query and return filtered results, for demo we filter at client side let filtered : any[] = []; for(let i = 0; i < countries.length; i++) { let country = countries[i]; if(country.name.toLowerCase().indexOf(query.toLowerCase()) == 0) { filtered.push(country); } } return filtered; } } </code> </pre> </p-tabPanel> </p-tabView> </div>
apache-2.0
togglz/togglz-site
apidocs/2.6.1.Final/org/togglz/spring/boot/legacy/actuate/autoconfigure/package-summary.html
6344
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_172) on Wed Jul 25 07:27:33 CEST 2018 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>org.togglz.spring.boot.legacy.actuate.autoconfigure (Togglz 2.6.1.Final API)</title> <meta name="date" content="2018-07-25"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.togglz.spring.boot.legacy.actuate.autoconfigure (Togglz 2.6.1.Final API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../../org/togglz/spring/boot/legacy/actuate/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../../../../org/togglz/spring/listener/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/togglz/spring/boot/legacy/actuate/autoconfigure/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Package" class="title">Package&nbsp;org.togglz.spring.boot.legacy.actuate.autoconfigure</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../../org/togglz/spring/boot/legacy/actuate/autoconfigure/TogglzEndpointAutoConfiguration.html" title="class in org.togglz.spring.boot.legacy.actuate.autoconfigure">TogglzEndpointAutoConfiguration</a></td> <td class="colLast"> <div class="block"><code>Auto-configuration</code> for Togglz Endpoint (Spring Boot 1.5).</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../../org/togglz/spring/boot/legacy/actuate/autoconfigure/TogglzManagementContextConfiguration.html" title="class in org.togglz.spring.boot.legacy.actuate.autoconfigure">TogglzManagementContextConfiguration</a></td> <td class="colLast"> <div class="block"><code>Auto-configuration</code> for Togglz.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../../org/togglz/spring/boot/legacy/actuate/autoconfigure/TogglzManagementContextConfiguration.TogglzConsoleConfiguration.html" title="class in org.togglz.spring.boot.legacy.actuate.autoconfigure">TogglzManagementContextConfiguration.TogglzConsoleConfiguration</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../../org/togglz/spring/boot/legacy/actuate/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../../../../org/togglz/spring/listener/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/togglz/spring/boot/legacy/actuate/autoconfigure/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2018. All Rights Reserved.</small></p> </body> </html>
apache-2.0
GitHubAFeng/AFengAndroid
app/src/main/java/com/afeng/xf/utils/AFengUtils/StatusBarUtil.java
28369
package com.afeng.xf.utils.AFengUtils; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.os.Build; import android.support.annotation.ColorInt; import android.support.design.widget.CoordinatorLayout; import android.support.v4.widget.DrawerLayout; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.LinearLayout; import com.afeng.xf.R; /** * Created by Jaeger on 16/2/14. * <p> * Email: [email protected] * GitHub: https://github.com/laobie */ public class StatusBarUtil { public static final int DEFAULT_STATUS_BAR_ALPHA = 112; private static final int FAKE_STATUS_BAR_VIEW_ID = R.id.statusbarutil_fake_status_bar_view; private static final int FAKE_TRANSLUCENT_VIEW_ID = R.id.statusbarutil_translucent_view; private static final int TAG_KEY_HAVE_SET_OFFSET = -123; /** * 隐藏菜单。沉浸式阅读 */ public static void hideSystemUI(Activity activity) { // Set the IMMERSIVE flag. // Set the content to appear under the system bars so that the content // doesn't resize when the system bars hide and show. activity.getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY ); } public static void showSystemUI(Activity activity) { activity.getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE // | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY ); } /** * 设置状态栏颜色 * * @param activity 需要设置的 activity * @param color 状态栏颜色值 */ public static void setColor(Activity activity, @ColorInt int color) { setColor(activity, color, DEFAULT_STATUS_BAR_ALPHA); } /** * 设置状态栏颜色 * * @param activity 需要设置的activity * @param color 状态栏颜色值 * @param statusBarAlpha 状态栏透明度 */ public static void setColor(Activity activity, @ColorInt int color, int statusBarAlpha) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); activity.getWindow().setStatusBarColor(calculateStatusColor(color, statusBarAlpha)); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); View fakeStatusBarView = decorView.findViewById(FAKE_STATUS_BAR_VIEW_ID); if (fakeStatusBarView != null) { if (fakeStatusBarView.getVisibility() == View.GONE) { fakeStatusBarView.setVisibility(View.VISIBLE); } fakeStatusBarView.setBackgroundColor(calculateStatusColor(color, statusBarAlpha)); } else { decorView.addView(createStatusBarView(activity, color, statusBarAlpha)); } setRootView(activity); } } /** * 为滑动返回界面设置状态栏颜色 * * @param activity 需要设置的activity * @param color 状态栏颜色值 */ public static void setColorForSwipeBack(Activity activity, int color) { setColorForSwipeBack(activity, color, DEFAULT_STATUS_BAR_ALPHA); } /** * 为滑动返回界面设置状态栏颜色 * * @param activity 需要设置的activity * @param color 状态栏颜色值 * @param statusBarAlpha 状态栏透明度 */ public static void setColorForSwipeBack(Activity activity, @ColorInt int color, int statusBarAlpha) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { ViewGroup contentView = ((ViewGroup) activity.findViewById(android.R.id.content)); View rootView = contentView.getChildAt(0); int statusBarHeight = getStatusBarHeight(activity); if (rootView != null && rootView instanceof CoordinatorLayout) { final CoordinatorLayout coordinatorLayout = (CoordinatorLayout) rootView; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { coordinatorLayout.setFitsSystemWindows(false); contentView.setBackgroundColor(calculateStatusColor(color, statusBarAlpha)); boolean isNeedRequestLayout = contentView.getPaddingTop() < statusBarHeight; if (isNeedRequestLayout) { contentView.setPadding(0, statusBarHeight, 0, 0); coordinatorLayout.post(new Runnable() { @Override public void run() { coordinatorLayout.requestLayout(); } }); } } else { coordinatorLayout.setStatusBarBackgroundColor(calculateStatusColor(color, statusBarAlpha)); } } else { contentView.setPadding(0, statusBarHeight, 0, 0); contentView.setBackgroundColor(calculateStatusColor(color, statusBarAlpha)); } setTransparentForWindow(activity); } } /** * 设置状态栏纯色 不加半透明效果 * * @param activity 需要设置的 activity * @param color 状态栏颜色值 */ public static void setColorNoTranslucent(Activity activity, @ColorInt int color) { setColor(activity, color, 0); } /** * 设置状态栏颜色(5.0以下无半透明效果,不建议使用) * * @param activity 需要设置的 activity * @param color 状态栏颜色值 */ @Deprecated public static void setColorDiff(Activity activity, @ColorInt int color) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } transparentStatusBar(activity); ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content); // 移除半透明矩形,以免叠加 View fakeStatusBarView = contentView.findViewById(FAKE_STATUS_BAR_VIEW_ID); if (fakeStatusBarView != null) { if (fakeStatusBarView.getVisibility() == View.GONE) { fakeStatusBarView.setVisibility(View.VISIBLE); } fakeStatusBarView.setBackgroundColor(color); } else { contentView.addView(createStatusBarView(activity, color)); } setRootView(activity); } /** * 使状态栏半透明 * <p> * 适用于图片作为背景的界面,此时需要图片填充到状态栏 * * @param activity 需要设置的activity */ public static void setTranslucent(Activity activity) { setTranslucent(activity, DEFAULT_STATUS_BAR_ALPHA); } /** * 使状态栏半透明 * <p> * 适用于图片作为背景的界面,此时需要图片填充到状态栏 * * @param activity 需要设置的activity * @param statusBarAlpha 状态栏透明度 */ public static void setTranslucent(Activity activity, int statusBarAlpha) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } setTransparent(activity); addTranslucentView(activity, statusBarAlpha); } /** * 针对根布局是 CoordinatorLayout, 使状态栏半透明 * <p> * 适用于图片作为背景的界面,此时需要图片填充到状态栏 * * @param activity 需要设置的activity * @param statusBarAlpha 状态栏透明度 */ public static void setTranslucentForCoordinatorLayout(Activity activity, int statusBarAlpha) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } transparentStatusBar(activity); addTranslucentView(activity, statusBarAlpha); } /** * 设置状态栏全透明 * * @param activity 需要设置的activity */ public static void setTransparent(Activity activity) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } transparentStatusBar(activity); setRootView(activity); } /** * 使状态栏透明(5.0以上半透明效果,不建议使用) * <p> * 适用于图片作为背景的界面,此时需要图片填充到状态栏 * * @param activity 需要设置的activity */ @Deprecated public static void setTranslucentDiff(Activity activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // 设置状态栏透明 activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); setRootView(activity); } } /** * 为DrawerLayout 布局设置状态栏变色 * * @param activity 需要设置的activity * @param drawerLayout DrawerLayout * @param color 状态栏颜色值 */ public static void setColorForDrawerLayout(Activity activity, DrawerLayout drawerLayout, @ColorInt int color) { setColorForDrawerLayout(activity, drawerLayout, color, DEFAULT_STATUS_BAR_ALPHA); } /** * 为DrawerLayout 布局设置状态栏颜色,纯色 * * @param activity 需要设置的activity * @param drawerLayout DrawerLayout * @param color 状态栏颜色值 */ public static void setColorNoTranslucentForDrawerLayout(Activity activity, DrawerLayout drawerLayout, @ColorInt int color) { setColorForDrawerLayout(activity, drawerLayout, color, 0); } /** * 为DrawerLayout 布局设置状态栏变色 * * @param activity 需要设置的activity * @param drawerLayout DrawerLayout * @param color 状态栏颜色值 * @param statusBarAlpha 状态栏透明度 */ public static void setColorForDrawerLayout(Activity activity, DrawerLayout drawerLayout, @ColorInt int color, int statusBarAlpha) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); activity.getWindow().setStatusBarColor(Color.TRANSPARENT); } else { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } // 生成一个状态栏大小的矩形 // 添加 statusBarView 到布局中 ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0); View fakeStatusBarView = contentLayout.findViewById(FAKE_STATUS_BAR_VIEW_ID); if (fakeStatusBarView != null) { if (fakeStatusBarView.getVisibility() == View.GONE) { fakeStatusBarView.setVisibility(View.VISIBLE); } fakeStatusBarView.setBackgroundColor(color); } else { contentLayout.addView(createStatusBarView(activity, color), 0); } // 内容布局不是 LinearLayout 时,设置padding top if (!(contentLayout instanceof LinearLayout) && contentLayout.getChildAt(1) != null) { contentLayout.getChildAt(1) .setPadding(contentLayout.getPaddingLeft(), getStatusBarHeight(activity) + contentLayout.getPaddingTop(), contentLayout.getPaddingRight(), contentLayout.getPaddingBottom()); } // 设置属性 setDrawerLayoutProperty(drawerLayout, contentLayout); addTranslucentView(activity, statusBarAlpha); } /** * 设置 DrawerLayout 属性 * * @param drawerLayout DrawerLayout * @param drawerLayoutContentLayout DrawerLayout 的内容布局 */ private static void setDrawerLayoutProperty(DrawerLayout drawerLayout, ViewGroup drawerLayoutContentLayout) { ViewGroup drawer = (ViewGroup) drawerLayout.getChildAt(1); drawerLayout.setFitsSystemWindows(false); drawerLayoutContentLayout.setFitsSystemWindows(false); drawerLayoutContentLayout.setClipToPadding(true); drawer.setFitsSystemWindows(false); } /** * 为DrawerLayout 布局设置状态栏变色(5.0以下无半透明效果,不建议使用) * * @param activity 需要设置的activity * @param drawerLayout DrawerLayout * @param color 状态栏颜色值 */ @Deprecated public static void setColorForDrawerLayoutDiff(Activity activity, DrawerLayout drawerLayout, @ColorInt int color) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // 生成一个状态栏大小的矩形 ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0); View fakeStatusBarView = contentLayout.findViewById(FAKE_STATUS_BAR_VIEW_ID); if (fakeStatusBarView != null) { if (fakeStatusBarView.getVisibility() == View.GONE) { fakeStatusBarView.setVisibility(View.VISIBLE); } fakeStatusBarView.setBackgroundColor(calculateStatusColor(color, DEFAULT_STATUS_BAR_ALPHA)); } else { // 添加 statusBarView 到布局中 contentLayout.addView(createStatusBarView(activity, color), 0); } // 内容布局不是 LinearLayout 时,设置padding top if (!(contentLayout instanceof LinearLayout) && contentLayout.getChildAt(1) != null) { contentLayout.getChildAt(1).setPadding(0, getStatusBarHeight(activity), 0, 0); } // 设置属性 setDrawerLayoutProperty(drawerLayout, contentLayout); } } /** * 为 DrawerLayout 布局设置状态栏透明 * * @param activity 需要设置的activity * @param drawerLayout DrawerLayout */ public static void setTranslucentForDrawerLayout(Activity activity, DrawerLayout drawerLayout) { setTranslucentForDrawerLayout(activity, drawerLayout, DEFAULT_STATUS_BAR_ALPHA); } /** * 为 DrawerLayout 布局设置状态栏透明 * * @param activity 需要设置的activity * @param drawerLayout DrawerLayout */ public static void setTranslucentForDrawerLayout(Activity activity, DrawerLayout drawerLayout, int statusBarAlpha) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } setTransparentForDrawerLayout(activity, drawerLayout); addTranslucentView(activity, statusBarAlpha); } /** * 为 DrawerLayout 布局设置状态栏透明 * * @param activity 需要设置的activity * @param drawerLayout DrawerLayout */ public static void setTransparentForDrawerLayout(Activity activity, DrawerLayout drawerLayout) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); activity.getWindow().setStatusBarColor(Color.TRANSPARENT); } else { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0); // 内容布局不是 LinearLayout 时,设置padding top if (!(contentLayout instanceof LinearLayout) && contentLayout.getChildAt(1) != null) { contentLayout.getChildAt(1).setPadding(0, getStatusBarHeight(activity), 0, 0); } // 设置属性 setDrawerLayoutProperty(drawerLayout, contentLayout); } /** * 为 DrawerLayout 布局设置状态栏透明(5.0以上半透明效果,不建议使用) * * @param activity 需要设置的activity * @param drawerLayout DrawerLayout */ @Deprecated public static void setTranslucentForDrawerLayoutDiff(Activity activity, DrawerLayout drawerLayout) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // 设置状态栏透明 activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // 设置内容布局属性 ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0); contentLayout.setFitsSystemWindows(true); contentLayout.setClipToPadding(true); // 设置抽屉布局属性 ViewGroup vg = (ViewGroup) drawerLayout.getChildAt(1); vg.setFitsSystemWindows(false); // 设置 DrawerLayout 属性 drawerLayout.setFitsSystemWindows(false); } } /** * 为头部是 ImageView 的界面设置状态栏全透明 * * @param activity 需要设置的activity * @param needOffsetView 需要向下偏移的 View */ public static void setTransparentForImageView(Activity activity, View needOffsetView) { setTranslucentForImageView(activity, 0, needOffsetView); } /** * 为头部是 ImageView 的界面设置状态栏透明(使用默认透明度) * * @param activity 需要设置的activity * @param needOffsetView 需要向下偏移的 View */ public static void setTranslucentForImageView(Activity activity, View needOffsetView) { setTranslucentForImageView(activity, DEFAULT_STATUS_BAR_ALPHA, needOffsetView); } /** * 为头部是 ImageView 的界面设置状态栏透明 * * @param activity 需要设置的activity * @param statusBarAlpha 状态栏透明度 * @param needOffsetView 需要向下偏移的 View */ public static void setTranslucentForImageView(Activity activity, int statusBarAlpha, View needOffsetView) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } setTransparentForWindow(activity); addTranslucentView(activity, statusBarAlpha); if (needOffsetView != null) { Object haveSetOffset = needOffsetView.getTag(TAG_KEY_HAVE_SET_OFFSET); if (haveSetOffset != null && (Boolean) haveSetOffset) { return; } ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) needOffsetView.getLayoutParams(); layoutParams.setMargins(layoutParams.leftMargin, layoutParams.topMargin + getStatusBarHeight(activity), layoutParams.rightMargin, layoutParams.bottomMargin); needOffsetView.setTag(TAG_KEY_HAVE_SET_OFFSET, true); } } /** * 为 fragment 头部是 ImageView 的设置状态栏透明 * * @param activity fragment 对应的 activity * @param needOffsetView 需要向下偏移的 View */ public static void setTranslucentForImageViewInFragment(Activity activity, View needOffsetView) { setTranslucentForImageViewInFragment(activity, DEFAULT_STATUS_BAR_ALPHA, needOffsetView); } /** * 为 fragment 头部是 ImageView 的设置状态栏透明 * * @param activity fragment 对应的 activity * @param needOffsetView 需要向下偏移的 View */ public static void setTransparentForImageViewInFragment(Activity activity, View needOffsetView) { setTranslucentForImageViewInFragment(activity, 0, needOffsetView); } /** * 为 fragment 头部是 ImageView 的设置状态栏透明 * * @param activity fragment 对应的 activity * @param statusBarAlpha 状态栏透明度 * @param needOffsetView 需要向下偏移的 View */ public static void setTranslucentForImageViewInFragment(Activity activity, int statusBarAlpha, View needOffsetView) { setTranslucentForImageView(activity, statusBarAlpha, needOffsetView); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { clearPreviousSetting(activity); } } /** * 隐藏伪状态栏 View * * @param activity 调用的 Activity */ public static void hideFakeStatusBarView(Activity activity) { ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); View fakeStatusBarView = decorView.findViewById(FAKE_STATUS_BAR_VIEW_ID); if (fakeStatusBarView != null) { fakeStatusBarView.setVisibility(View.GONE); } View fakeTranslucentView = decorView.findViewById(FAKE_TRANSLUCENT_VIEW_ID); if (fakeTranslucentView != null) { fakeTranslucentView.setVisibility(View.GONE); } } /////////////////////////////////////////////////////////////////////////////////// @TargetApi(Build.VERSION_CODES.KITKAT) private static void clearPreviousSetting(Activity activity) { ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); View fakeStatusBarView = decorView.findViewById(FAKE_STATUS_BAR_VIEW_ID); if (fakeStatusBarView != null) { decorView.removeView(fakeStatusBarView); ViewGroup rootView = (ViewGroup) ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0); rootView.setPadding(0, 0, 0, 0); } } /** * 添加半透明矩形条 * * @param activity 需要设置的 activity * @param statusBarAlpha 透明值 */ private static void addTranslucentView(Activity activity, int statusBarAlpha) { ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content); View fakeTranslucentView = contentView.findViewById(FAKE_TRANSLUCENT_VIEW_ID); if (fakeTranslucentView != null) { if (fakeTranslucentView.getVisibility() == View.GONE) { fakeTranslucentView.setVisibility(View.VISIBLE); } fakeTranslucentView.setBackgroundColor(Color.argb(statusBarAlpha, 0, 0, 0)); } else { contentView.addView(createTranslucentStatusBarView(activity, statusBarAlpha)); } } /** * 生成一个和状态栏大小相同的彩色矩形条 * * @param activity 需要设置的 activity * @param color 状态栏颜色值 * @return 状态栏矩形条 */ private static View createStatusBarView(Activity activity, @ColorInt int color) { return createStatusBarView(activity, color, 0); } /** * 生成一个和状态栏大小相同的半透明矩形条 * * @param activity 需要设置的activity * @param color 状态栏颜色值 * @param alpha 透明值 * @return 状态栏矩形条 */ private static View createStatusBarView(Activity activity, @ColorInt int color, int alpha) { // 绘制一个和状态栏一样高的矩形 View statusBarView = new View(activity); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(activity)); statusBarView.setLayoutParams(params); statusBarView.setBackgroundColor(calculateStatusColor(color, alpha)); statusBarView.setId(FAKE_STATUS_BAR_VIEW_ID); return statusBarView; } /** * 设置根布局参数 */ private static void setRootView(Activity activity) { ViewGroup parent = (ViewGroup) activity.findViewById(android.R.id.content); for (int i = 0, count = parent.getChildCount(); i < count; i++) { View childView = parent.getChildAt(i); if (childView instanceof ViewGroup) { childView.setFitsSystemWindows(true); ((ViewGroup) childView).setClipToPadding(true); } } } /** * 设置透明 */ private static void setTransparentForWindow(Activity activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { activity.getWindow().setStatusBarColor(Color.TRANSPARENT); activity.getWindow() .getDecorView() .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { activity.getWindow() .setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } } /** * 使状态栏透明 */ @TargetApi(Build.VERSION_CODES.KITKAT) private static void transparentStatusBar(Activity activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); activity.getWindow().setStatusBarColor(Color.TRANSPARENT); } else { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } } /** * 创建半透明矩形 View * * @param alpha 透明值 * @return 半透明 View */ private static View createTranslucentStatusBarView(Activity activity, int alpha) { // 绘制一个和状态栏一样高的矩形 View statusBarView = new View(activity); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(activity)); statusBarView.setLayoutParams(params); statusBarView.setBackgroundColor(Color.argb(alpha, 0, 0, 0)); statusBarView.setId(FAKE_TRANSLUCENT_VIEW_ID); return statusBarView; } /** * 获取状态栏高度 * * @param context context * @return 状态栏高度 */ private static int getStatusBarHeight(Context context) { // 获得状态栏高度 int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); return context.getResources().getDimensionPixelSize(resourceId); } /** * 计算状态栏颜色 * * @param color color值 * @param alpha alpha值 * @return 最终的状态栏颜色 */ private static int calculateStatusColor(@ColorInt int color, int alpha) { if (alpha == 0) { return color; } float a = 1 - alpha / 255f; int red = color >> 16 & 0xff; int green = color >> 8 & 0xff; int blue = color & 0xff; red = (int) (red * a + 0.5); green = (int) (green * a + 0.5); blue = (int) (blue * a + 0.5); return 0xff << 24 | red << 16 | green << 8 | blue; } }
apache-2.0
kopaka7/Visual-Summary
appengine-java-sdk-1.9.27/docs/javadoc/com/google/appengine/api/xmpp/PresenceBuilder.html
14825
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0-google-v7) on Wed Sep 02 13:30:33 PDT 2015 --> <title>PresenceBuilder (Google App Engine Java API)</title> <meta name="date" content="2015-09-02"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="PresenceBuilder (Google App Engine Java API)"; } } catch(err) { } //--> var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/google/appengine/api/xmpp/Presence.html" title="class in com.google.appengine.api.xmpp"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../com/google/appengine/api/xmpp/PresenceShow.html" title="enum in com.google.appengine.api.xmpp"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/google/appengine/api/xmpp/PresenceBuilder.html" target="_top">Frames</a></li> <li><a href="PresenceBuilder.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.google.appengine.api.xmpp</div> <h2 title="Class PresenceBuilder" class="title">Class PresenceBuilder</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>com.google.appengine.api.xmpp.PresenceBuilder</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="typeNameLabel">PresenceBuilder</span> extends java.lang.Object</pre> <div class="block">Builder used to generate <a href="../../../../../com/google/appengine/api/xmpp/Presence.html" title="class in com.google.appengine.api.xmpp"><code>Presence</code></a> instances to represent incoming XMPP presence stanzas.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/xmpp/PresenceBuilder.html#PresenceBuilder--">PresenceBuilder</a></span>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code><a href="../../../../../com/google/appengine/api/xmpp/Presence.html" title="class in com.google.appengine.api.xmpp">Presence</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/xmpp/PresenceBuilder.html#build--">build</a></span>()</code>&nbsp;</td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/google/appengine/api/xmpp/PresenceBuilder.html" title="class in com.google.appengine.api.xmpp">PresenceBuilder</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/xmpp/PresenceBuilder.html#withFromJid-com.google.appengine.api.xmpp.JID-">withFromJid</a></span>(<a href="../../../../../com/google/appengine/api/xmpp/JID.html" title="class in com.google.appengine.api.xmpp">JID</a>&nbsp;fromJid)</code>&nbsp;</td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code><a href="../../../../../com/google/appengine/api/xmpp/PresenceBuilder.html" title="class in com.google.appengine.api.xmpp">PresenceBuilder</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/xmpp/PresenceBuilder.html#withPresenceShow-com.google.appengine.api.xmpp.PresenceShow-">withPresenceShow</a></span>(<a href="../../../../../com/google/appengine/api/xmpp/PresenceShow.html" title="enum in com.google.appengine.api.xmpp">PresenceShow</a>&nbsp;presenceShow)</code>&nbsp;</td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/google/appengine/api/xmpp/PresenceBuilder.html" title="class in com.google.appengine.api.xmpp">PresenceBuilder</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/xmpp/PresenceBuilder.html#withPresenceType-com.google.appengine.api.xmpp.PresenceType-">withPresenceType</a></span>(<a href="../../../../../com/google/appengine/api/xmpp/PresenceType.html" title="enum in com.google.appengine.api.xmpp">PresenceType</a>&nbsp;presenceType)</code>&nbsp;</td> </tr> <tr id="i4" class="altColor"> <td class="colFirst"><code><a href="../../../../../com/google/appengine/api/xmpp/PresenceBuilder.html" title="class in com.google.appengine.api.xmpp">PresenceBuilder</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/xmpp/PresenceBuilder.html#withStatus-java.lang.String-">withStatus</a></span>(java.lang.String&nbsp;status)</code>&nbsp;</td> </tr> <tr id="i5" class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/google/appengine/api/xmpp/PresenceBuilder.html" title="class in com.google.appengine.api.xmpp">PresenceBuilder</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/xmpp/PresenceBuilder.html#withToJid-com.google.appengine.api.xmpp.JID-">withToJid</a></span>(<a href="../../../../../com/google/appengine/api/xmpp/JID.html" title="class in com.google.appengine.api.xmpp">JID</a>&nbsp;toJid)</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="PresenceBuilder--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>PresenceBuilder</h4> <pre>public&nbsp;PresenceBuilder()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="withPresenceType-com.google.appengine.api.xmpp.PresenceType-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>withPresenceType</h4> <pre>public&nbsp;<a href="../../../../../com/google/appengine/api/xmpp/PresenceBuilder.html" title="class in com.google.appengine.api.xmpp">PresenceBuilder</a>&nbsp;withPresenceType(<a href="../../../../../com/google/appengine/api/xmpp/PresenceType.html" title="enum in com.google.appengine.api.xmpp">PresenceType</a>&nbsp;presenceType)</pre> </li> </ul> <a name="withPresenceShow-com.google.appengine.api.xmpp.PresenceShow-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>withPresenceShow</h4> <pre>public&nbsp;<a href="../../../../../com/google/appengine/api/xmpp/PresenceBuilder.html" title="class in com.google.appengine.api.xmpp">PresenceBuilder</a>&nbsp;withPresenceShow(<a href="../../../../../com/google/appengine/api/xmpp/PresenceShow.html" title="enum in com.google.appengine.api.xmpp">PresenceShow</a>&nbsp;presenceShow)</pre> </li> </ul> <a name="withStatus-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>withStatus</h4> <pre>public&nbsp;<a href="../../../../../com/google/appengine/api/xmpp/PresenceBuilder.html" title="class in com.google.appengine.api.xmpp">PresenceBuilder</a>&nbsp;withStatus(java.lang.String&nbsp;status)</pre> </li> </ul> <a name="withFromJid-com.google.appengine.api.xmpp.JID-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>withFromJid</h4> <pre>public&nbsp;<a href="../../../../../com/google/appengine/api/xmpp/PresenceBuilder.html" title="class in com.google.appengine.api.xmpp">PresenceBuilder</a>&nbsp;withFromJid(<a href="../../../../../com/google/appengine/api/xmpp/JID.html" title="class in com.google.appengine.api.xmpp">JID</a>&nbsp;fromJid)</pre> </li> </ul> <a name="withToJid-com.google.appengine.api.xmpp.JID-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>withToJid</h4> <pre>public&nbsp;<a href="../../../../../com/google/appengine/api/xmpp/PresenceBuilder.html" title="class in com.google.appengine.api.xmpp">PresenceBuilder</a>&nbsp;withToJid(<a href="../../../../../com/google/appengine/api/xmpp/JID.html" title="class in com.google.appengine.api.xmpp">JID</a>&nbsp;toJid)</pre> </li> </ul> <a name="build--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>build</h4> <pre>public&nbsp;<a href="../../../../../com/google/appengine/api/xmpp/Presence.html" title="class in com.google.appengine.api.xmpp">Presence</a>&nbsp;build()</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/google/appengine/api/xmpp/Presence.html" title="class in com.google.appengine.api.xmpp"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../com/google/appengine/api/xmpp/PresenceShow.html" title="enum in com.google.appengine.api.xmpp"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/google/appengine/api/xmpp/PresenceBuilder.html" target="_top">Frames</a></li> <li><a href="PresenceBuilder.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
apache-2.0
torrances/swtk-commons
commons-dict-wordnet-indexbyid/src/main/java/org/swtk/commons/dict/wordnet/indexbyid/instance/p0/p1/WordnetNounIndexIdInstance0161.java
16360
package org.swtk.commons.dict.wordnet.indexbyid.instance.p0.p1; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.TreeMap; import org.swtk.common.dict.dto.wordnet.IndexNoun; import com.trimc.blogger.commons.utils.GsonUtils; public final class WordnetNounIndexIdInstance0161 { private static Map<String, Collection<IndexNoun>> map = new TreeMap<String, Collection<IndexNoun>>(); static { add("01610070", "{\"term\":\"buteo jamaicensis\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01610070\"]}"); add("01610070", "{\"term\":\"red-tailed hawk\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01610070\"]}"); add("01610070", "{\"term\":\"redtail\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"01564093\", \"01610070\"]}"); add("01610241", "{\"term\":\"buteo lagopus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01610241\"]}"); add("01610241", "{\"term\":\"rough-legged hawk\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01610241\"]}"); add("01610241", "{\"term\":\"roughleg\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01610241\"]}"); add("01610453", "{\"term\":\"buteo lineatus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01610453\"]}"); add("01610453", "{\"term\":\"red-shouldered hawk\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01610453\"]}"); add("01610603", "{\"term\":\"buteo buteo\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01610603\"]}"); add("01610603", "{\"term\":\"buzzard\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"01610603\", \"01621951\"]}"); add("01610727", "{\"term\":\"genus pernis\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01610727\"]}"); add("01610727", "{\"term\":\"pernis\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01610727\"]}"); add("01610906", "{\"term\":\"honey buzzard\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01610906\"]}"); add("01610906", "{\"term\":\"pernis apivorus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01610906\"]}"); add("01611073", "{\"term\":\"kite\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"01611073\", \"03626682\", \"13403479\", \"13403644\"]}"); add("01611326", "{\"term\":\"genus-milvus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01611326\"]}"); add("01611326", "{\"term\":\"milvus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01611326\"]}"); add("01611455", "{\"term\":\"black kite\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01611455\"]}"); add("01611455", "{\"term\":\"milvus migrans\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01611455\"]}"); add("01611575", "{\"term\":\"elanoides\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01611575\"]}"); add("01611575", "{\"term\":\"genus elanoides\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01611575\"]}"); add("01611703", "{\"term\":\"elanoides forficatus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01611703\"]}"); add("01611703", "{\"term\":\"swallow-tailed hawk\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01611703\"]}"); add("01611703", "{\"term\":\"swallow-tailed kite\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01611703\"]}"); add("01611877", "{\"term\":\"elanus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01611877\"]}"); add("01611877", "{\"term\":\"genus elanus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01611877\"]}"); add("01612032", "{\"term\":\"elanus leucurus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01612032\"]}"); add("01612032", "{\"term\":\"white-tailed kite\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01612032\"]}"); add("01612190", "{\"term\":\"circus\", \"synsetCount\":6, \"upperType\":\"NOUN\", \"ids\":[\"01612190\", \"03038845\", \"03039074\", \"00553716\", \"00520795\", \"08206141\"]}"); add("01612190", "{\"term\":\"genus circus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01612190\"]}"); add("01612392", "{\"term\":\"harrier\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"01612392\", \"02092781\", \"10179605\"]}"); add("01612597", "{\"term\":\"circus aeruginosus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01612597\"]}"); add("01612597", "{\"term\":\"marsh harrier\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01612597\"]}"); add("01612741", "{\"term\":\"circus pygargus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01612741\"]}"); add("01612741", "{\"term\":\"montagu\u0027s harrier\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01612741\"]}"); add("01612867", "{\"term\":\"circus cyaneus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01612867\"]}"); add("01612867", "{\"term\":\"hen harrier\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01612867\"]}"); add("01612867", "{\"term\":\"marsh hawk\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01612867\"]}"); add("01612867", "{\"term\":\"northern harrier\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01612867\"]}"); add("01613067", "{\"term\":\"circaetus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01613067\"]}"); add("01613067", "{\"term\":\"genus circaetus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01613067\"]}"); add("01613193", "{\"term\":\"harrier eagle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01613193\"]}"); add("01613193", "{\"term\":\"short-toed eagle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01613193\"]}"); add("01613399", "{\"term\":\"falconidae\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01613399\"]}"); add("01613399", "{\"term\":\"family falconidae\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01613399\"]}"); add("01613596", "{\"term\":\"falcon\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01613596\"]}"); add("01613893", "{\"term\":\"falco\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01613893\"]}"); add("01613893", "{\"term\":\"genus falco\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01613893\"]}"); add("01614113", "{\"term\":\"falco peregrinus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01614113\"]}"); add("01614113", "{\"term\":\"peregrine\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01614113\"]}"); add("01614113", "{\"term\":\"peregrine falcon\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01614113\"]}"); add("01614315", "{\"term\":\"falcon-gentil\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01614315\"]}"); add("01614315", "{\"term\":\"falcon-gentle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01614315\"]}"); add("01614441", "{\"term\":\"falco rusticolus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01614441\"]}"); add("01614441", "{\"term\":\"gerfalcon\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01614441\"]}"); add("01614441", "{\"term\":\"gyrfalcon\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01614441\"]}"); add("01614610", "{\"term\":\"falco tinnunculus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01614610\"]}"); add("01614610", "{\"term\":\"kestrel\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"01614610\", \"01614763\"]}"); add("01614763", "{\"term\":\"american kestrel\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01614763\"]}"); add("01614763", "{\"term\":\"falco sparverius\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01614763\"]}"); add("01614763", "{\"term\":\"kestrel\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"01614610\", \"01614763\"]}"); add("01614763", "{\"term\":\"sparrow hawk\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"01609313\", \"01614763\"]}"); add("01614916", "{\"term\":\"falco columbarius\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01614916\"]}"); add("01614916", "{\"term\":\"merlin\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"01614916\", \"11196378\"]}"); add("01614916", "{\"term\":\"pigeon hawk\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01614916\"]}"); add("01615117", "{\"term\":\"falco subbuteo\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01615117\"]}"); add("01615117", "{\"term\":\"hobby\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"01615117\", \"03528796\", \"00433629\"]}"); add("01615269", "{\"term\":\"caracara\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01615269\"]}"); add("01615444", "{\"term\":\"genus polyborus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01615444\"]}"); add("01615444", "{\"term\":\"polyborus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01615444\"]}"); add("01615596", "{\"term\":\"audubon\u0027s caracara\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01615596\"]}"); add("01615596", "{\"term\":\"polyborus cheriway audubonii\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01615596\"]}"); add("01615818", "{\"term\":\"carancha\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01615818\"]}"); add("01615818", "{\"term\":\"polyborus plancus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01615818\"]}"); add("01615935", "{\"term\":\"bird of jove\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01615935\"]}"); add("01615935", "{\"term\":\"eagle\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"06894613\", \"13413645\", \"13617211\", \"01615935\"]}"); add("01616256", "{\"term\":\"young bird\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01616256\"]}"); add("01616448", "{\"term\":\"eaglet\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01616448\"]}"); add("01616550", "{\"term\":\"genus harpia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01616550\"]}"); add("01616550", "{\"term\":\"harpia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01616550\"]}"); add("01616679", "{\"term\":\"harpia harpyja\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01616679\"]}"); add("01616679", "{\"term\":\"harpy\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"01616679\", \"02143143\", \"09519230\", \"10778005\"]}"); add("01616679", "{\"term\":\"harpy eagle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01616679\"]}"); add("01616836", "{\"term\":\"aquila\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"01616836\", \"08822171\", \"09225020\"]}"); add("01616836", "{\"term\":\"genus aquila\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01616836\"]}"); add("01616984", "{\"term\":\"aquila chrysaetos\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01616984\"]}"); add("01616984", "{\"term\":\"golden eagle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01616984\"]}"); add("01617197", "{\"term\":\"aquila rapax\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01617197\"]}"); add("01617197", "{\"term\":\"tawny eagle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01617197\"]}"); add("01617331", "{\"term\":\"ringtail\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"01617331\", \"02494666\", \"02510844\", \"02511373\"]}"); add("01617410", "{\"term\":\"genus haliaeetus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01617410\"]}"); add("01617410", "{\"term\":\"haliaeetus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01617410\"]}"); add("01617566", "{\"term\":\"american eagle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01617566\"]}"); add("01617566", "{\"term\":\"bald eagle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01617566\"]}"); add("01617566", "{\"term\":\"haliaeetus leucocephalus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01617566\"]}"); add("01617762", "{\"term\":\"sea eagle\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"01617762\", \"01618727\"]}"); add("01617944", "{\"term\":\"haliaeetus pelagicus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01617944\"]}"); add("01617944", "{\"term\":\"kamchatkan sea eagle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01617944\"]}"); add("01617944", "{\"term\":\"stellar\u0027s sea eagle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01617944\"]}"); add("01618099", "{\"term\":\"ern\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01618099\"]}"); add("01618099", "{\"term\":\"erne\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01618099\"]}"); add("01618099", "{\"term\":\"european sea eagle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01618099\"]}"); add("01618099", "{\"term\":\"gray sea eagle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01618099\"]}"); add("01618099", "{\"term\":\"grey sea eagle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01618099\"]}"); add("01618099", "{\"term\":\"haliatus albicilla\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01618099\"]}"); add("01618099", "{\"term\":\"white-tailed sea eagle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01618099\"]}"); add("01618344", "{\"term\":\"fishing eagle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01618344\"]}"); add("01618344", "{\"term\":\"haliaeetus leucorhyphus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01618344\"]}"); add("01618466", "{\"term\":\"family pandionidae\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01618466\"]}"); add("01618466", "{\"term\":\"pandionidae\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01618466\"]}"); add("01618590", "{\"term\":\"genus pandion\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01618590\"]}"); add("01618590", "{\"term\":\"pandion\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01618590\"]}"); add("01618727", "{\"term\":\"fish eagle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01618727\"]}"); add("01618727", "{\"term\":\"fish hawk\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01618727\"]}"); add("01618727", "{\"term\":\"osprey\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01618727\"]}"); add("01618727", "{\"term\":\"pandion haliaetus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01618727\"]}"); add("01618727", "{\"term\":\"sea eagle\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"01617762\", \"01618727\"]}"); add("01618959", "{\"term\":\"vulture\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"10312833\", \"01618959\"]}"); add("01619192", "{\"term\":\"aegypiidae\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01619192\"]}"); add("01619192", "{\"term\":\"family aegypiidae\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01619192\"]}"); add("01619405", "{\"term\":\"old world vulture\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01619405\"]}"); add("01619611", "{\"term\":\"genus gyps\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01619611\"]}"); add("01619611", "{\"term\":\"gyps\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01619611\"]}"); add("01619736", "{\"term\":\"griffon\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"01619736\", \"02105833\", \"02115149\", \"09519093\"]}"); add("01619736", "{\"term\":\"griffon vulture\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01619736\"]}"); add("01619736", "{\"term\":\"gyps fulvus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01619736\"]}"); add("01619930", "{\"term\":\"genus gypaetus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01619930\"]}"); add("01619930", "{\"term\":\"gypaetus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01619930\"]}"); } private static void add(final String ID, final String JSON) { IndexNoun indexNoun = GsonUtils.toObject(JSON, IndexNoun.class); Collection<IndexNoun> list = (map.containsKey(ID)) ? map.get(ID) : new ArrayList<IndexNoun>(); list.add(indexNoun); map.put(ID, list); } public static Collection<IndexNoun> get(final String TERM) { return map.get(TERM); } public static boolean has(final String TERM) { return map.containsKey(TERM); } public static Collection<String> ids() { return map.keySet(); } }
apache-2.0
anandaverma/NinjaParser
src/com/fiberlink/ninjaparser/output/StdOut.java
123
package com.fiberlink.ninjaparser.output; public class StdOut implements Output{ public void print() { } }
apache-2.0
adejanovski/cassandra-jdbc-wrapper
src/main/java/org/apache/cassandra2/cql/jdbc/CassandraDriver.java
844
/* * Copyright (C) 2012-2015 DataStax Inc. * * 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 org.apache.cassandra2.cql.jdbc; import java.sql.Driver; /** * The Class CassandraDriver. */ public class CassandraDriver extends com.github.adejanovski.cassandra.jdbc.CassandraDriver implements Driver {}
apache-2.0
dboissier/canardpc-base
src/templates/admin/users.html
2716
{% extends "admin/admin_layout.html" %} {% block page_title %}Administration : gestion des utilisateurs{% endblock %} {% block admin_content %} <div id="userForm"> <div class="row"> <table class="table table-striped"> <thead> <tr> <td>Login</td> <td>role</td> <td></td> </tr> </thead> <tbody data-bind="foreach: users"> <tr> <td data-bind="text: username"></td> <td data-bind="text: role"></td> <td> <a href="#" class="btn" data-bind="click: $root.editUser"> <li class="icon-edit"></li> Editer </a> </td> </tr> </tbody> </table> </div> <hr/> <div class="row"> <h3>Editer un utilisateur</h3> <div class="form-horizontal" id="userFormBody"> <input type="hidden" data-bind="value: oid"> <div class="control-group"> <label for="username" class="control-label"> Login </label> <div class="controls"> <input id="username" class="span6" type="text" data-bind="value: username" required> </div> </div> <div class="control-group"> <label for="password" class="control-label"> Mot de passe </label> <div class="controls"> <input id="password" class="span6" type="password" data-bind="value: password" required> </div> </div> <div class="control-group"> <label for="role" class="control-label"> Rôle </label> <div class="controls"> <select data-bind="options: ['admin', 'writer'], value: role"></select> </div> </div> </div> <span id="userFormFeedback"></span> <div class="form-actions"> <a href="#" class="btn btn-success" data-bind="click: save">Enregistrer</a> <a href="#" class="btn" data-bind="click: clearForm">Effacer</a> <a href="#" class="btn btn-danger pull-right" data-bind="css: { disabled: hasNoId }">Supprimer</a> </div> </div> </div> {% endblock %} {% block additionnal_js_libs %} {{ super() }} <script> $('#adminSubmenu').find('> li:contains("Utilisateurs")').addClass('active'); </script> <script src="{{ url_for('static', filename='js/admin/ko-user.js') }}"></script> {% endblock %}
apache-2.0
dcarbone/php-fhir-generated
src/DCarbone/PHPFHIRGenerated/DSTU1/PHPFHIRTests/FHIRElement/FHIRBackboneElement/FHIRFamilyHistory/FHIRFamilyHistoryConditionTest.php
3336
<?php namespace DCarbone\PHPFHIRGenerated\DSTU1\PHPFHIRTests\FHIRElement\FHIRBackboneElement\FHIRFamilyHistory; /*! * This class was generated with the PHPFHIR library (https://github.com/dcarbone/php-fhir) using * class definitions from HL7 FHIR (https://www.hl7.org/fhir/) * * Class creation date: December 26th, 2019 15:43+0000 * * PHPFHIR Copyright: * * Copyright 2016-2019 Daniel Carbone ([email protected]) * * 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. * * * FHIR Copyright Notice: * * Copyright (c) 2011-2013, HL7, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of HL7 nor the names of its contributors may be used to * endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * Generated on Tue, Sep 30, 2014 18:08+1000 for FHIR v0.0.82 */ use PHPUnit\Framework\TestCase; use DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRBackboneElement\FHIRFamilyHistory\FHIRFamilyHistoryCondition; /** * Class FHIRFamilyHistoryConditionTest * @package \DCarbone\PHPFHIRGenerated\DSTU1\PHPFHIRTests\FHIRElement\FHIRBackboneElement\FHIRFamilyHistory */ class FHIRFamilyHistoryConditionTest extends TestCase { public function testCanConstructTypeNoArgs() { $type = new FHIRFamilyHistoryCondition(); $this->assertInstanceOf('\DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRBackboneElement\FHIRFamilyHistory\FHIRFamilyHistoryCondition', $type); } }
apache-2.0
genialis/resolwe-bio
resolwe_bio/processes/support_processors/seqtk_reverse_complement.py
8764
"""Reverse complement reads with Seqtk.""" import os from plumbum import TEE from resolwe.process import ( Cmd, DataField, FileField, FileHtmlField, ListField, Process, StringField, ) class ReverseComplementSingle(Process): """Reverse complement single-end FASTQ reads file using Seqtk.""" slug = "seqtk-rev-complement-single" process_type = "data:reads:fastq:single:seqtk" name = "Reverse complement FASTQ (single-end)" requirements = { "expression-engine": "jinja", "executor": { "docker": {"image": "public.ecr.aws/s4q6j6e8/resolwebio/common:3.0.0"}, }, "resources": { "cores": 1, "memory": 16384, }, } entity = { "type": "sample", } data_name = '{{ reads|sample_name|default("?") }}' version = "1.2.0" class Input: """Input fields to process ReverseComplementSingle.""" reads = DataField("reads:fastq:single", label="Reads") class Output: """Output fields.""" fastq = ListField(FileField(), label="Reverse complemented FASTQ file") fastqc_url = ListField(FileHtmlField(), label="Quality control with FastQC") fastqc_archive = ListField(FileField(), label="Download FastQC archive") def run(self, inputs, outputs): """Run the analysis.""" basename = os.path.basename(inputs.reads.output.fastq[0].path) assert basename.endswith(".fastq.gz") name = basename[:-9] complemented_name = f"{name}_complemented.fastq" # Concatenate multilane reads ( Cmd["cat"][[reads.path for reads in inputs.reads.output.fastq]] > "input_reads.fastq.gz" )() # Reverse complement reads (Cmd["seqtk"]["seq", "-r", "input_reads.fastq.gz"] > complemented_name)() _, _, stderr = ( Cmd["fastqc"][complemented_name, "--extract", "--outdir=./"] & TEE ) if "Failed to process" in stderr or "Skipping" in stderr: self.error("Failed while processing with FastQC.") (Cmd["gzip"][complemented_name])() outputs.fastq = [f"{complemented_name}.gz"] outputs.fastqc_url = [f"{name}_complemented_fastqc.html"] outputs.fastqc_archive = [f"{name}_complemented_fastqc.zip"] class ReverseComplementPaired(Process): """Reverse complement paired-end FASTQ reads file using Seqtk.""" slug = "seqtk-rev-complement-paired" process_type = "data:reads:fastq:paired:seqtk" name = "Reverse complement FASTQ (paired-end)" requirements = { "expression-engine": "jinja", "executor": { "docker": {"image": "public.ecr.aws/s4q6j6e8/resolwebio/common:3.0.0"}, }, "resources": { "cores": 1, "memory": 16384, }, } entity = { "type": "sample", } data_name = '{{ reads|sample_name|default("?") }}' version = "1.1.0" class Input: """Input fields to process ReverseComplementPaired.""" reads = DataField("reads:fastq:paired", label="Reads") select_mate = StringField( label="Select mate", description="Select the which mate should be reverse complemented.", choices=[("Mate 1", "Mate 1"), ("Mate 2", "Mate 2"), ("Both", "Both")], default="Mate 1", ) class Output: """Output fields.""" fastq = ListField(FileField(), label="Reverse complemented FASTQ file") fastq2 = ListField(FileField(), label="Remaining mate") fastqc_url = ListField( FileHtmlField(), label="Quality control with FastQC (Mate 1)" ) fastqc_archive = ListField( FileField(), label="Download FastQC archive (Mate 1)" ) fastqc_url2 = ListField( FileHtmlField(), label="Quality control with FastQC (Mate 2)" ) fastqc_archive2 = ListField( FileField(), label="Download FastQC archive (Mate 2)" ) def run(self, inputs, outputs): """Run the analysis.""" basename_mate1 = os.path.basename(inputs.reads.output.fastq[0].path) basename_mate2 = os.path.basename(inputs.reads.output.fastq2[0].path) assert basename_mate1.endswith(".fastq.gz") assert basename_mate2.endswith(".fastq.gz") name_mate1 = basename_mate1[:-9] name_mate2 = basename_mate2[:-9] original_mate1 = f"{name_mate1}_original.fastq.gz" original_mate2 = f"{name_mate2}_original.fastq.gz" ( Cmd["cat"][[reads.path for reads in inputs.reads.output.fastq]] > original_mate1 )() ( Cmd["cat"][[reads.path for reads in inputs.reads.output.fastq2]] > original_mate2 )() if inputs.select_mate == "Mate 1": complemented_mate1 = f"{name_mate1}_complemented.fastq" (Cmd["seqtk"]["seq", "-r", original_mate1] > complemented_mate1)() _, _, stderr = ( Cmd["fastqc"][complemented_mate1, "--extract", "--outdir=./"] & TEE ) if "Failed to process" in stderr or "Skipping" in stderr: self.error("Failed while processing with FastQC.") _, _, stderr2 = ( Cmd["fastqc"][original_mate2, "--extract", "--outdir=./"] & TEE ) if "Failed to process" in stderr2 or "Skipping" in stderr2: self.error("Failed while processing with FastQC.") (Cmd["gzip"][complemented_mate1])() outputs.fastq = [f"{complemented_mate1}.gz"] outputs.fastq2 = [original_mate2] outputs.fastqc_url = [f"{name_mate1}_complemented_fastqc.html"] outputs.fastqc_archive = [f"{name_mate1}_complemented_fastqc.zip"] outputs.fastqc_url2 = [f"{name_mate2}_original_fastqc.html"] outputs.fastqc_archive2 = [f"{name_mate2}_original_fastqc.zip"] elif inputs.select_mate == "Mate 2": complemented_mate2 = f"{name_mate2}_complemented.fastq" ( Cmd["seqtk"]["seq", "-r", f"{name_mate2}_original.fastq.gz"] > complemented_mate2 )() _, _, stderr = ( Cmd["fastqc"][original_mate1, "--extract", "--outdir=./"] & TEE ) if "Failed to process" in stderr or "Skipping" in stderr: self.error("Failed while processing with FastQC.") _, _, stderr2 = ( Cmd["fastqc"][complemented_mate2, "--extract", "--outdir=./"] & TEE ) if "Failed to process" in stderr2 or "Skipping" in stderr2: self.error("Failed while processing with FastQC.") (Cmd["gzip"][complemented_mate2])() outputs.fastq = [original_mate1] outputs.fastq2 = [f"{complemented_mate2}.gz"] outputs.fastqc_url = [f"{name_mate1}_original_fastqc.html"] outputs.fastqc_archive = [f"{name_mate1}_original_fastqc.zip"] outputs.fastqc_url2 = [f"{name_mate2}_complemented_fastqc.html"] outputs.fastqc_archive2 = [f"{name_mate2}_complemented_fastqc.zip"] else: complemented_mate1 = f"{name_mate1}_complemented.fastq" complemented_mate2 = f"{name_mate2}_complemented.fastq" ( Cmd["seqtk"]["seq", "-r", f"{name_mate1}_original.fastq.gz"] > complemented_mate1 )() _, _, stderr = ( Cmd["fastqc"][complemented_mate1, "--extract", "--outdir=./"] & TEE ) if "Failed to process" in stderr or "Skipping" in stderr: self.error("Failed while processing with FastQC.") (Cmd["gzip"][complemented_mate1])() ( Cmd["seqtk"]["seq", "-r", f"{name_mate2}_original.fastq.gz"] > complemented_mate2 )() _, _, stderr2 = ( Cmd["fastqc"][complemented_mate2, "--extract", "--outdir=./"] & TEE ) if "Failed to process" in stderr2 or "Skipping" in stderr2: self.error("Failed while processing with FastQC.") (Cmd["gzip"][complemented_mate2])() outputs.fastq = [f"{complemented_mate1}.gz"] outputs.fastq2 = [f"{complemented_mate2}.gz"] outputs.fastqc_url = [f"{name_mate1}_complemented_fastqc.html"] outputs.fastqc_archive = [f"{name_mate1}_complemented_fastqc.zip"] outputs.fastqc_url2 = [f"{name_mate2}_complemented_fastqc.html"] outputs.fastqc_archive2 = [f"{name_mate2}_complemented_fastqc.zip"]
apache-2.0
kstilwell/tcex
tcex/services/common_service.py
14584
"""TcEx Framework Service Common module""" # standard library import json import threading import time import traceback import uuid from datetime import datetime from typing import Callable, Optional, Union from .mqtt_message_broker import MqttMessageBroker class CommonService: """TcEx Framework Service Common module Shared service logic between the supported service types: * API Service * Custom Trigger Service * Webhook Trigger Service """ def __init__(self, tcex: object): """Initialize the Class properties. Args: tcex: Instance of TcEx. """ self.tcex = tcex # properties self._ready = False self._start_time = datetime.now() self.args: object = tcex.default_args self.configs = {} self.heartbeat_max_misses = 3 self.heartbeat_sleep_time = 1 self.heartbeat_watchdog = 0 self.ij = tcex.ij self.key_value_store = self.tcex.key_value_store self.log = tcex.log self.logger = tcex.logger self.message_broker = MqttMessageBroker( broker_host=self.args.tc_svc_broker_host, broker_port=self.args.tc_svc_broker_port, broker_timeout=self.args.tc_svc_broker_conn_timeout, broker_token=self.args.tc_svc_broker_token, broker_cacert=self.args.tc_svc_broker_cacert_file, logger=tcex.log, ) self.ready = False self.redis_client = self.tcex.redis_client self.token = tcex.token # config callbacks self.shutdown_callback = None def _create_logging_handler(self): """Create a logging handler.""" if self.logger.handler_exist(self.thread_name): return # create trigger id logging filehandler self.logger.add_pattern_file_handler( name=self.thread_name, filename=f'''{datetime.today().strftime('%Y%m%d')}/{self.session_id}.log''', level=self.args.tc_log_level, path=self.args.tc_log_path, # uuid4 pattern for session_id pattern=r'^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}.log$', handler_key=self.session_id, thread_key='session_id', ) def add_metric(self, label: str, value: Union[int, str]) -> None: """Add a metric. Metrics are reported in heartbeat message. Args: label: The metric label (e.g., hits) to add. value: The value for the metric. """ self._metrics[label] = value @property def command_map(self) -> dict: """Return the command map for the current Service type.""" return { 'heartbeat': self.process_heartbeat_command, 'loggingchange': self.process_logging_change_command, 'shutdown': self.process_shutdown_command, } @staticmethod def create_session_id() -> str: # pylint: disable=unused-argument """Return a uuid4 session id. Returns: str: A unique UUID string value. """ return str(uuid.uuid4()) def heartbeat(self) -> None: """Start heartbeat process.""" self.service_thread(name='heartbeat', target=self.heartbeat_monitor) def heartbeat_monitor(self) -> None: """Publish heartbeat on timer.""" self.log.info('feature=service, event=heartbeat-monitor-started') while True: if self.heartbeat_watchdog > ( int(self.args.tc_svc_hb_timeout_seconds) / int(self.heartbeat_sleep_time) ): self.log.error( 'feature=service, event=missed-heartbeat, action=shutting-service-down' ) self.process_shutdown_command({'reason': 'Missed heartbeat commands.'}) break time.sleep(self.heartbeat_sleep_time) self.heartbeat_watchdog += 1 def increment_metric(self, label: str, value: Optional[int] = 1) -> None: """Increment a metric if already exists. Args: label: The metric label (e.g., hits) to increment. value: The increment value. Defaults to 1. """ if self._metrics.get(label) is not None: self._metrics[label] += value def listen(self) -> None: """List for message coming from broker.""" self.message_broker.add_on_connect_callback(self.on_connect_handler) self.message_broker.add_on_message_callback( self.on_message_handler, topics=[self.args.tc_svc_server_topic] ) self.message_broker.register_callbacks() # start listener thread self.service_thread(name='broker-listener', target=self.message_broker.connect) def loop_forever(self, sleep: Optional[int] = 1) -> bool: """Block and wait for shutdown. Args: sleep: The amount of time to sleep between iterations. Defaults to 1. Returns: Bool: Returns True until shutdown received. """ while True: deadline = time.time() + sleep while time.time() < deadline: if self.message_broker.shutdown: return False time.sleep(1) return True @property def metrics(self) -> dict: """Return current metrics.""" # TODO: move to trigger command and handle API Service if self._metrics.get('Active Playbooks') is not None: self.update_metric('Active Playbooks', len(self.configs)) return self._metrics @metrics.setter def metrics(self, metrics: dict): """Return current metrics.""" if isinstance(metrics, dict): self._metrics = metrics else: self.log.error('feature=service, event=invalid-metrics') def on_connect_handler( self, client, userdata, flags, rc # pylint: disable=unused-argument ) -> None: """On connect method for mqtt broker.""" self.log.info( f'feature=service, event=topic-subscription, topic={self.args.tc_svc_server_topic}' ) self.message_broker.client.subscribe(self.args.tc_svc_server_topic) self.message_broker.client.disable_logger() def on_message_handler( self, client, userdata, message # pylint: disable=unused-argument ) -> None: """On message for mqtt.""" try: # messages on server topic must be json objects m = json.loads(message.payload) except ValueError: self.log.warning( f'feature=service, event=parsing-issue, message="""{message.payload}"""' ) return # use the command to call the appropriate method defined in command_map command: str = m.get('command', 'invalid').lower() trigger_id: Optional[int] = m.get('triggerId') if trigger_id is not None: # coerce trigger_id to int in case a string was provided (testing framework) trigger_id = int(trigger_id) self.log.info(f'feature=service, event=command-received, command="{command}"') # create unique session id to be used as thread name # and stored as property of thread for logging emit session_id = self.create_session_id() # get the target method from command_map for the current command thread_method = self.command_map.get(command, self.process_invalid_command) self.service_thread( # use session_id as thread name to provide easy debugging per thread name=session_id, target=thread_method, args=(m,), session_id=session_id, trigger_id=trigger_id, ) def process_heartbeat_command(self, message: dict) -> None: # pylint: disable=unused-argument """Process the HeartBeat command. .. code-block:: python :linenos: :lineno-start: 1 { "command": "Heartbeat", "metric": {}, "memoryPercent": 0, "cpuPercent": 0 } Args: message: The message payload from the server topic. """ self.heartbeat_watchdog = 0 # send heartbeat -acknowledge- command response = {'command': 'Heartbeat', 'metric': self.metrics} self.message_broker.publish( message=json.dumps(response), topic=self.args.tc_svc_client_topic ) self.log.info(f'feature=service, event=heartbeat-sent, metrics={self.metrics}') def process_logging_change_command(self, message: dict) -> None: """Process the LoggingChange command. .. code-block:: python :linenos: :lineno-start: 1 { "command": "LoggingChange", "level": "DEBUG" } Args: message: The message payload from the server topic. """ level: str = message.get('level') self.log.info(f'feature=service, event=logging-change, level={level}') self.logger.update_handler_level(level) def process_invalid_command(self, message: dict) -> None: """Process all invalid commands. Args: message: The message payload from the server topic. """ self.log.warning( f'feature=service, event=invalid-command-received, message="""({message})""".' ) def process_shutdown_command(self, message: dict) -> None: """Implement parent method to process the shutdown command. .. code-block:: python :linenos: :lineno-start: 1 { "command": "Shutdown", "reason": "Service disabled by user." } Args: message: The message payload from the server topic. """ reason = message.get('reason') or ( 'A shutdown command was received on server topic. Service is shutting down.' ) self.log.info(f'feature=service, event=shutdown, reason={reason}') # acknowledge shutdown command self.message_broker.publish( json.dumps({'command': 'Acknowledged', 'type': 'Shutdown'}), self.args.tc_svc_client_topic, ) # call App shutdown callback if callable(self.shutdown_callback): try: # call callback for shutdown and handle exceptions to protect thread self.shutdown_callback() # pylint: disable=not-callable except Exception as e: self.log.error( f'feature=service, event=shutdown-callback-error, error="""({e})""".' ) self.log.trace(traceback.format_exc()) # unsubscribe and disconnect from the broker self.message_broker.client.unsubscribe(self.args.tc_svc_server_topic) self.message_broker.client.disconnect() # update shutdown flag self.message_broker.shutdown = True # delay shutdown to give App time to cleanup time.sleep(5) self.tcex.exit(0) # final shutdown in case App did not @property def ready(self) -> bool: """Return ready boolean.""" return self._ready @ready.setter def ready(self, bool_val: bool): """Set ready boolean.""" if isinstance(bool_val, bool) and bool_val is True: # wait until connected to send ready command while not self.message_broker._connected: if self.message_broker.shutdown: break time.sleep(1) else: # pylint: disable=useless-else-on-loop self.log.info('feature=service, event=service-ready') ready_command = {'command': 'Ready'} if self.ij.runtime_level.lower() in ['apiservice']: ready_command['discoveryTypes'] = self.ij.service_discovery_types self.message_broker.publish( json.dumps(ready_command), self.args.tc_svc_client_topic ) self._ready = True def service_thread( self, name: str, target: Callable[[], bool], args: Optional[tuple] = None, kwargs: Optional[dict] = None, session_id: Optional[str] = None, trigger_id: Optional[int] = None, ) -> None: """Start a message thread. Args: name: The name of the thread. target: The method to call for the thread. args: The args to pass to the target method. kwargs: Additional args. session_id: The current session id. trigger_id: The current trigger id. """ self.log.info(f'feature=service, event=service-thread-creation, name={name}') args = args or () try: t = threading.Thread(name=name, target=target, args=args, kwargs=kwargs, daemon=True) # add session_id to thread to use in logger emit t.session_id = session_id # add trigger_id to thread to use in logger emit t.trigger_id = trigger_id t.start() except Exception: self.log.trace(traceback.format_exc()) @property def session_id(self) -> Optional[str]: """Return the current session_id.""" if not hasattr(threading.current_thread(), 'session_id'): threading.current_thread().session_id = self.create_session_id() return threading.current_thread().session_id @property def thread_name(self) -> str: """Return a uuid4 session id.""" return threading.current_thread().name @property def trigger_id(self) -> Optional[int]: """Return the current trigger_id.""" trigger_id = None if hasattr(threading.current_thread(), 'trigger_id'): trigger_id = threading.current_thread().trigger_id if trigger_id is not None: trigger_id = int(trigger_id) return trigger_id def update_metric(self, label: str, value: Union[int, str]) -> None: """Update a metric if already exists. Args: label: The metric label (e.g., hits) to update. value: The updated value for the metric. """ if self._metrics.get(label) is not None: self._metrics[label] = value
apache-2.0
glameyzhou/scaffold
scaffold-component/src/test/java/org/glamey/scaffold/component/store/qiniu/QiNiuStoreTemplateTest.java
846
package org.glamey.scaffold.component.store.qiniu; import com.google.common.io.Files; import org.glamey.scaffold.BaseSpringJunit; import org.glamey.scaffold.component.store.StoreTemplate; import org.junit.Test; import javax.annotation.Resource; import java.io.File; /** * @author zhouyang.zhou. */ public class QiNiuStoreTemplateTest extends BaseSpringJunit { @Resource private StoreTemplate qiNiuStoreTemplate; @Test public void uploadFile() throws Exception { File uploadFile = new File("C:\\tmp\\dept.json"); qiNiuStoreTemplate.upload(uploadFile, uploadFile.getName()); } @Test public void uploadFileBytes() throws Exception { File uploadFile = new File("C:\\tmp\\qcache\\.gitignore"); qiNiuStoreTemplate.upload(Files.toByteArray(uploadFile), uploadFile.getName()); } }
apache-2.0
libris/librisxl
gui-whelktool/src/main/java/whelk/gui/ReplaceRecordsPanel.java
3153
package whelk.gui; import whelk.ScriptGenerator; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; class ReplaceRecordsPanel extends WizardCard implements ActionListener { final Wizard window; private final JFileChooser chooser = new JFileChooser(); private File chosenFile; private final JTextField chosenFileField; public ReplaceRecordsPanel(Wizard wizard) { super(wizard); window = wizard; chooser.setPreferredSize(new Dimension(1024, 768)); Box vbox = Box.createVerticalBox(); vbox.add(new JLabel("<html>Vänligen välj en fil med par av XL-IDn (EJ KONTROLLNUMMER!).<br/>" + "<br/>Filen måste innehålla två IDn per rad, separerade av ett mellanslag." + "<br/>Det första IDt på varje rad ersätter det andra IDt på samma rad." + "<br/><br/>Exempel:" + "<br/>vd6njp162pcr3zd c9ps03vw0cpqgx6" + "<br/>jvtbf1w0g7jhgttx fcrtxkcz4dxttr5" + "<br/><br/>Tolkas som:" + "<br/>c9ps03vw0cpqgx6 ersätts av vd6njp162pcr3zd." + "<br/>fcrtxkcz4dxttr5 ersätts av jvtbf1w0g7jhgttx." + "</html>")); vbox.add(Box.createVerticalStrut(10)); JButton chooseFileButton = new JButton("Välj fil"); chooseFileButton.setActionCommand("open"); chooseFileButton.addActionListener(this); vbox.add(chooseFileButton); vbox.add(Box.createVerticalStrut(10)); chosenFileField = new JTextField(); chosenFileField.setEditable(false); vbox.add(chosenFileField); vbox.add(Box.createVerticalStrut(10)); add(vbox); } @Override protected void beforeNext() { Set<String> ids = new HashSet<>(); try (BufferedReader reader = new BufferedReader(new FileReader(chosenFile))) { for (String line; (line = reader.readLine()) != null; ) { ids.add(line); } } catch (Throwable e) { Wizard.exitFatal(e); } try { setParameterForNextCard(ScriptGenerator.generateReplaceRecordsScript(ids)); } catch (IOException ioe) { Wizard.exitFatal(ioe); } } @Override void onShow(Object parameterFromPreviousCard) { setNextCard(Wizard.RUN); chosenFile = null; disableNext(); } @Override public void actionPerformed(ActionEvent actionEvent) { if (actionEvent.getActionCommand().equals("open")) { int returnVal = chooser.showOpenDialog(window); if(returnVal == JFileChooser.APPROVE_OPTION) { chosenFile = chooser.getSelectedFile(); chosenFileField.setText( chooser.getSelectedFile().getName() ); enableNext(); } } } }
apache-2.0
mschlenstedt/Loxberry
libs/perllib/File/Samba.pm
27073
package File::Samba; use strict; use warnings; use Carp qw(cluck croak confess); use Data::Dump qw(dump); require Exporter; our @ISA = qw(Exporter); # # We all for several exports # our $VERSION = '0.03'; our (@EXPORT, @EXPORT_OK, %EXPORT_TAGS); # # Exported Functions by request # @EXPORT_OK = qw( version keys value listShares deleteShare createShare sectionParameter globalParameter load save ); # symbols to export on request =head1 Object Methods =head2 new([config file]) Optionally a file can be specifided in the constructor to load the file on creation. Returns a new Samba Object =cut sub new { my $proto = shift; my $class = ref($proto) || $proto; my $self = {}; $self->{_global} = {}; $self->{_section} = {}; $self->{_version} = 2; eval { while(<DATA>) { chomp; next if /^#/; my ($st,$vers,$cmd) = split(/:/); if($cmd && $vers && $st) { chomp($cmd); $self->{_VALID}->{$st}->{"v$vers"}->{$cmd} = "1"; } last if /__END__/; } }; bless ($self, $class); if(@_) { $self->load(shift); } return $self; } =head2 version([version]) Set or get the version of this smb.conf your want to edit the load method tries to determine the smb.conf version based on the keys it find Params: [Optional] the version number Returns: the current version (either 2 or 3) Example: if($obj->version == 3) { # do Samba 3 options } =cut sub version { my $self = shift; if (@_) { my $ver = shift; croak "Samba version 2 or 3 only " if($ver < 2 || $ver > 3); $self->{_version} = $ver; # do we strip out bad values? NOPE } return $self->{_version}; } =head2 keys(section) Get a list of key for a given section, use 'global' for the globl section Params: section to list Returns: a sorted list of section keys Example: my @keys = $smb->keys('some section'); =cut sub keys { my $self = shift; my $section = shift; if($section eq "global") { return sort(CORE::keys(%{$self->{_global}})); } else { return sort(CORE::keys(%{$self->{_section}->{$section}})); } } =head2 value(section,key) Get the value associated with a key in a given section (READ ONLY) Params: section to list key to read Returns: the value associated with the key/section combination or undef if the key/section does nto exists Example: my $value = $smb->keys('some section','some key'); =cut sub value { my $self = shift; my $section = shift; my $key = shift; if($section eq "global") { return $self->{_global}->{$key}; } else { return $self->{_section}->{$section}->{$key}; } } =head2 listShares() Get a list of shares defined in the smb.conf file EXCLUDING the global section Params: none Returns: a sorted list of section names Example: my @list = $smb->listShares; =cut sub listShares { my $self = shift; my @list = CORE::keys(%{$self->{_section}}); return sort(@list); } =head2 deleteShare(share name) Delete a given share, this method can't delete the global section Params: the share to delete Returns: none Example: $smb->deleteShare('some share'); =cut sub deleteShare { my $self = shift; my $share = shift; delete $self->{_section}->{$share}; } =head2 createShare(share name) Create a share with a given name Params: the share to create Returns: none Example: $smb->createShare('some share'); Exceptions: If you try to create a share called global, the method will croak =cut sub createShare { my $self = shift; my $share = shift; if($share eq 'global') { croak("You can't create a share called global"); } $self->{_section}->{$share} = {} unless exists $self->{_section}->{$share}; } =head2 sectionParameter(section,key,[value]) Get or set a key in a given section, if value is not sepecifed this methods performs a lookup, otherwise it performs an edit Params: the section you wish to modify/view the key to view the value to set Returns: the value set or read Example: $smb->sectionParameter('homes','guest ok','yes'); Exceptions: The key you pass in for a 'Set' operrtion will be checked against a list of valid key names, based on the smb.conf version. Setting an invalid key will result if croak =cut sub sectionParameter { my $self = shift; my $section = shift; my $param = shift; if(@_) { my $value = shift; my $version = $self->{_version}; if($self->{_VALID}->{section}->{"v$version"}->{$param}) { $self->{_section}->{$section}->{$param} = $value; } else { croak("Invalid section key \"$param\" for samba version $version"); } } return $self->{_section}->{$section}->{$param}; } =head2 globalParameter(key,[value]) Get or set a key in the global section, if value is not sepecifed this methods performs a lookup, otherwise it performs an edit Params: the key to view the value to set Returns: the value set or read Example: $smb->globalParameter('homes','guest ok','yes'); Exceptions: The key you pass in for a 'Set' operrtion will be checked against a list of valid key names, based on the smb.conf version. Setting an invalid key will result if croak =cut sub globalParameter { my $self = shift; my $param = shift; if(@_) { my $value = shift; my $version = $self->{_version}; if($self->{_VALID}->{global}->{"v$version"}->{$param} || $self->{_VALID}->{section}->{"v$version"}->{$param}) { $self->{_global}->{$param} = $value; } else { croak("Invalid key \"$param\" for samba version $version"); } } return $self->{_global}->{$param}; } =head2 load(filename) Read a smb.conf file from disk, and parse it. The version will be identified as best as possible but may not be correct, you should use version method after calling load to make sure the version detected correctly Params: the smb.conf file to load Returns: none Example: $smb->load('/etc/samba/smbconf'); Exceptions: If the file does not exist croak =cut sub load { my $self = shift; my $file = shift; cluck("No such file $file") unless -e $file; # Load the file and run open(FH,$file); my $isGlobal; my $lastSection; # guess version 2 we need a good wy to see if version 3 my $lastDetVersion = 2; while(<FH>) { chomp; next if /^;|^#/; next if /^\s+$/; next if length($_) <= 1; s/\t//; s/\n//; s/^\s+//; s/\s+$//; next if /^;/; if(/\[global\]/i) { $isGlobal = 1; } elsif(/\[(\w+)\]/) { $isGlobal = 0; $lastSection = $1; } else { my($key,$value) = split('=',$_,2); $key =~ s/\s+$//; $value =~ s/^\s+//; if($isGlobal) { $self->{_global}->{$key}=$value; my ($v2,$v3); $v2 = $self->{_VALID}->{global}->{v2}->{$key}; $v3 = $self->{_VALID}->{global}->{v3}->{$key}; if($v3 && !$v2) { $self->{_version} = 3; } } else { if($self->{_section}->{$lastSection}) { $self->{_section}->{$lastSection}->{$key} = $value; } else { $self->{_section}->{$lastSection} = {}; $self->{_section}->{$lastSection}->{$key} = $value; } } } } close(FH); #print "[Global] \n",dump($self->{_global}); #print "\n[Sections] \n",dump($self->{_section}); #print "\n[Version] \n",$self->{_version}; } =head2 save(filename) Save the current inmemory smb.conf file Params: the file to save to Returns: none Example: $smb->save('/home/test.conf'); =cut sub save { my $self = shift; my $outputFile = shift; # Save it now !! open(WH,">$outputFile"); # Ok write Header print WH "################################################################################\n"; print WH "# Generate By File::Samba $VERSION #\n"; print WH "# This is the main Samba configuration file. You should read the #\n"; print WH "# smb.conf(5) manual page in order to understand the options listed #\n"; print WH "# here. #\n"; print WH "# Any line which starts with a ; (semi-colon) or a # (hash) #\n"; print WH "# is a comment and is ignored. In this example we will use a # #\n"; print WH "# for commentry and a ; for parts of the config file that you #\n"; print WH "# may wish to enable #\n"; print WH "# #\n"; print WH "# NOTE: Whenever you modify this file you should run the command \"testparm\" #\n"; print WH "# to check that you have not made any basic syntactic errors. #\n"; print WH "################################################################################\n"; print WH ";========================= Global Settings =====================================\n"; # write global section print WH "[global]\n"; foreach my $key ($self->keys('global')) { print WH "\t$key = ",$self->{_global}->{$key},"\n"; } print WH "\n"; print WH ";=========================== Share Settings =====================================\n"; my @sList = $self->listShares; foreach my $skey (@sList) { print WH "[$skey]\n"; if($skey eq "homes" || $skey eq "printers" ) { print WH "\t;special shares for samba see smb.conf(5)\n"; } my @skList = $self->keys($skey); foreach my $subK (@skList) { print WH "\t$subK = ",$self->{_section}->{$skey}->{$subK},"\n"; } print WH "\n"; } close(WH); } 1; __DATA__ # Samba version 2 global:2:add printer command global:2:add share command global:2:add user script global:2:allow trusted domains global:2:announce as global:2:announce version global:2:auto services global:2:bind interfaces only global:2:browse list global:2:change notify timeout global:2:change share command global:2:character set global:2:client code page global:2:code page directory global:2:coding system global:2:config file global:2:deadtime global:2:debug hires timestamp global:2:debug pid global:2:debug timestamp global:2:debug uid global:2:debuglevel global:2:default global:2:default service global:2:delete printer command global:2:delete share command global:2:delete user script global:2:dfree command global:2:disable spoolss global:2:dns proxy global:2:domain admin group global:2:domain guest group global:2:domain logons global:2:domain master global:2:encrypt passwords global:2:enhanced browsing global:2:enumports command global:2:getwd cache global:2:hide local users global:2:hide unreadable global:2:homedir map global:2:host msdfs global:2:hosts equiv global:2:interfaces global:2:keepalive global:2:kernel oplocks global:2:lanman auth global:2:large readwrite global:2:ldap admin dn global:2:ldap filter global:2:ldap port global:2:ldap server global:2:ldap ssl global:2:ldap suffix global:2:lm announce global:2:lm interval global:2:load printers global:2:local master global:2:lock dir global:2:lock directory global:2:lock spin count global:2:lock spin time global:2:pid directory global:2:log file global:2:log level global:2:logon drive global:2:logon home global:2:logon path global:2:logon script global:2:lpq cache time global:2:machine password timeout global:2:mangled stack global:2:mangling method global:2:map to guest global:2:max disk size global:2:max log size global:2:max mux global:2:max open files global:2:max protocol global:2:max smbd processes global:2:max ttl global:2:max wins ttl global:2:max xmit global:2:message command global:2:min passwd length global:2:min password length global:2:min protocol global:2:min wins ttl global:2:name resolve order global:2:netbios aliases global:2:netbios name global:2:netbios scope global:2:nis homedir global:2:nt pipe support global:2:nt smb support global:2:nt status support global:2:null passwords global:2:obey pam restrictions global:2:oplock break wait time global:2:os level global:2:os2 driver map global:2:pam password change global:2:panic action global:2:passwd chat global:2:passwd chat debug global:2:passwd program global:2:password level global:2:password server global:2:prefered master global:2:preferred master global:2:preload global:2:printcap global:2:printcap name global:2:printer driver file global:2:protocol global:2:read bmpx global:2:read raw global:2:read size global:2:remote announce global:2:remote browse sync global:2:restrict anonymous global:2:root global:2:root dir global:2:root directory global:2:security global:2:server string global:2:show add printer wizard global:2:smb passwd file global:2:socket address global:2:socket options global:2:source environment global:2:ssl global:2:ssl CA certDir global:2:ssl CA certFile global:2:ssl ciphers global:2:ssl client cert global:2:ssl client key global:2:ssl compatibility global:2:ssl egd socket global:2:ssl entropy bytes global:2:ssl entropy file global:2:ssl hosts global:2:ssl hosts resign global:2:ssl require clientcert global:2:ssl require servercert global:2:ssl server cert global:2:ssl server key global:2:ssl version global:2:stat cache global:2:stat cache size global:2:strip dot global:2:syslog global:2:syslog only global:2:template homedir global:2:template shell global:2:time offset global:2:time server global:2:timestamp logs global:2:total print jobs global:2:unix extensions global:2:unix password sync global:2:update encrypted global:2:use mmap global:2:use rhosts global:2:username level global:2:username map global:2:utmp global:2:utmp directory global:2:valid chars global:2:winbind cache time global:2:winbind enum users global:2:winbind enum groups global:2:winbind gid global:2:winbind separator global:2:winbind uid global:2:winbind use default domain global:2:wins hook global:2:wins proxy global:2:wins server global:2:wins support global:2:workgroup global:2:write raw section:2:admin users section:2:allow hosts section:2:available section:2:blocking locks section:2:block size section:2:browsable section:2:browseable section:2:case sensitive section:2:casesignames section:2:comment section:2:copy section:2:create mask section:2:create mode section:2:csc policy section:2:default case section:2:default devmode section:2:delete readonly section:2:delete veto files section:2:deny hosts section:2:directory section:2:directory mask section:2:directory mode section:2:directory security mask section:2:dont descend section:2:dos filemode section:2:dos filetime resolution section:2:dos filetimes section:2:exec section:2:fake directory create times section:2:fake oplocks section:2:follow symlinks section:2:force create mode section:2:force directory mode section:2:force directory security mode section:2:force group section:2:force security mode section:2:force unknown acl user section:2:force user section:2:fstype section:2:group section:2:guest account section:2:guest ok section:2:guest only section:2:hide dot files section:2:hide files section:2:hosts allow section:2:hosts deny section:2:include section:2:inherit acls section:2:inherit permissions section:2:invalid users section:2:level2 oplocks section:2:locking section:2:lppause command section:2:lpq command section:2:lpresume command section:2:lprm command section:2:magic output section:2:magic script section:2:mangle case section:2:mangled map section:2:mangled names section:2:mangling char section:2:map archive section:2:map hidden section:2:map system section:2:max connections section:2:max print jobs section:2:min print space section:2:msdfs root section:2:nt acl support section:2:only guest section:2:only user section:2:oplock contention limit section:2:oplocks section:2:path section:2:posix locking section:2:postexec section:2:postscript section:2:preexec section:2:preexec close section:2:preserve case section:2:print command section:2:print ok section:2:printable section:2:printer section:2:printer admin section:2:printer driver section:2:printer driver location section:2:printer name section:2:printing section:2:profile acls section:2:public section:2:queuepause command section:2:queueresume command section:2:read list section:2:read only section:2:root postexec section:2:root preexec section:2:root preexec close section:2:security mask section:2:set directory section:2:share modes section:2:short preserve case section:2:status section:2:strict allocate section:2:strict locking section:2:strict sync section:2:sync always section:2:use client driver section:2:use sendfile section:2:user section:2:username section:2:users section:2:valid users section:2:veto files section:2:veto oplock files section:2:vfs object section:2:vfs options section:2:volume section:2:wide links section:2:writable section:2:write cache size section:2:write list section:2:write ok section:2:writeable # Samba Version 3 global:3:abort shutdown script global:3:add group script global:3:add machine script global:3:addprinter command global:3:add share command global:3:add user script global:3:add user to group script global:3:algorithmic rid base global:3:allow trusted domains global:3:announce as global:3:announce version global:3:auth methods global:3:auto services global:3:bind interfaces only global:3:browse list global:3:change notify timeout global:3:change share command global:3:client lanman auth global:3:client ntlmv2 auth global:3:client plaintext auth global:3:client schannel global:3:client signing global:3:client use spnego global:3:config file global:3:deadtime global:3:debug hires timestamp global:3:debuglevel global:3:debug pid global:3:debug timestamp global:3:debug uid global:3:default global:3:default service global:3:delete group script global:3:deleteprinter command global:3:delete share command global:3:delete user from group script global:3:delete user script global:3:dfree command global:3:disable netbios global:3:disable spoolss global:3:display charset global:3:dns proxy global:3:domain logons global:3:domain master global:3:dos charset global:3:enable rid algorithm global:3:encrypt passwords global:3:enhanced browsing global:3:enumports command global:3:get quota command global:3:getwd cache global:3:guest account global:3:hide local users global:3:homedir map global:3:host msdfs global:3:hostname lookups global:3:hosts equiv global:3:idmap backend global:3:idmap gid global:3:idmap uid global:3:include global:3:interfaces global:3:keepalive global:3:kernel change notify global:3:kernel oplocks global:3:lanman auth global:3:large readwrite global:3:ldap admin dn global:3:ldap delete dn global:3:ldap filter global:3:ldap group suffix global:3:ldap idmap suffix global:3:ldap machine suffix global:3:ldap passwd sync global:3:ldap port global:3:ldap server global:3:ldap ssl global:3:ldap suffix global:3:ldap user suffix global:3:lm announce global:3:lm interval global:3:load printers global:3:local master global:3:lock dir global:3:lock directory global:3:lock spin count global:3:lock spin time global:3:log file global:3:log level global:3:logon drive global:3:logon home global:3:logon path global:3:logon script global:3:lpq cache time global:3:machine password timeout global:3:mangled stack global:3:mangle prefix global:3:mangling method global:3:map to guest global:3:max disk size global:3:max log size global:3:max mux global:3:max open files global:3:max protocol global:3:max smbd processes global:3:max ttl global:3:max wins ttl global:3:max xmit global:3:message command global:3:min passwd length global:3:min password length global:3:min protocol global:3:min wins ttl global:3:name cache timeout global:3:name resolve order global:3:netbios aliases global:3:netbios name global:3:netbios scope global:3:nis homedir global:3:ntlm auth global:3:nt pipe support global:3:nt status support global:3:null passwords global:3:obey pam restrictions global:3:oplock break wait time global:3:os2 driver map global:3:os level global:3:pam password change global:3:panic action global:3:paranoid server security global:3:passdb backend global:3:passwd chat global:3:passwd chat debug global:3:passwd program global:3:password level global:3:password server global:3:pid directory global:3:prefered master global:3:preferred master global:3:preload global:3:preload modules global:3:printcap global:3:private dir global:3:protocol global:3:read bmpx global:3:read raw global:3:read size global:3:realm global:3:remote announce global:3:remote browse sync global:3:restrict anonymous global:3:root global:3:root dir global:3:root directory global:3:security global:3:server schannel global:3:server signing global:3:server string global:3:set primary group script global:3:set quota command global:3:show add printer wizard global:3:shutdown script global:3:smb passwd file global:3:smb ports global:3:socket address global:3:socket options global:3:source environment global:3:stat cache global:3:strip dot global:3:syslog global:3:syslog only global:3:template homedir global:3:template primary group global:3:template shell global:3:time offset global:3:time server global:3:timestamp logs global:3:unicode global:3:unix charset global:3:unix extensions global:3:unix password sync global:3:update encrypted global:3:use mmap global:3:username level global:3:username map global:3:use spnego global:3:utmp global:3:utmp directory global:3:winbind cache time global:3:winbind enable local accounts global:3:winbind enum groups global:3:winbind enum users global:3:winbind gid global:3:winbind separator global:3:winbind trusted domains only global:3:winbind uid global:3:winbind use default domain global:3:wins hook global:3:wins partners global:3:wins proxy global:3:wins server global:3:wins support global:3:workgroup global:3:write raw global:3:wtmp directory section:3:acl compatibility section:3:admin users section:3:allow hosts section:3:available section:3:blocking locks section:3:block size section:3:browsable section:3:browseable section:3:case sensitive section:3:casesignames section:3:comment section:3:copy section:3:create mask section:3:create mode section:3:csc policy section:3:default case section:3:default devmode section:3:delete readonly section:3:delete veto files section:3:deny hosts section:3:directory section:3:directory mask section:3:directory mode section:3:directory security mask section:3:dont descend section:3:dos filemode section:3:dos filetime resolution section:3:dos filetimes section:3:exec section:3:fake directory create times section:3:fake oplocks section:3:follow symlinks section:3:force create mode section:3:force directory mode section:3:force directory security mode section:3:force group section:3:force security mode section:3:force user section:3:fstype section:3:group section:3:guest account section:3:guest ok section:3:guest only section:3:hide dot files section:3:hide files section:3:hide special files section:3:hide unreadable section:3:hide unwriteable files section:3:hosts allow section:3:hosts deny section:3:inherit acls section:3:inherit permissions section:3:invalid users section:3:level2 oplocks section:3:locking section:3:lppause command section:3:lpq command section:3:lpresume command section:3:lprm command section:3:magic output section:3:magic script section:3:mangle case section:3:mangled map section:3:mangled names section:3:mangling char section:3:map acl inherit section:3:map archive section:3:map hidden section:3:map system section:3:max connections section:3:max print jobs section:3:max reported print jobs section:3:min print space section:3:msdfs proxy section:3:msdfs root section:3:nt acl support section:3:only guest section:3:only user section:3:oplock contention limit section:3:oplocks section:3:path section:3:posix locking section:3:postexec section:3:preexec section:3:preexec close section:3:preserve case section:3:printable section:3:printcap name section:3:print command section:3:printer section:3:printer admin section:3:printer name section:3:printing section:3:print ok section:3:profile acls section:3:public section:3:queuepause command section:3:queueresume command section:3:read list section:3:read only section:3:root postexec section:3:root preexec section:3:root preexec close section:3:security mask section:3:set directory section:3:share modes section:3:short preserve case section:3:strict allocate section:3:strict locking section:3:strict sync section:3:sync always section:3:use client driver section:3:user section:3:username section:3:users section:3:use sendfile section:3:-valid section:3:valid users section:3:veto files section:3:veto oplock files section:3:vfs object section:3:vfs objects section:3:volume section:3:wide links section:3:writable section:3:writeable section:3:write cache size section:3:write list section:3:write ok __END__ # Below is stub documentation for your module. You'd better edit it! =head1 NAME File::Samba - Samba configuration Object =head1 SYNOPSIS use File::Samba; my $smb = File::Samba->new("/etc/samba/smb.conf"); @list = $smb->listShares; $smb->deleteShare('homes'); $smb->createShare('newShare'); =head1 DESCRIPTION This module allows for easy editing of smb.conf in an OO way. The need arised from openfiler http://www.openfiler.org which at this current time setups a smb conf for you, however any changes you made by hand are lost when you make change due to the fact it doesnt havea way to edit an existing smb.conf but simply creates a new one. This modules allows for any program to be ables to extract the current config, make changes nd save the file. Comments are lost however on save. =head2 EXPORT The following methods may be imported version keys value listShares deleteShare createShare sectionParameter globalParameter load save =head1 SEE ALSO http://www.samba.org Samba homepage All the config keys were extracted from version 2 and 3 man pages =head1 AUTHOR Salvatore E. ScottoDiLuzio<lt>[email protected]<gt> =head1 COPYRIGHT AND LICENSE Copyright (C) 2004 by Salvatore ScottoDiLuzio This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.3 or, at your option, any later version of Perl 5 you may have available. =cut
apache-2.0
bytePassion/OpenQuoridorFramework
OpenQuoridorFramework/OQF.PlayerVsBot.GameLogic/GameService.cs
4020
using System; using System.Threading; using bytePassion.Lib.Communication.State; using bytePassion.Lib.ConcurrencyLib; using OQF.AnalysisAndProgress.ProgressUtils; using OQF.Bot.Contracts; using OQF.Bot.Contracts.Coordination; using OQF.Bot.Contracts.GameElements; using OQF.Bot.Contracts.Moves; using OQF.PlayerVsBot.Contracts; using OQF.Utils.Enum; namespace OQF.PlayerVsBot.GameLogic { public class GameService : IGameService { private readonly bool disableBotTimeout; private readonly ISharedStateWriteOnly<bool> isBoardRotatedVariable; public event Action<BoardState> NewBoardStateAvailable; public event Action<string> NewDebugMsgAvailable; public event Action<Player, WinningReason, Move> WinnerAvailable; public event Action<GameStatus> NewGameStatusAvailable; private TimeoutBlockingQueue<Move> humenMoves; private IGameLoopThread gameLoopThread; private IQuoridorBot quoridorBot; private BoardState currentBoardState; private GameStatus currentGameStatus; public GameService(bool disableBotTimeout, ISharedStateWriteOnly<bool> isBoardRotatedVariable) { this.disableBotTimeout = disableBotTimeout; this.isBoardRotatedVariable = isBoardRotatedVariable; CurrentBoardState = null; gameLoopThread = null; CurrentGameStatus = GameStatus.Unloaded; } public BoardState CurrentBoardState { get { return currentBoardState; } private set { if (value != currentBoardState) { currentBoardState = value; NewBoardStateAvailable?.Invoke(currentBoardState); } } } public GameStatus CurrentGameStatus { get { return currentGameStatus; } private set { if (currentGameStatus != value) { currentGameStatus = value; NewGameStatusAvailable?.Invoke(currentGameStatus); } } } public PlayerType HumanPlayerPosition { get; private set; } public void CreateGame(IQuoridorBot uninitializedBot, string botName, GameConstraints gameConstraints, PlayerType startingPosition, QProgress initialProgress) { HumanPlayerPosition = startingPosition; isBoardRotatedVariable.Value = startingPosition == PlayerType.TopPlayer; if (gameLoopThread != null) { StopGame(); } var finalGameConstraints = disableBotTimeout ? new GameConstraints(Timeout.InfiniteTimeSpan,gameConstraints.MaximalMovesPerPlayer) : gameConstraints; quoridorBot = uninitializedBot; quoridorBot.DebugMessageAvailable += OnDebugMessageAvailable; humenMoves = new TimeoutBlockingQueue<Move>(200); gameLoopThread = startingPosition == PlayerType.BottomPlayer ? (IGameLoopThread) new GameLoopThreadPvB(quoridorBot, botName, humenMoves, finalGameConstraints, initialProgress) : (IGameLoopThread) new GameLoopThreadBvP(quoridorBot, botName, humenMoves, finalGameConstraints, initialProgress); gameLoopThread.NewBoardStateAvailable += OnNewBoardStateAvailable; gameLoopThread.WinnerAvailable += OnWinnerAvailable; CurrentGameStatus = GameStatus.Active; new Thread(gameLoopThread.Run).Start(); } private void OnWinnerAvailable(Player player, WinningReason winningReason, Move invalidMove) { WinnerAvailable?.Invoke(player, winningReason, invalidMove); CurrentGameStatus = GameStatus.Finished; } private void OnNewBoardStateAvailable (BoardState boardState) { CurrentBoardState = boardState; } private void OnDebugMessageAvailable(string s) { NewDebugMsgAvailable?.Invoke(s); } public void ReportHumanMove(Move move) { humenMoves.Put(move); } public void StopGame() { if (gameLoopThread != null) { quoridorBot.DebugMessageAvailable -= OnDebugMessageAvailable; gameLoopThread.Stop(); gameLoopThread.NewBoardStateAvailable -= OnNewBoardStateAvailable; gameLoopThread.WinnerAvailable -= OnWinnerAvailable; gameLoopThread = null; CurrentBoardState = null; } CurrentGameStatus = GameStatus.Unloaded; } } }
apache-2.0
gocd-contrib/docker-elastic-agents
src/main/java/cd/go/contrib/elasticagents/docker/requests/JobCompletionRequest.java
3654
/* * Copyright 2018 ThoughtWorks, Inc. * * 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 cd.go.contrib.elasticagents.docker.requests; import cd.go.contrib.elasticagents.docker.*; import cd.go.contrib.elasticagents.docker.executors.JobCompletionRequestExecutor; import cd.go.contrib.elasticagents.docker.models.JobIdentifier; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.Map; public class JobCompletionRequest { private static final Gson GSON = new GsonBuilder().excludeFieldsWithoutExposeAnnotation() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); @Expose @SerializedName("elastic_agent_id") private String elasticAgentId; @Expose @SerializedName("job_identifier") private JobIdentifier jobIdentifier; @Expose @SerializedName("elastic_agent_profile_properties") private Map<String, String> properties; @Expose @SerializedName("cluster_profile_properties") private ClusterProfileProperties clusterProfileProperties; public JobCompletionRequest() { } public JobCompletionRequest(String elasticAgentId, JobIdentifier jobIdentifier, Map<String, String> properties, Map<String, String> clusterProfile) { this.elasticAgentId = elasticAgentId; this.jobIdentifier = jobIdentifier; this.properties = properties; this.clusterProfileProperties = ClusterProfileProperties.fromConfiguration(clusterProfile); } public JobCompletionRequest(String elasticAgentId, JobIdentifier jobIdentifier, Map<String, String> properties, ClusterProfileProperties clusterProfileProperties) { this.elasticAgentId = elasticAgentId; this.jobIdentifier = jobIdentifier; this.properties = properties; this.clusterProfileProperties = clusterProfileProperties; } public static JobCompletionRequest fromJSON(String json) { JobCompletionRequest jobCompletionRequest = GSON.fromJson(json, JobCompletionRequest.class); return jobCompletionRequest; } public String getElasticAgentId() { return elasticAgentId; } public JobIdentifier jobIdentifier() { return jobIdentifier; } public ClusterProfileProperties getClusterProfileProperties() { return clusterProfileProperties; } public Map<String, String> getProperties() { return properties; } public RequestExecutor executor(AgentInstances<DockerContainer> agentInstances, PluginRequest pluginRequest) { return new JobCompletionRequestExecutor(this, agentInstances, pluginRequest); } @Override public String toString() { return "JobCompletionRequest{" + "elasticAgentId='" + elasticAgentId + '\'' + ", jobIdentifier=" + jobIdentifier + ", properties=" + properties + ", clusterProfileProperties=" + clusterProfileProperties + '}'; } }
apache-2.0
ihr/akka-di
README.md
186
akka-di ======= Dependency Injection for AKKA A small library for bridging the gap between Dependency Injection and AKKA There are two branches: -) master branch with dependencies on
apache-2.0
rolandio/inkstand
inkstand-http-undertow/src/main/java/io/inkstand/http/undertow/AuthenticatingUndertowWebServerProvider.java
3953
/* * Copyright 2015 Gerald Muecke, [email protected] * * 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 io.inkstand.http.undertow; import io.undertow.Undertow; import io.undertow.security.api.AuthenticationMechanism; import io.undertow.security.api.AuthenticationMode; import io.undertow.security.handlers.AuthenticationCallHandler; import io.undertow.security.handlers.AuthenticationConstraintHandler; import io.undertow.security.handlers.AuthenticationMechanismsHandler; import io.undertow.security.handlers.SecurityInitialHandler; import io.undertow.security.idm.IdentityManager; import io.undertow.security.impl.BasicAuthenticationMechanism; import io.undertow.server.HttpHandler; import io.undertow.servlet.Servlets; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.DeploymentManager; import java.util.Collections; import java.util.List; import javax.annotation.Priority; import javax.enterprise.inject.Produces; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.ServletException; import io.inkstand.ProtectedService; import io.inkstand.InkstandRuntimeException; import io.inkstand.config.WebServerConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provider of an Undertow WebServer instance with a specific deployment configuration. The deployment configuration is * injected itself and may be provided by an implementation of {@link UndertowDeploymentProvider}. The {@link Undertow} * instance provided by this provider is only configured, but not started. * * @author <a href="mailto:[email protected]">Gerald M&uuml;cke</a> */ @Singleton @Priority(0) @ProtectedService public class AuthenticatingUndertowWebServerProvider { /** * SLF4J Logger for this class */ private static final Logger LOG = LoggerFactory.getLogger(UndertowWebServerProvider.class); @Inject private WebServerConfiguration config; @Inject private DeploymentInfo deploymentInfo; @Inject private IdentityManager identityManager; @Produces public Undertow getLdapAuthUndertow() { deploymentInfo.setIdentityManager(identityManager); final DeploymentManager deploymentManager = Servlets.defaultContainer().addDeployment(deploymentInfo); deploymentManager.deploy(); try { LOG.info("Creating service endpoint {}:{}/{} for {} at ", config.getBindAddress(), config.getPort(), deploymentInfo.getContextPath(), deploymentInfo.getDeploymentName()); return Undertow.builder().addHttpListener(config.getPort(), config.getBindAddress()) .setHandler(addSecurity(deploymentManager.start())).build(); } catch (final ServletException e) { throw new InkstandRuntimeException(e); } } HttpHandler addSecurity(final HttpHandler toWrap) { HttpHandler handler = toWrap; handler = new AuthenticationCallHandler(handler); handler = new AuthenticationConstraintHandler(handler); final List<AuthenticationMechanism> mechanisms = Collections .<AuthenticationMechanism> singletonList(new BasicAuthenticationMechanism("My Realm")); handler = new AuthenticationMechanismsHandler(handler, mechanisms); handler = new SecurityInitialHandler(AuthenticationMode.PRO_ACTIVE, identityManager, handler); return handler; } }
apache-2.0
googleapis/java-aiplatform
proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/DeleteContextRequestOrBuilder.java
2785
/* * Copyright 2020 Google 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 * * https://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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/aiplatform/v1/metadata_service.proto package com.google.cloud.aiplatform.v1; public interface DeleteContextRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.aiplatform.v1.DeleteContextRequest) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Required. The resource name of the Context to delete. * Format: * `projects/{project}/locations/{location}/metadataStores/{metadatastore}/contexts/{context}` * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ java.lang.String getName(); /** * * * <pre> * Required. The resource name of the Context to delete. * Format: * `projects/{project}/locations/{location}/metadataStores/{metadatastore}/contexts/{context}` * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ com.google.protobuf.ByteString getNameBytes(); /** * * * <pre> * The force deletion semantics is still undefined. * Users should not use this field. * </pre> * * <code>bool force = 2;</code> * * @return The force. */ boolean getForce(); /** * * * <pre> * Optional. The etag of the Context to delete. * If this is provided, it must match the server's etag. Otherwise, the * request will fail with a FAILED_PRECONDITION. * </pre> * * <code>string etag = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The etag. */ java.lang.String getEtag(); /** * * * <pre> * Optional. The etag of the Context to delete. * If this is provided, it must match the server's etag. Otherwise, the * request will fail with a FAILED_PRECONDITION. * </pre> * * <code>string etag = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for etag. */ com.google.protobuf.ByteString getEtagBytes(); }
apache-2.0
obulpathi/poppy
poppy/transport/validators/stoplight/helpers.py
823
# Copyright (c) 2014 Rackspace, Inc. # # 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. """ Some useful getters for thread local request style validation. """ def pecan_getter(parm): """pecan getter.""" pecan_module = __import__('pecan', globals(), locals(), ['request']) return getattr(pecan_module, 'request')
apache-2.0
nishantmehta/mainGrokit
src/Test_DistMsg/headers/DistMsgTest.h
1687
// Copyright 2013 Tera Insights, LLC. All Rights Reserved. #ifndef _DIST_MSG_TEST_H_ #define _DIST_MSG_TEST_H_ #include "EventGenerator.h" #include "EventGeneratorImp.h" #include "EventProcessorImp.h" #include "EventProcessor.h" #include "RemoteAddress.h" #include "ProxyEventProcessor.h" #include "MessageMacros.h" #include "CommunicationFramework.h" #include "TestMessages.h" class TestSenderImp : public EventGeneratorImp { private: // Proxy to send the test messages ProxyEventProcessor target; // Current message ID int id; public: // Constructors / Destructor TestSenderImp() {} TestSenderImp( MailboxAddress & addr ); virtual ~TestSenderImp() { } virtual int ProduceMessage(void); }; class TestSender : public EventGenerator { public: TestSender() { } TestSender(MailboxAddress & addr ) { evGen = new TestSenderImp(addr); } virtual ~TestSender() { } }; class TestReceiverImp : public EventProcessorImp { private: public: // Constructors / Destructor TestReceiverImp() { } virtual ~TestReceiverImp() { } void ProcessTestMessage(TestMessage &msg); ACTOR_HANDLE HANDLER(TestMessage, ProcessTestMessage) END_HANDLE }; class TestReceiver : public EventProcessor { public: TestReceiver() { } TestReceiver( std::string mailbox ) { evProc = new TestReceiverImp(); RegisterAsRemoteEventProcessor(*this, mailbox); } virtual ~TestReceiver() { } }; #endif // _DIST_MSG_TEST_H_
apache-2.0
masukomi/mobtvse
vendor/bundle/gems/mongoid-2.4.11/CHANGELOG.md
38657
# Overview For instructions on upgrading to newer versions, visit [mongoid.org](http://mongoid.org/docs/upgrading.html). ## 2.4.11 (branch: 2.4.0-stable) ### Resolved Issues * This release forces a cap on the mongo driver version at 1.6.2 due to changes in the `Mongo::Connection.from_uri` API not allowing valid connection options anymore. * \#2040 Fixed bad interpolation for locale presence validation. * \#2038 Allow inverse relations to be determined by foreign keys alone if defined on both sides, not just an inverse_of declaration. * \#2023 Allow serilialization of dynamic types that conflict with core Ruby methods to still be serialized. * \#2008 Presence validation should hit the db to check validity if the relation in memory is blank. * \#2006 Allow excluding only the _id field post execution of an #only call. ## 2.4.10 ### Resolved Issues * \#2003 Don't fail on document generation when an embedded document was stored as nil in the database. * \#1997 Don't delete paranoid embedded docs via nested attributes when a before_destroy callback returns false. * \#1994 `dependent: :delete` only hits the database once now for one to many and many to many relations instead of once for each document. * \#1987 Don't double-insert documents into identity map when eager loading twice inside the unit of work. * \#1976 Don't execute eager load queries when base query is empty. * \#1953 Uniqueness validation now works on localized fields. * \#1936 Allow setting n levels deep embedded documents atomically without conflicting mods when not using nested attributes or documents themselves in an update call from the parent. * \#1957/\#1954 Ensure database name is set with inheritance. (Hans Hasselberg) ## 2.4.9 ### Resolved Issues * \#1943 Ensure numericality validation works for big decimals. * \#1938 Length validation now works with localized fields. * \#1936 Conflicting pushes with other pushes is now properly handled. * \#1933 `Proxy#extend` should delegate through to the target, where extending the proxy itself is now handled through `Proxy#proxy_extend`. * \#1930 Ensure complex criteria are expanded in all where clauses. (Hans Hasselberg) * \#1928 Deletion of embedded documents via nested attributes now performs a $pull with id match criteria instead of a $pullAll to cover all cases. Previously newly added defaults to documents that had already persisted could not be deleted in this matter since the doc did not match what was in the database. * \#1924/\#1917 Fix pushing to embedded relations with default scopes not scoping on the new document. (Hans Hasselberg) * \#1922/\#1919 Dropping collections unmemoizes the internally wrapped collection, in order to ensure when defining capped collections that they are always recreated as capped. (Hans Hasselberg) * \#1916/\#1913 Uniqueness validation no longer is affected by the default scope. (Hans Hasselberg) * \#1778 Ensure foreign keys are always set regardless of binding state. ## 2.4.8 ### Resolved Issues * \#1892 When getting not master operation error, Mongoid should reconnect before retrying the operation. * \#1887 Don't cascade callbacks to children that don't have the callback defined. * \#1882 Don't expand duplicate id criterion into an $and with duplicate selections. * \#1878 Fixed default application values not to apply in certain `only` or `without` selection on iteration, not just `first` and `last`. * \#1874 Fixed the reject all blank proc constant to handle values properly with a destroy non blank value. (Stefan Daschek) * \#1869/\#1868 Delayed atomic sets now uses the atomic path instead of the metadata name to fix multiple level embedding issues. (Chris Micacchi provided specs) * \#1866 Post processed defaults (procs) should be applied post binding of the child in a relation.build. ## 2.4.7 ### Resolved Issues * Ensure reloading of embedded documents retains reference to the parent. * \#1837 Always pass symbol options to the driver. * \#1836 Ensure relation counts pick up persisted document that have not had the foreign key link persisted. * \#1820 Destroying embedded documents in an embeds_many should also removed the document from the underlying _uncoped target and reindex the relation. * \#1814 Don't cascade callbacks on after_initialize. * \#1800 Invalid options for the Mongo connection are now filtered out. * \#1785 Case equality has been fixed to handle instance checks properly. ## 2.4.6 ### Resolved Issues * \#1772 Allow skip and limit to convert strings to integers. (Jean Boussier) * \#1767 Model#update_attributes accepts mass assignment options again. (Hans Hasselberg) * \#1762 Criteria#any_of now properly handles localized fields. * \#1758 Metadata now returns self on options for external library support. * \#1757 Ensure serialization converts any attribute types to the type defined by the field. * \#1756 Serializable hash options should pass through to embedded docs. ## 2.4.5 ### Resolved Issues * \#1751 Mongoid's logger now responds to level for Ruby logging API compatibility. * \#1744/#1750 Sorting works now for localized fields in embedded documents using the criteria API. (Hans Hasselberg) * \#1746 Presence validation now shows which locales were empty for localized fields. (Cyril Mougel) * \#1727 Allow dot notation in embedded criteria to work on both embeds one and embeds many. (Lyle Underwood) * \#1723 Initialize callbacks should cascade through children without needing to determine if the child is changed. * \#1715 Serializable hashes are now consistent on inclusion of embedded documents per or post save. * \#1713 Fixing === checks when comparing a class with an instance of a subclass. * \#1495 Callbacks no longer get the 'super called outside of method` errors on busted 1.8.7 rubies. ## 2.4.4 ### Resolved Issues * \#1705 Allow changing the order of many to many foreign keys. * \#1703 Updated at is now versioned again. (Lucas Souza) * \#1686 Set the base metadata on unbind as well as bind for belongs to relations. * \#1681 Attempt to create indexes for models without namespacing if the namespace does not exist for the subdirectory. * \#1676 Allow eager loading to work as a default scope. * \#1665/#1672 Expand complex criteria in nested criteria selectors, like #matches. (Hans Hasselberg) * \#1668 Ensure Mongoid logger exists before calling warn. (Rémy Coutable) * \#1661 Ensure uniqueness validation works on cloned documents. * \#1659 Clear delayed atomic sets when resetting the same embedded relation. * \#1656/#1657 Don't hit database for uniqueness validation if BOTH scope and attribute hasn't changed. (priyaaank) * \#1205/#1642 When limiting fields returned from the database via `Criteria#only` and `Criteria#without` and then subsequently saving the document. Default values no longer override excluded fields. ## 2.4.3 ### Resolved Issues * \#1647 DateTime serialization when already in UTC does not convert to local time. * \#1640 Update consumers should be tied to the name of the collection they persist to, not the name of the class. * \#1636 Scopes no longer modify parent class scopes when subclassing. (Hans Hasselberg) * \#1629 $all and $in criteria on embedded many relations now properly handles regex searches and elements of varying length. (Douwe Maan) * \#1623 Default scopes no longer break Mongoid::Versioning. (Hans Hasselberg) * \#1605 Fix regression of rescue responses, Rails 3.2 ## 2.4.2 ### Resolved Issues * \#1627 Validating format now works properly with localized fields. (Douwe Maan) * \#1617 Relation proxy methods now show up in Mongoid's list of prohibited fields. * \#1615 Allow a single configuration of host and port for all spec runs, overridden by setting MONGOID_SPEC_HOST and MONGOID_SPEC_PORT env vars. * \#1610 When versioning paranoid documents and max version is set, hard delete old versions from the embedded relation. * \#1609 Allow connection retry during cursor iteration as well as all other operations. * \#1608 Guard against no method errors when passing ids in nested attributes and the documents do not exist. * \#1605 Remove deprecation warning on rescue responses, Rails 3.2 * \#1602 Preserve structure of $and and $or queries when typecasting. * \#1600 Uniqueness validation no longer errors when provided a relation. * \#1599 Make sure enumerable targets yield to what is in memory first when performing #each, not always the unloaded first. * \#1597 Fix the ability to change the order of array fields with the same elements. * \#1590 Allow proper serialization of boolean values in criteria where the field is nested inside an array. ## 2.4.1 ### Resolved Issues * \#1593 Arrays on embedded documents now properly atomically update when modified from original version. * \#1592 Don't swallow exceptions from index generation in the create_indexes rake task. * \#1589 Allow assignment of empty array to HABTM when no documents are yet loaded into memory. * \#1587 When a previous value for an array field was an explicit nil, it can now be reset atomically with new values. * \#1585 `Model#respond_to?` returns true now for the setter when allowing dynamic fields. * \#1582 Allow nil values to be set in arrays. * \#1580 Allow arrays to be set to nil post save, and not just empty. * \#1579 Don't call #to_a on individual set field elements in criterion. * \#1576 Don't hit database on uniqueness validation if the field getting validated has not changed. * \#1571 Aliased fields get all the dirty attribute methods and all getters and setters for both the original name and the alias. (Hans Hasselberg) * \#1568 Fallback to development environment with warning when no env configured. * \#1565 For fields and foreign keys with non-standard Ruby or database names, use define_method instead of class_eval for creating the accessors and dirty methods. * \#1557 Internal strategy class no longer conflicts with models. * \#1551 Parent documents now return `true` for `Model#changed?` if only child (embedded) documents have changed. * \#1547 Resetting persisted children from a parent save when new waits until post callbacks, mirroring update functionality. * \#1536 Eager loading now happens when calling `first` or `last` on a criteria if inclusions are specified. ## 2.4.0 ### New Features * Ranges can now be passed to #where criteria to create a $gte/$lte query under the covers. `Person.where(dob: start_date...end_date)` * Custom serializable fields can now override #selection to provide customized serialization for criteria queries. * \#1544 Internals use `Array.wrap` instead of `to_a` now where possible. * \#1511 Presence validation now supports localized fields. (Tiago Rafael Godinho) * \#1506 `Model.set` will now accept false and nil values. (Marten Veldthuis) * \#1505 `Model.delete_all/destroy_all` now take either a :conditions hash or the attributes directly. * \#1504 `Model.recursively_embeds_many` now accepts a :cascade_callbacks option. (Pavel Pravosud) * \#1496 Mongoid now casts strings back to symbols for symbol fields that get saved as strings by another application. * \#1454, \#900 Associations now have an `after_build` callback that gets executed after `.build` or `build_` methods are called. (Jeffrey Jones, Ryan Townsend) * \#1451 Ranges can now be any range value, not just numbers. (aupajo) * \#1448 Localization is now used when sorting. (Hans Hasselberg) * \#1422 Mongoid raises an error at yaml load if no environment is found. (Tom Stuart) * \#1413 $not support added to criteria symbol methods. (Marc Weil) * \#1403 Added configuration option `scope_overwrite_exception` which defaults to false for raising an error when defining a named scope with the same name of an existing method. (Christoph Grabo) * \#1388 `model.add_to_set` now supports adding multiple values and performs an $addToSet with $each under the covers. (Christian Felder) * \#1387 Added `Model#cache_key` for use in Rails caching. (Seivan Heidari) * \#1380 Calling Model.find(id) will now properly convert to and from any type based on the type of the _id field. * \#1363 Added fallbacks and default support to localized fields, and added ability to get and set all translations at once. * \#1362 Aliased fields now properly typecast in criteria. * \#1337 Array fields, including HABTM many foreign keys now have smarter dirty checking and no longer perform a simple $set if the array has changed. If items have only been added to the array, it performs a $pushAll. If items have only been removed, it performs a $pullAll. If both additions and removals have occurred it performs a $set to avoid conflicting mods. ### Resolved Issues * Calling `Document#as_document` on a frozen document on Rubinius returns the attributes instead of nil. * \#1554 Split application of default values into proc/non-procs, where non-procs get executed immediately during instantiation, and procs get executed after all other values are set. * \#1553 Combinations of adding and removing values from an array use a $set on the current contents of the array, not the new values. * \#1546 Dirty changes should be returned in a hash with indifferent access. * \#1542 Eager loading now respects the options (ie skip, limit) provided to the criteria when fetch the associations. * \#1530 Don't duplicate added values to arrays via dirty tracking if the array is a foreign key field. * \#1529 Calling `unscoped` on relational associations now works properly. * \#1524 Allow access to relations in overridden field setters by pre-setting foreign key default values. * \#1523 Allow disabling of observers via `disable`. (Jonas Schneider) * \#1522 Fixed create indexes rake task for Rails 3.2. (Gray Manley) * \#1517 Fix Mongoid documents to properly work with RSpec's stub_model. (Tiago Rafael Godinho) * \#1516 Don't duplicate relational many documents on bind. * \#1515 Mongoid no longer attempts to serialize custom fields on complex criteria by default. * \#1503 Has many relation substitution now handles any kind of mix of existing and new docs. * \#1502 Nested attributes on embedded documents respects if the child is paranoid. * \#1497 Use provided message on failing uniqueness validation. (Justin Etheredge) * \#1491 Return nil when no default set on localized fields. (Tiago Rafael Godinho) * \#1483 Sending module includes at runtime which add new fields to a parent document, also have the fields added to subclasses. * \#1482 Applying new sorting options does not merge into previously chained criteria. (Gerad Suyderhoud) * \#1481 Fix invalid query when accessing many-to-many relations before defaults are set. * \#1480 Mongoid's internal serialized field types renamespaced to Internal in order to not conflict with ruby core classes in custom serializable types. * \#1479 Don't duplicate ids on many-to-many when using create or create! * \#1469 When extract_id returns nil, get the document out of the identity map by the criteria selector. * \#1467 Defining a field named metadata now properly raises an invalid field error. * \#1463 Batch insert consumers are now scoped to collection to avoid persistence of documents to other collections in callbacks going to the wrong place. * \#1462 Assigning has many relations via nested attribtues `*_attributes=` does not autosave the relation. * \#1461 Fixed serialization of foreign key fields in complex criteria not to escape the entire hash. * \#1458 Versioning no longer skips fields that have been protected from mass assignment. * \#1455, \#1456 Calling destroy on any document now temporarily marks it as flagged for destroy until the operation is complete. (Nader Akhnoukh) * \#1453 `Model#to_key` should return a value when the document is destroyed. * \#1449 New documents no longer get persisted when replaced on a has one as a side effect. (jasonsydes) * \#1439 embedded? should return true when relation defined as cyclic. * \#1433 Polymorphic nested attributes for embedded and relational 1-1 now update properly. * \#1426 Frozen documents can now be cloned. (aagrawal2001) * \#1382 Raise proper error when creating indexes via rake task if index definition is incorrect. (Mathieu Ravaux) * \#1381, \#1371 The identity map now functions properly with inherited documents. (Paul Canavese) * \#1370 Split concat on embedded arrays into its own method to handle the batch processing due to after callback run execution issues. * \#1366 Array and hash values now get deep copied for dirty tracking. * \#1359 Provide ability to not have default scope applied to all named scopes via using lambdas. * \#1333 Fixed errors with custom types that exist in namespaces. (Peter Gumeson) * \#1259 Default values are treated as dirty if they differ from the database state. * \#1255 Ensure embedded documents respect the defined default scope. ## 2.3.4 * \#1445 Prevent duplicate documents in the loaded array on the target enumerable for relational associations. * \#1442 When using create_ methods for has one relations, the appropriate destructive methods now get called when replacing an existing document. * \#1431 Enumerable context should add to the loaded array post yield, so that methods like #any? that short circuit based on the value of the block dont falsely have extra documents. * \#1418 Documents being loaded from the database for revision purposes no longer get placed in the identity map. * \#1399 Allow conversion of strings to integers in foreign keys where the id is defined as an int. * \#1397 Don't add default sorting criteria on first if they sort criteria already exists. * \#1394 Fix exists? to work when count is greater than 1. (Nick Hoffman) * \#1392 Return 0 on aggregation functions where field is nonexistant. * \#1391 Uniqueness validation now works properly on embedded documents that are using primary key definitions. * \#1390 When _type field is lower case class camelize before constantizing. * \#1383 Fix cast on read for serializable fields that are subclassed. * \#1357 Delayed atomic sets from update_attributes on embedded documents multiple levels deep now properly persist. * \#1326 Ensure base document on HABTM gets its keys saved after saving a newly build child document. * \#1301 Don't overwrite base metadata on embedded in relations if already set. * \#1221 HABTM with inverse nil is allowed again on embedded documents. * \#1208 Don't auto-persist child documents via the setter when setting from an embedded_in. * \#791 Root document updates its timestamps when only embedded documents have changed. ## 2.3.3 ### Resolved Issues * \#1386 Lowered mongo/bson dependency to 1.3 * \#1377 Fix aggregation functions to properly handle nil or indefined values. (Maxime Garcia) * \#1373 Warn if a scope overrides another scope. * \#1372 Never persist when binding inside of a read attribute for validation. * \#1364 Fixed reloading of documents with non bson object id ids. * \#1360 Fixed performance of Mongoid's observer instantiation by hooking into Active Support's load hooks, a la AR. * \#1358 Fixed type error on many to many synchronization when inverse_of is set to nil. * \#1356 $in criteria can now be chained to non-complex criteria on the same key without error. * \#1350, \#1351 Fixed errors in the string conversions of double quotes and tilde when paramterizing keys. * \#1349 Mongoid documents should not blow up when including Enumerable. (Jonas Nicklas) ## 2.3.2 ### Resolved Issues * \#1347 Fix embedded matchers when provided a hash value that does not have a modifier as a key. * \#1346 Dup default sorting criteria when calling first/last on a criteria. * \#1343 When passing no arguments to `Criteria#all_of` return all documents. (Chris Leishman) * \#1339 Ensure destroy callbacks are run on cascadable children when deleting via nested attributes. * \#1324 Setting `inverse_of: nil` on a many-to-many referencing the same class returns nil for the inverse foreign key. * \#1323 Allow both strings and symbols as ids in the attributes array for nested attributes. (Michael Wood) * \#1312 Setting a logger on the config now accepts anything that quacks like a logger. * \#1297 Don't hit the database when accessing relations if the base is new. * \#1239 Allow appending of referenced relations in create blocks, post default set. * \#1236 Ensure all models are loaded in rake tasks, so even in threadsafe mode all indexes can be created. * \#736 Calling #reload on embedded documents now works properly. ## 2.3.1 ### Resolved Issues * \#1338 Calling #find on a scope or relation checks that the document in the identity map actually matches other scope parameters. * \#1321 HABTM no longer allows duplicate entries or keys, instead of the previous inconsistencies. * \#1320 Fixed errors in perf benchmark. * \#1316 Added a separate Rake task "db:mongoid:drop" so Mongoid and AR can coexist. (Daniel Vartanov) * \#1311 Fix issue with custom field serialization inheriting from hash. * \#1310 The referenced many enumerable target no longer duplicates loaded and added documents when the identity map is enabled. * \#1295 Fixed having multiple includes only execute the eager loading of the first. * \#1287 Fixed max versions limitation with versioning. * \#1277 attribute_will_change! properly flags the attribute even if no change occured. * \#1063 Paranoid documents properly run destroy callbacks on soft destroy. * \#1061 Raise `Mongoid::Errors::InvalidTime` when time serialization fails. * \#1002 Check for legal bson ids when attempting conversion. * \#920 Allow relations to be named target. * \#905 Return normalized class name in metadata if string was defined with a prefixed ::. * \#861 accepts_nested_attributes_for is no longer needed to set embedded documents via a hash or array of hashes directly. * \#857 Fixed cascading of dependent relations when base document is paranoid. * \#768 Fixed class_attribute definitions module wide. * \#408 Embedded documents can now be soft deleted via `Mongoid::Paranoia`. ## 2.3.0 ### New Features * Mongoid now supports basic localized fields, storing them under the covers as a hash of locale => value pairs. `field :name, localize: true` * \#1275 For applications that default safe mode to true, you can now tell a single operation to persist without safe mode via #unsafely: `person.unsafely.save`, `Person.unsafely.create`. (Matt Sanders) * \#1256 Mongoid now can create indexes for models in Rails engines. (Caio Filipini) * \#1228 Allow pre formatting of compsoite keys by passing a block to #key. (Ben Hundley) * \#1222 Scoped mass assignment is now supported. (Andrew Shaydurov) * \#1196 Timestamps can now be turned off on a call-by-call basis via the use of #timeless: `person.timeless.save`, `Person.timeless.create(:title => "Sir")`. * \#1103 Allow developers to create their own custom complex criteria. (Ryan Ong) * Mongoid now includes all defined fields in `serializable_hash` and `to_json` results even if the fields have no values to make serialized documents easier to use by ActiveResource clients. * Support for MongoDB's $and operator is now available in the form of: `Criteria#all_of(*args)` where args is multiple hash expressions. * \#1250, \#1058 Embedded documents now can have their callbacks fired on a parent save by setting `:cascade_callbacks => true` on the relation. (pyromanic, Paul Rosania, Jak Charlton) ### Major Changes * Mongoid now depends on Active Model 3.1 and higher. * Mongoid now depends on the Mongo Ruby Driver 1.4 and higher. * Mongoid requires MongoDB 2.0.0 and higher. ### Resolved Issues * \#1308 Fixed scoping of HABTM finds. * \#1300 Namespaced models should handle recursive embedding properly. * \#1299 Self referenced documents with versioning no longer fail when inverse_of is not defined on all relations. * \#1296 Renamed internal building method to _building. * \#1288, \#1289 _id and updated_at should not be part of versioned attributes. * \#1273 Mongoid.preload_models now checks if preload configuration option is set, where Mongoid.load_models always loads everything. (Ryan McGeary) * \#1244 Has one relations now adhere to default dependant behaviour. * \#1225 Fixed delayed persistence of embedded documents via $set. * \#1166 Don't load config in Railtie if no env variables defined. (Terence Lee) * \#1052 `alias_attribute` now works again as expected. * \#939 Apply default attributes when upcasting via #becomes. (Christos Pappas) * \#932 Fixed casting of integer fields with leading zeros. * \#948 Reset version number on clone if versions existed. * \#763 Don't merge $in criteria arrays when chaining named scopes. * \#730 Existing models that have relations added post persistence of originals can now have new relations added with no migrations. * \#726 Embedded documents with compound keys not validate uniqueness correctly. * \#582 Cyclic non embedded relations now validate uniqueness correctly. * \#484 Validates uniqueness with multiple scopes of all types now work properly. * Deleting versions created with `Mongoid::Versioning` no longer fires off dependent cascading on relations. ## 2.2.5 * This was a small patch release to address 2.2.x Heroku errors during asset compilation. ## 2.2.4 * \#1377 Fix aggregation functions to properly handle nil or indefined values. (Maxime Garcia) * \#1373 Warn if a scope overrides another scope. * \#1372 Never persist when binding inside of a read attribute for validation. * \#1358 Fixed type error on many to many synchronization when inverse_of is set to nil. * \#1356 $in criteria can now be chained to non-complex criteria on the same key without error. * \#1350, \#1351 Fixed errors in the string conversions of double quotes and tilde when paramterizing keys. * \#1349 Mongoid documents should not blow up when including Enumerable. (Jonas Nicklas) ## 2.2.3 * \#1295 Fixed having multiple includes only execute the eager loading of the first. * \#1225 Fixed delayed persistence of embedded documents via $set. * \#1002 Fix BSON object id conversion to check if legal first. ## 2.2.2 * This release removes the restriction of a dependency on 1.3.x of the mongo ruby driver. Users may now use 1.3.x through 1.4.x. ## 2.2.1 ### Resolved Issues * \#1210, \#517 Allow embedded document relation queries to use dot notation. (Scott Ellard) * \#1198 Enumerable target should use criteria count if loaded has no docs. * \#1164 Get rid of remaining no method in_memory errors. * \#1070 Allow custom field serializers to have their own constructors. * \#1176 Allow access to parent documents from embedded docs in after_destroy callbacks. * \#1191 Context group methods (min, max, sum) no longer return NaN but instead return nil if field doesn't exist or have values. * \#1193, \#1271 Always return Integers for integer fields with .000 precisions, not floats. * \#1199 Fixed performance issues of hash and array field access when reading multiple times. * \#1218 Fixed issues with relations referencing models with integer foreign keys. * \#1219 Fixed various conflicting modifications issues when pushing and pulling from the same embedded document in a single call. * \#1220 Metadata should not get overwritten by nil on binding. * \#1231 Renamed Mongoid's atomic set class to Sets to avoid conflicts with Ruby's native Set after document inclusion. * \#1232 Fix access to related models during before_destroy callbacks when cascading. * \#1234 Fixed HABTM foreign key synchronization issues when destroying documents. * \#1243 Polymorphic relations dont convert to object ids when querying if the ids are defined as strings. * \#1247 Force Model.first to sort by ascending id to guarantee first document. * \#1248 Added #unscoped to embedded many relations. * \#1249 Destroy flags in nested attributes now actually destroy the document for has_many instead of just breaking the relation. * \#1272 Don't modify configuration options in place when creating replica set connections. ## 2.2.0 ### New Features * Mongoid now contains eager loading in the form of `Criteria#includes(*args)`. This works on has_one, has_many, belongs_to associations and requires the identity map to be enabled in order to function. Set `identity_map_enabled: true` in your `mongoid.yml`. Ex: `Person.where(title: "Sir").includes(:posts, :game)` * Relations can now take a module as a value to the `:extend` option. (Roman Shterenzon) * Capped collections can be created by passing the options to the `#store_in` macro: `Person.store_in :people, capped: true, max: 1000000` * Mongoid::Collection now supports `collection.find_and_modify` * `Document#has_attribute?` now aliases to `Document#attribute_present?` * \#930 You can now turn off the Mongoid logger via the mongoid.yml by doing `logger: false` * \#909 We now raise a `Mongoid::Errors::Callback` exception if persisting with a bang method and a callback returns false, instead of the uninformative validations error from before. ### Major Changes * \#1173 has_many relations no longer delete all documents on a set of the relation (= [ doc_one, doc_two ]) but look to the dependent option to determine what behaviour should occur. :delete and :destroy will behave as before, :nullify and no option specified will both nullify the old documents without deleting. * \#1142, \#767 Embedded relations no longer immediately persist atomically when accessed via a parent attributes set. This includes nested attributes setting and `attributes=` or `write_attributes`. The child changes then remain dirty and atomically update when save is called on them or the parent document. ### Resolved Issues * \#1190 Fixed the gemspec errors due to changing README and CHANGELOG to markdown. * \#1180, \#1084, \#955 Mongoid now checks the field types rather than if the name contains `/id/` when trying to convert to object ids on criteria. * \#1176 Enumerable targets should always return the in memory documents first, when calling `#first` * \#1175 Make sure both sides of many to many relations are in sync during a create. * \#1172 Referenced enumerable relations now properly handle `#to_json` (Daniel Doubrovkine) * \#1040 Increased performance of class load times by removing all delegate calls to self.class. ## 2.1.9 ### Resolved Issues * \#1159 Fixed build blocks not to cancel out each other when nested. * \#1154 Don't delete many-to-many documents on empty array set. * \#1153 Retain parent document reference in after callbacks. * \#1151 Fix associated validation infinite loop on self referencing documents. * \#1150 Validates associated on `belongs_to` is `false` by default. * \#1149 Fixed metadata setting on `belongs_to` relations. * \#1145 Metadata inverse should return `nil` if `inverse_of` was set as `nil`. * \#1139 Enumerable targets now quack like arrays. * \#1136 Setting `belongs_to` parent to `nil` no longer deletes the parent. * \#1120 Don't call `in_memory` on relations if they don't respond to it. * \#1075 Set `self` in default procs to the document instance. * \#1072 Writing attributes for nested documents can take a hash or array of hashes. * \#990 Embedded documents can use a single `embedded_in` with multiple parent definitions. ## 2.1.8 ### Resolved Issues * \#1148 Fixed `respond_to?` on all relations to return properly. * \#1146 Added back the Mongoid destructive fields check when defining fields. * \#1141 Fixed conversions of `nil` values in criteria. * \#1131 Verified Mongoid/Kaminari paginating correctly. * \#1105 Fixed atomic update consumer to be scoped to class. * \#1075 `self` in default lambdas and procs now references the document instance. * \#740 Removed `embedded_object_id` configuration parameter. * \#661 Fixed metadata caching on embedded documents. * \#595 Fixed relation reload flagging. * \#410 Moving documents from one relation to another now works as expected. ## 2.1.7 This was a specific release to fix MRI 1.8.7 breakages introduced by 2.1.6. ## 2.1.6 ### Resolved Issues * \#1126 Fix setting of relations with other relation proxies. * \#1122 Hash and array fields now properly flag as dirty on access and change. * \#656 Fixed reload breaking relations on unsetting of already loaded associations. * \#647 Prefer `#unset` to `#remove_attribute` for removing values. * \#290 Verify pushes into deeply embedded documents. ## 2.1.5 ### Resolved Issues * \#1116 Embedded children retain reference to parent in destroy callbacks. * \#1110, \#1115 Don't memoize metadata related helpers on documents. * \#1112 `db:create_indexes` no longer indexes subclasses multiple times. * \#1111, \#1098 Don't set `_id` in `$set` operations. * \#1007 Update attribute properly tracks array changes. ## 2.1.4 This was a specific release to get a Psych generated gemspec so no more parse errors would occur on those rubies that were using the new YAML parser. ## 2.1.3 ### Resolved Issues * \#1109 Fixed validations not loading one to ones into memory. * \#1107 Mongoid no longer wants required `mongoid/railtie` in `application.rb`. * \#1102 Fixed nested attributes deletion. * \#1097 Reload now runs `after_initialize` callbacks. * \#1079 Embeds many no longer duplicates documents. * \#1078 Fixed array criteria matching on embedded documents. * \#1028 Implement scoped on one-to-many and many-to-many relations. * \#988 Many-to-many clear no longer deletes the child documents. * \#977 Autosaving relations works also through nested attributes. * \#972 Recursive embedding now handles namespacing on generated names. * \#943 Don't override `Document#attributes`. * \#893 Verify count is not caching on many to many relations. * \#815 Verify `after_initialize` is run in the correct place. * \#793 Verify `any_of` scopes chain properly with any other scope. * \#776 Fixed mongoid case quality when dealing with subclasses. * \#747 Fixed complex criteria using its keys to render its string value. * \#721 `#safely` now properly raises validation errors when they occur. ## 2.1.2 ### Resolved Issues * \#1082 Alias `size` and `length` to `count` on criteria. (Adam Greene) * \#1044 When multiple relations are defined for the same class, always return the default inverse first if `inverse_of` is not defined. * \#710 Nested attributes accept both `id` and `_id` in hashes or arrays. * \#1047 Ignore `nil` values passed to `embeds_man` pushes and substitution. (Derick Bailey) ## 2.1.1 ### Resolved Issues * \#1021, \#719 Many to many relations dont trigger extra database queries when pushing new documents. * \#607 Calling `create` on large associations does not load the entire relation. * \#1064 `Mongoid::Paranoia` should respect `unscoped` and `scoped`. * \#1026 `model#update_attribute` now can update booleans to `false`. * \#618 Crack XML library breaks Mongoid by adding `#attributes` method to the `String` class. (Stephen McGinty) ## 2.1.0 ### Major Changes * Mongoid now requires MongoDB 1.8.x in order to properly support the `#bit` and `#rename` atomic operations. * Traditional slave support has been removed from Mongoid. Replica sets should be used in place of traditional master and slave setups. * Custom field serialization has changed. Please see [serializable](https://github.com/mongoid/mongoid/blob/master/lib/mongoid/fields/serializable.rb) for changes. * The dirty attribute tracking has been switched to use ActiveModel, this brings many bug fixes and changes: * \#756 After callbacks and observers see what was changed instead of changes just made being in previous_changes * \#434 Documents now are flagged as dirty when brand new or the state on instantiation differs from the database state. This is consistent with ActiveRecord. * \#323 Mongoid now supports [field]_will_change! from ActiveModel::Dirty * Mongoid model preloading in development mode now defaults to `false`. * `:autosave => true` on relational associations now saves on update as well as create. * Mongoid now has an identity map for simple `find_by_id` queries. See the website for documentation. ### New Features * \#1067 Fields now accept a `:versioned` attribute to be able to disable what fields are versioned with `Mongoid::Versioning`. (Jim Benton) * \#587 Added order preference to many and many to many associations. (Gregory Man) * Added ability to chain `order_by` statements. (Gregory Man) * \#961 Allow arbitrary `Mongo::Connection` options to pass through `Mongoid::Config::Database` object. (Morgan Nelson) * Enable `autosave` for many to many references. (Dave Krupinski) * The following explicit atomic operations have been added: `Model#bit`, `Model#pop`, `Model#pull`, `Model#push_all`, `Model#rename`, `Model#unset`. * Added exception translations for Hindi. (Sukeerthi Adiga) ### Resolved Issues * \#974 Fix `attribute_present?` to work correctly then attribute value is `false`, thanks to @nickhoffman. (Gregory Man) * \#960 create indexes rake task is not recognizing a lot of mongoid models because it has problems guessing their model names from filenames. (Tobias Schlottke) * \#874 Deleting from a M-M reference is one-sided. (nickhoffman, davekrupinski) * Replace deprecated `class_inheritable_hash` dropped in Rails 3.1+. (Konstantin Shabanov) * Fix inconsistent state when replacing an entire many to many relation. * Don't clobber inheritable attributes when adding subclass field inheritance. (Dave Krupinski) * \#914 Querying embedded documents with `$or` selector. (Max Golovnia) * \#514 Fix marshaling of documents with relation extensions. (Chris Griego) * `Metadata#extension` now returns a `Module`, instead of a `Proc`, when an extension is defined. * \#837 When `allow_dynamic_fields` is set to `false` and loading an embedded document with an unrecognized field, an exception is raised. * \#963 Initializing array of embedded documents via hash regressed (Chris Griego, Morgan Nelson) * `Mongoid::Config.reset` resets the options to their default values. * `Mongoid::Fields.defaults` is memoized for faster instantiation of models.
apache-2.0
jaredly/pyjamas
library/pyjamas/dnd/util/CoordinateLocation.py
1133
""" * Copyright 2007 Fred Sauer * * 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. """ import AbstractLocation """* * A position represented by a left (x) and top (y) coordinate. """ class CoordinateLocation(AbstractLocation): def __init__(self, left, top): self.left = left self.top = top """ * (non-Javadoc) * * @see com.allen_sauer.gwt.dnd.client.util.Location#getLeft() """ def getLeft(self): return left """ * (non-Javadoc) * * @see com.allen_sauer.gwt.dnd.client.util.Location#getTop() """ def getTop(self): return top
apache-2.0
tanvirehsan/TreeConstructionFromQuartets
TreeConstructionFromQuartets/Model/PartitionSet.cs
4522
namespace TreeConstructionFromQuartets.Model { using System; using System.Collections.Generic; using System.Linq; public class PartitionSet { public PartitionSet(string PartitionSetName) { this._PartitionSetName = PartitionSetName; this._Final_Score = 0; this._IsolatedCount = 0; this._ViotatedCount = 0; this._SatisfiedCount = 0; this._DifferedCount = 0; this._taxValueForGainCalculation = string.Empty; this._Gain = 0; this.PartitionList = new List<Partition>(); this._ListQuatrets = new List<Quartet>(); } public PartitionSet(string PartitionSetName, int _Final_Score, int _IsolatedCount, int _ViotatedCount, int _SatisfiedCount, int _DifferedCount, string _taxValueForGainCalculation, int _Gain, List<Partition> PartitionList, List<Quartet> _ListQuatrets) { this._PartitionSetName = PartitionSetName; this._Final_Score = _Final_Score; this._IsolatedCount = _IsolatedCount; this._ViotatedCount = _ViotatedCount; this._SatisfiedCount = _SatisfiedCount; this._DifferedCount = _DifferedCount; this._taxValueForGainCalculation = _taxValueForGainCalculation; this._Gain = _Gain; this.PartitionList = new List<Partition>(PartitionList.Select(x => new Partition(x._PartitionName) { _PartitionName = x._PartitionName, TaxaList = new List<Taxa>(x.TaxaList.Select(m => new Taxa() { _Taxa_Value = m._Taxa_Value, _Quartet_Name = m._Quartet_Name, _Taxa_ValuePosition_In_Quartet = m._Taxa_ValuePosition_In_Quartet, _Gain = m._Gain, _CumulativeGain = m._CumulativeGain, IsFreeze = m.IsFreeze, _IsolatedCount = m._IsolatedCount, _ViotatedCount = m._ViotatedCount, _DifferedCount = m._DifferedCount, _SatisfiedCount = m._SatisfiedCount, _TaxaPartitionSet = m._TaxaPartitionSet != null ? new PartitionSet(m._TaxaPartitionSet._PartitionSetName, m._TaxaPartitionSet._Final_Score, m._TaxaPartitionSet._IsolatedCount, m._TaxaPartitionSet._ViotatedCount, m._TaxaPartitionSet._SatisfiedCount, m._TaxaPartitionSet._DifferedCount, m._TaxaPartitionSet._taxValueForGainCalculation, m._TaxaPartitionSet._Gain, m._TaxaPartitionSet.PartitionList, m._TaxaPartitionSet._ListQuatrets) : null, StepK = m.StepK })) })); this._ListQuatrets = new List<Quartet>(_ListQuatrets.Select(x => new Quartet() { _First_Taxa_Value = x._First_Taxa_Value, _Second_Taxa_Value = x._Second_Taxa_Value, _Third_Taxa_Value = x._Third_Taxa_Value, _Fourth_Taxa_Value = x._Fourth_Taxa_Value, _Quartet_Name = x._Quartet_Name, _Quartet_Input = x._Quartet_Input, _Quartet_LeftPart = x._Quartet_LeftPart, _Quartet_LeftPartReverse = x._Quartet_LeftPartReverse, _Quartet_RightPart = x._Quartet_RightPart, _Quartet_RightPartReverse = x._Quartet_RightPartReverse, _isDistinct = x._isDistinct, _Frequency = x._Frequency, _DuplicateQuatrets = x._DuplicateQuatrets, _PartitionStatus = x._PartitionStatus, _ConsistancyStatus = x._ConsistancyStatus, _TaxaSplitLeft = x._TaxaSplitLeft, _TaxaSplitRight = x._TaxaSplitRight })); } public string _PartitionSetName { get; set; } public string _taxValueForGainCalculation { get; set; } public int _Gain { get; set; } public int _Final_Score { get; set; } public int _IsolatedCount { get; set; } public int _ViotatedCount { get; set; } public int _DifferedCount { get; set; } public int _SatisfiedCount { get; set; } public List<Quartet> _ListQuatrets { get; set; } private List<Partition> _PartitionList = new List<Partition>(); public List<Partition> PartitionList { get { return _PartitionList; } set { _PartitionList = value; } } } }
apache-2.0
googleapis/google-api-ruby-client
google-api-client/generated/google/apis/securitycenter_v1beta1/service.rb
66146
# Copyright 2015 Google Inc. # # 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. require 'google/apis/core/base_service' require 'google/apis/core/json_representation' require 'google/apis/core/hashable' require 'google/apis/errors' module Google module Apis module SecuritycenterV1beta1 # Security Command Center API # # Security Command Center API provides access to temporal views of assets and # findings within an organization. # # @example # require 'google/apis/securitycenter_v1beta1' # # Securitycenter = Google::Apis::SecuritycenterV1beta1 # Alias the module # service = Securitycenter::SecurityCommandCenterService.new # # @see https://console.cloud.google.com/apis/api/securitycenter.googleapis.com/overview class SecurityCommandCenterService < Google::Apis::Core::BaseService # @return [String] # API key. Your API key identifies your project and provides you with API access, # quota, and reports. Required unless you provide an OAuth 2.0 token. attr_accessor :key # @return [String] # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. attr_accessor :quota_user def initialize super('https://securitycenter.googleapis.com/', '') @batch_path = 'batch' end # Gets the settings for an organization. # @param [String] name # Required. Name of the organization to get organization settings for. Its # format is "organizations/[organization_id]/organizationSettings". # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::OrganizationSettings] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::OrganizationSettings] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_organization_organization_settings(name, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1beta1/{+name}', options) command.response_representation = Google::Apis::SecuritycenterV1beta1::OrganizationSettings::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::OrganizationSettings command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Updates an organization's settings. # @param [String] name # The relative resource name of the settings. See: https://cloud.google.com/apis/ # design/resource_names#relative_resource_name Example: "organizations/` # organization_id`/organizationSettings". # @param [Google::Apis::SecuritycenterV1beta1::OrganizationSettings] organization_settings_object # @param [String] update_mask # The FieldMask to use when updating the settings resource. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::OrganizationSettings] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::OrganizationSettings] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def update_organization_organization_settings(name, organization_settings_object = nil, update_mask: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:patch, 'v1beta1/{+name}', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::OrganizationSettings::Representation command.request_object = organization_settings_object command.response_representation = Google::Apis::SecuritycenterV1beta1::OrganizationSettings::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::OrganizationSettings command.params['name'] = name unless name.nil? command.query['updateMask'] = update_mask unless update_mask.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Filters an organization's assets and groups them by their specified properties. # @param [String] parent # Required. Name of the organization to groupBy. Its format is "organizations/[ # organization_id]". # @param [Google::Apis::SecuritycenterV1beta1::GroupAssetsRequest] group_assets_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::GroupAssetsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::GroupAssetsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def group_assets(parent, group_assets_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1beta1/{+parent}/assets:group', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::GroupAssetsRequest::Representation command.request_object = group_assets_request_object command.response_representation = Google::Apis::SecuritycenterV1beta1::GroupAssetsResponse::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::GroupAssetsResponse command.params['parent'] = parent unless parent.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Lists an organization's assets. # @param [String] parent # Required. Name of the organization assets should belong to. Its format is " # organizations/[organization_id]". # @param [String] compare_duration # When compare_duration is set, the ListAssetResult's "state" attribute is # updated to indicate whether the asset was added, removed, or remained present # during the compare_duration period of time that precedes the read_time. This # is the time between (read_time - compare_duration) and read_time. The state # value is derived based on the presence of the asset at the two points in time. # Intermediate state changes between the two times don't affect the result. For # example, the results aren't affected if the asset is removed and re-created # again. Possible "state" values when compare_duration is specified: * "ADDED": # indicates that the asset was not present before compare_duration, but present # at read_time. * "REMOVED": indicates that the asset was present at the start # of compare_duration, but not present at read_time. * "ACTIVE": indicates that # the asset was present at both the start and the end of the time period defined # by compare_duration and read_time. If compare_duration is not specified, then # the only possible state is "UNUSED", which indicates that the asset is present # at read_time. # @param [String] field_mask # Optional. A field mask to specify the ListAssetsResult fields to be listed in # the response. An empty field mask will list all fields. # @param [String] filter # Expression that defines the filter to apply across assets. The expression is a # list of zero or more restrictions combined via logical operators `AND` and `OR` # . Parentheses are not supported, and `OR` has higher precedence than `AND`. # Restrictions have the form ` ` and may have a `-` character in front of them # to indicate negation. The fields map to those defined in the Asset resource. # Examples include: * name * security_center_properties.resource_name * # resource_properties.a_property * security_marks.marks.marka The supported # operators are: * `=` for all value types. * `>`, `<`, `>=`, `<=` for integer # values. * `:`, meaning substring matching, for strings. The supported value # types are: * string literals in quotes. * integer literals without quotes. * # boolean literals `true` and `false` without quotes. For example, ` # resource_properties.size = 100` is a valid filter string. # @param [String] order_by # Expression that defines what fields and order to use for sorting. The string # value should follow SQL syntax: comma separated list of fields. For example: " # name,resource_properties.a_property". The default sorting order is ascending. # To specify descending order for a field, a suffix " desc" should be appended # to the field name. For example: "name desc,resource_properties.a_property". # Redundant space characters in the syntax are insignificant. "name desc, # resource_properties.a_property" and " name desc , resource_properties. # a_property " are equivalent. # @param [Fixnum] page_size # The maximum number of results to return in a single response. Default is 10, # minimum is 1, maximum is 1000. # @param [String] page_token # The value returned by the last `ListAssetsResponse`; indicates that this is a # continuation of a prior `ListAssets` call, and that the system should return # the next page of data. # @param [String] read_time # Time used as a reference point when filtering assets. The filter is limited to # assets existing at the supplied time and their values are those at that # specific time. Absence of this field will default to the API's version of NOW. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::ListAssetsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::ListAssetsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_organization_assets(parent, compare_duration: nil, field_mask: nil, filter: nil, order_by: nil, page_size: nil, page_token: nil, read_time: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1beta1/{+parent}/assets', options) command.response_representation = Google::Apis::SecuritycenterV1beta1::ListAssetsResponse::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::ListAssetsResponse command.params['parent'] = parent unless parent.nil? command.query['compareDuration'] = compare_duration unless compare_duration.nil? command.query['fieldMask'] = field_mask unless field_mask.nil? command.query['filter'] = filter unless filter.nil? command.query['orderBy'] = order_by unless order_by.nil? command.query['pageSize'] = page_size unless page_size.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['readTime'] = read_time unless read_time.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Runs asset discovery. The discovery is tracked with a long-running operation. # This API can only be called with limited frequency for an organization. If it # is called too frequently the caller will receive a TOO_MANY_REQUESTS error. # @param [String] parent # Required. Name of the organization to run asset discovery for. Its format is " # organizations/[organization_id]". # @param [Google::Apis::SecuritycenterV1beta1::RunAssetDiscoveryRequest] run_asset_discovery_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::Operation] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::Operation] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def run_organization_asset_discovery(parent, run_asset_discovery_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1beta1/{+parent}/assets:runDiscovery', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::RunAssetDiscoveryRequest::Representation command.request_object = run_asset_discovery_request_object command.response_representation = Google::Apis::SecuritycenterV1beta1::Operation::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::Operation command.params['parent'] = parent unless parent.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Updates security marks. # @param [String] name # The relative resource name of the SecurityMarks. See: https://cloud.google.com/ # apis/design/resource_names#relative_resource_name Examples: "organizations/` # organization_id`/assets/`asset_id`/securityMarks" "organizations/` # organization_id`/sources/`source_id`/findings/`finding_id`/securityMarks". # @param [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks] google_cloud_securitycenter_v1beta1_security_marks_object # @param [String] start_time # The time at which the updated SecurityMarks take effect. # @param [String] update_mask # The FieldMask to use when updating the security marks resource. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def update_organization_asset_security_marks(name, google_cloud_securitycenter_v1beta1_security_marks_object = nil, start_time: nil, update_mask: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:patch, 'v1beta1/{+name}', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks::Representation command.request_object = google_cloud_securitycenter_v1beta1_security_marks_object command.response_representation = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks command.params['name'] = name unless name.nil? command.query['startTime'] = start_time unless start_time.nil? command.query['updateMask'] = update_mask unless update_mask.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Starts asynchronous cancellation on a long-running operation. The server makes # a best effort to cancel the operation, but success is not guaranteed. If the # server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. # Clients can use Operations.GetOperation or other methods to check whether the # cancellation succeeded or whether the operation completed despite cancellation. # On successful cancellation, the operation is not deleted; instead, it becomes # an operation with an Operation.error value with a google.rpc.Status.code of 1, # corresponding to `Code.CANCELLED`. # @param [String] name # The name of the operation resource to be cancelled. # @param [Google::Apis::SecuritycenterV1beta1::CancelOperationRequest] cancel_operation_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::Empty] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::Empty] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def cancel_operation(name, cancel_operation_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1beta1/{+name}:cancel', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::CancelOperationRequest::Representation command.request_object = cancel_operation_request_object command.response_representation = Google::Apis::SecuritycenterV1beta1::Empty::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::Empty command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Deletes a long-running operation. This method indicates that the client is no # longer interested in the operation result. It does not cancel the operation. # If the server doesn't support this method, it returns `google.rpc.Code. # UNIMPLEMENTED`. # @param [String] name # The name of the operation resource to be deleted. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::Empty] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::Empty] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def delete_organization_operation(name, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:delete, 'v1beta1/{+name}', options) command.response_representation = Google::Apis::SecuritycenterV1beta1::Empty::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::Empty command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Gets the latest state of a long-running operation. Clients can use this method # to poll the operation result at intervals as recommended by the API service. # @param [String] name # The name of the operation resource. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::Operation] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::Operation] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_organization_operation(name, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1beta1/{+name}', options) command.response_representation = Google::Apis::SecuritycenterV1beta1::Operation::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::Operation command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Lists operations that match the specified filter in the request. If the server # doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` # binding allows API services to override the binding to use different resource # name schemes, such as `users/*/operations`. To override the binding, API # services can add a binding such as `"/v1/`name=users/*`/operations"` to their # service configuration. For backwards compatibility, the default name includes # the operations collection id, however overriding users must ensure the name # binding is the parent resource, without the operations collection id. # @param [String] name # The name of the operation's parent resource. # @param [String] filter # The standard list filter. # @param [Fixnum] page_size # The standard list page size. # @param [String] page_token # The standard list page token. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::ListOperationsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::ListOperationsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_organization_operations(name, filter: nil, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1beta1/{+name}', options) command.response_representation = Google::Apis::SecuritycenterV1beta1::ListOperationsResponse::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::ListOperationsResponse command.params['name'] = name unless name.nil? command.query['filter'] = filter unless filter.nil? command.query['pageSize'] = page_size unless page_size.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Creates a source. # @param [String] parent # Required. Resource name of the new source's parent. Its format should be " # organizations/[organization_id]". # @param [Google::Apis::SecuritycenterV1beta1::Source] source_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::Source] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::Source] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def create_organization_source(parent, source_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1beta1/{+parent}/sources', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::Source::Representation command.request_object = source_object command.response_representation = Google::Apis::SecuritycenterV1beta1::Source::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::Source command.params['parent'] = parent unless parent.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Gets a source. # @param [String] name # Required. Relative resource name of the source. Its format is "organizations/[ # organization_id]/source/[source_id]". # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::Source] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::Source] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_organization_source(name, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1beta1/{+name}', options) command.response_representation = Google::Apis::SecuritycenterV1beta1::Source::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::Source command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Gets the access control policy on the specified Source. # @param [String] resource # REQUIRED: The resource for which the policy is being requested. See the # operation documentation for the appropriate value for this field. # @param [Google::Apis::SecuritycenterV1beta1::GetIamPolicyRequest] get_iam_policy_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::Policy] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::Policy] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_source_iam_policy(resource, get_iam_policy_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1beta1/{+resource}:getIamPolicy', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::GetIamPolicyRequest::Representation command.request_object = get_iam_policy_request_object command.response_representation = Google::Apis::SecuritycenterV1beta1::Policy::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::Policy command.params['resource'] = resource unless resource.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Lists all sources belonging to an organization. # @param [String] parent # Required. Resource name of the parent of sources to list. Its format should be # "organizations/[organization_id]". # @param [Fixnum] page_size # The maximum number of results to return in a single response. Default is 10, # minimum is 1, maximum is 1000. # @param [String] page_token # The value returned by the last `ListSourcesResponse`; indicates that this is a # continuation of a prior `ListSources` call, and that the system should return # the next page of data. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::ListSourcesResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::ListSourcesResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_organization_sources(parent, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1beta1/{+parent}/sources', options) command.response_representation = Google::Apis::SecuritycenterV1beta1::ListSourcesResponse::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::ListSourcesResponse command.params['parent'] = parent unless parent.nil? command.query['pageSize'] = page_size unless page_size.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Updates a source. # @param [String] name # The relative resource name of this source. See: https://cloud.google.com/apis/ # design/resource_names#relative_resource_name Example: "organizations/` # organization_id`/sources/`source_id`" # @param [Google::Apis::SecuritycenterV1beta1::Source] source_object # @param [String] update_mask # The FieldMask to use when updating the source resource. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::Source] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::Source] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def patch_organization_source(name, source_object = nil, update_mask: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:patch, 'v1beta1/{+name}', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::Source::Representation command.request_object = source_object command.response_representation = Google::Apis::SecuritycenterV1beta1::Source::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::Source command.params['name'] = name unless name.nil? command.query['updateMask'] = update_mask unless update_mask.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Sets the access control policy on the specified Source. # @param [String] resource # REQUIRED: The resource for which the policy is being specified. See the # operation documentation for the appropriate value for this field. # @param [Google::Apis::SecuritycenterV1beta1::SetIamPolicyRequest] set_iam_policy_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::Policy] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::Policy] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def set_source_iam_policy(resource, set_iam_policy_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1beta1/{+resource}:setIamPolicy', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::SetIamPolicyRequest::Representation command.request_object = set_iam_policy_request_object command.response_representation = Google::Apis::SecuritycenterV1beta1::Policy::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::Policy command.params['resource'] = resource unless resource.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Returns the permissions that a caller has on the specified source. # @param [String] resource # REQUIRED: The resource for which the policy detail is being requested. See the # operation documentation for the appropriate value for this field. # @param [Google::Apis::SecuritycenterV1beta1::TestIamPermissionsRequest] test_iam_permissions_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::TestIamPermissionsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::TestIamPermissionsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def test_source_iam_permissions(resource, test_iam_permissions_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1beta1/{+resource}:testIamPermissions', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::TestIamPermissionsRequest::Representation command.request_object = test_iam_permissions_request_object command.response_representation = Google::Apis::SecuritycenterV1beta1::TestIamPermissionsResponse::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::TestIamPermissionsResponse command.params['resource'] = resource unless resource.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Creates a finding. The corresponding source must exist for finding creation to # succeed. # @param [String] parent # Required. Resource name of the new finding's parent. Its format should be " # organizations/[organization_id]/sources/[source_id]". # @param [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding] google_cloud_securitycenter_v1beta1_finding_object # @param [String] finding_id # Required. Unique identifier provided by the client within the parent scope. It # must be alphanumeric and less than or equal to 32 characters and greater than # 0 characters in length. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def create_organization_source_finding(parent, google_cloud_securitycenter_v1beta1_finding_object = nil, finding_id: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1beta1/{+parent}/findings', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding::Representation command.request_object = google_cloud_securitycenter_v1beta1_finding_object command.response_representation = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding command.params['parent'] = parent unless parent.nil? command.query['findingId'] = finding_id unless finding_id.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Filters an organization or source's findings and groups them by their # specified properties. To group across all sources provide a `-` as the source # id. Example: /v1beta1/organizations/`organization_id`/sources/-/findings # @param [String] parent # Required. Name of the source to groupBy. Its format is "organizations/[ # organization_id]/sources/[source_id]". To groupBy across all sources provide a # source_id of `-`. For example: organizations/`organization_id`/sources/- # @param [Google::Apis::SecuritycenterV1beta1::GroupFindingsRequest] group_findings_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::GroupFindingsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::GroupFindingsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def group_findings(parent, group_findings_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1beta1/{+parent}/findings:group', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::GroupFindingsRequest::Representation command.request_object = group_findings_request_object command.response_representation = Google::Apis::SecuritycenterV1beta1::GroupFindingsResponse::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::GroupFindingsResponse command.params['parent'] = parent unless parent.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Lists an organization or source's findings. To list across all sources provide # a `-` as the source id. Example: /v1beta1/organizations/`organization_id`/ # sources/-/findings # @param [String] parent # Required. Name of the source the findings belong to. Its format is " # organizations/[organization_id]/sources/[source_id]". To list across all # sources provide a source_id of `-`. For example: organizations/` # organization_id`/sources/- # @param [String] field_mask # Optional. A field mask to specify the Finding fields to be listed in the # response. An empty field mask will list all fields. # @param [String] filter # Expression that defines the filter to apply across findings. The expression is # a list of one or more restrictions combined via logical operators `AND` and ` # OR`. Parentheses are not supported, and `OR` has higher precedence than `AND`. # Restrictions have the form ` ` and may have a `-` character in front of them # to indicate negation. Examples include: * name * source_properties.a_property * # security_marks.marks.marka The supported operators are: * `=` for all value # types. * `>`, `<`, `>=`, `<=` for integer values. * `:`, meaning substring # matching, for strings. The supported value types are: * string literals in # quotes. * integer literals without quotes. * boolean literals `true` and ` # false` without quotes. For example, `source_properties.size = 100` is a valid # filter string. # @param [String] order_by # Expression that defines what fields and order to use for sorting. The string # value should follow SQL syntax: comma separated list of fields. For example: " # name,resource_properties.a_property". The default sorting order is ascending. # To specify descending order for a field, a suffix " desc" should be appended # to the field name. For example: "name desc,source_properties.a_property". # Redundant space characters in the syntax are insignificant. "name desc, # source_properties.a_property" and " name desc , source_properties.a_property " # are equivalent. # @param [Fixnum] page_size # The maximum number of results to return in a single response. Default is 10, # minimum is 1, maximum is 1000. # @param [String] page_token # The value returned by the last `ListFindingsResponse`; indicates that this is # a continuation of a prior `ListFindings` call, and that the system should # return the next page of data. # @param [String] read_time # Time used as a reference point when filtering findings. The filter is limited # to findings existing at the supplied time and their values are those at that # specific time. Absence of this field will default to the API's version of NOW. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::ListFindingsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::ListFindingsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_organization_source_findings(parent, field_mask: nil, filter: nil, order_by: nil, page_size: nil, page_token: nil, read_time: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1beta1/{+parent}/findings', options) command.response_representation = Google::Apis::SecuritycenterV1beta1::ListFindingsResponse::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::ListFindingsResponse command.params['parent'] = parent unless parent.nil? command.query['fieldMask'] = field_mask unless field_mask.nil? command.query['filter'] = filter unless filter.nil? command.query['orderBy'] = order_by unless order_by.nil? command.query['pageSize'] = page_size unless page_size.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['readTime'] = read_time unless read_time.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Creates or updates a finding. The corresponding source must exist for a # finding creation to succeed. # @param [String] name # The relative resource name of this finding. See: https://cloud.google.com/apis/ # design/resource_names#relative_resource_name Example: "organizations/` # organization_id`/sources/`source_id`/findings/`finding_id`" # @param [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding] google_cloud_securitycenter_v1beta1_finding_object # @param [String] update_mask # The FieldMask to use when updating the finding resource. This field should not # be specified when creating a finding. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def patch_organization_source_finding(name, google_cloud_securitycenter_v1beta1_finding_object = nil, update_mask: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:patch, 'v1beta1/{+name}', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding::Representation command.request_object = google_cloud_securitycenter_v1beta1_finding_object command.response_representation = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding command.params['name'] = name unless name.nil? command.query['updateMask'] = update_mask unless update_mask.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Updates the state of a finding. # @param [String] name # Required. The relative resource name of the finding. See: https://cloud.google. # com/apis/design/resource_names#relative_resource_name Example: "organizations/` # organization_id`/sources/`source_id`/finding/`finding_id`". # @param [Google::Apis::SecuritycenterV1beta1::SetFindingStateRequest] set_finding_state_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def set_organization_source_finding_state(name, set_finding_state_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1beta1/{+name}:setState', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::SetFindingStateRequest::Representation command.request_object = set_finding_state_request_object command.response_representation = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Updates security marks. # @param [String] name # The relative resource name of the SecurityMarks. See: https://cloud.google.com/ # apis/design/resource_names#relative_resource_name Examples: "organizations/` # organization_id`/assets/`asset_id`/securityMarks" "organizations/` # organization_id`/sources/`source_id`/findings/`finding_id`/securityMarks". # @param [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks] google_cloud_securitycenter_v1beta1_security_marks_object # @param [String] start_time # The time at which the updated SecurityMarks take effect. # @param [String] update_mask # The FieldMask to use when updating the security marks resource. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def update_organization_source_finding_security_marks(name, google_cloud_securitycenter_v1beta1_security_marks_object = nil, start_time: nil, update_mask: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:patch, 'v1beta1/{+name}', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks::Representation command.request_object = google_cloud_securitycenter_v1beta1_security_marks_object command.response_representation = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks command.params['name'] = name unless name.nil? command.query['startTime'] = start_time unless start_time.nil? command.query['updateMask'] = update_mask unless update_mask.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end protected def apply_command_defaults(command) command.query['key'] = key unless key.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? end end end end end
apache-2.0
ArcherCraftStore/ArcherVMPeridot
apps/owncloud/htdocs/apps/calendar/l10n/da.php
7568
<?php $TRANSLATIONS = array( "Not all calendars are completely cached" => "Ikke alle kalendere er fuldstændig cached", "Everything seems to be completely cached" => "Alt ser ud til at være cached", "No calendars found." => "Der blev ikke fundet nogen kalendere.", "No events found." => "Der blev ikke fundet nogen begivenheder.", "Wrong calendar" => "Forkert kalender", "You do not have the permissions to edit this event." => "Du har ikke rettigheder til at redigere denne begivenhed.", "The file contained either no events or all events are already saved in your calendar." => "Enten indeholdt filen ingen begivenheder, eller også er alle begivenheder allerede gemt i din kalender.", "events has been saved in the new calendar" => "begivenheder er gemt i den nye kalender", "Import failed" => "Import mislykkedes", "events has been saved in your calendar" => "begivenheder er gemt i din kalender", "New Timezone:" => "Ny tidszone:", "Timezone changed" => "Tidszone ændret", "Invalid request" => "Ugyldig forespørgsel", "Calendar" => "Kalender", "Deletion failed" => "Fejl ved sletning", "ddd d MMMM[ yyyy]{ - [ddd d] MMMM yyyy}" => "ddd d MMMM[ yyyy]{ - [ddd d] MMMM yyyy}", "ddd d MMMM[ yyyy] HH:mm{ - [ ddd d MMMM yyyy] HH:mm}" => "ddd d MMMM[ yyyy] HH:mm{ - [ ddd d MMMM yyyy] HH:mm}", "group" => "gruppe", "can edit" => "kan redigere", "ddd" => "ddd", "ddd M/d" => "ddd M/d", "dddd M/d" => "dddd M/d", "MMMM yyyy" => "MMMM yyyy", "MMM d[ yyyy]{ '–'[ MMM] d yyyy}" => "MMM d[ yyyy]{ '–'[ MMM] d yyyy}", "dddd, MMM d, yyyy" => "dddd, MMM d, yyyy", "Sunday" => "Søndag", "Monday" => "Mandag", "Tuesday" => "Tirsdag", "Wednesday" => "Onsdag", "Thursday" => "Torsdag", "Friday" => "Fredag", "Saturday" => "Lørdag", "Sun." => "Søn.", "Mon." => "Man.", "Tue." => "Tir.", "Wed." => "Ons.", "Thu." => "Tor.", "Fri." => "Fre.", "Sat." => "Lør.", "January" => "Januar", "February" => "Februar", "March" => "Marts", "April" => "April", "May" => "Maj", "June" => "Juni", "July" => "Juli", "August" => "August", "September" => "September", "October" => "Oktober", "November" => "November", "December" => "December", "Jan." => "Jan.", "Feb." => "Feb.", "Mar." => "Mar.", "Apr." => "Apr.", "May." => "Maj", "Jun." => "Jun.", "Jul." => "Jul.", "Aug." => "Aug.", "Sep." => "Sep.", "Oct." => "Okt.", "Nov." => "Nov.", "Dec." => "Dec.", "All day" => "Hele dagen", "New Calendar" => "Ny kalender", "Missing or invalid fields" => "Manglende eller ugyldige felter", "Title" => "Titel", "From Date" => "Fra dato", "From Time" => "Fra tidspunkt", "To Date" => "Til dato", "To Time" => "Til tidspunkt", "The event ends before it starts" => "Begivenheden slutter, inden den begynder", "There was a database fail" => "Der var en fejl i databasen", "Birthday" => "Fødselsdag", "Business" => "Erhverv", "Call" => "Ring", "Clients" => "Kunder", "Deliverer" => "Leverance", "Holidays" => "Helligdage", "Ideas" => "Ideer", "Journey" => "Rejse", "Jubilee" => "Jubilæum", "Meeting" => "Møde", "Other" => "Andet", "Personal" => "Privat", "Projects" => "Projekter", "Questions" => "Spørgsmål", "Work" => "Arbejde", "by" => "af", "unnamed" => "unavngivet", "You do not have the permissions to update this calendar." => "Du har ikke rettigheder til at opdatere denne kalender.", "You do not have the permissions to delete this calendar." => "Du har ikke rettigheder til at slette denne kalender.", "You do not have the permissions to add to this calendar." => "Du har ikke rettigheder til at tilføje til denne kalender.", "You do not have the permissions to add events to this calendar." => "Du har ikke rettigheder til at tilføje begivenheder til denne kalender.", "You do not have the permissions to delete this event." => "Du har ikke rettigheder til at slette denne begivenhed.", "Busy" => "Optaget", "Does not repeat" => "Gentages ikke", "Daily" => "Dagligt", "Weekly" => "Ugentligt", "Every Weekday" => "Alle hverdage", "Bi-Weekly" => "Hver anden uge", "Monthly" => "Månedligt", "Yearly" => "Årligt", "never" => "aldrig", "by occurrences" => "efter forekomster", "by date" => "efter dato", "by monthday" => "efter dag i måneden", "by weekday" => "efter ugedag", "events week of month" => "begivenhedens uge i måneden", "first" => "første", "second" => "anden", "third" => "tredje", "fourth" => "fjerde", "fifth" => "femte", "last" => "sidste", "by events date" => "efter begivenheders dato", "by yearday(s)" => "efter dag(e) i året", "by weeknumber(s)" => "efter ugenummer/-numre", "by day and month" => "efter dag og måned", "Contact birthdays" => "Kontakt fødselsdage", "Date" => "Dato", "Cal." => "Kal.", "Day" => "Dag", "Week" => "Uge", "Month" => "Måned", "Today" => "I dag", "Settings" => "Indstillinger", "Share Calendar" => "Del kalender", "CalDav Link" => "CalDav-link", "Download" => "Hent", "Edit" => "Rediger", "Delete" => "Slet", "New calendar" => "Ny kalender", "Edit calendar" => "Rediger kalender", "Displayname" => "Vist navn", "Calendar color" => "Kalenderfarve", "Save" => "Gem", "Submit" => "Send", "Cancel" => "Annuller", "Eventinfo" => "Begivenhedsinfo", "Repeating" => "Gentagende", "Alarm" => "Alarm", "Attendees" => "Deltagere", "Share" => "Del", "Title of the Event" => "Titel på begivenheden", "from" => "fra", "All Day Event" => "Heldagsarrangement", "Advanced options" => "Avancerede indstillinger", "Location" => "Sted", "Edit categories" => "Rediger kategorier", "Description" => "Beskrivelse", "Repeat" => "Gentag", "Advanced" => "Avanceret", "Select weekdays" => "Vælg ugedage", "Select days" => "Vælg dage", "and the events day of year." => "og begivenhedens dag i året.", "and the events day of month." => "og begivenhedens dag i måneden", "Select months" => "Vælg måneder", "Select weeks" => "Vælg uger", "and the events week of year." => "og begivenhedens uge i året.", "Interval" => "Interval", "End" => "Afslutning", "occurrences" => "forekomster", "create a new calendar" => "opret en ny kalender", "Import a calendar file" => "Importer en kalenderfil", "Please choose a calendar" => "Vælg en kalender", "Name of new calendar" => "Navn på ny kalender", "Take an available name!" => "Vælg et ledigt navn!", "A Calendar with this name already exists. If you continue anyhow, these calendars will be merged." => "En kalender med dette navn findes allerede. Hvis du fortsætter alligevel, vil disse kalendere blive sammenlagt.", "Remove all events from the selected calendar" => "Fjern alle events fra den valgte kalender", "Import" => "Importer", "Close Dialog" => "Luk dialog", "Create a new event" => "Opret en ny begivenhed", "Unshare" => "Fjern deling", "Send Email" => "Send Email", "Shared via calendar" => "Delt via kalender", "View an event" => "Vis en begivenhed", "Category" => "Kategori", "No categories selected" => "Ingen categorier valgt", "of" => "fra", "Access Class" => "Adgangsklasse", "From" => "Fra", "at" => "kl.", "To" => "Til", "Your calendars" => "Dine kalendere", "General" => "Generel", "Timezone" => "Tidszone", "Update timezone automatically" => "Opdater tidszone automatisk", "Time format" => "Tidsformat", "24h" => "24T", "12h" => "12T", "Start week on" => "Start ugen med", "Cache" => "Cache", "Clear cache for repeating events" => "Ryd cache for gentagende begivenheder", "URLs" => "URLs", "Calendar CalDAV syncing addresses" => "Adresser til kalendersynkronisering over CalDAV", "more info" => "flere oplysninger", "Primary address (Kontact et al)" => "Primær adresse (Kontakt o.a.)", "iOS/OS X" => "iOS/OS X", "Read only iCalendar link(s)" => "Skrivebeskyttet iCalendar-link(s)" );
apache-2.0
uwroute/study
ML/eval/auc.cpp
2402
#include <iostream> #include <vector> #include <cmath> #include <algorithm> #include <fstream> #include "gflags/gflags.h" #include "Common/log.h" DEFINE_string(res_file, "", "predict res"); DEFINE_int32(log_level, 2, "LogLevel :" "0 : TRACE " "1 : DEBUG " "2 : INFO " "3 : ERROR"); uint32_t log_level = 0; namespace ML { struct Elem { double p; double y; }; bool LessThan(const Elem& a, const Elem& b) { return a.p < b.p; } bool Equal(const Elem& a, const Elem& b) { return fabs(a.p - b.p) < 1.e-10; } void check(const Elem& e, int& n, int& p) { if (e.y < 0.5) { n++; } else { p++; } } double logistic_loss(Elem& e) { if (e.y > 0.5) { return -log(e.p); } else { return -log(1-e.p); } } double auc(std::vector<Elem>& res) { if (res.size() <= 0) { return 0.5; } std::sort(res.begin(), res.end(), LessThan); int n = 0; int p = 0; int cur_n = 0; int cur_p = 0; double correct = 0; check(res[0], cur_n, cur_p); for (size_t i=1; i<res.size(); ++i) { if (Equal(res[i], res[i-1])) { check(res[i], cur_n, cur_p); } else { correct += cur_p*n + 0.5*cur_p*cur_n; p += cur_p; n += cur_n; cur_p = 0; cur_n = 0; check(res[i], cur_n, cur_p); } } correct += cur_p*n + 0.5*cur_p*cur_n; p += cur_p; n += cur_n; LOG_INFO("POSITIVE : %d , NEGATIVE : %d, CORRECT : %lf", p, n, correct); if (n == 0) return 1.0; if (p == 0) return 0.0; return correct*1.0/p/n; } } using namespace ML; int main(int argc, char** argv) { google::ParseCommandLineFlags(&argc, &argv, true); log_level = FLAGS_log_level; if (FLAGS_res_file.empty()) { std::cout<< "res file is empty!" << std::endl; return 0; } std::ifstream infile(FLAGS_res_file.c_str()); if (!infile) { LOG_ERROR("Load res file : %s failed!", FLAGS_res_file.c_str()); return 0; } std::string line; std::vector<Elem> res; Elem e; e.p = 0.0; e.y = 1.0; double total_loss = 0; getline(infile, line); while (!infile.eof()) { sscanf(line.c_str(), "%lf %lf", &(e.y), &(e.p)); LOG_TRACE("Elem p : %lf, y : %lf", e.p, e.y); res.push_back(e); total_loss += logistic_loss(e); getline(infile, line); } LOG_TRACE("Res size : %lu", res.size()); printf("[%s]AUC = %.5lf, LOSS = %.3lf\n", FLAGS_res_file.c_str(), auc(res), total_loss); return 0; }
apache-2.0
mdoering/backbone
life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Cortinariaceae/Cortinarius/Cortinarius lucorum/ Syn. Cortinarius impennis lucorum/README.md
276
# Cortinarius impennis var. lucorum Fr., 1838 VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in Epicr. syst. mycol. (Upsaliae) 294 (1838) #### Original name Cortinarius impennis var. lucorum Fr., 1838 ### Remarks null
apache-2.0
Mobet/Mobet-Net
Mobet-Net/Mobet/Runtime/Cookie/CookieManager.cs
1723
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace Mobet.Runtime.Cookie { public static class CookieManager { /// <summary> /// 创建cookie /// </summary> /// <param name="name">cookie名</param> /// <param name="value">cookie值</param> /// <param name="expires">过期时间</param> public static void CreateCookie(string name, string value, DateTime expires) { HttpCookie hc = value.Trim() == "" ? new HttpCookie(name) : new HttpCookie(name, value.Trim()); hc.Path = "/"; // 当过期时间为MinValue时,不设置cookie的过期时间,也就是说,关闭浏览器后cookie即过期 if (expires != DateTime.MinValue) { hc.Expires = expires; } HttpContext.Current.Response.Cookies.Set(hc); } /// <summary> /// 清除cookie /// </summary> /// <param name="name">cookie名</param> /// <param name="domain">域名</param> public static void ClearCookie(string name) { CreateCookie(name, "", DateTime.Now.AddDays(-1)); } /// <summary> /// 获取cookie值 /// </summary> /// <param name="name"></param> /// <returns></returns> public static string GetCookieValue(string name) { var cookie = HttpContext.Current.Request.Cookies[name]; if (cookie == null) { return null; } else { return cookie.Value; } } } }
apache-2.0
smart-e/lifemap
plugins/lfPosPlugin/apps/pc_backend/modules/pos/templates/_googlearea.php
520
<tr> <td><?php echo $area->id ?></td> <td><?php echo $area->lat ?></td> <td><?php echo $area->lng ?></td> <td><?php echo $area->radius ?></td> <td width="300px"><?php echo $area->url ?></td> <td><?php echo $area->area ?></td> <td><?php echo $area->min_radius_area ?></td> <td><?php echo $area->radius_area ?></td> <td> <?php echo link_to('Tạo flow','pos/newGoogleFlow?area='.$area->area) ?> | <?php echo link_to('Sửa','pos/edit?id='.$area->id) ?> | </td> </tr>
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Machaonia/Machaonia tiffina/README.md
188
# Machaonia tiffina Urb. & Ekman SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Phoma/Phoma camelinae/README.md
171
# Phoma camelinae Sandu SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Phoma camelinae Sandu ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Laurales/Lauraceae/Borbonia/Borbonia cupularis/README.md
180
# Borbonia cupularis C.F.Gaertn. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Cactaceae/Echinocactus/Echinocactus multiflorus/Echinocactus multiflorus parisiensis/README.md
205
# Echinocactus multiflorus f. parisiensis (K.Schum.) Schelle FORM #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Chromista/Ochrophyta/Phaeophyceae/Ectocarpales/Chordariaceae/Chordaria/Chordaria flagelliformis/ Syn. Chordaria flagelliformis minor/README.md
202
# Chordaria flagelliformis var. minor C. Agardh VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Orobanchaceae/Castilleja/Castilleja galehintoniae/README.md
184
# Castilleja galehintoniae G.L.Nesom SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Malvales/Malvaceae/Malva/Malva trachelifolia/README.md
174
# Malva trachelifolia Link SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Fungi/Ascomycota/Sordariomycetes/Hypocreales/Niessliaceae/Taiwanascus/Taiwanascus tetrasporus/README.md
278
# Taiwanascus tetrasporus Sivan. & H.S. Chang, 1997 SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Mycol. Res. 101(2): 176 (1997) #### Original name Taiwanascus tetrasporus Sivan. & H.S. Chang, 1997 ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Alismatales/Hydrocharitaceae/Vallisneria/Vallisneria anhuiensis/README.md
189
# Vallisneria anhuiensis X.S.Shen SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Dactylorhiza/Dactylorhiza fuchsii/ Syn. Dactylorhiza maculata meyeri/README.md
195
# Dactylorhiza maculata subsp. meyeri SUBSPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Fungi/Ascomycota/Pezizomycetes/Pezizales/Pyronemataceae/Leucoloma/Leucoloma ascoboloides/README.md
183
# Leucoloma ascoboloides Rehm SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Leucoloma ascoboloides Rehm ### Remarks null
apache-2.0
mdoering/backbone
life/Fungi/Basidiomycota/Agaricomycetes/Corticiales/Corticiaceae/Corticium/Corticium jamaicensis/README.md
212
# Corticium jamaicensis Burt SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Ann. Mo. bot. Gdn 13(3): 273 (1926) #### Original name Corticium jamaicensis Burt ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Dipsacales/Dipsacaceae/Trichera/Trichera slovaca/README.md
211
# Trichera slovaca (Štěpánek) J.Holub SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name Knautia slovaca Štěpánek ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Melastomataceae/Miconia/Miconia paucidens/ Syn. Acinodendron paucidens/README.md
192
# Acinodendron paucidens (DC.) Kuntze SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Eulophia/Eulophia mackinnonii/README.md
185
# Eulophia mackinnonii Duthie SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
virtualopensystems/snabbswitch
src/lib/ipc/fs.lua
1179
-- Snabb Switch filesystem layout for IPC shmem files. module(...,package.seeall) local syscall = require("syscall") local lib = require("core.lib") local fs = {} local default_root = "/var/run/snabb" function fs:instances (root) return lib.files_in_directory(root or default_root) end function fs:exists (pid, root) local root = root or default_root return not not syscall.stat(fs_directory(root, pid)) end function fs:new (pid, root) local root = root or default_root local pid = pid or syscall.getpid() local o = { directory = fs_directory(root, pid) } syscall.mkdir(root, "RWXU") syscall.mkdir(o.directory, "RWXU") return setmetatable(o, {__index = fs}) end function fs:resource (name) return { filename = name, directory = self.directory } end function fs:delete () for _, file in ipairs(lib.files_in_directory(self.directory)) do syscall_assert(syscall.unlink(self.directory.."/"..file)) end syscall_assert(syscall.rmdir(self.directory)) end function fs_directory (root, pid) return string.format("%s/%s", root, pid) end function syscall_assert (status, message) assert(status, tostring(message)) end return fs
apache-2.0
mono/roslyn
src/Features/Core/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.cs
9908
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal class DiagnosticIncrementalAnalyzer : BaseDiagnosticIncrementalAnalyzer { private readonly int _correlationId; private readonly DiagnosticAnalyzerService _owner; private readonly Workspace _workspace; private readonly AnalyzerManager _analyzerManager; public DiagnosticIncrementalAnalyzer(DiagnosticAnalyzerService owner, int correlationId, Workspace workspace, AnalyzerManager analyzerManager) { _correlationId = correlationId; _owner = owner; _workspace = workspace; _analyzerManager = analyzerManager; } #region IIncrementalAnalyzer public override Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public override async Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken) { var diagnostics = await GetDiagnosticsAsync(project.Solution, project.Id, null, cancellationToken).ConfigureAwait(false); RaiseEvents(project, diagnostics); } public override Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public override Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public override Task DocumentResetAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public override Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public override void RemoveDocument(DocumentId documentId) { _owner.RaiseDiagnosticsUpdated( this, new DiagnosticsUpdatedArgs(ValueTuple.Create(this, documentId), _workspace, null, null, null, ImmutableArray<DiagnosticData>.Empty)); } public override void RemoveProject(ProjectId projectId) { _owner.RaiseDiagnosticsUpdated( this, new DiagnosticsUpdatedArgs(ValueTuple.Create(this, projectId), _workspace, null, null, null, ImmutableArray<DiagnosticData>.Empty)); } #endregion public override Task<ImmutableArray<DiagnosticData>> GetCachedDiagnosticsAsync(Solution solution, ProjectId projectId = null, DocumentId documentId = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetDiagnosticsAsync(solution, projectId, documentId, cancellationToken); } public override Task<ImmutableArray<DiagnosticData>> GetSpecificCachedDiagnosticsAsync(Solution solution, object id, CancellationToken cancellationToken) { return GetSpecificDiagnosticsAsync(solution, id, cancellationToken); } public override async Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Solution solution, ProjectId projectId = null, DocumentId documentId = null, CancellationToken cancellationToken = default(CancellationToken)) { if (documentId != null) { var diagnostics = await GetProjectDiagnosticsAsync(solution.GetProject(projectId), cancellationToken).ConfigureAwait(false); return diagnostics.Where(d => d.DocumentId == documentId).ToImmutableArrayOrEmpty(); } if (projectId != null) { return await GetProjectDiagnosticsAsync(solution.GetProject(projectId), cancellationToken).ConfigureAwait(false); } var builder = ImmutableArray.CreateBuilder<DiagnosticData>(); foreach (var project in solution.Projects) { builder.AddRange(await GetProjectDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false)); } return builder.ToImmutable(); } public override async Task<ImmutableArray<DiagnosticData>> GetSpecificDiagnosticsAsync(Solution solution, object id, CancellationToken cancellationToken) { if (id is ValueTuple<DiagnosticIncrementalAnalyzer, DocumentId>) { var key = (ValueTuple<DiagnosticIncrementalAnalyzer, DocumentId>)id; return await GetDiagnosticsAsync(solution, key.Item2.ProjectId, key.Item2, cancellationToken).ConfigureAwait(false); } if (id is ValueTuple<DiagnosticIncrementalAnalyzer, ProjectId>) { var key = (ValueTuple<DiagnosticIncrementalAnalyzer, ProjectId>)id; var diagnostics = await GetDiagnosticsAsync(solution, key.Item2, null, cancellationToken).ConfigureAwait(false); return diagnostics.Where(d => d.DocumentId == null).ToImmutableArray(); } return ImmutableArray<DiagnosticData>.Empty; } public override async Task<ImmutableArray<DiagnosticData>> GetDiagnosticsForIdsAsync(Solution solution, ProjectId projectId = null, DocumentId documentId = null, ImmutableHashSet<string> diagnosticIds = null, CancellationToken cancellationToken = default(CancellationToken)) { var diagnostics = await GetDiagnosticsAsync(solution, projectId, documentId, cancellationToken).ConfigureAwait(false); return diagnostics.Where(d => diagnosticIds.Contains(d.Id)).ToImmutableArrayOrEmpty(); } public override async Task<ImmutableArray<DiagnosticData>> GetProjectDiagnosticsForIdsAsync(Solution solution, ProjectId projectId = null, ImmutableHashSet<string> diagnosticIds = null, CancellationToken cancellationToken = default(CancellationToken)) { var diagnostics = await GetDiagnosticsForIdsAsync(solution, projectId, null, diagnosticIds, cancellationToken).ConfigureAwait(false); return diagnostics.Where(d => d.DocumentId == null).ToImmutableArray(); } public override async Task<bool> TryAppendDiagnosticsForSpanAsync(Document document, TextSpan range, List<DiagnosticData> result, CancellationToken cancellationToken) { result.AddRange(await GetDiagnosticsForSpanAsync(document, range, cancellationToken).ConfigureAwait(false)); return true; } public override async Task<IEnumerable<DiagnosticData>> GetDiagnosticsForSpanAsync(Document document, TextSpan range, CancellationToken cancellationToken) { var diagnostics = await GetDiagnosticsAsync(document.Project.Solution, document.Project.Id, document.Id, cancellationToken).ConfigureAwait(false); return diagnostics.Where(d => range.IntersectsWith(d.TextSpan)); } private async Task<ImmutableArray<DiagnosticData>> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken) { if (project == null) { return ImmutableArray<DiagnosticData>.Empty; } var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var analyzers = _analyzerManager.CreateDiagnosticAnalyzers(project); var compilationWithAnalyzer = compilation.WithAnalyzers(analyzers, project.AnalyzerOptions, cancellationToken); // REVIEW: this API is a bit strange. // if getting diagnostic is cancelled, it has to create new compilation and do everything from scretch again? return GetDiagnosticData(project, await compilationWithAnalyzer.GetAnalyzerDiagnosticsAsync().ConfigureAwait(false)).ToImmutableArrayOrEmpty(); } private IEnumerable<DiagnosticData> GetDiagnosticData(Project project, ImmutableArray<Diagnostic> diagnostics) { foreach (var diagnostic in diagnostics) { if (diagnostic.Location == Location.None) { yield return DiagnosticData.Create(project, diagnostic); continue; } var document = project.GetDocument(diagnostic.Location.SourceTree); if (document == null) { continue; } yield return DiagnosticData.Create(document, diagnostic); } } private void RaiseEvents(Project project, ImmutableArray<DiagnosticData> diagnostics) { var groups = diagnostics.GroupBy(d => d.DocumentId); var solution = project.Solution; var workspace = solution.Workspace; foreach (var kv in groups) { if (kv.Key == null) { _owner.RaiseDiagnosticsUpdated( this, new DiagnosticsUpdatedArgs( ValueTuple.Create(this, project.Id), workspace, solution, project.Id, null, kv.ToImmutableArrayOrEmpty())); continue; } _owner.RaiseDiagnosticsUpdated( this, new DiagnosticsUpdatedArgs( ValueTuple.Create(this, kv.Key), workspace, solution, project.Id, kv.Key, kv.ToImmutableArrayOrEmpty())); } } } }
apache-2.0
kawatan/Milk
MNISTTest/Properties/AssemblyInfo.cs
1389
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MNISTTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MNISTTest")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6d135fe2-ccdd-4c72-b6ae-3cce024289ba")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
google-code/android-scripting
jruby/src/test/externals/ruby1.9/ruby/test_literal.rb
6345
require 'test/unit' class TestRubyLiteral < Test::Unit::TestCase def test_special_const assert_equal 'true', true.inspect assert_instance_of TrueClass, true assert_equal 'false', false.inspect assert_instance_of FalseClass, false assert_equal 'nil', nil.inspect assert_instance_of NilClass, nil assert_equal ':sym', :sym.inspect assert_instance_of Symbol, :sym assert_equal '1234', 1234.inspect assert_instance_of Fixnum, 1234 assert_equal '1234', 1_2_3_4.inspect assert_instance_of Fixnum, 1_2_3_4 assert_equal '18', 0x12.inspect assert_instance_of Fixnum, 0x12 assert_raise(SyntaxError) { eval("0x") } assert_equal '15', 0o17.inspect assert_instance_of Fixnum, 0o17 assert_raise(SyntaxError) { eval("0o") } assert_equal '5', 0b101.inspect assert_instance_of Fixnum, 0b101 assert_raise(SyntaxError) { eval("0b") } assert_equal '123456789012345678901234567890', 123456789012345678901234567890.inspect assert_instance_of Bignum, 123456789012345678901234567890 assert_instance_of Float, 1.3 end def test_self assert_equal self, self assert_instance_of TestRubyLiteral, self assert_respond_to self, :test_self end def test_string assert_instance_of String, ?a assert_equal "a", ?a assert_instance_of String, ?A assert_equal "A", ?A assert_instance_of String, ?\n assert_equal "\n", ?\n assert_equal " ", ?\ # space assert_equal '', '' assert_equal 'string', 'string' assert_equal 'string string', 'string string' assert_equal ' ', ' ' assert_equal ' ', " " assert_equal "\0", "\0" assert_equal "\1", "\1" assert_equal "3", "\x33" assert_equal "\n", "\n" end def test_dstring assert_equal '2', "#{1+1}" assert_equal '16', "#{2 ** 4}" s = "string" assert_equal s, "#{s}" end def test_dsymbol assert_equal :a3c, :"a#{1+2}c" end def test_xstring assert_equal "foo\n", `echo foo` s = 'foo' assert_equal "foo\n", `echo #{s}` end def test_regexp assert_instance_of Regexp, // assert_match //, 'a' assert_match //, '' assert_instance_of Regexp, /a/ assert_match /a/, 'a' assert_no_match /test/, 'tes' re = /test/ assert_match re, 'test' str = 'test' assert_match re, str assert_match /test/, str assert_equal 0, (/test/ =~ 'test') assert_equal 0, (re =~ 'test') assert_equal 0, (/test/ =~ str) assert_equal 0, (re =~ str) assert_equal 0, ('test' =~ /test/) assert_equal 0, ('test' =~ re) assert_equal 0, (str =~ /test/) assert_equal 0, (str =~ re) end def test_dregexp assert_instance_of Regexp, /re#{'ge'}xp/ assert_equal(/regexp/, /re#{'ge'}xp/) end def test_array assert_instance_of Array, [] assert_equal [], [] assert_equal 0, [].size assert_instance_of Array, [0] assert_equal [3], [3] assert_equal 1, [3].size a = [3] assert_equal 3, a[0] assert_instance_of Array, [1,2] assert_equal [1,2], [1,2] assert_instance_of Array, [1,2,3,4,5] assert_equal [1,2,3,4,5], [1,2,3,4,5] assert_equal 5, [1,2,3,4,5].size a = [1,2] assert_equal 1, a[0] assert_equal 2, a[1] a = [1 + 2, 3 + 4, 5 + 6] assert_instance_of Array, a assert_equal [3, 7, 11], a assert_equal 7, a[1] assert_equal 1, ([0][0] += 1) assert_equal 1, ([2][0] -= 1) a = [obj = Object.new] assert_instance_of Array, a assert_equal 1, a.size assert_equal obj, a[0] a = [1,2,3] a[1] = 5 assert_equal 5, a[1] end def test_hash assert_instance_of Hash, {} assert_equal({}, {}) assert_instance_of Hash, {1 => 2} assert_equal({1 => 2}, {1 => 2}) h = {1 => 2} assert_equal 2, h[1] h = {"string" => "literal", "goto" => "hell"} assert_equal h, h assert_equal 2, h.size assert_equal h, h assert_equal "literal", h["string"] end def test_range assert_instance_of Range, (1..2) assert_equal(1..2, 1..2) r = 1..2 assert_equal 1, r.begin assert_equal 2, r.end assert_equal false, r.exclude_end? assert_instance_of Range, (1...3) assert_equal(1...3, 1...3) r = 1...3 assert_equal 1, r.begin assert_equal 3, r.end assert_equal true, r.exclude_end? r = 1+2 .. 3+4 assert_instance_of Range, r assert_equal 3, r.begin assert_equal 7, r.end assert_equal false, r.exclude_end? r = 1+2 ... 3+4 assert_instance_of Range, r assert_equal 3, r.begin assert_equal 7, r.end assert_equal true, r.exclude_end? assert_instance_of Range, 'a'..'c' r = 'a'..'c' assert_equal 'a', r.begin assert_equal 'c', r.end end def test__FILE__ assert_instance_of String, __FILE__ assert_equal __FILE__, __FILE__ assert_equal 'test_literal.rb', File.basename(__FILE__) end def test__LINE__ assert_instance_of Fixnum, __LINE__ assert_equal __LINE__, __LINE__ end def test_integer head = ['', '0x', '0o', '0b', '0d', '-', '+'] chars = ['0', '1', '_', '9', 'f'] head.each {|h| 4.times {|len| a = [h] len.times { a = a.product(chars).map {|x| x.join('') } } a.each {|s| next if s.empty? begin r1 = Integer(s) rescue ArgumentError r1 = :err end begin r2 = eval(s) rescue NameError, SyntaxError r2 = :err end assert_equal(r1, r2, "Integer(#{s.inspect}) != eval(#{s.inspect})") } } } end def test_float head = ['', '-', '+'] chars = ['0', '1', '_', '9', 'f', '.'] head.each {|h| 6.times {|len| a = [h] len.times { a = a.product(chars).map {|x| x.join('') } } a.each {|s| next if s.empty? next if /\.\z/ =~ s next if /\A[-+]?\./ =~ s next if /\A[-+]?0/ =~ s begin r1 = Float(s) rescue ArgumentError r1 = :err end begin r2 = eval(s) rescue NameError, SyntaxError r2 = :err end r2 = :err if Range === r2 assert_equal(r1, r2, "Float(#{s.inspect}) != eval(#{s.inspect})") } } } end end
apache-2.0
wpxiong/beargo
util/dbutil/db_util.go
94
package dbutil import ( "github.com/wpxiong/beargo/log" ) func init() { log.InitLog() }
apache-2.0
wittyResry/leetcode
src/main/java/WordPattern.java
1026
import java.util.HashMap; import java.util.Map; public class WordPattern { public static boolean wordPattern(String pattern, String str) { Map<String, String> a2b = new HashMap<String, String>(); Map<String, String> b2a = new HashMap<String, String>(); String[] tokens = str.split(" "); if (tokens.length != pattern.length()) return false; int i = 0; for (String token : tokens) { StringBuilder tmp = new StringBuilder(); tmp.append(pattern.charAt(i)); if (a2b.containsKey(tmp.toString())) { String r = a2b.get(tmp.toString()); if (!r.equals(token)) return false; } else if (b2a.containsKey(token)) { String r = b2a.get(token); if (!r.equals(tmp.toString())) return false; } else { a2b.put(tmp.toString(), token); b2a.put(token, tmp.toString()); } ++i; } return true; } }
apache-2.0
AKSW/R2RLint
src/main/java/org/aksw/sparqlify/qa/pinpointing/Pinpointer.java
2208
package org.aksw.sparqlify.qa.pinpointing; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.aksw.sparqlify.core.algorithms.CandidateViewSelectorImpl; import org.aksw.sparqlify.core.algorithms.ViewQuad; import org.aksw.sparqlify.core.domain.input.ViewDefinition; import org.aksw.sparqlify.database.Clause; import org.aksw.sparqlify.database.NestedNormalForm; import org.aksw.sparqlify.restriction.RestrictionManagerImpl; import org.springframework.stereotype.Component; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.Triple; import com.hp.hpl.jena.sparql.core.Quad; import com.hp.hpl.jena.sparql.core.Var; import com.hp.hpl.jena.sparql.expr.E_Equals; import com.hp.hpl.jena.sparql.expr.ExprVar; import com.hp.hpl.jena.sparql.expr.NodeValue; @Component public class Pinpointer { // private Collection<ViewDefinition> viewDefs; CandidateViewSelectorImpl candidateSelector; /* * TODO: * - add query method * - add caching */ public void registerViewDefs(Collection<ViewDefinition> viewDefs) { candidateSelector = new CandidateViewSelectorImpl(); for (ViewDefinition viewDef : viewDefs) { candidateSelector.addView(viewDef); } } public Set<ViewQuad<ViewDefinition>> getViewCandidates(Triple triple) { Var g = Var.alloc("g"); Var s = Var.alloc("s"); Var p = Var.alloc("p"); Var o = Var.alloc("o"); Node gv = Quad.defaultGraphNodeGenerated; Node sv = triple.getSubject(); Node pv = triple.getPredicate(); Node ov = triple.getObject(); Quad tmpQuad = new Quad(g, s, p, o); RestrictionManagerImpl r = new RestrictionManagerImpl(); Set<Clause> clauses = new HashSet<Clause>(); clauses.add(new Clause(new E_Equals(new ExprVar(g), NodeValue.makeNode(gv)))); clauses.add(new Clause(new E_Equals(new ExprVar(s), NodeValue.makeNode(sv)))); clauses.add(new Clause(new E_Equals(new ExprVar(p), NodeValue.makeNode(pv)))); clauses.add(new Clause(new E_Equals(new ExprVar(o), NodeValue.makeNode(ov)))); NestedNormalForm nnf = new NestedNormalForm(clauses); r.stateCnf(nnf); Set<ViewQuad<ViewDefinition>> result = candidateSelector.findCandidates(tmpQuad, r); return result; } }
apache-2.0
nitram509/macaroons.js
src/main/ts/MacaroonsVerifier.ts
9915
/* * Copyright 2014 Martin W. Kirst * * 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. */ import CaveatPacket = require('./CaveatPacket'); import CaveatPacketType = require('./CaveatPacketType'); import Macaroon = require('./Macaroon'); import MacaroonsConstants = require('./MacaroonsConstants'); import BufferTools = require('./BufferTools'); import CryptoTools = require('./CryptoTools'); export = MacaroonsVerifier; /** * Used to verify Macaroons */ class MacaroonsVerifier { "use strict"; private predicates:string[] = []; private boundMacaroons:Macaroon[] = []; private generalCaveatVerifiers:GeneralCaveatVerifier[] = []; private macaroon:Macaroon; constructor(macaroon:Macaroon) { this.macaroon = macaroon; } /** * @param secret string this secret will be enhanced, in case it's shorter than {@link MacaroonsConstants.MACAROON_SUGGESTED_SECRET_LENGTH} * @throws Error if macaroon isn't valid */ public assertIsValid(secret:string):void; /** * @param secret a Buffer, that will be used, a minimum length of {@link MacaroonsConstants.MACAROON_SUGGESTED_SECRET_LENGTH} is highly recommended * @throws Error if macaroon isn't valid */ public assertIsValid(secret:Buffer):void; public assertIsValid(secret:any):void { var secretBuffer = (secret instanceof Buffer) ? secret : CryptoTools.generate_derived_key(secret); var result = this.isValid_verify_raw(this.macaroon, secretBuffer); if (result.fail) { var msg = result.failMessage != null ? result.failMessage : "This macaroon isn't valid."; throw new Error(msg); } } /** * @param secret string this secret will be enhanced, in case it's shorter than {@link MacaroonsConstants.MACAROON_SUGGESTED_SECRET_LENGTH} * @return true/false if the macaroon is valid */ public isValid(secret:string):boolean; /** * @param secret a Buffer, that will be used, a minimum length of {@link MacaroonsConstants.MACAROON_SUGGESTED_SECRET_LENGTH} is highly recommended * @return true/false if the macaroon is valid */ public isValid(secret:Buffer):boolean; public isValid(secret:any):boolean { var secretBuffer = (secret instanceof Buffer) ? secret : CryptoTools.generate_derived_key(secret); return !this.isValid_verify_raw(this.macaroon, secretBuffer).fail; } /** * Caveats like these are called "exact caveats" because there is exactly one way * to satisfy them. Either the given caveat matches, or it doesn't. At * verification time, the verifier will check each caveat in the macaroon against * the list of satisfied caveats provided to satisfyExact(String). * When it finds a match, it knows that the caveat holds and it can move onto the next caveat in * the macaroon. * * @param caveat caveat * @return this {@link MacaroonsVerifier} */ public satisfyExact(caveat:string):MacaroonsVerifier { if (caveat) { this.predicates.push(caveat); } return this; } /** * Binds a prepared macaroon. * * @param preparedMacaroon preparedMacaroon * @return this {@link MacaroonsVerifier} */ public satisfy3rdParty(preparedMacaroon:Macaroon):MacaroonsVerifier { if (preparedMacaroon) { this.boundMacaroons.push(preparedMacaroon); } return this; } /** * Another technique for informing the verifier that a caveat is satisfied * allows for expressive caveats. Whereas exact caveats are checked * by simple byte-wise equality, general caveats are checked using * an application-provided callback that returns true if and only if the caveat * is true within the context of the request. * There's no limit on the contents of a general caveat, * so long as the callback understands how to determine whether it is satisfied. * This technique is called "general caveats". * * @param generalVerifier generalVerifier a function(caveat:string):boolean which does the verification * @return this {@link MacaroonsVerifier} */ public satisfyGeneral(generalVerifier:(caveat:string)=>boolean):MacaroonsVerifier { if (generalVerifier) { this.generalCaveatVerifiers.push(generalVerifier); } return this; } private isValid_verify_raw(M:Macaroon, secret:Buffer):VerificationResult { var vresult = this.macaroon_verify_inner(M, secret); if (!vresult.fail) { vresult.fail = !BufferTools.equals(vresult.csig, this.macaroon.signatureBuffer); if (vresult.fail) { vresult = new VerificationResult("Verification failed. Signature doesn't match. Maybe the key was wrong OR some caveats aren't satisfied."); } } return vresult; } private macaroon_verify_inner(M:Macaroon, key:Buffer):VerificationResult { var csig:Buffer = CryptoTools.macaroon_hmac(key, M.identifier); if (M.caveatPackets != null) { var caveatPackets = M.caveatPackets; for (var i = 0; i < caveatPackets.length; i++) { var caveat = caveatPackets[i]; if (caveat == null) continue; if (caveat.type == CaveatPacketType.cl) continue; if (!(caveat.type == CaveatPacketType.cid && caveatPackets[Math.min(i + 1, caveatPackets.length - 1)].type == CaveatPacketType.vid)) { if (MacaroonsVerifier.containsElement(this.predicates, caveat.getValueAsText()) || this.verifiesGeneral(caveat.getValueAsText())) { csig = CryptoTools.macaroon_hmac(csig, caveat.rawValue); } } else { i++; var caveat_vid = caveatPackets[i]; var boundMacaroon = this.findBoundMacaroon(caveat.getValueAsText()); if (boundMacaroon == null) { var msg = "Couldn't verify 3rd party macaroon, because no discharged macaroon was provided to the verifier."; return new VerificationResult(msg); } if (!this.macaroon_verify_inner_3rd(boundMacaroon, caveat_vid, csig)) { var msg = "Couldn't verify 3rd party macaroon, identifier= " + boundMacaroon.identifier; return new VerificationResult(msg); } var data = caveat.rawValue; var vdata = caveat_vid.rawValue; csig = CryptoTools.macaroon_hash2(csig, vdata, data); } } } return new VerificationResult(csig); } private macaroon_verify_inner_3rd(M:Macaroon, C:CaveatPacket, sig:Buffer):boolean { if (!M) return false; var enc_plaintext = Buffer.alloc(MacaroonsConstants.MACAROON_SECRET_TEXT_ZERO_BYTES + MacaroonsConstants.MACAROON_HASH_BYTES); var enc_ciphertext = Buffer.alloc(MacaroonsConstants.MACAROON_HASH_BYTES + MacaroonsConstants.SECRET_BOX_OVERHEAD); enc_plaintext.fill(0); enc_ciphertext.fill(0); var vid_data = C.rawValue; //assert vid_data.length == VID_NONCE_KEY_SZ; /** * the nonce is in the first MACAROON_SECRET_NONCE_BYTES * of the vid; the ciphertext is in the rest of it. */ var enc_nonce = Buffer.alloc(MacaroonsConstants.MACAROON_SECRET_NONCE_BYTES); vid_data.copy(enc_nonce, 0, 0, enc_nonce.length); /* fill in the ciphertext */ vid_data.copy(enc_ciphertext, 0, MacaroonsConstants.MACAROON_SECRET_NONCE_BYTES, MacaroonsConstants.MACAROON_SECRET_NONCE_BYTES + vid_data.length - MacaroonsConstants.MACAROON_SECRET_NONCE_BYTES); try { var enc_plaintext = CryptoTools.macaroon_secretbox_open(sig, enc_nonce, enc_ciphertext); } catch (error) { if (/Cipher bytes fail verification/.test(error.message)) { return false; } else { throw new Error("Error while deciphering 3rd party caveat, msg=" + error); } } var key = Buffer.alloc(MacaroonsConstants.MACAROON_HASH_BYTES); key.fill(0); enc_plaintext.copy(key, 0, 0, MacaroonsConstants.MACAROON_HASH_BYTES); var vresult = this.macaroon_verify_inner(M, key); var data = this.macaroon.signatureBuffer; var csig = CryptoTools.macaroon_bind(data, vresult.csig); return BufferTools.equals(csig, M.signatureBuffer); } private findBoundMacaroon(identifier:string):Macaroon { for (var i = 0; i < this.boundMacaroons.length; i++) { var boundMacaroon = this.boundMacaroons[i]; if (identifier === boundMacaroon.identifier) { return boundMacaroon; } } return null; } private verifiesGeneral(caveat:string):boolean { var found:boolean = false; for (var i = 0; i < this.generalCaveatVerifiers.length; i++) { var verifier:GeneralCaveatVerifier = this.generalCaveatVerifiers[i]; found = found || verifier(caveat); } return found; } private static containsElement(elements:string[], anElement:string):boolean { if (elements != null) { for (var i = 0; i < elements.length; i++) { var element = elements[i]; if (element === anElement) return true; } } return false; } } class VerificationResult { csig:Buffer = null; fail:boolean = false; failMessage:string = null; constructor(csig:Buffer); constructor(failMessage:string); constructor(arg:any) { if (typeof arg === 'string') { this.failMessage = arg; this.fail = true; } else if (typeof arg === 'object') { this.csig = arg; } } } interface GeneralCaveatVerifier { /** * @param caveat caveat * @return True, if this caveat is satisfies the applications requirements. False otherwise. */ (caveat:string):boolean; }
apache-2.0
ctr-lang/ctr
lib/ctr-nodes/animation/anim-config.js
1529
const _ = require('lodash'); const teFlow = require('te-flow'); const AnimManager = require('./anim-manager.js'); const _H = require('./../helpers/helper-index.js'); const animConfig = function (_key, _data) { /** * Preps the data to be processed * @param {str} key -> anim key * @param {obj} data -> anim data * @return {---} -> {key, data, globalData} */ const formatData = function (key, data) { let globalData; ({data, globalData} = _H.util.getGlobal(data)); //plural container check, don't want to format if plural if (!_H.util.regularExp.pluralTest(key, 'animation')) { data = _H.util.formatData(data, key, { addOnKeys: ['timeline', 'tl'], globalData }); } return { key, data, globalData }; }; /** * Inits the manager and then sets the data from the raw data obj * to create a itteration to cycle over in extract * @return {---} -> {animMgr} animation class with configed data */ const initSetData = function (key, data, globalData) { //init the manager to set data to const animMgr = new AnimManager(key, globalData); //loop through data and the objs _.forEach(data, function (val, objKey) { animMgr.set(val, objKey); }); return { animMgr }; }; //-> passing data to anim-extract return teFlow.call({ args: { key: _key, data: _data }}, formatData, initSetData ); }; module.exports = animConfig;
apache-2.0
mattiamascia/jrank
src/main/java/com/f1000/rank/helper/RankingHelper.java
361
/** * */ package com.f1000.rank.helper; import java.util.List; import com.f1000.rank.journal.model.Rank; /** * The Interface RankingHelper. * * @author mattiam */ public interface RankingHelper { /** * Ranking. * * @param <T> the generic type * @param list the list */ public <T extends Rank<T>> void ranking(List<T> list); }
apache-2.0
gsoundar/mambo-ec2-deploy
packages/hbase-0.98.7-hadoop2/docs/devapidocs/org/apache/hadoop/hbase/util/hbck/package-use.html
7214
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_67) on Wed Oct 08 15:57:26 PDT 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Package org.apache.hadoop.hbase.util.hbck (HBase 0.98.7-hadoop2 API)</title> <meta name="date" content="2014-10-08"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Package org.apache.hadoop.hbase.util.hbck (HBase 0.98.7-hadoop2 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/hadoop/hbase/util/hbck/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Uses of Package org.apache.hadoop.hbase.util.hbck" class="title">Uses of Package<br>org.apache.hadoop.hbase.util.hbck</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../org/apache/hadoop/hbase/util/hbck/package-summary.html">org.apache.hadoop.hbase.util.hbck</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.apache.hadoop.hbase.util">org.apache.hadoop.hbase.util</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.apache.hadoop.hbase.util.hbck">org.apache.hadoop.hbase.util.hbck</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.apache.hadoop.hbase.util"> <!-- --> </a> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../org/apache/hadoop/hbase/util/hbck/package-summary.html">org.apache.hadoop.hbase.util.hbck</a> used by <a href="../../../../../../org/apache/hadoop/hbase/util/package-summary.html">org.apache.hadoop.hbase.util</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../../../org/apache/hadoop/hbase/util/hbck/class-use/HFileCorruptionChecker.html#org.apache.hadoop.hbase.util">HFileCorruptionChecker</a> <div class="block">This class marches through all of the region's hfiles and verifies that they are all valid files.</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../../../org/apache/hadoop/hbase/util/hbck/class-use/TableIntegrityErrorHandler.html#org.apache.hadoop.hbase.util">TableIntegrityErrorHandler</a> <div class="block">This interface provides callbacks for handling particular table integrity invariant violations.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.apache.hadoop.hbase.util.hbck"> <!-- --> </a> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../org/apache/hadoop/hbase/util/hbck/package-summary.html">org.apache.hadoop.hbase.util.hbck</a> used by <a href="../../../../../../org/apache/hadoop/hbase/util/hbck/package-summary.html">org.apache.hadoop.hbase.util.hbck</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../../../org/apache/hadoop/hbase/util/hbck/class-use/TableIntegrityErrorHandler.html#org.apache.hadoop.hbase.util.hbck">TableIntegrityErrorHandler</a> <div class="block">This interface provides callbacks for handling particular table integrity invariant violations.</div> </td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/hadoop/hbase/util/hbck/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2014 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p> </body> </html>
apache-2.0
JasonTsoi/Test
README.md
42
# Test This is a github test. a brand add
apache-2.0
HanderWei/ZhihuDaily
app/src/main/java/me/chen_wei/zhihu/MyApplication.java
489
package me.chen_wei.zhihu; import android.app.Application; import android.support.v7.app.AppCompatDelegate; /** * Created by Hander on 16/2/28. * <p/> * Email : [email protected] */ public class MyApplication extends Application { static{ //设置DayNightTheme模式 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO); } @Override public void onCreate() { super.onCreate(); // LeakCanary.install(this); } }
apache-2.0
jaredsburrows/cs-interview-questions
java/src/main/java/leetcode/Problem167TwoSumII.java
752
package leetcode; /** * https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ * https://leetcode.com/explore/learn/card/array-and-string/205/array-two-pointer-technique/1153/ */ public final class Problem167TwoSumII { public int[] twoSum(int[] numbers, int target) { if (numbers == null || numbers.length == 0) { return new int[0]; } int i = 0; int j = numbers.length - 1; while (i < j) { int sum = numbers[i] + numbers[j]; if (sum == target) { return new int[] {i + 1, j + 1}; } else if (sum < target) { i++; } else { j--; } } return new int[0]; } }
apache-2.0
consulo/consulo
modules/base/lang-impl/src/main/java/com/intellij/ide/actions/runAnything/RunAnythingContextRecentDirectoryCache.java
1682
/* * Copyright 2013-2019 consulo.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.actions.runAnything; import com.intellij.openapi.components.*; import com.intellij.openapi.project.Project; import com.intellij.util.xmlb.XmlSerializerUtil; import jakarta.inject.Singleton; import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; /** * from kotlin */ @Singleton @State(name = "RunAnythingContextRecentDirectoryCache", storages = @Storage(StoragePathMacros.WORKSPACE_FILE)) public class RunAnythingContextRecentDirectoryCache implements PersistentStateComponent<RunAnythingContextRecentDirectoryCache.State> { static class State { public List<String> paths = new ArrayList<>(); } @Nonnull public static RunAnythingContextRecentDirectoryCache getInstance(@Nonnull Project project) { return ServiceManager.getService(project, RunAnythingContextRecentDirectoryCache.class); } private State myState = new State(); @Nonnull @Override public State getState() { return myState; } @Override public void loadState(State state) { XmlSerializerUtil.copyBean(state, myState); } }
apache-2.0
AmartC/synthea
lib/world/birth_rate.rb
515
module Synthea module World class BirthRate def initialize @area = Synthea::Config.population.area @population_variance = Synthea::Config.population.birth_variance @rate_per_sq_mile = (Synthea::Config.population.daily_births_per_square_mile * Synthea::Config.time_step) mean = @rate_per_sq_mile * @area @distribution = Distribution::Normal.rng(mean, mean * @population_variance) end def births @distribution.call end end end end
apache-2.0
Dakror/Vloxlands
core/src/de/dakror/vloxlands/generate/WorldGenerator.java
1624
/******************************************************************************* * Copyright 2015 Maximilian Stark | Dakror <[email protected]> * * 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 de.dakror.vloxlands.generate; import com.badlogic.gdx.math.Vector3; import de.dakror.vloxlands.game.Game; import de.dakror.vloxlands.game.world.Island; /** * @author Dakror */ public class WorldGenerator extends Thread { public float progress; public boolean done; public WorldGenerator() { setName("WorldGenerator Thread"); } @Override public void run() { for (int i = 0; i < Game.world.getWidth(); i++) { for (int j = 0; j < Game.world.getDepth(); j++) { Island island = IslandGenerator.generate(this); island.setPos(new Vector3(i * Island.SIZE, island.pos.y, j * Island.SIZE)); Game.world.addIsland(i, j, island); } } done = true; } public void step() { int total = Game.world.getWidth() * Game.world.getDepth() * 6; progress += 1f / total; } }
apache-2.0
graviton57/ITArticles
app/src/main/java/com/havryliuk/itarticles/data/local/preferences/AppPreferencesHelper.java
1546
package com.havryliuk.itarticles.data.local.preferences; import javax.inject.Inject; /** * Created by Igor Havrylyuk on 23.10.2017. */ public class AppPreferencesHelper implements IPreferencesHelper { private static final String PREF_KEY_IS_LOGGED_IN = "PREF_KEY_IS_LOGGED_IN"; private static final String PREF_KEY_USER_NAME = "PREF_KEY_USER_NAME_VALUE"; private static final String PREF_KEY_USER_TOKEN = "PREF_KEY_USER_TOKEN_VALUE"; private CommonPreferencesHelper commonPreferencesHelper; @Inject public AppPreferencesHelper(CommonPreferencesHelper commonPreferencesHelper) { this.commonPreferencesHelper = commonPreferencesHelper; } @Override public void setLoggedIn(boolean value) { commonPreferencesHelper.setBooleanToPrefs(PREF_KEY_IS_LOGGED_IN, value); } @Override public boolean isLoggedIn() { return commonPreferencesHelper.getBooleanFromPrefs(PREF_KEY_IS_LOGGED_IN); } @Override public void setUserName(String userName) { commonPreferencesHelper.setStringToPrefs(PREF_KEY_USER_NAME, userName); } @Override public String getUserName() { return commonPreferencesHelper.getStringFromPrefs(PREF_KEY_USER_NAME); } @Override public String getAccessToken() { return commonPreferencesHelper.getStringFromPrefs(PREF_KEY_USER_TOKEN); } @Override public void setAccessToken(String accessToken) { commonPreferencesHelper.setStringToPrefs(PREF_KEY_USER_TOKEN, accessToken); } }
apache-2.0
WilliamDo/ignite
modules/ml/src/main/java/org/apache/ignite/ml/math/impls/matrix/AbstractMatrix.java
26094
/* * 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. */ package org.apache.ignite.ml.math.impls.matrix; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.Spliterator; import java.util.function.Consumer; import org.apache.ignite.lang.IgniteUuid; import org.apache.ignite.ml.math.Blas; import org.apache.ignite.ml.math.Matrix; import org.apache.ignite.ml.math.MatrixStorage; import org.apache.ignite.ml.math.Vector; import org.apache.ignite.ml.math.decompositions.LUDecomposition; import org.apache.ignite.ml.math.exceptions.CardinalityException; import org.apache.ignite.ml.math.exceptions.ColumnIndexException; import org.apache.ignite.ml.math.exceptions.RowIndexException; import org.apache.ignite.ml.math.functions.Functions; import org.apache.ignite.ml.math.functions.IgniteBiFunction; import org.apache.ignite.ml.math.functions.IgniteDoubleFunction; import org.apache.ignite.ml.math.functions.IgniteFunction; import org.apache.ignite.ml.math.functions.IgniteTriFunction; import org.apache.ignite.ml.math.functions.IntIntToDoubleFunction; import org.apache.ignite.ml.math.impls.vector.DenseLocalOnHeapVector; import org.apache.ignite.ml.math.impls.vector.MatrixVectorView; import org.apache.ignite.ml.math.util.MatrixUtil; /** * This class provides a helper implementation of the {@link Matrix} * interface to minimize the effort required to implement it. * Subclasses may override some of the implemented methods if a more * specific or optimized implementation is desirable. */ public abstract class AbstractMatrix implements Matrix { // Stochastic sparsity analysis. /** */ private static final double Z95 = 1.959964; /** */ private static final double Z80 = 1.281552; /** */ private static final int MAX_SAMPLES = 500; /** */ private static final int MIN_SAMPLES = 15; /** Cached minimum element. */ private Element minElm; /** Cached maximum element. */ private Element maxElm = null; /** Matrix storage implementation. */ private MatrixStorage sto; /** Meta attributes storage. */ private Map<String, Object> meta = new HashMap<>(); /** Matrix's GUID. */ private IgniteUuid guid = IgniteUuid.randomUuid(); /** * @param sto Backing {@link MatrixStorage}. */ public AbstractMatrix(MatrixStorage sto) { this.sto = sto; } /** * */ public AbstractMatrix() { // No-op. } /** * @param sto Backing {@link MatrixStorage}. */ protected void setStorage(MatrixStorage sto) { assert sto != null; this.sto = sto; } /** * @param row Row index in the matrix. * @param col Column index in the matrix. * @param v Value to set. */ protected void storageSet(int row, int col, double v) { sto.set(row, col, v); // Reset cached values. minElm = maxElm = null; } /** * @param row Row index in the matrix. * @param col Column index in the matrix. */ protected double storageGet(int row, int col) { return sto.get(row, col); } /** {@inheritDoc} */ @Override public Element maxElement() { if (maxElm == null) { double max = Double.NEGATIVE_INFINITY; int row = 0, col = 0; int rows = rowSize(); int cols = columnSize(); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) { double d = storageGet(x, y); if (d > max) { max = d; row = x; col = y; } } maxElm = mkElement(row, col); } return maxElm; } /** {@inheritDoc} */ @Override public Element minElement() { if (minElm == null) { double min = Double.MAX_VALUE; int row = 0, col = 0; int rows = rowSize(); int cols = columnSize(); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) { double d = storageGet(x, y); if (d < min) { min = d; row = x; col = y; } } minElm = mkElement(row, col); } return minElm; } /** {@inheritDoc} */ @Override public double maxValue() { return maxElement().get(); } /** {@inheritDoc} */ @Override public double minValue() { return minElement().get(); } /** * @param row Row index in the matrix. * @param col Column index in the matrix. */ private Element mkElement(int row, int col) { return new Element() { /** {@inheritDoc} */ @Override public double get() { return storageGet(row, col); } /** {@inheritDoc} */ @Override public int row() { return row; } /** {@inheritDoc} */ @Override public int column() { return col; } /** {@inheritDoc} */ @Override public void set(double d) { storageSet(row, col, d); } }; } /** {@inheritDoc} */ @Override public Element getElement(int row, int col) { return mkElement(row, col); } /** {@inheritDoc} */ @Override public Matrix swapRows(int row1, int row2) { checkRowIndex(row1); checkRowIndex(row2); int cols = columnSize(); for (int y = 0; y < cols; y++) { double v = getX(row1, y); setX(row1, y, getX(row2, y)); setX(row2, y, v); } return this; } /** {@inheritDoc} */ @Override public Matrix swapColumns(int col1, int col2) { checkColumnIndex(col1); checkColumnIndex(col2); int rows = rowSize(); for (int x = 0; x < rows; x++) { double v = getX(x, col1); setX(x, col1, getX(x, col2)); setX(x, col2, v); } return this; } /** {@inheritDoc} */ @Override public MatrixStorage getStorage() { return sto; } /** {@inheritDoc} */ @Override public boolean isSequentialAccess() { return sto.isSequentialAccess(); } /** {@inheritDoc} */ @Override public boolean isDense() { return sto.isDense(); } /** {@inheritDoc} */ @Override public boolean isRandomAccess() { return sto.isRandomAccess(); } /** {@inheritDoc} */ @Override public boolean isDistributed() { return sto.isDistributed(); } /** {@inheritDoc} */ @Override public boolean isArrayBased() { return sto.isArrayBased(); } /** * Check row index bounds. * * @param row Row index. */ void checkRowIndex(int row) { if (row < 0 || row >= rowSize()) throw new RowIndexException(row); } /** * Check column index bounds. * * @param col Column index. */ void checkColumnIndex(int col) { if (col < 0 || col >= columnSize()) throw new ColumnIndexException(col); } /** * Check column and row index bounds. * * @param row Row index. * @param col Column index. */ private void checkIndex(int row, int col) { checkRowIndex(row); checkColumnIndex(col); } /** {@inheritDoc} */ @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(sto); out.writeObject(meta); out.writeObject(guid); } /** {@inheritDoc} */ @Override public Map<String, Object> getMetaStorage() { return meta; } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { sto = (MatrixStorage)in.readObject(); meta = (Map<String, Object>)in.readObject(); guid = (IgniteUuid)in.readObject(); } /** {@inheritDoc} */ @Override public Matrix assign(double val) { if (sto.isArrayBased()) Arrays.fill(sto.data(), val); else { int rows = rowSize(); int cols = columnSize(); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) storageSet(x, y, val); } return this; } /** {@inheritDoc} */ @Override public Matrix assign(IntIntToDoubleFunction fun) { int rows = rowSize(); int cols = columnSize(); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) storageSet(x, y, fun.apply(x, y)); return this; } /** */ private void checkCardinality(Matrix mtx) { checkCardinality(mtx.rowSize(), mtx.columnSize()); } /** */ private void checkCardinality(int rows, int cols) { if (rows != rowSize()) throw new CardinalityException(rowSize(), rows); if (cols != columnSize()) throw new CardinalityException(columnSize(), cols); } /** {@inheritDoc} */ @Override public Matrix assign(double[][] vals) { checkCardinality(vals.length, vals[0].length); int rows = rowSize(); int cols = columnSize(); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) storageSet(x, y, vals[x][y]); return this; } /** {@inheritDoc} */ @Override public Matrix assign(Matrix mtx) { checkCardinality(mtx); int rows = rowSize(); int cols = columnSize(); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) storageSet(x, y, mtx.getX(x, y)); return this; } /** {@inheritDoc} */ @Override public Matrix map(IgniteDoubleFunction<Double> fun) { int rows = rowSize(); int cols = columnSize(); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) storageSet(x, y, fun.apply(storageGet(x, y))); return this; } /** {@inheritDoc} */ @Override public Matrix map(Matrix mtx, IgniteBiFunction<Double, Double, Double> fun) { checkCardinality(mtx); int rows = rowSize(); int cols = columnSize(); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) storageSet(x, y, fun.apply(storageGet(x, y), mtx.getX(x, y))); return this; } /** {@inheritDoc} */ @Override public Spliterator<Double> allSpliterator() { return new Spliterator<Double>() { /** {@inheritDoc} */ @Override public boolean tryAdvance(Consumer<? super Double> act) { int rLen = rowSize(); int cLen = columnSize(); for (int i = 0; i < rLen; i++) for (int j = 0; j < cLen; j++) act.accept(storageGet(i, j)); return true; } /** {@inheritDoc} */ @Override public Spliterator<Double> trySplit() { return null; // No Splitting. } /** {@inheritDoc} */ @Override public long estimateSize() { return rowSize() * columnSize(); } /** {@inheritDoc} */ @Override public int characteristics() { return ORDERED | SIZED; } }; } /** {@inheritDoc} */ @Override public int nonZeroElements() { int cnt = 0; for (int i = 0; i < rowSize(); i++) for (int j = 0; j < rowSize(); j++) if (get(i, j) != 0.0) cnt++; return cnt; } /** {@inheritDoc} */ @Override public Spliterator<Double> nonZeroSpliterator() { return new Spliterator<Double>() { /** {@inheritDoc} */ @Override public boolean tryAdvance(Consumer<? super Double> act) { int rLen = rowSize(); int cLen = columnSize(); for (int i = 0; i < rLen; i++) for (int j = 0; j < cLen; j++) { double val = storageGet(i, j); if (val != 0.0) act.accept(val); } return true; } /** {@inheritDoc} */ @Override public Spliterator<Double> trySplit() { return null; // No Splitting. } /** {@inheritDoc} */ @Override public long estimateSize() { return nonZeroElements(); } /** {@inheritDoc} */ @Override public int characteristics() { return ORDERED | SIZED; } }; } /** {@inheritDoc} */ @Override public Matrix assignColumn(int col, Vector vec) { checkColumnIndex(col); int rows = rowSize(); for (int x = 0; x < rows; x++) storageSet(x, col, vec.getX(x)); return this; } /** {@inheritDoc} */ @Override public Matrix assignRow(int row, Vector vec) { checkRowIndex(row); int cols = columnSize(); if (cols != vec.size()) throw new CardinalityException(cols, vec.size()); // TODO: IGNITE-5777, use Blas for this. for (int y = 0; y < cols; y++) storageSet(row, y, vec.getX(y)); return this; } /** {@inheritDoc} */ @Override public Vector foldRows(IgniteFunction<Vector, Double> fun) { int rows = rowSize(); Vector vec = likeVector(rows); for (int i = 0; i < rows; i++) vec.setX(i, fun.apply(viewRow(i))); return vec; } /** {@inheritDoc} */ @Override public Vector foldColumns(IgniteFunction<Vector, Double> fun) { int cols = columnSize(); Vector vec = likeVector(cols); for (int i = 0; i < cols; i++) vec.setX(i, fun.apply(viewColumn(i))); return vec; } /** {@inheritDoc} */ @Override public <T> T foldMap(IgniteBiFunction<T, Double, T> foldFun, IgniteDoubleFunction<Double> mapFun, T zeroVal) { T res = zeroVal; int rows = rowSize(); int cols = columnSize(); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) res = foldFun.apply(res, mapFun.apply(storageGet(x, y))); return res; } /** {@inheritDoc} */ @Override public int columnSize() { return sto.columnSize(); } /** {@inheritDoc} */ @Override public int rowSize() { return sto.rowSize(); } /** {@inheritDoc} */ @Override public double determinant() { //TODO: IGNITE-5799, This decomposition should be cached LUDecomposition dec = new LUDecomposition(this); double res = dec.determinant(); dec.destroy(); return res; } /** {@inheritDoc} */ @Override public Matrix inverse() { if (rowSize() != columnSize()) throw new CardinalityException(rowSize(), columnSize()); //TODO: IGNITE-5799, This decomposition should be cached LUDecomposition dec = new LUDecomposition(this); Matrix res = dec.solve(likeIdentity()); dec.destroy(); return res; } /** */ protected Matrix likeIdentity() { int n = rowSize(); Matrix res = like(n, n); for (int i = 0; i < n; i++) res.setX(i, i, 1.0); return res; } /** {@inheritDoc} */ @Override public Matrix divide(double d) { int rows = rowSize(); int cols = columnSize(); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) setX(x, y, getX(x, y) / d); return this; } /** {@inheritDoc} */ @Override public double get(int row, int col) { checkIndex(row, col); return storageGet(row, col); } /** {@inheritDoc} */ @Override public double getX(int row, int col) { return storageGet(row, col); } /** {@inheritDoc} */ @Override public Matrix minus(Matrix mtx) { int rows = rowSize(); int cols = columnSize(); checkCardinality(rows, cols); Matrix res = like(rows, cols); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) res.setX(x, y, getX(x, y) - mtx.getX(x, y)); return res; } /** {@inheritDoc} */ @Override public Matrix plus(double x) { Matrix cp = copy(); cp.map(Functions.plus(x)); return cp; } /** {@inheritDoc} */ @Override public Matrix plus(Matrix mtx) { int rows = rowSize(); int cols = columnSize(); checkCardinality(rows, cols); Matrix res = like(rows, cols); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) res.setX(x, y, getX(x, y) + mtx.getX(x, y)); return res; } /** {@inheritDoc} */ @Override public IgniteUuid guid() { return guid; } /** {@inheritDoc} */ @Override public Matrix set(int row, int col, double val) { checkIndex(row, col); storageSet(row, col, val); return this; } /** {@inheritDoc} */ @Override public Matrix setRow(int row, double[] data) { checkRowIndex(row); int cols = columnSize(); if (cols != data.length) throw new CardinalityException(cols, data.length); // TODO: IGNITE-5777, use Blas for this. for (int y = 0; y < cols; y++) setX(row, y, data[y]); return this; } /** {@inheritDoc} */ @Override public Vector getRow(int row) { checkRowIndex(row); Vector res = new DenseLocalOnHeapVector(columnSize()); for (int i = 0; i < columnSize(); i++) res.setX(i, getX(row, i)); return res; } /** {@inheritDoc} */ @Override public Matrix setColumn(int col, double[] data) { checkColumnIndex(col); int rows = rowSize(); if (rows != data.length) throw new CardinalityException(rows, data.length); for (int x = 0; x < rows; x++) setX(x, col, data[x]); return this; } /** {@inheritDoc} */ @Override public Vector getCol(int col) { checkColumnIndex(col); Vector res; if (isDistributed()) res = MatrixUtil.likeVector(this, rowSize()); else res = new DenseLocalOnHeapVector(rowSize()); for (int i = 0; i < rowSize(); i++) res.setX(i, getX(i, col)); return res; } /** {@inheritDoc} */ @Override public Matrix setX(int row, int col, double val) { storageSet(row, col, val); return this; } /** {@inheritDoc} */ @Override public double maxAbsRowSumNorm() { double max = 0.0; int rows = rowSize(); int cols = columnSize(); for (int x = 0; x < rows; x++) { double sum = 0; for (int y = 0; y < cols; y++) sum += Math.abs(getX(x, y)); if (sum > max) max = sum; } return max; } /** {@inheritDoc} */ @Override public Matrix times(double x) { Matrix cp = copy(); cp.map(Functions.mult(x)); return cp; } /** {@inheritDoc} */ @Override public Vector times(Vector vec) { int cols = columnSize(); if (cols != vec.size()) throw new CardinalityException(cols, vec.size()); int rows = rowSize(); Vector res = likeVector(rows); Blas.gemv(1, this, vec, 0, res); return res; } /** {@inheritDoc} */ @Override public Matrix times(Matrix mtx) { int cols = columnSize(); if (cols != mtx.rowSize()) throw new CardinalityException(cols, mtx.rowSize()); Matrix res = like(rowSize(), mtx.columnSize()); Blas.gemm(1, this, mtx, 0, res); return res; } /** {@inheritDoc} */ @Override public double sum() { int rows = rowSize(); int cols = columnSize(); double sum = 0.0; for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) sum += getX(x, y); return sum; } /** {@inheritDoc} */ @Override public Matrix transpose() { int rows = rowSize(); int cols = columnSize(); Matrix mtx = like(cols, rows); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) mtx.setX(y, x, getX(x, y)); return mtx; } /** {@inheritDoc} */ @Override public boolean density(double threshold) { assert threshold >= 0.0 && threshold <= 1.0; int n = MIN_SAMPLES; int rows = rowSize(); int cols = columnSize(); double mean = 0.0; double pq = threshold * (1 - threshold); Random rnd = new Random(); for (int i = 0; i < MIN_SAMPLES; i++) if (getX(rnd.nextInt(rows), rnd.nextInt(cols)) != 0.0) mean++; mean /= MIN_SAMPLES; double iv = Z80 * Math.sqrt(pq / n); if (mean < threshold - iv) return false; // Sparse. else if (mean > threshold + iv) return true; // Dense. while (n < MAX_SAMPLES) { // Determine upper bound we may need for 'n' to likely relinquish the uncertainty. // Here, we use confidence interval formula but solved for 'n'. double ivX = Math.max(Math.abs(threshold - mean), 1e-11); double stdErr = ivX / Z80; double nX = Math.min(Math.max((int)Math.ceil(pq / (stdErr * stdErr)), n), MAX_SAMPLES) - n; if (nX < 1.0) // IMPL NOTE this can happen with threshold 1.0 nX = 1.0; double meanNext = 0.0; for (int i = 0; i < nX; i++) if (getX(rnd.nextInt(rows), rnd.nextInt(cols)) != 0.0) meanNext++; mean = (n * mean + meanNext) / (n + nX); n += nX; // Are we good now? iv = Z80 * Math.sqrt(pq / n); if (mean < threshold - iv) return false; // Sparse. else if (mean > threshold + iv) return true; // Dense. } return mean > threshold; // Dense if mean > threshold. } /** {@inheritDoc} */ @Override public Matrix viewPart(int[] off, int[] size) { return new MatrixView(this, off[0], off[1], size[0], size[1]); } /** {@inheritDoc} */ @Override public Matrix viewPart(int rowOff, int rows, int colOff, int cols) { return viewPart(new int[] {rowOff, colOff}, new int[] {rows, cols}); } /** {@inheritDoc} */ @Override public Vector viewRow(int row) { return new MatrixVectorView(this, row, 0, 0, 1); } /** {@inheritDoc} */ @Override public Vector viewColumn(int col) { return new MatrixVectorView(this, 0, col, 1, 0); } /** {@inheritDoc} */ @Override public Vector viewDiagonal() { return new MatrixVectorView(this, 0, 0, 1, 1); } /** {@inheritDoc} */ @Override public void destroy() { getStorage().destroy(); } /** {@inheritDoc} */ @Override public Matrix copy() { Matrix cp = like(rowSize(), columnSize()); cp.assign(this); return cp; } /** {@inheritDoc} */ @Override public int hashCode() { int res = 1; res = res * 37 + guid.hashCode(); res = res * 37 + sto.hashCode(); res = res * 37 + meta.hashCode(); return res; } /** * {@inheritDoc} * * We ignore guid's for comparisons. */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AbstractMatrix that = (AbstractMatrix)o; MatrixStorage sto = getStorage(); return (sto != null ? sto.equals(that.getStorage()) : that.getStorage() == null); } /** {@inheritDoc} */ @Override public void compute(int row, int col, IgniteTriFunction<Integer, Integer, Double, Double> f) { setX(row, col, f.apply(row, col, getX(row, col))); } /** * Return max amount of columns in 2d array. * * TODO: why this in this class, mb some util class? * * @param data Data. */ protected int getMaxAmountOfColumns(double[][] data) { int maxAmountOfCols = 0; for (int i = 0; i < data.length; i++) maxAmountOfCols = Math.max(maxAmountOfCols, data[i].length); return maxAmountOfCols; } }
apache-2.0
markcowl/azure-sdk-for-net
sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/SensitivityLabelsRestOperations.cs
61980
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager.Sql.Models; namespace Azure.ResourceManager.Sql { internal partial class SensitivityLabelsRestOperations { private string subscriptionId; private Uri endpoint; private ClientDiagnostics _clientDiagnostics; private HttpPipeline _pipeline; /// <summary> Initializes a new instance of SensitivityLabelsRestOperations. </summary> /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param> /// <param name="endpoint"> server parameter. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception> public SensitivityLabelsRestOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string subscriptionId, Uri endpoint = null) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } endpoint ??= new Uri("https://management.azure.com"); this.subscriptionId = subscriptionId; this.endpoint = endpoint; _clientDiagnostics = clientDiagnostics; _pipeline = pipeline; } internal HttpMessage CreateListCurrentByDatabaseRequest(string resourceGroupName, string serverName, string databaseName, string filter) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Sql/servers/", false); uri.AppendPath(serverName, true); uri.AppendPath("/databases/", false); uri.AppendPath(databaseName, true); uri.AppendPath("/currentSensitivityLabels", false); if (filter != null) { uri.AppendQuery("$filter", filter, true); } uri.AppendQuery("api-version", "2017-03-01-preview", true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); return message; } /// <summary> Gets the sensitivity labels of a given database. </summary> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="filter"> An OData filter expression that filters elements in the collection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, or <paramref name="databaseName"/> is null. </exception> public async Task<Response<SensitivityLabelListResult>> ListCurrentByDatabaseAsync(string resourceGroupName, string serverName, string databaseName, string filter = null, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } using var message = CreateListCurrentByDatabaseRequest(resourceGroupName, serverName, databaseName, filter); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { SensitivityLabelListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = SensitivityLabelListResult.DeserializeSensitivityLabelListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets the sensitivity labels of a given database. </summary> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="filter"> An OData filter expression that filters elements in the collection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, or <paramref name="databaseName"/> is null. </exception> public Response<SensitivityLabelListResult> ListCurrentByDatabase(string resourceGroupName, string serverName, string databaseName, string filter = null, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } using var message = CreateListCurrentByDatabaseRequest(resourceGroupName, serverName, databaseName, filter); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { SensitivityLabelListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = SensitivityLabelListResult.DeserializeSensitivityLabelListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListRecommendedByDatabaseRequest(string resourceGroupName, string serverName, string databaseName, bool? includeDisabledRecommendations, string skipToken, string filter) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Sql/servers/", false); uri.AppendPath(serverName, true); uri.AppendPath("/databases/", false); uri.AppendPath(databaseName, true); uri.AppendPath("/recommendedSensitivityLabels", false); if (includeDisabledRecommendations != null) { uri.AppendQuery("includeDisabledRecommendations", includeDisabledRecommendations.Value, true); } if (skipToken != null) { uri.AppendQuery("$skipToken", skipToken, true); } if (filter != null) { uri.AppendQuery("$filter", filter, true); } uri.AppendQuery("api-version", "2017-03-01-preview", true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); return message; } /// <summary> Gets the sensitivity labels of a given database. </summary> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="includeDisabledRecommendations"> Specifies whether to include disabled recommendations or not. </param> /// <param name="skipToken"> The String to use. </param> /// <param name="filter"> An OData filter expression that filters elements in the collection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, or <paramref name="databaseName"/> is null. </exception> public async Task<Response<SensitivityLabelListResult>> ListRecommendedByDatabaseAsync(string resourceGroupName, string serverName, string databaseName, bool? includeDisabledRecommendations = null, string skipToken = null, string filter = null, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } using var message = CreateListRecommendedByDatabaseRequest(resourceGroupName, serverName, databaseName, includeDisabledRecommendations, skipToken, filter); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { SensitivityLabelListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = SensitivityLabelListResult.DeserializeSensitivityLabelListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets the sensitivity labels of a given database. </summary> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="includeDisabledRecommendations"> Specifies whether to include disabled recommendations or not. </param> /// <param name="skipToken"> The String to use. </param> /// <param name="filter"> An OData filter expression that filters elements in the collection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, or <paramref name="databaseName"/> is null. </exception> public Response<SensitivityLabelListResult> ListRecommendedByDatabase(string resourceGroupName, string serverName, string databaseName, bool? includeDisabledRecommendations = null, string skipToken = null, string filter = null, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } using var message = CreateListRecommendedByDatabaseRequest(resourceGroupName, serverName, databaseName, includeDisabledRecommendations, skipToken, filter); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { SensitivityLabelListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = SensitivityLabelListResult.DeserializeSensitivityLabelListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateEnableRecommendationRequest(string resourceGroupName, string serverName, string databaseName, string schemaName, string tableName, string columnName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Sql/servers/", false); uri.AppendPath(serverName, true); uri.AppendPath("/databases/", false); uri.AppendPath(databaseName, true); uri.AppendPath("/schemas/", false); uri.AppendPath(schemaName, true); uri.AppendPath("/tables/", false); uri.AppendPath(tableName, true); uri.AppendPath("/columns/", false); uri.AppendPath(columnName, true); uri.AppendPath("/sensitivityLabels/", false); uri.AppendPath("recommended", true); uri.AppendPath("/enable", false); uri.AppendQuery("api-version", "2017-03-01-preview", true); request.Uri = uri; return message; } /// <summary> Enables sensitivity recommendations on a given column (recommendations are enabled by default on all columns). </summary> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="schemaName"> The name of the schema. </param> /// <param name="tableName"> The name of the table. </param> /// <param name="columnName"> The name of the column. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/>, <paramref name="schemaName"/>, <paramref name="tableName"/>, or <paramref name="columnName"/> is null. </exception> public async Task<Response> EnableRecommendationAsync(string resourceGroupName, string serverName, string databaseName, string schemaName, string tableName, string columnName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } if (schemaName == null) { throw new ArgumentNullException(nameof(schemaName)); } if (tableName == null) { throw new ArgumentNullException(nameof(tableName)); } if (columnName == null) { throw new ArgumentNullException(nameof(columnName)); } using var message = CreateEnableRecommendationRequest(resourceGroupName, serverName, databaseName, schemaName, tableName, columnName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Enables sensitivity recommendations on a given column (recommendations are enabled by default on all columns). </summary> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="schemaName"> The name of the schema. </param> /// <param name="tableName"> The name of the table. </param> /// <param name="columnName"> The name of the column. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/>, <paramref name="schemaName"/>, <paramref name="tableName"/>, or <paramref name="columnName"/> is null. </exception> public Response EnableRecommendation(string resourceGroupName, string serverName, string databaseName, string schemaName, string tableName, string columnName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } if (schemaName == null) { throw new ArgumentNullException(nameof(schemaName)); } if (tableName == null) { throw new ArgumentNullException(nameof(tableName)); } if (columnName == null) { throw new ArgumentNullException(nameof(columnName)); } using var message = CreateEnableRecommendationRequest(resourceGroupName, serverName, databaseName, schemaName, tableName, columnName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateDisableRecommendationRequest(string resourceGroupName, string serverName, string databaseName, string schemaName, string tableName, string columnName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Sql/servers/", false); uri.AppendPath(serverName, true); uri.AppendPath("/databases/", false); uri.AppendPath(databaseName, true); uri.AppendPath("/schemas/", false); uri.AppendPath(schemaName, true); uri.AppendPath("/tables/", false); uri.AppendPath(tableName, true); uri.AppendPath("/columns/", false); uri.AppendPath(columnName, true); uri.AppendPath("/sensitivityLabels/", false); uri.AppendPath("recommended", true); uri.AppendPath("/disable", false); uri.AppendQuery("api-version", "2017-03-01-preview", true); request.Uri = uri; return message; } /// <summary> Disables sensitivity recommendations on a given column. </summary> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="schemaName"> The name of the schema. </param> /// <param name="tableName"> The name of the table. </param> /// <param name="columnName"> The name of the column. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/>, <paramref name="schemaName"/>, <paramref name="tableName"/>, or <paramref name="columnName"/> is null. </exception> public async Task<Response> DisableRecommendationAsync(string resourceGroupName, string serverName, string databaseName, string schemaName, string tableName, string columnName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } if (schemaName == null) { throw new ArgumentNullException(nameof(schemaName)); } if (tableName == null) { throw new ArgumentNullException(nameof(tableName)); } if (columnName == null) { throw new ArgumentNullException(nameof(columnName)); } using var message = CreateDisableRecommendationRequest(resourceGroupName, serverName, databaseName, schemaName, tableName, columnName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Disables sensitivity recommendations on a given column. </summary> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="schemaName"> The name of the schema. </param> /// <param name="tableName"> The name of the table. </param> /// <param name="columnName"> The name of the column. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/>, <paramref name="schemaName"/>, <paramref name="tableName"/>, or <paramref name="columnName"/> is null. </exception> public Response DisableRecommendation(string resourceGroupName, string serverName, string databaseName, string schemaName, string tableName, string columnName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } if (schemaName == null) { throw new ArgumentNullException(nameof(schemaName)); } if (tableName == null) { throw new ArgumentNullException(nameof(tableName)); } if (columnName == null) { throw new ArgumentNullException(nameof(columnName)); } using var message = CreateDisableRecommendationRequest(resourceGroupName, serverName, databaseName, schemaName, tableName, columnName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateGetRequest(string resourceGroupName, string serverName, string databaseName, string schemaName, string tableName, string columnName, SensitivityLabelSource sensitivityLabelSource) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Sql/servers/", false); uri.AppendPath(serverName, true); uri.AppendPath("/databases/", false); uri.AppendPath(databaseName, true); uri.AppendPath("/schemas/", false); uri.AppendPath(schemaName, true); uri.AppendPath("/tables/", false); uri.AppendPath(tableName, true); uri.AppendPath("/columns/", false); uri.AppendPath(columnName, true); uri.AppendPath("/sensitivityLabels/", false); uri.AppendPath(sensitivityLabelSource.ToSerialString(), true); uri.AppendQuery("api-version", "2017-03-01-preview", true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); return message; } /// <summary> Gets the sensitivity label of a given column. </summary> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="schemaName"> The name of the schema. </param> /// <param name="tableName"> The name of the table. </param> /// <param name="columnName"> The name of the column. </param> /// <param name="sensitivityLabelSource"> The source of the sensitivity label. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/>, <paramref name="schemaName"/>, <paramref name="tableName"/>, or <paramref name="columnName"/> is null. </exception> public async Task<Response<SensitivityLabel>> GetAsync(string resourceGroupName, string serverName, string databaseName, string schemaName, string tableName, string columnName, SensitivityLabelSource sensitivityLabelSource, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } if (schemaName == null) { throw new ArgumentNullException(nameof(schemaName)); } if (tableName == null) { throw new ArgumentNullException(nameof(tableName)); } if (columnName == null) { throw new ArgumentNullException(nameof(columnName)); } using var message = CreateGetRequest(resourceGroupName, serverName, databaseName, schemaName, tableName, columnName, sensitivityLabelSource); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { SensitivityLabel value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = SensitivityLabel.DeserializeSensitivityLabel(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets the sensitivity label of a given column. </summary> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="schemaName"> The name of the schema. </param> /// <param name="tableName"> The name of the table. </param> /// <param name="columnName"> The name of the column. </param> /// <param name="sensitivityLabelSource"> The source of the sensitivity label. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/>, <paramref name="schemaName"/>, <paramref name="tableName"/>, or <paramref name="columnName"/> is null. </exception> public Response<SensitivityLabel> Get(string resourceGroupName, string serverName, string databaseName, string schemaName, string tableName, string columnName, SensitivityLabelSource sensitivityLabelSource, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } if (schemaName == null) { throw new ArgumentNullException(nameof(schemaName)); } if (tableName == null) { throw new ArgumentNullException(nameof(tableName)); } if (columnName == null) { throw new ArgumentNullException(nameof(columnName)); } using var message = CreateGetRequest(resourceGroupName, serverName, databaseName, schemaName, tableName, columnName, sensitivityLabelSource); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { SensitivityLabel value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = SensitivityLabel.DeserializeSensitivityLabel(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateCreateOrUpdateRequest(string resourceGroupName, string serverName, string databaseName, string schemaName, string tableName, string columnName, SensitivityLabel parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Put; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Sql/servers/", false); uri.AppendPath(serverName, true); uri.AppendPath("/databases/", false); uri.AppendPath(databaseName, true); uri.AppendPath("/schemas/", false); uri.AppendPath(schemaName, true); uri.AppendPath("/tables/", false); uri.AppendPath(tableName, true); uri.AppendPath("/columns/", false); uri.AppendPath(columnName, true); uri.AppendPath("/sensitivityLabels/", false); uri.AppendPath("current", true); uri.AppendQuery("api-version", "2017-03-01-preview", true); request.Uri = uri; request.Headers.Add("Content-Type", "application/json"); request.Headers.Add("Accept", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; return message; } /// <summary> Creates or updates the sensitivity label of a given column. </summary> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="schemaName"> The name of the schema. </param> /// <param name="tableName"> The name of the table. </param> /// <param name="columnName"> The name of the column. </param> /// <param name="parameters"> The column sensitivity label resource. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/>, <paramref name="schemaName"/>, <paramref name="tableName"/>, <paramref name="columnName"/>, or <paramref name="parameters"/> is null. </exception> public async Task<Response<SensitivityLabel>> CreateOrUpdateAsync(string resourceGroupName, string serverName, string databaseName, string schemaName, string tableName, string columnName, SensitivityLabel parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } if (schemaName == null) { throw new ArgumentNullException(nameof(schemaName)); } if (tableName == null) { throw new ArgumentNullException(nameof(tableName)); } if (columnName == null) { throw new ArgumentNullException(nameof(columnName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateCreateOrUpdateRequest(resourceGroupName, serverName, databaseName, schemaName, tableName, columnName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 201: { SensitivityLabel value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = SensitivityLabel.DeserializeSensitivityLabel(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Creates or updates the sensitivity label of a given column. </summary> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="schemaName"> The name of the schema. </param> /// <param name="tableName"> The name of the table. </param> /// <param name="columnName"> The name of the column. </param> /// <param name="parameters"> The column sensitivity label resource. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/>, <paramref name="schemaName"/>, <paramref name="tableName"/>, <paramref name="columnName"/>, or <paramref name="parameters"/> is null. </exception> public Response<SensitivityLabel> CreateOrUpdate(string resourceGroupName, string serverName, string databaseName, string schemaName, string tableName, string columnName, SensitivityLabel parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } if (schemaName == null) { throw new ArgumentNullException(nameof(schemaName)); } if (tableName == null) { throw new ArgumentNullException(nameof(tableName)); } if (columnName == null) { throw new ArgumentNullException(nameof(columnName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateCreateOrUpdateRequest(resourceGroupName, serverName, databaseName, schemaName, tableName, columnName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 201: { SensitivityLabel value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = SensitivityLabel.DeserializeSensitivityLabel(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateDeleteRequest(string resourceGroupName, string serverName, string databaseName, string schemaName, string tableName, string columnName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Delete; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Sql/servers/", false); uri.AppendPath(serverName, true); uri.AppendPath("/databases/", false); uri.AppendPath(databaseName, true); uri.AppendPath("/schemas/", false); uri.AppendPath(schemaName, true); uri.AppendPath("/tables/", false); uri.AppendPath(tableName, true); uri.AppendPath("/columns/", false); uri.AppendPath(columnName, true); uri.AppendPath("/sensitivityLabels/", false); uri.AppendPath("current", true); uri.AppendQuery("api-version", "2017-03-01-preview", true); request.Uri = uri; return message; } /// <summary> Deletes the sensitivity label of a given column. </summary> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="schemaName"> The name of the schema. </param> /// <param name="tableName"> The name of the table. </param> /// <param name="columnName"> The name of the column. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/>, <paramref name="schemaName"/>, <paramref name="tableName"/>, or <paramref name="columnName"/> is null. </exception> public async Task<Response> DeleteAsync(string resourceGroupName, string serverName, string databaseName, string schemaName, string tableName, string columnName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } if (schemaName == null) { throw new ArgumentNullException(nameof(schemaName)); } if (tableName == null) { throw new ArgumentNullException(nameof(tableName)); } if (columnName == null) { throw new ArgumentNullException(nameof(columnName)); } using var message = CreateDeleteRequest(resourceGroupName, serverName, databaseName, schemaName, tableName, columnName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Deletes the sensitivity label of a given column. </summary> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="schemaName"> The name of the schema. </param> /// <param name="tableName"> The name of the table. </param> /// <param name="columnName"> The name of the column. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/>, <paramref name="schemaName"/>, <paramref name="tableName"/>, or <paramref name="columnName"/> is null. </exception> public Response Delete(string resourceGroupName, string serverName, string databaseName, string schemaName, string tableName, string columnName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } if (schemaName == null) { throw new ArgumentNullException(nameof(schemaName)); } if (tableName == null) { throw new ArgumentNullException(nameof(tableName)); } if (columnName == null) { throw new ArgumentNullException(nameof(columnName)); } using var message = CreateDeleteRequest(resourceGroupName, serverName, databaseName, schemaName, tableName, columnName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListCurrentByDatabaseNextPageRequest(string nextLink, string resourceGroupName, string serverName, string databaseName, string filter) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); return message; } /// <summary> Gets the sensitivity labels of a given database. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="filter"> An OData filter expression that filters elements in the collection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, or <paramref name="databaseName"/> is null. </exception> public async Task<Response<SensitivityLabelListResult>> ListCurrentByDatabaseNextPageAsync(string nextLink, string resourceGroupName, string serverName, string databaseName, string filter = null, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } using var message = CreateListCurrentByDatabaseNextPageRequest(nextLink, resourceGroupName, serverName, databaseName, filter); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { SensitivityLabelListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = SensitivityLabelListResult.DeserializeSensitivityLabelListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets the sensitivity labels of a given database. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="filter"> An OData filter expression that filters elements in the collection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, or <paramref name="databaseName"/> is null. </exception> public Response<SensitivityLabelListResult> ListCurrentByDatabaseNextPage(string nextLink, string resourceGroupName, string serverName, string databaseName, string filter = null, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } using var message = CreateListCurrentByDatabaseNextPageRequest(nextLink, resourceGroupName, serverName, databaseName, filter); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { SensitivityLabelListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = SensitivityLabelListResult.DeserializeSensitivityLabelListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListRecommendedByDatabaseNextPageRequest(string nextLink, string resourceGroupName, string serverName, string databaseName, bool? includeDisabledRecommendations, string skipToken, string filter) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); return message; } /// <summary> Gets the sensitivity labels of a given database. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="includeDisabledRecommendations"> Specifies whether to include disabled recommendations or not. </param> /// <param name="skipToken"> The String to use. </param> /// <param name="filter"> An OData filter expression that filters elements in the collection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, or <paramref name="databaseName"/> is null. </exception> public async Task<Response<SensitivityLabelListResult>> ListRecommendedByDatabaseNextPageAsync(string nextLink, string resourceGroupName, string serverName, string databaseName, bool? includeDisabledRecommendations = null, string skipToken = null, string filter = null, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } using var message = CreateListRecommendedByDatabaseNextPageRequest(nextLink, resourceGroupName, serverName, databaseName, includeDisabledRecommendations, skipToken, filter); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { SensitivityLabelListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = SensitivityLabelListResult.DeserializeSensitivityLabelListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets the sensitivity labels of a given database. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="includeDisabledRecommendations"> Specifies whether to include disabled recommendations or not. </param> /// <param name="skipToken"> The String to use. </param> /// <param name="filter"> An OData filter expression that filters elements in the collection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, or <paramref name="databaseName"/> is null. </exception> public Response<SensitivityLabelListResult> ListRecommendedByDatabaseNextPage(string nextLink, string resourceGroupName, string serverName, string databaseName, bool? includeDisabledRecommendations = null, string skipToken = null, string filter = null, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } using var message = CreateListRecommendedByDatabaseNextPageRequest(nextLink, resourceGroupName, serverName, databaseName, includeDisabledRecommendations, skipToken, filter); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { SensitivityLabelListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = SensitivityLabelListResult.DeserializeSensitivityLabelListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } } }
apache-2.0
ctripcorp/x-pipe
redis/redis-proxy/src/main/java/com/ctrip/xpipe/redis/proxy/spring/Production.java
2700
package com.ctrip.xpipe.redis.proxy.spring; import com.ctrip.xpipe.redis.core.proxy.endpoint.DefaultProxyEndpointManager; import com.ctrip.xpipe.redis.core.proxy.endpoint.ProxyEndpointManager; import com.ctrip.xpipe.redis.core.proxy.handler.NettyClientSslHandlerFactory; import com.ctrip.xpipe.redis.core.proxy.handler.NettyServerSslHandlerFactory; import com.ctrip.xpipe.redis.core.proxy.handler.NettySslHandlerFactory; import com.ctrip.xpipe.redis.proxy.config.DefaultProxyConfig; import com.ctrip.xpipe.redis.proxy.config.ProxyConfig; import com.ctrip.xpipe.spring.AbstractProfile; import com.ctrip.xpipe.utils.OsUtils; import com.ctrip.xpipe.utils.XpipeThreadFactory; import com.google.common.util.concurrent.MoreExecutors; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * @author chen.zhu * <p> * May 10, 2018 */ @Configuration @Profile(AbstractProfile.PROFILE_NAME_PRODUCTION) public class Production extends AbstractProfile { public static final String GLOBAL_ENDPOINT_MANAGER = "globalProxyEndpointManager"; public static final String CLIENT_SSL_HANDLER_FACTORY = "clientSslHandlerFactory"; public static final String SERVER_SSL_HANDLER_FACTORY = "serverSslHandlerFactory"; public static final String BACKEND_EVENTLOOP_GROUP = "backendEventLoopGroup"; public static final String GLOBAL_SCHEDULED = "globalScheduled"; private ProxyConfig config = new DefaultProxyConfig(); @Bean public ProxyConfig getProxyConfig() { return config; } @Bean(name = CLIENT_SSL_HANDLER_FACTORY) public NettySslHandlerFactory clientSslHandlerFactory() { return new NettyClientSslHandlerFactory(config); } @Bean(name = SERVER_SSL_HANDLER_FACTORY) public NettySslHandlerFactory serverSslHandlerFactory() { return new NettyServerSslHandlerFactory(config); } @Bean(name = GLOBAL_SCHEDULED) public ScheduledExecutorService getScheduled() { int corePoolSize = Math.min(OsUtils.getCpuCount(), 4); return MoreExecutors.getExitingScheduledExecutorService( new ScheduledThreadPoolExecutor(corePoolSize, XpipeThreadFactory.create(GLOBAL_SCHEDULED)), 1, TimeUnit.SECONDS ); } @Bean(name = GLOBAL_ENDPOINT_MANAGER) public ProxyEndpointManager getProxyResourceManager() { return new DefaultProxyEndpointManager(() -> config.endpointHealthCheckIntervalSec()); } }
apache-2.0
mdoering/backbone
life/Fungi/Zygomycota/Mucorales/Mucoraceae/Mucor/Mucor fimeti/README.md
169
# Mucor fimeti Schrank SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Mucor fimeti Schrank ### Remarks null
apache-2.0
holajan/dotvvm
src/DotVVM.Framework/Parser/Dothtml/Parser/DothtmlBindingNode.cs
666
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace DotVVM.Framework.Parser.Dothtml.Parser { [DebuggerDisplay("{debuggerDisplay,nq}")] public class DothtmlBindingNode : DothtmlLiteralNode { #region debbuger display [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string debuggerDisplay { get { return "{" + Name + ": " + Value + "}"; } } #endregion public string Name { get; set; } public DothtmlBindingNode() { Escape = true; } } }
apache-2.0
Mageswaran1989/aja
src/examples/scala/org/aja/tej/examples/ml/Pipeline.scala
1867
package org.aja.tej.examples.ml import org.aja.tej.utils.TejUtils import org.apache.spark.sql.SQLContext import org.apache.spark.ml.Pipeline import org.apache.spark.ml.classification.LogisticRegression import org.apache.spark.ml.feature.{HashingTF, Tokenizer} import org.apache.spark.mllib.linalg.Vector import org.apache.spark.sql.Row /** * Created by mageswaran on 27/9/15. */ object Pipeline extends App { val sc = TejUtils.getSparkContext("Pipeline") val sqlContext= new SQLContext(sc) // Prepare training documents from a list of (id, text, label) tuples. val training = sqlContext.createDataFrame(Seq( (0L, "a b c d e spark", 1.0), (1L, "b d", 0.0), (2L, "spark f g h", 1.0), (3L, "hadoop mapreduce", 0.0) )).toDF("id", "text", "label") // Configure an ML pipeline, which consists of three stages: tokenizer, hashingTF, and lr. val tokenizer = new Tokenizer() .setInputCol("text") .setOutputCol("words") val hashingTF = new HashingTF() .setNumFeatures(1000) .setInputCol(tokenizer.getOutputCol) .setOutputCol("features") val lr = new LogisticRegression() .setMaxIter(10) .setRegParam(0.01) val pipeline = new Pipeline() .setStages(Array(tokenizer, hashingTF, lr)) // Fit the pipeline to training documents. val model = pipeline.fit(training) // Prepare test documents, which are unlabeled (id, text) tuples. val test = sqlContext.createDataFrame(Seq( (4L, "spark i j k"), (5L, "l m n"), (6L, "mapreduce spark"), (7L, "apache hadoop") )).toDF("id", "text") // Make predictions on test documents. model.transform(test.toDF) .select("id", "text", "probability", "prediction") .collect() .foreach { case Row(id: Long, text: String, prob: Vector, prediction: Double) => println(s"($id, $text) --> prob=$prob, prediction=$prediction") } }
apache-2.0
Lucidastar/hodgepodgeForAndroid
app/src/main/java/com/lucidastar/hodgepodge/view/CircleProgressView.java
22758
package com.lucidastar.hodgepodge.view; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.os.Bundle; import android.os.Parcelable; import android.util.AttributeSet; import android.view.animation.AccelerateDecelerateInterpolator; import android.widget.ProgressBar; import androidx.annotation.IntDef; import com.lucidastar.hodgepodge.R; import com.mine.lucidastarutils.utils.ScreenUtils; import com.mine.lucidastarutils.utils.Utils; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Created by qiuyouzone on 2018/10/9. */ public class CircleProgressView extends ProgressBar { private int mReachBarSize = ScreenUtils.dp2px(getContext(), 2); // 未完成进度条大小 private int mNormalBarSize = ScreenUtils.dp2px(getContext(), 2); // 未完成进度条大小 private int mReachBarColor = Color.parseColor("#108ee9"); // 已完成进度颜色 private int mNormalBarColor = Color.parseColor("#FFD3D6DA"); // 未完成进度颜色 private int mTextSize = ScreenUtils.sp2px(getContext(), 14); // 进度值字体大小 private int mTextColor = Color.parseColor("#108ee9"); // 进度的值字体颜色 private float mTextSkewX; // 进度值字体倾斜角度 private String mTextSuffix = "%"; // 进度值前缀 private String mTextPrefix = ""; // 进度值后缀 private boolean mTextVisible = true; // 是否显示进度值 private boolean mReachCapRound; // 画笔是否使用圆角边界,normalStyle下生效 private int mRadius = ScreenUtils.dp2px(getContext(), 20); // 半径 private int mStartArc; // 起始角度 private int mInnerBackgroundColor; // 内部背景填充颜色 private int mProgressStyle = ProgressStyle.NORMAL; // 进度风格 private int mInnerPadding = ScreenUtils.dp2px(getContext(), 1); // 内部圆与外部圆间距 private int mOuterColor; // 外部圆环颜色 private boolean needDrawInnerBackground; // 是否需要绘制内部背景 private RectF rectF; // 外部圆环绘制区域 private RectF rectInner; // 内部圆环绘制区域 private int mOuterSize = ScreenUtils.dp2px(getContext(), 1); // 外层圆环宽度 private Paint mTextPaint; // 绘制进度值字体画笔 private Paint mNormalPaint; // 绘制未完成进度画笔 private Paint mReachPaint; // 绘制已完成进度画笔 private Paint mInnerBackgroundPaint; // 内部背景画笔 private Paint mOutPaint; // 外部圆环画笔 private int mRealWidth; private int mRealHeight; @IntDef({ProgressStyle.NORMAL, ProgressStyle.FILL_IN, ProgressStyle.FILL_IN_ARC}) @Retention(RetentionPolicy.SOURCE) public @interface ProgressStyle { int NORMAL = 0; int FILL_IN = 1; int FILL_IN_ARC = 2; } public CircleProgressView(Context context) { this(context, null); } public CircleProgressView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CircleProgressView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); obtainAttributes(attrs); initPaint(); } private void initPaint() { mTextPaint = new Paint(); mTextPaint.setColor(mTextColor); mTextPaint.setStyle(Paint.Style.FILL); mTextPaint.setTextSize(mTextSize); mTextPaint.setTextSkewX(mTextSkewX); mTextPaint.setAntiAlias(true); mNormalPaint = new Paint(); mNormalPaint.setColor(mNormalBarColor); mNormalPaint.setStyle(mProgressStyle == ProgressStyle.FILL_IN_ARC ? Paint.Style.FILL : Paint.Style.STROKE); mNormalPaint.setAntiAlias(true); mNormalPaint.setStrokeWidth(mNormalBarSize); mReachPaint = new Paint(); mReachPaint.setColor(mReachBarColor); mReachPaint.setStyle(mProgressStyle == ProgressStyle.FILL_IN_ARC ? Paint.Style.FILL : Paint.Style.STROKE); mReachPaint.setAntiAlias(true); mReachPaint.setStrokeCap(mReachCapRound ? Paint.Cap.ROUND : Paint.Cap.BUTT); mReachPaint.setStrokeWidth(mReachBarSize); if (needDrawInnerBackground) { mInnerBackgroundPaint = new Paint(); mInnerBackgroundPaint.setStyle(Paint.Style.FILL); mInnerBackgroundPaint.setAntiAlias(true); mInnerBackgroundPaint.setColor(mInnerBackgroundColor); } if (mProgressStyle == ProgressStyle.FILL_IN_ARC) { mOutPaint = new Paint(); mOutPaint.setStyle(Paint.Style.STROKE); mOutPaint.setColor(mOuterColor); mOutPaint.setStrokeWidth(mOuterSize); mOutPaint.setAntiAlias(true); } } private void obtainAttributes(AttributeSet attrs) { TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.CircleProgressView); mProgressStyle = ta.getInt(R.styleable.CircleProgressView_cpv_progressStyle, ProgressStyle.NORMAL); // 获取三种风格通用的属性 mNormalBarSize = (int) ta.getDimension(R.styleable.CircleProgressView_cpv_progressNormalSize, mNormalBarSize); mNormalBarColor = ta.getColor(R.styleable.CircleProgressView_cpv_progressNormalColor, mNormalBarColor); mReachBarSize = (int) ta.getDimension(R.styleable.CircleProgressView_cpv_progressReachSize, mReachBarSize); mReachBarColor = ta.getColor(R.styleable.CircleProgressView_cpv_progressReachColor, mReachBarColor); mTextSize = (int) ta.getDimension(R.styleable.CircleProgressView_cpv_progressTextSize, mTextSize); mTextColor = ta.getColor(R.styleable.CircleProgressView_cpv_progressTextColor, mTextColor); mTextSkewX = ta.getDimension(R.styleable.CircleProgressView_cpv_progressTextSkewX, 0); if (ta.hasValue(R.styleable.CircleProgressView_cpv_progressTextSuffix)) { mTextSuffix = ta.getString(R.styleable.CircleProgressView_cpv_progressTextSuffix); } if (ta.hasValue(R.styleable.CircleProgressView_cpv_progressTextPrefix)) { mTextPrefix = ta.getString(R.styleable.CircleProgressView_cpv_progressTextPrefix); } mTextVisible = ta.getBoolean(R.styleable.CircleProgressView_cpv_progressTextVisible, mTextVisible); mRadius = (int) ta.getDimension(R.styleable.CircleProgressView_cpv_radius, mRadius); rectF = new RectF(-mRadius, -mRadius, mRadius, mRadius); switch (mProgressStyle) { case ProgressStyle.FILL_IN: mReachBarSize = 0; mNormalBarSize = 0; mOuterSize = 0; break; case ProgressStyle.FILL_IN_ARC: mStartArc = ta.getInt(R.styleable.CircleProgressView_cpv_progressStartArc, 0) + 270; mInnerPadding = (int) ta.getDimension(R.styleable.CircleProgressView_cpv_innerPadding, mInnerPadding); mOuterColor = ta.getColor(R.styleable.CircleProgressView_cpv_outerColor, mReachBarColor); mOuterSize = (int) ta.getDimension(R.styleable.CircleProgressView_cpv_outerSize, mOuterSize); mReachBarSize = 0;// 将画笔大小重置为0 mNormalBarSize = 0; if (!ta.hasValue(R.styleable.CircleProgressView_cpv_progressNormalColor)) { mNormalBarColor = Color.TRANSPARENT; } int mInnerRadius = mRadius - mOuterSize / 2 - mInnerPadding; rectInner = new RectF(-mInnerRadius, -mInnerRadius, mInnerRadius, mInnerRadius); break; case ProgressStyle.NORMAL: mReachCapRound = ta.getBoolean(R.styleable.CircleProgressView_cpv_reachCapRound, true); mStartArc = ta.getInt(R.styleable.CircleProgressView_cpv_progressStartArc, 0) + 270; if (ta.hasValue(R.styleable.CircleProgressView_cpv_innerBackgroundColor)) { mInnerBackgroundColor = ta.getColor(R.styleable.CircleProgressView_cpv_innerBackgroundColor, Color.argb(0, 0, 0, 0)); needDrawInnerBackground = true; } break; } ta.recycle(); } @Override protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int maxBarPaintWidth = Math.max(mReachBarSize, mNormalBarSize); int maxPaintWidth = Math.max(maxBarPaintWidth, mOuterSize); int height = 0; int width = 0; switch (mProgressStyle) { case ProgressStyle.FILL_IN: height = getPaddingTop() + getPaddingBottom() // 边距 + Math.abs(mRadius * 2); // 直径 width = getPaddingLeft() + getPaddingRight() // 边距 + Math.abs(mRadius * 2); // 直径 break; case ProgressStyle.FILL_IN_ARC: height = getPaddingTop() + getPaddingBottom() // 边距 + Math.abs(mRadius * 2) // 直径 + maxPaintWidth;// 边框 width = getPaddingLeft() + getPaddingRight() // 边距 + Math.abs(mRadius * 2) // 直径 + maxPaintWidth;// 边框 break; case ProgressStyle.NORMAL: height = getPaddingTop() + getPaddingBottom() // 边距 + Math.abs(mRadius * 2) // 直径 + maxBarPaintWidth;// 边框 width = getPaddingLeft() + getPaddingRight() // 边距 + Math.abs(mRadius * 2) // 直径 + maxBarPaintWidth;// 边框 break; } mRealWidth = resolveSize(width, widthMeasureSpec); mRealHeight = resolveSize(height, heightMeasureSpec); setMeasuredDimension(mRealWidth, mRealHeight); } @Override protected synchronized void onDraw(Canvas canvas) { switch (mProgressStyle) { case ProgressStyle.NORMAL: drawNormalCircle(canvas); break; case ProgressStyle.FILL_IN: drawFillInCircle(canvas); break; case ProgressStyle.FILL_IN_ARC: drawFillInArcCircle(canvas); break; } } /** * 绘制PROGRESS_STYLE_FILL_IN_ARC圆形 */ private void drawFillInArcCircle(Canvas canvas) { canvas.save(); canvas.translate(mRealWidth / 2, mRealHeight / 2); // 绘制外层圆环 canvas.drawArc(rectF, 0, 360, false, mOutPaint); // 绘制内层进度实心圆弧 // 内层圆弧半径 float reachArc = getProgress() * 1.0f / getMax() * 360; canvas.drawArc(rectInner, mStartArc, reachArc, true, mReachPaint); // 绘制未到达进度 if (reachArc != 360) { canvas.drawArc(rectInner, reachArc + mStartArc, 360 - reachArc, true, mNormalPaint); } canvas.restore(); } /** * 绘制PROGRESS_STYLE_FILL_IN圆形 */ private void drawFillInCircle(Canvas canvas) { canvas.save(); canvas.translate(mRealWidth / 2, mRealHeight / 2); float progressY = getProgress() * 1.0f / getMax() * (mRadius * 2); float angle = (float) (Math.acos((mRadius - progressY) / mRadius) * 180 / Math.PI); float startAngle = 90 + angle; float sweepAngle = 360 - angle * 2; // 绘制未到达区域 rectF = new RectF(-mRadius, -mRadius, mRadius, mRadius); mNormalPaint.setStyle(Paint.Style.FILL); canvas.drawArc(rectF, startAngle, sweepAngle, false, mNormalPaint); // 翻转180度绘制已到达区域 canvas.rotate(180); mReachPaint.setStyle(Paint.Style.FILL); canvas.drawArc(rectF, 270 - angle, angle * 2, false, mReachPaint); // 文字显示在最上层最后绘制 canvas.rotate(180); // 绘制文字 if (mTextVisible) { String text = mTextPrefix + getProgress() + mTextSuffix; float textWidth = mTextPaint.measureText(text); float textHeight = (mTextPaint.descent() + mTextPaint.ascent()); canvas.drawText(text, -textWidth / 2, -textHeight / 2, mTextPaint); } } /** * 绘制PROGRESS_STYLE_NORMAL圆形 */ private void drawNormalCircle(Canvas canvas) { canvas.save(); canvas.translate(mRealWidth / 2, mRealHeight / 2); // 绘制内部圆形背景色 if (needDrawInnerBackground) { canvas.drawCircle(0, 0, mRadius - Math.min(mReachBarSize, mNormalBarSize) / 2, mInnerBackgroundPaint); } // 绘制文字 if (mTextVisible) { String text = mTextPrefix + getProgress() + mTextSuffix; float textWidth = mTextPaint.measureText(text); float textHeight = (mTextPaint.descent() + mTextPaint.ascent()); canvas.drawText(text, -textWidth / 2, -textHeight / 2, mTextPaint); } // 计算进度值 float reachArc = getProgress() * 1.0f / getMax() * 360; // 绘制未到达进度 if (reachArc != 360) { canvas.drawArc(rectF, reachArc + mStartArc, 360 - reachArc, false, mNormalPaint); } // 绘制已到达进度 canvas.drawArc(rectF, mStartArc, reachArc, false, mReachPaint); canvas.restore(); } /** * 动画进度(0-当前进度) * * @param duration 动画时长 */ public void runProgressAnim(long duration) { setProgressInTime(0, duration); } /** * @param progress 进度值 * @param duration 动画播放时间 */ public void setProgressInTime(final int progress, final long duration) { setProgressInTime(progress, getProgress(), duration); } /** * @param startProgress 起始进度 * @param progress 进度值 * @param duration 动画播放时间 */ public void setProgressInTime(int startProgress, final int progress, final long duration) { ValueAnimator valueAnimator = ValueAnimator.ofInt(startProgress, progress); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animator) { //获得当前动画的进度值,整型,1-100之间 int currentValue = (Integer) animator.getAnimatedValue(); setProgress(currentValue); } }); AccelerateDecelerateInterpolator interpolator = new AccelerateDecelerateInterpolator(); valueAnimator.setInterpolator(interpolator); valueAnimator.setDuration(duration); valueAnimator.start(); } public int getReachBarSize() { return mReachBarSize; } public void setReachBarSize(int reachBarSize) { mReachBarSize = ScreenUtils.dp2px(getContext(), reachBarSize); invalidate(); } public int getNormalBarSize() { return mNormalBarSize; } public void setNormalBarSize(int normalBarSize) { mNormalBarSize = ScreenUtils.dp2px(getContext(), normalBarSize); invalidate(); } public int getReachBarColor() { return mReachBarColor; } public void setReachBarColor(int reachBarColor) { mReachBarColor = reachBarColor; invalidate(); } public int getNormalBarColor() { return mNormalBarColor; } public void setNormalBarColor(int normalBarColor) { mNormalBarColor = normalBarColor; invalidate(); } public int getTextSize() { return mTextSize; } public void setTextSize(int textSize) { mTextSize = ScreenUtils.sp2px(getContext(), textSize); invalidate(); } public int getTextColor() { return mTextColor; } public void setTextColor(int textColor) { mTextColor = textColor; invalidate(); } public float getTextSkewX() { return mTextSkewX; } public void setTextSkewX(float textSkewX) { mTextSkewX = textSkewX; invalidate(); } public String getTextSuffix() { return mTextSuffix; } public void setTextSuffix(String textSuffix) { mTextSuffix = textSuffix; invalidate(); } public String getTextPrefix() { return mTextPrefix; } public void setTextPrefix(String textPrefix) { mTextPrefix = textPrefix; invalidate(); } public boolean isTextVisible() { return mTextVisible; } public void setTextVisible(boolean textVisible) { mTextVisible = textVisible; invalidate(); } public boolean isReachCapRound() { return mReachCapRound; } public void setReachCapRound(boolean reachCapRound) { mReachCapRound = reachCapRound; invalidate(); } public int getRadius() { return mRadius; } public void setRadius(int radius) { mRadius = ScreenUtils.dp2px(getContext(), radius); invalidate(); } public int getStartArc() { return mStartArc; } public void setStartArc(int startArc) { mStartArc = startArc; invalidate(); } public int getInnerBackgroundColor() { return mInnerBackgroundColor; } public void setInnerBackgroundColor(int innerBackgroundColor) { mInnerBackgroundColor = innerBackgroundColor; invalidate(); } public int getProgressStyle() { return mProgressStyle; } public void setProgressStyle(int progressStyle) { mProgressStyle = progressStyle; invalidate(); } public int getInnerPadding() { return mInnerPadding; } public void setInnerPadding(int innerPadding) { mInnerPadding = ScreenUtils.dp2px(getContext(), innerPadding); int mInnerRadius = mRadius - mOuterSize / 2 - mInnerPadding; rectInner = new RectF(-mInnerRadius, -mInnerRadius, mInnerRadius, mInnerRadius); invalidate(); } public int getOuterColor() { return mOuterColor; } public void setOuterColor(int outerColor) { mOuterColor = outerColor; invalidate(); } public int getOuterSize() { return mOuterSize; } public void setOuterSize(int outerSize) { mOuterSize = ScreenUtils.dp2px(getContext(), outerSize); invalidate(); } private static final String STATE = "state"; private static final String PROGRESS_STYLE = "progressStyle"; private static final String TEXT_COLOR = "textColor"; private static final String TEXT_SIZE = "textSize"; private static final String TEXT_SKEW_X = "textSkewX"; private static final String TEXT_VISIBLE = "textVisible"; private static final String TEXT_SUFFIX = "textSuffix"; private static final String TEXT_PREFIX = "textPrefix"; private static final String REACH_BAR_COLOR = "reachBarColor"; private static final String REACH_BAR_SIZE = "reachBarSize"; private static final String NORMAL_BAR_COLOR = "normalBarColor"; private static final String NORMAL_BAR_SIZE = "normalBarSize"; private static final String IS_REACH_CAP_ROUND = "isReachCapRound"; private static final String RADIUS = "radius"; private static final String START_ARC = "startArc"; private static final String INNER_BG_COLOR = "innerBgColor"; private static final String INNER_PADDING = "innerPadding"; private static final String OUTER_COLOR = "outerColor"; private static final String OUTER_SIZE = "outerSize"; @Override public Parcelable onSaveInstanceState() { final Bundle bundle = new Bundle(); bundle.putParcelable(STATE, super.onSaveInstanceState()); // 保存当前样式 bundle.putInt(PROGRESS_STYLE, getProgressStyle()); bundle.putInt(RADIUS, getRadius()); bundle.putBoolean(IS_REACH_CAP_ROUND, isReachCapRound()); bundle.putInt(START_ARC, getStartArc()); bundle.putInt(INNER_BG_COLOR, getInnerBackgroundColor()); bundle.putInt(INNER_PADDING, getInnerPadding()); bundle.putInt(OUTER_COLOR, getOuterColor()); bundle.putInt(OUTER_SIZE, getOuterSize()); // 保存text信息 bundle.putInt(TEXT_COLOR, getTextColor()); bundle.putInt(TEXT_SIZE, getTextSize()); bundle.putFloat(TEXT_SKEW_X, getTextSkewX()); bundle.putBoolean(TEXT_VISIBLE, isTextVisible()); bundle.putString(TEXT_SUFFIX, getTextSuffix()); bundle.putString(TEXT_PREFIX, getTextPrefix()); // 保存已到达进度信息 bundle.putInt(REACH_BAR_COLOR, getReachBarColor()); bundle.putInt(REACH_BAR_SIZE, getReachBarSize()); // 保存未到达进度信息 bundle.putInt(NORMAL_BAR_COLOR, getNormalBarColor()); bundle.putInt(NORMAL_BAR_SIZE, getNormalBarSize()); return bundle; } @Override public void onRestoreInstanceState(Parcelable state) { if (state instanceof Bundle) { final Bundle bundle = (Bundle) state; mProgressStyle = bundle.getInt(PROGRESS_STYLE); mRadius = bundle.getInt(RADIUS); mReachCapRound = bundle.getBoolean(IS_REACH_CAP_ROUND); mStartArc = bundle.getInt(START_ARC); mInnerBackgroundColor = bundle.getInt(INNER_BG_COLOR); mInnerPadding = bundle.getInt(INNER_PADDING); mOuterColor = bundle.getInt(OUTER_COLOR); mOuterSize = bundle.getInt(OUTER_SIZE); mTextColor = bundle.getInt(TEXT_COLOR); mTextSize = bundle.getInt(TEXT_SIZE); mTextSkewX = bundle.getFloat(TEXT_SKEW_X); mTextVisible = bundle.getBoolean(TEXT_VISIBLE); mTextSuffix = bundle.getString(TEXT_SUFFIX); mTextPrefix = bundle.getString(TEXT_PREFIX); mReachBarColor = bundle.getInt(REACH_BAR_COLOR); mReachBarSize = bundle.getInt(REACH_BAR_SIZE); mNormalBarColor = bundle.getInt(NORMAL_BAR_COLOR); mNormalBarSize = bundle.getInt(NORMAL_BAR_SIZE); initPaint(); super.onRestoreInstanceState(bundle.getParcelable(STATE)); return; } super.onRestoreInstanceState(state); } @Override public void invalidate() { initPaint(); super.invalidate(); } }
apache-2.0
bowlofstew/kythe
third_party/typescript/src/server/editorServices.ts
96179
/// <reference path="..\compiler\commandLineParser.ts" /> /// <reference path="..\services\services.ts" /> /// <reference path="protocol.d.ts" /> /// <reference path="session.ts" /> namespace ts.server { export interface Logger { close(): void; isVerbose(): boolean; loggingEnabled(): boolean; perftrc(s: string): void; info(s: string): void; startGroup(): void; endGroup(): void; msg(s: string, type?: string): void; } const lineCollectionCapacity = 4; function mergeFormatOptions(formatCodeOptions: FormatCodeOptions, formatOptions: protocol.FormatOptions): void { const hasOwnProperty = Object.prototype.hasOwnProperty; Object.keys(formatOptions).forEach((key) => { const codeKey = key.charAt(0).toUpperCase() + key.substring(1); if (hasOwnProperty.call(formatCodeOptions, codeKey)) { formatCodeOptions[codeKey] = formatOptions[key]; } }); } export class ScriptInfo { svc: ScriptVersionCache; children: ScriptInfo[] = []; // files referenced by this file defaultProject: Project; // project to use by default for file fileWatcher: FileWatcher; formatCodeOptions = ts.clone(CompilerService.defaultFormatCodeOptions); path: Path; constructor(private host: ServerHost, public fileName: string, public content: string, public isOpen = false) { this.path = toPath(fileName, host.getCurrentDirectory(), createGetCanonicalFileName(host.useCaseSensitiveFileNames)); this.svc = ScriptVersionCache.fromString(host, content); } setFormatOptions(formatOptions: protocol.FormatOptions): void { if (formatOptions) { mergeFormatOptions(this.formatCodeOptions, formatOptions); } } close() { this.isOpen = false; } addChild(childInfo: ScriptInfo) { this.children.push(childInfo); } snap() { return this.svc.getSnapshot(); } getText() { const snap = this.snap(); return snap.getText(0, snap.getLength()); } getLineInfo(line: number) { const snap = this.snap(); return snap.index.lineNumberToInfo(line); } editContent(start: number, end: number, newText: string): void { this.svc.edit(start, end - start, newText); } getTextChangeRangeBetweenVersions(startVersion: number, endVersion: number): ts.TextChangeRange { return this.svc.getTextChangesBetweenVersions(startVersion, endVersion); } getChangeRange(oldSnapshot: ts.IScriptSnapshot): ts.TextChangeRange { return this.snap().getChangeRange(oldSnapshot); } } interface TimestampedResolvedModule extends ResolvedModuleWithFailedLookupLocations { lastCheckTime: number; } export class LSHost implements ts.LanguageServiceHost { ls: ts.LanguageService; compilationSettings: ts.CompilerOptions; filenameToScript: ts.FileMap<ScriptInfo>; roots: ScriptInfo[] = []; private resolvedModuleNames: ts.FileMap<Map<TimestampedResolvedModule>>; private moduleResolutionHost: ts.ModuleResolutionHost; private getCanonicalFileName: (fileName: string) => string; constructor(public host: ServerHost, public project: Project) { this.getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); this.resolvedModuleNames = createFileMap<Map<TimestampedResolvedModule>>(); this.filenameToScript = createFileMap<ScriptInfo>(); this.moduleResolutionHost = { fileExists: fileName => this.fileExists(fileName), readFile: fileName => this.host.readFile(fileName) }; } resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModule[] { const path = toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); const currentResolutionsInFile = this.resolvedModuleNames.get(path); const newResolutions: Map<TimestampedResolvedModule> = {}; const resolvedModules: ResolvedModule[] = []; const compilerOptions = this.getCompilationSettings(); for (const moduleName of moduleNames) { // check if this is a duplicate entry in the list let resolution = lookUp(newResolutions, moduleName); if (!resolution) { const existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, moduleName); if (moduleResolutionIsValid(existingResolution)) { // ok, it is safe to use existing module resolution results resolution = existingResolution; } else { resolution = <TimestampedResolvedModule>resolveModuleName(moduleName, containingFile, compilerOptions, this.moduleResolutionHost); resolution.lastCheckTime = Date.now(); newResolutions[moduleName] = resolution; } } ts.Debug.assert(resolution !== undefined); resolvedModules.push(resolution.resolvedModule); } // replace old results with a new one this.resolvedModuleNames.set(path, newResolutions); return resolvedModules; function moduleResolutionIsValid(resolution: TimestampedResolvedModule): boolean { if (!resolution) { return false; } if (resolution.resolvedModule) { // TODO: consider checking failedLookupLocations // TODO: use lastCheckTime to track expiration for module name resolution return true; } // consider situation if we have no candidate locations as valid resolution. // after all there is no point to invalidate it if we have no idea where to look for the module. return resolution.failedLookupLocations.length === 0; } } getDefaultLibFileName() { const nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath())); return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings)); } getScriptSnapshot(filename: string): ts.IScriptSnapshot { const scriptInfo = this.getScriptInfo(filename); if (scriptInfo) { return scriptInfo.snap(); } } setCompilationSettings(opt: ts.CompilerOptions) { this.compilationSettings = opt; // conservatively assume that changing compiler options might affect module resolution strategy this.resolvedModuleNames.clear(); } lineAffectsRefs(filename: string, line: number) { const info = this.getScriptInfo(filename); const lineInfo = info.getLineInfo(line); if (lineInfo && lineInfo.text) { const regex = /reference|import|\/\*|\*\//; return regex.test(lineInfo.text); } } getCompilationSettings() { // change this to return active project settings for file return this.compilationSettings; } getScriptFileNames() { return this.roots.map(root => root.fileName); } getScriptVersion(filename: string) { return this.getScriptInfo(filename).svc.latestVersion().toString(); } getCurrentDirectory(): string { return ""; } getScriptIsOpen(filename: string) { return this.getScriptInfo(filename).isOpen; } removeReferencedFile(info: ScriptInfo) { if (!info.isOpen) { this.filenameToScript.remove(info.path); this.resolvedModuleNames.remove(info.path); } } getScriptInfo(filename: string): ScriptInfo { const path = toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); let scriptInfo = this.filenameToScript.get(path); if (!scriptInfo) { scriptInfo = this.project.openReferencedFile(filename); if (scriptInfo) { this.filenameToScript.set(path, scriptInfo); } } return scriptInfo; } addRoot(info: ScriptInfo) { if (!this.filenameToScript.contains(info.path)) { this.filenameToScript.set(info.path, info); this.roots.push(info); } } removeRoot(info: ScriptInfo) { if (!this.filenameToScript.contains(info.path)) { this.filenameToScript.remove(info.path); this.roots = copyListRemovingItem(info, this.roots); this.resolvedModuleNames.remove(info.path); } } saveTo(filename: string, tmpfilename: string) { const script = this.getScriptInfo(filename); if (script) { const snap = script.snap(); this.host.writeFile(tmpfilename, snap.getText(0, snap.getLength())); } } reloadScript(filename: string, tmpfilename: string, cb: () => any) { const script = this.getScriptInfo(filename); if (script) { script.svc.reloadFromFile(tmpfilename, cb); } } editScript(filename: string, start: number, end: number, newText: string) { const script = this.getScriptInfo(filename); if (script) { script.editContent(start, end, newText); return; } throw new Error("No script with name '" + filename + "'"); } resolvePath(path: string): string { const start = new Date().getTime(); const result = this.host.resolvePath(path); return result; } fileExists(path: string): boolean { const start = new Date().getTime(); const result = this.host.fileExists(path); return result; } directoryExists(path: string): boolean { return this.host.directoryExists(path); } /** * @param line 1 based index */ lineToTextSpan(filename: string, line: number): ts.TextSpan { const path = toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); const script: ScriptInfo = this.filenameToScript.get(path); const index = script.snap().index; const lineInfo = index.lineNumberToInfo(line + 1); let len: number; if (lineInfo.leaf) { len = lineInfo.leaf.text.length; } else { const nextLineInfo = index.lineNumberToInfo(line + 2); len = nextLineInfo.offset - lineInfo.offset; } return ts.createTextSpan(lineInfo.offset, len); } /** * @param line 1 based index * @param offset 1 based index */ lineOffsetToPosition(filename: string, line: number, offset: number): number { const path = toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); const script: ScriptInfo = this.filenameToScript.get(path); const index = script.snap().index; const lineInfo = index.lineNumberToInfo(line); // TODO: assert this offset is actually on the line return (lineInfo.offset + offset - 1); } /** * @param line 1-based index * @param offset 1-based index */ positionToLineOffset(filename: string, position: number): ILineInfo { const path = toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); const script: ScriptInfo = this.filenameToScript.get(path); const index = script.snap().index; const lineOffset = index.charOffsetToLineNumberAndPos(position); return { line: lineOffset.line, offset: lineOffset.offset + 1 }; } } // assumes normalized paths function getAbsolutePath(filename: string, directory: string) { const rootLength = ts.getRootLength(filename); if (rootLength > 0) { return filename; } else { const splitFilename = filename.split("/"); const splitDir = directory.split("/"); let i = 0; let dirTail = 0; const sflen = splitFilename.length; while ((i < sflen) && (splitFilename[i].charAt(0) == ".")) { const dots = splitFilename[i]; if (dots == "..") { dirTail++; } else if (dots != ".") { return undefined; } i++; } return splitDir.slice(0, splitDir.length - dirTail).concat(splitFilename.slice(i)).join("/"); } } export interface ProjectOptions { // these fields can be present in the project file files?: string[]; compilerOptions?: ts.CompilerOptions; } export class Project { compilerService: CompilerService; projectFilename: string; projectFileWatcher: FileWatcher; directoryWatcher: FileWatcher; // Used to keep track of what directories are watched for this project directoriesWatchedForTsconfig: string[] = []; program: ts.Program; filenameToSourceFile: ts.Map<ts.SourceFile> = {}; updateGraphSeq = 0; /** Used for configured projects which may have multiple open roots */ openRefCount = 0; constructor(public projectService: ProjectService, public projectOptions?: ProjectOptions) { if (projectOptions && projectOptions.files) { // If files are listed explicitly, allow all extensions projectOptions.compilerOptions.allowNonTsExtensions = true; } this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions); } addOpenRef() { this.openRefCount++; } deleteOpenRef() { this.openRefCount--; return this.openRefCount; } openReferencedFile(filename: string) { return this.projectService.openFile(filename, false); } getRootFiles() { return this.compilerService.host.roots.map(info => info.fileName); } getFileNames() { const sourceFiles = this.program.getSourceFiles(); return sourceFiles.map(sourceFile => sourceFile.fileName); } getSourceFile(info: ScriptInfo) { return this.filenameToSourceFile[info.fileName]; } getSourceFileFromName(filename: string, requireOpen?: boolean) { const info = this.projectService.getScriptInfo(filename); if (info) { if ((!requireOpen) || info.isOpen) { return this.getSourceFile(info); } } } isRoot(info: ScriptInfo) { return this.compilerService.host.roots.some(root => root === info); } removeReferencedFile(info: ScriptInfo) { this.compilerService.host.removeReferencedFile(info); this.updateGraph(); } updateFileMap() { this.filenameToSourceFile = {}; const sourceFiles = this.program.getSourceFiles(); for (let i = 0, len = sourceFiles.length; i < len; i++) { const normFilename = ts.normalizePath(sourceFiles[i].fileName); this.filenameToSourceFile[normFilename] = sourceFiles[i]; } } finishGraph() { this.updateGraph(); this.compilerService.languageService.getNavigateToItems(".*"); } updateGraph() { this.program = this.compilerService.languageService.getProgram(); this.updateFileMap(); } isConfiguredProject() { return this.projectFilename; } // add a root file to project addRoot(info: ScriptInfo) { this.compilerService.host.addRoot(info); } // remove a root file from project removeRoot(info: ScriptInfo) { this.compilerService.host.removeRoot(info); } filesToString() { let strBuilder = ""; ts.forEachValue(this.filenameToSourceFile, sourceFile => { strBuilder += sourceFile.fileName + "\n"; }); return strBuilder; } setProjectOptions(projectOptions: ProjectOptions) { this.projectOptions = projectOptions; if (projectOptions.compilerOptions) { projectOptions.compilerOptions.allowNonTsExtensions = true; this.compilerService.setCompilerOptions(projectOptions.compilerOptions); } } } export interface ProjectOpenResult { success?: boolean; errorMsg?: string; project?: Project; } function copyListRemovingItem<T>(item: T, list: T[]) { const copiedList: T[] = []; for (let i = 0, len = list.length; i < len; i++) { if (list[i] != item) { copiedList.push(list[i]); } } return copiedList; } export interface ProjectServiceEventHandler { (eventName: string, project: Project, fileName: string): void; } export interface HostConfiguration { formatCodeOptions: ts.FormatCodeOptions; hostInfo: string; } export class ProjectService { filenameToScriptInfo: ts.Map<ScriptInfo> = {}; // open, non-configured root files openFileRoots: ScriptInfo[] = []; // projects built from openFileRoots inferredProjects: Project[] = []; // projects specified by a tsconfig.json file configuredProjects: Project[] = []; // open files referenced by a project openFilesReferenced: ScriptInfo[] = []; // open files that are roots of a configured project openFileRootsConfigured: ScriptInfo[] = []; // a path to directory watcher map that detects added tsconfig files directoryWatchersForTsconfig: ts.Map<FileWatcher> = {}; // count of how many projects are using the directory watcher. If the // number becomes 0 for a watcher, then we should close it. directoryWatchersRefCount: ts.Map<number> = {}; hostConfiguration: HostConfiguration; timerForDetectingProjectFilelistChanges: Map<NodeJS.Timer> = {}; constructor(public host: ServerHost, public psLogger: Logger, public eventHandler?: ProjectServiceEventHandler) { // ts.disableIncrementalParsing = true; this.addDefaultHostConfiguration(); } addDefaultHostConfiguration() { this.hostConfiguration = { formatCodeOptions: ts.clone(CompilerService.defaultFormatCodeOptions), hostInfo: "Unknown host" }; } getFormatCodeOptions(file?: string) { if (file) { const info = this.filenameToScriptInfo[file]; if (info) { return info.formatCodeOptions; } } return this.hostConfiguration.formatCodeOptions; } watchedFileChanged(fileName: string) { const info = this.filenameToScriptInfo[fileName]; if (!info) { this.psLogger.info("Error: got watch notification for unknown file: " + fileName); } if (!this.host.fileExists(fileName)) { // File was deleted this.fileDeletedInFilesystem(info); } else { if (info && (!info.isOpen)) { info.svc.reloadFromFile(info.fileName); } } } /** * This is the callback function when a watched directory has added or removed source code files. * @param project the project that associates with this directory watcher * @param fileName the absolute file name that changed in watched directory */ directoryWatchedForSourceFilesChanged(project: Project, fileName: string) { // If a change was made inside "folder/file", node will trigger the callback twice: // one with the fileName being "folder/file", and the other one with "folder". // We don't respond to the second one. if (fileName && !ts.isSupportedSourceFileName(fileName)) { return; } this.log("Detected source file changes: " + fileName); this.startTimerForDetectingProjectFilelistChanges(project); } startTimerForDetectingProjectFilelistChanges(project: Project) { if (this.timerForDetectingProjectFilelistChanges[project.projectFilename]) { clearTimeout(this.timerForDetectingProjectFilelistChanges[project.projectFilename]); } this.timerForDetectingProjectFilelistChanges[project.projectFilename] = setTimeout( () => this.handleProjectFilelistChanges(project), 250 ); } handleProjectFilelistChanges(project: Project) { const { succeeded, projectOptions, error } = this.configFileToProjectOptions(project.projectFilename); const newRootFiles = projectOptions.files.map((f => this.getCanonicalFileName(f))); const currentRootFiles = project.getRootFiles().map((f => this.getCanonicalFileName(f))); // We check if the project file list has changed. If so, we update the project. if (!arrayIsEqualTo(currentRootFiles && currentRootFiles.sort(), newRootFiles && newRootFiles.sort())) { // For configured projects, the change is made outside the tsconfig file, and // it is not likely to affect the project for other files opened by the client. We can // just update the current project. this.updateConfiguredProject(project); // Call updateProjectStructure to clean up inferred projects we may have // created for the new files this.updateProjectStructure(); } } /** * This is the callback function when a watched directory has an added tsconfig file. */ directoryWatchedForTsconfigChanged(fileName: string) { if (ts.getBaseFileName(fileName) != "tsconfig.json") { this.log(fileName + " is not tsconfig.json"); return; } this.log("Detected newly added tsconfig file: " + fileName); const { succeeded, projectOptions, error } = this.configFileToProjectOptions(fileName); const rootFilesInTsconfig = projectOptions.files.map(f => this.getCanonicalFileName(f)); const openFileRoots = this.openFileRoots.map(s => this.getCanonicalFileName(s.fileName)); // We should only care about the new tsconfig file if it contains any // opened root files of existing inferred projects for (const openFileRoot of openFileRoots) { if (rootFilesInTsconfig.indexOf(openFileRoot) >= 0) { this.reloadProjects(); return; } } } getCanonicalFileName(fileName: string) { const name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); return ts.normalizePath(name); } watchedProjectConfigFileChanged(project: Project) { this.log("Config file changed: " + project.projectFilename); this.updateConfiguredProject(project); this.updateProjectStructure(); } log(msg: string, type = "Err") { this.psLogger.msg(msg, type); } setHostConfiguration(args: ts.server.protocol.ConfigureRequestArguments) { if (args.file) { const info = this.filenameToScriptInfo[args.file]; if (info) { info.setFormatOptions(args.formatOptions); this.log("Host configuration update for file " + args.file, "Info"); } } else { if (args.hostInfo !== undefined) { this.hostConfiguration.hostInfo = args.hostInfo; this.log("Host information " + args.hostInfo, "Info"); } if (args.formatOptions) { mergeFormatOptions(this.hostConfiguration.formatCodeOptions, args.formatOptions); this.log("Format host information updated", "Info"); } } } closeLog() { this.psLogger.close(); } createInferredProject(root: ScriptInfo) { const project = new Project(this); project.addRoot(root); let currentPath = ts.getDirectoryPath(root.fileName); let parentPath = ts.getDirectoryPath(currentPath); while (currentPath != parentPath) { if (!project.projectService.directoryWatchersForTsconfig[currentPath]) { this.log("Add watcher for: " + currentPath); project.projectService.directoryWatchersForTsconfig[currentPath] = this.host.watchDirectory(currentPath, fileName => this.directoryWatchedForTsconfigChanged(fileName)); project.projectService.directoryWatchersRefCount[currentPath] = 1; } else { project.projectService.directoryWatchersRefCount[currentPath] += 1; } project.directoriesWatchedForTsconfig.push(currentPath); currentPath = parentPath; parentPath = ts.getDirectoryPath(parentPath); } project.finishGraph(); this.inferredProjects.push(project); return project; } fileDeletedInFilesystem(info: ScriptInfo) { this.psLogger.info(info.fileName + " deleted"); if (info.fileWatcher) { info.fileWatcher.close(); info.fileWatcher = undefined; } if (!info.isOpen) { this.filenameToScriptInfo[info.fileName] = undefined; const referencingProjects = this.findReferencingProjects(info); if (info.defaultProject) { info.defaultProject.removeRoot(info); } for (let i = 0, len = referencingProjects.length; i < len; i++) { referencingProjects[i].removeReferencedFile(info); } for (let j = 0, flen = this.openFileRoots.length; j < flen; j++) { const openFile = this.openFileRoots[j]; if (this.eventHandler) { this.eventHandler("context", openFile.defaultProject, openFile.fileName); } } for (let j = 0, flen = this.openFilesReferenced.length; j < flen; j++) { const openFile = this.openFilesReferenced[j]; if (this.eventHandler) { this.eventHandler("context", openFile.defaultProject, openFile.fileName); } } } this.printProjects(); } updateConfiguredProjectList() { const configuredProjects: Project[] = []; for (let i = 0, len = this.configuredProjects.length; i < len; i++) { if (this.configuredProjects[i].openRefCount > 0) { configuredProjects.push(this.configuredProjects[i]); } } this.configuredProjects = configuredProjects; } removeProject(project: Project) { this.log("remove project: " + project.getRootFiles().toString()); if (project.isConfiguredProject()) { project.projectFileWatcher.close(); project.directoryWatcher.close(); this.configuredProjects = copyListRemovingItem(project, this.configuredProjects); } else { for (const directory of project.directoriesWatchedForTsconfig) { // if the ref count for this directory watcher drops to 0, it's time to close it if (!(--project.projectService.directoryWatchersRefCount[directory])) { this.log("Close directory watcher for: " + directory); project.projectService.directoryWatchersForTsconfig[directory].close(); delete project.projectService.directoryWatchersForTsconfig[directory]; } } this.inferredProjects = copyListRemovingItem(project, this.inferredProjects); } const fileNames = project.getFileNames(); for (const fileName of fileNames) { const info = this.getScriptInfo(fileName); if (info.defaultProject == project) { info.defaultProject = undefined; } } } setConfiguredProjectRoot(info: ScriptInfo) { for (let i = 0, len = this.configuredProjects.length; i < len; i++) { const configuredProject = this.configuredProjects[i]; if (configuredProject.isRoot(info)) { info.defaultProject = configuredProject; configuredProject.addOpenRef(); return true; } } return false; } addOpenFile(info: ScriptInfo) { if (this.setConfiguredProjectRoot(info)) { this.openFileRootsConfigured.push(info); } else { this.findReferencingProjects(info); if (info.defaultProject) { this.openFilesReferenced.push(info); } else { // create new inferred project p with the newly opened file as root info.defaultProject = this.createInferredProject(info); const openFileRoots: ScriptInfo[] = []; // for each inferred project root r for (let i = 0, len = this.openFileRoots.length; i < len; i++) { const r = this.openFileRoots[i]; // if r referenced by the new project if (info.defaultProject.getSourceFile(r)) { // remove project rooted at r this.removeProject(r.defaultProject); // put r in referenced open file list this.openFilesReferenced.push(r); // set default project of r to the new project r.defaultProject = info.defaultProject; } else { // otherwise, keep r as root of inferred project openFileRoots.push(r); } } this.openFileRoots = openFileRoots; this.openFileRoots.push(info); } } this.updateConfiguredProjectList(); } /** * Remove this file from the set of open, non-configured files. * @param info The file that has been closed or newly configured */ closeOpenFile(info: ScriptInfo) { // Closing file should trigger re-reading the file content from disk. This is // because the user may chose to discard the buffer content before saving // to the disk, and the server's version of the file can be out of sync. info.svc.reloadFromFile(info.fileName); const openFileRoots: ScriptInfo[] = []; let removedProject: Project; for (let i = 0, len = this.openFileRoots.length; i < len; i++) { // if closed file is root of project if (info === this.openFileRoots[i]) { // remove that project and remember it removedProject = info.defaultProject; } else { openFileRoots.push(this.openFileRoots[i]); } } this.openFileRoots = openFileRoots; if (!removedProject) { const openFileRootsConfigured: ScriptInfo[] = []; for (let i = 0, len = this.openFileRootsConfigured.length; i < len; i++) { if (info === this.openFileRootsConfigured[i]) { if (info.defaultProject.deleteOpenRef() === 0) { removedProject = info.defaultProject; } } else { openFileRootsConfigured.push(this.openFileRootsConfigured[i]); } } this.openFileRootsConfigured = openFileRootsConfigured; } if (removedProject) { this.removeProject(removedProject); const openFilesReferenced: ScriptInfo[] = []; const orphanFiles: ScriptInfo[] = []; // for all open, referenced files f for (let i = 0, len = this.openFilesReferenced.length; i < len; i++) { const f = this.openFilesReferenced[i]; // if f was referenced by the removed project, remember it if (f.defaultProject === removedProject || !f.defaultProject) { f.defaultProject = undefined; orphanFiles.push(f); } else { // otherwise add it back to the list of referenced files openFilesReferenced.push(f); } } this.openFilesReferenced = openFilesReferenced; // treat orphaned files as newly opened for (let i = 0, len = orphanFiles.length; i < len; i++) { this.addOpenFile(orphanFiles[i]); } } else { this.openFilesReferenced = copyListRemovingItem(info, this.openFilesReferenced); } info.close(); } findReferencingProjects(info: ScriptInfo, excludedProject?: Project) { const referencingProjects: Project[] = []; info.defaultProject = undefined; for (let i = 0, len = this.inferredProjects.length; i < len; i++) { const inferredProject = this.inferredProjects[i]; inferredProject.updateGraph(); if (inferredProject !== excludedProject) { if (inferredProject.getSourceFile(info)) { info.defaultProject = inferredProject; referencingProjects.push(inferredProject); } } } for (let i = 0, len = this.configuredProjects.length; i < len; i++) { const configuredProject = this.configuredProjects[i]; configuredProject.updateGraph(); if (configuredProject.getSourceFile(info)) { info.defaultProject = configuredProject; } } return referencingProjects; } /** * This function rebuilds the project for every file opened by the client */ reloadProjects() { this.log("reload projects."); // First check if there is new tsconfig file added for inferred project roots for (const info of this.openFileRoots) { this.openOrUpdateConfiguredProjectForFile(info.fileName); } this.updateProjectStructure(); } /** * This function is to update the project structure for every projects. * It is called on the premise that all the configured projects are * up to date. */ updateProjectStructure() { this.log("updating project structure from ...", "Info"); this.printProjects(); const unattachedOpenFiles: ScriptInfo[] = []; const openFileRootsConfigured: ScriptInfo[] = []; for (const info of this.openFileRootsConfigured) { const project = info.defaultProject; if (!project || !(project.getSourceFile(info))) { info.defaultProject = undefined; unattachedOpenFiles.push(info); } else { openFileRootsConfigured.push(info); } } this.openFileRootsConfigured = openFileRootsConfigured; // First loop through all open files that are referenced by projects but are not // project roots. For each referenced file, see if the default project still // references that file. If so, then just keep the file in the referenced list. // If not, add the file to an unattached list, to be rechecked later. const openFilesReferenced: ScriptInfo[] = []; for (let i = 0, len = this.openFilesReferenced.length; i < len; i++) { const referencedFile = this.openFilesReferenced[i]; referencedFile.defaultProject.updateGraph(); const sourceFile = referencedFile.defaultProject.getSourceFile(referencedFile); if (sourceFile) { openFilesReferenced.push(referencedFile); } else { unattachedOpenFiles.push(referencedFile); } } this.openFilesReferenced = openFilesReferenced; // Then, loop through all of the open files that are project roots. // For each root file, note the project that it roots. Then see if // any other projects newly reference the file. If zero projects // newly reference the file, keep it as a root. If one or more // projects newly references the file, remove its project from the // inferred projects list (since it is no longer a root) and add // the file to the open, referenced file list. const openFileRoots: ScriptInfo[] = []; for (let i = 0, len = this.openFileRoots.length; i < len; i++) { const rootFile = this.openFileRoots[i]; const rootedProject = rootFile.defaultProject; const referencingProjects = this.findReferencingProjects(rootFile, rootedProject); if (rootFile.defaultProject && rootFile.defaultProject.isConfiguredProject()) { // If the root file has already been added into a configured project, // meaning the original inferred project is gone already. if (!rootedProject.isConfiguredProject()) { this.removeProject(rootedProject); } this.openFileRootsConfigured.push(rootFile); } else { if (referencingProjects.length === 0) { rootFile.defaultProject = rootedProject; openFileRoots.push(rootFile); } else { // remove project from inferred projects list because root captured this.removeProject(rootedProject); this.openFilesReferenced.push(rootFile); } } } this.openFileRoots = openFileRoots; // Finally, if we found any open, referenced files that are no longer // referenced by their default project, treat them as newly opened // by the editor. for (let i = 0, len = unattachedOpenFiles.length; i < len; i++) { this.addOpenFile(unattachedOpenFiles[i]); } this.printProjects(); } getScriptInfo(filename: string) { filename = ts.normalizePath(filename); return ts.lookUp(this.filenameToScriptInfo, filename); } /** * @param filename is absolute pathname */ openFile(fileName: string, openedByClient: boolean) { fileName = ts.normalizePath(fileName); let info = ts.lookUp(this.filenameToScriptInfo, fileName); if (!info) { let content: string; if (this.host.fileExists(fileName)) { content = this.host.readFile(fileName); } if (!content) { if (openedByClient) { content = ""; } } if (content !== undefined) { info = new ScriptInfo(this.host, fileName, content, openedByClient); info.setFormatOptions(this.getFormatCodeOptions()); this.filenameToScriptInfo[fileName] = info; if (!info.isOpen) { info.fileWatcher = this.host.watchFile(fileName, _ => { this.watchedFileChanged(fileName); }); } } } if (info) { if (openedByClient) { info.isOpen = true; } } return info; } // This is different from the method the compiler uses because // the compiler can assume it will always start searching in the // current directory (the directory in which tsc was invoked). // The server must start searching from the directory containing // the newly opened file. findConfigFile(searchPath: string): string { while (true) { const fileName = ts.combinePaths(searchPath, "tsconfig.json"); if (this.host.fileExists(fileName)) { return fileName; } const parentPath = ts.getDirectoryPath(searchPath); if (parentPath === searchPath) { break; } searchPath = parentPath; } return undefined; } /** * Open file whose contents is managed by the client * @param filename is absolute pathname */ openClientFile(fileName: string) { this.openOrUpdateConfiguredProjectForFile(fileName); const info = this.openFile(fileName, true); this.addOpenFile(info); this.printProjects(); return info; } /** * This function tries to search for a tsconfig.json for the given file. If we found it, * we first detect if there is already a configured project created for it: if so, we re-read * the tsconfig file content and update the project; otherwise we create a new one. */ openOrUpdateConfiguredProjectForFile(fileName: string) { const searchPath = ts.normalizePath(getDirectoryPath(fileName)); this.log("Search path: " + searchPath, "Info"); const configFileName = this.findConfigFile(searchPath); if (configFileName) { this.log("Config file name: " + configFileName, "Info"); const project = this.findConfiguredProjectByConfigFile(configFileName); if (!project) { const configResult = this.openConfigFile(configFileName, fileName); if (!configResult.success) { this.log("Error opening config file " + configFileName + " " + configResult.errorMsg); } else { this.log("Opened configuration file " + configFileName, "Info"); this.configuredProjects.push(configResult.project); } } else { this.updateConfiguredProject(project); } } else { this.log("No config files found."); } } /** * Close file whose contents is managed by the client * @param filename is absolute pathname */ closeClientFile(filename: string) { const info = ts.lookUp(this.filenameToScriptInfo, filename); if (info) { this.closeOpenFile(info); info.isOpen = false; } this.printProjects(); } getProjectForFile(filename: string) { const scriptInfo = ts.lookUp(this.filenameToScriptInfo, filename); if (scriptInfo) { return scriptInfo.defaultProject; } } printProjectsForFile(filename: string) { const scriptInfo = ts.lookUp(this.filenameToScriptInfo, filename); if (scriptInfo) { this.psLogger.startGroup(); this.psLogger.info("Projects for " + filename); const projects = this.findReferencingProjects(scriptInfo); for (let i = 0, len = projects.length; i < len; i++) { this.psLogger.info("Project " + i.toString()); } this.psLogger.endGroup(); } else { this.psLogger.info(filename + " not in any project"); } } printProjects() { if (!this.psLogger.isVerbose()) { return; } this.psLogger.startGroup(); for (let i = 0, len = this.inferredProjects.length; i < len; i++) { const project = this.inferredProjects[i]; project.updateGraph(); this.psLogger.info("Project " + i.toString()); this.psLogger.info(project.filesToString()); this.psLogger.info("-----------------------------------------------"); } for (let i = 0, len = this.configuredProjects.length; i < len; i++) { const project = this.configuredProjects[i]; project.updateGraph(); this.psLogger.info("Project (configured) " + (i + this.inferredProjects.length).toString()); this.psLogger.info(project.filesToString()); this.psLogger.info("-----------------------------------------------"); } this.psLogger.info("Open file roots of inferred projects: "); for (let i = 0, len = this.openFileRoots.length; i < len; i++) { this.psLogger.info(this.openFileRoots[i].fileName); } this.psLogger.info("Open files referenced by inferred or configured projects: "); for (let i = 0, len = this.openFilesReferenced.length; i < len; i++) { let fileInfo = this.openFilesReferenced[i].fileName; if (this.openFilesReferenced[i].defaultProject.isConfiguredProject()) { fileInfo += " (configured)"; } this.psLogger.info(fileInfo); } this.psLogger.info("Open file roots of configured projects: "); for (let i = 0, len = this.openFileRootsConfigured.length; i < len; i++) { this.psLogger.info(this.openFileRootsConfigured[i].fileName); } this.psLogger.endGroup(); } configProjectIsActive(fileName: string) { return this.findConfiguredProjectByConfigFile(fileName) === undefined; } findConfiguredProjectByConfigFile(configFileName: string) { for (let i = 0, len = this.configuredProjects.length; i < len; i++) { if (this.configuredProjects[i].projectFilename == configFileName) { return this.configuredProjects[i]; } } return undefined; } configFileToProjectOptions(configFilename: string): { succeeded: boolean, projectOptions?: ProjectOptions, error?: ProjectOpenResult } { configFilename = ts.normalizePath(configFilename); // file references will be relative to dirPath (or absolute) const dirPath = ts.getDirectoryPath(configFilename); const contents = this.host.readFile(configFilename); const rawConfig: { config?: ProjectOptions; error?: Diagnostic; } = ts.parseConfigFileTextToJson(configFilename, contents); if (rawConfig.error) { return { succeeded: false, error: rawConfig.error }; } else { const parsedCommandLine = ts.parseJsonConfigFileContent(rawConfig.config, this.host, dirPath); Debug.assert(!!parsedCommandLine.fileNames); if (parsedCommandLine.errors && (parsedCommandLine.errors.length > 0)) { return { succeeded: false, error: { errorMsg: "tsconfig option errors" } }; } else if (parsedCommandLine.fileNames.length === 0) { return { succeeded: false, error: { errorMsg: "no files found" } }; } else { const projectOptions: ProjectOptions = { files: parsedCommandLine.fileNames, compilerOptions: parsedCommandLine.options }; return { succeeded: true, projectOptions }; } } } openConfigFile(configFilename: string, clientFileName?: string): ProjectOpenResult { const { succeeded, projectOptions, error } = this.configFileToProjectOptions(configFilename); if (!succeeded) { return error; } else { const project = this.createProject(configFilename, projectOptions); for (const rootFilename of projectOptions.files) { if (this.host.fileExists(rootFilename)) { const info = this.openFile(rootFilename, /*openedByClient*/ clientFileName == rootFilename); project.addRoot(info); } else { return { errorMsg: "specified file " + rootFilename + " not found" }; } } project.finishGraph(); project.projectFileWatcher = this.host.watchFile(configFilename, _ => this.watchedProjectConfigFileChanged(project)); this.log("Add recursive watcher for: " + ts.getDirectoryPath(configFilename)); project.directoryWatcher = this.host.watchDirectory( ts.getDirectoryPath(configFilename), path => this.directoryWatchedForSourceFilesChanged(project, path), /*recursive*/ true ); return { success: true, project: project }; } } updateConfiguredProject(project: Project) { if (!this.host.fileExists(project.projectFilename)) { this.log("Config file deleted"); this.removeProject(project); } else { const { succeeded, projectOptions, error } = this.configFileToProjectOptions(project.projectFilename); if (!succeeded) { return error; } else { const oldFileNames = project.compilerService.host.roots.map(info => info.fileName); const newFileNames = projectOptions.files; const fileNamesToRemove = oldFileNames.filter(f => newFileNames.indexOf(f) < 0); const fileNamesToAdd = newFileNames.filter(f => oldFileNames.indexOf(f) < 0); for (const fileName of fileNamesToRemove) { const info = this.getScriptInfo(fileName); if (info) { project.removeRoot(info); } } for (const fileName of fileNamesToAdd) { let info = this.getScriptInfo(fileName); if (!info) { info = this.openFile(fileName, false); } else { // if the root file was opened by client, it would belong to either // openFileRoots or openFileReferenced. if (info.isOpen) { if (this.openFileRoots.indexOf(info) >= 0) { this.openFileRoots = copyListRemovingItem(info, this.openFileRoots); if (info.defaultProject && !info.defaultProject.isConfiguredProject()) { this.removeProject(info.defaultProject); } } if (this.openFilesReferenced.indexOf(info) >= 0) { this.openFilesReferenced = copyListRemovingItem(info, this.openFilesReferenced); } this.openFileRootsConfigured.push(info); info.defaultProject = project; } } project.addRoot(info); } project.setProjectOptions(projectOptions); project.finishGraph(); } } } createProject(projectFilename: string, projectOptions?: ProjectOptions) { const project = new Project(this, projectOptions); project.projectFilename = projectFilename; return project; } } export class CompilerService { host: LSHost; languageService: ts.LanguageService; classifier: ts.Classifier; settings: ts.CompilerOptions; documentRegistry = ts.createDocumentRegistry(); constructor(public project: Project, opt?: ts.CompilerOptions) { this.host = new LSHost(project.projectService.host, project); if (opt) { this.setCompilerOptions(opt); } else { const defaultOpts = ts.getDefaultCompilerOptions(); defaultOpts.allowNonTsExtensions = true; this.setCompilerOptions(defaultOpts); } this.languageService = ts.createLanguageService(this.host, this.documentRegistry); this.classifier = ts.createClassifier(); } setCompilerOptions(opt: ts.CompilerOptions) { this.settings = opt; this.host.setCompilationSettings(opt); } isExternalModule(filename: string): boolean { const sourceFile = this.languageService.getSourceFile(filename); return ts.isExternalModule(sourceFile); } static defaultFormatCodeOptions: ts.FormatCodeOptions = { IndentSize: 4, TabSize: 4, NewLineCharacter: ts.sys ? ts.sys.newLine : "\n", ConvertTabsToSpaces: true, IndentStyle: ts.IndentStyle.Smart, InsertSpaceAfterCommaDelimiter: true, InsertSpaceAfterSemicolonInForStatements: true, InsertSpaceBeforeAndAfterBinaryOperators: true, InsertSpaceAfterKeywordsInControlFlowStatements: true, InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false, InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, PlaceOpenBraceOnNewLineForFunctions: false, PlaceOpenBraceOnNewLineForControlBlocks: false, }; } export interface LineCollection { charCount(): number; lineCount(): number; isLeaf(): boolean; walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker): void; } export interface ILineInfo { line: number; offset: number; text?: string; leaf?: LineLeaf; } export enum CharRangeSection { PreStart, Start, Entire, Mid, End, PostEnd } export interface ILineIndexWalker { goSubtree: boolean; done: boolean; leaf(relativeStart: number, relativeLength: number, lineCollection: LineLeaf): void; pre?(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineNode, nodeType: CharRangeSection): LineCollection; post?(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineNode, nodeType: CharRangeSection): LineCollection; } class BaseLineIndexWalker implements ILineIndexWalker { goSubtree = true; done = false; leaf(rangeStart: number, rangeLength: number, ll: LineLeaf) { } } class EditWalker extends BaseLineIndexWalker { lineIndex = new LineIndex(); // path to start of range startPath: LineCollection[]; endBranch: LineCollection[] = []; branchNode: LineNode; // path to current node stack: LineNode[]; state = CharRangeSection.Entire; lineCollectionAtBranch: LineCollection; initialText = ""; trailingText = ""; suppressTrailingText = false; constructor() { super(); this.lineIndex.root = new LineNode(); this.startPath = [this.lineIndex.root]; this.stack = [this.lineIndex.root]; } insertLines(insertedText: string) { if (this.suppressTrailingText) { this.trailingText = ""; } if (insertedText) { insertedText = this.initialText + insertedText + this.trailingText; } else { insertedText = this.initialText + this.trailingText; } const lm = LineIndex.linesFromText(insertedText); const lines = lm.lines; if (lines.length > 1) { if (lines[lines.length - 1] == "") { lines.length--; } } let branchParent: LineNode; let lastZeroCount: LineCollection; for (let k = this.endBranch.length - 1; k >= 0; k--) { (<LineNode>this.endBranch[k]).updateCounts(); if (this.endBranch[k].charCount() === 0) { lastZeroCount = this.endBranch[k]; if (k > 0) { branchParent = <LineNode>this.endBranch[k - 1]; } else { branchParent = this.branchNode; } } } if (lastZeroCount) { branchParent.remove(lastZeroCount); } // path at least length two (root and leaf) let insertionNode = <LineNode>this.startPath[this.startPath.length - 2]; const leafNode = <LineLeaf>this.startPath[this.startPath.length - 1]; const len = lines.length; if (len > 0) { leafNode.text = lines[0]; if (len > 1) { let insertedNodes = <LineCollection[]>new Array(len - 1); let startNode = <LineCollection>leafNode; for (let i = 1, len = lines.length; i < len; i++) { insertedNodes[i - 1] = new LineLeaf(lines[i]); } let pathIndex = this.startPath.length - 2; while (pathIndex >= 0) { insertionNode = <LineNode>this.startPath[pathIndex]; insertedNodes = insertionNode.insertAt(startNode, insertedNodes); pathIndex--; startNode = insertionNode; } let insertedNodesLen = insertedNodes.length; while (insertedNodesLen > 0) { const newRoot = new LineNode(); newRoot.add(this.lineIndex.root); insertedNodes = newRoot.insertAt(this.lineIndex.root, insertedNodes); insertedNodesLen = insertedNodes.length; this.lineIndex.root = newRoot; } this.lineIndex.root.updateCounts(); } else { for (let j = this.startPath.length - 2; j >= 0; j--) { (<LineNode>this.startPath[j]).updateCounts(); } } } else { // no content for leaf node, so delete it insertionNode.remove(leafNode); for (let j = this.startPath.length - 2; j >= 0; j--) { (<LineNode>this.startPath[j]).updateCounts(); } } return this.lineIndex; } post(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineCollection, nodeType: CharRangeSection): LineCollection { // have visited the path for start of range, now looking for end // if range is on single line, we will never make this state transition if (lineCollection === this.lineCollectionAtBranch) { this.state = CharRangeSection.End; } // always pop stack because post only called when child has been visited this.stack.length--; return undefined; } pre(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineCollection, nodeType: CharRangeSection) { // currentNode corresponds to parent, but in the new tree const currentNode = this.stack[this.stack.length - 1]; if ((this.state === CharRangeSection.Entire) && (nodeType === CharRangeSection.Start)) { // if range is on single line, we will never make this state transition this.state = CharRangeSection.Start; this.branchNode = currentNode; this.lineCollectionAtBranch = lineCollection; } let child: LineCollection; function fresh(node: LineCollection): LineCollection { if (node.isLeaf()) { return new LineLeaf(""); } else return new LineNode(); } switch (nodeType) { case CharRangeSection.PreStart: this.goSubtree = false; if (this.state !== CharRangeSection.End) { currentNode.add(lineCollection); } break; case CharRangeSection.Start: if (this.state === CharRangeSection.End) { this.goSubtree = false; } else { child = fresh(lineCollection); currentNode.add(child); this.startPath[this.startPath.length] = child; } break; case CharRangeSection.Entire: if (this.state !== CharRangeSection.End) { child = fresh(lineCollection); currentNode.add(child); this.startPath[this.startPath.length] = child; } else { if (!lineCollection.isLeaf()) { child = fresh(lineCollection); currentNode.add(child); this.endBranch[this.endBranch.length] = child; } } break; case CharRangeSection.Mid: this.goSubtree = false; break; case CharRangeSection.End: if (this.state !== CharRangeSection.End) { this.goSubtree = false; } else { if (!lineCollection.isLeaf()) { child = fresh(lineCollection); currentNode.add(child); this.endBranch[this.endBranch.length] = child; } } break; case CharRangeSection.PostEnd: this.goSubtree = false; if (this.state !== CharRangeSection.Start) { currentNode.add(lineCollection); } break; } if (this.goSubtree) { this.stack[this.stack.length] = <LineNode>child; } return lineCollection; } // just gather text from the leaves leaf(relativeStart: number, relativeLength: number, ll: LineLeaf) { if (this.state === CharRangeSection.Start) { this.initialText = ll.text.substring(0, relativeStart); } else if (this.state === CharRangeSection.Entire) { this.initialText = ll.text.substring(0, relativeStart); this.trailingText = ll.text.substring(relativeStart + relativeLength); } else { // state is CharRangeSection.End this.trailingText = ll.text.substring(relativeStart + relativeLength); } } } // text change information export class TextChange { constructor(public pos: number, public deleteLen: number, public insertedText?: string) { } getTextChangeRange() { return ts.createTextChangeRange(ts.createTextSpan(this.pos, this.deleteLen), this.insertedText ? this.insertedText.length : 0); } } export class ScriptVersionCache { changes: TextChange[] = []; versions: LineIndexSnapshot[] = []; minVersion = 0; // no versions earlier than min version will maintain change history private currentVersion = 0; private host: ServerHost; static changeNumberThreshold = 8; static changeLengthThreshold = 256; static maxVersions = 8; // REVIEW: can optimize by coalescing simple edits edit(pos: number, deleteLen: number, insertedText?: string) { this.changes[this.changes.length] = new TextChange(pos, deleteLen, insertedText); if ((this.changes.length > ScriptVersionCache.changeNumberThreshold) || (deleteLen > ScriptVersionCache.changeLengthThreshold) || (insertedText && (insertedText.length > ScriptVersionCache.changeLengthThreshold))) { this.getSnapshot(); } } latest() { return this.versions[this.currentVersion]; } latestVersion() { if (this.changes.length > 0) { this.getSnapshot(); } return this.currentVersion; } reloadFromFile(filename: string, cb?: () => any) { const content = this.host.readFile(filename); this.reload(content); if (cb) cb(); } // reload whole script, leaving no change history behind reload reload(script: string) { this.currentVersion++; this.changes = []; // history wiped out by reload const snap = new LineIndexSnapshot(this.currentVersion, this); this.versions[this.currentVersion] = snap; snap.index = new LineIndex(); const lm = LineIndex.linesFromText(script); snap.index.load(lm.lines); // REVIEW: could use linked list for (let i = this.minVersion; i < this.currentVersion; i++) { this.versions[i] = undefined; } this.minVersion = this.currentVersion; } getSnapshot() { let snap = this.versions[this.currentVersion]; if (this.changes.length > 0) { let snapIndex = this.latest().index; for (let i = 0, len = this.changes.length; i < len; i++) { const change = this.changes[i]; snapIndex = snapIndex.edit(change.pos, change.deleteLen, change.insertedText); } snap = new LineIndexSnapshot(this.currentVersion + 1, this); snap.index = snapIndex; snap.changesSincePreviousVersion = this.changes; this.currentVersion = snap.version; this.versions[snap.version] = snap; this.changes = []; if ((this.currentVersion - this.minVersion) >= ScriptVersionCache.maxVersions) { const oldMin = this.minVersion; this.minVersion = (this.currentVersion - ScriptVersionCache.maxVersions) + 1; for (let j = oldMin; j < this.minVersion; j++) { this.versions[j] = undefined; } } } return snap; } getTextChangesBetweenVersions(oldVersion: number, newVersion: number) { if (oldVersion < newVersion) { if (oldVersion >= this.minVersion) { const textChangeRanges: ts.TextChangeRange[] = []; for (let i = oldVersion + 1; i <= newVersion; i++) { const snap = this.versions[i]; for (let j = 0, len = snap.changesSincePreviousVersion.length; j < len; j++) { const textChange = snap.changesSincePreviousVersion[j]; textChangeRanges[textChangeRanges.length] = textChange.getTextChangeRange(); } } return ts.collapseTextChangeRangesAcrossMultipleVersions(textChangeRanges); } else { return undefined; } } else { return ts.unchangedTextChangeRange; } } static fromString(host: ServerHost, script: string) { const svc = new ScriptVersionCache(); const snap = new LineIndexSnapshot(0, svc); svc.versions[svc.currentVersion] = snap; svc.host = host; snap.index = new LineIndex(); const lm = LineIndex.linesFromText(script); snap.index.load(lm.lines); return svc; } } export class LineIndexSnapshot implements ts.IScriptSnapshot { index: LineIndex; changesSincePreviousVersion: TextChange[] = []; constructor(public version: number, public cache: ScriptVersionCache) { } getText(rangeStart: number, rangeEnd: number) { return this.index.getText(rangeStart, rangeEnd - rangeStart); } getLength() { return this.index.root.charCount(); } // this requires linear space so don't hold on to these getLineStartPositions(): number[] { const starts: number[] = [-1]; let count = 1; let pos = 0; this.index.every((ll, s, len) => { starts[count++] = pos; pos += ll.text.length; return true; }, 0); return starts; } getLineMapper() { return ((line: number) => { return this.index.lineNumberToInfo(line).offset; }); } getTextChangeRangeSinceVersion(scriptVersion: number) { if (this.version <= scriptVersion) { return ts.unchangedTextChangeRange; } else { return this.cache.getTextChangesBetweenVersions(scriptVersion, this.version); } } getChangeRange(oldSnapshot: ts.IScriptSnapshot): ts.TextChangeRange { const oldSnap = <LineIndexSnapshot>oldSnapshot; return this.getTextChangeRangeSinceVersion(oldSnap.version); } } export class LineIndex { root: LineNode; // set this to true to check each edit for accuracy checkEdits = false; charOffsetToLineNumberAndPos(charOffset: number) { return this.root.charOffsetToLineNumberAndPos(1, charOffset); } lineNumberToInfo(lineNumber: number): ILineInfo { const lineCount = this.root.lineCount(); if (lineNumber <= lineCount) { const lineInfo = this.root.lineNumberToInfo(lineNumber, 0); lineInfo.line = lineNumber; return lineInfo; } else { return { line: lineNumber, offset: this.root.charCount() }; } } load(lines: string[]) { if (lines.length > 0) { const leaves: LineLeaf[] = []; for (let i = 0, len = lines.length; i < len; i++) { leaves[i] = new LineLeaf(lines[i]); } this.root = LineIndex.buildTreeFromBottom(leaves); } else { this.root = new LineNode(); } } walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker) { this.root.walk(rangeStart, rangeLength, walkFns); } getText(rangeStart: number, rangeLength: number) { let accum = ""; if ((rangeLength > 0) && (rangeStart < this.root.charCount())) { this.walk(rangeStart, rangeLength, { goSubtree: true, done: false, leaf: (relativeStart: number, relativeLength: number, ll: LineLeaf) => { accum = accum.concat(ll.text.substring(relativeStart, relativeStart + relativeLength)); } }); } return accum; } getLength(): number { return this.root.charCount(); } every(f: (ll: LineLeaf, s: number, len: number) => boolean, rangeStart: number, rangeEnd?: number) { if (!rangeEnd) { rangeEnd = this.root.charCount(); } const walkFns = { goSubtree: true, done: false, leaf: function (relativeStart: number, relativeLength: number, ll: LineLeaf) { if (!f(ll, relativeStart, relativeLength)) { this.done = true; } } }; this.walk(rangeStart, rangeEnd - rangeStart, walkFns); return !walkFns.done; } edit(pos: number, deleteLength: number, newText?: string) { function editFlat(source: string, s: number, dl: number, nt = "") { return source.substring(0, s) + nt + source.substring(s + dl, source.length); } if (this.root.charCount() === 0) { // TODO: assert deleteLength === 0 if (newText) { this.load(LineIndex.linesFromText(newText).lines); return this; } } else { let checkText: string; if (this.checkEdits) { checkText = editFlat(this.getText(0, this.root.charCount()), pos, deleteLength, newText); } const walker = new EditWalker(); if (pos >= this.root.charCount()) { // insert at end pos = this.root.charCount() - 1; const endString = this.getText(pos, 1); if (newText) { newText = endString + newText; } else { newText = endString; } deleteLength = 0; walker.suppressTrailingText = true; } else if (deleteLength > 0) { // check whether last characters deleted are line break const e = pos + deleteLength; const lineInfo = this.charOffsetToLineNumberAndPos(e); if ((lineInfo && (lineInfo.offset === 0))) { // move range end just past line that will merge with previous line deleteLength += lineInfo.text.length; // store text by appending to end of insertedText if (newText) { newText = newText + lineInfo.text; } else { newText = lineInfo.text; } } } if (pos < this.root.charCount()) { this.root.walk(pos, deleteLength, walker); walker.insertLines(newText); } if (this.checkEdits) { const updatedText = this.getText(0, this.root.charCount()); Debug.assert(checkText == updatedText, "buffer edit mismatch"); } return walker.lineIndex; } } static buildTreeFromBottom(nodes: LineCollection[]): LineNode { const nodeCount = Math.ceil(nodes.length / lineCollectionCapacity); const interiorNodes: LineNode[] = []; let nodeIndex = 0; for (let i = 0; i < nodeCount; i++) { interiorNodes[i] = new LineNode(); let charCount = 0; let lineCount = 0; for (let j = 0; j < lineCollectionCapacity; j++) { if (nodeIndex < nodes.length) { interiorNodes[i].add(nodes[nodeIndex]); charCount += nodes[nodeIndex].charCount(); lineCount += nodes[nodeIndex].lineCount(); } else { break; } nodeIndex++; } interiorNodes[i].totalChars = charCount; interiorNodes[i].totalLines = lineCount; } if (interiorNodes.length === 1) { return interiorNodes[0]; } else { return this.buildTreeFromBottom(interiorNodes); } } static linesFromText(text: string) { const lineStarts = ts.computeLineStarts(text); if (lineStarts.length === 0) { return { lines: <string[]>[], lineMap: lineStarts }; } const lines = <string[]>new Array(lineStarts.length); const lc = lineStarts.length - 1; for (let lmi = 0; lmi < lc; lmi++) { lines[lmi] = text.substring(lineStarts[lmi], lineStarts[lmi + 1]); } const endText = text.substring(lineStarts[lc]); if (endText.length > 0) { lines[lc] = endText; } else { lines.length--; } return { lines: lines, lineMap: lineStarts }; } } export class LineNode implements LineCollection { totalChars = 0; totalLines = 0; children: LineCollection[] = []; isLeaf() { return false; } updateCounts() { this.totalChars = 0; this.totalLines = 0; for (let i = 0, len = this.children.length; i < len; i++) { const child = this.children[i]; this.totalChars += child.charCount(); this.totalLines += child.lineCount(); } } execWalk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker, childIndex: number, nodeType: CharRangeSection) { if (walkFns.pre) { walkFns.pre(rangeStart, rangeLength, this.children[childIndex], this, nodeType); } if (walkFns.goSubtree) { this.children[childIndex].walk(rangeStart, rangeLength, walkFns); if (walkFns.post) { walkFns.post(rangeStart, rangeLength, this.children[childIndex], this, nodeType); } } else { walkFns.goSubtree = true; } return walkFns.done; } skipChild(relativeStart: number, relativeLength: number, childIndex: number, walkFns: ILineIndexWalker, nodeType: CharRangeSection) { if (walkFns.pre && (!walkFns.done)) { walkFns.pre(relativeStart, relativeLength, this.children[childIndex], this, nodeType); walkFns.goSubtree = true; } } walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker) { // assume (rangeStart < this.totalChars) && (rangeLength <= this.totalChars) let childIndex = 0; let child = this.children[0]; let childCharCount = child.charCount(); // find sub-tree containing start let adjustedStart = rangeStart; while (adjustedStart >= childCharCount) { this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, CharRangeSection.PreStart); adjustedStart -= childCharCount; child = this.children[++childIndex]; childCharCount = child.charCount(); } // Case I: both start and end of range in same subtree if ((adjustedStart + rangeLength) <= childCharCount) { if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, CharRangeSection.Entire)) { return; } } else { // Case II: start and end of range in different subtrees (possibly with subtrees in the middle) if (this.execWalk(adjustedStart, childCharCount - adjustedStart, walkFns, childIndex, CharRangeSection.Start)) { return; } let adjustedLength = rangeLength - (childCharCount - adjustedStart); child = this.children[++childIndex]; childCharCount = child.charCount(); while (adjustedLength > childCharCount) { if (this.execWalk(0, childCharCount, walkFns, childIndex, CharRangeSection.Mid)) { return; } adjustedLength -= childCharCount; child = this.children[++childIndex]; childCharCount = child.charCount(); } if (adjustedLength > 0) { if (this.execWalk(0, adjustedLength, walkFns, childIndex, CharRangeSection.End)) { return; } } } // Process any subtrees after the one containing range end if (walkFns.pre) { const clen = this.children.length; if (childIndex < (clen - 1)) { for (let ej = childIndex + 1; ej < clen; ej++) { this.skipChild(0, 0, ej, walkFns, CharRangeSection.PostEnd); } } } } charOffsetToLineNumberAndPos(lineNumber: number, charOffset: number): ILineInfo { const childInfo = this.childFromCharOffset(lineNumber, charOffset); if (!childInfo.child) { return { line: lineNumber, offset: charOffset, }; } else if (childInfo.childIndex < this.children.length) { if (childInfo.child.isLeaf()) { return { line: childInfo.lineNumber, offset: childInfo.charOffset, text: (<LineLeaf>(childInfo.child)).text, leaf: (<LineLeaf>(childInfo.child)) }; } else { const lineNode = <LineNode>(childInfo.child); return lineNode.charOffsetToLineNumberAndPos(childInfo.lineNumber, childInfo.charOffset); } } else { const lineInfo = this.lineNumberToInfo(this.lineCount(), 0); return { line: this.lineCount(), offset: lineInfo.leaf.charCount() }; } } lineNumberToInfo(lineNumber: number, charOffset: number): ILineInfo { const childInfo = this.childFromLineNumber(lineNumber, charOffset); if (!childInfo.child) { return { line: lineNumber, offset: charOffset }; } else if (childInfo.child.isLeaf()) { return { line: lineNumber, offset: childInfo.charOffset, text: (<LineLeaf>(childInfo.child)).text, leaf: (<LineLeaf>(childInfo.child)) }; } else { const lineNode = <LineNode>(childInfo.child); return lineNode.lineNumberToInfo(childInfo.relativeLineNumber, childInfo.charOffset); } } childFromLineNumber(lineNumber: number, charOffset: number) { let child: LineCollection; let relativeLineNumber = lineNumber; let i: number; let len: number; for (i = 0, len = this.children.length; i < len; i++) { child = this.children[i]; const childLineCount = child.lineCount(); if (childLineCount >= relativeLineNumber) { break; } else { relativeLineNumber -= childLineCount; charOffset += child.charCount(); } } return { child: child, childIndex: i, relativeLineNumber: relativeLineNumber, charOffset: charOffset }; } childFromCharOffset(lineNumber: number, charOffset: number) { let child: LineCollection; let i: number; let len: number; for (i = 0, len = this.children.length; i < len; i++) { child = this.children[i]; if (child.charCount() > charOffset) { break; } else { charOffset -= child.charCount(); lineNumber += child.lineCount(); } } return { child: child, childIndex: i, charOffset: charOffset, lineNumber: lineNumber }; } splitAfter(childIndex: number) { let splitNode: LineNode; const clen = this.children.length; childIndex++; const endLength = childIndex; if (childIndex < clen) { splitNode = new LineNode(); while (childIndex < clen) { splitNode.add(this.children[childIndex++]); } splitNode.updateCounts(); } this.children.length = endLength; return splitNode; } remove(child: LineCollection) { const childIndex = this.findChildIndex(child); const clen = this.children.length; if (childIndex < (clen - 1)) { for (let i = childIndex; i < (clen - 1); i++) { this.children[i] = this.children[i + 1]; } } this.children.length--; } findChildIndex(child: LineCollection) { let childIndex = 0; const clen = this.children.length; while ((this.children[childIndex] !== child) && (childIndex < clen)) childIndex++; return childIndex; } insertAt(child: LineCollection, nodes: LineCollection[]) { let childIndex = this.findChildIndex(child); const clen = this.children.length; const nodeCount = nodes.length; // if child is last and there is more room and only one node to place, place it if ((clen < lineCollectionCapacity) && (childIndex === (clen - 1)) && (nodeCount === 1)) { this.add(nodes[0]); this.updateCounts(); return []; } else { const shiftNode = this.splitAfter(childIndex); let nodeIndex = 0; childIndex++; while ((childIndex < lineCollectionCapacity) && (nodeIndex < nodeCount)) { this.children[childIndex++] = nodes[nodeIndex++]; } let splitNodes: LineNode[] = []; let splitNodeCount = 0; if (nodeIndex < nodeCount) { splitNodeCount = Math.ceil((nodeCount - nodeIndex) / lineCollectionCapacity); splitNodes = <LineNode[]>new Array(splitNodeCount); let splitNodeIndex = 0; for (let i = 0; i < splitNodeCount; i++) { splitNodes[i] = new LineNode(); } let splitNode = <LineNode>splitNodes[0]; while (nodeIndex < nodeCount) { splitNode.add(nodes[nodeIndex++]); if (splitNode.children.length === lineCollectionCapacity) { splitNodeIndex++; splitNode = <LineNode>splitNodes[splitNodeIndex]; } } for (let i = splitNodes.length - 1; i >= 0; i--) { if (splitNodes[i].children.length === 0) { splitNodes.length--; } } } if (shiftNode) { splitNodes[splitNodes.length] = shiftNode; } this.updateCounts(); for (let i = 0; i < splitNodeCount; i++) { (<LineNode>splitNodes[i]).updateCounts(); } return splitNodes; } } // assume there is room for the item; return true if more room add(collection: LineCollection) { this.children[this.children.length] = collection; return (this.children.length < lineCollectionCapacity); } charCount() { return this.totalChars; } lineCount() { return this.totalLines; } } export class LineLeaf implements LineCollection { udata: any; constructor(public text: string) { } setUdata(data: any) { this.udata = data; } getUdata() { return this.udata; } isLeaf() { return true; } walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker) { walkFns.leaf(rangeStart, rangeLength, this); } charCount() { return this.text.length; } lineCount() { return 1; } } }
apache-2.0
treper/SlidingMenuUsage
DxStore/src/com/dxbook/ui/SearchResultActivity.java
63
package com.dxbook.ui; public class SearchResultActivity { }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-managedblockchain/src/main/java/com/amazonaws/services/managedblockchain/model/NetworkSummary.java
16696
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.managedblockchain.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * A summary of network configuration properties. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/managedblockchain-2018-09-24/NetworkSummary" target="_top">AWS * API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class NetworkSummary implements Serializable, Cloneable, StructuredPojo { /** * <p> * The unique identifier of the network. * </p> */ private String id; /** * <p> * The name of the network. * </p> */ private String name; /** * <p> * An optional description of the network. * </p> */ private String description; /** * <p> * The blockchain framework that the network uses. * </p> */ private String framework; /** * <p> * The version of the blockchain framework that the network uses. * </p> */ private String frameworkVersion; /** * <p> * The current status of the network. * </p> */ private String status; /** * <p> * The date and time that the network was created. * </p> */ private java.util.Date creationDate; /** * <p> * The Amazon Resource Name (ARN) of the network. For more information about ARNs and their format, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names * (ARNs)</a> in the <i>AWS General Reference</i>. * </p> */ private String arn; /** * <p> * The unique identifier of the network. * </p> * * @param id * The unique identifier of the network. */ public void setId(String id) { this.id = id; } /** * <p> * The unique identifier of the network. * </p> * * @return The unique identifier of the network. */ public String getId() { return this.id; } /** * <p> * The unique identifier of the network. * </p> * * @param id * The unique identifier of the network. * @return Returns a reference to this object so that method calls can be chained together. */ public NetworkSummary withId(String id) { setId(id); return this; } /** * <p> * The name of the network. * </p> * * @param name * The name of the network. */ public void setName(String name) { this.name = name; } /** * <p> * The name of the network. * </p> * * @return The name of the network. */ public String getName() { return this.name; } /** * <p> * The name of the network. * </p> * * @param name * The name of the network. * @return Returns a reference to this object so that method calls can be chained together. */ public NetworkSummary withName(String name) { setName(name); return this; } /** * <p> * An optional description of the network. * </p> * * @param description * An optional description of the network. */ public void setDescription(String description) { this.description = description; } /** * <p> * An optional description of the network. * </p> * * @return An optional description of the network. */ public String getDescription() { return this.description; } /** * <p> * An optional description of the network. * </p> * * @param description * An optional description of the network. * @return Returns a reference to this object so that method calls can be chained together. */ public NetworkSummary withDescription(String description) { setDescription(description); return this; } /** * <p> * The blockchain framework that the network uses. * </p> * * @param framework * The blockchain framework that the network uses. * @see Framework */ public void setFramework(String framework) { this.framework = framework; } /** * <p> * The blockchain framework that the network uses. * </p> * * @return The blockchain framework that the network uses. * @see Framework */ public String getFramework() { return this.framework; } /** * <p> * The blockchain framework that the network uses. * </p> * * @param framework * The blockchain framework that the network uses. * @return Returns a reference to this object so that method calls can be chained together. * @see Framework */ public NetworkSummary withFramework(String framework) { setFramework(framework); return this; } /** * <p> * The blockchain framework that the network uses. * </p> * * @param framework * The blockchain framework that the network uses. * @return Returns a reference to this object so that method calls can be chained together. * @see Framework */ public NetworkSummary withFramework(Framework framework) { this.framework = framework.toString(); return this; } /** * <p> * The version of the blockchain framework that the network uses. * </p> * * @param frameworkVersion * The version of the blockchain framework that the network uses. */ public void setFrameworkVersion(String frameworkVersion) { this.frameworkVersion = frameworkVersion; } /** * <p> * The version of the blockchain framework that the network uses. * </p> * * @return The version of the blockchain framework that the network uses. */ public String getFrameworkVersion() { return this.frameworkVersion; } /** * <p> * The version of the blockchain framework that the network uses. * </p> * * @param frameworkVersion * The version of the blockchain framework that the network uses. * @return Returns a reference to this object so that method calls can be chained together. */ public NetworkSummary withFrameworkVersion(String frameworkVersion) { setFrameworkVersion(frameworkVersion); return this; } /** * <p> * The current status of the network. * </p> * * @param status * The current status of the network. * @see NetworkStatus */ public void setStatus(String status) { this.status = status; } /** * <p> * The current status of the network. * </p> * * @return The current status of the network. * @see NetworkStatus */ public String getStatus() { return this.status; } /** * <p> * The current status of the network. * </p> * * @param status * The current status of the network. * @return Returns a reference to this object so that method calls can be chained together. * @see NetworkStatus */ public NetworkSummary withStatus(String status) { setStatus(status); return this; } /** * <p> * The current status of the network. * </p> * * @param status * The current status of the network. * @return Returns a reference to this object so that method calls can be chained together. * @see NetworkStatus */ public NetworkSummary withStatus(NetworkStatus status) { this.status = status.toString(); return this; } /** * <p> * The date and time that the network was created. * </p> * * @param creationDate * The date and time that the network was created. */ public void setCreationDate(java.util.Date creationDate) { this.creationDate = creationDate; } /** * <p> * The date and time that the network was created. * </p> * * @return The date and time that the network was created. */ public java.util.Date getCreationDate() { return this.creationDate; } /** * <p> * The date and time that the network was created. * </p> * * @param creationDate * The date and time that the network was created. * @return Returns a reference to this object so that method calls can be chained together. */ public NetworkSummary withCreationDate(java.util.Date creationDate) { setCreationDate(creationDate); return this; } /** * <p> * The Amazon Resource Name (ARN) of the network. For more information about ARNs and their format, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names * (ARNs)</a> in the <i>AWS General Reference</i>. * </p> * * @param arn * The Amazon Resource Name (ARN) of the network. For more information about ARNs and their format, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names * (ARNs)</a> in the <i>AWS General Reference</i>. */ public void setArn(String arn) { this.arn = arn; } /** * <p> * The Amazon Resource Name (ARN) of the network. For more information about ARNs and their format, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names * (ARNs)</a> in the <i>AWS General Reference</i>. * </p> * * @return The Amazon Resource Name (ARN) of the network. For more information about ARNs and their format, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names * (ARNs)</a> in the <i>AWS General Reference</i>. */ public String getArn() { return this.arn; } /** * <p> * The Amazon Resource Name (ARN) of the network. For more information about ARNs and their format, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names * (ARNs)</a> in the <i>AWS General Reference</i>. * </p> * * @param arn * The Amazon Resource Name (ARN) of the network. For more information about ARNs and their format, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names * (ARNs)</a> in the <i>AWS General Reference</i>. * @return Returns a reference to this object so that method calls can be chained together. */ public NetworkSummary withArn(String arn) { setArn(arn); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getId() != null) sb.append("Id: ").append(getId()).append(","); if (getName() != null) sb.append("Name: ").append(getName()).append(","); if (getDescription() != null) sb.append("Description: ").append(getDescription()).append(","); if (getFramework() != null) sb.append("Framework: ").append(getFramework()).append(","); if (getFrameworkVersion() != null) sb.append("FrameworkVersion: ").append(getFrameworkVersion()).append(","); if (getStatus() != null) sb.append("Status: ").append(getStatus()).append(","); if (getCreationDate() != null) sb.append("CreationDate: ").append(getCreationDate()).append(","); if (getArn() != null) sb.append("Arn: ").append(getArn()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof NetworkSummary == false) return false; NetworkSummary other = (NetworkSummary) obj; if (other.getId() == null ^ this.getId() == null) return false; if (other.getId() != null && other.getId().equals(this.getId()) == false) return false; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getDescription() == null ^ this.getDescription() == null) return false; if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false; if (other.getFramework() == null ^ this.getFramework() == null) return false; if (other.getFramework() != null && other.getFramework().equals(this.getFramework()) == false) return false; if (other.getFrameworkVersion() == null ^ this.getFrameworkVersion() == null) return false; if (other.getFrameworkVersion() != null && other.getFrameworkVersion().equals(this.getFrameworkVersion()) == false) return false; if (other.getStatus() == null ^ this.getStatus() == null) return false; if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false) return false; if (other.getCreationDate() == null ^ this.getCreationDate() == null) return false; if (other.getCreationDate() != null && other.getCreationDate().equals(this.getCreationDate()) == false) return false; if (other.getArn() == null ^ this.getArn() == null) return false; if (other.getArn() != null && other.getArn().equals(this.getArn()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getId() == null) ? 0 : getId().hashCode()); hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode()); hashCode = prime * hashCode + ((getFramework() == null) ? 0 : getFramework().hashCode()); hashCode = prime * hashCode + ((getFrameworkVersion() == null) ? 0 : getFrameworkVersion().hashCode()); hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode()); hashCode = prime * hashCode + ((getCreationDate() == null) ? 0 : getCreationDate().hashCode()); hashCode = prime * hashCode + ((getArn() == null) ? 0 : getArn().hashCode()); return hashCode; } @Override public NetworkSummary clone() { try { return (NetworkSummary) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.managedblockchain.model.transform.NetworkSummaryMarshaller.getInstance().marshall(this, protocolMarshaller); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-servicecatalog/src/main/java/com/amazonaws/services/servicecatalog/model/DescribeTagOptionResult.java
3915
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.servicecatalog.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DescribeTagOption" target="_top">AWS * API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeTagOptionResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * Information about the TagOption. * </p> */ private TagOptionDetail tagOptionDetail; /** * <p> * Information about the TagOption. * </p> * * @param tagOptionDetail * Information about the TagOption. */ public void setTagOptionDetail(TagOptionDetail tagOptionDetail) { this.tagOptionDetail = tagOptionDetail; } /** * <p> * Information about the TagOption. * </p> * * @return Information about the TagOption. */ public TagOptionDetail getTagOptionDetail() { return this.tagOptionDetail; } /** * <p> * Information about the TagOption. * </p> * * @param tagOptionDetail * Information about the TagOption. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeTagOptionResult withTagOptionDetail(TagOptionDetail tagOptionDetail) { setTagOptionDetail(tagOptionDetail); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getTagOptionDetail() != null) sb.append("TagOptionDetail: ").append(getTagOptionDetail()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeTagOptionResult == false) return false; DescribeTagOptionResult other = (DescribeTagOptionResult) obj; if (other.getTagOptionDetail() == null ^ this.getTagOptionDetail() == null) return false; if (other.getTagOptionDetail() != null && other.getTagOptionDetail().equals(this.getTagOptionDetail()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getTagOptionDetail() == null) ? 0 : getTagOptionDetail().hashCode()); return hashCode; } @Override public DescribeTagOptionResult clone() { try { return (DescribeTagOptionResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
Scavi/BrainSqueeze
src/main/java/com/scavi/brainsqueeze/codefight/challenge/CreditCycle.java
923
/* * 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 com.scavi.brainsqueeze.codefight.challenge; import java.util.GregorianCalendar; public class CreditCycle { int creditCycle(int m, int d, int y, int c) { if (c < d) return d - c; if (--m == 0) { m = 12; --y; } return new GregorianCalendar(y, m-1, 1).getActualMaximum(5) - c + d; } }
apache-2.0
thomasdarimont/spring-data-examples
jpa/multiple-datasources/src/test/java/example/springdata/jpa/multipleds/order/OrderRepositoryTests.java
1608
/* * Copyright 2015-2018 the original author or authors. * * 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 example.springdata.jpa.multipleds.order; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import example.springdata.jpa.multipleds.customer.CustomerRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; /** * Integration test for {@link CustomerRepository}. * * @author Oliver Gierke */ @RunWith(SpringRunner.class) @SpringBootTest @Transactional(transactionManager = "orderTransactionManager") public class OrderRepositoryTests { @Autowired OrderRepository orders; @Autowired CustomerRepository customers; @Test public void persistsAndFindsCustomer() { customers.findAll().forEach(customer -> { assertThat(orders.findByCustomer(customer.getId()), hasSize(1)); }); } }
apache-2.0
rfuertesp/pruebas2
common/app/com/commercetools/sunrise/common/template/cms/filebased/FileBasedCmsService.java
1294
package com.commercetools.sunrise.common.template.cms.filebased; import com.commercetools.sunrise.cms.CmsPage; import com.commercetools.sunrise.cms.CmsService; import com.commercetools.sunrise.common.template.i18n.I18nResolver; import javax.inject.Inject; import javax.inject.Named; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.concurrent.CompletionStage; import static java.util.concurrent.CompletableFuture.completedFuture; /** * Service that provides content data from i18n files that can be found in a local file. * Internally it uses a I18nResolver to resolve the requested messages. * * The mapping of the {@link CmsService} parameters to {@link I18nResolver} parameters goes as follows: * * - {@code bundle} = {@code entryType} (e.g. banner) * - {@code messageKey} = {@code entryKey.fieldName} (e.g. homeTopLeft.subtitle.text) */ public final class FileBasedCmsService implements CmsService { @Inject @Named("cms") private I18nResolver i18nResolver; @Override public CompletionStage<Optional<CmsPage>> page(final String pageKey, final List<Locale> locales) { final CmsPage cmsPage = new FileBasedCmsPage(i18nResolver, pageKey, locales); return completedFuture(Optional.of(cmsPage)); } }
apache-2.0
UKPLab/sentence-transformers
sentence_transformers/losses/DenoisingAutoEncoderLoss.py
6700
import torch from torch import nn, Tensor from typing import Iterable, Dict from sentence_transformers import SentenceTransformer from transformers import AutoConfig, AutoTokenizer, AutoModelForCausalLM, PreTrainedModel import logging logger = logging.getLogger(__name__) class DenoisingAutoEncoderLoss(nn.Module): """ This loss expects as input a batch consisting of damaged sentences and the corresponding original ones. The data generation process has already been implemented in readers/DenoisingAutoEncoderReader.py During training, the decoder reconstructs the original sentences from the encoded sentence embeddings. Here the argument 'decoder_name_or_path' indicates the pretrained model (supported by Huggingface) to be used as the decoder. Since decoding process is included, here the decoder should have a class called XXXLMHead (in the context of Huggingface's Transformers). Flag 'tie_encoder_decoder' indicates whether to tie the trainable parameters of encoder and decoder, which is shown beneficial to model performance while limiting the amount of required memory. Only when the encoder and decoder are from the same architecture, can the flag 'tie_encoder_decoder' works. For more information, please refer to the TSDAE paper. """ def __init__( self, model: SentenceTransformer, decoder_name_or_path: str = None, tie_encoder_decoder: bool = True ): """ :param model: SentenceTransformer model :param decoder_name_or_path: Model name or path for initializing a decoder (compatible with Huggingface's Transformers) :param tie_encoder_decoder: whether to tie the trainable parameters of encoder and decoder """ super(DenoisingAutoEncoderLoss, self).__init__() self.encoder = model # This will be the final model used during the inference time. self.tokenizer_encoder = model.tokenizer encoder_name_or_path = model[0].auto_model.config._name_or_path if decoder_name_or_path is None: assert tie_encoder_decoder, "Must indicate the decoder_name_or_path argument when tie_encoder_decoder=False!" if tie_encoder_decoder: if decoder_name_or_path: logger.warning('When tie_encoder_decoder=True, the decoder_name_or_path will be invalid.') decoder_name_or_path = encoder_name_or_path self.tokenizer_decoder = AutoTokenizer.from_pretrained(decoder_name_or_path) self.need_retokenization = not (type(self.tokenizer_encoder) == type(self.tokenizer_decoder)) decoder_config = AutoConfig.from_pretrained(decoder_name_or_path) decoder_config.is_decoder = True decoder_config.add_cross_attention = True kwargs_decoder = {'config': decoder_config} try: self.decoder = AutoModelForCausalLM.from_pretrained(decoder_name_or_path, **kwargs_decoder) except ValueError as e: logger.error(f'Model name or path "{decoder_name_or_path}" does not support being as a decoder. Please make sure the decoder model has an "XXXLMHead" class.') raise e assert model[0].auto_model.config.hidden_size == decoder_config.hidden_size, 'Hidden sizes do not match!' if self.tokenizer_decoder.pad_token is None: # Needed by GPT-2, etc. self.tokenizer_decoder.pad_token = self.tokenizer_decoder.eos_token self.decoder.config.pad_token_id = self.decoder.config.eos_token_id if len(AutoTokenizer.from_pretrained(encoder_name_or_path)) != len(self.tokenizer_encoder): logger.warning('WARNING: The vocabulary of the encoder has been changed. One might need to change the decoder vocabulary, too.') if tie_encoder_decoder: assert not self.need_retokenization, "The tokenizers should be the same when tie_encoder_decoder=True." if len(self.tokenizer_encoder) != len(self.tokenizer_decoder): # The vocabulary has been changed. self.tokenizer_decoder = self.tokenizer_encoder self.decoder.resize_token_embeddings(len(self.tokenizer_decoder)) logger.warning('Since the encoder vocabulary has been changed and --tie_encoder_decoder=True, now the new vocabulary has also been used for the decoder.') decoder_base_model_prefix = self.decoder.base_model_prefix PreTrainedModel._tie_encoder_decoder_weights( model[0].auto_model, self.decoder._modules[decoder_base_model_prefix], self.decoder.base_model_prefix ) def retokenize(self, sentence_features): input_ids = sentence_features['input_ids'] device = input_ids.device sentences_decoded = self.tokenizer_decoder.batch_decode( input_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True ) retokenized = self.tokenizer_decoder( sentences_decoded, padding=True, truncation='longest_first', return_tensors="pt", max_length=None ).to(device) return retokenized def forward(self, sentence_features: Iterable[Dict[str, Tensor]], labels: Tensor): source_features, target_features = tuple(sentence_features) if self.need_retokenization: # since the sentence_features here are all tokenized by encoder's tokenizer, # retokenization by the decoder's one is needed if different tokenizers used target_features = self.retokenize(target_features) reps = self.encoder(source_features)['sentence_embedding'] # (bsz, hdim) # Prepare input and output target_length = target_features['input_ids'].shape[1] decoder_input_ids = target_features['input_ids'].clone()[:, :target_length - 1] label_ids = target_features['input_ids'][:, 1:] # Decode decoder_outputs = self.decoder( input_ids=decoder_input_ids, inputs_embeds=None, attention_mask=None, encoder_hidden_states=reps[:, None], # (bsz, hdim) -> (bsz, 1, hdim) encoder_attention_mask=source_features['attention_mask'][:, 0:1], labels=None, return_dict=None, use_cache=False ) # Calculate loss lm_logits = decoder_outputs[0] ce_loss_fct = nn.CrossEntropyLoss(ignore_index=self.tokenizer_decoder.pad_token_id) loss = ce_loss_fct(lm_logits.view(-1, lm_logits.shape[-1]), label_ids.reshape(-1)) return loss
apache-2.0
florian-shellfire/shellfirebox-files
files_template/usr/lib/lua/luci/controller/admin/index.lua
2161
-- Copyright 2008 Steven Barth <[email protected]> -- Licensed to the public under the Apache License 2.0. module("luci.controller.admin.index", package.seeall) local debugger = require "luci.debugger" -- Shellfire Box modifications index function --[[ function index() local root = node() if not root.target then root.target = alias("admin") root.index = true end local page = node("admin") page.target = firstchild() page.title = _("Administration") page.order = 10 page.sysauth = "root" page.sysauth_authenticator = "htmlauth" page.ucidata = true page.index = true -- Empty services menu to be populated by addons entry({"admin", "services"}, firstchild(), _("Services"), 40).index = true entry({"admin", "logout"}, call("action_logout"), _("Logout"), 90) end --]] function index() local root = node() if not root.target then root.target = alias("admin") root.index = true end local page = node("admin") page.target = alias("admin", "services", "shellfirebox") page.title = _("Administration") page.order = 10 local shellfirebox = require "luci.shellfirebox" if luci.sys.user.getpasswd("root") then page.sysauth = "root" page.sysauth_authenticator = "htmlauth" entry({"admin", "logout"}, call("action_logout"), _("Logout"), 90) else page.sysauth = false end page.ucidata = true page.index = true -- Empty services menu to be populated by addons entry({"admin", "services"}, firstchild(), _("Services"), 40).index = true end function action_logout() -- Shellfire Box modiciations below -- following 2 lines inserted (+ added tabs in if ... statement) local shellfirebox = require "luci.shellfirebox" if shellfirebox.isAdvancedMode() then local dsp = require "luci.dispatcher" local utl = require "luci.util" local sid = dsp.context.authsession if sid then utl.ubus("session", "destroy", { ubus_rpc_session = sid }) luci.http.header("Set-Cookie", "sysauth=%s; expires=%s; path=%s/" %{ sid, 'Thu, 01 Jan 1970 01:00:00 GMT', dsp.build_url() }) end -- Shellfire Box modification below -- following line inserted end luci.http.redirect(dsp.build_url()) end
apache-2.0
WIgor/hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DNConf.java
17321
/** * 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. */ package org.apache.hadoop.hdfs.server.datanode; import org.apache.hadoop.classification.InterfaceAudience; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCKREPORT_INITIAL_DELAY_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCKREPORT_INITIAL_DELAY_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCKREPORT_SPLIT_THRESHOLD_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCKREPORT_SPLIT_THRESHOLD_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CACHEREPORT_INTERVAL_MSEC_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CACHEREPORT_INTERVAL_MSEC_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_LIFELINE_INTERVAL_SECONDS_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_NON_LOCAL_LAZY_PERSIST; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_NON_LOCAL_LAZY_PERSIST_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_OUTLIERS_REPORT_INTERVAL_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_OUTLIERS_REPORT_INTERVAL_KEY; import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_CLIENT_SOCKET_TIMEOUT_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_MAX_LOCKED_MEMORY_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_MAX_LOCKED_MEMORY_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_SOCKET_WRITE_TIMEOUT_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_SYNCONCLOSE_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_SYNCONCLOSE_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_TRANSFERTO_ALLOWED_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_TRANSFERTO_ALLOWED_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_XCEIVER_STOP_TIMEOUT_MILLIS_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_XCEIVER_STOP_TIMEOUT_MILLIS_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_MIN_SUPPORTED_NAMENODE_VERSION_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_MIN_SUPPORTED_NAMENODE_VERSION_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_ENCRYPT_DATA_TRANSFER_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_ENCRYPT_DATA_TRANSFER_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATA_ENCRYPTION_ALGORITHM_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_RESTART_REPLICA_EXPIRY_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_RESTART_REPLICA_EXPIRY_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.IGNORE_SECURE_PORTS_FOR_TESTING_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.IGNORE_SECURE_PORTS_FOR_TESTING_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_BP_READY_TIMEOUT_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_BP_READY_TIMEOUT_DEFAULT; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys; import org.apache.hadoop.hdfs.protocol.HdfsConstants; import org.apache.hadoop.hdfs.protocol.datatransfer.TrustedChannelResolver; import org.apache.hadoop.hdfs.protocol.datatransfer.sasl.DataTransferSaslUtil; import org.apache.hadoop.hdfs.server.common.Util; import org.apache.hadoop.security.SaslPropertiesResolver; import java.util.concurrent.TimeUnit; /** * Simple class encapsulating all of the configuration that the DataNode * loads at startup time. */ @InterfaceAudience.Private public class DNConf { final int socketTimeout; final int socketWriteTimeout; final int socketKeepaliveTimeout; private final int transferSocketSendBufferSize; private final int transferSocketRecvBufferSize; private final boolean tcpNoDelay; final boolean transferToAllowed; final boolean dropCacheBehindWrites; final boolean syncBehindWrites; final boolean syncBehindWritesInBackground; final boolean dropCacheBehindReads; final boolean syncOnClose; final boolean encryptDataTransfer; final boolean connectToDnViaHostname; final long readaheadLength; final long heartBeatInterval; private final long lifelineIntervalMs; final long blockReportInterval; final long blockReportSplitThreshold; final boolean peerStatsEnabled; final boolean diskStatsEnabled; final long outliersReportIntervalMs; final long ibrInterval; final long initialBlockReportDelayMs; final long cacheReportInterval; final long datanodeSlowIoWarningThresholdMs; final String minimumNameNodeVersion; final String encryptionAlgorithm; final SaslPropertiesResolver saslPropsResolver; final TrustedChannelResolver trustedChannelResolver; private final boolean ignoreSecurePortsForTesting; final long xceiverStopTimeout; final long restartReplicaExpiry; final long maxLockedMemory; private final long bpReadyTimeout; // Allow LAZY_PERSIST writes from non-local clients? private final boolean allowNonLocalLazyPersist; private final int volFailuresTolerated; private final int volsConfigured; private final int maxDataLength; private Configurable dn; public DNConf(final Configurable dn) { this.dn = dn; socketTimeout = getConf().getInt(DFS_CLIENT_SOCKET_TIMEOUT_KEY, HdfsConstants.READ_TIMEOUT); socketWriteTimeout = getConf().getInt(DFS_DATANODE_SOCKET_WRITE_TIMEOUT_KEY, HdfsConstants.WRITE_TIMEOUT); socketKeepaliveTimeout = getConf().getInt( DFSConfigKeys.DFS_DATANODE_SOCKET_REUSE_KEEPALIVE_KEY, DFSConfigKeys.DFS_DATANODE_SOCKET_REUSE_KEEPALIVE_DEFAULT); this.transferSocketSendBufferSize = getConf().getInt( DFSConfigKeys.DFS_DATANODE_TRANSFER_SOCKET_SEND_BUFFER_SIZE_KEY, DFSConfigKeys.DFS_DATANODE_TRANSFER_SOCKET_SEND_BUFFER_SIZE_DEFAULT); this.transferSocketRecvBufferSize = getConf().getInt( DFSConfigKeys.DFS_DATANODE_TRANSFER_SOCKET_RECV_BUFFER_SIZE_KEY, DFSConfigKeys.DFS_DATANODE_TRANSFER_SOCKET_RECV_BUFFER_SIZE_DEFAULT); this.tcpNoDelay = getConf().getBoolean( DFSConfigKeys.DFS_DATA_TRANSFER_SERVER_TCPNODELAY, DFSConfigKeys.DFS_DATA_TRANSFER_SERVER_TCPNODELAY_DEFAULT); /* Based on results on different platforms, we might need set the default * to false on some of them. */ transferToAllowed = getConf().getBoolean( DFS_DATANODE_TRANSFERTO_ALLOWED_KEY, DFS_DATANODE_TRANSFERTO_ALLOWED_DEFAULT); readaheadLength = getConf().getLong( HdfsClientConfigKeys.DFS_DATANODE_READAHEAD_BYTES_KEY, HdfsClientConfigKeys.DFS_DATANODE_READAHEAD_BYTES_DEFAULT); maxDataLength = getConf().getInt(DFSConfigKeys.IPC_MAXIMUM_DATA_LENGTH, DFSConfigKeys.IPC_MAXIMUM_DATA_LENGTH_DEFAULT); dropCacheBehindWrites = getConf().getBoolean( DFSConfigKeys.DFS_DATANODE_DROP_CACHE_BEHIND_WRITES_KEY, DFSConfigKeys.DFS_DATANODE_DROP_CACHE_BEHIND_WRITES_DEFAULT); syncBehindWrites = getConf().getBoolean( DFSConfigKeys.DFS_DATANODE_SYNC_BEHIND_WRITES_KEY, DFSConfigKeys.DFS_DATANODE_SYNC_BEHIND_WRITES_DEFAULT); syncBehindWritesInBackground = getConf().getBoolean( DFSConfigKeys.DFS_DATANODE_SYNC_BEHIND_WRITES_IN_BACKGROUND_KEY, DFSConfigKeys.DFS_DATANODE_SYNC_BEHIND_WRITES_IN_BACKGROUND_DEFAULT); dropCacheBehindReads = getConf().getBoolean( DFSConfigKeys.DFS_DATANODE_DROP_CACHE_BEHIND_READS_KEY, DFSConfigKeys.DFS_DATANODE_DROP_CACHE_BEHIND_READS_DEFAULT); connectToDnViaHostname = getConf().getBoolean( DFSConfigKeys.DFS_DATANODE_USE_DN_HOSTNAME, DFSConfigKeys.DFS_DATANODE_USE_DN_HOSTNAME_DEFAULT); this.blockReportInterval = getConf().getLong( DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, DFS_BLOCKREPORT_INTERVAL_MSEC_DEFAULT); this.peerStatsEnabled = getConf().getBoolean( DFSConfigKeys.DFS_DATANODE_PEER_STATS_ENABLED_KEY, DFSConfigKeys.DFS_DATANODE_PEER_STATS_ENABLED_DEFAULT); this.diskStatsEnabled = Util.isDiskStatsEnabled(getConf().getDouble( DFSConfigKeys.DFS_DATANODE_FILEIO_PROFILING_SAMPLING_FRACTION_KEY, DFSConfigKeys.DFS_DATANODE_FILEIO_PROFILING_SAMPLING_FRACTION_DEFAULT)); this.outliersReportIntervalMs = getConf().getTimeDuration( DFS_DATANODE_OUTLIERS_REPORT_INTERVAL_KEY, DFS_DATANODE_OUTLIERS_REPORT_INTERVAL_DEFAULT, TimeUnit.MILLISECONDS); this.ibrInterval = getConf().getLong( DFSConfigKeys.DFS_BLOCKREPORT_INCREMENTAL_INTERVAL_MSEC_KEY, DFSConfigKeys.DFS_BLOCKREPORT_INCREMENTAL_INTERVAL_MSEC_DEFAULT); this.blockReportSplitThreshold = getConf().getLong( DFS_BLOCKREPORT_SPLIT_THRESHOLD_KEY, DFS_BLOCKREPORT_SPLIT_THRESHOLD_DEFAULT); this.cacheReportInterval = getConf().getLong( DFS_CACHEREPORT_INTERVAL_MSEC_KEY, DFS_CACHEREPORT_INTERVAL_MSEC_DEFAULT); this.datanodeSlowIoWarningThresholdMs = getConf().getLong( DFSConfigKeys.DFS_DATANODE_SLOW_IO_WARNING_THRESHOLD_KEY, DFSConfigKeys.DFS_DATANODE_SLOW_IO_WARNING_THRESHOLD_DEFAULT); long initBRDelay = getConf().getTimeDuration( DFS_BLOCKREPORT_INITIAL_DELAY_KEY, DFS_BLOCKREPORT_INITIAL_DELAY_DEFAULT, TimeUnit.SECONDS) * 1000L; if (initBRDelay >= blockReportInterval) { initBRDelay = 0; DataNode.LOG.info("dfs.blockreport.initialDelay is " + "greater than or equal to" + "dfs.blockreport.intervalMsec." + " Setting initial delay to 0 msec:"); } initialBlockReportDelayMs = initBRDelay; heartBeatInterval = getConf().getTimeDuration(DFS_HEARTBEAT_INTERVAL_KEY, DFS_HEARTBEAT_INTERVAL_DEFAULT, TimeUnit.SECONDS) * 1000L; long confLifelineIntervalMs = getConf().getLong(DFS_DATANODE_LIFELINE_INTERVAL_SECONDS_KEY, 3 * getConf().getTimeDuration(DFS_HEARTBEAT_INTERVAL_KEY, DFS_HEARTBEAT_INTERVAL_DEFAULT, TimeUnit.SECONDS)) * 1000L; if (confLifelineIntervalMs <= heartBeatInterval) { confLifelineIntervalMs = 3 * heartBeatInterval; DataNode.LOG.warn( String.format("%s must be set to a value greater than %s. " + "Resetting value to 3 * %s, which is %d milliseconds.", DFS_DATANODE_LIFELINE_INTERVAL_SECONDS_KEY, DFS_HEARTBEAT_INTERVAL_KEY, DFS_HEARTBEAT_INTERVAL_KEY, confLifelineIntervalMs)); } lifelineIntervalMs = confLifelineIntervalMs; // do we need to sync block file contents to disk when blockfile is closed? this.syncOnClose = getConf().getBoolean(DFS_DATANODE_SYNCONCLOSE_KEY, DFS_DATANODE_SYNCONCLOSE_DEFAULT); this.minimumNameNodeVersion = getConf().get( DFS_DATANODE_MIN_SUPPORTED_NAMENODE_VERSION_KEY, DFS_DATANODE_MIN_SUPPORTED_NAMENODE_VERSION_DEFAULT); this.encryptDataTransfer = getConf().getBoolean( DFS_ENCRYPT_DATA_TRANSFER_KEY, DFS_ENCRYPT_DATA_TRANSFER_DEFAULT); this.encryptionAlgorithm = getConf().get(DFS_DATA_ENCRYPTION_ALGORITHM_KEY); this.trustedChannelResolver = TrustedChannelResolver.getInstance(getConf()); this.saslPropsResolver = DataTransferSaslUtil.getSaslPropertiesResolver( getConf()); this.ignoreSecurePortsForTesting = getConf().getBoolean( IGNORE_SECURE_PORTS_FOR_TESTING_KEY, IGNORE_SECURE_PORTS_FOR_TESTING_DEFAULT); this.xceiverStopTimeout = getConf().getLong( DFS_DATANODE_XCEIVER_STOP_TIMEOUT_MILLIS_KEY, DFS_DATANODE_XCEIVER_STOP_TIMEOUT_MILLIS_DEFAULT); this.maxLockedMemory = getConf().getLong( DFS_DATANODE_MAX_LOCKED_MEMORY_KEY, DFS_DATANODE_MAX_LOCKED_MEMORY_DEFAULT); this.restartReplicaExpiry = getConf().getLong( DFS_DATANODE_RESTART_REPLICA_EXPIRY_KEY, DFS_DATANODE_RESTART_REPLICA_EXPIRY_DEFAULT) * 1000L; this.allowNonLocalLazyPersist = getConf().getBoolean( DFS_DATANODE_NON_LOCAL_LAZY_PERSIST, DFS_DATANODE_NON_LOCAL_LAZY_PERSIST_DEFAULT); this.bpReadyTimeout = getConf().getTimeDuration( DFS_DATANODE_BP_READY_TIMEOUT_KEY, DFS_DATANODE_BP_READY_TIMEOUT_DEFAULT, TimeUnit.SECONDS); this.volFailuresTolerated = getConf().getInt( DFSConfigKeys.DFS_DATANODE_FAILED_VOLUMES_TOLERATED_KEY, DFSConfigKeys.DFS_DATANODE_FAILED_VOLUMES_TOLERATED_DEFAULT); String[] dataDirs = getConf().getTrimmedStrings(DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY); this.volsConfigured = (dataDirs == null) ? 0 : dataDirs.length; } // We get minimumNameNodeVersion via a method so it can be mocked out in tests. String getMinimumNameNodeVersion() { return this.minimumNameNodeVersion; } /** * Returns the configuration. * * @return Configuration the configuration */ public Configuration getConf() { return this.dn.getConf(); } /** * Returns true if encryption enabled for DataTransferProtocol. * * @return boolean true if encryption enabled for DataTransferProtocol */ public boolean getEncryptDataTransfer() { return encryptDataTransfer; } /** * Returns encryption algorithm configured for DataTransferProtocol, or null * if not configured. * * @return encryption algorithm configured for DataTransferProtocol */ public String getEncryptionAlgorithm() { return encryptionAlgorithm; } public long getXceiverStopTimeout() { return xceiverStopTimeout; } public long getMaxLockedMemory() { return maxLockedMemory; } /** * Returns true if connect to datanode via hostname * * @return boolean true if connect to datanode via hostname */ public boolean getConnectToDnViaHostname() { return connectToDnViaHostname; } /** * Returns socket timeout * * @return int socket timeout */ public int getSocketTimeout() { return socketTimeout; } /** * Returns socket write timeout * * @return int socket write timeout */ public int getSocketWriteTimeout() { return socketWriteTimeout; } /** * Returns the SaslPropertiesResolver configured for use with * DataTransferProtocol, or null if not configured. * * @return SaslPropertiesResolver configured for use with DataTransferProtocol */ public SaslPropertiesResolver getSaslPropsResolver() { return saslPropsResolver; } /** * Returns the TrustedChannelResolver configured for use with * DataTransferProtocol, or null if not configured. * * @return TrustedChannelResolver configured for use with DataTransferProtocol */ public TrustedChannelResolver getTrustedChannelResolver() { return trustedChannelResolver; } /** * Returns true if configuration is set to skip checking for proper * port configuration in a secured cluster. This is only intended for use in * dev testing. * * @return true if configured to skip checking secured port configuration */ public boolean getIgnoreSecurePortsForTesting() { return ignoreSecurePortsForTesting; } public boolean getAllowNonLocalLazyPersist() { return allowNonLocalLazyPersist; } public int getTransferSocketRecvBufferSize() { return transferSocketRecvBufferSize; } public int getTransferSocketSendBufferSize() { return transferSocketSendBufferSize; } public boolean getDataTransferServerTcpNoDelay() { return tcpNoDelay; } public long getBpReadyTimeout() { return bpReadyTimeout; } /** * Returns the interval in milliseconds between sending lifeline messages. * * @return interval in milliseconds between sending lifeline messages */ public long getLifelineIntervalMs() { return lifelineIntervalMs; } public int getVolFailuresTolerated() { return volFailuresTolerated; } public int getVolsConfigured() { return volsConfigured; } public long getSlowIoWarningThresholdMs() { return datanodeSlowIoWarningThresholdMs; } int getMaxDataLength() { return maxDataLength; } }
apache-2.0
defuz/sublimate
src/toolkit/draw.rs
345
pub trait Drawing { fn char(&self, c: char, x: usize, y: usize); fn text(&self, s: &str, x: usize, y: usize); fn fill_char(&self, c: char); fn fill(&self); } pub trait HasSize { fn width(&self) -> usize; fn height(&self) -> usize; } pub trait HasChildren { type Item; fn children(&self) -> &[Self::Item]; }
apache-2.0
edx/repo-tools
edx_repo_tools/codemods/django2/foreignkey_on_delete_mod.py
1718
import sys from typing import Optional from bowler import Query, LN, Capture, Filename, TOKEN, SYMBOL from fissix.pytree import Node, Leaf from lib2to3.fixer_util import Name, KeywordArg, Dot, Comma, Newline, ArgList def filter_print_string(node, capture, filename) -> bool: function_name = capture.get("function_name") from pprint import pprint pprint(node) pprint(capture) return True def filter_has_no_on_delete(node: LN, capture: Capture, filename: Filename) -> bool: arguments = capture.get("function_arguments")[0].children for arg in arguments: if arg.type == SYMBOL.argument and arg.children[0].type == TOKEN.NAME: arg_name = arg.children[0].value if arg_name == "on_delete": return False # this call already has an on_delete argument. return True def add_on_delete_cascade( node: LN, capture: Capture, filename: Filename ) -> Optional[LN]: arguments = capture.get("function_arguments")[0] new_on_delete_node = KeywordArg(Name(" on_delete"), Name("models.CASCADE")) if isinstance(arguments, Leaf): # Node is a leaf and so we need to replace it with a list of things we want instead. arguments.replace([arguments.clone(),Comma(),new_on_delete_node]) else: arguments.append_child(Comma()) arguments.append_child(new_on_delete_node) return node ( Query(sys.argv[1]) .select_method("ForeignKey") .is_call() .filter(filter_has_no_on_delete) .modify(add_on_delete_cascade) .idiff() ), ( Query(sys.argv[1]) .select_method("OneToOneField") .is_call() .filter(filter_has_no_on_delete) .modify(add_on_delete_cascade) .idiff() )
apache-2.0
xnx3/iw
doc/index-files/index-19.html
92996
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="zh"> <head> <!-- Generated by javadoc (1.8.0_40) on Sat Feb 10 09:47:11 CST 2018 --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>S - 索引</title> <meta name="date" content="2018-02-10"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> <script type="text/javascript" src="../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="S - \u7D22\u5F15"; } } catch(err) { } //--> </script> <noscript> <div>您的浏览器已禁用 JavaScript。</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="跳过导航链接">跳过导航链接</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="导航"> <li><a href="../overview-summary.html">概览</a></li> <li>程序包</li> <li>类</li> <li>使用</li> <li><a href="../overview-tree.html">树</a></li> <li><a href="../deprecated-list.html">已过时</a></li> <li class="navBarCell1Rev">索引</li> <li><a href="../help-doc.html">帮助</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-18.html">上一个字母</a></li> <li><a href="index-20.html">下一个字母</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-19.html" target="_top">框架</a></li> <li><a href="index-19.html" target="_top">无框架</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">所有类</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="contentContainer"><a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">J</a>&nbsp;<a href="index-11.html">K</a>&nbsp;<a href="index-12.html">L</a>&nbsp;<a href="index-13.html">M</a>&nbsp;<a href="index-14.html">N</a>&nbsp;<a href="index-15.html">O</a>&nbsp;<a href="index-16.html">P</a>&nbsp;<a href="index-17.html">Q</a>&nbsp;<a href="index-18.html">R</a>&nbsp;<a href="index-19.html">S</a>&nbsp;<a href="index-20.html">T</a>&nbsp;<a href="index-21.html">U</a>&nbsp;<a href="index-22.html">V</a>&nbsp;<a href="index-23.html">W</a>&nbsp;<a href="index-24.html">X</a>&nbsp;<a name="I:S"> <!-- --> </a> <h2 class="title">S</h2> <dl> <dt><a href="../com/xnx3/j2ee/func/Safety.html" title="com.xnx3.j2ee.func中的类"><span class="typeNameLink">Safety</span></a> - <a href="../com/xnx3/j2ee/func/package-summary.html">com.xnx3.j2ee.func</a>中的类</dt> <dd> <div class="block">安全方面操作</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/func/Safety.html#Safety--">Safety()</a></span> - 类 的构造器com.xnx3.j2ee.func.<a href="../com/xnx3/j2ee/func/Safety.html" title="com.xnx3.j2ee.func中的类">Safety</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/baidu/ueditor/upload/Base64Uploader.html#save-java.lang.String-java.util.Map-">save(String, Map&lt;String, Object&gt;)</a></span> - 类 中的静态方法com.baidu.ueditor.upload.<a href="../com/baidu/ueditor/upload/Base64Uploader.html" title="com.baidu.ueditor.upload中的类">Base64Uploader</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/baidu/ueditor/upload/BinaryUploader.html#save-javax.servlet.http.HttpServletRequest-java.util.Map-">save(HttpServletRequest, Map&lt;String, Object&gt;)</a></span> - 类 中的静态方法com.baidu.ueditor.upload.<a href="../com/baidu/ueditor/upload/BinaryUploader.html" title="com.baidu.ueditor.upload中的类">BinaryUploader</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/dao/MessageDAO.html#save-com.xnx3.j2ee.entity.Message-">save(Message)</a></span> - 类 中的方法com.xnx3.j2ee.dao.<a href="../com/xnx3/j2ee/dao/MessageDAO.html" title="com.xnx3.j2ee.dao中的类">MessageDAO</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/dao/PermissionDAO.html#save-com.xnx3.j2ee.entity.Permission-">save(Permission)</a></span> - 类 中的方法com.xnx3.j2ee.dao.<a href="../com/xnx3/j2ee/dao/PermissionDAO.html" title="com.xnx3.j2ee.dao中的类">PermissionDAO</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/dao/SqlDAO.html#save-java.lang.Object-">save(Object)</a></span> - 类 中的方法com.xnx3.j2ee.dao.<a href="../com/xnx3/j2ee/dao/SqlDAO.html" title="com.xnx3.j2ee.dao中的类">SqlDAO</a></dt> <dd> <div class="block">添加/修改</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/FriendLogService.html#save-com.xnx3.j2ee.entity.FriendLog-">save(FriendLog)</a></span> - 接口 中的方法com.xnx3.j2ee.service.<a href="../com/xnx3/j2ee/service/FriendLogService.html" title="com.xnx3.j2ee.service中的接口">FriendLogService</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/SqlServiceImpl.html#save-java.lang.Object-">save(Object)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/SqlServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">SqlServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/SqlService.html#save-java.lang.Object-">save(Object)</a></span> - 接口 中的方法com.xnx3.j2ee.service.<a href="../com/xnx3/j2ee/service/SqlService.html" title="com.xnx3.j2ee.service中的接口">SqlService</a></dt> <dd> <div class="block">添加/修改</div> </dd> <dt><span class="memberNameLink"><a href="../com/baidu/ueditor/upload/StorageManager.html#saveBinaryFile-byte:A-java.lang.String-">saveBinaryFile(byte[], String)</a></span> - 类 中的静态方法com.baidu.ueditor.upload.<a href="../com/baidu/ueditor/upload/StorageManager.html" title="com.baidu.ueditor.upload中的类">StorageManager</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/controller/admin/BbsAdminController_.html#saveClass-javax.servlet.http.HttpServletRequest-org.springframework.ui.Model-">saveClass(HttpServletRequest, Model)</a></span> - 类 中的方法com.xnx3.j2ee.controller.admin.<a href="../com/xnx3/j2ee/controller/admin/BbsAdminController_.html" title="com.xnx3.j2ee.controller.admin中的类">BbsAdminController_</a></dt> <dd> <div class="block">添加/修改板块提交页面</div> </dd> <dt><span class="memberNameLink"><a href="../com/baidu/ueditor/upload/StorageManager.html#saveFileByInputStream-java.io.InputStream-java.lang.String-long-">saveFileByInputStream(InputStream, String, long)</a></span> - 类 中的静态方法com.baidu.ueditor.upload.<a href="../com/baidu/ueditor/upload/StorageManager.html" title="com.baidu.ueditor.upload中的类">StorageManager</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/baidu/ueditor/upload/StorageManager.html#saveFileByInputStream-java.io.InputStream-java.lang.String-">saveFileByInputStream(InputStream, String)</a></span> - 类 中的静态方法com.baidu.ueditor.upload.<a href="../com/baidu/ueditor/upload/StorageManager.html" title="com.baidu.ueditor.upload中的类">StorageManager</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/controller/admin/RoleAdminController_.html#savePermission-com.xnx3.j2ee.entity.Permission-org.springframework.ui.Model-javax.servlet.http.HttpServletRequest-">savePermission(Permission, Model, HttpServletRequest)</a></span> - 类 中的方法com.xnx3.j2ee.controller.admin.<a href="../com/xnx3/j2ee/controller/admin/RoleAdminController_.html" title="com.xnx3.j2ee.controller.admin中的类">RoleAdminController_</a></dt> <dd> <div class="block">Permission提交保存</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/controller/admin/BbsAdminController_.html#savePost-javax.servlet.http.HttpServletRequest-org.springframework.ui.Model-">savePost(HttpServletRequest, Model)</a></span> - 类 中的方法com.xnx3.j2ee.controller.admin.<a href="../com/xnx3/j2ee/controller/admin/BbsAdminController_.html" title="com.xnx3.j2ee.controller.admin中的类">BbsAdminController_</a></dt> <dd> <div class="block">添加、编辑时保存帖子</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/PostServiceImpl.html#savePost-javax.servlet.http.HttpServletRequest-">savePost(HttpServletRequest)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/PostServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">PostServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/PostService.html#savePost-javax.servlet.http.HttpServletRequest-">savePost(HttpServletRequest)</a></span> - 接口 中的方法com.xnx3.j2ee.service.<a href="../com/xnx3/j2ee/service/PostService.html" title="com.xnx3.j2ee.service中的接口">PostService</a></dt> <dd> <div class="block">发表帖子</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/PostServiceImpl.html#savePostClass-javax.servlet.http.HttpServletRequest-">savePostClass(HttpServletRequest)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/PostServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">PostServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/PostService.html#savePostClass-javax.servlet.http.HttpServletRequest-">savePostClass(HttpServletRequest)</a></span> - 接口 中的方法com.xnx3.j2ee.service.<a href="../com/xnx3/j2ee/service/PostService.html" title="com.xnx3.j2ee.service中的接口">PostService</a></dt> <dd> <div class="block">添加、修改板块</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/controller/admin/RoleAdminController_.html#saveRole-com.xnx3.j2ee.entity.Role-org.springframework.ui.Model-javax.servlet.http.HttpServletRequest-">saveRole(Role, Model, HttpServletRequest)</a></span> - 类 中的方法com.xnx3.j2ee.controller.admin.<a href="../com/xnx3/j2ee/controller/admin/RoleAdminController_.html" title="com.xnx3.j2ee.controller.admin中的类">RoleAdminController_</a></dt> <dd> <div class="block">添加/修改角色提交页</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/controller/admin/RoleAdminController_.html#saveRolePermission-int-java.lang.String-org.springframework.ui.Model-javax.servlet.http.HttpServletRequest-">saveRolePermission(int, String, Model, HttpServletRequest)</a></span> - 类 中的方法com.xnx3.j2ee.controller.admin.<a href="../com/xnx3/j2ee/controller/admin/RoleAdminController_.html" title="com.xnx3.j2ee.controller.admin中的类">RoleAdminController_</a></dt> <dd> <div class="block">保存角色-资源设置</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/RoleServiceImpl.html#saveRolePermission-int-java.lang.String-">saveRolePermission(int, String)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/RoleServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">RoleServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/RoleService.html#saveRolePermission-int-java.lang.String-">saveRolePermission(int, String)</a></span> - 接口 中的方法com.xnx3.j2ee.service.<a href="../com/xnx3/j2ee/service/RoleService.html" title="com.xnx3.j2ee.service中的接口">RoleService</a></dt> <dd> <div class="block">修改某个角色下所拥有的资源,提交保存的操作。</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/controller/admin/RoleAdminController_.html#saveUserRole-int-java.lang.String-org.springframework.ui.Model-javax.servlet.http.HttpServletRequest-">saveUserRole(int, String, Model, HttpServletRequest)</a></span> - 类 中的方法com.xnx3.j2ee.controller.admin.<a href="../com/xnx3/j2ee/controller/admin/RoleAdminController_.html" title="com.xnx3.j2ee.controller.admin中的类">RoleAdminController_</a></dt> <dd> <div class="block">保存用户-角色设置</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/RoleServiceImpl.html#saveUserRole-int-java.lang.String-">saveUserRole(int, String)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/RoleServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">RoleServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/RoleService.html#saveUserRole-int-java.lang.String-">saveUserRole(int, String)</a></span> - 接口 中的方法com.xnx3.j2ee.service.<a href="../com/xnx3/j2ee/service/RoleService.html" title="com.xnx3.j2ee.service中的接口">RoleService</a></dt> <dd> <div class="block">保存用户拥有哪些角色,多用于form表单提交后,多选框将选中的角色保存</div> </dd> <dt><span class="memberNameLink"><a href="../com/qikemi/packages/alibaba/aliyun/oss/properties/OSSClientProperties.html#secret">secret</a></span> - 类 中的静态变量com.qikemi.packages.alibaba.aliyun.oss.properties.<a href="../com/qikemi/packages/alibaba/aliyun/oss/properties/OSSClientProperties.html" title="com.qikemi.packages.alibaba.aliyun.oss.properties中的类">OSSClientProperties</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/dao/MessageDAO.html#SELF">SELF</a></span> - 类 中的静态变量com.xnx3.j2ee.dao.<a href="../com/xnx3/j2ee/dao/MessageDAO.html" title="com.xnx3.j2ee.dao中的类">MessageDAO</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/controller/MessageController_.html#send-javax.servlet.http.HttpServletRequest-org.springframework.ui.Model-">send(HttpServletRequest, Model)</a></span> - 类 中的方法com.xnx3.j2ee.controller.<a href="../com/xnx3/j2ee/controller/MessageController_.html" title="com.xnx3.j2ee.controller中的类">MessageController_</a></dt> <dd> <div class="block">发送信息提交</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/SmsLogServiceImpl.html#sendByAliyunSMS-javax.servlet.http.HttpServletRequest-com.xnx3.net.AliyunSMSUtil-java.lang.String-java.lang.String-java.lang.String-java.lang.Short-">sendByAliyunSMS(HttpServletRequest, AliyunSMSUtil, String, String, String, Short)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/SmsLogServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">SmsLogServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/SmsLogService.html#sendByAliyunSMS-javax.servlet.http.HttpServletRequest-com.xnx3.net.AliyunSMSUtil-java.lang.String-java.lang.String-java.lang.String-java.lang.Short-">sendByAliyunSMS(HttpServletRequest, AliyunSMSUtil, String, String, String, Short)</a></span> - 接口 中的方法com.xnx3.j2ee.service.<a href="../com/xnx3/j2ee/service/SmsLogService.html" title="com.xnx3.j2ee.service中的接口">SmsLogService</a></dt> <dd> <div class="block">使用阿里云短信通道,向指定手机号发送指定内容的验证码。</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/MessageServiceImpl.html#sendMessage-javax.servlet.http.HttpServletRequest-">sendMessage(HttpServletRequest)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/MessageServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">MessageServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/MessageServiceImpl.html#sendMessage-int-java.lang.String-">sendMessage(int, String)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/MessageServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">MessageServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/MessageServiceImpl.html#sendMessage-int-int-java.lang.String-">sendMessage(int, int, String)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/MessageServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">MessageServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/MessageService.html#sendMessage-javax.servlet.http.HttpServletRequest-">sendMessage(HttpServletRequest)</a></span> - 接口 中的方法com.xnx3.j2ee.service.<a href="../com/xnx3/j2ee/service/MessageService.html" title="com.xnx3.j2ee.service中的接口">MessageService</a></dt> <dd> <div class="block">发送信息</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/MessageService.html#sendMessage-int-java.lang.String-">sendMessage(int, String)</a></span> - 接口 中的方法com.xnx3.j2ee.service.<a href="../com/xnx3/j2ee/service/MessageService.html" title="com.xnx3.j2ee.service中的接口">MessageService</a></dt> <dd> <div class="block">发送信息,发送者就是当前登陆的用户</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/MessageService.html#sendMessage-int-int-java.lang.String-">sendMessage(int, int, String)</a></span> - 接口 中的方法com.xnx3.j2ee.service.<a href="../com/xnx3/j2ee/service/MessageService.html" title="com.xnx3.j2ee.service中的接口">MessageService</a></dt> <dd> <div class="block">发送信息</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/controller/LoginController_.html#sendPhoneLoginCode-javax.servlet.http.HttpServletRequest-">sendPhoneLoginCode(HttpServletRequest)</a></span> - 类 中的方法com.xnx3.j2ee.controller.<a href="../com/xnx3/j2ee/controller/LoginController_.html" title="com.xnx3.j2ee.controller中的类">LoginController_</a></dt> <dd> <div class="block">发送手机号登录的验证码</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/SmsLogServiceImpl.html#sendPhoneLoginCode-javax.servlet.http.HttpServletRequest-">sendPhoneLoginCode(HttpServletRequest)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/SmsLogServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">SmsLogServiceImpl</a></dt> <dd> <div class="block">发送手机号登录的验证码</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/SmsLogService.html#sendPhoneLoginCode-javax.servlet.http.HttpServletRequest-">sendPhoneLoginCode(HttpServletRequest)</a></span> - 接口 中的方法com.xnx3.j2ee.service.<a href="../com/xnx3/j2ee/service/SmsLogService.html" title="com.xnx3.j2ee.service中的接口">SmsLogService</a></dt> <dd> <div class="block">发送手机号登录的验证码</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/SmsLogServiceImpl.html#sendSms-javax.servlet.http.HttpServletRequest-java.lang.String-java.lang.String-java.lang.Short-">sendSms(HttpServletRequest, String, String, Short)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/SmsLogServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">SmsLogServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/SmsLogService.html#sendSms-javax.servlet.http.HttpServletRequest-java.lang.String-java.lang.String-java.lang.Short-">sendSms(HttpServletRequest, String, String, Short)</a></span> - 接口 中的方法com.xnx3.j2ee.service.<a href="../com/xnx3/j2ee/service/SmsLogService.html" title="com.xnx3.j2ee.service中的接口">SmsLogService</a></dt> <dd> <div class="block">向指定手机号发送指定内容的验证码,内容里六位动态验证码用${code}表示</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/MessageServiceImpl.html#sendSystemMessage-int-java.lang.String-">sendSystemMessage(int, String)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/MessageServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">MessageServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/MessageService.html#sendSystemMessage-int-java.lang.String-">sendSystemMessage(int, String)</a></span> - 接口 中的方法com.xnx3.j2ee.service.<a href="../com/xnx3/j2ee/service/MessageService.html" title="com.xnx3.j2ee.service中的接口">MessageService</a></dt> <dd> <div class="block">向某人发送一条系统信息(发件人用户id为0)</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Collect.html#setAddtime-java.lang.Integer-">setAddtime(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Collect.html" title="com.xnx3.j2ee.entity中的类">Collect</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/PayLog.html#setAddtime-java.lang.Integer-">setAddtime(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/PayLog.html" title="com.xnx3.j2ee.entity中的类">PayLog</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Post.html#setAddtime-java.lang.Integer-">setAddtime(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Post.html" title="com.xnx3.j2ee.entity中的类">Post</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/PostComment.html#setAddtime-java.lang.Integer-">setAddtime(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/PostComment.html" title="com.xnx3.j2ee.entity中的类">PostComment</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/SmsLog.html#setAddtime-java.lang.Integer-">setAddtime(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/SmsLog.html" title="com.xnx3.j2ee.entity中的类">SmsLog</a></dt> <dd> <div class="block">添加时间</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/shiro/ActiveUser.html#setAllowUploadForUEditor-boolean-">setAllowUploadForUEditor(boolean)</a></span> - 类 中的方法com.xnx3.j2ee.shiro.<a href="../com/xnx3/j2ee/shiro/ActiveUser.html" title="com.xnx3.j2ee.shiro中的类">ActiveUser</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/User.html#setAuthority-java.lang.String-">setAuthority(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/User.html" title="com.xnx3.j2ee.entity中的类">User</a></dt> <dd> <div class="block">用户权限,主要纪录表再user_role表,一个用户可以有多个权限。</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/vo/BaseVO.html#setBaseVOForSuper-com.xnx3.BaseVO-">setBaseVOForSuper(BaseVO)</a></span> - 类 中的方法com.xnx3.j2ee.vo.<a href="../com/xnx3/j2ee/vo/BaseVO.html" title="com.xnx3.j2ee.vo中的类">BaseVO</a></dt> <dd> <div class="block">将 <code>BaseVO</code> 转为 <a href="../com/xnx3/j2ee/vo/BaseVO.html" title="com.xnx3.j2ee.vo中的类"><code>BaseVO</code></a></div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/PayLog.html#setChannel-java.lang.String-">setChannel(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/PayLog.html" title="com.xnx3.j2ee.entity中的类">PayLog</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Area.html#setCity-java.lang.String-">setCity(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Area.html" title="com.xnx3.j2ee.entity中的类">Area</a></dt> <dd> <div class="block">市</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Post.html#setClassid-java.lang.Integer-">setClassid(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Post.html" title="com.xnx3.j2ee.entity中的类">Post</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/SmsLog.html#setCode-java.lang.String-">setCode(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/SmsLog.html" title="com.xnx3.j2ee.entity中的类">SmsLog</a></dt> <dd> <div class="block">发送的验证码,6位数字</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/vo/PostVO.html#setCommentCount-int-">setCommentCount(int)</a></span> - 类 中的方法com.xnx3.j2ee.vo.<a href="../com/xnx3/j2ee/vo/PostVO.html" title="com.xnx3.j2ee.vo中的类">PostVO</a></dt> <dd> <div class="block">回帖评论总数</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/MessageData.html#setContent-java.lang.String-">setContent(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/MessageData.html" title="com.xnx3.j2ee.entity中的类">MessageData</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/vo/MessageVO.html#setContent-java.lang.String-">setContent(String)</a></span> - 类 中的方法com.xnx3.j2ee.vo.<a href="../com/xnx3/j2ee/vo/MessageVO.html" title="com.xnx3.j2ee.vo中的类">MessageVO</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/User.html#setCurrency-java.lang.Integer-">setCurrency(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/User.html" title="com.xnx3.j2ee.entity中的类">User</a></dt> <dd> <div class="block">资金,可以是积分、金币、等等站内虚拟货币。</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/func/Language.html#setCurrentLanguagePackageName-java.lang.String-">setCurrentLanguagePackageName(String)</a></span> - 类 中的静态方法com.xnx3.j2ee.func.<a href="../com/xnx3/j2ee/func/Language.html" title="com.xnx3.j2ee.func中的类">Language</a></dt> <dd> <div class="block">设置某个用户当前使用哪种语言</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/vo/LogLineGraphVO.html#setDataArray-net.sf.json.JSONArray-">setDataArray(JSONArray)</a></span> - 类 中的方法com.xnx3.j2ee.vo.<a href="../com/xnx3/j2ee/vo/LogLineGraphVO.html" title="com.xnx3.j2ee.vo中的类">LogLineGraphVO</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/vo/LogLineGraphVO.html#setDataArray2-net.sf.json.JSONArray-">setDataArray2(JSONArray)</a></span> - 类 中的方法com.xnx3.j2ee.vo.<a href="../com/xnx3/j2ee/vo/LogLineGraphVO.html" title="com.xnx3.j2ee.vo中的类">LogLineGraphVO</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Permission.html#setDescription-java.lang.String-">setDescription(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Permission.html" title="com.xnx3.j2ee.entity中的类">Permission</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Role.html#setDescription-java.lang.String-">setDescription(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Role.html" title="com.xnx3.j2ee.entity中的类">Role</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/System.html#setDescription-java.lang.String-">setDescription(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/System.html" title="com.xnx3.j2ee.entity中的类">System</a></dt> <dd> <div class="block">说明描述,给后台操作人员看的</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Area.html#setDistrict-java.lang.Integer-">setDistrict(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Area.html" title="com.xnx3.j2ee.entity中的类">Area</a></dt> <dd> <div class="block">区</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/User.html#setEmail-java.lang.String-">setEmail(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/User.html" title="com.xnx3.j2ee.entity中的类">User</a></dt> <dd> <div class="block">邮箱</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/vo/UploadFileVO.html#setFileName-java.lang.String-">setFileName(String)</a></span> - 类 中的方法com.xnx3.j2ee.vo.<a href="../com/xnx3/j2ee/vo/UploadFileVO.html" title="com.xnx3.j2ee.vo中的类">UploadFileVO</a></dt> <dd> <div class="block">上传成功后的文件名,如 "xnx3.jar"</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/User.html#setFreezemoney-float-">setFreezemoney(float)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/User.html" title="com.xnx3.j2ee.entity中的类">User</a></dt> <dd> <div class="block">账户冻结余额,金钱,RMB,单位:元</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/User.html#setHead-java.lang.String-">setHead(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/User.html" title="com.xnx3.j2ee.entity中的类">User</a></dt> <dd> <div class="block">头像,图片文件名,如 29.jpg</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Area.html#setId-java.lang.Integer-">setId(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Area.html" title="com.xnx3.j2ee.entity中的类">Area</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Collect.html#setId-java.lang.Integer-">setId(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Collect.html" title="com.xnx3.j2ee.entity中的类">Collect</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Friend.html#setId-java.lang.Integer-">setId(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Friend.html" title="com.xnx3.j2ee.entity中的类">Friend</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/FriendLog.html#setId-java.lang.Integer-">setId(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/FriendLog.html" title="com.xnx3.j2ee.entity中的类">FriendLog</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Message.html#setId-java.lang.Integer-">setId(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Message.html" title="com.xnx3.j2ee.entity中的类">Message</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/MessageData.html#setId-java.lang.Integer-">setId(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/MessageData.html" title="com.xnx3.j2ee.entity中的类">MessageData</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/PayLog.html#setId-java.lang.Integer-">setId(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/PayLog.html" title="com.xnx3.j2ee.entity中的类">PayLog</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Permission.html#setId-java.lang.Integer-">setId(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Permission.html" title="com.xnx3.j2ee.entity中的类">Permission</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Post.html#setId-java.lang.Integer-">setId(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Post.html" title="com.xnx3.j2ee.entity中的类">Post</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/PostClass.html#setId-java.lang.Integer-">setId(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/PostClass.html" title="com.xnx3.j2ee.entity中的类">PostClass</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/PostComment.html#setId-java.lang.Integer-">setId(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/PostComment.html" title="com.xnx3.j2ee.entity中的类">PostComment</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Role.html#setId-java.lang.Integer-">setId(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Role.html" title="com.xnx3.j2ee.entity中的类">Role</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/RolePermission.html#setId-java.lang.Integer-">setId(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/RolePermission.html" title="com.xnx3.j2ee.entity中的类">RolePermission</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/SmsLog.html#setId-java.lang.Integer-">setId(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/SmsLog.html" title="com.xnx3.j2ee.entity中的类">SmsLog</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/System.html#setId-java.lang.Integer-">setId(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/System.html" title="com.xnx3.j2ee.entity中的类">System</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/User.html#setId-java.lang.Integer-">setId(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/User.html" title="com.xnx3.j2ee.entity中的类">User</a></dt> <dd> <div class="block">用户id</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/UserRole.html#setId-java.lang.Integer-">setId(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/UserRole.html" title="com.xnx3.j2ee.entity中的类">UserRole</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/User.html#setIdcardauth-java.lang.Short-">setIdcardauth(Short)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/User.html" title="com.xnx3.j2ee.entity中的类">User</a></dt> <dd> <div class="block">是否已经经过真实身份认证了(身份证、银行卡绑定等)。</div> </dd> <dt><span class="memberNameLink"><a href="../com/baidu/ueditor/define/BaseState.html#setInfo-java.lang.String-">setInfo(String)</a></span> - 类 中的方法com.baidu.ueditor.define.<a href="../com/baidu/ueditor/define/BaseState.html" title="com.baidu.ueditor.define中的类">BaseState</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/baidu/ueditor/define/BaseState.html#setInfo-int-">setInfo(int)</a></span> - 类 中的方法com.baidu.ueditor.define.<a href="../com/baidu/ueditor/define/BaseState.html" title="com.baidu.ueditor.define中的类">BaseState</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Post.html#setInfo-java.lang.String-">setInfo(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Post.html" title="com.xnx3.j2ee.entity中的类">Post</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/FriendLog.html#setIp-java.lang.String-">setIp(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/FriendLog.html" title="com.xnx3.j2ee.entity中的类">FriendLog</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/SmsLog.html#setIp-java.lang.String-">setIp(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/SmsLog.html" title="com.xnx3.j2ee.entity中的类">SmsLog</a></dt> <dd> <div class="block">触发发送操作的客户ip地址</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Message.html#setIsdelete-java.lang.Short-">setIsdelete(Short)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Message.html" title="com.xnx3.j2ee.entity中的类">Message</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Post.html#setIsdelete-java.lang.Short-">setIsdelete(Short)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Post.html" title="com.xnx3.j2ee.entity中的类">Post</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/PostClass.html#setIsdelete-java.lang.Short-">setIsdelete(Short)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/PostClass.html" title="com.xnx3.j2ee.entity中的类">PostClass</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/PostComment.html#setIsdelete-java.lang.Short-">setIsdelete(Short)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/PostComment.html" title="com.xnx3.j2ee.entity中的类">PostComment</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/User.html#setIsfreeze-java.lang.Short-">setIsfreeze(Short)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/User.html" title="com.xnx3.j2ee.entity中的类">User</a></dt> <dd> <div class="block">是否已冻结 <a href="../com/xnx3/j2ee/entity/BaseEntity.html#ISFREEZE_NORMAL"><code>BaseEntity.ISFREEZE_NORMAL</code></a>:正常 <a href="../com/xnx3/j2ee/entity/BaseEntity.html#ISFREEZE_FREEZE"><code>BaseEntity.ISFREEZE_FREEZE</code></a>:已冻结(拉入黑名单) </div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/shiro/ActiveUser.html#setLanguagePackageName-java.lang.String-">setLanguagePackageName(String)</a></span> - 类 中的方法com.xnx3.j2ee.shiro.<a href="../com/xnx3/j2ee/shiro/ActiveUser.html" title="com.xnx3.j2ee.shiro中的类">ActiveUser</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/User.html#setLastip-java.lang.String-">setLastip(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/User.html" title="com.xnx3.j2ee.entity中的类">User</a></dt> <dd> <div class="block">最后一次登陆的ip</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/System.html#setLasttime-java.lang.Integer-">setLasttime(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/System.html" title="com.xnx3.j2ee.entity中的类">System</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/User.html#setLasttime-java.lang.Integer-">setLasttime(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/User.html" title="com.xnx3.j2ee.entity中的类">User</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Area.html#setLatitude-float-">setLatitude(float)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Area.html" title="com.xnx3.j2ee.entity中的类">Area</a></dt> <dd> <div class="block">玮度,如 39.63</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/bean/PermissionTree.html#setList-java.util.List-">setList(List&lt;PermissionMark&gt;)</a></span> - 类 中的方法com.xnx3.j2ee.bean.<a href="../com/xnx3/j2ee/bean/PermissionTree.html" title="com.xnx3.j2ee.bean中的类">PermissionTree</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/vo/FriendListVO.html#setList-java.util.List-">setList(List&lt;Friend&gt;)</a></span> - 类 中的方法com.xnx3.j2ee.vo.<a href="../com/xnx3/j2ee/vo/FriendListVO.html" title="com.xnx3.j2ee.vo中的类">FriendListVO</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Area.html#setLongitude-float-">setLongitude(float)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Area.html" title="com.xnx3.j2ee.entity中的类">Area</a></dt> <dd> <div class="block">经度,如 118.22</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/vo/MessageVO.html#setMessage-com.xnx3.j2ee.entity.Message-">setMessage(Message)</a></span> - 类 中的方法com.xnx3.j2ee.vo.<a href="../com/xnx3/j2ee/vo/MessageVO.html" title="com.xnx3.j2ee.vo中的类">MessageVO</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/MessageServiceImpl.html#setMessageDao-com.xnx3.j2ee.dao.MessageDAO-">setMessageDao(MessageDAO)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/MessageServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">MessageServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/PayLog.html#setMoney-java.lang.Float-">setMoney(Float)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/PayLog.html" title="com.xnx3.j2ee.entity中的类">PayLog</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/User.html#setMoney-float-">setMoney(float)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/User.html" title="com.xnx3.j2ee.entity中的类">User</a></dt> <dd> <div class="block">账户可用余额,金钱,RMB,单位:元</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Permission.html#setName-java.lang.String-">setName(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Permission.html" title="com.xnx3.j2ee.entity中的类">Permission</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/PostClass.html#setName-java.lang.String-">setName(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/PostClass.html" title="com.xnx3.j2ee.entity中的类">PostClass</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Role.html#setName-java.lang.String-">setName(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Role.html" title="com.xnx3.j2ee.entity中的类">Role</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/System.html#setName-java.lang.String-">setName(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/System.html" title="com.xnx3.j2ee.entity中的类">System</a></dt> <dd> <div class="block">参数名,程序内调用 <a href="../com/xnx3/j2ee/Global.html#get-java.lang.String-"><code>Global.get(String)</code></a></div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/shiro/CustomRealm.html#setName-java.lang.String-">setName(String)</a></span> - 类 中的方法com.xnx3.j2ee.shiro.<a href="../com/xnx3/j2ee/shiro/CustomRealm.html" title="com.xnx3.j2ee.shiro中的类">CustomRealm</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/vo/LogLineGraphVO.html#setNameArray-net.sf.json.JSONArray-">setNameArray(JSONArray)</a></span> - 类 中的方法com.xnx3.j2ee.vo.<a href="../com/xnx3/j2ee/vo/LogLineGraphVO.html" title="com.xnx3.j2ee.vo中的类">LogLineGraphVO</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/func/AttachmentFile.html#setNetUrl-java.lang.String-">setNetUrl(String)</a></span> - 类 中的静态方法com.xnx3.j2ee.func.<a href="../com/xnx3/j2ee/func/AttachmentFile.html" title="com.xnx3.j2ee.func中的类">AttachmentFile</a></dt> <dd> <div class="block">设置当前的netUrl</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/User.html#setNickname-java.lang.String-">setNickname(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/User.html" title="com.xnx3.j2ee.entity中的类">User</a></dt> <dd> <div class="block">昵称</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/shiro/ActiveUser.html#setObj-java.lang.Object-">setObj(Object)</a></span> - 类 中的方法com.xnx3.j2ee.shiro.<a href="../com/xnx3/j2ee/shiro/ActiveUser.html" title="com.xnx3.j2ee.shiro中的类">ActiveUser</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/PayLog.html#setOrderno-java.lang.String-">setOrderno(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/PayLog.html" title="com.xnx3.j2ee.entity中的类">PayLog</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Friend.html#setOther-java.lang.Integer-">setOther(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Friend.html" title="com.xnx3.j2ee.entity中的类">Friend</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/FriendLog.html#setOther-java.lang.Integer-">setOther(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/FriendLog.html" title="com.xnx3.j2ee.entity中的类">FriendLog</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Collect.html#setOthersid-java.lang.Integer-">setOthersid(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Collect.html" title="com.xnx3.j2ee.entity中的类">Collect</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Permission.html#setParentId-java.lang.Integer-">setParentId(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Permission.html" title="com.xnx3.j2ee.entity中的类">Permission</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/User.html#setPassword-java.lang.String-">setPassword(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/User.html" title="com.xnx3.j2ee.entity中的类">User</a></dt> <dd> <div class="block">密码,+salt加密后的密码</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/vo/UploadFileVO.html#setPath-java.lang.String-">setPath(String)</a></span> - 类 中的方法com.xnx3.j2ee.vo.<a href="../com/xnx3/j2ee/vo/UploadFileVO.html" title="com.xnx3.j2ee.vo中的类">UploadFileVO</a></dt> <dd> <div class="block">上传成功后的路径,如 "/jar/file/xnx3.jar"</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Permission.html#setPercode-java.lang.String-">setPercode(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Permission.html" title="com.xnx3.j2ee.entity中的类">Permission</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/bean/PermissionMark.html#setPermission-com.xnx3.j2ee.entity.Permission-">setPermission(Permission)</a></span> - 类 中的方法com.xnx3.j2ee.bean.<a href="../com/xnx3/j2ee/bean/PermissionMark.html" title="com.xnx3.j2ee.bean中的类">PermissionMark</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/RolePermission.html#setPermissionid-java.lang.Integer-">setPermissionid(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/RolePermission.html" title="com.xnx3.j2ee.entity中的类">RolePermission</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/bean/PermissionTree.html#setPermissionMark-com.xnx3.j2ee.bean.PermissionMark-">setPermissionMark(PermissionMark)</a></span> - 类 中的方法com.xnx3.j2ee.bean.<a href="../com/xnx3/j2ee/bean/PermissionTree.html" title="com.xnx3.j2ee.bean中的类">PermissionTree</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/shiro/ActiveUser.html#setPermissions-java.util.List-">setPermissions(List&lt;Permission&gt;)</a></span> - 类 中的方法com.xnx3.j2ee.shiro.<a href="../com/xnx3/j2ee/shiro/ActiveUser.html" title="com.xnx3.j2ee.shiro中的类">ActiveUser</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/shiro/ActiveUser.html#setPermissionTreeList-java.util.List-">setPermissionTreeList(List&lt;PermissionTree&gt;)</a></span> - 类 中的方法com.xnx3.j2ee.shiro.<a href="../com/xnx3/j2ee/shiro/ActiveUser.html" title="com.xnx3.j2ee.shiro中的类">ActiveUser</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/SmsLog.html#setPhone-java.lang.String-">setPhone(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/SmsLog.html" title="com.xnx3.j2ee.entity中的类">SmsLog</a></dt> <dd> <div class="block">发送到的手机号</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/User.html#setPhone-java.lang.String-">setPhone(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/User.html" title="com.xnx3.j2ee.entity中的类">User</a></dt> <dd> <div class="block">手机号</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/vo/PostVO.html#setPost-com.xnx3.j2ee.entity.Post-">setPost(Post)</a></span> - 类 中的方法com.xnx3.j2ee.vo.<a href="../com/xnx3/j2ee/vo/PostVO.html" title="com.xnx3.j2ee.vo中的类">PostVO</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/vo/PostVO.html#setPostClass-com.xnx3.j2ee.entity.PostClass-">setPostClass(PostClass)</a></span> - 类 中的方法com.xnx3.j2ee.vo.<a href="../com/xnx3/j2ee/vo/PostVO.html" title="com.xnx3.j2ee.vo中的类">PostVO</a></dt> <dd> <div class="block">所属的栏目信息</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/PostComment.html#setPostid-java.lang.Integer-">setPostid(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/PostComment.html" title="com.xnx3.j2ee.entity中的类">PostComment</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/PostData.html#setPostid-java.lang.Integer-">setPostid(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/PostData.html" title="com.xnx3.j2ee.entity中的类">PostData</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Area.html#setProvince-java.lang.String-">setProvince(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Area.html" title="com.xnx3.j2ee.entity中的类">Area</a></dt> <dd> <div class="block">省</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Message.html#setRecipientid-java.lang.Integer-">setRecipientid(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Message.html" title="com.xnx3.j2ee.entity中的类">Message</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/vo/MessageVO.html#setRecipientUser-com.xnx3.j2ee.entity.User-">setRecipientUser(User)</a></span> - 类 中的方法com.xnx3.j2ee.vo.<a href="../com/xnx3/j2ee/vo/MessageVO.html" title="com.xnx3.j2ee.vo中的类">MessageVO</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/User.html#setReferrerid-java.lang.Integer-">setReferrerid(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/User.html" title="com.xnx3.j2ee.entity中的类">User</a></dt> <dd> <div class="block">推荐人的用户id。</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/User.html#setRegip-java.lang.String-">setRegip(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/User.html" title="com.xnx3.j2ee.entity中的类">User</a></dt> <dd> <div class="block">注册ip</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/User.html#setRegtime-java.lang.Integer-">setRegtime(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/User.html" title="com.xnx3.j2ee.entity中的类">User</a></dt> <dd> <div class="block">注册时间,时间戳</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/bean/RoleMark.html#setRole-com.xnx3.j2ee.entity.Role-">setRole(Role)</a></span> - 类 中的方法com.xnx3.j2ee.bean.<a href="../com/xnx3/j2ee/bean/RoleMark.html" title="com.xnx3.j2ee.bean中的类">RoleMark</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/RolePermission.html#setRoleid-java.lang.Integer-">setRoleid(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/RolePermission.html" title="com.xnx3.j2ee.entity中的类">RolePermission</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/UserRole.html#setRoleid-java.lang.Integer-">setRoleid(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/UserRole.html" title="com.xnx3.j2ee.entity中的类">UserRole</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/User.html#setSalt-java.lang.String-">setSalt(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/User.html" title="com.xnx3.j2ee.entity中的类">User</a></dt> <dd> <div class="block">shiro加密使用</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/bean/PermissionMark.html#setSelected-boolean-">setSelected(boolean)</a></span> - 类 中的方法com.xnx3.j2ee.bean.<a href="../com/xnx3/j2ee/bean/PermissionMark.html" title="com.xnx3.j2ee.bean中的类">PermissionMark</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/bean/RoleMark.html#setSelected-boolean-">setSelected(boolean)</a></span> - 类 中的方法com.xnx3.j2ee.bean.<a href="../com/xnx3/j2ee/bean/RoleMark.html" title="com.xnx3.j2ee.bean中的类">RoleMark</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Friend.html#setSelf-java.lang.Integer-">setSelf(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Friend.html" title="com.xnx3.j2ee.entity中的类">Friend</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/FriendLog.html#setSelf-java.lang.Integer-">setSelf(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/FriendLog.html" title="com.xnx3.j2ee.entity中的类">FriendLog</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Message.html#setSenderid-java.lang.Integer-">setSenderid(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Message.html" title="com.xnx3.j2ee.entity中的类">Message</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/vo/MessageVO.html#setSenderUser-com.xnx3.j2ee.entity.User-">setSenderUser(User)</a></span> - 类 中的方法com.xnx3.j2ee.vo.<a href="../com/xnx3/j2ee/vo/MessageVO.html" title="com.xnx3.j2ee.vo中的类">MessageVO</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/dao/MessageDAO.html#setSessionFactory-org.hibernate.SessionFactory-">setSessionFactory(SessionFactory)</a></span> - 类 中的方法com.xnx3.j2ee.dao.<a href="../com/xnx3/j2ee/dao/MessageDAO.html" title="com.xnx3.j2ee.dao中的类">MessageDAO</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/dao/PermissionDAO.html#setSessionFactory-org.hibernate.SessionFactory-">setSessionFactory(SessionFactory)</a></span> - 类 中的方法com.xnx3.j2ee.dao.<a href="../com/xnx3/j2ee/dao/PermissionDAO.html" title="com.xnx3.j2ee.dao中的类">PermissionDAO</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/dao/SqlDAO.html#setSessionFactory-org.hibernate.SessionFactory-">setSessionFactory(SessionFactory)</a></span> - 类 中的方法com.xnx3.j2ee.dao.<a href="../com/xnx3/j2ee/dao/SqlDAO.html" title="com.xnx3.j2ee.dao中的类">SqlDAO</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/User.html#setSex-java.lang.String-">setSex(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/User.html" title="com.xnx3.j2ee.entity中的类">User</a></dt> <dd> <div class="block">性别,三个值:男、女、未知</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/User.html#setSign-java.lang.String-">setSign(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/User.html" title="com.xnx3.j2ee.entity中的类">User</a></dt> <dd> <div class="block">用户签名,限制50个汉字或100个英文字符</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/ApiServiceImpl.html#setSqlDAO-com.xnx3.j2ee.dao.SqlDAO-">setSqlDAO(SqlDAO)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/ApiServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">ApiServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/CollectServiceImpl.html#setSqlDAO-com.xnx3.j2ee.dao.SqlDAO-">setSqlDAO(SqlDAO)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/CollectServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">CollectServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/MessageServiceImpl.html#setSqlDAO-com.xnx3.j2ee.dao.SqlDAO-">setSqlDAO(SqlDAO)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/MessageServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">MessageServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/PostServiceImpl.html#setSqlDAO-com.xnx3.j2ee.dao.SqlDAO-">setSqlDAO(SqlDAO)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/PostServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">PostServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/RoleServiceImpl.html#setSqlDAO-com.xnx3.j2ee.dao.SqlDAO-">setSqlDAO(SqlDAO)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/RoleServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">RoleServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/SmsLogServiceImpl.html#setSqlDAO-com.xnx3.j2ee.dao.SqlDAO-">setSqlDAO(SqlDAO)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/SmsLogServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">SmsLogServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/SqlServiceImpl.html#setSqlDAO-com.xnx3.j2ee.dao.SqlDAO-">setSqlDAO(SqlDAO)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/SqlServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">SqlServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/SystemServiceImpl.html#setSqlDAO-com.xnx3.j2ee.dao.SqlDAO-">setSqlDAO(SqlDAO)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/SystemServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">SystemServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/UserServiceImpl.html#setSqlDAO-com.xnx3.j2ee.dao.SqlDAO-">setSqlDAO(SqlDAO)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/UserServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">UserServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/baidu/ueditor/define/BaseState.html#setState-boolean-">setState(boolean)</a></span> - 类 中的方法com.baidu.ueditor.define.<a href="../com/baidu/ueditor/define/BaseState.html" title="com.baidu.ueditor.define中的类">BaseState</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/FriendLog.html#setState-java.lang.Short-">setState(Short)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/FriendLog.html" title="com.xnx3.j2ee.entity中的类">FriendLog</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Message.html#setState-java.lang.Short-">setState(Short)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Message.html" title="com.xnx3.j2ee.entity中的类">Message</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Post.html#setState-java.lang.Short-">setState(Short)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Post.html" title="com.xnx3.j2ee.entity中的类">Post</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/PostComment.html#setText-java.lang.String-">setText(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/PostComment.html" title="com.xnx3.j2ee.entity中的类">PostComment</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/PostData.html#setText-java.lang.String-">setText(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/PostData.html" title="com.xnx3.j2ee.entity中的类">PostData</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/vo/PostVO.html#setText-java.lang.String-">setText(String)</a></span> - 类 中的方法com.xnx3.j2ee.vo.<a href="../com/xnx3/j2ee/vo/PostVO.html" title="com.xnx3.j2ee.vo中的类">PostVO</a></dt> <dd> <div class="block">帖子的内容</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/FriendLog.html#setTime-java.lang.Integer-">setTime(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/FriendLog.html" title="com.xnx3.j2ee.entity中的类">FriendLog</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Message.html#setTime-java.lang.Integer-">setTime(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Message.html" title="com.xnx3.j2ee.entity中的类">Message</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Post.html#setTitle-java.lang.String-">setTitle(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Post.html" title="com.xnx3.j2ee.entity中的类">Post</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/SmsLog.html#setType-java.lang.Short-">setType(Short)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/SmsLog.html" title="com.xnx3.j2ee.entity中的类">SmsLog</a></dt> <dd> <div class="block">验证码所属功能类型, 1:登录 ; 2:找回密码</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/shiro/ShiroFunc.html#setUEditorAllowUpload-boolean-">setUEditorAllowUpload(boolean)</a></span> - 类 中的静态方法com.xnx3.j2ee.shiro.<a href="../com/xnx3/j2ee/shiro/ShiroFunc.html" title="com.xnx3.j2ee.shiro中的类">ShiroFunc</a></dt> <dd> <div class="block">设置当前用户是否能使用UEditor编辑器进行图片、文件、视频等上传。</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/shiro/ActiveUser.html#setUeUploadParam1-java.lang.String-">setUeUploadParam1(String)</a></span> - 类 中的方法com.xnx3.j2ee.shiro.<a href="../com/xnx3/j2ee/shiro/ActiveUser.html" title="com.xnx3.j2ee.shiro中的类">ActiveUser</a></dt> <dd> <div class="block">UEditor上传文件相关的路径替换参数,可用{uploadParam1}来调用。</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Permission.html#setUrl-java.lang.String-">setUrl(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Permission.html" title="com.xnx3.j2ee.entity中的类">Permission</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/vo/UploadFileVO.html#setUrl-java.lang.String-">setUrl(String)</a></span> - 类 中的方法com.xnx3.j2ee.vo.<a href="../com/xnx3/j2ee/vo/UploadFileVO.html" title="com.xnx3.j2ee.vo中的类">UploadFileVO</a></dt> <dd> <div class="block">文件上传成功后,外网访问的url</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/SmsLog.html#setUsed-java.lang.Short-">setUsed(Short)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/SmsLog.html" title="com.xnx3.j2ee.entity中的类">SmsLog</a></dt> <dd> <div class="block">是否被使用了 <a href="../com/xnx3/j2ee/entity/SmsLog.html#USED_TRUE"><code>SmsLog.USED_TRUE</code></a>:已经使用了 <a href="../com/xnx3/j2ee/entity/SmsLog.html#USED_FALSE"><code>SmsLog.USED_FALSE</code></a>:未使用 </div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/shiro/ActiveUser.html#setUser-com.xnx3.j2ee.entity.User-">setUser(User)</a></span> - 类 中的方法com.xnx3.j2ee.shiro.<a href="../com/xnx3/j2ee/shiro/ActiveUser.html" title="com.xnx3.j2ee.shiro中的类">ActiveUser</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/vo/PostVO.html#setUser-com.xnx3.j2ee.entity.User-">setUser(User)</a></span> - 类 中的方法com.xnx3.j2ee.vo.<a href="../com/xnx3/j2ee/vo/PostVO.html" title="com.xnx3.j2ee.vo中的类">PostVO</a></dt> <dd> <div class="block">发帖用户</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/vo/UserVO.html#setUser-com.xnx3.j2ee.entity.User-">setUser(User)</a></span> - 类 中的方法com.xnx3.j2ee.vo.<a href="../com/xnx3/j2ee/vo/UserVO.html" title="com.xnx3.j2ee.vo中的类">UserVO</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/controller/BaseController.html#setUserForSession-com.xnx3.j2ee.entity.User-">setUserForSession(User)</a></span> - 类 中的方法com.xnx3.j2ee.controller.<a href="../com/xnx3/j2ee/controller/BaseController.html" title="com.xnx3.j2ee.controller中的类">BaseController</a></dt> <dd> <div class="block">更新登录的用户的用户信息</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Collect.html#setUserid-java.lang.Integer-">setUserid(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Collect.html" title="com.xnx3.j2ee.entity中的类">Collect</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/PayLog.html#setUserid-java.lang.Integer-">setUserid(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/PayLog.html" title="com.xnx3.j2ee.entity中的类">PayLog</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Post.html#setUserid-java.lang.Integer-">setUserid(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Post.html" title="com.xnx3.j2ee.entity中的类">Post</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/PostComment.html#setUserid-java.lang.Integer-">setUserid(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/PostComment.html" title="com.xnx3.j2ee.entity中的类">PostComment</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/SmsLog.html#setUserid-java.lang.Integer-">setUserid(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/SmsLog.html" title="com.xnx3.j2ee.entity中的类">SmsLog</a></dt> <dd> <div class="block">哪个用户使用了此验证码</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/UserRole.html#setUserid-java.lang.Integer-">setUserid(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/UserRole.html" title="com.xnx3.j2ee.entity中的类">UserRole</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/User.html#setUsername-java.lang.String-">setUsername(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/User.html" title="com.xnx3.j2ee.entity中的类">User</a></dt> <dd> <div class="block">用户名</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/System.html#setValue-java.lang.String-">setValue(String)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/System.html" title="com.xnx3.j2ee.entity中的类">System</a></dt> <dd> <div class="block">值</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Post.html#setView-java.lang.Integer-">setView(Integer)</a></span> - 类 中的方法com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Post.html" title="com.xnx3.j2ee.entity中的类">Post</a></dt> <dd>&nbsp;</dd> <dt><a href="../com/xnx3/j2ee/shiro/ShiroFunc.html" title="com.xnx3.j2ee.shiro中的类"><span class="typeNameLink">ShiroFunc</span></a> - <a href="../com/xnx3/j2ee/shiro/package-summary.html">com.xnx3.j2ee.shiro</a>中的类</dt> <dd> <div class="block">shiro权限相关用到的函数</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/shiro/ShiroFunc.html#ShiroFunc--">ShiroFunc()</a></span> - 类 的构造器com.xnx3.j2ee.shiro.<a href="../com/xnx3/j2ee/shiro/ShiroFunc.html" title="com.xnx3.j2ee.shiro中的类">ShiroFunc</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/func/Language.html#show-java.lang.String-">show(String)</a></span> - 类 中的静态方法com.xnx3.j2ee.func.<a href="../com/xnx3/j2ee/func/Language.html" title="com.xnx3.j2ee.func中的类">Language</a></dt> <dd> <div class="block">调用语言包中设置的具体内容显示出来</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/func/Language.html#show-java.lang.String-java.lang.String-">show(String, String)</a></span> - 类 中的静态方法com.xnx3.j2ee.func.<a href="../com/xnx3/j2ee/func/Language.html" title="com.xnx3.j2ee.func中的类">Language</a></dt> <dd> <div class="block">调用语言包中设置的具体内容显示出来</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/func/Captcha.html#showImage-com.xnx3.media.CaptchaUtil-javax.servlet.http.HttpServletRequest-javax.servlet.http.HttpServletResponse-">showImage(CaptchaUtil, HttpServletRequest, HttpServletResponse)</a></span> - 类 中的静态方法com.xnx3.j2ee.func.<a href="../com/xnx3/j2ee/func/Captcha.html" title="com.xnx3.j2ee.func中的类">Captcha</a></dt> <dd> <div class="block">显示图片验证码,直接创建出jpg格式图片</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/func/Captcha.html#showImage-javax.servlet.http.HttpServletRequest-javax.servlet.http.HttpServletResponse-">showImage(HttpServletRequest, HttpServletResponse)</a></span> - 类 中的静态方法com.xnx3.j2ee.func.<a href="../com/xnx3/j2ee/func/Captcha.html" title="com.xnx3.j2ee.func中的类">Captcha</a></dt> <dd> <div class="block">显示图片验证码,直接创建出jpg格式图片</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/func/QRCode.html#showQRCodeForPage-java.lang.String-javax.servlet.http.HttpServletResponse-">showQRCodeForPage(String, HttpServletResponse)</a></span> - 类 中的静态方法com.xnx3.j2ee.func.<a href="../com/xnx3/j2ee/func/QRCode.html" title="com.xnx3.j2ee.func中的类">QRCode</a></dt> <dd> <div class="block">在当前页面上输出二维码。</div> </dd> <dt><a href="../com/xnx3/j2ee/entity/SmsLog.html" title="com.xnx3.j2ee.entity中的类"><span class="typeNameLink">SmsLog</span></a> - <a href="../com/xnx3/j2ee/entity/package-summary.html">com.xnx3.j2ee.entity</a>中的类</dt> <dd> <div class="block">使用此需配置src下的systemConfig.xml文件下的sms节点</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/SmsLog.html#SmsLog--">SmsLog()</a></span> - 类 的构造器com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/SmsLog.html" title="com.xnx3.j2ee.entity中的类">SmsLog</a></dt> <dd> <div class="block">default constructor</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/SmsLog.html#SmsLog-java.lang.Integer-">SmsLog(Integer)</a></span> - 类 的构造器com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/SmsLog.html" title="com.xnx3.j2ee.entity中的类">SmsLog</a></dt> <dd> <div class="block">minimal constructor</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/SmsLog.html#SmsLog-java.lang.Integer-java.lang.String-java.lang.Integer-java.lang.Short-java.lang.Short-java.lang.Integer-">SmsLog(Integer, String, Integer, Short, Short, Integer)</a></span> - 类 的构造器com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/SmsLog.html" title="com.xnx3.j2ee.entity中的类">SmsLog</a></dt> <dd> <div class="block">full constructor</div> </dd> <dt><a href="../com/xnx3/j2ee/generateCache/SmsLog.html" title="com.xnx3.j2ee.generateCache中的类"><span class="typeNameLink">SmsLog</span></a> - <a href="../com/xnx3/j2ee/generateCache/package-summary.html">com.xnx3.j2ee.generateCache</a>中的类</dt> <dd> <div class="block">发送短信验证码的日志相关缓存</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/generateCache/SmsLog.html#SmsLog--">SmsLog()</a></span> - 类 的构造器com.xnx3.j2ee.generateCache.<a href="../com/xnx3/j2ee/generateCache/SmsLog.html" title="com.xnx3.j2ee.generateCache中的类">SmsLog</a></dt> <dd>&nbsp;</dd> <dt><a href="../com/xnx3/j2ee/controller/admin/SmsLogAdminController_.html" title="com.xnx3.j2ee.controller.admin中的类"><span class="typeNameLink">SmsLogAdminController_</span></a> - <a href="../com/xnx3/j2ee/controller/admin/package-summary.html">com.xnx3.j2ee.controller.admin</a>中的类</dt> <dd> <div class="block">手机验证码相关,比如手机登陆时的验证码</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/controller/admin/SmsLogAdminController_.html#SmsLogAdminController_--">SmsLogAdminController_()</a></span> - 类 的构造器com.xnx3.j2ee.controller.admin.<a href="../com/xnx3/j2ee/controller/admin/SmsLogAdminController_.html" title="com.xnx3.j2ee.controller.admin中的类">SmsLogAdminController_</a></dt> <dd>&nbsp;</dd> <dt><a href="../com/xnx3/j2ee/service/SmsLogService.html" title="com.xnx3.j2ee.service中的接口"><span class="typeNameLink">SmsLogService</span></a> - <a href="../com/xnx3/j2ee/service/package-summary.html">com.xnx3.j2ee.service</a>中的接口</dt> <dd>&nbsp;</dd> <dt><a href="../com/xnx3/j2ee/service/impl/SmsLogServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类"><span class="typeNameLink">SmsLogServiceImpl</span></a> - <a href="../com/xnx3/j2ee/service/impl/package-summary.html">com.xnx3.j2ee.service.impl</a>中的类</dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/SmsLogServiceImpl.html#SmsLogServiceImpl--">SmsLogServiceImpl()</a></span> - 类 的构造器com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/SmsLogServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">SmsLogServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><a href="../com/xnx3/j2ee/dao/SqlDAO.html" title="com.xnx3.j2ee.dao中的类"><span class="typeNameLink">SqlDAO</span></a> - <a href="../com/xnx3/j2ee/dao/package-summary.html">com.xnx3.j2ee.dao</a>中的类</dt> <dd> <div class="block">通用的</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/dao/SqlDAO.html#SqlDAO--">SqlDAO()</a></span> - 类 的构造器com.xnx3.j2ee.dao.<a href="../com/xnx3/j2ee/dao/SqlDAO.html" title="com.xnx3.j2ee.dao中的类">SqlDAO</a></dt> <dd>&nbsp;</dd> <dt><a href="../com/xnx3/j2ee/service/SqlService.html" title="com.xnx3.j2ee.service中的接口"><span class="typeNameLink">SqlService</span></a> - <a href="../com/xnx3/j2ee/service/package-summary.html">com.xnx3.j2ee.service</a>中的接口</dt> <dd> <div class="block">公共查询,直接执行SQL</div> </dd> <dt><a href="../com/xnx3/j2ee/service/impl/SqlServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类"><span class="typeNameLink">SqlServiceImpl</span></a> - <a href="../com/xnx3/j2ee/service/impl/package-summary.html">com.xnx3.j2ee.service.impl</a>中的类</dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/SqlServiceImpl.html#SqlServiceImpl--">SqlServiceImpl()</a></span> - 类 的构造器com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/SqlServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">SqlServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><a href="../com/baidu/ueditor/define/State.html" title="com.baidu.ueditor.define中的接口"><span class="typeNameLink">State</span></a> - <a href="../com/baidu/ueditor/define/package-summary.html">com.baidu.ueditor.define</a>中的接口</dt> <dd> <div class="block">处理状态接口</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/dao/MessageDAO.html#STATE">STATE</a></span> - 类 中的静态变量com.xnx3.j2ee.dao.<a href="../com/xnx3/j2ee/dao/MessageDAO.html" title="com.xnx3.j2ee.dao中的类">MessageDAO</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/generateCache/Bbs.html#state--">state()</a></span> - 类 中的方法com.xnx3.j2ee.generateCache.<a href="../com/xnx3/j2ee/generateCache/Bbs.html" title="com.xnx3.j2ee.generateCache中的类">Bbs</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/generateCache/Message.html#state--">state()</a></span> - 类 中的方法com.xnx3.j2ee.generateCache.<a href="../com/xnx3/j2ee/generateCache/Message.html" title="com.xnx3.j2ee.generateCache中的类">Message</a></dt> <dd> <div class="block">message.state 值-描述 缓存</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Post.html#STATE_AUDITING">STATE_AUDITING</a></span> - 类 中的静态变量com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Post.html" title="com.xnx3.j2ee.entity中的类">Post</a></dt> <dd> <div class="block">审核中</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Post.html#STATE_INCONGRUENT">STATE_INCONGRUENT</a></span> - 类 中的静态变量com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Post.html" title="com.xnx3.j2ee.entity中的类">Post</a></dt> <dd> <div class="block">审核完毕不符合要求</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Post.html#STATE_LOCK">STATE_LOCK</a></span> - 类 中的静态变量com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Post.html" title="com.xnx3.j2ee.entity中的类">Post</a></dt> <dd> <div class="block">锁定冻结中</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/Post.html#STATE_NORMAL">STATE_NORMAL</a></span> - 类 中的静态变量com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/Post.html" title="com.xnx3.j2ee.entity中的类">Post</a></dt> <dd> <div class="block">状态:正常</div> </dd> <dt><a href="../com/baidu/ueditor/upload/StorageManager.html" title="com.baidu.ueditor.upload中的类"><span class="typeNameLink">StorageManager</span></a> - <a href="../com/baidu/ueditor/upload/package-summary.html">com.baidu.ueditor.upload</a>中的类</dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/baidu/ueditor/upload/StorageManager.html#StorageManager--">StorageManager()</a></span> - 类 的构造器com.baidu.ueditor.upload.<a href="../com/baidu/ueditor/upload/StorageManager.html" title="com.baidu.ueditor.upload中的类">StorageManager</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/dao/SqlDAO.html#subtractOne-java.lang.String-java.lang.String-java.lang.String-">subtractOne(String, String, String)</a></span> - 类 中的方法com.xnx3.j2ee.dao.<a href="../com/xnx3/j2ee/dao/SqlDAO.html" title="com.xnx3.j2ee.dao中的类">SqlDAO</a></dt> <dd> <div class="block">数据表的某项数值-1</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/SqlServiceImpl.html#subtractOne-java.lang.String-java.lang.String-java.lang.String-">subtractOne(String, String, String)</a></span> - 类 中的方法com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/SqlServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">SqlServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/SqlService.html#subtractOne-java.lang.String-java.lang.String-java.lang.String-">subtractOne(String, String, String)</a></span> - 接口 中的方法com.xnx3.j2ee.service.<a href="../com/xnx3/j2ee/service/SqlService.html" title="com.xnx3.j2ee.service中的接口">SqlService</a></dt> <dd> <div class="block">数据表的某项数值-1</div> </dd> <dt><span class="memberNameLink"><a href="../com/baidu/ueditor/define/AppInfo.html#SUCCESS">SUCCESS</a></span> - 类 中的静态变量com.baidu.ueditor.define.<a href="../com/baidu/ueditor/define/AppInfo.html" title="com.baidu.ueditor.define中的类">AppInfo</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/controller/BaseController.html#success-org.springframework.ui.Model-java.lang.String-java.lang.String-">success(Model, String, String)</a></span> - 类 中的方法com.xnx3.j2ee.controller.<a href="../com/xnx3/j2ee/controller/BaseController.html" title="com.xnx3.j2ee.controller中的类">BaseController</a></dt> <dd> <div class="block">成功提示中转页面</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/controller/BaseController.html#success-org.springframework.ui.Model-java.lang.String-">success(Model, String)</a></span> - 类 中的方法com.xnx3.j2ee.controller.<a href="../com/xnx3/j2ee/controller/BaseController.html" title="com.xnx3.j2ee.controller中的类">BaseController</a></dt> <dd> <div class="block">成功提示中转页面</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/controller/BaseController.html#success--">success()</a></span> - 类 中的方法com.xnx3.j2ee.controller.<a href="../com/xnx3/j2ee/controller/BaseController.html" title="com.xnx3.j2ee.controller中的类">BaseController</a></dt> <dd> <div class="block">成功提示,返回JSON</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/controller/BaseController.html#success-java.lang.String-">success(String)</a></span> - 类 中的方法com.xnx3.j2ee.controller.<a href="../com/xnx3/j2ee/controller/BaseController.html" title="com.xnx3.j2ee.controller中的类">BaseController</a></dt> <dd> <div class="block">成功提示,返回JSON</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/vo/BaseVO.html#success--">success()</a></span> - 类 中的静态方法com.xnx3.j2ee.vo.<a href="../com/xnx3/j2ee/vo/BaseVO.html" title="com.xnx3.j2ee.vo中的类">BaseVO</a></dt> <dd> <div class="block">返回失败成功的 <a href="../com/xnx3/j2ee/vo/BaseVO.html" title="com.xnx3.j2ee.vo中的类"><code>BaseVO</code></a></div> </dd> <dt><a href="../com/qikemi/packages/baidu/ueditor/upload/SynUploader.html" title="com.qikemi.packages.baidu.ueditor.upload中的类"><span class="typeNameLink">SynUploader</span></a> - <a href="../com/qikemi/packages/baidu/ueditor/upload/package-summary.html">com.qikemi.packages.baidu.ueditor.upload</a>中的类</dt> <dd> <div class="block">同步上传文件到阿里云OSS<br></div> </dd> <dt><span class="memberNameLink"><a href="../com/qikemi/packages/baidu/ueditor/upload/SynUploader.html#SynUploader--">SynUploader()</a></span> - 类 的构造器com.qikemi.packages.baidu.ueditor.upload.<a href="../com/qikemi/packages/baidu/ueditor/upload/SynUploader.html" title="com.qikemi.packages.baidu.ueditor.upload中的类">SynUploader</a></dt> <dd>&nbsp;</dd> <dt><a href="../com/xnx3/j2ee/entity/System.html" title="com.xnx3.j2ee.entity中的类"><span class="typeNameLink">System</span></a> - <a href="../com/xnx3/j2ee/entity/package-summary.html">com.xnx3.j2ee.entity</a>中的类</dt> <dd> <div class="block">Friend entity.</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/entity/System.html#System--">System()</a></span> - 类 的构造器com.xnx3.j2ee.entity.<a href="../com/xnx3/j2ee/entity/System.html" title="com.xnx3.j2ee.entity中的类">System</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/Global.html#system">system</a></span> - 类 中的静态变量com.xnx3.j2ee.<a href="../com/xnx3/j2ee/Global.html" title="com.xnx3.j2ee中的类">Global</a></dt> <dd> <div class="block">system表的参数,name-value</div> </dd> <dt><a href="../com/xnx3/j2ee/controller/admin/SystemAdminController_.html" title="com.xnx3.j2ee.controller.admin中的类"><span class="typeNameLink">SystemAdminController_</span></a> - <a href="../com/xnx3/j2ee/controller/admin/package-summary.html">com.xnx3.j2ee.controller.admin</a>中的类</dt> <dd> <div class="block">系统管理</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/controller/admin/SystemAdminController_.html#SystemAdminController_--">SystemAdminController_()</a></span> - 类 的构造器com.xnx3.j2ee.controller.admin.<a href="../com/xnx3/j2ee/controller/admin/SystemAdminController_.html" title="com.xnx3.j2ee.controller.admin中的类">SystemAdminController_</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/Global.html#systemForInteger">systemForInteger</a></span> - 类 中的静态变量com.xnx3.j2ee.<a href="../com/xnx3/j2ee/Global.html" title="com.xnx3.j2ee中的类">Global</a></dt> <dd> <div class="block">同上system, 只不过这里的value是Integer 取这里的数据时,会先判断这个map中是否有数据 若有,直接取出 若没有,再找上面的system的map中是否有这个值 若有,则将其转换位int,并缓存到这个map里,下次再取这个值的时候就直接从这里就能取 若没有,返回 null (不返回0,因为如果返回null,开发程序的时候就会报错,就能直接定位到问题所在) </div> </dd> <dt><a href="../com/xnx3/j2ee/system/SystemInterceptor.html" title="com.xnx3.j2ee.system中的类"><span class="typeNameLink">SystemInterceptor</span></a> - <a href="../com/xnx3/j2ee/system/package-summary.html">com.xnx3.j2ee.system</a>中的类</dt> <dd> <div class="block">每次请求页面时,都会先通过这个</div> </dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/system/SystemInterceptor.html#SystemInterceptor--">SystemInterceptor()</a></span> - 类 的构造器com.xnx3.j2ee.system.<a href="../com/xnx3/j2ee/system/SystemInterceptor.html" title="com.xnx3.j2ee.system中的类">SystemInterceptor</a></dt> <dd>&nbsp;</dd> <dt><a href="../com/xnx3/j2ee/service/SystemService.html" title="com.xnx3.j2ee.service中的接口"><span class="typeNameLink">SystemService</span></a> - <a href="../com/xnx3/j2ee/service/package-summary.html">com.xnx3.j2ee.service</a>中的接口</dt> <dd> <div class="block">角色、权限相关</div> </dd> <dt><a href="../com/xnx3/j2ee/service/impl/SystemServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类"><span class="typeNameLink">SystemServiceImpl</span></a> - <a href="../com/xnx3/j2ee/service/impl/package-summary.html">com.xnx3.j2ee.service.impl</a>中的类</dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/xnx3/j2ee/service/impl/SystemServiceImpl.html#SystemServiceImpl--">SystemServiceImpl()</a></span> - 类 的构造器com.xnx3.j2ee.service.impl.<a href="../com/xnx3/j2ee/service/impl/SystemServiceImpl.html" title="com.xnx3.j2ee.service.impl中的类">SystemServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><a href="../com/qikemi/packages/utils/SystemUtil.html" title="com.qikemi.packages.utils中的类"><span class="typeNameLink">SystemUtil</span></a> - <a href="../com/qikemi/packages/utils/package-summary.html">com.qikemi.packages.utils</a>中的类</dt> <dd> <div class="block">System Utils</div> </dd> <dt><span class="memberNameLink"><a href="../com/qikemi/packages/utils/SystemUtil.html#SystemUtil--">SystemUtil()</a></span> - 类 的构造器com.qikemi.packages.utils.<a href="../com/qikemi/packages/utils/SystemUtil.html" title="com.qikemi.packages.utils中的类">SystemUtil</a></dt> <dd>&nbsp;</dd> </dl> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">J</a>&nbsp;<a href="index-11.html">K</a>&nbsp;<a href="index-12.html">L</a>&nbsp;<a href="index-13.html">M</a>&nbsp;<a href="index-14.html">N</a>&nbsp;<a href="index-15.html">O</a>&nbsp;<a href="index-16.html">P</a>&nbsp;<a href="index-17.html">Q</a>&nbsp;<a href="index-18.html">R</a>&nbsp;<a href="index-19.html">S</a>&nbsp;<a href="index-20.html">T</a>&nbsp;<a href="index-21.html">U</a>&nbsp;<a href="index-22.html">V</a>&nbsp;<a href="index-23.html">W</a>&nbsp;<a href="index-24.html">X</a>&nbsp;</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="跳过导航链接">跳过导航链接</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="导航"> <li><a href="../overview-summary.html">概览</a></li> <li>程序包</li> <li>类</li> <li>使用</li> <li><a href="../overview-tree.html">树</a></li> <li><a href="../deprecated-list.html">已过时</a></li> <li class="navBarCell1Rev">索引</li> <li><a href="../help-doc.html">帮助</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-18.html">上一个字母</a></li> <li><a href="index-20.html">下一个字母</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-19.html" target="_top">框架</a></li> <li><a href="index-19.html" target="_top">无框架</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">所有类</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
apache-2.0