text:
package cn.finalteam.rxgalleryfinal.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import cn.finalteam.rxgalleryfinal.BuildConfig;
import cn.finalteam.rxgalleryfinal.Configuration;
import cn.finalteam.rxgalleryfinal.utils.Logger;

/**
 * Desction:
 * Author:pengjianbo
 * Date:16/5/14 上午10:46
 */
public abstract class BaseFragment extends Fragment {

    private final String CLASS_NAME = getClass().getSimpleName();
    public static final String EXTRA_PREFIX = BuildConfig.APPLICATION_ID;
    public static final String EXTRA_CONFIGURATION = EXTRA_PREFIX +".Configuration";

    protected Bundle mSaveDataBundle;
    protected String BUNDLE_KEY = "KEY_" + CLASS_NAME;

    protected Configuration mConfiguration;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        printFragmentLife("onAttach");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        printFragmentLife("onCreate");
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        printFragmentLife("onViewCreated");

        Bundle argsBundle = getArguments();

        if(savedInstanceState != null){
            mConfiguration = savedInstanceState.getParcelable(EXTRA_CONFIGURATION);
        }
        if(mConfiguration == null && argsBundle != null) {
            mConfiguration = argsBundle.getParcelable(EXTRA_CONFIGURATION);
        }

        if(mConfiguration != null){
            if(argsBundle == null){
                argsBundle = savedInstanceState;
            }
            onViewCreatedOk(view, argsBundle);
            setTheme();
        } else {
            if(getActivity() != null && !getActivity().isFinishing()) {
                getActivity().finish();
            }
        }
    }

    public abstract void onViewCreatedOk(View view, @Nullable Bundle savedInstanceState);

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        printFragmentLife("onCreateView");
        return inflater.inflate(getContentView(), container, false);
    }

    @Override
    public void onStart() {
        super.onStart();
        printFragmentLife("onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        printFragmentLife("onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        printFragmentLife("onPause");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        printFragmentLife("onDestroyView");
        saveStateToArguments();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        printFragmentLife("onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        printFragmentLife("onDetach");
    }

    public abstract int getContentView();

    public void setTheme(){}

    private void printFragmentLife(String method){
        Logger.i(String.format("Fragment:%s Method:%s", CLASS_NAME, method));
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        printFragmentLife("onActivityCreated");
        if (!restoreStateFromArguments()) {
            onFirstTimeLaunched();
        }
    }

    protected abstract void onFirstTimeLaunched();

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        printFragmentLife("onSaveInstanceState");
        saveStateToArguments();
    }

    private void saveStateToArguments() {
        if (getView() != null) {
            mSaveDataBundle = saveState();
        }

        if (mSaveDataBundle != null) {
            Bundle b = getArguments();
            if(b != null) {
                b.putBundle(BUNDLE_KEY, mSaveDataBundle);
            }
        }
    }

    private boolean restoreStateFromArguments() {
        Bundle b = getArguments();
        if(b != null) {
            mSaveDataBundle = b.getBundle(BUNDLE_KEY);
            if (mSaveDataBundle != null) {
                restoreState();
                return true;
            }
        }
        return false;
    }

    /**
     * Restore Instance State Here
     */
    private void restoreState() {
        if (mSaveDataBundle != null) {
            mConfiguration = mSaveDataBundle.getParcelable(EXTRA_CONFIGURATION);
            onRestoreState(mSaveDataBundle);
        }
    }

    /**
     * 恢复数据
     * @param savedInstanceState
     */
    protected abstract void onRestoreState(Bundle savedInstanceState);

    /**
     * Save Instance State Here
     */
    private Bundle saveState() {
        Bundle state = new Bundle();
        state.putParcelable(EXTRA_CONFIGURATION, mConfiguration);
        onSaveState(state);
        return state;
    }

    protected abstract void onSaveState(Bundle outState);
}


text:
`Encore\Admin\Widgets\Collapse` class used to generate folding components:
```php
use Encore\Admin\Widgets\Collapse;

$collapse = new Collapse();

$collapse->add('Bar', 'xxxxx');
$collapse->add('Orders', new Table());

echo $collapse->render();

```

The `Collapse::add($title, $content)` method is used to add a collapsed item to the collapsing component. The `$title` parameter sets the title of the item. The`$content` parameter is used to .

redpajama_set_name: RedPajamaGithub


text:
/**
 * Volume Detail
 */

@interface EC2VolumeDetail:NSObject

{
    NSNumber *size;
}

/**
 * Default constructor for a new  object.  Callers should use the
 * property methods to initialize this object after creating it.
 */
-(id)init;

/**
 * The value of the Size property for this object.
 */
@property (nonatomic, retain) NSNumber *size;

/**
 * Returns a string representation of this object; useful for testing and
 * debugging.
 *
 * @return A string representation of this object.
 */
-(NSString *)description;

@end


text:
'use strict';

require('configureForRelayOSS');

jest
  .unmock('GraphQLRange')
  .unmock('GraphQLSegment');

const Relay = require('Relay');
const RelayQueryTracker = require('RelayQueryTracker');
const RelayTestUtils = require('RelayTestUtils');

const diffRelayQuery = require('diffRelayQuery');

describe('diffRelayQuery', () => {
  let RelayRecordStore;
  let RelayRecordWriter;

  const {getNode, writePayload} = RelayTestUtils;

  beforeEach(() => {
    jest.resetModuleRegistry();

    RelayRecordStore = require('RelayRecordStore');
    RelayRecordWriter = require('RelayRecordWriter');

    jasmine.addMatchers(RelayTestUtils.matchers);
  });

  it('keeps queries if the root dataID is unknown', () => {
    const records = {};
    const store = new RelayRecordStore({records});
    const tracker = new RelayQueryTracker();

    const query = getNode(Relay.QL`
      query {
        username(name:"joe") {
          id
          firstName
          lastName
        }
      }
    `);
    const diffQueries = diffRelayQuery(query, store, tracker);
    expect(diffQueries.length).toBe(1);
    expect(diffQueries[0]).toBeQueryRoot(query);
  });

  it('returns original query if all fields unfetched', () => {
    const records = {};
    const store = new RelayRecordStore({records});
    const tracker = new RelayQueryTracker();

    const query = getNode(Relay.QL`
      query {
        node(id:"123") {
          id
          firstName
          lastName
        }
      }
    `);
    const diffQueries = diffRelayQuery(query, store, tracker);
    expect(diffQueries.length).toBe(1);
    expect(diffQueries[0]).toBeQueryRoot(query);
  });

  it('keeps unfetched scalar fields', () => {
    const records = {};
    const store = new RelayRecordStore({records});
    const writer = new RelayRecordWriter(records, {}, false);
    const tracker = new RelayQueryTracker();

    const writeQuery = getNode(Relay.QL`
      query {
        node(id:"123") {
          firstName
        }
      }
    `);
    const payload = {
      node: {
        id: '123',
        firstName: 'Joe',
        __typename: 'User',
      },
    };
    writePayload(store, writer, writeQuery, payload, tracker);

    const fetchQuery = getNode(Relay.QL`
      query {
        node(id:"123") {
          id
          firstName
          lastName
        }
      }
    `);
    const diffQueries = diffRelayQuery(fetchQuery, store, tracker);
    expect(diffQueries.length).toBe(1);
    expect(diffQueries[0]).toEqualQueryRoot(getNode(Relay.QL`
      query {
        node(id:"123") {
          lastName
        }
      }
    `));
  });
});


text:
             Graffiti Jagd Derendorf

                    Graffity Bilderbuch

                    Gefunden!

                    Sende Graffitivorschlag


text:
import 'babel-polyfill';
import React from 'react';
import {shallow} from 'enzyme';
import {ScriptListScreen} from '../ScriptListScreen.js';
import ScriptTableRow from '../../components/ScriptTableRow.js';
import Loading from '../../components/Loading.js';

test('ScriptListScreen renders properly', () => {
  const tankList = [
    { id: 'tank932', scriptName: 'orange0984'},
    { id: 'tank883', scriptName: 'pink884323'},
    { id: 'tank521', scriptName: 'blue887431'}
  ];
  const wrapper = shallow(<ScriptListScreen
    tankList={tankList}
  />);

  expect(wrapper.find(ScriptTableRow)).toHaveLength(3);
  expect(wrapper.find(ScriptTableRow).at(0).props()).toHaveProperty('id', 'tank932');
  expect(wrapper.find(ScriptTableRow).at(0).props()).toHaveProperty('name', 'orange0984');
  expect(wrapper.find(ScriptTableRow).at(0).props()).toHaveProperty('link', '/sandbox/tank932');

  expect(wrapper.find(ScriptTableRow).at(1).props()).toHaveProperty('id', 'tank883');
  expect(wrapper.find(ScriptTableRow).at(1).props()).toHaveProperty('name', 'pink884323');
  expect(wrapper.find(ScriptTableRow).at(1).props()).toHaveProperty('link', '/sandbox/tank883');

  expect(wrapper.find(ScriptTableRow).at(2).props()).toHaveProperty('id', 'tank521');
  expect(wrapper.find(ScriptTableRow).at(2).props()).toHaveProperty('name', 'blue887431');
  expect(wrapper.find(ScriptTableRow).at(2).props()).toHaveProperty('link', '/sandbox/tank521');
});

test('Display loading info', () => {
  const wrapperLoading = shallow(<ScriptListScreen
    isLoading={true}
  />);
  expect(wrapperLoading.find(Loading)).toHaveLength(1);

  const wrapperCreating = shallow(<ScriptListScreen
    isCreating={true}
  />);
  expect(wrapperCreating.find(Loading)).toHaveLength(1);

  const wrapperDeleting = shallow(<ScriptListScreen
    isDeleting={true}
  />);
  expect(wrapperDeleting.find(Loading)).toHaveLength(1);

});

test('delete script', () => {
  const tankList = [
    { id: 'tank932', scriptName: 'orange0984'},
    { id: 'tank883', scriptName: 'pink884323'},
    { id: 'tank521', scriptName: 'blue887431'}
  ];
  const deleteAiScript = jest.fn();
  const wrapper = shallow(<ScriptListScreen
    tankList={tankList}
    deleteAiScript={deleteAiScript}
  />);

  wrapper.find(ScriptTableRow).at(1).props().onDelete();
  expect(deleteAiScript.mock.calls).toHaveLength(1);
  expect(deleteAiScript.mock.calls[0][0]).toBe('tank883');
});


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W30119_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans15.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">PUMPING

    <p class="styleSans14.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">SCHEDULE

    <p class="styleSans122.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">
Sm m: 1 ——'_— —-5Eim_—'E-

_E-—-§!_ 13-" m—m_—m_
Stage Descnptwons /' Flush anumes
Stage Description ""3" "MS Huglvo'ume
Stae 1 (Perf MD = 20524.0 - 20692.0 ft) Slickwater 12.7

    <p class="styleSans56.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Fluid Totals
23374 a!
1000 gal YF128FlexD + 0450 @ 2 t 52000 al YFIZBFlexD 1000 al

Pmppant Totals
20/40 White Sand 80000 lb

    <p class="styleSans133.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans33.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Schlumllergel'

    <p class="styleSans44.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">


text:
.. _cluster-config:

Cluster YAML Configuration Options
==================================

The cluster configuration is defined within a YAML file that will be used by the Cluster Launcher to launch the head node, and by the Autoscaler to launch worker nodes. Once the cluster configuration is defined, you will need to use the :ref:`Ray CLI <ray-cli>` to perform any operations such as starting and stopping the cluster.

Syntax
------

.. parsed-literal::

    :ref:`cluster_name <cluster-configuration-cluster-name>`: str
    :ref:`max_workers <cluster-configuration-max-workers>`: int
    :ref:`upscaling_speed <cluster-configuration-upscaling-speed>`: float
    :ref:`idle_timeout_minutes <cluster-configuration-idle-timeout-minutes>`: int
    :ref:`docker <cluster-configuration-docker>`:
        :ref:`docker <cluster-configuration-docker-type>`
    :ref:`provider <cluster-configuration-provider>`:
        :ref:`provider <cluster-configuration-provider-type>`
    :ref:`auth <cluster-configuration-auth>`:
        :ref:`auth <cluster-configuration-auth-type>`
    :ref:`available_node_types <cluster-configuration-available-node-types>`:
        :ref:`node_types <cluster-configuration-node-types-type>`
    :ref:`head_node_type <cluster-configuration-head-node-type>`: str
    :ref:`file_mounts <cluster-configuration-file-mounts>`:
        :ref:`file_mounts <cluster-configuration-file-mounts-type>`
    :ref:`cluster_synced_files <cluster-configuration-cluster-synced-files>`:
        - str
    :ref:`rsync_exclude <cluster-configuration-rsync-exclude>`:
        - str
    :ref:`rsync_filter <cluster-configuration-rsync-filter>`:
        - str
    :ref:`initialization_commands <cluster-configuration-initialization-commands>`:
        - str
    :ref:`setup_commands <cluster-configuration-setup-commands>`:
        - str
    :ref:`head_setup_commands <cluster-configuration-head-setup-commands>`:
        - str
    :ref:`worker_setup_commands <cluster-configuration-worker-setup-commands>`:
        - str
    :ref:`head_start_ray_commands <cluster-configuration-head-start-ray-commands>`:
        - str
    :ref:`worker_start_ray_commands <cluster-configuration-worker-start-ray-commands>`:
        - str

Custom types
------------

.. _cluster-configuration-docker-type:

Docker
~~~~~~

.. parsed-literal::
    :ref:`image <cluster-configuration-image>`: str
    :ref:`head_image <cluster-configuration-head-image>`: str
    :ref:`worker_image <cluster-configuration-worker-image>`: str
    :ref:`container_name <cluster-configuration-container-name>`: str
    :ref:`pull_before_run <cluster-configuration-pull-before-run>`: bool
    :ref:`run_options <cluster-configuration-run-options>`:
        - str
    :ref:`head_run_options <cluster-configuration-head-run-options>`:
        - str
    :ref:`worker_run_options <cluster-configuration-worker-run-options>`:
        - str
    :ref:`disable_automatic_runtime_detection <cluster-configuration-disable-automatic-runtime-detection>`: bool
    :ref:`disable_shm_size_detection <cluster-configuration-disable-shm-size-detection>`: bool

.. _cluster-configuration-auth-type:

Auth
~~~~

.. tabs::
    .. group-tab:: AWS

        .. parsed-literal::

            :ref:`ssh_user <cluster-configuration-ssh-user>`: str
            :ref:`ssh_private_key <cluster-configuration-ssh-private-key>`: str

    .. group-tab:: Azure

        .. parsed-literal::

            :ref:`ssh_user <cluster-configuration-ssh-user>`: str
            :ref:`ssh_private_key <cluster-configuration-ssh-private-key>`: str
            :ref:`ssh_public_key <cluster-configuration-ssh-public-key>`: str

    .. group-tab:: GCP

        .. parsed-literal::

            :ref:`ssh_user <cluster-configuration-ssh-user>`: str
            :ref:`ssh_private_key <cluster-configuration-ssh-private-key>`: str

.. _cluster-configuration-provider-type:

Provider
~~~~~~~~

.. tabs::
    .. group-tab:: AWS

        .. parsed-literal::

            :ref:`type <cluster-configuration-type>`: str
            :ref:`region <cluster-configuration-region>`: str
            :ref:`availability_zone <cluster-configuration-availability-zone>`: str
            :ref:`cache_stopped_nodes <cluster-configuration-cache-stopped-nodes>`: bool

    .. group-tab:: Azure

        .. parsed-literal::

            :ref:`type <cluster-configuration-type>`: str
            :ref:`location <cluster-configuration-location>`: str
            :ref:`resource_group <cluster-configuration-resource-group>`: str
            :ref:`subscription_id <cluster-configuration-subscription-id>`: str
            :ref:`cache_stopped_nodes <cluster-configuration-cache-stopped-nodes>`: bool

    .. group-tab:: GCP

        .. parsed-literal::

            :ref:`type <cluster-configuration-type>`: str
            :ref:`region <cluster-configuration-region>`: str
            :ref:`availability_zone <cluster-configuration-availability-zone>`: str
            :ref:`project_id <cluster-configuration-project-id>`: str
            :ref:`cache_stopped_nodes <cluster-configuration-cache-stopped-nodes>`: bool

.. _cluster-configuration-node-types-type:

Node types
~~~~~~~~~~

The ``available_nodes_types`` object's keys represent the names of the different node types.

Deleting a node type from ``available_node_types`` and updating with :ref:`ray up<ray-up-doc>` will cause the autoscaler to scale down all nodes of that type.
In particular, changing the key of a node type object will
result in removal of nodes corresponding to the old key; nodes with the new key name will then be
created according to cluster configuration and Ray resource demands.

.. parsed-literal::
    <node_type_1_name>:
        :ref:`node_config <cluster-configuration-node-config>`:
            :ref:`Node config <cluster-configuration-node-config-type>`
        :ref:`resources <cluster-configuration-resources>`:
            :ref:`Resources <cluster-configuration-resources-type>`
        :ref:`min_workers <cluster-configuration-node-min-workers>`: int
        :ref:`max_workers <cluster-configuration-node-max-workers>`: int
        :ref:`worker_setup_commands <cluster-configuration-node-type-worker-setup-commands>`:
            - str
        :ref:`docker <cluster-configuration-node-docker>`:
            :ref:`Node Docker <cluster-configuration-node-docker-type>`
    <node_type_2_name>:
        ...
    ...

.. _cluster-configuration-node-config-type:

Node config
~~~~~~~~~~~

Cloud-specific configuration for nodes of a given node type.

Modifying the ``node_config`` and updating with :ref:`ray up<ray-up-doc>` will cause the autoscaler to scale down all existing nodes of the node type;
nodes with the newly applied ``node_config`` will then be created according to cluster configuration and Ray resource demands.

.. tabs::
    .. group-tab:: AWS

        A YAML object which conforms to the EC2 ``create_instances`` API in `the AWS docs <https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.ServiceResource.create_instances>`_.

    .. group-tab:: Azure

        A YAML object as defined in `the deployment template <https://docs.microsoft.com/en-us/azure/templates/microsoft.compute/virtualmachines>`_ whose resources are defined in `the Azure docs <https://docs.microsoft.com/en-us/azure/templates/>`_.

    .. group-tab:: GCP

        A YAML object as defined in `the GCP docs <https://cloud.google.com/compute/docs/reference/rest/v1/instances>`_.

.. _cluster-configuration-node-docker-type:

Node Docker
~~~~~~~~~~~

.. parsed-literal::

    :ref:`image <cluster-configuration-image>`: str
    :ref:`pull_before_run <cluster-configuration-pull-before-run>`: bool
    :ref:`worker_run_options <cluster-configuration-worker-run-options>`:
        - str
    :ref:`disable_automatic_runtime_detection <cluster-configuration-disable-automatic-runtime-detection>`: bool
    :ref:`disable_shm_size_detection <cluster-configuration-disable-shm-size-detection>`: bool

.. _cluster-configuration-resources-type:

Resources
~~~~~~~~~

.. parsed-literal::

    :ref:`CPU <cluster-configuration-CPU>`: int
    :ref:`GPU <cluster-configuration-GPU>`: int
    :ref:`object_store_memory <cluster-configuration-object-store-memory>`: int
    :ref:`memory <cluster-configuration-memory>`: int
    <custom_resource1>: int
    <custom_resource2>: int
    ...

.. _cluster-configuration-file-mounts-type:

File mounts
~~~~~~~~~~~

.. parsed-literal::
    <path1_on_remote_machine>: str # Path 1 on local machine
    <path2_on_remote_machine>: str # Path 2 on local machine
    ...

Properties and Definitions
--------------------------

.. _cluster-configuration-cluster-name:

``cluster_name``
~~~~~~~~~~~~~~~~

The name of the cluster. This is the namespace of the cluster.

* **Required:** Yes
* **Importance:** High
* **Type:** String
* **Default:** "default"
* **Pattern:** ``[a-zA-Z0-9_]+``

.. _cluster-configuration-max-workers:

``max_workers``
~~~~~~~~~~~~~~~

The maximum number of workers the cluster will have at any given time.

* **Required:** No
* **Importance:** High
* **Type:** Integer
* **Default:** ``2``
* **Minimum:** ``0``
* **Maximum:** Unbounded

.. _cluster-configuration-upscaling-speed:

``upscaling_speed``
~~~~~~~~~~~~~~~~~~~

The number of nodes allowed to be pending as a multiple of the current number of nodes. For example, if set to 1.0, the cluster can grow in size by at most 100% at any time, so if the cluster currently has 20 nodes, at most 20 pending launches are allowed.

* **Required:** No
* **Importance:** Medium
* **Type:** Float
* **Default:** ``1.0``
* **Minimum:** ``0.0``
* **Maximum:** Unbounded

.. _cluster-configuration-idle-timeout-minutes:

``idle_timeout_minutes``
~~~~~~~~~~~~~~~~~~~~~~~~

The number of minutes that need to pass before an idle worker node is removed by the Autoscaler.

* **Required:** No
* **Importance:** Medium
* **Type:** Integer
* **Default:** ``5``
* **Minimum:** ``0``
* **Maximum:** Unbounded

.. _cluster-configuration-docker:

``docker``
~~~~~~~~~~

Configure Ray to run in Docker containers.

* **Required:** No
* **Importance:** High
* **Type:** :ref:`Docker <cluster-configuration-docker-type>`
* **Default:** ``{}``

In rare cases when Docker is not available on the system by default (e.g., bad AMI), add the following commands to :ref:`initialization_commands <cluster-configuration-initialization-commands>` to install it.

.. code-block:: yaml

    initialization_commands:
        - curl -fsSL https://get.docker.com -o get-docker.sh
        - sudo sh get-docker.sh
        - sudo usermod -aG docker $USER
        - sudo systemctl restart docker -f

.. _cluster-configuration-provider:

``provider``
~~~~~~~~~~~~

The cloud provider-specific configuration properties.

* **Required:** Yes
* **Importance:** High
* **Type:** :ref:`Provider <cluster-configuration-provider-type>`

.. _cluster-configuration-auth:

``auth``
~~~~~~~~

Authentication credentials that Ray will use to launch nodes.

* **Required:** Yes
* **Importance:** High
* **Type:** :ref:`Auth <cluster-configuration-auth-type>`

.. _cluster-configuration-available-node-types:

``available_node_types``
~~~~~~~~~~~~~~~~~~~~~~~~

Tells the autoscaler the allowed node types and the resources they provide.
Each node type is identified by a user-specified key.

* **Required:** No
* **Importance:** High
* **Type:** :ref:`Node types <cluster-configuration-node-types-type>`
* **Default:**

.. tabs::
    .. group-tab:: AWS

        .. code-block:: yaml

          available_node_types:
            ray.head.default:
                node_config:
                  InstanceType: m5.large
                  BlockDeviceMappings:
                      - DeviceName: /dev/sda1
                        Ebs:
                            VolumeSize: 100
                resources: {"CPU": 2}
                min_workers: 0
                max_workers: 0
            ray.worker.default:
                node_config:
                  InstanceType: m5.large
                  InstanceMarketOptions:
                      MarketType: spot
                resources: {"CPU": 2}
                min_workers: 0

.. _cluster-configuration-head-node-type:

``head_node_type``
~~~~~~~~~~~~~~~~~~

The key for one of the node types in :ref:`available_node_types <cluster-configuration-available-node-types>`. This node type will be used to launch the head node.

If the field ``head_node_type`` is changed and an update is executed with :ref:`ray up<ray-up-doc>`, the currently running head node will
be considered outdated. The user will receive a prompt asking to confirm scale-down of the outdated head node, and the cluster will restart with a new
head node. Changing the :ref:`node_config<cluster-configuration-node-config>` of the :ref:`node_type<cluster-configuration-node-types-type>` with key ``head_node_type`` will also result in cluster restart after a user prompt.

* **Required:** Yes
* **Importance:** High
* **Type:** String
* **Pattern:** ``[a-zA-Z0-9_]+``

.. _cluster-configuration-file-mounts:

``file_mounts``
~~~~~~~~~~~~~~~

The files or directories to copy to the head and worker nodes.

* **Required:** No
* **Importance:** High
* **Type:** :ref:`File mounts <cluster-configuration-file-mounts-type>`
* **Default:** ``[]``

.. _cluster-configuration-cluster-synced-files:

``cluster_synced_files``
~~~~~~~~~~~~~~~~~~~~~~~~

A list of paths to the files or directories to copy from the head node to the worker nodes. The same path on the head node will be copied to the worker node. This behavior is a subset of the file_mounts behavior, so in the vast majority of cases one should just use :ref:`file_mounts <cluster-configuration-file-mounts>`.

* **Required:** No
* **Importance:** Low
* **Type:** List of String
* **Default:** ``[]``

.. _cluster-configuration-rsync-exclude:

``rsync_exclude``
~~~~~~~~~~~~~~~~~

A list of patterns for files to exclude when running ``rsync up`` or ``rsync down``. The filter is applied on the source directory only.

Example for a pattern in the list: ``**/.git/**``.

* **Required:** No
* **Importance:** Low
* **Type:** List of String
* **Default:** ``[]``

.. _cluster-configuration-rsync-filter:

``rsync_filter``
~~~~~~~~~~~~~~~~

A list of patterns for files to exclude when running ``rsync up`` or ``rsync down``. The filter is applied on the source directory and recursively through all subdirectories.

Example for a pattern in the list: ``.gitignore``.

* **Required:** No
* **Importance:** Low
* **Type:** List of String
* **Default:** ``[]``

.. _cluster-configuration-initialization-commands:

``initialization_commands``
~~~~~~~~~~~~~~~~~~~~~~~~~~~

A list of commands that will be run before the :ref:`setup commands <cluster-configuration-setup-commands>`. If Docker is enabled, these commands will run outside the container and before Docker is setup.

* **Required:** No
* **Importance:** Medium
* **Type:** List of String
* **Default:** ``[]``

.. _cluster-configuration-setup-commands:

``setup_commands``
~~~~~~~~~~~~~~~~~~

A list of commands to run to set up nodes. These commands will always run on the head and worker nodes and will be merged with :ref:`head setup commands <cluster-configuration-head-setup-commands>` for head and with :ref:`worker setup commands <cluster-configuration-worker-setup-commands>` for workers.

* **Required:** No
* **Importance:** Medium
* **Type:** List of String
* **Default:**

.. tabs::
    .. group-tab:: AWS

        .. code-block:: yaml

            # Default setup_commands:
            setup_commands:
              - echo 'export PATH="$HOME/anaconda3/envs/tensorflow_p36/bin:$PATH"' >> ~/.bashrc
              - pip install -U https://s3-us-west-2.amazonaws.com/ray-wheels/latest/ray-2.0.0.dev0-cp36-cp36m-manylinux2014_x86_64.whl

- Setup commands should ideally be *idempotent* (i.e., can be run multiple times without changing the result); this allows Ray to safely update nodes after they have been created. You can usually make commands idempotent with small modifications, e.g. ``git clone foo`` can be rewritten as ``test -e foo || git clone foo`` which checks if the repo is already cloned first.

- Setup commands are run sequentially but separately. For example, if you are using anaconda, you need to run ``conda activate env && pip install -U ray`` because splitting the command into two setup commands will not work.

- Ideally, you should avoid using setup_commands by creating a docker image with all the dependencies preinstalled to minimize startup time.

- **Tip**: if you also want to run apt-get commands during setup add the following list of commands:

    .. code-block:: yaml

        setup_commands:
          - sudo pkill -9 apt-get || true
          - sudo pkill -9 dpkg || true
          - sudo dpkg --configure -a

.. _cluster-configuration-head-setup-commands:

``head_setup_commands``
~~~~~~~~~~~~~~~~~~~~~~~

A list of commands to run to set up the head node. These commands will be merged with the general :ref:`setup commands <cluster-configuration-setup-commands>`.

* **Required:** No
* **Importance:** Low
* **Type:** List of String
* **Default:** ``[]``

.. _cluster-configuration-worker-setup-commands:

``worker_setup_commands``
~~~~~~~~~~~~~~~~~~~~~~~~~

A list of commands to run to set up the worker nodes. These commands will be merged with the general :ref:`setup commands <cluster-configuration-setup-commands>`.

* **Required:** No
* **Importance:** Low
* **Type:** List of String
* **Default:** ``[]``

.. _cluster-configuration-head-start-ray-commands:

``head_start_ray_commands``
~~~~~~~~~~~~~~~~~~~~~~~~~~~

Commands to start ray on the head node. You don't need to change this.

* **Required:** No
* **Importance:** Low
* **Type:** List of String
* **Default:**

.. tabs::
    .. group-tab:: AWS

        .. code-block:: yaml

            head_start_ray_commands:
              - ray stop
              - ulimit -n 65536; ray start --head --port=6379 --object-manager-port=8076 --autoscaling-config=~/ray_bootstrap_config.yaml

.. _cluster-configuration-worker-start-ray-commands:

``worker_start_ray_commands``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Command to start ray on worker nodes. You don't need to change this.

* **Required:** No
* **Importance:** Low
* **Type:** List of String
* **Default:**

.. tabs::
    .. group-tab:: AWS

        .. code-block:: yaml

            worker_start_ray_commands:
              - ray stop
              - ulimit -n 65536; ray start --address=$RAY_HEAD_IP:6379 --object-manager-port=8076

.. _cluster-configuration-image:

``docker.image``
~~~~~~~~~~~~~~~~

The default Docker image to pull in the head and worker nodes. This can be overridden by the :ref:`head_image <cluster-configuration-head-image>` and :ref:`worker_image <cluster-configuration-worker-image>` fields. If neither `image` nor (:ref:`head_image <cluster-configuration-head-image>` and :ref:`worker_image <cluster-configuration-worker-image>`) are specified, Ray will not use Docker.

* **Required:** Yes (If Docker is in use.)
* **Importance:** High
* **Type:** String

The Ray project provides Docker images on `DockerHub <https://hub.docker.com/u/rayproject>`_. The repository includes following images:

* ``rayproject/ray-ml:latest-gpu``: CUDA support, includes ML dependencies.
* ``rayproject/ray:latest-gpu``: CUDA support, no ML dependencies.
* ``rayproject/ray-ml:latest``: No CUDA support, includes ML dependencies.
* ``rayproject/ray:latest``: No CUDA support, no ML dependencies.

.. _cluster-configuration-head-image:

``docker.head_image``
~~~~~~~~~~~~~~~~~~~~~
Docker image for the head node to override the default :ref:`docker image <cluster-configuration-image>`.

* **Required:** No
* **Importance:** Low
* **Type:** String

.. _cluster-configuration-worker-image:

``docker.worker_image``
~~~~~~~~~~~~~~~~~~~~~~~
Docker image for the worker nodes to override the default :ref:`docker image <cluster-configuration-image>`.

* **Required:** No
* **Importance:** Low
* **Type:** String

.. _cluster-configuration-container-name:

``docker.container_name``
~~~~~~~~~~~~~~~~~~~~~~~~~

The name to use when starting the Docker container.

* **Required:** Yes (If Docker is in use.)
* **Importance:** Low
* **Type:** String
* **Default:** ray_container

.. _cluster-configuration-pull-before-run:

``docker.pull_before_run``
~~~~~~~~~~~~~~~~~~~~~~~~~~

If enabled, the latest version of image will be pulled when starting Docker. If disabled, ``docker run`` will only pull the image if no cached version is present.

* **Required:** No
* **Importance:** Medium
* **Type:** Boolean
* **Default:** ``True``

.. _cluster-configuration-run-options:

``docker.run_options``
~~~~~~~~~~~~~~~~~~~~~~

The extra options to pass to ``docker run``.

* **Required:** No
* **Importance:** Medium
* **Type:** List of String
* **Default:** ``[]``

.. _cluster-configuration-head-run-options:

``docker.head_run_options``
~~~~~~~~~~~~~~~~~~~~~~~~~~~

The extra options to pass to ``docker run`` for head node only.

* **Required:** No
* **Importance:** Low
* **Type:** List of String
* **Default:** ``[]``

.. _cluster-configuration-worker-run-options:

``docker.worker_run_options``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The extra options to pass to ``docker run`` for worker nodes only.

* **Required:** No
* **Importance:** Low
* **Type:** List of String
* **Default:** ``[]``

.. _cluster-configuration-disable-automatic-runtime-detection:

``docker.disable_automatic_runtime_detection``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If enabled, Ray will not try to use the NVIDIA Container Runtime if GPUs are present.

* **Required:** No
* **Importance:** Low
* **Type:** Boolean
* **Default:** ``False``

.. _cluster-configuration-disable-shm-size-detection:

``docker.disable_shm_size_detection``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If enabled, Ray will not automatically specify the size ``/dev/shm`` for the started container and the runtime's default value (64MiB for Docker) will be used.
If ``--shm-size=<>`` is manually added to ``run_options``, this is *automatically* set to ``True``, meaning that Ray will defer to the user-provided value.

* **Required:** No
* **Importance:** Low
* **Type:** Boolean
* **Default:** ``False``

.. _cluster-configuration-ssh-user:

``auth.ssh_user``
~~~~~~~~~~~~~~~~~

The user that Ray will authenticate with when launching new nodes.

* **Required:** Yes
* **Importance:** High
* **Type:** String

.. _cluster-configuration-ssh-private-key:

``auth.ssh_private_key``
~~~~~~~~~~~~~~~~~~~~~~~~

.. tabs::
    .. group-tab:: AWS

        The path to an existing private key for Ray to use. If not configured, Ray will create a new private keypair (default behavior). If configured, the key must be added to the project-wide metadata and ``KeyName`` has to be defined in the :ref:`node configuration <cluster-configuration-node-config>`.

        * **Required:** No
        * **Importance:** Low
        * **Type:** String

    .. group-tab:: Azure

        The path to an existing private key for Ray to use.

        * **Required:** Yes
        * **Importance:** High
        * **Type:** String

        You may use ``ssh-keygen -t rsa -b 4096`` to generate a new ssh keypair.

    .. group-tab:: GCP

        The path to an existing private key for Ray to use. If not configured, Ray will create a new private keypair (default behavior). If configured, the key must be added to the project-wide metadata and ``KeyName`` has to be defined in the :ref:`node configuration <cluster-configuration-node-config>`.

        * **Required:** No
        * **Importance:** Low
        * **Type:** String

.. _cluster-configuration-ssh-public-key:

``auth.ssh_public_key``
~~~~~~~~~~~~~~~~~~~~~~~

.. tabs::
    .. group-tab:: AWS

        Not available.

    .. group-tab:: Azure

        The path to an existing public key for Ray to use.

        * **Required:** Yes
        * **Importance:** High
        * **Type:** String

    .. group-tab:: GCP

        Not available.

.. _cluster-configuration-type:

``provider.type``
~~~~~~~~~~~~~~~~~

.. tabs::
    .. group-tab:: AWS

        The cloud service provider. For AWS, this must be set to ``aws``.

        * **Required:** Yes
        * **Importance:** High
        * **Type:** String

    .. group-tab:: Azure

        The cloud service provider. For Azure, this must be set to ``azure``.

        * **Required:** Yes
        * **Importance:** High
        * **Type:** String

    .. group-tab:: GCP

        The cloud service provider. For GCP, this must be set to ``gcp``.

        * **Required:** Yes
        * **Importance:** High
        * **Type:** String

.. _cluster-configuration-region:

``provider.region``
~~~~~~~~~~~~~~~~~~~

.. tabs::
    .. group-tab:: AWS

        The region to use for deployment of the Ray cluster.

        * **Required:** Yes
        * **Importance:** High
        * **Type:** String
        * **Default:** us-west-2

    .. group-tab:: Azure

        Not available.

    .. group-tab:: GCP

        The region to use for deployment of the Ray cluster.

        * **Required:** Yes
        * **Importance:** High
        * **Type:** String
        * **Default:** us-west1

.. _cluster-configuration-availability-zone:

``provider.availability_zone``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. tabs::
    .. group-tab:: AWS

        A string specifying a comma-separated list of availability zone(s) that nodes may be launched in.

        * **Required:** No
        * **Importance:** Low
        * **Type:** String
        * **Default:** us-west-2a,us-west-2b

    .. group-tab:: Azure

        Not available.

    .. group-tab:: GCP

        A string specifying a comma-separated list of availability zone(s) that nodes may be launched in.

        * **Required:** No
        * **Importance:** Low
        * **Type:** String
        * **Default:** us-west1-a

.. _cluster-configuration-location:

``provider.location``
~~~~~~~~~~~~~~~~~~~~~

.. tabs::
    .. group-tab:: AWS

        Not available.

    .. group-tab:: Azure

        The location to use for deployment of the Ray cluster.

        * **Required:** Yes
        * **Importance:** High
        * **Type:** String
        * **Default:** westus2

    .. group-tab:: GCP

        Not available.

.. _cluster-configuration-resource-group:

``provider.resource_group``
~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. tabs::
    .. group-tab:: AWS

        Not available.

    .. group-tab:: Azure

        The resource group to use for deployment of the Ray cluster.

        * **Required:** Yes
        * **Importance:** High
        * **Type:** String
        * **Default:** ray-cluster

    .. group-tab:: GCP

        Not available.

.. _cluster-configuration-subscription-id:

``provider.subscription_id``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. tabs::
    .. group-tab:: AWS

        Not available.

    .. group-tab:: Azure

        The subscription ID to use for deployment of the Ray cluster. If not specified, Ray will use the default from the Azure CLI.

        * **Required:** No
        * **Importance:** High
        * **Type:** String
        * **Default:** ``""``

    .. group-tab:: GCP

        Not available.

.. _cluster-configuration-project-id:

``provider.project_id``
~~~~~~~~~~~~~~~~~~~~~~~

.. tabs::
    .. group-tab:: AWS

        Not available.

    .. group-tab:: Azure

        Not available.

    .. group-tab:: GCP

        The globally unique project ID to use for deployment of the Ray cluster.

        * **Required:** Yes
        * **Importance:** Low
        * **Type:** String
        * **Default:** ``null``

.. _cluster-configuration-cache-stopped-nodes:

``provider.cache_stopped_nodes``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If enabled, nodes will be *stopped* when the cluster scales down. If disabled, nodes will be *terminated* instead. Stopped nodes launch faster than terminated nodes.

* **Required:** No
* **Importance:** Low
* **Type:** Boolean
* **Default:** ``True``

.. _cluster-configuration-node-config:

``available_node_types.<node_type_name>.node_type.node_config``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The configuration to be used to launch the nodes on the cloud service provider. Among other things, this will specify the instance type to be launched.

* **Required:** Yes
* **Importance:** High
* **Type:** :ref:`Node config <cluster-configuration-node-config-type>`

.. _cluster-configuration-resources:

``available_node_types.<node_type_name>.node_type.resources``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The resources that a node type provides, which enables the autoscaler to automatically select the right type of nodes to launch given the resource demands of the application. The resources specified will be automatically passed to the ``ray start`` command for the node via an environment variable. If not provided, Autoscaler can automatically detect them only for AWS/Kubernetes cloud providers. For more information, see also the `resource demand scheduler <https://github.com/ray-project/ray/blob/master/python/ray/autoscaler/_private/resource_demand_scheduler.py>`_

* **Required:** Yes (except for AWS/K8s)
* **Importance:** High
* **Type:** :ref:`Resources <cluster-configuration-resources-type>`
* **Default:** ``{}``

In some cases, adding special nodes without any resources may be desirable. Such nodes can be used as a driver which connects to the cluster to launch jobs. In order to manually add a node to an autoscaled cluster, the *ray-cluster-name* tag should be set and *ray-node-type* tag should be set to unmanaged. Unmanaged nodes can be created by setting the resources to ``{}`` and the :ref:`maximum workers <cluster-configuration-node-min-workers>` to 0. The Autoscaler will not attempt to start, stop, or update unmanaged nodes. The user is responsible for properly setting up and cleaning up unmanaged nodes.

.. _cluster-configuration-node-min-workers:

``available_node_types.<node_type_name>.node_type.min_workers``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The minimum number of workers to maintain for this node type regardless of utilization.

* **Required:** No
* **Importance:** High
* **Type:** Integer
* **Default:** ``0``
* **Minimum:** ``0``
* **Maximum:** Unbounded

.. _cluster-configuration-node-max-workers:

``available_node_types.<node_type_name>.node_type.max_workers``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The maximum number of workers to have in the cluster for this node type regardless of utilization. This takes precedence over :ref:`minimum workers <cluster-configuration-node-min-workers>`. By default, the number of workers of a node type is unbounded, constrained only by the cluster-wide :ref:`max_workers <cluster-configuration-max-workers>`. (Prior to Ray 1.3.0, the default value for this field was 0.)

* **Required:** No
* **Importance:** High
* **Type:** Integer
* **Default:** cluster-wide :ref:`max_workers <cluster-configuration-max-workers>`
* **Minimum:** ``0``
* **Maximum:** cluster-wide :ref:`max_workers <cluster-configuration-max-workers>`

.. _cluster-configuration-node-type-worker-setup-commands:

``available_node_types.<node_type_name>.node_type.worker_setup_commands``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A list of commands to run to set up worker nodes of this type. These commands will replace the general :ref:`worker setup commands <cluster-configuration-worker-setup-commands>` for the node.

* **Required:** No
* **Importance:** low
* **Type:** List of String
* **Default:** ``[]``

.. _cluster-configuration-cpu:

``available_node_types.<node_type_name>.node_type.resources.CPU``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. tabs::
    .. group-tab:: AWS

        The number of CPUs made available by this node. If not configured, Autoscaler can automatically detect them only for AWS/Kubernetes cloud providers.

        * **Required:** Yes (except for AWS/K8s)
        * **Importance:** High
        * **Type:** Integer

    .. group-tab:: Azure

        The number of CPUs made available by this node.

        * **Required:** Yes
        * **Importance:** High
        * **Type:** Integer

    .. group-tab:: GCP

        The number of CPUs made available by this node.

        * **Required:** No
        * **Importance:** High
        * **Type:** Integer

.. _cluster-configuration-gpu:

``available_node_types.<node_type_name>.node_type.resources.GPU``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. tabs::
    .. group-tab:: AWS

        The number of GPUs made available by this node. If not configured, Autoscaler can automatically detect them only for AWS/Kubernetes cloud providers.

        * **Required:** No
        * **Importance:** Low
        * **Type:** Integer

    .. group-tab:: Azure

        The number of GPUs made available by this node.

        * **Required:** No
        * **Importance:** High
        * **Type:** Integer

    .. group-tab:: GCP

        The number of GPUs made available by this node.

        * **Required:** No
        * **Importance:** High
        * **Type:** Integer

.. _cluster-configuration-memory:

``available_node_types.<node_type_name>.node_type.resources.memory``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. tabs::
    .. group-tab:: AWS

        The memory in bytes allocated for python worker heap memory on the node. If not configured, Autoscaler will automatically detect the amount of RAM on the node for AWS/Kubernetes and allocate 70% of it for the heap.

        * **Required:** No
        * **Importance:** Low
        * **Type:** Integer

    .. group-tab:: Azure

        The memory in bytes allocated for python worker heap memory on the node.

        * **Required:** No
        * **Importance:** High
        * **Type:** Integer

    .. group-tab:: GCP

        The memory in bytes allocated for python worker heap memory on the node.

        * **Required:** No
        * **Importance:** High
        * **Type:** Integer

 .. _cluster-configuration-object-store-memory:

``available_node_types.<node_type_name>.node_type.resources.object-store-memory``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. tabs::
    .. group-tab:: AWS

        The memory in bytes allocated for the object store on the node. If not configured, Autoscaler will automatically detect the amount of RAM on the node for AWS/Kubernetes and allocate 30% of it for the object store.

        * **Required:** No
        * **Importance:** Low
        * **Type:** Integer

    .. group-tab:: Azure

        The memory in bytes allocated for the object store on the node.

        * **Required:** No
        * **Importance:** High
        * **Type:** Integer

    .. group-tab:: GCP

        The memory in bytes allocated for the object store on the node.

        * **Required:** No
        * **Importance:** High
        * **Type:** Integer

.. _cluster-configuration-node-docker:

``available_node_types.<node_type_name>.docker``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A set of overrides to the top-level :ref:`Docker <cluster-configuration-docker>` configuration.

* **Required:** No
* **Importance:** Low
* **Type:** :ref:`docker <cluster-configuration-node-docker-type>`
* **Default:** ``{}``

Examples
--------

Minimal configuration
~~~~~~~~~~~~~~~~~~~~~

.. tabs::
    .. group-tab:: AWS

        .. literalinclude:: ../../../python/ray/autoscaler/aws/example-minimal.yaml
            :language: yaml

    .. group-tab:: Azure

        .. literalinclude:: ../../../python/ray/autoscaler/azure/example-minimal.yaml
            :language: yaml

    .. group-tab:: GCP

        .. literalinclude:: ../../../python/ray/autoscaler/gcp/example-minimal.yaml
            :language: yaml

Full configuration
~~~~~~~~~~~~~~~~~~

.. tabs::
    .. group-tab:: AWS

        .. literalinclude:: ../../../python/ray/autoscaler/aws/example-full.yaml
            :language: yaml

    .. group-tab:: Azure

        .. literalinclude:: ../../../python/ray/autoscaler/azure/example-full.yaml
            :language: yaml

    .. group-tab:: GCP

        .. literalinclude:: ../../../python/ray/autoscaler/gcp/example-full.yaml
            :language: yaml


text:
import subprocess
sp = subprocess.Popen(['cargo', 'run', '--example', 'hello'], stdout=subprocess.PIPE)
stdout = sp.communicate()[0].decode("utf-8")
lines = stdout.splitlines()
assert lines == ["life before main", "main"], "got %s" % lines
print("Test Passed")


text:
"""Test the generic data encoding and decoding module."""
import json

import pytest

import ipfshttpclient.encoding
import ipfshttpclient.exceptions

@pytest.fixture
def json_encoder():
	return ipfshttpclient.encoding.Json()

def test_json_parse(json_encoder):
	"""Asserts parsed key/value json matches expected output."""
	data = {'key': 'value'}
	raw = json.dumps(data).encode("utf-8")
	res = json_encoder.parse(raw)
	assert res['key'] == 'value'

def test_json_parse_partial(json_encoder):
	"""Tests if feeding parts of JSON strings in the right order to the JSON parser produces the right results."""
	data1 = {'key1': 'value1'}
	data2 = {'key2': 'value2'}

	# Try single fragmented data set
	data1_binary = json.dumps(data1).encode("utf-8")
	assert list(json_encoder.parse_partial(data1_binary[:8])) == []
	assert list(json_encoder.parse_partial(data1_binary[8:])) == [data1]
	assert list(json_encoder.parse_finalize()) == []

	# Try multiple data sets contained in whitespace
	data2_binary = json.dumps(data2).encode("utf-8")
	data2_final  = b"  " + data1_binary + b"  \r\n  " + data2_binary + b"  "
	assert list(json_encoder.parse_partial(data2_final)) == [data1, data2]
	assert list(json_encoder.parse_finalize()) == []

	# String containing broken UTF-8
	with pytest.raises(ipfshttpclient.exceptions.DecodingError):
		list(json_encoder.parse_partial(b'{"hello": "\xc3ber world!"}'))
	assert list(json_encoder.parse_finalize()) == []

def test_json_with_newlines(json_encoder):
	"""Tests if feeding partial JSON strings with line breaks behaves as expected."""
	data1 = '{"key1":\n"value1",\n'
	data2 = '"key2":\n\n\n"value2"\n}'

	data_expected = json.loads(data1 + data2)

	assert list(json_encoder.parse_partial(data1.encode("utf-8"))) == []
	assert list(json_encoder.parse_partial(data2.encode("utf-8"))) == [data_expected]
	assert list(json_encoder.parse_finalize()) == []

def test_json_parse_incomplete(json_encoder):
	"""Tests if feeding the JSON parse incomplete data correctly produces an error."""
	list(json_encoder.parse_partial(b'{"bla":'))
	with pytest.raises(ipfshttpclient.exceptions.DecodingError):
		json_encoder.parse_finalize()

	list(json_encoder.parse_partial(b'{"\xc3')) # Incomplete UTF-8 sequence
	with pytest.raises(ipfshttpclient.exceptions.DecodingError):
		json_encoder.parse_finalize()

def test_json_parse_chained(json_encoder):
	"""Tests if concatenated string of JSON object is being parsed correctly."""
	data1 = {'key1': 'value1'}
	data2 = {'key2': 'value2'}
	res = json_encoder.parse(
		json.dumps(data1).encode("utf-8") + json.dumps(data2).encode("utf-8")
	)
	assert len(res) == 2
	assert res[0]['key1'] == 'value1'
	assert res[1]['key2'] == 'value2'

def test_json_parse_chained_newlines(json_encoder):
	"""Tests parsing of concatenated string of JSON object containing a new line."""
	data1 = {'key1': 'value1'}
	data2 = {'key2': 'value2'}
	res = json_encoder.parse(
		json.dumps(data1).encode("utf-8") + b'\n' + json.dumps(data2).encode("utf-8")
	)
	assert len(res) == 2
	assert res[0]['key1'] == 'value1'
	assert res[1]['key2'] == 'value2'

def test_json_encode(json_encoder):
	"""Tests serilization of an object into a json formatted UTF-8 string."""
	data = {'key': 'value with Ünicøde characters ☺'}
	assert json_encoder.encode(data) == \
	       b'{"key":"value with \xc3\x9cnic\xc3\xb8de characters \xe2\x98\xba"}'

def test_get_encoder_by_name():
	"""Tests the process of obtaining an Encoder object given the named encoding."""
	encoder = ipfshttpclient.encoding.get_encoding('json')
	assert encoder.name == 'json'

def test_get_invalid_encoder():
	"""Tests the exception handling given an invalid named encoding."""
	with pytest.raises(ipfshttpclient.exceptions.EncoderMissingError):
		ipfshttpclient.encoding.get_encoding('fake')


text: ~/.openmpi/bin/mpirun --ompi-server file:ompi-server.txt -n 1 python job_manager.py --cmd stop


text:
find_path(XV_INCLUDE_DIR NAMES X11/extensions/Xv.h
          PATH_SUFFIXES X11/extensions
          DOC "The Xv include directory"
)

find_library(XV_LIBRARY NAMES Xv
          DOC "The Xv library"
)

include(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Xv DEFAULT_MSG XV_LIBRARY XV_INCLUDE_DIR)

if(XV_FOUND)
  set( XV_LIBRARIES ${XV_LIBRARY} )
  set( XV_INCLUDE_DIRS ${XV_INCLUDE_DIR} )
endif()

mark_as_advanced(XV_INCLUDE_DIR XV_LIBRARY)


text:
cask "enpass" do
  version "6.6.1.809"
  sha256 "9f8e3e60faab1d233497636ec1ce31f2f81e21ead62c88f39c0ba19eaa0e9cdf"

  url "https://dl.enpass.io/stable/mac/package/#{version}/Enpass.pkg"
  name "Enpass"
  desc "Password and credentials mananger"
  homepage "https://www.enpass.io/"

  livecheck do
    url "https://www.enpass.io/downloads/"
    regex(%r{href=.*?/(\d+(?:\.\d+)*)/Enpass\.pkg}i)
  end

  depends_on macos: ">= :sierra"

  pkg "Enpass.pkg"

  uninstall pkgutil: "in.sinew.Enpass-Desktop.App"

  zap trash: [
    "~/Library/Caches/com.plausiblelabs.crashreporter.data/in.sinew.Enpass-Desktop",
    "~/Library/Caches/in.sinew.Enpass-Desktop",
    "~/Library/Preferences/in.sinew.Enpass-Desktop.plist",
    "~/Library/Saved Application State/in.sinew.Enpass-Desktop.savedState",
  ]
end


text:
require "win32/daemon"

class SpecService < ::Win32::Daemon
  def service_init
    @test_service_file = "#{ENV['TMP']}/spec_service_file"
  end

  def service_main(*startup_parameters)
    while running?
      if !File.exists?(@test_service_file)
        File.open(@test_service_file, "wb") do |f|
          f.write("This file is created by SpecService")
        end
      end

      sleep 1
    end
  end

  ################################################################################
  # Control Signal Callback Methods
  ################################################################################

  def service_stop
  end

  def service_pause
  end

  def service_resume
  end

  def service_shutdown
  end
end

# To run this file as a service, it must be called as a script from within
# the Windows Service framework.  In that case, kick off the main loop!
if __FILE__ == $0
  SpecService.mainloop
end


text:
namespace DX
{
    class AnimationSDKMESH
    {
    public:
        AnimationSDKMESH() noexcept;
        ~AnimationSDKMESH() = default;

        AnimationSDKMESH(AnimationSDKMESH&&) = default;
        AnimationSDKMESH& operator= (AnimationSDKMESH&&) = default;

        AnimationSDKMESH(AnimationSDKMESH const&) = delete;
        AnimationSDKMESH& operator= (AnimationSDKMESH const&) = delete;

        HRESULT Load(_In_z_ const wchar_t* fileName);

        void Release()
        {
            m_animTime = 0.0;
            m_animSize = 0;
            m_animData.reset();
            m_boneToTrack.clear();
            m_animBones.reset();
        }

        bool Bind(const DirectX::Model& model);

        void Update(float delta);

        void Apply(
            const DirectX::Model& model,
            size_t nbones,
            _Out_writes_(nbones) DirectX::XMMATRIX* boneTransforms) const;

    private:
        double                              m_animTime;
        std::unique_ptr<uint8_t[]>          m_animData;
        size_t                              m_animSize;
        std::vector<uint32_t>               m_boneToTrack;
        DirectX::ModelBone::TransformArray  m_animBones;
    };

    class AnimationCMO
    {
    public:
        AnimationCMO() noexcept;
        ~AnimationCMO() = default;

        AnimationCMO(AnimationCMO&&) = default;
        AnimationCMO& operator= (AnimationCMO&&) = default;

        AnimationCMO(AnimationCMO const&) = delete;
        AnimationCMO& operator= (AnimationCMO const&) = delete;

        HRESULT Load(_In_z_ const wchar_t* fileName, size_t offset, _In_opt_z_ const wchar_t* clipName = nullptr);

        void Release()
        {
            m_animTime = m_startTime = m_endTime = 0.f;
            m_keys.clear();
            m_transforms.reset();
            m_animBones.reset();
        }

        void Bind(const DirectX::Model& model);

        void Update(float delta);

        void Apply(
            const DirectX::Model& model,
            size_t nbones,
            _Out_writes_(nbones) DirectX::XMMATRIX* boneTransforms) const;

    private:
        using Key = std::pair<uint32_t, float>;

        float                               m_animTime;
        float                               m_startTime;
        float                               m_endTime;
        std::vector<Key>                    m_keys;
        DirectX::ModelBone::TransformArray  m_transforms;
        DirectX::ModelBone::TransformArray  m_animBones;
    };
}


text:
"""Integration platform for recorder."""
from __future__ import annotations

from homeassistant.core import HomeAssistant, callback

from . import ATTR_MAX_TEMP, ATTR_MIN_TEMP, ATTR_OPERATION_LIST

@callback
def exclude_attributes(hass: HomeAssistant) -> set[str]:
    """Exclude static attributes from being recorded in the database."""
    return {ATTR_OPERATION_LIST, ATTR_MIN_TEMP, ATTR_MAX_TEMP}


text:
enum CFO_TYPE
{
#define ADD(a,b) CFO_##a,
#include "../tables/CSFileObjContainer_props.tbl"
#undef ADD
    CFO_QTY
};

lpctstr const CSFileObjContainer::sm_szLoadKeys[CFO_QTY+1] =
{
#define ADD(a,b) b,
#include "../tables/CSFileObjContainer_props.tbl"
#undef ADD
    nullptr
};

enum CFOV_TYPE
{
#define ADD(a,b) CFOV_##a,
#include "../tables/CSFileObjContainer_functions.tbl"
#undef ADD
    CFOV_QTY
};

lpctstr const CSFileObjContainer::sm_szVerbKeys[CFOV_QTY+1] =
{
#define ADD(a,b) b,
#include "../tables/CSFileObjContainer_functions.tbl"
#undef ADD
    nullptr
};

void CSFileObjContainer::ResizeContainer( size_t iNewRange )
{
    ADDTOCALLSTACK("CSFileObjContainer::ResizeContainer");
    if ( iNewRange == sFileList.size() )
    {
        return;
    }

    bool bDeleting = ( iNewRange < sFileList.size() );
    int howMuch = (int)(iNewRange - sFileList.size());
    if ( howMuch < 0 )
    {
        howMuch = (-howMuch);
    }

    if ( bDeleting )
    {
        if ( sFileList.empty() )
        {
            return;
        }

        CSFileObj * pObjHolder = nullptr;

        for ( size_t i = (sFileList.size() - 1); howMuch > 0; --howMuch, --i )
        {
            pObjHolder = sFileList.at(i);
            sFileList.pop_back();

            if ( pObjHolder )
            {
                delete pObjHolder;
            }
        }
    }
    else
    {
        for ( int i = 0; i < howMuch; ++i )
        {
            sFileList.emplace_back();
        }
    }
}

CSFileObjContainer::CSFileObjContainer()
{
    iGlobalTimeout = iCurrentTick = 0;
    SetFilenumber(0);
}

CSFileObjContainer::~CSFileObjContainer()
{
    ResizeContainer(0);
    sFileList.clear();
}

int CSFileObjContainer::GetFilenumber()
{
    ADDTOCALLSTACK("CSFileObjContainer::GetFilenumber");
    return iFilenumber;
}

void CSFileObjContainer::SetFilenumber( int iHowMuch )
{
    ADDTOCALLSTACK("CSFileObjContainer::SetFilenumber");
    ResizeContainer(iHowMuch);
    iFilenumber = iHowMuch;
}

bool CSFileObjContainer::OnTick()
{
    ADDTOCALLSTACK("CSFileObjContainer::OnTick");
    EXC_TRY("Tick");

    if ( !iGlobalTimeout )
        return true;

    if ( ++iCurrentTick >= iGlobalTimeout )
    {
        iCurrentTick = 0;

        for ( std::vector<CSFileObj *>::iterator i = sFileList.begin(); i != sFileList.end(); ++i )
        {
            if ( !(*i)->OnTick() )
            {
                // Error and fixweirdness
            }
        }
    }

    return true;
    EXC_CATCH;

    //EXC_DEBUG_START;
    //EXC_DEBUG_END;
    return false;
}

int CSFileObjContainer::FixWeirdness()
{
    ADDTOCALLSTACK("CSFileObjContainer::FixWeirdness");
    return 0;
}

bool CSFileObjContainer::r_GetRef( lpctstr & ptcKey, CScriptObj * & pRef )
{
    ADDTOCALLSTACK("CSFileObjContainer::r_GetRef");
    if ( !strnicmp("FIRSTUSED.",ptcKey,10) )
    {
        ptcKey += 10;

        CSFileObj * pFirstUsed = nullptr;
        for ( std::vector<CSFileObj *>::iterator i = sFileList.begin(); i != sFileList.end(); ++i )
        {
            if ( (*i)->IsInUse() )
            {
                pFirstUsed = (*i);
                break;
            }
        }

        if ( pFirstUsed != nullptr )
        {
            pRef = pFirstUsed;
            return true;
        }
    }
    else
    {
        size_t nNumber = (size_t)( Exp_GetVal(ptcKey) );
        SKIP_SEPARATORS(ptcKey);

        if ( nNumber >= sFileList.size() )
            return false;

        CSFileObj * pFile = sFileList.at(nNumber);

        if ( pFile != nullptr )
        {
            pRef = pFile;
            return true;
        }
    }

    return false;
}

bool CSFileObjContainer::r_LoadVal( CScript & s )
{
    ADDTOCALLSTACK("CSFileObjContainer::r_LoadVal");
    EXC_TRY("LoadVal");
    lpctstr ptcKey = s.GetKey();

    int index = FindTableSorted( ptcKey, sm_szLoadKeys, CountOf( sm_szLoadKeys )-1 );

    switch ( index )
    {
        case CFO_OBJECTPOOL:
            SetFilenumber(s.GetArgVal());
            break;

        case CFO_GLOBALTIMEOUT:
            iGlobalTimeout = (int64)llabs(s.GetArgLLVal()*MSECS_PER_SEC);
            break;

        default:
            return false;
    }

    return true;
    EXC_CATCH;

    EXC_DEBUG_START;
    EXC_ADD_SCRIPT;
    EXC_DEBUG_END;
    return false;
}

bool CSFileObjContainer::r_WriteVal( lpctstr ptcKey, CSString &sVal, CTextConsole * pSrc, bool fNoCallParent, bool fNoCallChildren )
{
    UNREFERENCED_PARAMETER(fNoCallChildren);
    ADDTOCALLSTACK("CSFileObjContainer::r_WriteVal");
    EXC_TRY("WriteVal");

    if ( !strnicmp("FIRSTUSED.",ptcKey,10) )
    {
        ptcKey += 10;

        CSFileObj * pFirstUsed = nullptr;
        for ( std::vector<CSFileObj *>::iterator i = sFileList.begin(); i != sFileList.end(); ++i )
        {
            if ( (*i)->IsInUse() )
            {
                pFirstUsed = (*i);
                break;
            }
        }

        if ( pFirstUsed != nullptr )
        {
            return static_cast<CScriptObj *>(pFirstUsed)->r_WriteVal(ptcKey, sVal, pSrc);
        }

        return false;
    }

    int iIndex = FindTableHeadSorted( ptcKey, sm_szLoadKeys, CountOf( sm_szLoadKeys )-1 );

    if ( iIndex < 0 )
    {
        if (!fNoCallParent)
        {
            uint nNumber = Exp_GetUVal(ptcKey);
            SKIP_SEPARATORS(ptcKey);

            if ( nNumber >= sFileList.size() )
                return false;

            CSFileObj * pFile = sFileList[nNumber];
            if ( pFile != nullptr )
            {
                CScriptObj * pObj = dynamic_cast<CScriptObj*>( pFile );
                if (pObj != nullptr)
                    return pObj->r_WriteVal(ptcKey, sVal, pSrc);
            }
        }

        return false;
    }

    switch ( iIndex )
    {
        case CFO_OBJECTPOOL:
            sVal.FormatVal( GetFilenumber() );
            break;

        case CFO_GLOBALTIMEOUT:
            sVal.FormatLLVal(iGlobalTimeout/MSECS_PER_SEC);
            break;

        default:
            return false;
    }

    return true;
    EXC_CATCH;

    EXC_DEBUG_START;
    EXC_ADD_KEYRET(pSrc);
    EXC_DEBUG_END;
    return false;
}

bool CSFileObjContainer::r_Verb( CScript & s, CTextConsole * pSrc )
{
    ADDTOCALLSTACK("CSFileObjContainer::r_Verb");
    EXC_TRY("Verb");
    ASSERT(pSrc);

    lpctstr ptcKey = s.GetKey();

    if ( !strnicmp("FIRSTUSED.",ptcKey,10) )
    {
        ptcKey += 10;

        CSFileObj * pFirstUsed = nullptr;
        for ( std::vector<CSFileObj *>::iterator i = sFileList.begin(); i != sFileList.end(); ++i )
        {
            if ( (*i)->IsInUse() )
            {
                pFirstUsed = (*i);
                break;
            }
        }

        if ( pFirstUsed != nullptr )
            return static_cast<CScriptObj *>(pFirstUsed)->r_Verb(s,pSrc);

        return false;
    }

    int index = FindTableSorted( ptcKey, sm_szVerbKeys, CountOf( sm_szVerbKeys )-1 );

    if ( index < 0 )
    {
        if ( strchr( ptcKey, '.') ) // 0.blah format
        {
            size_t nNumber = Exp_GetSTVal(ptcKey);
            if ( nNumber < sFileList.size() )
            {
                CSFileObj * pFile = sFileList.at(nNumber);
                if ( pFile != nullptr )
                {
                    CScriptObj* pObj = dynamic_cast<CScriptObj*>(pFile);
                    if (pObj != nullptr)
                    {
                        SKIP_SEPARATORS(ptcKey);
                        CScript script(ptcKey, s.GetArgStr());
                        script.m_iResourceFileIndex = s.m_iResourceFileIndex;	// Index in g_Cfg.m_ResourceFiles of the CResourceScript (script file) where the CScript originated
                        script.m_iLineNum = s.m_iLineNum;						// Line in the script file where Key/Arg were read
                        return pObj->r_Verb(script, pSrc);
                    }
                }

                return false;
            }
        }

        return ( this->r_LoadVal( s ) );
    }

    switch ( index )
    {
        case CFOV_CLOSEOBJECT:
        case CFOV_RESETOBJECT:
        {
            bool bResetObject = ( index == CFOV_RESETOBJECT );
            if ( s.HasArgs() )
            {
                size_t nNumber = (size_t)( s.GetArgVal() );
                if ( nNumber >= sFileList.size() )
                    return false;

                CSFileObj * pObjVerb = sFileList.at(nNumber);
                if ( bResetObject )
                {
                    delete pObjVerb;
                    sFileList.at(nNumber) = new CSFileObj();
                }
                else
                {
                    pObjVerb->FlushAndClose();
                }
            }
        } break;

        default:
            return false;
    }

    return true;
    EXC_CATCH;

    EXC_DEBUG_START;
    EXC_ADD_SCRIPTSRC;
    EXC_DEBUG_END;
    return false;
}


text:
<?php namespace Tuurbo\Spreedly\Exceptions;

class MissingPaymentTokenException extends \Exception {

	public function __construct($message = 'Payment token is required', $code = 0)
	{
		parent::__construct($message, $code);
	}

}


text:
package com.ozodrukh.instant.eclass.accounts;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StyleRes;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.TextViewCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.BounceInterpolator;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.ozodrukh.eclass.InhaEclassController;
import com.ozodrukh.eclass.InhaEclassWebService;
import com.ozodrukh.eclass.InhaSessionEncoder;
import com.ozodrukh.eclass.Timber;
import com.ozodrukh.eclass.entity.User;
import com.ozodrukh.instant.eclass.BaseFragment;
import com.ozodrukh.instant.eclass.R;
import com.ozodrukh.instant.eclass.utils.AndroidUtils;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import retrofit2.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

public class LoginEclassFragment extends BaseFragment {

  /** Provides access to signed user when he was authenticated in Application */
  public static final String KEY_USER = "arg:user";

  public static final String TAG = "fragment:sign-in";

  private View signInForm;
  private View signInButton;
  private EditText userIdView;
  private EditText userPasswordView;
  private TextView loginStatusView;
  private ProgressBar progressBar;

  private Deque<Snackbar> snackBarQueue = new ArrayDeque<>();

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.eclass_login_fragmnet, container, false);
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    userIdView = (EditText) view.findViewById(R.id.user_id);
    userPasswordView = (EditText) view.findViewById(R.id.password);
    signInForm = view.findViewById(R.id.sign_in_form);
    signInButton = view.findViewById(R.id.signIn);

    progressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
    loginStatusView = (TextView) view.findViewById(R.id.additional_subtitle);

    loginStatusView.setOnClickListener(new View.OnClickListener() {
      int clicksCounter = 0;

      @Override public void onClick(View v) {
        clicksCounter++;

        if (clicksCounter == 5) {
          clicksCounter = 0;
          showSnackbar("Hey, dude, here is no eastern eggs:)", Snackbar.LENGTH_LONG);
        }
      }
    });

    signInButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        if (Build.VERSION.SDK_INT >= 19) {
          signInButton.cancelPendingInputEvents();
        }

        setLoginFormEnabled(false);

        if (AndroidUtils.isNetworkAvailable(getContext())) {
          setAdditionalInformation(getString(R.string.eclass_signin_process_description),
              R.style.TextAppearance_AppTheme_Info, false);
        } else {
          setAdditionalInformation(getString(R.string.no_network_connection),
              R.style.TextAppearance_AppTheme_Error, true);

          setLoginFormEnabled(true);
          return;
        }

        Observable<Response<List<User>>> observable;
        if (!AndroidUtils.isNetworkAvailable(getContext())) {
          observable = Observable.empty();
        } else {
          observable = InhaEclassController.getInstance()
              .getWebService()
              .signIn(encode(userIdView), encode(userPasswordView), InhaEclassWebService.GR_CODE)
              .subscribeOn(Schedulers.io())
              .observeOn(AndroidSchedulers.mainThread())
              .compose(LoginEclassFragment.this.<Response<List<User>>>bindToLifecycle());
        }

        observable.filter(new Func1<Response<List<User>>, Boolean>() {
          @Override public Boolean call(Response<List<User>> users) {
            return users != null;
          }
        }).subscribe(new Action1<Response<List<User>>>() {
          @Override public void call(Response<List<User>> usersResponse) {
            final List<User> users = usersResponse.body();
            final String token = usersResponse.raw().header(InhaEclassWebService.KEY_TOKEN);

            if (users.isEmpty()) {
              setAdditionalInformation(getString(R.string.login_failed_user_not_found),
                  R.style.TextAppearance_AppTheme_Error, true);

              Timber.d("Users list is empty");
            } else {
              User user = users.get(0);
              Timber.d("Logged in as " + user.getName());

              if (user.isAuthenticated()) {
                onUserSignedIn(user, token);
              } else {
                Timber.e("User not found");

                setAdditionalInformation(getString(R.string.login_failed_user_not_found),
                    R.style.TextAppearance_AppTheme_Error, true);
              }

              setLoginFormEnabled(true);
            }
          }
        }, new Action1<Throwable>() {
          @Override public void call(Throwable e) {
            Timber.e(e, "Login failed");

            View view = getView();
            if (view == null) {
              return;
            }

            if (e instanceof IOException) {
              setLoginFormEnabled(true);

              showSnackbar(AndroidUtils.getExceptionDetailHumanReadableMessage(getContext(),
                  (IOException) e), Snackbar.LENGTH_LONG);
            } else {
              showSnackbar(e.getLocalizedMessage(), Snackbar.LENGTH_LONG);
            }
          }
        });
      }
    });
  }

  protected void showSnackbar(@NonNull CharSequence message, @Snackbar.Duration int length) {
    Snackbar snackbar = Snackbar.make((View) signInForm.getParent(), message, length);

    if (signInForm.getLayoutParams().width != MATCH_PARENT) {
      View snackBarLayout = snackbar.getView();
      ViewGroup parent = (ViewGroup) signInForm.getParent();
      FrameLayout.LayoutParams params =
          new FrameLayout.LayoutParams(parent.getWidth() - signInForm.getWidth(), WRAP_CONTENT);
      params.leftMargin = getResources().getDimensionPixelSize(R.dimen.snack_bar_margins);
      params.bottomMargin = params.rightMargin = params.leftMargin;
      params.width -= params.leftMargin * 2;
      params.gravity = Gravity.RIGHT | Gravity.BOTTOM;
      params.leftMargin += signInForm.getWidth();

      snackBarLayout.setLayoutParams(params);
    } else {
      snackbar.setCallback(snackBarCallback);
    }

    snackbar.show();
  }

  protected Snackbar.Callback snackBarCallback = new Snackbar.Callback() {
    @Override public void onDismissed(Snackbar snackbar, int event) {
      if (event != Snackbar.Callback.DISMISS_EVENT_MANUAL) {
        snackBarQueue.remove(snackbar);
      }
    }

    @Override public void onShown(Snackbar snackbar) {
      snackBarQueue.push(snackbar);
    }
  };

  boolean onBackPressed() {
    if (snackBarQueue.isEmpty()) {
      return false;
    } else {
      snackBarQueue.pop().dismiss();
      return true;
    }
  }

  /**
   * Called after authentication was succeed and user was found
   * using account manager we need save account in the system
   *
   * @param user User found in IUT E-class
   */
  protected void onUserSignedIn(User user, String token) {
    setAdditionalInformation(getString(R.string.login_proceed_welcome_tpl) + user.getName(),
        R.style.TextAppearance_AppTheme_Info, false);

    InhaEclassController.getInstance().setCurrentUser(user);

    Account account = new Account(user.getUserId(), EclassAuthenticator.ECLASS_USER);

    AccountManager manager = AccountManager.get(getContext());
    if (manager.addAccountExplicitly(account, userPasswordView.getText().toString(),
        EclassAuthenticator.getUserData(user))) {

      manager.setAuthToken(account, EclassAuthenticator.ECLASS_USER, token);
    }

    Intent intent = new Intent();
    intent.putExtra(KEY_USER, user);

    Activity hostActivity = getActivity();
    hostActivity.setResult(Activity.RESULT_OK, intent);
    hostActivity.finish();
  }

  /**
   * Returns encoded text from view
   *
   * @param view View with text to encode
   * @return Encoded text from TextView
   */
  private String encode(TextView view) {
    return InhaSessionEncoder.encode(view.getText().toString());
  }

  protected void setAdditionalInformation(CharSequence text, @StyleRes int textApperance,
      boolean shake) {
    loginStatusView.setText(text);

    TextViewCompat.setTextAppearance(loginStatusView, textApperance);

    if (loginStatusView.getVisibility() != View.VISIBLE) {
      loginStatusView.setVisibility(View.VISIBLE);
    }

    if (!shake) {
      loginStatusView.setScaleY(0.3f);
      loginStatusView.setAlpha(0.3f);
      loginStatusView.animate()
          .scaleY(1f)
          .alpha(1f)
          .setDuration(300)
          .setInterpolator(new AccelerateDecelerateInterpolator())
          .start();
    } else {
      ObjectAnimator shakeAnimator =
          ObjectAnimator.ofFloat(loginStatusView, View.TRANSLATION_X, 0, 100, -100, 0);
      shakeAnimator.setInterpolator(new BounceInterpolator());
      shakeAnimator.setDuration(575);
      shakeAnimator.start();
    }
  }

  protected void setLoginFormEnabled(boolean enabled) {
    signInButton.setEnabled(enabled);
    userIdView.setEnabled(enabled);
    userPasswordView.setEnabled(enabled);

    if (!enabled) {
      if (progressBar.getVisibility() != View.VISIBLE) {
        progressBar.setVisibility(View.VISIBLE);
      }

      progressBar.setScaleY(0.3f);
      progressBar.setAlpha(0.3f);
      progressBar.animate()
          .scaleY(1f)
          .alpha(1f)
          .setDuration(500)
          .setInterpolator(new AccelerateDecelerateInterpolator())
          .withEndAction(null)
          .start();
    } else {
      progressBar.animate()
          .scaleY(0f)
          .alpha(0f)
          .setDuration(500)
          .setInterpolator(new AccelerateDecelerateInterpolator())
          .withEndAction(new Runnable() {
            @Override public void run() {
              progressBar.setVisibility(View.INVISIBLE);
            }
          })
          .start();
    }
  }
}


text:
package com.heyzap.android.extension;

import com.adobe.fre.FREContext;
import com.adobe.fre.FREExtension;

public class Extension implements FREExtension
{
	public static FREContext context;

	@Override
	public FREContext createContext(String contextType)
	{
		if (context == null)
			context = new ExtensionContext();
		return context;
	}

	@Override
	public void dispose()
	{
	}

	@Override
	public void initialize()
	{
	}
}


text:
package com.thebuzzmedia.exiftool.exceptions;

import java.io.File;

/**
 * Exception thrown when a file cannot be written.
 * A file cannot be written because:
 * - It does not exist.
 * - It is corrupted and cannot be updated.
 */
public class UnwritableFileException extends AbstractExifException {

	/**
	 * Unwritable file.
	 */
	private final File file;

	/**
	 * Create exception.
	 *
	 * @param file Unwritable file.
	 * @param message Error message.
	 */
	public UnwritableFileException(File file, String message) {
		super(message);
		this.file = file;
	}

	/**
	 * Get {@link #file}
	 *
	 * @return {@link #file}
	 */
	public File getFile() {
		return file;
	}
}


text:
package com.wizzardo.tools.interfaces;

/**
 * Created by wizzardo on 15.11.15.
 */
public interface BiConsumer<A, B> {
    void consume(A a, B b);
}


text:
package org.ops4j.pax.exam.cm.internal;

import java.io.IOException;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.cm.ConfigurationEvent;
import org.osgi.service.cm.ConfigurationListener;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Tracks the {@link ConfigurationAdmin} and uses {@link ConfigurationListener} to be notified when
 * configuration changes
 */
public class ConfigurationOptionConfigurationListener implements ConfigurationListener,
    ServiceTrackerCustomizer<ConfigurationAdmin, ConfigurationAdmin> {

    private static final Logger LOG = LoggerFactory
        .getLogger(ConfigurationOptionConfigurationListener.class);

    private final Map<String, Object> properties;
    private final BundleContext context;
    private final String pid;
    private final boolean create;
    private final boolean override;
    private final boolean factory;

    private Configuration factoryConfiguration;

    public ConfigurationOptionConfigurationListener(String pid, Map<String, Object> properties,
        BundleContext context, boolean create, boolean override, boolean factory) {
        this.properties = properties;
        this.context = context;
        this.pid = pid;
        this.create = create;
        this.override = override;
        this.factory = factory;
    }

    @Override
    public void configurationEvent(ConfigurationEvent event) {
        if (!factory && override && event.getPid().equals(pid)) {
            ServiceReference<ConfigurationAdmin> reference = event.getReference();
            ConfigurationAdmin service = context.getService(reference);
            if (service != null) {
                try {
                    checkIfConfigurationNeeded(service);
                }
                finally {
                    context.ungetService(reference);
                }
            }
        }
    }

    /**
     * Check if an override of config values is needed for the given {@link ConfigurationAdmin}
     * service, since events can occur asycrounous we synchronized here to handle each event one by
     * one since this method might trigger other async events also...
     *
     * @param service
     *            the {@link ConfigurationAdmin} to check
     */
    private synchronized void checkIfConfigurationNeeded(ConfigurationAdmin service) {
        try {
            if (factory) {
                if (factoryConfiguration == null) {
                    factoryConfiguration = service.createFactoryConfiguration(pid, null);
                    factoryConfiguration.update(new Hashtable<String, Object>(properties));
                    LOG.info(
                        "Created new factory configuration for factory-pid {}, generated pid is {} with properties: {}",
                        new Object[] { pid, factoryConfiguration.getPid(), properties });
                }
            }
            else {
                Configuration configuration = service.getConfiguration(pid, null);
                Dictionary<String, Object> dictionary = configuration.getProperties();
                if (dictionary != null) {
                    boolean update = false;
                    Set<Entry<String, Object>> entrySet = properties.entrySet();
                    for (Entry<String, Object> entry : entrySet) {
                        Object object = dictionary.get(entry.getKey());
                        if (object == null) {
                            if (entry.getValue() == null) {
                                // Not changed...
                                continue;
                            }
                        }
                        else {
                            if (object.equals(entry.getValue())) {
                                // Not changed...
                                continue;
                            }
                        }
                        // A change is detected...
                        update = true;
                        dictionary.put(entry.getKey(), entry.getValue());
                    }
                    if (update) {
                        LOG.info("Update existing configuration for pid {} with properties: {}",
                            pid, dictToString(dictionary));
                        configuration.update(dictionary);
                    }
                }
                else {
                    if (create) {
                        configuration.update(new Hashtable<String, Object>(properties));
                        LOG.info("Created new configuration for pid {} with properties: {}", pid,
                            properties);
                    }
                }
            }
        }
        catch (IOException e) {
            LOG.warn("can't modify configuration for PID {}", pid, e);
        }
    }

    private static Object dictToString(Dictionary<String, Object> dictionary) {
        StringBuilder sb = new StringBuilder();
        Enumeration<String> keys = dictionary.keys();
        while (keys.hasMoreElements()) {
            if (sb.length() == 0) {
                sb.append("[");
            }
            else {
                sb.append(", ");
            }
            String key = keys.nextElement();
            sb.append(key);
            sb.append(": ");
            sb.append(dictionary.get(key));
        }
        return sb.append("]");
    }

    @Override
    public ConfigurationAdmin addingService(ServiceReference<ConfigurationAdmin> reference) {
        ConfigurationAdmin service = (ConfigurationAdmin) context.getService(reference);
        if (service != null) {
            checkIfConfigurationNeeded(service);
        }
        return service;
    }

    @Override
    public void modifiedService(ServiceReference<ConfigurationAdmin> reference, ConfigurationAdmin service) {
        // don't care
    }

    @Override
    public void removedService(ServiceReference<ConfigurationAdmin> reference, ConfigurationAdmin service) {
        if (factoryConfiguration != null) {
            // We delete it here, just in case the ConfigAdmin is restarted so we are not ending up
            // with two factory configs
            try {
                factoryConfiguration.delete();
            }
            catch (IOException e) {
                LOG.debug("Deleting factoryConfiguration failed", e);
            }
            catch (IllegalStateException e) {
                // Ignore... it was already deleted!
            }
        }
        context.ungetService(reference);
    }

}


text:
ACCEPTED

#### According to
Integrated Taxonomic Information System

#### Published in
Syn. fl. N. Amer. ed. 2, 1(2):448. 1886

#### Original name
null

### Remarks
null


text:
package org.springframework.content.renditions.config;

import org.springframework.content.commons.renditions.RenditionProvider;
import org.springframework.content.commons.renditions.RenditionService;
import org.springframework.content.renditions.renderers.PdfToJpegRenderer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import internal.org.springframework.content.commons.renditions.RenditionServiceImpl;

@Configuration
@ComponentScan(basePackageClasses=PdfToJpegRenderer.class)
public class RenditionsConfiguration {

    @Bean
    public RenditionService renditionService(RenditionProvider... providers) {
        return new RenditionServiceImpl(providers);
    }
}


text:
// ==++==
//
//   Copyright (c) Microsoft Corporation.  All rights reserved.
//
// ==--==
/*==========================================================================
**
** Interface:  IEnumerable
**
**
** Purpose:
** This interface is redefined here since the original IEnumerable interface
** has all its methods marked as ecall's since it is a managed standard
** interface. This interface is used from within the runtime to make a call
** on the COM server directly when it implements the IEnumerable interface.
**
**
==========================================================================*/
namespace System.Runtime.InteropServices.ComTypes
{
    using System;

    [Guid("496B0ABE-CDEE-11d3-88E8-00902754C43A")]
    internal interface IEnumerable
    {
        [DispId(-4)]
        System.Collections.IEnumerator GetEnumerator();
    }
}


text:
Sticky is a jQuery plugin that gives you the ability to make any element on your page always stay visible.

## Sticky in brief

This is how it works:

- When the target element is about to be hidden, the plugin will add the class `className` to it (and to a wrapper added as its parent), set it to `position: fixed` and calculate its new `top`, based on the element's height, the page height and the `topSpacing` and `bottomSpacing` options.
- That's it. In some cases you might need to set a fixed width to your element when it is "sticked". Check the `example-*.html` files for some examples.

## Usage

- Include jQuery & Sticky.
- Call Sticky.

```html
<script src="jquery.js"></script>
<script src="jquery.sticky.js"></script>
<script>
  $(document).ready(function(){
    $("#sticker").sticky({topSpacing:0});
  });
</script>
```

- Edit your css to position the elements (check the examples in `example-*.html`).

## Options

- `topSpacing`: Pixels between the page top and the element's top.
- `bottomSpacing`: Pixels between the page bottom and the element's bottom.
- `className`: CSS class added to the element and its wrapper when "sticked".
- `wrapperClassName`: CSS class added to the wrapper.
- `getWidthFrom`: Selector of element referenced to set fixed width of "sticky" element.

## Methods

- `sticky(options)`: Initializer. `options` is optional.
- `sticky('update')`: Recalculates the element's position.


text:
SELECT _allelepair_key, _genotype_key, _allele_key_1, _allele_key_2, allele1, allele2, allelestate
FROM gxd_allelepair_view


text:
package models

import (
	"testing"

	"github.com/wandoulabs/codis/pkg/utils/assert"
	"github.com/wandoulabs/zkhelper"
)

func TestSlots(t *testing.T) {
	fakeZkConn := zkhelper.NewConn()
	path := GetSlotBasePath(productName)
	children, _, _ := fakeZkConn.Children(path)
	assert.Must(len(children) == 0)

	err := InitSlotSet(fakeZkConn, productName, 1024)
	assert.MustNoError(err)

	children, _, _ = fakeZkConn.Children(path)
	assert.Must(len(children) == 1024)

	s, err := GetSlot(fakeZkConn, productName, 1)
	assert.MustNoError(err)

	assert.Must(s.GroupId == -1)

	g := NewServerGroup(productName, 1)
	g.Create(fakeZkConn)

	// test create new group
	_, err = ServerGroups(fakeZkConn, productName)
	assert.MustNoError(err)

	ok, err := g.Exists(fakeZkConn)
	assert.MustNoError(err)
	assert.Must(ok)

	err = SetSlotRange(fakeZkConn, productName, 0, 1023, 1, SLOT_STATUS_ONLINE)
	assert.MustNoError(err)

	s, err = GetSlot(fakeZkConn, productName, 1)
	assert.MustNoError(err)
	assert.Must(s.GroupId == 1)

	err = s.SetMigrateStatus(fakeZkConn, 1, 2)
	assert.MustNoError(err)
	assert.Must(s.GroupId == 2)
	assert.Must(s.State.Status == SLOT_STATUS_MIGRATE)
}


text:
REPORTER ?= spec
TESTS = $(shell find ./test/integration/* -name "*.test.js")
DIALECT ?= mysql

# test commands

teaser:
	@echo "" && \
	node -pe "Array(20 + '$(DIALECT)'.length + 3).join('#')" && \
	echo '# Running tests for $(DIALECT) #' && \
	node -pe "Array(20 + '$(DIALECT)'.length + 3).join('#')" && \
	echo ''

ifeq (true,$(COVERAGE))
test: codeclimate
else
test:
	make jshint && make teaser && make test-unit && make test-integration
	@if [ "$$GREP" ]; then \
		make jshint && make teaser && ./node_modules/mocha/bin/mocha --globals setImmediate,clearImmediate --ui tdd --check-leaks --colors -t 10000 --reporter $(REPORTER) -g "$$GREP" $(TESTS); \
	else \
		make jshint && make teaser && ./node_modules/mocha/bin/mocha --globals setImmediate,clearImmediate --ui tdd --check-leaks --colors -t 10000 --reporter $(REPORTER) $(TESTS); \
	fi
endif

# Unit tests
test-unit:
	./node_modules/mocha/bin/mocha --globals setImmediate,clearImmediate --ui tdd --check-leaks --colors -t 10000 --reporter $(REPORTER) ./test/unit/*.js ./test/unit/**/*.js

test-unit-all: test-unit-sqlite test-unit-mysql test-unit-postgres test-unit-postgres-native test-unit-mariadb test-unit-mssql

test-unit-mariadb:
	@DIALECT=mariadb make test-unit
test-unit-sqlite:
	@DIALECT=sqlite make test-unit
test-unit-mysql:
	@DIALECT=mysql make test-unit
test-unit-mssql:
	@DIALECT=mssql make test-unit
test-unit-postgres:
	@DIALECT=postgres make test-unit
test-unit-postgres-native:
	@DIALECT=postgres-native make test-unit

# Integration tests
test-integration:
	@if [ "$$GREP" ]; then \
		./node_modules/mocha/bin/mocha --globals setImmediate,clearImmediate --ui tdd --check-leaks --colors -t 10000 --reporter $(REPORTER) -g "$$GREP" $(TESTS); \
	else \
		./node_modules/mocha/bin/mocha --globals setImmediate,clearImmediate --ui tdd --check-leaks --colors -t 10000 --reporter $(REPORTER) $(TESTS); \
	fi

test-integration-all: test-integration-sqlite test-integration-mysql test-integration-postgres test-integration-postgres-native test-integration-mariadb test-integration-mssql

test-integration-mariadb:
	@DIALECT=mariadb make test-integration
test-integration-sqlite:
	@DIALECT=sqlite make test-integration
test-integration-mysql:
	@DIALECT=mysql make test-integration
test-integration-mssql:
	@DIALECT=mssql make test-integration
test-integration-postgres:
	@DIALECT=postgres make test-integration
test-integration-postgres-native:
	@DIALECT=postgres-native make test-integration

jshint:
	./node_modules/.bin/jshint lib test

mariadb:
	@DIALECT=mariadb make test
sqlite:
	@DIALECT=sqlite make test
mysql:
	@DIALECT=mysql make test
mssql:
	@DIALECT=mssql make test
postgres:
	@DIALECT=postgres make test
postgres-native:
	@DIALECT=postgres-native make test

# Coverage
cover:
	rm -rf coverage \
	make teaser && ./node_modules/.bin/istanbul cover ./node_modules/.bin/_mocha --report lcovonly -- -t 10000 --ui tdd $(TESTS); \

mariadb-cover:
	rm -rf coverage
	@DIALECT=mariadb make cover
	mv coverage coverage-mariadb
sqlite-cover:
	rm -rf coverage
	@DIALECT=sqlite make cover
	mv coverage coverage-sqlite
mysql-cover:
	rm -rf coverage
	@DIALECT=mysql make cover
	mv coverage coverage-mysql
postgres-cover:
	rm -rf coverage
	@DIALECT=postgres make cover
	mv coverage coverage-postgres
postgres-native-cover:
	rm -rf coverage
	@DIALECT=postgres-native make cover
	mv coverage coverage-postgresnative

merge-coverage:
	rm -rf coverage
	mkdir coverage
	./node_modules/.bin/lcov-result-merger 'coverage-*/lcov.info' 'coverage/lcov.info'

coveralls-send:
	cat ./coverage/lcov.info | ./node_modules/.bin/coveralls && rm -rf ./coverage*

codeclimate-send:
	npm install -g codeclimate-test-reporter
	CODECLIMATE_REPO_TOKEN=ce835a510bbf423a5ab5400a9bdcc2ec2d189d840b31657c6ee7cb9916b161d6 codeclimate < coverage/lcov.info

# test aliases

pgsql: postgres
postgresn: postgres-native

# test all the dialects \o/

all: sqlite mysql postgres postgres-native mariadb

all-cover: sqlite-cover mysql-cover postgres-cover postgres-native-cover mariadb-cover merge-coverage
coveralls: sqlite-cover mysql-cover postgres-cover postgres-native-cover mariadb-cover merge-coverage coveralls-send
codeclimate: sqlite-cover mysql-cover postgres-cover postgres-native-cover mariadb-cover merge-coverage codeclimate-send

.PHONY: sqlite mysql postgres pgsql postgres-native postgresn all test


text:
from motorengine import connect
from tornado import gen, ioloop
import config
from data.collections import School

@gen.coroutine
def create_schools():
    schools = [
        {'name': u'广州大学', 'verifier': u''},
        {'name': u'中山大学', 'verifier': u''},
        {'name': u'华南理工大学', 'verifier': u''},
    ]

    # School.objects.delete()
    for school in schools:
        yield School(**school).save()

@gen.coroutine
def init_db():
    yield create_schools()

    io_loop.stop()

if __name__ == '__main__':
    io_loop = ioloop.IOLoop.instance()
    connect(config.DB_NAME, host=config.DB_HOST, port=config.DB_PORT, io_loop=io_loop)
            #username=config.DB_USER, password=config.DB_PWD)

    io_loop.add_timeout(1, init_db)
    io_loop.start()


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package starchart;

import java.util.Arrays;

/**
 *
 * @author seeocon
 */
public class Star implements Comparable<Star> {

    // basic star attributes used to classify and describe the star
    private float x;
    private float y;
    private float z;
    private int henryDraper;
    private double magnitude;
    private int revisedNumber;
    private String[] constellation;
    private double radius;
    private double angle;

    /**
     * Star Object
     * @param x Coordinate
     * @param y Coordinate
     * @param z Coordinate
     * @param henryDraper Henry Draper
     * @param magnitude Magnitude of the star
     * @param revisedNumber The revised identification number
     * @param constellation The stars name used later for which constellation it belongs to
     */
    public Star(float x, float y, float z, int henryDraper, double magnitude, int revisedNumber, String[] constellation) {
        this.x = x;
        this.y = y;
        this.z = z;
        this.henryDraper = henryDraper;
        this.magnitude = magnitude;
        this.revisedNumber = revisedNumber;
        this.constellation = constellation;
        // Calculates the radius and angle for the rotation effect
        radius = Math.sqrt(Math.pow(x,2) + Math.pow(y,2));
        angle = Math.atan2(y,x);

    }

    // Getters and Setters... pointless to write javadocs
    public String[] getConstellation() {
        return constellation;
    }

    public void setConstellation(String[] constellation) {
        this.constellation = constellation;
    }

    public float getX() {
        return x;
    }

    public void setX(float x) {
        this.x = x;
    }

    public float getY() {
        return y;
    }

    public void setY(float y) {
        this.y = y;
    }

    public float getZ() {
        return z;
    }

    public void setZ(float z) {
        this.z = z;
    }

    public int getHenryDraper() {
        return henryDraper;
    }

    public void setHenryDraper(int henryDraper) {
        this.henryDraper = henryDraper;
    }

    public double getMagnitude() {
        return magnitude;
    }

    public void setMagnitude(double magnitude) {
        this.magnitude = magnitude;
    }

    public int getRevisedNumber() {
        return revisedNumber;
    }

    public void setRevisedNumber(int revisedNumber) {
        this.revisedNumber = revisedNumber;
    }

    public void setAngle(double angle) {
        this.angle = angle;
    }

    public double getRadius() {
        return radius;
    }

    public double getAngle() {
        return angle;
    }

    /**
     * Compares the star names of two star objects
     *
     * @param other the other object to compare it to
     * @return the sorted objects
     */
    @Override
    public int compareTo(Star other) {
        Star temp = (Star) other;
        return Arrays.toString(this.constellation).compareTo(Arrays.toString(temp.constellation));

    }

}