text:
#pragma once

#include <cstdarg>
#include <climits>
#include <cstdint>

#include "stacker_token.h"
#include "stacker_attribute.h"
#include "stacker_style.h"
#include "stacker_diagnostics.h"
#include "stacker_message.h"

namespace urlcache { class UrlCache; struct ParsedUrl; enum UrlFetchPriority; }

namespace stkr {

struct System;
struct BackEnd;
struct Document;
struct Message;
struct Node;
struct Box;
struct View;
struct Rule;

enum Axis { AXIS_H, AXIS_V };

enum AxisBit {
	AXIS_BIT_H = 1 << AXIS_H,
	AXIS_BIT_V = 1 << AXIS_V
};

enum TextEncoding {
	ENCODING_ASCII, /* Encode strings as byte arrays, truncating to 7 bits. */
	ENCODING_LATIN1, /* Encode strings as byte arrays, truncating to 8 bits. */
	ENCODING_UTF8,
	ENCODING_UTF16,
	ENCODING_UTF32,
	NUM_ENCODINGS
};

enum NodeType {
	LNODE_INVALID = -1,

	LNODE_BASIC,
	LNODE_TEXT,
	LNODE_HBOX,
	LNODE_VBOX,
	LNODE_PARAGRAPH,
	LNODE_HEADING,
	LNODE_HYPERLINK,
	LNODE_IMAGE,
	LNODE_USER,

	NUM_NODE_TYPES
};

enum NodeFlag {
	/* Bits that say things need to be recalculated. */
	NFLAG_PARENT_CHANGED               = 1 << 0,  // The node has been moved in the graph.
	NFLAG_UPDATE_BACKGROUND_LAYERS     = 1 << 1,  // The node's visual layer stack must be updated to reflect its current attributes.
	NFLAG_UPDATE_BOX_LAYERS            = 1 << 2,  // The box's layer stack must by synchronized with the node's.
	NFLAG_FOLD_ATTRIBUTES              = 1 << 3,  // Folded attribute values must be recalculated.
	NFLAG_REBUILD_BOXES                = 1 << 4,  // This node's box must be recreated.
	NFLAG_RECONSTRUCT_PARAGRAPH        = 1 << 5,  // Rebuild paragraph elements from children if this is an inline container.
	NFLAG_REMEASURE_PARAGRAPH_ELEMENTS = 1 << 6,  // Update text advances if this is an inline container.
	NFLAG_RECOMPOSE_CHILD_BOXES        = 1 << 8,  // Node child boxes have changed, and should be rearranged within the parent.
	NFLAG_UPDATE_RULE_KEYS             = 1 << 9,  // The set of keys used to match rules for this node must be recalculated.
	NFLAG_UPDATE_MATCHED_RULES         = 1 << 10, // The node's match rule list must be recalculated.
	NFLAG_UPDATE_CHILD_RULES           = 1 << 11, // Selectors that match parents may now match differently for children of this node.

	/* Memory management flags. */
	NFLAG_HAS_STATIC_TEXT           = 1 << 12, // The node's text buffer is allocated as part of the node block.
	NFLAG_HAS_STATIC_RULE_KEYS      = 1 << 13, // The node's rule key buffer is allocated as part of the node block.

	/* Hit testing bits. */
	NFLAG_IN_HIT_CHAIN              = 1 << 14, // The node is a member of the most recently calculated hit set.
	NFLAG_MOUSE_OVER                = 1 << 15, // One of the node's boxes is the top of the mouse hit stack.
	NFLAG_MOUSE_OVER_CHILD          = 1 << 16, // A box of one of the node's children is the top of the mouse hit stack.
	NFLAG_MOUSE_INSIDE              = 1 << 17, // The node's box or the box of one of its children is in the hit stack.

	/* Selection bits. */
	NFLAG_IN_SELECTION_CHAIN        = 1 << 18, // The node is part of the selection chain.
	NFLAG_UPDATE_SELECTION_LAYERS   = 1 << 19, // The node's selection state has changed.

	/* Interaction states. */
	NFLAG_INTERACTION_HIGHLIGHTED   = 1 << 20, // Mouse over.
	NFLAG_INTERACTION_ACTIVE        = 1 << 21, // Mouse down.

	/* Set for nodes that have a box when that box changes size. */
	NFLAG_WIDTH_CHANGED             = 1 << 22,
	NFLAG_HEIGHT_CHANGED            = 1 << 23,

	/* Bits that say which direction a node expanded or contracted in. It's not
	 * always possible to say. */
	NFLAG_NOTIFY_EXPANSION          = 1 << 24, // Send messages when the node expands or contracts.
	NFLAG_EXPANDED_LEFT             = 1 << 25, // The left edge of the node has moved.
	NFLAG_EXPANDED_RIGHT            = 1 << 26, // The right edge of the node has moved.
	NFLAG_EXPANDED_UP               = 1 << 27, // The top edge of the node has moved.
	NFLAG_EXPANDED_DOWN             = 1 << 28, // The bottom edge of the node has moved.

	/* Set for nodes that contribute one or more paragraph elements to an inline
	 * layout. Used to skip over zero-element nodes when co-iterating nodes and
	 * elements. */
	NFLAG_HAS_PARAGRAPH_ELEMENTS    = 1 << 29
};

const unsigned NFLAG_EXPANSION_MASK = NFLAG_EXPANDED_LEFT |
	NFLAG_EXPANDED_RIGHT | NFLAG_EXPANDED_UP | NFLAG_EXPANDED_DOWN;

/* Flags that should be passed to the parent when updating nodes. */
const unsigned NFLAG_PROPAGATE_UP_MASK = 0;

/* A special value for InlineAddress::offset signifying the position after
 * the last character. This exists to allow us to distinguish "before" and
 * "after" positions for zero-width tokens, which would otherwise share
 * offset 0. */
static const unsigned IA_END = UINT_MAX;

/* A tree position between any two characters. */
struct CaretAddress {
	const Node *node;
	unsigned offset;
};

enum DocumentFlag {
	DOCFLAG_CONSTRAIN_WIDTH         = 1 <<  0, // root_width contains a dimension to maintain on the root box.
	DOCFLAG_CONSTRAIN_HEIGHT        = 1 <<  1, // root_height contains a dimension to maintain on the root box.
	DOCFLAG_ENABLE_SELECTION        = 1 <<  2, // Allow text selection.
	DOCFLAG_SELECTING               = 1 <<  3, // Mouse selection in progress.
	DOCFLAG_HAS_SELECTION           = 1 <<  4, // Document has a final, non-empty selection.
	DOCFLAG_UPDATE_SELECTION_CHAIN  = 1 <<  5, // Selection chain must be rebuilt.
	DOCFLAG_EXTERNAL_MESSAGES       = 1 <<  6, // Unhandled document-level messages are added to a queue to be processed by the client.
	DOCFLAG_RULE_TABLE_CHANGED      = 1 <<  7, // The document rule table has changed since the last layout.
	DOCFLAG_KEEP_SOURCE             = 1 <<  8, // Keep a copy of the markup last parsed into the document.

	DOCFLAG_DEBUG_LAYOUT            = 1 <<  9, // Send layout diagnostics to the dump function.
	DOCFLAG_DEBUG_FULL_LAYOUT       = 1 << 10, // Send layout diagnostics to the dump function.
	DOCFLAG_DEBUG_PARAGRAPHS        = 1 << 11, // Dump paragraph breakpoint info.
	DOCFLAG_DEBUG_SELECTION         = 1 << 12, // Print selection hit testing messages.

	/* Internal, do not use. */
	DOCFLAG_UPDATE_REMATCH_RULES    = 1 << 14  // Assume rule tables have changed during the current update.
};

/* The status of a document's attempt to navigate to a URL. */
enum NavigationState {
	DOCNAV_IDLE,
	DOCNAV_IN_PROGRESS,
	DOCNAV_FAILED,
	DOCNAV_PARSE_ERROR,
	DOCNAV_SUCCESS
};

enum ViewFlag {
	VFLAG_CONSTRAIN_DOCUMENT_WIDTH   = 1 <<  0, // Constrain root node width to view bounds.
	VFLAG_CONSTRAIN_DOCUMENT_HEIGHT  = 1 <<  1, // Constrain root node height to view bounds.
	VFLAG_DEBUG_OUTER_BOXES          = 1 <<  2, // Debug box visualization.
	VFLAG_DEBUG_PADDING_BOXES        = 1 <<  3, // Debug box visualization.
	VFLAG_DEBUG_CONTENT_BOXES        = 1 <<  4, // Debug box visualization.
	VFLAG_DEBUG_DIMENSIONS           = 1 <<  5, // Show box dimensions.
	VFLAG_DEBUG_PARAGRAPH            = 1 <<  6, // Show paragraph line demerits.
	VFLAG_DEBUG_MOUSE_HIT            = 1 <<  7, // Show mouse hit set.

	/* Internal. Do not use. */
	VFLAG_REBUILD_COMMANDS           = 1 << 12  // Must rebuild draw commands.
};

/* Enables all view debug features. */
const unsigned VFLAG_DEBUG_MASK =
	VFLAG_DEBUG_OUTER_BOXES |
	VFLAG_DEBUG_PADDING_BOXES |
	VFLAG_DEBUG_CONTENT_BOXES |
	VFLAG_DEBUG_DIMENSIONS |
	VFLAG_DEBUG_PARAGRAPH |
	VFLAG_DEBUG_MOUSE_HIT;

enum SystemFlag {
	SYSFLAG_SINGLE_LINE_TEXT_LAYERS   = 1 << 0, // The back end requires that all characters in a text share have the same Y position.
	SYSFLAG_CACHE_HIDDEN_NODE_LAYOUTS = 1 << 1  // Spend memory to make showing and hiding nodes fast.
};

enum Code {
	STKR_CANNOT_FOLD                    = -26,
	STKR_INVALID_SET_LITERAL            = -25,
	STKR_INVALID_OPERATION              = -24,
	STKR_NO_SUCH_ATTRIBUTE              = -23,
	STKR_TYPE_MISMATCH                  = -22,
	STKR_OUT_OF_BOUNDS                  = -21,
	STKR_INCORRECT_CONTEXT              = -20,
	STKR_MISSING_SELECTOR               = -19,
	STKR_SELECTOR_ILL_FORMED            = -18,
	STKR_SELECTOR_EMPTY                 = -17,
	STKR_SELECTOR_INVALID_CHAR          = -16,
	STKR_SELECTOR_MISSING_CLASS         = -15,
	STKR_SELECTOR_TOO_LONG              = -14,
	STKR_COLOR_COMPONENT_OUT_OF_RANGE   = -13,
	STKR_INVALID_INPUT                  = -12,
	STKR_INVALID_TAG                    = -11,
	STKR_INVALID_KEYWORD                = -10,
	STKR_MISMATCHED_TAGS                = -9,
	STKR_UNTERMINATED_STRING            = -8,
	STKR_ATTRIBUTE_VALUE_OUT_OF_BOUNDS  = -7,
	STKR_ATTRIBUTE_VALUE_TYPE_MISMATCH  = -6,
	STKR_TOO_MANY_ATTRIBUTES            = -5,
	STKR_UNEXPECTED_TOKEN               = -4,
	STKR_INVALID_NUMERIC_LITERAL        = -3,
	STKR_INVALID_TOKEN                  = -2,
	STKR_ERROR                          = -1,
	STKR_OK                             = 0
};

const unsigned MAX_SELECTOR_DEPTH         = 16;
const unsigned MAX_SELECTOR_CLAUSES       = 16;
const unsigned MAX_SELECTOR_KEYS          = MAX_SELECTOR_CLAUSES * MAX_SELECTOR_DEPTH;

/* A special priority threshold which causes attributes of a rule to override
 * even those of the node against which it is matched. */
const int RULE_PRIORITY_OVERRIDE =  -64;
const int RULE_PRIORITY_LOWEST   =  127;
const int RULE_PRIORITY_HIGHEST  = -128;

/* Rule priority keys contain the user-supplied priority in the upper 8 bits
 * and the document order in the lower bits. */
const unsigned RULE_PRIORITY_SHIFT = 24;

enum RuleFlag {
	RFLAG_ENABLED           = 1 << 0, // Attributes in this rule should be
	                                  // applied to matching nodes.
	RFLAG_GLOBAL            = 1 << 1, // Create a global rule.
	RFLAG_IN_DOCUMENT_TABLE = 1 << 2, // Rule is in a document rule table.
	RFLAG_IN_SYSTEM_TABLE   = 1 << 3, // Rule is in the system rule table.
	RFLAG_MODIFIES_CLASS    = 1 << 4  // Rule alters the "class" attribute.
};

/* A set of rule keys representing a multi-clause selector expression. */
struct ParsedSelector {
	uint64_t keys[MAX_SELECTOR_KEYS];
	unsigned total_keys;
	unsigned num_clauses;
	unsigned keys_per_clause[MAX_SELECTOR_CLAUSES];
};

typedef void (*DumpCallback)(void *data, const char *fmt, va_list args);

/*
 * Node
 */
int create_node(Node **result, Document *document, NodeType type, int tag_name,
	const AttributeAssignment *attributes = 0, unsigned num_attributes = 0,
	const char *text = 0, uint32_t text_length = 0);
void destroy_node(Document *document, Node *node, bool recursive = true);
void destroy_children(Document *document, Node *node);
void insert_child_before(Document *document, Node *parent, Node *child,
	Node *before);
void append_child(Document *document, Node *parent, Node *child);
void prepend_child(Document *document, Node *parent, Node *child);
void remove_from_parent(Document *document, Node *child);
NodeType get_type(const Node *node);
unsigned get_text_length(const Node *node);
Box *get_box(Node *node);
const Box *get_box(const Node *node);
const char *get_text(const Node *node);
Layout get_layout(const Node *node);
unsigned get_flags(const Node *node);
void set_node_flags(Document *document, Node *node, unsigned mask, bool value);
void set_node_flags_internal(Document *document, Node *node,
	unsigned mask, bool value);
const NodeStyle *get_style(const Node *node);
NodeStyle *get_style(Node *node);
bool is_enabled(const Node *node);
Token get_token(const Node *node);
bool send_message(Document *document, Node *node, Message *message);
const char *get_node_debug_string(const Node *node, const char *value_if_null = "NULL");
void set_node_debug_string(Node *node, const char *fmt, ...);

/*
 * Traversal
 */
const Node *parent(const Node *node);
const Node *next_sibling(const Node *node);
const Node *previous_sibling(const Node *node);
const Node *first_child(const Node *node);
const Node *last_child(const Node *node);

Node *parent(Node *node);
Node *next_sibling(Node *node);
Node *previous_sibling(Node *node);
Node *first_child(Node *node);
Node *last_child(Node *node);

/*
 * Attribute Access
 */
int read_mode(const Node *node, int name_token, int defmode = ADEF_UNDEFINED);
int read_as_integer(const Node *node, int name_token, int32_t *result,
	int32_t defval = 0);
int read_as_float(const Node *node, int name, float *result,
	float defval = 0.0f);
int read_as_string(const Node *node, int name, const char **out_data,
	unsigned *out_length = 0, const char *defval = 0);
int read_as_string(const Node *node, int name, char *buffer,
	unsigned bufer_size, unsigned *out_length = 0, const char *defval = 0,
	StringSetRepresentation ssr = SSR_INTERNAL);
int read_as_url(const Node *node, int name_token,
	urlcache::ParsedUrl **out_url, char *buffer = 0,
	unsigned buffer_size = 0);

int set_integer_attribute(Document *document, Node *node, int name,
	ValueSemantic vs, int value, AttributeOperator op = AOP_SET);
int set_float_attribute(Document *document, Node *node, int name,
	ValueSemantic vs, float value, AttributeOperator op = AOP_SET);
int set_string_attribute(Document *document, Node *node, int name,
	ValueSemantic vs, const char *value, int length = -1,
	AttributeOperator op = AOP_SET);

int fold_integer_attribute(Document *document, Node *node, int name,
	ValueSemantic vs, int value, AttributeOperator op);
int fold_float_attribute(Document *document, Node *node, int name,
	ValueSemantic vs, float value, AttributeOperator op);
int fold_string_attribute(Document *document, Node *node, int name,
	ValueSemantic vs, const char *value, int length, AttributeOperator op);

void set_node_text(Document *document, Node *node, const char *text,
	int length = -1);
void set_outer_dimension(Document *document, Node *node,
	Axis axis, int dim);

/*
 * Rules
 */
int add_rule(
	Rule **result,
	System *system,
	Document *document,
	const ParsedSelector *ps,
	const AttributeAssignment *attributes = 0,
	unsigned num_attributes = 0,
	unsigned flags = 0,
	int priority = 0);
int add_rule(
	Rule **result,
	System *system,
	Document *document,
	const char *selector,
	int selector_length,
	const AttributeAssignment *attributes = 0,
	unsigned num_attributes = 0,
	unsigned flags = RFLAG_ENABLED,
	int priority = 0);
void destroy_rule(Rule *rule);
unsigned get_rule_flags(const Rule *rule);
void set_rule_flags(Rule *rule, unsigned mask, bool value);
int set_integer_attribute(Rule *rule, int name,
	ValueSemantic vs, int value);
int set_float_attribute(Rule *rule, int name,
	ValueSemantic vs, float value);
int set_string_attribute(Rule *rule, int name,
	ValueSemantic vs, const char *value, int length);
int parse_selector(ParsedSelector *ps, const char *s, int length = -1);
int node_matches_selector(const Document *document, const Node *node,
	const ParsedSelector *ps);
int node_matches_selector(const Document *document, const Node *node,
	const char *selector, int length = -1);
int match_nodes(const Document *document, const Node *root,
	const ParsedSelector *ps, const Node **matched_nodes = 0,
	unsigned max_matched = 0, int max_depth = -1);
int match_nodes(const Document *document, const Node *root,
	const char *selector, int selector_length = -1,
	const Node **matched_nodes = 0, unsigned max_matched = 0,
	int max_depth = -1);

/*
 * Box
 */
const char *get_box_debug_string(const Box *box, const char *value_if_null = "NULL");
void set_box_debug_string(Box *box, const char *fmt, ...);

/*
 * System
 */
System *create_system(unsigned flags = 0, BackEnd *back_end = 0,
	urlcache::UrlCache *url_cache = 0, TextEncoding encoding = ENCODING_UTF8,
	TextEncoding message_encoding = ENCODING_UTF8);
void destroy_system(System *system);
BackEnd *get_back_end(System *system);
unsigned get_total_nodes(const System *system);
unsigned get_total_boxes(const System *system);

/*
 * Document
 */
Document *create_document(System *system, unsigned flags = 0);
void destroy_document(Document *document);
void reset_document(Document *document);
void set_document_flags(Document *document, unsigned mask, bool value);
float get_root_dimension(const Document *document, Axis axis);
void set_root_dimension(Document *document, Axis axis, unsigned dimension);
void set_layout_dump_callback(Document *document, DumpCallback layout_dump,
	void *layout_dump_data = 0);
bool update_document(Document *document, uintptr_t timeout = 0);
Node *get_root(Document *document);
const Node *get_root(const Document  *document);
unsigned get_hit_clock(const Document *document);
unsigned get_layout_clock(const Document *document);
unsigned get_flags(const Document *document);
const Box *get_selection_start_anchor(const Document *document);
const Box *get_selection_end_anchor(const Document *document);
CaretAddress get_selection_start(const Document *document);
CaretAddress get_selection_end(const Document *document);
const Message *dequeue_message(Document *document);
CursorType get_cursor(const Document *document);
urlcache::ParsedUrl *get_url(const Document *document, void *buffer = 0,
	unsigned buffer_size = 0);
int set_url(Document *document, const char *url);
int navigate(Document *document, const char *url,
	urlcache::UrlFetchPriority priority = urlcache::UrlFetchPriority(1));
NavigationState get_navigation_state(const Document *document);
const char *get_source(const Document *document, unsigned *out_size);

/*
 * View
 */
View *create_view(Document *document, unsigned flags);
void destroy_view(View *view);
void update_view(View *view);
unsigned get_view_flags(const View *view);
void set_view_flags(View *view, unsigned flags, bool value);
unsigned get_paint_clock(const View *view);
void set_view_bounds(View *view, float x0, float x1, float y0, float y1);
void set_view_bounds(View *view, float *bounds);
void view_handle_mouse_event(View *view, MessageType type,
	int x, int y, unsigned flags);
void view_handle_keyboard_event(View *view, MessageType type,
	unsigned key_code, unsigned flags);

/*
 * Parser
 */
int parse(System *system, Document *document, Node *root, const char *input,
	unsigned length, void *error_buffer = 0, unsigned error_buffer_size = 0);
int create_node_from_markup(
	Node **out_node,
	Document *document,
	const char *input,
	unsigned length,
	char *error_buffer = 0,
	unsigned error_buffer_size = 0);

/*
 * Utilities
 */
unsigned murmur3_32(const void *key, int len, unsigned seed = 0);
uint64_t murmur3_64(const void *key, const int len, unsigned seed = 0);
uint64_t murmur3_64_cstr(const char *key, unsigned seed = 0);

} // namespace stkr


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.DocumentSet;
using OfficeDevPnP.PowerShell.CmdletHelpAttributes;
using OfficeDevPnP.PowerShell.Commands.Base.PipeBinds;
using OfficeDevPnP.PowerShell.Commands.Enums;

namespace OfficeDevPnP.PowerShell.Commands.DocumentSets
{
    [Cmdlet(VerbsCommon.Get,"SPODocumentSetTemplate")]
    [CmdletHelp("Retrieves a document set template",
        Category = CmdletHelpCategory.DocumentSets)]
    [CmdletExample(
        Code = @"PS:> Get-SPODocumentSetTemplate -Identity ""Test Document Set""",
        Remarks = @"This will get the document set template with the name ""Test Document Set""",
        SortOrder = 1)]
    [CmdletExample(
        Code = @"PS:> Get-SPODocumentSetTemplate -Identity ""0x0120D520005DB65D094035A241BAC9AF083F825F3B""",
        Remarks = @"This will get the document set template with the id ""0x0120D520005DB65D094035A241BAC9AF083F825F3B""",
        SortOrder = 2)]
    public class GetDocumentSetTemplate : SPOWebCmdlet
    {
        [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, HelpMessage = "Either specify a name, an id, a document set template object or a content type object")]
        public DocumentSetPipeBind Identity;

        protected override void ExecuteCmdlet()
        {
            var docSetTemplate = Identity.GetDocumentSetTemplate(SelectedWeb);

            ClientContext.Load(docSetTemplate, t => t.AllowedContentTypes, t => t.DefaultDocuments, t => t.SharedFields, t => t.WelcomePageFields);

            ClientContext.ExecuteQuery();

            WriteObject(docSetTemplate);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.codedeploy.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.codedeploy.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * GenericRevisionInfo JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GenericRevisionInfoJsonUnmarshaller implements Unmarshaller<GenericRevisionInfo, JsonUnmarshallerContext> {

    public GenericRevisionInfo unmarshall(JsonUnmarshallerContext context) throws Exception {
        GenericRevisionInfo genericRevisionInfo = new GenericRevisionInfo();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("description", targetDepth)) {
                    context.nextToken();
                    genericRevisionInfo.setDescription(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("deploymentGroups", targetDepth)) {
                    context.nextToken();
                    genericRevisionInfo.setDeploymentGroups(new ListUnmarshaller<String>(context.getUnmarshaller(String.class)).unmarshall(context));
                }
                if (context.testExpression("firstUsedTime", targetDepth)) {
                    context.nextToken();
                    genericRevisionInfo.setFirstUsedTime(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
                }
                if (context.testExpression("lastUsedTime", targetDepth)) {
                    context.nextToken();
                    genericRevisionInfo.setLastUsedTime(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
                }
                if (context.testExpression("registerTime", targetDepth)) {
                    context.nextToken();
                    genericRevisionInfo.setRegisterTime(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return genericRevisionInfo;
    }

    private static GenericRevisionInfoJsonUnmarshaller instance;

    public static GenericRevisionInfoJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new GenericRevisionInfoJsonUnmarshaller();
        return instance;
    }
}


text:
package jmh.benchmark;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;

import jenkins.benchmark.jmh.BenchmarkFinder;

import org.junit.Test;

import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.results.format.ResultFormatType;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.ChainedOptionsBuilder;
import org.openjdk.jmh.runner.options.OptionsBuilder;

/**
 * A runner class which finds benchmark tests annotated with @JmhBenchmark and launches them with the selected options
 * provided by JMH
 */
public class BenchmarkRunner {
    /**
     * Returns true if property benchmark.run is set.
     * @return true if benchmarks should be run
     */
    private boolean shouldRunBenchmarks() throws Exception {
        return Boolean.parseBoolean(System.getProperty("benchmark.run", "false"));
    }

    @Test
    public void runJmhBenchmarks() throws Exception {
        if (!shouldRunBenchmarks()) {
            String msg = "{\"benchmark.run\": false, \"reason\": \"Benchmark not run because benchmark.run is false\"}";
            Files.write(Paths.get("jmh-report.json"), msg.getBytes(StandardCharsets.UTF_8));
            return;
        }
        ChainedOptionsBuilder options = new OptionsBuilder()
                .mode(Mode.AverageTime) // Performance metric is Average time (ms per operation)
                .warmupIterations(1) // Used to warm JVM before executing benchmark tests
                .measurementIterations(3)
                .timeUnit(TimeUnit.MILLISECONDS)
                .threads(2) // TODO: Increase the number of threads and measure performance
                .forks(1)   // Need to increase more forks to get more observations, increases precision.
                .shouldFailOnError(true) // Will stop forking of JVM as soon as there is a compilation error
                .shouldDoGC(true) // do GC between measurement iterations
                .resultFormat(ResultFormatType.JSON) // store the results in a file called jmh-report.json
                .result("jmh-report.json");

        BenchmarkFinder bf = new BenchmarkFinder(getClass());
        bf.findBenchmarks(options);
        new Runner(options.build()).run();
    }
}


text:
package api

import (
	"github.com/Unknwon/macaron"
	"github.com/macaron-contrib/session"
	"github.com/sapk/GoWatch/modules/api/network"
	"github.com/sapk/GoWatch/modules/auth"
)

// Ping ping the ip or hostname
func Ping(ctx *macaron.Context, auth *auth.Auth, sess session.Store) {
	if err := auth.VerificationAuth(ctx, sess, []string{"api.network.ping"}); err != nil {
		return
	}
	hostorip := ctx.Req.URL.RawQuery
	ctx.JSON(200, network.Ping(hostorip))
}

// SNMPTest the snmp service of the ip or hostname
func SNMPTest(ctx *macaron.Context, auth *auth.Auth, sess session.Store) {
	if err := auth.VerificationAuth(ctx, sess, []string{"api.network.snmp"}); err != nil {
		return
	}
	hostorip := ctx.Query("host")
	community := ctx.Query("community")
	ctx.JSON(200, network.SNMPTest(hostorip, community))
}


text:
package lrucache

// wencan
// 2017-09-02 09:01

import (
	"container/list"
)

type listEntry struct {
	key   interface{}
	value interface{}
}

type ListMap struct {
	sequence *list.List
	mapping  map[interface{}]*list.Element
}

func NewListMap() *ListMap {
	return &ListMap{
		sequence: list.New(),
		mapping:  make(map[interface{}]*list.Element),
	}
}

func (m *ListMap) Get(key interface{}) (value interface{}, ok bool) {
	elem, ok := m.mapping[key]
	if ok {
		entry := elem.Value.(*listEntry)
		return entry.value, ok
	}
	return nil, false
}

func (m *ListMap) Pop(key interface{}) (value interface{}, ok bool) {
	elem, ok := m.mapping[key]
	if ok {
		delete(m.mapping, key)
		m.sequence.Remove(elem)

		entry := elem.Value.(*listEntry)
		return entry.value, true
	}
	return nil, false
}

func (m *ListMap) Len() int {
	return m.sequence.Len()
}

func (m *ListMap) Front() (value interface{}, ok bool) {
	elem := m.sequence.Front()
	if elem != nil {
		entry := elem.Value.(*listEntry)
		return entry.value, true
	}
	return nil, false
}

func (m *ListMap) Back() (value interface{}, ok bool) {
	elem := m.sequence.Back()
	if elem != nil {
		entry := elem.Value.(*listEntry)
		return entry.value, true
	}
	return nil, false
}

func (m *ListMap) PopFront() (value interface{}, ok bool) {
	elem := m.sequence.Front()
	if elem != nil {
		entry := elem.Value.(*listEntry)

		m.sequence.Remove(elem)
		delete(m.mapping, entry.key)

		return entry.value, true
	}
	return nil, false
}

func (m *ListMap) PopBack() (value interface{}, ok bool) {
	elem := m.sequence.Back()
	if elem != nil {
		entry := elem.Value.(*listEntry)

		m.sequence.Remove(elem)
		delete(m.mapping, entry.key)

		return entry.value, true
	}
	return nil, false
}

func (m *ListMap) PushFront(key interface{}, value interface{}) {
	entry := &listEntry{
		key:   key,
		value: value,
	}

	elem := m.sequence.PushFront(entry)
	m.mapping[key] = elem
}

func (m *ListMap) PushBack(key interface{}, value interface{}) {
	entry := &listEntry{
		key:   key,
		value: value,
	}

	elem := m.sequence.PushBack(entry)
	m.mapping[key] = elem
}

func (m *ListMap) MoveToFront(key interface{}) {
	elem, ok := m.mapping[key]
	if ok {
		m.sequence.MoveToFront(elem)
	}
}

func (m *ListMap) MoveToBack(key interface{}) {
	elem, ok := m.mapping[key]
	if ok {
		m.sequence.MoveToBack(elem)
	}
}

func (m *ListMap) Clear() {
	m.mapping = make(map[interface{}]*list.Element)
	m.sequence = list.New()
}


text:
<?php

namespace Jacobine\Application;

/**
 * Interface KernelInterface
 *
 * Interface of a Kernel.
 * The Kernel is the heart of the application.
 *
 * @package Jacobine\Consumer
 * @author Andy Grunwald <andygrunwald@gmail.com>
 */
interface KernelInterface
{

    /**
     * Entry point to run the application.
     * This is the first method to call.
     *
     * For an example have a look at the console file
     *
     * @return void
     */
    public function run();

    /**
     * Gets the application root dir.
     *
     * @return string
     */
    public function getRootDir();
}


text:
package objsets

import TweetReader._

/**
 * A class to represent tweets.
 */
class Tweet(val user: String, val text: String, val retweets: Int) {
  override def toString: String =
    "User: " + user + "\n" +
      "Text: " + text + " [" + retweets + "]"
}

/**
 * This represents a set of objects of type `Tweet` in the form of a binary search
 * tree. Every branch in the tree has two children (two `TweetSet`s). There is an
 * invariant which always holds: for every branch `b`, all elements in the left
 * subtree are smaller than the tweet at `b`. The elements in the right subtree are
 * larger.
 *
 * Note that the above structure requires us to be able to compare two tweets (we
 * need to be able to say which of two tweets is larger, or if they are equal). In
 * this implementation, the equality / order of tweets is based on the tweet's text
 * (see `def incl`). Hence, a `TweetSet` could not contain two tweets with the same
 * text from different users.
 *
 *
 * The advantage of representing sets as binary search trees is that the elements
 * of the set can be found quickly. If you want to learn more you can take a look
 * at the Wikipedia page [1], but this is not necessary in order to solve this
 * assignment.
 *
 * [1] http://en.wikipedia.org/wiki/Binary_search_tree
 */
abstract class TweetSet {

  /**
   * Tests if this set is empty.
   */
  def isEmpty: Boolean

  /**
   * This method takes a predicate and returns a subset of all the elements
   * in the original set for which the predicate is true.
   *
   * Question: Can we implment this method here, or should it remain abstract
   * and be implemented in the subclasses?
   */
  def filter(p: Tweet => Boolean): TweetSet = filterAcc(p, new Empty)

  /**
   * This is a helper method for `filter` that propagetes the accumulated tweets.
   */
  def filterAcc(p: Tweet => Boolean, acc: TweetSet): TweetSet

  /**
   * Returns a new `TweetSet` that is the union of `TweetSet`s `this` and `that`.
   *
   * Question: Should we implment this method here, or should it remain abstract
   * and be implemented in the subclasses?
   */
  def union(that: TweetSet): TweetSet

  /**
   * Returns the tweet from this set which has the greatest retweet count.
   *
   * Calling `mostRetweeted` on an empty set should throw an exception of
   * type `java.util.NoSuchElementException`.
   *
   * Question: Should we implment this method here, or should it remain abstract
   * and be implemented in the subclasses?
   */
  def mostRetweeted: Tweet

  /**
   * Returns a list containing all tweets of this set, sorted by retweet count
   * in descending order. In other words, the head of the resulting list should
   * have the highest retweet count.
   *
   * Hint: the method `remove` on TweetSet will be very useful.
   * Question: Should we implment this method here, or should it remain abstract
   * and be implemented in the subclasses?
   */
  def descendingByRetweet: TweetList

  /**
   * The following methods are already implemented
   */

  /**
   * Returns a new `TweetSet` which contains all elements of this set, and the
   * the new element `tweet` in case it does not already exist in this set.
   *
   * If `this.contains(tweet)`, the current set is returned.
   */
  def incl(tweet: Tweet): TweetSet

  /**
   * Returns a new `TweetSet` which excludes `tweet`.
   */
  def remove(tweet: Tweet): TweetSet

  /**
   * Tests if `tweet` exists in this `TweetSet`.
   */
  def contains(tweet: Tweet): Boolean

  /**
   * This method takes a function and applies it to every element in the set.
   */
  def foreach(f: Tweet => Unit): Unit
}

class Empty extends TweetSet {

  def isEmpty: Boolean = true

  def filterAcc(p: Tweet => Boolean, acc: TweetSet): TweetSet = acc

  def union(that: TweetSet): TweetSet = that

  def mostRetweeted: Tweet = throw new NoSuchElementException

  def descendingByRetweet: TweetList = Nil

  /**
   * The following methods are already implemented
   */

  def contains(tweet: Tweet): Boolean = false

  def incl(tweet: Tweet): TweetSet = new NonEmpty(tweet, new Empty, new Empty)

  def remove(tweet: Tweet): TweetSet = this

  def foreach(f: Tweet => Unit): Unit = ()

  override def toString = "."
}

class NonEmpty(elem: Tweet, left: TweetSet, right: TweetSet) extends TweetSet {

  def isEmpty: Boolean = false

  def filterAcc(p: Tweet => Boolean, acc: TweetSet): TweetSet =
    if (p(elem))
      left.union(right).filterAcc(p, acc.incl(elem))
    else
      left.union(right).filterAcc(p, acc)

  def union(that: TweetSet): TweetSet =
    left union (right union (that incl elem))

  def mostRetweeted: Tweet = {
    var result = elem
    foreach(tweet => if (tweet.retweets > result.retweets) result = tweet)
    result
  }

  def descendingByRetweet: TweetList = {
    val mostRetweeted = this.mostRetweeted
    new Cons(mostRetweeted, this.remove(mostRetweeted).descendingByRetweet)
  }

  /**
   * The following methods are already implemented
   */

  def contains(x: Tweet): Boolean =
    if (x.text < elem.text) left.contains(x)
    else if (elem.text < x.text) right.contains(x)
    else true

  def incl(x: Tweet): TweetSet = {
    if (x.text < elem.text) new NonEmpty(elem, left.incl(x), right)
    else if (elem.text < x.text) new NonEmpty(elem, left, right.incl(x))
    else this
  }

  def remove(tw: Tweet): TweetSet =
    if (tw.text < elem.text) new NonEmpty(elem, left.remove(tw), right)
    else if (elem.text < tw.text) new NonEmpty(elem, left, right.remove(tw))
    else left.union(right)

  def foreach(f: Tweet => Unit): Unit = {
    f(elem)
    left.foreach(f)
    right.foreach(f)
  }

  override def toString = "{" + left + elem + right + "}"
}

trait TweetList {
  def head: Tweet
  def tail: TweetList
  def isEmpty: Boolean
  def foreach(f: Tweet => Unit): Unit =
    if (!isEmpty) {
      f(head)
      tail.foreach(f)
    }
}

object Nil extends TweetList {
  def head = throw new java.util.NoSuchElementException("head of EmptyList")
  def tail = throw new java.util.NoSuchElementException("tail of EmptyList")
  def isEmpty = true
  override def toString = "."
}

class Cons(val head: Tweet, val tail: TweetList) extends TweetList {
  def isEmpty = false
  override def toString = head + ", " + tail
}

object GoogleVsApple {
  val google = List("android", "Android", "galaxy", "Galaxy", "nexus", "Nexus")
  val apple = List("ios", "iOS", "iphone", "iPhone", "ipad", "iPad")

  lazy val googleTweets: TweetSet =
    TweetReader.allTweets.filter(tweet => google.exists(s => tweet.text.contains(s)))
  lazy val appleTweets: TweetSet =
    TweetReader.allTweets.filter(tweet => apple.exists(s => tweet.text.contains(s)))

  /**
   * A list of all tweets mentioning a keyword from either apple or google,
   * sorted by the number of retweets.
   */
  lazy val trending: TweetList = googleTweets.union(appleTweets).descendingByRetweet
}

object Main extends App {
  // Print the trending tweets
  GoogleVsApple.trending foreach println
}


text:
/**
 * @param {Object} plainMessage
 * @constructor
 */
function JanusMessage(plainMessage) {
  this._plainMessage = plainMessage;
}

/**
 * @returns {Object}
 */
JanusMessage.prototype.getPlainMessage = function() {
  return this._plainMessage;
};

/**
 * @returns {Object}
 */
JanusMessage.prototype.getError = function() {
  return this.get('error');
};

/**
 * @param {...string} name
 * @returns {*}
 */
JanusMessage.prototype.get = function(name) {
  var names = Array.prototype.slice.call(arguments, 1);
  var result = this._plainMessage[name];

  for (var i = 0; i < names.length; i++) {
    name = names[i];
    if (result) {
      result = result[name];
    } else {
      break;
    }
  }

  return result || null;
};

module.exports = JanusMessage;


text:
package main

import (
	"bytes"
	"net/http"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/xmidt-org/webpa-common/logging"
	"github.com/xmidt-org/webpa-common/webhook"
	"github.com/xmidt-org/wrp-go/v2"
)

type result struct {
	URL      string
	event    string
	transID  string
	deviceID string
}

// Make a simple RoundTrip implementation that let's me short-circuit the network
type swTransport struct {
	i       int32
	fn      func(*http.Request, int) (*http.Response, error)
	results []result
	mutex   sync.Mutex
}

func (t *swTransport) RoundTrip(req *http.Request) (*http.Response, error) {

	//
	atomic.AddInt32(&t.i, 1)

	r := result{URL: req.URL.String(),
		event:    req.Header.Get("X-Webpa-Event"),
		transID:  req.Header.Get("X-Webpa-Transaction-Id"),
		deviceID: req.Header.Get("X-Webpa-Device-Id"),
	}

	t.mutex.Lock()
	t.results = append(t.results, r)
	t.mutex.Unlock()

	resp := &http.Response{Status: "200 OK", StatusCode: 200}
	return resp, nil
}

func getFakeFactory() *SenderWrapperFactory {

	fakeDDTIP := new(mockCounter)
	fakeDDTIP.On("Add", 1.0).Return()

	fakeGauge := new(mockGauge)
	fakeGauge.On("Add", 1.0).Return().
		On("Add", -1.0).Return().
		//On("With", []string{"url", "unknown"}).Return(fakeGauge).
		On("With", []string{"url", "http://localhost:8888/foo"}).Return(fakeGauge).
		On("With", []string{"url", "http://localhost:9999/foo"}).Return(fakeGauge)

	fakeIgnore := new(mockCounter)
	fakeIgnore.On("Add", 1.0).Return().On("Add", 0.0).Return().
		On("With", []string{"url", "http://localhost:8888/foo"}).Return(fakeIgnore).
		On("With", []string{"url", "http://localhost:9999/foo"}).Return(fakeIgnore).
		On("With", []string{"url", "http://localhost:8888/foo", "event", "unknown"}).Return(fakeIgnore).
		On("With", []string{"url", "http://localhost:9999/foo", "event", "unknown"}).Return(fakeIgnore).
		On("With", []string{"url", "http://localhost:8888/foo", "reason", "cut_off"}).Return(fakeIgnore).
		On("With", []string{"url", "http://localhost:8888/foo", "reason", "queue_full"}).Return(fakeIgnore).
		On("With", []string{"url", "http://localhost:8888/foo", "reason", "expired"}).Return(fakeIgnore).
		On("With", []string{"url", "http://localhost:8888/foo", "reason", "expired_before_queueing"}).Return(fakeIgnore).
		On("With", []string{"url", "http://localhost:8888/foo", "reason", "network_err"}).Return(fakeIgnore).
		On("With", []string{"url", "http://localhost:8888/foo", "reason", "invalid_config"}).Return(fakeIgnore).
		On("With", []string{"url", "http://localhost:9999/foo", "reason", "cut_off"}).Return(fakeIgnore).
		On("With", []string{"url", "http://localhost:9999/foo", "reason", "queue_full"}).Return(fakeIgnore).
		On("With", []string{"url", "http://localhost:9999/foo", "reason", "expired"}).Return(fakeIgnore).
		On("With", []string{"url", "http://localhost:9999/foo", "reason", "expired_before_queueing"}).Return(fakeIgnore).
		On("With", []string{"url", "http://localhost:9999/foo", "reason", "network_err"}).Return(fakeIgnore).
		On("With", []string{"url", "http://localhost:9999/foo", "reason", "invalid_config"}).Return(fakeIgnore).
		On("With", []string{"url", "http://localhost:8888/foo", "code", "200", "event", "unknown"}).Return(fakeIgnore).
		On("With", []string{"url", "http://localhost:9999/foo", "code", "200", "event", "unknown"}).Return(fakeIgnore).
		On("With", []string{"event", "iot"}).Return(fakeIgnore).
		On("With", []string{"event", "test/extra-stuff"}).Return(fakeIgnore).
		On("With", []string{"event", "bob/magic/dog"}).Return(fakeIgnore).
		On("With", []string{"event", "unknown"}).Return(fakeIgnore).
		On("With", []string{"content_type", "msgpack"}).Return(fakeIgnore).
		On("With", []string{"content_type", "json"}).Return(fakeIgnore).
		On("With", []string{"content_type", "http"}).Return(fakeIgnore).
		On("With", []string{"content_type", "other"}).Return(fakeIgnore)

	fakeRegistry := new(mockCaduceusMetricsRegistry)
	fakeRegistry.On("NewCounter", DropsDueToInvalidPayload).Return(fakeDDTIP)
	fakeRegistry.On("NewCounter", DeliveryRetryCounter).Return(fakeIgnore)
	fakeRegistry.On("NewCounter", DeliveryCounter).Return(fakeIgnore)
	fakeRegistry.On("NewCounter", SlowConsumerCounter).Return(fakeIgnore)
	fakeRegistry.On("NewCounter", SlowConsumerDroppedMsgCounter).Return(fakeIgnore)
	fakeRegistry.On("NewCounter", IncomingContentTypeCounter).Return(fakeIgnore)
	fakeRegistry.On("NewCounter", IncomingEventTypeCounter).Return(fakeIgnore)
	fakeRegistry.On("NewCounter", DropsDueToPanic).Return(fakeIgnore)
	fakeRegistry.On("NewGauge", OutgoingQueueDepth).Return(fakeGauge)
	fakeRegistry.On("NewGauge", DeliveryRetryMaxGauge).Return(fakeGauge)
	fakeRegistry.On("NewGauge", ConsumerRenewalTimeGauge).Return(fakeGauge)
	fakeRegistry.On("NewGauge", ConsumerDeliverUntilGauge).Return(fakeGauge)
	fakeRegistry.On("NewGauge", ConsumerDropUntilGauge).Return(fakeGauge)
	fakeRegistry.On("NewGauge", ConsumerDeliveryWorkersGauge).Return(fakeGauge)
	fakeRegistry.On("NewGauge", ConsumerMaxDeliveryWorkersGauge).Return(fakeGauge)

	return &SenderWrapperFactory{
		NumWorkersPerSender: 10,
		QueueSizePerSender:  10,
		CutOffPeriod:        30 * time.Second,
		Logger:              logging.DefaultLogger(),
		Linger:              0 * time.Second,
		MetricsRegistry:     fakeRegistry,
	}
}

func TestInvalidLinger(t *testing.T) {
	swf := getFakeFactory()
	sw, err := swf.New()

	assert := assert.New(t)
	assert.Nil(sw)
	assert.NotNil(err)
}

// Commenting this test out is accumulating technical debt.
// The reason this code doesn't work now is because the timeout in webpa-common
// is hard coded to 5min at this point.  The ways to address this are:
// 1. Remove the limitation of 5min as the only timeout
// -or-
// 2. Add a mock for the webhook implementation

func TestSwSimple(t *testing.T) {
	assert := assert.New(t)

	wrpMessage := wrp.SimpleRequestResponse{
		Source:          "mac:112233445566",
		Destination:     "event:wrp",
		TransactionUUID: "12345",
	}

	var buffer bytes.Buffer
	encoder := wrp.NewEncoder(&buffer, wrp.Msgpack)
	err := encoder.Encode(&wrpMessage)
	assert.Nil(err)

	iot := simpleRequest()
	iot.Destination = "mac:112233445566/event/iot"
	test := simpleRequest()
	test.Destination = "mac:112233445566/event/test/extra-stuff"

	trans := &swTransport{}

	swf := getFakeFactory()
	swf.Sender = trans.RoundTrip

	swf.Linger = 1 * time.Second
	sw, err := swf.New()

	assert.Nil(err)
	assert.NotNil(sw)

	// No listeners
	sw.Queue(iot)
	sw.Queue(iot)
	sw.Queue(iot)

	assert.Equal(int32(0), trans.i)

	w1 := webhook.W{
		Duration: 6 * time.Second,
		Until:    time.Now().Add(6 * time.Second),
		Events:   []string{"iot"},
	}
	w1.Config.URL = "http://localhost:8888/foo"
	w1.Config.ContentType = "application/json"
	w1.Matcher.DeviceId = []string{"mac:112233445566"}

	w2 := webhook.W{
		Duration: 4 * time.Second,
		Until:    time.Now().Add(4 * time.Second),
		Events:   []string{"iot", "test/extra-stuff", "wrp"},
	}
	w2.Config.URL = "http://localhost:9999/foo"
	w2.Config.ContentType = "application/json"
	w2.Matcher.DeviceId = []string{"mac:112233445566"}

	// Add 2 listeners
	list := []webhook.W{w1, w2}

	sw.Update(list)

	// Send iot message

	sw.Queue(iot)

	// Send test message
	sw.Queue(test)

	// Send it again
	sw.Queue(test)

	w3 := webhook.W{
		Events: []string{"iot"},
	}
	w3.Config.URL = "http://localhost:9999/foo"
	w3.Config.ContentType = "application/json"

	// We get a registration
	list2 := []webhook.W{w3}
	sw.Update(list2)
	time.Sleep(time.Second)

	// Send iot
	sw.Queue(iot)

	sw.Shutdown(true)
	//assert.Equal(int32(4), atomic.LoadInt32(&trans.i))
}


text:
'use strict';

angular.module('myApp')
    .directive('ngbsForm', function ($timeout) {
        return {
            'template': '<form autocomplete="off" novalidate class="form-horizontal" role="form" name="{{name}}" ng-transclude></form>',
            'restrict': 'E',
            'transclude': true,
            'scope': {
                'submit': "&onSubmit",
                'name': "@"
            },
            'controller': function ($scope) {

                var _target = {},
                    self = this;

                this.getForm = function () {
                    return $scope[$scope.name];
                };
                this.submit = function (e) {

                    $scope.$broadcast('submit');
                    if (!self.getForm().$invalid) {
                        $timeout(function () {
                            $scope.submit({"target": _target});
                        });
                    }
                };
                this.clean = function () {
                    $scope.$broadcast('clean');
                };

                this.set = function (name, value) {
                    _target[name] = value;
                }

            }
        };
    })
    .directive('ngbsFieldset', function () {
        return {
            'require': '^ngbsForm',
            'restrict': 'E',
            'replace': true,
            'scope': {
                name: '@',
                label: '@',
                type: '@',
                required: '=',
                options: '=',
                equal: '@',
            },

            'transclude': true,

            'template': '
' +
            '' +
            '
' +
            '<input class="form-control" autocomplete="off" >' +
            '

' +
            '
' +
            '
',

            'controller': function ($scope) {
                this.invaild = function (type) {
                    var _type = type;
                    switch (type) {
                        case 'min':
                            _type = "minlength";
                            break;
                        case 'max':
                            _type = "maxlength";
                            break;
                        case 'equal':
                            _type = "equalto";
                            break;
                        case 'error':
                            _type = "ngbserror";
                            break;
                    }

                    return ($scope.submitted || $scope.filedset.$dirty) && !!$scope.filedset.$error[_type];
                };
            },

            'compile': function (tElems, tAttrs, form) {

                function setCommonAttr (ele) {
                    ele.attr("id", "_id_" + tAttrs.name)
                        .attr("name", tAttrs.name)
                        .attr("ng-model", "target." + tAttrs.name);
                }

                function setValidationOption (target) {

                    tAttrs.min && target.attr("ng-minlength", tAttrs.min);

                    tAttrs.max && target.attr("ng-maxlength", tAttrs.max);

                    tAttrs.equal && target.attr("equalTo", tAttrs.equal);

                    tAttrs.error && target.attr("ngbserror", "");

                    tAttrs.required == "true" && target.attr("required", "");

                }

                var $input = $(tElems).find("input");
                switch (tAttrs.type) {
                    case "select":
                        var $select = $('<select class="form-control"><option value="">---请选择---</option></select>');

                        $select.attr("ng-options", "opt.label for opt in options");
                        setCommonAttr($select);
                        setValidationOption($select);
                        $input.replaceWith($select);
                        break;
                    default :
                        if (tAttrs.type) {
                            $input.attr("type", tAttrs.type);
                        }
                        setCommonAttr($input);
                        setValidationOption($input);
                }

                $(tElems).find("label").attr("for", "_id_" + tAttrs.name).html('* ' + tAttrs.label);

                return {

                    post: function (scope, elems, attrs, form) {
                        var nbsform = form.getForm();

                        scope.submitted = false;
                        scope.filedset = nbsform[scope.name];
                        scope.defaultErrMessage = "";

                        scope.isError = function () {
                            return (scope.submitted || scope.filedset.$dirty ) && scope.filedset.$invalid;
                        };

                        scope.$on('submit', function (event) {
                            scope.submitted = true;
                            scope.target && form.set(tAttrs.name, scope.target[tAttrs.name]);
                        });

                        scope.$on('clean', function () {
                            scope.target && (scope.target[tAttrs.name] = "");
                        });
                    }
                }
            }
        };
    })
    .directive('invaildMessage', function () {
        return {
            'restrict': 'E',
            'require': '^ngbsFieldset',
            'replace': true,
            'transclude': true,
            'template': '',
            'scope': {
                'type': '@'
            },
            'link': function (scope, element, attrs, field) {
                scope.invaild = function () {
                    return field.invaild(scope.type)
                };
            }
        };
    })
    .directive('ngbsController', function () {
        return {
            'restrict': 'E',
            'require': '^ngbsForm',
            'replace': true,
            'scope': {},
            'transclude': true,
            'template': '
' +
            '
' +
            '<button class="btn btn-success" type="button" ng-click="submit($event)">提交</button> ' +
            '<button class="btn btn-default" type="button" ng-click="reset()">重置</button>' +
            '
' +
            '
',
            'link': function (scope, element, attrs, form) {
                scope.submit = form.submit;
                scope.reset = form.clean;
            }
        };
    })

    .directive('equalto', function () {
        return {
            require: 'ngModel',
            link: function (scope, elem, attrs, ctrl) {
                var preNode = elem.parents("form").find('input[name="' + attrs.equalto + '"]');

                elem.add(preNode).on('keyup', function () {
                    scope.$apply(function () {
                        ctrl.$setValidity('equalto', elem.val() === preNode.val());
                    });
                });
            }
        };
    })
    .directive('ngbserror', function () {
        return {
            require: 'ngModel',
            link: function (scope, elem, attrs, ctrl) {
                scope.$on('ngbs-error', function (event, isError, formname) {
                    if(!formname){
                        ctrl.$setValidity('ngbserror', !isError);
                    }else{
                        if(formname === ctrl.$name){
                            ctrl.$setValidity('ngbserror', !isError);
                        }
                    }
                });

            }
        };
    });


text:
from lucene import PythonSet, PythonIterator, JavaError

class JavaSet(PythonSet):
    """
    This class implements java.util.Set around a Python set instance it wraps.
    """

    def __init__(self, _set):
        super(JavaSet, self).__init__()
        self._set = _set

    def __contains__(self, obj):
        return obj in self._set

    def __len__(self):
        return len(self._set)

    def __iter__(self):
        return iter(self._set)

    def add(self, obj):
        if obj not in self._set:
            self._set.add(obj)
            return True
        return False

    def addAll(self, collection):
        size = len(self._set)
        self._set.update(collection)
        return len(self._set) > size

    def clear(self):
        self._set.clear()

    def contains(self, obj):
        return obj in self._set

    def containsAll(self, collection):
        for obj in collection:
            if obj not in self._set:
                return False
        return True

    def equals(self, collection):
        if type(self) is type(collection):
            return self._set == collection._set
        return False

    def isEmpty(self):
        return len(self._set) == 0

    def iterator(self):
        class _iterator(PythonIterator):
            def __init__(_self):
                super(_iterator, _self).__init__()
                _self._iterator = iter(self._set)
            def hasNext(_self):
                if hasattr(_self, '_next'):
                    return True
                try:
                    _self._next = _self._iterator.next()
                    return True
                except StopIteration:
                    return False
            def next(_self):
                if hasattr(_self, '_next'):
                    next = _self._next
                    del _self._next
                else:
                    next = _self._iterator.next()
                return next
        return _iterator()

    def remove(self, obj):
        try:
            self._set.remove(obj)
            return True
        except KeyError:
            return False

    def removeAll(self, collection):
        result = False
        for obj in collection:
            try:
                self._set.remove(obj)
                result = True
            except KeyError:
                pass
        return result

    def retainAll(self, collection):
        result = False
        for obj in list(self._set):
            if obj not in c:
                self._set.remove(obj)
                result = True
        return result

    def size(self):
        return len(self._set)

    def toArray(self):
        return list(self._set)


text:
<?php

namespace DCarbone\PHPFHIRGenerated\R4\PHPFHIRTests\FHIRElement;

use PHPUnit\Framework\TestCase;
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRAuditEventAction;

/**
 * Class FHIRAuditEventActionTest
 * @package \DCarbone\PHPFHIRGenerated\R4\PHPFHIRTests\FHIRElement
 */
class FHIRAuditEventActionTest extends TestCase
{
    public function testCanConstructTypeNoArgs()
    {
        $type = new FHIRAuditEventAction();
        $this->assertInstanceOf('\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRAuditEventAction', $type);
    }
}


text:
'''
Copyright 2015 Planet Labs, Inc.
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.
'''
import logging
import numpy

from osgeo import gdal

from radiometric_normalization import gimage
from radiometric_normalization import pif

def generate(candidate_path, reference_path,
             method='filter_alpha', method_options=None,
             last_band_alpha=False):
    ''' Generates psuedo invariant features as a mask

    :param str candidate_path: Path to the candidate image
    :param str reference_path: Path to the reference image
    :param str method: Which psuedo invariant feature generation method to use
    :param object method_options: A passthrough argument for any specific
        options for the method chosen:
            - Not applicable for 'filter_alpha'
            - The width of the filter for 'filter_PCA'

    :returns: A boolean array in the same coordinate system of the
        candidate/reference image (True for the PIF)
    '''
    if method == 'filter_alpha':
        _, c_alpha, c_band_count = _open_image_and_get_info(
            candidate_path, last_band_alpha)
        _, r_alpha, r_band_count = _open_image_and_get_info(
            reference_path, last_band_alpha)

        _assert_consistent(c_alpha, r_alpha, c_band_count, r_band_count)
        combined_alpha = numpy.logical_and(c_alpha, r_alpha)

        pif_mask = pif.generate_alpha_band_pifs(combined_alpha)
    elif method == 'filter_PCA':
        c_ds, c_alpha, c_band_count = _open_image_and_get_info(
            candidate_path, last_band_alpha)
        r_ds, r_alpha, r_band_count = _open_image_and_get_info(
            reference_path, last_band_alpha)

        _assert_consistent(c_alpha, r_alpha, c_band_count, r_band_count)
        combined_alpha = numpy.logical_and(c_alpha, r_alpha)

        if method_options:
            parameters = method_options
        else:
            parameters = pif.DEFAULT_PCA_OPTIONS

        pif_mask = numpy.ones(c_alpha.shape, dtype=numpy.bool)
        for band_no in range(1, c_band_count + 1):
            logging.info('PIF: Band {}'.format(band_no))
            c_band = gimage.read_single_band(c_ds, band_no)
            r_band = gimage.read_single_band(r_ds, band_no)
            pif_band_mask = pif.generate_pca_pifs(
                c_band, r_band, combined_alpha, parameters)
            pif_mask = numpy.logical_and(pif_mask, pif_band_mask)

        no_total_pixels = c_alpha.size
        no_valid_pixels = len(numpy.nonzero(pif_mask)[0])
        valid_percent = 100.0 * no_valid_pixels / no_total_pixels
        logging.info(
            'PIF: Found {} final pifs out of {} pixels ({}%) for all '
            'bands'.format(no_valid_pixels, no_total_pixels, valid_percent))
    elif method == 'filter_robust':
        c_ds, c_alpha, c_band_count = _open_image_and_get_info(
            candidate_path, last_band_alpha)
        r_ds, r_alpha, r_band_count = _open_image_and_get_info(
            reference_path, last_band_alpha)

        _assert_consistent(c_alpha, r_alpha, c_band_count, r_band_count)
        combined_alpha = numpy.logical_and(c_alpha, r_alpha)

        if method_options:
            parameters = method_options
        else:
            parameters = pif.DEFAULT_ROBUST_OPTIONS

        pif_mask = numpy.ones(c_alpha.shape, dtype=numpy.bool)
        for band_no in range(1, c_band_count + 1):
            logging.info('PIF: Band {}'.format(band_no))
            c_band = gimage.read_single_band(c_ds, band_no)
            r_band = gimage.read_single_band(r_ds, band_no)
            pif_band_mask = pif.generate_robust_pifs(
                c_band, r_band, combined_alpha, parameters)
            pif_mask = numpy.logical_and(pif_mask, pif_band_mask)

        no_total_pixels = c_alpha.size
        no_valid_pixels = len(numpy.nonzero(pif_mask)[0])
        valid_percent = 100.0 * no_valid_pixels / no_total_pixels
        logging.info(
            'PIF: Found {} final pifs out of {} pixels ({}%) for all '
            'bands'.format(no_valid_pixels, no_total_pixels, valid_percent))
    else:
        raise NotImplementedError('Only "filter_alpha", "filter_PCA" and '
                                  '"filter_robust" methods are implemented.')

    return pif_mask

def _open_image_and_get_info(path, last_band_alpha):
    gdal_ds = gdal.Open(path)
    alpha_band, band_count = gimage.read_alpha_and_band_count(
        gdal_ds, last_band_alpha=last_band_alpha)
    return gdal_ds, alpha_band, band_count

def _assert_consistent(c_alpha, r_alpha, c_band_count, r_band_count):
    assert r_band_count == c_band_count
    assert r_alpha.shape == c_alpha.shape


text:
#ifndef MEGAMOL_UTILITY_JSONHELPER_INCLUDED
#define MEGAMOL_UTILITY_JSONHELPER_INCLUDED

#include <string>

#include <nlohmann/json.hpp>

#include "mmcore/utility/log/Log.h"

namespace megamol {
namespace core {
namespace utility {

/**
 * Read value from given JSON node
 */
template<typename T>
bool get_json_value(
    const nlohmann::json& in_json, const std::vector<std::string>& in_nodes, T* out_value, size_t array_size = 0) {

    try {
        std::string node_name;
        auto json_value = in_json;
        auto node_count = in_nodes.size();
        if (node_count != 0) {
            node_name = in_nodes.front();
            json_value = in_json.at(in_nodes.front());
            for (size_t i = 1; i < node_count; i++) {
                node_name = node_name + "/" + in_nodes[i];
                json_value = json_value.at(in_nodes[i]);
            }
        }
        if (array_size > 0) {
            if (!json_value.is_array()) {
                megamol::core::utility::log::Log::DefaultLog.WriteError(
                    "JSON ERROR - %s is no JSON array. [%s, %s, line %d]\n", node_name.c_str(), __FILE__, __FUNCTION__,
                    __LINE__);
                return false;
            }
            if (json_value.size() != array_size) {
                megamol::core::utility::log::Log::DefaultLog.WriteError(
                    "JSON ERROR - %s is no JSON array of size %i. [%s, %s, line %d]\n", node_name.c_str(), array_size,
                    __FILE__, __FUNCTION__, __LINE__);
                return false;
            }
            for (size_t i = 0; i < array_size; i++) {
                if constexpr (std::is_same_v<T, bool>) {
                    if (json_value[i].is_boolean()) {
                        out_value[i] = json_value[i];
                    } else {
                        megamol::core::utility::log::Log::DefaultLog.WriteError(
                            "JSON ERROR - Couldn't read 'bool' value from json node '%s'. [%s, %s, line %d]\n",
                            node_name.c_str(), __FILE__, __FUNCTION__, __LINE__);
                        return false;
                    }
                } else if constexpr (std::is_same_v<T, float> || std::is_same_v<T, int>) {
                    if (json_value[i].is_number()) {
                        out_value[i] = json_value[i];
                    } else {
                        bool nan_case = false;
                        if (json_value[i].is_string()) {
                            if (json_value[i] == "null") {
                                out_value[i] = std::numeric_limits<T>::quiet_NaN();
                                nan_case = true;
                            }
                        }
                        if (!nan_case) {
                            megamol::core::utility::log::Log::DefaultLog.WriteError(
                                "JSON ERROR - Couldn't read 'float' or 'int' value from json node '%s'. [%s, %s, line "
                                "%d]\n",
                                node_name.c_str(), __FILE__, __FUNCTION__, __LINE__);
                            return false;
                        }
                    }
                } else {
                    megamol::core::utility::log::Log::DefaultLog.WriteError(
                        "JSON ERROR - Unknown value type for array. [%s, %s, line %d]\n", node_name.c_str(), __FILE__,
                        __FUNCTION__, __LINE__);
                    return false;
                }
            }
        } else {
            if constexpr (std::is_same_v<T, bool>) {
                if (json_value.is_boolean()) {
                    json_value.get_to((*out_value));
                } else {
                    megamol::core::utility::log::Log::DefaultLog.WriteError(
                        "JSON ERROR - Couldn't read 'bool' value from json node '%s'. [%s, %s, line %d]\n",
                        node_name.c_str(), __FILE__, __FUNCTION__, __LINE__);
                    return false;
                }
            } else if constexpr (std::is_same_v<T, std::string>) {
                if (json_value.is_string()) {
                    std::string value;
                    json_value.get_to((*out_value));
                } else {
                    megamol::core::utility::log::Log::DefaultLog.WriteError(
                        "JSON ERROR - Couldn't read 'string' value from json node '%s'. [%s, %s, line %d]\n",
                        node_name.c_str(), __FILE__, __FUNCTION__, __LINE__);
                    return false;
                }
            } else if constexpr (std::is_same_v<T, float> || std::is_same_v<T, int> ||
                                 std::is_same_v<T, unsigned int>) {
                if (json_value.is_number()) {
                    json_value.get_to((*out_value));
                } else {
                    bool nan_case = false;
                    if (json_value.is_string()) {
                        if (json_value == "null") {
                            (*out_value) = std::numeric_limits<T>::quiet_NaN();
                            nan_case = true;
                        }
                    }
                    if (!nan_case) {
                        megamol::core::utility::log::Log::DefaultLog.WriteError(
                            "JSON ERROR - Couldn't read 'float' or 'int' value from json node '%s'. [%s, %s, line "
                            "%d]\n",
                            node_name.c_str(), __FILE__, __FUNCTION__, __LINE__);
                        return false;
                    }
                }
            } else {
                megamol::core::utility::log::Log::DefaultLog.WriteError(
                    "JSON ERROR - Unknown value type. [%s, %s, line %d]\n", node_name.c_str(), __FILE__, __FUNCTION__,
                    __LINE__);
                return false;
            }
        }
        return true;
    } catch (nlohmann::json::type_error& e) {
        megamol::core::utility::log::Log::DefaultLog.WriteError(
            "JSON TYPE ERROR: %s. [%s, %s, line %d]\n", e.what(), __FILE__, __FUNCTION__, __LINE__);
        return false;
    } catch (nlohmann::json::exception& e) {
        megamol::core::utility::log::Log::DefaultLog.WriteWarn(
            "JSON: %s. [%s, %s, line %d]\n", e.what(), __FILE__, __FUNCTION__, __LINE__);
        return false;
    } catch (...) {
        megamol::core::utility::log::Log::DefaultLog.WriteError(
            "JSON ERROR - Unknown Error. [%s, %s, line %d]\n", __FILE__, __FUNCTION__, __LINE__);
        return false;
    }
}

} /* namespace utility */
} /* namespace core */
} /* namespace megamol */

#endif // MEGAMOL_UTILITY_JSONHELPER_INCLUDED


text:
package org.fest.assertions.api;

import static java.math.BigDecimal.ONE;
import static java.math.BigDecimal.ZERO;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;

import java.math.BigDecimal;

import org.junit.Test;

/**
 * Tests for {@link Assertions#assertThat(BigDecimal)}.
 *
 * @author Alex Ruiz
 * @author Yvonne Wang
 */
public class Assertions_assertThat_with_BigDecimal_Test {

  @Test
  public void should_create_Assert() {
    BigDecimalAssert assertions = Assertions.assertThat(ZERO);
    assertNotNull(assertions);
  }

  @Test
  public void should_pass_actual() {
    BigDecimalAssert assertions = Assertions.assertThat(ONE);
    assertSame(ONE, assertions.actual);
  }
}


text:
<#
.SYNOPSIS
    Get installed Appx package information.
.DESCRIPTION
    A wrapper for Get-AppxPackage, this script provides additional info beyond
    Get-AppxPackage's including:
     - DisplayName
     - Manifest parsed as XML
     - InstallLocation as file item
     - Application IDs
     - Registered background tasks
.PARAMETER Filter
    The filter passed to Get-AppxPackage.
.PARAMETER MergeType
    Usually the results output are of a custom PSObject type that cannot be
    fed into pre-existing PowerShell Appx commands. MergeType will instead
    use the pre-existing PowerShell types and attach new properties (that
    will not be displayed by the existing type) to the existing types.
.EXAMPLE
    PS C:\Users\Dave> Get-AppxPackageExt.ps1 *Skype*

    PackageFullName     : Microsoft.SkypeApp_2.8.0.1001_x86__kzf8qxf38zg5c
    DisplayName         : Skype
    InstallLocationItem : C:\Program Files\WindowsApps\Microsoft.SkypeApp_2.8.0.1001_x86__kzf8qxf38zg5c
    Manifest            : #document
    ApplicationIds      : {App}
    BackgroundTasks     : {@{Name=userAccountStateChangedBackgroundTask; Id={516560FE-4EEE-4FDE-9017-7B7742D656C4}},
                          @{Name=keepAliveTimerTriggerBackgroundTask; Id={47B17C4A-0953-416A-8EF0-EDFF9415E080}},
                          @{Name=refreshChannelUriBackgroundTask; Id={BC523B83-5B2F-4F37-972C-50877A49DE7A}}}
    InstallTimeUtc      : 5/7/2014 10:14:32 AM
.LINK
    Add-AppxPackageExt.ps1
.LINK
    Debug-AppxPackage.ps1
.LINK
    Get-AppxPackageExt.ps1
.LINK
    Get-AppxPackageFile.ps1
.LINK
    Get-ProcessAppxPackage.ps1
.LINK
    Launch-AppxPackage.ps1
.LINK
    Launch-AppxPackageBackgroundTask.ps1
.LINK
    Resume-AppxPackage.ps1
.LINK
    Suspend-AppxPackage.ps1
.LINK
    Terminate-AppxPackage.ps1
#>
param([string] $Filter,
	[switch] $MergeType);

$merge = !!$MergeType;
$myPath = (Split-Path -Parent ($MyInvocation.MyCommand.Path));
function ScriptDir($additional) {
	 $myPath + "\" + $additional;
}

$appxPackageType = "AppxPackageExtType";
if ((Get-TypeData $appxPackageType) -eq $null) {
	Update-TypeData -TypeName $appxPackageType -DefaultDisplayPropertySet @("PackageFullName","DisplayName","InstallLocationItem","Manifest","ApplicationIds","BackgroundTasks","InstallTimeUtc");
}

$packages = ($input | %{ $_; } | ?{ $_; });

if (!$packages) {
	if ($Filter) {
		$packages = Get-AppxPackage $Filter;
	}
	else {
		$packages = Get-AppxPackage;
	}
}

$packages | %{
	$appxPackage = $_;

	$installLocationItem = $null;
	$installTimeUtc = $null;
	$manifestAsXml = $null;
	$displayName = $null;
	$applicationIds = @();
	$backgroundTasks = @();

	if ($_.InstallLocation -and (Test-Path $_.InstallLocation)) {
		$installLocationItem = (gi $_.InstallLocation);
		$installTimeUtc = $installLocationItem.CreationTimeUtc;
		$manifestAsXml = Get-AppxPackageManifest -Package $_.PackageFullName;
		$displayName = (select-xml -xml $manifestAsXml -xpath "/*[local-name() = 'Package']/*[local-name() = 'Properties']/*[local-name() = 'DisplayName']").Node."#text"
		$applicationIds = (@() + (select-xml -xml $manifestAsXml -xpath "//*[local-name() = 'Application']/@Id" )) |
			%{ $_.Node."#text" };
		$applicationIds = @() + $applicationIds; # Make sure its an array even if there's only one element.
	}

	.(ScriptDir("LaunchAppxPackageBackgroundTask.exe")) /get $appxPackage.PackageFullName | %{
		$split = $_.Split(",");
		New-Object PSObject | Add-Member Name $split[0] -PassThru | Add-Member Id $split[1] -PassThru;
	} | %{
		$backgroundTasks += @($_);
	};

	$outputObject = $_;
	if (!$merge) {
		$outputObject = New-Object PSObject `
			| Add-Member PackageFullName $appxPackage.PackageFullName -PassThru `
			| Add-Member Package $appxPackage -PassThru `
		;
		$outputObject.PSTypeNames.Add($appxPackageType);
	}

	($outputObject `
		| Add-Member DisplayName $displayName -PassThru `
		| Add-Member ApplicationIds $applicationIds -PassThru `
		| Add-Member InstallLocationItem $installLocationItem -PassThru `
		| Add-Member Manifest $manifestAsXml -PassThru `
		| Add-Member InstallTimeUtc $installTimeUtc -PassThru `
		| Add-Member BackgroundTasks $backgroundTasks -PassThru `
		);
}


text:
require 'spec_helper'

describe AkamaiApi::CCU::Purge::Request do
  describe "#action" do
    it "is :remove by default" do
      expect(subject.action).to eq :remove
    end

    it "can be changed" do
      expect { subject.action = 'invalidate' }.to change(subject, :action).to 'invalidate'
    end

    it "raises an error if an invalid value is set" do
      expect { subject.action = 'foobar' }.to raise_error AkamaiApi::CCU::UnrecognizedOption
    end
  end

  describe "#type" do
    it "is :arl by default" do
      expect(subject.type).to eq :arl
    end

    it "can be changed" do
      expect { subject.type = 'cpcode' }.to change(subject, :type).to eq 'cpcode'
    end

    it "raises an error if an invalid value is set" do
      expect { subject.type = 'foobar' }.to raise_error AkamaiApi::CCU::UnrecognizedOption
    end
  end

  describe "#domain" do
    it "is :production by default" do
      expect(subject.domain).to eq :production
    end

    it "can be changed" do
      expect { subject.domain = 'staging' }.to change(subject, :domain).to eq 'staging'
    end

    it "raises an error if an invalid value is set" do
      expect { subject.domain = 'foobar' }.to raise_error AkamaiApi::CCU::UnrecognizedOption
    end
  end

  describe "#execute" do
    let(:fake_response) { double code: 201, parsed_response: { 'httpStatus' => 201, 'submissionTime' => 1 } }
    let(:sample_arl) { 'http://www.foo.bar/t.txt' }

    before(:each) do
      allow_any_instance_of(Net::HTTP).to receive(:request).and_return(double code: 201, body: '{ "httpStatus" : 201}')
      allow_any_instance_of(Akamai::Edgegrid::HTTP).to receive(:make_auth_header)
    end

    it "executes a post on the base url" do
      expect_any_instance_of(Net::HTTP).to receive(:request).with an_instance_of(Net::HTTP::Post)
      subject.execute sample_arl
    end

    it "sets the auth in the post" do
      expect_any_instance_of(Akamai::Edgegrid::HTTP).to receive(:setup_edgegrid).with({:username => 'USERNAME', :password => 'PASSWORD', :max_body=>131072, :client_token => "client_token", :client_secret => "client_secret", :access_token => "access_token"})
      subject.execute sample_arl
    end

    it "sets headers and base uri" do
      fake_net_http_post = double
      allow(fake_net_http_post).to receive(:body=)
      allow(fake_net_http_post).to receive(:[]=)
      expect(Net::HTTP::Post).to receive(:new) do |base_uri, initheaders|
        expect(base_uri).to eq "https://some-subdomain.purge.akamaiapis.net/ccu/v2/queues/default"
        expect(initheaders)
        fake_net_http_post
      end
      subject.execute sample_arl
    end

    it "accepts a single element" do
      require "json"
      expect_any_instance_of(Net::HTTP::Post).to receive(:body=).with({type: :arl, action: :remove, domain: :production, objects: [ sample_arl ] }.to_json)
      subject.execute sample_arl
    end

    it "accepts a collection" do
      require "json"
      expect_any_instance_of(Net::HTTP::Post).to receive(:body=).with({type: :arl, action: :remove, domain: :production, objects: ["a", "b"]}.to_json)
      subject.execute ["a", "b"]
    end

    it "works with splatting" do
      require "json"
      expect_any_instance_of(Net::HTTP::Post).to receive(:body=).with({type: :arl, action: :remove, domain: :production, objects: ["a", "b"]}.to_json)
      subject.execute "a", "b"
    end

    it "raises an exception when the response code is 401" do
      fake_response = double code: 401, body: '{ "httpStatus" : 401}'
      allow_any_instance_of(Net::HTTP).to receive(:request) { fake_response }
      expect { subject.execute sample_arl }.to raise_error AkamaiApi::Unauthorized
    end

    it "returns a response built with the resulted json" do
      fake_response = double code: 201, parsed_response: { 'httpStatus' => 201 }
      allow(subject.class).to receive(:post) { fake_response }
      expect(subject.execute(sample_arl).raw).to eq 'httpStatus' => 201
    end

    it "raises an error when json code in response is not successful" do
      fake_response = double code: 403, body: '{ "httpStatus" : 403 }'
      allow_any_instance_of(Net::HTTP).to receive(:request) { fake_response }
      expect { subject.execute sample_arl }.to raise_error AkamaiApi::CCU::Error
    end
  end
end


text:
package org.huangsu.sharesdk.listener;

import com.google.gson.JsonObject;

public interface ResponseListener {
	void onError(String msg, Throwable error);

	void onSuccess(JsonObject result);
}


text:
package test;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import hdf.hdf5lib.H5;
import hdf.hdf5lib.HDF5Constants;
import hdf.hdf5lib.exceptions.HDF5LibraryException;
import hdf.hdf5lib.structs.H5G_info_t;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;

public class TestH5Giterate {
    @Rule public TestName testname = new TestName();
    private static final String H5_FILE = "h5ex_g_iterate.hdf";
    long H5fid = -1;

    private final long _openGroup(long fid, String name) {
        long gid = -1;
        try {
            gid = H5.H5Gopen(fid, name, HDF5Constants.H5P_DEFAULT);
        }
        catch (Throwable err) {
            gid = -1;
            err.printStackTrace();
            fail("H5.H5Gcreate: " + err);
        }

        return gid;
    }

    @Before
    public void openH5file()
            throws HDF5LibraryException, NullPointerException {
        assertTrue("H5 open ids is 0",H5.getOpenIDCount()==0);
        System.out.print(testname.getMethodName());

        try {
            H5fid = H5.H5Fopen(H5_FILE, HDF5Constants.H5F_ACC_RDONLY,
                HDF5Constants.H5P_DEFAULT);
        }
        catch (Throwable err) {
            err.printStackTrace();
            fail("H5.H5Fopen: openH5file: " + err);
        }
    }

    @After
    public void deleteH5file() throws HDF5LibraryException {
        if (H5fid > 0) {
            try {H5.H5Fclose(H5fid);} catch (Exception ex) {}
        }
        System.out.println();
    }

    @Test
    public void testH5Gget_obj_info_all() {
        H5G_info_t info = null;

        long gid = _openGroup(H5fid, "/");

        try {
            info = H5.H5Gget_info(gid);
        }
        catch (Throwable err) {
            err.printStackTrace();
            fail("H5.H5Gget_info: " + err);
        }
        try {
            H5.H5Gclose(gid);
        }
        catch (Exception ex) {
        }
        assertNotNull(info);
        assertTrue("number of links is empty", info.nlinks > 0);
        String objNames[] = new String[(int) info.nlinks];
        int objTypes[] = new int[(int) info.nlinks];
        int lnkTypes[] = new int[(int) info.nlinks];
        long objRefs[] = new long[(int) info.nlinks];

        int names_found = 0;
        try {
            names_found = H5.H5Gget_obj_info_all(H5fid, "/", objNames,
                    objTypes, lnkTypes, objRefs, HDF5Constants.H5_INDEX_NAME);
        }
        catch (Throwable err) {
            err.printStackTrace();
            fail("H5.H5Gget_obj_info_all: " + err);
        }

        assertTrue("number found[" + names_found + "] different than expected["
                + objNames.length + "]", names_found == objNames.length);
        for (int i = 0; i < objNames.length; i++) {
            assertNotNull("name #" + i + " does not exist", objNames[i]);
            assertTrue(objNames[i].length() > 0);
            if (objTypes[i]==HDF5Constants.H5O_TYPE_GROUP) {
                assertTrue("Group is index: "+i + " ",i==2);
                assertTrue("Group is : "+objNames[i] + " ",objNames[i].compareToIgnoreCase("G1")==0);
            }
            else if (objTypes[i]==HDF5Constants.H5O_TYPE_DATASET) {
                assertTrue("Dataset is index: "+i + " ",(i==0)||(i==3));
                if(i==0)
                    assertTrue("Dataset is : "+objNames[i] + " ",objNames[i].compareToIgnoreCase("DS1")==0);
                else
                    assertTrue("Dataset is : "+objNames[i] + " ",objNames[i].compareToIgnoreCase("L1")==0);
            }
            else if (objTypes[i]==HDF5Constants.H5O_TYPE_NAMED_DATATYPE) {
                assertTrue("Datatype is index: "+i + " ",i==1);
                assertTrue("Datatype is : "+objNames[i] + " ",objNames[i].compareToIgnoreCase("DT1")==0);
            }
            else {
                fail("  Unknown at index: " + i + " " + objNames[i]);
            }
        }
    }

}


text:
Print debug tools in conditional breakpoints for Java applications.

## Usage

To use, add conditonal breakpoints with code using JazCode classes.

```java
jaz.Jaz.table("loop").timeColumn().locationColumn().columns(i, i * i).skipBreakpoint()
```

![Breakpoint](./screenshots/breakpoint.png)

After starting a debugger, JazCode opens a window for print debug automatically.

![Window](./screenshots/window.png)

## Setup

Add the latest Maven dependency to your project.

```
<repositories>
	<repository>
		<id>jitpack.io</id>
		<url>https://jitpack.io</url>
	</repository>
</repositories>
```

```
<dependency>
	<groupId>com.github.hisano</groupId>
	<artifactId>jazcode</artifactId>
	<version>1.0.0</version>
</dependency>
```

## Advantages

- Simple API
- Row Filtering
- Row Bookmarking
- Row Coloring
- Image Support


text:
import logging
logger = logging.getLogger(__name__)

#~ from django.utils import unittest
#~ from django.test.client import Client
#from lino.igen import models
#from lino_xl.lib.contacts.models import Contact, Companies
#from lino_xl.lib.countries.models import Country
#~ from lino_xl.lib.contacts.models import Companies

from lino.core.utils import resolve_model
#Companies = resolve_model('contacts.Companies')
from lino.utils.djangotest import TestCase

#~ Person = resolve_model('contacts.Person')
Invoice = resolve_model('sales.Invoice')
#~ Property = resolve_model('properties.Property')
#~ PersonProperty = resolve_model('properties.PersonProperty')

class DemoTest(TestCase):
    #~ fixtures = [ 'std','demo' ]
    fixtures = 'std few_countries few_languages few_cities demo'.split()

def test01(self):
    """
    """
    self.assertEqual(Invoice.objects.all().count(), 28)
    i = Invoice.objects.all()[0]
    self.assertEqual(str(i), u"Invoice # 1")
    s = i.customer.address()
    self.assertEquals(s, u"""\
Rumma & Ko OÜ
Tartu mnt 71
10115 Tallinn
Estonia""")


text:
import axios from 'axios';

const API_KEY = '065d4844e4497435f89a6039a0ebac75';
const ROOT_URL = `http://api.openweathermap.org/data/2.5/forecast?appid=${API_KEY}`;

export const FETCH_WEATHER = 'FETCH_WEATHER';

export function fetchWeather(city) {
  const url = `${ROOT_URL}&q=${city},gb`;
  const request = axios.get(url);

  return {
    type: FETCH_WEATHER,
    payload: request
  }
}


text:
from helpers import *
import random
import time
import math

class Path:
	def __init__(self, puzzle, screen):
		self.puzzle = puzzle
		self.screen = screen
		self.steps = []

		self.offset_time = 0.2
		self.offset_start = time.clock()
		self.offset_end = self.offset_start + self.offset_time

		self.wrong = False
		self.wrong_since = None
		self.errors = []

	def animate_undo(self):
		self.offset_end = time.clock()
		self.offset_start = self.offset_end + self.offset_time

		while time.clock() < self.offset_start:
			time.sleep(0.01)
			self.puzzle.draw(self.screen)
			self.draw()
			self.screen.update()

		self.offset_start = self.offset_end - self.offset_time

	def start(self):
		self.steps = [self.puzzle.entry]

		self.offset_start = time.clock()
		self.offset_end = self.offset_start + self.offset_time

	def move(self, direction):
		if len(self.steps) == 0:
			return

		if abs(direction.x) + abs(direction.y) != 1:
			return

		next = Point(self.steps[len(self.steps )- 1].x + direction.x, self.steps[len(self.steps) - 1].y + direction.y)

		if next.x < 0 or next.y < 0 or next.x >= self.puzzle.width or next.y >= self.puzzle.height:
			return

		if len(self.steps) > 1 and self.steps[len(self.steps) - 2] == next:
			self.animate_undo()
			self.steps.pop()
			return

		if next in self.steps:
			return

		self.offset_start = time.clock()
		self.offset_end = self.offset_start + self.offset_time

		self.steps.append(next)

	def draw(self):
		if len(self.steps) == 0:
			return

		offset = 1.0 - min(1, max(0, (time.clock() - self.offset_start) / (self.offset_end - self.offset_start)))

		path_color = self.puzzle.path_color
		if self.wrong:
			path_color = Color(0, 0, 0)

		if self.steps[len(self.steps) - 1] == self.puzzle.exit and offset == 0 and not self.wrong:
			path_color = blend_colors(Color(255, 255, 255), path_color, math.sin(time.clock() * 8) ** 2)

		opacity = 1
		if self.wrong_since != None:
			opacity = 1.0 - min(1, (time.clock() - self.wrong_since) / 4.0)

		for i in range(len(self.steps) - 1):
			for p in range(self.puzzle.cell_size):
				local_offset = offset
				if i != len(self.steps) - 2:
					local_offset = 0
				pixel_offset = max(0, min(1, (1 - local_offset ) * (self.puzzle.cell_size) - p + 1))

				position = Point(self.puzzle.offset.x + self.steps[i].x * self.puzzle.cell_size + (self.steps[i + 1].x - self.steps[i].x) * p, self.puzzle.offset.y + self.steps[i].y * self.puzzle.cell_size + (self.steps[i + 1].y - self.steps[i].y) * p)
				color = blend_colors(self.screen.pixel[position.x][position.y], path_color, pixel_offset)

				if opacity != 1:
					color = blend_colors(self.screen.pixel[position.x][position.y], color, opacity)

				self.screen.pixel[position.x][position.y] = color

		position = Point(self.puzzle.offset.x + self.steps[len(self.steps) - 1].x * self.puzzle.cell_size, self.puzzle.offset.y + self.steps[len(self.steps) - 1].y * self.puzzle.cell_size)
		color = blend_colors(self.screen.pixel[position.x][position.y], path_color, 1.0 -  min(1, max(0, offset * self.puzzle.cell_size)))
		if opacity != 1:
			color = blend_colors(self.screen.pixel[position.x][position.y], color, opacity)
		self.screen.pixel[position.x][position.y] = color

		if self.steps[len(self.steps) -1] == self.puzzle.exit and offset == 0:
			color = path_color

			if opacity != 1:
				color = blend_colors(self.screen.pixel[self.puzzle.exit_on_screen.x][self.puzzle.exit_on_screen.y], color, opacity)

			self.screen.pixel[self.puzzle.exit_on_screen.x][self.puzzle.exit_on_screen.y] = color

		if len(self.steps) > 0:
			for x in range(3):
				for y in range(3):
					color = path_color
					if len(self.steps) == 1:
						color = blend_colors(path_color, self.puzzle.line_color, offset)

					pos = Point(self.puzzle.offset.x + x + self.steps[0].x * self.puzzle.cell_size - 1, self.puzzle.offset.y + y + self.steps[0].y * self.puzzle.cell_size - 1)

					if opacity != 1:
						color = blend_colors(self.screen.pixel[pos.x][pos.y], color, opacity)

					self.screen.pixel[pos.x][pos.y] = color

		if self.wrong:
			for error in self.errors:
				self.screen.pixel[error.x][error.y] = blend_colors(self.screen.pixel[error.x][error.y], Color(255, 0, 0), math.sin(time.clock() * 8) ** 2)

	def contains_node(self, point):
		for step in self.steps:
			if step == point:
				return True
		return False

	def contains_edge(self, point1, point2):
		for i in range(len(self.steps) - 1):
			if (self.steps[i] == point1 and self.steps[i + 1] == point2) or (self.steps[i] == point2 and self.steps[i + 1] == point1):
				return True
		return False

	# Makes a random change to the path that either keeps the length or extends it
	def extend(self):
		blocks = []

		# Find all blocks that can be used to extend the path
		# Block must contain an existing edge and two empty nodes
		for x in range(self.puzzle.height - 1):
			for y in range(self.puzzle.width - 1):
				nodes = [Point(x, y), Point(x + 1, y), Point(x + 1, y + 1), Point(x, y + 1)]

				nodes_in_path = 0
				for node in nodes:
					if self.contains_node(node):
						nodes_in_path += 1

				if nodes_in_path != 2:
					continue

				contains_edge = False
				for i in range(4):
					if self.contains_edge(nodes[i], nodes[(i + 1) % 4]):
						contains_edge = True

				if contains_edge:
					blocks.append(Point(x, y))

		if len(blocks) == 0:
			return

		# Chose a block in which to extend the path
		block = random.choice(blocks)

		nodes = [Point(block.x, block.y), Point(block.x + 1, block.y), Point(block.x + 1, block.y + 1), Point(block.x, block.y + 1)]

		#Extend
		to_add = []

		for node in nodes:
			if not self.contains_node(node):
				to_add.append(node)

		entry = None

		for node in self.steps:
			if entry == None and node in nodes:
				entry = node

		if entry.x != to_add[0].x and entry.y != to_add[0].y:
			to_add = to_add[::-1]

		self.steps.insert(self.steps.index(entry) + 1, to_add[0])
		self.steps.insert(self.steps.index(entry) + 2, to_add[1])

	def check(self):
		if self.steps[len(self.steps) - 1] != self.puzzle.exit:
			return False

		for feature in self.puzzle.features:
			if not feature.check(self):
				return False
		return True

	def fill_zone(self, x, y, value):
		queue = [Point(x, y)]
		self.zones[x][y] = value

		while len(queue) != 0:
			block = queue.pop(0)

			if block.x > 0 and self.zones[block.x - 1][block.y] == -1 and not self.contains_edge(block, Point(block.x, block.y + 1)):
				self.zones[block.x - 1][block.y] = value
				queue.append(Point(block.x - 1, block.y))
			if block.y > 0 and self.zones[block.x][block.y - 1] == -1 and not self.contains_edge(block, Point(block.x + 1, block.y)):
				self.zones[block.x][block.y - 1] = value
				queue.append(Point(block.x, block.y - 1))
			if block.x < self.puzzle.width - 2 and self.zones[block.x + 1][block.y] == -1 and not self.contains_edge(Point(block.x + 1, block.y), Point(block.x + 1, block.y + 1)):
				self.zones[block.x + 1][block.y] = value
				queue.append(Point(block.x + 1, block.y))
			if block.y < self.puzzle.height - 2 and self.zones[block.x][block.y + 1] == -1 and not self.contains_edge(Point(block.x, block.y  + 1), Point(block.x + 1, block.y + 1)):
				self.zones[block.x][block.y + 1] = value
				queue.append(Point(block.x, block.y + 1))

	def get_zones(self):
		self.zones = [[-1 for y in range(self.puzzle.height - 1)] for x in range(self.puzzle.width -1)]

		zone_index = 0

		for x in range(self.puzzle.width - 1):
			for y in range(self.puzzle.height - 1):
				if self.zones[x][y] == -1:
					self.fill_zone(x, y, zone_index)
					zone_index += 1

		self.zone_count = zone_index
		return self.zones


text:
from django.apps import apps
from django.urls import path, register_converter

from c3nav.editor.converters import EditPkConverter
from c3nav.editor.views.account import change_password_view, login_view, logout_view, register_view
from c3nav.editor.views.changes import changeset_detail, changeset_edit, changeset_redirect
from c3nav.editor.views.edit import edit, graph_edit, level_detail, list_objects, main_index, sourceimage, space_detail
from c3nav.editor.views.users import user_detail, user_redirect

register_converter(EditPkConverter, 'editpk')

def add_editor_urls(model_name, parent_model_name=None, with_list=True, explicit_edit=False):
    model = apps.get_model('mapdata', model_name)
    model_name_plural = model._meta.default_related_name
    if parent_model_name:
        parent_model = apps.get_model('mapdata', parent_model_name)
        parent_model_name_plural = parent_model._meta.default_related_name
        prefix = (parent_model_name_plural+r'/<editpk:'+parent_model_name.lower()+'>/')+model_name_plural
    else:
        prefix = model_name_plural

    name_prefix = 'editor.'+model_name_plural+'.'
    kwargs = {'model': model_name, 'explicit_edit': explicit_edit}
    explicit_edit = 'edit' if explicit_edit else ''

    result = []
    if with_list:
        result.append(path(prefix+'/', list_objects, name=name_prefix+'list', kwargs=kwargs))
    result.extend([
        path(prefix+'/<editpk:pk>/'+explicit_edit, edit, name=name_prefix+'edit', kwargs=kwargs),
        path(prefix+'/create', edit, name=name_prefix+'create', kwargs=kwargs),
    ])
    return result

# todo: custom path converters
urlpatterns = [
    path('levels/<editpk:pk>/', level_detail, name='editor.levels.detail'),
    path('levels/<editpk:level>/spaces/<editpk:pk>/', space_detail, name='editor.spaces.detail'),
    path('levels/<editpk:on_top_of>/levels_on_top/create', edit, {'model': 'Level'},
         name='editor.levels_on_top.create'),
    path('levels/<editpk:level>/graph/', graph_edit, name='editor.levels.graph'),
    path('spaces/<editpk:space>/graph/', graph_edit, name='editor.spaces.graph'),
    path('changeset/', changeset_redirect, name='editor.changesets.current'),
    path('changesets/<editpk:pk>/', changeset_detail, name='editor.changesets.detail'),
    path('changesets/<editpk:pk>/edit', changeset_edit, name='editor.changesets.edit'),
    path('sourceimage/<str:filename>', sourceimage, name='editor.sourceimage'),
    path('user/', user_redirect, name='editor.users.redirect'),
    path('users/<int:pk>/', user_detail, name='editor.users.detail'),
    path('login', login_view, name='editor.login'),
    path('logout', logout_view, name='editor.logout'),
    path('register', register_view, name='editor.register'),
    path('change_password', change_password_view, name='editor.change_password'),
    path('', main_index, name='editor.index'),
]
urlpatterns.extend(add_editor_urls('Level', with_list=False, explicit_edit=True))
urlpatterns.extend(add_editor_urls('LocationGroupCategory'))
urlpatterns.extend(add_editor_urls('LocationGroup'))
urlpatterns.extend(add_editor_urls('DynamicLocation'))
urlpatterns.extend(add_editor_urls('WayType'))
urlpatterns.extend(add_editor_urls('AccessRestriction'))
urlpatterns.extend(add_editor_urls('AccessRestrictionGroup'))
urlpatterns.extend(add_editor_urls('Source'))
urlpatterns.extend(add_editor_urls('LabelSettings'))
urlpatterns.extend(add_editor_urls('Building', 'Level'))
urlpatterns.extend(add_editor_urls('Space', 'Level', explicit_edit=True))
urlpatterns.extend(add_editor_urls('Door', 'Level'))
urlpatterns.extend(add_editor_urls('Hole', 'Space'))
urlpatterns.extend(add_editor_urls('Area', 'Space'))
urlpatterns.extend(add_editor_urls('Stair', 'Space'))
urlpatterns.extend(add_editor_urls('Ramp', 'Space'))
urlpatterns.extend(add_editor_urls('Obstacle', 'Space'))
urlpatterns.extend(add_editor_urls('LineObstacle', 'Space'))
urlpatterns.extend(add_editor_urls('Column', 'Space'))
urlpatterns.extend(add_editor_urls('POI', 'Space'))
urlpatterns.extend(add_editor_urls('AltitudeMarker', 'Space'))
urlpatterns.extend(add_editor_urls('LeaveDescription', 'Space'))
urlpatterns.extend(add_editor_urls('CrossDescription', 'Space'))
urlpatterns.extend(add_editor_urls('WifiMeasurement', 'Space'))