text:
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- leap-catalog -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-8429465058616611"
     data-ad-slot="9970614443"
     data-ad-format="auto"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

redpajama_set_name: RedPajamaGithub


text:
'*******************************************************************************************'
'                                                                                '
' Download Free Evaluation Version From:     https://bytescout.com/download/web-installer   '
'                                                                                '
' Also available as Web API! Get free API Key https://app.pdf.co/signup                     '
'                                                                                '
' Copyright © 2017-2020 ByteScout, Inc. All rights reserved.                                '
' https://www.bytescout.com                                                                 '
' https://www.pdf.co                                                                        '
'*******************************************************************************************'

Imports Bytescout.PDF

''' <summary>
''' This example demonstrates how to lock the document with a password.
''' PDF format supports two kinds of passwords: owner and user password.
''' User password allows to view document and perform allowed actions.
''' Owner password allows everything, including changing passwords and permissions.
''' </summary>
Class Program

    Shared Sub Main()

        ' Create new document
        Dim pdfDocument = New Document()
        pdfDocument.RegistrationName = "demo"
		pdfDocument.RegistrationKey = "demo"

        ' If you wish to load an existing document uncomment the line below And comment the Add page section instead
        ' pdfDocument.Load(".\existing_document.pdf")

        ' Add page
        pdfDocument.Pages.Add(New Page(PaperFormat.A4))

        ' Set document encryption algorythm
        pdfDocument.Security.EncryptionAlgorithm = EncryptionAlgorithm.RC4_40bit
        ' Set various user permissions
        pdfDocument.Security.AllowPrintDocument = False
        pdfDocument.Security.AllowContentExtraction = False
        pdfDocument.Security.AllowModifyAnnotations = False
        pdfDocument.Security.PrintQuality = PrintQuality.LowResolution

        ' Set owner password
        pdfDocument.Security.OwnerPassword = "ownerpassword"

        ' Set user password
        pdfDocument.Security.UserPassword = "userpassword"

        ' Save document to file
        pdfDocument.Save("result.pdf")

        ' Cleanup
		pdfDocument.Dispose()

        ' Open document in default PDF viewer app
        Process.Start("result.pdf")

    End Sub

End Class


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class VoiceCommand : MonoBehaviour {

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {

	}

    public void NextScene()
    {
        if (Collide.getCollideState())
        {
            SceneManager.LoadScene("AppServiceDemo");
        }
    }

    public void ARtoWelcomeScene()
    {
        SceneManager.LoadScene("WelcomeScene");
    }
}


text:
namespace ui {

extern const base::Feature kWaylandSurfaceSubmissionInPixelCoordinates;
extern const base::Feature kWaylandOverlayDelegation;

bool IsWaylandSurfaceSubmissionInPixelCoordinatesEnabled();
bool IsWaylandOverlayDelegationEnabled();

}  // namespace ui

#endif  // UI_OZONE_COMMON_FEATURES_H_


text:
FROM alpine:3.11.5

# TODO: The following env variables should be auto detected.
ENV MAYA_API_SERVER_NETWORK="eth0"

RUN apk add --no-cache \
    iproute2 \
    bash \
    curl \
    net-tools \
    mii-tool \
    procps \
    libc6-compat \
    ca-certificates
RUN mkdir -p /etc/apiserver/orchprovider
RUN mkdir -p /etc/apiserver/specs

COPY demo-vol1.yaml /etc/apiserver/specs/
COPY maya-apiserver /usr/local/bin/
COPY mayactl /usr/local/bin/

COPY entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/entrypoint.sh

ARG ARCH
ARG DBUILD_DATE
ARG DBUILD_REPO_URL
ARG DBUILD_SITE_URL
LABEL org.label-schema.name="m-apiserver"
LABEL org.label-schema.description="API server for OpenEBS"
LABEL org.label-schema.schema-version="1.0"
LABEL org.label-schema.build-date=$DBUILD_DATE
LABEL org.label-schema.vcs-url=$DBUILD_REPO_URL
LABEL org.label-schema.url=$DBUILD_SITE_URL

ENTRYPOINT entrypoint.sh "${MAYA_API_SERVER_NETWORK}"

EXPOSE 5656


text:
#ifndef __DGNC_TTY_H
#define __DGNC_TTY_H

#include "dgnc_driver.h"

int	dgnc_tty_register(struct dgnc_board *brd);

int	dgnc_tty_preinit(void);
int     dgnc_tty_init(struct dgnc_board *);

void	dgnc_tty_post_uninit(void);
void	dgnc_tty_uninit(struct dgnc_board *);

void	dgnc_input(struct channel_t *ch);
void	dgnc_carrier(struct channel_t *ch);
void	dgnc_wakeup_writes(struct channel_t *ch);
void	dgnc_check_queue_flow_control(struct channel_t *ch);

#endif


text:
package models

import (
	"html/template"
	"testing"

	"github.com/stretchr/testify/assert"
)

// TODO TestGetLabelTemplateFile

func TestLabel_CalOpenIssues(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	label := AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label)
	label.CalOpenIssues()
	assert.EqualValues(t, 2, label.NumOpenIssues)
}

func TestLabel_ForegroundColor(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	label := AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label)
	assert.Equal(t, template.CSS("#000"), label.ForegroundColor())

	label = AssertExistsAndLoadBean(t, &Label{ID: 2}).(*Label)
	assert.Equal(t, template.CSS("#fff"), label.ForegroundColor())
}

func TestNewLabels(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	labels := []*Label{
		{RepoID: 2, Name: "labelName2", Color: "#123456"},
		{RepoID: 3, Name: "labelName3", Color: "#23456F"},
	}
	assert.Error(t, NewLabel(&Label{RepoID: 3, Name: "invalid Color", Color: ""}))
	assert.Error(t, NewLabel(&Label{RepoID: 3, Name: "invalid Color", Color: "123456"}))
	assert.Error(t, NewLabel(&Label{RepoID: 3, Name: "invalid Color", Color: "#12345G"}))
	for _, label := range labels {
		AssertNotExistsBean(t, label)
	}
	assert.NoError(t, NewLabels(labels...))
	for _, label := range labels {
		AssertExistsAndLoadBean(t, label, Cond("id = ?", label.ID))
	}
	CheckConsistencyFor(t, &Label{}, &Repository{})
}

func TestGetLabelByID(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	label, err := GetLabelByID(1)
	assert.NoError(t, err)
	assert.EqualValues(t, 1, label.ID)

	_, err = GetLabelByID(NonexistentID)
	assert.True(t, IsErrLabelNotExist(err))
}

func TestGetLabelInRepoByName(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	label, err := GetLabelInRepoByName(1, "label1")
	assert.NoError(t, err)
	assert.EqualValues(t, 1, label.ID)
	assert.Equal(t, "label1", label.Name)

	_, err = GetLabelInRepoByName(1, "")
	assert.True(t, IsErrRepoLabelNotExist(err))

	_, err = GetLabelInRepoByName(NonexistentID, "nonexistent")
	assert.True(t, IsErrRepoLabelNotExist(err))
}

func TestGetLabelInRepoByNames(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	labelIDs, err := GetLabelIDsInRepoByNames(1, []string{"label1", "label2"})
	assert.NoError(t, err)

	assert.Len(t, labelIDs, 2)

	assert.Equal(t, int64(1), labelIDs[0])
	assert.Equal(t, int64(2), labelIDs[1])
}

func TestGetLabelInRepoByNamesDiscardsNonExistentLabels(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	// label3 doesn't exists.. See labels.yml
	labelIDs, err := GetLabelIDsInRepoByNames(1, []string{"label1", "label2", "label3"})
	assert.NoError(t, err)

	assert.Len(t, labelIDs, 2)

	assert.Equal(t, int64(1), labelIDs[0])
	assert.Equal(t, int64(2), labelIDs[1])
	assert.NoError(t, err)
}

func TestGetLabelInRepoByID(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	label, err := GetLabelInRepoByID(1, 1)
	assert.NoError(t, err)
	assert.EqualValues(t, 1, label.ID)

	_, err = GetLabelInRepoByID(1, -1)
	assert.True(t, IsErrRepoLabelNotExist(err))

	_, err = GetLabelInRepoByID(NonexistentID, NonexistentID)
	assert.True(t, IsErrRepoLabelNotExist(err))
}

func TestGetLabelsInRepoByIDs(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	labels, err := GetLabelsInRepoByIDs(1, []int64{1, 2, NonexistentID})
	assert.NoError(t, err)
	if assert.Len(t, labels, 2) {
		assert.EqualValues(t, 1, labels[0].ID)
		assert.EqualValues(t, 2, labels[1].ID)
	}
}

func TestGetLabelsByRepoID(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	testSuccess := func(repoID int64, sortType string, expectedIssueIDs []int64) {
		labels, err := GetLabelsByRepoID(repoID, sortType, ListOptions{})
		assert.NoError(t, err)
		assert.Len(t, labels, len(expectedIssueIDs))
		for i, label := range labels {
			assert.EqualValues(t, expectedIssueIDs[i], label.ID)
		}
	}
	testSuccess(1, "leastissues", []int64{2, 1})
	testSuccess(1, "mostissues", []int64{1, 2})
	testSuccess(1, "reversealphabetically", []int64{2, 1})
	testSuccess(1, "default", []int64{1, 2})
}

// Org vrsions

func TestGetLabelInOrgByName(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	label, err := GetLabelInOrgByName(3, "orglabel3")
	assert.NoError(t, err)
	assert.EqualValues(t, 3, label.ID)
	assert.Equal(t, "orglabel3", label.Name)

	_, err = GetLabelInOrgByName(3, "")
	assert.True(t, IsErrOrgLabelNotExist(err))

	_, err = GetLabelInOrgByName(0, "orglabel3")
	assert.True(t, IsErrOrgLabelNotExist(err))

	_, err = GetLabelInOrgByName(-1, "orglabel3")
	assert.True(t, IsErrOrgLabelNotExist(err))

	_, err = GetLabelInOrgByName(NonexistentID, "nonexistent")
	assert.True(t, IsErrOrgLabelNotExist(err))
}

func TestGetLabelInOrgByNames(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	labelIDs, err := GetLabelIDsInOrgByNames(3, []string{"orglabel3", "orglabel4"})
	assert.NoError(t, err)

	assert.Len(t, labelIDs, 2)

	assert.Equal(t, int64(3), labelIDs[0])
	assert.Equal(t, int64(4), labelIDs[1])
}

func TestGetLabelInOrgByNamesDiscardsNonExistentLabels(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	// orglabel99 doesn't exists.. See labels.yml
	labelIDs, err := GetLabelIDsInOrgByNames(3, []string{"orglabel3", "orglabel4", "orglabel99"})
	assert.NoError(t, err)

	assert.Len(t, labelIDs, 2)

	assert.Equal(t, int64(3), labelIDs[0])
	assert.Equal(t, int64(4), labelIDs[1])
	assert.NoError(t, err)
}

func TestGetLabelInOrgByID(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	label, err := GetLabelInOrgByID(3, 3)
	assert.NoError(t, err)
	assert.EqualValues(t, 3, label.ID)

	_, err = GetLabelInOrgByID(3, -1)
	assert.True(t, IsErrOrgLabelNotExist(err))

	_, err = GetLabelInOrgByID(0, 3)
	assert.True(t, IsErrOrgLabelNotExist(err))

	_, err = GetLabelInOrgByID(-1, 3)
	assert.True(t, IsErrOrgLabelNotExist(err))

	_, err = GetLabelInOrgByID(NonexistentID, NonexistentID)
	assert.True(t, IsErrOrgLabelNotExist(err))
}

func TestGetLabelsInOrgByIDs(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	labels, err := GetLabelsInOrgByIDs(3, []int64{3, 4, NonexistentID})
	assert.NoError(t, err)
	if assert.Len(t, labels, 2) {
		assert.EqualValues(t, 3, labels[0].ID)
		assert.EqualValues(t, 4, labels[1].ID)
	}
}

func TestGetLabelsByOrgID(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	testSuccess := func(orgID int64, sortType string, expectedIssueIDs []int64) {
		labels, err := GetLabelsByOrgID(orgID, sortType, ListOptions{})
		assert.NoError(t, err)
		assert.Len(t, labels, len(expectedIssueIDs))
		for i, label := range labels {
			assert.EqualValues(t, expectedIssueIDs[i], label.ID)
		}
	}
	testSuccess(3, "leastissues", []int64{3, 4})
	testSuccess(3, "mostissues", []int64{4, 3})
	testSuccess(3, "reversealphabetically", []int64{4, 3})
	testSuccess(3, "default", []int64{3, 4})

	var err error
	_, err = GetLabelsByOrgID(0, "leastissues", ListOptions{})
	assert.True(t, IsErrOrgLabelNotExist(err))

	_, err = GetLabelsByOrgID(-1, "leastissues", ListOptions{})
	assert.True(t, IsErrOrgLabelNotExist(err))

}

//

func TestGetLabelsByIssueID(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	labels, err := GetLabelsByIssueID(1)
	assert.NoError(t, err)
	if assert.Len(t, labels, 1) {
		assert.EqualValues(t, 1, labels[0].ID)
	}

	labels, err = GetLabelsByIssueID(NonexistentID)
	assert.NoError(t, err)
	assert.Len(t, labels, 0)
}

func TestUpdateLabel(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	label := AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label)
	// make sure update wont overwrite it
	update := &Label{
		ID:          label.ID,
		Color:       "#ffff00",
		Name:        "newLabelName",
		Description: label.Description,
	}
	label.Color = update.Color
	label.Name = update.Name
	assert.NoError(t, UpdateLabel(update))
	newLabel := AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label)
	assert.EqualValues(t, label.ID, newLabel.ID)
	assert.EqualValues(t, label.Color, newLabel.Color)
	assert.EqualValues(t, label.Name, newLabel.Name)
	assert.EqualValues(t, label.Description, newLabel.Description)
	CheckConsistencyFor(t, &Label{}, &Repository{})
}

func TestDeleteLabel(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	label := AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label)
	assert.NoError(t, DeleteLabel(label.RepoID, label.ID))
	AssertNotExistsBean(t, &Label{ID: label.ID, RepoID: label.RepoID})

	assert.NoError(t, DeleteLabel(label.RepoID, label.ID))
	AssertNotExistsBean(t, &Label{ID: label.ID})

	assert.NoError(t, DeleteLabel(NonexistentID, NonexistentID))
	CheckConsistencyFor(t, &Label{}, &Repository{})
}

func TestHasIssueLabel(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	assert.True(t, HasIssueLabel(1, 1))
	assert.False(t, HasIssueLabel(1, 2))
	assert.False(t, HasIssueLabel(NonexistentID, NonexistentID))
}

func TestNewIssueLabel(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	label := AssertExistsAndLoadBean(t, &Label{ID: 2}).(*Label)
	issue := AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue)
	doer := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)

	// add new IssueLabel
	prevNumIssues := label.NumIssues
	assert.NoError(t, NewIssueLabel(issue, label, doer))
	AssertExistsAndLoadBean(t, &IssueLabel{IssueID: issue.ID, LabelID: label.ID})
	AssertExistsAndLoadBean(t, &Comment{
		Type:     CommentTypeLabel,
		PosterID: doer.ID,
		IssueID:  issue.ID,
		LabelID:  label.ID,
		Content:  "1",
	})
	label = AssertExistsAndLoadBean(t, &Label{ID: 2}).(*Label)
	assert.EqualValues(t, prevNumIssues+1, label.NumIssues)

	// re-add existing IssueLabel
	assert.NoError(t, NewIssueLabel(issue, label, doer))
	CheckConsistencyFor(t, &Issue{}, &Label{})
}

func TestNewIssueLabels(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	label1 := AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label)
	label2 := AssertExistsAndLoadBean(t, &Label{ID: 2}).(*Label)
	issue := AssertExistsAndLoadBean(t, &Issue{ID: 5}).(*Issue)
	doer := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)

	assert.NoError(t, NewIssueLabels(issue, []*Label{label1, label2}, doer))
	AssertExistsAndLoadBean(t, &IssueLabel{IssueID: issue.ID, LabelID: label1.ID})
	AssertExistsAndLoadBean(t, &Comment{
		Type:     CommentTypeLabel,
		PosterID: doer.ID,
		IssueID:  issue.ID,
		LabelID:  label1.ID,
		Content:  "1",
	})
	AssertExistsAndLoadBean(t, &IssueLabel{IssueID: issue.ID, LabelID: label1.ID})
	label1 = AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label)
	assert.EqualValues(t, 3, label1.NumIssues)
	assert.EqualValues(t, 1, label1.NumClosedIssues)
	label2 = AssertExistsAndLoadBean(t, &Label{ID: 2}).(*Label)
	assert.EqualValues(t, 1, label2.NumIssues)
	assert.EqualValues(t, 1, label2.NumClosedIssues)

	// corner case: test empty slice
	assert.NoError(t, NewIssueLabels(issue, []*Label{}, doer))

	CheckConsistencyFor(t, &Issue{}, &Label{})
}

func TestDeleteIssueLabel(t *testing.T) {
	assert.NoError(t, PrepareTestDatabase())
	testSuccess := func(labelID, issueID, doerID int64) {
		label := AssertExistsAndLoadBean(t, &Label{ID: labelID}).(*Label)
		issue := AssertExistsAndLoadBean(t, &Issue{ID: issueID}).(*Issue)
		doer := AssertExistsAndLoadBean(t, &User{ID: doerID}).(*User)

		expectedNumIssues := label.NumIssues
		expectedNumClosedIssues := label.NumClosedIssues
		if BeanExists(t, &IssueLabel{IssueID: issueID, LabelID: labelID}) {
			expectedNumIssues--
			if issue.IsClosed {
				expectedNumClosedIssues--
			}
		}

		assert.NoError(t, DeleteIssueLabel(issue, label, doer))
		AssertNotExistsBean(t, &IssueLabel{IssueID: issueID, LabelID: labelID})
		AssertExistsAndLoadBean(t, &Comment{
			Type:     CommentTypeLabel,
			PosterID: doerID,
			IssueID:  issueID,
			LabelID:  labelID,
		}, `content=""`)
		label = AssertExistsAndLoadBean(t, &Label{ID: labelID}).(*Label)
		assert.EqualValues(t, expectedNumIssues, label.NumIssues)
		assert.EqualValues(t, expectedNumClosedIssues, label.NumClosedIssues)
	}
	testSuccess(1, 1, 2)
	testSuccess(2, 5, 2)
	testSuccess(1, 1, 2) // delete non-existent IssueLabel

	CheckConsistencyFor(t, &Issue{}, &Label{})
}


text:
package com.ickstream.controller.browse;

import com.fasterxml.jackson.databind.JsonNode;
import com.ickstream.common.jsonrpc.MessageHandlerAdapter;
import com.ickstream.controller.service.ServiceController;
import com.ickstream.protocol.common.data.ContentItem;
import com.ickstream.protocol.service.content.*;

import java.util.*;

public class PreferredBrowseMenu implements BrowseMenu {
    protected ServiceController service;
    protected final Map<String, Map<String, Map<String, RequestDescription2>>> contexts = new HashMap<String, Map<String, Map<String, RequestDescription2>>>();
    protected final List<PreferredMenuItem> preferredMenuItems = new ArrayList<PreferredMenuItem>();

    public PreferredBrowseMenu(ServiceController service) {
        this.service = service;
    }

    @Override
    public void findChilds(final String language, final MenuItem contentItem, final ResponseListener<BrowseResponse> listener) {
        getProtocolDescription2(language, new BrowseMenu.ResponseListener<Boolean>() {
            @Override
            public void onResponse(Boolean contentResponse) {
                getPreferredMenus(language, new BrowseMenu.ResponseListener<Boolean>() {
                    @Override
                    public void onResponse(Boolean contentResponse) {
                        if (contentItem != null) {
                            if (((AbstractPreferredMenuItem) contentItem).getPreferredMenuItem().getChildItems() != null) {
                                List<PreferredMenuItem> preferredMenuItems = ((AbstractPreferredMenuItem) contentItem).getPreferredMenuItem().getChildItems();
                                BrowseResponse response = new BrowseResponse();
                                response.setItems(new ArrayList<MenuItem>());
                                for (PreferredMenuItem preferredMenuItem : preferredMenuItems) {
                                    if (!preferredMenuItem.getType().equals("search")) {
                                        response.getItems().add(new PreferredTextMenuItem(preferredMenuItem, service, preferredMenuItem.getText(), contentItem));
                                    }
                                }
                                listener.onResponse(response);
                            } else if (((AbstractPreferredMenuItem) contentItem).getPreferredMenuItem().getChildRequest() != null) {
                                final PreferredMenuRequest childRequest = ((AbstractPreferredMenuItem) contentItem).getPreferredMenuItem().getChildRequest();
                                String requestId = childRequest.getRequest();
                                Map<String, Object> request = getRequest(requestId, contentItem);
                                service.findItems(null, (String) request.get("contextId"), language, request, new MessageHandlerAdapter<ContentResponse>() {
                                    @Override
                                    public void onMessage(ContentResponse message) {
                                        BrowseResponse response = new BrowseResponse();
                                        response.setItems(new ArrayList<MenuItem>());
                                        response.setLastChanged(message.getLastChanged());

                                        for (ContentItem item : message.getItems()) {
                                            response.getItems().add(new PreferredContentMenuItem(childRequest, service, null, item, contentItem));
                                        }
                                        listener.onResponse(response);
                                    }
                                });
                            } else if ((contentItem instanceof PreferredContentMenuItem && ((PreferredContentMenuItem) contentItem).getContentItem().getPreferredChildRequest() != null)) {

                                final PreferredMenuRequest childRequest = new PreferredMenuRequest(((PreferredContentMenuItem) contentItem).getContentItem().getPreferredChildRequest());
                                String requestId = childRequest.getRequest();
                                Map<String, Object> request = getRequest(requestId, contentItem);
                                service.findItems(null, (String) request.get("contextId"), language, request, new MessageHandlerAdapter<ContentResponse>() {
                                    @Override
                                    public void onMessage(ContentResponse message) {
                                        BrowseResponse response = new BrowseResponse();
                                        response.setItems(new ArrayList<MenuItem>());
                                        response.setLastChanged(message.getLastChanged());

                                        for (ContentItem item : message.getItems()) {
                                            response.getItems().add(new PreferredContentMenuItem(childRequest, service, null, item, contentItem));
                                        }
                                        listener.onResponse(response);
                                    }
                                });
                            } else {
                                listener.onResponse(new BrowseResponse());
                            }
                        } else {
                            BrowseResponse response = new BrowseResponse();
                            response.setItems(new ArrayList<MenuItem>());
                            for (PreferredMenuItem preferredMenuItem : preferredMenuItems) {
                                if (!preferredMenuItem.getType().equals("search")) {
                                    response.getItems().add(new PreferredTextMenuItem(preferredMenuItem, service, preferredMenuItem.getText(), contentItem));
                                }
                            }
                            listener.onResponse(response);
                        }
                    }
                });
            }
        });
    }

    private Map<String, Object> getRequest(String request, MenuItem contentItem) {
        for (Map.Entry<String, Map<String, Map<String, RequestDescription2>>> contextEntry : contexts.entrySet()) {
            for (Map.Entry<String, Map<String, RequestDescription2>> typeEntry : contextEntry.getValue().entrySet()) {
                if (typeEntry.getValue().containsKey(request)) {
                    RequestDescription2 spec = typeEntry.getValue().get(request);
                    Map<String, Object> params = new HashMap<String, Object>();
                    if (spec.getParameters().contains("contextId")) {
                        params.put("contextId", contextEntry.getKey());
                    }
                    if (spec.getParameters().contains("type")) {
                        params.put("type", typeEntry.getKey());
                    }
                    if (spec.getValues() != null) {
                        Iterator<Map.Entry<String, JsonNode>> it = spec.getValues().fields();
                        while (it.hasNext()) {
                            Map.Entry<String, JsonNode> param = it.next();
                            if (param.getValue().isNumber()) {
                                params.put(param.getKey(), param.getValue().numberValue());
                            } else if (param.getValue().isTextual()) {
                                params.put(param.getKey(), param.getValue().textValue());
                            }
                        }
                    }
                    if (spec.getParameters() != null && spec.getParameters().size() > 0) {
                        MenuItem item = contentItem;
                        while (item != null) {
                            if (item.getType() != null && spec.getParameters().contains(item.getType() + "Id") && !params.containsKey(item.getType() + "Id")) {
                                params.put(item.getType() + "Id", item.getId());
                            }
                            item = item.getParent();
                        }
                    }
                    return params;
                }
            }
        }
        return null;
    }

    protected void getProtocolDescription2(String language, final ResponseListener<Boolean> listener) {
        if (contexts.size() == 0) {
            service.getProtocolDescription2(new GetProtocolDescriptionRequest(language), new MessageHandlerAdapter<GetProtocolDescription2Response>() {
                @Override
                public void onMessage(GetProtocolDescription2Response message) {
                    synchronized (contexts) {
                        contexts.clear();
                        for (ProtocolDescription2Context context : message.getItems()) {
                            contexts.put(context.getContextId(), context.getSupportedRequests());
                        }
                    }
                    listener.onResponse(Boolean.TRUE);
                }
            }, 10000);
        } else {
            listener.onResponse(Boolean.FALSE);
        }
    }

    protected void getPreferredMenus(String language, final BrowseMenu.ResponseListener<Boolean> listener) {
        if (preferredMenuItems.size() == 0) {
            service.getPreferredMenus(new GetPreferredMenusRequest(language), new MessageHandlerAdapter<GetPreferredMenusResponse>() {
                @Override
                public void onMessage(GetPreferredMenusResponse message) {
                    synchronized (preferredMenuItems) {
                        preferredMenuItems.clear();
                        preferredMenuItems.addAll(message.getItems());
                    }
                    listener.onResponse(Boolean.TRUE);
                }
            }, 10000);
        } else {
            listener.onResponse(Boolean.FALSE);
        }
    }
}


text:
{-# LANGUAGE CPP #-}
#ifdef LANGUAGE_DeriveDataTypeable
{-# LANGUAGE DeriveDataTypeable #-}
#endif
#if __GLASGOW_HASKELL__ >= 706
{-# LANGUAGE PolyKinds #-}
#endif
#if __GLASGOW_HASKELL__ >= 702
{-# LANGUAGE DeriveGeneric #-}
#endif
-- manual generics instances are not safe
#if __GLASGOW_HASKELL__ >= 707
{-# LANGUAGE Safe #-}
#elif __GLASGOW_HASKELL__ >= 702
{-# LANGUAGE Trustworthy #-}
#endif

{-# OPTIONS_GHC -fno-warn-deprecations #-}
----------------------------------------------------------------------------
-- |
-- Module     : Data.Tagged
-- Copyright  : 2009-2015 Edward Kmett
-- License    : BSD3
--
-- Maintainer  : Edward Kmett <ekmett@gmail.com>
-- Stability   : experimental
-- Portability : portable
--
-------------------------------------------------------------------------------

module Data.Tagged
    (
    -- * Tagged values
      Tagged(..)
    , retag
    , untag
    , tagSelf
    , untagSelf
    , asTaggedTypeOf
    , witness
    -- * Conversion
    , proxy
    , unproxy
    , tagWith
    -- * Proxy methods GHC dropped
    , reproxy
    ) where

#if MIN_VERSION_base(4,8,0)
import Control.Applicative (liftA2)
#else
import Control.Applicative ((<$>), liftA2, Applicative(..))
import Data.Traversable (Traversable(..))
import Data.Monoid
#endif
import Data.Bits
import Data.Foldable (Foldable(..))
#ifdef MIN_VERSION_deepseq
import Control.DeepSeq (NFData(..))
#endif
#ifdef MIN_VERSION_transformers
import Data.Functor.Classes ( Eq1(..), Ord1(..), Read1(..), Show1(..)
# if !(MIN_VERSION_transformers(0,4,0)) || MIN_VERSION_transformers(0,5,0)
                            , Eq2(..), Ord2(..), Read2(..), Show2(..)
# endif
                            )
#endif
import Control.Monad (liftM)
#if MIN_VERSION_base(4,8,0)
import Data.Bifunctor
#endif
#if MIN_VERSION_base(4,10,0)
import Data.Bifoldable (Bifoldable(..))
import Data.Bitraversable (Bitraversable(..))
#endif
#ifdef __GLASGOW_HASKELL__
import Data.Data
#endif
import Data.Ix (Ix(..))
#if __GLASGOW_HASKELL__ < 707
import Data.Proxy
#endif
#if MIN_VERSION_base(4,9,0)
import Data.Semigroup (Semigroup(..))
#endif
import Data.String (IsString(..))
import Foreign.Ptr (castPtr)
import Foreign.Storable (Storable(..))
#if __GLASGOW_HASKELL__ >= 702
import GHC.Generics (Generic)
#if __GLASGOW_HASKELL__ >= 706
import GHC.Generics (Generic1)
#endif
#endif

-- | A @'Tagged' s b@ value is a value @b@ with an attached phantom type @s@.
-- This can be used in place of the more traditional but less safe idiom of
-- passing in an undefined value with the type, because unlike an @(s -> b)@,
-- a @'Tagged' s b@ can't try to use the argument @s@ as a real value.
--
-- Moreover, you don't have to rely on the compiler to inline away the extra
-- argument, because the newtype is \"free\"
--
-- 'Tagged' has kind @k -> * -> *@ if the compiler supports @PolyKinds@, therefore
-- there is an extra @k@ showing in the instance haddocks that may cause confusion.
newtype Tagged s b = Tagged { unTagged :: b } deriving
  ( Eq, Ord, Ix, Bounded
#if __GLASGOW_HASKELL__ >= 702
  , Generic
#if __GLASGOW_HASKELL__ >= 706
  , Generic1
#endif
#endif

#if __GLASGOW_HASKELL__ >= 707
  , Typeable
#endif

  )

#ifdef __GLASGOW_HASKELL__
#if __GLASGOW_HASKELL__ < 707
instance Typeable2 Tagged where
  typeOf2 _ = mkTyConApp taggedTyCon []

taggedTyCon :: TyCon
#if __GLASGOW_HASKELL__ < 704
taggedTyCon = mkTyCon "Data.Tagged.Tagged"
#else
taggedTyCon = mkTyCon3 "tagged" "Data.Tagged" "Tagged"
#endif

#endif

instance (Data s, Data b) => Data (Tagged s b) where
  gfoldl f z (Tagged b) = z Tagged `f` b
  toConstr _ = taggedConstr
  gunfold k z c = case constrIndex c of
    1 -> k (z Tagged)
    _ -> error "gunfold"
  dataTypeOf _ = taggedDataType
  dataCast1 f = gcast1 f
  dataCast2 f = gcast2 f

taggedConstr :: Constr
taggedConstr = mkConstr taggedDataType "Tagged" [] Prefix
{-# INLINE taggedConstr #-}

taggedDataType :: DataType
taggedDataType = mkDataType "Data.Tagged.Tagged" [taggedConstr]
{-# INLINE taggedDataType #-}
#endif

instance Show b => Show (Tagged s b) where
    showsPrec n (Tagged b) = showParen (n > 10) $
        showString "Tagged " .
        showsPrec 11 b

instance Read b => Read (Tagged s b) where
    readsPrec d = readParen (d > 10) $ \r ->
        [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- readsPrec 11 s]

#if MIN_VERSION_base(4,9,0)
instance Semigroup a => Semigroup (Tagged s a) where
    Tagged a <> Tagged b = Tagged (a <> b)
    stimes n (Tagged a)  = Tagged (stimes n a)

instance (Semigroup a, Monoid a) => Monoid (Tagged s a) where
    mempty = Tagged mempty
    mappend = (<>)
#else
instance Monoid a => Monoid (Tagged s a) where
    mempty = Tagged mempty
    mappend (Tagged a) (Tagged b) = Tagged (mappend a b)
#endif

instance Functor (Tagged s) where
    fmap f (Tagged x) = Tagged (f x)
    {-# INLINE fmap #-}

#if MIN_VERSION_base(4,8,0)
-- this instance is provided by the bifunctors package for GHC<7.9
instance Bifunctor Tagged where
    bimap _ g (Tagged b) = Tagged (g b)
    {-# INLINE bimap #-}
#endif

#if MIN_VERSION_base(4,10,0)
-- these instances are provided by the bifunctors package for GHC<8.1
instance Bifoldable Tagged where
    bifoldMap _ g (Tagged b) = g b
    {-# INLINE bifoldMap #-}

instance Bitraversable Tagged where
    bitraverse _ g (Tagged b) = Tagged <$> g b
    {-# INLINE bitraverse #-}
#endif

#ifdef MIN_VERSION_deepseq
instance NFData b => NFData (Tagged s b) where
    rnf (Tagged b) = rnf b
#endif

#ifdef MIN_VERSION_transformers
# if MIN_VERSION_transformers(0,4,0) && !(MIN_VERSION_transformers(0,5,0))
instance Eq1 (Tagged s) where
    eq1 = (==)

instance Ord1 (Tagged s) where
    compare1 = compare

instance Read1 (Tagged s) where
    readsPrec1 = readsPrec

instance Show1 (Tagged s) where
    showsPrec1 = showsPrec
# else
instance Eq1 (Tagged s) where
    liftEq eq (Tagged a) (Tagged b) = eq a b

instance Ord1 (Tagged s) where
    liftCompare cmp (Tagged a) (Tagged b) = cmp a b

instance Read1 (Tagged s) where
    liftReadsPrec rp _ d = readParen (d > 10) $ \r ->
        [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- rp 11 s]

instance Show1 (Tagged s) where
    liftShowsPrec sp _ n (Tagged b) = showParen (n > 10) $
        showString "Tagged " .
        sp 11 b

instance Eq2 Tagged where
    liftEq2 _ eq (Tagged a) (Tagged b) = eq a b

instance Ord2 Tagged where
    liftCompare2 _ cmp (Tagged a) (Tagged b) = cmp a b

instance Read2 Tagged where
    liftReadsPrec2 _ _ rp _ d = readParen (d > 10) $ \r ->
        [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- rp 11 s]

instance Show2 Tagged where
    liftShowsPrec2 _ _ sp _ n (Tagged b) = showParen (n > 10) $
        showString "Tagged " .
        sp 11 b
# endif
#endif

instance Applicative (Tagged s) where
    pure = Tagged
    {-# INLINE pure #-}
    Tagged f <*> Tagged x = Tagged (f x)
    {-# INLINE (<*>) #-}
    _ *> n = n
    {-# INLINE (*>) #-}

instance Monad (Tagged s) where
    return = pure
    {-# INLINE return #-}
    Tagged m >>= k = k m
    {-# INLINE (>>=) #-}
    (>>) = (*>)
    {-# INLINE (>>) #-}

instance Foldable (Tagged s) where
    foldMap f (Tagged x) = f x
    {-# INLINE foldMap #-}
    fold (Tagged x) = x
    {-# INLINE fold #-}
    foldr f z (Tagged x) = f x z
    {-# INLINE foldr #-}
    foldl f z (Tagged x) = f z x
    {-# INLINE foldl #-}
    foldl1 _ (Tagged x) = x
    {-# INLINE foldl1 #-}
    foldr1 _ (Tagged x) = x
    {-# INLINE foldr1 #-}

instance Traversable (Tagged s) where
    traverse f (Tagged x) = Tagged <$> f x
    {-# INLINE traverse #-}
    sequenceA (Tagged x) = Tagged <$> x
    {-# INLINE sequenceA #-}
    mapM f (Tagged x) = liftM Tagged (f x)
    {-# INLINE mapM #-}
    sequence (Tagged x) = liftM Tagged x
    {-# INLINE sequence #-}

instance Enum a => Enum (Tagged s a) where
    succ = fmap succ
    pred = fmap pred
    toEnum = Tagged . toEnum
    fromEnum (Tagged x) = fromEnum x
    enumFrom (Tagged x) = map Tagged (enumFrom x)
    enumFromThen (Tagged x) (Tagged y) = map Tagged (enumFromThen x y)
    enumFromTo (Tagged x) (Tagged y) = map Tagged (enumFromTo x y)
    enumFromThenTo (Tagged x) (Tagged y) (Tagged z) =
        map Tagged (enumFromThenTo x y z)

instance Num a => Num (Tagged s a) where
    (+) = liftA2 (+)
    (-) = liftA2 (-)
    (*) = liftA2 (*)
    negate = fmap negate
    abs = fmap abs
    signum = fmap signum
    fromInteger = Tagged . fromInteger

instance Real a => Real (Tagged s a) where
    toRational (Tagged x) = toRational x

instance Integral a => Integral (Tagged s a) where
    quot = liftA2 quot
    rem = liftA2 rem
    div = liftA2 div
    mod = liftA2 mod
    quotRem (Tagged x) (Tagged y) = (Tagged a, Tagged b) where
        (a, b) = quotRem x y
    divMod (Tagged x) (Tagged y) = (Tagged a, Tagged b) where
        (a, b) = divMod x y
    toInteger (Tagged x) = toInteger x

instance Fractional a => Fractional (Tagged s a) where
    (/) = liftA2 (/)
    recip = fmap recip
    fromRational = Tagged . fromRational

instance Floating a => Floating (Tagged s a) where
    pi = Tagged pi
    exp = fmap exp
    log = fmap log
    sqrt = fmap sqrt
    sin = fmap sin
    cos = fmap cos
    tan = fmap tan
    asin = fmap asin
    acos = fmap acos
    atan = fmap atan
    sinh = fmap sinh
    cosh = fmap cosh
    tanh = fmap tanh
    asinh = fmap asinh
    acosh = fmap acosh
    atanh = fmap atanh
    (**) = liftA2 (**)
    logBase = liftA2 logBase

instance RealFrac a => RealFrac (Tagged s a) where
    properFraction (Tagged x) = (a, Tagged b) where
        (a, b) = properFraction x
    truncate (Tagged x) = truncate x
    round (Tagged x) = round x
    ceiling (Tagged x) = ceiling x
    floor (Tagged x) = floor x

instance RealFloat a => RealFloat (Tagged s a) where
    floatRadix (Tagged x) = floatRadix x
    floatDigits (Tagged x) = floatDigits x
    floatRange (Tagged x) = floatRange x
    decodeFloat (Tagged x) = decodeFloat x
    encodeFloat m n = Tagged (encodeFloat m n)
    exponent (Tagged x) = exponent x
    significand = fmap significand
    scaleFloat n = fmap (scaleFloat n)
    isNaN (Tagged x) = isNaN x
    isInfinite (Tagged x) = isInfinite x
    isDenormalized (Tagged x) = isDenormalized x
    isNegativeZero (Tagged x) = isNegativeZero x
    isIEEE (Tagged x) = isIEEE x
    atan2 = liftA2 atan2

instance Bits a => Bits (Tagged s a) where
    Tagged a .&. Tagged b = Tagged (a .&. b)
    Tagged a .|. Tagged b = Tagged (a .|. b)
    xor (Tagged a) (Tagged b) = Tagged (xor a b)
    complement (Tagged a) = Tagged (complement a)
    shift (Tagged a) i = Tagged (shift a i)
    shiftL (Tagged a) i = Tagged (shiftL a i)
    shiftR (Tagged a) i = Tagged (shiftR a i)
    rotate (Tagged a) i = Tagged (rotate a i)
    rotateL (Tagged a) i = Tagged (rotateL a i)
    rotateR (Tagged a) i = Tagged (rotateR a i)
    bit i = Tagged (bit i)
    setBit (Tagged a) i = Tagged (setBit a i)
    clearBit (Tagged a) i = Tagged (clearBit a i)
    complementBit (Tagged a) i = Tagged (complementBit a i)
    testBit (Tagged a) i = testBit a i
    isSigned (Tagged a) = isSigned a
    bitSize (Tagged a) = bitSize a -- deprecated, but still required :(
#if MIN_VERSION_base(4,5,0)
    unsafeShiftL (Tagged a) i = Tagged (unsafeShiftL a i)
    unsafeShiftR (Tagged a) i = Tagged (unsafeShiftR a i)
    popCount (Tagged a) = popCount a
#endif
#if MIN_VERSION_base(4,7,0)
    bitSizeMaybe (Tagged a) = bitSizeMaybe a
    zeroBits = Tagged zeroBits
#endif

#if MIN_VERSION_base(4,7,0)
instance FiniteBits a => FiniteBits (Tagged s a) where
    finiteBitSize (Tagged a) = finiteBitSize a
# if MIN_VERSION_base(4,8,0)
    countLeadingZeros (Tagged a) = countLeadingZeros a
    countTrailingZeros (Tagged a) = countTrailingZeros a
# endif
#endif

instance IsString a => IsString (Tagged s a) where
    fromString = Tagged . fromString

instance Storable a => Storable (Tagged s a) where
    sizeOf t = sizeOf a
      where
        Tagged a = Tagged undefined `asTypeOf` t
    alignment t = alignment a
      where
        Tagged a = Tagged undefined `asTypeOf` t
    peek ptr = Tagged <$> peek (castPtr ptr)
    poke ptr (Tagged a) = poke (castPtr ptr) a
    peekElemOff ptr i = Tagged <$> peekElemOff (castPtr ptr) i
    pokeElemOff ptr i (Tagged a) = pokeElemOff (castPtr ptr) i a
    peekByteOff ptr i = Tagged <$> peekByteOff (castPtr ptr) i
    pokeByteOff ptr i (Tagged a) = pokeByteOff (castPtr ptr) i a

-- | Some times you need to change the tag you have lying around.
-- Idiomatic usage is to make a new combinator for the relationship between the
-- tags that you want to enforce, and define that combinator using 'retag'.
--
-- @
-- data Succ n
-- retagSucc :: 'Tagged' n a -> 'Tagged' (Succ n) a
-- retagSucc = 'retag'
-- @
retag :: Tagged s b -> Tagged t b
retag = Tagged . unTagged
{-# INLINE retag #-}

-- | Alias for 'unTagged'
untag :: Tagged s b -> b
untag = unTagged

-- | Tag a value with its own type.
tagSelf :: a -> Tagged a a
tagSelf = Tagged
{-# INLINE tagSelf #-}

-- | 'asTaggedTypeOf' is a type-restricted version of 'const'. It is usually used as an infix operator, and its typing forces its first argument (which is usually overloaded) to have the same type as the tag of the second.
asTaggedTypeOf :: s -> tagged s b -> s
asTaggedTypeOf = const
{-# INLINE asTaggedTypeOf #-}

witness :: Tagged a b -> a -> b
witness (Tagged b) _ = b
{-# INLINE witness #-}

-- | 'untagSelf' is a type-restricted version of 'untag'.
untagSelf :: Tagged a a -> a
untagSelf (Tagged x) = x
{-# INLINE untagSelf #-}

-- | Convert from a 'Tagged' representation to a representation
-- based on a 'Proxy'.
proxy :: Tagged s a -> proxy s -> a
proxy (Tagged x) _ = x
{-# INLINE proxy #-}

-- | Convert from a representation based on a 'Proxy' to a 'Tagged'
-- representation.
unproxy :: (Proxy s -> a) -> Tagged s a
unproxy f = Tagged (f Proxy)
{-# INLINE unproxy #-}

-- | Another way to convert a proxy to a tag.
tagWith :: proxy s -> a -> Tagged s a
tagWith _ = Tagged
{-# INLINE tagWith #-}

-- | Some times you need to change the proxy you have lying around.
-- Idiomatic usage is to make a new combinator for the relationship
-- between the proxies that you want to enforce, and define that
-- combinator using 'reproxy'.
--
-- @
-- data Succ n
-- reproxySucc :: proxy n -> 'Proxy' (Succ n)
-- reproxySucc = 'reproxy'
-- @
reproxy :: proxy a -> Proxy b
reproxy _ = Proxy


text:
#import "MBElement.h"
#import "MBAttributeDefinition.h"
#import "MBDocumentDefinition.h"
#import "StringUtilities.h"

@interface MBElement()
  -(void) setDefinition:(MBElementDefinition*) definition;
  -(NSString*) cookValue:(NSString*) uncooked;
@end

@interface MBElementContainer()
- (void) copyChildrenInto:(MBElementContainer*) other;
- (void) addAllPathsTo:(NSMutableSet*) set currentPath:(NSString*) currentPath;
@end

@implementation MBElement

-(id) initWithDefinition:(id) definition {
	self = [super init];
	if (self != nil) {
		self.definition = definition;
		_values = [[NSMutableDictionary alloc] initWithCapacity:8];
	}
	return self;
}

- (void) dealloc
{
	[_definition release];
	[_values release];
	[super dealloc];
}

- (id) copy {
	MBElement *newElement = [[MBElement alloc] initWithDefinition: self.definition];
	[newElement->_values addEntriesFromDictionary:_values];
	[self copyChildrenInto: newElement];
	return newElement;
}

- (BOOL)isEqualToElement:(MBElement *)element {
    return [self isEqualToElementContainer:element];
}

- (void) assignByName:(MBElementContainer*) other {
	[other deleteAllChildElements];

	MBElementDefinition *def = self.definition;
	for(MBAttributeDefinition *attrDef in [def attributes]) {
		if([other.definition isValidAttribute: attrDef.name]) {
			[other setValue:[self valueForAttribute: attrDef.name] forKey:attrDef.name];
		}
	}

	for(NSString *elementName in [_elements allKeys]) {
		for(MBElement *src in [_elements valueForKey:elementName]) {
			MBElement *newElem = [other createElementWithName: src.definition.name];
			[src assignByName:newElem];
		}
	}
}

- (void) assignToElement:(MBElement*) target {
	if(![target->_definition.name isEqualToString:_definition.name]) {
		NSString *msg = [NSString stringWithFormat:@"Cannot assign element since types differ: %@ != %@ (use assignByName:)", target->_definition.name, _definition.name];
		@throw [NSException exceptionWithName:@"CannotAssign" reason:msg userInfo:nil];

	}
	[target->_values removeAllObjects];
	[target->_values addEntriesFromDictionary:_values];
	[target->_elements removeAllObjects];
	[self copyChildrenInto: target];
}

- (NSString*) uniqueId {
	NSMutableString *uid = [NSMutableString stringWithCapacity:200];
	[uid appendFormat:@"%@", [self definition].name];
	for(MBAttributeDefinition* def in [_definition attributes]) {
		NSString *attrName = def.name;
		if(![attrName isEqualToString:@"xmlns"]) {
			NSString *attrValue = [_values objectForKey: attrName];
			[uid appendString: @"_"];
			if (attrValue) [uid appendString: [self cookValue: attrValue]];
		}
	}
	[uid appendString:[super uniqueId]];
	return uid;
}

-(void) addAllPathsTo:(NSMutableSet*) set currentPath:(NSString*) currentPath {

	NSString *elementName = [[self definition]name];
#pragma unused(elementName)

	for(NSString *attr in [_values allKeys]) {
		[set addObject: [NSString stringWithFormat:@"%@/@%@", currentPath, attr]];
	}
	[super addAllPathsTo:set currentPath:currentPath];
}

- (id) valueForPathComponents:(NSMutableArray*)pathComponents withPath: (NSString*) originalPath nillIfMissing:(BOOL) nillIfMissing translatedPathComponents:(NSMutableArray*)translatedPathComponents {
    if([pathComponents count] > 0 && [[pathComponents objectAtIndex:0] hasPrefix:@"@"]) {
	   NSString *attrName = [pathComponents objectAtIndex:0];
		[translatedPathComponents addObject:attrName];
	   return [self valueForAttribute: [attrName substringFromIndex:1]];
	}
	else return [super valueForPathComponents: pathComponents withPath:originalPath nillIfMissing: nillIfMissing translatedPathComponents:translatedPathComponents];
}

-(BOOL) isValidAttribute:(NSString*) attributeName {
	return [[self definition] isValidAttribute: attributeName];
}

-(void) validateAttribute:(NSString*) attributeName {
	if(![self isValidAttribute: attributeName]) {
     	NSString *msg = [NSString stringWithFormat:@"Attribute %@ not defined for element %@. Use one of %@", attributeName, [[self definition] name], [[self definition] attributeNames]];
     	@throw [NSException exceptionWithName: @"InvalidAttributeName" reason:msg userInfo:nil];
	}
}

-(void) setValue:(NSString *)value forPath:(NSString *)path {
	if([path hasPrefix:@"@"]) [self setValue:value forAttribute:[path substringFromIndex:1]];
	else [super setValue:value forPath:path];
}

-(void) setValue:(id)value forAttribute:(NSString *)attributeName {
	[self setValue:value forAttribute:attributeName throwIfInvalid: TRUE];
}

- (void) setValue:(id)value forAttribute:(NSString *)attributeName throwIfInvalid:(BOOL) throwIfInvalid {
   	if(throwIfInvalid) {
		[self validateAttribute: attributeName];
        if (value)
            [_values setObject:value forKey:attributeName];
        else
            [_values removeObjectForKey:attributeName];
	}
	else {
        if([self isValidAttribute: attributeName]) {
            if (value) [_values setObject:value forKey:attributeName];
            else [_values removeObjectForKey:attributeName];
        }
	}
}

-(NSString*) valueForAttribute:(NSString*)attributeName {
	[self validateAttribute: attributeName];
	id result =  [_values objectForKey:attributeName];
    return result;
}

-(id) valueForKey:(NSString *)key {
	return [self valueForAttribute:key];
}

-(void) setValue:(id)value forKey:(NSString *)key {
	[self setValue:value forAttribute:key];
}

-(void) setDefinition:(MBElementDefinition*) definition {
	[definition retain];
	_definition = definition;
}

- (id) definition {
	return _definition;
}

-(NSString*) cookValue:(NSString*) uncooked {
	if(uncooked == nil) return nil;

	NSMutableString *cooked = [NSMutableString stringWithString:@""];
	for(int i=0; i<[uncooked length]; i++) {
		int c = [uncooked characterAtIndex:i];
		if(c < 32 || c=='&' || c=='\'' || c>126) [cooked appendFormat:@"&#%i;", c];
		else [cooked appendFormat:@"%c", c];
	}
	return cooked;
}

-(void) attributeAsXml:(NSString*)name withValue:(id) attrValue withBuffer:(NSMutableString*) buffer {

	NSString *escaped = [attrValue xmlSimpleEscape];
    if (attrValue) [buffer appendFormat:@" %@='%@'", name, escaped];
}

- (NSString *) bodyText {
	if([self isValidAttribute: TEXT_ATTRIBUTE]) return [self valueForAttribute:TEXT_ATTRIBUTE];
	return nil;
}

-(void) setBodyText:(NSString*) text {
	[self setValue:text forAttribute:TEXT_ATTRIBUTE];
}

- (void) asXml:(NSMutableString*) buffer withLevel:(int)level {
    BOOL hasBodyText = [[self bodyText] length];
    [buffer appendString:[NSString stringWithSpaces:level]];
    [buffer appendString:@"<"];
    [buffer appendString:_definition.name];

    for(MBAttributeDefinition* def in [_definition attributes]) {
        NSString *attrName = def.name;
        NSString *attrValue = [_values objectForKey: attrName];
        if(![attrName isEqualToString:TEXT_ATTRIBUTE]) [self attributeAsXml:attrName withValue:attrValue withBuffer:buffer];
    }
    if([[_definition children] count] == 0 && !hasBodyText)
        [buffer appendString:@"/>\n"];
    else {
        [buffer appendString:@">"];
        if(hasBodyText) {
            NSString *escaped =[self.bodyText xmlSimpleEscape];
            [buffer appendString: escaped];
        }
        else [buffer appendString: @"\n"];

        for(MBElementDefinition *elemDef in [_definition children]) {
            NSArray *lst = [[self elements] objectForKey:elemDef.name];
            for(MBElement *elem in lst)
                [elem asXml: buffer withLevel:(level + 2)];
        }

        [buffer appendString:[NSString stringWithSpaces:hasBodyText?0:level]];
        [buffer appendString:@"</"];
        [buffer appendString:_definition.name];
        [buffer appendString:@">"];
    }

}

- (NSString *) asXmlWithLevel:(int)level
{
    NSMutableString *result = [[NSMutableString new] autorelease];
    [self asXml:result withLevel: level];
    return result;
}

- (NSString *) description {
	return [self asXmlWithLevel: 0];
}

- (NSString *) name {
	return [self definition].name;
}

- (NSInteger) physicalIndexWithCurrentPath: (NSString *)path {
	NSMutableArray *pathComponents = [path splitPath];
	NSString *lastPathComponent = [pathComponents objectAtIndex:[pathComponents count] - 1];
	NSArray *elementComponentParts = [lastPathComponent componentsSeparatedByString:@"["];
	NSString *elementName = [elementComponentParts objectAtIndex:0];

	if([elementName isEqualToString: [self name]]) {
		NSMutableString *idxStr = [NSMutableString stringWithString: [elementComponentParts objectAtIndex:1]];
		[idxStr replaceOccurrencesOfString:@"]" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [idxStr length])];
		return [idxStr intValue];
	}else {
		NSString *msg = [NSString stringWithFormat:@"Path %@ not for element %@.", path, [self name]];
     	@throw [NSException exceptionWithName: @"InvalidElementPath" reason:msg userInfo:nil];
	}

	return -1;
}

@end


text:
package uk.gov.hmrc.ct.ct600a.v2

import uk.gov.hmrc.ct.box.{Calculated, CtBoxIdentifier, CtOptionalInteger}
import uk.gov.hmrc.ct.ct600.v2.calculations.LoansToParticipatorsCalculator
import uk.gov.hmrc.ct.ct600a.v2.retriever.CT600ABoxRetriever

case class A9(value: Option[Int]) extends CtBoxIdentifier(name = "A9 - Date that part/whole loan released/written off more than 9 months after period end date and date completing return is later than resolution date")
 with CtOptionalInteger

object A9 extends Calculated[A9, CT600ABoxRetriever] with LoansToParticipatorsCalculator {

  override def calculate(fieldValueRetriever: CT600ABoxRetriever): A9 = {
    import fieldValueRetriever._
    calculateA9(computationsBoxRetriever.cp2(), lp03(), lpq07())
  }
}


text:
package fsb.explore;

import java.util.Arrays;
import java.util.List;
import java.util.WeakHashMap;

import fsb.ast.Assume;
import fsb.ast.SymbolTable;
import fsb.tvl.ArithValue;
import fsb.tvl.DetArithValue;
import fsb.utils.Options;
import gnu.trove.map.hash.THashMap;

public abstract class SBState extends State {

//protected class LocalResMap extends TreeMap<String, ArithValue> {}
//	@SuppressWarnings("serial")
//	protected class LocalResMap extends StateVariables{
//
//		protected LocalResMap(int sizeLocals) {
//			super(sizeLocals,false);
//			// TODO Auto-generated constructor stub
//		}
//
//		public LocalResMap(StateVariables other) {
//			// TODO Auto-generated constructor stub
//			super(other);
//		}
//
//	}

	//private static THashMap<LocalResMap, LocalResMap> cachedLocals = new THashMap<LocalResMap, LocalResMap>();
	private static WeakHashMap<StateVariables, StateVariables> cachedLocals = new WeakHashMap<StateVariables, StateVariables>();

	protected final StateVariables locals[];
	protected int pc[];
	public SBState() {
		super();

		this.locals = new StateVariables[numProcs];
		this.pc = new int[numProcs];
		List<Integer> program_locals = program.getLocals();

		for (int i = 0; i < numProcs; i++) {
			this.locals[i] = new StateVariables(program_locals.size(),false);
			for (Integer var : program_locals) {
				this.locals[i].put(var, DetArithValue.getInstance(0));
			}
			this.pc[i] = 0;
		}
		//this.lastMem = 1;
	}

	public SBState(SBState s) {
		super(s);
		this.locals = new StateVariables[numProcs];
		this.pc = new int[numProcs];
		//this.lastMem = s.lastMem;

		for (int i = 0; i < numProcs; i++) {
			this.locals[i] = (StateVariables) s.locals[i];
			this.pc[i] = s.pc[i];
		}

		if (!Options.LAZY_COPY) {
			for (int i = 0; i < numProcs; i++) {
				this.locals[i] = new StateVariables(locals[i].size(),false);
				this.locals[i].putAll(s.locals[i]);
			}
		}
	}

	public void advancePC(int pid) {
		pc[pid]++;
	}

	public void setPC(int pid, int toLabel) {
		pc[pid] = getLabelIndex(pid, toLabel);
	}

	@Override
	public ArithValue getLocal(int pid, int res) {
		ArithValue val = locals[pid].get(res);
		if (val == null)
			throw new RuntimeException("Local " + res + " not found");

		return val;
	}

	public void setLocal(int pid, int res, ArithValue val) {
		if (!program.getLocals().contains(res))
			throw new RuntimeException("Local " + res + " not found");

		if (Options.LAZY_COPY){
			StateVariables tmp = new StateVariables(locals[pid].size(),false);
			tmp.putAll(locals[pid]);
			locals[pid] = tmp;
		}

		locals[pid].put(res, val);
		StateVariables cached = cachedLocals.get(locals[pid]);
		if (cached == null)
		{
			cachedLocals.put(locals[pid], locals[pid]);
		} else {
			locals[pid] = cached;
		}

	}

	public int getPC(int pid) {
		return pc[pid];
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = super.hashCode();
		//result = prime * result + lastMem;
		result = prime * result + Arrays.hashCode(locals);
		result = prime * result + Arrays.hashCode(pc);

		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (!super.equals(obj))
			return false;

		if (!(obj instanceof SBState))
			return false;
		SBState other = (SBState) obj;

//		if (lastMem != other.lastMem)
//			return false;
		if (!Arrays.equals(locals, other.locals))
			return false;
		if (!Arrays.equals(pc, other.pc))
			return false;

		return true;
	}
	 /**
	  * this >= obj
	  */
	@Override
	public boolean equals_subsumes(Object obj) {
		if (!super.equals(obj))
			return false;

		if (!(obj instanceof SBState))
			return false;
		SBState other = (SBState) obj;

//		if (lastMem != other.lastMem)
//			return false;
		if (!Arrays.equals(pc, other.pc))
			return false;
		if (!myLocalsEqOrSubsumeLocalsOf(other))
			return false;

		return true;
	}
	/**
	 * this <= obj
	 */
	@Override
	public boolean equals_subsumed(Object obj) {
		if (!super.equals(obj))
			return false;

		if (!(obj instanceof SBState))
			return false;
		SBState other = (SBState) obj;

//		if (lastMem != other.lastMem)
//			return false;
		if (!Arrays.equals(pc, other.pc))
			return false;
		if (!myLocalsEqOrSubsumedByLocalsOf(other))
			return false;

		return true;
	}
	/**
	 * this >= other
	 * @param other
	 * @return
	 */
	private boolean myLocalsEqOrSubsumeLocalsOf(SBState other) {
		if(Options.USE_STATE_SUBSUMPTIUON_LEVEL != -1){
			for(int i=0; i< locals.length; ++i){
				if(!locals[i].equals_subsumes(other.locals[i])){
					return false;
				}
			}
			return true;
		}else{
			return Arrays.equals(locals, other.locals);
		}
	}

	/**
	 * @param other
	 * this <= other
	 * @return
	 */
	private boolean myLocalsEqOrSubsumedByLocalsOf(SBState other) {
		if(Options.USE_STATE_SUBSUMPTIUON_LEVEL != -1){
			for(int i=0; i< locals.length; ++i){
				if(!locals[i].equals_subsumed(other.locals[i])){
					return false;
				}
			}
			return true;
		}else{
			return Arrays.equals(locals, other.locals);
		}
	}

	public int allocate(int num) {
//		int start = lastMem;
//		for (; lastMem < start + num; lastMem++) {
//			addShared(getMemResource(lastMem), DetArithValue.getInstance(0));
//		}
//		return start;
		return 0;
	}

	public boolean isInitFinished() {
		// return program.getInitListing().get(initpc).isLast();
		return program.getListing(0).get(pc[0]).isLast();
	}

	static public int getMemResource(ArithValue num) {
		return ((DetArithValue)num).getValue();
	}

	static public int getMemResource(int num) {
		return num;
	}

	public abstract void addShared(int str, ArithValue initval);

	public abstract ArithValue getShared(int res);

	public abstract List<SBState> focus(Assume assume, int pid);

	/**
	 * performing a join of the local variables
	 * if {@link Options#USE_STATE_SUBSUMPTIUON_LEVEL} is true
	 */
	@Override
	public boolean join(State other_s) {
			// TODO Auto-generated method stub
		if(Options.USE_STATE_SUBSUMPTIUON_LEVEL == -1){
			return super.join(other_s);
		}
		if(! (other_s instanceof SBState)){
			throw new RuntimeException("joining an SBState with something that is not an SBState how did that happen?");
		}
		SBState other = (SBState)other_s;

		Boolean ret = false;
		for(int i=0; i<locals.length; ++i){
			StateVariables joined = locals[i].join(other.locals[i]);
			if(joined != null){
				ret = true;
				locals[i] = new StateVariables(joined);
			}

		}

		return ret;
	}
	@Override
	public int hashCode_subs() {
		final int prime = 31;
		int result = super.hashCode_subs();
		//result = prime * result + lastMem;
		result = prime * result + Arrays.hashCode(pc);

		return result;
	}

	@Override
	public String getKeyString(){
		String ret = super.getKeyString();
		for(int i=0; i<locals.length;++i){
			ret += locals[i].getKeyString() + " ";
		}
		return ret;
	}
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('allaccess', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='accountaccess',
            name='created',
            field=models.DateTimeField(auto_now_add=True),
        ),
        migrations.AlterField(
            model_name='accountaccess',
            name='modified',
            field=models.DateTimeField(auto_now=True),
        ),
    ]


text:
/**
 * @param {number} numerator
 * @param {number} denominator
 * @return {string}
 */
var fractionToDecimal = function (numerator, denominator) {
    // zero numerator
    if (numerator == 0) return "0";

    let res = '';
    // determine the sign
    if (numerator < 0 ^ denominator < 0) res += '-';

    // remove sign of operands
    numerator = Math.abs(numerator);
    denominator = Math.abs(denominator);

    // append integral part
    res += Math.floor(numerator / denominator);

    // in case no fractional part
    if (numerator % denominator === 0) return res;

    res += '.';

    const map = new Map();
    // simulate the division process
    for (let r = numerator % denominator; r; r %= denominator) {

        // meet a known remainder
        // so we reach the end of the repeating part
        if (map.has(r)) {
            const pos = map.get(r);
            res = res.substring(0, pos) + '(' + res.substring(pos);
            res += ')';
            break;
        }

        // the remainder is first seen
        // remember the current position for it
        map.set(r, res.length);

        r *= 10;

        // append the quotient digit
        res += Math.floor(r / denominator);
    }

    return res;
};


text:
ptab
=======
[![Build Status](https://travis-ci.org/andybug/ptab.svg?branch=master)](https://travis-ci.org/andybug/ptab) [![Coverage Status](https://img.shields.io/coveralls/andybug/ptab.svg)](https://coveralls.io/r/andybug/ptab?branch=master)

_ptab_ (pretty table) is a tool that allows the easy creation of human-
readable data tables. The row and column data is parsed from stdin
and the beautified table is printed to stdout. The back end work is
handled by _libptab_, a very simple library and API that can be used
in external programs. The API can be viewed at
[include/ptab.h](include/ptab.h).

# Sample
Contents of _sample.csv_:

    School,City,State,Stadium,Size
    Alabama,Tuscaloosa,AL,Bryant Denny,101821
    Arkansas,Fayetteville,AR,Razorback Stadium,72000
    Auburn,Auburn,AL,Jordan Hare,87451
    LSU,Baton Rouge,LA,Tiger Stadium,102321
    Mississippi State,Starkville,MS,Davis Wade,61337
    Ole Miss,Oxford,MS,Vaught-Hemingway,60580
    Texas A&M,College Station,TX,Kyle Field,106511

Command, setting the delimiter to ',' for the CSV file:

    ptab -d ',' < sample.csv

Output:

    +-------------------+-----------------+-------+-------------------+--------+
    | School            | City            | State | Stadium           | Size   |
    +-------------------+-----------------+-------+-------------------+--------+
    | Alabama           | Tuscaloosa      | AL    | Bryant Denny      | 101821 |
    | Arkansas          | Fayetteville    | AR    | Razorback Stadium |  72000 |
    | Auburn            | Auburn          | AL    | Jordan Hare       |  87451 |
    | LSU               | Baton Rouge     | LA    | Tiger Stadium     | 102321 |
    | Mississippi State | Starkville      | MS    | Davis Wade        |  61337 |
    | Ole Miss          | Oxford          | MS    | Vaught-Hemingway  |  60580 |
    | Texas A&M         | College Station | TX    | Kyle Field        | 106511 |
    +-------------------+-----------------+-------+-------------------+--------+

# Building
## Dependencies
_ptab_ requires the following packages be installed for building:
 1. **cmake** - build tool
 2. **check** - unit test framework (optional)
 3. **tclap** - command line processing library (headers only)

## Build
_ptab_ is a typical cmake project:

    mkdir build
    cd build
    cmake ..
    make
    make test

And optionally:

    make install


text:
		<progressbar max="10" class="progress slotStatus" type="{{determineType()}}" value="data.stats.slotFullCount">
			{{data.stats.slotFullCount}} noms left
		</progressbar>

 0">

NomNom !

Feed the beast

<button class="btn btn-lg btn-success" ng-click="feed()"> Feed now </button>

 Oops, nothing left :(

Need a refill

<button class="btn btn-lg btn-default" ng-click="fill()">Refill </button>


text:
require 'zh/version'
require 'open-uri'
require 'yajl/json_gem'

class Zh
  class Error < StandardError; end

  class << self
    RB_LT_25 = Gem::Version.new(RUBY_VERSION) < Gem::Version.new('2.5.0')
    TRADITIONAL_LOCALE = %i[tw hk].freeze
    SIMPLIFIED_LOCALE = %i[cn sg].freeze
    LOCALE = TRADITIONAL_LOCALE + SIMPLIFIED_LOCALE

    # sg, cn are Simplified Chinese, tw, hk are Traditional Chinese
    LOCALE.each do |method|
      define_method "to_#{method}" do |message|
        converter(method, message)
      end
    end

    def converter(method, message)
      default_locale_data = locale_data(method)
      default_locale_data.each_key { |k| message.gsub!(k, default_locale_data[k]) }
      hanx_data = locale_data(TRADITIONAL_LOCALE.include?(method) ? 'hant' : 'hans')
      hanx_data.each_key { |k| message.gsub!(k, hanx_data[k]) }
      message
    end

    def update_data
      %i[cn sg tw hk hans hant].each do |locale|
        data = locale_data(locale)
        url = "https://zh.wikipedia.org/w/index.php?title=MediaWiki:Conversiontable/zh-#{locale}&action=raw&templates=expand"
        table = RB_LT_25 ? open(url).read : URI.open(url).read
        table.lines do |line|
          matches = line.match(%r{^[*"]([^"=]+)"?\s*=>\s*"?([^\s/"]+)\s?.*"?[;,]$})
          data[matches[1].strip] = matches[2].strip if matches
        end
        write_to_json(locale, data)
      end
      true
    end

    private

    def locale_data(locale)
      json = File.new(__dir__ + "/data/zh-#{locale}.json", 'r')
      parser = Yajl::Parser.new
      parser.parse(json)
    end

    def write_to_json(locale, data)
      file = File.open(__dir__ + "/data/zh-#{locale}.json", 'w')
      file.write(data.to_json)
    rescue IOError => e
      puts "An error occurred: #{$ERROR_INFO}"
    ensure
      file&.close
    end
  end
end


text:
<?php

/*
 * This file is part of the Shade project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

namespace ActiveCollab\Shade\Element;

use ActiveCollab\Shade\Ability\DescribableInterface;

class Video extends Element implements DescribableInterface
{
    const GETTING_STARTED = 'getting-started';

    public function getShortName(): string
    {
        return $this->getSlug();
    }

    /**
     * Cached group name value.
     *
     * @var string
     */
    private $group_name = false;

    /**
     * Return name of the group that this video belongs to.
     *
     * @return string
     */
    public function getGroupName()
    {
        if ($this->group_name === false) {
            $this->group_name = $this->getProperty('group');

            if (empty($this->group_name)) {
                $this->group_name = self::GETTING_STARTED;
            }
        }

        return $this->group_name;
    }

    public function getDescription(): string
    {
        return $this->getProperty('description', '');
    }

    /**
     * Return source URL.
     *
     * Only supported modifier at the moment is 2X
     *
     * @param  string $modifier
     * @return string
     */
    public function getSourceUrl($modifier = null)
    {
        if (empty($modifier)) {
            return $this->getProperty('url');
        } else {
            return $this->getProperty('url' . strtolower($modifier));
        }
    }

    /**
     * Cached play time value.
     *
     * @var string
     */
    private $play_time = false;

    /**
     * Return video play time.
     *
     * @return string
     */
    public function getPlayTime()
    {
        if ($this->play_time === false) {
            $this->play_time = $this->getProperty('play_time');

            if (empty($this->play_time)) {
                $this->play_time = '-:--';
            }
        }

        return $this->play_time;
    }
}


text:
package pony.net;

import pony.IEvent;
import pony.IRequest;

public class Request implements IRequest {

	private IEvent message;

	public Request(final IEvent _message){
		this.message = _message;
	}

	@Override
	public IEvent getMessage() {
		return this.message;
	}

}


text:
package app.domain.dtos.lenses;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

import com.google.gson.annotations.Expose;

public class LensJsonDto implements Serializable {

	@Expose
	private Integer focalLength;

	@Expose
	private String make;

	@Expose
	private Double maxAperture;

	@Expose
	private String compatibleWith;

	public LensJsonDto() {
		super();
	}

	public Integer getFocalLength() {
		return focalLength;
	}

	public void setFocalLength(Integer focalLength) {
		this.focalLength = focalLength;
	}

	public Double getMaxAperture() {
		return maxAperture;
	}

	public void setMaxAperture(Double maxAperture) {
		this.maxAperture = maxAperture;
	}

	public String getCompatibleWith() {
		return compatibleWith;
	}

	public void setCompatibleWith(String compatibleWith) {
		this.compatibleWith = compatibleWith;
	}

	public String getMake() {
		return make;
	}

	public void setMake(String make) {
		this.make = make;
	}

}


text:
import {Component} from '@angular/core';
import {LoaderComponent} from "../../shared/loader/loader.component";
import { NDV_DIRECTIVES } from 'angular2-click-to-edit/components';
import {UserService} from "../../servicies/user.service";
import {NotificationsService} from "angular2-notifications/components";
import {AuthService} from "../../servicies/auth.service";
import {WorkplaceService} from "../../servicies/workplace.service";
import {MessagesService} from "../../servicies/message.service";
import {SelectComponent} from "ng2-select/ng2-select";

@Component({
  moduleId: module.id,
  selector: 'profile-cmp',
  templateUrl: 'profile.component.html',
  directives: [LoaderComponent, NDV_DIRECTIVES, SelectComponent]
})

export class ProfileComponent {

  public user={};
  public isLoading = true;
  public workplaces = [];
  public sentMessages = [];
  public inbox = [];
  public pageNumberSent:number = 2;
  private users = ['1','2'];
  public userLogins = [];
  public selectedReceiver;

  constructor(
    private userService: UserService,
    private notificationService: NotificationsService,
    private authService: AuthService,
    private workplaceService: WorkplaceService,
    private messagesService: MessagesService) {
  }

  ngOnInit(){
    let self = this;
    this.userService.getAll().then(function (result) {
      if(result.statusCode == 0){
        self.users = result.data;
        self.userLogins = result.data.map(function (user) {
          return {
            text: user.login,
            id: user._id
          }
        });
      }
    });
    this.userService.getByLogin(this.authService.getCurrentUser()).then(
      result => {
        self.user = result.data;
        self.user.id = result.data._id;
        self.workplaceService.getByUser(self.user.id).then(function (result) {
          if(result.statusCode == 0){
            self.workplaces = result.data;
          }
        });
        self.messagesService.getByAuthor(self.user.id).then(function (result) {
          if(result.statusCode == 0){
            self.sentMessages = result.data;
          }
        });
        self.messagesService.getByReceiver(self.user.id).then(function (result) {
          if(result.statusCode == 0){
            self.inbox = result.data;
            self.toggleLoader();
          }
        });
      }
    );
  }

  saveChanges(){
    let self = this;
    self.toggleLoader();
    this.userService.update(this.user).then(
      function(result){
        if(result.data){
          self.authService.setCurrentUser(result.data);
          self.notificationService.success("Success", "Changes saved");
          self.toggleLoader();
        }
      }
    );
  }

  saveEditable(event){
    if(event['email']){
      this.user.email = event['email'];
    } else {
      this.user.age = event['age']
    }
  }

  addWorkplace(){
    let self = this;
    self.toggleLoader();
    let newWorkplace = {
      company : self.company,
      duration : self.duration,
      userId: self.user.id
    };
    self.workplaceService.add(newWorkplace).then(function (result) {
      if(result.statusCode == 0){
        self.workplaces.push(result.data);
        self.notificationService.success("Success", "Workplace added");
        self.company = "";
        self.duration = "";
        self.toggleLoader();
      }
    }, function (error) {
      console.log(error);
    });
  }

  deleteWorkplace(workplace){
    let self = this;
    self.toggleLoader();
    this.workplaceService.remove(workplace._id).then(function (result) {
      if(result.statusCode == 0){
        self.workplaces.splice(self.workplaces.indexOf(workplace), 1);
        self.notificationService.success("Success", "Workplace deleted");
        self.toggleLoader();
      }
    });
  }

  removeMessage(message):void{
    let self = this;
    self.toggleLoader();
    self.messagesService.remove(message._id).then(function (result) {
      if(result.statusCode == 0){
        let inboxIndex = self.inbox.indexOf(message);
        if(inboxIndex != -1){
          self.inbox.splice(inboxIndex, 1)
        } else{
          self.sentMessages.splice(self.sentMessages.indexOf(message), 1)
        }
        self.notificationService.success("Success", "Message deleted");
        self.toggleLoader();
      }
    });
  }

  selected(event){
    this.selectedReceiver = event;
  }

  sendMessage(){
    let self = this;
    self.toggleLoader();
    if(self.messageText && self.selectedReceiver && self.messageTitle){
      self.messagesService.addMessage({
        title: self.messageTitle,
        text: self.messageText,
        authorId: self.user._id,
        receiverId: self.selectedReceiver.id
      }).then(function (result) {
        if(result.statusCode == 0){
          self.sentMessages.push(result.data);
          self.notificationService.success("Success", "Message sent");
        }
        self.toggleLoader();
      })
    } else{
      self.notificationService.alert("Error","Please, fill in message data");
      self.toggleLoader();
    }
  }

  private toggleLoader(): void{
    let self = this;
    if(!this.isLoading){
      self.isLoading = true;
    } else{
      setTimeout(function () {
        self.isLoading = false;
      }, 500)
    }
  }
}


text:
include common.mk

all:	dirs
	make -f autoconf.mk
	make -f automake.mk
	make -f lha.mk
	make -f pkg-config.mk
	make -f libtool.mk
	make -f libpng.mk
	make -f pngquant.mk
	make -f graphicsmagic.mk
	make -f cmake.mk
	make -f tmx-loader.mk
	make -f sox.mk
	make -f vlink.mk
	make -f vasm.mk
	make -f wget.mk
	make -f gcc-vasm.mk

install: dirs
	make -f autoconf.mk install
	make -f automake.mk install
	make -f lha.mk install
	make -f pkg-config.mk install
	make -f libtool.mk install
	make -f libpng.mk install
	make -f pngquant.mk install
	make -f graphicsmagic.mk install
	make -f cmake.mk install
	make -f tmx-loader.mk install
	#make -f sox.mk install
	make -f vlink.mk install
	make -f vasm.mk install
	make -f wget.mk
	make -f gcc-vasm.mk install

fs-uae: dirs
	make -f sdl.mk
	make -f libffi.mk
	make -f gettext.mk
	make -f pcre.mk
	make -f glib.mk
	make -f glew.mk
	make -f readline.mk
	make -f libmpeg.mk
	make -f fs-uae.mk

fs-uae-install:
	make -f sdl.mk install
	make -f libffi.mk install
	make -f gettext.mk install
	make -f pcre.mk install
	make -f glib.mk install
	make -f glew.mk install
	make -f readline.mk install
	make -f libmpeg.mk install

ndk: dirs
	make -f ndk.mk

dirs:
	@if [ ! -d $(PROJECT_DIR)/downloads ] ; then  mkdir -p $(PROJECT_DIR)/downloads ; fi
	@if [ ! -d $(PROJECT_DIR)/build ] ; then  mkdir -p $(PROJECT_DIR)/build ; fi
	@if [ ! -d $(PROJECT_DIR)/repos ] ; then  mkdir -p $(PROJECT_DIR)/repos ; fi
	@mkdir -p $(INSTALL_DIR)
	@mkdir -p $(INSTALL_DIR)/bin
	@mkdir -p $(INSTALL_DIR)/ndk
	@mkdir -p $(INSTALL_DIR)/ndk/include
	@mkdir -p $(INSTALL_DIR)/ndk/lib


text:
from .base import *

ALLOWED_HOSTS = []


text:
Package.describe({
  summary: 'Sluggable behavior for Meteor\'s Verin Model package'
});

Package.on_use(function (api) {
  api.use([
    'verin-model'
  ], ['client', 'server']);

  api.add_files([
    'lib/urlify.js',
    'lib/sluggable.js'
  ], ['client', 'server']);
});


text:
<?php

namespace Danilo\ProdutoBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table()
 * @ORM\Entity()
 */
class ProdutoDetalhe {

    /**
     * @ORM\Id
     * @ORM\Column(name="id",type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     * @var integer
     */
    private $id;
    /**
     * @ORM\Column(name="peso",type="decimal", precision=10, scale=1)
     */
    private $peso;
    /**
     * @ORM\Column(name="largura",type="decimal", precision=10, scale=1)
     */
    private $largura;
    /**
     * @ORM\Column(name="altura",type="decimal", precision=10, scale=1)
     */
    private $altura;

    public function getId() {
        return $this->id;
    }

    public function getPeso() {
        return $this->peso;
    }

    public function getLargura() {
        return $this->largura;
    }

    public function getAltura() {
        return $this->altura;
    }

    public function setId($id) {
        $this->id = $id;
    }

    public function setPeso($peso) {
        $this->peso = $peso;
    }

    public function setLargura($largura) {
        $this->largura = $largura;
    }

    public function setAltura($altura) {
        $this->altura = $altura;
    }

}


text:
public class Egg {
	public Egg() {
		number = 5;
	}

	public static void main (String [] args) {
		Egg egg = new Egg();
		System.out.println(egg.number);
	}

	private int number = 3;
	{ number = 4; }
}


text:
export * from './lib/core/backend';

export * from './lib/types';

export * from './lib/core/plugin/pluginContext';

export * from './lib/core/shared/sdk/embeddedSdk';

export * from './lib/api/request';

export * from './lib/kerror/errors';

export * from './lib/util/mutex';

export * from './lib/util/inflector';

export { NameGenerator } from './lib/util/name-generator';

export * from 'kuzzle-sdk';

export * from './lib/core/shared/KoncordeWrapper';


text:
var express = require('express')
var db = require('../../models')

module.exports = function() {
  var router = express.Router()

  router.post('/', function(req, res, next) {
    var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    var userAgent = req.headers['user-agent']

    db.Log.create({
      browserInfo: userAgent,
      ip: ip,
      data: req.body.dataId
    }).then(function(result) {
      res.json({message: 'success'})
    }).error(function(err) {
      res.status(500).send(err)
    })
  })

  return router
}


text:
package com.sohu.cache.server.data;

import org.apache.commons.lang.math.NumberUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 网络流量
 */
public class Net implements LineParser{
	public static final String FLAG = "NET,";

	private float nin;
	private float nout;
	private StringBuilder ninDetail = new StringBuilder();
	private StringBuilder noutDetail = new StringBuilder();

	private List<NetworkInterfaceCard> ncList = new ArrayList<NetworkInterfaceCard>();

	/**
	 * line format:
	 * NET,Network I/O bx-50-13,lo-read-KB/s,eth0-read-KB/s,eth1-read-KB/s,eth2-read-KB/s,eth3-read-KB/s,lo-write-KB/s,eth0-write-KB/s,eth1-write-KB/s,eth2-write-KB/s,eth3-write-KB/s,
	 * NET,T0001,190.3,3317.8,0.0,0.0,0.0,190.3,3377.7,0.0,0.0,0.0,
	 */
	public void parse(String line, String timeKey) throws Exception{
		if(line.startsWith(FLAG)) {
			String[] items = line.split(",");
			if(items[1].startsWith("Network")) {
				for(int i = 0; i < items.length; ++i) {
					if(items[i].startsWith("eth")) {
						NetworkInterfaceCard nic = new NetworkInterfaceCard();
						nic.setName(items[i]);
						nic.setIdx(i);
						ncList.add(nic);
					}
				}
			} else {
				for(NetworkInterfaceCard nic : ncList) {
					nic.setValue(NumberUtils.toFloat(items[nic.getIdx()]));
				}
				caculate();
			}
		}
	}

	private void caculate() {
		float totalIn = 0;
		float totalOut = 0;
		for(NetworkInterfaceCard nic : ncList) {
			String[] array = nic.getName().split("-");
			if("read".equals(array[1])) {
				ninDetail.append(array[0]);
				ninDetail.append(",");
				ninDetail.append(nic.getValue());
				ninDetail.append(";");
				totalIn += nic.getValue();
			} else if("write".equals(array[1])) {
				noutDetail.append(array[0]);
				noutDetail.append(",");
				noutDetail.append(nic.getValue());
				noutDetail.append(";");
				totalOut += nic.getValue();
			}
		}
		nin = BigDecimal.valueOf(totalIn).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
		nout = BigDecimal.valueOf(totalOut).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
	}

	public float getNin() {
		return nin;
	}

	public float getNout() {
		return nout;
	}
	public String getNinDetail() {
		return ninDetail.toString();
	}

	public String getNoutDetail() {
		return noutDetail.toString();
	}

	static class NetworkInterfaceCard{
		private String name;
		private float value;
		private int idx;
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public float getValue() {
			return value;
		}
		public void setValue(float value) {
			this.value = value;
		}
		public int getIdx() {
			return idx;
		}
		public void setIdx(int idx) {
			this.idx = idx;
		}
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
RegularExpressionSelectionCriteria (DependencyFinder)
</TITLE>

<META NAME="keywords" CONTENT="com.jeantessier.dependency.RegularExpressionSelectionCriteria class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.jeantessier.dependency

Class RegularExpressionSelectionCriteria

java.lang.Object
  com.jeantessier.dependency.RegularExpressionSelectionCriteria

All Implemented Interfaces:
SelectionCriteria

public class RegularExpressionSelectionCriteria
extends java.lang.Object
implements SelectionCriteria

Constructor Summary

RegularExpressionSelectionCriteria()

RegularExpressionSelectionCriteria(java.lang.String initialGlobalIncludes)

Method Summary

 java.util.List<java.lang.String>
getClassExcludes()

 java.util.List<java.lang.String>
getClassIncludes()

 java.util.List<java.lang.String>
getFeatureExcludes()

 java.util.List<java.lang.String>
getFeatureIncludes()

 java.util.List<java.lang.String>
getGlobalExcludes()

 java.util.List<java.lang.String>
getGlobalIncludes()

 java.util.List<java.lang.String>
getPackageExcludes()

 java.util.List<java.lang.String>
getPackageIncludes()

 boolean
isMatchingClasses()

 boolean
isMatchingFeatures()

 boolean
isMatchingPackages()

 boolean
matches(ClassNode node)

 boolean
matches(FeatureNode node)

 boolean
matches(PackageNode node)

 boolean
matchesClassName(java.lang.String name)

 boolean
matchesFeatureName(java.lang.String name)

 boolean
matchesPackageName(java.lang.String name)

 void
setClassExcludes(java.util.List<java.lang.String> classExcludes)

 void
setClassExcludes(java.lang.String classExcludes)

 void
setClassIncludes(java.util.List<java.lang.String> classIncludes)

 void
setClassIncludes(java.lang.String classIncludes)

 void
setFeatureExcludes(java.util.List<java.lang.String> featureExcludes)

 void
setFeatureExcludes(java.lang.String featureExcludes)

 void
setFeatureIncludes(java.util.List<java.lang.String> featureIncludes)

 void
setFeatureIncludes(java.lang.String featureIncludes)

 void
setGlobalExcludes(java.util.List<java.lang.String> globalExcludes)

 void
setGlobalExcludes(java.lang.String globalExcludes)

 void
setGlobalIncludes(java.util.List<java.lang.String> globalIncludes)

 void
setGlobalIncludes(java.lang.String globalIncludes)

 void
setMatchingClasses(boolean matchingClasses)

 void
setMatchingFeatures(boolean matchingFeatures)

 void
setMatchingPackages(boolean matchingPackages)

 void
setPackageExcludes(java.util.List<java.lang.String> packageExcludes)

 void
setPackageExcludes(java.lang.String packageExcludes)

 void
setPackageIncludes(java.util.List<java.lang.String> packageIncludes)

 void
setPackageIncludes(java.lang.String packageIncludes)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

RegularExpressionSelectionCriteria

public RegularExpressionSelectionCriteria()

RegularExpressionSelectionCriteria

public RegularExpressionSelectionCriteria(java.lang.String initialGlobalIncludes)

Method Detail

getGlobalIncludes

public java.util.List<java.lang.String> getGlobalIncludes()

setGlobalIncludes

public void setGlobalIncludes(java.lang.String globalIncludes)

setGlobalIncludes

public void setGlobalIncludes(java.util.List<java.lang.String> globalIncludes)

getGlobalExcludes

public java.util.List<java.lang.String> getGlobalExcludes()

setGlobalExcludes

public void setGlobalExcludes(java.lang.String globalExcludes)

setGlobalExcludes

public void setGlobalExcludes(java.util.List<java.lang.String> globalExcludes)

isMatchingPackages

public boolean isMatchingPackages()

Specified by:
isMatchingPackages in interface SelectionCriteria

setMatchingPackages

public void setMatchingPackages(boolean matchingPackages)

getPackageIncludes

public java.util.List<java.lang.String> getPackageIncludes()

setPackageIncludes

public void setPackageIncludes(java.lang.String packageIncludes)

setPackageIncludes

public void setPackageIncludes(java.util.List<java.lang.String> packageIncludes)

getPackageExcludes

public java.util.List<java.lang.String> getPackageExcludes()

setPackageExcludes

public void setPackageExcludes(java.lang.String packageExcludes)

setPackageExcludes

public void setPackageExcludes(java.util.List<java.lang.String> packageExcludes)

isMatchingClasses

public boolean isMatchingClasses()

Specified by:
isMatchingClasses in interface SelectionCriteria

setMatchingClasses

public void setMatchingClasses(boolean matchingClasses)

getClassIncludes

public java.util.List<java.lang.String> getClassIncludes()

setClassIncludes

public void setClassIncludes(java.lang.String classIncludes)

setClassIncludes

public void setClassIncludes(java.util.List<java.lang.String> classIncludes)

getClassExcludes

public java.util.List<java.lang.String> getClassExcludes()

setClassExcludes

public void setClassExcludes(java.lang.String classExcludes)

setClassExcludes

public void setClassExcludes(java.util.List<java.lang.String> classExcludes)

isMatchingFeatures

public boolean isMatchingFeatures()

Specified by:
isMatchingFeatures in interface SelectionCriteria

setMatchingFeatures

public void setMatchingFeatures(boolean matchingFeatures)

getFeatureIncludes

public java.util.List<java.lang.String> getFeatureIncludes()

setFeatureIncludes

public void setFeatureIncludes(java.lang.String featureIncludes)

setFeatureIncludes

public void setFeatureIncludes(java.util.List<java.lang.String> featureIncludes)

getFeatureExcludes

public java.util.List<java.lang.String> getFeatureExcludes()

setFeatureExcludes

public void setFeatureExcludes(java.lang.String featureExcludes)

setFeatureExcludes

public void setFeatureExcludes(java.util.List<java.lang.String> featureExcludes)

matches

public boolean matches(PackageNode node)

Specified by:
matches in interface SelectionCriteria

matches

public boolean matches(ClassNode node)

Specified by:
matches in interface SelectionCriteria

matches

public boolean matches(FeatureNode node)

Specified by:
matches in interface SelectionCriteria

matchesPackageName

public boolean matchesPackageName(java.lang.String name)

Specified by:
matchesPackageName in interface SelectionCriteria

matchesClassName

public boolean matchesClassName(java.lang.String name)

Specified by:
matchesClassName in interface SelectionCriteria

matchesFeatureName

public boolean matchesFeatureName(java.lang.String name)

Specified by:
matchesFeatureName in interface SelectionCriteria

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Dependency Finder 1.2.1-beta1 © 2001-2008 Jean Tessier.


text:
<?php

namespace Lunr\Vortex\FCM\Tests;

/**
 * This class contains base tests for the FCMResponse class.
 *
 * @covers Lunr\Vortex\FCM\FCMResponse
 */
class FCMResponseBaseTest extends FCMResponseTest
{

    /**
     * Test statuses is initialized as an empty array.
     */
    public function testStatusesIsInitializedAsEmptyArray()
    {
        $this->assertArrayEmpty($this->get_reflection_property_value('statuses'));
    }

}

?>


text:
package com.ximalaya.sdk4j.model.dto.album;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.ximalaya.sdk4j.http.HttpResponse;
import com.ximalaya.sdk4j.model.XimalayaException;

/**
 * 增量专辑DTO模型
 * @author william
 *
 */
public class IncrementAlbum extends Album {
	private static final long serialVersionUID = -697459276083288173L;

	private boolean isOnline;   // 上线/下线

	public IncrementAlbum() {
	}

	public IncrementAlbum(HttpResponse response) throws XimalayaException {
		super(response);
		init(response.asJSONObject());
	}

	public IncrementAlbum(JSONObject json) throws XimalayaException {
		super(json);
		init(json);
	}

	private void init(JSONObject json) throws XimalayaException{
		if(json != null) {
			isOnline = json.getBoolean("is_online");
		}
	}

	public static IncrementAlbumList constructIncrementAlbumList(HttpResponse response) throws XimalayaException {
		IncrementAlbumList albumList = new IncrementAlbumList();
		JSONObject albumListJsonObject = response.asJSONObject();
 		try {
 			albumList.setTotalPage(albumListJsonObject.getIntValue("total_page"));
 	 		albumList.setTotalCount(albumListJsonObject.getIntValue("total_count"));
 	 		albumList.setCurrentPage(albumListJsonObject.getIntValue("current_page"));
 	 		albumList.setCategoryID(albumListJsonObject.getLong("category_id"));
 	 		albumList.setTagName(albumListJsonObject.getString("tag_name"));

 	 		List<IncrementAlbum> albums = new ArrayList<IncrementAlbum>();
 	 		JSONArray albumsJsonArray = albumListJsonObject.getJSONArray("albums");
 	 		for(int i = 0; i < albumsJsonArray.size(); i++) {
 	 			albums.add(new IncrementAlbum(albumsJsonArray.getJSONObject(i)));
 	 		}
 	 		albumList.setAlbums(albums);
		} catch(JSONException jsone) {
			throw new XimalayaException(jsone.getMessage() + ":" + jsone.toString(), jsone);
		}
		return albumList;
	}

	public boolean isOnline() {
		return isOnline;
	}
	public void setOnline(boolean isOnline) {
		this.isOnline = isOnline;
	}
}


text:
package com.vurtcloud.HadoopClient;

import java.io.IOException;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class MaxTemperature {

	public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
		if(args.length != 2){
			System.err.println("Uses: MaxTemerature <input Path> <output Path>");
			System.exit(-1);
		}
		Job job = new Job();
		job.setJarByClass(MaxTemperature.class);
		job.setJobName("Max Temerature");

		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, new Path(args[1]));

		job.setMapperClass(MaxTemperatureMapper.class);
		job.setReducerClass(MaxTemperatureReducer.class);

		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);

		System.exit(job.waitForCompletion(true) ? 0 : 1);

	}

}


text:
/*************************
 Authentication Module
 **************************/
(function () {
    'use strict';

    angular
        .module('JetThunder2.authentication')
        /*************************
         Authentication Controller
         **************************/
        .controller('AuthCtrl', AuthCtrl);

    /*************************
     Controller Function
     **************************/
    AuthCtrl.$inject = ['$mdDialog', 'authFactory'];
    function AuthCtrl($mdDialog, authFactory) {
        var vm = this;

        /** View Bindings */
        vm.displayImage = '';
        vm.email = '';
        vm.firstName = '';
        vm.lastName = '';
        vm.password = '';
        vm.uid = '';

        /** Bindings */
        vm.closeAuthDialog = closeAuthDialog;
        vm.createUser = createUser;
        vm.getUser = getUser;
        vm.signIn = signIn;
        vm.signOut = signOut;

        function closeAuthDialog() {
            $mdDialog.cancel();
        }

        /**
         * Creates a new user through Firebase
         * @param {string} email - The users emails
         * @param {string} password - The users password
         */
        function createUser(email, password) {
            authFactory.createUser(email, password);
        }

        /** Gets the current user details */
        function getUser() {
            authFactory.getUser();
        }

        /**
         * Signs in the user through Firebase
         * @param {string} email - The users emails
         * @param {string} password - The users password
         */
        function signIn(email, password) {
            authFactory.signIn(email, password);
        }

        /** Signs out the current user */
        function signOut() {
            authFactory.signOut();
        }
    }
})();