text:
package io.crnk.example.wildfly.endpoints;

import io.crnk.core.queryspec.QuerySpec;
import io.crnk.core.repository.ResourceRepositoryBase;
import io.crnk.core.resource.list.ResourceList;
import io.crnk.example.wildfly.model.User;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class UserRepository extends ResourceRepositoryBase<User, String> {

	private Map<String, User> users = new HashMap<>();

	public UserRepository() {
		super(User.class);
		List<String> interests = new ArrayList<>();
		interests.add("coding");
		interests.add("art");
		save(new User(UUID.randomUUID().toString(), "grogdj@gmail.com", "grogdj", "grogj", "dj", interests));
		save(new User(UUID.randomUUID().toString(), "bot@gmail.com", "bot", "bot", "harry", interests));
		save(new User(UUID.randomUUID().toString(), "evilbot@gmail.com", "evilbot", "bot", "john", interests));
	}

	@Override
	public synchronized void delete(String id) {
		users.remove(id);
	}

	@Override
	public synchronized <S extends User> S save(S user) {
		if (user.getId() == null) {
			user.setId(UUID.randomUUID().toString());
		}
		users.put(user.getId(), user);
		return user;
	}

	@Override
	public synchronized ResourceList<User> findAll(QuerySpec querySpec) {
		return querySpec.apply(users.values());
	}
}


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using Squidex.Domain.Apps.Core.Apps;
using Squidex.Domain.Apps.Entities.Apps.DomainObject;
using Squidex.Domain.Apps.Events;
using Squidex.Domain.Apps.Events.Apps;
using Squidex.Infrastructure;
using Squidex.Infrastructure.Collections;
using Squidex.Infrastructure.Commands;
using Squidex.Infrastructure.EventSourcing;
using Squidex.Infrastructure.Reflection;

namespace Migrations.OldEvents;

[EventType(nameof(AppPatternAdded))]
[Obsolete("New Event introduced")]
public sealed class AppPatternAdded : AppEvent, IMigratedStateEvent<AppDomainObject.State>
{
    public DomainId PatternId { get; set; }

    public string Name { get; set; }

    public string Pattern { get; set; }

    public string? Message { get; set; }

    public IEvent Migrate(AppDomainObject.State state)
    {
        var newSettings = state.Settings with
        {
            Patterns = new List<Pattern>(state.Settings.Patterns.Where(x => x.Name != Name || x.Regex != Pattern))
            {
                new Pattern(Name, Pattern)
                {
                    Message = Message
                }
            }.ToReadonlyList()
        };

        var newEvent = new AppSettingsUpdated
        {
            Settings = newSettings
        };

        return SimpleMapper.Map(this, newEvent);
    }
}

redpajama_set_name: RedPajamaGithub


text:
    #include <cstdbool>
    #include <cstdint>
#endif

// Public API

#ifdef __cplusplus
extern "C" {
#endif

// -- Circa Types --

#ifdef __cplusplus
namespace circa {
    struct Block;
    struct ListData;
    struct NativePatch;
    struct Term;
    struct Type;
    struct World;
    struct Value;
    struct VM;
}

typedef circa::Block caBlock;

typedef circa::VM caVM;

typedef circa::Term caTerm;

// a Type holds data for a single Circa type, including a name, handlers for
// initialization and destruction, and various other handlers and metadata.
typedef circa::Type caType;

// a World holds miscellaneous shared runtime information. Typically, a process should
// create a single World at startup.
typedef circa::World caWorld;

typedef circa::NativePatch caNativePatch;
typedef circa::Value caValue;

#else

typedef struct caBlock caBlock;
typedef struct caVM caVM;
typedef struct caStack caStack;
typedef struct caTerm caTerm;
typedef struct caType caType;
typedef struct caWorld caWorld;
typedef struct caNativePatch caNativePatch;
typedef struct caValue caValue;

#endif

// a Symbol is an alias for an integer, used to reference an interned string.
typedef int caSymbol;

union caValueData {
    int asint;
    float asfloat;
    bool asbool;
    void* ptr;
};

// a Value is a variant value. It holds two pointers, one pointer to the Type object and
// one to the value's data. For some types (such as integers, floats, booleans), the data
// section holds the actual value and not a pointer.
//
// If you allocate caValue yourself then you must call circa_init_value before using it,
// and call circa_set_null before deallocating it.

#ifdef __cplusplus

namespace circa {

struct Value
{
    caValueData value_data;
    caType* value_type;

    Value();
    ~Value();
    Value(Value const&);
    Value& operator=(Value const&);

    caTerm* asTerm();
    caBlock* asBlock();
    bool asBool();
    caSymbol asSymbol();
    int asInt();
    float asFloat();
    ListData* listData();
    int as_i() { return asInt(); }
    float as_f() { return asFloat(); }
    float to_f();
    caSymbol as_s() { return asSymbol(); }
    const char* as_str();
    caSymbol as_b() { return asBool(); }

    Value* index(int i);
    int length();

    // Assignment
    Value* set(caValue* v) { return set_value(v); }
    Value* set_value(caValue* v);
    Value* set_block(Block* b);
    Value* set_bool(bool b);
    Value* set_string(const char* s);
    Value* set_int(int i);
    Value* set_float(float f);
    Value* set_symbol(caSymbol s);
    Value* set_term(Term* t);

    // List utils
    Value* set_list(int size);
    Value* resize(int size);
    bool isEmpty();
    Value* set_element_int(int index, int i);
    Value* set_element_null(int index);
    Value* set_element_str(int index, const char* s);
    Value* set_element_sym(int index, caSymbol s);
    Value* set_element(int index, Value* val);
    Value* append();
    Value* append_sym(caSymbol s);
    Value* append_str(const char* s);
    Value* extend(Value* rhsList);
    void pop();
    Value* last();

    // Hashtable utils
    Value* set_hashtable();
    Value* field(caSymbol field);
    Value* int_key(int key);
    Value* val_key(Value* key);
    Value* term_key(Term* key);
    Value* block_key(Block* key);
    Value* set_field_int(caSymbol field, int i);
    Value* set_field_str(caSymbol field, const char*);
    Value* set_field_sym(caSymbol field, caSymbol sym);
    Value* set_field_term(caSymbol field, Term* term);
    Value* set_field_bool(caSymbol field, bool b);
    bool field_bool(caSymbol field, bool defaultValue);
    Value* insert(caSymbol key);
    Value* insert_int(int key);
    Value* insert_val(Value* valueKey);
    Value* insert_term(Term* key);

    // For debugging:
    void dump();
    char* to_c_string(); // caller must free() this char*.
};

} // namespace circa

#endif // __cplusplus

// EvaluateFunc is the signature for a C evaluation function. The function will access the
// vm to read inputs (if any), possibly perform some action, and write output values
// (if any) back to the vm.
typedef void (*caEvaluateFunc)(caVM* vm);

typedef void (*caNativePtrRelease)(void* ptr);

typedef void (*caLogFunc)(void* context, const char* msg);

// -- Setting up the Circa environment --

// Create a caWorld. This should be done once at the start of the program.
caWorld* circa_initialize();

// Uninitialize a caWorld. This call is entirely optional, but using it will make memory-
// leak checking tools happier.
void circa_shutdown(caWorld*);

void circa_set_log_handler(caWorld*, void* context, caLogFunc func);

// Add a module search path. This is used when processing 'import' statements.
void circa_add_module_search_path(caWorld* world, const char* path);

// Load a module by opening the given filename as a source file.
caBlock* circa_load_module_from_file(caWorld* world,
                                      const char* module_name,
                                      const char* filename);
caBlock* circa_load_module(caWorld* world, const char* moduleName);

// -- VM --
caVM* circa_new_vm(caWorld* world);
void circa_free_vm(caVM* vm);
void circa_set_main(caVM* vm, caBlock* main);
caValue* circa_vm_get_error(caVM* vm);

// Check for changed files, and run any relevant change actions.
void circa_update_changed_files(caWorld* world);

// Run the VM
void circa_run(caVM* vm);

// Signal that an error has occurred.
void circa_output_error_val(caVM* vm, caValue* val);
void circa_output_error(caVM* vm, const char* msg);

// Return whether a runtime error occurred.
bool circa_has_error(caVM* vm);

void circa_dump_stack_trace(caVM* vm);

// Clear all frames from a Stack.
void circa_clear_stack(caVM* vm);

// Clear all frames but the topmost, rewind the PC, and clear temporary values.
void circa_restart(caVM* vm);

caValue* circa_env_insert(caVM* vm, const char* name);

void circa_throw(caVM* vm, const char* message);

// -- Fetching Inputs & Outputs --

// Get the number of inputs.
int circa_num_inputs(caVM* vm);

// Retrieve the given input value. This value may not be modified.
caValue* circa_input(caVM* vm, int index);

// Read the given input index as an integer.
// Equivalent to: circa_int(circa_input(vm, index))
int circa_int_input(caVM* vm, int index);

// Read the given input index as a string
// Equivalent to: circa_string(circa_input(vm, index))
const char* circa_string_input(caVM* vm, int index);

// Read the given input index as a float
// Equivalent to: circa_to_float(circa_input(vm, index))
// (Note that we use circa_to_float, not circa_float)
float circa_float_input(caVM* vm, int index);

// Read the given input index as a bool
// Equivalent to: circa_bool(circa_input(vm, index))
float circa_bool_input(caVM* vm, int index);

// Fetch the current frame's output value.
caValue* circa_output(caVM* vm);

// Fetch the caller Term, this is the term whose function is currently being evaluated.
caTerm* circa_caller_term(caVM* vm);

// Fetch the Block that holds the caller Term.
caBlock* circa_caller_block(caVM* vm);

caBlock* circa_stack_top_block(caVM* vm);

// -- Tagged Values --
//
// General documentation: Safely using container values.
//
//     When using a container (such as a list or map), you will commonly need to access or
//   modify the contents of the container (such as accessing a list's element). This is
//   done through the use of *deep pointers*. An accessor function, such as circa_index,
//   will return a deep pointer into the list.
//
//     Since Circa uses persistent data structures (two Values may share the same
//   underlying data), there are rules on safely using deep pointers. The rules are:
//
//   If you are only reading from the deep pointer:
//     - Many operations on the container value will invalidate all deep pointers. It's advised that
//       you don't touch the container at all while accessing the deep pointer.
//     - When in doubt, use circa_copy to copy a deep pointer to a new Value. The newly copied Value
//       is now safe to read from, even if its container is touched.
//
//   If you are also *writing* to a deep pointer:
//     - The above warnings on reading are applicable.
//     - Additionally, you can only write to a deep pointer if its container is deep-write-safe.
//       Check the documentation, each relevant call will describe whether its result is
//       deep-write-safe.
//     - When in doubt, use circa_touch to ensure that a Value is deep-write-safe.
//
//   Terminology
//     - deep-write-safe - A description applied to a container Value, indicating that the
//       value's contents can be safely modified. A newly created value is deep-write-safe,
//       and circa_touch will ensure that a value is deep-write-safe. Sharing a value's data
//       with other values will make that value not deep-write-safe.
//
//     - deep pointer - A (caValue*) that points to the contents of a container. These pointers
//       can easily be made invalid by operations on the owning container.

// Allocate a new caValue container on the heap. This will call circa_init_value for you.
caValue* circa_alloc_value();

// Deallocate a caValue that was created with circa_alloc_value.
void circa_dealloc_value(caValue* value);

// Initialize a newly allocated caValue container to a null value. If you allocated the
// caValue container yourself, then this function must be called before using the value.
// Do not call circa_init_value on an already allocated value, doing so will cause a
// memory leak.
void circa_init_value(caValue* value);

// Create a Value using the type's default initializer.
//   Effect on safety: The result is deep-write-safe.
void circa_make(caValue* value, caType* type);

// Copy a value from 'source' to 'dest'.
//   Effect on safety: 'source' and 'dest' are no longer deep-write-safe.
void circa_copy(caValue* source, caValue* dest);

// Swap values between caValue containers. This is a very cheap operation.
//   Effect on safety: none.
void circa_swap(caValue* left, caValue* right);

// Move a value from 'source' to 'dest', so that no copy takes place. The preexisting value
// at 'dest' is released. After this call, 'source' will be null.
void circa_move(caValue* source, caValue* dest);

// Obtain a deep-write-safe reference to 'value'.
//   Effect on safety: 'value' is now deep-write-safe. Existing deep pointers are invalid.
void circa_touch(caValue* value);

// Check two values for equality.
//   Effect on safety: 'source' and 'dest' are no longer deep-write-safe. Existing deep pointers
//   are invalid.
bool circa_equals(caValue* left, caValue* right);

// Fetch the value's type.
caType* circa_type_of(caValue* value);

// -- Accessors --

// Check the type of a caValue.
bool circa_is_bool(caValue* value);
bool circa_is_blob(caValue* value);
bool circa_is_block(caValue* value);
bool circa_is_error(caValue* value);
bool circa_is_function(caValue* value);
bool circa_is_float(caValue* value);
bool circa_is_int(caValue* value);
bool circa_is_list(caValue* value);
bool circa_is_null(caValue* value);
bool circa_is_number(caValue* value);
bool circa_is_stack(caValue* value);
bool circa_is_string(caValue* value);
bool circa_is_symbol(caValue* value);
bool circa_is_type(caValue* value);

// Read the value from a caValue.
bool        circa_bool(caValue* value);
char*       circa_blob(caValue* value);
caBlock*    circa_block(caValue* value);
float       circa_float(caValue* value);
int         circa_int(caValue* value);
void*       circa_native_ptr(caValue* val);
const char* circa_string(caValue* value);
caType*     circa_type(caValue* value);
void        circa_vec2(caValue* vec2, float* xOut, float* yOut);
void        circa_vec3(caValue* vec3, float* xOut, float* yOut, float* zOut);
void        circa_vec4(caValue* vec4, float* xOut, float* yOut, float* zOut, float* wOut);

void* circa_get_boxed_native_ptr(caValue* val);
uint32_t circa_blob_size(caValue* blob);

// Create a new blob based on a backing value. Caller must guarantee that 'data' is owned
// or contained inside the backingValue.
void circa_set_blob_slice(caValue* blob, caValue* backingValue, const char* data, uint32_t size);

// Read the pointer value from a caValue. This call will do dereferencing: if the caValue
// is actually a Handle then we'll dereference the handle.
// (Deprecated)
void*       circa_get_pointer(caValue* value);

// Fetch a caValue as a float (converting it from an int if necessary)
float circa_to_float(caValue* value);

// Returns the number of elements in a list value.
int circa_length(caValue* container);

// Allocate a new list value, with the given initial size.
caValue* circa_alloc_list(int size);

// Access a list's element by index. The result is a deep pointer. See the above section titled
// "Safely using container values".
caValue* circa_index(caValue* container, int index);

// Access a map's element by key. Returns NULL if the key is not found. The result is a deep
// pointer. See the above section titled "Safely using container values".
caValue* circa_map_get(caValue* map, caValue* key);

// -- Writing to a caValue --

// Assign to a caValue.
void circa_set_blob(caValue* container, uint32_t size);
void circa_set_bool(caValue* container, bool value);
void circa_set_error(caValue* container, const char* msg);
void circa_set_float(caValue* container, float value);
void circa_set_int(caValue* container, int value);
void circa_set_native_ptr(caValue* val, void* ptr, caNativePtrRelease release);
void circa_set_boxed_native_ptr(caValue* val, void* ptr, caNativePtrRelease release);
void circa_set_null(caValue* container);
void circa_set_pointer(caValue* container, void* ptr);
void circa_set_term(caValue* container, caTerm* term);
void circa_set_string(caValue* container, const char* str);
void circa_set_symbol(caValue* container, const char* str);
void circa_set_typed_pointer(caValue* container, caType* type, void* ptr);
void circa_set_vec2(caValue* container, float x, float y);
void circa_set_vec3(caValue* container, float x, float y, float z);
void circa_set_vec4(caValue* container, float x, float y, float z, float w);

// Assign to a string, with the given length. 'str' does not need to be NULL-terminated.
void circa_set_string_size(caValue* container, const char* str, int size);
void circa_set_empty_string(caValue* container, int size);

int circa_string_length(caValue* string);

const char* circa_symbol_text(caValue* symbol);
bool circa_symbol_equals(caValue* symbol, const char* text);

// Append to a string
void circa_string_append(caValue* str, const char* suffix);
void circa_string_append_val(caValue* str, caValue* suffix);
void circa_string_append_len(caValue* str, const char* suffix, int len);
void circa_string_append_char(caValue* str, char suffix);

bool circa_string_equals(caValue* value, const char* str);

// Initialize a list. The container will have length 'numElements' and each element will
// be NULL.
void circa_set_list(caValue* container, int numElements);

// Append a value to a list and return the newly appended value. The result is a deep pointer.
// See the above section titled "Safely using container values".
//   Effect on safety: 'list' is now deep-write-safe, and existing deep pointers are invalid.
caValue* circa_append(caValue* list);

// Resize a list.
//   Effect on safety: Existing deep pointers are invalid.
void circa_resize(caValue* list, int count);

// Initialize a value with an empty Map.
void circa_set_map(caValue* map);

// Access a map's element by key. If the map doesn't contain the key, it is inserted.
// The result is a deep pointer. See the above section titled "Safely using container values".
//   Effect on safety: Existing deep pointers are invalid.
caValue* circa_map_insert(caValue* map, caValue* key);

// Like circa_map_insert, but the 'key' value is moved instead of copied. (see circa_move)
caValue* circa_map_insert_move(caValue* map, caValue* key);

void circa_map_set_int(caValue* map, caValue* key, int val);

void* circa_raw_pointer(caValue* value);
void circa_set_raw_pointer(caValue* value, void* ptr);

// -- String Representation --

// Load a Circa value from a string representation. The result will be written to 'out'.
// If there is a parsing error, an error value will be saved to 'out'. (the caller should
// check for this).
void circa_parse_string(const char* str, caValue* out);
void circa_parse_string_len(const char* str, int len, caValue* out);

// Write a string representation of 'value' to 'out'.
void circa_to_string(caValue* value, caValue* out);

// -- Code Reflection --

// Find a Term by name, looking in the given block.
caTerm* circa_find_term(caBlock* block, const char* name);

// Find a Function by name, looking in the given block.
caBlock* circa_find_function_local(caBlock* block, const char* name);

// Find a Type by name, looking in the given block.
caType* circa_find_type(caBlock* block, const char* name);

// Get a Term from a Block by index.
caTerm* circa_get_term(caBlock* block, int index);

// Get the nth input placeholder from this block. Returns NULL if there is no such input.
caTerm* circa_input_placeholder(caBlock* block, int index);

// Get the nth output placeholder from this block. Returns NULL if there is no such output.
caTerm* circa_output_placeholder(caBlock* block, int index);

// Get the Block contents for a given Term. This may return NULL.
caBlock* circa_nested_block(caTerm* term);

// Get the Block contents for a term with the given name.
caBlock* circa_get_nested_block(caBlock* block, const char* name);

// Get the parent Block for a given Term
caBlock* circa_parent_block(caTerm* term);

// Get the owning Term for a given Block
caTerm* circa_owning_term(caBlock* block);

// Access the fixed value of a value() Term. Returns NULL if Term is not a value.
caValue* circa_term_value(caTerm* term);

// Fetch the term's index (its position inside the parent block)
int circa_term_get_index(caTerm* term);

// Fetch the number of inputs for the given term.
int circa_term_num_inputs(caTerm* term);

// Fetch the nth input for the given term. May return NULL.
caTerm* circa_term_get_input(caTerm* term, int index);

// Fetch the Term's declared type.
caType* circa_term_declared_type(caTerm* term);

caBlock* circa_term_get_function(caTerm* term);
caValue* circa_function_get_name(caBlock* func);

// -- Code Building --

// Create a new value() term with the given name. Returns the term's value. The value
// is deep-write-safe.
caValue* circa_declare_value(caBlock* block, const char* name);

// -- Native module support --
caNativePatch* circa_create_native_patch(caWorld* world, const char* name);
void circa_patch_function(caNativePatch* patch, const char* nameStr, caEvaluateFunc func);
void circa_finish_native_patch(caNativePatch* module);

// -- File IO --
void circa_read_file(caWorld* world, const char* filename, caValue* contentsOut);
void circa_read_file_with_vm(caVM* vm, const char* filename, caValue* contentsOut);
bool circa_file_exists(caWorld* world, const char* filename);
int circa_file_get_version(caWorld* world, const char* filename);
void circa_use_local_filesystem(caWorld* world, const char* rootDir);
void circa_use_tarball_filesystem(caWorld* world, caValue* tarball);
void circa_use_in_memory_filesystem(caWorld* world);
void circa_load_file_in_memory(caWorld* world, caValue* filename, caValue* contents);
void circa_load_tar_in_memory(caWorld* world, char* data, uint32_t numBytes);

// -- Path tools --
void circa_get_directory_for_filename(caValue* filename, caValue* result);
void circa_get_parent_directory(caValue* filename, caValue* result);

// Deprecated:
void circa_chdir(caValue* dir);
void circa_cwd(caValue* cwd);

// -- Builtin REPL --
void circa_repl_start(caVM* vm);
void circa_repl_run_line(caVM* vm, caValue* input, caValue* output);

void circa_resolve_possible_module_path(caWorld* world, caValue* dir, caValue* moduleName, caValue* result);
caBlock* circa_load_module_by_filename(caWorld* world, const char* filename);

// -- Debugging --

// 'dump' commands will print a representation to stdout
void circa_dump_s(caVM* vm);
void circa_dump_b(caBlock* block);

void circa_perf_stats_dump();
void circa_perf_stats_reset();

#ifdef __cplusplus
} // extern "C"
#endif

#define CIRCA_EXPORT extern "C"

#endif


text:
import logging
class ConfigWebhook():
    import os
    root_dir = os.path.split(os.path.abspath(os.path.dirname(__file__)))[0]
    LOGFILE="/tmp/webhook.log"
    CONFIGFILE=root_dir + "/src/main/resources/webhook.conf"
    jiraUser=""
    jiraPassword=""
    jiraURL=""
    jiraProjects=[]
    monitoredBranches=[]
    parser=None
    TYPE_PUSH = "push"
    TYPE_MERGE = "merge_request"
    validRequests = [TYPE_PUSH,TYPE_MERGE]
    logger = logging.getLogger()
    currentLogLevel=0
    consumerKey=""
    token=""
    tokenSecret=""
    keyPath=""
    authType=""

    def load(self):
        try:
            from ConfigParser import SafeConfigParser
            self.parser = SafeConfigParser()
            self.parser.read(self.CONFIGFILE)
            return True
        except:
            self.logger.warn("Failed to load configuration.")
            return False
        return

    def update(self):
        if self.load():
            self.setConfiguration()
        else:
            self.logger.warn("Failed to update configuration, reverting")
            f=open(self.configFile, "w")
            self.parser.write(f)
            f.close()

    def writeconfig(self, s):
        f=open(self.CONFIGFILE, "w")
        f.write(s)
        f.flush()
        f.close()

    def setConfiguration(self):
        try:
            self.jiraUser=self.parser.get("JIRA", "user")
            self.jiraPassword=self.parser.get("JIRA", "password")
            self.jiraURL=self.parser.get("JIRA", "url")
            self.jiraProjects=list(s for s in self.parser.get("PROJECTS", "projects").split(","))
            self.monitoredBranches=list(s for s in self.parser.get("PROJECTS", "branches").split(","))
            l=self.getLogLevel(self.parser.get("CONFIG", "loglevel"))
            logging.getLogger().setLevel(l)
            self.currentLogLevel=l
            self.consumerKey=self.parser.get("JIRA","consumerKey")
            self.token=self.parser.get("JIRA","token")
            self.tokenSecret=self.parser.get("JIRA","tokenSecret")
            self.keyPath=self.parser.get("JIRA","keyPath")
            self.authType=self.parser.get("JIRA","authType")
        except:
            return False

    def getLogLevel(self,s):
        lvls={"NONE":0, "DEBUG":10, "INFO":20, "WARN":30, "WARNING":30, "ERROR":40, "CRITICAL":50}
        if s not in lvls:
            return 0
        else:
            return lvls.get(s)

    def updateConfiguration(self, newConfig):
        self.writeconfig(newConfig)
        self.update()
        return

    def __init__(self):
        if self.load(): self.setConfiguration()


text:
<?php

/**
 * This file is part of the PHP ST utility.
 *
 * (c) Sankar <sankar.suda@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace toTwig;

/**
 * @author sankar <sankar.suda@gmail.com>
 */
abstract class ConverterAbstract
{
	const ALL_LEVEL  = 15;

	/**
	 * Fixes a file.
	 *
	 * @param \SplFileInfo $file    A \SplFileInfo instance
	 * @param string       $content The file content
	 *
	 * @return string The fixed file content
	 */
	public function convert(\SplFileInfo $file, $content)
	{

	}

	/**
	 * Returns the priority of the converter.
	 *
	 * The default priority is 0 and higher priorities are executed first.
	 */
	public abstract function getPriority();

	/**
	 * Returns the name of the converter.
	 *
	 * The name must be all lowercase and without any spaces.
	 *
	 * @return string The name of the converter
	 */
	public abstract function getName();

	/**
	 * Returns the description of the converter.
	 *
	 * A short one-line description of what the converter does.
	 *
	 * @return string The description of the converter
	 */
	public abstract function getDescription();

    /**
     * Returns true if the file is supported by this converter.
     *
     * @return Boolean true if the file is supported by this converter, false otherwise
     */
    public function supports(\SplFileInfo $file)
    {
    	return true;
    }

    /**
     * Method to extract key/value pairs out of a string with xml style attributes
     *
     * @param   string  $string String containing xml style attributes
     * @return  array   Key/Value pairs for the attributes
     */
    protected function attributes( $string )
    {
        //Initialize variables
        $attr       = array();
        $retarray   = array();
        $pattern    = '/(?:([\w:-]+)\s*=\s*)?(".*?"|\'.*?\'|(?:[$\w:-]+))/';
        // Lets grab all the key/value pairs using a regular expression
        preg_match_all( $pattern, $string, $attr );
        if (is_array($attr)) {
            $numPairs = count($attr[1]);
            for ($i = 0; $i < $numPairs; $i++) {

                $value = trim($attr[2][$i]);
                $key   = ($attr[1][$i]) ? trim($attr[1][$i]) : trim(trim($value,'"'),"'");

                $retarray[$key] = $value;
            }
        }
        return $retarray;
    }

	/**
	 * Sanitize value, remove $,' or " from string
	 * @param string $string
	 */
	protected function variable($string)
	{
		return str_replace(array('$','"',"'"),'',trim($string));
	}

	/**
	 * Sanitize variable, remove $,' or " from string
	 * @param string $string
	 */
	protected function value($string)
	{
		$string = trim(trim($string),"'");
		$string = ($string{0} == '$') ? ltrim($string,'$') : "'".str_replace("'", "\'", $string)."'";
		$string = str_replace(array('"',"''"), "'", $string);

		return $string;
	}

	/**
	 * Replace named args in string
	 *
	 * @param  string $string
	 * @param  array $args
	 * @return string         Formated string
	 */
	protected function vsprintf($string, $args)
	{
		$pattern = '/:([a-zA-Z0-9_-]+)/';
		return preg_replace_callback($pattern, function($matches) use ($args) {

		    return str_replace($matches[0],$args[$matches[1]],$matches[0]);
		}, $string);
	}
}


text:
<?php

require_once( 'paypal-express-checkout.php' );
require_once( 'paypal-express-checkout-response.php' );

class PHP_Merchant_Paypal_Digital_Goods extends PHP_Merchant_Paypal_Express_Checkout
{
	public function __construct( $options = array() ) {
		parent::__construct( $options );
	}

	/**
	 * Creates and returns the payment component of a PayPal Digital Goods NVP API request.
	 *
	 * PayPal requires the category component for all items in a digital goods purchase to be set as Digital.
	 * This function specifies that all goods are digital, then calls @see parent::add_payment() to create
	 * the rest of the API request (which is the same as a vanilla Express Checkout request).
	 *
	 * @uses parent::add_payment() to create non digital goods components of the request.
	 * @return Array An array of name value pairs for each element representing a payment in a PayPal Digital Goods NVP API request.
	 */
	protected function add_payment( $action ) {
		$request = parent::add_payment( $action );

		// Make sure PayPal knows all goods are digital
		for( $i = 0; $i < count( $this->options['items'] ); $i++ ) {
			$request += array( "L_PAYMENTREQUEST_0_ITEMCATEGORY{$i}" => 'Digital' );
		}

		return $request;
	}

	/**
	 * For Digital Goods purchases, PayPal requires the PAYMENTREQUEST_n_ITEMAMT. This function sets the 'items' flag to required
	 * then calls @see parent::setup_purchase() to initiate an Express Checkout payment.
	 *
	 * @uses self::requires() to flag 'items' as required
	 * @uses parent::setup_purchase() to create and make the request.
	 * @return PHP_Merchant_Paypal_Express_Checkout_Response An object containing the details of PayPal's response to the request.
	 */
	public function setup_purchase( $options = array(), $action = 'Sale' ) {
		return parent::setup_purchase( $options, $action );
	}

	/**
	 * For Digital Goods purchases, PayPal requires the PAYMENTREQUEST_n_ITEMAMT. This function sets the 'items' flag to required
	 * then calls @see parent::setup_purchase() to complete the payment.
	 *
	 * @uses self::requires() to flag 'items' as required
	 * @uses parent::setup_purchase() to create and make the request.
	 * @return PHP_Merchant_Paypal_Express_Checkout_Response An object containing the details of PayPal's response to the request.
	 */
	public function purchase( $options = array(), $action = 'Sale' ) {
		return parent::purchase( $options, $action );
	}

	/**
	 * The Javascript to invoke the digital goods in context checkout process.
	 *
	 * No need to call this function manually, required scripts are automatically printed with @see print_buy_buttion().
	 * If you do print this script manually, print it after the button in the DOM to ensure the
	 * click event is properly hooked.
	 */
	public function get_script( $args = array() ){

		if( empty( $args['element_id'] ) )
			$args['element_id'] = 'paypal-submit';

		$dg_script  = '<script src ="https://www.paypalobjects.com/js/external/dg.js" type="text/javascript"></script>'
					. '<script>'
					. 'var dg = new PAYPAL.apps.DGFlow({'
					. 'trigger: "' . $args['element_id'] . '"' // the ID of the HTML element which calls setExpressCheckout
					. '}); </script>';

		return $dg_script;
	}

}


text:
A Project Template (as in directory structure, init scripts etc) for Computational Biology projects

Author: Samuel Lampa, Dept of Pharm. Bio, Uppsala University


text:
' Copyright (c) Microsoft. All rights reserved.
' Licensed under the MIT license. See LICENSE file in the project root for full license information.

'
' SR.vb
'
'   This is a standin for the SR class used throughout FX.
'

Imports System.Resources
Imports System.Text

Namespace System

    Friend Class SR

        Private Shared s_resourceManager As ResourceManager
        Private Sub New()
        End Sub
        Private Shared ReadOnly Property ResourceManager As ResourceManager
            Get

                If SR.s_resourceManager Is Nothing Then

                    ' The following constructor ResourceManager(Type) is going to be replaced by the private constructor ResourceManager(String)
                    ' we'll pass s_resourcesName to this constructor
                    SR.s_resourceManager = New ResourceManager(GetType(SR))
                End If
                Return SR.s_resourceManager
            End Get
        End Property

        ' This method is used to decide if we need to append the exception message parameters to the message when calling SR.Format.
        ' by default it returns false. We overwrite the implementation of this method to return true through IL transformer
        ' when compiling ProjectN app as retail build.
        <Global.System.Runtime.CompilerServices.MethodImpl(Global.System.Runtime.CompilerServices.MethodImplOptions.NoInlining)>
        Public Shared Function UsingResourceKeys() As Boolean
            Return False
        End Function

        Friend Shared Function GetResourceString(ByVal resourceKey As String, ByVal defaultString As String) As String

            Dim resourceString As String = Nothing
            Try
                resourceString = ResourceManager.GetString(resourceKey)
            Catch ex As MissingManifestResourceException
            End Try

            ' if we are running on desktop, ResourceManager.GetString will just return resourceKey. so
            ' in this case we'll return defaultString (if it is not null)
            If defaultString IsNot Nothing AndAlso resourceKey.Equals(resourceString, StringComparison.Ordinal) Then
                Return defaultString
            End If

            Return resourceString
        End Function

        Friend Shared Function Format(ByVal resourceFormat As String, ParamArray args() As Object) As String
            If args IsNot Nothing Then
                If (UsingResourceKeys()) Then
                    Return resourceFormat + String.Join(", ", args)
                End If
                Return String.Format(resourceFormat, args)
            End If
            Return resourceFormat
        End Function

        <Global.System.Runtime.CompilerServices.MethodImpl(Global.System.Runtime.CompilerServices.MethodImplOptions.NoInlining)>
        Friend Shared Function Format(ByVal resourceFormat As String, p1 As Object) As String
            If (UsingResourceKeys()) Then
                Return String.Join(", ", resourceFormat, p1)
            End If

            Return String.Format(resourceFormat, p1)
        End Function

        <Global.System.Runtime.CompilerServices.MethodImpl(Global.System.Runtime.CompilerServices.MethodImplOptions.NoInlining)>
        Friend Shared Function Format(ByVal resourceFormat As String, p1 As Object, p2 As Object) As String
            If (UsingResourceKeys()) Then
                Return String.Join(", ", resourceFormat, p1, p2)
            End If

            Return String.Format(resourceFormat, p1, p2)
        End Function

        <Global.System.Runtime.CompilerServices.MethodImpl(Global.System.Runtime.CompilerServices.MethodImplOptions.NoInlining)>
        Friend Shared Function Format(ByVal resourceFormat As String, p1 As Object, p2 As Object, p3 As Object) As String
            If (UsingResourceKeys()) Then
                Return String.Join(", ", resourceFormat, p1, p2, p3)
            End If
            Return String.Format(resourceFormat, p1, p2, p3)
        End Function
    End Class
End Namespace


text:
package es.npatarino.android.gotchallenge.houses.data.source.local.entities;

import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;

public class BddHouse extends RealmObject {

  public static final String PRIMARY_KEY_NAME = "houseId";

  @PrimaryKey
  private String houseId;
  private String houseName;
  private String houseImageUrl;

  public BddHouse() {
  }

  public String getHouseId() {
    return houseId;
  }

  public void setHouseId(String houseId) {
    this.houseId = houseId;
  }

  public String getHouseName() {
    return houseName;
  }

  public void setHouseName(String houseName) {
    this.houseName = houseName;
  }

  public String getHouseImageUrl() {
    return houseImageUrl;
  }

  public void setHouseImageUrl(String houseImageUrl) {
    this.houseImageUrl = houseImageUrl;
  }
}


text:
<l:dependencies xmlns:l='licenses'>
  <l:dependency name='javadoc' groupId='org.jenkins-ci.plugins' artifactId='javadoc' version='1.0' url='http://wiki.jenkins-ci.org/display/JENKINS/Javadoc+Plugin'>
    <l:description />
    <l:license name='The MIT license' url='http://www.opensource.org/licenses/mit-license.php' />
  </l:dependency>
</l:dependencies>


text:
package io.atomix.primitive;

/**
 * State of distributed primitive.
 */
public enum PrimitiveState {

  /**
   * Signifies a state wherein the primitive is operating correctly and is capable of meeting the advertised
   * consistency and reliability guarantees.
   */
  CONNECTED,

  /**
   * Signifies a state wherein the primitive is temporarily incapable of providing the advertised
   * consistency properties.
   */
  SUSPENDED,

  /**
   * Signifies a state wherein the primitive's session has been expired and therefore cannot perform its functions.
   */
  EXPIRED,

  /**
   * Signifies a state wherein the primitive session has been closed and therefore cannot perform its functions.
   */
  CLOSED
}


text:
@implementation NSString (RSSAttributes)
- (BOOL) isMultiple{
    return [self hasPrefix:@"*"];
}
- (NSString *)parentElementName{
    NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:@"[@\\|]" options:0 error:nil];
    NSArray *matches = [re matchesInString:self options:0 range:NSMakeRange(0, [self length])];
    if ([matches count] > 0) {
        NSArray *elements = [self componentsSeparatedByString:@"|"];
        if ([elements count] == 1) {
            elements = [self componentsSeparatedByString:@"@"];
            return [elements objectAtIndex:0];
        }else{
            return [elements objectAtIndex:0];
        }

    }else{
        return self;
    }
}
@end

#pragma mark
@implementation GSRSSPrimitive
@synthesize rssDictionary = _rssDictionary;

- (id) initWithElement:(TBXMLElement *)elm{
    if (self = [super init]) {
        _rssDictionary = [[NSMutableDictionary alloc] init];
    }
    return self;
}
#pragma mark -
- (id) simpleValueFromKey:(NSString *)key andElement:(TBXMLElement *)elm{
    NSArray *elements = [key componentsSeparatedByString:@"@"];
    if ([elements count] > 1) {
        return [[GSLinkItem alloc] initWithItem:elm];
//        return [TBXML valueOfAttributeNamed:[elements objectAtIndex:1] forElement:elm];
    }
    return [TBXML textForElement:elm];
}
#pragma mark -
- (id) valueFromKey:(NSString *)key andElement:(TBXMLElement *)elm{
    NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:@"[@\\|]" options:0 error:nil];
    TBXMLElement *e = nil;
    NSArray *matches = [re matchesInString:key options:0 range:NSMakeRange(0, [key length])];
    if ([matches count] == 0) {
        e = [TBXML childElementNamed:key parentElement:elm];
        if (e != nil) {
            return [TBXML textForElement:e];
        }
        return nil;
    }
    NSArray *elements = [key componentsSeparatedByString:@"|"];
    if ([elements count] == 1) {
        elements = [key componentsSeparatedByString:@"@"];
        e = [TBXML childElementNamed:[elements objectAtIndex:0] parentElement:elm];
        if (e != nil) {
            return [[GSLinkItem alloc] initWithItem:e];
//            GSLinkItem *link = [[GSLinkItem alloc] initWithItem:e];
//            return @[[elements objectAtIndex:0], [TBXML valueOfAttributeNamed:[elements objectAtIndex:1] forElement:e] ];
        }
    }else{
        for (NSString *subKey in elements) {
            elm = [TBXML childElementNamed:subKey parentElement:elm];
            if (elm == nil) {
                break;
            }
        }
        if (elm != nil) {
            return @[[elements objectAtIndex:0], [TBXML textForElement:elm]];
        }
    }
    return nil;
}
#pragma mark -
- (void) setValue:(id)value forAttribute:(NSString *)attr{
    id val = [_rssDictionary objectForKey:[attr parentElementName]];
    if (val == nil) {
         [self.rssDictionary setObject:value forKey:[attr parentElementName]];
    }else{
        if ([val isKindOfClass:[NSArray class]]) {
            NSMutableArray *mx = [[NSMutableArray alloc] initWithArray:(NSArray *)val];
            [mx addObject:value];
            [self.rssDictionary setObject:mx forKey:[attr parentElementName]];
        }else{
            [self.rssDictionary setObject:@[val, value] forKey:[attr parentElementName]];
        }
    }
}
- (void) setElement:(TBXMLElement *)elm forKey:(NSString *)key{
//    NSLog(@"%@", key);
    id val = nil;
    if ([key isMultiple]) {
        key = [key substringFromIndex:1];
        val = [self simpleValueFromKey:key andElement:elm];
    }else{
        val = [self valueFromKey:key andElement:elm];
    }
    if (val != nil) {
        if ([val isKindOfClass:[NSString class]]) {

            [self setValue:val forAttribute:key];
        }else if ([val isKindOfClass:[GSLinkItem class]]){
            [self setValue:val forAttribute:key];
        }
        else{
            NSArray *arrVal = (NSArray *)val;
            [self setValue:[arrVal objectAtIndex:1] forAttribute:[arrVal objectAtIndex:0]];
        }
    }
}
- (NSArray *)properties{
    return [self.rssDictionary allKeys];
}
- (id) valueForKey:(NSString *)key{
    if ([self.properties containsObject:key]) {
        return [self.rssDictionary objectForKey:key];
    }
    return nil;
}

@end


text:
<!DOCTYPE html>
<meta charset="utf-8">

    <meta http-equiv="content-type" content="text/html; charset=UTF8">
    <title>Scatter Plus Line Chart Example</title>

    <link rel="stylesheet" href="stylesheets/nv.d3.css"/>

    <nvd3-scatter-plus-line-chart
            data="exampleData"
            id="exampleId"
            width="600"
            height="300"
            margin="{left:150,top:100,bottom:100,right:150}"
            tooltips="true"
            interactive="true"
            tooltipContent="tooltipXContentFunction()"
            shape="getShapeCross()">
        <svg></svg>
    </nvd3-scatter-chart>


text:
package com.sun.max.ve.jdk;

import java.io.*;

import com.sun.max.ve.fs.*;

/**
 * Support methods for FileInputStream, RandomAccessFile.
 *
 * One of the interesting questions, given that readBytes/writeBytes are private methods in FileIn/OutputStream,
 * is exactly how conservative we need to be in checking things. The Hotspot native code
 * checks everything, e.g. whether bytes == null, which seems extremely improbable.
 * For now, we follow the same script almost exactly.
 *
 * N.B. There is no explicit check in FileInputStream etc., for a closed file descriptor (fd == -1)
 * It is checked here explicitly in the call to VirtualFileSystem.getVfs, which must be the first call made.
 *
* @author Mick Jordan
 *
 */
public class JavaIOUtil {

    /*
     * A helper class for storing the important information extracted by getFdInfo.
     * Instances of this class do not escape the methods that allocate them so
     * should be implemented on-stack without allocation.
     */
    public static class FdInfo {
        public int _fd;
        public VirtualFileSystem _vfs;
        public long _fileOffset;

        private FdInfo(int fd) throws IOException {
            this._fd = fd;
            this._vfs = VirtualFileSystemId.getVfs(fd);
            this._fileOffset = VirtualFileSystemOffset.get(fd);
        }

        public static FdInfo getFdInfo(FileDescriptor fdObj) throws IOException {
            return new FdInfo(JDK_java_io_FileDescriptor.getFd(fdObj));
        }

        public static FdInfo getFdInfo(int fd)  throws IOException {
            return new FdInfo(fd);
        }

    }

    static int read(FileDescriptor fdObj)  throws IOException {
        final FdInfo fdInfo = FdInfo.getFdInfo(fdObj);
        final int result = fdInfo._vfs.read(VirtualFileSystemId.getFd(fdInfo._fd), fdInfo._fileOffset);
        if (result >= 0) {
            VirtualFileSystemOffset.inc(fdInfo._fd);
            return result;
        }
        if (result != -1) {
            throw new IOException("Read error: " + ErrorDecoder.getMessage(-result));
        }
        return result;
    }

    static int readBytes(byte[] bytes, int offset, int length, FileDescriptor fdObj) throws IOException {
        if (bytes == null) {
            throw new NullPointerException();
        }
        if ((offset < 0) || (offset > bytes.length) || (length < 0) || ((offset + length) > bytes.length) || ((offset + length) < 0)) {
            throw new IndexOutOfBoundsException();
        }
        if (length == 0) {
            return 0;
        }
        final FdInfo fdInfo = FdInfo.getFdInfo(fdObj);
        final int result = fdInfo._vfs.readBytes(VirtualFileSystemId.getFd(fdInfo._fd), bytes, offset, length, fdInfo._fileOffset);
        if (result > 0) {
            VirtualFileSystemOffset.add(fdInfo._fd, result);
            return result;
        } else if (result != -1) {
            throw new IOException("Read error: " + ErrorDecoder.getMessage(-result));
        }
        return result;
    }

    static void write(int b, FileDescriptor fdObj) throws IOException {
        final FdInfo fdInfo = FdInfo.getFdInfo(fdObj);
        final int result = fdInfo._vfs.write(VirtualFileSystemId.getFd(fdInfo._fd), b, fdInfo._fileOffset);
        if (result > 0) {
            VirtualFileSystemOffset.inc(fdInfo._fd);
        }
    }

    static void writeBytes(byte[] bytes, int offset, int length, FileDescriptor fdObj) throws IOException {
        if (bytes == null) {
            throw new NullPointerException();
        }
        if ((offset < 0) || (offset > bytes.length) || (length < 0) || ((offset + length) > bytes.length) || ((offset + length) < 0)) {
            throw new IndexOutOfBoundsException();
        }
        // This is interesting - it suggests a requirement to check the offsets even if we are not going to output anything!
        if (length == 0) {
            return;
        }
        final FdInfo fdInfo = FdInfo.getFdInfo(fdObj);
        final int result = fdInfo._vfs.writeBytes(VirtualFileSystemId.getFd(fdInfo._fd), bytes, offset, length, fdInfo._fileOffset);
        if (result < 0) {
            throw new IOException("Write error: " + ErrorDecoder.getMessage(-result));
        } else {
            VirtualFileSystemOffset.add(fdInfo._fd, result);
        }
    }

    static int open(FileDescriptor fdObj, String name, int flags) throws FileNotFoundException {
        // You might think that at this point, name would be absolute (or canonical) but not so.
        // We, obviously, assume Unix conventions here.
        if (name.length() > 0 && name.charAt(0) != '/') {
            // Checkstyle: stop parameter assignment check
            name = new File(name).getAbsolutePath();
            // Checkstyle: resume parameter assignment check
        }
        final VirtualFileSystem fs = FSTable.exports(name);
        if (fs == null) {
            throw new FileNotFoundException(name + " (Unmounted or uninitialized file system)");
        }
        int fd = fs.open(name, flags);
        if (fd >= 0) {
            fd = VirtualFileSystemId.getUniqueFd(fs, fd);
            JDK_java_io_FileDescriptor.setFd(fdObj, fd);
            return fd;
        } else {
            throw new FileNotFoundException(ErrorDecoder.getFileMessage(-fd, name));
        }
    }

    public static void close0(FileDescriptor fdObj) throws IOException {
        final int fd = JDK_java_io_FileDescriptor.getFd(fdObj);
        if (fd > 0) {
            JDK_java_io_FileDescriptor.setFd(fdObj, -1);
            close0FD(fd);
        }
    }

    static void close0FD(int fd) throws IOException {
        final int result = VirtualFileSystemId.getVfs(fd).close0(VirtualFileSystemId.getFd(fd));
        VirtualFileSystemOffset.remove(fd);
        if (result < 0) {
            throw new IOException("Close error: " + ErrorDecoder.getMessage(-result));
        }
    }
}


text:
using System;
using System.Collections.Generic;
using NLog;
using NLog.Config;
using NLog.Targets;
using VersionOne.VisualStudio.DataLayer.Logging;

using LogLevel = VersionOne.VisualStudio.DataLayer.Logging.LogLevel;
using NLogLevel = NLog.LogLevel;

namespace VersionOne.VisualStudio.VSPackage.Logging {
    internal class LoggerFactory : ILoggerFactory {
        private readonly IDictionary<LogLevel, NLogLevel> levelMap = new Dictionary<LogLevel, NLogLevel> {
                                                                             {LogLevel.Debug, NLogLevel.Debug},
                                                                             {LogLevel.Info, NLogLevel.Info},
                                                                             {LogLevel.Warn, NLogLevel.Warn},
                                                                             {LogLevel.Error, NLogLevel.Error},
                                                                         };

        private LogLevel minLogLevel;

        public LogLevel MinLogLevel {
            get { return minLogLevel; }
            set {
                minLogLevel = value;
                RecreateConfiguration();
            }
        }

        public LoggerFactory() {
            minLogLevel = LogLevel.Debug;
            RecreateConfiguration();
        }

        private void RecreateConfiguration() {
            var minimumLogLevel = TranslateLogLevel(MinLogLevel);
            var loggingConfiguration = new LoggingConfiguration();
            var fileTarget = new FileTarget {
                                 ArchiveAboveSize = 10485760,
                                 MaxArchiveFiles = 2,
                                 FileName = "${specialfolder:dir=.VersionOne.VisualStudioTracker:folder=MyDocuments}\\v1tracker-log.txt",
                                 Layout = "${longdate} | ${level:uppercase=true} | ${logger} | ${message} | ${exception:format=ToString}",
                             };
            loggingConfiguration.AddTarget("file", fileTarget);
            loggingConfiguration.LoggingRules.Add(new LoggingRule("*", minimumLogLevel, fileTarget));
            LogManager.Configuration = loggingConfiguration;
        }

        public ILogger GetLogger(string name, Type type) {
            return new Logger(LogManager.GetLogger(name, type));
        }

        public ILogger GetLogger(string name) {
            return new Logger(LogManager.GetLogger(name));
        }

        private NLogLevel TranslateLogLevel(LogLevel level) {
            return levelMap.ContainsKey(level) ? levelMap[level] : NLogLevel.Debug;
        }
    }
}


text:
<?php

namespace Usuarios\UsuariosBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;

class DefaultController extends Controller
{
    public function indexAction()
    {
        return $this->render('UsuariosBundle:Default:index.html.twig');
    }

    public function loginAction()
    {
        $peticion = $this->getRequest();
        $sesion = $peticion->getSession();
        $error = $peticion->attributes->get(
             SecurityContext::AUTHENTICATION_ERROR,
             $sesion->get(SecurityContext::AUTHENTICATION_ERROR)
             );
        return $this->render('UsuariosBundle:Default:login.html.twig', array(
            'error' => $error
        ));
    }
}


text:
require "simplecov"
SimpleCov.start do
  add_filter "/vendor/"
  add_filter "/bin/"
  add_filter "/exe/"
  add_filter "/spec/"
end

$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'gemometer'

Dir["spec/support/**/*.rb"].each { |f| load f }
Dir["spec/shared_examples/**/*.rb"].each { |f| load f }


text:
import * as React from 'react';
import styles from './TaxonomyPickerSample.module.scss';
import { ITaxonomyPickerSampleProps } from './ITaxonomyPickerSampleProps';
import { escape } from '@microsoft/sp-lodash-subset';

export default class TaxonomyPickerSample extends React.Component<ITaxonomyPickerSampleProps, void> {

  public render(): React.ReactElement<ITaxonomyPickerSampleProps> {
    return (

          <div className={`ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}`}>

              Welcome to Taxonomy Picker demo webpart!

{escape(this.props.description)}

                Selected Languages: {this.props.pickerValue || 'none selected'}

                Learn more

    );
  }
}


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.contentwarehouse.v1.model;

/**
 * Time range (start time and end time). Used to indicate the times in which a LiveResult is
 * considered "hot" and thus a potential for boosting. Specified as Unix time (seconds since
 * midnight, January 1, 1970). Time zone is same as that for query_start_time (i.e., GMT). Next ID:
 * 3
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the contentwarehouse API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class WeboftrustTimeRange extends com.google.api.client.json.GenericJson {

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key @com.google.api.client.json.JsonString
  private java.lang.Long endUnixTime;

  /**
   * Start and end times should always appear. Marked as optional to avoid breaking code.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key @com.google.api.client.json.JsonString
  private java.lang.Long startUnixTime;

  /**
   * @return value or {@code null} for none
   */
  public java.lang.Long getEndUnixTime() {
    return endUnixTime;
  }

  /**
   * @param endUnixTime endUnixTime or {@code null} for none
   */
  public WeboftrustTimeRange setEndUnixTime(java.lang.Long endUnixTime) {
    this.endUnixTime = endUnixTime;
    return this;
  }

  /**
   * Start and end times should always appear. Marked as optional to avoid breaking code.
   * @return value or {@code null} for none
   */
  public java.lang.Long getStartUnixTime() {
    return startUnixTime;
  }

  /**
   * Start and end times should always appear. Marked as optional to avoid breaking code.
   * @param startUnixTime startUnixTime or {@code null} for none
   */
  public WeboftrustTimeRange setStartUnixTime(java.lang.Long startUnixTime) {
    this.startUnixTime = startUnixTime;
    return this;
  }

  @Override
  public WeboftrustTimeRange set(String fieldName, Object value) {
    return (WeboftrustTimeRange) super.set(fieldName, value);
  }

  @Override
  public WeboftrustTimeRange clone() {
    return (WeboftrustTimeRange) super.clone();
  }

}


text:
// ----------------------------------------------------------------------------
// Copyright 2007-2017, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// 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.
//
// ----------------------------------------------------------------------------
// Notes:
//  - http://wiki.openstreetmap.org/wiki/Nominatim
//  - http://open.mapquestapi.com/nominatim/
//  - http://nominatim.openstreetmap.org
//  - OpenStreetMap "Nominative Usage Policy" can be found at the following link:
//      http://wiki.openstreetmap.org/wiki/Nominatim_usage_policy
//  - http://koo.fi/blog/2015/03/19/openstreetmap-nominatim-server-for-geocoding/#more-1094
// ----------------------------------------------------------------------------
// Example
//  - http://nominatim.openstreetmap.org/reverse?format=xml&lat=46.17330&lon=21.29370&zoom=18&addressdetails=1
//  - http://open.mapquestapi.com/nominatim/v1/reverse?format=xml&lat=46.17330&lon=21.29370&zoom=18&addressdetails=1
//   <?xml version="1.0" encoding="UTF-8" ?>
//   <reversegeocode timestamp='Sat, 08 Jan 11 01:43:35 -0500'
//      attribution='Data Copyright OpenStreetMap Contributors, Some Rights Reserved. CC-BY-SA 2.0.'
//      querystring='format=xml&lat=46.17330&lon=21.29370&zoom=18&addressdetails=1'>
//      <result place_id="25016501" osm_type="way" osm_id="17508617">P?durii, Arad, 310365, Romania</result>
//      <addressparts>
//          <tram>P?durii</tram>
//          <road>P?durii</road>
//          <residential>Arad</residential>
//          <city>Arad</city>
//          <postcode>310365</postcode>
//          <country>Romania</country>
//          <country_code>ro</country_code>
//      </addressparts>
//   </reversegeocode>
// ----------------------------------------------------------------------------
// Change History:
//  2011/01/28  Martin D. Flynn
//     -Initial release
//  2013/05/21  Martin D. Flynn
//     -Added language support (see "accept-language=")
//  2014/09/16  Martin D. Flynn
//     -Added property "useResultAddress" to use "result" tag value as full address
//  2015/09/16  Martin D. Flynn
//     -Added support for new "key=" AppKey requirement. [2.6.0-B83]
//     -Added support for ReverseGeocodeCache (EXPERIMENTAL) [2.6.0-B83]
//     -Added lazy starting of auto-trim thread [2.6.1-B35]
// ----------------------------------------------------------------------------
package org.opengts.geocoder.nominatim;

import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import org.opengts.util.*;
import org.opengts.geocoder.*;

public class Nominatim
    extends ReverseGeocodeProviderAdapter
    implements ReverseGeocodeProvider
{

    // ------------------------------------------------------------------------
    // TAGs

    protected static final String TAG_reversegeocode            = "reversegeocode";     // main tag
    protected static final String TAG_result                    = "result";             // full address
    protected static final String TAG_addressparts              = "addressparts";       // address components
    protected static final String TAG_bar                       = "bar";                // not sure what this is
    protected static final String TAG_fast_food                 = "fast_food";          // not sure what this is
    protected static final String TAG_house                     = "house";              //
    protected static final String TAG_tram                      = "tram";               // same as road?
    protected static final String TAG_road                      = "road";               //
    protected static final String TAG_residential               = "residential";        // same as city?
    protected static final String TAG_village                   = "village";            //
    protected static final String TAG_town                      = "town";               // alternate for city?
    protected static final String TAG_city                      = "city";               //
    protected static final String TAG_county                    = "county";             //
    protected static final String TAG_postcode                  = "postcode";           //
    protected static final String TAG_hamlet                    = "hamlet";             // Wherefor art thou?
    protected static final String TAG_suburb                    = "suburb";             //
    protected static final String TAG_state                     = "state";              //
    protected static final String TAG_state_district            = "state_district";     //
    protected static final String TAG_country                   = "country";            // Country name
    protected static final String TAG_country_code              = "country_code";       // Country code

    protected static final String ATTR_osm_type                 = "osm_type";

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

    protected static final String PROP_reverseURL               = "reverseURL";      // String: "http://localhost:8081/reverse?"
    protected static final String PROP_hostName                 = "host";            // String: "localhost:8081"
    protected static final String PROP_zoom                     = "zoom";            // String: "18"
    protected static final String PROP_addressdetails           = "addressdetails";  // String: "1"
    protected static final String PROP_email                    = "email";           // String: "joe@example.com"
    protected static final String PROP_useResultAddress         = "useResultAddress";// Boolean: use "result" tag as full address
    protected static final String PROP_mapquestAppKey           = "mapquestAppKey";  // String: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    protected static final String PROP_ignoreIfMoving           = "ignoreIfMoving";  // Boolean: Reverse-Geocode iff stopped

    protected static final String PROP_cacheMaximumSize         = "cacheMaximumSize";
    protected static final String PROP_cacheMaxEntryAgeSec      = "cacheMaxEntryAgeSec";
    protected static final String PROP_cacheMaxEntryAgeMS       = "cacheMaxEntryAgeMS";
    protected static final String PROP_cacheTrimIntervalSec     = "cacheTrimIntervalSec";
    protected static final String PROP_cacheTrimIntervalMS      = "cacheTrimIntervalMS";

    protected static       String HOST_OPENSTREETMAP            = "nominatim.openstreetmap.org";
    protected static       String HOST_MAPQUEST                 = "open.mapquestapi.com";
    protected static       String HOST_PRIMARY                  = HOST_MAPQUEST;

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

    /* ReverseGeocodeCache */
    public    static       int    CACHE_MAXIMUM_SIZE            = 0;            // "0" means disabled
    public    static       long   CACHE_MAXIMUM_AGE_MS          = 20L * 60000L; // 20 minutes?
    public    static       long   AUTO_TRIM_INTERVAL_MS         = 10L * 60000L; // 10 minutes?

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

    protected static final String ENCODING_UTF8                 = StringTools.CharEncoding_UTF_8;

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

    private boolean                 ignoreIfMoving  = false;

    private ReverseGeocodeCache     rgCache         = null;

    /**
    *** Constructor
    *** @param name    The name assigned to this ReverseGeocodeProvider
    *** @param key     The optional authorization key
    *** @param rtProps The properties associated with this ReverseGeocodeProvider
    **/
    public Nominatim(String name, String key, RTProperties rtProps)
    {
        super(name, key, rtProps);

        /* load runtime properties */
        if (rtProps != null) {
            // -- do not reverse-geocode if moving
            this.ignoreIfMoving = rtProps.getBoolean(PROP_ignoreIfMoving,false);
            // -- ReverseGeocodeCache (may not be supported in this release)
            CACHE_MAXIMUM_SIZE = rtProps.getInt(PROP_cacheMaximumSize, CACHE_MAXIMUM_SIZE);
            long maxEntryAgeMS = rtProps.getLong(PROP_cacheMaxEntryAgeSec,0L) * 1000L;
            CACHE_MAXIMUM_AGE_MS = (maxEntryAgeMS > 0L)? maxEntryAgeMS :
                rtProps.getLong(PROP_cacheMaxEntryAgeMS,CACHE_MAXIMUM_AGE_MS);
            // -- auto-trim interval
            long autoTrimIntervMS = rtProps.getLong(PROP_cacheTrimIntervalSec,0L) * 1000L;
            AUTO_TRIM_INTERVAL_MS = (autoTrimIntervMS > 0L)? autoTrimIntervMS :
                rtProps.getLong(PROP_cacheTrimIntervalMS,AUTO_TRIM_INTERVAL_MS);
        }

        /* start ReverseGeocodeCache */
        // -- may not be supported in this release
        if (CACHE_MAXIMUM_SIZE > 0L) {
            this.rgCache = new ReverseGeocodeCache(this.getName(),
                CACHE_MAXIMUM_SIZE, CACHE_MAXIMUM_AGE_MS, AUTO_TRIM_INTERVAL_MS);
        }

    }

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

    /**
    *** Gets the authorization key of this ReverseGeocodeProvider
    *** @return The access key of this reverse-geocode provider
    **/
    @Override
    public String getAuthorization()
    {
        String appKey = this.getProperties().getString(PROP_mapquestAppKey,null);
        if (!StringTools.isBlank(appKey)) {
            return appKey;
        } else {
            return super.getAuthorization();
        }
    }

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

    /**
    *** Returns true if locally resolved, false otherwise.
    *** (ie. remote address resolution takes more than 20ms to complete)
    *** @return true if locally resolved, false otherwise.
    **/
    @Override
    public boolean isFastOperation()
    {
        // -- this is a slow operation
        return super.isFastOperation();
    }

    /**
    *** Returns a ReverseGeocode instance for the specified GeoPoint
    *** @param gp  The GeoPoint
    *** @return The ReverseGeocode instance
    **/
    @Override
    public ReverseGeocode getReverseGeocode(GeoPoint gp, String localeStr, boolean cache)
    {
        RTProperties rtp = this.getProperties();

        /* check "cache" state */
        // -- NOTE: This method depends on "cache" being true when stopped, and false when
        // -  moving (ie. speed > 0).  See EventData.updateAddress(...) for more info.
        boolean isStopped = cache;      // true if stopped, false if moving
        boolean isMoving  = !isStopped; // moving is opposite of stopped

        /* get ReverseGeocode */
        ReverseGeocode rg = null;
        boolean isCached = false;
        long startMS = System.currentTimeMillis();
        for (;;) {

            /* check ReverseGeocodeCache */
            if (this.rgCache != null) {
                // -- ReverseGeocodeCache check here
                rg = this.rgCache.getReverseGeocode(gp); // "localeStr" is ignored
                if (rg != null) {
                    isCached = true;
                    break;
                }
            }

            /* ReverseGeocoding iff moving? */
            if (this.ignoreIfMoving && isMoving) {
                // -- do not reverse-geocode if moving
                break;
            }

            /* get ReverseGeocode from provider */
            rg = this.getAddressReverseGeocode(gp, localeStr, cache);
            if (rg != null) {
                isCached = false;
                if (this.rgCache != null) {
                    this.rgCache.addReverseGeocode(gp, rg);
                }
                break;
            }

            /* single-pass loop break */
            // -- no Reverse-Geocode at this point
            break;

        }
        long endMS = System.currentTimeMillis();

        /* report */
        if (rg != null) {
            Print.logDebug("Time to obtain ReverseGeocode: " + (endMS - startMS) + " ms" + (isCached?" [cached]":""));
        }

        /* return result */
        return rg; // may be null

    }

    /* return subdivision */
    public String getSubdivision(GeoPoint gp)
    {
        throw new UnsupportedOperationException("Not supported");
    }

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

    /**
    *** Returns a ReverseGeocode instance containing address information
    *** @param gp  The GeoPoint
    *** @return The ReverseGeocode instance
    **/
    private ReverseGeocode getAddressReverseGeocode(GeoPoint gp, String localeStr, boolean cache)
    {
        RTProperties rtp = this.getProperties();

        /* URL */
        String url = this.getAddressReverseGeocodeURL(gp, localeStr);
        Print.logInfo("Address URL: " + url);

        /* create XML document */
        Document xmlDoc = GetXMLDocument(url);
        if (xmlDoc == null) {
            return null;
        }

        /* create ReverseGeocode response */
        Element reversegeocode = xmlDoc.getDocumentElement();
        if (!reversegeocode.getTagName().equalsIgnoreCase(TAG_reversegeocode)) {
            return null;
        }

        /* init */
        String address_val      = null;     // full address
        String bar_val          = null;     // ???
        String house_val        = null;     // house number
        String road_val         = null;     // street name
        String city_val         = null;     // city name
        String county_val       = null;     // county name
        String suburb_val       = null;     // suburb name
        String state_val        = null;     // state/province
        String postcode_val     = null;     // postal code
        String hamlet_val       = null;     //
        String country_name_val = null;     // country name
        String country_code_val = null;     // country code

        // -- full address
        NodeList resultList = XMLTools.getChildElements(reversegeocode,TAG_result);
        for (int r = 0; r < resultList.getLength(); r++) {
            Element result = (Element)resultList.item(r);
            //String osmType = XMLTools.getAttribute(result, ATTR_osm_type, null, false);
            address_val = XMLTools.getNodeText(result," ",false);
            break; // only the first element
        }

        // -- address components
        NodeList addresspartsList = XMLTools.getChildElements(reversegeocode,TAG_addressparts);
        for (int a = 0; (a < addresspartsList.getLength()); a++) {
            Element addressparts = (Element)addresspartsList.item(a);
            NodeList addresspartsChildren = addressparts.getChildNodes();
            for (int ac = 0; ac < addresspartsChildren.getLength(); ac++) {
                Node child = addresspartsChildren.item(ac);
                if (!(child instanceof Element)) { continue; }
                Element elem = (Element)child;
                String elemName = elem.getNodeName();
                //Print.logInfo("Element Name: " + elemName);
                if (elemName.equalsIgnoreCase(TAG_bar)) {
                    bar_val = XMLTools.getNodeText(elem," ",false);
                } else
                if (elemName.equalsIgnoreCase(TAG_house)) {
                    house_val = XMLTools.getNodeText(elem," ",false);
                } else
                if (elemName.equalsIgnoreCase(TAG_tram)) {
                    // -- ignore
                } else
                if (elemName.equalsIgnoreCase(TAG_road)) {
                    road_val = XMLTools.getNodeText(elem," ",false);
                } else
                if (elemName.equalsIgnoreCase(TAG_residential)) {
                    // -- ignore
                } else
                if (elemName.equalsIgnoreCase(TAG_village)) {
                    // -- ignore
                } else
                if (elemName.equalsIgnoreCase(TAG_town)) {
                    if (StringTools.isBlank(city_val)) {
                        city_val = XMLTools.getNodeText(elem," ",false);
                    }
                } else
                if (elemName.equalsIgnoreCase(TAG_city)) {
                    city_val = XMLTools.getNodeText(elem," ",false);
                } else
                if (elemName.equalsIgnoreCase(TAG_county)) {
                    county_val = XMLTools.getNodeText(elem," ",false);
                } else
                if (elemName.equalsIgnoreCase(TAG_postcode)) {
                    postcode_val = XMLTools.getNodeText(elem," ",false);
                } else
                if (elemName.equalsIgnoreCase(TAG_hamlet)) {
                    hamlet_val = XMLTools.getNodeText(elem," ",false);
                } else
                if (elemName.equalsIgnoreCase(TAG_suburb)) {
                    suburb_val = XMLTools.getNodeText(elem," ",false);
                } else
                if (elemName.equalsIgnoreCase(TAG_state)) {
                    state_val = XMLTools.getNodeText(elem," ",false);
                } else
                if (elemName.equalsIgnoreCase(TAG_country)) {
                    country_name_val = XMLTools.getNodeText(elem," ",false);
                } else
                if (elemName.equalsIgnoreCase(TAG_country_code)) {
                    country_code_val = StringTools.trim(XMLTools.getNodeText(elem," ",false)).toUpperCase();
                } else {
                    // elemName unrecognized
                }
            }
            break; // only the first element
        }

        /* populate ReverseGeocode instance */
        ReverseGeocode rg = new ReverseGeocode();
        StringBuffer addr = new StringBuffer();
        // -- house number /road
        if (!StringTools.isBlank(house_val)) {
            addr.append(house_val);
            if (!StringTools.isBlank(road_val)) {
                addr.append(" ");
                addr.append(road_val);
                rg.setStreetAddress(house_val + " " + road_val);
            } else {
                rg.setStreetAddress(house_val);
            }
        } else
        if (!StringTools.isBlank(road_val)) {
            addr.append(road_val);
            rg.setStreetAddress(road_val);
        }
        // -- suburb
        if (!StringTools.isBlank(suburb_val)) {
            if (addr.length() > 0) { addr.append(", "); }
            addr.append(suburb_val);
            //rg.setSuburb(suburb_val);
        }
        // -- city/county
        if (!StringTools.isBlank(city_val)) {
            if (addr.length() > 0) { addr.append(", "); }
            addr.append(city_val);
            rg.setCity(city_val);
        }
        if (!StringTools.isBlank(county_val)) {
            if (StringTools.isBlank(city_val)) {
                // "city" not provided, at least include the "county"
                if (addr.length() > 0) { addr.append(", "); }
                addr.append("[").append(county_val).append("]");
            }
            //rg.setCounty(county_val);
        }
        // -- state/province/postcode
        if (!StringTools.isBlank(state_val)) {
            if (addr.length() > 0) { addr.append(", "); }
            addr.append(state_val);
            rg.setStateProvince(state_val);
            if (!StringTools.isBlank(postcode_val)) {
                addr.append(" ").append(postcode_val);
                rg.setPostalCode(postcode_val);
            }
        } else {
            if (!StringTools.isBlank(postcode_val)) {
                if (addr.length() > 0) { addr.append(", "); }
                addr.append(postcode_val);
                rg.setPostalCode(postcode_val);
            }
        }
        // -- country
        if (!StringTools.isBlank(country_code_val)) {
            if (country_code_val.equalsIgnoreCase("US")) {
                //if (addr.length() > 0) { addr.append(", "); }
                //addr.append("USA");
            } else
            if (!StringTools.isBlank(country_name_val)) {
                if (addr.length() > 0) { addr.append(", "); }
                addr.append(country_name_val);
            } else {
                if (addr.length() > 0) { addr.append(", "); }
                addr.append(country_code_val);
            }
            rg.setCountryCode(country_code_val);
        }
        // -- full address
        if (!StringTools.isBlank(address_val) && rtp.getBoolean(PROP_useResultAddress,false)) {
            rg.setFullAddress(address_val);
        } else {
            rg.setFullAddress(addr.toString());
        }

        return rg;

    }

    private String getEmail()
    {
        return this.getProperties().getString(PROP_email,null);
    }

    private String getAddressReverseGeocodeURL(GeoPoint gp, String localeStr)
    {
        //  - http://nominatim.openstreetmap.org/reverse?format=xml&addressdetails=1&zoom=18&lat=46.17330&lon=21.29370
        StringBuffer sb = new StringBuffer();
        RTProperties rtp = this.getProperties();
        String url = rtp.getString(PROP_reverseURL, null);
        boolean urlHasKey = false;
        if (!StringTools.isBlank(url)) {
            sb.append(url);
            urlHasKey = (url.indexOf("key=") >= 0)? true : false;
        } else {
            String host = rtp.getString(PROP_hostName, HOST_PRIMARY);
            sb.append("http://");
            sb.append(host);
            if (host.indexOf("mapquest") >= 0) {
                sb.append("/nominatim/v1/reverse?");
            } else {
                sb.append("/reverse?");
            }
        }
        // --- key
        if (!urlHasKey && this.hasAuthorization()) {
            String key = this.getAuthorization();
            sb.append("key="+key+"&");
        }
        // --- format xml
        sb.append("format=xml&");
        // --- limit to 1 match only
        sb.append("limit=1&");
        // --- language
        if (!StringTools.isBlank(localeStr)) {
            sb.append("accept-language=").append(localeStr).append("&");
        }
        //sb.append("osm_type=W&");
        sb.append("addressdetails=").append(rtp.getString(PROP_addressdetails,"1")).append("&"); // 0|1
        sb.append("zoom=").append(rtp.getString(PROP_zoom,"18")).append("&"); // 0..18
        sb.append("email=").append(this.getEmail()).append("&"); // required, per usage policy
        sb.append("lat=").append(gp.getLatitudeString( GeoPoint.SFORMAT_DEC_5,null)).append("&");
        sb.append("lon=").append(gp.getLongitudeString(GeoPoint.SFORMAT_DEC_5,null));
        return sb.toString();
    }

    private Document GetXMLDocument(String url)
    {
         try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputStream input = HTMLTools.inputStream_GET(url, null, 5000);
            InputStreamReader reader = new InputStreamReader(input, ENCODING_UTF8);
            InputSource inSrc = new InputSource(reader);
            inSrc.setEncoding(ENCODING_UTF8);
            return db.parse(inSrc);
        } catch (ParserConfigurationException pce) {
            Print.logError("Parse error: " + pce);
            return null;
        } catch (SAXException se) {
            Print.logError("Parse error: " + se);
            return null;
        } catch (IOException ioe) {
            Print.logError("IO error: " + ioe);
            return null;
        }
    }

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

    /**
    *** Main entery point for debugging/testing
    **/
    public static void main(String argv[])
    {
        RTConfig.setCommandLineArgs(argv);
        Print.setAllOutputToStdout(true);
        Print.setEncoding(ENCODING_UTF8);

        /* host */
        String host = RTConfig.getString("host",null);
        if (!StringTools.isBlank(host)) {
            HOST_PRIMARY = host;
        }

        /* GeoPoint */
        GeoPoint gp = new GeoPoint(RTConfig.getString("gp",null));
        if (!gp.isValid()) {
            Print.logInfo("Invalid GeoPoint specified");
            System.exit(1);
        }
        Print.logInfo("Reverse-Geocoding GeoPoint: " + gp);

        /* Reverse Geocoding */
        Nominatim gn = new Nominatim("nominatim", null, RTConfig.getCommandLineProperties());
        Print.sysPrintln("RevGeocode = " + gn.getReverseGeocode(gp,null/*localeStr*/,false/*cache*/));

    }

}


text:
Review Apps are automatically deployed by each pipeline, both in
[CE](https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/22010) and
[EE](https://gitlab.com/gitlab-org/gitlab-ee/merge_requests/6665).

## How does it work?

1. On every [pipeline][gitlab-pipeline] during the `test` stage, the
  [`review-deploy`][review-deploy-job] job is automatically started.
1. The `review-deploy` job:
    1. Waits for the `gitlab:assets:compile` job to finish since the
      [`CNG-mirror`][cng-mirror] pipeline triggerred in the following step
      depends on it.
    1. [Triggers a pipeline][cng-pipeline] in the [`CNG-mirror`][cng-mirror]
      project.
        - We use the `CNG-mirror` project so that the `CNG`, (**C**loud
          **N**ative **G**itLab), project's registry is not overloaded with a
          lot of transient Docker images.
        - The `CNG-mirror` pipeline creates the Docker images of each component
          (e.g. `gitlab-rails-ee`, `gitlab-shell`, `gitaly` etc.) based on the
          commit from the [GitLab pipeline][gitlab-pipeline] and store them in
          its [registry][cng-mirror-registry].
    1. Once all images are built by [`CNG-mirror`][cng-mirror], the Review App
      is deployed using [the official GitLab Helm chart][helm-chart] to the
      [`review-apps-ce`][review-apps-ce] / [`review-apps-ee`][review-apps-ee]
      Kubernetes cluster on GCP.
        - The actual scripts used to deploy the Review App can be found at
          [`scripts/review_apps/review-apps.sh`][review-apps.sh].
        - These scripts are basically
          [our official Auto DevOps scripts][Auto-DevOps.gitlab-ci.yml] where the
          default CNG images are overridden with the images built and stored in the
          [`CNG-mirror` project's registry][cng-mirror-registry].
        - Since we're using [the official GitLab Helm chart][helm-chart], this means
          you get a dedicated environment for your branch that's very close to what
          it would look in production.
1. Once the `review-deploy` job succeeds, you should be able to use your Review
  App thanks to the direct link to it from the MR widget. The default username
  is `root` and its password can be found in the 1Password secure note named
  **gitlab-{ce,ee} Review App's root password** (note that there's currently
  [a bug where the default password seems to be overridden][password-bug]).

**Additional notes:**

- The Kubernetes cluster is connected to the `gitlab-{ce,ee}` projects using
  [GitLab's Kubernetes integration][gitlab-k8s-integration]. This basically
  allows to have a link to the Review App directly from the merge request
  widget.
- If the Review App deployment fails, you can simply retry it (there's no need
  to run the [`review-stop`][gitlab-ci-yml] job first).
- The manual [`review-stop`][gitlab-ci-yml] in the `test` stage can be used to
  stop a Review App manually, and is also started by GitLab once a branch is
  deleted.
- Review Apps are cleaned up regularly using a pipeline schedule that runs
  the [`schedule:review-cleanup`][gitlab-ci-yml] job.

## QA runs

On every [pipeline][gitlab-pipeline] during the `test` stage, the
`review-qa-smoke` job is automatically started: it runs the smoke QA suite.
You can also manually start the `review-qa-all`: it runs the full QA suite.

Note that both jobs first wait for the `review-deploy` job to be finished.

## How to?

### Find my Review App slug?

1. Open the `review-deploy` job.
1. Look for `Checking for previous deployment of review-*`.
1. For instance for `Checking for previous deployment of review-qa-raise-e-12chm0`,
  your Review App slug would be `review-qa-raise-e-12chm0` in this case.

### Run a Rails console?

1. [Filter Workloads by your Review App slug](https://console.cloud.google.com/kubernetes/workload?project=gitlab-review-apps)
  , e.g. `review-29951-issu-id2qax`.
1. Find and open the `task-runner` Deployment, e.g. `review-29951-issu-id2qax-task-runner`.
1. Click on the Pod in the "Managed pods" section, e.g. `review-29951-issu-id2qax-task-runner-d5455cc8-2lsvz`.
1. Click on the `KUBECTL` dropdown, then `Exec` -> `task-runner`.
1. Replace `-c task-runner -- ls` with `-- /srv/gitlab/bin/rails c` from the
  default command or
  - Run `kubectl exec --namespace review-apps-ce -it review-29951-issu-id2qax-task-runner-d5455cc8-2lsvz -- /srv/gitlab/bin/rails c`
    and
  - Replace `review-apps-ce` with `review-apps-ee` if the Review App
    is running EE, and
  - Replace `review-29951-issu-id2qax-task-runner-d5455cc8-2lsvz`
    with your Pod's name.

### Dig into a Pod's logs?

1. [Filter Workloads by your Review App slug](https://console.cloud.google.com/kubernetes/workload?project=gitlab-review-apps)
  , e.g. `review-1979-1-mul-dnvlhv`.
1. Find and open the `migrations` Deployment, e.g.
  `review-1979-1-mul-dnvlhv-migrations.1`.
1. Click on the Pod in the "Managed pods" section, e.g.
  `review-1979-1-mul-dnvlhv-migrations.1-nqwtx`.
1. Click on the `Container logs` link.

## Frequently Asked Questions

**Isn't it too much to trigger CNG image builds on every test run? This creates
thousands of unused Docker images.**

  > We have to start somewhere and improve later. Also, we're using the
  CNG-mirror project to store these Docker images so that we can just wipe out
  the registry at some point, and use a new fresh, empty one.

**How big are the Kubernetes clusters (`review-apps-ce` and `review-apps-ee`)?**

  > The clusters are currently set up with a single pool of preemptible nodes,
  with a minimum of 1 node and a maximum of 100 nodes.

**What are the machine running on the cluster?**

  > We're currently using `n1-standard-4` (4 vCPUs, 15 GB memory) machines.

**How do we secure this from abuse? Apps are open to the world so we need to
find a way to limit it to only us.**

  > This isn't enabled for forks.

[gitlab-pipeline]: https://gitlab.com/gitlab-org/gitlab-ce/pipelines/35850709
[review-deploy-job]: https://gitlab.com/gitlab-org/gitlab-ce/-/jobs/118076368
[cng-mirror]: https://gitlab.com/gitlab-org/build/CNG-mirror
[cng-pipeline]: https://gitlab.com/gitlab-org/build/CNG-mirror/pipelines/35883435
[cng-mirror-registry]: https://gitlab.com/gitlab-org/build/CNG-mirror/container_registry
[helm-chart]: https://gitlab.com/charts/gitlab/
[review-apps-ce]: https://console.cloud.google.com/kubernetes/clusters/details/us-central1-a/review-apps-ce?project=gitlab-review-apps
[review-apps-ee]: https://console.cloud.google.com/kubernetes/clusters/details/us-central1-b/review-apps-ee?project=gitlab-review-apps
[review-apps.sh]: https://gitlab.com/gitlab-org/gitlab-ee/blob/master/scripts/review_apps/review-apps.sh
[automated_cleanup.rb]: https://gitlab.com/gitlab-org/gitlab-ee/blob/master/scripts/review_apps/automated_cleanup.rb
[Auto-DevOps.gitlab-ci.yml]: https://gitlab.com/gitlab-org/gitlab-ce/blob/master/lib/gitlab/ci/templates/Auto-DevOps.gitlab-ci.yml
[gitlab-ci-yml]: https://gitlab.com/gitlab-org/gitlab-ce/blob/master/.gitlab-ci.yml
[gitlab-k8s-integration]: https://docs.gitlab.com/ee/user/project/clusters/index.html
[password-bug]: https://gitlab.com/gitlab-org/gitlab-ce/issues/53621

---

[Return to Testing documentation](index.md)