text:
Committer Guide
===============

New committer guidelines
------------------------

.. note::

    This section outlines steps which need to be completed by new team members and
    is indented for people who have been voted to join Libcloud project as a
    committer and / or PMC member. It also assumes you have already filled
    your ICLA and your Apache account has been created.

First congratulations and welcome to the team!

1. Subscribe to the public mailing lists
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If you haven't yet, subscribe to {dev,users,notifications}@libcloud.apache.org
mailing lists. Notifications mailing list is especially important because all of
Github Issue, Pull Request and build notifications are sent there.

2. Subscribe to the private mailing list
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Subscribe to private@libcloud.apache.org by sending an email to
private-subscribe@libcloud.apache.org. Keep in mind that this list is private
and your subscription needs to be approved by a moderator.

3. Create PyPi account
~~~~~~~~~~~~~~~~~~~~~~

Creating a PyPi account by going to
https://pypi.python.org/pypi?%3Aaction=register_form and send an email to
private@libcloud.apache.org requesting to be added as a maintainer to
`apache-libcloud <https://pypi.python.org/pypi/apache-libcloud/>`_ package.
Make sure to select a strong and unique password (``pwgen -s 48 1`` is your
friend).

After you have registered go to
"`Your details <https://pypi.python.org/pypi?%3Aaction=user_form>`_" page and
populate `PGP Key ID` field with your PGP key ID.

4. Link your ASF and Github account
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

We use Github for managing issues and user contributions (pull requests). As
such, you need to link your Github.com account with your ASF account using
`Gitbox <https://gitbox.apache.org/setup/>`_. This way you will get write
access to github.com/apache/libcloud repository and you will be able to
manage issues and pull request directly through our Github repository.

Merging user contributions
--------------------------

When a pull request with user contribution (changes) has been reviewed and
all the criteria for merging has been met (tests and code coverage, Travis
build is passing, user signed an ICLA, etc.), you can directly merge those
changes into trunk either by using Github web interface or doing it manually
on the command line.

It's also important that you update changelog in ``CHANGES.rst`` file after
you merged the changes.

Making a release (for release managers)
---------------------------------------

This section contains information a release manager should follow when
preparing a release.

0. Update committed files
~~~~~~~~~~~~~~~~~~~~~~~~~

* Make sure ``CHANGES`` file is up to date
* Make sure ``__version__`` string in ``libcloud/__init__.py`` is up to date
* Make sure ``version`` and ``release`` in ``docs/conf.py`` are up to date
* Update constants, pricing and other auto-generated data: ``tox -e scrape-ec2-sizes,scrape-ec2-prices``

1. Pre-release check list
~~~~~~~~~~~~~~~~~~~~~~~~~

* Make sure tests pass on all the supported Python versions (``tox``)
* Remove the ``tox`` directory with ``rm -rf .tox``
* Remove the _secrets_ file with ``rm libcloud/test/secrets.py``
* Remove leftover builds from previous releases. ``rm -f dist/apache* ; rm -rf apache_libcloud.egg-info``

2. Update Github
~~~~~~~~~~~~~~~~~

* Create a new Github milestone for the release in question (if one doesn't exist
  yet)
* Update affected issues and pull requests and add the corresponding release
  milestone to them

3. Creating release artifacts
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. note::

  It's important that you have the latest versions of ``setuptools``, ``wheel``
  and ``pip`` installed to ensure the generated wheel files contain correct
  metadata.

We have a script that runs the required setup.py commands and then hashes
and signs the files. You will need the latest version of ``pip`` and the ``wheel``
package. To run it:

.. sourcecode:: bash

    cd dist
    ./release.sh -u <yourusername>@apache.org

``-u`` argument will be used to find a key with a matching email address in
your local GPG database.

This should result in a set of
``apache-libcloud-${VERSION}.{tar.bz2,tar.gz,zip,whl}{,asc,md5,sha1}`` files that
are suitable to be uploaded for a release.

Copy the artifacts in another directory, unpack one of them and test it with ``tox``.

4. Tagging a release
~~~~~~~~~~~~~~~~~~~~

Tag the tentative release with a ``-tentative`` postfix.

.. sourcecode:: bash

    git tag <version> <commit hash>

For example:

.. sourcecode:: bash

    git tag --sign v0.15.0-tentative 105b9610835f99704996d861d613c5a9a8b3f8b1

5. Upload the release artifacts and start a [VOTE] thread
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Upload all release artifacts including the ``whl`` files to your people.apache.org
space. Then start a [VOTE] thread on the dev@libcloud.apache.org mailing list.

Once the vote has passed tag the release with a new tag, removing the ``-tentative`` postfix.
Upload the release artifacts to Apache servers and Pypi.

For example:

.. sourcecode:: bash

    git tag --sign v0.15.0 105b9610835f99704996d861d613c5a9a8b3f8b1

The commit SHA needs to be the one release artifacts are based on (aka the one
people voted on) and the same one you used for the ``-tentative`` tag.

Keep in mind that it's important that you sign the commit / tag with your GPG
key.

6. Uploading release artifacts to Apache servers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

* Add release artifacts to the dist SVN repository at
  https://dist.apache.org/repos/dist/release/libcloud/

  It may take up to a day for the artifacts to be available on all the
  Apache mirrors, but they should be instantly available at
  http://www.apache.org/dist/libcloud/.

* If there is more than one old release in the repository, delete rest of the
  old release and only leave current and previous release there. Old releases
  are automatically archived and available at
  https://dist.apache.org/repos/dist/release/libcloud/.

7. Publishing package to PyPi
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

We have a script that runs uploads the signed Python source files to PyPi. It uses twine, so ensure
you have twine available in your path `which twine` before running. Twine can be downloaded from https://pypi.python.org/pypi/twine

.. sourcecode:: bash

    cd dist
    ./deploy.sh

Once all the files have been uploaded, the page should look similar to the
screenshot below.

.. image:: _static/images/pypi_files_page.png
   :width: 700px
   :align: center

8. Verifying the release artifact check sums
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

To verify that nothing went wrong doing the release process, run the
``./dist/verify_checksums.sh`` script.

This script downloads the release artifacts from the Apache and PyPi server and
makes sure that the MD5 check sums of the both files match.

Usage:

.. sourcecode:: bash

    ./dist/verify_checksums.sh <version>

For example

.. sourcecode:: bash

    ./dist/verify_checksums.sh apache-libcloud-3.5.0

9. Updating doap_libcloud.rdf, __init__.py
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Add information about the new release to the ``doap_libcloud.rdf`` file in the
root of the main code repository.

Update ``__version__`` attribute in ``libcloud/__init.py__`` file and indicate
we are now working on a new release by incrementing a number and adding ``-dev``
suffix. For example, if version ``2.2.1`` has been released you would change
it from:

.. sourcecode:: python

    __version__ = '2.2.1'

To:

.. sourcecode:: python

    __version__ = '2.2.2-dev'

10. Updating website
~~~~~~~~~~~~~~~~~~~~

Check out the website using git: ``git clone http://gitbox.apache.org/repos/asf/libcloud-site.git``

* Update the front page (``source/index.html`` file)
* Update "Downloads" page (``source/downloads.md`` file)
* Add a blog entry in the ``_posts`` directory.

Build the site locally and make sure everything is correct before pushing website updated. Check
the ``README.md`` file in that repo on how to do that.

11. Sending announcements
~~~~~~~~~~~~~~~~~~~~~~~~~

* Send a release announcement to {dev,users}@libcloud.apache.org. If it's a
  major release also send it to announce@apache.org.
* Send a release announcement to Twitter and Google+

Note: If the release fixes a security vulnerability, you should also send
information about a vulnerability to the following full disclosure mailing
lists:

* full-disclosure@lists.grok.org.uk
* bugtraq@securityfocus.com

The email you send should also be signed using your GPG key. You can find
an example of such announcement on the `following url <http://seclists.org/fulldisclosure/2014/Jan/11>`_.

If needed, use Apache URL shortening service - http://s.apache.org/

Mailing list email templates
----------------------------

This section includes email templates which can be used when sending out
official communication to the mailing lists.

Release voting thread template
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This template should be used when starting a voting thread for a new release.

Subject::

    [VOTE] Release Apache Libcloud <version>

Body::

    This is a voting thread for Libcloud <version>.

    <short description and highlights of this release>

    Full changelog can be found at <link to the CHANGES file for this release>.

    Release artifacts can be found at <link to your Apache space where a release
    artifacts can be found>.

    KEYS file can found at https://dist.apache.org/repos/dist/release/libcloud/KEYS

    Please test the release and post your votes.

    +/- 1
    [  ]  Release Apache Libcloud <version>

    Vote will be opened until <date, it should be at minimum today + 3 days> (or longer, if needed).

    Thanks,
    <name>

For example:

Subject::

    [VOTE] Release Apache Libcloud 0.13.2

Body::

    This is a voting thread for Libcloud 0.13.2.

    This is another primarily a bug-fix release. Previous release included a fix for the Content-Length bug which didn't fully fix the original issue. It missed out "raw" requests which are fixed in this release (LIBCLOUD-396).

    This bug could manifest itself while uploading a file with some of the storage providers.

    Besides this bug fix, it includes a couple of other smaller bug fixes and changes. Full change log
    can be found at https://git-wip-us.apache.org/repos/asf?p=libcloud.git;a=blob;f=CHANGES;h=b7747f777afdeb63bcacf496d1d034f1b3287c31;hb=c4b3daae946049652a500a8515929b4cbf14a6b4

    Release artifacts can be found at http://people.apache.org/~tomaz/libcloud/.

    Please test the release and post your votes.

    +/- 1
    [  ]  Release Apache Libcloud 0.13.2

    Vote will be opened until September 18th, 2013 (or longer, if needed).

    Thanks,
    Tomaz

Release announcement
~~~~~~~~~~~~~~~~~~~~

This template should be used when sending out a release announcement.

Subject::

    [ANNOUNCE] Apache Libcloud 0.13.1 release

Body::

    Libcloud is a Python library that abstracts away the differences among
    multiple cloud provider APIs. It allows users to manage cloud services
    (servers, storage, loadbalancers, DNS) offered by many different providers
    through a single, unified and easy to use API.

    We are pleased to announce the release of Libcloud <version>!

    <short description of the release which should include release highlights>

    Full change log can be found at <link to CHANGES file for this release>

    Download

    Libcloud <version> can be downloaded from http://libcloud.apache.org/downloads.html
    or installed using pip:

    pip install apache-libcloud

    Upgrading

    If you have installed Libcloud using pip you can also use it to upgrade it:

    pip install --upgrade apache-libcloud

    Upgrade notes

    A page which describes backward incompatible or semi-incompatible
    changes and how to preserve the old behavior when this is possible
    can be found at http://libcloud.apache.org/upgrade-notes.html.

    Documentation

    API documentation can be found at http://libcloud.apache.org/apidocs/<version>/.

    We also have a new Sphinx documentation which can be found at https://libcloud.apache.org/docs/.

    Bugs / Issues

    If you find any bug or issue, please report it on our issue tracker
    <https://github.com/apache/libcloud/issues>.
    Don't forget to attach an example and / or test which reproduces your problem.

    Thanks

    Thanks to everyone who contributed and made this release possible! Full list of
    people who contributed to this release can be found in the CHANGES file
    <link to the changes file for this release>.

For example:

Subject::

    [ANNOUNCE] Apache Libcloud 0.13.1 release

Body::

    Libcloud is a Python library that abstracts away the differences among
    multiple cloud provider APIs. It allows users to manage cloud services
    (servers, storage, loadbalancers, DNS) offered by many different providers
    through a single, unified and easy to use API.

    We are pleased to announce the release of Libcloud 0.13.1!

    This is a bug-fix only release. Among some smaller bugs it also fixes
    Content-Length regression which broke create and update operations in
    the Bluebox Compute and Azure Storage driver (LIBCLOUD-362, LIBCLOUD-3901).

    Full change log can be found at <https://git-wip-us.apache.org/repos/asf?p=libcloud.git;a=blob;f=CHANGES;h=ca90c84e296ca82e2206eb86ed7364c588aad503;hb=602b6a7a27dca6990a38eb887e1d6615826387d5>

    Download

    Libcloud 0.13.1 can be downloaded from http://libcloud.apache.org/downloads.html
    or installed using pip:

    pip install apache-libcloud

    Upgrading

    If you have installed Libcloud using pip you can also use it to upgrade it:

    pip install --upgrade apache-libcloud

    Upgrade notes

    A page which describes backward incompatible or semi-incompatible
    changes and how to preserve the old behavior when this is possible
    can be found at http://libcloud.apache.org/upgrade-notes.html.

    Documentation

    API documentation can be found at http://libcloud.apache.org/apidocs/0.13.1/.

    We also have a new Sphinx documentation which can be found at https://libcloud.apache.org/docs/.
    Keep in mind though, that this documentation reflects state in trunk which
    includes some backward incompatible changes which aren't present in 0.13.1.
    All the examples in the documentation which only work with trunk are clearly marked with a note.

    Bugs / Issues

    If you find any bug or issue, please report it on our issue tracker
    <https://github.com/apache/libcloud/issues>.
    Don't forget to attach an example and / or test which reproduces your problem.

    Thanks

    Thanks to everyone who contributed and made this release possible! Full list of
    people who contributed to this release can be found in the CHANGES file
    <https://git-wip-us.apache.org/repos/asf?p=libcloud.git;a=blob;f=CHANGES;h=ca90c84e296ca82e2206eb86ed7364c588aad503;hb=602b6a7a27dca6990a38eb887e1d6615826387d5>.

.. _`PyPi release management page`: https://pypi.python.org/pypi?%3Aaction=pkg_edit&name=apache-libcloud


text:
namespace MenuConstructor.RestaurantCrews
{

    public abstract class Crew
    {
        protected Menu Menu { get; set; }

        public abstract void AddBurger();

        public abstract void AddDrink();

        public abstract void AddSalad();

        public abstract void AddDessert();
    }
}

redpajama_set_name: RedPajamaGithub


text:
id: bad87fee1348bd9aed508826
title: Clone an Element Using jQuery
challengeType: 6
videoUrl: ''
localeTitle: Клонирование элемента с помощью jQuery
---

## Description

 В дополнение к движущимся элементам вы также можете копировать их из одного места в другое. jQuery имеет функцию clone() которая делает копию элемента. Например, если мы хотим скопировать target2 из нашей left-well target2 в нашу right-well target2 , мы будем использовать: $("#target2").clone().appendTo("#right-well"); Вы заметили, что это связано с объединением двух функций jQuery? Это называется function chaining и это удобный способ добиться успеха с помощью jQuery. target5 свой элемент target5 и добавьте его в left-well target5 .

## Instructions

## Tests

```yml
tests:
  - text: Элемент <code>target5</code> должен находиться внутри вашей <code>right-well</code> <code>target5</code> .
    testString: 'assert($("#right-well").children("#target5").length > 0, "Your <code>target5</code> element should be inside your <code>right-well</code>.");'
  - text: Копия элемента <code>target5</code> также должна находиться внутри вашей <code>left-well</code> <code>target5</code> .
    testString: 'assert($("#left-well").children("#target5").length > 0, "A copy of your <code>target5</code> element should also be inside your <code>left-well</code>.");'
  - text: Используйте только jQuery для перемещения этих элементов.
    testString: 'assert(!code.match(/class.*animated/g), "Only use jQuery to move these elements.");'

```

## Challenge Seed

```html
<script>
  $(document).ready(function() {
    $("#target1").css("color", "red");
    $("#target1").prop("disabled", true);
    $("#target4").remove();
    $("#target2").appendTo("#right-well");

  });
</script>

<!-- Only change code above this line. -->

<div class="container-fluid">
  <h3 class="text-primary text-center">jQuery Playground</h3>
  <div class="row">
    <div class="col-xs-6">
      <h4>#left-well</h4>
      <div class="well" id="left-well">
        <button class="btn btn-default target" id="target1">#target1</button>
        <button class="btn btn-default target" id="target2">#target2</button>
        <button class="btn btn-default target" id="target3">#target3</button>
      </div>
    </div>
    <div class="col-xs-6">
      <h4>#right-well</h4>
      <div class="well" id="right-well">
        <button class="btn btn-default target" id="target4">#target4</button>
        <button class="btn btn-default target" id="target5">#target5</button>
        <button class="btn btn-default target" id="target6">#target6</button>
      </div>
    </div>
  </div>
</div>

```

## Solution

```js
// solution required
```


text:
import Control.Applicative

main = do
    [a, b] <- map read . words <$> getLine
    let x = area a b
        y = circumference a b
    putStrLn $ show x ++ " " ++ show y

area :: Int -> Int -> Int
area a b = a * b

circumference :: Int -> Int -> Int
circumference a b = (a + b) * 2


text:
module Admin
  class UsersController < Admin::ApplicationController
    def index
      @users = User.all
    end
  end
end


text:
package com.noveogroup.clap.gradle;

public final class BuildConfigHelper {

    private BuildConfigHelper() {
        throw new UnsupportedOperationException();
    }

    public static final String FIELD_CLAP_SERVER_URL = "CLAP_SERVER_URL";
    public static final String FIELD_CLAP_PROJECT_ID = "CLAP_PROJECT_ID";
    public static final String FIELD_CLAP_REVISION_HASH = "CLAP_REVISION_HASH";
    public static final String FIELD_CLAP_VARIANT_HASH = "CLAP_VARIANT_HASH";
    public static final String FIELD_CLAP_RANDOM = "CLAP_RANDOM";

}


text:
using EventSource4Net;
using Maybe5.SharpSpark;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace beakn
{
    public class SparkCore : Protocol
    {
        private SparkClient sparkClient;
        private EventSource eventSource;

        public override void Setup()
        {
            if (!IsConfigValid())
            {
                throw new ArgumentNullException("", "Please enter your Spark Core Device Id and Access Token in Settings dialog.");
            }
            else
            {
                sparkClient = new SparkClient(Properties.Settings.Default.AccessToken, Properties.Settings.Default.DeviceId);

                eventSource = sparkClient.GetEventStream();
                eventSource.EventReceived += eventSource_EventReceived;
                eventSource.Start(new CancellationToken());
            }
        }

        private bool IsConfigValid()
        {
            return !string.IsNullOrEmpty(Properties.Settings.Default.AccessToken) || !string.IsNullOrEmpty(Properties.Settings.Default.DeviceId);
        }

        void eventSource_EventReceived(object sender, ServerSentEventReceivedEventArgs e)
        {
            if (string.Compare(e.Message.EventType, "spark/status", true) == 0)
                OnEventReceived(e);
        }

        public override void Send(string message)
        {
            try
            {
                var result = sparkClient.ExecuteFunctionReturnValue("setStatus", message);
                if (result == 1)
                {
                    OnSendSuccess(new MessageEventArgs("Message Send Success:" + message));
                }
                else
                {
                    OnSendFailure(new MessageEventArgs("Message Send Failure:" + message));

                }
            }
            catch (Exception e)
            {
                OnSendFailure(new MessageEventArgs(string.Format("Exception when sending message: {0}, Exception={1}", message, e.ToString())));
            }
        }
    }
}


text: yum -y groupinstall "Development Tools"


text:
#ifndef __AMF_H__
#define __AMF_H__

#include <stdint.h>

#ifndef TRUE
#define TRUE	1
#define FALSE	0
#endif

#ifdef __cplusplus
extern "C"
{
#endif

  typedef enum
  { AMF_NUMBER = 0, AMF_BOOLEAN, AMF_STRING, AMF_OBJECT,
    AMF_MOVIECLIP,		/* reserved, not used */
    AMF_NULL, AMF_UNDEFINED, AMF_REFERENCE, AMF_ECMA_ARRAY, AMF_OBJECT_END,
    AMF_STRICT_ARRAY, AMF_DATE, AMF_LONG_STRING, AMF_UNSUPPORTED,
    AMF_RECORDSET,		/* reserved, not used */
    AMF_XML_DOC, AMF_TYPED_OBJECT,
    AMF_AVMPLUS,		/* switch to AMF3 */
    AMF_INVALID = 0xff
  } AMFDataType;

  typedef enum
  { AMF3_UNDEFINED = 0, AMF3_NULL, AMF3_FALSE, AMF3_TRUE,
    AMF3_INTEGER, AMF3_DOUBLE, AMF3_STRING, AMF3_XML_DOC, AMF3_DATE,
    AMF3_ARRAY, AMF3_OBJECT, AMF3_XML, AMF3_BYTE_ARRAY
  } AMF3DataType;

  typedef struct AVal
  {
    char *av_val;
    int av_len;
  } AVal;
#define AVC(str)	{str,sizeof(str)-1}
#define AVMATCH(a1,a2)	((a1)->av_len == (a2)->av_len && !memcmp((a1)->av_val,(a2)->av_val,(a1)->av_len))

  struct AMFObjectProperty;

  typedef struct AMFObject
  {
    int o_num;
    struct AMFObjectProperty *o_props;
  } AMFObject;

  typedef struct AMFObjectProperty
  {
    AVal p_name;
    AMFDataType p_type;
    union
    {
      double p_number;
      AVal p_aval;
      AMFObject p_object;
    } p_vu;
    int16_t p_UTCoffset;
  } AMFObjectProperty;

  char *AMF_EncodeString(char *output, char *outend, const AVal * str);
  char *AMF_EncodeNumber(char *output, char *outend, double dVal);
  char *AMF_EncodeInt16(char *output, char *outend, short nVal);
  char *AMF_EncodeInt24(char *output, char *outend, int nVal);
  char *AMF_EncodeInt32(char *output, char *outend, int nVal);
  char *AMF_EncodeBoolean(char *output, char *outend, int bVal);

  /* Shortcuts for AMFProp_Encode */
  char *AMF_EncodeNamedString(char *output, char *outend, const AVal * name, const AVal * value);
  char *AMF_EncodeNamedNumber(char *output, char *outend, const AVal * name, double dVal);
  char *AMF_EncodeNamedBoolean(char *output, char *outend, const AVal * name, int bVal);

  unsigned short AMF_DecodeInt16(const char *data);
  unsigned int AMF_DecodeInt24(const char *data);
  unsigned int AMF_DecodeInt32(const char *data);
  void AMF_DecodeString(const char *data, AVal * str);
  void AMF_DecodeLongString(const char *data, AVal * str);
  int AMF_DecodeBoolean(const char *data);
  double AMF_DecodeNumber(const char *data);

  char *AMF_Encode(AMFObject * obj, char *pBuffer, char *pBufEnd);
  int AMF_Decode(AMFObject * obj, const char *pBuffer, int nSize,
		 int bDecodeName);
  int AMF_DecodeArray(AMFObject * obj, const char *pBuffer, int nSize,
		      int nArrayLen, int bDecodeName);
  int AMF3_Decode(AMFObject * obj, const char *pBuffer, int nSize,
		  int bDecodeName);
  void AMF_Dump(AMFObject * obj);
  void AMF_Reset(AMFObject * obj);

  void AMF_AddProp(AMFObject * obj, const AMFObjectProperty * prop);
  int AMF_CountProp(AMFObject * obj);
  AMFObjectProperty *AMF_GetProp(AMFObject * obj, const AVal * name,
				 int nIndex);

  AMFDataType AMFProp_GetType(AMFObjectProperty * prop);
  void AMFProp_SetNumber(AMFObjectProperty * prop, double dval);
  void AMFProp_SetBoolean(AMFObjectProperty * prop, int bflag);
  void AMFProp_SetString(AMFObjectProperty * prop, AVal * str);
  void AMFProp_SetObject(AMFObjectProperty * prop, AMFObject * obj);

  void AMFProp_GetName(AMFObjectProperty * prop, AVal * name);
  void AMFProp_SetName(AMFObjectProperty * prop, AVal * name);
  double AMFProp_GetNumber(AMFObjectProperty * prop);
  int AMFProp_GetBoolean(AMFObjectProperty * prop);
  void AMFProp_GetString(AMFObjectProperty * prop, AVal * str);
  void AMFProp_GetObject(AMFObjectProperty * prop, AMFObject * obj);

  int AMFProp_IsValid(AMFObjectProperty * prop);

  char *AMFProp_Encode(AMFObjectProperty * prop, char *pBuffer, char *pBufEnd);
  int AMF3Prop_Decode(AMFObjectProperty * prop, const char *pBuffer,
		      int nSize, int bDecodeName);
  int AMFProp_Decode(AMFObjectProperty * prop, const char *pBuffer,
		     int nSize, int bDecodeName);

  void AMFProp_Dump(AMFObjectProperty * prop);
  void AMFProp_Reset(AMFObjectProperty * prop);

  typedef struct AMF3ClassDef
  {
    AVal cd_name;
    char cd_externalizable;
    char cd_dynamic;
    int cd_num;
    AVal *cd_props;
  } AMF3ClassDef;

  void AMF3CD_AddProp(AMF3ClassDef * cd, AVal * prop);
  AVal *AMF3CD_GetProp(AMF3ClassDef * cd, int idx);

#ifdef __cplusplus
}
#endif

#endif				/* __AMF_H__ */


text:
First of all: we very much welcome all contributions so want to make it as easy as possible & don't want to build in any barriers (technical or practical) that would hold anyone back from contributing.

So don't hesitate to ask questions or get in touch if something is not clear or you have suggestions for improvements.

But to make sure that everything remains manageable and maintainable, there is this document (a work in progress) with some guidelines & best practices to contribute to this project.
## How Can I contribute?

### Become a part of the community

Join our [slack](http://bebadges.herokuapp.com/) or [meetupgroup](https://www.meetup.com/Belgian-Open-Badges-Meetup/) and take part in community discussions & events.

### Report bugs or request features
If you have a feature request or bug you want to report, you can do so via posting [github issues](https://github.com/BeBadges/escobadges/issues).
Make sure before your post [to check the list of issues](https://github.com/BeBadges/escobadges/issues) if the **same issue hasn't already been posted**.

### Github workflow for developers
In the workflow we follow for this project, we would like to keep the relation between the issue tracker and the code as clear as possible.
So we suggest that each significant change to the code , should start with an issue where the goal is described.

The workflow we propose:
- **Create an issue** describing the desired change that you want to make (if it doesn't exist yet)
- When you (or someone else) is ready to code: **start a branch** for the issue from the master branch. The name of this branch should start **with the issue number** + description of the issue, for example '8-update-readme-file-with-installation-instruction'.
- When you are done you **open a pull request** to the master branch
- Before it is merged into the master branch , **it will be reviewed** . You can indicate when your pull request would be a Work in Progress & not ready to be merged yet (start the title of the pull request with "WIP:").

This way we can keep track on who is working on what.


text:
copyright:
 years: 2015, 2016

---

# Push-SDK für iOS-Apps initialisieren
{: #enable-push-ios-notifications-initialize}

Das Anwendungs-Delegat für die iOS-Anwendung ist eine übliche Position für den
Initialisierungscode.
Klicken Sie auf den Link **Mobile Optionen** in Ihrem Bluemix-Anwendungsdashboard, um
die Anwendungsroute und die GUID abzurufen.

##Core-SDK initialisieren

###Objective-C

```
// Initialize the SDK for Object-C with IBM Bluemix GUID and route
IMFClient *imfClient = [IMFClient sharedInstance];
[imfClient initializeWithBackendRoute:"add_your_applicationRoute_here" backendGUID:"add_your_appId_here"];
```

###Swift

```
// Initialize the Core SDK for Swift with IBM Bluemix GUID, route, and region
let myBMSClient = BMSClient.sharedInstance

myBMSClient.initializeWithBluemixAppRoute("BluemixAppRoute", bluemixAppGUID: "APPGUID", bluemixRegion:"Location where your app Hosted")
myBMSClient.defaultRequestTimeout = 10.0 // Timput in seconds
```

##Client-Push-SDK initialisieren

###Objective-C

```
//Initialize client Push SDK for Objective-C
IMFPushClient _pushService = [IMFPushClient sharedInstance];
```

###Swift

```
//Initialize client Push SDK for Swift
let push = BMSPushClient.sharedInstance
```

## Route, GUID und Bluemix-Region

**appRoute**

Gibt die Route an, die der Serveranwendung zugewiesen ist, die Sie in Bluemix erstellt haben.

**GUID**

Gibt den eindeutigen Schlüssel an, der der Anwendung zugewiesen wird, die Sie in Bluemix erstellt haben. Bei diesem Wert muss die Groß-/Kleinschreibung beachtet werden.

**bluemixRegionSuffix**

Gibt den Standort an, an dem die App gehostet ist. Der Parameter `bluemixRegion` gibt an, welche Bluemix-Bereitstellung Sie verwenden. Sie können diesen Wert mit der statischen Eigenschaft `BMSClient.REGION` angeben und einen von drei Werten verwenden:

- BMSClient.REGION_US_SOUTH
- BMSClient.REGION_UK
- BMSClient.REGION_SYDNEY


text:
angular.module('openspecimen')
  .directive('osUiElement', function($parse) {
    return {
      restrict: 'A',

      scope: true,

      link: function(scope, element, attrs) {
         if (attrs.osUiElement) {
           $parse(attrs.osUiElement).assign(scope, element);
         }
      }
    }
  });


text:
<?php
 /*
     Example14: A smooth flat pie graph
 */

 // Standard inclusions
 include("pChart/pData.class");
 include("pChart/pChart.class");

 // Dataset definition
 $DataSet = new pData;
 $DataSet->AddPoint(array(10,2,3,5,3),"Serie1");
 $DataSet->AddPoint(array("Jan","Feb","Mar","Apr","May"),"Serie2");
 $DataSet->AddAllSeries();
 $DataSet->SetAbsciseLabelSerie("Serie2");

 // Initialise the graph
 $Test = new pChart(300,200);
 $Test->loadColorPalette("Sample/softtones.txt");
 $Test->drawFilledRoundedRectangle(7,7,293,193,5,240,240,240);
 $Test->drawRoundedRectangle(5,5,295,195,5,230,230,230);

 // This will draw a shadow under the pie chart
 $Test->drawFilledCircle(122,102,70,200,200,200);

 // Draw the pie chart
 $Test->setFontProperties("Fonts/tahoma.ttf",8);
 $Test->AntialiasQuality = 0;
 $Test->drawBasicPieGraph($DataSet->GetData(),$DataSet->GetDataDescription(),120,100,70,PIE_PERCENTAGE,255,255,218);
 $Test->drawPieLegend(230,15,$DataSet->GetData(),$DataSet->GetDataDescription(),250,250,250);

 $Test->Render("example14.png");
?>


text:
.. _type.constraint:

Constraints
-----------

ASN.1 standard has a built-in way of limiting the set of values
a type can possibly have. Imposing value constraints on an ASN.1
type, together with :ref:`tagging <type.tag>`, is a way of creating
a more specialized subtype of an ASN.1 type.

The pyasn1 implementation represents all flavors of constraints,
as well as their combinations, as immutable Python objects. Ultimately,
they get attached to ASN.1 type object at a *.subtypeSpec* attribute.

.. code-block:: python

   class Age(Integer):
       """
       ASN.1 specification:

       Age ::= INTEGER (0..120)
       """
       subtypeSpec = ValueRangeConstraint(0, 120)

.. toctree::
   :maxdepth: 2

   /pyasn1/type/constraint/singlevalue
   /pyasn1/type/constraint/containedsubtype
   /pyasn1/type/constraint/valuerange
   /pyasn1/type/constraint/valuesize
   /pyasn1/type/constraint/permittedalphabet
   /pyasn1/type/constraint/withcomponents

Logic operations on constraints
+++++++++++++++++++++++++++++++

Sometimes multiple constraints are applied on an ASN.1 type. To capture
this situation, individual constraint objects can be glued together
by the logic operator objects.

The logic operators are Python objects that exhibit similar behaviour
as the constraint objects do with the only difference that logic operators
are instantiated on the constraint and logic operator objects, not on the
bare values.

.. code-block:: python

   class PhoneNumber(NumericString):
       """
       ASN.1 specification:

       PhoneNumber ::=
           NumericString (FROM ("0".."9")) (SIZE (10))
       """
       subtypeSpec = ConstraintsIntersection(
           ValueRangeConstraint('0', '9'), ValueSizeConstraint(10)
       )

.. toctree::
   :maxdepth: 2

   /pyasn1/type/constraint/constraintsintersection
   /pyasn1/type/constraint/constraintsunion
   /pyasn1/type/constraint/constraintsexclusion


text:
@interface YMBarButton : UIButton

@end


text:
class CreateExtendedProfiles < ActiveRecord::Migration
  def change
    create_table :extended_profiles do |t|
      t.text :skill_level
      t.text :special_interests
      t.text :availability
      t.text :time_zone
      t.text :notes
      t.boolean :is_mentor
      t.boolean :is_pair_partner
      t.references :user
      t.timestamps
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2015 The Chromium Authors. All rights reserved.
     Use of this source code is governed by a BSD-style license that can be
     found in the LICENSE file. -->

<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="@style/TextAppearance.TextMedium.Secondary"
    android:textColorLink="@color/default_text_color_link" />


text:
#include <linux/module.h>
#include <linux/ioport.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/mii.h>
#include <linux/platform_device.h>
#include <linux/mdio-bitbang.h>
#include <linux/of_address.h>
#include <linux/of_mdio.h>
#include <linux/of_platform.h>

#include "fs_enet.h"

struct bb_info {
	struct mdiobb_ctrl ctrl;
	__be32 __iomem *dir;
	__be32 __iomem *dat;
	u32 mdio_msk;
	u32 mdc_msk;
};

/* FIXME: If any other users of GPIO crop up, then these will have to
 * have some sort of global synchronization to avoid races with other
 * pins on the same port.  The ideal solution would probably be to
 * bind the ports to a GPIO driver, and have this be a client of it.
 */
static inline void bb_set(u32 __iomem *p, u32 m)
{
	out_be32(p, in_be32(p) | m);
}

static inline void bb_clr(u32 __iomem *p, u32 m)
{
	out_be32(p, in_be32(p) & ~m);
}

static inline int bb_read(u32 __iomem *p, u32 m)
{
	return (in_be32(p) & m) != 0;
}

static inline void mdio_dir(struct mdiobb_ctrl *ctrl, int dir)
{
	struct bb_info *bitbang = container_of(ctrl, struct bb_info, ctrl);

	if (dir)
		bb_set(bitbang->dir, bitbang->mdio_msk);
	else
		bb_clr(bitbang->dir, bitbang->mdio_msk);

	/* Read back to flush the write. */
	in_be32(bitbang->dir);
}

static inline int mdio_read(struct mdiobb_ctrl *ctrl)
{
	struct bb_info *bitbang = container_of(ctrl, struct bb_info, ctrl);
	return bb_read(bitbang->dat, bitbang->mdio_msk);
}

static inline void mdio(struct mdiobb_ctrl *ctrl, int what)
{
	struct bb_info *bitbang = container_of(ctrl, struct bb_info, ctrl);

	if (what)
		bb_set(bitbang->dat, bitbang->mdio_msk);
	else
		bb_clr(bitbang->dat, bitbang->mdio_msk);

	/* Read back to flush the write. */
	in_be32(bitbang->dat);
}

static inline void mdc(struct mdiobb_ctrl *ctrl, int what)
{
	struct bb_info *bitbang = container_of(ctrl, struct bb_info, ctrl);

	if (what)
		bb_set(bitbang->dat, bitbang->mdc_msk);
	else
		bb_clr(bitbang->dat, bitbang->mdc_msk);

	/* Read back to flush the write. */
	in_be32(bitbang->dat);
}

static struct mdiobb_ops bb_ops = {
	.owner = THIS_MODULE,
	.set_mdc = mdc,
	.set_mdio_dir = mdio_dir,
	.set_mdio_data = mdio,
	.get_mdio_data = mdio_read,
};

static int fs_mii_bitbang_init(struct mii_bus *bus, struct device_node *np)
{
	struct resource res;
	const u32 *data;
	int mdio_pin, mdc_pin, len;
	struct bb_info *bitbang = bus->priv;

	int ret = of_address_to_resource(np, 0, &res);
	if (ret)
		return ret;

	if (resource_size(&res) <= 13)
		return -ENODEV;

	/* This should really encode the pin number as well, but all
	 * we get is an int, and the odds of multiple bitbang mdio buses
	 * is low enough that it's not worth going too crazy.
	 */
	snprintf(bus->id, MII_BUS_ID_SIZE, "%x", res.start);

	data = of_get_property(np, "fsl,mdio-pin", &len);
	if (!data || len != 4)
		return -ENODEV;
	mdio_pin = *data;

	data = of_get_property(np, "fsl,mdc-pin", &len);
	if (!data || len != 4)
		return -ENODEV;
	mdc_pin = *data;

	bitbang->dir = ioremap(res.start, resource_size(&res));
	if (!bitbang->dir)
		return -ENOMEM;

	bitbang->dat = bitbang->dir + 4;
	bitbang->mdio_msk = 1 << (31 - mdio_pin);
	bitbang->mdc_msk = 1 << (31 - mdc_pin);

	return 0;
}

static int fs_enet_mdio_probe(struct platform_device *ofdev)
{
	struct mii_bus *new_bus;
	struct bb_info *bitbang;
	int ret = -ENOMEM;

	bitbang = kzalloc(sizeof(struct bb_info), GFP_KERNEL);
	if (!bitbang)
		goto out;

	bitbang->ctrl.ops = &bb_ops;

	new_bus = alloc_mdio_bitbang(&bitbang->ctrl);
	if (!new_bus)
		goto out_free_priv;

	new_bus->name = "CPM2 Bitbanged MII",

	ret = fs_mii_bitbang_init(new_bus, ofdev->dev.of_node);
	if (ret)
		goto out_free_bus;

	new_bus->phy_mask = ~0;
	new_bus->irq = kmalloc(sizeof(int) * PHY_MAX_ADDR, GFP_KERNEL);
	if (!new_bus->irq) {
		ret = -ENOMEM;
		goto out_unmap_regs;
	}

	new_bus->parent = &ofdev->dev;
	platform_set_drvdata(ofdev, new_bus);

	ret = of_mdiobus_register(new_bus, ofdev->dev.of_node);
	if (ret)
		goto out_free_irqs;

	return 0;

out_free_irqs:
	kfree(new_bus->irq);
out_unmap_regs:
	iounmap(bitbang->dir);
out_free_bus:
	free_mdio_bitbang(new_bus);
out_free_priv:
	kfree(bitbang);
out:
	return ret;
}

static int fs_enet_mdio_remove(struct platform_device *ofdev)
{
	struct mii_bus *bus = platform_get_drvdata(ofdev);
	struct bb_info *bitbang = bus->priv;

	mdiobus_unregister(bus);
	kfree(bus->irq);
	free_mdio_bitbang(bus);
	iounmap(bitbang->dir);
	kfree(bitbang);

	return 0;
}

static const struct of_device_id fs_enet_mdio_bb_match[] = {
	{
		.compatible = "fsl,cpm2-mdio-bitbang",
	},
	{},
};
MODULE_DEVICE_TABLE(of, fs_enet_mdio_bb_match);

static struct platform_driver fs_enet_bb_mdio_driver = {
	.driver = {
		.name = "fsl-bb-mdio",
		.of_match_table = fs_enet_mdio_bb_match,
	},
	.probe = fs_enet_mdio_probe,
	.remove = fs_enet_mdio_remove,
};

module_platform_driver(fs_enet_bb_mdio_driver);


text:
<?php
  /**
  * QuickSkin Extension htmlentities
  * Converts Special Characters to HTML Entities
  *
  * Usage Example:
  * Content:  $template->assign('NEXT', 'Next Page >>');
  * Template: {htmlentities:NEXT}
  * Result:   Next Page >>
  *
  * @author Andy Prevost andy@codeworxtech.com - original by Philipp v. Criegern philipp@criegern.de
  */
  function qx_htmlentities ( $param ) {
    return htmlentities( $param );
  }

?>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>pygame.scrap — Pygame v1.9.2 documentation</title>
    <link rel="stylesheet" href="../_static/pygame.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/pygame.ico"/>
    <link rel="top" title="Pygame v1.9.2 documentation" href="../index.html" />
    <link rel="next" title="pygame.sndarray" href="sndarray.html" />
    <link rel="prev" title="pygame.Rect" href="rect.html" />

pygame documentation

	    ||
	    Pygame Home ||
	    Help Contents ||
	    Reference Index ||

	    camera ||
	    cdrom ||
	    Color ||
	    cursors ||
	    display ||
	    draw ||
	    event ||
	    examples ||
	    font ||
	    gfxdraw ||
	    image ||
	    joystick ||
	    key ||
	    locals ||
	    mask ||
	    math ||
	    midi ||
	    mixer ||
	    mouse ||
	    movie ||
	    music ||
	    Overlay ||
	    PixelArray ||
	    pixelcopy ||
	    pygame ||
	    Rect ||
	    scrap ||
	    sndarray ||
	    sprite ||
	    Surface ||
	    surfarray ||
	    tests ||
	    time ||
	    transform ||
	    version

<tt class="docutils literal">pygame.scrap</tt>

pygame module for clipboard support.

<colgroup>
<col width="24%" />
<col width="1%" />
<col width="75%" />
</colgroup>

pygame.scrap.init
—
Initializes the scrap module.

pygame.scrap.get
—
Gets the data for the specified type from the clipboard.

pygame.scrap.get_types
—
Gets a list of the available clipboard types.

pygame.scrap.put
—
Places data into the clipboard.

pygame.scrap.contains
—
Checks, whether a certain type is available in the clipboard.

pygame.scrap.lost
—
Checks whether the clipboard is currently owned by the application.

pygame.scrap.set_mode
—
Sets the clipboard access mode.

EXPERIMENTAL!: meaning this api may change, or dissapear in later pygame
releases. If you use this, your code will break with the next pygame release.

The scrap module is for getting and putting stuff from the clipboard. So you
can copy and paste things between pygame, and other application types. It
defines some basic own data types

SCRAP_PPM
SCRAP_PBM
SCRAP_BMP
SCRAP_TEXT

to be placed into the clipboard and allows to use define own clipboard types.
<tt class="docutils literal">SCRAP_PPM</tt>, <tt class="docutils literal">SCRAP_PBM</tt> and <tt class="docutils literal">SCRAP_BMP</tt> are suitable for surface buffers
to be shared with other applications, while <tt class="docutils literal">SCRAP_TEXT</tt> is an alias for the
plain text clipboard type.

The SCRAP_* types refer to the following <tt class="docutils literal">MIME</tt> types and register those as
well as the default operating system type for this type of data:

SCRAP_TEXT text/plain    for plain text
SCRAP_PBM  image/pbm     for PBM encoded image data
SCRAP_PPM  image/ppm     for PPM encoded image data
SCRAP_BMP  image/bmp     for BMP encoded image data

Depending on the platform additional types are automatically registered when
data is placed into the clipboard to guarantee a consistent sharing behaviour
with other applications. The following listed types can be used as string to be
passed to the respective <tt class="xref py py-mod docutils literal">pygame.scrap</tt>pygame module for clipboard support. module functions.

For Windows platforms, the additional types are supported automatically and
resolve to their internal definitions:

text/plain;charset=utf-8 for UTF-8 encoded text
audio/wav                for WAV encoded audio
image/tiff               for TIFF encoded image data

For <tt class="docutils literal">X11</tt> platforms, the additional types are supported automatically and
resolve to their internal definitions:

UTF8_STRING               for UTF-8 encoded text
text/plain;charset=utf-8  for UTF-8 encoded text
COMPOUND_TEXT             for COMPOUND text

As stated before you can define own types for the clipboard, those however
might not be usable by other applications. Thus data pasted into the clipboard
using

pygame.scrap.put ("own_data", data)

can only be used by applications, which query the clipboard for the “own_data”
type.

New in pygame 1.8. Only works for Windows, <tt class="docutils literal">X11</tt> and Mac <tt class="docutils literal">OS</tt> <tt class="docutils literal">X</tt> so far.
On Mac <tt class="docutils literal">OSX</tt> only text works at the moment - other types will be supported in
the next release.

<tt class="descclassname">pygame.scrap.</tt><tt class="descname">init</tt><big>(</big><big>)</big>¶

Initializes the scrap module.

init () -> None

Tries to initialize the scrap module and raises an exception, if it fails.
Note that this module requires a set display surface, so you have to make
sure, you acquired one earlier using <tt class="docutils literal">pygame.display.set_mode()</tt>.

<tt class="descclassname">pygame.scrap.</tt><tt class="descname">get</tt><big>(</big><big>)</big>¶

Gets the data for the specified type from the clipboard.

get (type) -> string

Returns the data for the specified type from the clipboard. The data is
returned as string and might need further processing. If no data for the
passed type is available, None is returned.

text = pygame.scrap.get (SCRAP_TEXT)
if text:
    # Do stuff with it.
else:
    print "There does not seem to be text in the clipboard."

<tt class="descclassname">pygame.scrap.</tt><tt class="descname">get_types</tt><big>(</big><big>)</big>¶

Gets a list of the available clipboard types.

get_types () -> list

Gets a list of strings with the identifiers for the available clipboard
types. Each identifier can be used in the <tt class="docutils literal">scrap.get()</tt> method to get the
clipboard content of the specific type. If there is no data in the
clipboard, an empty list is returned.

types = pygame.scrap.get_types ()
for t in types:
    if "text" in t:
        # There is some content with the word "text" in it. It's
        # possibly text, so print it.
        print pygame.scrap.get (t)

<tt class="descclassname">pygame.scrap.</tt><tt class="descname">put</tt><big>(</big><big>)</big>¶

Places data into the clipboard.

put(type, data) -> None

Places data for a specific clipboard type into the clipboard. The data must
be a string buffer. The type is a string identifying the type of data placed
into the clipboard. This can be one of the native <tt class="docutils literal">SCRAP_PBM</tt>,
<tt class="docutils literal">SCRAP_PPM</tt>, <tt class="docutils literal">SCRAP_BMP</tt> or <tt class="docutils literal">SCRAP_TEXT</tt> values or an own string
identifier.

The method raises an exception, if the content could not be placed into the
clipboard.

fp = open ("example.bmp", "rb")
pygame.scrap.put (SCRAP_BMP, fp.read ())
fp.close ()
# Now you can acquire the image data from the clipboard in other
# applications.
pygame.scrap.put (SCRAP_TEXT, "A text to copy")
pygame.scrap.put ("Plain text", "A text to copy")

<tt class="descclassname">pygame.scrap.</tt><tt class="descname">contains</tt><big>(</big><big>)</big>¶

Checks, whether a certain type is available in the clipboard.

contains (type) -> bool

Returns True, if data for the passed type is available in the clipboard,
False otherwise.

if pygame.scrap.contains (SCRAP_TEXT):
    print "There is text in the clipboard."
if pygame.scrap.contains ("own_data_type"):
    print "There is stuff in the clipboard."

<tt class="descclassname">pygame.scrap.</tt><tt class="descname">lost</tt><big>(</big><big>)</big>¶

Checks whether the clipboard is currently owned by the application.

lost() -> bool

Returns True, if the clipboard is currently owned by the pygame application,
False otherwise.

if pygame.scrap.lost ():
   print "No content from me anymore. The clipboard is used by someone else."

<tt class="descclassname">pygame.scrap.</tt><tt class="descname">set_mode</tt><big>(</big><big>)</big>¶

Sets the clipboard access mode.

set_mode(mode) -> None

Sets the access mode for the clipboard. This is only of interest for <tt class="docutils literal">X11</tt>
environments, where clipboard modes for mouse selections (SRAP_SELECTION)
and the clipboard (SCRAP_CLIPBOARD) are available. Setting the mode to
<tt class="docutils literal">SCRAP_SELECTION</tt> in other environments will not cause any difference.

If a value different from <tt class="docutils literal">SCRAP_CLIPBOARD</tt> or <tt class="docutils literal">SCRAP_SELECTION</tt> is
passed, a ValueError will be raised.

Navigation

          index

          next |

          previous |

Pygame v1.9.2 documentation »

        © Copyright 2011, Pygame Developers.


text:
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GatewaySimulator.Business
{
    public static class RegisterBusiness
    {
        public static void RegesterCommand(string name, string mac)
        {
            var errorMap = new Dictionary<int, string>
            {
                {1,"Invalid name"},
                {2,"Invalid code"},
                {3,"Customer not exist"},
                {4,"Box already exist"},
                {5,"Box not exist"},
            };

            var response = Register(name, mac);

            var validation = ValidateResponse(response, errorMap, 4);

            if (validation.HasValue && validation.Value == 4)
            {
                Console.WriteLine("Box already exist, replace? Y,N");
                var input = Console.ReadLine();
                if (input.Trim().ToLower().StartsWith("y"))
                {
                    var r2 = Replace(name, mac);
                    var v2 = ValidateResponse(r2, errorMap);
                }
            }
        }

        public static dynamic Replace(string name, string mac)
        {
            var url = string.Format("{0}{1}", ConfigurationManager.AppSettings["WebHost"], ConfigurationManager.AppSettings["ReplaceUrl"]);

            string parameter = string.Format("boxname={0}&boxmac={1}", name, mac);
            string absolute = string.Format("{0}?{1}", url, parameter);

            var responseText = HttpHelper.Get(absolute);

            dynamic response = JObject.Parse(responseText);

            return response;
        }

        public static dynamic Register(string name, string mac)
        {
            var url = string.Format("{0}{1}", ConfigurationManager.AppSettings["WebHost"], ConfigurationManager.AppSettings["RegisterUrl"]);

            string parameter = string.Format("boxname={0}&boxmac={1}", name, mac);
            string absolute = string.Format("{0}?{1}", url, parameter);

            var responseText = HttpHelper.Get(absolute);

            dynamic response = JObject.Parse(responseText);

            return response;
        }

        public static int? ValidateResponse(ResponseMessage response, Dictionary<int, string> errorMap, int? specialCode = null)
        {
            var code = Convert.ToInt32(response.Error);

            if (specialCode.HasValue && specialCode.Value == code)
            {
                return specialCode;
            }

            if (code == 0)
            {
                var result = response.Result;
                Console.WriteLine(result.GetType());
            }
            else if (code == -1)
            {
                Console.WriteLine("server error");
            }
            else
            {
                var message = errorMap[code];
                Console.WriteLine("error: {0}", message);
            }

            return null;
        }
    }
}


text:
/*
 * Problem 3. Read file contents
 * Write a program that enters file name along with its full file path
 * (e.g. C:\WINDOWS\win.ini), reads its contents and prints it on the console.
 * Find in MSDN how to use System.IO.File.ReadAllText(…).
 * Be sure to catch all possible exceptions and print user-friendly error messages.
 */

using System;
using System.IO;

class P03_ReadFileContents
{
    static void Main()
    {
        // input and variable initiazlization
        Console.Write("path to file please: ");
        string path = Console.ReadLine();
        string text = string.Empty;

        // reading of file (if we read the file as whole thats the only exception I can think of)
        try
        {
            text = File.ReadAllText(path);
        }
        catch (System.IO.FileNotFoundException)
        {
            Console.WriteLine("not a valid path, file not found");
            throw;
        }

        // output
        Console.WriteLine(text);
    }
}


text:
Formats the content of the HTML wrapped by the Scribe instance and applies [Guardian](http://www.theguardian.com) rules for cleaning content to a standard format.

## Rules summary

* Reduce multiple whitespace to a single space
* Turns ` -- ` into the endash character, regards of spacing around the double-hyphens
* Turns ` - ` into the endash character
* Removes elements that only consist of break return elements
* Reduces multiple break-returns to a single break return
* Where a break-return separates non-boundary characters the break-return is replaced with a space

## Running the tests

* `npm install`
* `npm test`

## Known issues

Tests are not running locally on Firefox due to an out-of-date Selenium Webdriver dependency


text:
package jetbrains.jetpad.model.composite.dump;

public interface DumpContext {
  void withIndent(Runnable r);
  void println(String text);
}


text:
<?php

namespace Rhubarb\Stem\Tests\unit\Schema\Columns;

use Rhubarb\Crown\Tests\Fixtures\TestCases\RhubarbTestCase;
use Rhubarb\Stem\Tests\unit\Fixtures\TestContact;

class DecimalTest extends RhubarbTestCase
{
    public function testDataTransforms()
    {
        $example = new TestContact();

        // Test the min and max limits of the range
        $example->CreditLimit = 1000000000000000000;
        $example->Balance = -10000000000000000000;
        $this->assertEquals(99999999.99, $example->CreditLimit);
        $this->assertEquals(-9999.9999, $example->Balance);

        // Test rounding to the correct number of decimal places
        $example->CreditLimit = 3000.1256;
        $example->Balance = 3000.10002;
        $this->assertNotEquals(3000.1256, $example->CreditLimit);
        $this->assertEquals(3000.13, $example->CreditLimit);
        $this->assertNotEquals(3000.10002, $example->Balance);
        $this->assertEquals(3000.1, $example->Balance);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml;

using Trifolia.DB;

namespace Trifolia.Export.MSWord
{
    /// <summary>
    /// Supports adding a code system appendix to exported word documents
    /// List of code systems is based on constraints that directly reference a code system and
    /// constraints that reference a valueset that has members associated with code systems.
    /// </summary>
    public class CodeSystemTable
    {
        private IObjectRepository tdb;
        private Body documentBody;
        private List<Template> templates;
        private TableCollection tables;
        private IEnumerable<CodeSystemTable.CodeSystem> codeSystems;

        public CodeSystemTable(IObjectRepository tdb, Body documentBody, List<Template> templates, TableCollection tables)
        {
            this.tdb = tdb;
            this.documentBody = documentBody;
            this.templates = templates;
            this.tables = tables;

            var implementationGuides = this.templates.Select(y => y.OwningImplementationGuideId).Distinct();

            // Perform the query first, then determine the distinct values next. This is for performance. Without it being
            // done like this, the DB query hangs forever.
            var igCodeSytsems = (from igcs in this.tdb.ViewImplementationGuideCodeSystems
                                 join ig in implementationGuides on igcs.ImplementationGuideId equals ig
                                 select new CodeSystemTable.CodeSystem()
                                 {
                                     Name = igcs.Name,
                                     Identifier = igcs.Identifier
                                 }).ToList();
            this.codeSystems = igCodeSytsems
                .GroupBy(y => new { y.Identifier, y.Name })
                .Select(y => new CodeSystemTable.CodeSystem()
                {
                    Name = y.First().Name,
                    Identifier = y.First().Identifier
                })
                .OrderBy(y => y.Name);
        }

        /// <summary>
        /// Adds an appendix heading for "Code Systems in this Guide" and a table listing all code systems
        /// used, by name and oid
        /// </summary>
        public void AddCodeSystemAppendix()
        {
            if (this.codeSystems.Count() > 0)
            {
                this.AddAppendixHeading();

                this.AddCodeSystemTable();
            }
        }

        private void AddAppendixHeading()
        {
            Paragraph heading = new Paragraph(
                new ParagraphProperties(
                    new ParagraphStyleId() { Val = Properties.Settings.Default.TemplateTypeHeadingStyle }),
                new Run(
                    new Text("Code Systems in This Guide")));
            this.documentBody.AppendChild(heading);
        }

        private void AddCodeSystemTable()
        {
            string[] headers = new string[] { "Name", "OID" };
            Table table = this.tables.AddTable("Code Systems", headers);

            foreach (var cCodeSystem in codeSystems)
            {
                TableRow newRow = new TableRow(
                    new TableCell(
                        new Paragraph(
                            DocHelper.CreateRun(cCodeSystem.Name))),
                    new TableCell(
                        new Paragraph(
                            DocHelper.CreateRun(cCodeSystem.Identifier))));

                table.Append(newRow);
            }
        }

        public class CodeSystem : IEquatable<CodeSystem>
        {
            public string Name { get; set; }
            public string Identifier { get; set; }

            public bool Equals(CodeSystem other)
            {
                string thisIdentifier = !string.IsNullOrEmpty(this.Identifier) ? this.Identifier : string.Empty;
                string otherIdentifier = other != null && !string.IsNullOrEmpty(other.Identifier) ? other.Identifier : string.Empty;
                return thisIdentifier.Equals(otherIdentifier);
            }
        }
    }
}


text:
[![NPM](https://nodei.co/npm/prng-well1024a.png)](https://nodei.co/npm/prng-well1024a/)

This is a Javascript implementation of the
[WELL-1024a](http://en.wikipedia.org/wiki/Well_equidistributed_long-period_linear)
pseudorandom number generation algorithm.

Javascript's built-in `Math.random()` function is
[implementation-dependent](http://www.ecma-international.org/publications/standards/Ecma-262.htm)
and therefore of limited usefulness if your program depends on random
numbers, as you risk running into crappy implementations.  Even the V8
engine (used by Node.js) only provides 32-bit entropy, and is based on
the platform-dependent C++ `rand()` function.

This module is very bare-bones.  I have also written a randomness library called
[randy](http://github.com/deestan/randy.git) that provides useful functions like
`RandInt(min, max)`, `shuffle(array)` etc., based on this module.

## Quick Example

```javascript
var rng = well1024a();
var number = rng.getUInt32();
var coin = ['heads', 'tails'][number % 2];
// coin == 'heads'
```

## Download

For [Node.js](http://nodejs.org/), use [npm](http://npmjs.org/):

    npm install prng-well1024a

### In the Browser

Download and include as a `<script>`.  The module will be available as
the global object `randy`.

__Development:__ [well1024a.js](https://github.com/deestan/well1024a/raw/master/browser/well1024a.js) - 2Kb Uncompressed

__Production:__ [well1024a.min.js](https://github.com/deestan/well1024a/raw/master/browser/well1024a.min.js) - < 1Kb Minified

__Example__

```html
<script src="well1024a.min.js"></script>

I am <span id="age"></span> years old!

<script>
    var n = document.getElementById("age");
    var myAge = well1024a.getUInt32();
    n.innerText = myAge.toString();
</script>
```

## Documentation

### Constructor

* [well1024a](#well1024a)

### Instance Functions

* [getUInt32](#getUInt32)
* [getState](#getstate)
* [setState](#setState)

-----------------------------------

## well1024a(entropy)
## well1024a()

Returns a new well1024a instance, which is an object with 3 functions:

* [getUInt32](#getUInt32)
* [getState](#getstate)
* [setState](#setState)

The instance will use `Math.random()` to fill out the initial seed state.

__Arguments__

* entropy - default=[].  Array of numbers to add to the initial seed.  These should be based on environmental values that are likely to be different on each run such as system time, process ID, browser window height, values from `/dev/urandom` etc.

__Example__

```javascript
var w = well1024a([
    Date.now(),
    os.freemem(),
    process.pid
]);
```

-----------------------------------

## getUInt32()

Returns a random positive integer less than 2^32.

__Example__

```javascript
var w = well1024a();

console.log('For Christmas this year, I want ' + w.getUInt32().toString() + ' ponies!');
```

-----------------------------------

## getState()

Returns an object representing the current state of the random number generator.

The object can safely be converted to and restored from JSON.

This object can be used as a parameter to `setState`.

-----------------------------------

## setState(state)

Sets the random number generator to a specific state, allowing for replay of random values.

__Arguments__

* state - Must be object retrieved from an earlier call to `getState()`.

__Example__

This will flip a pair of coins, reset the generator state, and flip the
coins again with the exact same output.

```javascript
var w = well1024a();
var coins = ['heads', 'tails'];

console.log("Flippin' the coins:");
var state = w.getState();
var d1 = coins[w.getUInt32() % 2];
var d2 = coins[w.getUInt32() % 2];
console.log(d1 + " and " + d2);

console.log("Instant replay:");
w.setState(state);
d1 = coins[w.getUInt32() % 2];
d2 = coins[w.getUInt32() % 2];
console.log(d1 + " and " + d2);
```

---------------------------------------

## Notes

No functions rely on `this`, so it's safe to e.g. assign
`randy.good.randInt` to a variable or pass it around as a
parameter.


text:
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../test/dummy/config/environment.rb',  __FILE__)
ActiveRecord::Migrator.migrations_paths = [File.expand_path('../../test/dummy/db/migrate', __FILE__)]
require 'rails/test_help'

# Require PushType testing setup
require 'push_type/testing/setup'
require 'push_type/testing/factories'

# Load support files
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }

class ActionController::TestCase
  before :all do
    @routes = PushType::Api::Engine.routes
    @request.headers['Accept']        = 'application/json'
    @request.headers['Content-Type']  = 'application/json'
  end

  def json_response
    JSON.parse(response.body)
  end
end


text:
var App = require('app');
require('models/host');
require('models/service');
require('models/host_component');
require('mappers/server_data_mapper');
require('views/main/host/summary');

var mainHostSummaryView;
var modelSetup = require('test/init_model_test');

describe('App.MainHostSummaryView', function() {

  beforeEach(function() {
    modelSetup.setupStackServiceComponent();
    mainHostSummaryView = App.MainHostSummaryView.create({content: Em.Object.create()});
  });

  afterEach(function(){
    modelSetup.cleanStackServiceComponent();
  });

  describe("#installedServices", function() {

    beforeEach(function() {
      sinon.stub(App.Service, 'find').returns([Em.Object.create({serviceName: 'S1'})]);
    });
    afterEach(function() {
      App.Service.find.restore();
    });

    it("should return installed services", function() {
      expect(mainHostSummaryView.get('installedServices')).to.eql(['S1']);
    });
  });

  describe('#sortedComponentsFormatter()', function() {

    var tests = Em.A([
      {
        content: Em.Object.create({
          hostComponents: Em.A([
            Em.Object.create({isMaster: false, isSlave: true, componentName: 'B'}),
            Em.Object.create({isMaster: true, isSlave: false, componentName: 'A'}),
            Em.Object.create({isMaster: true, isSlave: false, componentName: 'C'}),
            Em.Object.create({isMaster: false, isSlave: false, componentName: 'D'})
          ])
        }),
        m: 'List of masters, slaves and clients',
        e: ['A', 'C', 'B']
      },
      {
        content: Em.Object.create({
          hostComponents: Em.A([
            Em.Object.create({isMaster: false, isSlave: true, componentName: 'B'}),
            Em.Object.create({isMaster: true, isSlave: false, componentName: 'A'}),
            Em.Object.create({isMaster: true, isSlave: false, componentName: 'C'}),
            Em.Object.create({isMaster: true, isSlave: false, componentName: 'D'})
          ])
        }),
        m: 'List of masters and slaves',
        e: ['A', 'C', 'D', 'B']
      },
      {
        content: Em.Object.create({
          hostComponents: Em.A([
            Em.Object.create({isMaster: true, isSlave: false, componentName: 'B'}),
            Em.Object.create({isMaster: true, isSlave: false, componentName: 'A'}),
            Em.Object.create({isMaster: true, isSlave: false, componentName: 'C'}),
            Em.Object.create({isMaster: true, isSlave: false, componentName: 'D'})
          ])
        }),
        m: 'List of masters',
        e: ['B', 'A', 'C', 'D']
      },
      {
        content: Em.Object.create({
          hostComponents: Em.A([
            Em.Object.create({isMaster: false, isSlave: true, componentName: 'B'}),
            Em.Object.create({isMaster: false, isSlave: true, componentName: 'A'}),
            Em.Object.create({isMaster: false, isSlave: true, componentName: 'C'}),
            Em.Object.create({isMaster: false, isSlave: true, componentName: 'D'})
          ])
        }),
        m: 'List of slaves',
        e: ['B', 'A', 'C', 'D']
      },
      {
        content: Em.Object.create({
          hostComponents: Em.A([])
        }),
        m: 'Empty list',
        e: []
      },
      {
        content: Em.Object.create({
          hostComponents: Em.A([
            Em.Object.create({isMaster: false, isSlave: false, componentName: 'B'}),
            Em.Object.create({isMaster: false, isSlave: false, componentName: 'A'}),
            Em.Object.create({isMaster: false, isSlave: false, componentName: 'C'}),
            Em.Object.create({isMaster: false, isSlave: false, componentName: 'D'})
          ])
        }),
        m: 'List of clients',
        e: []
      }
    ]);

    tests.forEach(function(test) {
      it(test.m, function() {
        test.content.get('hostComponents').forEach(function(component) {
          component.set('id', component.get('componentName'));
        });
        mainHostSummaryView.set('sortedComponents', []);
        mainHostSummaryView.set('content', test.content);
        mainHostSummaryView.sortedComponentsFormatter();
        expect(mainHostSummaryView.get('sortedComponents').mapProperty('componentName')).to.eql(test.e);
      });
    });

  });

  describe('#clients', function() {

    var tests = Em.A([
      {
        content: Em.Object.create({
          hostComponents: Em.A([
            Em.Object.create({isMaster: false, isSlave: true, componentName: 'B'}),
            Em.Object.create({isMaster: true, isSlave: false, componentName: 'A'}),
            Em.Object.create({isMaster: true, isSlave: false, componentName: 'C'}),
            Em.Object.create({isMaster: false, isSlave: false, componentName: 'D'})
          ])
        }),
        m: 'List of masters, slaves and clients',
        e: ['D']
      },
      {
        content: Em.Object.create({
          hostComponents: Em.A([
            Em.Object.create({isMaster: false, isSlave: true, componentName: 'B'}),
            Em.Object.create({isMaster: true, isSlave: false, componentName: 'A'}),
            Em.Object.create({isMaster: true, isSlave: false, componentName: 'C'}),
            Em.Object.create({isMaster: true, isSlave: false, componentName: 'D'})
          ])
        }),
        m: 'List of masters and slaves',
        e: []
      },
      {
        content: Em.Object.create({
          hostComponents: Em.A([
            Em.Object.create({isMaster: true, isSlave: false, componentName: 'B'}),
            Em.Object.create({isMaster: true, isSlave: false, componentName: 'A'}),
            Em.Object.create({isMaster: true, isSlave: false, componentName: 'C'}),
            Em.Object.create({isMaster: true, isSlave: false, componentName: 'D'})
          ])
        }),
        m: 'List of masters',
        e: []
      },
      {
        content: Em.Object.create({
          hostComponents: Em.A([
            Em.Object.create({isMaster: false, isSlave: true, componentName: 'B'}),
            Em.Object.create({isMaster: false, isSlave: true, componentName: 'A'}),
            Em.Object.create({isMaster: false, isSlave: true, componentName: 'C'}),
            Em.Object.create({isMaster: false, isSlave: true, componentName: 'D'})
          ])
        }),
        m: 'List of slaves',
        e: []
      },
      {
        content: Em.Object.create({
          hostComponents: Em.A([])
        }),
        m: 'Empty list',
        e: []
      },
      {
        content: Em.Object.create({
          hostComponents: Em.A([
            Em.Object.create({isMaster: false, isSlave: false, componentName: 'B'}),
            Em.Object.create({isMaster: false, isSlave: false, componentName: 'A'}),
            Em.Object.create({isMaster: false, isSlave: false, componentName: 'C'}),
            Em.Object.create({isMaster: false, isSlave: false, componentName: 'D'})
          ])
        }),
        m: 'List of clients',
        e: ['B', 'A', 'C', 'D']
      }
    ]);

    tests.forEach(function(test) {
      it(test.m, function() {
        mainHostSummaryView.set('content', test.content);
        expect(mainHostSummaryView.get('clients').mapProperty('componentName')).to.eql(test.e);
      });
    });

    it('should set isInstallFailed for clients with INIT and INSTALL_FAILED workStatus', function() {
      mainHostSummaryView.set('content', Em.Object.create({
        hostComponents: [
          Em.Object.create({isMaster: false, isSlave: false, componentName: 'B', workStatus: 'INIT'}),
          Em.Object.create({isMaster: false, isSlave: false, componentName: 'A', workStatus: 'INSTALLED'}),
          Em.Object.create({isMaster: false, isSlave: false, componentName: 'C', workStatus: 'INSTALL_FAILED'}),
          Em.Object.create({isMaster: false, isSlave: false, componentName: 'D', workStatus: 'INSTALLING'})
        ]
      }));
      expect(mainHostSummaryView.get('clients').filterProperty('isInstallFailed', true).mapProperty('componentName')).to.eql(['B', 'C']);
      expect(mainHostSummaryView.get('clients').filterProperty('isInstallFailed', false).mapProperty('componentName')).to.eql(['A', 'D']);
    });

  });

  describe('#areClientWithStaleConfigs', function() {

    var tests = Em.A([
      {
        content: Em.Object.create({
          hostComponents: Em.A([
            Em.Object.create({isMaster: false, isSlave: false, componentName: 'D', staleConfigs: true}),
            Em.Object.create({isMaster: false, isSlave: false, componentName: 'C', staleConfigs: false})
          ])
        }),
        m: 'Some clients with stale configs',
        e: true
      },
      {
        content: Em.Object.create({
          hostComponents: Em.A([
            Em.Object.create({isMaster: false, isSlave: false, componentName: 'D', staleConfigs: false}),
            Em.Object.create({isMaster: false, isSlave: false, componentName: 'C', staleConfigs: false})
          ])
        }),
        m: 'No clients with stale configs',
        e: false
      },
      {
        content: Em.Object.create({
          hostComponents: Em.A([
            Em.Object.create({isMaster: false, isSlave: false, componentName: 'D', staleConfigs: true}),
            Em.Object.create({isMaster: false, isSlave: false, componentName: 'C', staleConfigs: true})
          ])
        }),
        m: 'All clients with stale configs',
        e: true
      },
      {
        content: Em.Object.create({
          hostComponents: Em.A([])
        }),
        m: 'Empty list',
        e: false
      }
    ]);

    tests.forEach(function(test) {
      it(test.m, function() {
        mainHostSummaryView.set('content', test.content);
        expect(mainHostSummaryView.get('areClientWithStaleConfigs')).to.equal(test.e);
      });
    });

  });

  describe('#isAddComponent', function() {

    var tests = Em.A([
      {content: {healthClass: 'health-status-DEAD-YELLOW', hostComponents: Em.A([])}, e: false},
      {content: {healthClass: 'OTHER_VALUE', hostComponents: Em.A([])}, e: true}
    ]);

    tests.forEach(function(test) {
      it(test.content.healthClass, function() {
        mainHostSummaryView.set('content', test.content);
        expect(mainHostSummaryView.get('isAddComponent')).to.equal(test.e);
      });
    });

  });

  describe('#addableComponents', function() {

    beforeEach(function() {
      this.mock = sinon.stub(App.StackServiceComponent, 'find');
      sinon.stub(mainHostSummaryView, 'hasCardinalityConflict').returns(false);
    });
    afterEach(function() {
      App.StackServiceComponent.find.restore();
      mainHostSummaryView.hasCardinalityConflict.restore();
    });

    var tests = Em.A([
      {
        addableToHostComponents: [
          Em.Object.create({
            serviceName: 'HDFS',
            componentName: 'DATANODE',
            isAddableToHost: true
          }),
          Em.Object.create({
            serviceName: 'HDFS',
            componentName: 'HDFS_CLIENT',
            isAddableToHost: true
          })
        ],
        content: Em.Object.create({
          hostComponents: Em.A([
            Em.Object.create({
              componentName: 'HDFS_CLIENT'
            })
          ])
        }),
        services: ['HDFS'],
        e: ['DATANODE'],
        m: 'some components are already installed'
      },
      {
        addableToHostComponents: [
          Em.Object.create({
            serviceName: 'HDFS',
            componentName: 'HDFS_CLIENT',
            isAddableToHost: true
          })
        ],
        content: Em.Object.create({
          hostComponents: Em.A([
            Em.Object.create({
              componentName: 'HDFS_CLIENT'
            })
          ])
        }),
        services: ['HDFS'],
        e: [],
        m: 'all components are already installed'
      }
    ]);

    tests.forEach(function(test) {
      it(test.m, function() {
        this.mock.returns(test.addableToHostComponents);
        mainHostSummaryView.set('content', test.content);
        mainHostSummaryView.reopen({
          installedServices: test.services
        });
        mainHostSummaryView.propertyDidChange('addableComponents');
        expect(mainHostSummaryView.get('addableComponents').mapProperty('componentName')).to.eql(test.e);
      });
    });
  });

  describe('#areClientsNotInstalled', function () {

    var cases = [
      {
        clients: [
          {
            isInstallFailed: true
          }
        ],
        installableClientComponents: [],
        areClientsNotInstalled: true,
        title: 'some clients failed to install, no clients to add'
      },
      {
        clients: [
          {
            isInstallFailed: false
          }
        ],
        installableClientComponents: [{}],
        areClientsNotInstalled: true,
        title: 'no clients failed to install, some clients to add'
      },
      {
        clients: [
          {
            isInstallFailed: true
          }
        ],
        installableClientComponents: [{}],
        areClientsNotInstalled: true,
        title: 'some clients failed to install, some clients to add'
      },
      {
        clients: [
          {
            isInstallFailed: false
          }
        ],
        installableClientComponents: [],
        areClientsNotInstalled: false,
        title: 'no clients failed to install, no clients to add'
      }
    ];

    cases.forEach(function (item) {
      it(item.title, function () {
        mainHostSummaryView.reopen({
          clients: item.clients,
          installableClientComponents: item.installableClientComponents
        });
        expect(mainHostSummaryView.get('areClientsNotInstalled')).to.equal(item.areClientsNotInstalled);
      });
    });

  });

  describe('#notInstalledClientComponents', function () {

    it('should concat not added clients and the ones that failed to install', function () {
      mainHostSummaryView.reopen({
        clients: [
          Em.Object.create({
            componentName: 'c0',
            workStatus: 'INIT'
          }),
          Em.Object.create({
            componentName: 'c1',
            workStatus: 'INSTALL_FAILED'
          }),
          Em.Object.create({
            componentName: 'c2',
            workStatus: 'INSTALLED'
          })
        ],
        installableClientComponents: [
          Em.Object.create({
            componentName: 'c3'
          })
        ]
      });
      expect(mainHostSummaryView.get('notInstalledClientComponents')).to.eql([
        Em.Object.create({
          componentName: 'c0',
          workStatus: 'INIT'
        }),
        Em.Object.create({
          componentName: 'c1',
          workStatus: 'INSTALL_FAILED'
        }),
        Em.Object.create({
          componentName: 'c3'
        })
      ]);
    });

  });

  describe("#needToRestartMessage", function() {

    it("one component", function() {
      var expected = Em.I18n.t('hosts.host.details.needToRestart').format(1, Em.I18n.t('common.component').toLowerCase());
      mainHostSummaryView.set('content', Em.Object.create({
        componentsWithStaleConfigsCount: 1
      }));
      expect(mainHostSummaryView.get('needToRestartMessage')).to.equal(expected);
    });

    it("multiple components", function() {
      var expected = Em.I18n.t('hosts.host.details.needToRestart').format(2, Em.I18n.t('common.components').toLowerCase());
      mainHostSummaryView.set('content', Em.Object.create({
        componentsWithStaleConfigsCount: 2
      }));
      expect(mainHostSummaryView.get('needToRestartMessage')).to.equal(expected);
    });

  });

  describe("#redrawComponents()", function() {

    beforeEach(function() {
      this.mock = sinon.stub(App.router, 'get');
      sinon.stub(mainHostSummaryView, 'sortedComponentsFormatter');
      sinon.stub(App.router, 'set');
    });
    afterEach(function() {
      this.mock.restore();
      mainHostSummaryView.sortedComponentsFormatter.restore();
      App.router.set.restore();
    });

    it("redrawComponents is false", function() {
      this.mock.returns(false);
      mainHostSummaryView.redrawComponents();
      expect(mainHostSummaryView.sortedComponentsFormatter.called).to.be.false;
    });

    it("redrawComponents is true", function() {
      this.mock.returns(true);
      mainHostSummaryView.redrawComponents();
      expect(mainHostSummaryView.sortedComponentsFormatter.calledOnce).to.be.true;
      expect(mainHostSummaryView.get('sorteComponents')).to.be.empty;
      expect(App.router.set.calledWith('mainHostDetailsController.redrawComponents', false)).to.be.true;
    });

  });

  describe("#willInsertElement()", function() {

    beforeEach(function() {
      sinon.stub(mainHostSummaryView, 'sortedComponentsFormatter');
      sinon.stub(mainHostSummaryView, 'addObserver');
    });
    afterEach(function() {
      mainHostSummaryView.sortedComponentsFormatter.restore();
      mainHostSummaryView.addObserver.restore();
    });

    it("sortedComponentsFormatter should be called ", function() {
      mainHostSummaryView.willInsertElement();
      expect(mainHostSummaryView.sortedComponentsFormatter.calledOnce).to.be.true;
      expect(mainHostSummaryView.addObserver.calledWith('content.hostComponents.length', mainHostSummaryView, 'sortedComponentsFormatter')).to.be.true;
      expect(mainHostSummaryView.get('sortedComponents')).to.be.empty;
    });
  });

  describe("#didInsertElement()", function() {

    beforeEach(function() {
      sinon.stub(mainHostSummaryView, 'addToolTip');
    });
    afterEach(function() {
      mainHostSummaryView.addToolTip.restore();
    });

    it("addToolTip should be called", function() {
      mainHostSummaryView.didInsertElement();
      expect(mainHostSummaryView.addToolTip.calledOnce).to.be.true;
    });
  });

  describe("#addToolTip()", function() {

    beforeEach(function() {
      sinon.stub(App, 'tooltip');
      mainHostSummaryView.removeObserver('addComponentDisabled', mainHostSummaryView, 'addToolTip');
    });
    afterEach(function() {
      App.tooltip.restore();
    });

    it("addComponentDisabled is false ", function() {
      mainHostSummaryView.reopen({
        addComponentDisabled: false
      });
      mainHostSummaryView.addToolTip();
      expect(App.tooltip.called).to.be.false;
    });

    it("addComponentDisabled is true ", function() {
      mainHostSummaryView.reopen({
        addComponentDisabled: true
      });
      mainHostSummaryView.addToolTip();
      expect(App.tooltip.called).to.be.true;
    });

  });

  describe("#installableClientComponents", function() {

    beforeEach(function() {
      sinon.stub(App.StackServiceComponent, 'find').returns([
        Em.Object.create({
          isClient: true,
          serviceName: 'S1',
          componentName: 'C1'
        }),
        Em.Object.create({
          isClient: true,
          serviceName: 'S1',
          componentName: 'C2'
        }),
        Em.Object.create({
          isClient: true,
          serviceName: 'S2',
          componentName: 'C1'
        })
      ]);
    });
    afterEach(function() {
      App.StackServiceComponent.find.restore();
    });

    it("should return installable client components", function() {
      mainHostSummaryView.reopen({
        installedServices: ['S1'],
        clients: [
          Em.Object.create({componentName: 'C2'})
        ]
      });
      mainHostSummaryView.propertyDidChange('installableClientComponents');
      expect(mainHostSummaryView.get('installableClientComponents').mapProperty('componentName')).to.eql(['C1']);
    });
  });

  describe("#hasCardinalityConflict()", function () {

    beforeEach(function() {
      this.mockSlave = sinon.stub(App.SlaveComponent, 'find');
      this.mockStack = sinon.stub(App.StackServiceComponent, 'find');
    });

    afterEach(function() {
      this.mockSlave.restore();
      this.mockStack.restore();
    });

    it("totalCount equal to maxToInstall", function() {
      this.mockSlave.returns(Em.Object.create({
        totalCount: 1
      }));
      this.mockStack.returns(Em.Object.create({
        maxToInstall: 1
      }));
      expect(mainHostSummaryView.hasCardinalityConflict('C1')).to.be.true;
    });

    it("totalCount more than maxToInstall", function() {
      this.mockSlave.returns(Em.Object.create({
        totalCount: 2
      }));
      this.mockStack.returns(Em.Object.create({
        maxToInstall: 1
      }));
      expect(mainHostSummaryView.hasCardinalityConflict('C1')).to.be.true;
    });

    it("totalCount less than maxToInstall", function() {
      this.mockSlave.returns(Em.Object.create({
        totalCount: 0
      }));
      this.mockStack.returns(Em.Object.create({
        maxToInstall: 1
      }));
      expect(mainHostSummaryView.hasCardinalityConflict('C1')).to.be.false;
    });
  });

  describe("#installClients()", function () {

    beforeEach(function () {
      var controller = {installClients: Em.K};
      sinon.spy(controller, 'installClients');
      mainHostSummaryView.set('controller', controller);
      mainHostSummaryView.reopen({'notInstalledClientComponents': [1,2,3]});
    });

    afterEach(function () {
      mainHostSummaryView.get('controller.installClients').restore();
    });

    it("should call installClients method from controller", function () {
      mainHostSummaryView.installClients();
      expect(mainHostSummaryView.get('controller.installClients').calledWith([1,2,3])).to.be.true;
    });
  });

  describe("#reinstallClients()", function () {

    beforeEach(function () {
      var controller = {installClients: Em.K};
      sinon.spy(controller, 'installClients');
      mainHostSummaryView.set('controller', controller);
      mainHostSummaryView.reopen({'installFailedClients': [1,2,3]});
    });

    afterEach(function () {
      mainHostSummaryView.get('controller.installClients').restore();
    });

    it("should call installClients method from controller", function () {
      mainHostSummaryView.reinstallClients();
      expect(mainHostSummaryView.get('controller.installClients').calledWith([1,2,3])).to.be.true;
    });
  });
});