text:
<!DOCTYPE html>

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

    <title>LeetCode 94 : Binary Tree Inorder Traversal</title>
    <meta name="description" content="Make Today Better Than Yesterday - Code, Food, Photo and some Geek stuff ..." />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="/assets/images/favicon.ico" >

    <link rel="stylesheet" type="text/css" href="/assets/css/screen.css" />
    <link rel="stylesheet" type="text/css"
          href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />
    <link rel="stylesheet" type="text/css" href="/assets/css/syntax.css" />

        <link rel="canonical" href="/" />
    <meta name="referrer" content="origin" />
    <link rel="next" href="/page2/" />

    <meta property="og:site_name" content="Make Today Better Than Yesterday" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="Make Today Better Than Yesterday" />
    <meta property="og:description" content="Code, Food, Photo and some Geek stuff ..." />
    <meta property="og:url" content="/" />
    <meta property="og:image" content="/assets/images/cover1.jpg" />

    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:title" content="Make Today Better Than Yesterday" />
    <meta name="twitter:description" content="Code, Food, Photo and some Geek stuff ..." />
    <meta name="twitter:url" content="/" />
    <meta name="twitter:image:src" content="/assets/images/cover1.jpg" />

    <meta name="generator" content="Jekyll 3.0.0" />
    <link rel="alternate" type="application/rss+xml" title="Make Today Better Than Yesterday" href="/rss.xml" />

Menu

        Close

Home

About

Photo

Food

Geek

Code

Author

    Subscribe

            Menu

LeetCode 94 : Binary Tree Inorder Traversal

            <time class="post-date" datetime="2016-03-11">11 Mar 2016</time>

                on

                       Code

Given a binary tree, return the inorder traversal of its nodes' values.

For example:
Given binary tree

 1
  \
   2
  /
 3

return [1,3,2]

Initial Though

這題如果用 recursive 的話十分簡單,但是如果要用 iterative 作的話就不是這麼容易,最主要的原因是你無法用 call recursive 的順序來決定你 output value 的順序。

Guide

首先你需要有一個 Stack 來倒序記錄,由於 Inorder 是 中->左->右 ,所以必須有一個方式來記錄走到最左之間的所有 Node 。 所以作法就是每次 iteration 先看 Stack Q 的 top, 如果他有左子孫的話,就把它加上去。所以我們會走到樹的最左邊,並且 Stack Q 到目前為止的 Node 。 此時 top 就沒有左子孫,因為此時是作 Inorder , 所以這時候我們要先把 top 的 value 輸出 。 並判斷他有沒有右子孫,如果有的話就要加到 Stack Q 上面。 這裡有一個很重要的步驟就是,要能標記哪些 Node 已經輸出,這樣才不會重複輸出, 所以在把 top 的 value 輸出後,除了要 removeFirst,並且把 values 設成 Integer.MIN_VALUE 來標示已經輸出了。如此做到 Stack Q 為空的時候後停止。以下就用跟上面一樣的例子,來看 Stack Q 在整個演算法之中的情況,應該就會比較好理解。

[ ]    [ ]    [1]    [1]    [1]   [1,3] [1,3,2]
| |    | |    | |    | |    | |    | |    | |
| | -> | | -> | | -> | | -> |3| -> | | -> | |
| |    |1|    | |    |2|    |2|    |2|    | |
|_|    |_|    |_|    |_|    |_|    |_|    |_|
        1      2      2      3      4      5

put root 1

top node 1 has no left child -> pop and output value, top node 1 has right child -> put right child 2

top node 2 has left child -> put left child 3 and skip the rest

top node 3 has no left child -> pop and output value, top node 3 has no right child then do nothing

top node 2 has no left child -> pop and output value, top node 2 has no right child then do nothing

Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        LinkedList<TreeNode> Q = new LinkedList<TreeNode>();
        List<Integer> result = new ArrayList<Integer>();
        if(root!=null)
            Q.addFirst(root);
        while(!Q.isEmpty()){
           TreeNode iter = Q.get(0);
            if(iter.left != null ){
                if(iter.left.val != Integer.MIN_VALUE){
                    Q.addFirst(iter.left);
                    continue;
                }
            }
            TreeNode output = Q.removeFirst();
            result.add(output.val);
            output.val = Integer.MIN_VALUE;
            if(iter.right != null){
                Q.addFirst(iter.right);
            }
        }
        return result;
    }
}

Postorder

如此掌握 Inorder 的作法後,用類似的模式也可以做到 Postorder。

public class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        LinkedList<TreeNode> Q = new LinkedList<TreeNode>();
        List<Integer> result = new ArrayList<Integer>();
        if(root!=null)
            Q.addFirst(root);
        while(!Q.isEmpty()){
           TreeNode iter = Q.get(0);
            if(iter.left != null ){
                if(iter.left.val != Integer.MIN_VALUE){
                    Q.addFirst(iter.left);
                    continue;
                }
            }
            if(iter.right != null){
                if(iter.right.val != Integer.MIN_VALUE){
                    Q.addFirst(iter.right);
                    continue;
                }
            }
            TreeNode output = Q.removeFirst();
            result.add(output.val);
            output.val = Integer.MIN_VALUE;
        }
        return result;
    }
}

                's Picture

Ching Tsai

 每天努力學習的研究攻城獅,略懂平行運算,分散式系統及機器學習,平時偶爾攝影,興趣是看 YouTube 學煮菜。

                     Hsinchu, Taiwan
                     ChingTsai.github.io/chingtsai.github.io/

Share this post

                    Twitter

                    Facebook

                    Google+

        Please enable JavaScript to view the comments powered by Disqus.
        blog comments powered by Disqus

CentOS 網管小筆記 : 凍結帳號及強制登出

以前曾經管理一個 8 node 的 cluster 一段時間,而當時有個需求就是再某一段時間要對整個 cluster 作封測,由於當時 cluster 有外借一個帳號給別人,所以就會擔心再封得時候其他人跑進來玩耍,這樣封測的結果就不準了。但是如果直接刪除帳號到時候再開給他,顯得麻煩,於是就 survey 了一下如何凍結帳號,最好是可以凍結後時間到了就會自動解鎖,設定完後就不用煩惱。 - 以下的這些指令都是 Linux...

Shell Script : Jekyll Markdown Generator

很多人都問我說為什麼要用 MAC?除了做工精良,續航力高,還有一點非常棒的就是他可以和 Linux 共用大部分的 Unix Script。以下就用一個小小的例子來解釋能寫一些簡單的 Script 可以讓工程師一天過的更愉快。 一開始的緣由在於 Jekyll 的 Markdown 有一個既定的格式,就是檔名要是 日期-標題.md 並且內部要以特定的...

Make Today Better Than Yesterday © 2016

Proudly published with Jekyll using Jasper


text:
import sys
import os
import json
from subprocess import Popen, PIPE

# Import this way to produce a more useful error message.
try:
    import yaml
except ImportError:
    print('Unable to import YAML module: please install PyYAML', file=sys.stderr)
    sys.exit(1)

# Things an image file's name can end with.
IMAGE_FILE_SUFFIX = {
    '.gif',
    '.jpg',
    '.png',
    '.svg'
}

# Files that shouldn't be present.
UNWANTED_FILES = [
    '.nojekyll'
]

# Marker to show that an expected value hasn't been provided.
# (Can't use 'None' because that might be a legitimate value.)
REPORTER_NOT_SET = []

class Reporter:
    """Collect and report errors."""

    def __init__(self):
        """Constructor."""
        self.messages = []

    def check_field(self, filename, name, values, key, expected=REPORTER_NOT_SET):
        """Check that a dictionary has an expected value."""

        if key not in values:
            self.add(filename, '{0} does not contain {1}', name, key)
        elif expected is REPORTER_NOT_SET:
            pass
        elif type(expected) in (tuple, set, list):
            if values[key] not in expected:
                self.add(
                    filename, '{0} {1} value {2} is not in {3}', name, key, values[key], expected)
        elif values[key] != expected:
            self.add(filename, '{0} {1} is {2} not {3}',
                     name, key, values[key], expected)

    def check(self, condition, location, fmt, *args):
        """Append error if condition not met."""

        if not condition:
            self.add(location, fmt, *args)

    def add(self, location, fmt, *args):
        """Append error unilaterally."""

        self.messages.append((location, fmt.format(*args)))

    @staticmethod
    def pretty(item):
        location, message = item
        if isinstance(location, type(None)):
            return message
        elif isinstance(location, str):
            return location + ': ' + message
        elif isinstance(location, tuple):
            return '{0}:{1}: '.format(*location) + message

        print('Unknown item "{0}"'.format(item), file=sys.stderr)
        return NotImplemented

    @staticmethod
    def key(item):
        location, message = item
        if isinstance(location, type(None)):
            return ('', -1, message)
        elif isinstance(location, str):
            return (location, -1, message)
        elif isinstance(location, tuple):
            return (location[0], location[1], message)

        print('Unknown item "{0}"'.format(item), file=sys.stderr)
        return NotImplemented

    def report(self, stream=sys.stdout):
        """Report all messages in order."""

        if not self.messages:
            return

        for m in sorted(self.messages, key=self.key):
            print(self.pretty(m), file=stream)

def read_markdown(parser, path):
    """
    Get YAML and AST for Markdown file, returning
    {'metadata':yaml, 'metadata_len':N, 'text':text, 'lines':[(i, line, len)], 'doc':doc}.
    """

    # Split and extract YAML (if present).
    with open(path, 'r') as reader:
        body = reader.read()
    metadata_raw, metadata_yaml, body = split_metadata(path, body)

    # Split into lines.
    metadata_len = 0 if metadata_raw is None else metadata_raw.count('\n')
    lines = [(metadata_len+i+1, line, len(line))
             for (i, line) in enumerate(body.split('\n'))]

    # Parse Markdown.
    cmd = 'ruby {0}'.format(parser)
    p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE,
              close_fds=True, universal_newlines=True)
    stdout_data, stderr_data = p.communicate(body)
    doc = json.loads(stdout_data)

    return {
        'metadata': metadata_yaml,
        'metadata_len': metadata_len,
        'text': body,
        'lines': lines,
        'doc': doc
    }

def split_metadata(path, text):
    """
    Get raw (text) metadata, metadata as YAML, and rest of body.
    If no metadata, return (None, None, body).
    """

    metadata_raw = None
    metadata_yaml = None

    pieces = text.split('---', 2)
    if len(pieces) == 3:
        metadata_raw = pieces[1]
        text = pieces[2]
        try:
            metadata_yaml = yaml.load(metadata_raw)
        except yaml.YAMLError as e:
            print('Unable to parse YAML header in {0}:\n{1}'.format(
                path, e), file=sys.stderr)
            sys.exit(1)

    return metadata_raw, metadata_yaml, text

def load_yaml(filename):
    """
    Wrapper around YAML loading so that 'import yaml' is only needed
    in one file.
    """

    try:
        with open(filename, 'r') as reader:
            return yaml.load(reader)
    except (yaml.YAMLError, IOError) as e:
        print('Unable to load YAML file {0}:\n{1}'.format(
            filename, e), file=sys.stderr)
        sys.exit(1)

def check_unwanted_files(dir_path, reporter):
    """
    Check that unwanted files are not present.
    """

    for filename in UNWANTED_FILES:
        path = os.path.join(dir_path, filename)
        reporter.check(not os.path.exists(path),
                       path,
                       "Unwanted file found")

def require(condition, message):
    """Fail if condition not met."""

    if not condition:
        print(message, file=sys.stderr)
        sys.exit(1)

redpajama_set_name: RedPajamaGithub


text:
from django.shortcuts import render_to_response, render
from models import *

def template(request,template_id=1):
	"""
	you will have to replace "index.html"
	with (yourappname)/index.html
	and createa folder named (yourappname) in the templates directory.
	"""

	#required functions:
	#Add Row
	#Remove Row
	#Add cell
	#remove cell

	#for now - we just
	sections = Section.objects.filter(template=template_id)

	if request.method == 'POST':

		# possible actions from here:
		# Add a new block to a section
		# remove a block from a section
		if 'section' in request.POST.keys():
			# We are now either adding a block, removing a block, or gettin a section
			if 'add_block' in request.POST.keys():
				section = Section.objects.get(id=request.POST['section'])
				block = Block()
				block.section=section
				block.width=request.POST['add_block']
				block.title="-untitled-"
				block.save()

		else:
			section = Section()
			section.template_id=template_id
			section.save()

	return render(request,'grid_designer/index.html',{'sections':sections})


text:
Surgery Center

        {{item.id}}

{{item.name}}

        There are no Surgery Centers

Click here to add a Center!


text:
<?php

namespace common\models\query;

/**
 * This is the ActiveQuery class for [[\common\models\Currency]].
 *
 * @see \common\models\Currency
 */
class CurrencyQuery extends \yii\db\ActiveQuery
{
    /*public function active()
    {
        return $this->andWhere('[[status]]=1');
    }*/

    /**
     * @inheritdoc
     * @return \common\models\Currency[]|array
     */
    public function all($db = null)
    {
        return parent::all($db);
    }

    /**
     * @inheritdoc
     * @return \common\models\Currency|array|null
     */
    public function one($db = null)
    {
        return parent::one($db);
    }
}


text:
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/ec2/model/ResponseMetadata.h>
#include <aws/ec2/model/VolumeStatusItem.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Xml
{
  class XmlDocument;
} // namespace Xml
} // namespace Utils
namespace EC2
{
namespace Model
{
  /**
   *
Contains the output of DescribeVolumeStatus.

See Also:
   AWS
   * API Reference

   */
  class AWS_EC2_API DescribeVolumeStatusResponse
  {
  public:
    DescribeVolumeStatusResponse();
    DescribeVolumeStatusResponse(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
    DescribeVolumeStatusResponse& operator=(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);

    /**
     *
The token to use to retrieve the next page of results. This value is
     * null when there are no more results to return.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
The token to use to retrieve the next page of results. This value is
     * null when there are no more results to return.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextToken = value; }

    /**
     *
The token to use to retrieve the next page of results. This value is
     * null when there are no more results to return.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); }

    /**
     *
The token to use to retrieve the next page of results. This value is
     * null when there are no more results to return.

     */
    inline void SetNextToken(const char* value) { m_nextToken.assign(value); }

    /**
     *
The token to use to retrieve the next page of results. This value is
     * null when there are no more results to return.

     */
    inline DescribeVolumeStatusResponse& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
The token to use to retrieve the next page of results. This value is
     * null when there are no more results to return.

     */
    inline DescribeVolumeStatusResponse& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
The token to use to retrieve the next page of results. This value is
     * null when there are no more results to return.

     */
    inline DescribeVolumeStatusResponse& WithNextToken(const char* value) { SetNextToken(value); return *this;}

    /**
     *
A list of volumes.

     */
    inline const Aws::Vector<VolumeStatusItem>& GetVolumeStatuses() const{ return m_volumeStatuses; }

    /**
     *
A list of volumes.

     */
    inline void SetVolumeStatuses(const Aws::Vector<VolumeStatusItem>& value) { m_volumeStatuses = value; }

    /**
     *
A list of volumes.

     */
    inline void SetVolumeStatuses(Aws::Vector<VolumeStatusItem>&& value) { m_volumeStatuses = std::move(value); }

    /**
     *
A list of volumes.

     */
    inline DescribeVolumeStatusResponse& WithVolumeStatuses(const Aws::Vector<VolumeStatusItem>& value) { SetVolumeStatuses(value); return *this;}

    /**
     *
A list of volumes.

     */
    inline DescribeVolumeStatusResponse& WithVolumeStatuses(Aws::Vector<VolumeStatusItem>&& value) { SetVolumeStatuses(std::move(value)); return *this;}

    /**
     *
A list of volumes.

     */
    inline DescribeVolumeStatusResponse& AddVolumeStatuses(const VolumeStatusItem& value) { m_volumeStatuses.push_back(value); return *this; }

    /**
     *
A list of volumes.

     */
    inline DescribeVolumeStatusResponse& AddVolumeStatuses(VolumeStatusItem&& value) { m_volumeStatuses.push_back(std::move(value)); return *this; }

    inline const ResponseMetadata& GetResponseMetadata() const{ return m_responseMetadata; }

    inline void SetResponseMetadata(const ResponseMetadata& value) { m_responseMetadata = value; }

    inline void SetResponseMetadata(ResponseMetadata&& value) { m_responseMetadata = std::move(value); }

    inline DescribeVolumeStatusResponse& WithResponseMetadata(const ResponseMetadata& value) { SetResponseMetadata(value); return *this;}

    inline DescribeVolumeStatusResponse& WithResponseMetadata(ResponseMetadata&& value) { SetResponseMetadata(std::move(value)); return *this;}

  private:
    Aws::String m_nextToken;
    Aws::Vector<VolumeStatusItem> m_volumeStatuses;
    ResponseMetadata m_responseMetadata;
  };

} // namespace Model
} // namespace EC2
} // namespace Aws


text:
package org.apache.commons.beanutils;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.util.HashMap;
import java.util.Map;

import junit.framework.TestCase;

/**
 * Test class for {@code FluentPropertyBeanIntrospector}.
 *
 * @version $Id: FluentPropertyBeanIntrospectorTestCase.java 1540359 2013-11-09 18:10:52Z oheger $
 */
public class FluentPropertyBeanIntrospectorTestCase extends TestCase {
    /**
     * Puts all property descriptors into a map so that they can be accessed by
     * property name.
     *
     * @param descs the array with descriptors
     * @return a map with property names as keys
     */
    private static Map<String, PropertyDescriptor> createDescriptorMap(
            PropertyDescriptor[] descs) {
        Map<String, PropertyDescriptor> map = new HashMap<String, PropertyDescriptor>();
        for (PropertyDescriptor pd : descs) {
            map.put(pd.getName(), pd);
        }
        return map;
    }

    /**
     * Convenience method for obtaining a specific property descriptor and
     * checking whether it exists.
     *
     * @param props the map with property descriptors
     * @param name the name of the desired descriptor
     * @return the descriptor from the map
     */
    private static PropertyDescriptor fetchDescriptor(
            Map<String, PropertyDescriptor> props, String name) {
        assertTrue("Property not found: " + name, props.containsKey(name));
        return props.get(name);
    }

    /**
     * Tries to create an instance without a prefix for write methods.
     */
    public void testInitNoPrefix() {
        try {
            new FluentPropertyBeanIntrospector(null);
            fail("Missing prefix for write methods not detected!");
        } catch (IllegalArgumentException iex) {
            // ok
        }
    }

    /**
     * Tests whether correct property descriptors are detected.
     */
    public void testIntrospection() throws IntrospectionException {
        PropertyUtilsBean pu = new PropertyUtilsBean();
        FluentPropertyBeanIntrospector introspector = new FluentPropertyBeanIntrospector();
        pu.addBeanIntrospector(introspector);
        Map<String, PropertyDescriptor> props = createDescriptorMap(pu
                .getPropertyDescriptors(FluentIntrospectionTestBean.class));
        PropertyDescriptor pd = fetchDescriptor(props, "name");
        assertNotNull("No read method for name", pd.getReadMethod());
        assertNotNull("No write method for name", pd.getWriteMethod());
        fetchDescriptor(props, "stringProperty");
        pd = fetchDescriptor(props, "fluentProperty");
        assertNull("Read method for fluentProperty", pd.getReadMethod());
        assertNotNull("No write method for fluentProperty", pd.getWriteMethod());
        pd = fetchDescriptor(props, "fluentGetProperty");
        assertNotNull("No read method for fluentGetProperty",
                pd.getReadMethod());
        assertNotNull("No write method for fluentGetProperty",
                pd.getWriteMethod());
    }
}


text:
package wandou.util

import java.lang.reflect.Method
import java.lang.reflect.Modifier
import scala.reflect.ClassTag

/**
 *
 * @param <C> type of class
 * @param <V> type of var
 *
 * @author Caoyuan Deng
 */
final class ClassVar[C, V: ClassTag](val name: String, val getter: Method, val setter: Method) {
  if (getter != null) getter.setAccessible(true)
  if (setter != null) setter.setAccessible(true)

  def get(from: C): V = {
    try {
      getter.invoke(from).asInstanceOf[V]
    } catch {
      case e: Exception => throw new RuntimeException(e)
    }
  }

  /**
   * @Note set(to: C, value: Any) instead of set(to: C, value: V) here to prevent
   * the AnyVal type case to be broadcasted to usages.
   */
  def set(to: C, value: V) {
    try {
      if (value != null) {
        setter.invoke(to, value.asInstanceOf[AnyRef])
      } else {
        val propValue = reflect.classTag[V].newArray(1).apply(0)
        setter.invoke(to, propValue.asInstanceOf[AnyRef])
      }
    } catch {
      case e: Exception => throw new RuntimeException(e)
    }
  }

  def copy(from: C, to: C) {
    set(to, get(from))
  }
}

object ClassVar {
  def apply[C, V: ClassTag](name: String, getter: Method, setter: Method) = new ClassVar[C, V](name, getter, setter)

  def unapply(x: ClassVar[_, _]) = Some((x.name, x.getter, x.setter))

  def getPublicVars[C](clz: Class[C]): List[ClassVar[C, _]] = {
    var fields: List[ClassVar[C, _]] = Nil
    val methods = clz.getMethods
    for (method <- methods; if Modifier.isPublic(method.getModifiers)) {
      val name = method.getName
      val params = method.getParameterTypes
      if (name.endsWith("_$eq") && params.length == 1) {
        val getterName = name.substring(0, name.length - 4)
        val paramType = params(0)
        methods find (x => x.getName == getterName && x.getReturnType == paramType) match {
          case Some(getter) => fields ::= ClassVar(getterName, getter, method)
          case _            =>
        }
      }
    }
    fields
  }
}


text:
<?php

require_once __DIR__ . '/../bootstrap.php';

$source = \Rx\Observable::of(4)
    ->startWithArray([1, 2, 3]);

$subscription = $source->subscribe($stdoutObserver);


text:
local matchers = require('matchers')
local parser = clink.arg.new_parser

local boxes = matchers.create_dirs_matcher(clink.get_env("userprofile") .. "/.vagrant.d/boxes/*")

local vagrant_parser = parser({
    "box" .. parser({
        "add" .. parser(
            "--checksum",
            "--checksum-type" .. parser({"md5", "sha1", "sha256"}),
            "-c", "--clean",
            "-f", "--force",
            "--insecure",
            "--cacert",
            "--cert",
            "--provider"
            ),
        "list" .. parser("-i", "--box-info"),
        "outdated"..parser("--global", "-h", "--help"),
        "remove" .. parser({boxes}),
        "repackage" .. parser({boxes}),
        "update"
        }),
    "connect",
    "destroy" .. parser("-f", "--force"),
    "halt" .. parser("-f", "--force"),
    "init" .. parser({boxes}, {}, "--output"),
    "package" .. parser("--base", "--output", "--include", "--vagrantfile"),
    "plugin" .. parser({
        "install" .. parser(
            "--entry-point",
            "--plugin-prerelease",
            "--plugin-source",
            "--plugin-version"
            ),
        "license",
        "list",
        "uninstall",
        "update" .. parser(
            "--entry-point",
            "--plugin-prerelease",
            "--plugin-source",
            "--plugin-version"
            )
        }),
    "provision" .. parser("--provision-with", "--no-parallel", "--parallel"),
    "reload" .. parser("--provision-with", "--no-parallel", "--parallel"),
    "resume",
    "ssh" .. parser("-c", "--command", "-p", "--plain") ,
    "ssh-config",
    "status",
    "suspend",
    "up" .. parser(
        "--provision",
        "--no-provision",
        "--provision-with",
        "--destroy-on-error",
        "--no-destroy-on-error",
        "--parallel",
        "--no-parallel",
        "--provider"
        )
    }, "-h", "--help", "-v", "--version")

local help_parser = parser({
    "help" .. parser(vagrant_parser:flatten_argument(1))
})

clink.arg.register_parser("vagrant", vagrant_parser)
clink.arg.register_parser("vagrant", help_parser)


text:
from common import run

# See https://github.com/PyMySQL/PyMySQL for more details
URL = '' # e.g. mysql+pymysql://username:password@hostname:port
OPTIONS = {} # e.g. {"encoding": "latin1"}
PLATFORM = 'mysql'

run(URL, OPTIONS, PLATFORM)


text:
title: Getting started
page_title: Getting started - WinForms RadialGauge Control
description: WinForms RadialGauge control is designed to display a simple value within a definite range.
slug: winforms/gauges/radialgauge/getting-started
tags: getting,started
published: True
position: 3
previous_url: radialgauge-getting-started
---

# Getting Started

This article shows how you can add the control at design time or with code

## Design Time

When you drag a __RadRadialGauge__ from the Toolbox and drop it onto the form, the gauge gallery will offer you to pick up the desired type:

>caption Figure 1: Gallery Types
![radialgauge-getting-started 001](images/radialgauge-getting-started001.png)

>note If you do not choose a gauge's style and just close the gallery, an empty __RadRadialGauge__ will be created.
>

You can change the gauge's style via the Smart tag's option *Open Gallery* as well.

>caption Figure 2: Change Style
![radialgauge-getting-started 002](images/radialgauge-getting-started002.png)

## Adding Items Programmatically

You can create your own gauge's style programmatically from the scratch by adding the desired labels, ticks, needles, arcs to the RadRadialGauge.__Items__ collection. Here is a sample code snippet:

>caption Figure 3: Programmatically Added Items
![radialgauge-getting-started 003](images/radialgauge-getting-started003.png)

#### Add Items

{{source=..\SamplesCS\Gauges\RadialGauge\RadialGaugeGettingStarted.cs region=AddItemsProgrammatically}}
{{source=..\SamplesVB\Gauges\RadialGauge\RadialGaugeGettingStarted.vb region=AddItemsProgrammatically}}

````C#

RadialGaugeLabels labels = new RadialGaugeLabels();
RadialGaugeTicks smallTicks = new RadialGaugeTicks();
RadialGaugeTicks bigTicks = new RadialGaugeTicks();
RadialGaugeNeedle needle = new RadialGaugeNeedle();
RadialGaugeArc arc = new RadialGaugeArc();
labels.LabelFontSize = 4;
smallTicks.TickColor = Color.Red;
smallTicks.TickThickness = 0.5f;
smallTicks.TicksCount = 30;
smallTicks.TickStartIndexVisibleRange = 15;
bigTicks.TickColor = Color.DimGray;
bigTicks.TickThickness = 1f;
bigTicks.TicksCount = 10;
bigTicks.TicksLenghtPercentage = 20;
bigTicks.TicksRadiusPercentage = 80;
needle.LenghtPercentage = 60;
arc.Width = 0.5f;
arc.BackColor = Color.Gray;
radRadialGauge1.Items.Add(labels);
radRadialGauge1.Items.Add(smallTicks);
radRadialGauge1.Items.Add(bigTicks);
radRadialGauge1.Items.Add(needle);
radRadialGauge1.Items.Add(arc);

````
````VB.NET
Dim labels As New RadialGaugeLabels()
Dim smallTicks As New RadialGaugeTicks()
Dim bigTicks As New RadialGaugeTicks()
Dim needle As New RadialGaugeNeedle()
Dim arc As New RadialGaugeArc()
labels.LabelFontSize = 4
smallTicks.TickColor = Color.Red
smallTicks.TickThickness = 0.5F
smallTicks.TicksCount = 30
smallTicks.TickStartIndexVisibleRange = 15
bigTicks.TickColor = Color.DimGray
bigTicks.TickThickness = 1.0F
bigTicks.TicksCount = 10
bigTicks.TicksLenghtPercentage = 20
bigTicks.TicksRadiusPercentage = 80
needle.LenghtPercentage = 60
arc.Width = 0.5F
arc.BackColor = Color.Gray
radRadialGauge1.Items.Add(labels)
radRadialGauge1.Items.Add(smallTicks)
radRadialGauge1.Items.Add(bigTicks)
radRadialGauge1.Items.Add(needle)
radRadialGauge1.Items.Add(arc)

````

{{endregion}}

## Adding Additional Elements

Drag a __RadRadialGauge__ from the Toolbox and drop it onto the form. The gauge gallery will offer you to pick up the desired type. Select the first gauge type. Now, we will customize the gauge in order to obtain the result illustrated on the screen-shot below:

>caption Figure 4: Additional Element
![radialgauge-getting-started 004](images/radialgauge-getting-started004.gif)

#### Additional Element

{{source=..\SamplesCS\Gauges\RadialGauge\RadialGaugeGettingStarted.cs region=AdvancedExample}}
{{source=..\SamplesVB\Gauges\RadialGauge\RadialGaugeGettingStarted.vb region=AdvancedExample}}

````C#

Timer timer = new Timer();
float step = 0f;

private void AdvancedExample()
{
    this.AVGRadialGauge1.RangeStart = 0;
    this.AVGRadialGauge1.RangeEnd = 9;
    this.AVGRadialGauge1.ValueChanged += AVGRadialGauge1_ValueChanged;
    step = -(float)(AVGRadialGauge1.RangeEnd - AVGRadialGauge1.RangeStart) / 10f;

    this.radialGaugeLabels1.LabelFormat = "#,##0.00#";
    this.radialGaugeLabels1.LabelRadiusPercentage = 70;
    this.radialGaugeLabels1.LabelEndVisibleRange = 5;
    this.radialGaugeLabels2.LabelRadiusPercentage = 70;
    this.radialGaugeLabels2.LabelFormat = "#,##0.00#";
        this.radialGaugeLabels2.LabelStartVisibleRange=6;

    this.radialGaugeNeedle1.Visibility = ElementVisibility.Collapsed;
    this.radialGaugeNeedle2.Value = 4.25f;
    this.radialGaugeNeedle2.BackColor = Color.Black;
    this.radialGaugeNeedle2.BackColor2 = Color.Black;
    this.radialGaugeNeedle2.BackLenghtPercentage = 0;
    this.radialGaugeNeedle2.Thickness = 0.2f;
    this.radialGaugeNeedle2.BindValue = true;

    RadialGaugeTicks firstCircleTick = new RadialGaugeTicks();
    this.AVGRadialGauge1.Items.Add(firstCircleTick);

    firstCircleTick.TicksCount = 18;
    firstCircleTick.TickStartIndexVisibleRange = 5;
    firstCircleTick.TickEndIndexVisibleRange = 5;
    firstCircleTick.TicksLenghtPercentage = 3;
    firstCircleTick.TicksRadiusPercentage = 115;
    firstCircleTick.CircleTicks = true;
    firstCircleTick.TickThickness = 1;
    firstCircleTick.TickColor = Color.DimGray;

    RadialGaugeTicks firstTick = new RadialGaugeTicks();
    this.AVGRadialGauge1.Items.Add(firstTick);

    firstTick.TicksCount = 18;
    firstTick.TickStartIndexVisibleRange = 5;
    firstTick.TickEndIndexVisibleRange = 5;
    firstTick.TicksRadiusPercentage = 103;
    firstTick.CircleTicks = false;
    firstTick.TickThickness = 1;
    firstTick.TickColor = Color.DimGray;

    RadialGaugeTicks secondCircleTick = new RadialGaugeTicks();
    this.AVGRadialGauge1.Items.Add(secondCircleTick);

    secondCircleTick.TicksCount = 18;
    secondCircleTick.TickStartIndexVisibleRange = 9;
    secondCircleTick.TickEndIndexVisibleRange = 9;
    secondCircleTick.TicksLenghtPercentage = 3;
    secondCircleTick.TicksRadiusPercentage = 115;
    secondCircleTick.CircleTicks = true;
    secondCircleTick.TickThickness = 1;
    secondCircleTick.TickColor = Color.DimGray;

    RadialGaugeTicks secondTick = new RadialGaugeTicks();
    this.AVGRadialGauge1.Items.Add(secondTick);

    secondTick.TicksCount = 18;
    secondTick.TickStartIndexVisibleRange = 9;
    secondTick.TickEndIndexVisibleRange = 9;
    secondTick.TicksRadiusPercentage = 103;
    secondTick.CircleTicks = false;
    secondTick.TickThickness = 1;
    secondTick.TickColor = Color.DimGray;

    timer.Interval = 1000;
    timer.Tick += timer_Tick;
    timer.Start();
}
private void AVGRadialGauge1_ValueChanged(object sender, EventArgs e)
{
    if (this.AVGRadialGauge1.Value >= 6f)
    {
        this.radialGaugeNeedle2.BackColor = Color.FromArgb(224, 90, 90);
        this.radialGaugeNeedle2.BackColor2 = Color.FromArgb(224, 90, 90);
    }
    else
    {
        this.radialGaugeNeedle2.BackColor = Color.Black;
        this.radialGaugeNeedle2.BackColor2 = Color.Black;
    }
}

private void timer_Tick(object sender, EventArgs e)
{
    if (AVGRadialGauge1.Value + step > AVGRadialGauge1.RangeEnd || AVGRadialGauge1.Value + step < AVGRadialGauge1.RangeStart)
    {
        step = -step;
    }
    AnimatedPropertySetting setting = new AnimatedPropertySetting(RadRadialGaugeElement.ValueProperty,
        AVGRadialGauge1.Value, AVGRadialGauge1.Value + step, 12, 40);
    setting.ApplyEasingType = RadEasingType.OutBounce;
    setting.ApplyValue(AVGRadialGauge1.GaugeElement);
}

````
````VB.NET
Private timer As New Timer()
Private [step] As Single = 0.0F
Private Sub AdvancedExample()
    Me.AVGRadialGauge1.RangeStart = 0
    Me.AVGRadialGauge1.RangeEnd = 9
    AddHandler Me.AVGRadialGauge1.ValueChanged, AddressOf AVGRadialGauge1_ValueChanged
    [step] = -CSng(AVGRadialGauge1.RangeEnd - AVGRadialGauge1.RangeStart) / 10.0F
    Me.RadialGaugeLabels1.LabelFormat = "#,##0.00#"
    Me.RadialGaugeLabels1.LabelRadiusPercentage = 70
    Me.RadialGaugeLabels1.LabelEndVisibleRange = 5
    Me.RadialGaugeLabels2.LabelRadiusPercentage = 70
    Me.RadialGaugeLabels2.LabelFormat = "#,##0.00#"
    Me.RadialGaugeLabels2.LabelStartVisibleRange = 6
    Me.RadialGaugeNeedle1.Visibility = ElementVisibility.Collapsed
    Me.RadialGaugeNeedle2.Value = 4.25F
    Me.RadialGaugeNeedle2.BackColor = Color.Black
    Me.RadialGaugeNeedle2.BackColor2 = Color.Black
    Me.RadialGaugeNeedle2.BackLenghtPercentage = 0
    Me.RadialGaugeNeedle2.Thickness = 0.2F
    Me.RadialGaugeNeedle2.BindValue = True
    Dim firstCircleTick As New RadialGaugeTicks()
    Me.AVGRadialGauge1.Items.Add(firstCircleTick)
    firstCircleTick.TicksCount = 18
    firstCircleTick.TickStartIndexVisibleRange = 5
    firstCircleTick.TickEndIndexVisibleRange = 5
    firstCircleTick.TicksLenghtPercentage = 3
    firstCircleTick.TicksRadiusPercentage = 115
    firstCircleTick.CircleTicks = True
    firstCircleTick.TickThickness = 1
    firstCircleTick.TickColor = Color.DimGray
    Dim firstTick As New RadialGaugeTicks()
    Me.AVGRadialGauge1.Items.Add(firstTick)
    firstTick.TicksCount = 18
    firstTick.TickStartIndexVisibleRange = 5
    firstTick.TickEndIndexVisibleRange = 5
    firstTick.TicksRadiusPercentage = 103
    firstTick.CircleTicks = False
    firstTick.TickThickness = 1
    firstTick.TickColor = Color.DimGray
    Dim secondCircleTick As New RadialGaugeTicks()
    Me.AVGRadialGauge1.Items.Add(secondCircleTick)
    secondCircleTick.TicksCount = 18
    secondCircleTick.TickStartIndexVisibleRange = 9
    secondCircleTick.TickEndIndexVisibleRange = 9
    secondCircleTick.TicksLenghtPercentage = 3
    secondCircleTick.TicksRadiusPercentage = 115
    secondCircleTick.CircleTicks = True
    secondCircleTick.TickThickness = 1
    secondCircleTick.TickColor = Color.DimGray
    Dim secondTick As New RadialGaugeTicks()
    Me.AVGRadialGauge1.Items.Add(secondTick)
    secondTick.TicksCount = 18
    secondTick.TickStartIndexVisibleRange = 9
    secondTick.TickEndIndexVisibleRange = 9
    secondTick.TicksRadiusPercentage = 103
    secondTick.CircleTicks = False
    secondTick.TickThickness = 1
    secondTick.TickColor = Color.DimGray
    timer.Interval = 1000
    AddHandler timer.Tick, AddressOf timer_Tick
    timer.Start()
End Sub
Private Sub AVGRadialGauge1_ValueChanged(sender As Object, e As EventArgs)
    If Me.AVGRadialGauge1.Value >= 6.0F Then
        Me.RadialGaugeNeedle2.BackColor = Color.FromArgb(224, 90, 90)
        Me.RadialGaugeNeedle2.BackColor2 = Color.FromArgb(224, 90, 90)
    Else
        Me.RadialGaugeNeedle2.BackColor = Color.Black
        Me.RadialGaugeNeedle2.BackColor2 = Color.Black
    End If
End Sub
Private Sub timer_Tick(sender As Object, e As EventArgs)
    If AVGRadialGauge1.Value + [step] > AVGRadialGauge1.RangeEnd OrElse AVGRadialGauge1.Value + [step] < AVGRadialGauge1.RangeStart Then
        [step] = -[step]
    End If
    Dim setting As New AnimatedPropertySetting(RadRadialGaugeElement.ValueProperty, AVGRadialGauge1.Value, AVGRadialGauge1.Value + [step], 12, 40)
    setting.ApplyEasingType = RadEasingType.OutBounce
    setting.ApplyValue(AVGRadialGauge1.GaugeElement)
End Sub

````

{{endregion}}

## Clock Example

The following code snippet is purposed to demonstrate how to create a simple clock. For this purpose we will add the necessary clock's elements to the RadRadialGauge.__Items__ collection. Afterwards, we need to drag a timer from the Toolbox and drop it onto the form. Set the timer's __Interval__ property to *1000*. Subscribe to its __Tick__ event where we should  update the time.

>caption Figure 5: Clock
![radialgauge-getting-started 005](images/radialgauge-getting-started005.gif)

#### Clock

{{source=..\SamplesCS\Gauges\RadialGauge\RadialGaugeGettingStarted.cs region=Clock}}
{{source=..\SamplesVB\Gauges\RadialGauge\RadialGaugeGettingStarted.vb region=Clock}}

````C#

RadialGaugeNeedle hoursNeedle ;
RadialGaugeNeedle minutesNeedle;
RadialGaugeNeedle secondsNeedle;

private void RadialGaugeGettingStarted_Load(object sender, EventArgs e)
{
    RadialGaugeLabels hoursLabels = new RadialGaugeLabels();
    RadialGaugeTicks minutesTicks = new RadialGaugeTicks();
    RadialGaugeTicks bigTicks = new RadialGaugeTicks();

    hoursNeedle = new RadialGaugeNeedle();
    minutesNeedle = new RadialGaugeNeedle();
    secondsNeedle = new RadialGaugeNeedle();

    RadialGaugeArc arc = new RadialGaugeArc();

    hoursLabels.LabelFontSize = 4;
    bigTicks.TickColor = Color.DimGray;
    bigTicks.TickThickness = 1f;
    bigTicks.TicksCount = 12;
    bigTicks.TicksLenghtPercentage = 20;
    bigTicks.TicksRadiusPercentage = 80;

    minutesTicks.TicksCount = 60;
    minutesTicks.TickColor = Color.Black;
    minutesTicks.TickThickness = 0.5f;

    hoursNeedle.LenghtPercentage = 40;
    hoursNeedle.BackColor = Color.Gray;
    hoursNeedle.BackColor2 = Color.Gray;
    minutesNeedle.LenghtPercentage = 60;
    minutesNeedle.BackColor = Color.Gray;
    minutesNeedle.BackColor2 = Color.Gray;
    secondsNeedle.LenghtPercentage = 80;
    secondsNeedle.BackColor = Color.CadetBlue;
    secondsNeedle.BackColor2 = Color.CadetBlue;

    arc.Width = 0.5f;
    arc.BackColor = Color.Gray;

    radRadialGauge1.StartAngle = 270;
    radRadialGauge1.SweepAngle = 360;
    radRadialGauge1.RangeStart = 0;
    radRadialGauge1.RangeEnd = 12;
    hoursLabels.LabelStartVisibleRange = 1;
    hoursLabels.LabelFormat = "N0";
    hoursLabels.LabelsCount = 12;

    radRadialGauge1.Items.Add(hoursLabels);
    radRadialGauge1.Items.Add(minutesTicks);
    radRadialGauge1.Items.Add(bigTicks);

    radRadialGauge1.Items.Add(hoursNeedle);
    radRadialGauge1.Items.Add(minutesNeedle);
    radRadialGauge1.Items.Add(secondsNeedle);

    radRadialGauge1.Items.Add(arc);

    this.timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    float angleHour = (float)(DateTime.Now.Hour * 30 + DateTime.Now.Minute * 0.5);
    hoursNeedle.Value = angleHour % 360 / 360 * 12 ;
    minutesNeedle.Value = 12 * ((float)DateTime.Now.Minute / 60);
    secondsNeedle.Value = 12 * ((float)DateTime.Now.Second / 60);
}

````
````VB.NET
Private hoursNeedle As RadialGaugeNeedle
Private minutesNeedle As RadialGaugeNeedle
Private secondsNeedle As RadialGaugeNeedle
Private Sub RadialGaugeGettingStarted_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim hoursLabels As New RadialGaugeLabels()
    Dim minutesTicks As New RadialGaugeTicks()
    Dim bigTicks As New RadialGaugeTicks()

    hoursNeedle = New RadialGaugeNeedle()
    minutesNeedle = New RadialGaugeNeedle()
    secondsNeedle = New RadialGaugeNeedle()
    Dim arc As New RadialGaugeArc()
    hoursLabels.LabelFontSize = 4
    bigTicks.TickColor = Color.DimGray
    bigTicks.TickThickness = 1.0F
    bigTicks.TicksCount = 12
    bigTicks.TicksLenghtPercentage = 20
    bigTicks.TicksRadiusPercentage = 80
    minutesTicks.TicksCount = 60
    minutesTicks.TickColor = Color.Black
    minutesTicks.TickThickness = 0.5F
    hoursNeedle.LenghtPercentage = 40
    hoursNeedle.BackColor = Color.Gray
    hoursNeedle.BackColor2 = Color.Gray
    minutesNeedle.LenghtPercentage = 60
    minutesNeedle.BackColor = Color.Gray
    minutesNeedle.BackColor2 = Color.Gray
    secondsNeedle.LenghtPercentage = 80
    secondsNeedle.BackColor = Color.CadetBlue
    secondsNeedle.BackColor2 = Color.CadetBlue
    arc.Width = 0.5F
    arc.BackColor = Color.Gray
    radRadialGauge1.StartAngle = 270
    radRadialGauge1.SweepAngle = 360
    radRadialGauge1.RangeStart = 0
    radRadialGauge1.RangeEnd = 12
    hoursLabels.LabelStartVisibleRange = 1
    hoursLabels.LabelFormat = "N0"
    hoursLabels.LabelsCount = 12
    radRadialGauge1.Items.Add(hoursLabels)
    radRadialGauge1.Items.Add(minutesTicks)
    radRadialGauge1.Items.Add(bigTicks)
    radRadialGauge1.Items.Add(hoursNeedle)
    radRadialGauge1.Items.Add(minutesNeedle)
    radRadialGauge1.Items.Add(secondsNeedle)
    radRadialGauge1.Items.Add(arc)
    Me.Timer1.Start()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Dim angleHour As Single = CSng(DateTime.Now.Hour * 30 + DateTime.Now.Minute * 0.5)
    hoursNeedle.Value = (angleHour Mod 360) / 360 * 12
    minutesNeedle.Value = 12 * (CSng(DateTime.Now.Minute) / 60)
    secondsNeedle.Value = 12 * (CSng(DateTime.Now.Second) / 60)
End Sub

````

{{endregion}}

# See Also

* [Structure]({%slug winforms/gauges/radialgauge/structure%})
* [Smart Tag]({%slug winforms/gauges/radialgauge/design-time%})


text:
package com.amazonaws.services.sagemaker.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Provides configuration information for labeling jobs.
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class LabelingJobResourceConfig implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The AWS Key Management Service (AWS KMS) key that Amazon SageMaker uses to encrypt data on the storage volume
     * attached to the ML compute instance(s) that run the training job. The VolumeKmsKeyId can be any of
     * the following formats:
     *

     *

     *

     *

     * // KMS Key ID
     *

     *

     * "1234abcd-12ab-34cd-56ef-1234567890ab"
     *

     *

     *

     *

     * // Amazon Resource Name (ARN) of a KMS Key
     *

     *

     * "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"
     *

     *

     *

     */
    private String volumeKmsKeyId;

    /**
     *

     * The AWS Key Management Service (AWS KMS) key that Amazon SageMaker uses to encrypt data on the storage volume
     * attached to the ML compute instance(s) that run the training job. The VolumeKmsKeyId can be any of
     * the following formats:
     *

     *

     *

     *

     * // KMS Key ID
     *

     *

     * "1234abcd-12ab-34cd-56ef-1234567890ab"
     *

     *

     *

     *

     * // Amazon Resource Name (ARN) of a KMS Key
     *

     *

     * "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"
     *

     *

     *

     *
     * @param volumeKmsKeyId
     *        The AWS Key Management Service (AWS KMS) key that Amazon SageMaker uses to encrypt data on the storage
     *        volume attached to the ML compute instance(s) that run the training job. The VolumeKmsKeyId
     *        can be any of the following formats:

     *

     *

     *

     *        // KMS Key ID
     *

     *

     *        "1234abcd-12ab-34cd-56ef-1234567890ab"
     *

     *

     *

     *

     *        // Amazon Resource Name (ARN) of a KMS Key
     *

     *

     *        "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"
     *

     *

     */

    public void setVolumeKmsKeyId(String volumeKmsKeyId) {
        this.volumeKmsKeyId = volumeKmsKeyId;
    }

    /**
     *

     * The AWS Key Management Service (AWS KMS) key that Amazon SageMaker uses to encrypt data on the storage volume
     * attached to the ML compute instance(s) that run the training job. The VolumeKmsKeyId can be any of
     * the following formats:
     *

     *

     *

     *

     * // KMS Key ID
     *

     *

     * "1234abcd-12ab-34cd-56ef-1234567890ab"
     *

     *

     *

     *

     * // Amazon Resource Name (ARN) of a KMS Key
     *

     *

     * "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"
     *

     *

     *

     *
     * @return The AWS Key Management Service (AWS KMS) key that Amazon SageMaker uses to encrypt data on the storage
     *         volume attached to the ML compute instance(s) that run the training job. The VolumeKmsKeyId
     *         can be any of the following formats:

     *

     *

     *

     *         // KMS Key ID
     *

     *

     *         "1234abcd-12ab-34cd-56ef-1234567890ab"
     *

     *

     *

     *

     *         // Amazon Resource Name (ARN) of a KMS Key
     *

     *

     *         "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"
     *

     *

     */

    public String getVolumeKmsKeyId() {
        return this.volumeKmsKeyId;
    }

    /**
     *

     * The AWS Key Management Service (AWS KMS) key that Amazon SageMaker uses to encrypt data on the storage volume
     * attached to the ML compute instance(s) that run the training job. The VolumeKmsKeyId can be any of
     * the following formats:
     *

     *

     *

     *

     * // KMS Key ID
     *

     *

     * "1234abcd-12ab-34cd-56ef-1234567890ab"
     *

     *

     *

     *

     * // Amazon Resource Name (ARN) of a KMS Key
     *

     *

     * "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"
     *

     *

     *

     *
     * @param volumeKmsKeyId
     *        The AWS Key Management Service (AWS KMS) key that Amazon SageMaker uses to encrypt data on the storage
     *        volume attached to the ML compute instance(s) that run the training job. The VolumeKmsKeyId
     *        can be any of the following formats:

     *

     *

     *

     *        // KMS Key ID
     *

     *

     *        "1234abcd-12ab-34cd-56ef-1234567890ab"
     *

     *

     *

     *

     *        // Amazon Resource Name (ARN) of a KMS Key
     *

     *

     *        "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"
     *

     *

     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public LabelingJobResourceConfig withVolumeKmsKeyId(String volumeKmsKeyId) {
        setVolumeKmsKeyId(volumeKmsKeyId);
        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 (getVolumeKmsKeyId() != null)
            sb.append("VolumeKmsKeyId: ").append(getVolumeKmsKeyId());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof LabelingJobResourceConfig == false)
            return false;
        LabelingJobResourceConfig other = (LabelingJobResourceConfig) obj;
        if (other.getVolumeKmsKeyId() == null ^ this.getVolumeKmsKeyId() == null)
            return false;
        if (other.getVolumeKmsKeyId() != null && other.getVolumeKmsKeyId().equals(this.getVolumeKmsKeyId()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getVolumeKmsKeyId() == null) ? 0 : getVolumeKmsKeyId().hashCode());
        return hashCode;
    }

    @Override
    public LabelingJobResourceConfig clone() {
        try {
            return (LabelingJobResourceConfig) 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.sagemaker.model.transform.LabelingJobResourceConfigMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Zuki
 * Date: 4/16/15
 * Time: 10:08 PM
 */

namespace business_logic;
use data_access\NotificationDALFactory;
use external_data_access\centrality\OutageCasesEDAL,
    helpers\OracleToString,
    data_access\AccountDALFactory;
/**
 * Class OutageCasesManager
 * Se encarga de los casos de cortes registrados en centrality
 * @package business_logic
 */
class OutageCasesManager {

    /**
     * Obtiene todos los casos de cortes registrados
     * @return array
     */
    public static function getAllOutageCases()
    {
        $outage_cases = OutageCasesEDAL::getAllExecutingOutageCases();
        foreach ($outage_cases as $outage_case)
        {
            $outage_case->sent_notifications = self::getOutageCaseNotifications($outage_case->caso);
        }
        return $outage_cases;
    }

    /**
     * Obtiene las cuentas que son parte de un numero de caso de corte
     * @param $outageCase
     * @return array
     */
    public static function getOutageCaseAccounts($outageCase)
    {
        $outageCaseAccounts = OutageCasesEDAL::getOutageCaseAccounts($outageCase);
        $accountINFilter = OracleToString::convertToSQL(($outageCaseAccounts),"nus");
        return $accounts = AccountDALFactory::instance()->findAccountsINClause($accountINFilter);
    }

    /**
     * Obtiene un  caso de corte según su numero de caso
     * @param $outageCase , El numero de caso
     * @return array , null en caso de que no se haya encontrado un caso con el numero provisto
     */
    public static function getOutageCase($outageCase)
    {
        $result = OutageCasesEDAL::findOutageCase($outageCase);
        if (count($result)>0)
            return $result[0];
        return null;
    }

    /**
     * Obtiene las notificaciones enviadas de un caso específico
     * @param $outageCase , El numero de caso
     * @return array , null en caso de que no se haya encontrado un caso con el numero provisto
     */
    public static function getOutageCaseNotifications($outageCase)
    {
        return NotificationDALFactory::instance()->getOutageCaseNotifications($outageCase);
    }

}


text:
describe Carver::Presenter do
  let(:path) { 'api/v1/examples' }
  let(:action) { 'index' }
  let(:parent) { 'ApplicationController' }
  let!(:results) { Carver::Result.new(MemoryProfilerResults.new, :memory) }

  describe '#log' do
    subject { described_class.new(results, path, action, parent).log }

    context 'when profiled entity is a controller' do
      it 'logs profiling results' do
        expect(Rails.logger).to receive(:info).with('[Carver] source=Api::V1::ExamplesController#index type=controller category=memory total_allocated_memsize=0.02003 total_retained_memsize=0.00143')
        subject
      end

      context 'when benchmarking' do
        let!(:results) { Carver::Result.new(BenchmarkResults.new, :benchmark) }

        it 'logs profiling results' do
          expect(Rails.logger).to receive(:info).with('[Carver] source=Api::V1::ExamplesController#index type=controller category=benchmark real=3.5 total=5.2')
          subject
        end
      end
    end

    context 'when profiled entity is a job' do
      let(:path) { 'ExampleJob' }
      let(:action) { 'perform' }
      let(:parent) { 'ApplicationJob' }

      it 'logs profiling results' do
        expect(Rails.logger).to receive(:info).with('[Carver] source=ExampleJob#perform type=job category=memory total_allocated_memsize=0.02003 total_retained_memsize=0.00143')
        subject
      end

      context 'when benchmarking' do
        let!(:results) { Carver::Result.new(BenchmarkResults.new, :benchmark) }

        it 'logs profiling results' do
          expect(Rails.logger).to receive(:info).with('[Carver] source=ExampleJob#perform type=job category=benchmark real=3.5 total=5.2')
          subject
        end
      end
    end
  end

  describe '#add_to_results' do
    subject { described_class.new(results, path, action, parent).add_to_results }

    it 'adds results to report' do
      Carver.clear_results
      expect(Carver.current_results).to eq({})
      subject
      expect(Carver.current_results).to eq({ 'Api::V1::ExamplesController#index' => [{ category: :memory, total_allocated_memsize: 0.02003, total_retained_memsize: 0.00143 }] })
    end

    context 'when benchmarking' do
      let!(:results) { Carver::Result.new(BenchmarkResults.new, :benchmark) }

      it 'adds benchmarking results' do
        Carver.clear_results
        expect(Carver.current_results).to eq({})
        subject
        expect(Carver.current_results).to eq({ 'Api::V1::ExamplesController#index' => [{ category: :benchmark, real: 3.5, total: 5.2 }] })
      end
    end
  end
end


text:
import anyTest, { TestInterface } from 'ava';
import { initialize } from '../../worker-thread/initialize';
import { WorkerStorageInit } from '../../worker-thread/initialize-storage';
import { Document } from '../../worker-thread/dom/Document';
import { HydrateableNode } from '../../transfer/TransferrableNodes';

const test = anyTest as TestInterface<{
  doc: Document;
  self: any;
}>;
test.beforeEach((t) => {
  const doc = { defaultView: {} } as Document;
  const self: any = {};
  (globalThis as any).self = self;
  t.context = { doc, self };
});

test.serial('Should install throwing storage', (t) => {
  const unsupportedAccess: WorkerStorageInit = {
    storage: null,
    errorMsg: 'Access denied',
  };
  const { doc, self } = t.context;
  initialize(doc, [], {} as HydrateableNode, [], [], [0, 0], unsupportedAccess, unsupportedAccess);
  t.falsy(doc.defaultView.localStorage);
  t.falsy(doc.defaultView.sessionStorage);
  t.falsy(self.localStorage);
  t.falsy(self.sessionStorage);
});

test.serial('Should install accessible storage', (t) => {
  const supportedAccess: WorkerStorageInit = {
    storage: {},
    errorMsg: null,
  };
  const { doc } = t.context;
  initialize(doc, [], {} as HydrateableNode, [], [], [0, 0], supportedAccess, supportedAccess);
  t.truthy(doc.defaultView.localStorage);
  t.truthy(doc.defaultView.sessionStorage);
});