text:
.class public Lcom/android/internal/app/RestrictionsPinActivity;
.super Lcom/android/internal/app/AlertActivity;
.source "RestrictionsPinActivity.java"

# interfaces
.implements Landroid/text/TextWatcher;
.implements Landroid/view/View$OnClickListener;
.implements Landroid/widget/TextView$OnEditorActionListener;

# instance fields
.field private mCancelButton:Landroid/widget/Button;

.field private mCountdownRunnable:Ljava/lang/Runnable;

.field protected mHasRestrictionsPin:Z

.field private mOkButton:Landroid/widget/Button;

.field protected mPinErrorMessage:Landroid/widget/TextView;

.field protected mPinText:Landroid/widget/EditText;

.field protected mUserManager:Landroid/os/UserManager;

# direct methods
.method public constructor <init>()V
    .locals 1

    .prologue
    .line 39
    invoke-direct {p0}, Lcom/android/internal/app/AlertActivity;-><init>()V

    .line 163
    new-instance v0, Lcom/android/internal/app/RestrictionsPinActivity$1;

    invoke-direct {v0, p0}, Lcom/android/internal/app/RestrictionsPinActivity$1;-><init>(Lcom/android/internal/app/RestrictionsPinActivity;)V

    iput-object v0, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mCountdownRunnable:Ljava/lang/Runnable;

    return-void
.end method

.method static synthetic access$000(Lcom/android/internal/app/RestrictionsPinActivity;I)Z
    .locals 1
    .param p0, "x0"    # Lcom/android/internal/app/RestrictionsPinActivity;
    .param p1, "x1"    # I

    .prologue
    .line 39
    invoke-direct {p0, p1}, Lcom/android/internal/app/RestrictionsPinActivity;->updatePinTimer(I)Z

    move-result v0

    return v0
.end method

.method private updatePinTimer(I)Z
    .locals 8
    .param p1, "pinTimerMs"    # I

    .prologue
    const/4 v6, 0x0

    .line 102
    if-gez p1, :cond_0

    .line 103
    iget-object v3, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mUserManager:Landroid/os/UserManager;

    const/4 v4, 0x0

    invoke-virtual {v3, v4}, Landroid/os/UserManager;->checkRestrictionsChallenge(Ljava/lang/String;)I

    move-result p1

    .line 106
    :cond_0
    const/16 v3, 0xc8

    if-lt p1, v3, :cond_2

    .line 108
    const v3, 0xea60

    if-gt p1, v3, :cond_1

    .line 109
    add-int/lit16 v3, p1, 0xc8

    div-int/lit16 v2, v3, 0x3e8

    .line 110
    .local v2, "seconds":I
    invoke-virtual {p0}, Lcom/android/internal/app/RestrictionsPinActivity;->getResources()Landroid/content/res/Resources;

    move-result-object v3

    const v4, 0x1140018

    invoke-virtual {v3, v4, v2}, Landroid/content/res/Resources;->getQuantityString(II)Ljava/lang/String;

    move-result-object v1

    .line 113
    .local v1, "formatString":Ljava/lang/String;
    iget-object v3, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mPinErrorMessage:Landroid/widget/TextView;

    const/4 v4, 0x1

    new-array v4, v4, [Ljava/lang/Object;

    invoke-static {v2}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v5

    aput-object v5, v4, v6

    invoke-static {v1, v4}, Ljava/lang/String;->format(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;

    move-result-object v4

    invoke-virtual {v3, v4}, Landroid/widget/TextView;->setText(Ljava/lang/CharSequence;)V

    .line 117
    .end local v1    # "formatString":Ljava/lang/String;
    .end local v2    # "seconds":I
    :goto_0
    const/4 v0, 0x0

    .line 118
    .local v0, "enableInput":Z
    iget-object v3, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mPinErrorMessage:Landroid/widget/TextView;

    invoke-virtual {v3, v6}, Landroid/widget/TextView;->setVisibility(I)V

    .line 119
    iget-object v3, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mPinText:Landroid/widget/EditText;

    const-string v4, ""

    invoke-virtual {v3, v4}, Landroid/widget/EditText;->setText(Ljava/lang/CharSequence;)V

    .line 120
    iget-object v3, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mPinText:Landroid/widget/EditText;

    iget-object v4, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mCountdownRunnable:Ljava/lang/Runnable;

    const/16 v5, 0x3e8

    invoke-static {v5, p1}, Ljava/lang/Math;->min(II)I

    move-result v5

    int-to-long v6, v5

    invoke-virtual {v3, v4, v6, v7}, Landroid/widget/EditText;->postDelayed(Ljava/lang/Runnable;J)Z

    .line 125
    :goto_1
    iget-object v3, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mPinText:Landroid/widget/EditText;

    invoke-virtual {v3, v0}, Landroid/widget/EditText;->setEnabled(Z)V

    .line 126
    invoke-virtual {p0, v0}, Lcom/android/internal/app/RestrictionsPinActivity;->setPositiveButtonState(Z)V

    .line 127
    return v0

    .line 115
    .end local v0    # "enableInput":Z
    :cond_1
    iget-object v3, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mPinErrorMessage:Landroid/widget/TextView;

    const v4, 0x1040660

    invoke-virtual {v3, v4}, Landroid/widget/TextView;->setText(I)V

    goto :goto_0

    .line 122
    :cond_2
    const/4 v0, 0x1

    .line 123
    .restart local v0    # "enableInput":Z
    iget-object v3, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mPinErrorMessage:Landroid/widget/TextView;

    const v4, 0x1040659

    invoke-virtual {v3, v4}, Landroid/widget/TextView;->setText(I)V

    goto :goto_1
.end method

# virtual methods
.method public afterTextChanged(Landroid/text/Editable;)V
    .locals 0
    .param p1, "s"    # Landroid/text/Editable;

    .prologue
    .line 155
    return-void
.end method

.method public beforeTextChanged(Ljava/lang/CharSequence;III)V
    .locals 0
    .param p1, "s"    # Ljava/lang/CharSequence;
    .param p2, "start"    # I
    .param p3, "count"    # I
    .param p4, "after"    # I

    .prologue
    .line 145
    return-void
.end method

.method protected initUi()V
    .locals 4

    .prologue
    .line 61
    iget-object v0, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mAlertParams:Lcom/android/internal/app/AlertController$AlertParams;

    .line 62
    .local v0, "ap":Lcom/android/internal/app/AlertController$AlertParams;
    const v2, 0x1040657

    invoke-virtual {p0, v2}, Lcom/android/internal/app/RestrictionsPinActivity;->getString(I)Ljava/lang/String;

    move-result-object v2

    iput-object v2, v0, Lcom/android/internal/app/AlertController$AlertParams;->mTitle:Ljava/lang/CharSequence;

    .line 63
    const-string/jumbo v2, "layout_inflater"

    invoke-virtual {p0, v2}, Lcom/android/internal/app/RestrictionsPinActivity;->getSystemService(Ljava/lang/String;)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Landroid/view/LayoutInflater;

    .line 65
    .local v1, "inflater":Landroid/view/LayoutInflater;
    const v2, 0x10900b0

    const/4 v3, 0x0

    invoke-virtual {v1, v2, v3}, Landroid/view/LayoutInflater;->inflate(ILandroid/view/ViewGroup;)Landroid/view/View;

    move-result-object v2

    iput-object v2, v0, Lcom/android/internal/app/AlertController$AlertParams;->mView:Landroid/view/View;

    .line 67
    iget-object v2, v0, Lcom/android/internal/app/AlertController$AlertParams;->mView:Landroid/view/View;

    const v3, 0x1020368

    invoke-virtual {v2, v3}, Landroid/view/View;->findViewById(I)Landroid/view/View;

    move-result-object v2

    check-cast v2, Landroid/widget/TextView;

    iput-object v2, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mPinErrorMessage:Landroid/widget/TextView;

    .line 68
    iget-object v2, v0, Lcom/android/internal/app/AlertController$AlertParams;->mView:Landroid/view/View;

    const v3, 0x1020367

    invoke-virtual {v2, v3}, Landroid/view/View;->findViewById(I)Landroid/view/View;

    move-result-object v2

    check-cast v2, Landroid/widget/EditText;

    iput-object v2, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mPinText:Landroid/widget/EditText;

    .line 69
    iget-object v2, v0, Lcom/android/internal/app/AlertController$AlertParams;->mView:Landroid/view/View;

    const v3, 0x102036a

    invoke-virtual {v2, v3}, Landroid/view/View;->findViewById(I)Landroid/view/View;

    move-result-object v2

    check-cast v2, Landroid/widget/Button;

    iput-object v2, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mOkButton:Landroid/widget/Button;

    .line 70
    iget-object v2, v0, Lcom/android/internal/app/AlertController$AlertParams;->mView:Landroid/view/View;

    const v3, 0x1020369

    invoke-virtual {v2, v3}, Landroid/view/View;->findViewById(I)Landroid/view/View;

    move-result-object v2

    check-cast v2, Landroid/widget/Button;

    iput-object v2, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mCancelButton:Landroid/widget/Button;

    .line 72
    iget-object v2, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mPinText:Landroid/widget/EditText;

    invoke-virtual {v2, p0}, Landroid/widget/EditText;->addTextChangedListener(Landroid/text/TextWatcher;)V

    .line 74
    iget-object v2, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mOkButton:Landroid/widget/Button;

    invoke-virtual {v2, p0}, Landroid/widget/Button;->setOnClickListener(Landroid/view/View$OnClickListener;)V

    .line 75
    iget-object v2, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mCancelButton:Landroid/widget/Button;

    invoke-virtual {v2, p0}, Landroid/widget/Button;->setOnClickListener(Landroid/view/View$OnClickListener;)V

    .line 76
    return-void
.end method

.method public onClick(Landroid/view/View;)V
    .locals 1
    .param p1, "v"    # Landroid/view/View;

    .prologue
    .line 174
    iget-object v0, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mOkButton:Landroid/widget/Button;

    if-ne p1, v0, :cond_1

    .line 175
    invoke-virtual {p0}, Lcom/android/internal/app/RestrictionsPinActivity;->performPositiveButtonAction()V

    .line 180
    :cond_0
    :goto_0
    return-void

    .line 176
    :cond_1
    iget-object v0, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mCancelButton:Landroid/widget/Button;

    if-ne p1, v0, :cond_0

    .line 177
    const/4 v0, 0x0

    invoke-virtual {p0, v0}, Lcom/android/internal/app/RestrictionsPinActivity;->setResult(I)V

    .line 178
    invoke-virtual {p0}, Lcom/android/internal/app/RestrictionsPinActivity;->finish()V

    goto :goto_0
.end method

.method public onCreate(Landroid/os/Bundle;)V
    .locals 1
    .param p1, "icicle"    # Landroid/os/Bundle;

    .prologue
    .line 52
    invoke-super {p0, p1}, Lcom/android/internal/app/AlertActivity;->onCreate(Landroid/os/Bundle;)V

    .line 54
    const-string/jumbo v0, "user"

    invoke-virtual {p0, v0}, Lcom/android/internal/app/RestrictionsPinActivity;->getSystemService(Ljava/lang/String;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/os/UserManager;

    iput-object v0, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mUserManager:Landroid/os/UserManager;

    .line 55
    iget-object v0, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mUserManager:Landroid/os/UserManager;

    invoke-virtual {v0}, Landroid/os/UserManager;->hasRestrictionsChallenge()Z

    move-result v0

    iput-boolean v0, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mHasRestrictionsPin:Z

    .line 56
    invoke-virtual {p0}, Lcom/android/internal/app/RestrictionsPinActivity;->initUi()V

    .line 57
    invoke-virtual {p0}, Lcom/android/internal/app/RestrictionsPinActivity;->setupAlert()V

    .line 58
    return-void
.end method

.method public onEditorAction(Landroid/widget/TextView;ILandroid/view/KeyEvent;)Z
    .locals 1
    .param p1, "v"    # Landroid/widget/TextView;
    .param p2, "actionId"    # I
    .param p3, "event"    # Landroid/view/KeyEvent;

    .prologue
    .line 159
    invoke-virtual {p0}, Lcom/android/internal/app/RestrictionsPinActivity;->performPositiveButtonAction()V

    .line 160
    const/4 v0, 0x1

    return v0
.end method

.method public onResume()V
    .locals 4

    .prologue
    const/4 v3, -0x1

    .line 83
    invoke-super {p0}, Lcom/android/internal/app/AlertActivity;->onResume()V

    .line 85
    const/4 v1, 0x0

    invoke-virtual {p0, v1}, Lcom/android/internal/app/RestrictionsPinActivity;->setPositiveButtonState(Z)V

    .line 86
    iget-object v1, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mUserManager:Landroid/os/UserManager;

    invoke-virtual {v1}, Landroid/os/UserManager;->hasRestrictionsChallenge()Z

    move-result v0

    .line 87
    .local v0, "hasPin":Z
    if-eqz v0, :cond_1

    .line 88
    iget-object v1, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mPinErrorMessage:Landroid/widget/TextView;

    const/4 v2, 0x4

    invoke-virtual {v1, v2}, Landroid/widget/TextView;->setVisibility(I)V

    .line 89
    iget-object v1, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mPinText:Landroid/widget/EditText;

    invoke-virtual {v1, p0}, Landroid/widget/EditText;->setOnEditorActionListener(Landroid/widget/TextView$OnEditorActionListener;)V

    .line 90
    invoke-direct {p0, v3}, Lcom/android/internal/app/RestrictionsPinActivity;->updatePinTimer(I)Z

    .line 95
    :cond_0
    :goto_0
    return-void

    .line 91
    :cond_1
    invoke-virtual {p0}, Lcom/android/internal/app/RestrictionsPinActivity;->verifyingPin()Z

    move-result v1

    if-eqz v1, :cond_0

    .line 92
    invoke-virtual {p0, v3}, Lcom/android/internal/app/RestrictionsPinActivity;->setResult(I)V

    .line 93
    invoke-virtual {p0}, Lcom/android/internal/app/RestrictionsPinActivity;->finish()V

    goto :goto_0
.end method

.method public onTextChanged(Ljava/lang/CharSequence;III)V
    .locals 3
    .param p1, "s"    # Ljava/lang/CharSequence;
    .param p2, "start"    # I
    .param p3, "before"    # I
    .param p4, "count"    # I

    .prologue
    .line 149
    iget-object v1, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mPinText:Landroid/widget/EditText;

    invoke-virtual {v1}, Landroid/widget/EditText;->getText()Landroid/text/Editable;

    move-result-object v0

    .line 150
    .local v0, "pin":Ljava/lang/CharSequence;
    if-eqz v0, :cond_0

    invoke-interface {v0}, Ljava/lang/CharSequence;->length()I

    move-result v1

    const/4 v2, 0x4

    if-lt v1, v2, :cond_0

    const/4 v1, 0x1

    :goto_0
    invoke-virtual {p0, v1}, Lcom/android/internal/app/RestrictionsPinActivity;->setPositiveButtonState(Z)V

    .line 151
    return-void

    .line 150
    :cond_0
    const/4 v1, 0x0

    goto :goto_0
.end method

.method protected performPositiveButtonAction()V
    .locals 4

    .prologue
    const/4 v3, -0x1

    .line 131
    iget-object v1, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mUserManager:Landroid/os/UserManager;

    iget-object v2, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mPinText:Landroid/widget/EditText;

    invoke-virtual {v2}, Landroid/widget/EditText;->getText()Landroid/text/Editable;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/Object;->toString()Ljava/lang/String;

    move-result-object v2

    invoke-virtual {v1, v2}, Landroid/os/UserManager;->checkRestrictionsChallenge(Ljava/lang/String;)I

    move-result v0

    .line 132
    .local v0, "result":I
    if-ne v0, v3, :cond_1

    .line 133
    invoke-virtual {p0, v3}, Lcom/android/internal/app/RestrictionsPinActivity;->setResult(I)V

    .line 134
    invoke-virtual {p0}, Lcom/android/internal/app/RestrictionsPinActivity;->finish()V

    .line 141
    :cond_0
    :goto_0
    return-void

    .line 135
    :cond_1
    if-ltz v0, :cond_0

    .line 136
    iget-object v1, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mPinErrorMessage:Landroid/widget/TextView;

    const v2, 0x1040659

    invoke-virtual {v1, v2}, Landroid/widget/TextView;->setText(I)V

    .line 137
    iget-object v1, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mPinErrorMessage:Landroid/widget/TextView;

    const/4 v2, 0x0

    invoke-virtual {v1, v2}, Landroid/widget/TextView;->setVisibility(I)V

    .line 138
    invoke-direct {p0, v0}, Lcom/android/internal/app/RestrictionsPinActivity;->updatePinTimer(I)Z

    .line 139
    iget-object v1, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mPinText:Landroid/widget/EditText;

    const-string v2, ""

    invoke-virtual {v1, v2}, Landroid/widget/EditText;->setText(Ljava/lang/CharSequence;)V

    goto :goto_0
.end method

.method protected setPositiveButtonState(Z)V
    .locals 1
    .param p1, "enabled"    # Z

    .prologue
    .line 98
    iget-object v0, p0, Lcom/android/internal/app/RestrictionsPinActivity;->mOkButton:Landroid/widget/Button;

    invoke-virtual {v0, p1}, Landroid/widget/Button;->setEnabled(Z)V

    .line 99
    return-void
.end method

.method protected verifyingPin()Z
    .locals 1

    .prologue
    .line 79
    const/4 v0, 0x1

    return v0
.end method


text:
package v1alpha1

import (
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
)

// GroupName is the group name use in this package
const GroupName = "storage.k8s.io"

// SchemeGroupVersion is group version used to register these objects
var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1alpha1"}

// Resource takes an unqualified resource and returns a Group qualified GroupResource
func Resource(resource string) schema.GroupResource {
	return SchemeGroupVersion.WithResource(resource).GroupResource()
}

var (
	SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes)
	AddToScheme   = SchemeBuilder.AddToScheme
)

// Adds the list of known types to the given scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
	scheme.AddKnownTypes(SchemeGroupVersion,
		&VolumeAttachment{},
		&VolumeAttachmentList{},
		&CSIStorageCapacity{},
		&CSIStorageCapacityList{},
	)

	metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
	return nil
}

redpajama_set_name: RedPajamaGithub


text:
<?PHP
//  typically this is a staticly include into index.php
//  used to populate 'signup' portion of home page

namespace MyTake;

function mail_activation($a) {
	//  CITATION: http://php.net/manual/en/function.mail.php
	global $actv_url;

	$to  = $a['email'];
	$subject = 'mytake - account activation';

	// message
	$message = "

<title>mytake - account activation</title>

mytake - account activation

Activation code

".$a['act_code']."

[ click ] to activate your account.

";
	// To send HTML mail, the Content-type header must be set
	$headers  = 'MIME-Version: 1.0' . "\r\n";
	$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
	// Additional headers
	//  $headers .= 'From: No Reply <noreply@holistik.org>' . "\r\n";
	//  $headers .= 'Reply-To: No Reply <noreply@mytake.zaptech.com>' . "\r\n";
	$headers .= 'Reply-To: No Reply <mytake@zaptech.com>' . "\r\n";
	mail($to, $subject, $message, $headers);
}


text:
var path = require("path");

exports.meta = function (req, res){
    var id = req.params.id, username;
    if (!id) {
        res.send(500, { error: 'something blew up. param id is required!' });
    }

    req.app.get('model')('template').find({"_id": id}, function (err, docs) {
        if (err || !docs) {
            res.send(500, { error: 'something blew up' });
        } else {
            res.render('manage/metaedit',
                {
                    "template": docs[0]
                }
            );
        }
    })
}

exports.createform = function (req, res){
    req.app.get('model')('templateMeta').find({}, function (err, docs) {
        if (err) {
            res.send(500, { error: 'something blew up' });
        } else {
            res.render('manage/create',
                {
                    "groups" : docs
                }
            );
        }
    })
}

exports.create = function (req, res){
    var username;
    if(req.session !== undefined && req.session.user !== undefined) {
        username = req.session.user;
    } else {
        username = "public";
    }
    var template = {
        "creator": username,
        "name": req.body.name,
        "simple_url": escape(req.body.simple_url),
        "group": req.body.group,
        "subgroup": req.body.subgroup,
        "ie": req.body.ie,
        "type": req.body.pageType || "html",
        "utime": Date.now(),
        "ctime": Date.now(),
        "description": req.body.description,
        "available": (req.body.available && req.body.available === "on") ? "true" : "false"
    }
    if (req.body.authors && typeof req.body.authors === "string") {
        template.authors = req.body.authors.split(",");
    }
    // logger.debug(template);
    req.app.get('model')('template').create(template, function (err, doc) {
        if (err) {
            res.send(500, { error: 'something blew up' });
        } else {
            res.redirect("/manage/" + req.body.group + "/" + req.body.subgroup);
        }
    });
}

exports.metaedit = function (req, res){
    var id = req.params.id, username;
    if (!id) {
        res.send(500, { error: 'something blew up' });
    }
    if(req.session !== undefined && req.session.user !== undefined) {
        username = req.session.user;
    } else {
        username = "public";
    }
    var templateModel = req.app.get('model')('template');
    templateModel.find({"_id": id},function (err, docs) {
        if (err || !docs) {
            res.send(500, { error: 'something blew up' });
        } else {
            // check auth
            var authors = docs[0].authors;
            authors.push(docs[0].creator);
            req.body.group = docs[0].group;
            req.body.subgroup = docs[0].subgroup;

            if (authors.indexOf(username) === -1 && admin.indexOf(username) === -1) {
                res.send(404, { error: 'you have no auth to do this! please contact ' + authors.join(",") + admin.join(",") });
            } else {
                var update = {
                    "name": req.body.name,
                    "type": req.body.pageType || "html",
                    "simple_url": escape(req.body.simple_url),
                    "description": req.body.description,
                    "ie": req.body.ie,
                    "available": (req.body.available && req.body.available === "on") ? "true" : "false"
                };
                if (req.body.authors && typeof req.body.authors === "string") {
                    updata_authors = req.body.authors.split(",");
                    update.authors = updata_authors;
                }
                update.utime = Date.now();
                // console.log(id, update);
                templateModel.findByIdAndUpdate(id, update, function(err){
                    if(err) {
                        res.send(500, { error: 'something blew up' });
                    } else {
                        res.redirect("/manage/" + req.body.group + "/" + req.body.subgroup);
                    }
                });
            }
        }
    })
}

exports.remove = function (req, res){
    var id = req.params.id || req.query.id, username;
    if (!id) {
        res.send(500, { error: 'something blew up' });
        return null;
    }
    if(req.session !== undefined && req.session.user !== undefined) {
        username = req.session.user;
    } else {
        username = "public";
    }
    var templateModel = req.app.get('model')('template');
    templateModel.find({"_id": id},function (err, docs) {
        if (err || !docs) {
            res.send(500, { error: 'something blew up' });
        } else {
            // check auth
            var authors = docs[0].authors;
            authors.push(docs[0].creator);
            if (authors.indexOf(username) === -1 && admin.indexOf(username) === -1) {
                res.send({"code": 1, "msg": "
You have no auth to do this
"});
            } else {
                templateModel.findByIdAndRemove(id, function(err){
                    if(err) {
                        res.send(500, { error: 'something blew up' });
                    } else {
                        res.send({"code": 0, "msg": "
Success
"});
                    }
                });
            }
        }
    })
}

// templates manage
exports.manage = function (req, res){
    var username, group = req.params.group
        subgroup = req.params.subgroup;

    if(req.session !== undefined && req.session.user !== undefined) {
        username = req.session.user;
    } else {
        username = "public";
    }

    req.app.get('model')('templateMeta').find({}, function (err, docs) {
        if (err) {
            res.send(500, { error: 'something blew up' });
        } else {
            // console.log(docs);
            res.render('manage',
                {
                    "title": 'Harvest.io',
                    "user": username,
                    "group": group,
                    "subgroup": subgroup,
                    "groups" : docs
                }
            );
        }

    })
}

exports.manageAjax = function (req, res){
    var group = req.params.group
        subgroup = req.params.subgroup;

    req.app.get('model')('template').find({"group": group, "subgroup": subgroup},function (err, docs) {
        if (err) {
            res.send(500, { error: 'something blew up' });
        } else {
            // console.log(docs);
            res.render('manage/templates',
                {
                    "templates": docs
                }
            );
        }
    })
}

exports.apiTemplates = function (req, res){
    var selector = {};
    req.query.group ? selector.group = req.query.group : null;
    req.query.subgroup ? selector.subgroup = req.query.subgroup : null;

    req.app.get('model')('template').find(selector, {"code": false}, function (err, docs) {
        if (err) {
            res.send(500, { error: 'something blew up' });
        } else {
            // logger.info(docs);
            res.send(docs);
        }
    })
}


text:
'use strict';

const $ = require('gulp-load-plugins')();
const gulp = require('gulp');
const uglify = require('gulp-uglify');
const combine = require('stream-combiner2').obj;
const extend = require('extend');
const pathJoin = require('../path.join.js');
const ignoreFiles = require("../ignore-files");

module.exports = function(options) {

    options = extend(true, {
        sourcemaps: false,
        minification: true,
        dest: "",
        coffeeOptions: {
            bare: true
        },
        changed: true,
        rigger: false
    }, options);

    return function() {
        const coffeeFilter = $.filter('**/*.coffee', {restore: true});

        var stream = combine(
            gulp.src(options.src),

            "ignoreFiles" in options ? ignoreFiles.stream(options.ignoreFiles) : combine(),

            $.if(options.changed, $.changed('base_dest' in options ? pathJoin(options.base_dest, options.dest) : options.dest, {extension: '.js'})),

            $.if(options.sourcemaps, $.sourcemaps.init()),

            $.if(options.rigger, $.rigger()),

            coffeeFilter, $.coffee(options.coffeeOptions), coffeeFilter.restore,

            $.if(options.minification, $.uglify()),

            $.if(options.sourcemaps, $.sourcemaps.write('.'))
        ).on('error', $.notify.onError());

        stream.pipe(gulp.dest('base_dest' in options ? pathJoin(options.base_dest, options.dest) : options.dest))
            .on('error', $.notify.onError())
            .pipe("writeJsStream" in options ? options.writeJsStream() : combine())
            .on('error', $.notify.onError());

        return stream;
    };

};


text:
{% extends "library/base.html" %}
{% load i18n %}

{% block title %}{% trans "Albums" %}{% endblock title %}

{% block content %}

{% trans "Albums" %}

  {% regroup alpha_list by initial as thelist %}

  {% for initial in thelist %}

{{ initial.grouper }}

    {% for item in initial.list %}

{{ item.instance }}

    {% endfor %}

  {% endfor %}
{% endblock content %}


text:
module KitchenInspector
  module Inspector
    module Models
      # The class that contains information about a cookbook on Repository Manager
      class RepoCookbook
        include Comparable

        # The ID of the cookbook on Repository Manager
        attr_reader :id

        # The name of the cookbook
        attr_reader :name

        # Path to metadata.rb
        attr_accessor :metadata_path

        def initialize(id, name, metadata_path)
          @id = id
          @name = name
          @metadata_path = metadata_path
        end

        def ==(anOther)
          name == anOther.name && metadata_path == anOther.metadata_path
        end
      end
    end
  end
end


text:
`defprotocol` and `defimpl` macros inspired by [Elixir](http://elixir-lang.org/getting-started/protocols.html).
Under the hood this uses modules and abstract methods to make sure classes claiming to adhere to a certain protocol
actually implement it fully.

## Installation

Add this to your application's `shard.yml`:

```yaml
dependencies:
  protocols:
    github: citizen428/protocols
```

## Usage

```crystal
require "protocols"
```

### Definining protocols

`defprotocol` is used for defining new protocols (which will be created as toplevel modules).

```crystal
defprotocol Greetable do
  def greet
    "Hello from #{name}"
  end

  abstract def name
end
```

The above form allows us to specify both concrete and abstract methods for the protocol. There is
also a shortcut for protocols which only contain abstract methods:

```crystal
defprotocol Greetable, :greet, :name
```

### Implementing protocols

Given the following `Blank` protocol

```crystal
# Returns true if if data is considered blank/empty
defprotocol Blank, :blank?
```

we can define define an implementation inside a class or struct body:

```crystal
class Array
  defimpl Blank do
    def blank?
      true
    end
  end
end

nil.blank? #=> true
```

`defimpl` will `include` the protocol module, define a nested module called `"#{protocol_name}Implementation"`
and include this module too. While this may seem complicated, it makes it possible to `derive` implementations
from other classes.

### Deriving protocols

To avoid code duplication, it's possible to `derive` protocol implementations from other classes/structs:

```crystal
struct Tuple
  derive Blank, from: Array
end

Tuple.new.blank? #=> true
```

## Todo

* [ ] Write specs

## Contributing

1. Fork it ( https://github.com/citizen428/protocols/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request

## Contributors

- [citizen428](https://github.com/citizen428) Michael Kohl - creator, maintainer


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest
    package="setting.example.com.peference_setting"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name="setting.example.com.peference_setting.MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity
            android:name="setting.example.com.peference_setting.Preferences"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Holo.Light.Dialog.NoActionBar">
        </activity>
        <activity
            android:name="setting.example.com.peference_setting.Preferences2"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Holo.Light.Dialog.NoActionBar">
        </activity>
        <activity
            android:name="setting.example.com.peference_setting.Preferences3"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Holo.Light.Dialog.NoActionBar">
        </activity>
        <activity
            android:name=".Preferences4"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Holo.Light.Dialog.NoActionBar">
        </activity>

        <activity
            android:name="setting.example.com.peference_setting.TabBar"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Holo.Light.Dialog.NoActionBar">
        </activity>

        <activity
            android:name="setting.example.com.peference_setting.Tab1"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Holo.Light.Dialog.NoActionBar">
        </activity>

        <activity
            android:name="setting.example.com.peference_setting.Tab2"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Holo.Light.Dialog.NoActionBar">
        </activity>

        <!--<activity android:name=".Tab1"  -->
        <!--</activity>-->
        <!--<activity android:name=".Tab2"  </activity>-->
    </application>

</manifest>


text:
<?php
/**
 * Functions run on activation / deactivation.
 *
 * @package Top_Ten
 */

/**
 * Fired when the plugin is Network Activated.
 *
 * @since 1.9.10.1
 *
 * @param    boolean $network_wide    True if WPMU superadmin uses
 *                                    "Network Activate" action, false if
 *                                    WPMU is disabled or plugin is
 *                                    activated on an individual blog.
 */
function tptn_activation_hook( $network_wide ) {
	global $wpdb;

	if ( is_multisite() && $network_wide ) {

		// Get all blogs in the network and activate plugin on each one.
		$blog_ids = $wpdb->get_col( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery
			"
        	SELECT blog_id FROM $wpdb->blogs
			WHERE archived = '0' AND spam = '0' AND deleted = '0'
		"
		);
		foreach ( $blog_ids as $blog_id ) {
			switch_to_blog( $blog_id );
			tptn_single_activate();
		}

		// Switch back to the current blog.
		restore_current_blog();

	} else {
		tptn_single_activate();
	}
}
register_activation_hook( TOP_TEN_PLUGIN_FILE, 'tptn_activation_hook' );

/**
 * Fired for each blog when the plugin is activated.
 *
 * @since 2.0.0
 */
function tptn_single_activate() {
	global $wpdb, $tptn_db_version;

	$tptn_settings   = tptn_get_settings();
	$charset_collate = $wpdb->get_charset_collate();
	require_once ABSPATH . 'wp-admin/includes/upgrade.php';

	$table_name       = $wpdb->base_prefix . 'top_ten';
	$table_name_daily = $wpdb->base_prefix . 'top_ten_daily';

	if ( $wpdb->get_var( "show tables like '$table_name'" ) != $table_name ) { // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery

		$sql = 'CREATE TABLE ' . $table_name . // phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange
			" (
			postnumber bigint(20) NOT NULL,
			cntaccess bigint(20) NOT NULL,
			blog_id bigint(20) NOT NULL DEFAULT '1',
			PRIMARY KEY  (postnumber, blog_id)
			) $charset_collate;";

		dbDelta( $sql );

	}

	if ( $wpdb->get_var( "show tables like '$table_name_daily'" ) != $table_name_daily ) { // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery

		$sql = 'CREATE TABLE ' . $table_name_daily . // phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange
			" (
			postnumber bigint(20) NOT NULL,
			cntaccess bigint(20) NOT NULL,
			dp_date DATETIME NOT NULL,
			blog_id bigint(20) NOT NULL DEFAULT '1',
			PRIMARY KEY  (postnumber, dp_date, blog_id)
			) $charset_collate;";

		dbDelta( $sql );

	}

	add_site_option( 'tptn_db_version', $tptn_db_version );

	// Upgrade table code.
	$installed_ver = get_site_option( 'tptn_db_version' );

	if ( $installed_ver != $tptn_db_version ) { // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison

		$sql = 'ALTER TABLE ' . $table_name . ' DROP PRIMARY KEY ';
		$wpdb->query( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery
		$sql = 'ALTER TABLE ' . $table_name_daily . ' DROP PRIMARY KEY ';
		$wpdb->query( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery

		$sql = 'CREATE TABLE ' . $table_name . " (
			postnumber bigint(20) NOT NULL,
			cntaccess bigint(20) NOT NULL,
			blog_id bigint(20) NOT NULL DEFAULT '1',
			PRIMARY KEY  (postnumber, blog_id)
			) $charset_collate;";

		$sql .= 'CREATE TABLE ' . $table_name_daily . " (
			postnumber bigint(20) NOT NULL,
			cntaccess bigint(20) NOT NULL,
			dp_date DATETIME NOT NULL,
			blog_id bigint(20) NOT NULL DEFAULT '1',
			PRIMARY KEY  (postnumber, dp_date, blog_id)
			) $charset_collate;";

		dbDelta( $sql );

		update_site_option( 'tptn_db_version', $tptn_db_version );
	}

}

/**
 * Fired when a new site is activated with a WPMU environment.
 *
 * @since 2.0.0
 *
 * @param    int $blog_id    ID of the new blog.
 */
function tptn_activate_new_site( $blog_id ) {

	if ( 1 !== did_action( 'wpmu_new_blog' ) ) {
		return;
	}

	switch_to_blog( $blog_id );
	tptn_single_activate();
	restore_current_blog();

}
add_action( 'wpmu_new_blog', 'tptn_activate_new_site' );

/**
 * Fired when a site is deleted in a WPMU environment.
 *
 * @since 2.0.0
 *
 * @param    array $tables    Tables in the blog.
 */
function tptn_on_delete_blog( $tables ) {
	global $wpdb;

	$tables[] = $wpdb->prefix . 'top_ten';
	$tables[] = $wpdb->prefix . 'top_ten_daily';

	return $tables;
}
add_filter( 'wpmu_drop_tables', 'tptn_on_delete_blog' );

/**
 * Function to call install function if needed.
 *
 * @since   1.9
 */
function tptn_update_db_check() {
	global $tptn_db_version, $network_wide;

	if ( get_site_option( 'tptn_db_version' ) != $tptn_db_version ) { // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison
		tptn_activation_hook( $network_wide );
	}
}
add_action( 'plugins_loaded', 'tptn_update_db_check' );


text:
const path = require('path');
const assert = require('yeoman-assert');
const helpers = require('yeoman-test');
const fse = require('fs-extra');
const expectedFiles = require('../utils/expected-files');
const getFilesForOptions = require('../utils/utils').getFilesForOptions;
const angularFiles = require('../../generators/client/files-angular').files;
const EnvironmentBuilder = require('../../cli/environment-builder');

describe('JHipster application generator with scoped blueprint', () => {
  describe('generate monolith application with scoped blueprint', () => {
    before(() => {
      return helpers
        .create('jhipster:app', {}, { createEnv: EnvironmentBuilder.createEnv })
        .inTmpDir(dir => {
          // Fake the presence of the blueprint in node_modules
          const fakeBlueprintModuleDir = path.join(dir, 'node_modules/@jhipster/generator-jhipster-scoped-blueprint');
          fse.ensureDirSync(fakeBlueprintModuleDir);
          fse.copySync(path.join(__dirname, '../../test/templates/fake-blueprint'), fakeBlueprintModuleDir);
        })
        .withOptions({
          fromCli: true,
          skipInstall: true,
          skipChecks: true,
          blueprints: '@jhipster/generator-jhipster-scoped-blueprint',
          baseName: 'jhipster',
          defaults: true,
        })
        .run();
    });

    it('creates expected default files for server and angularX', () => {
      assert.file(expectedFiles.common);
      assert.file(expectedFiles.server);
      assert.file(
        getFilesForOptions(angularFiles, {
          enableTranslation: true,
          serviceDiscoveryType: false,
          authenticationType: 'jwt',
          testFrameworks: [],
        })
      );
    });

    it('blueprint version is saved in .yo-rc.json', () => {
      assert.JSONFileContent('.yo-rc.json', {
        'generator-jhipster': { blueprints: [{ name: '@jhipster/generator-jhipster-scoped-blueprint', version: '9.9.9' }] },
      });
    });
    it('blueprint module and version are in package.json', () => {
      assert.fileContent('package.json', /"@jhipster\/generator-jhipster-scoped-blueprint": "9.9.9"/);
    });
  });
});


text:
<project name="zepto.tab.js" default="build.dev">
	<tstamp>
		<format property="build.time"
		pattern="MMMM d, yyyy hh:mm:ss"
		locale="en,US"/>
	</tstamp>
	<!-- import properties -->
	<loadproperties srcfile="build.properties" />
	<!-- initialization and cleanup -->

	<!-- define or import utility targets here -->
	<target name="init">
		<mkdir dir="${build.dir}"/>
		<mkdir dir="${yuidoc.output}"/>
	</target>
	<target name="clean">
		<delete dir="${build.dir}"/>
		<delete dir="${yuidoc.output}"/>
	</target>
	<target name="validate">
		<apply executable="java" failonerror="true" parallel="true">
			<fileset dir="${src.dir}" includes="**/*.js" />
			<arg line="-jar"/>
			<arg path="${rhino}"/>
			<arg path="${jshint}" />
			<arg line="${jshint.options}" />
			<srcfile/>
		</apply>
	</target>
	<target name="concatenate">
		<concat destfile="${build.dir}/zepto.carousel.js" fixlastline="yes" eol="lf">
			<header trimleading="yes">/*!
			zepto.carousel v${version} http://yanhaijing.com/zepto.carousel ${license}
			*/
			/* Build time: ${build.time} */
			</header>
			<filelist dir="${src.dir}" files="" />
			<fileset dir="${src.dir}" includes="**/*.js" excludes=""/>
		</concat>
		<concat destfile="${build.dir}/zepto.carousel.css" fixlastline="yes" eol="lf">
			<header trimleading="yes">/*!
			zepto.carousel v${version} http://yanhaijing.com/zepto.carousel ${license}
			*/
			/* Build time: ${build.time} */
			</header>
			<filelist dir="${src.dir}" files="" />
			<fileset dir="${src.dir}" includes="**/*.css" excludes=""/>
		</concat>
	</target>
	<target name="test">
	</target>
	<target name="minify">
		<apply executable="java" failonerror="true">
			<fileset dir="${build.dir}" includes="*.js"/>
			<mapper type="glob" from="*.js" to="${build.dir}/*-min.js"/>
			<arg line="-jar"/>
			<arg path="${yuicompressor}"/>
			<arg line="${yuicompressor.options}"/>
			<srcfile/>
			<arg line="-o"/>
			<targetfile/>
		</apply>
		<apply executable="java" failonerror="true">
			<fileset dir="${build.dir}" includes="*.css"/>
			<mapper type="glob" from="*.css" to="${build.dir}/*-min.css"/>
			<arg line="-jar"/>
			<arg path="${yuicompressor}"/>
			<arg line="${yuicompressor.options}"/>
			<srcfile/>
			<arg line="-o"/>
			<targetfile/>
		</apply>
	</target>
	<target name="document">
		<exec executable="yuidoc" failonerror="true">
			<arg path="${src.dir}"/>
			<arg line="-o" />
			<arg path="${yuidoc.output}"/>
		</exec>
	</target>
	<target name="bake">
		<replaceregexp match="@VERSION@" replace="${version}" flags="g" byline="true">
			<fileset dir="${build.dir}" includes="**/*"/>
		</replaceregexp>
	</target>
	<!-- main builds -->
	<target name="build.dev" depends="clean,init,concatenate">
	</target>
	<target name="build.int" depends="build.dev,minify,test">
	</target>
	<target name="build.release" depends="build.int,bake">
	</target>

</project>


text:
/**
 * Created by Praveen on 10/09/2015.
 */

import React, { PropTypes, Component } from 'react';
import DeviceListItem from './Devices.List.Item';

export default class DevicesList extends Component {

    render() {

        let { dispatch, devices, deviceAttributes, selectedDevices } = this.props;
        //console.log(devices);

        let fixSidesStyle = {
            margin: 0
        };

        return (

                    { devices.map((device) => {
                        return (
                            <DeviceListItem
                                key={device._id}
                                device={device}
                                dispatch={dispatch}
                                deviceAttributes={deviceAttributes}
                                selectedDevices={selectedDevices}
                            />
                        );
                    }) }

        );
    }
}


text:
package com.rackspacecloud.blueflood.outputs.formats;

import com.rackspacecloud.blueflood.types.DataType;
import com.rackspacecloud.blueflood.types.Points;
import com.rackspacecloud.blueflood.types.RollupType;

public class MetricData {
    private final Points data;
    private final String unit;
    private final Type type;

    public MetricData(Points points, String unit, Type type) {
        this.data = points;
        this.unit = unit;
        this.type = type;
    }

    public Points getData() {
        return data;
    }

    public String getUnit() {
        return unit;
    }

    public String getType() {
        return type.toString();
    }

    public enum Type {
        NUMBER("number"),
        BOOLEAN("boolean"),
        STRING("string"),
        HISTOGRAM("histogram");

        private Type(String s) {
            this.name = s;
        }

        private String name;

        @Override
        public String toString() {
            return name;
        }

        public static Type from(RollupType rollupType, DataType dataType) {
            if (dataType.equals(DataType.STRING)) {
                return STRING;
            } else if (dataType.equals(DataType.BOOLEAN)) {
                return BOOLEAN;
            } else {
                if (rollupType == RollupType.BF_HISTOGRAMS) {
                    return HISTOGRAM;
                }

                return NUMBER;
            }
        }
    }
}


text:
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

/**
 * Demonstrates how to update fields on a security findings
 * source.
 */
function main(sourceName = 'FULL_PATH_TO_SOURCE') {
  // [START securitycenter_get_source]
  // Imports the Google Cloud client library.
  const {SecurityCenterClient} = require('@google-cloud/security-center');

  // Creates a new client.
  const client = new SecurityCenterClient();
  // sourceName is the full resource name of the source to be retrieved.
  /*
   * TODO(developer): Uncomment the following lines
   */
  // const sourceName = "organizations/111122222444/sources/1234";
  async function getSource() {
    const [source] = await client.getSource({name: sourceName});
    console.log('Source: %j', source);
  }

  getSource();
  // [END securitycenter_get_source]
}

main(...process.argv.slice(2));


text:
module Til
  class NoteList
    include Thor::Base
    include Thor::Actions
    attr_accessor :notes

    def initialize(notes=Array.new)
      @notes = notes
    end

    def sort_by_modified_time
      notes.sort { |a, b| b.mtime <=> a.mtime }
    end

    def most_recent
      notes.sort { |a, b| b.mtime <=> a.mtime }.fetch(0)
    end

    def filter
      if notes.length == 1
        notes.first
      else
        notes.each_with_index do |note, index|
          puts "#{index+1}) #{note.title.bold} (#{note.subject})"
        end

        begin
          choice = ask("Choice: ").to_i
        rescue Interrupt
          warn "\nAborted!"
          abort
        end

        notes.fetch(choice-1) do
          puts "Invalid choice!"
          abort
        end
      end
    end

    def method_missing(m, *args, &block)
      notes.send(m, *args, &block)
    end

    # def push arg
    #   self.notes.send(:push, arg)
    # end
    # def each &block
    #   self.notes.send(:each, &block)
    # end
    # def each_with_index &block
    #   self.notes.send(:each_with_index, &block)
    # end
    # def empty?
    #   self.notes.send(:empty?)
    # end
    # def length
    #   self.notes.send(:length)
    # end
    # def first
    #   self.notes.send(:first)
    # end

  end
end


text:
status=1

#Call this from anywhere to fail the test with an error message
# usage: fail "reason why the test failed"
fail()
 { echo "The test failed :-("
   echo "$*" 1>&2
   echo "exit status was $status"
   exit $status
 } #end of fail()

#Call this from anywhere to pass the test with a message
# usage: pass "reason why the test passed if applicable"
pass()
 { echo "The test passed!!!"
   echo "$*" 1>&2
   exit 0
 } #end of pass()

# end of subroutines

if [ $# = 0 ] ; then
    echo "Error: no testname specified on cmd line"
    exit 1
fi
testName=$1
shift

#Set appropriate jdk

if [ -z "${TESTJAVA}" ] ; then
   # TESTJAVA is not set, so the test is running stand-alone.
   # TESTJAVA holds the path to the root directory of the build of the JDK
   # to be tested.  That is, any java files run explicitly in this shell
   # should use TESTJAVA in the path to the java interpreter.
   # So, we'll set this to the JDK spec'd on the command line.  If none
   # is given on the command line, tell the user that and use a default.
   # THIS IS THE JDK BEING TESTED.
   if [ -n "$1" ] ; then
          TESTJAVA=$1
      else
          echo "no JDK specified on command line so using JAVA_HOME=$JAVA_HOME"
	  TESTJAVA=$JAVA_HOME
   fi
   TESTSRC=.
   TESTCLASSES=.
   STANDALONE=1;
fi
echo "JDK under test is: $TESTJAVA"

# The beginning of the script proper

# Checking for proper OS and processor type.
#
# This test is only interested in SunOS SPARC sparcv9 and SunOS AMD64
# (supporting both 32 and 64 bit Solaris binaries).
#
# All other platforms will instantly complete with passing
# status.
#
OS=`uname -s`
case "$OS" in
   SunOS )
      PATHSEP=":"
      PTYPE=`uname -p`
      if [ -x /usr/bin/isainfo ]; then
	  # Instruction set being used by the OS
	  ISET=`isainfo -k`
      else
	  #SunOS 5.6 didn't have "isainfo"
          pass "This test always passes on $OS/$PTYPE (32-bit ${ISET})"
      fi
      ;;

   Linux )
      pass "This test always passes on $OS"
      ;;

   Windows* | CYGWIN*)
      pass "This test always passes on $OS"
      ;;

   # catch all other OSs
   * )
      echo "Unrecognized system!  $OS"
      fail "Unrecognized system!  $OS"
      ;;
esac

# Is the OS running in sparcv9 or amd64 mode?
case "${ISET}" in
  sparc )
      pass "This test always passes on $OS/$PTYPE (32-bit ${ISET})"
      ;;
  i386 )
      pass "This test always passes on $OS/$PTYPE (32-bit ${ISET})"
      ;;
  amd64 )
      echo "OS is running in ${ISET} mode"
      ;;
  sparcv9 )
      echo "OS is running in ${ISET} mode"
      ;;
  # catch all others
  * )
      echo "Unrecognized instruction set!  $OS/$PTYPE/${ISET}"
      fail "Unrecognized instruction set!  $OS/$PTYPE/${ISET}"
      ;;
esac

# SunOS 32 and 64 bit binaries must be available
#     to test in the remainder of the script below.
$TESTJAVA/bin/java -d64 -version > /dev/null 2<&1
if [ $? = 1 ]; then
   # The 64 bit version is not installed.  Make the test pass.
   pass "This test always passes on $OS/$PTYPE if 64 bit jdk is not installed"
fi

# Want this test to run standalone as well as in the harness, so do the
#  following to copy the test's directory into the harness's scratch directory
#  and set all appropriate variables:

#Deal with .class files:
if [ -n "${STANDALONE}" ] ; then
   #if running standalone, compile the support files
   ${TESTJAVA}/bin/javac -d ${TESTCLASSES} \
            -classpath "$TESTJAVA/lib/tools.jar${PATHSEP}${TESTSRC}" \
            TestScaffold.java VMConnection.java TargetListener.java TargetAdapter.java
   ${TESTJAVA}/bin/javac -d ${TESTCLASSES} \
            -classpath "$TESTJAVA/lib/tools.jar${PATHSEP}${TESTSRC}" -g \
            FetchLocals.java DataModelTest.java
fi

# Get DEBUGGEE flags
DEBUGGEEFLAGS=
filename=$TESTCLASSES/@debuggeeVMOptions
if [ ! -r ${filename} ] ; then
    filename=$TESTCLASSES/../@debuggeeVMOptions
fi
# Remove -d32, -d64 if present, and remove -XX:[+-]UseCompressedOops
# if present since it is illegal in 32 bit mode.
if [ -r ${filename} ] ; then
    DEBUGGEEFLAGS=`cat ${filename} | sed \
                        -e 's/-d32//g' \
                        -e 's/-d64//g' \
                        -e 's/-XX:.UseCompressedOops//g' \
                        `
fi

#
CLASSPATH="$TESTJAVA/lib/tools.jar${PATHSEP}${TESTCLASSES}"
export CLASSPATH
CP="-classpath \"${CLASSPATH}\""

for DEBUGGERMODEL in \
    32 \
    64 \
; do

    for TARGETMODEL in \
        32 \
        64 \
    ; do
        DEBUGGERFLAGS="-d${DEBUGGERMODEL} -showversion -DEXPECTED=${TARGETMODEL}"
        CONNECTSTRING="-connect 'com.sun.jdi.CommandLineLaunch:options=-d${TARGETMODEL} $DEBUGGEEFLAGS -showversion'"

	for TARGETCLASS in $testName ; do
	    echo "--------------------------------------------"
	    echo "debugger=${DEBUGGERMODEL} debugee=${TARGETMODEL} class=${TARGETCLASS}"
	    echo "--------------------------------------------"
	    echo ${TESTJAVA}/bin/java -DHANGINGJAVA_DEB ${DEBUGGERFLAGS} ${CP} ${TARGETCLASS} ${CONNECTSTRING}
	    eval ${TESTJAVA}/bin/java -DHANGINGJAVA_DEB ${DEBUGGERFLAGS} ${CP} ${TARGETCLASS} ${CONNECTSTRING}
	    status=$?
	    if [ $status -ne "0" ];
	       then fail "$DEBUGGERMODEL to $TARGETMODEL test failed for class=$TARGETCLASS!"
	    fi
	done
    done
done
#
# pass or fail the test based on status of the command
if [ $status -eq "0" ];
   then pass ""

   else fail "unspecified test failure"
fi


text:
import MockRequest from './mock-request'
import Request from '../request'

const VALUE_NOT_MATCHED = '<MAPPERSMITH_VALUE_NOT_MATCHED>'

/**
 * @param {Integer} id
 * @param {Object} client - the client generated by {@link forge}
 */
function MockResource (id, client) {
  if (!client || !client._manifest) {
    throw new Error('[Mappersmith Test] "mockClient" received an invalid client')
  }

  this.id = id
  this.manifest = client._manifest
  this.resourceName = null
  this.methodName = null
  this.requestParams = {}
  this.responseData = null
  this.responseHeaders = {}
  this.responseStatus = 200
  this.mockRequest = null
}

MockResource.prototype = {
  /**
   * @return {MockResource}
   */
  resource (resourceName) {
    this.resourceName = resourceName
    return this
  },

  /**
   * @return {MockResource}
   */
  method (methodName) {
    this.methodName = methodName
    return this
  },

  /**
   * @return {MockResource}
   */
  with (requestParams) {
    this.requestParams = requestParams
    return this
  },

  /**
   * @return {MockResource}
   */
  headers (responseHeaders) {
    this.responseHeaders = responseHeaders
    return this
  },

  /**
   * @return {MockResource}
   */
  status (responseStatus) {
    this.responseStatus = responseStatus
    return this
  },

  /**
   * @return {MockResource}
   */
  response (responseData) {
    this.responseData = responseData
    return this
  },

  /**
   * @return {MockAssert}
   */
  assertObject () {
    return this.toMockRequest().assertObject()
  },

  /**
   * @return {MockRequest}
   */
  toMockRequest () {
    if (!this.mockRequest) {
      const methodDescriptor = this.manifest.createMethodDescriptor(this.resourceName, this.methodName)
      const initialRequest = new Request(methodDescriptor, this.requestParams)
      const middlewares = this.manifest.createMiddlewares({
        resourceName: this.resourceName,
        resourceMethod: this.methodName,
        mockRequest: true
      })
      const finalRequest = middlewares
        .reduce((request, middleware) => middleware.request(request), initialRequest)

      const params = finalRequest.params()
      const hasParamMatchers = Object.keys(params).find((key) => typeof params[key] === 'function')
      const urlMatcher = (requestUrl, requestParams) => {
        const expandedParams = this.expandParams(params, requestParams)
        const testRequest = finalRequest.enhance({ params: expandedParams })
        return testRequest.url() === requestUrl
      }

      const url = hasParamMatchers ? urlMatcher : finalRequest.url()

      this.mockRequest = new MockRequest(this.id, {
        method: finalRequest.method(),
        url,
        body: finalRequest.body(),
        response: {
          status: this.responseStatus,
          headers: this.responseHeaders,
          body: this.responseData
        }
      })
    }

    return this.mockRequest
  },

  /**
   * @private
   */
  expandParams (mockParams, requestParams) {
    return Object.keys(mockParams).reduce((obj, key) => {
      const value = requestParams[key]
      if (typeof mockParams[key] === 'function') {
        obj[key] = mockParams[key](value) ? value : VALUE_NOT_MATCHED
      } else {
        obj[key] = value
      }
      return obj
    }, {})
  }
}

export default MockResource


text:
/*
 * DITURLConnection.m
 */

#import "DITURLConnection.h"

@implementation DITURLConnection

#pragma mark - LIFE CYCLE

- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate {
	self = [super initWithRequest:request delegate:delegate];
	if(self) {
        /* At init time we create a dictionary to hold arbitrary key values */
		_metaData = [[NSMutableDictionary alloc] init];
	}
	return self;
}

/* override NSObject's desription to call po in gdb and make debugging easier */
- (NSString *)description {
	return [NSString stringWithFormat:@"%@ with %d metadata ", [super description], [_metaData count]];
}

#pragma mark - PROPERTIES SETTER

- (void)setMetaObject:(id) anObject forKey:(NSString *)aKey {

    /* Add or replace a meta info property */
	if( (nil != anObject) &&  (nil != aKey) ){
		[_metaData setObject:anObject forKey:aKey];
	}
}

- (id) metaObjectForKey:(NSString *)aKey {

	id result = nil;

	if(aKey) {
		result = [_metaData objectForKey:aKey];
	}
	return result;
}

- (void) removeMetaObjectForKey:(NSString *)aKey {

	if (nil != aKey){
		[_metaData removeObjectForKey:aKey];
	}
}

#pragma mark - CLEANUP CREW

- (void) dealloc {
}

@end


text:
import React from 'react';
import PropTypes from 'prop-types';
import sdk from '../../../index';

export default React.createClass({
    displayName: 'TextInputDialog',
    propTypes: {
        title: PropTypes.string,
        description: PropTypes.oneOfType([
            PropTypes.element,
            PropTypes.string,
        ]),
        value: PropTypes.string,
        button: PropTypes.string,
        focus: PropTypes.bool,
        onFinished: PropTypes.func.isRequired,
    },

    getDefaultProps: function() {
        return {
            title: "",
            value: "",
            description: "",
            focus: true,
        };
    },

    componentDidMount: function() {
        if (this.props.focus) {
            // Set the cursor at the end of the text input
            this.refs.textinput.value = this.props.value;
        }
    },

    onOk: function() {
        this.props.onFinished(true, this.refs.textinput.value);
    },

    onCancel: function() {
        this.props.onFinished(false);
    },

    render: function() {
        const BaseDialog = sdk.getComponent('views.dialogs.BaseDialog');
        const DialogButtons = sdk.getComponent('views.elements.DialogButtons');
        return (
            <BaseDialog className="mx_TextInputDialog" onFinished={this.props.onFinished}
                title={this.props.title}
            >
                <form onSubmit={this.onOk}>

                             { this.props.description }

                            <input id="textinput" ref="textinput" className="mx_TextInputDialog_input" defaultValue={this.props.value} autoFocus={this.props.focus} size="64" />

                </form>
                <DialogButtons primaryButton={this.props.button}
                    onPrimaryButtonClick={this.onOk}
                    onCancel={this.onCancel} />
            </BaseDialog>
        );
    },
});


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title><t></title>
    <link rel="stylesheet" type="text/css" href="jasmine/jasmine.css">
    <script type="text/javascript" src="js/platform.js"></script>
    <script type="text/javascript" src="jasmine/jasmine.js"></script>
    <script type="text/javascript" src="jasmine/console.js"></script>
    <script type="text/javascript" src="jasmine/jasmine-html.js"></script>
    <script type="text/javascript" src="jasmine/boot.js"></script>
    <link rel="import" href="P.html">
  </head>
  <body>
  </body>
</html>


text:
'use strict';
//Putting in forms today
var form = document.getElementById('store_info');//accessing my form
var table = document.getElementById('cookie_sales');//accessing table
var cookieDataForm = [];

//useing my constructor function
function Store(name, minCust, maxCust, avgCookieSales) {
  this.name = name; //grabs from user
  this.minCust = minCust; //grabs from user
  this.maxCust = maxCust; // grabs from user
  this.avgCookieSales = avgCookieSales; //grabs from user
  this.hours = ['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm']; //hours store is open to sell cookies
  this.cookiesPerHour = []; //cookies totals per hour each store
  this.dailyTotal = 0; //total cookies sold each day per store
  this.randNum = []; //randum customer generater
}

Store.prototype.randomCust = function () {//this function generates a random number to represent customers in the store each hour
  for(var i = 0; i < this.hours.length; i++) { //runs loop for each hour store is open
    this.randNum.push(Math.floor(Math.random() * (this.maxCust - this.minCust + 1) + this.minCust));
  }
  this.generateCookieSales(); //calls next function
  return this.randNum;
};
Store.prototype.generateCookieSales = function () { //this multiplies average cookie sales by the random customer number wach hour
  for(var j = 0; j < this.randNum.length; j ++) {
    this.cookiesPerHour.push(this.randNum[j] * this.avgCookieSales);
  }
  this.createDailyTotal(); //calls next function
};
Store.prototype.createDailyTotal = function() { //this function adds total number of cookies sold in a day
  // console.log(this);
  for(var k = 0; k < this.hours.length; k ++) {
    this.dailyTotal += (Math.ceil(this.randNum[k] * this.avgCookieSales));
  }
  // console.log('daily total', this.dailyTotal);
  return this.dailyTotal;
};

function formData(event) { //creating event function
  event.preventDefault(); //stops page from reloading

  var name = event.target.store.value;//takes input from user
  var minCust = parseInt(event.target.min_customers.value);
  var maxCust = parseInt(event.target.max_customers.value);
  var avgCookieSales = parseInt(event.target.avg_cook_sales.value);
  var storeOne = new Store(name, minCust, maxCust, avgCookieSales); //instantiates Store contructor function
  storeOne.randomCust();//calls function once data is entered
  // storeOne.generateCookieSales();
  cookieDataForm.push(storeOne); //moves table data created from createTable function to variable established above
  createTable(storeOne);//calls createTable function
  addFooter(storeOne);// addFooter(storeOne); //calls addFooter function, but not currently working
  form.reset(); //once submit button has been pressed
};

function createTable(store) { //helper function to create  tags around each cookiesPerHour item in an array
  var row = document.createElement('tr');
  var td = '' + store.name + '	' + '';
  for (var l = 0; l < store.cookiesPerHour.length; l ++) {
    td = td + '' + store.cookiesPerHour[l] + '	';
  };
  td = td + '' + store.dailyTotal + '	';
  row.innerHTML = td;
  table.appendChild(row);
};
form.addEventListener('submit', formData); //calls event function

//***footer is adding row under each entry, not one only at bottom of table***
var hourTotal = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
function addFooter(storeOne) {
  var tf = ['Hourly Totals	'];
  for (var m = 0; m < storeOne.cookiesPerHour.length; m++) {
    hourTotal[m] += storeOne.cookiesPerHour[m];
    tf = tf + '' + hourTotal[m] + '	';
    for (var n = 0; storeOne.length; n++) {
      hourTotal[n] += storeOne[m].cookiesPerHour[m];
    }
  };
  var footRow = document.createElement('tr');
  footRow.innerHTML = tf;
  table.appendChild(footRow);
  console.log('hourly total', hourTotal);
};


text:
<?php

namespace app\index\model;
use think\Model;
use think\Db;
use traits\model\SoftDelete;
 class Classify extends Model
 {
 	use SoftDelete;
 	protected $deleTime = 'delete_time';
 }


text:
1. package latest terraform binary inside gem
2. package/fetch older terraform binaries?
3. add more providers (AWS only right now)
4. matcher for default values for variables
5. matcher for output variables (we have to apply the plan for this to work...)


text:
import * as sinon from "sinon";
import BodyResourceBoundIriTemplateExpansionStrategy from "../src/BodyResourceBoundIriTemplateExpansionStrategy";
import MappingsCollection from "../src/DataModel/Collections/MappingsCollection";
import { MappingBuilder } from "../src/DataModel/ITemplatedResource";
import MappingsBuilder from "../src/DataModel/MappingsBuilder";
/* tslint:disable:no-var-requires */
require("jasmine-sinon");

describe("Given instance of the BodyResourceBoundIriTemplateExpansionStrategy class", () => {
  beforeEach(() => {
    this.mappings = [
      {
        property: { iri: "http://schema.org/name" },
        variable: "eventName"
      },
      {
        property: { iri: "http://schema.org/description" },
        variable: "eventDescription"
      }
    ];
    this.builder = new MappingsBuilder(new MappingsCollection(this.mappings));
    this.strategy = new BodyResourceBoundIriTemplateExpansionStrategy();
    this.body = { "http://schema.org/description": "Some description" };
    this.parameters = { "http://schema.org/name": "the-name" };
  });

  describe("when handling a standard operation without a template", () => {
    beforeEach(() => {
      this.operation = {};

      this.result = this.strategy.createRequest(this.operation, this.body, this.paramters);
    });

    it("should provide an expanded operation", () => {
      expect(this.result).toBe(this.operation);
    });
  });

  describe("when handling a templated operation", () => {
    beforeEach(() => {
      this.operation = {
        expandTarget: sinon.stub().callsFake((config: MappingBuilder) => {
          config(this.builder);
          this.variables = this.builder.complete();
          return {};
        })
      };

      this.result = this.strategy.createRequest(this.operation, this.body, this.parameters);
    });

    it("should expand target", () => {
      expect(this.operation.expandTarget).toHaveBeenCalledOnce();
    });

    it("should use mappings from the body resource", () => {
      expect(this.variables.eventDescription).toBe(this.body["http://schema.org/description"]);
    });

    it("should use mappings from the auxiliary resource", () => {
      expect(this.variables.eventName).toBe(this.parameters["http://schema.org/name"]);
    });
  });
});


text:
import styled from 'styled-components';

// Models
import { IStepCommonComponentProps, IStepComponentProps, IStepHeaderComponentProps, IStepsComponentProps } from './model';

// Components
import { Box } from '../Box/Box';

import variables from '../_utils/globals/variables';

export const StyledSteps = styled(Box)<IStepsComponentProps>`
	display: flex;
	flex-direction: column;
`;

StyledSteps.displayName = 'StyledSteps';

export const StyledStep = styled(Box)<IStepComponentProps>``;

StyledStep.displayName = 'StyledStep';

export const StyledStepHeader = styled(Box)<IStepHeaderComponentProps>`
	border-bottom: ${(props) => (props.active ? 'solid 2px #293346' : 'solid 2px #9d9d9d')};
	color: ${(props) =>
		props.active
			? `${props.palette?.fontColors.text || variables.fontColors.text}`
			: `${props.palette?.fontColors.medgray1 || variables.fontColors.medgray1}`};
	width: 200px;
	height: 40px;
	font-size: 14px;
	font-weight: 500;
	font-stretch: normal;
	font-style: normal;
	letter-spacing: normal;
	display: flex;
	justify-content: center;
	align-items: center;
	cursor: ${(props) => (props.disabled ? 'not-allowed' : 'pointer')};
	opacity: ${(props) => (props.disabled ? 0.5 : 1)};
	position: relative;
`;

StyledStepHeader.displayName = 'StyledStepHeader';

export const StyledStepContent = styled(Box)<IStepCommonComponentProps>``;

StyledStepContent.displayName = 'StyledStepContent';

export const StyledStepArrow = styled(Box)<IStepCommonComponentProps>`
	font-family: 'Mooskin Icons';
	position: absolute;
	top: 10px;
	right: -5px;
	color: inherit;
	font-size: 12px;
`;

StyledStepArrow.displayName = 'StyledStepArrow';


text:
"""
Unit tests for find_tag.py.
"""

import boto3
from botocore.exceptions import ClientError
import pytest

import find_tag

@pytest.mark.parametrize('error_code,stop_on_method', [
    (None, None),
    ('TestException', 'stub_list_projects'),
    ('TestException', 'stub_list_models'),
    ('TestException', 'stub_describe_model'),
    ('TestException', 'stub_list_tags_for_resource'),
])
def test_find_tag_in_projects(make_stubber, stub_runner, error_code, stop_on_method):
    lookoutvision_client = boto3.client('lookoutvision')
    lookoutvision_stubber = make_stubber(lookoutvision_client)
    project_name = 'test-project'
    model_version = 'test-model'
    model_arn = 'test-arn'
    key = 'test-key'
    value = 'test-value'

    with stub_runner(error_code, stop_on_method) as runner:
        runner.add(lookoutvision_stubber.stub_list_projects, [project_name])
        runner.add(lookoutvision_stubber.stub_list_models, project_name, [model_version])
        runner.add(
            lookoutvision_stubber.stub_describe_model, project_name, model_version,
            model_arn)
        runner.add(
            lookoutvision_stubber.stub_list_tags_for_resource, model_arn, {key: value})

    if error_code is None:
        got_project = find_tag.find_tag_in_projects(lookoutvision_client, key, value)
        assert got_project == [{'Project': project_name, 'ModelVersion': model_version}]
    else:
        with pytest.raises(ClientError) as exc_info:
            find_tag.find_tag_in_projects(lookoutvision_client, key, value)
        assert exc_info.value.response['Error']['Code'] == error_code


text:
var events = require('events');
var util = require('util');

var debug = require('debug')('node-sensor');

var noble = require('noble');

var SERVICE_UUID                            = 'da2b84f1627948debdc0afbea0226079';

var DEVICE_NAME_UUID                        = '2a00';

var SERVICE_1_UUID                          = 'a87988b9694c479c900e95dfa6c00a24';
var COMMAND_UUID                            = 'bf03260c72054c25af4393b1c299d159';
var SERVICE_4_UUID                          = '18cda7844bd3437085bbbfed91ec86af';
var SERVICE_6_UUID                          = 'fdd6b4d3046d4330bdec1fd0c90cb43b';

function NodeSensor(peripheral) {
  this._peripheral = peripheral;
  this._services = {};
  this._characteristics = {};

  this.name = peripheral.advertisement.localName;
  this.uuid = peripheral.uuid;

  this._moduleAType = 'Unknown';
  this._moduleBType = 'Unknown';

  this._moduleASubtype = 'Unknown';
  this._moduleBSubtype = 'Unknown';

  this._responseBuffer = new Buffer(0);

  this._peripheral.on('disconnect', this.onDisconnect.bind(this));
}

util.inherits(NodeSensor, events.EventEmitter);

NodeSensor.discover = function(callback) {
  var startScanningOnPowerOn = function() {
    if (noble.state === 'poweredOn') {
      var onDiscover = function(peripheral) {
        noble.removeListener('discover', onDiscover);

        noble.stopScanning();

        var nodeSensor = new NodeSensor(peripheral);

        callback(nodeSensor);
      };

      noble.on('discover', onDiscover);

      noble.startScanning([SERVICE_UUID]);
    } else {
      noble.once('stateChange', startScanningOnPowerOn);
    }
  };

  startScanningOnPowerOn();
};

NodeSensor.prototype.onDisconnect = function() {
  this.emit('disconnect');
};

NodeSensor.prototype.onConnect = function() {
  this.emit('connect');
};

NodeSensor.prototype.toString = function() {
  return JSON.stringify({
    uuid: this.uuid,
    name: this.name
  });
};

NodeSensor.prototype.connect = function(callback) {
  this._peripheral.connect(function() {
    callback();
  });
};

NodeSensor.prototype.disconnect = function(callback) {
  this._peripheral.disconnect(callback);
};

NodeSensor.prototype.discoverServicesAndCharacteristics = function(callback) {
  this._peripheral.discoverAllServicesAndCharacteristics(function(error, services, characteristics) {
    if (error === null) {
      for (var i in services) {
        var service = services[i];
        this._services[service.uuid] = service;
      }

      for (var j in characteristics) {
        var characteristic = characteristics[j];

        this._characteristics[characteristic.uuid] = characteristic;
      }
    }

    callback();
  }.bind(this));
};

NodeSensor.prototype.readDataCharacteristic = function(uuid, callback) {
  this._characteristics[uuid].read(function(error, data) {
    callback(data);
  });
};

NodeSensor.prototype.writeDataCharacteristic = function(uuid, data, callback) {
  this._characteristics[uuid].write(data, false, function(error) {
    if (callback) {
      callback();
    }
  });
};

NodeSensor.prototype.notifyCharacteristic = function(uuid, notify, listener, callback) {
  var characteristic = this._characteristics[uuid];

  characteristic.notify(notify, function(state) {
    if (notify) {
      characteristic.addListener('read', listener);
    } else {
      characteristic.removeListener('read', listener);
    }

    callback();
  });
};

NodeSensor.prototype.readStringCharacteristic = function(uuid, callback) {
  this.readDataCharacteristic(uuid, function(data) {
    callback(data.toString());
  });
};

NodeSensor.prototype.readDeviceName = function(callback) {
  this.readStringCharacteristic(DEVICE_NAME_UUID, callback);
};

NodeSensor.prototype.setup = function(callback) {
  this.notifyCharacteristic(SERVICE_6_UUID, true, this.onService6Notify.bind(this), function() {
    this.notifyCharacteristic(SERVICE_4_UUID, true, this.onService4Notify.bind(this), function() {
      this.readService6(function(data) {
        this.writeService1(new Buffer('01', 'hex'), function() {
          this.writeService1(new Buffer('01', 'hex'), function() {
            this.readService1(function(data) {
              this.readService1(function(data) {
                callback();
              }.bind(this));
            }.bind(this));
          }.bind(this));
        }.bind(this));
      }.bind(this));
    }.bind(this));
  }.bind(this));
};

NodeSensor.prototype.readService1 = function(callback) {
  this.readDataCharacteristic(SERVICE_1_UUID, callback);
};

NodeSensor.prototype.writeService1 = function(data, callback) {
  this.writeDataCharacteristic(SERVICE_1_UUID, data, callback);
};

NodeSensor.prototype.writeCommand = function(command, callback) {
  debug('writeCommand $' + command + '$');

  this.writeDataCharacteristic(COMMAND_UUID, new Buffer('$' + command + '$'), callback);
};

// Table of: type, subtype: size, parser method
var responseHandlers = {
  0x01: {
    0x01: [8,  'parseKoreReading'],
    0x02: [8,  'parseKoreReading'],
    0x03: [14, 'parseKoreReading'],
    0x04: [8,  'parseKoreReading'],
    0x05: [14, 'parseKoreReading'],
    0x06: [14, 'parseKoreReading'],
    0x07: [20, 'parseKoreReading'],
  },
  0x03: {
    0x03: [6, 'parseThermaReading']
  },
  0x04: {
    0x00: [10, 'parseClimaTemperaturePressure'],
    0x01: [4,  'parseClimaHumidity'],
    0x03: [6,  'parseClimaLight']
  },
  0x05: {
    0x00: [6, 'parseBatteryLevel'],
    0x05: [3, 'parseButtonPush'],
    0x06: [3, 'parseButtonRelease'],
    0x07: [4, 'parseModuleTypes'],
    0x08: [4, 'parseModuleSubtypes'],
    0x09: [9, 'parseSerial'],
    0x0a: [4, 'parseModuleVersions'],
    0x11: [3, 'parseQuietMode'],
    0x12: [4, 'parseFirmwareVersion'],
    0x20: [6, 'parseModel']
  },
  0x06: {
    0x00: [10, 'parseChromaReading'],
    0x02: [6,  'parseChromaTemperatureReading']
  },
  0x07: {
    0x01: [6, 'parseOxaReading'],
    0x12: [6, 'parseOxaBaseline']
  },
  0x09: {
    0x00: [6, 'parseThermocoupleReading']
  },
  0x0c: {
    0x0c: [0, 'parseBarCodeReading']
  }
};

NodeSensor.prototype.onService4Notify = function(data) {
  debug('service 4 notify ' + data.toString('hex'));

  this._responseBuffer = Buffer.concat([this._responseBuffer, data]);

  var parsed;

  do {
    var type = this._responseBuffer[0];
    var subtype = this._responseBuffer[1];

    data = this._responseBuffer.slice(2);

    parsed = false;

    if (responseHandlers[type] && responseHandlers[type][subtype]) {
      var size       = responseHandlers[type][subtype][0];
      var methodName = responseHandlers[type][subtype][1];

      if (size === 0) {
        size = this._responseBuffer.length;
      }

      if (this._responseBuffer.length >= size) {
        this[methodName](type, subtype, data);

        parsed = true;
        this._responseBuffer = this._responseBuffer.slice(size);
      }
    }
  } while(parsed && this._responseBuffer.length);
};

NodeSensor.prototype.onService6Notify = function(data) {
  debug('service 6 notify ' + data.toString('hex'));
};

NodeSensor.prototype.readService6 = function(callback) {
  this.readDataCharacteristic(SERVICE_6_UUID, callback);
};

NodeSensor.prototype.readVersion = function(callback) {
  this.once('firmwareVersion', function(firmwareVersion) {
    this.once('model', function(model) {
      callback(firmwareVersion, model);
    }.bind(this));
  }.bind(this));

  this.writeCommand('VER');
};

NodeSensor.prototype.parseFirmwareVersion = function(type, subtype, data) {
  var firmwareVersion = data[0] + '.' + data[1];

  this.emit('firmwareVersion', firmwareVersion);
};

NodeSensor.prototype.parseModel = function(type, subtype, data) {
  var model = data.toString();

  this.emit('model', model);
};

NodeSensor.prototype.readStatus = function(callback) {
  this.once('batteryLevel', function(batteryLevel) {
    this.once('moduleTypes', function(moduleA, moduleB) {
      callback(batteryLevel, moduleA, moduleB);
    }.bind(this));
  }.bind(this));

  this.writeCommand('STAT');
};

NodeSensor.prototype.parseBatteryLevel = function(type, subtype, data) {
  var batteryLevel = data.readFloatLE(0); // 3.7 - 4.2 volts

  this.emit('batteryLevel', batteryLevel);
};

NodeSensor.prototype.parseModuleTypes = function(type, subtype, data) {
  var MODULE_MAPPER = {
    0xff: 'None',
    0x00: 'Luma',
    0x01: 'Clima',
    0x02: 'Therma',
    0x03: 'Oxa',
    0x04: 'Chroma',
    0x05: 'ArrTherma',
    0x06: 'GPS',
    0x07: 'Thermocouple',
    0x08: 'ClimaPro',
    0x09: 'BarCode',
    0x0a: 'IO'
  };

  var moduleA = MODULE_MAPPER[data[0]] || 'Unknown';
  var moduleB = MODULE_MAPPER[data[1]] || 'Unknown';

  this._moduleAType = moduleA;
  this._moduleBType = moduleB;

  this.emit('moduleTypes', moduleA, moduleB);
};

NodeSensor.prototype.readSerials = function(callback) {
  this.once('serialCore', function(serialCore) {
    this.once('serialModuleA', function(serialModuleA) {
      this.once('serialModuleB', function(serialModuleB) {
        callback(serialCore, serialModuleA, serialModuleB);
      }.bind(this));
    }.bind(this));
  }.bind(this));

  this.writeCommand('SER');
};

NodeSensor.prototype.parseSerial = function(type, subtype, data) {
  var serialType = {
    0x00: 'Core',
    0x01: 'ModuleA',
    0x02: 'ModuleB'
  }[data[0]];

  var serial = data.slice(1).toString('hex');

  if (serialType) {
    this.emit('serial' + serialType, serial);
  }
};

NodeSensor.prototype.readModuleSubtypes = function(callback) {
  this.once('moduleSubtypes', callback);

  this.writeCommand('STATMOD');
};

NodeSensor.prototype.parseModuleSubtypes = function(type, subtype, data) {
  var moduleASubtype = data[0];
  var moduleBSubtype = data[1];

  var OXA_MAPPER = {
    0: 'CO',
    1: 'CL2',
    2: 'SO2',
    3: 'NO',
    4: 'NO2',
    5: 'H2S'
  };

  var CHROMA_MAPPER = {
    0: '1.0',
    1: '1.1',
    2: '2.0'
  };

  if (this._moduleAType === 'Oxa') {
    this._moduleASubtype = moduleASubtype = OXA_MAPPER[moduleASubtype] || moduleASubtype;
  } else if (this._moduleAType === 'Chroma') {
    this._moduleASubtype = moduleASubtype = CHROMA_MAPPER[moduleASubtype] || moduleASubtype;
  }

  if (this._moduleBType === 'Oxa') {
    this._moduleBSubtype = moduleASubtype = OXA_MAPPER[moduleBSubtype] || moduleBSubtype;
  } else if (this._moduleBType === 'Chroma') {
    this._moduleBSubtype = moduleBSubtype = CHROMA_MAPPER[moduleBSubtype] || moduleBSubtype;
  }

  this.emit('moduleSubtypes', moduleASubtype, moduleBSubtype);
};

NodeSensor.prototype.readModuleVersions = function(callback) {
  this.once('moduleVersions', callback);

  this.writeCommand('STATMODVER');
};

NodeSensor.prototype.parseModuleVersions = function(type, subtype, data) {
  var moduleAVersion = data[0];
  var moduleBVersion = data[1];

  this.emit('moduleVersions', moduleAVersion, moduleBVersion);
};

NodeSensor.prototype.readQuietMode = function(callback) {
  this.once('quietMode', callback);

  this.writeCommand('QM?');
};

NodeSensor.prototype.parseQuietMode = function(type, subtype, data) {
  var quietMode = data[0] ? true : false;

  this.emit('quietMode', quietMode);
};

NodeSensor.prototype.writeQuietMode = function(on, callback) {
  this.once('quietMode', callback);

  this.writeCommand('QM,' + (on ? '1' : '0'));
};

NodeSensor.prototype.parseButtonPush = function(type, subtype, data) {
  this.emit('buttonPush');
};

NodeSensor.prototype.parseButtonRelease = function(type, subtype, data) {
  this.emit('buttonRelease');
};

NodeSensor.prototype.writeKoreMode = function(accelerometer, gyroscope, magnetometer, period, callback) {
  this.writeCommand(
    'KORE,' +
    (accelerometer ? '1' : '0') + ',' +
    (gyroscope ? '1' : '0') + ',' +
    (magnetometer ? '1' : '0') + ',' +
    Math.round(period / 10) + ',' +
    '0',
    callback
  );
};

NodeSensor.prototype.parseKoreReading = function(type, subtype, data) {
  var dataOffset = 0;

  if (subtype & 0x01) {
    var accelerometerX = data.readInt16BE(0 + dataOffset) / 32767.0 * 16;
    var accelerometerY = data.readInt16BE(2 + dataOffset) / 32767.0 * 16;
    var accelerometerZ = data.readInt16BE(4 + dataOffset) / 32767.0 * 16;

    this.emit('koreAccelerometerReading', accelerometerX, accelerometerY, accelerometerZ);

    dataOffset += 6;
  }

  if (subtype & 0x02) {
    var gyroscopeX = data.readInt16BE(0 + dataOffset) / 32767.0 * 2000;
    var gyroscopeY = data.readInt16BE(2 + dataOffset) / 32767.0 * 2000;
    var gyroscopeZ = data.readInt16BE(4 + dataOffset) / 32767.0 * 2000;

    this.emit('koreGyroscopeReading', gyroscopeX, gyroscopeY, gyroscopeZ);

    dataOffset += 6;
  }

  if (subtype & 0x04) {
    var magnetometerX = data.readInt16BE(0 + dataOffset) / 980.0;
    var magnetometerY = data.readInt16BE(2 + dataOffset) / 980.0;
    var magnetometerZ = data.readInt16BE(4 + dataOffset) / 1100.0;

    this.emit('koreMagnetometerReading', magnetometerX, magnetometerY, magnetometerZ);

    dataOffset += 6;
  }
};

NodeSensor.prototype.writeLumaMode = function(mode, callback) { // mode 0 - 255, 1 bit per LED
  this.writeCommand('LUMA,' + mode, callback);
};

NodeSensor.prototype.writeLumaStrobe = function(strobe, callback) {
  this.writeCommand('LUMASTROBE,' + strobe.toFixed(1), callback);
};

NodeSensor.prototype.writeClimaMode = function(temperaturePressure, humidity, lightProximity, period, callback) {
  this.writeCommand(
    'CLIMA,' +
    (temperaturePressure ? '1' : '0') + ',' +
    (humidity ? '1' : '0') + ',' +
    (lightProximity ? '1' : '0') + ',' +
    Math.round(period / 10) + ',' +
    '0',
    callback
  );
};

NodeSensor.prototype.parseClimaTemperaturePressure = function(type, subtype, data) {
  var temperature = data.readInt32LE(0) / 10.0;
  var pressure = data.readInt32LE(4) / 10000.0;

  this.emit('climaTemperatureReading', temperature);
  this.emit('climaPressureReading', pressure);
};

NodeSensor.prototype.parseClimaHumidity = function(type, subtype, data) {
  var humidity = data.readInt16LE(0) / 10.0;

  this.emit('climaHumidityReading', humidity);
};

NodeSensor.prototype.parseClimaLight = function(type, subtype, data) {
  var light = data.readFloatLE(0);

  this.emit('climaLightReading', light);
};

NodeSensor.prototype.readOxaBaseline = function(module, callback) { // module 'A', or 'B'
  this.once('oxaBaseline', callback);

  var port = (module.indexOf('A') === 0) ? '1' : '2';

  this.writeCommand('OXABP?,' + port);
};

NodeSensor.prototype.parseOxaBaseline = function(type, subtype, data) {
  var baseline = data.readFloatLE(0);

  this.emit('oxaBaseline', baseline);
};

NodeSensor.prototype.writeOxaMode = function(enabled, tiaGain, rLoad, refSource, intZ, biasSign, bias, eftShort, opMode, period, callback) {
  this.writeCommand(
    'OXA,' +
    (enabled ? '1' : '0') + ',' +
    (tiaGain << 2 | rLoad) + ',' +
    (refSource << 7 | intZ << 5 | biasSign << 4 | bias) + ',' +
    (eftShort << 7 | opMode) + ',' +
    period + ',' +
    '0',
    callback
  );
};

NodeSensor.prototype.writeOxaCOMode = function(enabled, period, callback) {
  // Tia Gain       35
  // Int Z          20
  // Ref Source     External
  // Bias Sign      Positive
  // Bias Value     0
  // Shorting EFT   Disabled
  // Op mode        3 Lead Amperometric

  // this.writeOxaMode(enabled, 5, 0, 1, 0, 1, 0, 0, 1, period, callback);

  this.writeCommand(
    'OXA,' +
    (enabled ? '2' : '0') + ',' +
    '28,128,2,' +
    Math.round(period / 25) + ',' +
    '0',
    callback
  );
};

NodeSensor.prototype.parseOxaReading = function(type, subtype, data) {
  var reading = data.readFloatLE(0);

  this.emit('oxaReading', reading);
};

NodeSensor.prototype.readChroma = function(callback) {
  this.once('chromaReading', function(clear, red, green, blue) {
    this.once('chromaTemperatureReading', function(temperature) {
      callback(clear, red, green, blue, temperature);
    }.bind(this));
  }.bind(this));

  this.writeCommand('VERA,255,3,0,120'); // for version 1: VERA,255,1,1,2
};

NodeSensor.prototype.parseChromaReading = function(type, subtype, data) {
  // TODO: these are raw values, need to convert
  var clear = data.readUInt16LE(0);
  var red   = data.readUInt16LE(2);
  var green = data.readUInt16LE(4);
  var blue  = data.readUInt16LE(6);

  this.emit('chromaReading', clear, red, green, blue);
};

NodeSensor.prototype.parseChromaTemperatureReading = function(type, subtype, data) {
  var temperature = data.readFloatLE(0);

  this.emit('chromaTemperatureReading', temperature);
};

NodeSensor.prototype.writeThermaMode = function(ir, led, period, callback) {
  this.writeCommand(
    'IRTHRM,' +
    (ir ? '1' : '0') + ',' +
    (led ? '1' : '0') + ',' +
    Math.round(period / 10) + ',' +
    '0',
    callback
  );
};

NodeSensor.prototype.parseThermaReading = function(type, subtype, data) {
  var irTemperature = data.readFloatLE(0);

  this.emit('thermaTemperatureReading', irTemperature);
};

NodeSensor.prototype.writeThermocoupleMode = function(enabled, period, callback) {
  this.writeCommand(
    'TCPL,' +
    (enabled ? '1' : '0') + ',' +
    period + ',' +
    '0',
    callback
  );
};

NodeSensor.prototype.parseThermocoupleReading = function(type, subtype, data) {
  var thermocouplTemperature = data.readFloatLE(0);

  this.emit('thermocoupleTemperatureReading', thermocouplTemperature);
};

NodeSensor.prototype.parseBarCodeReading = function(type, subtype, data) {
  var barCode = data.toString();

  this.emit('barCodeReading', barCode);
};

module.exports = NodeSensor;


text:
require("../core/core.module");

import { IndexEditorComponent } from "./index-editor.component";
import { IndexListComponent } from "./index-list.component";
import { IndexComponent } from "./index.component";
import { IndexesContainerComponent } from "./indexes-container.component";
import { IndexActionCreator } from "./index.actions";
import { IndexService } from "./index.service";
import *  as reducers from "./index.reducers";
import { provide } from "../core";

var app = (<any>angular.module("app.index", [
    "app.core"
]));

provide(app, IndexActionCreator);
app.service("indexService",["$q","apiEndpoint","fetch",IndexService]);
app.component(IndexEditorComponent);
app.component(IndexListComponent);
app.component(IndexComponent);
app.component(IndexesContainerComponent);

app.config(["reducersProvider", reducersProvider => {
    for (var reducer in reducers) { reducersProvider.configure(reducers[reducer]); }
}]);


text:
[![Gem Version](https://badge.fury.io/rb/j-cap-recipes.png)](http://badge.fury.io/rb/j-cap-recipes)

A simple number of capistrano recipes to deploy rails application using Capistrano v3.

## Installation

Add this line to your application's Gemfile:

    gem 'j-cap-recipes', group: :development

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install j-cap-recipes

## Usage

In the `Capfile` to include all recipes add:

    require 'j-cap-recipes/default'

If you want to load only specified recipe:

    require 'j-cap-recipes/setup'
    require 'j-cap-recipes/check'
    require 'j-cap-recipes/nginx'
    require 'j-cap-recipes/monit'
    require 'j-cap-recipes/database'
    require 'j-cap-recipes/delayed_job'
    require 'j-cap-recipes/log'
    require 'j-cap-recipes/rails'
    require 'j-cap-recipes/unicorn'
    require 'j-cap-recipes/honeybadger'
    require 'j-cap-recipes/airbrake'

Also you need to include rake tasks in your `Rakefile`:

    require 'j-cap-recipes'

### Nginx
### Setup
### Check
### Monit

### Database recipes

 `cap production db:create`
 `cap production db:backup`
 `cap production db:dump_download`
 `cap production db:dump_download[rails_env]` - Download the file that located in `<current>/db/backups/<application>_<rails_env>_latest.dump`
 `cap production db:dump_upload`
 `cap production db:dump_upload[rails_env]` - Upload the file `<current>/db/backups/<application>_<rails_env>_latest.dump` to remote host
 `cap production db:restore`

### Rails

To run remote rails console you should update to the latest gems `capistrano-rbenv` and `capistrano-bundler`
and run command `cap production rails:console`.

To setup a custom `database.yml` config you should provide the directory of the templates

```ruby
set :template_dir, `config/deploy/templates`
```

After you should create a file `database.yml.erb` example:

```yaml
# store your custom template at foo/bar/database.yml.erb `set :template_dir, "foo/bar"`
#
# example of database template

base: &base
  adapter: postgresql
  encoding: unicode
  timeout: 5000
  username: deployer
  password: <%#= ask(:db_password, SecureRandom.base64(6)) && fetch(:db_password) %>
  host: localhost
 port: 5432

test:
  database: <%= fetch(:application) %>_test
  <<: *base

<%= fetch(:rails_env).to_s %>:
  database: <%= fetch(:application) %>_<%= fetch(:rails_env).to_s %>
  <<: *base

```

### Honeybadger

`honeybadger:deploy` - notify the service about deploy and it would be invoked after `deploy:migrate`

### Settings

Support to manage https://github.com/bigbinary/handy config files. First should add `require 'j-cap-recipes/settings'` to `Capfile`.
There are tasks available:

- `cap staging config:settings` Show the current staging config files;
- `cap staging config:settings:delete` Remove the custom env settings file;
- `cap staging config:settings:upload` Update the remote config file with local one;
- `cap staging config:settings:get` Download the remote config file to local one
- `cap staging config:settings:edit` Direct editing of the settings file

### Update VERSION file with build number

Task `deploy:update_version` adds to end of line the `:build_number` string. You may set it to:

```ruby
set :build_number, proc { [fetch(:current_revision), Time.now.strftime("%Y%m%d"), ].compact.join('-') }
set :version_filename, 'VERSION'
```

### Git

First should add `require 'j-cap-recipes/git'` to `Capfile`.
- `cap staging git:release:tag` Create tag in local repo by variable `git_tag_name`
 Example of usage in your `deploy.rb`:

```ruby
set :git_tag_name, proc { Time.now.to_s.gsub(/[\s\+]+/, '_') }
after 'deploy:finished', 'git:release:tag'
```

### Files

Add 'j-cap-recipes/git'` to `Capfile`.
And now you have task to download any remote file to local via:
`bundle exec cap staging "files:download[config/database.yml]"`.
You will find `download.tar` file in current directory with `config/database.yml`.

To download all share folder use:
`bundle exec cap staging "files:download[.]"`

To extract the archive `tar -xvf download.tar -C tmp`

### Airbrake

Add 'j-cap-recipes/airbrake'` to `Capfile`. The original version capistrano task to notify airbrake service support only
Capistrano version 2. Migrate the task to support version 3.

To send Airbrake deploy notification, you should also add hook to `deploy.rb`

```ruby
after 'deploy:finishing', 'airbrake:deploy'
```

You can change the default api key using `ENV['API_KEY']`.

### Rake tasks

Added utility rake task to create database backup for postgresql and rails.

### SSHKit addon

`SSHKit::Backend::SshCommand` a new backend to invoke the ssh command using system command `ssh`.
Now you can easy to execute interactive applications with similar changes. Example:

```ruby
namespace :rails do
  desc 'Execute rails console'
  task :console do
    on roles(:app), in: :parallel, backend: :ssh_command do |*args|
      within release_path do
        with rails_env: fetch(:rails_env) do
          execute(:rails, :console)
        end
      end
    end
  end
end
```

And you have a easy and fast way to run remote interactive rails console via command `cap production rails:console`.

```ruby
task :less_log do
  on roles(:app), in: :parallel, backend: :ssh_command do |*args|
    within current_path.join('log') do
      execute(:less, '-R', fetch(:rails_env)+'.log')
    end
  end
end
```

And you have way to look to logs `cap production less_log`.

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
package org.apache.jackrabbit.oak.jcr;

import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.ValueFactory;
import javax.jcr.ValueFormatException;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.fail;

/**
 * ValueFactoryTest...
 */
public class ValueFactoryTest extends AbstractRepositoryTest {

    private ValueFactory valueFactory;

    public ValueFactoryTest(NodeStoreFixture fixture) {
        super(fixture);
    }

    @Before
    public void setup() throws RepositoryException {
        valueFactory = getAdminSession().getValueFactory();
    }

    // TODO: this tests should be moved to the TCK. retrieving "invalidIdentifier" from the config.

    @Test
    public void testReferenceValue() {
        try {
            valueFactory.createValue("invalidIdentifier", PropertyType.REFERENCE);
            fail("Conversion to REFERENCE value must validate identifier string ");
        } catch (ValueFormatException e) {
            // success
        }
    }

    @Test
    public void testWeakReferenceValue() {
        try {
            valueFactory.createValue("invalidIdentifier", PropertyType.WEAKREFERENCE);
            fail("Conversion to WEAK_REFERENCE value must validate identifier string ");
        } catch (ValueFormatException e) {
            // success
        }
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.zeroturnaround.com" xsi:schemaLocation="http://www.zeroturnaround.com http://www.zeroturnaround.com/alderaan/rebel-2_0.xsd">

	<classpath>
		<dir name="E:/giftovators/eclipse-workspace/DemoSite/admin/target/admin/WEB-INF/classes">
		</dir>
	</classpath>

	<web>
		<link target="/">
			<dir name="E:/giftovators/eclipse-workspace/DemoSite/admin/src/main/webapp">
			</dir>
		</link>
	</web>

</application>