text:
#ifndef FREERDP_ERROR_H
#define FREERDP_ERROR_H

#include <winpr/crt.h>

#include <freerdp/api.h>

#ifdef	__cplusplus
extern "C" {
#endif

/**
 * Error Info Codes (Error Info PDU)
 */

/* Protocol-independent codes */
#define ERRINFO_RPC_INITIATED_DISCONNECT			0x00000001
#define ERRINFO_RPC_INITIATED_LOGOFF				0x00000002
#define ERRINFO_IDLE_TIMEOUT					0x00000003
#define ERRINFO_LOGON_TIMEOUT					0x00000004
#define ERRINFO_DISCONNECTED_BY_OTHER_CONNECTION		0x00000005
#define ERRINFO_OUT_OF_MEMORY					0x00000006
#define ERRINFO_SERVER_DENIED_CONNECTION			0x00000007
#define ERRINFO_SERVER_INSUFFICIENT_PRIVILEGES			0x00000009
#define ERRINFO_SERVER_FRESH_CREDENTIALS_REQUIRED		0x0000000A
#define ERRINFO_RPC_INITIATED_DISCONNECT_BY_USER		0x0000000B
#define ERRINFO_LOGOFF_BY_USER					0x0000000C

/* Protocol-independent codes generated by the Connection Broker */
#define	ERRINFO_CB_DESTINATION_NOT_FOUND			0x0000400
#define	ERRINFO_CB_LOADING_DESTINATION				0x0000402
#define	ERRINFO_CB_REDIRECTING_TO_DESTINATION			0x0000404
#define	ERRINFO_CB_SESSION_ONLINE_VM_WAKE			0x0000405
#define	ERRINFO_CB_SESSION_ONLINE_VM_BOOT			0x0000406
#define	ERRINFO_CB_SESSION_ONLINE_VM_NO_DNS			0x0000407
#define	ERRINFO_CB_DESTINATION_POOL_NOT_FREE			0x0000408
#define	ERRINFO_CB_CONNECTION_CANCELLED				0x0000409
#define	ERRINFO_CB_CONNECTION_ERROR_INVALID_SETTINGS		0x0000410
#define	ERRINFO_CB_SESSION_ONLINE_VM_BOOT_TIMEOUT		0x0000411
#define	ERRINFO_CB_SESSION_ONLINE_VM_SESSMON_FAILED		0x0000412

/* Protocol-independent licensing codes */
#define	ERRINFO_LICENSE_INTERNAL				0x00000100
#define ERRINFO_LICENSE_NO_LICENSE_SERVER			0x00000101
#define ERRINFO_LICENSE_NO_LICENSE				0x00000102
#define ERRINFO_LICENSE_BAD_CLIENT_MSG				0x00000103
#define ERRINFO_LICENSE_HWID_DOESNT_MATCH_LICENSE		0x00000104
#define ERRINFO_LICENSE_BAD_CLIENT_LICENSE			0x00000105
#define ERRINFO_LICENSE_CANT_FINISH_PROTOCOL			0x00000106
#define ERRINFO_LICENSE_CLIENT_ENDED_PROTOCOL			0x00000107
#define ERRINFO_LICENSE_BAD_CLIENT_ENCRYPTION			0x00000108
#define ERRINFO_LICENSE_CANT_UPGRADE_LICENSE			0x00000109
#define ERRINFO_LICENSE_NO_REMOTE_CONNECTIONS			0x0000010A

/* RDP specific codes */
#define ERRINFO_UNKNOWN_DATA_PDU_TYPE				0x000010C9
#define ERRINFO_UNKNOWN_PDU_TYPE				0x000010CA
#define ERRINFO_DATA_PDU_SEQUENCE				0x000010CB
#define ERRINFO_CONTROL_PDU_SEQUENCE				0x000010CD
#define ERRINFO_INVALID_CONTROL_PDU_ACTION			0x000010CE
#define ERRINFO_INVALID_INPUT_PDU_TYPE				0x000010CF
#define ERRINFO_INVALID_INPUT_PDU_MOUSE				0x000010D0
#define ERRINFO_INVALID_REFRESH_RECT_PDU			0x000010D1
#define ERRINFO_CREATE_USER_DATA_FAILED				0x000010D2
#define ERRINFO_CONNECT_FAILED					0x000010D3
#define ERRINFO_CONFIRM_ACTIVE_HAS_WRONG_SHAREID		0x000010D4
#define ERRINFO_CONFIRM_ACTIVE_HAS_WRONG_ORIGINATOR		0x000010D5
#define ERRINFO_PERSISTENT_KEY_PDU_BAD_LENGTH			0x000010DA
#define ERRINFO_PERSISTENT_KEY_PDU_ILLEGAL_FIRST		0x000010DB
#define ERRINFO_PERSISTENT_KEY_PDU_TOO_MANY_TOTAL_KEYS		0x000010DC
#define ERRINFO_PERSISTENT_KEY_PDU_TOO_MANY_CACHE_KEYS		0x000010DD
#define ERRINFO_INPUT_PDU_BAD_LENGTH				0x000010DE
#define ERRINFO_BITMAP_CACHE_ERROR_PDU_BAD_LENGTH		0x000010DF
#define ERRINFO_SECURITY_DATA_TOO_SHORT				0x000010E0
#define ERRINFO_VCHANNEL_DATA_TOO_SHORT				0x000010E1
#define ERRINFO_SHARE_DATA_TOO_SHORT				0x000010E2
#define ERRINFO_BAD_SUPPRESS_OUTPUT_PDU				0x000010E3
#define ERRINFO_CONFIRM_ACTIVE_PDU_TOO_SHORT			0x000010E5
#define ERRINFO_CAPABILITY_SET_TOO_SMALL			0x000010E7
#define ERRINFO_CAPABILITY_SET_TOO_LARGE			0x000010E8
#define ERRINFO_NO_CURSOR_CACHE					0x000010E9
#define ERRINFO_BAD_CAPABILITIES				0x000010EA
#define ERRINFO_VIRTUAL_CHANNEL_DECOMPRESSION			0x000010EC
#define ERRINFO_INVALID_VC_COMPRESSION_TYPE			0x000010ED
#define ERRINFO_INVALID_CHANNEL_ID				0x000010EF
#define ERRINFO_VCHANNELS_TOO_MANY				0x000010F0
#define ERRINFO_REMOTEAPP_NOT_ENABLED				0x000010F3
#define ERRINFO_CACHE_CAP_NOT_SET				0x000010F4
#define ERRINFO_BITMAP_CACHE_ERROR_PDU_BAD_LENGTH2 		0x000010F5
#define ERRINFO_OFFSCREEN_CACHE_ERROR_PDU_BAD_LENGTH		0x000010F6
#define ERRINFO_DRAWNINEGRID_CACHE_ERROR_PDU_BAD_LENGTH		0x000010F7
#define ERRINFO_GDIPLUS_PDU_BAD_LENGTH				0x000010F8
#define ERRINFO_SECURITY_DATA_TOO_SHORT2			0x00001111
#define ERRINFO_SECURITY_DATA_TOO_SHORT3			0x00001112
#define ERRINFO_SECURITY_DATA_TOO_SHORT4			0x00001113
#define ERRINFO_SECURITY_DATA_TOO_SHORT5			0x00001114
#define ERRINFO_SECURITY_DATA_TOO_SHORT6			0x00001115
#define ERRINFO_SECURITY_DATA_TOO_SHORT7			0x00001116
#define ERRINFO_SECURITY_DATA_TOO_SHORT8			0x00001117
#define ERRINFO_SECURITY_DATA_TOO_SHORT9			0x00001118
#define ERRINFO_SECURITY_DATA_TOO_SHORT10			0x00001119
#define ERRINFO_SECURITY_DATA_TOO_SHORT11			0x0000111A
#define ERRINFO_SECURITY_DATA_TOO_SHORT12			0x0000111B
#define ERRINFO_SECURITY_DATA_TOO_SHORT13			0x0000111C
#define ERRINFO_SECURITY_DATA_TOO_SHORT14			0x0000111D
#define ERRINFO_SECURITY_DATA_TOO_SHORT15			0x0000111E
#define ERRINFO_SECURITY_DATA_TOO_SHORT16			0x0000111F
#define ERRINFO_SECURITY_DATA_TOO_SHORT17			0x00001120
#define ERRINFO_SECURITY_DATA_TOO_SHORT18			0x00001121
#define ERRINFO_SECURITY_DATA_TOO_SHORT19			0x00001122
#define ERRINFO_SECURITY_DATA_TOO_SHORT20			0x00001123
#define ERRINFO_SECURITY_DATA_TOO_SHORT21			0x00001124
#define ERRINFO_SECURITY_DATA_TOO_SHORT22			0x00001125
#define ERRINFO_SECURITY_DATA_TOO_SHORT23			0x00001126
#define ERRINFO_BAD_MONITOR_DATA				0x00001129
#define ERRINFO_VC_DECOMPRESSED_REASSEMBLE_FAILED		0x0000112A
#define ERRINFO_VC_DATA_TOO_LONG				0x0000112B
#define ERRINFO_GRAPHICS_MODE_NOT_SUPPORTED			0x0000112D
#define ERRINFO_GRAPHICS_SUBSYSTEM_RESET_FAILED			0x0000112E
#define ERRINFO_GRAPHICS_SUBSYSTEM_FAILED			0x0000112F
#define ERRINFO_TIMEZONE_KEY_NAME_LENGTH_TOO_SHORT		0x00001130
#define ERRINFO_TIMEZONE_KEY_NAME_LENGTH_TOO_LONG		0x00001131
#define ERRINFO_DYNAMIC_DST_DISABLED_FIELD_MISSING		0x00001132
#define ERRINFO_VC_DECODING_ERROR				0x00001133
#define ERRINFO_UPDATE_SESSION_KEY_FAILED			0x00001191
#define ERRINFO_DECRYPT_FAILED					0x00001192
#define ERRINFO_ENCRYPT_FAILED					0x00001193
#define ERRINFO_ENCRYPTION_PACKAGE_MISMATCH			0x00001194
#define ERRINFO_DECRYPT_FAILED2					0x00001195
#define ERRINFO_PEER_DISCONNECTED				0x00001196

#define ERRINFO_SUCCESS						0x00000000
#define ERRINFO_NONE						0xFFFFFFFF

FREERDP_API const char* freerdp_get_error_info_string(UINT32 code);
FREERDP_API const char* freerdp_get_error_info_name(UINT32 code);

/**
* This static variable holds an error code if the return value from connect is FALSE.
* This variable is always set to 0 in the beginning of the connect sequence.
* The returned code can be used to inform the user of the detailed connect error.
* The value can hold one of the defined error codes below OR an error according to errno
*/

FREERDP_API extern int connectErrorCode;

#define ERRORSTART 10000
#define PREECONNECTERROR ERRORSTART + 1
#define UNDEFINEDCONNECTERROR ERRORSTART + 2
#define POSTCONNECTERROR ERRORSTART + 3
#define DNSERROR ERRORSTART + 4      /* general DNS ERROR */
#define DNSNAMENOTFOUND ERRORSTART + 5 /* EAI_NONAME */
#define CONNECTERROR ERRORSTART + 6  /* a connect error if errno is not define during tcp connect */
#define MCSCONNECTINITIALERROR ERRORSTART + 7
#define TLSCONNECTERROR ERRORSTART + 8
#define AUTHENTICATIONERROR ERRORSTART + 9
#define INSUFFICIENTPRIVILEGESERROR ERRORSTART + 10
#define CANCELEDBYUSER ERRORSTART + 11

/**
 * FreeRDP Context Error Codes
 */

#define MAKE_FREERDP_ERROR(_class, _type) \
	(((FREERDP_ERROR_ ## _class ## _CLASS) << 16) | (_type))

#define GET_FREERDP_ERROR_CLASS(_errorCode) \
	((_errorCode >> 16) & 0xFFFF)

#define GET_FREERDP_ERROR_TYPE(_errorCode) \
	(_errorCode & 0xFFFF)

#define GET_FREERDP_ERROR_SUBCODE

#define FREERDP_ERROR_BASE						0

/**
 * Error Base Codes
 */
#define FREERDP_ERROR_ERRBASE_CLASS					(FREERDP_ERROR_BASE + 0)

#define ERRBASE_SUCCESS							ERRINFO_SUCCESS
#define ERRBASE_NONE							ERRINFO_NONE

FREERDP_API const char* freerdp_get_error_base_string(UINT32 code);
FREERDP_API const char* freerdp_get_error_base_name(UINT32 code);

#define FREERDP_ERROR_SUCCESS						ERRINFO_SUCCESS
#define FREERDP_ERROR_NONE						ERRINFO_NONE

/* Error Info Codes */

#define FREERDP_ERROR_ERRINFO_CLASS					(FREERDP_ERROR_BASE + 1)

#define FREERDP_ERROR_RPC_INITIATED_DISCONNECT				MAKE_FREERDP_ERROR(ERRINFO, ERRINFO_RPC_INITIATED_DISCONNECT)
#define FREERDP_ERROR_RPC_INITIATED_LOGOFF				MAKE_FREERDP_ERROR(ERRINFO, ERRINFO_RPC_INITIATED_LOGOFF)
#define FREERDP_ERROR_IDLE_TIMEOUT					MAKE_FREERDP_ERROR(ERRINFO, ERRINFO_IDLE_TIMEOUT)
#define FREERDP_ERROR_LOGON_TIMEOUT					MAKE_FREERDP_ERROR(ERRINFO, ERRINFO_LOGON_TIMEOUT)
#define FREERDP_ERROR_DISCONNECTED_BY_OTHER_CONNECTION			MAKE_FREERDP_ERROR(ERRINFO, ERRINFO_DISCONNECTED_BY_OTHER_CONNECTION)
#define FREERDP_ERROR_OUT_OF_MEMORY					MAKE_FREERDP_ERROR(ERRINFO, ERRINFO_OUT_OF_MEMORY)
#define FREERDP_ERROR_SERVER_DENIED_CONNECTION				MAKE_FREERDP_ERROR(ERRINFO, ERRINFO_SERVER_DENIED_CONNECTION)
#define FREERDP_ERROR_SERVER_INSUFFICIENT_PRIVILEGES			MAKE_FREERDP_ERROR(ERRINFO, ERRINFO_SERVER_INSUFFICIENT_PRIVILEGES)
#define FREERDP_ERROR_SERVER_FRESH_CREDENTIALS_REQUIRED			MAKE_FREERDP_ERROR(ERRINFO, ERRINFO_SERVER_FRESH_CREDENTIALS_REQUIRED)
#define FREERDP_ERROR_RPC_INITIATED_DISCONNECT_BY_USER			MAKE_FREERDP_ERROR(ERRINFO, ERRINFO_RPC_INITIATED_DISCONNECT_BY_USER)
#define FREERDP_ERROR_LOGOFF_BY_USER					MAKE_FREERDP_ERROR(ERRINFO, ERRINFO_LOGOFF_BY_USER)

/* Connection Error Codes */
#define ERRCONNECT_PRE_CONNECT_FAILED					0x00000001
#define ERRCONNECT_CONNECT_UNDEFINED					0x00000002
#define ERRCONNECT_POST_CONNECT_FAILED					0x00000003
#define ERRCONNECT_DNS_ERROR						0x00000004
#define ERRCONNECT_DNS_NAME_NOT_FOUND					0x00000005
#define ERRCONNECT_CONNECT_FAILED					0x00000006
#define ERRCONNECT_MCS_CONNECT_INITIAL_ERROR				0x00000007
#define ERRCONNECT_TLS_CONNECT_FAILED					0x00000008
#define ERRCONNECT_AUTHENTICATION_FAILED				0x00000009
#define ERRCONNECT_INSUFFICIENT_PRIVILEGES				0x0000000A
#define ERRCONNECT_CONNECT_CANCELLED					0x0000000B
#define ERRCONNECT_SECURITY_NEGO_CONNECT_FAILED				0x0000000C
#define ERRCONNECT_CONNECT_TRANSPORT_FAILED				0x0000000D
#define ERRCONNECT_PASSWORD_EXPIRED					0x0000000E
/* For non-domain workstation where we can't contact a kerberos server */
#define ERRCONNECT_PASSWORD_CERTAINLY_EXPIRED				0x0000000F
#define ERRCONNECT_CLIENT_REVOKED				0x00000010
#define ERRCONNECT_KDC_UNREACHABLE				0x00000011

#define ERRCONNECT_ACCOUNT_DISABLED					0x00000012
#define ERRCONNECT_PASSWORD_MUST_CHANGE					0x00000013
#define ERRCONNECT_LOGON_FAILURE					0x00000014
#define ERRCONNECT_WRONG_PASSWORD					0x00000015
#define ERRCONNECT_ACCESS_DENIED					0x00000016
#define ERRCONNECT_ACCOUNT_RESTRICTION					0x00000017
#define ERRCONNECT_ACCOUNT_LOCKED_OUT					0x00000018
#define ERRCONNECT_ACCOUNT_EXPIRED					0x00000019
#define ERRCONNECT_LOGON_TYPE_NOT_GRANTED				0x0000001A

#define ERRCONNECT_SUCCESS						ERRINFO_SUCCESS
#define ERRCONNECT_NONE							ERRINFO_NONE

FREERDP_API const char* freerdp_get_error_connect_string(UINT32 code);
FREERDP_API const char* freerdp_get_error_connect_name(UINT32 code);

#define FREERDP_ERROR_CONNECT_CLASS					(FREERDP_ERROR_BASE + 2)

#define FREERDP_ERROR_PRE_CONNECT_FAILED \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_PRE_CONNECT_FAILED)

#define FREERDP_ERROR_CONNECT_UNDEFINED \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_CONNECT_UNDEFINED)

#define FREERDP_ERROR_POST_CONNECT_FAILED	\
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_POST_CONNECT_FAILED)

#define FREERDP_ERROR_DNS_ERROR	\
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_DNS_ERROR)

#define FREERDP_ERROR_DNS_NAME_NOT_FOUND \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_DNS_NAME_NOT_FOUND)

#define FREERDP_ERROR_CONNECT_FAILED \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_CONNECT_FAILED)

#define FREERDP_ERROR_MCS_CONNECT_INITIAL_ERROR \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_MCS_CONNECT_INITIAL_ERROR)

#define FREERDP_ERROR_TLS_CONNECT_FAILED \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_TLS_CONNECT_FAILED)

#define FREERDP_ERROR_AUTHENTICATION_FAILED \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_AUTHENTICATION_FAILED)

#define FREERDP_ERROR_INSUFFICIENT_PRIVILEGES \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_INSUFFICIENT_PRIVILEGES)

#define FREERDP_ERROR_CONNECT_CANCELLED \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_CONNECT_CANCELLED)

#define FREERDP_ERROR_SECURITY_NEGO_CONNECT_FAILED \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_SECURITY_NEGO_CONNECT_FAILED)

#define FREERDP_ERROR_CONNECT_TRANSPORT_FAILED \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_CONNECT_TRANSPORT_FAILED)

#define FREERDP_ERROR_CONNECT_PASSWORD_EXPIRED \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_PASSWORD_EXPIRED)

#define FREERDP_ERROR_CONNECT_PASSWORD_MUST_CHANGE \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_PASSWORD_MUST_CHANGE)

#define FREERDP_ERROR_CONNECT_KDC_UNREACHABLE \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_KDC_UNREACHABLE)

#define FREERDP_ERROR_CONNECT_ACCOUNT_DISABLED \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_ACCOUNT_DISABLED)

#define FREERDP_ERROR_CONNECT_PASSWORD_CERTAINLY_EXPIRED \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_PASSWORD_CERTAINLY_EXPIRED)

#define FREERDP_ERROR_CONNECT_CLIENT_REVOKED \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_CLIENT_REVOKED)

#define FREERDP_ERROR_CONNECT_LOGON_FAILURE \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_LOGON_FAILURE)

#define FREERDP_ERROR_CONNECT_WRONG_PASSWORD \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_WRONG_PASSWORD)

#define FREERDP_ERROR_CONNECT_ACCESS_DENIED \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_ACCESS_DENIED)

#define FREERDP_ERROR_CONNECT_ACCOUNT_RESTRICTION \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_ACCOUNT_RESTRICTION)

#define FREERDP_ERROR_CONNECT_ACCOUNT_LOCKED_OUT \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_ACCOUNT_LOCKED_OUT)

#define FREERDP_ERROR_CONNECT_ACCOUNT_EXPIRED \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_ACCOUNT_EXPIRED)

#define FREERDP_ERROR_CONNECT_LOGON_TYPE_NOT_GRANTED \
	MAKE_FREERDP_ERROR(CONNECT, ERRCONNECT_LOGON_TYPE_NOT_GRANTED)

#ifdef	__cplusplus
}
#endif

#endif	/* FREERDP_ERROR_H */


text:
HTML live form builders and validation for Elm. [![Build Status](https://travis-ci.org/etaque/elm-form.svg?branch=master)](https://travis-ci.org/etaque/elm-form)

    elm package install etaque/elm-form

For when the classical "a message per field" doesn't work well for you, at the price of losing some type safety (field names are made of strings, see [#97](https://github.com/etaque/elm-form/issues/97)).

## Support

We have a dedicated channel in [Elm slack](https://elmlang.herokuapp.com/), join us in `#elm-form` for any question, support or issues coordination.

## Features

* Validation API similar to `Json.Decode` with the standard `map`, `andThen`, etc: you either get the desired output value or all field errors
* HTML inputs helpers with pre-wired handlers for live validation
* Suite of basic validations, with a way to add your own
* Unlimited fields, see `andMap` function (as in `Json.Extra`)
* Nested fields (`foo.bar.baz`) and lists (`todos.1.checked`) enabling rich form build

See [complete example here](http://etaque.github.io/elm-form/example/) ([source code](https://github.com/etaque/elm-form/tree/master/example)).

## Basic usage

See the [example validation test suite](https://github.com/etaque/elm-form/blob/master/tests/ValidationTests.elm)
and [test helper function docs](http://package.elm-lang.org/packages/etaque/elm-form/latest/Form-Test)
for how to test-drive validations.

```elm
module Main exposing (Foo, Model, Msg(..), app, formView, init, update, validate, view)

import Browser
import Form exposing (Form)
import Form.Input as Input
import Form.Validate as Validate exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)

-- your expected form output

type alias Foo =
    { bar : String
    , baz : Bool
    }

-- Add form to your model and msgs

type alias Model =
    { form : Form () Foo }

type Msg
    = NoOp
    | FormMsg Form.Msg

-- Setup form validation

init : Model
init =
    { form = Form.initial [] validate }

validate : Validation () Foo
validate =
    succeed Foo
        |> andMap (field "bar" email)
        |> andMap (field "baz" bool)

-- Forward form msgs to Form.update

update : Msg -> Model -> Model
update msg ({ form } as model) =
    case msg of
        NoOp ->
            model

        FormMsg formMsg ->
            { model | form = Form.update validate formMsg form }

-- Render form with Input helpers

view : Model -> Html Msg
view { form } =
    Html.map FormMsg (formView form)

formView : Form () Foo -> Html Form.Msg
formView form =
    let
        -- error presenter
        errorFor field =
            case field.liveError of
                Just error ->
                    -- replace toString with your own translations
                    div [ class "error" ] [ text (Debug.toString error) ]

                Nothing ->
                    text ""

        -- fields states
        bar =
            Form.getFieldAsString "bar" form

        baz =
            Form.getFieldAsBool "baz" form
    in
    div []
        [ label [] [ text "Bar" ]
        , Input.textInput bar []
        , errorFor bar
        , label []
            [ Input.checkboxInput baz []
            , text "Baz"
            ]
        , errorFor baz
        , button
            [ onClick Form.Submit ]
            [ text "Submit" ]
        ]

app =
    Browser.sandbox
        { init = init
        , update = update
        , view = view
        }

```

## Advanced usage

### Custom inputs

 * For rendering, `Form.getFieldAsString`/`Bool` provides a `FieldState` record with all required fields (see package doc).

 * For event handling, see all field related messages in `Form.Msg` type.

Overall, having a look at current [helpers source code](https://github.com/etaque/elm-form/blob/master/src/Form/Input.elm) should give you a good idea of the thing.

### Incremental validation

Similar to what Json.Extra provides you can also use `Form.andMap`

```elm
Form.succeed Player
    |> andMap (field "email" (string |> andThen email))
    |> andMap (field "power" int)
```

### Nested records

* Validation:

```elm
validation =
    map2 Player
        (field "email" (string |> andThen email))
        (field "power" (int |> andThen (minInt 0)))
        (field "options"
            (map2 Options
                (field "foo" string)
                (field "bar" string)
            )
        )
```

* View:

```elm
Input.textInput (Form.getFieldAsString "options.foo" form) []
```

### Dynamic lists

```elm
-- model
type alias TodoList =
    { title : String
    , items : List String
    }

-- validation
validation : Validation () Issue
validation =
    map2 TodoList
        (field "title" string)
        (field "items" (list string))

-- view
formView : Form () Issue -> Html Form.Msg
formView form =
    div
        [ class "todo-list" ]
        [ Input.textInput
            (Form.getFieldAsString "title" form)
            [ placeholder "Title" ]
        , div [ class "items" ] <|
            List.map
                (itemView form)
                (Form.getListIndexes "items" form)
        , button
            [ class "add"
            , onClick (Form.Append "items")
            ]
            [ text "Add" ]
        ]

itemView : Form () Issue -> Int -> Html Form.Msg
itemView form i =
    div
        [ class "item" ]
        [ Input.textInput
            (Form.getFieldAsString ("items." ++ (String.fromInt i)) form)
            []
        , a
            [ class "remove"
            , onClick (Form.RemoveItem "items" i)
            ]
            [ text "Remove" ]
        ]
```

### Initial values and reset

* At form initialization:

```elm
import Form.Field as Field

initialFields : List ( String, Field )
initialFields =
    [ ( "power", Field.string "10" )
    , ( "options"
      , Field.group
            [ ( "foo", Field.string "blah" )
            , ( "bar", Field.string "meh" )
            ]
      )
    ]

initialForm : Form
initialForm =
    Form.initial initialFields validation
```

See `Form.Field` type for more options.

* On demand:

```elm
button [ onClick (Form.Reset initialFields) ] [ text "Reset" ]
```

*Note:* To have programmatic control over any `input[type=text]`/`textarea` value, like reseting or changing the value, you must set the `value` attribute with `Maybe.withDefault "" state.value`, as seen [here](https://github.com/etaque/elm-form/pull/57/files#diff-bfb877e82b2c89b329fcda943a258611R50). There's a downside of doing this: if the user types too fast, the caret can go crazy.

More info: https://github.com/evancz/elm-html/pull/81#issuecomment-145676200

### Custom errors

```elm
type LocalError = Fatal | NotSoBad

validation : Validation LocalError Foo
validation =
    (field "foo" (string |> customError Fatal))

-- creates `Form.Error.CustomError Fatal`
```

### Async validation

This package doesn't provide anything special for async validation, but doesn't prevent you to do that either. As field values are accessible from `update` with `Form.getStringAt/getBoolAt`, you can process them as you need, trigger effects like an HTTP request, and then add any errors to the view by yourself.

Another way would be to enable dynamic validation reload, to make it dependant of an effect, as it's part of the form state. Please ping me if this feature would be useful to you.

redpajama_set_name: RedPajamaGithub


text:
#include <stdbool.h>
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#ifdef __BORLANDC__
#include <process.h>
#endif
#include "bacdef.h"
#include "bacaddr.h"
#include "mstp.h"
#include "dlmstp.h"
#include "rs485.h"
#include "npdu.h"
#include "bits.h"
#include "ringbuf.h"
#include "timer.h"

#define WIN32_LEAN_AND_MEAN
#define STRICT 1
#include <windows.h>

/* Number of MS/TP Packets Rx/Tx */
uint16_t MSTP_Packets = 0;

/* packet queues */
static DLMSTP_PACKET Receive_Packet;
static HANDLE Receive_Packet_Flag;
/* mechanism to wait for a frame in state machine */
HANDLE Received_Frame_Flag;
static DLMSTP_PACKET Transmit_Packet;
/* local MS/TP port data - shared with RS-485 */
volatile struct mstp_port_struct_t MSTP_Port;
/* buffers needed by mstp port struct */
static uint8_t TxBuffer[MAX_MPDU];
static uint8_t RxBuffer[MAX_MPDU];
/* The minimum time without a DataAvailable or ReceiveError event */
/* that a node must wait for a station to begin replying to a */
/* confirmed request: 255 milliseconds. (Implementations may use */
/* larger values for this timeout, not to exceed 300 milliseconds.) */
static uint16_t Treply_timeout = 260;
/* The minimum time without a DataAvailable or ReceiveError event that a */
/* node must wait for a remote node to begin using a token or replying to */
/* a Poll For Master frame: 20 milliseconds. (Implementations may use */
/* larger values for this timeout, not to exceed 100 milliseconds.) */
static uint8_t Tusage_timeout = 95/*50*/;

unsigned long hThread1 = 0;
unsigned long hThread2 = 0;

bool thread1_run_flag = 1;
bool thread2_run_flag = 1;

static unsigned char source_addr[255] = { 0 };
static unsigned char source_addr_count = 0;
unsigned char mstp_polling_node = 0;
/* Timer that indicates line silence - and functions */
static uint32_t Timer_Silence(
    void *pArg)
{
    return timer_milliseconds(TIMER_SILENCE);
}

static void Timer_Silence_Reset(
    void *pArg)
{
    timer_reset(TIMER_SILENCE);
}

void dlmstp_cleanup(
    void)
{
    /* nothing to do for static buffers */
    if (Received_Frame_Flag) {
        CloseHandle(Received_Frame_Flag);
    }
    if (Receive_Packet_Flag) {
        CloseHandle(Receive_Packet_Flag);
    }
}

/* returns number of bytes sent on success, zero on failure */
int dlmstp_send_pdu(
    BACNET_ADDRESS * dest,      /* destination address */
    BACNET_NPDU_DATA * npdu_data,       /* network information */
    uint8_t * pdu,      /* any data to be sent - may be null */
    unsigned pdu_len)
{       /* number of bytes of data */
    int bytes_sent = 0;
    unsigned i = 0;

    if (!Transmit_Packet.ready) {
        if (npdu_data->data_expecting_reply) {
            Transmit_Packet.frame_type =
                FRAME_TYPE_BACNET_DATA_EXPECTING_REPLY;
        } else {
            Transmit_Packet.frame_type =
                FRAME_TYPE_BACNET_DATA_NOT_EXPECTING_REPLY;
        }
        Transmit_Packet.pdu_len = (uint16_t) pdu_len;
        for (i = 0; i < pdu_len; i++) {
            Transmit_Packet.pdu[i] = pdu[i];
        }
        bacnet_address_copy(&Transmit_Packet.address, dest);
        bytes_sent = pdu_len + MAX_HEADER;
        Transmit_Packet.ready = true;
    }

    return bytes_sent;
}

uint16_t dlmstp_receive(
    BACNET_ADDRESS * src,       /* source address */
    uint8_t * pdu,      /* PDU data */
    uint16_t max_pdu,   /* amount of space available in the PDU  */
    unsigned timeout)
{       /* milliseconds to wait for a packet */
    uint16_t pdu_len = 0;
    DWORD wait_status = 0;

    (void) max_pdu;
    /* see if there is a packet available, and a place
       to put the reply (if necessary) and process it */
    wait_status = WaitForSingleObject(Receive_Packet_Flag, timeout);
    if (wait_status == WAIT_OBJECT_0)
    {
        if (Receive_Packet.ready) {
            if (Receive_Packet.pdu_len) {
                MSTP_Packets++;
                if (src) {
                    memmove(src, &Receive_Packet.address,
                        sizeof(Receive_Packet.address));
                }
                if (pdu) {
                    memmove(pdu, &Receive_Packet.pdu,
                        sizeof(Receive_Packet.pdu));
                }
                pdu_len = Receive_Packet.pdu_len;
            }
            Receive_Packet.ready = false;
        }
    }
    else if (wait_status == STATUS_TIMEOUT)
    {
        Sleep(1);
    }

    return pdu_len;
}

static void dlmstp_receive_fsm_task(
    void *pArg)
{
    bool received_frame;

    (void) pArg;
    (void) SetThreadPriority(GetCurrentThread(),
        THREAD_PRIORITY_TIME_CRITICAL);
    //for (;;)
    while(thread1_run_flag)
    {
        /* only do receive state machine while we don't have a frame */
        if ((MSTP_Port.ReceivedValidFrame == false) &&
            (MSTP_Port.ReceivedInvalidFrame == false)) {
            do {
                RS485_Check_UART_Data(&MSTP_Port);
                MSTP_Receive_Frame_FSM(&MSTP_Port);
                received_frame = MSTP_Port.ReceivedValidFrame ||
                    MSTP_Port.ReceivedInvalidFrame;
                if (received_frame) {
                    ReleaseSemaphore(Received_Frame_Flag, 1, NULL);
                    break;
                }
            } while (MSTP_Port.DataAvailable);
        }
    }
}

//
///**
//* Description:Êý×éÈ¥ÖØËã·¨
//*/
//int arraydiff(unsigned char *A, unsigned char max, int len)
//{
//    unsigned char arrayflag[256];
//    int i, j;
//
//    //³õ'»¯±êÖ¾Êý×é
//    for (i = 0; i <= max; i++)
//    {
//        arrayflag[i] = false;
//    }
//
//    //ÌÞ³ýËã·¨
//    for (i = 0; i < len; i++)
//    {
//        arrayflag[A[i]] = A[i];
//    }
//
//    for (int i = 0; i < max; i++)
//    {
//        A[i] = 0;
//    }
//
//    //È¡³öÓÐЧÊý
//    for (i = 0, j = 0; i <= max; i++)
//    {
//        if (arrayflag[i] != false)
//        {
//            A[j++] = arrayflag[i];
//        }
//    }
//    return j;
//}

volatile struct mstp_port_struct_t MSTP_Port_Debug;
static void dlmstp_master_fsm_task(
    void *pArg)
{
    DWORD dwMilliseconds = 0;
    memset(source_addr, 0, 255);
    source_addr_count = 0;
    (void) pArg;
    (void) SetThreadPriority(GetCurrentThread(),
        THREAD_PRIORITY_TIME_CRITICAL);
    //for (;;)
    while(thread2_run_flag)
    {
        switch (MSTP_Port.master_state) {
            case MSTP_MASTER_STATE_IDLE:
                dwMilliseconds = Tno_token;
                break;
            case MSTP_MASTER_STATE_WAIT_FOR_REPLY:
                dwMilliseconds = Treply_timeout;
                break;
            case MSTP_MASTER_STATE_POLL_FOR_MASTER:
                dwMilliseconds = Tusage_timeout;
                break;
            default:
                dwMilliseconds = 0;
                break;
        }
        if (dwMilliseconds)
            WaitForSingleObject(Received_Frame_Flag, dwMilliseconds);
        MSTP_Master_Node_FSM(&MSTP_Port);
        memcpy(&MSTP_Port_Debug, &MSTP_Port, sizeof(MSTP_Port_Debug));

        //static int n_count = 0;
        //n_count++;
        //remove("C:\\log.txt");
        //FILE *st_dout;
        //st_dout = fopen("C:\\log.txt", "a");
        //fprintf(st_dout, "Count = %d Start\r\n", n_count);
        ////fprintf(st_dout, "test%d:\r\n", MSTP_Port.);
        //fprintf(st_dout, "Count = %d End\r\n", n_count);
        //fclose(st_dout);

        if (MSTP_Port_Debug.SourceAddress != 0)
        {
            int find_exsit = 0;
            for (int i = 0; i < source_addr_count; i++)
            {
                if (MSTP_Port_Debug.SourceAddress == source_addr[i])
                {
                    find_exsit = 1;
                    break;
                }
            }

            if (find_exsit == 0)
            {
                source_addr[source_addr_count] = MSTP_Port_Debug.SourceAddress;
                source_addr_count++;
            }
        }

        //if (source_addr_count > 0)
        //{
        //    unsigned char max_addr = 0;
        //    for (int j = 1; j < source_addr_count; j++)
        //    {
        //        if (max_addr < source_addr[j])
        //            max_addr = source_addr[j];
        //    }

        //    arraydiff(source_addr, max_addr, source_addr_count);
        //}

    }
}

void dlmstp_fill_bacnet_address(
    BACNET_ADDRESS * src,
    uint8_t mstp_address)
{
    int i = 0;

    if (mstp_address == MSTP_BROADCAST_ADDRESS) {
        /* mac_len = 0 if broadcast address */
        src->mac_len = 0;
        src->mac[0] = 0;
    } else {
        src->mac_len = 1;
        src->mac[0] = mstp_address;
    }
    /* fill with 0's starting with index 1; index 0 filled above */
    for (i = 1; i < MAX_MAC_LEN; i++) {
        src->mac[i] = 0;
    }
    src->net = 0;
    src->len = 0;
    for (i = 0; i < MAX_MAC_LEN; i++) {
        src->adr[i] = 0;
    }
}

/* for the MS/TP state machine to use for putting received data */
uint16_t MSTP_Put_Receive(
    volatile struct mstp_port_struct_t *mstp_port)
{
    uint16_t pdu_len = 0;
    BOOL rc;

    if (!Receive_Packet.ready) {
        /* bounds check - maybe this should send an abort? */
        pdu_len = mstp_port->DataLength;
        if (pdu_len > sizeof(Receive_Packet.pdu))
            pdu_len = sizeof(Receive_Packet.pdu);
        memmove((void *) &Receive_Packet.pdu[0],
            (void *) &mstp_port->InputBuffer[0], pdu_len);
        dlmstp_fill_bacnet_address(&Receive_Packet.address,
            mstp_port->SourceAddress);
        Receive_Packet.pdu_len = mstp_port->DataLength;
        Receive_Packet.ready = true;
        rc = ReleaseSemaphore(Receive_Packet_Flag, 1, NULL);
        (void) rc;
    }

    return pdu_len;
}

/* for the MS/TP state machine to use for getting data to send */
/* Return: amount of PDU data */
uint16_t MSTP_Get_Send(
    volatile struct mstp_port_struct_t * mstp_port,
    unsigned timeout)
{       /* milliseconds to wait for a packet */
    uint16_t pdu_len = 0;
    uint8_t destination = 0;    /* destination address */

    (void) timeout;
    if (!Transmit_Packet.ready) {
        return 0;
    }
    /* load destination MAC address */
    if (Transmit_Packet.address.mac_len) {
        destination = Transmit_Packet.address.mac[0];
    } else {
        destination = MSTP_BROADCAST_ADDRESS;
    }
    if ((MAX_HEADER + Transmit_Packet.pdu_len) > MAX_MPDU) {
        return 0;
    }
    /* convert the PDU into the MSTP Frame */
    pdu_len = MSTP_Create_Frame(&mstp_port->OutputBuffer[0],    /* <-- loading this */
        mstp_port->OutputBufferSize, Transmit_Packet.frame_type, destination,
        mstp_port->This_Station, &Transmit_Packet.pdu[0],
        Transmit_Packet.pdu_len);
    Transmit_Packet.ready = false;

    return pdu_len;
}

static bool dlmstp_compare_data_expecting_reply(
    uint8_t * request_pdu,
    uint16_t request_pdu_len,
    uint8_t src_address,
    uint8_t * reply_pdu,
    uint16_t reply_pdu_len,
    BACNET_ADDRESS * dest_address)
{
    uint16_t offset;
    /* One way to check the message is to compare NPDU
       src, dest, along with the APDU type, invoke id.
       Seems a bit overkill */
    struct DER_compare_t {
        BACNET_NPDU_DATA npdu_data;
        BACNET_ADDRESS address;
        uint8_t pdu_type;
        uint8_t invoke_id;
        uint8_t service_choice;
    };
    struct DER_compare_t request;
    struct DER_compare_t reply;

    /* unused parameters */
    request_pdu_len = request_pdu_len;
    reply_pdu_len = reply_pdu_len;
    /* decode the request data */
    request.address.mac[0] = src_address;
    request.address.mac_len = 1;
    offset =
        (uint16_t) npdu_decode(&request_pdu[0], NULL, &request.address,
        &request.npdu_data);
    if (request.npdu_data.network_layer_message) {
        return false;
    }
    request.pdu_type = request_pdu[offset] & 0xF0;
    if (request.pdu_type != PDU_TYPE_CONFIRMED_SERVICE_REQUEST) {
        return false;
    }
    request.invoke_id = request_pdu[offset + 2];
    /* segmented message? */
    if (request_pdu[offset] & BIT3)
        request.service_choice = request_pdu[offset + 5];
    else
        request.service_choice = request_pdu[offset + 3];
    /* decode the reply data */
    bacnet_address_copy(&reply.address, dest_address);
    offset =
        (uint16_t) npdu_decode(&reply_pdu[0], &reply.address, NULL,
        &reply.npdu_data);
    if (reply.npdu_data.network_layer_message) {
        return false;
    }
    /* reply could be a lot of things:
       confirmed, simple ack, abort, reject, error */
    reply.pdu_type = reply_pdu[offset] & 0xF0;
    switch (reply.pdu_type) {
        case PDU_TYPE_CONFIRMED_SERVICE_REQUEST:
            reply.invoke_id = reply_pdu[offset + 2];
            /* segmented message? */
            if (reply_pdu[offset] & BIT3)
                reply.service_choice = reply_pdu[offset + 5];
            else
                reply.service_choice = reply_pdu[offset + 3];
            break;
        case PDU_TYPE_SIMPLE_ACK:
            reply.invoke_id = reply_pdu[offset + 1];
            reply.service_choice = reply_pdu[offset + 2];
            break;
        case PDU_TYPE_COMPLEX_ACK:
            reply.invoke_id = reply_pdu[offset + 1];
            /* segmented message? */
            if (reply_pdu[offset] & BIT3)
                reply.service_choice = reply_pdu[offset + 4];
            else
                reply.service_choice = reply_pdu[offset + 2];
            break;
        case PDU_TYPE_ERROR:
            reply.invoke_id = reply_pdu[offset + 1];
            reply.service_choice = reply_pdu[offset + 2];
            break;
        case PDU_TYPE_REJECT:
        case PDU_TYPE_ABORT:
            reply.invoke_id = reply_pdu[offset + 1];
            break;
        default:
            return false;
    }
    /* these don't have service choice included */
    if ((reply.pdu_type == PDU_TYPE_REJECT) ||
        (reply.pdu_type == PDU_TYPE_ABORT)) {
        if (request.invoke_id != reply.invoke_id) {
            return false;
        }
    } else {
        if (request.invoke_id != reply.invoke_id) {
            return false;
        }
        if (request.service_choice != reply.service_choice) {
            return false;
        }
    }
    if (request.npdu_data.protocol_version != reply.npdu_data.protocol_version) {
        return false;
    }
#if 0
    /* the NDPU priority doesn't get passed through the stack, and
       all outgoing messages have NORMAL priority */
    if (request.npdu_data.priority != reply.npdu_data.priority) {
        return false;
    }
#endif
    if (!bacnet_address_same(&request.address, &reply.address)) {
        return false;
    }

    return true;
}

/* Get the reply to a DATA_EXPECTING_REPLY frame, or nothing */
uint16_t MSTP_Get_Reply(
    volatile struct mstp_port_struct_t * mstp_port,
    unsigned timeout)
{       /* milliseconds to wait for a packet */
    uint16_t pdu_len = 0;       /* return value */
    uint8_t destination = 0;    /* destination address */
    bool matched = false;

    (void) timeout;
    if (!Transmit_Packet.ready) {
        return 0;
    }
    /* load destination MAC address */
    if (Transmit_Packet.address.mac_len == 1) {
        destination = Transmit_Packet.address.mac[0];
    } else {
        return 0;
    }
    if ((MAX_HEADER + Transmit_Packet.pdu_len) > MAX_MPDU) {
        return 0;
    }
    /* is this the reply to the DER? */
    matched =
        dlmstp_compare_data_expecting_reply(&mstp_port->InputBuffer[0],
        mstp_port->DataLength, mstp_port->SourceAddress,
        &Transmit_Packet.pdu[0], Transmit_Packet.pdu_len,
        &Transmit_Packet.address);
    if (!matched)
        return 0;
    /* convert the PDU into the MSTP Frame */
    pdu_len = MSTP_Create_Frame(&mstp_port->OutputBuffer[0],    /* <-- loading this */
        mstp_port->OutputBufferSize, Transmit_Packet.frame_type, destination,
        mstp_port->This_Station, &Transmit_Packet.pdu[0],
        Transmit_Packet.pdu_len);
    Transmit_Packet.ready = false;

    return pdu_len;
}

void dlmstp_set_mac_address(
    uint8_t mac_address)
{
    /* Master Nodes can only have address 0-127 */
    if (mac_address <= 127) {
        MSTP_Port.This_Station = mac_address;
        /* FIXME: implement your data storage */
        /* I2C_Write_Byte(
           EEPROM_DEVICE_ADDRESS,
           mac_address,
           EEPROM_MSTP_MAC_ADDR); */
        if (mac_address > MSTP_Port.Nmax_master)
            dlmstp_set_max_master(mac_address);
    }

    return;
}

uint8_t dlmstp_mac_address(
    void)
{
    return MSTP_Port.This_Station;
}

/* This parameter represents the value of the Max_Info_Frames property of */
/* the node's Device object. The value of Max_Info_Frames specifies the */
/* maximum number of information frames the node may send before it must */
/* pass the token. Max_Info_Frames may have different values on different */
/* nodes. This may be used to allocate more or less of the available link */
/* bandwidth to particular nodes. If Max_Info_Frames is not writable in a */
/* node, its value shall be 1. */
void dlmstp_set_max_info_frames(
    uint8_t max_info_frames)
{
    if (max_info_frames >= 1) {
        MSTP_Port.Nmax_info_frames = max_info_frames;
        /* FIXME: implement your data storage */
        /* I2C_Write_Byte(
           EEPROM_DEVICE_ADDRESS,
           (uint8_t)max_info_frames,
           EEPROM_MSTP_MAX_INFO_FRAMES_ADDR); */
    }

    return;
}

uint8_t dlmstp_max_info_frames(
    void)
{
    return MSTP_Port.Nmax_info_frames;
}

/* This parameter represents the value of the Max_Master property of the */
/* node's Device object. The value of Max_Master specifies the highest */
/* allowable address for master nodes. The value of Max_Master shall be */
/* less than or equal to 127. If Max_Master is not writable in a node, */
/* its value shall be 127. */
void dlmstp_set_max_master(
    uint8_t max_master)
{
    if (max_master <= 254) {
        if (MSTP_Port.This_Station <= max_master) {
            MSTP_Port.Nmax_master = max_master;
            /* FIXME: implement your data storage */
            /* I2C_Write_Byte(
               EEPROM_DEVICE_ADDRESS,
               max_master,
               EEPROM_MSTP_MAX_MASTER_ADDR); */
        }
    }

    return;
}

uint8_t dlmstp_max_master(
    void)
{
    return MSTP_Port.Nmax_master;
}

/* RS485 Baud Rate 9600, 19200, 38400, 57600, 115200 */
void dlmstp_set_baud_rate(
    uint32_t baud)
{
    RS485_Set_Baud_Rate(baud);
}

uint32_t dlmstp_baud_rate(
    void)
{
    return RS485_Get_Baud_Rate();
}

void dlmstp_get_my_address(
    BACNET_ADDRESS * my_address)
{
    int i = 0;  /* counter */

    my_address->mac_len = 1;
    my_address->mac[0] = MSTP_Port.This_Station;
    my_address->net = 0;        /* local only, no routing */
    my_address->len = 0;
    for (i = 0; i < MAX_MAC_LEN; i++) {
        my_address->adr[i] = 0;
    }

    return;
}

void dlmstp_get_broadcast_address(
    BACNET_ADDRESS * dest)
{       /* destination address */
    int i = 0;  /* counter */

    if (dest) {
        dest->mac_len = 1;
        dest->mac[0] = MSTP_BROADCAST_ADDRESS;
        dest->net = BACNET_BROADCAST_NETWORK;
        dest->len = 0;  /* always zero when DNET is broadcast */
        for (i = 0; i < MAX_MAC_LEN; i++) {
            dest->adr[i] = 0;
        }
    }

    return;
}

  void Set_Thread1_Status(bool nstatus)
  {
      thread1_run_flag = nstatus;
  }

  void Set_Thread2_Status(bool nstatus)
  {
      thread2_run_flag = nstatus;
  }

  void Get_MSTP_STRUCT(struct mstp_port_struct_t * mstp_port)
  {
      memcpy(mstp_port, &MSTP_Port_Debug, sizeof(MSTP_Port_Debug));
  }

  void Get_MSTP_Nodes(unsigned char * node_address , unsigned char *ncount)
  {
      memcpy(node_address, source_addr, 255);
      *ncount = source_addr_count;
  }

  void Set_MSTP_Polling_Node(unsigned char node)
  {
      if (node > 2)
          node = node - 2;
      mstp_polling_node = node;
  }

  unsigned long  Get_Thread1()
  {
      return hThread1;
  }

  unsigned long  Get_Thread2()
  {
      return hThread2;
  }

bool dlmstp_init(
    char *ifname)
{
  //  unsigned long hThread = 0;
    int rs485_ret = 0;
    uint32_t arg_value = 0;
    thread1_run_flag = 1;
    thread2_run_flag = 1;
	Sleep(1);
    /* initialize packet queue */
    Receive_Packet.ready = false;
    Receive_Packet.pdu_len = 0;
    Receive_Packet_Flag = CreateSemaphore(NULL, 0, 1, "dlmstpReceivePacket");
    if (Receive_Packet_Flag == NULL)
    {
        return 0;
    }
    Received_Frame_Flag = CreateSemaphore(NULL, 0, 1, "dlsmtpReceiveFrame");
    if (Received_Frame_Flag == NULL) {
        CloseHandle(Receive_Packet_Flag);
        return 0;
    }
    /* initialize hardware */
    timer_init();
    if (ifname) {
        RS485_Set_Interface(ifname);
    }
    rs485_ret = RS485_Initialize();
    if (rs485_ret == 0)
        return false;
    MSTP_Port.InputBuffer = &RxBuffer[0];
    MSTP_Port.InputBufferSize = sizeof(RxBuffer);
    MSTP_Port.OutputBuffer = &TxBuffer[0];
    MSTP_Port.OutputBufferSize = sizeof(TxBuffer);
    MSTP_Port.SilenceTimer = Timer_Silence;
    MSTP_Port.SilenceTimerReset = Timer_Silence_Reset;
    MSTP_Port.This_Station = 0;
    MSTP_Init(&MSTP_Port);
#if 0
    uint8_t data;

    /* FIXME: implement your data storage */
    data = 64;  /* I2C_Read_Byte(
                   EEPROM_DEVICE_ADDRESS,
                   EEPROM_MSTP_MAC_ADDR); */
    if (data <= 127)
        MSTP_Port.This_Station = data;
    else
        dlmstp_set_my_address(DEFAULT_MAC_ADDRESS);
    /* FIXME: implement your data storage */
    data = 127; /* I2C_Read_Byte(
                   EEPROM_DEVICE_ADDRESS,
                   EEPROM_MSTP_MAX_MASTER_ADDR); */
    if ((data <= 127) && (data >= MSTP_Port.This_Station))
        MSTP_Port.Nmax_master = data;
    else
        dlmstp_set_max_master(DEFAULT_MAX_MASTER);
    /* FIXME: implement your data storage */
    data = 1;
    /* I2C_Read_Byte(
       EEPROM_DEVICE_ADDRESS,
       EEPROM_MSTP_MAX_INFO_FRAMES_ADDR); */
    if (data >= 1)
        MSTP_Port.Nmax_info_frames = data;
    else
        dlmstp_set_max_info_frames(DEFAULT_MAX_INFO_FRAMES);
#endif
#if PRINT_ENABLED
    fprintf(stderr, "MS/TP MAC: %02X\n", MSTP_Port.This_Station);
    fprintf(stderr, "MS/TP Max_Master: %02X\n", MSTP_Port.Nmax_master);
    fprintf(stderr, "MS/TP Max_Info_Frames: %u\n",
        (unsigned) MSTP_Port.Nmax_info_frames);
#endif
    //hThread1 = _beginthread(dlmstp_receive_fsm_task, 4096, &arg_value);
	  hThread1 = _beginthread(dlmstp_receive_fsm_task, 4096, &arg_value);
    if (hThread1 == 0) {
        fprintf(stderr, "Failed to start recive FSM task\n");
        return 0;
    }
    //hThread2 = _beginthread(dlmstp_master_fsm_task, 4096, &arg_value);
	  hThread2 = _beginthread(dlmstp_master_fsm_task, 4096, &arg_value);
    if (hThread2 == 0) {
        fprintf(stderr, "Failed to start Master Node FSM task\n");
        return 0;
    }

    return true;
}

#ifdef TEST_DLMSTP
#include <stdio.h>

void apdu_handler(
    BACNET_ADDRESS * src,       /* source address */
    uint8_t * apdu,     /* APDU data */
    uint16_t pdu_len)
{       /* for confirmed messages */
    (void) src;
    (void) apdu;
    (void) pdu_len;
}

/* returns a delta timestamp */
uint32_t timestamp_ms(
    void)
{
    DWORD ticks = 0, delta_ticks = 0;
    static DWORD last_ticks = 0;

    ticks = GetTickCount();
    delta_ticks =
        (ticks >= last_ticks ? ticks - last_ticks : MAXDWORD - last_ticks);
    last_ticks = ticks;

    return delta_ticks;
}

static char *Network_Interface = NULL;

int main(
    int argc,
    char *argv[])
{
    uint16_t pdu_len = 0;

    /* argv has the "COM4" or some other device */
    if (argc > 1) {
        Network_Interface = argv[1];
    }
    dlmstp_set_baud_rate(38400);
    dlmstp_set_mac_address(0x05);
    dlmstp_set_max_info_frames(DEFAULT_MAX_INFO_FRAMES);
    dlmstp_set_max_master(DEFAULT_MAX_MASTER);
    dlmstp_init(Network_Interface);
    /* forever task */
    for (;;) {
        pdu_len = dlmstp_receive(NULL, NULL, 0, INFINITE);
#if 0
        MSTP_Create_And_Send_Frame(&MSTP_Port, FRAME_TYPE_TEST_REQUEST,
            MSTP_Port.SourceAddress, MSTP_Port.This_Station, NULL, 0);
#endif
    }

    return 0;
}
#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.maxur</groupId>
        <artifactId>maxur-base-sample</artifactId>
        <version>0.1-SNAPSHOT</version>
    </parent>

    <artifactId>maxur-base-sample-junit</artifactId>
    <version>0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>maxur-base-sample-junit</name>

</project>


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MigratorMigrationsCommand.cs" company="KlusterKite">
//   All rights reserved
// </copyright>
// <summary>
//   The description of migrator action to migrate resources
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace KlusterKite.NodeManager.RemoteDomain
{
    using System.Collections.Generic;

    using JetBrains.Annotations;

    /// <summary>
    /// The description of migrator action to migrate resources within same migrator
    /// </summary>
    public class MigratorMigrationsCommand
    {
        /// <summary>
        /// Gets or sets the migrator type name
        /// </summary>
        public string TypeName { get; set; }

        /// <summary>
        /// Gets or sets the list of resources to migrate
        /// </summary>
        [UsedImplicitly]
        public List<ResourceMigrationCommand> Resources { get; set; } = new List<ResourceMigrationCommand>();
    }
}


text:
package com.github.benmanes.caffeine.cache.simulator.membership.bloom;

import com.github.benmanes.caffeine.cache.simulator.BasicSettings;
import com.github.benmanes.caffeine.cache.simulator.BasicSettings.MembershipSettings;
import com.github.benmanes.caffeine.cache.simulator.membership.Membership;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import com.typesafe.config.Config;

/**
 * @author ben.manes@gmail.com (Ben Manes)
 */
public final class GuavaBloomFilter implements Membership {
  private final long expectedInsertions;
  private final double fpp;

  private BloomFilter<Long> bloomFilter;

  public GuavaBloomFilter(Config config) {
    MembershipSettings settings = new BasicSettings(config).membership();
    this.expectedInsertions = settings.expectedInsertions();
    this.fpp = settings.fpp();
    reset();
  }

  @Override
  public boolean mightContain(long e) {
    return bloomFilter.mightContain(e);
  }

  @Override
  public void clear() {
    reset();
  }

  @Override
  public boolean put(long e) {
    return bloomFilter.put(e);
  }

  private void reset() {
    bloomFilter = BloomFilter.create(Funnels.longFunnel(), expectedInsertions, fpp);
  }
}


text:
require 'csv'

class Ruian
  class Parser < CSV
    CSV_OPTIONS = { :encoding => 'windows-1250', :col_sep => ';', :quote_char => '"', :headers => true }

    def self.foreach(path, options = Hash.new, &block)
      options = Ruian::Parser::CSV_OPTIONS.merge(options)
      super
    end
  end
end


text:
<?php

namespace ManDate\Rule;

class NighttimeRule extends SunlightRuleBase implements RuleInterface
{
    public function validate(\DateTime $dateTime)
    {
        $daytimeRule = new DaytimeRule();

        return !$daytimeRule->validate($dateTime);
    }
}


text:
namespace dbr
{
    namespace cc
    {
        class ThreadPool
        {
        public:
            using Ids = std::vector<std::thread::id>;

            // starts threadCount threads, waiting for jobs
            // may throw a std::system_error if a thread could not be started
            ThreadPool(std::size_t threadCount = 0);

            // non-copyable,
            ThreadPool(const ThreadPool&) = delete;
            ThreadPool& operator=(const ThreadPool&) = delete;

            // but movable
            ThreadPool(ThreadPool&&) = default;
            ThreadPool& operator=(ThreadPool&&) = default;

            // clears job queue, then blocks until all threads are finished executing their current job
            ~ThreadPool();

            // add a function to be executed, along with any arguments for it
            template<typename Func, typename... Args>
            auto add(Func&& func, Args&&... args)->std::future<typename std::result_of<Func(Args...)>::type>;

            // returns number of threads being used
            std::size_t threadCount() const;

            // returns the number of jobs waiting to be executed
            std::size_t waitingJobs() const;

            // returns a vector of ids of the threads used by the ThreadPool
            Ids ids() const;

            // clears currently queued jobs (jobs which are not currently running)
            void clear();

            // pause and resume job execution. Does not affect currently running jobs
            void pause(bool state);

            // blocks calling thread until job queue is empty
            void wait();

        private:
            using Job = std::function<void()>;

            // function each thread performs
            static void threadTask(ThreadPool* pool);

            std::queue<Job> jobs;
            mutable std::mutex jobsMutex;

            // notification variable for waiting threads
            std::condition_variable jobsAvailable;

            std::vector<std::thread> threads;
            std::atomic<std::size_t> threadsWaiting;

            std::atomic<bool> terminate;
            std::atomic<bool> paused;
        };

        template<typename Func, typename... Args>
        auto ThreadPool::add(Func&& func, Args&&... args) -> std::future<typename std::result_of<Func(Args...)>::type>
        {
            using PackedTask = std::packaged_task<typename std::result_of<Func(Args...)>::type()>;

            auto task = std::make_shared<PackedTask>(std::bind(std::forward<Func>(func), std::forward<Args>(args)...));

            // get the future to return later
            auto ret = task->get_future();

            {
                std::lock_guard<std::mutex> lock{ jobsMutex };
                jobs.emplace([task]() { (*task)(); });
            }

            // let a waiting thread know there is an available job
            jobsAvailable.notify_one();

            return ret;
        }
    }
}

#endif


text:
;modjewel.define("weinre/client/DOMTemplates", function(require, exports, module) { // Generated by CoffeeScript 1.8.0
var Ex, addToElement_Node, addToElement_Object, addToElement_String, elementName, elementNames, getElementFunction, _i, _len;

Ex = require('../common/Ex');

getElementFunction = function(elementName) {
  return function() {
    var args, argument, element, _i, _len;
    element = document.createElement(elementName);
    args = [].slice.call(arguments);
    for (_i = 0, _len = args.length; _i < _len; _i++) {
      argument = args[_i];
      if (argument.nodeType) {
        addToElement_Node(element, argument);
      } else if (typeof argument === "string") {
        addToElement_String(element, argument);
      } else if (typeof argument === "object") {
        addToElement_Object(element, argument);
      } else {
        throw new Ex(arguments, ("invalid value passed to DOMTemplates." + elementName + "(): ") + argument);
      }
    }
    return element;
  };
};

addToElement_String = function(element, aString) {
  return addToElement_Node(element, document.createTextNode(aString));
};

addToElement_Node = function(element, anElement) {
  return element.appendChild(anElement);
};

addToElement_Object = function(element, anObject) {
  var actualKey, key, val, _results;
  _results = [];
  for (key in anObject) {
    if (!anObject.hasOwnProperty(key)) {
      continue;
    }
    val = anObject[key];
    if (key.substr(0, 1) === "$") {
      actualKey = key.substr(1);
      _results.push(element[actualKey] = val);
    } else {
      _results.push(element.setAttribute(key, val));
    }
  }
  return _results;
};

elementNames = 'H1 H2 H3 H4 H5 H6 UL OL DL LI DT DD SPAN DIV A B I TT P HR BR PRE IMG CANVAS TABLE TR TD FORM INPUT BUTTON SELECT OPTGROUP OPTION TEXTAREA';

elementNames = elementNames.split(' ');

for (_i = 0, _len = elementNames.length; _i < _len; _i++) {
  elementName = elementNames[_i];
  exports[elementName] = getElementFunction(elementName);
  exports[elementName].name = "" + elementName;
  exports[elementName].displayName = "" + elementName;
  exports[elementName].signature = "DOMTemplates." + elementName;
}

});


text:
package com.pengyifan.brat;

import static com.pengyifan.brat.BratPreconditions.checkBratFormatArgument;
import static com.google.common.base.Preconditions.checkArgument;

import java.util.Objects;
import java.util.Set;

import com.google.common.base.Joiner;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

/**
 * Equivalence ie are symmetric and transitive ie that define
 * sets of annotations to be equivalent in some sense (e.g. referring to the
 * same real-world entity). Such ie can be represented in a compact way
 * as a SPACE-separated list of the IDs of the equivalent annotations. For
 * example
 *
 *

 * T1  Organization 0 43 International Business Machines Corporation
 * T2  Organization 45 48  IBM
 * T3  Organization 52 60  Big Blue
 * *   Equiv T1 T2 T3
 *

 *
 * For backward compatibility with existing standoff formats, brat supports
 * also the special "empty" ID value "*" for equivalence relation annotations.
 *

 * Represented in standoff as
 *
 *

 * * \t TYPE ID1 ID2 [...]
 *

 *
 * Where "*" is the literal asterisk character.
 *
 * @since 1.0.0
 * @author "Yifan Peng"
 */
public class BratEquivRelation extends BratAnnotation {

  /**
   * Parses the string argument as a equivalence relation annotation.
   *
   * @param s a String containing the equivalence relation annotation to be parsed
   * @return the equivalence relation annotation represented by the argument.
   */
  public static BratEquivRelation parseEquivRelation(String s) {
    String toks[] = s.split("\t");
    checkBratFormatArgument(toks.length == 2, "Illegal format: %s", s);

    BratEquivRelation relation = new BratEquivRelation();
    checkBratFormatArgument(toks[0].equals("*"), "Illegal format: %s", s);

    toks = toks[1].split(" ");
    checkBratFormatArgument(toks.length >= 2, "Illegal format: %s", s);
    checkBratFormatArgument(toks[0].equals("Equiv"), "Illegal format: %s", s);

    for (int i = 1; i < toks.length; i++) {
      relation.addArgId(toks[i]);
    }
    return relation;
  }

  private Set<String> argIds;

  public BratEquivRelation() {
    super();
    super.setId("*");
    super.setType("Equiv");
    argIds = Sets.newTreeSet();
  }

  public BratEquivRelation(BratEquivRelation relation) {
    super(relation);
    argIds = Sets.newHashSet(relation.argIds);
  }

  public void addArgId(String argId) {
    checkArgument(!argIds.contains(argId), "Duplicated arg: %s", argId);
    argIds.add(argId);
  }

  public boolean containsArgId(String argId) {
    return argIds.contains(argId);
  }

  @Override
  public boolean equals(Object o) {
    if (o == this) {
      return true;
    }
    if (!(o instanceof BratEquivRelation)) {
      return false;
    }
    BratEquivRelation rhs = (BratEquivRelation) o;
    return super.equals(o)
        && Objects.equals(argIds, rhs.argIds);
  }

  public Set<String> getArgIds() {
    return argIds;
  }

  @Override
  public int hashCode() {
    return Objects.hash(super.hashCode(), argIds);
  }

  @Override
  public void setId(String id) {
    throw new UnsupportedOperationException("Id is always *");
  }

  @Override
  public void setType(String type) {
    throw new UnsupportedOperationException("Type is always Equiv");
  }

  /**
   *

   * * \t TYPE ID1 ID2 [...]
   *

   */
  @Override
  public String toBratString() {
    StringBuilder sb = new StringBuilder(getId());
    // type
    sb.append('\t').append(getType());
    // args
    for(String argid: argIds) {
      sb.append(' ').append(argid);
    }
    return sb.toString();
  }

  @Override
  public String toString() {
    return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
        .append("id", getId())
        .append("type", getType())
        .append("args", getArgIds())
        .toString();
  }
}


text:
<System name="ApiCommand">
    <Function name="run">
        <Input>
            <Var name="Perspective" whenNot="requestCases">
                <Value name="Default"/>
                <Value name="Client"/>
                <Value name="Server"/>
            </Var>
            <Var name="Model-Type">
                <Value name="Default"/>
                <Value name="Input" property="modelInput"/>
                <Value name="Test"/>
            </Var>
            <Var name="Condition-Handler">
                <Value name="Default"/>
                <Value name="Log"/>
                <Value name="Fail"/>
                <Value name="Ignore"/>
            </Var>
            <VarSet name="Output-File">
                <Var name="Defined">
                    <Value name="Yes" property="outputFile"/>
                    <Value name="No"/>
                </Var>
                <Var name="Path" when="outputFile">
                    <Value name="Relative"/>
                    <Value name="Absolute"/>
                </Var>
            </VarSet>
            <VarSet name="Output-Dir">
                <Var name="Defined">
                    <Value name="Yes" property="outputDir"/>
                    <Value name="No"/>
                </Var>
                <Var name="Exists" when="outputDir">
                    <Value name="Yes"/>
                    <Value name="No"/>
                </Var>
            </VarSet>
            <Var name="Read-Only-Enforced">
                <Value name="Yes"/>
                <Value name="No"/>
            </Var>
            <Var name="Write-Only-Enforced">
                <Value name="Yes"/>
                <Value name="No"/>
            </Var>
            <Var name="Output-Transformer" whenNot="modelInput,requestCases">
                <Value name="None"/>
                <Value name="JUnit" once="true"/>
                <Value name="Html" once="true"/>
                <Value name="Custom" once="true"/>
            </Var>
            <VarSet name="Request-Cases">
                <Var name="Selected">
                    <Value name="Yes" property="requestCases"/>
                    <Value name="No"/>
                </Var>
                <Var name="Random-Seed" when="requestCases">
                    <Value name="Defined"/>
                    <Value name="Default"/>
                </Var>
                <Var name="Max-Tries" when="requestCases">
                    <Value name="Defined"/>
                    <Value name="Default"/>
                </Var>
                <Var name="Condition-Handler" when="requestCases">
                    <Value name="Default"/>
                    <Value name="Log"/>
                    <Value name="Fail"/>
                    <Value name="Ignore"/>
                </Var>
            </VarSet>
            <VarSet name="Api-Spec">
                <Var name="Defined">
                    <Value name="Yes" property="apiDef"/>
                    <Value name="No"/>
                </Var>
                <Var name="Path" when="apiDef">
                    <Value name="Relative"/>
                    <Value name="Absolute"/>
                </Var>
            </VarSet>
        </Input>
    </Function>
</System>


text:
import P from 'bluebird';
import * as searchPageActions from '../../action_creators/search/search_page_action_creators';
import notFoundActionCreator from '../../action_creators/not_found_status_action_creator';
import log from '../../../services/logger_service';
import searchAsyncAction from './async_search_actions';

export default function fetchRepoDetail(params, dispatch, state) {
  dispatch(searchPageActions.searchPageLoading());
  return P.all([searchAsyncAction(params, dispatch, state)])
    .then(function handleRepoDetailData() {
      dispatch(searchPageActions.searchPageLoaded());
    })
    .catch(function handleUserError(err) {
      log.error(err, 'Error in search page.');
      dispatch(notFoundActionCreator(500, 'ERROR_STATUS'));
      dispatch(searchPageActions.searchPageLoadError(err, state));
    });
}


text:
using System;
using De.Osthus.Ambeth.Annotation;
using System.Collections.Generic;

namespace De.Osthus.Ambeth.Filter.Model
{
    [XmlType(Name = "IFilterDescriptor", Namespace = "http://schemas.osthus.de/Ambeth")]
    public interface IFilterDescriptor
    {
        String Member { get; }

        IList<String> Value { get; }

        bool? IsCaseSensitive { get; }

        FilterOperator Operator { get; }

        LogicalOperator LogicalOperator { get; }

        IList<IFilterDescriptor> ChildFilterDescriptors { get; }
    }
}


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	Federation = mongoose.model('Federation'),
	_ = require('lodash');

/**
 * Create a Federation
 */
exports.create = function(req, res) {
	var federation = new Federation(req.body);
	federation.user = req.user;

	federation.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(federation);
		}
	});
};

/**
 * Show the current Federation
 */
exports.read = function(req, res) {
	res.jsonp(req.federation);
};

/**
 * Update a Federation
 */
exports.update = function(req, res) {
	var federation = req.federation ;

	federation = _.extend(federation , req.body);

	federation.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(federation);
		}
	});
};

/**
 * Delete an Federation
 */
exports.delete = function(req, res) {
	var federation = req.federation ;

	federation.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(federation);
		}
	});
};

/**
 * List of Federations
 */
exports.list = function(req, res) {
	Federation.find().sort('-created').populate('user', 'displayName').exec(function(err, federations) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(federations);
		}
	});
};

/**
 * Federation middleware
 */
exports.federationByID = function(req, res, next, id) {
	Federation.findById(id).populate('user', 'displayName').exec(function(err, federation) {
		if (err) return next(err);
		if (! federation) return next(new Error('Failed to load Federation ' + id));
		req.federation = federation ;
		next();
	});
};

/**
 * Federation authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.federation.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};


text:
namespace Microsoft.Azure.Management.Cdn.Models
{
    using System.Linq;

    /// <summary>
    /// Output of check name availability API.
    /// </summary>
    public partial class CheckNameAvailabilityOutput
    {
        /// <summary>
        /// Initializes a new instance of the CheckNameAvailabilityOutput
        /// class.
        /// </summary>
        public CheckNameAvailabilityOutput() { }

        /// <summary>
        /// Initializes a new instance of the CheckNameAvailabilityOutput
        /// class.
        /// </summary>
        /// <param name="nameAvailable">Indicates whether the name is
        /// available.</param>
        /// <param name="reason">The reason why the name is not
        /// available.</param>
        /// <param name="message">The detailed error message describing why
        /// the name is not available.</param>
        public CheckNameAvailabilityOutput(bool? nameAvailable = default(bool?), string reason = default(string), string message = default(string))
        {
            NameAvailable = nameAvailable;
            Reason = reason;
            Message = message;
        }

        /// <summary>
        /// Gets or sets indicates whether the name is available.
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "NameAvailable")]
        public bool? NameAvailable { get; set; }

        /// <summary>
        /// Gets or sets the reason why the name is not available.
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "Reason")]
        public string Reason { get; set; }

        /// <summary>
        /// Gets or sets the detailed error message describing why the name is
        /// not available.
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "Message")]
        public string Message { get; set; }

    }
}


text:
import debug_toolbar
from django.conf.urls import url, include
from django.contrib import admin
admin.autodiscover()

urlpatterns = [
    url(r'^contact/', include('contact_form.urls', namespace='contact_form')),
    url(r'^admin/', admin.site.urls),
    url(r'^__debug__/', include(debug_toolbar.urls)),
]


text:
function FourInARow(){
	this.bnx = 8;						//number of boxs
	this.bny = 8;
	this.bs = Math.min(width,height) /8; //boxsize

	this.cArray = [];					//chipArray

	this.blackTurn;
	this.teamArray = ["Neutral", "Red", "Yellow"];
	this.gameOver = false;

	//sends the starting game layout to wrapper
	this.callSendState = function(){
			var boardState = {
				cArray:			JSON.stringify(this.cArray),
				blackTurn:		JSON.stringify(this.blackTurn),
			}
		sendStateToServer(JSON.stringify(boardState));
	}

	this.recieveState = function (boardString) {
		var boardState = 	JSON.parse(boardString);
		this.cArray = 		JSON.parse(boardState.cArray);
		this.blackTurn = 	JSON.parse(boardState.blackTurn);
		this.drawBoard();
	}

	//initilizes empty arrays representing game state
	this.startGame = function() {
		setupCanvasObjects();

		//fills this.cArray with 0s
		for (var x = 0; x < this.bnx; x++) {
			this.cArray[x] = [];
			for (var y = 0; y < this.bny; y++) {
				this.cArray[x][y] = 0;
			}
		}

		//sets starting player
		this.blackTurn = true;

		this.callSendState();
	}

	//clears canvas and redraws board
	this.drawBoard = function() {
		//clear and resize canvas
		//board.width = width;
		//board.height = height;

		//clears canvas
		context.fillStyle = "rgb(255,255,255)";
		context.fillRect(0, 0, width, height);
		context.fillStyle = "Blue";
		context.fillRect(0, 0, this.bnx*this.bs, this.bny*this.bs);

		this.drawPieces();
	}

	//draw pieces placed by players
	this.drawPieces = function(){
		for (var x = 0; x < this.bnx; x++) {
			for (var y = 0; y < this.bny; y++) {
				this.drawPiece(x,y,this.cArray[x][y],this.bs/2.4);
			}
		}
	}

	//draws a single piece at x, y with color and size passed
	//larger size values make smaller pieces
	this.drawPiece = function(x, y, color, size) {
		if (color == 0) {
			context.fillStyle = "White";
		}
		else if (color == 1) {
			context.fillStyle = "Red";
		}
		else {
			context.fillStyle = "Yellow"
		}

		context.beginPath();
		context.arc((x+.5)*this.bs, (y+.5)*this.bs, size, 0, 2*Math.PI, false);
		context.fill();
		context.closePath();
	}

	//called when there are no valid moves. adds a button to start new game
	 this.endGame = function(){
	 	this.gameOver = true;

		//creates Winner text
		var winnerText = (this.blackTurn) ? "Yellow Wins!" : "Red Wins!";

		console.log(winnerText);
		gameEnded(winnerText);
	}

	//called when the page is clicked
	this.click = function(e){
		var color = (this.blackTurn) ? 1 : 2;
		var pos = this.findPos(board);
		var cord = this.findCord(e.pageX - pos.x, e.pageY - pos.y);

		if (cord) {

			var x = cord.x;
			var y = this.maxY(cord.x);
			//if click is on the board, see if it is valid move
			if (y >= 0) {
				//checks to see if it is the local player's turn
				if (isPlayerTurn(color) && !this.gameOver) {

					this.cArray[x][y] = color;
					this.drawBoard();
					this.blackTurn = !this.blackTurn;

					if (this.checkGameEnd(x,y)) {
						this.endGame();
					}

					//uploads newboard state
					this.callSendState();

				}
			}
		}
	}

	//returns position of lowest empty slot in column x
	this.maxY = function(x){
		var rv = 7;
		while (rv >= 0 && this.cArray[x][rv] != 0){
			rv--;
		}
		return rv;
	}

	this.checkGameEnd = function(x, y){
		var rv = false;
		if (this.cArray[x][y] != 0) {
			rv = (rv) ? rv : this.check4(x, y, 1, 0);
			rv = (rv) ? rv : this.check4(x, y, 1, -1);
			rv = (rv) ? rv : this.check4(x, y, 0, 1);
			rv = (rv) ? rv : this.check4(x, y, 1, 1);
		}
		return rv;
	}

	this.check4 = function(x, y, dx, dy) {
		var color = this.cArray[x][y];
		var length = 1;
		var i = 1;
		while (this.onBoard(x+dx*i,y+dy*i)) {
			if (this.cArray[x+dx*i][y+dy*i] == color){
				length++;
				i++;
			}
			else{
				break;
			}
		}
		i = -1;
		while (this.onBoard(x+dx*i,y+dy*i)) {
			if (this.cArray[x+dx*i][y+dy*i] == color){
				length++;
				i--;
			}
			else{
				break;
			}
		}

		return (length>=4);
	}

	//finds which line the passed cord is closest to
	this.findCord = function(x, y){
		var RV = new Object; 	//return value

		//true if point is inside grid
		if (0 < x && x < this.bs*this.bnx && 0 < y && y < this.bs*this.bnx ){
			xs = Math.floor(x/this.bs);
			ys = Math.floor(y/this.bs);

			RV.x = xs;
			RV.y = ys;
		}
		//cord not on grid; return false
		else {
			RV = false;
		}

		return RV;
	}

	//returns true if the cord is on the board
	this.onBoard = function(x, y) {
		return (0 <= x && x < this.bnx && 0 <= y && y < this.bny);
	}

	//finds how much the canvas is offset in the frame
	this.findPos = function(obj) {
		var curleft = 0, curtop = 0;
		if (obj.offsetParent) {
			do {
				curleft += obj.offsetLeft;
				curtop += obj.offsetTop;
			} while (obj = obj.offsetParent);
			return { x: curleft, y: curtop };
		}
		return undefined;
	}

	this.botMove = function(x){
		var color = (this.blackTurn) ? 1 : 2;
		var y = this.maxY(x);
		//if click is on the board, see if it is valid move
		if (y >= 0) {
			//checks to see if it is the local player's turn
			if (!this.gameOver) {

				this.cArray[x][y] = color;
				this.drawBoard();
				this.blackTurn = !this.blackTurn;

				//uploads newboard state
				this.callSendState();

				if (this.checkGameEnd(x,y)) {
					this.endGame();
				}
			}
		}
		else {
			console.log("bot selected invalid move");
		}
	}

}


text:
default[:iptables][:service_name] = "iptables"
default[:iptables][:bin_path]     = "/sbin/iptables"


text:
/* Prevent double inclusion */
 /**
 * Support and FAQ: visit Atmel Support
 */
#ifndef TAL_IRQ_HANDLER_H
#define TAL_IRQ_HANDLER_H

/* === INCLUDES ============================================================ */

/* === EXTERNALS =========================================================== */

/* === TYPES =============================================================== */

/* === MACROS ============================================================== */

/* === PROTOTYPES ========================================================== */

#ifdef __cplusplus
extern "C" {
#endif

/**
 * \addtogroup group_tal_irq
 * @{
 */

/**
 * \brief Transceiver interrupt handler
 *
 * This function handles the transceiver generated interrupts.
 */
void trx_irq_handler_cb(void);

/**
 * \brief Transceiver interrupt handler for awake end IRQ
 *
 * This function handles the transceiver awake end interrupt.
 */

void trx_irq_awake_handler_cb(void);

#if (defined BEACON_SUPPORT) || (defined ENABLE_TSTAMP) || (defined DOXYGEN)

/**
 * \brief Timestamp interrupt handler
 *
 * This function handles the interrupts handling the timestamp.
 */
void trx_irq_timestamp_handler_cb(void);

#endif  /* #if (defined BEACON_SUPPORT) || (defined ENABLE_TSTAMP) || (defined
         *DOXYGEN) */

/* ! @} */
#ifdef __cplusplus
} /* extern "C" */
#endif

#endif /* TAL_IRQ_HANDLER_H */

/* EOF */


text:
<?php

namespace ChrisKonnertz\StringCalc\Exceptions;

/**
 * Class InvalidIdentifier is thrown when validation of an identifier fails.
 * This exception type is especially used by the AbstractSymbol class.
 *
 * @package ChrisKonnertz\StringCalc\Exceptions
 */
class InvalidIdentifierException extends StringCalcException
{

}


text:
from pygw.config import geowave_pkg
from pygw.base import DataTypeAdapter

from .simple_feature_type import SimpleFeatureType

class FeatureDataAdapter(DataTypeAdapter):
    """
    Data adapter for storing and retrieving SimpleFeatures from a GeoWave data store.
    """

    def __init__(self, feature_type):
        """
        Constructs a feature data adapter using the given feature type.

        Args:
            feature_type (pygw.geotools.simple_feature_type.SimpleFeatureType): The feature type of the data.
        """
        self.feature_type = feature_type
        assert isinstance(feature_type, SimpleFeatureType)
        j_feat_type = feature_type._java_ref
        j_feat_adapter = geowave_pkg.adapter.vector.FeatureDataAdapter(j_feat_type)
        super().__init__(j_feat_adapter)


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll_header"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_header0"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#0ff"
        android:text="@string/about"
        android:visibility="gone"/>

    <TextView
        android:id="@+id/tv_header1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#0f0"
        android:text="@string/about" />

    <TextView
        android:id="@+id/tv_header2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#00f"
        android:text="@string/about"
        android:visibility="gone"/>

</LinearLayout>


text:
<?php
namespace YaoiTests\PHPUnit\Log;

use Yaoi\Log;
use Yaoi\Log\Settings;
use Yaoi\Storage\PhpVar;
use Yaoi\Test\PHPUnit\TestCase;

class Test extends TestCase
{
    public function testLog()
    {
        ob_start();
        Log::create(new Settings('stdout'))->push('test33');
        $result = ob_get_contents();
        ob_end_clean();
        $this->assertSame('test33' . "\n", $result);

        ob_start();
        Log::create(new Settings('nil'))->push('test33');
        $result = ob_get_contents();
        ob_end_clean();
        $this->assertSame('', $result);
    }

    public function testStorage()
    {
        $storage = new PhpVar();
        $logDsn = new Settings('storage');
        $logDsn->storage = $storage;
        $log = Log::getInstance($logDsn);

        $log->push(array('one', 'two', 'three'));

        $expected = array(
            'one' =>
                array(
                    'two' => 'three',
                ),
        );

        $this->assertSame($expected, $storage->exportArray());
    }
}


text:
///<reference path="IAdaptiveRPGroup.ts"/>
///<reference path="IBaseCallback.ts"/>
var Adaptive;
(function (Adaptive) {
    /**
       Base application for Callback purposes
       Auto-generated implementation of IBaseCallback specification.
    */
    /**
       @class Adaptive.BaseCallback
    */
    var BaseCallback = (function () {
        /**
           @method constructor
           Constructor with callback id.

           @param {number} id  The id of the callback.
        */
        function BaseCallback(id) {
            this.id = id;
            this.apiGroup = Adaptive.IAdaptiveRPGroup.Application;
        }
        /**
           @method
           @return {number}
           Get the callback id.
        */
        BaseCallback.prototype.getId = function () {
            return this.id;
        };
        /**
           @method
           @return {Adaptive.IAdaptiveRPGroup}
           Return the API group for the given interface.
        */
        BaseCallback.prototype.getAPIGroup = function () {
            return this.apiGroup;
        };
        /**
           @method
           Return the API version for the given interface.

           @return {string}
           The version of the API.
        */
        BaseCallback.prototype.getAPIVersion = function () {
            return Adaptive.bridgeApiVersion;
        };
        return BaseCallback;
    })();
    Adaptive.BaseCallback = BaseCallback;
})(Adaptive || (Adaptive = {}));
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
//# sourceMappingURL=BaseCallback.js.map


text:
Sith is a black noise generator based on Spotify Core.

This is a work in progress.

> This product uses SPOTIFY CORE but is not endorsed, certified or otherwise
> approved in any way by Spotify. Spotify is the registered trade mark of the
> Spotify Group.

## Hacking

Request your own API key from https://developer.spotify.com/ and download the
latest version of libspotify to your system.

For now you will need to specify the password through the command line.

    $ go install github.com/op/sith
    $ sith -key path/app.key -username user -password pass


text:
package org.elasticsearch.xpack.fleet;

import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.indices.SystemIndexDescriptor;
import org.elasticsearch.indices.SystemIndices;
import org.elasticsearch.indices.SystemIndices.Feature;
import org.elasticsearch.test.ESTestCase;

import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;

import static org.hamcrest.Matchers.containsInAnyOrder;

public class FleetTests extends ESTestCase {

    public void testFleetIndexNames() {
        Fleet module = new Fleet();

        final Collection<SystemIndexDescriptor> fleetDescriptors = module.getSystemIndexDescriptors(Settings.EMPTY);

        assertThat(
            fleetDescriptors.stream().map(SystemIndexDescriptor::getIndexPattern).collect(Collectors.toList()),
            containsInAnyOrder(
                ".fleet-servers*",
                ".fleet-policies-[0-9]+*",
                ".fleet-agents*",
                ".fleet-actions~(-results*)",
                ".fleet-policies-leader*",
                ".fleet-enrollment-api-keys*",
                ".fleet-artifacts*"
            )
        );

        assertTrue(fleetDescriptors.stream().anyMatch(d -> d.matchesIndexPattern(".fleet-servers")));

        assertTrue(fleetDescriptors.stream().anyMatch(d -> d.matchesIndexPattern(".fleet-policies")));
        assertTrue(fleetDescriptors.stream().anyMatch(d -> d.matchesIndexPattern(".fleet-policies-leader")));

        assertTrue(fleetDescriptors.stream().anyMatch(d -> d.matchesIndexPattern(".fleet-agents")));

        assertTrue(fleetDescriptors.stream().anyMatch(d -> d.matchesIndexPattern(".fleet-actions")));
        assertFalse(fleetDescriptors.stream().anyMatch(d -> d.matchesIndexPattern(".fleet-actions-results")));
    }

    public void testFleetFeature() {
        Fleet module = new Fleet();
        Feature fleet = Feature.fromSystemIndexPlugin(module, Settings.EMPTY);
        SystemIndices systemIndices = new SystemIndices(Map.of(module.getFeatureName(), fleet));
        assertNotNull(systemIndices);
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PersistentStorage;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.SQLite.v2
{
    internal class SQLitePersistentStorageService : AbstractSQLitePersistentStorageService
    {
        private const string StorageExtension = "sqlite3";
        private const string PersistentStorageFileName = "storage.ide";

        private readonly SQLiteConnectionPoolService _connectionPoolService;
        private readonly IAsynchronousOperationListener _asyncListener;
        private readonly OptionSet _options;
        private readonly IPersistentStorageFaultInjector? _faultInjector;

        public SQLitePersistentStorageService(
            OptionSet options,
            SQLiteConnectionPoolService connectionPoolService,
            IPersistentStorageLocationService locationService,
            IAsynchronousOperationListener asyncListener)
            : base(locationService)
        {
            _options = options;
            _connectionPoolService = connectionPoolService;
            _asyncListener = asyncListener;
        }

        public SQLitePersistentStorageService(
            OptionSet options,
            SQLiteConnectionPoolService connectionPoolService,
            IPersistentStorageLocationService locationService,
            IAsynchronousOperationListener asyncListener,
            IPersistentStorageFaultInjector? faultInjector)
            : this(options, connectionPoolService, locationService, asyncListener)
        {
            _faultInjector = faultInjector;
        }

        protected override string GetDatabaseFilePath(string workingFolderPath)
        {
            Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(workingFolderPath));
            return Path.Combine(workingFolderPath, StorageExtension, nameof(v2), PersistentStorageFileName);
        }

        protected override ValueTask<IChecksummedPersistentStorage?> TryOpenDatabaseAsync(
            SolutionKey solutionKey, string workingFolderPath, string databaseFilePath, CancellationToken cancellationToken)
        {
            if (!TryInitializeLibraries())
            {
                // SQLite is not supported on the current platform
                return new((IChecksummedPersistentStorage?)null);
            }

            if (solutionKey.FilePath == null)
                return new(NoOpPersistentStorage.GetOrThrow(_options));

            return new(SQLitePersistentStorage.TryCreate(
                _connectionPoolService,
                workingFolderPath,
                solutionKey.FilePath,
                databaseFilePath,
                _asyncListener,
                _faultInjector));
        }

        // Error occurred when trying to open this DB.  Try to remove it so we can create a good DB.
        protected override bool ShouldDeleteDatabase(Exception exception) => true;
    }
}


text:
<?php namespace _modules\user\datatypes\password;

class Password extends \Jhul\Core\Application\DataType\Types\String\Attribute
{
	use \Jhul\Core\_AccessKey;

	public function __construct()
	{
		parent::__construct();
		$this->config()->add( 'if_use_raw_password', FALSE );
	}

      public function hash( $raw )
      {
      	return $this->module()->security()->hashSA($raw);
      }

      public function verifyHash( $raw, $hash )
      {
		return $this->module()->security()->hashSAMatch( $raw, $hash );
      }

	public function ifUseRawPassword()
	{
		return TRUE == $this->config('if_use_raw_password');
	}
 }


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<meta name="description" content="A glance of my skills">
	<meta name="keywords" content="HTML,CSS,JavaScript, JS Frameworks, Programming Languages, Coding Skills">
	<meta name="author" content="Amit Kumar Sarangi">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">

	<title>Skills</title>

	<link rel="stylesheet" type="text/css" href="skills1.css">
	<link href="https://fonts.googleapis.com/css?family=Play" rel="stylesheet">

SKILLS

Frontend:

HTML5 | CSS3 | JavaScript

Data Visualization:

AngularJS | D3JS | ReactJS

Backend:

NodeJS | ExpressJS | Python

Data Management:

MySQL | MongoDB


text:
'use strict';
// https://github.com/tc39/proposal-iterator-helpers
var $ = require('../internals/export');
var apply = require('../internals/function-apply');
var call = require('../internals/function-call');
var anObject = require('../internals/an-object');
var toPositiveInteger = require('../internals/to-positive-integer');
var createIteratorProxy = require('../internals/iterator-create-proxy');

var IteratorProxy = createIteratorProxy(function (args) {
  var iterator = this.iterator;
  var next = this.next;
  var result, done;
  while (this.remaining) {
    this.remaining--;
    result = anObject(call(next, iterator));
    done = this.done = !!result.done;
    if (done) return;
  }
  result = anObject(apply(next, iterator, args));
  done = this.done = !!result.done;
  if (!done) return result.value;
});

$({ target: 'Iterator', proto: true, real: true, forced: true }, {
  drop: function drop(limit) {
    return new IteratorProxy({
      iterator: anObject(this),
      remaining: toPositiveInteger(limit)
    });
  }
});


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

using Foundation;
using UIKit;

namespace ApplicationModel.iOS
{
    // The UIApplicationDelegate for the application. This class is responsible for launching the
    // User Interface of the application, as well as listening (and optionally responding) to
    // application events from iOS.
    [Register("AppDelegate")]
    public partial class AppDelegate : UIApplicationDelegate
    {
        // class-level declarations
        UIWindow window;

        //
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            // create a new window instance based on the screen size
            window = new UIWindow(UIScreen.MainScreen.Bounds);

            // If you have defined a view, add it here:
            window.RootViewController = new UIViewController1();

            // make the window visible
            window.MakeKeyAndVisible();

            //UIApplication.SharedApplication.OpenUrl(new NSUrl(UIApplication.OpenSettingsUrlString));
            return true;
        }
    }
}


text:
import {namespaceParam} from 'chrome/chrome_state';
import module from 'common/namespace/namespace_module';

describe('Namespace module ', () => {
  beforeEach(() => {
    angular.mock.module(module.name);
  });

  it('should watch for changes', angular.mock.inject(($location, $rootScope) => {
    $location.search(namespaceParam, undefined);
    expect($location.search()[namespaceParam]).toBe(undefined);

    $rootScope.$broadcast('$locationChangeSuccess');
    $rootScope.$digest();
    expect($location.search()[namespaceParam]).toBe('default');

    $location.search(namespaceParam, undefined);
    expect($location.search()[namespaceParam]).toBe(undefined);
    $rootScope.$digest();
    expect($location.search()[namespaceParam]).toBe('default');
  }));
});


text:
require File.expand_path('../spec_helper', __dir__)
require 'app/models/github'

module Pod::TrunkApp
  describe 'GitHub' do
    before do
      @auth = { :username => 'alloy', :password => 'secret' }
      @github = GitHub.new('CocoaPods/Specs', @auth)
    end

    it 'returns a URL for a given API path' do
      @github.url_for('git/refs/heads/master').should == 'https://api.github.com/repos/CocoaPods/Specs/git/refs/heads/master'
    end

    it 'configures timeouts' do
      Net::HTTP.last_started_request = nil
      @github.put('/', :foo => 'bar')
      http_request = Net::HTTP.last_started_request
      http_request.open_timeout.should == 3
      http_request.read_timeout.should == 7
    end

    def stub_request(response = fixture_response('create_new_commit'))
      args = Array.new(5)
      REST::Request.stubs(:perform).with do |method, url, body, headers, auth|
        args.replace [method, url.to_s, body, headers, auth]
      end.returns(response)
      args
    end

    it 'creates a new commit' do
      # Capture the args so we can assert on them after the call.
      args = stub_request

      response = @github.create_new_commit(DESTINATION_PATH,
                                           fixture_read('AFNetworking.podspec'),
                                           '[Add] AFNetworking 1.2.0',
                                           'Eloy Durán',
                                           'eloy@example.com')
      response.should.be.success
      response.commit_sha.should == fixture_new_commit_sha

      method, url, body, headers, auth = args

      method.should == :put
      url.should == @github.url_for(File.join('contents', DESTINATION_PATH))
      headers.should == GitHub::HEADERS
      auth.should == @auth

      body = JSON.parse(body)
      Base64.decode64(body['content']).should == fixture_read('AFNetworking.podspec')
      body.delete('content')
      body.should == {
        'message' => MESSAGE,
        'branch' => 'master',
        'author' => { 'name' => 'Eloy Durán', 'email' => 'eloy@example.com' },
        'committer' => { 'name' => 'alloy', 'email' => 'bot@example.com' },
      }
    end

    it 'requests the sha for a file' do
      extend SpecHelpers::CommitResponse

      response = REST::Response.new(200, {}, '{ "sha": "123434324242" }')
      args = stub_request(response)

      @github.sha_for_file_at_path(DESTINATION_PATH).should == '123434324242'

      method, url, _body, headers, _auth = args

      method.should == :get
      url.should == 'https://api.github.com/repos/CocoaPods/Specs/contents/AFNetworking/1.2.0/AFNetworking.podspec.yaml'
      headers.should == GitHub::HEADERS
    end

    it 'deletes a file' do
      @github.expects(:sha_for_file_at_path).with(DESTINATION_PATH).
        returns('2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b')

      # Capture the args so we can assert on them after the call.
      args = stub_request

      response = @github.delete_file_at_path(DESTINATION_PATH,
                                             '[Add] AFNetworking 1.2.0',
                                             'Eloy Durán',
                                             'eloy@example.com')
      response.should.be.success
      response.commit_sha.should == fixture_new_commit_sha

      method, url, body, headers, auth = args

      method.should == :delete
      url.should == @github.url_for(File.join('contents', DESTINATION_PATH))
      headers.should == GitHub::HEADERS
      auth.should == @auth

      body = JSON.parse(body)
      body.should == {
        'message' => MESSAGE,
        'sha' => '2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b',
        'author' => { 'name' => 'Eloy Durán', 'email' => 'eloy@example.com' },
        'committer' => { 'name' => 'alloy', 'email' => 'bot@example.com' },
      }
    end

    describe 'concerning the response object' do
      extend SpecHelpers::CommitResponse

      it 'returns the commit was a success' do
        response(201).should.be.success
        response(201).should.not.be.failed_on_our_side
        response(201).should.not.be.failed_on_their_side
        response(302).should.be.success
        response(302).should.not.be.failed_on_our_side
        response(302).should.not.be.failed_on_their_side
      end

      it 'returns the commit failed on our side, i.e. our request was incorrect' do
        response(400).should.not.be.success
        response(400).should.be.failed_on_our_side
        response(400).should.not.be.failed_on_their_side
      end

      it 'returns the commit failed on their side, i.e. GitHub ran into an unexpected exception' do
        response(500).should.not.be.success
        response(500).should.not.be.failed_on_our_side
        response(500).should.be.failed_on_their_side
      end

      it 'raises in case of an unexpected status' do
        should.raise do
          response(100)
        end
      end

      it 'returns the commit failed due to a timeout' do
        {
          Errno::ETIMEDOUT => 'Connection timed out - connect(2)',
          Net::OpenTimeout => 'execution expired',
          Net::ReadTimeout => 'Does not have a message',
          Timeout::Error => 'execution expired',
        }.each do |error_class, message|
          res = response do
            error = error_class.new
            # ETIMEDOUT adds more useless text by itself, omitting for test purposes.
            error.stubs(:message).returns(message)
            raise error
          end
          res.should.not.be.success
          res.should.not.be.failed_on_our_side
          res.should.not.be.failed_on_their_side
          res.should.be.failed_due_to_timeout
          res.timeout_error.should == "[#{error_class.name}] #{message}"
        end
      end
    end
  end
end


text:
define({
	singleSort: "Ordine singolo",
	nestedSort: "Ordine nidificato",
	ascending: "Fare clic per ordinare in ordine Ascendente",
	descending: "Fare clic per ordinare in ordine Discendente",
	sortingState: "${0} - ${1}",
	unsorted: "Non ordinare questa colonna",
	waiSingleSortLabel: "${0} - è ordinato in base a ${1}. Scegliere l'ordinamento in base a ${2}",
	waiNestedSortLabel:"${0} - è ordinato e nidificato in base a ${1}. Scegliere l'ordinamento nidificato in base a ${2}"
});


text:
import {NgModule} from "@angular/core";
import {
    JigsawBadgeModule,
    JigsawButtonBarModule,
    JigsawButtonModule,
    JigsawCheckBoxModule,
    JigsawIconModule,
    JigsawInputModule,
    JigsawRadioLiteModule,
    JigsawSwitchModule,
} from "jigsaw/public_api";
import {JigsawDemoDescriptionModule} from "app/for-internal/description/demo-description";
import {BadgeBasicDemoComponent} from "./demo.component";

@NgModule({
    declarations: [BadgeBasicDemoComponent],
    imports: [
        JigsawDemoDescriptionModule, JigsawIconModule, JigsawBadgeModule,
        JigsawButtonModule, JigsawSwitchModule, JigsawCheckBoxModule,
        JigsawInputModule, JigsawRadioLiteModule, JigsawButtonBarModule,
    ],
    exports: [BadgeBasicDemoComponent]
})
export class BadgeBasicDemoModule {
}