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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>AbstractEvolution</title>
<meta name="date" content="2015-05-14">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

pjv.evolution.genetic

Class AbstractEvolution<Individual extends AbstractIndividual>

java.lang.Object

pjv.evolution.genetic.AbstractEvolution<Individual>

Type Parameters:

Individual - Individual in the evolution

All Implemented Interfaces:

java.lang.Runnable

Direct Known Subclasses:

Evolution

public abstract class AbstractEvolution<Individual extends AbstractIndividual>
extends java.lang.Object
implements java.lang.Runnable

Abstract superclass for evolutionary algorithm. This class is to be inherited
 to create concrete evolutionary algorithms.

Field Summary

Fields

Modifier and Type
Field and Description

protected PJVEvolutionController
context

Reference to the GUI.

protected double
crossoverProbability

Probability of crossover.

protected int
generations

Number of generations.

protected double
mutationProbability

Probability of mutation.

protected int
populationSize

Size of the population.

Constructor Summary

Constructors

Constructor and Description

AbstractEvolution()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

double
getCrossoverProbability()

Gets the crossover probability used by the evolutionary algorithm.

double
getMutationProbability()

Gets the mutation probability used by the evolutionary algorithm.

int
getPopulationSize()

Gets the number of individuals in the population used by the evolutionary
 algorithm.

protected void
setCrossoverProbability(double prob)

Sets the crossover probability to be used by the evolutionary algorithm.

protected void
setMutationProbability(double prob)

Sets the mutation probability to be used by the evolutionary algorithm.

protected void
setPopulationSize(int populationSize)

Sets the number of individuals in the population used by the evolutionary
 algorithm.

java.lang.String
toString()

Methods inherited from class java.lang.Object

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

Methods inherited from interface java.lang.Runnable

run

Field Detail

generations

protected int generations

Number of generations.

populationSize

protected int populationSize

Size of the population.

mutationProbability

protected double mutationProbability

Probability of mutation.

crossoverProbability

protected double crossoverProbability

Probability of crossover.

context

protected PJVEvolutionController context

Reference to the GUI.

Constructor Detail

AbstractEvolution

public AbstractEvolution()

Method Detail

getPopulationSize

public int getPopulationSize()

Gets the number of individuals in the population used by the evolutionary
 algorithm.

Returns:

Size of the population

setPopulationSize

protected void setPopulationSize(int populationSize)

Sets the number of individuals in the population used by the evolutionary
 algorithm.

Parameters:

populationSize - Size of the population

getMutationProbability

public double getMutationProbability()

Gets the mutation probability used by the evolutionary algorithm. Meaning
 of this number is ambiguous, depending on the actual type of EA being
 used. In case of genetic algorithm, it may encode the probability of
 bit-flip mutation for each bit.

Returns:

The current mutation probability

setMutationProbability

protected void setMutationProbability(double prob)

Sets the mutation probability to be used by the evolutionary algorithm.
 Meaning of this number is ambiguous, depending on the actual type of EA
 being used. In case of genetic algorithm, it may encode the probability
 of bit-flip mutation for each bit.

Parameters:

prob - The new mutation probability

getCrossoverProbability

public double getCrossoverProbability()

Gets the crossover probability used by the evolutionary algorithm. This
 is the probability of selected the individuals to be crossed over before
 being mutated.

Returns:

The current crossover probability

setCrossoverProbability

protected void setCrossoverProbability(double prob)

Sets the crossover probability to be used by the evolutionary algorithm.
 This is the probability of the selected individuals to be crossed over
 before being mutated.

Parameters:

prob - The new crossover probability

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web.Http;
using FancyTraveller.Domain.Infrastracture;
using FancyTraveller.Domain.Logic;
using FancyTraveller.Domain.Model;
using FancyTraveller.Domain.Services;
using FancyTraveller.Web.UI.ViewModels;

namespace FancyTraveller.Web.UI.Controllers
{
    public class RouteController : ApiController
    {
        private readonly RouteService service;

        public RouteController()
        {
            service = new RouteService(new VerticesRepository(ConfigurationManager.AppSettings, new ServerFileReader()), new DijkstraRouteFinder());
        }

        [ActionName("AvailableCities")]
        public IEnumerable<AvailableCityResponse> GetAvailableCities()
        {
            return service.AvailableCities.Select(c => new AvailableCityResponse() { Name = c.Name, Id = c.Id, Location = c.Location });
        }

        [HttpPost]
        public ShortestRouteResponse FindShortestRoute(ShortestRouteRequest request)
        {
            var allDistancesBetweenCities = service.LoadDistancesBetweenCities(request.CitiesToSkip);
            var result = service.FindShortestRoute(request.SourceCity.Id, request.DestinationCity.Id, allDistancesBetweenCities);

            return new ShortestRouteResponse()
            {
                SourceCity = request.SourceCity,
                DestinationCity = request.DestinationCity,
                Distance = result.Distance,
                VisitedCities = result.VisitedCities
            };
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Application\Model;

class BaseModel {

    // Holds all database table field names
    protected $field = Array();

    /**
     * Set values from array
     *
     * @param map $pData
     */
    public function exchangeArray($pData)
    {
        if (is_array($pData)) {
            foreach ($pData as $key => $value) {
                if (isset($this->field[$key])) {
                    $this->field[$key] = $pData[$key];
                }
            }
        }
    }

    /**
     * Sets field value if exists
     *
     * @param key $pKey
     * @param value $pValue
     */
    public function setField($pKey, $pValue)
    {
        if (isset($this->field[$pKey])) {
            $this->field[$pKey] = $pValue;
        }
    }

    /**
     * Gets field value
     *
     * @param key $pKey
     * @return value or null:
     */
    public function getField($pKey)
    {
        return $this->field[$pKey];
    }

    /**
     * Returns all data as array
     *
     * @return multitype:
     */
    public function toArray()
    {
        return $this->field;
    }
}


text:
namespace base {

template <typename Signature>
class OnceCallback;

template <typename Signature>
class RepeatingCallback;

template <typename Signature>
using Callback = RepeatingCallback<Signature>;

// Syntactic sugar to make OnceClosure<void()> and RepeatingClosure<void()>
// easier to declare since they will be used in a lot of APIs with delayed
// execution.
using OnceClosure = OnceCallback<void()>;
using RepeatingClosure = RepeatingCallback<void()>;
using Closure = Callback<void()>;

}  // namespace base

#endif  // BASE_CALLBACK_FORWARD_H_


text:
// NOTE: This file was generated by the ServiceGenerator.

// ----------------------------------------------------------------------------
// API:
//   Cloud Trace API (cloudtrace/v2)
// Description:
//   Sends application trace data to Cloud Trace for viewing. Trace data is
//   collected for all App Engine applications by default. Trace data from other
//   applications can be provided using this API. This library is used to
//   interact with the Cloud Trace API directly. If you are looking to
//   instrument your application for Cloud Trace, we recommend using
//   OpenTelemetry.
// Documentation:
//   https://cloud.google.com/trace

#import <GoogleAPIClientForREST/GTLRObject.h>

#if GTLR_RUNTIME_VERSION != 3000
#error This file was generated by a different version of ServiceGenerator which is incompatible with this GTLR library source.
#endif

@class GTLRCloudTrace_Annotation;
@class GTLRCloudTrace_Attributes;
@class GTLRCloudTrace_Attributes_AttributeMap;
@class GTLRCloudTrace_AttributeValue;
@class GTLRCloudTrace_Link;
@class GTLRCloudTrace_Links;
@class GTLRCloudTrace_MessageEvent;
@class GTLRCloudTrace_Module;
@class GTLRCloudTrace_Span;
@class GTLRCloudTrace_StackFrame;
@class GTLRCloudTrace_StackFrames;
@class GTLRCloudTrace_StackTrace;
@class GTLRCloudTrace_Status;
@class GTLRCloudTrace_Status_Details_Item;
@class GTLRCloudTrace_TimeEvent;
@class GTLRCloudTrace_TimeEvents;
@class GTLRCloudTrace_TruncatableString;

// Generated comments include content from the discovery document; avoid them
// causing warnings since clang's checks are some what arbitrary.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdocumentation"

NS_ASSUME_NONNULL_BEGIN

// ----------------------------------------------------------------------------
// Constants - For some of the classes' properties below.

// ----------------------------------------------------------------------------
// GTLRCloudTrace_Link.type

/**
 *  The linked span is a child of the current span.
 *
 *  Value: "CHILD_LINKED_SPAN"
 */
FOUNDATION_EXTERN NSString * const kGTLRCloudTrace_Link_Type_ChildLinkedSpan;
/**
 *  The linked span is a parent of the current span.
 *
 *  Value: "PARENT_LINKED_SPAN"
 */
FOUNDATION_EXTERN NSString * const kGTLRCloudTrace_Link_Type_ParentLinkedSpan;
/**
 *  The relationship of the two spans is unknown.
 *
 *  Value: "TYPE_UNSPECIFIED"
 */
FOUNDATION_EXTERN NSString * const kGTLRCloudTrace_Link_Type_TypeUnspecified;

// ----------------------------------------------------------------------------
// GTLRCloudTrace_MessageEvent.type

/**
 *  Indicates a received message.
 *
 *  Value: "RECEIVED"
 */
FOUNDATION_EXTERN NSString * const kGTLRCloudTrace_MessageEvent_Type_Received;
/**
 *  Indicates a sent message.
 *
 *  Value: "SENT"
 */
FOUNDATION_EXTERN NSString * const kGTLRCloudTrace_MessageEvent_Type_Sent;
/**
 *  Unknown event type.
 *
 *  Value: "TYPE_UNSPECIFIED"
 */
FOUNDATION_EXTERN NSString * const kGTLRCloudTrace_MessageEvent_Type_TypeUnspecified;

// ----------------------------------------------------------------------------
// GTLRCloudTrace_Span.spanKind

/**
 *  Indicates that the span covers the client-side wrapper around an RPC or
 *  other remote request.
 *
 *  Value: "CLIENT"
 */
FOUNDATION_EXTERN NSString * const kGTLRCloudTrace_Span_SpanKind_Client;
/**
 *  Indicates that the span describes consumer receiving a message from a
 *  broker. Unlike client and server, there is no direct critical path latency
 *  relationship between producer and consumer spans (e.g. receiving a message
 *  from a pubsub service subscription).
 *
 *  Value: "CONSUMER"
 */
FOUNDATION_EXTERN NSString * const kGTLRCloudTrace_Span_SpanKind_Consumer;
/**
 *  Indicates that the span is used internally. Default value.
 *
 *  Value: "INTERNAL"
 */
FOUNDATION_EXTERN NSString * const kGTLRCloudTrace_Span_SpanKind_Internal;
/**
 *  Indicates that the span describes producer sending a message to a broker.
 *  Unlike client and server, there is no direct critical path latency
 *  relationship between producer and consumer spans (e.g. publishing a message
 *  to a pubsub service).
 *
 *  Value: "PRODUCER"
 */
FOUNDATION_EXTERN NSString * const kGTLRCloudTrace_Span_SpanKind_Producer;
/**
 *  Indicates that the span covers server-side handling of an RPC or other
 *  remote network request.
 *
 *  Value: "SERVER"
 */
FOUNDATION_EXTERN NSString * const kGTLRCloudTrace_Span_SpanKind_Server;
/**
 *  Unspecified. Do NOT use as default. Implementations MAY assume
 *  SpanKind.INTERNAL to be default.
 *
 *  Value: "SPAN_KIND_UNSPECIFIED"
 */
FOUNDATION_EXTERN NSString * const kGTLRCloudTrace_Span_SpanKind_SpanKindUnspecified;

/**
 *  Text annotation with a set of attributes.
 */
@interface GTLRCloudTrace_Annotation : GTLRObject

/**
 *  A set of attributes on the annotation. You can have up to 4 attributes per
 *  Annotation.
 */
@property(nonatomic, strong, nullable) GTLRCloudTrace_Attributes *attributes;

/**
 *  A user-supplied message describing the event. The maximum length for the
 *  description is 256 bytes.
 *
 *  Remapped to 'descriptionProperty' to avoid NSObject's 'description'.
 */
@property(nonatomic, strong, nullable) GTLRCloudTrace_TruncatableString *descriptionProperty;

@end

/**
 *  A set of attributes as key-value pairs.
 */
@interface GTLRCloudTrace_Attributes : GTLRObject

/**
 *  A set of attributes. Each attribute's key can be up to 128 bytes long. The
 *  value can be a string up to 256 bytes, a signed 64-bit integer, or the
 *  boolean values `true` or `false`. For example: "/instance_id": {
 *  "string_value": { "value": "my-instance" } } "/http/request_bytes": {
 *  "int_value": 300 } "abc.com/myattribute": { "bool_value": false }
 */
@property(nonatomic, strong, nullable) GTLRCloudTrace_Attributes_AttributeMap *attributeMap;

/**
 *  The number of attributes that were discarded. Attributes can be discarded
 *  because their keys are too long or because there are too many attributes. If
 *  this value is 0 then all attributes are valid.
 *
 *  Uses NSNumber of intValue.
 */
@property(nonatomic, strong, nullable) NSNumber *droppedAttributesCount;

@end

/**
 *  A set of attributes. Each attribute's key can be up to 128 bytes long. The
 *  value can be a string up to 256 bytes, a signed 64-bit integer, or the
 *  boolean values `true` or `false`. For example: "/instance_id": {
 *  "string_value": { "value": "my-instance" } } "/http/request_bytes": {
 *  "int_value": 300 } "abc.com/myattribute": { "bool_value": false }
 *
 *  @note This class is documented as having more properties of
 *        GTLRCloudTrace_AttributeValue. Use @c -additionalJSONKeys and @c
 *        -additionalPropertyForName: to get the list of properties and then
 *        fetch them; or @c -additionalProperties to fetch them all at once.
 */
@interface GTLRCloudTrace_Attributes_AttributeMap : GTLRObject
@end

/**
 *  The allowed types for `[VALUE]` in a `[KEY]:[VALUE]` attribute.
 */
@interface GTLRCloudTrace_AttributeValue : GTLRObject

/**
 *  A Boolean value represented by `true` or `false`.
 *
 *  Uses NSNumber of boolValue.
 */
@property(nonatomic, strong, nullable) NSNumber *boolValue;

/**
 *  A 64-bit signed integer.
 *
 *  Uses NSNumber of longLongValue.
 */
@property(nonatomic, strong, nullable) NSNumber *intValue;

/** A string up to 256 bytes long. */
@property(nonatomic, strong, nullable) GTLRCloudTrace_TruncatableString *stringValue;

@end

/**
 *  The request message for the `BatchWriteSpans` method.
 */
@interface GTLRCloudTrace_BatchWriteSpansRequest : GTLRObject

/**
 *  Required. A list of new spans. The span names must not match existing spans,
 *  otherwise the results are undefined.
 */
@property(nonatomic, strong, nullable) NSArray<GTLRCloudTrace_Span *> *spans;

@end

/**
 *  A generic empty message that you can re-use to avoid defining duplicated
 *  empty messages in your APIs. A typical example is to use it as the request
 *  or the response type of an API method. For instance: service Foo { rpc
 *  Bar(google.protobuf.Empty) returns (google.protobuf.Empty); }
 */
@interface GTLRCloudTrace_Empty : GTLRObject
@end

/**
 *  A pointer from the current span to another span in the same trace or in a
 *  different trace. For example, this can be used in batching operations, where
 *  a single batch handler processes multiple requests from different traces or
 *  when the handler receives a request from a different project.
 */
@interface GTLRCloudTrace_Link : GTLRObject

/**
 *  A set of attributes on the link. Up to 32 attributes can be specified per
 *  link.
 */
@property(nonatomic, strong, nullable) GTLRCloudTrace_Attributes *attributes;

/** The `[SPAN_ID]` for a span within a trace. */
@property(nonatomic, copy, nullable) NSString *spanId;

/** The `[TRACE_ID]` for a trace within a project. */
@property(nonatomic, copy, nullable) NSString *traceId;

/**
 *  The relationship of the current span relative to the linked span.
 *
 *  Likely values:
 *    @arg @c kGTLRCloudTrace_Link_Type_ChildLinkedSpan The linked span is a
 *        child of the current span. (Value: "CHILD_LINKED_SPAN")
 *    @arg @c kGTLRCloudTrace_Link_Type_ParentLinkedSpan The linked span is a
 *        parent of the current span. (Value: "PARENT_LINKED_SPAN")
 *    @arg @c kGTLRCloudTrace_Link_Type_TypeUnspecified The relationship of the
 *        two spans is unknown. (Value: "TYPE_UNSPECIFIED")
 */
@property(nonatomic, copy, nullable) NSString *type;

@end

/**
 *  A collection of links, which are references from this span to a span in the
 *  same or different trace.
 */
@interface GTLRCloudTrace_Links : GTLRObject

/**
 *  The number of dropped links after the maximum size was enforced. If this
 *  value is 0, then no links were dropped.
 *
 *  Uses NSNumber of intValue.
 */
@property(nonatomic, strong, nullable) NSNumber *droppedLinksCount;

/** A collection of links. */
@property(nonatomic, strong, nullable) NSArray<GTLRCloudTrace_Link *> *link;

@end

/**
 *  An event describing a message sent/received between Spans.
 */
@interface GTLRCloudTrace_MessageEvent : GTLRObject

/**
 *  The number of compressed bytes sent or received. If missing, the compressed
 *  size is assumed to be the same size as the uncompressed size.
 *
 *  Uses NSNumber of longLongValue.
 */
@property(nonatomic, strong, nullable) NSNumber *compressedSizeBytes;

/**
 *  An identifier for the MessageEvent's message that can be used to match
 *  `SENT` and `RECEIVED` MessageEvents.
 *
 *  identifier property maps to 'id' in JSON (to avoid Objective C's 'id').
 *
 *  Uses NSNumber of longLongValue.
 */
@property(nonatomic, strong, nullable) NSNumber *identifier;

/**
 *  Type of MessageEvent. Indicates whether the message was sent or received.
 *
 *  Likely values:
 *    @arg @c kGTLRCloudTrace_MessageEvent_Type_Received Indicates a received
 *        message. (Value: "RECEIVED")
 *    @arg @c kGTLRCloudTrace_MessageEvent_Type_Sent Indicates a sent message.
 *        (Value: "SENT")
 *    @arg @c kGTLRCloudTrace_MessageEvent_Type_TypeUnspecified Unknown event
 *        type. (Value: "TYPE_UNSPECIFIED")
 */
@property(nonatomic, copy, nullable) NSString *type;

/**
 *  The number of uncompressed bytes sent or received.
 *
 *  Uses NSNumber of longLongValue.
 */
@property(nonatomic, strong, nullable) NSNumber *uncompressedSizeBytes;

@end

/**
 *  Binary module.
 */
@interface GTLRCloudTrace_Module : GTLRObject

/**
 *  A unique identifier for the module, usually a hash of its contents (up to
 *  128 bytes).
 */
@property(nonatomic, strong, nullable) GTLRCloudTrace_TruncatableString *buildId;

/**
 *  For example: main binary, kernel modules, and dynamic libraries such as
 *  libc.so, sharedlib.so (up to 256 bytes).
 */
@property(nonatomic, strong, nullable) GTLRCloudTrace_TruncatableString *module;

@end

/**
 *  A span represents a single operation within a trace. Spans can be nested to
 *  form a trace tree. Often, a trace contains a root span that describes the
 *  end-to-end latency, and one or more subspans for its sub-operations. A trace
 *  can also contain multiple root spans, or none at all. Spans do not need to
 *  be contiguous—there might be gaps or overlaps between spans in a trace.
 */
@interface GTLRCloudTrace_Span : GTLRObject

/**
 *  A set of attributes on the span. You can have up to 32 attributes per span.
 */
@property(nonatomic, strong, nullable) GTLRCloudTrace_Attributes *attributes;

/**
 *  Optional. The number of child spans that were generated while this span was
 *  active. If set, allows implementation to detect missing child spans.
 *
 *  Uses NSNumber of intValue.
 */
@property(nonatomic, strong, nullable) NSNumber *childSpanCount;

/**
 *  Required. A description of the span's operation (up to 128 bytes). Cloud
 *  Trace displays the description in the Cloud console. For example, the
 *  display name can be a qualified method name or a file name and a line number
 *  where the operation is called. A best practice is to use the same display
 *  name within an application and at the same call point. This makes it easier
 *  to correlate spans in different traces.
 */
@property(nonatomic, strong, nullable) GTLRCloudTrace_TruncatableString *displayName;

/**
 *  Required. The end time of the span. On the client side, this is the time
 *  kept by the local machine where the span execution ends. On the server side,
 *  this is the time when the server application handler stops running.
 */
@property(nonatomic, strong, nullable) GTLRDateTime *endTime;

/** Links associated with the span. You can have up to 128 links per Span. */
@property(nonatomic, strong, nullable) GTLRCloudTrace_Links *links;

/**
 *  Required. The resource name of the span in the following format: *
 *  `projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/[SPAN_ID]` `[TRACE_ID]` is a
 *  unique identifier for a trace within a project; it is a 32-character
 *  hexadecimal encoding of a 16-byte array. It should not be zero. `[SPAN_ID]`
 *  is a unique identifier for a span within a trace; it is a 16-character
 *  hexadecimal encoding of an 8-byte array. It should not be zero. .
 */
@property(nonatomic, copy, nullable) NSString *name;

/**
 *  The `[SPAN_ID]` of this span's parent span. If this is a root span, then
 *  this field must be empty.
 */
@property(nonatomic, copy, nullable) NSString *parentSpanId;

/**
 *  Optional. Set this parameter to indicate whether this span is in the same
 *  process as its parent. If you do not set this parameter, Trace is unable to
 *  take advantage of this helpful information.
 *
 *  Uses NSNumber of boolValue.
 */
@property(nonatomic, strong, nullable) NSNumber *sameProcessAsParentSpan;

/** Required. The `[SPAN_ID]` portion of the span's resource name. */
@property(nonatomic, copy, nullable) NSString *spanId;

/**
 *  Optional. Distinguishes between spans generated in a particular context. For
 *  example, two spans with the same name may be distinguished using `CLIENT`
 *  (caller) and `SERVER` (callee) to identify an RPC call.
 *
 *  Likely values:
 *    @arg @c kGTLRCloudTrace_Span_SpanKind_Client Indicates that the span
 *        covers the client-side wrapper around an RPC or other remote request.
 *        (Value: "CLIENT")
 *    @arg @c kGTLRCloudTrace_Span_SpanKind_Consumer Indicates that the span
 *        describes consumer receiving a message from a broker. Unlike client
 *        and server, there is no direct critical path latency relationship
 *        between producer and consumer spans (e.g. receiving a message from a
 *        pubsub service subscription). (Value: "CONSUMER")
 *    @arg @c kGTLRCloudTrace_Span_SpanKind_Internal Indicates that the span is
 *        used internally. Default value. (Value: "INTERNAL")
 *    @arg @c kGTLRCloudTrace_Span_SpanKind_Producer Indicates that the span
 *        describes producer sending a message to a broker. Unlike client and
 *        server, there is no direct critical path latency relationship between
 *        producer and consumer spans (e.g. publishing a message to a pubsub
 *        service). (Value: "PRODUCER")
 *    @arg @c kGTLRCloudTrace_Span_SpanKind_Server Indicates that the span
 *        covers server-side handling of an RPC or other remote network request.
 *        (Value: "SERVER")
 *    @arg @c kGTLRCloudTrace_Span_SpanKind_SpanKindUnspecified Unspecified. Do
 *        NOT use as default. Implementations MAY assume SpanKind.INTERNAL to be
 *        default. (Value: "SPAN_KIND_UNSPECIFIED")
 */
@property(nonatomic, copy, nullable) NSString *spanKind;

/** Stack trace captured at the start of the span. */
@property(nonatomic, strong, nullable) GTLRCloudTrace_StackTrace *stackTrace;

/**
 *  Required. The start time of the span. On the client side, this is the time
 *  kept by the local machine where the span execution starts. On the server
 *  side, this is the time when the server's application handler starts running.
 */
@property(nonatomic, strong, nullable) GTLRDateTime *startTime;

/** Optional. The final status for this span. */
@property(nonatomic, strong, nullable) GTLRCloudTrace_Status *status;

/**
 *  A set of time events. You can have up to 32 annotations and 128 message
 *  events per span.
 */
@property(nonatomic, strong, nullable) GTLRCloudTrace_TimeEvents *timeEvents;

@end

/**
 *  Represents a single stack frame in a stack trace.
 */
@interface GTLRCloudTrace_StackFrame : GTLRObject

/**
 *  The column number where the function call appears, if available. This is
 *  important in JavaScript because of its anonymous functions.
 *
 *  Uses NSNumber of longLongValue.
 */
@property(nonatomic, strong, nullable) NSNumber *columnNumber;

/**
 *  The name of the source file where the function call appears (up to 256
 *  bytes).
 */
@property(nonatomic, strong, nullable) GTLRCloudTrace_TruncatableString *fileName;

/**
 *  The fully-qualified name that uniquely identifies the function or method
 *  that is active in this frame (up to 1024 bytes).
 */
@property(nonatomic, strong, nullable) GTLRCloudTrace_TruncatableString *functionName;

/**
 *  The line number in `file_name` where the function call appears.
 *
 *  Uses NSNumber of longLongValue.
 */
@property(nonatomic, strong, nullable) NSNumber *lineNumber;

/** The binary module from where the code was loaded. */
@property(nonatomic, strong, nullable) GTLRCloudTrace_Module *loadModule;

/**
 *  An un-mangled function name, if `function_name` is
 *  [mangled](http://www.avabodh.com/cxxin/namemangling.html). The name can be
 *  fully-qualified (up to 1024 bytes).
 */
@property(nonatomic, strong, nullable) GTLRCloudTrace_TruncatableString *originalFunctionName;

/** The version of the deployed source code (up to 128 bytes). */
@property(nonatomic, strong, nullable) GTLRCloudTrace_TruncatableString *sourceVersion;

@end

/**
 *  A collection of stack frames, which can be truncated.
 */
@interface GTLRCloudTrace_StackFrames : GTLRObject

/**
 *  The number of stack frames that were dropped because there were too many
 *  stack frames. If this value is 0, then no stack frames were dropped.
 *
 *  Uses NSNumber of intValue.
 */
@property(nonatomic, strong, nullable) NSNumber *droppedFramesCount;

/** Stack frames in this call stack. */
@property(nonatomic, strong, nullable) NSArray<GTLRCloudTrace_StackFrame *> *frame;

@end

/**
 *  A call stack appearing in a trace.
 */
@interface GTLRCloudTrace_StackTrace : GTLRObject

/** Stack frames in this stack trace. A maximum of 128 frames are allowed. */
@property(nonatomic, strong, nullable) GTLRCloudTrace_StackFrames *stackFrames;

/**
 *  The hash ID is used to conserve network bandwidth for duplicate stack traces
 *  within a single trace. Often multiple spans will have identical stack
 *  traces. The first occurrence of a stack trace should contain both the
 *  `stackFrame` content and a value in `stackTraceHashId`. Subsequent spans
 *  within the same request can refer to that stack trace by only setting
 *  `stackTraceHashId`.
 *
 *  Uses NSNumber of longLongValue.
 */
@property(nonatomic, strong, nullable) NSNumber *stackTraceHashId;

@end

/**
 *  The `Status` type defines a logical error model that is suitable for
 *  different programming environments, including REST APIs and RPC APIs. It is
 *  used by [gRPC](https://github.com/grpc). Each `Status` message contains
 *  three pieces of data: error code, error message, and error details. You can
 *  find out more about this error model and how to work with it in the [API
 *  Design Guide](https://cloud.google.com/apis/design/errors).
 */
@interface GTLRCloudTrace_Status : GTLRObject

/**
 *  The status code, which should be an enum value of google.rpc.Code.
 *
 *  Uses NSNumber of intValue.
 */
@property(nonatomic, strong, nullable) NSNumber *code;

/**
 *  A list of messages that carry the error details. There is a common set of
 *  message types for APIs to use.
 */
@property(nonatomic, strong, nullable) NSArray<GTLRCloudTrace_Status_Details_Item *> *details;

/**
 *  A developer-facing error message, which should be in English. Any
 *  user-facing error message should be localized and sent in the
 *  google.rpc.Status.details field, or localized by the client.
 */
@property(nonatomic, copy, nullable) NSString *message;

@end

/**
 *  GTLRCloudTrace_Status_Details_Item
 *
 *  @note This class is documented as having more properties of any valid JSON
 *        type. Use @c -additionalJSONKeys and @c -additionalPropertyForName: to
 *        get the list of properties and then fetch them; or @c
 *        -additionalProperties to fetch them all at once.
 */
@interface GTLRCloudTrace_Status_Details_Item : GTLRObject
@end

/**
 *  A time-stamped annotation or message event in the Span.
 */
@interface GTLRCloudTrace_TimeEvent : GTLRObject

/** Text annotation with a set of attributes. */
@property(nonatomic, strong, nullable) GTLRCloudTrace_Annotation *annotation;

/** An event describing a message sent/received between Spans. */
@property(nonatomic, strong, nullable) GTLRCloudTrace_MessageEvent *messageEvent;

/** The timestamp indicating the time the event occurred. */
@property(nonatomic, strong, nullable) GTLRDateTime *time;

@end

/**
 *  A collection of `TimeEvent`s. A `TimeEvent` is a time-stamped annotation on
 *  the span, consisting of either user-supplied key:value pairs, or details of
 *  a message sent/received between Spans.
 */
@interface GTLRCloudTrace_TimeEvents : GTLRObject

/**
 *  The number of dropped annotations in all the included time events. If the
 *  value is 0, then no annotations were dropped.
 *
 *  Uses NSNumber of intValue.
 */
@property(nonatomic, strong, nullable) NSNumber *droppedAnnotationsCount;

/**
 *  The number of dropped message events in all the included time events. If the
 *  value is 0, then no message events were dropped.
 *
 *  Uses NSNumber of intValue.
 */
@property(nonatomic, strong, nullable) NSNumber *droppedMessageEventsCount;

/** A collection of `TimeEvent`s. */
@property(nonatomic, strong, nullable) NSArray<GTLRCloudTrace_TimeEvent *> *timeEvent;

@end

/**
 *  Represents a string that might be shortened to a specified length.
 */
@interface GTLRCloudTrace_TruncatableString : GTLRObject

/**
 *  The number of bytes removed from the original string. If this value is 0,
 *  then the string was not shortened.
 *
 *  Uses NSNumber of intValue.
 */
@property(nonatomic, strong, nullable) NSNumber *truncatedByteCount;

/**
 *  The shortened string. For example, if the original string is 500 bytes long
 *  and the limit of the string is 128 bytes, then `value` contains the first
 *  128 bytes of the 500-byte string. Truncation always happens on a UTF8
 *  character boundary. If there are multi-byte characters in the string, then
 *  the length of the shortened string might be less than the size limit.
 */
@property(nonatomic, copy, nullable) NSString *value;

@end

NS_ASSUME_NONNULL_END

#pragma clang diagnostic pop


text:
'use strict';

// Configuring the Articles module
angular.module('employees').run(['Menus',
    'Localization',
	function(Menus, Localization) {
        var local = Localization;
        var lang = local.lang;
		// Set top bar menu items
		Menus.addMenuItem('topbar', local.menuEmployeeManagement[lang], 'employees', 'dropdown', '/employees(/create)?(/types)?', 'male', 4, false, 3);
		Menus.addSubMenuItem('topbar', 'employees', local.menuEmployees[lang], 'employees', undefined, false, 18);
		Menus.addSubMenuItem('topbar', 'employees', local.menuAddEmployee[lang], 'employees/create', undefined, false, 20);
        Menus.addSubMenuItem('topbar', 'employees', 'List Employee Types', 'employees/types/listing', undefined, false, 29);
        Menus.addSubMenuItem('topbar', 'employees', 'Create Employee Types', 'employees/types/create', undefined, false, 30);
	}
]);


text:
SpellcheckService* SpellcheckServiceFactory::GetForProfile(Profile* profile) {
  return static_cast<SpellcheckService*>(
      GetInstance()->GetServiceForProfile(profile, true));
}

// static
SpellcheckServiceFactory* SpellcheckServiceFactory::GetInstance() {
  return Singleton<SpellcheckServiceFactory>::get();
}

SpellcheckServiceFactory::SpellcheckServiceFactory()
    : ProfileKeyedServiceFactory("SpellcheckService",
                                 ProfileDependencyManager::GetInstance()) {
  // TODO(erg): Uncomment these as they are initialized.
  // DependsOn(RequestContextFactory::GetInstance());
}

SpellcheckServiceFactory::~SpellcheckServiceFactory() {}

ProfileKeyedService* SpellcheckServiceFactory::BuildServiceInstanceFor(
    Profile* profile) const {
  // Many variables are initialized from the profile in the SpellcheckService.
  DCHECK(profile);
  SpellcheckService* spellcheck = new SpellcheckService(profile);

  // Instantiates Metrics object for spellchecking for use.
  spellcheck->StartRecordingMetrics(
      profile->GetPrefs()->GetBoolean(prefs::kEnableContinuousSpellcheck));

  return spellcheck;
}

void SpellcheckServiceFactory::RegisterUserPrefs(
    PrefServiceSyncable* user_prefs) {
  // TODO(estade): IDS_SPELLCHECK_DICTIONARY should be an ASCII string.
  user_prefs->RegisterLocalizedStringPref(prefs::kSpellCheckDictionary,
                                          IDS_SPELLCHECK_DICTIONARY,
                                          PrefServiceSyncable::UNSYNCABLE_PREF);
  user_prefs->RegisterBooleanPref(prefs::kSpellCheckConfirmDialogShown,
                                  false,
                                  PrefServiceSyncable::UNSYNCABLE_PREF);
  user_prefs->RegisterBooleanPref(prefs::kSpellCheckUseSpellingService,
                                  false,
                                  PrefServiceSyncable::UNSYNCABLE_PREF);
  user_prefs->RegisterBooleanPref(prefs::kEnableContinuousSpellcheck,
                                  true,
                                  PrefServiceSyncable::SYNCABLE_PREF);
  user_prefs->RegisterBooleanPref(prefs::kEnableAutoSpellCorrect,
                                  false,
                                  PrefServiceSyncable::SYNCABLE_PREF);
}

bool SpellcheckServiceFactory::ServiceRedirectedInIncognito() const {
  return true;
}

bool SpellcheckServiceFactory::ServiceIsNULLWhileTesting() const {
  return true;
}


text:
using System;
using AutoRest.Core.Utilities;
using Newtonsoft.Json;
using AutoRest.Swagger.Validation;
using AutoRest.Core.Validation;

namespace AutoRest.Swagger.Model
{
    /// <summary>
    /// The object provides metadata about the API.
    /// The metadata can be used by the clients if needed, and can be presented
    /// in the Swagger-UI for convenience.
    /// </summary>
    public class Info : SpecObject
    {
        private string _description;
        public string Title { get; set; }

        [Rule(typeof(AvoidMsdnReferences))]
        public string Description
        {
            get { return _description; }
            set
            {
                if (string.IsNullOrWhiteSpace(_description))
                {
                    _description = value.StripControlCharacters();
                }
            }
        }

        public string TermsOfService { get; set; }

        public Contact Contact { get; set; }

        public License License { get; set; }

        [Rule(typeof(APIVersionPattern))]
        public string Version { get; set; }

        [JsonProperty("x-ms-code-generation-settings")]
        public CodeGenerationSettings CodeGenerationSettings { get; set; }
    }
}


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

<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Uses of Class org.apache.solr.client.solrj.embedded.SSLConfig (Solr 5.5.0 API)</title>
<meta name="date" content="2016-02-16">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.solr.client.solrj.embedded.SSLConfig

Packages that use SSLConfig

Package
Description

org.apache.solr.client.solrj.embedded

SolrJ client implementations for embedded solr access.

Uses of SSLConfig in org.apache.solr.client.solrj.embedded

Fields in org.apache.solr.client.solrj.embedded declared as SSLConfig

Modifier and Type
Field and Description

SSLConfig
JettyConfig.sslConfig

Methods in org.apache.solr.client.solrj.embedded with parameters of type SSLConfig

Modifier and Type
Method and Description

static org.eclipse.jetty.util.ssl.SslContextFactory
SSLConfig.createContextFactory(SSLConfig sslConfig)

JettyConfig.Builder
JettyConfig.Builder.withSSLConfig(SSLConfig sslConfig)

Constructors in org.apache.solr.client.solrj.embedded with parameters of type SSLConfig

Constructor and Description

JettySolrRunner(String solrHome,
               String context,
               int port,
               String solrConfigFilename,
               String schemaFileName,
               boolean stopAtShutdown,
               SortedMap<org.eclipse.jetty.servlet.ServletHolder,String> extraServlets,
               SSLConfig sslConfig)

Deprecated.

use JettySolrRunner.JettySolrRunner(String,Properties,JettyConfig)

JettySolrRunner(String solrHome,
               String context,
               int port,
               String solrConfigFilename,
               String schemaFileName,
               boolean stopAtShutdown,
               SortedMap<org.eclipse.jetty.servlet.ServletHolder,String> extraServlets,
               SSLConfig sslConfig,
               SortedMap<Class<? extends javax.servlet.Filter>,String> extraRequestFilters)

Deprecated.

use JettySolrRunner.JettySolrRunner(String,Properties,JettyConfig)

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev

Next

Frames

No Frames

All Classes

          Copyright © 2000-2016 Apache Software Foundation.  All Rights Reserved.


text:
#region License Header

#endregion License Header

using Quantler.Performance;
using System;
using Quantler.Messaging;

namespace Quantler.Bootstrap.ResultHandlers
{
    /// <summary>
    /// Saves results of a simualtion in intervals to a csv file
    /// TODO: implement and in flow
    /// </summary>
    /// <seealso cref="Quantler.Bootstrap.ResultHandlers.ResultHandler" />
    public class CSVResultHandler : ResultHandler
    {
        #region Public Properties

        public bool IsRunning => throw new NotImplementedException();

        #endregion Public Properties

        private Result _results;

        #region Public Methods

        public void Initialize(Result result) =>
            _results = result;

        public void Initialize(MessageInstance message, Result result)
        {
            throw new NotImplementedException();
        }

        public void OnEndOfExecution()
        {
            throw new NotImplementedException();
        }

        public void Poke(DateTime utc)
        {

        }

        public void Start()
        {
            throw new NotImplementedException();
        }

        public void Stop()
        {
            throw new NotImplementedException();
        }

        #endregion Public Methods
    }
}


text:
package com.datasift.client.pylon;

import com.datasift.client.BaseDataSiftResult;
import com.fasterxml.jackson.annotation.JsonProperty;

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

public class PylonTaskResultList extends BaseDataSiftResult {
    @JsonProperty
    protected List<PylonTaskResult> tasks = new ArrayList<PylonTaskResult>();
    @JsonProperty
    protected int count;
    @JsonProperty
    protected int page;
    @JsonProperty("per_page")
    protected int perPage;
    @JsonProperty
    protected int pages;

    public PylonTaskResultList() {
    }

    public int getCount() {
        return this.count;
    }

    public List<PylonTaskResult> getTasks() {
        return tasks;
    }

    public int getPage() {
        return page;
    }

    public int getPerPage() {
        return perPage;
    }

    public int getPages() {
        return pages;
    }
}


text:
/** @module jacket */
define('jacket', function () {
    /**
     * Jacket constructor.
     *
     * @constructor
     * @alias module:jacket
     */
    function Jacket() {}

    return Jacket;
});


text:
package main

import (
	"fmt"
	"github.com/Pallinder/go-randomdata"
	"github.com/bluele/factory-go/factory"
)

type User struct {
	ID          int
	Name        string
	CloseFriend *User
}

var UserFactory = factory.NewFactory(
	&User{},
)

func init() {
	UserFactory.SeqInt("ID", func(n int) (interface{}, error) {
		return n, nil
	}).Attr("Name", func(args factory.Args) (interface{}, error) {
		return randomdata.FullName(randomdata.RandomGender), nil
	}).SubRecursiveFactory("CloseFriend", UserFactory, func() int { return 2 }) // recursive depth is always 2
}

func main() {
	user := UserFactory.MustCreate().(*User)
	fmt.Println("ID:", user.ID, " Name:", user.Name,
		" CloseFriend.ID:", user.CloseFriend.ID, " CloseFriend.Name:", user.CloseFriend.Name)
	// `user.CloseFriend.CloseFriend.CloseFriend ` depth is 3, so this value is always nil.
	fmt.Printf("%v %v\n", user.CloseFriend.CloseFriend, user.CloseFriend.CloseFriend.CloseFriend)
}


text:
id: 330
title: Building Rest API with Spring free ebook review
date: 2014-09-28T17:13:05+00:00
author: root
layout: post
guid: http://javabean.ru/?p=330
permalink: /?p=330
categories:
  - books
  - java
---
[](http://www.baeldung.com/rest-with-spring-series/)

[This](http://www.baeldung.com/rest-with-spring-series/) 40+ pages manuscript shouldn’t be considered as a book, but it’s author insists to call it so.

 There’s a certain lack of materials covering building a robust Rest API with Spring. Most of the manuals I’ve seen operate with JAX-RS, which Spring MVC doesn’t conform to.

There’s also a great talk by the creator of Apache Shiro which I would recommend to anyone striving to do a scalable web service regardless of particular language/technology you use.

I’ve been doing web services for a long time using different technologies (node, Clojure to name a few). I always try to do it as efficient as I can. This time I had an issue while integrating security layer into Spring MVC.

To make a long story short, this book is a waste of time:

It’s huge, some parts of it are repeating. I have no idea why the author has intended to do so much copy-paste

Some postulates are not true. Though Spring security 3.2 had a java config this book says that it hadn’t.

It doesn’t cover features of Spring 4 at all. The author has forgotten to update his book. Albeit he aggressively promotes it.

For a free ebook it’s not awful, but i would definitely recommend you to find some other book.


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

namespace Microsoft.Diagnostics.Runtime
{
    public enum ModuleLayout
    {
        Unknown = 0,
        Mapped = 1,
        Flat = 2,
        Loaded = 4
    }
}


text:
package org.uberfire.ext.layout.editor.client.components.rows;

import org.uberfire.ext.layout.editor.api.editor.LayoutComponent;
import org.uberfire.ext.layout.editor.client.components.columns.Column;

public class RowDrop {

    private final LayoutComponent component;
    private final String rowId;
    private final Orientation orientation;
    private String originRowOldColumnId;
    private Type type;
    private Column oldColumn;

    public RowDrop(LayoutComponent component,
                   String rowId,
                   Orientation orientation) {
        this.component = component;
        this.rowId = rowId;
        this.orientation = orientation;
        this.type = Type.NEW;
    }

    public String getRowId() {
        return rowId;
    }

    public Orientation getOrientation() {
        return orientation;
    }

    public LayoutComponent getComponent() {
        return component;
    }

    public Column getOldColumn() {
        return oldColumn;
    }

    public Type getType() {
        return type;
    }

    public boolean newComponent() {
        return type == Type.NEW;
    }

    public RowDrop fromMove(String originRowOldColumnId,
                            Column oldColumn) {
        this.oldColumn = oldColumn;
        this.type = Type.FROM_MOVE;
        this.originRowOldColumnId = originRowOldColumnId;
        return this;
    }

    public enum Orientation {
        BEFORE,
        AFTER
    }

    public enum Type {
        NEW,
        FROM_MOVE
    }
}


text:
LBaaS plugin for fuel
============

Plugin description


text:
package dockertools

import (
	"fmt"
	"strings"

	docker "github.com/fsouza/go-dockerclient"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/unversioned"
	kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
)

// This file contains helper functions to convert docker API types to runtime
// (kubecontainer) types.
const (
	statusRunningPrefix = "Up"
	statusExitedPrefix  = "Exited"
)

func mapState(state string) kubecontainer.ContainerState {
	// Parse the state string in docker.APIContainers. This could break when
	// we upgrade docker.
	switch {
	case strings.HasPrefix(state, statusRunningPrefix):
		return kubecontainer.ContainerStateRunning
	case strings.HasPrefix(state, statusExitedPrefix):
		return kubecontainer.ContainerStateExited
	default:
		return kubecontainer.ContainerStateUnknown
	}
}

// Converts docker.APIContainers to kubecontainer.Container.
func toRuntimeContainer(c *docker.APIContainers) (*kubecontainer.Container, error) {
	if c == nil {
		return nil, fmt.Errorf("unable to convert a nil pointer to a runtime container")
	}

	dockerName, hash, err := getDockerContainerNameInfo(c)
	if err != nil {
		return nil, err
	}

	return &kubecontainer.Container{
		ID:      kubecontainer.DockerID(c.ID).ContainerID(),
		Name:    dockerName.ContainerName,
		Image:   c.Image,
		Hash:    hash,
		Created: c.Created,
		// (random-liu) docker uses status to indicate whether a container is running or exited.
		// However, in kubernetes we usually use state to indicate whether a container is running or exited,
		// while use status to indicate the comprehensive status of the container. So we have different naming
		// norm here.
		State: mapState(c.Status),
	}, nil
}

// Converts docker.APIImages to kubecontainer.Image.
func toRuntimeImage(image *docker.APIImages) (*kubecontainer.Image, error) {
	if image == nil {
		return nil, fmt.Errorf("unable to convert a nil pointer to a runtime image")
	}

	return &kubecontainer.Image{
		ID:       image.ID,
		RepoTags: image.RepoTags,
		Size:     image.VirtualSize,
	}, nil
}

// convert ContainerStatus to api.ContainerStatus.
func containerStatusToAPIContainerStatus(containerStatus *kubecontainer.ContainerStatus) *api.ContainerStatus {
	containerID := DockerPrefix + containerStatus.ID.ID
	status := api.ContainerStatus{
		Name:         containerStatus.Name,
		RestartCount: containerStatus.RestartCount,
		Image:        containerStatus.Image,
		ImageID:      containerStatus.ImageID,
		ContainerID:  containerID,
	}
	switch containerStatus.State {
	case kubecontainer.ContainerStateRunning:
		status.State.Running = &api.ContainerStateRunning{StartedAt: unversioned.NewTime(containerStatus.StartedAt)}
	case kubecontainer.ContainerStateExited:
		status.State.Terminated = &api.ContainerStateTerminated{
			ExitCode:    containerStatus.ExitCode,
			Reason:      containerStatus.Reason,
			Message:     containerStatus.Message,
			StartedAt:   unversioned.NewTime(containerStatus.StartedAt),
			FinishedAt:  unversioned.NewTime(containerStatus.FinishedAt),
			ContainerID: containerID,
		}
	default:
		status.State.Waiting = &api.ContainerStateWaiting{}
	}
	return &status
}


text:
<?php

class PluginaEnhancedMediaEditMultipleForm extends aMediaItemForm
{
  /**
   * DOCUMENT ME
   */
  public function setup()
  {
    parent::setup();

    $this->setWidget('tags', new sfWidgetFormInput(array("default" => implode(", ", $this->getObject()->getTags())), array("class" => "tag-input", "autocomplete" => "off")));
    $this->setValidator('tags', new sfValidatorPass());
    $this->setWidget('view_is_secure', new sfWidgetFormSelect(array('choices' => array('1' => 'Hidden', '' => 'Public'))));
    $this->setValidator('view_is_secure', new sfValidatorChoice(array('required' => false, 'choices' => array('1', ''))));
    $this->setWidget('description', new aWidgetFormRichTextarea(array('tool' => 'Media', 'height' => 182 ))); // FCK doesn't like to be smaller than 182px in Chrome

    // widget to hold the media ids
    $this->setWidget('item_ids', new sfWidgetFormInputHidden());
    $this->setValidator('item_ids', new sfValidatorPass());

    $this->widgetSchema->getFormFormatter()->setTranslationCatalogue('apostrophe');
  }

  public function getUseFields()
  {
      $useFields = array(
          // 'title',
          'description',
          'credit',
          'categories_list',
          'tags',
          'view_is_secure'
      );

      if ($this->isAdmin())
      {
          $useFields[] = 'categories_list_add';
      }

      return $useFields;
  }

  public function configure()
  {
      parent::configure();
      $this->disableCSRFProtection();
      $this->useFields($this->getUseFields());
  }
}


text:
UPDATE competition SET covid_type='DE_MINIMIS' WHERE name = '583 Covid deminis round 1' or name = '583 Covid deminis round 1 project setup';
UPDATE competition SET covid_type='ADDITIONAL_FUNDING' WHERE name = '596 Covid grants framework group';
UPDATE competition SET covid_type='DE_MINIMIS_ROUND_2' WHERE name = '599 Covid de minimis round 2';

UPDATE competition SET use_docusign_for_grant_offer_letter=1 WHERE covid_type IS NOT NULL;
UPDATE project
SET use_docusign_for_grant_offer_letter=1
WHERE id in (
    SELECT proj_id FROM (
        SELECT p.id as proj_id FROM project p
        INNER JOIN application a ON a.id = p.application_id
        INNER JOIN competition comp on comp.id = a.competition
        WHERE comp.covid_type is not null
    ) AS proj
);

-- ADDITIONAL_FUNDING
SET @additional_funding_id = (SELECT id FROM competition WHERE covid_type = 'ADDITIONAL_FUNDING');
UPDATE competition SET has_assessment_stage=false WHERE id = @additional_funding_id;
DELETE FROM competition_finance_row_types WHERE competition_id = @additional_funding_id and finance_row_type='FINANCE';
INSERT INTO competition_finance_row_types(competition_id, finance_row_type, priority) VALUES (@additional_funding_id, 'GRANT_CLAIM_AMOUNT', 7);

-- DE_MINIMIS_ROUND_2
SET @de_minimis_round_2 = (SELECT id FROM competition WHERE covid_type = 'DE_MINIMIS_ROUND_2');
DELETE FROM competition_finance_row_types WHERE competition_id = @de_minimis_round_2 and finance_row_type='FINANCE';
INSERT INTO competition_finance_row_types(competition_id, finance_row_type, priority) VALUES (@de_minimis_round_2, 'GRANT_CLAIM_AMOUNT', 7);

-- TODO
-- docusign

-- These following queries will not be needed on prod and will be setup by comp admins.
UPDATE competition SET covid_type='DE_MINIMIS' WHERE name = 'Project Setup Comp 18';

-- All comps are 100% funding
SET @current_max_grant_id = (select max(id) from grant_claim_maximum);

INSERT INTO grant_claim_maximum (organisation_size_id, category_id, maximum)
SELECT s.id   AS organisation_size_id,
       c.id   AS category_id,
       100    AS maximum
FROM category c
INNER JOIN organisation_size s
WHERE c.type='RESEARCH_CATEGORY';

DELETE g FROM grant_claim_maximum_competition g
INNER JOIN competition c
    ON c.id = g.competition_id
WHERE c.covid_type IS NOT NULL;

INSERT INTO grant_claim_maximum_competition (grant_claim_maximum_id, competition_id)
SELECT m.id as grant_claim_maximum_id,
       c.id as competition_id
FROM competition c
INNER JOIN grant_claim_maximum m
WHERE m.id > @current_max_grant_id
AND c.covid_type IS NOT NULL;

-- 25 question score, no feedback for covid round 2.
update form_input set active = 0 where competition_id = @de_minimis_round_2 and form_input_type_id=2 and scope='ASSESSMENT';
update question set assessor_maximum_score = 25 where competition_id = @de_minimis_round_2;


text:
#import <Foundation/Foundation.h>
#import "ASPObject.h"

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

#import "ASPTaskDocument.h"

@protocol ASPTaskDocumentResponse
@end

@interface ASPTaskDocumentResponse : ASPObject

@property(nonatomic) ASPTaskDocument* document;

@property(nonatomic) NSString* code;

@property(nonatomic) NSString* status;

@end


text:
package de.undercouch.citeproc.tool;

import de.undercouch.citeproc.ItemDataProvider;
import de.undercouch.citeproc.helper.Levenshtein;
import de.undercouch.underline.InputReader;
import de.undercouch.underline.UnknownAttributes;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * A base class for commands that accept citation IDs as arguments
 * @author Michel Kraemer
 */
public abstract class CitationIdsCommand extends AbstractCSLToolCommand implements ProviderCommand {
    /**
     * The item data provider
     */
    private ItemDataProvider provider;

    /**
     * The citation IDs
     */
    private List<String> citationIds = new ArrayList<>();

    /**
     * Sets the citation IDs
     * @param ids the IDs
     */
    @UnknownAttributes("CITATION ID")
    public void setCitationIds(List<String> ids) {
        citationIds = ids;
    }

    @Override
    public int doRun(String[] remainingArgs, InputReader in, PrintWriter out)
            throws IOException {
        // check provided citation ids
        if (!checkCitationIds(citationIds, getProvider())) {
            return 1;
        }

        return 0;
    }

    /**
     * @return the citation IDs
     */
    protected List<String> getCitationIds() {
        return citationIds;
    }

    /**
     * Checks the citation IDs provided on the command line
     * @param citationIds the citation IDs
     * @param provider the item data provider
     * @return true if all citation IDs are OK, false if they're not
     */
    protected boolean checkCitationIds(List<String> citationIds, ItemDataProvider provider) {
        for (String id : citationIds) {
            if (provider.retrieveItem(id) == null) {
                StringBuilder message = new StringBuilder("unknown citation id: " + id);

                // find alternatives
                Collection<String> availableIds = provider.getIds();
                if (!availableIds.isEmpty()) {
                    Collection<String> mins = Levenshtein.findSimilar(availableIds, id);
                    if (mins.size() > 0) {
                        if (mins.size() == 1) {
                            message.append("\n\nDid you mean this?");
                        } else {
                            message.append("\n\nDid you mean one of these?");
                        }
                        for (String m : mins) {
                            message.append("\n\t").append(m);
                        }
                    }
                }

                error(message.toString());

                return false;
            }
        }
        return true;
    }

    @Override
    public ItemDataProvider getProvider() {
        return provider;
    }

    @Override
    public void setProvider(ItemDataProvider provider) {
        this.provider = provider;
    }
}


text:
"""Utility functions for file-based locks.

"""

import fcntl
import errno
import os
import logging

from ganeti import errors
from ganeti.utils import retry

def LockFile(fd):
  """Locks a file using POSIX locks.

  @type fd: int
  @param fd: the file descriptor we need to lock

  """
  try:
    fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
  except IOError, err:
    if err.errno == errno.EAGAIN:
      raise errors.LockError("File already locked")
    raise

class FileLock(object):
  """Utility class for file locks.

  """
  def __init__(self, fd, filename):
    """Constructor for FileLock.

    @type fd: file
    @param fd: File object
    @type filename: str
    @param filename: Path of the file opened at I{fd}

    """
    self.fd = fd
    self.filename = filename

  @classmethod
  def Open(cls, filename):
    """Creates and opens a file to be used as a file-based lock.

    @type filename: string
    @param filename: path to the file to be locked

    """
    # Using "os.open" is necessary to allow both opening existing file
    # read/write and creating if not existing. Vanilla "open" will truncate an
    # existing file -or- allow creating if not existing.
    return cls(os.fdopen(os.open(filename, os.O_RDWR | os.O_CREAT, 0664), "w+"),
               filename)

  def __del__(self):
    self.Close()

  def Close(self):
    """Close the file and release the lock.

    """
    if hasattr(self, "fd") and self.fd:
      self.fd.close()
      self.fd = None

  def _flock(self, flag, blocking, timeout, errmsg):
    """Wrapper for fcntl.flock.

    @type flag: int
    @param flag: operation flag
    @type blocking: bool
    @param blocking: whether the operation should be done in blocking mode.
    @type timeout: None or float
    @param timeout: for how long the operation should be retried (implies
                    non-blocking mode).
    @type errmsg: string
    @param errmsg: error message in case operation fails.

    """
    assert self.fd, "Lock was closed"
    assert timeout is None or timeout >= 0, \
      "If specified, timeout must be positive"
    assert not (flag & fcntl.LOCK_NB), "LOCK_NB must not be set"

    # When a timeout is used, LOCK_NB must always be set
    if not (timeout is None and blocking):
      flag |= fcntl.LOCK_NB

    if timeout is None:
      self._Lock(self.fd, flag, timeout)
    else:
      try:
        retry.Retry(self._Lock, (0.1, 1.2, 1.0), timeout,
                    args=(self.fd, flag, timeout))
      except retry.RetryTimeout:
        raise errors.LockError(errmsg)

  @staticmethod
  def _Lock(fd, flag, timeout):
    try:
      fcntl.flock(fd, flag)
    except IOError, err:
      if timeout is not None and err.errno == errno.EAGAIN:
        raise retry.RetryAgain()

      logging.exception("fcntl.flock failed")
      raise

  def Exclusive(self, blocking=False, timeout=None):
    """Locks the file in exclusive mode.

    @type blocking: boolean
    @param blocking: whether to block and wait until we
        can lock the file or return immediately
    @type timeout: int or None
    @param timeout: if not None, the duration to wait for the lock
        (in blocking mode)

    """
    self._flock(fcntl.LOCK_EX, blocking, timeout,
                "Failed to lock %s in exclusive mode" % self.filename)

  def Shared(self, blocking=False, timeout=None):
    """Locks the file in shared mode.

    @type blocking: boolean
    @param blocking: whether to block and wait until we
        can lock the file or return immediately
    @type timeout: int or None
    @param timeout: if not None, the duration to wait for the lock
        (in blocking mode)

    """
    self._flock(fcntl.LOCK_SH, blocking, timeout,
                "Failed to lock %s in shared mode" % self.filename)

  def Unlock(self, blocking=True, timeout=None):
    """Unlocks the file.

    According to C{flock(2)}, unlocking can also be a nonblocking
    operation::

      To make a non-blocking request, include LOCK_NB with any of the above
      operations.

    @type blocking: boolean
    @param blocking: whether to block and wait until we
        can lock the file or return immediately
    @type timeout: int or None
    @param timeout: if not None, the duration to wait for the lock
        (in blocking mode)

    """
    self._flock(fcntl.LOCK_UN, blocking, timeout,
                "Failed to unlock %s" % self.filename)


text:
'use strict';

const spawnSync = require('child_process').spawnSync;

class ServerlessPlugin {
  constructor(serverless, options) {
    this.serverless = serverless;
    this.options = options;
    this.commands = {
      syncToS3: {
        usage: 'Deploys the `app` directory to your bucket',
        lifecycleEvents: [
          'sync',
        ],
      },
      domainInfo: {
        usage: 'Fetches and prints out the deployed CloudFront domain names',
        lifecycleEvents: [
          'domainInfo',
        ],
      },
    };

    this.hooks = {
      'syncToS3:sync': this.syncDirectory.bind(this),
      'domainInfo:domainInfo': this.domainInfo.bind(this),
    };
  }

  // syncs the `app` directory to the provided bucket
  syncDirectory() {
    const s3Bucket = this.serverless.variables.service.custom.s3Bucket;
    const args = [
      's3',
      'sync',
      'app/',
      `s3://${s3Bucket}/`,
    ];
    const result = spawnSync('aws', args);
    const stdout = result.stdout.toString();
    const sterr = result.stderr.toString();
    if (stdout) {
      this.serverless.cli.log(stdout);
    }
    if (sterr) {
      this.serverless.cli.log(sterr);
    }
    if (!sterr) {
      this.serverless.cli.log('Successfully synced to the S3 bucket');
    }
  }

  // fetches the domain name from the CloudFront outputs and prints it out
  domainInfo() {
    const provider = this.serverless.getProvider('aws');
    const stackName = provider.naming.getStackName(this.options.stage);
    return provider
      .request(
        'CloudFormation',
        'describeStacks',
        { StackName: stackName },
        this.options.stage,
        this.options.region // eslint-disable-line comma-dangle
      )
      .then((result) => {
        const outputs = result.Stacks[0].Outputs;
        const output = outputs.find(entry => entry.OutputKey === 'WebAppCloudFrontDistributionOutput');
        if (output.OutputValue) {
          this.serverless.cli.log(`Web App Domain: ${output.OutputValue}`);
        } else {
          this.serverless.cli.log('Web App Domain: Not Found');
        }
      });
  }
}

module.exports = ServerlessPlugin;


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package project;

import java.awt.Component;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import javax.swing.border.Border;

/**
 *
 * @author arles96
 */
public class BackgroundBorder implements Border{

    //Atributes

    private BufferedImage image = null;

    //Contructor

    public BackgroundBorder(BufferedImage image) {
        this.image = image;
    }

    // administratio methods

    @Override
    public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
        if (image!=null) {
            g.drawImage(image, 0, 0, width, height, null);
        }
    }

    @Override
    public Insets getBorderInsets(Component c) {
        return new Insets(0, 0, 0, 0);
    }

    @Override
    public boolean isBorderOpaque() {
        return false;
    }

}


text:
namespace blink {

class DedicatedWorker;
class DedicatedWorkerObjectProxy;
class FetchClientSettingsObjectSnapshot;
class WorkerOptions;
struct WorkerMainScriptLoadParameters;

// A proxy class to talk to the DedicatedWorkerGlobalScope on a worker thread
// via the DedicatedWorkerMessagingProxy from the main thread. See class
// comments on ThreadedMessagingProxyBase for the lifetime and thread affinity.
class CORE_EXPORT DedicatedWorkerMessagingProxy
    : public ThreadedMessagingProxyBase {
 public:
  DedicatedWorkerMessagingProxy(ExecutionContext*, DedicatedWorker*);
  // Exposed for testing.
  DedicatedWorkerMessagingProxy(
      ExecutionContext*,
      DedicatedWorker*,
      base::FunctionRef<std::unique_ptr<DedicatedWorkerObjectProxy>(
          DedicatedWorkerMessagingProxy*,
          DedicatedWorker*,
          ParentExecutionContextTaskRunners*)> worker_object_proxy_factory);
  DedicatedWorkerMessagingProxy(const DedicatedWorkerMessagingProxy&) = delete;
  DedicatedWorkerMessagingProxy& operator=(
      const DedicatedWorkerMessagingProxy&) = delete;
  ~DedicatedWorkerMessagingProxy() override;

  // These methods should only be used on the parent context thread.
  void StartWorkerGlobalScope(
      std::unique_ptr<GlobalScopeCreationParams>,
      std::unique_ptr<WorkerMainScriptLoadParameters>
          worker_main_script_load_params,
      const WorkerOptions*,
      const KURL& script_url,
      const FetchClientSettingsObjectSnapshot& outside_settings_object,
      const v8_inspector::V8StackTraceId&,
      const String& source_code,
      RejectCoepUnsafeNone reject_coep_unsafe_none,
      const blink::DedicatedWorkerToken& token,
      mojo::PendingRemote<mojom::blink::DedicatedWorkerHost>
          dedicated_worker_host,
      mojo::PendingRemote<mojom::blink::BackForwardCacheControllerHost>
          back_forward_cache_controller_host);
  void PostMessageToWorkerGlobalScope(BlinkTransferableMessage);

  bool HasPendingActivity() const;

  // This is called from DedicatedWorkerObjectProxy when off-the-main-thread
  // worker script fetch is enabled. Otherwise, this is called from
  // DedicatedWorker.
  void DidFailToFetchScript();

  // These methods come from worker context thread via
  // DedicatedWorkerObjectProxy and are called on the parent context thread.
  void DidEvaluateScript(bool success);
  void PostMessageToWorkerObject(BlinkTransferableMessage);
  void DispatchErrorEvent(const String& error_message,
                          std::unique_ptr<SourceLocation>,
                          int exception_id);

  // Freezes the WorkerThread. `is_in_back_forward_cache` is true only when the
  // page goes to back/forward cache.
  void Freeze(bool is_in_back_forward_cache);
  void Resume();

  DedicatedWorkerObjectProxy& WorkerObjectProxy() {
    return *worker_object_proxy_.get();
  }

  void Trace(Visitor*) const override;

 private:
  friend class DedicatedWorkerMessagingProxyForTest;

  absl::optional<WorkerBackingThreadStartupData> CreateBackingThreadStartupData(
      v8::Isolate*);

  std::unique_ptr<WorkerThread> CreateWorkerThread() override;

  std::unique_ptr<DedicatedWorkerObjectProxy> worker_object_proxy_;

  // This must be weak. The base class (i.e., ThreadedMessagingProxyBase) has a
  // strong persistent reference to itself via SelfKeepAlive (see class-level
  // comments on ThreadedMessagingProxyBase.h for details). To cut the
  // persistent reference, this worker object needs to call a cleanup function
  // in its dtor. If this is a strong reference, the dtor is never called
  // because the worker object is reachable from the persistent reference.
  WeakMember<DedicatedWorker> worker_object_;

  // Set once the initial script evaluation has been completed and it's ready
  // to dispatch events (e.g., Message events) on the worker global scope.
  bool was_script_evaluated_ = false;

  // Tasks are queued here until worker scripts are evaluated on the worker
  // global scope.
  Vector<BlinkTransferableMessage> queued_early_tasks_;

  // Passed to DedicatedWorkerThread on worker thread creation.
  mojo::PendingRemote<mojom::blink::DedicatedWorkerHost>
      pending_dedicated_worker_host_;
  mojo::PendingRemote<mojom::blink::BackForwardCacheControllerHost>
      pending_back_forward_cache_controller_host_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_DEDICATED_WORKER_MESSAGING_PROXY_H_


text:
describe('test jest localization', () => {
    test('testing localization test', () => {
        expect('localization').toEqual('localization');
    });
});


text:
Included in this repo are tools shared by weave.git and scope.git.  They include

- ```provisioning```: a set of Terraform scripts to provision virtual machines in GCP, AWS or Digital Ocean.
- ```config_management```: a set of Ansible playbooks to configure virtual machines for development, testing, etc.
- ```cover```: a tool which merges overlapping coverage reports generated by go
  test
- ```files-with-type```: a tool to search directories for files of a given
  MIME type
- ```lint```: a script to lint go, sh and hcl files; runs various tools like
  golint, go vet, errcheck, shellcheck etc
- ```rebuild-image```: a script to rebuild docker images when their input files
  change; useful when you using docker images to build your software, but you
  don't want to build the image every time.
- ```shell-lint```: a script to lint multiple shell files with
  [shellcheck](http://www.shellcheck.net/)
- ```socks```: a simple, dockerised SOCKS proxy for getting your laptop onto
  the Weave network
- ```test```: a script to run all go unit tests in subdirectories, gather the
  coverage results, and merge them into a single report.
- ```runner```: a tool for running tests in parallel; given each test is
  suffixed with the number of hosts it requires, and the hosts available are
  contained in the environment variable HOSTS, the tool will run tests in
  parallel, on different hosts.
- ```scheduler```: an appengine application that can be used to distribute
  tests across different shards in CircleCI.

## Requirements

- ```lint``` requires shfmt to lint sh files; get shfmt with
  ```go get -u gopkg.in/mvdan/sh.v1/cmd/shfmt```

## Using build-tools.git

To allow you to tie your code to a specific version of build-tools.git, such
that future changes don't break you, we recommendation that you [`git subtree`]()
this repository into your own repository:

[`git subtree`]: http://blogs.atlassian.com/2013/05/alternatives-to-git-submodule-git-subtree/

```
git subtree add --prefix tools https://github.com/weaveworks/build-tools.git master --squash
````

To update the code in build-tools.git, the process is therefore:
- PR into build-tools.git, go through normal review process etc.
- Do `git subtree pull --prefix tools https://github.com/weaveworks/build-tools.git master --squash`
  in your repo, and PR that.


text:
using Commoner.Core;
using NUnit.Framework;
using Commoner.Core.Testing;

namespace Common.Test.Unit.Core.Testing
{
    [TestFixture]
    public class DataGeneratorTests
    {
        DataGenerator _unitUnderTest = new DataGenerator();
        DataValidator _dataValidator = new DataValidator();
        const int _maxCharLength = 1000;

        [Test]
        public void GetRandomAlphaNumericString_NormalArguments_ReturnsAlphaNumericString()
        {
            string value = _unitUnderTest.GetRandomAlphaNumericString(_maxCharLength);
            Assert.IsFalse(string.IsNullOrEmpty(value));
            Assert.AreEqual(_maxCharLength, value.Length);
            Assert.IsTrue(_dataValidator.IsValidAlphaNumericString(value));
        }

        [Test]
        public void GetRandomAlphaNumericString_ZeroLength_ReturnsEmptyString()
        {
            string value = _unitUnderTest.GetRandomAlphaNumericString(0);
            Assert.AreEqual(string.Empty, value);
        }

        [Test]
        public void GetRandomAlphaString_NormalArguments_ReturnsAlphaString()
        {
            string value = _unitUnderTest.GetRandomAlphaString(_maxCharLength);
            Assert.IsFalse(string.IsNullOrEmpty(value));
            Assert.AreEqual(_maxCharLength, value.Length);
            Assert.IsTrue(_dataValidator.IsValidAlphaString(value));
        }

        [Test]
        public void GetRandomAlphaString_ZeroLength_ReturnsEmptyString()
        {
            string value = _unitUnderTest.GetRandomAlphaString(0);
            Assert.AreEqual(string.Empty, value);
        }

        [Test]
        public void GetRandomNumericString_NormalArguments_ReturnsNumericString()
        {
            string value = _unitUnderTest.GetRandomNumericString(_maxCharLength);
            Assert.IsFalse(string.IsNullOrEmpty(value));
            Assert.AreEqual(_maxCharLength, value.Length);
            Assert.IsTrue(_dataValidator.IsValidNumericString(value));
        }

        [Test]
        public void GetRandomNumericString_ZeroLength_ReturnsEmptyString()
        {
            string value = _unitUnderTest.GetRandomNumericString(0);
            Assert.AreEqual(string.Empty, value);
        }

        [Test]
        public void GetRandomInteger_NormalArguments_ReturnsInt()
        {
            int value = _unitUnderTest.GetRandomInteger(0, 0);
            Assert.AreEqual(0, value);

            value = _unitUnderTest.GetRandomInteger(5, 5);
            Assert.AreEqual(5, value);

            value = _unitUnderTest.GetRandomInteger(10, 20);
            Assert.IsTrue(value >= 10);
            Assert.IsTrue(value <= 20);
        }
    }
}


text:
<?php

namespace Oro\Bundle\TranslationBundle\Translation;

use Doctrine\ORM\AbstractQuery;
use Doctrine\ORM\EntityManager;
use Gedmo\Exception\RuntimeException;
use Gedmo\Translatable\TranslatableListener;

/**
 * A "hint" is taken into account when creating a hash key for the "query cache".
 * Ensures that the cached 'query' has a dependency on the current localization and returns the result for а
 * current localization.
 */
trait TranslatableQueryTrait
{
    /**
     * @param AbstractQuery $query
     * @param EntityManager $entityManager
     */
    private function addTranslatableLocaleHint(AbstractQuery $query, EntityManager $entityManager)
    {
        $locale = $this->getTranslatableListener($entityManager)
            ->getListenerLocale();

        $query->setHint(TranslatableListener::HINT_TRANSLATABLE_LOCALE, $locale);
    }

    /**
     * Get the currently used TranslatableListener
     *
     * @param EntityManager $entityManager
     * @return TranslatableListener
     */
    private function getTranslatableListener(EntityManager $entityManager)
    {
        $allListeners = $entityManager->getEventManager()
            ->getListeners();

        foreach ($allListeners as $eventListeners) {
            foreach ($eventListeners as $listener) {
                if ($listener instanceof TranslatableListener) {
                    return $listener;
                }
            }
        }

        throw new RuntimeException('The translation listener could not be found');
    }
}


text:
package uva.tomo9;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
import java.util.StringTokenizer;

public class Permutations {
	static BufferedReader input;

	static StringTokenizer _stk;
	static String readln() throws IOException{
		String l=input.readLine();
		if(l!=null) _stk=new StringTokenizer(l," ");
		return l;
	}

	static String next(){return _stk.nextToken();}
	static int nextInt(){return Integer.parseInt(next());}
	static long nexLong(){return Long.parseLong(next());}
	static BigInteger nextBigi(){return new BigInteger(next());}

	static PrintWriter output = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));

	public static void main(String[] args) throws IOException {
		Locale.setDefault(Locale.US);
		input=new BufferedReader(new InputStreamReader(System.in));
//		input=new BufferedReader(new FileReader("Permutations"));
		readln();

		int numCases=nextInt();

		for (int casesId = 1; casesId <= numCases; casesId++) {
			readln();
			String s=next();
			char[] array=s.toCharArray();
			Arrays.sort(array);
			StringBuilder orde=new StringBuilder();
			for (char c : array) {
				orde.append(c);
			}
			readln();
			BigInteger cual=nextBigi();
			permutacionN(orde, cual);
		}
		output.close();
//		System.out.println(fact(3));
	}

	static void permutacionN(StringBuilder s, BigInteger target){
		BigInteger tamannoIntervalo=fact(s.length()-1);
		if (target.compareTo(BigInteger.ZERO)==0) {
			output.println(s);
			return;
		}

		int limite=s.length();
		char primero=0;
		BigInteger i;
		int j;
		for (i = BigInteger.ZERO,j=0; i.compareTo(target)<=0 ; i=i.add(tamannoIntervalo),j++) {
			j=j%limite;
			primero=s.charAt(j);
		}

		BigInteger nTarget=target.subtract(i.subtract(tamannoIntervalo));
		s.replace(j-1, j, "");
//		System.out.println(primero);
		output.print(primero);
		permutacionN(s, nTarget);
	}

	static HashMap<Integer, BigInteger> hMFactoriales=new HashMap<Integer, BigInteger>();

	static{
		hMFactoriales.put( 0, BigInteger.ONE);
		hMFactoriales.put(1, BigInteger.ONE);
	}

	static BigInteger fact(Integer n) {
		BigInteger tmp=hMFactoriales.get(n);
		if(tmp!=null)
			return tmp;
		tmp=fact(n-1);
		tmp=tmp.multiply(BigInteger.valueOf(n));
		hMFactoriales.put(n, tmp);
		return tmp;
		// TODO Auto-generated method stub
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="auto" package="edu.virginia.sie.ptl.sensus" android:versionName="12.0.0" android:versionCode="71">
	<uses-sdk android:minSdkVersion="18" android:targetSdkVersion="23" />
	<application android:label="Sensus" android:icon="@drawable/ic_launcher">
		<provider android:name="android.support.v4.content.FileProvider" android:authorities="edu.virginia.sie.ptl.sensus.fileprovider" android:grantUriPermissions="true" android:exported="false">
			<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/filepaths" />
		</provider>
		<activity android:name="com.facebook.FacebookActivity" android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation" android:theme="@android:style/Theme.Translucent.NoTitleBar" android:label="@string/app_name" />
		<!-- Google Maps V2 API Key. -->
		<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyBpz8X7CKS7FXQfyyWRkrw2pVisjypB8a0" />
		<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
	</application>
	<!-- Google Maps for Android v2 requires OpenGL ES v2 -->
	<uses-feature android:glEsVersion="0x00020000" android:required="true" />
	<!-- Allow the application to access Google web-based services. -->
	<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
	<!-- Permission to receive remote notifications from Google Play Services -->
	<uses-permission android:name="edu.virginia.sie.ptl.sensus.permission.MAPS_RECEIVE" />
	<permission android:name="edu.virginia.sie.ptl.sensus.permission.MAPS_RECEIVE" android:protectionLevel="signature" />
	<uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />
	<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
	<uses-permission android:name="android.permission.INTERNET" />
	<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
	<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
	<uses-permission android:name="android.permission.READ_PHONE_STATE" />
	<uses-permission android:name="android.permission.GET_TASKS" />
	<uses-permission android:name="android.permission.RECEIVE_SMS" />
	<uses-permission android:name="android.permission.READ_SMS" />
	<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
	<uses-permission android:name="android.permission.BLUETOOTH" />
	<uses-permission android:name="android.permission.RECORD_AUDIO" />
	<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
	<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
	<uses-permission android:name="android.permission.WAKE_LOCK" />
	<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
	<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
	<uses-permission android:name="android.permission.CAMERA" />
	<uses-permission android:name="android.permission.VIBRATE" />
	<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
</manifest>


text:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace ZptSharp.Cli
{
    /// <summary>
    /// Entry-point to the CLI app process, hosting the <c>static void Main</c> method.
    /// This uses .NET Generic Host to wire up and run an instance of <see cref="Application" />.
    /// </summary>
    public static class Program
    {
        /// <summary>
        /// Serves as the entry point to the application process.
        /// </summary>
        /// <param name="args">The command-line arguments.</param>
        public static void Main(string[] args) => GetHostBuilder(args).Build().Run();

        /// <summary>
        /// Gets a .NET Generic Host <see cref="IHostBuilder" /> for the app.
        /// </summary>
        /// <param name="args">The command-line arguments.</param>
        /// <returns>A host builder, from which the app may be started.</returns>
        public static IHostBuilder GetHostBuilder(string[] args)
        {
            var cliArgs = GetCliArguments(args);

            return Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) => {
                    services
                        .AddSingleton(cliArgs)
                        .AddTransient<IGetsBulkRenderingRequest, BulkRenderingRequestFactory>()
                        .AddTransient<ILoadsModel, ModelLoader>();

                    var builder = services.AddZptSharp();
                    var configurator = new ServiceConfigurator(builder);
                    configurator.ConfigureServices(cliArgs);

                    services.AddHostedService<Application>();
                });
        }

        static CliArguments GetCliArguments(string[] args) => CliArgumentsParser.Parse(args);
    }
}


text:
package dirconfig

// A DirConfig defines the manner in which a particular directory should be cleaned
type DirConfig interface {
	CleanDir() error
	GetDir() string
}


text:
using namespace std;

class Usuario;

class Numero
{
    public:

        enum Razon {LONGITUD, DIGITOS, NO_VALIDO};

	struct EsDigito
        {
            bool operator()(char c) const {return isdigit(c);}
            typedef char argument_type;
        };

        struct EsBlanco
        {
            bool operator()(char c) const {return isspace(c);}
	    typedef char argument_type;
        };

        class Incorrecto
        {
            public:
                Incorrecto(Razon r):razon_(r) {}
                Razon razon() const {return razon_;}

            private:
                Razon razon_;
        };

        Numero(const Cadena& no);

	Numero();

        operator const char*() const {return num_.c_str();};

        friend bool operator <(const Numero& n1, const Numero& n2);

    private:

        Cadena num_;
};

class Tarjeta
{
    public:

        class Caducada
        {
            public:
                Caducada(const Fecha& f):fech(f) {}
                Fecha cuando() const {return fech;}

            private:
                Fecha fech;
        };

        Tarjeta(const Numero& n, Usuario& usu, const Fecha& fech);

        Numero numero() const {return numero_;}
        Fecha caducidad() const {return caducidad_;};
        Cadena titular_facial() const {return titular_facial_;};
        const Usuario* titular() const {return titular_;};

        void anula_titular() {titular_ = 0;};

	friend ostream& operator <<(ostream& os, const Tarjeta& t);

        ~Tarjeta();

    private:

        Numero numero_;
        const Usuario* titular_;
        Fecha caducidad_;
        Cadena titular_facial_;

        Tarjeta(const Tarjeta& t);
        Tarjeta& operator =(const Tarjeta& t);
};

bool operator <(const Tarjeta& t1, const Tarjeta& t2);

#endif


text:
package bnw.abm.intg.geo;

import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.DataUtilities;
import org.geotools.data.FeatureSource;
import org.geotools.data.Query;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.feature.FeatureCollection;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.filter.Filter;
import org.opengis.filter.FilterFactory2;
import org.opengis.referencing.crs.CoordinateReferenceSystem;

import bnw.abm.intg.filemanager.zip.Zip;

/**
 * @author Bhagya N. Wickramasinghe
 *
 */
public class ShapefileGeoFeatureReader extends GeoFeatureReader {
	private static DataStore dataStore;

	public ShapefileGeoFeatureReader() {
	}

	public void loadFeatures(Path input) throws IOException {

		FeatureSource<SimpleFeatureType, SimpleFeature> source = this.getFeatureSource(input);
		Filter filter = Filter.INCLUDE; // ECQL.toFilter("BBOX(THE_GEOM,
		// 10,20,30,40)")

		this.featureCollection = source.getFeatures(filter);

	}

	// public void loadFeatures(List<Path> inputs) throws IOException {
	//
	// Map<String, Object> map = new HashMap<String, Object>();
	// DefaultFeatureCollection dfc = new DefaultFeatureCollection();
	// for (Path inPath : inputs) {
	// FeatureSource<SimpleFeatureType, SimpleFeature> source =
	// this.getFeatureSource(inPath);
	// Filter filter = Filter.INCLUDE;
	// FeatureCollection<SimpleFeatureType, SimpleFeature> collection =
	// source.getFeatures(filter);
	// dfc.addAll(collection);
	// }
	//
	// this.featureCollection = dfc;
	//
	// }

	public void loadFeaturesByProperty(Path target, String property, String[] propertyValues) throws IOException {

		FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = this.getFeatureSource(target);

		FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2();

		List<Filter> match = new ArrayList<>();
		if (property.equals("") || propertyValues.length == 0) {
			match.add(Filter.INCLUDE);
		} else {
			for (String name : propertyValues) {
				Filter aMatch = ff.equals(ff.property(property), ff.literal(name));
				match.add(aMatch);
			}
		}
		Filter filter = ff.or(match);
		FeatureCollection<SimpleFeatureType, SimpleFeature> tempFeatureCollection = featureSource.getFeatures(filter);
		this.featureCollection = DataUtilities.collection(tempFeatureCollection);
		featureSource.getDataStore().dispose();
	}

	/**
	 * Load features from a shapefile and filters the properties based on a
	 * property and its values. Multiple property values are handled like in a
	 * logical OR operation
	 *
	 * @param target
	 *            File path to shapefile
	 * @param property
	 *            Name of the property in shape file
	 * @param propertyValues
	 *            Values of the property
	 * @param crs
	 *            target coordinate reference system
	 * @throws IOException
	 */
	public void loadFeaturesByProperty(Path target, String property, String[] propertyValues,
			CoordinateReferenceSystem crs) throws IOException {

		FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = this.getFeatureSource(target);

		FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2();
		List<Filter> match = new ArrayList<>();
		if (property.equals("") || propertyValues.length == 0) {
			match.add(Filter.INCLUDE);
		} else {
			for (String name : propertyValues) {
				Filter aMatch = ff.equals(ff.property(property), ff.literal(name));
				match.add(aMatch);
			}
		}
		Filter filter = ff.or(match);
		Query query = new Query(property, filter);
		// query.setCoordinateSystem(crs);
		query.setCoordinateSystemReproject(crs);

		FeatureCollection features = featureSource.getFeatures(query);
		this.featureCollection = features;
	}

	public void loadFeatures(Path target, Filter filter) throws IOException {

		FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = this.getFeatureSource(target);

		this.featureCollection = featureSource.getFeatures(filter);

	}

	public FeatureSource<SimpleFeatureType, SimpleFeature> getFeatureSource(Path target) throws IOException {
		if (target.toString().endsWith(".zip")) {
			List<Path> shapes = Zip.findFiles(target, "*.shp");
			target = shapes.get(0);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("url", target.toUri().toURL());
		if (dataStore != null) {
			dataStore.dispose();
		}
		dataStore = DataStoreFinder.getDataStore(map);
		String typeName = dataStore.getTypeNames()[0];
		FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = dataStore.getFeatureSource(typeName);
		return featureSource;
	}

	public void close() {
		dataStore.dispose();
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 1.7.0//EN" "http://google-web-toolkit.googlecode.com/svn/tags/1.7.0/distro-source/core/src/gwt-module.dtd">
<module>
	<inherits name="com.vaadin.DefaultWidgetSet" />

    <!--
     Uncomment the following to compile the widgetset for one browser only.
     This can reduce the GWT compilation time significantly when debugging.
     The line should be commented out before deployment to production
     environments.

     Multiple browsers can be specified for GWT 1.7 as a comma separated
     list. The supported user agents at the moment of writing were:
     ie6,ie8,gecko,gecko1_8,safari,opera

     The value gecko1_8 is used for Firefox 3 and later and safari is used for
     webkit based browsers including Google Chrome.
    -->
    <!--
    <set-property name="user.agent" value="safari"/>
       -->

    <!--
     To enable SuperDevMode, uncomment this line.

     SuperDevMode enables debugging of the client side of a Vaadin
     application using the JavaScript debugger of a browser. Java code is
     shown and debugging can take place on the Java level when using a browser
     that support source maps (currently Chrome, implementation under work
     for Firefox).

     After uncommenting this property, compile the widgetset once and then
     start the SuperDevMode server process in parallel with your normal
     server. Then add the command line parameter ?superdevmode to your
     application URL. Vaadin Eclipse plug-in can create a launch for the
     SuperDevMode server (Project Properties... -> Vaadin).

     See https://vaadin.com/wiki/-/wiki/Main/Using%20SuperDevMode for more
     information and instructions.
    -->
    <!--
	<set-configuration-property name="devModeRedirectEnabled" value="true" />
	-->
</module>


text:
import PropTypes from 'prop-types';
import React from 'react';
import Box from 'grommet/components/Box';
import Image from 'grommet/components/Image';
import Markdown from 'grommet/components/Markdown';

export default function BlockImagePreview ({ content, image, imageDesc }) {
  return (
    <Box colorIndex="light-1" direction="row" pad={{ between: 'medium' }}>
      <Box>
        <Image src={image.path} />
        {imageDesc}
      </Box>
      <Box>
        <Markdown content={content} components={{
          'p': { 'props': { 'margin': 'none' } }
        }}/>
      </Box>
    </Box>
  );
}

BlockImagePreview.propTypes = {
  content: PropTypes.string,
  image: PropTypes.string
};