text:
.class public final Landroid/net/NetworkScorerAppManager;
.super Ljava/lang/Object;
.source "NetworkScorerAppManager.java"

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/net/NetworkScorerAppManager$NetworkScorerAppData;
    }
.end annotation

# static fields
.field private static final SCORE_INTENT:Landroid/content/Intent;

.field private static final TAG:Ljava/lang/String; = "NetworkScorerAppManager"

# direct methods
.method static constructor <clinit>()V
    .locals 2

    .prologue
    .line 47
    new-instance v0, Landroid/content/Intent;

    const-string v1, "android.net.scoring.SCORE_NETWORKS"

    invoke-direct {v0, v1}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V

    sput-object v0, Landroid/net/NetworkScorerAppManager;->SCORE_INTENT:Landroid/content/Intent;

    return-void
.end method

.method private constructor <init>()V
    .locals 0

    .prologue
    .line 51
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method public static getActiveScorer(Landroid/content/Context;)Landroid/net/NetworkScorerAppManager$NetworkScorerAppData;
    .locals 3
    .param p0, "context"    # Landroid/content/Context;

    .prologue
    .line 142
    invoke-virtual {p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v1

    const-string/jumbo v2, "network_scorer_app"

    invoke-static {v1, v2}, Landroid/provider/Settings$Global;->getString(Landroid/content/ContentResolver;Ljava/lang/String;)Ljava/lang/String;

    move-result-object v0

    .line 144
    .local v0, "scorerPackage":Ljava/lang/String;
    invoke-static {p0, v0}, Landroid/net/NetworkScorerAppManager;->getScorer(Landroid/content/Context;Ljava/lang/String;)Landroid/net/NetworkScorerAppManager$NetworkScorerAppData;

    move-result-object v1

    return-object v1
.end method

.method public static getAllValidScorers(Landroid/content/Context;)Ljava/util/Collection;
    .locals 14
    .param p0, "context"    # Landroid/content/Context;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Landroid/content/Context;",
            ")",
            "Ljava/util/Collection",
            "<",
            "Landroid/net/NetworkScorerAppManager$NetworkScorerAppData;",
            ">;"
        }
    .end annotation

    .prologue
    const/4 v13, 0x0

    .line 88
    new-instance v9, Ljava/util/ArrayList;

    invoke-direct {v9}, Ljava/util/ArrayList;-><init>()V

    .line 90
    .local v9, "scorers":Ljava/util/List;, "Ljava/util/List<Landroid/net/NetworkScorerAppManager$NetworkScorerAppData;>;"
    invoke-virtual {p0}, Landroid/content/Context;->getPackageManager()Landroid/content/pm/PackageManager;

    move-result-object v5

    .line 92
    .local v5, "pm":Landroid/content/pm/PackageManager;
    sget-object v10, Landroid/net/NetworkScorerAppManager;->SCORE_INTENT:Landroid/content/Intent;

    invoke-virtual {v5, v10, v13, v13}, Landroid/content/pm/PackageManager;->queryBroadcastReceivers(Landroid/content/Intent;II)Ljava/util/List;

    move-result-object v8

    .line 94
    .local v8, "receivers":Ljava/util/List;, "Ljava/util/List<Landroid/content/pm/ResolveInfo;>;"
    invoke-interface {v8}, Ljava/util/List;->iterator()Ljava/util/Iterator;

    move-result-object v3

    .local v3, "i$":Ljava/util/Iterator;
    :cond_0
    :goto_0
    invoke-interface {v3}, Ljava/util/Iterator;->hasNext()Z

    move-result v10

    if-eqz v10, :cond_2

    invoke-interface {v3}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v6

    check-cast v6, Landroid/content/pm/ResolveInfo;

    .line 96
    .local v6, "receiver":Landroid/content/pm/ResolveInfo;
    iget-object v7, v6, Landroid/content/pm/ResolveInfo;->activityInfo:Landroid/content/pm/ActivityInfo;

    .line 97
    .local v7, "receiverInfo":Landroid/content/pm/ActivityInfo;
    if-eqz v7, :cond_0

    .line 101
    const-string v10, "android.permission.BROADCAST_NETWORK_PRIVILEGED"

    iget-object v11, v7, Landroid/content/pm/ActivityInfo;->permission:Ljava/lang/String;

    invoke-virtual {v10, v11}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v10

    if-eqz v10, :cond_0

    .line 106
    const-string v10, "android.permission.SCORE_NETWORKS"

    iget-object v11, v7, Landroid/content/pm/ActivityInfo;->packageName:Ljava/lang/String;

    invoke-virtual {v5, v10, v11}, Landroid/content/pm/PackageManager;->checkPermission(Ljava/lang/String;Ljava/lang/String;)I

    move-result v10

    if-nez v10, :cond_0

    .line 114
    const/4 v2, 0x0

    .line 115
    .local v2, "configurationActivityClassName":Ljava/lang/String;
    new-instance v4, Landroid/content/Intent;

    const-string v10, "android.net.scoring.CUSTOM_ENABLE"

    invoke-direct {v4, v10}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V

    .line 116
    .local v4, "intent":Landroid/content/Intent;
    iget-object v10, v7, Landroid/content/pm/ActivityInfo;->packageName:Ljava/lang/String;

    invoke-virtual {v4, v10}, Landroid/content/Intent;->setPackage(Ljava/lang/String;)Landroid/content/Intent;

    .line 117
    invoke-virtual {v5, v4, v13}, Landroid/content/pm/PackageManager;->queryIntentActivities(Landroid/content/Intent;I)Ljava/util/List;

    move-result-object v1

    .line 118
    .local v1, "configActivities":Ljava/util/List;, "Ljava/util/List<Landroid/content/pm/ResolveInfo;>;"
    invoke-interface {v1}, Ljava/util/List;->isEmpty()Z

    move-result v10

    if-nez v10, :cond_1

    .line 119
    invoke-interface {v1, v13}, Ljava/util/List;->get(I)Ljava/lang/Object;

    move-result-object v10

    check-cast v10, Landroid/content/pm/ResolveInfo;

    iget-object v0, v10, Landroid/content/pm/ResolveInfo;->activityInfo:Landroid/content/pm/ActivityInfo;

    .line 120
    .local v0, "activityInfo":Landroid/content/pm/ActivityInfo;
    if-eqz v0, :cond_1

    .line 121
    iget-object v2, v0, Landroid/content/pm/ActivityInfo;->name:Ljava/lang/String;

    .line 127
    .end local v0    # "activityInfo":Landroid/content/pm/ActivityInfo;
    :cond_1
    new-instance v10, Landroid/net/NetworkScorerAppManager$NetworkScorerAppData;

    iget-object v11, v7, Landroid/content/pm/ActivityInfo;->packageName:Ljava/lang/String;

    invoke-virtual {v7, v5}, Landroid/content/pm/ActivityInfo;->loadLabel(Landroid/content/pm/PackageManager;)Ljava/lang/CharSequence;

    move-result-object v12

    invoke-direct {v10, v11, v12, v2}, Landroid/net/NetworkScorerAppManager$NetworkScorerAppData;-><init>(Ljava/lang/String;Ljava/lang/CharSequence;Ljava/lang/String;)V

    invoke-interface {v9, v10}, Ljava/util/List;->add(Ljava/lang/Object;)Z

    goto :goto_0

    .line 131
    .end local v1    # "configActivities":Ljava/util/List;, "Ljava/util/List<Landroid/content/pm/ResolveInfo;>;"
    .end local v2    # "configurationActivityClassName":Ljava/lang/String;
    .end local v4    # "intent":Landroid/content/Intent;
    .end local v6    # "receiver":Landroid/content/pm/ResolveInfo;
    .end local v7    # "receiverInfo":Landroid/content/pm/ActivityInfo;
    :cond_2
    return-object v9
.end method

.method public static getScorer(Landroid/content/Context;Ljava/lang/String;)Landroid/net/NetworkScorerAppManager$NetworkScorerAppData;
    .locals 5
    .param p0, "context"    # Landroid/content/Context;
    .param p1, "packageName"    # Ljava/lang/String;

    .prologue
    const/4 v3, 0x0

    .line 205
    invoke-static {p1}, Landroid/text/TextUtils;->isEmpty(Ljava/lang/CharSequence;)Z

    move-result v4

    if-eqz v4, :cond_0

    move-object v0, v3

    .line 214
    :goto_0
    return-object v0

    .line 208
    :cond_0
    invoke-static {p0}, Landroid/net/NetworkScorerAppManager;->getAllValidScorers(Landroid/content/Context;)Ljava/util/Collection;

    move-result-object v1

    .line 209
    .local v1, "applications":Ljava/util/Collection;, "Ljava/util/Collection<Landroid/net/NetworkScorerAppManager$NetworkScorerAppData;>;"
    invoke-interface {v1}, Ljava/util/Collection;->iterator()Ljava/util/Iterator;

    move-result-object v2

    .local v2, "i$":Ljava/util/Iterator;
    :cond_1
    invoke-interface {v2}, Ljava/util/Iterator;->hasNext()Z

    move-result v4

    if-eqz v4, :cond_2

    invoke-interface {v2}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/net/NetworkScorerAppManager$NetworkScorerAppData;

    .line 210
    .local v0, "app":Landroid/net/NetworkScorerAppManager$NetworkScorerAppData;
    iget-object v4, v0, Landroid/net/NetworkScorerAppManager$NetworkScorerAppData;->mPackageName:Ljava/lang/String;

    invoke-virtual {p1, v4}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v4

    if-eqz v4, :cond_1

    goto :goto_0

    .end local v0    # "app":Landroid/net/NetworkScorerAppManager$NetworkScorerAppData;
    :cond_2
    move-object v0, v3

    .line 214
    goto :goto_0
.end method

.method public static isCallerActiveScorer(Landroid/content/Context;I)Z
    .locals 5
    .param p0, "context"    # Landroid/content/Context;
    .param p1, "callingUid"    # I

    .prologue
    const/4 v3, 0x0

    .line 186
    invoke-static {p0}, Landroid/net/NetworkScorerAppManager;->getActiveScorer(Landroid/content/Context;)Landroid/net/NetworkScorerAppManager$NetworkScorerAppData;

    move-result-object v1

    .line 187
    .local v1, "defaultApp":Landroid/net/NetworkScorerAppManager$NetworkScorerAppData;
    if-nez v1, :cond_1

    .line 199
    :cond_0
    :goto_0
    return v3

    .line 190
    :cond_1
    const-string v4, "appops"

    invoke-virtual {p0, v4}, Landroid/content/Context;->getSystemService(Ljava/lang/String;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/app/AppOpsManager;

    .line 192
    .local v0, "appOpsMgr":Landroid/app/AppOpsManager;
    :try_start_0
    iget-object v4, v1, Landroid/net/NetworkScorerAppManager$NetworkScorerAppData;->mPackageName:Ljava/lang/String;

    invoke-virtual {v0, p1, v4}, Landroid/app/AppOpsManager;->checkPackage(ILjava/lang/String;)V
    :try_end_0
    .catch Ljava/lang/SecurityException; {:try_start_0 .. :try_end_0} :catch_0

    .line 199
    const-string v4, "android.permission.SCORE_NETWORKS"

    invoke-virtual {p0, v4}, Landroid/content/Context;->checkCallingPermission(Ljava/lang/String;)I

    move-result v4

    if-nez v4, :cond_0

    const/4 v3, 0x1

    goto :goto_0

    .line 193
    :catch_0
    move-exception v2

    .line 194
    .local v2, "e":Ljava/lang/SecurityException;
    goto :goto_0
.end method

.method public static setActiveScorer(Landroid/content/Context;Ljava/lang/String;)Z
    .locals 5
    .param p0, "context"    # Landroid/content/Context;
    .param p1, "packageName"    # Ljava/lang/String;

    .prologue
    const/4 v1, 0x1

    .line 158
    invoke-virtual {p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v2

    const-string/jumbo v3, "network_scorer_app"

    invoke-static {v2, v3}, Landroid/provider/Settings$Global;->getString(Landroid/content/ContentResolver;Ljava/lang/String;)Ljava/lang/String;

    move-result-object v0

    .line 160
    .local v0, "oldPackageName":Ljava/lang/String;
    invoke-static {v0, p1}, Landroid/text/TextUtils;->equals(Ljava/lang/CharSequence;Ljava/lang/CharSequence;)Z

    move-result v2

    if-eqz v2, :cond_0

    .line 179
    :goto_0
    return v1

    .line 165
    :cond_0
    const-string v2, "NetworkScorerAppManager"

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string v4, "Changing network scorer from "

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    const-string v4, " to "

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Landroid/util/Log;->i(Ljava/lang/String;Ljava/lang/String;)I

    .line 167
    if-nez p1, :cond_1

    .line 168
    invoke-virtual {p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v2

    const-string/jumbo v3, "network_scorer_app"

    const/4 v4, 0x0

    invoke-static {v2, v3, v4}, Landroid/provider/Settings$Global;->putString(Landroid/content/ContentResolver;Ljava/lang/String;Ljava/lang/String;)Z

    goto :goto_0

    .line 173
    :cond_1
    invoke-static {p0, p1}, Landroid/net/NetworkScorerAppManager;->getScorer(Landroid/content/Context;Ljava/lang/String;)Landroid/net/NetworkScorerAppManager$NetworkScorerAppData;

    move-result-object v2

    if-eqz v2, :cond_2

    .line 174
    invoke-virtual {p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v2

    const-string/jumbo v3, "network_scorer_app"

    invoke-static {v2, v3, p1}, Landroid/provider/Settings$Global;->putString(Landroid/content/ContentResolver;Ljava/lang/String;Ljava/lang/String;)Z

    goto :goto_0

    .line 178
    :cond_2
    const-string v1, "NetworkScorerAppManager"

    new-instance v2, Ljava/lang/StringBuilder;

    invoke-direct {v2}, Ljava/lang/StringBuilder;-><init>()V

    const-string v3, "Requested network scorer is not valid: "

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

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

    move-result-object v2

    invoke-static {v1, v2}, Landroid/util/Log;->w(Ljava/lang/String;Ljava/lang/String;)I

    .line 179
    const/4 v1, 0x0

    goto :goto_0
.end method


text:
#include <stdio.h>
#include <stdlib.h>
#include "allheaders.h"

/*
 *  paintmask_reg.c
 *
 *    Regression test for painting through a mask onto various
 *    depth images.
 *
 *    This file shows how one can start with a 32 bpp RGB image and
 *    derive from it the following:
 *       8 bpp color, cmapped
 *       4 bpp color, cmapped
 *       2 bpp color, cmapped
 *       8 bpp gray
 *       4 bpp gray
 *       4 bpp gray, cmapped
 *       2 bpp gray
 *       2 bpp gray, cmapped
 *
 *    For each of these, pixClipMasked() is used to place a 1 bpp
 *    mask over part of the image, clip out the rectangular region
 *    supporting the mask, and paint a given color through the
 *    mask onto the result.
 *
 *    Finally we do a clip/mask operation on 1 bpp sources.
 */

main(int    argc,
char **argv)
{
BOX         *box;
PIX         *pixs, *pixs8, *pixm, *pixg, *pixt1, *pixt2, *pixd;
static char  mainName[] = "paintmask_reg";

    pixDisplayWrite(NULL, -1);  /* reset */

        /* Start with a 32 bpp image and a mask.  Use the
	 * same mask for all clip/masked operations. */
    pixs = pixRead("test24.jpg");
    pixt1 = pixRead("rabi.png");
    box = boxCreate(303, 1983, 800, 500);
    pixm = pixClipRectangle(pixt1, box, NULL);
    pixInvert(pixm, pixm);
    boxDestroy(&box);
    box = boxCreate(100, 100, 800, 500);  /* clips on pixs and derivatives */
    pixt2 = pixClipRectangle(pixs, box, NULL);
    pixDisplayWrite(pixt2, 1);
    pixDestroy(&pixt1);
    pixDestroy(&pixt2);

        /* Clip 32 bpp RGB */
    pixd = pixClipMasked(pixs, pixm, 100, 100, 0x03c08000);
    pixDisplayWrite(pixd, 1);
    pixDestroy(&pixd);

        /* Clip 8 bpp colormapped */
    pixt1 = pixMedianCutQuant(pixs, 0);
    pixt2 = pixClipRectangle(pixt1, box, NULL);
    pixDisplayWrite(pixt2, 1);
    pixd = pixClipMasked(pixt1, pixm, 100, 100, 0x03c08000);
    pixDisplayWrite(pixd, 1);
    pixDestroy(&pixt1);
    pixDestroy(&pixt2);
    pixDestroy(&pixd);

        /* Clip 4 bpp colormapped */
    pixt1 = pixOctreeQuantNumColors(pixs, 16, 1);
    pixt2 = pixClipRectangle(pixt1, box, NULL);
    pixDisplayWrite(pixt2, 1);
    pixd = pixClipMasked(pixt1, pixm, 100, 100, 0x03c08000);
    pixDisplayWrite(pixd, 1);
    pixDestroy(&pixt1);
    pixDestroy(&pixt2);
    pixDestroy(&pixd);

        /* Clip 2 bpp colormapped */
    pixt1 = pixMedianCutQuantGeneral(pixs, 0, 2, 4, 5, 1, 1);
    pixt2 = pixClipRectangle(pixt1, box, NULL);
    pixDisplayWrite(pixt2, 1);
    pixd = pixClipMasked(pixt1, pixm, 100, 100, 0x03608000);
    pixDisplayWrite(pixd, 1);
    pixDestroy(&pixt1);
    pixDestroy(&pixt2);
    pixDestroy(&pixd);

        /* Clip 8 bpp gray */
    pixs8 = pixConvertRGBToLuminance(pixs);
    pixt2 = pixClipRectangle(pixs8, box, NULL);
    pixDisplayWrite(pixt2, 1);
    pixd = pixClipMasked(pixs8, pixm, 100, 100, 90);
    pixDisplayWrite(pixd, 1);
    pixDestroy(&pixt2);
    pixDestroy(&pixd);

        /* Clip 4 bpp gray */
    pixt1 = pixThresholdTo4bpp(pixs8, 16, 0);
    pixt2 = pixClipRectangle(pixt1, box, NULL);
    pixDisplayWrite(pixt2, 1);
    pixd = pixClipMasked(pixt1, pixm, 100, 100, 0);
    pixDisplayWrite(pixd, 1);
    pixDestroy(&pixd);
    pixd = pixClipMasked(pixt1, pixm, 100, 100, 5);
    pixDisplayWrite(pixd, 1);
    pixDestroy(&pixd);
    pixd = pixClipMasked(pixt1, pixm, 100, 100, 15);
    pixDisplayWrite(pixd, 1);
    pixDestroy(&pixt1);
    pixDestroy(&pixt2);
    pixDestroy(&pixd);

        /* Clip 4 bpp gray, colormapped */
    pixt1 = pixThresholdTo4bpp(pixs8, 16, 1);
    pixt2 = pixClipRectangle(pixt1, box, NULL);
    pixDisplayWrite(pixt2, 1);
    pixd = pixClipMasked(pixt1, pixm, 100, 100, 0x55555500);
    pixDisplayWrite(pixd, 1);
    pixDestroy(&pixt1);
    pixDestroy(&pixt2);
    pixDestroy(&pixd);

        /* Clip 2 bpp gray */
    pixt1 = pixThresholdTo2bpp(pixs8, 4, 0);
    pixt2 = pixClipRectangle(pixt1, box, NULL);
    pixDisplayWrite(pixt2, 1);
    pixd = pixClipMasked(pixt1, pixm, 100, 100, 1);
    pixDisplayWrite(pixd, 1);
    pixDestroy(&pixt1);
    pixDestroy(&pixt2);
    pixDestroy(&pixd);

        /* Clip 2 bpp gray, colormapped */
    pixt1 = pixThresholdTo2bpp(pixs8, 4, 1);
    pixt2 = pixClipRectangle(pixt1, box, NULL);
    pixDisplayWrite(pixt2, 1);
    pixd = pixClipMasked(pixt1, pixm, 100, 100, 0x55555500);
    pixDisplayWrite(pixd, 1);
    pixDestroy(&pixt1);
    pixDestroy(&pixt2);
    pixDestroy(&pixd);

    pixDestroy(&pixm);
    pixDestroy(&pixs);
    pixDestroy(&pixs8);
    boxDestroy(&box);

        /* Finally, do the 1 bpp painting through clipped region.
	 * We start with two 1 bpp text sources, use the inverse
	 * of the 2nd for the mask (so we take all of the 1st
	 * pixels under this mask), and for the remainder, which
	 * are the fg pixels in the 2nd, we paint them black (1).
	 * So this is a simple and fast blending of two 1 bpp pix. */
    pixs = pixRead("feyn.tif");
    box = boxCreate(670, 827, 800, 500);
    pixt2 = pixClipRectangle(pixs, box, NULL);
    boxDestroy(&box);
    pixDisplayWrite(pixt2, 1);
    pixt1 = pixRead("rabi.png");
    box = boxCreate(303, 1983, 800, 500);
    pixm = pixClipRectangle(pixt1, box, NULL);
    pixInvert(pixm, pixm);
    pixDisplayWrite(pixm, 1);
    pixd = pixClipMasked(pixs, pixm, 670, 827, 1);
    pixDisplayWrite(pixd, 1);
    pixDestroy(&pixs);
    pixDestroy(&pixt1);
    pixDestroy(&pixt2);
    pixDestroy(&pixm);
    pixDestroy(&pixd);
    boxDestroy(&box);

    pixDisplayMultiple("/tmp/junk_write_display*");
    return 0;
}

redpajama_set_name: RedPajamaGithub


text:
package gorethink

import (
	test "gopkg.in/check.v1"
)

func (s *RethinkSuite) TestManipulationDocField(c *test.C) {
	query := Expr(map[string]interface{}{"a": 1}).Do(Row.Field("a"))

	var response int
	res, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = res.One(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, test.Equals, 1)
}

func (s *RethinkSuite) TestManipulationPluck(c *test.C) {
	query := Expr(map[string]interface{}{"a": 1, "b": 2, "c": 3}).Pluck("a", "c")

	var response map[string]interface{}
	res, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = res.One(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, jsonEquals, map[string]interface{}{"a": 1, "c": 3})
}

func (s *RethinkSuite) TestManipulationWithout(c *test.C) {
	query := Expr(map[string]interface{}{"a": 1, "b": 2, "c": 3}).Pluck("a", "c")

	var response map[string]interface{}
	res, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = res.One(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, jsonEquals, map[string]interface{}{"a": 1, "c": 3})
}

func (s *RethinkSuite) TestManipulationMerge(c *test.C) {
	query := Expr(map[string]interface{}{"a": 1, "c": 3}).Merge(map[string]interface{}{"b": 2})

	var response map[string]interface{}
	res, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = res.One(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, jsonEquals, map[string]interface{}{"a": 1, "b": 2, "c": 3})
}

func (s *RethinkSuite) TestManipulationMergeLiteral(c *test.C) {
	query := Expr(map[string]interface{}{
		"a": map[string]interface{}{
			"aa": map[string]interface{}{
				"aaa": 1,
				"aab": 2,
			},
			"ab": map[string]interface{}{
				"aba": 3,
				"abb": 4,
			},
		},
	}).Merge(map[string]interface{}{"a": map[string]interface{}{"ab": Literal()}})

	var response map[string]interface{}
	res, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = res.One(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, jsonEquals, map[string]interface{}{"a": map[string]interface{}{"aa": map[string]interface{}{"aab": 2, "aaa": 1}}})
}

func (s *RethinkSuite) TestManipulationAppend(c *test.C) {
	query := Expr([]interface{}{1, 2, 3}).Append(4).Append(5)

	var response []interface{}
	res, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = res.All(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, jsonEquals, []interface{}{1, 2, 3, 4, 5})
}

func (s *RethinkSuite) TestManipulationPrepend(c *test.C) {
	query := Expr([]interface{}{3, 4, 5}).Prepend(2).Prepend(1)

	var response []interface{}
	res, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = res.All(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, jsonEquals, []interface{}{1, 2, 3, 4, 5})
}

func (s *RethinkSuite) TestManipulationDifference(c *test.C) {
	query := Expr([]interface{}{3, 4, 5}).Difference([]interface{}{3, 4})

	var response []interface{}
	res, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = res.All(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, jsonEquals, []interface{}{5})
}

func (s *RethinkSuite) TestManipulationSetInsert(c *test.C) {
	query := Expr([]interface{}{1, 2, 3}).SetInsert(3).SetInsert(4)

	var response []interface{}
	res, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = res.All(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, jsonEquals, []interface{}{1, 2, 3, 4})
}

func (s *RethinkSuite) TestManipulationSetUnion(c *test.C) {
	query := Expr([]interface{}{1, 2, 3}).SetUnion([]interface{}{3, 4})

	var response []interface{}
	res, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = res.All(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, jsonEquals, []interface{}{1, 2, 3, 4})
}

func (s *RethinkSuite) TestManipulationSetIntersection(c *test.C) {
	query := Expr([]interface{}{1, 2, 3}).SetIntersection([]interface{}{2, 3, 3, 4})

	var response []interface{}
	res, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = res.All(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, jsonEquals, []interface{}{2, 3})
}

func (s *RethinkSuite) TestManipulationSetDifference(c *test.C) {
	query := Expr([]interface{}{1, 2, 3}).SetDifference([]interface{}{2, 3, 4, 4})

	var response []interface{}
	res, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = res.All(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, jsonEquals, []interface{}{1})
}

func (s *RethinkSuite) TestManipulationHasFieldsTrue(c *test.C) {
	query := Expr(map[string]interface{}{"a": 1}).HasFields("a")

	var response bool
	r, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = r.One(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, test.Equals, true)
}

func (s *RethinkSuite) TestManipulationHasFieldsNested(c *test.C) {
	query := Expr(map[string]interface{}{"a": map[string]interface{}{"b": 1}}).HasFields(map[string]interface{}{"a": map[string]interface{}{"b": true}})

	var response bool
	res, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = res.One(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, test.Equals, true)
}

func (s *RethinkSuite) TestManipulationHasFieldsNestedShort(c *test.C) {
	query := Expr(map[string]interface{}{"a": map[string]interface{}{"b": 1}}).HasFields(map[string]interface{}{"a": "b"})

	var response bool
	res, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = res.One(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, test.Equals, true)
}

func (s *RethinkSuite) TestManipulationHasFieldsFalse(c *test.C) {
	query := Expr(map[string]interface{}{"a": 1}).HasFields("b")

	var response bool
	res, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = res.One(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, test.Equals, false)
}

func (s *RethinkSuite) TestManipulationInsertAt(c *test.C) {
	query := Expr([]interface{}{1, 2, 3}).InsertAt(1, 1.5)

	var response []interface{}
	res, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = res.All(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, jsonEquals, []interface{}{1, 1.5, 2, 3})
}

func (s *RethinkSuite) TestManipulationSpliceAt(c *test.C) {
	query := Expr([]interface{}{1, 2, 3}).SpliceAt(1, []interface{}{1.25, 1.5, 1.75})

	var response []interface{}
	res, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = res.All(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, jsonEquals, []interface{}{1, 1.25, 1.5, 1.75, 2, 3})
}

func (s *RethinkSuite) TestManipulationDeleteAt(c *test.C) {
	query := Expr([]interface{}{1, 2, 3}).DeleteAt(1)

	var response []interface{}
	res, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = res.All(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, jsonEquals, []interface{}{1, 3})
}

func (s *RethinkSuite) TestManipulationDeleteAtRange(c *test.C) {
	query := Expr([]interface{}{1, 2, 3, 4}).DeleteAt(1, 3)

	var response []interface{}
	res, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = res.All(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, jsonEquals, []interface{}{1, 4})
}

func (s *RethinkSuite) TestManipulationChangeAt(c *test.C) {
	query := Expr([]interface{}{1, 5, 3, 4}).ChangeAt(1, 2)

	var response []interface{}
	res, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = res.All(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, jsonEquals, []interface{}{1, 2, 3, 4})
}

func (s *RethinkSuite) TestManipulationKeys(c *test.C) {
	query := Expr(map[string]interface{}{"a": 1, "b": 2, "c": 3}).Keys()

	var response []interface{}
	res, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = res.All(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, jsonEquals, []interface{}{"a", "b", "c"})
}

func (s *RethinkSuite) TestManipulationObject(c *test.C) {
	query := Object("a", 1, "b", 2)

	var response interface{}
	res, err := query.Run(sess)
	c.Assert(err, test.IsNil)

	err = res.One(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, jsonEquals, map[string]interface{}{
		"a": 1,
		"b": 2,
	})
}


text:
local uci = require "luci.model.uci".cursor()
local ipv =  uci:get_first("olsrd", "olsrd", "IpVersion", "4")

mh = Map("olsrd", translate("OLSR - HNA-Announcements"), translate("Hosts in a OLSR routed network can announce connecitivity " ..
	"to external networks using HNA messages."))

if ipv == "6and4" or ipv == "4" then
	hna4 = mh:section(TypedSection, "Hna4", translate("Hna4"), translate("Both values must use the dotted decimal notation."))
	hna4.addremove = true
	hna4.anonymous = true
	hna4.template  = "cbi/tblsection"

	net4 = hna4:option(Value, "netaddr", translate("Network address"))
	net4.datatype = "ip4addr"
	net4.placeholder = "10.11.12.13"
	net4.default = "10.11.12.13"
	msk4 = hna4:option(Value, "netmask", translate("Netmask"))
	msk4.datatype = "ip4addr"
	msk4.placeholder = "255.255.255.255"
	msk4.default = "255.255.255.255"
end

if ipv == "6and4" or ipv == "6" then
	hna6 = mh:section(TypedSection, "Hna6", translate("Hna6"), translate("IPv6 network must be given in full notation, " ..
		"prefix must be in CIDR notation."))
	hna6.addremove = true
	hna6.anonymous = true
	hna6.template  = "cbi/tblsection"

	net6 = hna6:option(Value, "netaddr", translate("Network address"))
	net6.datatype = "ip6addr"
	net6.placeholder = "fec0:2200:106:0:0:0:0:0"
	net6.default = "fec0:2200:106:0:0:0:0:0"
	msk6 = hna6:option(Value, "prefix", translate("Prefix"))
	msk6.datatype = "range(0,128)"
	msk6.placeholder = "128"
	msk6.default = "128"
end

return mh


text:
<?php

namespace Xentriq\Core\Engine\Parser;

class Argument
{
    private $name;

    private $value;

    private $literal;

    function __construct(string $name, $value = null, bool $literal = false)
    {
        $this->name = $name;
        $this->value = $value;
        $this->literal = $literal;
    }

    function setName($name)
    {
        $this->name = $name;
    }

    function getName()
    {
        return $this->name;
    }

    function setValue($value)
    {
        $this->value = $value;
    }

    function getValue()
    {
        return $this->value;
    }

    function setLiteral(bool $literal)
    {
        $this->literal = $literal;
    }

    function isLiteral(): bool
    {
        return $this->literal;
    }
}


text:
require 'test/unit'

class NodestroyedTest < Test::Unit::TestCase
  # Replace this with your real tests.
  def test_this_plugin
    flunk
  end
end


text:
package dpyl.eddy.nomorse.view;

import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;

import dpyl.eddy.nomorse.R;
import dpyl.eddy.nomorse.Utility;

import static dpyl.eddy.nomorse.Constants.STATE_ABOUT;
import static dpyl.eddy.nomorse.Constants.STATE_KEY;
import static dpyl.eddy.nomorse.Constants.STATE_SETTINGS;

public class DrawerActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private Integer state;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.AppTheme_NoActionBar);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drawer);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        Resources resources = getResources();
        Bitmap bitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher_round);
        bitmap = Bitmap.createScaledBitmap(bitmap, 300, 300, false);
        RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(resources, bitmap);
        roundedBitmapDrawable.setCornerRadius(Math.max(bitmap.getWidth(), bitmap.getHeight()));
        ImageView navHeader = navigationView.getHeaderView(0).findViewById(R.id.imageView_navHeader);
        navHeader.setImageDrawable(roundedBitmapDrawable);

        state = savedInstanceState != null ? savedInstanceState.getInt(STATE_KEY) : STATE_SETTINGS;
        navigationView.getMenu().getItem(state).setChecked(true);

        Fragment fragment;
        FragmentManager fragmentManager = getSupportFragmentManager();
        switch (state) {
            case STATE_SETTINGS:
                fragment = new SettingsFragment();
                setTitle(R.string.menu_settings);
                break;
            case STATE_ABOUT:
                fragment = new AboutFragment();
                setTitle(R.string.menu_about);
                break;
            default:
                fragment = new SettingsFragment();
                setTitle(R.string.menu_settings);
        } fragmentManager.beginTransaction().replace(R.id.content, fragment).commit();

        Utility.enableListener(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(STATE_KEY, state);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else super.onBackPressed();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_help, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem menuItem = menu.findItem(R.id.action_help);
        if (menuItem != null) {
            if (state == STATE_SETTINGS) menuItem.setVisible(true);
            else menuItem.setVisible(false);
        } return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_help) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(R.string.content_help_settings_message).setTitle(R.string.content_help_settings_title);
            builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.dismiss();
                }
            }); builder.create().show();
            return true;
        } return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        Fragment fragment = null;
        if (id == R.id.nav_manage) {
            state = STATE_SETTINGS;
            fragment = new SettingsFragment();
            setTitle(R.string.menu_settings);
        } else if (id == R.id.nav_about) {
            state = STATE_ABOUT;
            fragment = new AboutFragment();
            setTitle(R.string.menu_about);
        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content, fragment).commit();
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        invalidateOptionsMenu();
        return true;
    }
}


text:
#include <linux/netdevice.h>
#if defined(CONFIG_VLAN_8021Q) || defined(CONFIG_VLAN_8021Q_MODULE)
#define STMMAC_VLAN_TAG_USED
#include <linux/if_vlan.h>
#endif

#include "descs.h"
#include "mmc.h"

#undef CHIP_DEBUG_PRINT
/* Turn-on extra printk debug for MAC core, dma and descriptors */
/* #define CHIP_DEBUG_PRINT */

#ifdef CHIP_DEBUG_PRINT
#define CHIP_DBG(fmt, args...)  printk(fmt, ## args)
#else
#define CHIP_DBG(fmt, args...)  do { } while (0)
#endif

#undef FRAME_FILTER_DEBUG
/* #define FRAME_FILTER_DEBUG */

struct stmmac_extra_stats {
	/* Transmit errors */
	unsigned long tx_underflow ____cacheline_aligned;
	unsigned long tx_carrier;
	unsigned long tx_losscarrier;
	unsigned long vlan_tag;
	unsigned long tx_deferred;
	unsigned long tx_vlan;
	unsigned long tx_jabber;
	unsigned long tx_frame_flushed;
	unsigned long tx_payload_error;
	unsigned long tx_ip_header_error;
	/* Receive errors */
	unsigned long rx_desc;
	unsigned long sa_filter_fail;
	unsigned long overflow_error;
	unsigned long ipc_csum_error;
	unsigned long rx_collision;
	unsigned long rx_crc;
	unsigned long rx_length;
	unsigned long rx_mii;
	unsigned long rx_multicast;
	unsigned long rx_gmac_overflow;
	unsigned long rx_watchdog;
	unsigned long da_rx_filter_fail;
	unsigned long sa_rx_filter_fail;
	unsigned long rx_missed_cntr;
	unsigned long rx_overflow_cntr;
	unsigned long rx_vlan;
	/* Tx/Rx IRQ errors */
	unsigned long tx_undeflow_irq;
	unsigned long tx_process_stopped_irq;
	unsigned long tx_jabber_irq;
	unsigned long rx_overflow_irq;
	unsigned long rx_buf_unav_irq;
	unsigned long rx_process_stopped_irq;
	unsigned long rx_watchdog_irq;
	unsigned long tx_early_irq;
	unsigned long fatal_bus_error_irq;
	/* Extra info */
	unsigned long threshold;
	unsigned long tx_pkt_n;
	unsigned long rx_pkt_n;
	unsigned long poll_n;
	unsigned long sched_timer_n;
	unsigned long normal_irq_n;
};

#define HASH_TABLE_SIZE 64
#define PAUSE_TIME 0x200

/* Flow Control defines */
#define FLOW_OFF	0
#define FLOW_RX		1
#define FLOW_TX		2
#define FLOW_AUTO	(FLOW_TX | FLOW_RX)

#define SF_DMA_MODE 1 /* DMA STORE-AND-FORWARD Operation Mode */

/* DAM HW feature register fields */
#define DMA_HW_FEAT_MIISEL	0x00000001 /* 10/100 Mbps Support */
#define DMA_HW_FEAT_GMIISEL	0x00000002 /* 1000 Mbps Support */
#define DMA_HW_FEAT_HDSEL	0x00000004 /* Half-Duplex Support */
#define DMA_HW_FEAT_EXTHASHEN	0x00000008 /* Expanded DA Hash Filter */
#define DMA_HW_FEAT_HASHSEL	0x00000010 /* HASH Filter */
#define DMA_HW_FEAT_ADDMACADRSEL	0x00000020 /* Multiple MAC Addr Reg */
#define DMA_HW_FEAT_PCSSEL	0x00000040 /* PCS registers */
#define DMA_HW_FEAT_L3L4FLTREN	0x00000080 /* Layer 3 & Layer 4 Feature */
#define DMA_HW_FEAT_SMASEL	0x00000100 /* SMA(MDIO) Interface */
#define DMA_HW_FEAT_RWKSEL	0x00000200 /* PMT Remote Wakeup */
#define DMA_HW_FEAT_MGKSEL	0x00000400 /* PMT Magic Packet */
#define DMA_HW_FEAT_MMCSEL	0x00000800 /* RMON Module */
#define DMA_HW_FEAT_TSVER1SEL	0x00001000 /* Only IEEE 1588-2002 Timestamp */
#define DMA_HW_FEAT_TSVER2SEL	0x00002000 /* IEEE 1588-2008 Adv Timestamp */
#define DMA_HW_FEAT_EEESEL	0x00004000 /* Energy Efficient Ethernet */
#define DMA_HW_FEAT_AVSEL	0x00008000 /* AV Feature */
#define DMA_HW_FEAT_TXCOESEL	0x00010000 /* Checksum Offload in Tx */
#define DMA_HW_FEAT_RXTYP1COE	0x00020000 /* IP csum Offload(Type 1) in Rx */
#define DMA_HW_FEAT_RXTYP2COE	0x00040000 /* IP csum Offload(Type 2) in Rx */
#define DMA_HW_FEAT_RXFIFOSIZE	0x00080000 /* Rx FIFO > 2048 Bytes */
#define DMA_HW_FEAT_RXCHCNT	0x00300000 /* No. of additional Rx Channels */
#define DMA_HW_FEAT_TXCHCNT	0x00c00000 /* No. of additional Tx Channels */
#define DMA_HW_FEAT_ENHDESSEL	0x01000000 /* Alternate (Enhanced Descriptor) */
#define DMA_HW_FEAT_INTTSEN	0x02000000 /* Timestamping with Internal
					      System Time */
#define DMA_HW_FEAT_FLEXIPPSEN	0x04000000 /* Flexible PPS Output */
#define DMA_HW_FEAT_SAVLANINS	0x08000000 /* Source Addr or VLAN Insertion */
#define DMA_HW_FEAT_ACTPHYIF	0x70000000 /* Active/selected PHY interface */

enum rx_frame_status { /* IPC status */
	good_frame = 0,
	discard_frame = 1,
	csum_none = 2,
	llc_snap = 4,
};

enum tx_dma_irq_status {
	tx_hard_error = 1,
	tx_hard_error_bump_tc = 2,
	handle_tx_rx = 3,
};

/* DMA HW capabilities */
struct dma_features {
	unsigned int mbps_10_100;
	unsigned int mbps_1000;
	unsigned int half_duplex;
	unsigned int hash_filter;
	unsigned int multi_addr;
	unsigned int pcs;
	unsigned int sma_mdio;
	unsigned int pmt_remote_wake_up;
	unsigned int pmt_magic_frame;
	unsigned int rmon;
	/* IEEE 1588-2002*/
	unsigned int time_stamp;
	/* IEEE 1588-2008*/
	unsigned int atime_stamp;
	/* 802.3az - Energy-Efficient Ethernet (EEE) */
	unsigned int eee;
	unsigned int av;
	/* TX and RX csum */
	unsigned int tx_coe;
	unsigned int rx_coe_type1;
	unsigned int rx_coe_type2;
	unsigned int rxfifo_over_2048;
	/* TX and RX number of channels */
	unsigned int number_rx_channel;
	unsigned int number_tx_channel;
	/* Alternate (enhanced) DESC mode*/
	unsigned int enh_desc;
};

/* GMAC TX FIFO is 8K, Rx FIFO is 16K */
#define BUF_SIZE_16KiB 16384
#define BUF_SIZE_8KiB 8192
#define BUF_SIZE_4KiB 4096
#define BUF_SIZE_2KiB 2048

/* Power Down and WOL */
#define PMT_NOT_SUPPORTED 0
#define PMT_SUPPORTED 1

/* Common MAC defines */
#define MAC_CTRL_REG		0x00000000	/* MAC Control */
#define MAC_ENABLE_TX		0x00000008	/* Transmitter Enable */
#define MAC_RNABLE_RX		0x00000004	/* Receiver Enable */

struct stmmac_desc_ops {
	/* DMA RX descriptor ring initialization */
	void (*init_rx_desc) (struct dma_desc *p, unsigned int ring_size,
			      int disable_rx_ic);
	/* DMA TX descriptor ring initialization */
	void (*init_tx_desc) (struct dma_desc *p, unsigned int ring_size);

	/* Invoked by the xmit function to prepare the tx descriptor */
	void (*prepare_tx_desc) (struct dma_desc *p, int is_fs, int len,
				 int csum_flag);
	/* Set/get the owner of the descriptor */
	void (*set_tx_owner) (struct dma_desc *p);
	int (*get_tx_owner) (struct dma_desc *p);
	/* Invoked by the xmit function to close the tx descriptor */
	void (*close_tx_desc) (struct dma_desc *p);
	/* Clean the tx descriptor as soon as the tx irq is received */
	void (*release_tx_desc) (struct dma_desc *p);
	/* Clear interrupt on tx frame completion. When this bit is
	 * set an interrupt happens as soon as the frame is transmitted */
	void (*clear_tx_ic) (struct dma_desc *p);
	/* Last tx segment reports the transmit status */
	int (*get_tx_ls) (struct dma_desc *p);
	/* Return the transmit status looking at the TDES1 */
	int (*tx_status) (void *data, struct stmmac_extra_stats *x,
			  struct dma_desc *p, void __iomem *ioaddr);
	/* Get the buffer size from the descriptor */
	int (*get_tx_len) (struct dma_desc *p);
	/* Handle extra events on specific interrupts hw dependent */
	int (*get_rx_owner) (struct dma_desc *p);
	void (*set_rx_owner) (struct dma_desc *p);
	/* Get the receive frame size */
	int (*get_rx_frame_len) (struct dma_desc *p);
	/* Return the reception status looking at the RDES1 */
	int (*rx_status) (void *data, struct stmmac_extra_stats *x,
			  struct dma_desc *p);
};

struct stmmac_dma_ops {
	/* DMA core initialization */
	int (*init) (void __iomem *ioaddr, int pbl, u32 dma_tx, u32 dma_rx);
	/* Dump DMA registers */
	void (*dump_regs) (void __iomem *ioaddr);
	/* Set tx/rx threshold in the csr6 register
	 * An invalid value enables the store-and-forward mode */
	void (*dma_mode) (void __iomem *ioaddr, int txmode, int rxmode);
	/* To track extra statistic (if supported) */
	void (*dma_diagnostic_fr) (void *data, struct stmmac_extra_stats *x,
				   void __iomem *ioaddr);
	void (*enable_dma_transmission) (void __iomem *ioaddr);
	void (*enable_dma_irq) (void __iomem *ioaddr);
	void (*disable_dma_irq) (void __iomem *ioaddr);
	void (*start_tx) (void __iomem *ioaddr);
	void (*stop_tx) (void __iomem *ioaddr);
	void (*start_rx) (void __iomem *ioaddr);
	void (*stop_rx) (void __iomem *ioaddr);
	int (*dma_interrupt) (void __iomem *ioaddr,
			      struct stmmac_extra_stats *x);
	/* If supported then get the optional core features */
	unsigned int (*get_hw_feature) (void __iomem *ioaddr);
};

struct stmmac_ops {
	/* MAC core initialization */
	void (*core_init) (void __iomem *ioaddr) ____cacheline_aligned;
	/* Support checksum offload engine */
	int  (*rx_coe) (void __iomem *ioaddr);
	/* Dump MAC registers */
	void (*dump_regs) (void __iomem *ioaddr);
	/* Handle extra events on specific interrupts hw dependent */
	void (*host_irq_status) (void __iomem *ioaddr);
	/* Multicast filter setting */
	void (*set_filter) (struct net_device *dev);
	/* Flow control setting */
	void (*flow_ctrl) (void __iomem *ioaddr, unsigned int duplex,
			   unsigned int fc, unsigned int pause_time);
	/* Set power management mode (e.g. magic frame) */
	void (*pmt) (void __iomem *ioaddr, unsigned long mode);
	/* Set/Get Unicast MAC addresses */
	void (*set_umac_addr) (void __iomem *ioaddr, unsigned char *addr,
			       unsigned int reg_n);
	void (*get_umac_addr) (void __iomem *ioaddr, unsigned char *addr,
			       unsigned int reg_n);
};

struct mac_link {
	int port;
	int duplex;
	int speed;
};

struct mii_regs {
	unsigned int addr;	/* MII Address */
	unsigned int data;	/* MII Data */
};

struct stmmac_ring_mode_ops {
	unsigned int (*is_jumbo_frm) (int len, int ehn_desc);
	unsigned int (*jumbo_frm) (void *priv, struct sk_buff *skb, int csum);
	void (*refill_desc3) (int bfsize, struct dma_desc *p);
	void (*init_desc3) (int des3_as_data_buf, struct dma_desc *p);
	void (*init_dma_chain) (struct dma_desc *des, dma_addr_t phy_addr,
				unsigned int size);
	void (*clean_desc3) (struct dma_desc *p);
	int (*set_16kib_bfsize) (int mtu);
};

struct mac_device_info {
	const struct stmmac_ops		*mac;
	const struct stmmac_desc_ops	*desc;
	const struct stmmac_dma_ops	*dma;
	const struct stmmac_ring_mode_ops	*ring;
	struct mii_regs mii;	/* MII register Addresses */
	struct mac_link link;
	unsigned int synopsys_uid;
};

struct mac_device_info *dwmac1000_setup(void __iomem *ioaddr);
struct mac_device_info *dwmac100_setup(void __iomem *ioaddr);

extern void stmmac_set_mac_addr(void __iomem *ioaddr, u8 addr[6],
				unsigned int high, unsigned int low);
extern void stmmac_get_mac_addr(void __iomem *ioaddr, unsigned char *addr,
				unsigned int high, unsigned int low);
extern void dwmac_dma_flush_tx_fifo(void __iomem *ioaddr);
extern const struct stmmac_ring_mode_ops ring_mode_ops;


text:
class InterfereFile {
  // This file will print at least 82 * delay milliseconds
}


text:
AJS.$(function () {
    require([
        'bitbucket-invite-message-panel-view'
    ], function (
        Panel
    )
    {
        "use strict";

        new Panel({
            jiraSoftwareCheckboxSelector: '.application-picker-applications .checkbox input.application-jira-software',
            el: 'div#bitbucket-invite-message-panel'
        });

    });
})


text:
module.exports = function() {
    var package = require("../../package.json");
    return package.version;
}


text:
(function () {
  'use strict';

  angular.module('pnc.common.components').component('pncCorruptedBuildRecordLabel', {
    bindings: {

      /**
       * Object: a BuildRecord object to display it's corrupted status.
       */
      buildRecord: '<'
    },
    templateUrl: 'common/components/pnc-corrupted-build-record-label/pnc-corrupted-build-record-label.html',
    controller: [Controller]
  });

  function Controller() {
    var $ctrl = this;

    // -- Controller API --

    $ctrl.isCorrupted = isCorrupted;

    // --------------------

    function isCorrupted() {
      var attrs = $ctrl.buildRecord.attributes;

      return attrs && (
        attrs.POST_BUILD_REPO_VALIDATION === 'REPO_SYSTEM_ERROR' ||
        attrs.PNC_SYSTEM_ERROR           === 'DISABLED_FIREWALL'
      );
    }
  }

})();


text:
<?php

namespace app\migrations;

use yii\db\Migration;

/**
 * Initializes tables.
 *
 * @author Dmitry Naumenko <d.naumenko.a@gmail.com>
 */
class m170618_000000_db_init extends Migration
{
    public function up()
    {
        $this->createTable('article', [
            'id' => $this->primaryKey(),
            'title' => $this->string(),
            'text' => $this->text(),
        ]);

        $this->createTable('tag', [
            'id' => $this->primaryKey(),
            'name' => $this->string(),
        ]);

        $this->createTable('article_tags', [
            'article_id' => $this->integer(),
            'tag_id' => $this->integer(),
        ]);
    }

    public function down()
    {
        $this->dropTable('article');
        $this->dropTable('tag');
        $this->dropTable('article_tags');
    }
}


text:
namespace TweetSharp
{
    /// <summary>
    ///     Used for Twitter searches where it takes a geocode paramater
    /// </summary>
    public class TwitterGeoLocationSearch : TwitterGeoLocation
    {
        /// <summary>
        /// Radius type in Miles or Kilometers
        /// </summary>
        public enum RadiusType
        {
            Mi,
            Km
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="TwitterGeoLocationSearch"/> struct.
        /// </summary>
        public TwitterGeoLocationSearch()
        {
        }

        /// <summary>
        /// /// <summary>
        /// Initializes a new instance of the <see cref="TwitterGeoLocation"/> struct.
        /// </summary>
        /// </summary>
        /// <param name="latitutde">The latitude of search location.</param>
        /// <param name="longitude">The longitude of search location.</param>
        /// <param name="radius">The radius of search location.</param>
        /// <param name="unitOfMeasurement">The unit of measurement (Mi or Km).</param>
        public TwitterGeoLocationSearch(double latitutde, double longitude, int radius, RadiusType unitOfMeasurement)
            : base(latitutde, longitude)
        {
            Radius = radius;
            UnitOfMeasurement = unitOfMeasurement;
        }

        /// <summary>
        ///     Radius in specified <see cref="RadiusType" />
        /// </summary>
        /// <seealso cref="UnitOfMeasurement" />
        public int Radius { get; set; }

        public RadiusType UnitOfMeasurement { get; set; }

        public override string ToString()
        {
            return string.Format("{0},{1},{2}{3}", Coordinates.Latitude, Coordinates.Longitude, Radius,
                                 UnitOfMeasurement.ToString().ToLower());
        }
    }
}


text:
**Note that other versions of Fedora are not supported at this time.**

To install Plaso and dependencies from the GIFT Cool Other Package Repo (COPR) you'll need to have dnf plugins installed:

```
sudo dnf install dnf-plugins-core
```

Add the [GIFT COPR](https://copr.fedorainfracloud.org/groups/g/gift/coprs/) to your dnf configuration:

```
sudo dnf copr enable @gift/stable
```

Install Plaso, tools and dependencies:

```
sudo dnf install plaso-tools
```


text:
#ifndef __COLLATIONCOMPARE_H__
#define __COLLATIONCOMPARE_H__

#include "unicode/utypes.h"

#if !UCONFIG_NO_COLLATION

#include "unicode/ucol.h"

U_NAMESPACE_BEGIN

class CollationIterator;
struct CollationSettings;

class U_I18N_API CollationCompare /* not : public UObject because all methods are static */ {
public:
    static UCollationResult compareUpToQuaternary(CollationIterator &left, CollationIterator &right,
                                                  const CollationSettings &settings,
                                                  UErrorCode &errorCode);
};

U_NAMESPACE_END

#endif  // !UCONFIG_NO_COLLATION
#endif  // __COLLATIONCOMPARE_H__


text:
from nova.openstack.common import log as logging
from nova.scheduler import filters

LOG = logging.getLogger(__name__)

class PciPassthroughFilter(filters.BaseHostFilter):
    """Pci Passthrough Filter based on PCI request

    Filter that schedules instances on a host if the host has devices
    to meet the device requests in the 'extra_specs' for the flavor.

    PCI resource tracker provides updated summary information about the
    PCI devices for each host, like::

        | [{"count": 5, "vendor_id": "8086", "product_id": "1520",
        |   "extra_info":'{}'}],

    and VM requests PCI devices via PCI requests, like::

        | [{"count": 1, "vendor_id": "8086", "product_id": "1520",}].

    The filter checks if the host passes or not based on this information.

    """

    def host_passes(self, host_state, filter_properties):
        """Return true if the host has the required PCI devices."""
        pci_requests = filter_properties.get('pci_requests')
        if not pci_requests:
            return True
        if not host_state.pci_stats.support_requests(pci_requests.requests):
            LOG.debug("%(host_state)s doesn't have the required PCI devices"
                      " (%(requests)s)",
                      {'host_state': host_state, 'requests': pci_requests})
            return False
        return True


text:
import utils as utils
import tensorflow as tf

"""
  Free parameters to control the synthesis
"""
MAX_SIGMA = 50  # convert shadow from hard --> soft
INT_SIGMA = 0.5  # how mnuch intensity variation: 1 --> no variation; 0 --> intense variation
TONE_SIGMA = 0.1  # tone curve jitter: if set to None --> no color jitter
SS_SIGMA = 0.5  # probability to apply ss approximation: 1 --> not apply; 0 --> always apply

"""
  Data loader
"""
def decode_line_foreign_wild(line):
  """Decode the line to tensor. Foreign shadow generation using images in the wild. Each line has 7 fields."""
  data_dict = {}
  record_defaults = [''] * 7
  items = tf.io.decode_csv(line, record_defaults, field_delim=',')
  data_dict['image_path'] = items[0]
  data_dict['silhouette_path'] = items[2]
  data_dict['bbox'] = [tf.strings.to_number(items[3], tf.float32),
                       tf.strings.to_number(items[4], tf.float32),
                       tf.strings.to_number(items[5], tf.float32),
                       tf.strings.to_number(items[6], tf.float32)]

  data_dict['shadowed_before'] = utils.read_float(items[0], channel=3, itype='jpg', is_linear=True)
  data_dict['segmentation'] = utils.read_float(items[1], channel=1, itype='png', is_linear=False)
  data_dict['silhouette'] = utils.read_float(items[2], channel=1, itype='png', is_linear=False)

  return data_dict

def read_bbox(txt_path):
  """Read face bbox into a list for a given .txt path."""
  bboxs = []
  with open(txt_path, 'r') as f:
    lines = f.readlines()
    for bbox in lines:
      bboxs.append([int(float(x)) for x in bbox.strip().split(',')])
  return bboxs

def prepare_train_foreign_wild(
    data_dict, size, is_train=True):
  """Prepare training data from images in the wild."""
  out_dict = {}
  out_dict['image_path'] = data_dict['image_path']

  if is_train:  # random resize the image during training
    rsz_ratio = tf.random.uniform(shape=(), minval=0.8, maxval=1.2, dtype=tf.float32)
  else:
    rsz_ratio = tf.constant(1., dtype=tf.float32)
  image_concat = tf.concat([data_dict['shadowed_before'], data_dict['segmentation']], axis=2)

  bbox = data_dict['bbox']
  processed_images, process_params = align_images_and_segmentation(
  	image_concat, size=size, bbox=bbox, rsz=rsz_ratio, param_save=True, is_train=True)

  shadow_lit_image = processed_images[..., :3]
  segmentation = processed_images[..., -1:]

  curve_gain = 0.5 + tf.random.uniform([3], -TONE_SIGMA, TONE_SIGMA, tf.float32)
  shadow_occl_image = utils.apply_tone_curve(shadow_lit_image, gain=curve_gain, is_rgb=True)
  color_matrix = utils.get_ctm_ls(shadow_lit_image, shadow_occl_image)
  shadow_occl_image = utils.apply_ctm(shadow_occl_image, color_matrix)

  # Create a shadow map, randomly choosing between using perlin noise or a random silhouette image
  shadow_mask_hard = 1- data_dict['silhouette']
  shadow_mask_hard = tf.cond(
      tf.greater(tf.random.uniform([]), tf.constant(0.5)),
      lambda: utils.render_perlin_mask(size=size),
      lambda: utils.render_silhouette_mask(
          silhouette=shadow_mask_hard,
          size=size,
          segmentation=segmentation))
  shadow_mask_hard_inv = 1 - shadow_mask_hard

  # Randomly apply ss approximation
  prob_apply_ss = tf.random.uniform([])
  shadow_mask_ss = tf.cond(
    tf.greater(prob_apply_ss, tf.constant(SS_SIGMA)),
    lambda: utils.apply_ss_shadow_map(shadow_mask_hard),
    lambda: tf.image.grayscale_to_rgb(shadow_mask_hard))
  shadow_mask_ss_inv = 1 - shadow_mask_ss

  # Apply intensity variation
  intensity_mask = utils.get_brightness_mask(size=size, min_val=INT_SIGMA)
  shadow_mask_sv = shadow_mask_ss_inv * tf.expand_dims(intensity_mask, 2)

  # Apply shadow mask to image
  shadow_hard_image = shadow_mask_sv * shadow_occl_image + shadow_mask_ss * shadow_lit_image
  input_shadowed_hard = ((shadow_hard_image * 2) - 1) * segmentation
  image_concat = tf.concat(
      [input_shadowed_hard, shadow_lit_image, shadow_occl_image, shadow_mask_hard, segmentation], axis=2)

  if is_train:
    image_concat = utils.apply_geometric_augmentation(image_concat)

  segmentation = image_concat[..., -1:]
  out_dict['shadowed_hard'] = image_concat[..., :3]  # input_shadowed_hard
  out_dict['shadowed_before'] = ((image_concat[..., 3:6] * 2) - 1) * segmentation  # shadow_lit_image
  out_dict['shadowed_after'] = ((image_concat[..., -7:-4] * 2) - 1) * segmentation  # shadow_occl_image
  out_dict['shadow_mask'] = image_concat[..., -4:-1]  # shadow_mask_hard
  out_dict['segmentation'] = segmentation  # segmentation
  return out_dict

def align_images_and_segmentation(images, size, bbox, rsz=1., param_save=False, is_train=True):
  """Apply the same resize / crop to a batch of images with face alignment using the input face bbox."""
  with tf.name_scope('align_img_seg'):
    out_params = dict()
    if is_train:  # insert some uncertainty during training
      golden_ratio = tf.random.uniform(
          shape=(), minval=0.75, maxval=0.85, dtype=tf.float32)
    else:
      golden_ratio = 0.8  # roughly align faces to the center, heuristic number
    w = bbox[2]
    h = bbox[3]
    target_h = size[0]
    target_w = size[1]
    resize_ratio = (target_w * golden_ratio) / (w) * rsz
    out_params['resize_ratio'] = resize_ratio
    image_resize = utils.resize_image(images, rsz=resize_ratio)
    out_params['resize_height'] = tf.shape(image_resize)[0]
    out_params['resize_width'] = tf.shape(image_resize)[1]
    yhstart = tf.cast(((bbox[1] + h/2) * resize_ratio) - target_h/2, tf.int32)
    xwstart = tf.cast(((bbox[0] + w/2) * resize_ratio) - target_w/2, tf.int32)
    out_params['pad_offset_height'] = tf.maximum(0, -yhstart+1)
    out_params['pad_offset_width'] = tf.maximum(0, -xwstart+1)
    out_params['pad_target_height'] = tf.maximum(target_h, tf.shape(image_resize)[0] + tf.maximum(yhstart, 0)) + tf.maximum(0, -yhstart+1)
    out_params['pad_target_width'] = tf.maximum(target_w, tf.shape(image_resize)[1] + tf.maximum(xwstart, 0)) + tf.maximum(0, -xwstart+1)
    image_resize = tf.image.pad_to_bounding_box(
        image_resize,
        tf.maximum(0, -yhstart+1),
        tf.maximum(0, -xwstart+1),
        tf.maximum(target_h, tf.shape(image_resize)[0] + tf.maximum(yhstart, 0)) + tf.maximum(0, -yhstart+1),
        tf.maximum(target_w, tf.shape(image_resize)[1] + tf.maximum(xwstart, 0)) + tf.maximum(0, -xwstart+1))
    out_params['crop_offset_height'] = tf.maximum(yhstart, 0)
    out_params['crop_offset_width'] = tf.maximum(xwstart, 0)
    out_params['crop_target_height'] = target_h
    out_params['crop_target_width'] = target_w
    processed_images = tf.image.crop_to_bounding_box(
        image_resize,
        tf.maximum(yhstart, 0),
        tf.maximum(xwstart, 0),
        target_h,
        target_w)
  if param_save:
    return processed_images, out_params
  return processed_images

def input_fn(
    dataset_name,
    train_txt_paths,
    eval_txt_paths,
    is_train=True,
    image_size=(512, 512),
    batch_size=4,
    seed=None,
    n_interleave_workers=12,
    n_map_workers=12,
    shuffle_buffer_size=64):
  """Input function for training and eval parallel I/O.
  """

  with tf.name_scope('data-prep-%s'%(dataset_name)):
    if dataset_name == 'wild':
      decode_fn = decode_line_foreign_wild
      data_process_fn = prepare_train_foreign_wild
    else:
      raise NotImplementedError('Unknown dataset ', dataset_name)

  if is_train:
    with tf.name_scope('data-train-%s'%(dataset_name)):
      next_batch = _input_fn(
          decode_fn=decode_fn,
          is_train=True,
          dataset_txt_paths=train_txt_paths,
          image_size=image_size,
          batch_size=batch_size,
          seed=seed,
          process_fn=data_process_fn,
          n_interleave_workers=n_interleave_workers,
          n_map_workers=n_map_workers,
          shuffle_buffer_size=shuffle_buffer_size,
          )
  else:
    with tf.name_scope('data-eval-%s'%(dataset_name)):
      next_batch = _input_fn(
          decode_fn=decode_fn,
          is_train=False,
          dataset_txt_paths=eval_txt_paths,
          image_size=image_size,
          batch_size=batch_size,
          seed=seed,
          process_fn=data_process_fn,
          n_interleave_workers=n_interleave_workers,
          n_map_workers=n_map_workers,
          shuffle_buffer_size=shuffle_buffer_size,
          )
  return next_batch

def _input_fn(
    decode_fn,
    process_fn,
    is_train=True,
    dataset_txt_paths=[''],
    image_size=(512, 512),
    batch_size=4,
    seed=None,
    n_interleave_workers=12,
    n_map_workers=12,
    shuffle_buffer_size=64):

  """Customized input func with different decoding and processing functions.
  """

  dataset = (tf.data.Dataset.from_tensor_slices(dataset_txt_paths)
             .interleave(
                 lambda x: tf.data.TextLineDataset(x).map(
                     decode_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE),
                 cycle_length=tf.data.experimental.AUTOTUNE))

  # Parallelize processing and ignore errors
  dataset = dataset.map(
      lambda v: process_fn(v, image_size, is_train),
      num_parallel_calls=tf.data.experimental.AUTOTUNE)
  dataset = dataset.apply(tf.data.experimental.ignore_errors())

  # Shuffle
  if is_train:
    dataset = dataset.shuffle(shuffle_buffer_size, seed=seed)
  dataset = dataset.repeat()

  # Batching
  dataset = dataset.batch(batch_size=batch_size, drop_remainder=True)

  # Preprocessing on CPU while computing a training step
  dataset = dataset.prefetch(buffer_size=8)
  return dataset.make_one_shot_iterator().get_next()


text:
shared_examples_for 'Delayed::Worker' do
  def job_create(opts = {})
    Delayed::Job.create({:payload_object => SimpleJob.new, :queue => Delayed::Settings.queue}.merge(opts))
  end
  def worker_create(opts = {})
    Delayed::Worker.new(opts.merge(:max_priority => nil, :min_priority => nil, :quiet => true))
  end

  before(:each) do
    @worker = worker_create
    SimpleJob.runs = 0
    Delayed::Worker.on_max_failures = nil
    Delayed::Settings.sleep_delay = ->{ 0.01 }
  end

  after do
    Delayed::Settings.sleep_delay = 2.0
  end

  describe "running a job" do
    it "should not fail when running a job with a % in the name" do
      @job = "Some % Name here".send_later_enqueue_args(:starts_with?, { no_delay: true }, "Some % Name")
      @worker.perform(@job)
    end
  end

  describe "running a batch" do
    context "serially" do
      before do
        @runs = 0
        Delayed::Worker.lifecycle.after(:perform) { @runs += 1 }
      end

      after do
        Delayed::Worker.lifecycle.reset!
      end

      it "should run each job in order" do
        bar = "bar"
        expect(bar).to receive(:scan).with("b").ordered
        expect(bar).to receive(:scan).with("a").ordered
        expect(bar).to receive(:scan).with("r").ordered
        batch = Delayed::Batch::PerformableBatch.new(:serial, [
          { :payload_object => Delayed::PerformableMethod.new(bar, :scan, ["b"]) },
          { :payload_object => Delayed::PerformableMethod.new(bar, :scan, ["a"]) },
          { :payload_object => Delayed::PerformableMethod.new(bar, :scan, ["r"]) },
        ])

        batch_job = Delayed::Job.create :payload_object => batch
        @worker.perform(batch_job).should == 3
        expect(@runs).to eql 4 # batch, plus all jobs
      end

      it "should succeed regardless of the success/failure of its component jobs" do
        change_setting(Delayed::Settings, :max_attempts, 2) do
          batch = Delayed::Batch::PerformableBatch.new(:serial, [
            { :payload_object => Delayed::PerformableMethod.new("foo", :reverse, []) },
            { :payload_object => Delayed::PerformableMethod.new(1, :/, [0]) },
            { :payload_object => Delayed::PerformableMethod.new("bar", :scan, ["r"]) },
          ])
          batch_job = Delayed::Job.create :payload_object => batch

          @worker.perform(batch_job).should == 3
          expect(@runs).to eql 3 # batch, plus two successful jobs

          to_retry = Delayed::Job.list_jobs(:future, 100)
          to_retry.size.should eql 1
          to_retry[0].payload_object.method.should eql :/
          to_retry[0].last_error.should =~ /divided by 0/
          to_retry[0].attempts.should == 1
        end
      end

      it "should retry a failed individual job" do
        batch = Delayed::Batch::PerformableBatch.new(:serial, [
          { :payload_object => Delayed::PerformableMethod.new(1, :/, [0]) },
        ])
        batch_job = Delayed::Job.create :payload_object => batch

        expect_any_instance_of(Delayed::Job).to receive(:reschedule).once
        @worker.perform(batch_job).should == 1
        expect(@runs).to eql 1 # just the batch
      end
    end
  end

  context "worker prioritization" do
    before(:each) do
      @worker = Delayed::Worker.new(:max_priority => 5, :min_priority => 2, :quiet => true)
    end

    it "should only run jobs that are >= min_priority" do
      SimpleJob.runs.should == 0

      job_create(:priority => 1)
      job_create(:priority => 3)
      @worker.run

      SimpleJob.runs.should == 1
    end

    it "should only run jobs that are <= max_priority" do
      SimpleJob.runs.should == 0

      job_create(:priority => 10)
      job_create(:priority => 4)

      @worker.run

      SimpleJob.runs.should == 1
    end
  end

  context "while running with locked jobs" do
    it "should not run jobs locked by another worker" do
      job_create(:locked_by => 'other_worker', :locked_at => (Delayed::Job.db_time_now - 1.minutes))
      lambda { @worker.run }.should_not change { SimpleJob.runs }
    end

    it "should run open jobs" do
      job_create
      lambda { @worker.run }.should change { SimpleJob.runs }.from(0).to(1)
    end
  end

  describe "failed jobs" do
    before do
      # reset defaults
      Delayed::Settings.max_attempts = 25
      @job = Delayed::Job.enqueue ErrorJob.new
    end

    it "should record last_error when destroy_failed_jobs = false, max_attempts = 1" do
      Delayed::Worker.on_max_failures = proc { false }
      @job.max_attempts = 1
      @job.save!
      (job = Delayed::Job.get_and_lock_next_available('w1')).should == @job
      @worker.perform(job)
      old_id = @job.id
      @job = Delayed::Job.list_jobs(:failed, 1).first
      @job.original_job_id.should == old_id
      @job.last_error.should =~ /did not work/
      @job.last_error.should =~ /shared\/worker.rb/
      @job.attempts.should == 1
      @job.failed_at.should_not be_nil
      @job.run_at.should > Delayed::Job.db_time_now - 10.minutes
      @job.run_at.should < Delayed::Job.db_time_now + 10.minutes
      # job stays locked after failing, for record keeping of time/worker
      @job.should be_locked

      Delayed::Job.find_available(100, @job.queue).should == []
    end

    it "should re-schedule jobs after failing" do
      @worker.perform(@job)
      @job = Delayed::Job.find(@job.id)
      @job.last_error.should =~ /did not work/
      @job.last_error.should =~ /sample_jobs.rb:8:in `perform'/
      @job.attempts.should == 1
      @job.run_at.should > Delayed::Job.db_time_now - 10.minutes
      @job.run_at.should < Delayed::Job.db_time_now + 10.minutes
    end

    it "should accept :unlock return value from on_failure during reschedule and unlock the job" do
      expect_any_instance_of(Delayed::Job).to receive(:unlock).once
      @job = Delayed::Job.enqueue(UnlockJob.new(1))
      @worker.perform(@job)
    end

    it "should notify jobs on failure" do
      ErrorJob.failure_runs = 0
      @worker.perform(@job)
      ErrorJob.failure_runs.should == 1
    end

    it "should notify jobs on permanent failure" do
      (Delayed::Settings.max_attempts - 1).times { @job.reschedule }
      ErrorJob.permanent_failure_runs = 0
      @worker.perform(@job)
      ErrorJob.permanent_failure_runs.should == 1
    end
  end

  context "reschedule" do
    before do
      @job = Delayed::Job.create :payload_object => SimpleJob.new
    end

    context "and we want to destroy jobs" do
      it "should be destroyed if it failed more than Settings.max_attempts times" do
        expect(@job).to receive(:destroy)
        Delayed::Settings.max_attempts.times { @job.reschedule }
      end

      it "should not be destroyed if failed fewer than Settings.max_attempts times" do
        expect(@job).to receive(:destroy).never
        (Delayed::Settings.max_attempts - 1).times { @job.reschedule }
      end

      it "should be destroyed if failed more than Job#max_attempts times" do
        Delayed::Settings.max_attempts = 25
        expect(@job).to receive(:destroy)
        @job.max_attempts = 2
        @job.save!
        2.times { @job.reschedule }
      end

      it "should be destroyed if it has expired" do
        job = Delayed::Job.create :payload_object => SimpleJob.new, :expires_at => Delayed::Job.db_time_now - 1.day
        expect(job).to receive(:destroy)
        job.reschedule
      end
    end

    context "and we don't want to destroy jobs" do
      before do
        Delayed::Worker.on_max_failures = proc { false }
      end

      after do
        Delayed::Worker.on_max_failures = nil
      end

      it "should be failed if it failed more than Settings.max_attempts times" do
        @job.failed_at.should == nil
        Delayed::Settings.max_attempts.times { @job.reschedule }
        Delayed::Job.list_jobs(:failed, 100).size.should == 1
      end

      it "should not be failed if it failed fewer than Settings.max_attempts times" do
        (Delayed::Settings.max_attempts - 1).times { @job.reschedule }
        @job = Delayed::Job.find(@job.id)
        @job.failed_at.should == nil
      end

      it "should be failed if it has expired" do
        job = Delayed::Job.create :payload_object => SimpleJob.new, :expires_at => Delayed::Job.db_time_now - 1.day
        expect(job).to receive(:fail!)
        job.reschedule
      end
    end

    context "and we give an on_max_failures callback" do
      it "should be failed max_attempts times and cb is false" do
        Delayed::Worker.on_max_failures = proc do |job, ex|
          job.should == @job
          false
        end
        expect(@job).to receive(:fail!)
        Delayed::Settings.max_attempts.times { @job.reschedule }
      end

      it "should be destroyed if it failed max_attempts times and cb is true" do
        Delayed::Worker.on_max_failures = proc do |job, ex|
          job.should == @job
          true
        end
        expect(@job).to receive(:destroy)
        Delayed::Settings.max_attempts.times { @job.reschedule }
      end
    end
  end

  context "Queue workers" do
    before :each do
      Delayed::Settings.queue = "Queue workers test"
      job_create(:queue => 'queue1')
      job_create(:queue => 'queue2')
    end

    it "should only work off jobs assigned to themselves" do
      worker = worker_create(:queue=>'queue1')
      SimpleJob.runs.should == 0
      worker.run
      SimpleJob.runs.should == 1

      SimpleJob.runs = 0

      worker = worker_create(:queue=>'queue2')
      SimpleJob.runs.should == 0
      worker.run
      SimpleJob.runs.should == 1
    end

    it "should not work off jobs not assigned to themselves" do
      worker = worker_create(:queue=>'queue3')

      SimpleJob.runs.should == 0
      worker.run
      SimpleJob.runs.should == 0
    end

    it "should get the default queue if none is set" do
      queue_name = "default_queue"
      Delayed::Settings.queue = queue_name
      worker = worker_create(:queue=>nil)
      worker.queue_name.should == queue_name
    end

    it "should override default queue name if specified in initialize" do
      queue_name = "my_queue"
      Delayed::Settings.queue = "default_queue"
      worker = worker_create(:queue=>queue_name)
      worker.queue_name.should == queue_name
    end
  end

  context "plugins" do
    class TestPlugin < ::Delayed::Plugin
      cattr_accessor :runs
      self.runs = 0
      callbacks do |lifecycle|
        lifecycle.around(:invoke_job) do |job, *args, &block|
          TestPlugin.runs += 1
          block.call(job, *args)
        end
      end
    end

    it "should create and call the plugin callbacks" do
      TestPlugin.runs = 0
      Delayed::Worker.plugins << TestPlugin
      job_create
      @worker = Delayed::Worker.new(:quiet => true)
      @worker.run
      expect(TestPlugin.runs).to eq(1)
      expect(SimpleJob.runs).to eq(1)
    end
  end

  describe "expires_at" do
    it "should run non-expired jobs" do
      Delayed::Job.enqueue SimpleJob.new, :expires_at => Delayed::Job.db_time_now + 1.day
      expect { @worker.run }.to change { SimpleJob.runs }.by(1)
    end

    it "should not run expired jobs" do
      Delayed::Job.enqueue SimpleJob.new, :expires_at => Delayed::Job.db_time_now - 1.day
      expect { @worker.run }.to change { SimpleJob.runs }.by(0)
    end

    it "should report a permanent failure when an expired job is dequeued" do
      ErrorJob.last_error = nil
      Delayed::Job.enqueue ErrorJob.new, :expires_at => Delayed::Job.db_time_now - 1.day
      expect { @worker.run }.to change { ErrorJob.permanent_failure_runs }.by(1)
      expect(ErrorJob.last_error).to be_a Delayed::Backend::JobExpired
    end
  end

  describe "send_later_enqueue_args failure callbacks" do
    it "should call the on_failure callback" do
      ErrorJob.last_error = nil
      ErrorJob.new.send_later_enqueue_args(:perform, :max_attempts => 2, :on_failure => :on_failure)
      expect { @worker.run }.to change { ErrorJob.failure_runs }.by(1)
      expect(ErrorJob.last_error.to_s).to eq 'did not work'
    end

    it "should call the on_permanent_failure callback" do
      ErrorJob.last_error = nil
      ErrorJob.new.send_later_enqueue_args(:perform, :max_attempts => 1, :on_permanent_failure => :on_failure)
      expect { @worker.run }.to change { ErrorJob.failure_runs }.by(1)
      expect(ErrorJob.last_error.to_s).to eq 'did not work'
    end
  end

  describe "custom deserialization errors" do
    it "should reschedule with more attempts left" do
      job = Delayed::Job.create({:payload_object => DeserializeErrorJob.new, max_attempts: 2})
      job.instance_variable_set("@payload_object", nil)
      worker = Delayed::Worker.new(:max_priority => nil, :min_priority => nil, :quiet => true)
      expect { worker.perform(job) }.not_to raise_error
    end

    it "run permanent failure code on last attempt" do
      job = Delayed::Job.create({:payload_object => DeserializeErrorJob.new, max_attempts: 1})
      job.instance_variable_set("@payload_object", nil)
      worker = Delayed::Worker.new(:max_priority => nil, :min_priority => nil, :quiet => true)
      expect { worker.perform(job) }.not_to raise_error
    end
  end

  describe "#start" do
    it "fires off an execute callback on the processing jobs loop" do
      fired = false
      expect(@worker).to receive(:exit?).and_return(true)
      Delayed::Worker.lifecycle.before(:execute) { |w| w == @worker && fired = true }
      @worker.start
      expect(fired).to eq(true)
    end
  end

  describe "#run" do
    it "fires off a loop callback on each call to run" do
      fired = 0
      Delayed::Worker.lifecycle.before(:loop) { |w| w == @worker && fired += 1 }
      expect(Delayed::Job).to receive(:get_and_lock_next_available).twice.and_return(nil)
      @worker.run
      @worker.run
      expect(fired).to eq(2)
    end
  end
end


text:
mkdir -p /usr/lib/edison_config_tools
cp -r public /usr/lib/edison_config_tools
cp server.js /usr/lib/edison_config_tools/edison-config-server.js

cp edison_config.service /lib/systemd/system
systemctl daemon-reload
systemctl enable edison_config

cp configure_edison /usr/bin
chmod a+x /usr/bin/configure_edison

#cp start_edison_config_service /usr/bin
#chmod a+x /usr/bin/start_edison_config_service

echo ""
echo ""
echo "SETUP COMPLETE"
echo ""
echo "Feel free to delete this folder or keep it here."


text:
[![Greenkeeper badge](https://badges.greenkeeper.io/ajafff/tsutils.svg)](https://greenkeeper.io/)

## Usage

This package consists of two major parts: utilities and typeguard functions.
By importing the project you will get both of them.
```js
import * as utils from "tsutils";
utils.isIdentifier(node); // typeguard
utils.getLineRanges(sourceFile); // utilities
```

If you don't need everything offered by this package, you can select what should be imported. The parts that are not imported are never read from disk and may save some startup time and reduce memory consumtion.

If you only need typeguards you can explicitly import them:
```js
import { isIdentifier } from "tsutils/typeguard";
// You can even distiguish between typeguards for nodes and types
import { isUnionTypeNode } from "tsutils/typeguard/node";
import { isUnionType } from "tsutils/typeguard/type";
```

If you only need the utilities you can also explicitly import them:
```js
import { forEachComment, forEachToken } from "tsutils/util";
```

### Typescript version dependency

This package is backwards compatible with typescript 2.8.0 at runtime although compiling might need a newer version of typescript installed.

Using `typescript@next` might work, but it's not officially supported. If you encounter any bugs, please open an issue.

For compatibility with older versions of TypeScript typeguard functions are separated by TypeScript version. If you are stuck on `typescript@2.8`, you should import directly from the submodule for that version:

```js
// all typeguards compatible with typescript@2.8
import { isIdentifier } from "tsutils/typeguard/2.8";
// you can even use nested submodules
import { isIdentifier } from "tsutils/typeguard/2.8/node";

// all typeguards compatible with typescript@2.9 (includes those of 2.8)
import { isIdentifier } from "tsutils/typeguard/2.9";

// always points to the latest stable version (2.9 as of writing this)
import { isIdentifier } from "tsutils/typeguard";
import { isIdentifier } from "tsutils";

// always points to the typeguards for the next TypeScript version (3.0 as of writing this)
import { isIdentifier } from "tsutils/typeguard/next";
```

Note that if you are also using utility functions, you should prefer the relevant submodule:

```js
// importing directly from 'tsutils' would pull in the latest typeguards
import { forEachToken } from 'tsutils/util';
import { isIdentifier } from 'tsutils/typeguard/2.8';
```


text:
/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the top of the
 * compiled file, but it's generally better to create a new file per style scope.
 *
 *= require_self
 *
 *= require base
 *= require themes/djime-cerulean/style
 *= require chef
 *= require facebox/facebox
 *= require jquery-ui-1.7.1.custom
 *= require jquery.treeTable
 *= require jsonedit_main
 *= require jquery.suggest
*/


text:
import AssetsPlugin from 'assets-webpack-plugin'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import path from 'path'
import webpack from 'webpack'

const DEBUG = process.env.NODE_ENV !== 'production'

export default {
  entry: DEBUG ? ['webpack-hot-middleware/client', './index.js'] : './index.js',
  context: path.resolve(__dirname, './client'),
  output: {
    filename: `[name]${DEBUG ? '' : '.[hash]'}.js`,
    hashDigestLength: 7,
    path: path.resolve(__dirname, './build'),
    publicPath: '/'
  },
  module: {
    loaders: [
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('style', `css?modules&localIdentName=[name]__[local]${DEBUG ? '' : '-[hash:base64:4]'}`)
      },
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract('style', `css!sass?modules&localIdentName=[name]__[local]${DEBUG ? '' : '-[hash:base64:4]'}`)
      },
      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/,
        query: DEBUG ? {
          plugins: [['react-transform', {
            transforms: [{
              transform: 'react-transform-hmr',
              imports: ['react'],
              locals: ['module']
            }]
          }]]
        } : {}
      },
      {
        test: /\.json?$/,
        loader: 'json'
      },
      {
        test: /\.gif$|\.jpe?g$|\.woff|\.eot|\.ttf|\.png$|\.svg$/i,
        loader: `url?limit=10000&name=[name]${DEBUG ? '' : '.[hash:7]'}.[ext]`,
        exclude: /node_modules/
      }
    ]
  },
  plugins: [
    new AssetsPlugin({
      filename: 'assets.json',
      path: 'build'
    }),
    new ExtractTextPlugin(`[name]${DEBUG ? '' : '.[hash]'}.css`),
    new webpack.DefinePlugin({'process.env.NODE_ENV': JSON.stringify(DEBUG ? 'development' : 'production')}),
    ...DEBUG ? [
      new webpack.HotModuleReplacementPlugin()
    ] : [
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.OccurenceOrderPlugin(),
      new webpack.optimize.UglifyJsPlugin({compress: {warnings: false}})
    ]
  ]
}


text:
from PIL import Image

def get_image_background_color(img, alpha=False):
    img = img.convert('RGBA' if alpha else 'RGB')
    pixel_color = img.getpixel((1, 1))
    color_format = '#' + '%02x' * len(pixel_color)
    color = color_format % pixel_color
    color = color.upper()
    return color

def get_image_file_background_color(img_file, alpha=False):
    color = ''
    with Image.open(img_file) as image:
        color = get_image_background_color(image, alpha)
    return color


text:
<#
.Synopsis
   .\install-ddve.ps1 -MasterPath F:\labbuildr\ddve-5.6.0.3-485123\
.DESCRIPTION
  install-ddve only applies to Testers of the Virtual DDVe
  install-ddve is a 1 Step Process.
  Once DDVE is downloaded via feedbckcentral, run
   .\install-ddve.ps1 -defauls
   This creates a DDVE Master in your labbuildr directory.
   This installs a DDVE using the defaults file and the just extracted ddve Master

      Copyright 2016 Karsten Bott

   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.
.LINK
   http://labbuildr.readthedocs.io/en/master/Solutionpacks///SolutionPacks#install-ddve
.EXAMPLE
    Importing the ovf template
 .\install-ddve.ps1 -ovf G:\Sources\ddve-5.6.0.3-485123\ddve-5.6.0.3-485123.ovf
    Opening OVF source: G:\Sources\ddve-5.6.0.3-485123\ddve-5.6.0.3-485123.ovf
    The manifest does not validate
    Opening VMX target: F:\labbuildr_beta
    Warning:
    - Hardware compatibility check is disabled.
    - Line 54: Unsupported virtual hardware device 'VirtualSCSI'.
    Writing VMX file: F:\labbuildr_beta\ddve-5.6.0.3-485123\ddve-5.6.0.3-485123.vmx
    Transfer Completed
    Warning:
    - ExtraConfig option 'tools.guestlib.enableHostInfo' is not allowed, will skip it.
    - ExtraConfig option 'sched.mem.pin' is not allowed, will skip it.
    Completed successfully
.EXAMPLE
    Install a DDVeNode with defaults from defaults.json
    .\install-ddve.ps1 -MasterPath .\ddve-5.6.0.3-485123\ -Defaults
    WARNING: VM Path does currently not exist
    WARNING: Get-VMX : VM does currently not exist

    VMXname   Status  Starttime
    -------   ------  ---------
    DDvENode1 Started 07.21.2015 12:27:11
.EXAMPLE
    to create a 2TB Node DDvENde2 run
    .\install-ddve.ps1 -MasterPath .\ddve-5.5.1.4-464376  -Defaults -DDVESize 2TB -Verbose -Startnode 2 -Nodes 1
#>
[CmdletBinding(DefaultParametersetName = "default")]
Param(
[Parameter(ParameterSetName = "import",Mandatory=$true)][String]
[ValidateScript({ Test-Path -Path $_ -Filter *.ova -PathType Leaf -ErrorAction SilentlyContinue })]$ovf,
[Parameter(ParameterSetName = "import",Mandatory=$false)][String]$mastername,

#[Parameter(ParameterSetName = "install",Mandatory=$true)][ValidateScript({ Test-Path -Path $_ -ErrorAction SilentlyContinue })]$MasterPath,
[Parameter(ParameterSetName = "defaults",Mandatory=$False)]
[Parameter(ParameterSetName = "install",Mandatory=$true)]$MasterPath,
<# specify your desireed DDVE Size
Valid Parameters:2TB,4TB,8TB
This will result in the following
Machine Configurations:
=================================
Size    | Memory  | CPU | Disk
_____ __|_________|_____|_________
0.5TB   |  6GB    |  2  |  1*500GB
  2TB   |  6GB    |  2  |  4*500GB
  4TB   |  8GB    |  2  |  8*500GB
  8TB   |  16GB   |  2  |  16*500GB

#>
[Parameter(ParameterSetName = "defaults",Mandatory=$False)]
[Parameter(ParameterSetName = "install",Mandatory=$False)][ValidateSet('0.5TB','2TB','4TB','8TB')][string]$DDVESize = "2TB",
[Parameter(ParameterSetName = "defaults", Mandatory = $false)][switch]$Defaults = $true,
[Parameter(ParameterSetName = "defaults", Mandatory = $false)][ValidateScript({ Test-Path -Path $_ })]$Defaultsfile=".\defaults.json",
[Parameter(ParameterSetName = "defaults", Mandatory = $false)]
[Parameter(ParameterSetName = "install",Mandatory=$false)][int32]$Nodes=1,
[Parameter(ParameterSetName = "defaults", Mandatory = $false)]
[Parameter(ParameterSetName = "install",Mandatory=$false)][int32]$Startnode = 1,
<# Specify your own Class-C Subnet in format xxx.xxx.xxx.xxx #>
[Parameter(ParameterSetName = "install",Mandatory=$false)][ValidateScript({$_ -match [IPAddress]$_ })][ipaddress]$subnet = "192.168.2.0",
[Parameter(ParameterSetName = "install",Mandatory=$False)]
[ValidateLength(1,15)][ValidatePattern("^[a-zA-Z0-9][a-zA-Z0-9-]{1,15}[a-zA-Z0-9]+$")][string]$BuildDomain = "labbuildr",
[Parameter(ParameterSetName = "install", Mandatory = $true)][ValidateSet('vmnet2','vmnet3','vmnet4','vmnet5','vmnet6','vmnet7','vmnet9','vmnet10','vmnet11','vmnet12','vmnet13','vmnet14','vmnet15','vmnet16','vmnet17','vmnet18','vmnet19')]$VMnet = "vmnet2"

)
#requires -version 3.0
#requires -module vmxtoolkit

switch ($PsCmdlet.ParameterSetName)
{
    "import"
        {
		$labdefaults = Get-LABDefaults
		try
			{
			$Sourcedir = $labdefaults.Sourcedir
			}
		catch [System.Management.Automation.ValidationMetadataException]
			{
			Write-Warning "Could not test Sourcedir Found from Defaults, USB stick connected ?"
			Break
			}
		catch [System.Management.Automation.ParameterBindingException]
			{
			Write-Warning "No valid Sourcedir Found from Defaults, USB stick connected ?"
			Break
			}
		try
			{
			$Masterpath = $LabDefaults.Masterpath
			}
		catch
			{
			Write-Host -ForegroundColor Gray " ==> No Masterpath specified, trying $Builddir"
			$Masterpath = $Builddir
			}
        Write-Host -ForegroundColor Gray " ==>Validating OVF"
        try
            {
            $Importfile = Get-ChildItem $ovf -ErrorAction SilentlyContinue
            }
        catch
            {
            Write-Warning "$ovf is no valid ovf / ova location"
            exit
            }
        if (!($mastername))
            {
            $OVFfile = Get-Item $ovf
            $mastername = $OVFfile.BaseName
            }
        if ((import-VMXOVATemplate -OVA $Importfile.FullName -Name $mastername -destination $MasterPath  -acceptAllEulas -AllowExtraConfig).success -eq $true)
            {
            Write-Host -ForegroundColor Gray " ==>preparation of template done, please run " -NoNewline
			write-host -ForegroundColor White ".\$($MyInvocation.MyCommand) -MasterPath $MasterPath\$mastername -Defaults"
            }
        else
            {
            Write-Host "Error importing Base VM. Already Exists ?"
            exit
            }
        }

     default
        {
        If ($Defaults.IsPresent)
            {
            $labdefaults = Get-labDefaults
            if (!($labdefaults))
                {
                try
                    {
                        New-LabDefaults
                        $labdefaults = Get-labDefaults
                    }
                catch
                    {
                Write-Warning "no  defaults or example defaults found, exiting now"
                exit
                    }
            Write-Host -ForegroundColor Magenta " ==>Using generic defaults from labbuildr"
            }
            $vmnet = $labdefaults.vmnet
            $subnet = $labdefaults.MySubnet
            $BuildDomain = $labdefaults.BuildDomain
            $Sourcedir = $labdefaults.Sourcedir
            $Gateway = $labdefaults.Gateway
            $DefaultGateway = $labdefaults.Defaultgateway
            $DNS1 = $labdefaults.DNS1
            $DNS1 = $labdefaults.DNS2
            $configure = $true
            }
		if ($LabDefaults.custom_domainsuffix)
			{
			$custom_domainsuffix = $LabDefaults.custom_domainsuffix
			}
		else
			{
			$custom_domainsuffix = "local"
			}

        [System.Version]$subnet = $Subnet.ToString()
        $Subnet = $Subnet.major.ToString() + "." + $Subnet.Minor + "." + $Subnet.Build

        $Builddir = $PSScriptRoot
        $Nodeprefix = "DDvENode"
        if (!$MasterPath)
            {
            $MasterVMX = get-vmx Ddve-5.7* -WarningAction SilentlyContinue
            iF ($MasterVMX)
                {
                $MasterVMX = $MasterVMX | Sort-Object -Descending
                $MasterVMX = $MasterVMX[-1]
                }
            }
        else
            {
            if ($MasterPath)
                {
                $MasterVMX = get-vmx -path $MasterPath -WarningAction SilentlyContinue
                }
            }

        if (!$MasterVMX)
            {
            write-Host -ForegroundColor Magenta "Could not find existing DDVEMaster"
            if ($Defaults.IsPresent)
                {
                Write-Host -ForegroundColor Magenta "Trying Latest OVF fom $Sourcedir"
                try
                    {
                    $OVFpath =Join-Path $Sourcedir "ddve-*.ov*" -ErrorAction Stop
                    }
                catch [System.Management.Automation.DriveNotFoundException]
                    {
                    Write-Warning "Drive not found, make sure to have your Source Stick connected"
                    exit
                    }

                    $OVFfile = get-item -Path $OVFpath | Sort-Object -Descending -Property Name
                    If (!$OVFfile)
                        {
                        Write-Warning "No OVF for DDVE found, please conntact feedbackcentral"
                        exit
                        }
                    else
                        {
                        Write-Host -ForegroundColor Magenta "testing OVA File"
                        $OVFfile = $OVFfile[0]
                        $mastername = $OVFfile.BaseName
                        & $global:vmwarepath\OVFTool\ovftool.exe --lax --skipManifestCheck --acceptAllEulas   --name=$mastername $OVFfile.FullName $PSScriptRoot #
                        if ($LASTEXITCODE -ne 0)
                            {
                            Write-Warning "Error Extraxting OVF"
                            exit
                            }
                        $MasterVMX = get-vmx $mastername -WarningAction SilentlyContinue
                        }
                }
            else
                {
                Write-Warning "Please import with -ovf or use -Defaults"
                exit
                }

            }

        if (!$MasterVMX.Template)
            {
            write-verbose "Templating Master VMX"
            $template = $MasterVMX | Set-VMXTemplate
            }
        $Basesnap = $MasterVMX | Get-VMXSnapshot -WarningAction SilentlyContinue| where Snapshot -Match "Base"

        if (!$Basesnap)
            {
            Write-Host -ForegroundColor Magenta " ==>Tweaking Base VMX"
            $config = Get-VMXConfig -config $MasterVMX.config
            $config = $config -notmatch "virtualhw.version"
            $config += 'virtualhw.version = "9"'
            $config = $config -notmatch 'scsi0:0.mode = "independent_persistent"'
            $config += 'scsi0:0.mode = "persistent"'
            $config = $config -notmatch 'scsi0:1.mode = "independent_persistent"'
            $config += 'scsi0:1.mode = "persistent"'
            Set-Content -Path $MasterVMX.config -Value $config
            foreach ($scsi in 0..3)
                {
				$Mastervmx | Set-VMXScsiController -SCSIController $scsi -Type pvscsi | Out-Null
                }
            Write-verbose "Base snap does not exist, creating now"
            $Basesnap = $MasterVMX | New-VMXSnapshot -SnapshotName Base
            }
            # $Basesnap
            foreach ($Node in $Startnode..(($Startnode-1)+$Nodes))
            {
            Write-Verbose "Checking VM $Nodeprefix$node already Exists"
            If (!(get-vmx -path $Nodeprefix$node -WarningAction SilentlyContinue))
                {
                $NodeClone = $MasterVMX | Get-VMXSnapshot | where Snapshot -Match "Base" | New-VMXlinkedClone -CloneName $Nodeprefix$node -Clonepath $Builddir
                switch ($DDvESize)
                    {
                "0.5TB"
                    {
                    Write-Verbose "0.5TB DDvE Selected"
                    $NumDisks = 1
                    $NumCrtl = 1
                    [uint64]$Disksize = 500GB
                    $memsize = 6044
                    $Numcpu = 2
                    }
                "2TB"
                    {
                    Write-Verbose "2TB DDvE Selected"
                    $NumDisks = 1
                    $NumCrtl = 4
                    [uint64]$Disksize = 500GB
                    $memsize = 6044
                    $Numcpu = 2
                    }
                "4TB"
                    {
                    Write-Verbose "4TB DDvE Selected"
                    $NumDisks = 2
                    $NumCrtl = 4
                    [uint64]$Disksize = 500GB
                    $memsize = 8192
                    $Numcpu = 2
                    }
                "8TB"
                    {
                    Write-Verbose "8TB DDvE Selected"
                    $NumDisks = 4
                    $NumCrtl = 4
                    [uint64]$Disksize = 500GB
                    $memsize = 8192
                    $Numcpu = 2
                    }

            }
            $scsi = 0
            Write-Host -ForegroundColor Magenta "Adding Disks"
            foreach ($LUN in (2..($NumDisks+1)))
                    {
                    $Diskname =  "SCSI$SCSI"+"_LUN$LUN.vmdk"
                    $Newdisk = New-VMXScsiDisk -NewDiskSize $Disksize -NewDiskname $Diskname -Verbose -VMXName $NodeClone.VMXname -Path $NodeClone.Path
                    $AddDisk = $NodeClone | Add-VMXScsiDisk -Diskname $Newdisk.Diskname -LUN $LUN -Controller $SCSI
                    }

            if ($NumCrtl -gt 1)
                {
                foreach ($SCSI in 1..($NumCrtl-1))
                    {
                    foreach ($LUN in (0..($NumDisks-1)))
                        {
                        $Diskname =  "SCSI$SCSI"+"_LUN$LUN.vmdk"
                        $Newdisk = New-VMXScsiDisk -NewDiskSize $Disksize -NewDiskname $Diskname -Verbose -VMXName $NodeClone.VMXname -Path $NodeClone.Path
                        $AddDisk = $NodeClone | Add-VMXScsiDisk -Diskname $Newdisk.Diskname -LUN $LUN -Controller $SCSI
                        }
                    }
                }

            $Netadater0 = $NodeClone | Set-VMXVnet -Adapter 0 -vnet $VMnet
            $Netadater1 = $NodeClone | Set-VMXNetworkAdapter -Adapter 1 -ConnectionType nat -AdapterType vmxnet3
            $Netadater1connected = $NodeClone | Disconnect-VMXNetworkAdapter -Adapter 1

            $Displayname = $NodeClone | Set-VMXDisplayName -DisplayName $NodeClone.CloneName
            $MainMem = $NodeClone | Set-VMXMainMemory -usefile:$false
            $Memory = $NodeClone | Set-VMXmemory -MemoryMB $memsize
            $Processor = $nodeclone | Set-VMXprocessor -Processorcount $Numcpu
            $NodeClone | start-vmx | Out-Null
            if ($configure.IsPresent)
                {
                $ip="$subnet.2$Node"
                }
            }
            else
            {
                Write-Warning "Node $Nodeprefix$node already exists"
            }

        }
    Write-host
    Write-host -ForegroundColor White "****** To Configure  DDVE 5.7 ******
Go to VMware Console an wait for system to boot"
    Write-host -ForegroundColor White "
    Please login with
    localhost login : sysadmin
    Password: changeme
    Change the Password or type no
    Answer yes for GUI Wizard
    Answer yes for Configure Network at this time
    Answer No for DHCP
    Enter $Nodeprefix$Node.$BuildDomain.$Custom_DomainSuffix as hostname
    Enter $BuildDomain.$Custom_DomainSuffix as DNSDomainname
    (The orde of the next command and Devicenames may vary from Version to Version )
Ethernet Port ethV1
    Enter NO for Enable Ethernet ethV1
Ethernet Port ethV1
    Enter Yes for Enable Ethernet Port ethV0
    Enter NO for DHCP
    Enter IP Address for ethV0:
    $subnet.2$Node as IP Address
    enter the netmask for ethV0:
    255.255.255.0
Default Gateway
    Enter $DefaultGateway for Gateway IP Address
    Leave IPv6 Gateway Blank
DNS Server
    Enter $DNS1,$DNS2 as DNS Server
    Enter Save to Save

Open Your webbrowser to Configure Licences and Features !!!
"
    }# end default
}