text:
  /**
   *  Metrics class for CartoDB
   *
   *  - Track user events in CartoDB.
   *  - When an event is launched, you can use our God to
   *  save the action (cdb.god.trigger('metrics', '{{ metric_name }}', { email: {{ email }}, data: {{ data }} });).
   *
   *  new cdb.admin.Metrics();
   */

  cdb.admin.Metrics = cdb.core.Model.extend({

    initialize: function(opts) {
      this.bindEvents();
    },

    bindEvents: function() {
      cdb.god.bind("metrics", this._setTrack, this);
    },

    _setTrack: function(name, obj) {

      // HubSpot tracking
      if (window.hubspot_token) {
        window._hsq = window._hsq || [];
        window._hsq.push(['identify', {
          email: obj.email
        }]);

        var event_id;

        switch(name) {
          case 'published_visualization':
            event_id = window.hubspot_ids.published_visualization
            break;
          case 'visited_dashboard':
            event_id = window.hubspot_ids.visited_dashboard
            break;
          case 'connect_dataset':
            event_id = window.hubspot_ids.connect_dataset
            break;
          case 'create_map':
            event_id = window.hubspot_ids.create_map
            break;
          case 'export_table':
            event_id = window.hubspot_ids.export_table
            break;
          case 'select_wms':
            event_id = window.hubspot_ids.select_wms
            break;
          case 'color_basemap':
            event_id = window.hubspot_ids.color_basemap
            break;
          case 'pattern_basemap':
            event_id = window.hubspot_ids.pattern_basemap
            break;
          case 'geocoding':
            event_id = window.hubspot_ids.geocoding
            break;
          case 'visual_merge':
            event_id = window.hubspot_ids.visual_merge
            break;
          case 'common_data':
            event_id = window.hubspot_ids.common_data
            break;
          case 'cartocss_manually':
            event_id = window.hubspot_ids.cartocss_manually
            break;
          case 'wizard':
            event_id = window.hubspot_ids.wizard
            break;
          case 'filter':
            event_id = window.hubspot_ids.filter
            break;
          case 'query':
            event_id = window.hubspot_ids.query
            break;
          case 'logged_in':
            event_id = window.hubspot_ids.logged_in
            break;
          case 'visited_dashboard_first_time':
            event_id = window.hubspot_ids.visited_dashboard_first_time
            break;
          case 'applied_pecan':
            event_id = window.hubspot_ids.applied_pecan
            break;
          case 'open_pecan_list':
            event_id = window.hubspot_ids.open_pecan_list
            break;

        }

        window._hsq.push(['trackEvent', {
          id: event_id
        }]);
      }

    }

  });


text:
package ospatch

import (
	"fmt"
	"regexp"
)

// Exclude represents package exclude entry by a user
type Exclude struct {
	isRegexp     bool
	regex        *regexp.Regexp
	strictString *string
}

func (exclude Exclude) String() string {
	return fmt.Sprintf("{isRegexp: %t, regex: %+v, strictString: %s}", exclude.isRegexp, exclude.regex, *exclude.strictString)
}

// CreateRegexExclude returns new Exclude struct that represents exclusion with regex
func CreateRegexExclude(regex *regexp.Regexp) *Exclude {
	return &Exclude{
		isRegexp: true,
		regex:    regex,
	}
}

// CreateStringExclude returns new Exclude struct that represents exclusion with string
func CreateStringExclude(strictString *string) *Exclude {
	strictStringCopied := *strictString //copy the string for safety reason
	return &Exclude{
		isRegexp:     false,
		strictString: &strictStringCopied,
	}
}

// MatchesName returns if a package with a certain name matches Exclude struct and should be excluded
func (exclude *Exclude) MatchesName(name *string) bool {
	if exclude.isRegexp {
		return exclude.regex.MatchString(*name)
	}
	return *exclude.strictString == *name
}

redpajama_set_name: RedPajamaGithub


text:
namespace renderer  { class Assembly; }
namespace renderer  { class AssemblyInstance; }
namespace renderer  { class Intersector; }
namespace renderer  { class Light; }
namespace renderer  { class Material; }
namespace renderer  { class MaterialArray; }
namespace renderer  { class ObjectInstance; }
namespace renderer  { class ParamArray; }
namespace renderer  { class Scene; }
#ifdef APPLESEED_WITH_OSL
namespace renderer  { class ShaderGroup; }
#endif
namespace renderer  { class ShadingPoint; }

namespace renderer
{

//
// Non-physical light.
//

class NonPhysicalLightInfo
{
  public:
    TransformSequence           m_transform_sequence;           // assembly instance (parent of the light) space to world space
    const Light*                m_light;
};

//
// Light-emitting triangle.
//

class EmittingTriangle
{
  public:
    const AssemblyInstance*     m_assembly_instance;
    size_t                      m_object_instance_index;
    size_t                      m_region_index;
    size_t                      m_triangle_index;
    foundation::Vector3d        m_v0, m_v1, m_v2;               // world space vertices of the triangle
    foundation::Vector3d        m_n0, m_n1, m_n2;               // world space vertex normals
    foundation::Vector3d        m_geometric_normal;             // world space geometric normal, unit-length
    TriangleSupportPlaneType    m_triangle_support_plane;       // support plane of the triangle in assembly space
    double                      m_rcp_area;                     // world space triangle area reciprocal
    double                      m_triangle_prob;                // probability density of this triangle
    const Material*             m_material;
};

//
// A key to uniquely identify a light-emitting triangle in a hash table.
//

class EmittingTriangleKey
{
  public:
    foundation::UniqueID            m_assembly_instance_uid;
    foundation::uint32              m_object_instance_index;
    foundation::uint32              m_region_index;
    foundation::uint32              m_triangle_index;

    EmittingTriangleKey();
    EmittingTriangleKey(
        const foundation::UniqueID  assembly_instance_uid,
        const size_t                object_instance_index,
        const size_t                region_index,
        const size_t                triangle_index);

    bool operator==(const EmittingTriangleKey& rhs) const;
};

//
// A hash table of light-emitting triangles.
//

struct EmittingTriangleKeyHasher
{
    size_t operator()(const EmittingTriangleKey& key) const;
};

typedef foundation::HashTable<
    EmittingTriangleKey,
    EmittingTriangleKeyHasher,
    const EmittingTriangle*
> EmittingTriangleHashTable;

//
// Light sample: the result of sampling the sets of non-physical lights and light-emitting triangles.
//

class LightSample
{
  public:
    // Data for a light-emitting triangle sample.
    const EmittingTriangle*     m_triangle;
    foundation::Vector2d        m_bary;                         // barycentric coordinates of the sample
    foundation::Vector3d        m_point;                        // world space position of the sample
    foundation::Vector3d        m_shading_normal;               // world space shading normal at the sample, unit-length
    foundation::Vector3d        m_geometric_normal;             // world space geometric normal at the sample, unit-length

    // Data for a non-physical light sample.
    const Light*                m_light;
    foundation::Transformd      m_light_transform;              // light space to world space transform

    // Data common to all sample types.
    double                      m_probability;                  // probability density of this sample

    // Construct a shading point out of this light sample and a given direction.
    void make_shading_point(
        ShadingPoint&                   shading_point,
        const foundation::Vector3d&     direction,
        const Intersector&              intersector) const;
};

//
// The light sampler collects all the light-emitting entities (non-physical lights, mesh lights)
// and allows to sample them.
//

class LightSampler
  : public foundation::NonCopyable
{
  public:
    // Constructor.
    LightSampler(
        const Scene&                        scene,
        const ParamArray&                   params = ParamArray());

    // Return the number of non-physical lights in the scene.
    size_t get_non_physical_light_count() const;

    // Return the number of emitting triangles in the scene.
    size_t get_emitting_triangle_count() const;

    // Return true if the scene contains at least one light or emitting triangle.
    bool has_lights_or_emitting_triangles() const;

    // Sample the set of non-physical lights.
    void sample_non_physical_lights(
        const ShadingRay::Time&             time,
        const foundation::Vector3d&         s,
        LightSample&                        light_sample) const;

    // Sample a single given non-physical light.
    void sample_non_physical_light(
        const ShadingRay::Time&             time,
        const foundation::Vector2d&         s,
        const size_t                        light_index,
        LightSample&                        light_sample) const;

    // Sample the set of emitting triangles.
    void sample_emitting_triangles(
        const ShadingRay::Time&             time,
        const foundation::Vector3d&         s,
        LightSample&                        light_sample) const;

    // Sample the sets of non-physical lights and emitting triangles.
    void sample(
        const ShadingRay::Time&             time,
        const foundation::Vector3d&         s,
        LightSample&                        light_sample) const;

    // Compute the probability density in area measure of a given light sample.
    double evaluate_pdf(const ShadingPoint& shading_point) const;

  private:
    struct Parameters
    {
        const bool m_importance_sampling;

        explicit Parameters(const ParamArray& params);
    };

    typedef std::vector<NonPhysicalLightInfo> NonPhysicalLightVector;
    typedef std::vector<EmittingTriangle> EmittingTriangleVector;
    typedef foundation::CDF<size_t, double> EmitterCDF;

    const Parameters            m_params;

    NonPhysicalLightVector      m_non_physical_lights;
    size_t                      m_non_physical_light_count;

    EmittingTriangleVector      m_emitting_triangles;

    EmitterCDF                  m_non_physical_lights_cdf;
    EmitterCDF                  m_emitting_triangles_cdf;

    EmittingTriangleKeyHasher   m_triangle_key_hasher;
    EmittingTriangleHashTable   m_emitting_triangle_hash_table;

    // Recursively collect non-physical lights from a given set of assembly instances.
    void collect_non_physical_lights(
        const AssemblyInstanceContainer&    assembly_instances,
        const TransformSequence&            parent_transform_seq);

    // Collect non-physical lights from a given assembly.
    void collect_non_physical_lights(
        const Assembly&                     assembly,
        const TransformSequence&            transform_sequence);

    // Recursively collect emitting triangles from a given set of assembly instances.
    void collect_emitting_triangles(
        const AssemblyInstanceContainer&    assembly_instances,
        const TransformSequence&            parent_transform_seq);

    // Collect emitting triangles from a given assembly.
    void collect_emitting_triangles(
        const Assembly&                     assembly,
        const AssemblyInstance&             assembly_instance,
        const TransformSequence&            transform_sequence);

    // Build a hash table that allows to find the emitting triangle at a given shading point.
    void build_emitting_triangle_hash_table();

    // Sample a given non-physical light.
    void sample_non_physical_light(
        const ShadingRay::Time&             time,
        const foundation::Vector2d&         s,
        const size_t                        light_index,
        const double                        light_prob,
        LightSample&                        sample) const;

    // Sample a given emitting triangle.
    void sample_emitting_triangle(
        const ShadingRay::Time&             time,
        const foundation::Vector2d&         s,
        const size_t                        triangle_index,
        const double                        triangle_prob,
        LightSample&                        sample) const;

#ifdef APPLESEED_WITH_OSL
    void store_object_area_in_shadergroups(
        const AssemblyInstance*             assembly_instance,
        const ObjectInstance*               object_instance,
        const double                        object_area,
        const MaterialArray&                materials);
#endif
};

//
// EmittingTriangleKey class implementation.
//

inline EmittingTriangleKey::EmittingTriangleKey()
{
}

inline EmittingTriangleKey::EmittingTriangleKey(
    const foundation::UniqueID              assembly_instance_uid,
    const size_t                            object_instance_index,
    const size_t                            region_index,
    const size_t                            triangle_index)
  : m_assembly_instance_uid(static_cast<foundation::uint32>(assembly_instance_uid))
  , m_object_instance_index(static_cast<foundation::uint32>(object_instance_index))
  , m_region_index(static_cast<foundation::uint32>(region_index))
  , m_triangle_index(static_cast<foundation::uint32>(triangle_index))
{
}

inline bool EmittingTriangleKey::operator==(const EmittingTriangleKey& rhs) const
{
    return
        m_triangle_index == rhs.m_triangle_index &&
        m_object_instance_index == rhs.m_object_instance_index &&
        m_assembly_instance_uid == rhs.m_assembly_instance_uid &&
        m_region_index == rhs.m_region_index;
}

//
// EmittingTriangleKeyHasher class implementation.
//

inline size_t EmittingTriangleKeyHasher::operator()(const EmittingTriangleKey& key) const
{
    return
        foundation::mix_uint32(
            static_cast<foundation::uint32>(key.m_assembly_instance_uid),
            key.m_object_instance_index,
            key.m_region_index,
            key.m_triangle_index);
}

//
// LightSampler class implementation.
//

inline size_t LightSampler::get_non_physical_light_count() const
{
    return m_non_physical_light_count;
}

inline size_t LightSampler::get_emitting_triangle_count() const
{
    return m_emitting_triangles.size();
}

inline bool LightSampler::has_lights_or_emitting_triangles() const
{
    return m_non_physical_lights_cdf.valid() || m_emitting_triangles_cdf.valid();
}

inline void LightSampler::sample_non_physical_light(
    const ShadingRay::Time&                 time,
    const foundation::Vector2d&             s,
    const size_t                            light_index,
    LightSample&                            sample) const
{
    sample_non_physical_light(time, s, light_index, 1.0, sample);
}

}       // namespace renderer

#endif  // !APPLESEED_RENDERER_KERNEL_LIGHTING_LIGHTSAMPLER_H


text:
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

//
// Scenario4_lanid.xaml.h
// Declaration of the LanId class
//

#pragma once

#include "pch.h"
#include "Scenario4_lanid.g.h"
#include "MainPage.xaml.h"

using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::System;
using namespace Windows::Foundation;
using namespace Platform;
using namespace Windows::Networking;
using namespace Windows::Networking::Connectivity;

namespace SDKSample
{
    namespace NetworkInformationApi
    {
        /// <summary>
        /// An empty page that can be used on its own or navigated to within a Frame.
        /// </summary>
        [Windows::Foundation::Metadata::WebHostHidden]
        public ref class LanId sealed
        {
        public:
            LanId();

        protected:
            virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
        private:
            MainPage^ rootPage;
            void LanId_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
            String^ lanIdInfo;
            void DisplayLanIdentifierData(LanIdentifier^ lanIdentifier);
        };
    }
}


text:
package org.apache.flink.cep;

import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.typeutils.TypeExtractor;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.transformations.SourceTransformation;
import org.apache.flink.util.Collector;
import org.apache.flink.util.TestLogger;

import org.junit.Ignore;
import org.junit.Test;

import java.util.List;
import java.util.Map;

import static org.junit.Assert.assertEquals;

/**
 * Tests for lambda support in CEP.
 */
public class CEPLambdaTest extends TestLogger {
	/**
	 * Test event class.
	 */
	public static class EventA {}

	/**
	 * Test event class.
	 */
	public static class EventB {}

	/**
	 * Tests that a Java8 lambda can be passed as a CEP select function.
	 */
	@Test
	@Ignore
	public void testLambdaSelectFunction() {
		TypeInformation<EventA> eventTypeInformation = TypeExtractor.getForClass(EventA.class);
		TypeInformation<EventB> outputTypeInformation = TypeExtractor.getForClass(EventB.class);

		DataStream<EventA> inputStream = new DataStream<>(
			StreamExecutionEnvironment.getExecutionEnvironment(),
			new SourceTransformation<>(
				"source",
				null,
				eventTypeInformation,
				1));

		Pattern<EventA, ?> dummyPattern = Pattern.begin("start");

		PatternStream<EventA> patternStream = new PatternStream<>(inputStream, dummyPattern);

		DataStream<EventB> result = patternStream.select(
				(Map<String, List<EventA>> map) -> new EventB()
		);

		assertEquals(outputTypeInformation, result.getType());
	}

	/**
	 * Tests that a Java8 lambda can be passed as a CEP flat select function.
	 */
	@Test
	@Ignore
	public void testLambdaFlatSelectFunction() {
		TypeInformation<EventA> eventTypeInformation = TypeExtractor.getForClass(EventA.class);
		TypeInformation<EventB> outputTypeInformation = TypeExtractor.getForClass(EventB.class);

		DataStream<EventA> inputStream = new DataStream<>(
			StreamExecutionEnvironment.getExecutionEnvironment(),
			new SourceTransformation<>(
				"source",
				null,
				eventTypeInformation,
				1));

		Pattern<EventA, ?> dummyPattern = Pattern.begin("start");

		PatternStream<EventA> patternStream = new PatternStream<>(inputStream, dummyPattern);

		DataStream<EventB> result = patternStream.flatSelect(
			(Map<String, List<EventA>> map, Collector<EventB> collector) -> collector.collect(new EventB())
		);

		assertEquals(outputTypeInformation, result.getType());
	}
}


text:
//
//  $Id: PGPostgresConnection.m 3848 2012-09-12 12:19:31Z stuart02 $
//
//  PGPostgresConnection.m
//  PostgresKit
//
//  Copyright (c) 2008-2009 David Thorpe, djt@mutablelogic.com
//
//  Forked by the Sequel Pro Team on July 22, 2012.
//
//  Licensed under the Apache License, Version 2.0 (the "License"); you may not
//  use this file except in compliance with the License. You may obtain a copy of
//  the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
//  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
//  License for the specific language governing permissions and limitations under
//  the License.

#import "PGPostgresConnection.h"
#import "PGPostgresConnectionParameters.h"
#import "PGPostgresConnectionTypeHandling.h"
#import "PGPostgresKitPrivateAPI.h"
#import "PGPostgresTypeHandlerProtocol.h"
#import "PGPostgresTypeNumberHandler.h"
#import "PGPostgresTypeStringHandler.h"
#import "PGPostgresException.h"
#import "PGPostgresStatement.h"
#import "PGPostgresResult.h"

#import <pthread.h>
#import <poll.h>

@interface PGPostgresConnection ()

- (void)_loadDatabaseParameters;
- (void)_createConnectionParameters;
- (void)_pollConnection:(NSNumber *)isReset;

// libpq callback
static void _PGPostgresConnectionNoticeProcessor(void *arg, const char *message);

@end

@implementation PGPostgresConnection

@synthesize port = _port;
@synthesize host = _host;
@synthesize user = _user;
@synthesize database = _database;
@synthesize password = _password;
@synthesize useSocket = _useSocket;
@synthesize socketPath = _socketPath;
@synthesize delegate = _delegate;
@synthesize timeout = _timeout;
@synthesize useKeepAlive = _useKeepAlive;
@synthesize keepAliveInterval = _keepAliveInterval;
@synthesize lastQueryWasCancelled = _lastQueryWasCancelled;
@synthesize lastError = _lastError;
@synthesize encoding = _encoding;
@synthesize connectionError = _connectionError;
@synthesize stringEncoding = _stringEncoding;
@synthesize parameters = _parameters;
@synthesize applicationName = _applicationName;
@synthesize lastQueryAffectedRowCount = _lastQueryAffectedRowCount;

#pragma mark -
#pragma mark Initialisation

- (id)init
{
	return [self initWithDelegate:nil];
}

/**
 * Initialise a new connection with the supplied delegate.
 *
 * @param delegate The delegate this connection should use.
 *
 * @return The new connection instance.
 */
- (id)initWithDelegate:(NSObject <PGPostgresConnectionDelegate> *)delegate
{
	if ((self = [super init])) {

		_delegate = delegate;

		_port = PGPostgresConnectionDefaultServerPort;
		_timeout = PGPostgresConnectionDefaultTimeout;

		_useKeepAlive = YES;
		_keepAliveInterval = PGPostgresConnectionDefaultKeepAlive;

		_lastQueryAffectedRowCount = 0;

		_lastError = nil;
		_connection = nil;
		_connectionError = nil;
		_lastQueryWasCancelled = NO;

		_stringEncoding = PGPostgresConnectionDefaultStringEncoding;
		_encoding = [NSString stringWithString:PGPostgresConnectionDefaultEncoding];

		_delegateSupportsWillExecute = [_delegate respondsToSelector:@selector(connection:willExecute:withValues:)];

		_typeMap = [[NSMutableDictionary alloc] init];

		[self registerTypeHandlers];
	}

	return self;
}

#pragma mark -
#pragma mark Accessors

/**
 * Get the underlying connection associated with this wrapper.
 *
 * @return The PGConn instance.
 */
- (PGconn *)postgresConnection
{
	return _connection;
}

#pragma mark -
#pragma mark Connection Handling

/**
 * Does this connection have an underlying connection established with the server.
 *
 * @return A BOOL indicating the result of the query.
 */
- (BOOL)isConnected
{
	if (!_connection) return NO;

	return PQstatus(_connection) == CONNECTION_OK;
}

/**
 * Attempts to disconnect the underlying connection with the server.
 */
- (void)disconnect
{
	if (!_connection) return;

	[self cancelCurrentQuery:nil];

	PQfinish(_connection);

	_connection = nil;

	if (_delegate && [_delegate respondsToSelector:@selector(connectionDisconnected:)]) {
		[_delegate connectionDisconnected:self];
	}
}

/**
 * Initiates the underlying connection to the server asynchronously.
 *
 * Note, that if no user, host or database is set when connect is called, then libpq's defaults are used.
 * For no host, this means a socket connection to /tmp is attempted.
 *
 * @return A BOOL indicating the success of requesting the connection. Note, that this does not indicate
 *         that a successful connection has been made, only that it has successfullly been requested.
 */
- (BOOL)connect
{
	if ([self isConnected]) return YES;

	[self _createConnectionParameters];

	// Perform the connection
	_connection = PQconnectStartParams(_connectionParamNames, _connectionParamValues, 0);

	if (!_connection || PQstatus(_connection) == CONNECTION_BAD) {

		if (_connectionError) [_connectionError release];

		_connectionError = [[NSString alloc] initWithUTF8String:PQerrorMessage(_connection)];

		PQfinish(_connection);

		_connection = nil;

		return NO;
	}

	[self performSelectorInBackground:@selector(_pollConnection:) withObject:nil];

	return YES;
}

/**
 * Attempts the reset the underlying connection.
 *
 * @note A return value of NO means that the connection is not currently
 *       connected or the request to reset it failed. YES means the reset request was successful,
 *       not that the connection re-establishment has succeeded. Wait for the
 *       delegate connection reset method to be called and check -isConnected.
 *
 * @return A BOOL indicating the success of the call.
 */
- (BOOL)reset
{
	if (![self isConnected]) return NO;

	if (!PQresetStart(_connection)) return NO;

	[self performSelectorInBackground:@selector(_pollConnection:) withObject:[NSNumber numberWithBool:YES]];

	return YES;
}

/**
 * Returns the PostgreSQL client library (libpq) version being used.
 *
 * @return The library version (e.g. version 9.1 is 90100).
 */
- (NSUInteger)clientVersion
{
	return PQlibVersion();
}

/**
 * Returns the version of the server we're connected to.
 *
 * @return The server version (e.g. version 9.1 is 90100). -1 is returned if there's no connection.
 */
- (NSUInteger)serverVersion
{
	if (![self isConnected]) return -1;

	return PQserverVersion(_connection);
}

/**
 * Returns the ID of the process handling this connection on the remote host.
 *
 * @return The process ID or -1 if no connection is available.
 */
- (NSUInteger)serverProcessId
{
	if (![self isConnected]) return -1;

	return PQbackendPID(_connection);
}

/**
 * Attempts to cancel the query currently executing on this connection.
 *
 * @param error Populated if query was unabled to be cancelled.
 *
 * @return A BOOL indicating the success of the request
 */
- (BOOL)cancelCurrentQuery:(NSError **)error
{
	if (![self isConnected]) return NO;

	PGcancel *cancel = PQgetCancel(_connection);

	if (!cancel) return NO;

	char errorBuf[256];

	int result = PQcancel(cancel, errorBuf, 256);

	PQfreeCancel(cancel);

	if (!result) {
		if (error != NULL) {
			*error = [NSError errorWithDomain:PGPostgresConnectionErrorDomain
										 code:0
									 userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithUTF8String:errorBuf] forKey:NSLocalizedDescriptionKey]];
		}

		return NO;
	}

	_lastQueryWasCancelled = YES;

	return YES;
}

#pragma mark -
#pragma mark Private API

/**
 * Polls the connection that was previously requested via -connect and waits for meaninful status.
 *
 * @note This method should be called on a background thread as it will block waiting for the connection.
 */
- (void)_pollConnection:(NSNumber *)isReset
{
	@autoreleasepool {
		BOOL reset = isReset && [isReset boolValue];

		int sock = PQsocket(_connection);

		if (sock == -1) {
			[pool release];
			return;
		}

		struct pollfd fdinfo[1];

		fdinfo[0].fd = sock;
		fdinfo[0].events = POLLIN|POLLOUT;

		PostgresPollingStatusType status;

		do
		{
			status = reset ? PQresetPoll(_connection) : PQconnectPoll(_connection);

			if (status == PGRES_POLLING_READING || status == PGRES_POLLING_WRITING) {
				if (poll(fdinfo, 1, -1) < 0) break;
			}
		}
		while (status != PGRES_POLLING_OK && status != PGRES_POLLING_FAILED);

		if (status == PGRES_POLLING_OK && [self isConnected]) {

			// Increase error verbosity
			PQsetErrorVerbosity(_connection, PQERRORS_VERBOSE);

			// Set notice processor
			PQsetNoticeProcessor(_connection, _PGPostgresConnectionNoticeProcessor, self);

			// Register or clear type extensions
			NSInteger success = reset ? PQclearTypes(_connection) : PQinitTypes(_connection);

			if (!success) {
				NSLog(@"PostgresKit: Error: Failed to initialise or clear type extensions. Connection might return unexpected results!");
			}

			[self _loadDatabaseParameters];

			if (reset) {
				if (_delegate && [_delegate respondsToSelector:@selector(connectionReset:)]) {
					[_delegate performSelectorOnMainThread:@selector(connectionReset:) withObject:self waitUntilDone:NO];
				}
			}
			else {
				if (_delegate && [_delegate respondsToSelector:@selector(connectionEstablished:)]) {
					[_delegate performSelectorOnMainThread:@selector(connectionEstablished:) withObject:self waitUntilDone:NO];
				}
			}
		}
	}
}

/**
 * Loads the database parameters.
 */
- (void)_loadDatabaseParameters
{
	if (_parameters) [_parameters release];

	_parameters = [[PGPostgresConnectionParameters alloc] initWithConnection:self];

	BOOL success = [_parameters loadParameters];

	if (!success) NSLog(@"PostgresKit: Warning: Failed to load database parameters.");
}

/**
 * libpq notice processor function. Simply passes the message onto the connection delegate.
 *
 * @param arg     The calling connection.
 * @param message The message that was sent.
 */
static void _PGPostgresConnectionNoticeProcessor(void *arg, const char *message)
{
	PGPostgresConnection *connection = (PGPostgresConnection *)arg;

	if ([connection isKindOfClass:[PGPostgresConnection class]]) {

		if ([connection delegate] && [[connection delegate] respondsToSelector:@selector(connection:notice:)]) {
			[[connection delegate] connection:connection notice:[NSString stringWithUTF8String:message]];
		}
	}
}

/**
 * Creates the parameter arrays required to establish a connection.
 */
- (void)_createConnectionParameters
{
	BOOL hasUser = NO;
	BOOL hasHost = NO;
	BOOL hasPassword = NO;
	BOOL hasDatabase = NO;

	if (_connectionParamNames) free(_connectionParamNames);
	if (_connectionParamValues) free(_connectionParamValues);

	int paramCount = 5;

	if (_user && [_user length]) paramCount++, hasUser = YES;
	if (_host && [_host length]) paramCount++, hasHost = YES;
	if (_password && [_password length]) paramCount++, hasPassword = YES;
	if (_database && [_database length]) paramCount++, hasDatabase = YES;

	_connectionParamNames = malloc(paramCount * sizeof(*_connectionParamNames));
	_connectionParamValues = malloc(paramCount * sizeof(*_connectionParamValues));

	_connectionParamNames[0] = PGPostgresApplicationParam;
	_connectionParamValues[0] = !_applicationName ? [_applicationName UTF8String] : PGPostgresKitApplicationName;

	_connectionParamNames[1] = PGPostgresPortParam;
	_connectionParamValues[1] = [[[NSNumber numberWithUnsignedInteger:_port] stringValue] UTF8String];

	_connectionParamNames[2] = PGPostgresClientEncodingParam;
	_connectionParamValues[2] = [_encoding UTF8String];

	_connectionParamNames[3] = PGPostgresKeepAliveParam;
	_connectionParamValues[3] = _useKeepAlive ? "1" : "0";

	_connectionParamNames[4] = PGPostgresKeepAliveIntervalParam;
	_connectionParamValues[4] = [[[NSNumber numberWithUnsignedInteger:_keepAliveInterval] stringValue] UTF8String];

	NSUInteger i = 5;

	if (hasUser) {
		_connectionParamNames[i] = PGPostgresUserParam;
		_connectionParamValues[i] = [_user UTF8String];

		i++;
	}

	if (hasHost) {
		_connectionParamNames[i] = PGPostgresHostParam;
		_connectionParamValues[i] = [_host UTF8String];

		i++;
	}

	if (hasPassword) {
		_connectionParamNames[i] = PGPostgresPasswordParam;
		_connectionParamValues[i] = [_password UTF8String];

		i++;
	}

	if (hasDatabase) {
		_connectionParamNames[i] = PGPostgresDatabaseParam;
		_connectionParamValues[i] = [_database UTF8String];

		i++;
	}

	_connectionParamNames[i] = '\0';
	_connectionParamValues[i] = '\0';
}

#pragma mark -

- (void)dealloc
{
	[_typeMap release];

	[self disconnect];

	[self setHost:nil];
	[self setUser:nil];
	[self setDatabase:nil];

	if (_connectionParamNames) free(_connectionParamNames);
	if (_connectionParamValues) free(_connectionParamValues);

	if (_lastError) [_lastError release], _lastError = nil;
	if (_parameters) [_parameters release], _parameters = nil;
	if (_connectionError) [_connectionError release], _connectionError = nil;
	if (_applicationName) [_applicationName release], _applicationName = nil;

	[super dealloc];
}

@end


text:
package gw.testharness;

import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.*;

/**
 * See http://wiki/index.php/KnownBreak for detailed document
 */
@Retention(RUNTIME)
@Inherited
@IncludeInTestResults
public @interface KnownBreak {
  String targetUser() default "ignore";
  String targetBranch() default "none";
  String jira();
}


text:
<?php

declare(strict_types=1);

namespace FSi\DoctrineExtensions\Uploadable\Keymaker;

use Doctrine\Common\Util\ClassUtils;

class TransliterateEntity implements KeymakerInterface
{
    const DEFAULT_PATTERN = '/{fqcn}/{property}/{id}/{original_name}';

    public function createKey(
        $object,
        string $property,
        $id,
        string $originalName,
        ?string $pattern = null
    ): string {
        if (is_null($pattern)) {
            $pattern = self::DEFAULT_PATTERN;
        }

        return preg_replace(
            [
                '/\{fqcn\}/',
                '/\{property\}/',
                '/\{id\}/',
                '/\{original_name\}/',
            ],
            [
                preg_replace('/\\\\/', '', ClassUtils::getClass($object)),
                $property,
                $id,
                $this->cleanFileName($originalName),
            ],
            $pattern
        );
    }

    private function cleanFileName(string $originalName): string
    {
        $transliteratedName = transliterator_transliterate(
            'Any-Latin; Latin-ASCII; Lower()',
            $originalName
        );

        return trim(preg_replace(
            '/[-\s]+/', '-',
            preg_replace('/[^\da-z.\-\s]+/', '', $transliteratedName)
        ));
    }
}


text:
var ms = require("milsymbol");

module.exports = function(properties, mapping) {
  this.SIDC = this.SIDC.toUpperCase();

  var codingscheme = this.SIDC.charAt(0) != "" ? this.SIDC.charAt(0) : "-";
  var affiliation = this.SIDC.charAt(1) != "" ? this.SIDC.charAt(1) : "-";
  var battledimension = this.SIDC.charAt(2) != "" ? this.SIDC.charAt(2) : "-";
  var status = this.SIDC.charAt(3) != "" ? this.SIDC.charAt(3) : "-";
  var functionid = (properties.functionid = this.SIDC.substr(4, 6) != ""
    ? this.SIDC.substr(4, 6)
    : "------");
  var symbolmodifier11 = this.SIDC.charAt(10) != ""
    ? this.SIDC.charAt(10)
    : "-";
  var symbolmodifier12 = this.SIDC.charAt(11) != ""
    ? this.SIDC.charAt(11)
    : "-";
  var countrycode = this.SIDC.substr(12, 2) != ""
    ? this.SIDC.substr(12, 2)
    : "--";
  var orderofbattle = this.SIDC.charAt(14) != "" ? this.SIDC.charAt(14) : "-";

  if (["H", "S", "J", "K"].indexOf(affiliation) > -1)
    properties.affiliation = mapping.affiliation[0];
  if (["F", "A", "D", "M"].indexOf(affiliation) > -1)
    properties.affiliation = mapping.affiliation[1];
  if (["N", "L"].indexOf(affiliation) > -1)
    properties.affiliation = mapping.affiliation[2];
  if (["P", "U", "G", "W", "O"].indexOf(affiliation) > -1)
    properties.affiliation = mapping.affiliation[3];

  if (["P", "A"].indexOf(battledimension) > -1)
    properties.dimension = mapping.dimension[0];
  if (["G", "Z", "F", "X"].indexOf(battledimension) > -1)
    properties.dimension = mapping.dimension[1];
  if (["S"].indexOf(battledimension) > -1)
    properties.dimension = mapping.dimension[2];
  if (["U"].indexOf(battledimension) > -1)
    properties.dimension = mapping.dimension[3];

  //Planned/Anticipated/Suspect symbols should have a dashed outline
  if (status == "A") {
    properties.notpresent = ms._dashArrays.anticipated;
  }
  if (["P", "A", "S", "G", "M"].indexOf(affiliation) > -1) {
    properties.notpresent = ms._dashArrays.pending;
  }

  if (orderofbattle == "X") {
    properties.graphic = true;
  }

  // Army XML compability
  //sidc['CIRCLE----'] = ms.geometryConverter.circle;

  // Systematic SitaWare compatibility
  var genericSIDC =
    this.SIDC.substr(0, 1) +
    "-" +
    this.SIDC.substr(2, 1) +
    "-" +
    this.SIDC.substr(4, 6);
  if (["X---C-----", "X---I-----", "X---A-----"].indexOf(genericSIDC) != -1) {
    properties.graphic = true;
  }

  return properties;
};


text:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <ListPreference
        android:defaultValue="-1"
        android:entries="@array/pref_example_list_titles"
        android:entryValues="@array/pref_example_list_values"
        android:key="example_list"
        android:negativeButtonText="@null"
        android:positiveButtonText="@null"
        android:title="User Mode" />
    <EditTextPreference
        android:key="teamNumber"
        android:title="Team Number"
        android:persistent="true"
        android:dialogTitle="Update team number."
        android:dialogMessage="Changed Number"
        android:defaultValue="1"/>
</PreferenceScreen>


text:
{# ------------------------------------------------------- #}

{# 404 PAGE #}

{# This is the 404 page that will display on the live site for users. #}
{# It does not appear when you run your site locally. #}

{# ------------------------------------------------------- #}

{# Confused what extends and blocks do? Watch a primer: #}
{# http://www.webhook.com/docs/template-inheritance-blocks/ #}
{% extends "templates/partials/base.html" %}

{% block header %}

{% endblock %}

{% set item = cms.audiences[0] %}

{% block body_attributes %}
  class="layout__white"
{% endblock %}

{% block content %}

  {% set events = cms.events %}
  {% for event in events %}
    {% set event.modal_id = "modal-"+loop.index %}
    {# event_link = '#', lowercase, ' ' replaced with '-', non-alphanumeric characters except for ' ' and '-' replaced with '', multiple consecutive '-' replaced with '-' #}
    {% set event.event_link = event.name|lower|replace(' ','-','g')|replace('[^a-zA-Z0-9 -]','','g')|replace('-+','-','g') %}
  {% endfor %}
  {% set infoSnippets = item.information_snippets %}

  {#  #}

    {# Poster Moment #}

RISD

FOUR

O

FOUR

{{ modifier_line.line }}

WEEK—

END¹⁶

{% endblock %}


text:
package de.flexiprovider.core.kdf;

import de.flexiprovider.api.parameters.AlgorithmParameterSpec;
import de.flexiprovider.common.util.ByteUtils;

/**
 * This class specifies parameters used by the {@link KDF1}, {@link KDF2}, and
 * {@link X963} key derivation functions. The parameters consist of a byte array
 * containing shared information.
 *
 * @author Martin Döring
 */
public class KDFParameterSpec implements AlgorithmParameterSpec {

    // the shared information
    private byte[] sharedInfo;

    /**
     * Constructor. Set the shared information.
     *
     * @param sharedInfo
     *                the shared information
     */
    public KDFParameterSpec(byte[] sharedInfo) {
	this.sharedInfo = ByteUtils.clone(sharedInfo);
    }

    /**
     * @return the shared information
     */
    public byte[] getSharedInfo() {
	return ByteUtils.clone(sharedInfo);
    }

}


text:
void FileDataManager::JsonSave(string Filename, string JsonString)
{
    ofstream fileOut;
    fileOut.open(Filename, ios_base::out);
    fileOut << JsonString;
    fileOut.close();
}

void FileDataManager::FileAppend(string Filename, string StringData)
{
    ofstream fileOut;
    fileOut.open(Filename, ios_base::app);
    fileOut << StringData;
    fileOut.close();
}

void FileDataManager::TextSave(char * SaveFilename, vector<string> VecString)
{
    HANDLE hFile;
    string szBuffer;
    DWORD write;

    //  String copy to buffer
    //strncpy_s(szBuffer, 128, VectorArrayCombine(VecString), 126);
    szBuffer = VectorArrayCombine(VecString);

    //  Create file Handle
    hFile = CreateFile(SaveFilename
                        , GENERIC_WRITE
                        , 0
                        , NULL
                        , CREATE_ALWAYS
                        , FILE_ATTRIBUTE_NORMAL
                        , NULL);

    //  Write
    WriteFile(hFile, szBuffer.c_str(), (DWORD)strlen(szBuffer.c_str()), &write, NULL);

    //  Close handle
    CloseHandle(hFile);
}

string FileDataManager::MakeCsvString(vector<string> VecArray)
{
    string szBuffer = "";

    for (int i = 0; i < (int)VecArray.size(); i++)
    {
        szBuffer.append(VecArray[i]);
        szBuffer.append(",");
    }

    return szBuffer;
}

char * FileDataManager::VectorArrayCombine(vector<string> VecArray)
{
    char szBuffer[128];
    ZeroMemory(szBuffer, sizeof(szBuffer));

    for (int i = 0; i < (int)VecArray.size(); i++)
    {
        strcat_s(szBuffer, VecArray[i].c_str());

        if (i < VecArray.size() - 1)
        {
            strcat_s(szBuffer, ",");
        }
    }

    return szBuffer;
}

vector<string> FileDataManager::TextLoad(char * LoadFilename)
{
    HANDLE hFile;
    char szBuffer[128];
    DWORD read;

    ZeroMemory(szBuffer, strlen(szBuffer));

    //  Create file Handle
    hFile = CreateFile(LoadFilename
        , GENERIC_READ
        , 0
        , NULL
        , OPEN_EXISTING
        , FILE_ATTRIBUTE_NORMAL
        , NULL);

    //  Read
    ReadFile(hFile, szBuffer, (DWORD)strlen(szBuffer), &read, NULL);

    //  Close handle
    CloseHandle(hFile);

    return CharArraySeperation(szBuffer);
}

vector<string> FileDataManager::CharArraySeperation(char CharArray[])
{
    vector<string> vecArray;
    char* temp = NULL;
    char* separator = ",";
    char* token;

    token = strtok_s(CharArray, separator, &temp);
    if (token != NULL)
    {
        vecArray.push_back(token);
    }

    while ((token = strtok_s(NULL, separator, &temp)) != NULL)
    {
        vecArray.push_back(token);
    }

    return vecArray;
}


text:
namespace CrosspostSharp3.Mastodon {
	partial class MastodonLoginDialog {
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing) {
			if (disposing && (components != null)) {
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent() {
            this.btnOkay = new System.Windows.Forms.Button();
            this.btnCancel = new System.Windows.Forms.Button();
            this.txtPassword = new System.Windows.Forms.TextBox();
            this.lblPassword = new System.Windows.Forms.Label();
            this.txtEmail = new System.Windows.Forms.TextBox();
            this.lblEmail = new System.Windows.Forms.Label();
            this.comboBox1 = new System.Windows.Forms.ComboBox();
            this.label1 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            //
            // btnOkay
            //
            this.btnOkay.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.btnOkay.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.btnOkay.Location = new System.Drawing.Point(197, 106);
            this.btnOkay.Name = "btnOkay";
            this.btnOkay.Size = new System.Drawing.Size(75, 23);
            this.btnOkay.TabIndex = 7;
            this.btnOkay.Text = "OK";
            this.btnOkay.UseVisualStyleBackColor = true;
            //
            // btnCancel
            //
            this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.btnCancel.Location = new System.Drawing.Point(116, 106);
            this.btnCancel.Name = "btnCancel";
            this.btnCancel.Size = new System.Drawing.Size(75, 23);
            this.btnCancel.TabIndex = 6;
            this.btnCancel.Text = "Cancel";
            this.btnCancel.UseVisualStyleBackColor = true;
            //
            // txtPassword
            //
            this.txtPassword.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.txtPassword.Location = new System.Drawing.Point(73, 65);
            this.txtPassword.Name = "txtPassword";
            this.txtPassword.PasswordChar = '*';
            this.txtPassword.Size = new System.Drawing.Size(199, 20);
            this.txtPassword.TabIndex = 5;
            //
            // lblPassword
            //
            this.lblPassword.AutoSize = true;
            this.lblPassword.Location = new System.Drawing.Point(14, 68);
            this.lblPassword.Name = "lblPassword";
            this.lblPassword.Size = new System.Drawing.Size(53, 13);
            this.lblPassword.TabIndex = 4;
            this.lblPassword.Text = "Password";
            //
            // txtEmail
            //
            this.txtEmail.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.txtEmail.Location = new System.Drawing.Point(73, 39);
            this.txtEmail.Name = "txtEmail";
            this.txtEmail.Size = new System.Drawing.Size(199, 20);
            this.txtEmail.TabIndex = 3;
            //
            // lblEmail
            //
            this.lblEmail.AutoSize = true;
            this.lblEmail.Location = new System.Drawing.Point(35, 42);
            this.lblEmail.Name = "lblEmail";
            this.lblEmail.Size = new System.Drawing.Size(32, 13);
            this.lblEmail.TabIndex = 2;
            this.lblEmail.Text = "Email";
            //
            // comboBox1
            //
            this.comboBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.comboBox1.FormattingEnabled = true;
            this.comboBox1.Items.AddRange(new object[] {
            "mastodon.social",
            "mastodon.xyz",
            "mastodon.technology",
            "octodon.social",
            "mstdn.io",
            "mastodon.art"});
            this.comboBox1.Location = new System.Drawing.Point(73, 12);
            this.comboBox1.Name = "comboBox1";
            this.comboBox1.Size = new System.Drawing.Size(199, 21);
            this.comboBox1.TabIndex = 1;
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(19, 15);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(48, 13);
            this.label1.TabIndex = 0;
            this.label1.Text = "Instance";
            //
            // MastodonLoginDialog
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 141);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.comboBox1);
            this.Controls.Add(this.btnOkay);
            this.Controls.Add(this.btnCancel);
            this.Controls.Add(this.txtPassword);
            this.Controls.Add(this.lblPassword);
            this.Controls.Add(this.txtEmail);
            this.Controls.Add(this.lblEmail);
            this.Name = "MastodonLoginDialog";
            this.Text = "Log In";
            this.ResumeLayout(false);
            this.PerformLayout();

		}

		#endregion

		private System.Windows.Forms.Button btnOkay;
		private System.Windows.Forms.Button btnCancel;
		private System.Windows.Forms.TextBox txtPassword;
		private System.Windows.Forms.Label lblPassword;
		private System.Windows.Forms.TextBox txtEmail;
		private System.Windows.Forms.Label lblEmail;
		private System.Windows.Forms.ComboBox comboBox1;
		private System.Windows.Forms.Label label1;
	}
}


text:
import { Component, ChangeDetectionStrategy, OnInit, ChangeDetectorRef, ViewChild, TemplateRef } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { MatIconRegistry } from '@angular/material';

import { BlockUI, NgBlockUI } from 'ng-block-ui';
import { saveAs } from 'file-saver';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

import { SecurityService } from './service/security.service';
import { Employe } from './shared/dto/employe';
import { FullDayLeave } from './shared/dto/leave';
import { FullYearLeavesComponent } from './full-year-leaves/full-year-leaves.component';
import { FullYearLeavesOverlapsComponent } from './full-year-leaves-overlaps/full-year-leaves-overlaps.component';
import { AccessDeniedComponent } from './access-denied/access-denied.component';
import { NotFoundComponent } from './not-found/not-found.component';
import { ApprovationMode, MenuItemIds, Profile } from './shared/enums';
import { LeaveService } from './service/leave.service';
import { NavigationNode } from './layout/nav-menu/nav-menu.model';
import { sideNavNodes } from './layout/nav-menu/menu-nodes';
import { CoverageService } from './service/coverage.service';
import { ApplicationSharedData } from './shared/application-shared-data';
import { EmployeLeaves } from './shared/dto/employe-leaves';

@Component({
    changeDetection: ChangeDetectionStrategy.OnPush,
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

    @ViewChild('employesModal') employesModal: TemplateRef<any>;
    @ViewChild('shutDownModal') shutDownModal: TemplateRef<any>;
    @ViewChild('inflexibilityPeriodModal') inflexibilityPeriodModal: TemplateRef<any>;
    @ViewChild('approvationModal') approvationModal: TemplateRef<any>;

    @BlockUI() blockUI: NgBlockUI;

    sideNavNodes = sideNavNodes;

    fabToolTipMsg: string;
    fabLeavesIcon: boolean;

    leavesPlanTooltip = 'Piano Ferie';
    yearCoverageTooltip = 'Copertura annuale';
    showCoverageTitle = false;

    ApplicationSharedData = ApplicationSharedData;
    ApprovationMode = ApprovationMode;
    requestedApprovationMode: ApprovationMode;

    title = 'Flessibiltà';

    currentView: any;
    loggedEmploye: Employe;
    displayLeavesPlanDownload = false;
    isManager = false;

    constructor(private securityService: SecurityService, private leaveService: LeaveService,
        private coverageService: CoverageService, private ref: ChangeDetectorRef, private modal: NgbModal,
        iconRegistry: MatIconRegistry, sanitizer: DomSanitizer) {
        iconRegistry.addSvgIcon('keyboard-arrow-right',
            sanitizer.bypassSecurityTrustResourceUrl('assets/images/keyboard-arrow-right.svg'));
    }

    ngOnInit() {
        this.securityService.getLoggedEmploye().then(e => this.setLoggedUser(e)).catch(reason => this.setLoggedUser(undefined));
    }

    private setLoggedUser(e: Employe): void {
        this.loggedEmploye = e;
        this.isManager = e ? (this.loggedEmploye.profile === Profile.Manager) : false;
        ApplicationSharedData.getInstance().loggedEmploye = e;
        if (e && this.isManager) {
            this.employesListChanged();
            this.showCoverageTitle = true;
            this.currentView = FullYearLeavesOverlapsComponent;
            this.displayLeavesPlanDownload = true;
            this.fabToolTipMsg = this.leavesPlanTooltip;
            this.fabLeavesIcon = true;
        } else if (e && !this.isManager) {
            this.showCoverageTitle = false;
            this.currentView = FullYearLeavesComponent;
        } else {
            this.currentView = AccessDeniedComponent;
        }
        this.ref.markForCheck();
    }

    private toggleLeavesCoverage(): void {
        if (this.currentView === FullYearLeavesOverlapsComponent) {
            this.showCoverageTitle = false;
            this.currentView = FullYearLeavesComponent;
            this.fabToolTipMsg = this.yearCoverageTooltip;
            this.fabLeavesIcon = false;
            this.displayLeavesPlanDownload = false;
        } else {
            this.showCoverageTitle = true;
            this.currentView = FullYearLeavesOverlapsComponent;
            this.fabToolTipMsg = this.leavesPlanTooltip;
            this.fabLeavesIcon = true;
            this.displayLeavesPlanDownload = true;
        }
        this.ref.markForCheck();
    }

    private goToEmploeLeaves(employeleaves: EmployeLeaves): void {
        ApplicationSharedData.getInstance().setEmpAutoCompInjectSearch(employeleaves.fullName);
        if (this.currentView === FullYearLeavesOverlapsComponent) {
            this.showCoverageTitle = false;
            this.currentView = FullYearLeavesComponent;
            this.fabToolTipMsg = this.yearCoverageTooltip;
            this.fabLeavesIcon = false;
            this.displayLeavesPlanDownload = false;
        }
        this.ref.markForCheck();
    }

    private downloadLeavesPlan(): void {
        this.blockUI.start('Attendere prego...');
        this.leaveService.getLeavesPlan(ApplicationSharedData.getInstance().currentYear)
            .then(blob => {
                saveAs(blob, `piano_ferie-${ApplicationSharedData.getInstance().currentYear}.xlsx`);
                this.stopBlockUI();
            }).catch(error => this.stopBlockUI());
    }

    private employesListChanged(): void {
        ApplicationSharedData.getInstance().setFlexibilityComposition(this.coverageService, this.leaveService);
    }

    private stopBlockUI(): void {
        this.blockUI.stop();
        this.ref.markForCheck();
    }

    private logout(): void {
        this.currentView = undefined;
        this.loggedEmploye = undefined;
        ApplicationSharedData.getInstance().loggedEmploye = undefined;
        this.securityService.logout().catch(feak => {
            window.location.reload(true);
        });
    }

    openNodeModal(node: NavigationNode): void {
        switch (node.id) {
            case MenuItemIds.Employes:
                this.modal.open(this.employesModal, { size: 'lg', windowClass: 'animated bounceInLeft' });
                break;
            case MenuItemIds.Shutdowns:
                this.modal.open(this.shutDownModal, { size: 'lg', windowClass: 'animated bounceInLeft' });
                break;
            case MenuItemIds.presences:
                this.modal.open(this.inflexibilityPeriodModal, { size: 'lg', windowClass: 'modal-xxl animated bounceInLeft' });
                break;
            case MenuItemIds.AddedLeaves:
                this.requestedApprovationMode = ApprovationMode.Add;
                this.modal.open(this.approvationModal, { size: 'lg', windowClass: 'animated bounceInLeft' });
                break;
            case MenuItemIds.RemovedLeaves:
                this.requestedApprovationMode = ApprovationMode.Remove;
                this.modal.open(this.approvationModal, { size: 'lg', windowClass: 'animated bounceInLeft' });
                break;
        }
    }
}


text:
<?php

namespace RedKiteCms\Action\Page;

use RedKiteCms\TestCase;

/**
 * Class TestBaseAction
 *
 * @author RedKite Labs <webmaster@redkite-labs.com>
 */
abstract class TestBaseAction extends TestCase
{
    protected $app = null;

    abstract protected function configurePageManagerCollection($pageManagerCollection, $values, $username);

    protected function boot(array $values, $username)
    {
        $pageManagerCollection = $this
            ->getMockBuilder('\RedKiteCms\Content\PageCollection\PageCollectionManager')
            ->disableOriginalConstructor()
            ->getMock()
        ;
        $this->configurePageManagerCollection($pageManagerCollection, $values, $username);
        $this->initApp($pageManagerCollection);
    }

    protected function initApp($pageManagerCollection)
    {
        $this->app = $this
            ->getMockBuilder('\Silex\Application')
            ->disableOriginalConstructor()
            ->getMock()
        ;

        $this->app
            ->expects($this->at(0))
            ->method('offsetGet')
            ->with('red_kite_cms.page_collection_manager')
            ->will($this->returnValue($pageManagerCollection));
        ;
    }
}


text:
require 'helper'
require 'json'
require 'memcached_mock'

describe 'Serializer' do

  it 'default to Marshal' do
    memcached(29198) do |dc|
      dc.set 1,2
      assert_equal Marshal, dc.instance_variable_get('@ring').servers.first.serializer
    end
  end

  it 'support a custom serializer' do
    memcached(29198) do |dc, port|
      memcache = Dalli::Client.new("127.0.0.1:#{port}", :serializer => JSON)
      memcache.set 1,2
      begin
        assert_equal JSON, memcache.instance_variable_get('@ring').servers.first.serializer

        memcached(21956) do |newdc|
          assert newdc.set("json_test", {"foo" => "bar"})
          assert_equal({"foo" => "bar"}, newdc.get("json_test"))
        end
      end
    end
  end
end


text:
Clojure wrapper for Coursera Private API

## Examples

```clj
;; Get all your watchable videos
(with-coursera-credentials "your@email.com" "yourpassword"
  (let [sessions (enrolled-sessions)
        sections (map session->sections sessions)
        items (mapcat section->items sections)
        videos (map item->video items)]
    (map :link videos)))

;; Get all the videos from session 278
(with-coursera-credentials "your@email.com" "yourpassword"
  (let [sections (session->sections {:id 278})
        items (mapcat section->items sections)
        videos (map item->video items)]
    videos))

;; Same but shorter
(with-coursera-credentials "your@email.com" "yourpassword"
  (session->videos {:id 278}))
```


text:
export interface IKubernetesClusterNodePoolTaint {
  key: string;
  value: string;
  effect: string;
}


text:
package io.sniffy.sql;

import io.sniffy.BaseTest;
import io.sniffy.Sniffy;
import io.sniffy.Spy;
import org.junit.Test;

import static io.sniffy.Query.*;

public class SqlQueriesTest extends BaseTest {

    @Test
    public void testMinMaxQueries() {
        try (Spy $= Sniffy.expect(SqlQueries.minQueries(2).maxQueries(3))) {
            executeStatement();
            executeStatement();
            executeStatement();
        }
    }

    @Test(expected = WrongNumberOfQueriesError.class)
    public void testMaxMinQueries_Exception() {
        try (Spy $= Sniffy.expect(SqlQueries.maxQueries(3).minQueries(2))) {
            executeStatement();
        }
    }

    @Test
    public void testEqualMaxMinQueries() {
        try (Spy $= Sniffy.expect(SqlQueries.maxQueries(2).minQueries(2))) {
            executeStatement();
            executeStatement();
        }
    }

    @Test
    public void testExactTwoSelectQueries() {
        try (Spy $= Sniffy.expect(SqlQueries.exactQueries(2).select())) {
            executeStatement(SELECT);
            executeStatement(SELECT);
            executeStatement(INSERT);
        }
    }

    @Test
    public void testExactTwoInsertQueries() {
        try (Spy $= Sniffy.expect(SqlQueries.exactQueries(2).insert())) {
            executeStatement(INSERT);
            executeStatement(INSERT);
            executeStatement(SELECT);
        }
    }

    @Test
    public void testExactTwoUpdateQueries() {
        try (Spy $= Sniffy.expect(SqlQueries.exactQueries(2).update())) {
            executeStatement(UPDATE);
            executeStatement(UPDATE);
            executeStatement(SELECT);
        }
    }

    @Test
    public void testExactTwoDeleteQueries() {
        try (Spy $= Sniffy.expect(SqlQueries.exactQueries(2).delete())) {
            executeStatement(DELETE);
            executeStatement(DELETE);
            executeStatement(SELECT);
        }
    }

    @Test
    public void testExactTwoMergeQueries() {
        try (Spy $= Sniffy.expect(SqlQueries.exactQueries(2).merge())) {
            executeStatement(MERGE);
            executeStatement(MERGE);
            executeStatement(SELECT);
        }
    }

    @Test
    public void testExactTwoOtherQueries() {
        try (Spy $= Sniffy.expect(SqlQueries.exactQueries(2).other())) {
            executeStatement(OTHER);
            executeStatement(OTHER);
            executeStatement(SELECT);
        }
    }

    @Test
    public void testExactTwoCurrentThreadQueries() {
        try (Spy $= Sniffy.expect(SqlQueries.exactQueries(2).currentThread())) {
            executeStatement();
            executeStatement();
            executeStatementInOtherThread();
        }
    }

    @Test
    public void testExactTwoOtherThreadsQueries() {
        try (Spy $= Sniffy.expect(SqlQueries.exactQueries(2).otherThreads())) {
            executeStatementInOtherThread();
            executeStatementInOtherThread();
            executeStatement();
        }
    }

    @Test
    public void testExactTwoAnyThreadsQueries() {
        try (Spy $= Sniffy.expect(SqlQueries.exactQueries(2).anyThreads())) {
            executeStatementInOtherThread();
            executeStatement();
        }
    }

    @Test
    public void testExactTwoSelectCurrentThreadQueries() {
        try (Spy $= Sniffy.expect(SqlQueries.exactQueries(2).select().currentThread())) {
            executeStatement();
            executeStatement();
            executeStatementInOtherThread();
        }
    }

    @Test
    public void testExactTwoSelectOtherThreadsQueries() {
        try (Spy $= Sniffy.expect(SqlQueries.exactQueries(2).select().otherThreads())) {
            executeStatementInOtherThread();
            executeStatementInOtherThread();
            executeStatement();
        }
    }

    @Test
    public void testExactTwoSelectAnyThreadsQueries() {
        try (Spy $= Sniffy.expect(SqlQueries.exactQueries(2).select().anyThreads())) {
            executeStatementInOtherThread();
            executeStatement();
        }
    }

    @Test
    public void testExactTwoAnyThreadsSelectQueries() {
        try (Spy $= Sniffy.expect(SqlQueries.exactQueries(2).anyThreads().select())) {
            executeStatement(SELECT);
            executeStatementInOtherThread(SELECT);
        }
    }

    @Test
    public void testExactTwoAnyThreadsInsertQueries() {
        try (Spy $= Sniffy.expect(SqlQueries.exactQueries(2).anyThreads().insert())) {
            executeStatement(INSERT);
            executeStatementInOtherThread(INSERT);
        }
    }

    @Test
    public void testExactTwoAnyThreadsUpdateQueries() {
        try (Spy $= Sniffy.expect(SqlQueries.exactQueries(2).anyThreads().update())) {
            executeStatement(UPDATE);
            executeStatementInOtherThread(UPDATE);
        }
    }

    @Test
    public void testExactTwoAnyThreadsDeleteQueries() {
        try (Spy $= Sniffy.expect(SqlQueries.exactQueries(2).anyThreads().delete())) {
            executeStatement(DELETE);
            executeStatementInOtherThread(DELETE);
        }
    }

    @Test
    public void testExactTwoAnyThreadsMergeQueries() {
        try (Spy $= Sniffy.expect(SqlQueries.exactQueries(2).anyThreads().merge())) {
            executeStatement(MERGE);
            executeStatementInOtherThread(MERGE);
        }
    }

    @Test
    public void testExactTwoAnyThreadsOtherQueries() {
        try (Spy $= Sniffy.expect(SqlQueries.exactQueries(2).anyThreads().other())) {
            executeStatement(OTHER);
            executeStatementInOtherThread(OTHER);
        }
    }

}


text:
using System;

namespace SharpVectors.Text
{
	public class StringUtil
	{
		public static bool IsInArray(string[] arrayToLookIn, string strToFind)
		{
			foreach (string item in arrayToLookIn)
			{
				if (item == strToFind)
                    return true;
			}
			return false;
		}
	}
}


text: var specsNonI = 23;


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

AAAAA

BBBBBBBBBBB

CCCCCCCC


text:
//go:build test_unit

package common

import (
	"net/http"
	"testing"

	"github.com/nuclio/errors"
	"github.com/nuclio/nuclio-sdk-go"
	"github.com/stretchr/testify/suite"
)

type ErrorsTestSuite struct {
	suite.Suite
}

func (ets *ErrorsTestSuite) TestResolveErrorStatusCodeOrDefault() {
	for _, testCase := range []struct {
		inputError         error
		expectedStatusCode int
		defaultStatusCode  int
	}{

		// test get status code from deepest error cause
		{
			inputError:         errors.Wrap(errors.Wrap(nuclio.NewErrBadRequest("err"), "err"), "err"),
			expectedStatusCode: http.StatusBadRequest,
		},

		// test get status code from middle error cause
		{
			inputError:         errors.Wrap(errors.Wrap(nuclio.WrapErrConflict(nuclio.NewErrBadRequest("err")), "err"), "err"),
			expectedStatusCode: http.StatusConflict,
		},

		// test get status code from the top
		{
			inputError:         nuclio.WrapErrMethodNotAllowed(errors.Wrap(nuclio.WrapErrConflict(nuclio.NewErrBadRequest("err")), "err")),
			expectedStatusCode: http.StatusMethodNotAllowed,
		},

		// test get general internal status code when error has no status code
		{
			inputError:         errors.Wrap(errors.Wrap(errors.New("err"), "err"), "err"),
			expectedStatusCode: http.StatusInternalServerError,
			defaultStatusCode:  http.StatusOK,
		},

		// test get default status code when error is nil
		{
			inputError:         nil,
			expectedStatusCode: http.StatusOK,
			defaultStatusCode:  http.StatusOK,
		},
	} {

		// set default status code
		defaultStatusCode := http.StatusInternalServerError
		if testCase.defaultStatusCode != 0 {
			defaultStatusCode = testCase.defaultStatusCode
		}

		// run the tested function
		statusCode := ResolveErrorStatusCodeOrDefault(testCase.inputError, defaultStatusCode)

		// validate we got the expected status code
		ets.Require().Equal(testCase.expectedStatusCode, statusCode)
	}
}

func TestErrorsTestSuite(t *testing.T) {
	suite.Run(t, new(ErrorsTestSuite))
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources name="ru" flag="ru" title="Russian">
	<string_upd name="_bx_contact_et_contact_form_message_body"><![CDATA[{email_header}

Дорогой Administrator,

Вам написал пользователь {SenderName} с имейл-адресом {SenderEmail}

{MessageSubject}

{MessageBody}

{email_footer}]]></string_upd>
</resources>


text:
angular.module('ngBoilerplate', [
    'templates-app',
    'templates-common',
    'ngBoilerplate.home',
    'ngBoilerplate.about',
    'ui.router'
])

    .config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
        $urlRouterProvider.otherwise('/');
    }])

    .run(function run() {
    })

    .controller('AppCtrl', function AppCtrl($scope, $location) {
        $scope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
            if (angular.isDefined(toState.data.pageTitle)) {
                $scope.pageTitle = toState.data.pageTitle + ' | ngBoilerplate';
            }
        });
    })

;


text:
import React, { Component, PropTypes } from 'react'
import classNames from 'classnames'
import debounce from 'lodash/debounce'
import ImmutablePropTypes from 'react-immutable-proptypes'
import CustomPropTypes from '../../constants/CustomPropTypes'
import Form from '../../elements/Form'
import ListItem from '../../elements/ListItem'
import SelectField from '../../elements/SelectField'
import AutoComplete from '../../elements/AutoComplete'
import Button from '../../elements/Button'
import Icon from '../../elements/Icon'
import Box from '../elements/Box'
import Ad from '../Ad'
import AthleteInfo from '../athlete/AthleteInfo'
import AthleteList from './AthleteList'
import './ComparisonSelection.scss'

export default class ComparisonSelection extends Component {
  static propTypes = {
    className: PropTypes.string,
    loadDisciplines: PropTypes.func.isRequired,
    disciplineSelected: PropTypes.func.isRequired,
    disciplinesLoading: PropTypes.bool.isRequired,
    selectedDiscipline: PropTypes.string,
    disciplines: ImmutablePropTypes.listOf(CustomPropTypes.discipline).isRequired,
    applySelection: PropTypes.func.isRequired,
    loadAthlete: PropTypes.func.isRequired,
    searchAthlete: PropTypes.func.isRequired,
    athleteSelected: PropTypes.func.isRequired,
    selectedAthletes: ImmutablePropTypes.set,
    athletes: ImmutablePropTypes.setOf(CustomPropTypes.athlete),
    searching: PropTypes.bool.isRequired,
    searchResults: ImmutablePropTypes.listOf(CustomPropTypes.athlete)
  }

  componentWillMount() {
    this.props.loadDisciplines()

    if (this.props.selectedAthletes) {
      this.props.selectedAthletes.forEach(value => this.props.loadAthlete(value))
    }
  }

  handleDisciplineSelect = (item, value) => {
    this.props.disciplineSelected(value)
  }

  handleAthleteSelect = (item, value) => {
    this.props.athleteSelected(value, true)
  }

  handleAthleteUnselect = value => () => {
    this.props.athleteSelected(value, false)
  }

  itemFilter = (query, item) => {
    const parts = query.toLowerCase().split(' ')
    return parts.some(part => item.props.children.toLowerCase().includes(part))
  }

  render() {
    const {
      className,
      disciplinesLoading,
      selectedDiscipline,
      disciplines,
      applySelection,
      searching,
      searchAthlete,
      athletes,
      searchResults
    } = this.props
    const classes = classNames('ladbCompareSel', className)

    const disciplineSelectProps = {
      id: 'compDisSel',
      label: 'Disziplin',
      placeholder: 'Disziplin auswählen',
      value: selectedDiscipline,
      onChange: this.handleDisciplineSelect,
      busy: disciplinesLoading,
      filter: this.itemFilter
    }
    const disciplineItems = []
    disciplines.forEach((discipline) => {
      const itemProps = {
        key: discipline.get('id'),
        value: discipline.get('id')
      }
      disciplineItems.push(
        <ListItem {...itemProps}>
          {discipline.get('name')}
        </ListItem>
      )
    })

    const athleteSelectProps = {
      label: 'Athleten hinzufügen',
      placeholder: 'Athlet hinzufügen',
      busy: searching,
      onChange: debounce(searchAthlete, 300),
      onSelect: this.handleAthleteSelect
    }

    const athleteListProps = {
      label: 'Ausgewählte Athleten',
      placeholder: 'Noch kein Athlet hinzugefügt',
      hasItems: athletes.size > 0
    }

    let searchedAthletes = []
    if (searchResults) {
      searchedAthletes = searchResults.map((result, index) => {
        const athleteProps = {
          data: result,
          club: result.get('currentClub')
        }

        return (
          <ListItem key={index} value={result.get('id')}>
            <AthleteInfo {...athleteProps} />
          </ListItem>
        )
      })
    }

    const icon = (<Icon name="trash" />)
    const athleteItems = athletes.map((result, index) => {
      const athleteProps = {
        data: result,
        club: result.get('currentClub')
      }

      return (
        <ListItem key={index} value={result.get('id')} className="ladbCompareAthItm">
          <AthleteInfo {...athleteProps} />
          <Button icon={icon} onClick={this.handleAthleteUnselect(result.get('id'))} />
        </ListItem>
      )
    })

    return (

        <Box title="Athletenauswahl">
          <Form>
            <SelectField {...disciplineSelectProps}>
              {disciplineItems}
            </SelectField>
            <AutoComplete {...athleteSelectProps}>
              {searchedAthletes}
            </AutoComplete>
            <AthleteList {...athleteListProps}>
              {athleteItems}
            </AthleteList>
          </Form>

            <Button onClick={applySelection}>Anzeigen</Button>

        </Box>
        <Ad client="ca-pub-8743599418315465" slot="2730895435" position="side" />

    )
  }
}


text:
<?php

namespace Gantry\Component\Assignments;

use Gantry\Component\Config\CompiledConfig;
use Gantry\Component\Config\ConfigFileFinder;
use Gantry\Component\Gantry\GantryTrait;
use Gantry\Framework\Gantry;
use RocketTheme\Toolbox\File\YamlFile;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;

abstract class AbstractAssignments
{
    /**
     * @var string
     */
    protected $configuration;

    /**
     * @var string
     */
    protected $className = '\Gantry\%s\Assignments\Assignments%s';

    /**
     * @var string
     */
    protected $platform;

    /**
     * @var AssignmentFilter
     */
    protected $filter;

    /**
     * @var array
     */
    protected $candidates;

    /**
     * @var array
     */
    protected $page;

    /**
     * @param string $configuration
     */
    public function __construct($configuration = null)
    {
        $this->configuration = $configuration;
    }

    /**
     * Get list of assignment items.
     */
    public function get()
    {
        return $this->getTypes();
    }

    /**
     * Set (save) assignments.
     *
     * @param array $data
     */
    public function set(array $data)
    {
        $this->save($data);
    }

    /**
     * Select assigned outline.
     *
     * @param string $default
     * @return string
     */
    public function select($default = 'default')
    {
        $scores = $this->scores();

        return key($scores) ?: $default;
    }

    /**
     * List matching outlines sorted by score.
     *
     * @param array $candidates
     * @return array
     */
    public function scores(array $candidates = null)
    {
        $this->init();
        $candidates = $candidates ?: $this->candidates;
        return $this->filter->scores($candidates, $this->page);
    }

    /**
     * List matching outlines with matched assignments.
     *
     * @param array $candidates
     * @return array
     */
    public function matches(array $candidates = null)
    {
        $this->init();
        $candidates = $candidates ?: $this->candidates;
        return $this->filter->matches($candidates, $this->page);
    }

    /**
     * Load all assignments.
     *
     * @return array
     */
    public function loadAssignments()
    {
        $gantry = Gantry::instance();

        /** @var UniformResourceLocator $locator */
        $locator = $gantry['locator'];

        // Find all the assignment files.
        $paths = $locator->findResources("gantry-config://");
        $files = (new ConfigFileFinder)->locateFileInFolder('assignments', $paths);

        // Make sure that base or system outlines aren't in the list.
        foreach ($files as $key => $array) {
            if ($key && (((string)$key[0]) === '_' || $key === 'default')) {
                unset($files[$key]);
            }
        }

        $cache = $locator->findResource('gantry-cache://theme/compiled/config', true, true);

        $config = new CompiledConfig($cache, [$files], GANTRY5_ROOT);

        return $config->load()->toArray();
    }

    /**
     * Get all assignments for the current page.
     *
     * @return array
     */
    public function getPage()
    {
        $list = [];

        foreach($this->types() as $class => $type) {
            $class = is_numeric($class) ? sprintf($this->className, $this->platform, ucfirst($type)) : $class;

            if (!class_exists($class)) {
                throw new \RuntimeException("Assignment type {$type} is missing");
            }

            /** @var AssignmentsInterface $instance */
            $instance = new $class;
            $list[$type] = $instance->getRules();
            unset($instance);
        }

        return $list;
    }

    /**
     * Filter assignments data.
     *
     * @param array $data
     * @param bool $minimize
     * @return array
     */
    public function filter(array $data, $minimize = false)
    {
        $types = [];
        foreach ($this->types() as $type) {
            $types[$type] = [];
        }

        $data = array_replace($types, $data);
        foreach ($data as $tname => &$type) {
            if (is_array($type)) {
                foreach ($type as $gname => &$group) {
                    if (is_array($group)) {
                        foreach ($group as $key => $value) {
                            if (!$value) {
                                unset($group[$key]);
                            } else {
                                $group[$key] = (bool) $value;
                            }
                        }
                        if (empty($group)) {
                            unset($type[$gname]);
                        }
                    } else {
                        $group = (bool) $group;
                    }
                }
                if ($minimize && empty($type)) {
                    unset($data[$tname]);
                }
            } else {
                $type = (bool) $type;
            }
        }

        return $data;
    }

    /**
     * Save assignments for the configuration.
     *
     * @param array $data
     */
    public function save(array $data)
    {
        $data = $this->filter($data);

        $gantry = Gantry::instance();

        /** @var UniformResourceLocator $locator */
        $locator = $gantry['locator'];

        // Save layout into custom directory for the current theme.
        $save_dir = $locator->findResource("gantry-config://{$this->configuration}", true, true);
        $filename = "{$save_dir}/assignments.yaml";

        $file = YamlFile::instance($filename);
        $file->save($data);
        $file->free();
    }

    /**
     * Get list of all assignment types for assignments form.
     *
     * @return array
     */
    public function getTypes()
    {
        $list = [];

        foreach ($this->types() as $class => $type) {
            $class = is_numeric($class) ? sprintf($this->className, $this->platform, ucfirst($type)) : $class;

            if (!class_exists($class)) {
                throw new \RuntimeException("Assignment type '{$type}' is missing");
            }

            /** @var AssignmentsInterface $instance */
            $instance = new $class;
            $list[$type] = $instance->listRules($this->configuration);
            unset($instance);
        }

        return $list;
    }

    /**
     * Get selected assignment option.
     *
     * @return string
     */
    public function getAssignment()
    {
        return 'default';
    }

    /**
     * Set extra options for assignments.
     *
     * @param $value
     */
    public function setAssignment($value)
    {
    }

    /**
     * Get extra options for assignments.
     *
     * @return array
     */
    public function assignmentOptions()
    {
        return [];
    }

    protected function init()
    {
        if (!$this->filter) {
            $this->filter = new AssignmentFilter;
            $this->candidates = $this->loadAssignments();
            $this->page = $this->getPage();
        }
    }

    /**
     * Return list of assignment types.
     *
     * @return array
     */
    abstract public function types();
}


text:
Presentations made with reveal.js
=================================

## Introduction

This repo is designed to hold various presentations for training,
 talks and conferences purposes

### 2015
* [Regular expressions for the JPD2015 conference - MAD][jpd2015-1]
* [Developer perspective on working in a newsroom - BCN][jpd2015-2]
* [Regular expressions for the JPD2015 conference - BCN][jpd2015-3]
* [Elections: Continuous learning in a newsroom - BA][hhba2015-1]
* [Regular expressions for the HHBA conference - BA][hhba2015-2]
* [Developer perspective for Master La Nación - BA][masterLN2015]
* [Open Refine for La Nación - BA][LNtraining2015_1]
* [Mozfest Science Fair - London][mozfest1]
* [Mozfest Intro to d3js - London][mozfest2]

### 2016
* [Regular expressions for 2016 Master UE - MAD][master2016-1]
* [Intro to d3 for 2016 Master UE - MAD][master2016-2]

### 2017
* [Pym.js lazyload - Washington D.C.][skillshare-npr-1]

### 2022
* [Keynote MPVD - Alcalá][keynote-mpvd-2022]

## Acknowledgements

* To Hakim El Hattab for creating [reveal.js](Hakim El Hattab) and making our life this easy.

[jpd2015-1]: https://www.juanelosua.com/presentations/2015/20150604-jpd2015-regexp/
[jpd2015-2]: https://www.juanelosua.com/presentations/2015/20150605-jpd2015-coloquio/
[jpd2015-3]: https://www.juanelosua.com/presentations/2015/20150606-jpd2015-regexp/
[hhba2015-1]: https://www.juanelosua.com/presentations/2015/20150828-hhba2015-keynote/
[hhba2015-2]: https://www.juanelosua.com/presentations/2015/20150828-hhba2015-regexp/
[masterLN2015]: https://www.juanelosua.com/presentations/2015/20150916-masterLN-perspectiva/
[LNtraining2015_1]: https://www.juanelosua.com/presentations/2015/20150923-lanacion-refine/
[mozfest1]: https://www.juanelosua.com/presentations/2015/20151106-mozfest-sciencefair/
[mozfest2]: https://www.juanelosua.com/presentations/2015/20151107-mozfest-d3/
[master2016-1]: https://www.juanelosua.com/presentations/2016/20160314-masterUE-regexp/
[master2016-2]: https://www.juanelosua.com/presentations/2016/20160315-masterUE-d3/
[skillshare-npr-1]: https://www.juanelosua.com/presentations/2017/20170723-pym-lazyload/
[keynote-mpvd-2022]: https://www.juanelosua.com/presentations/2022/20220613-mpvd-keynote/


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

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

import org.cipango.server.SipConnector;
import org.cipango.server.SipRequest;
import org.cipango.servlet.SipServletHolder;
import org.eclipse.jetty.security.UserDataConstraint;
import org.eclipse.jetty.server.UserIdentity;

public class ConstraintSecurityHandler extends SipSecurityHandler<RoleInfo>
{

    private final List<ConstraintMapping> _constraintMappings= new CopyOnWriteArrayList<ConstraintMapping>();
    private final Set<String> _roles = new CopyOnWriteArraySet<String>();
    private boolean _strict = true;

    private Map<String, Map<String, RoleInfo>> _servletsMap = new HashMap<String, Map<String,RoleInfo>>();

    /* ------------------------------------------------------------ */
    /** Get the strict mode.
     * @return true if the security handler is running in strict mode.
     */
    public boolean isStrict()
    {
        return _strict;
    }

    /* ------------------------------------------------------------ */
    /** Set the strict mode of the security handler.
     *

     * When in strict mode (the default), the full servlet specification
     * will be implemented.
     * If not in strict mode, some additional flexibility in configuration
     * is allowed:

     *
All users do not need to have a role defined in the deployment descriptor
     *
The * role in a constraint applies to ANY role rather than all roles defined in
     * the deployment descriptor.
     *

     *
     * @param strict the strict to set
     * @see #setRoles(Set)
     * @see #setConstraintMappings(List, Set)
     */
    public void setStrict(boolean strict)
    {
        _strict = strict;
    }

    /* ------------------------------------------------------------ */
    /**
     * @return Returns the constraintMappings.
     */
    public List<ConstraintMapping> getConstraintMappings()
    {
        return _constraintMappings;
    }

    /* ------------------------------------------------------------ */
    public Set<String> getRoles()
    {
        return _roles;
    }

    /* ------------------------------------------------------------ */
    /**
     * Process the constraints following the combining rules in Servlet 3.0 EA
     * spec section 13.7.1 Note that much of the logic is in the RoleInfo class.
     *
     * @param constraintMappings
     *            The constraintMappings to set, from which the set of known roles
     *            is determined.
     */
    public void setConstraintMappings(List<ConstraintMapping> constraintMappings)
    {
        setConstraintMappings(constraintMappings,null);
    }

    /* ------------------------------------------------------------ */
    /**
     * Process the constraints following the combining rules in Servlet 3.0 EA
     * spec section 13.7.1 Note that much of the logic is in the RoleInfo class.
     *
     * @param constraintMappings
     *            The constraintMappings to set.
     * @param roles The known roles (or null to determine them from the mappings)
     */
    public void setConstraintMappings(List<ConstraintMapping> constraintMappings, Set<String> roles)
    {
        if (isStarted())
            throw new IllegalStateException("Started");
        _constraintMappings.clear();
        _constraintMappings.addAll(constraintMappings);

        if (roles==null)
        {
            roles = new HashSet<String>();
            for (ConstraintMapping cm : constraintMappings)
            {
                String[] cmr = cm.getConstraint().getRoles();
                if (cmr!=null)
                {
                    for (String r : cmr)
                        if (!"*".equals(r))
                            roles.add(r);
                }
            }
        }
        setRoles(roles);
    }

    /* ------------------------------------------------------------ */
    /**
     * Set the known roles.
     * This may be overridden by a subsequent call to {@link #setConstraintMappings(ConstraintMapping[])} or
     * {@link #setConstraintMappings(List, Set)}.
     * @see #setStrict(boolean)
     * @param roles The known roles (or null to determine them from the mappings)
     */
    public void setRoles(Set<String> roles)
    {
        if (isStarted())
            throw new IllegalStateException("Started");

        _roles.clear();
        _roles.addAll(roles);
    }

    /* ------------------------------------------------------------ */
    /**
     * @see org.eclipse.jetty.security.ConstraintAware#addConstraintMapping(org.eclipse.jetty.security.ConstraintMapping)
     */
    public void addConstraintMapping(ConstraintMapping mapping)
    {
        _constraintMappings.add(mapping);
        if (mapping.getConstraint()!=null && mapping.getConstraint().getRoles()!=null)
            for (String role :  mapping.getConstraint().getRoles())
                addRole(role);
    }

    /* ------------------------------------------------------------ */
    /**
     * @see org.eclipse.jetty.security.ConstraintAware#addRole(java.lang.String)
     */
    public void addRole(String role)
    {
        _roles.add(role);
    }

    @Override
    protected void doStart() throws Exception
    {
        _servletsMap.clear();
        if (_constraintMappings!=null)
        {
            for (ConstraintMapping mapping : _constraintMappings)
            {
                processConstraintMapping(mapping);
            }
        }

        super.doStart();
    }

    @Override
    protected void doStop() throws Exception
    {
    	_servletsMap.clear();
        _constraintMappings.clear();
        _roles.clear();
        super.doStop();
    }

	@Override
	protected RoleInfo prepareConstraintInfo(SipServletHolder holder, SipRequest request)
	{
		Map<String, RoleInfo> mappings = _servletsMap.get(holder.getName());
		// FIXME merge in case method && servlets

        if (mappings != null)
        {
            String method = request.getMethod();
            RoleInfo roleInfo = mappings.get(method);

            if (roleInfo == null)
                roleInfo = mappings.get(null);

            return roleInfo;
        }
        mappings = _servletsMap.get(null);

        if (mappings != null)
            return mappings.get(request.getMethod());

        return null;
	}

	@Override
	protected boolean checkUserDataPermissions(SipServletHolder holder, SipRequest request,
			RoleInfo constraintInfo) throws IOException
	{
	    if (constraintInfo == null)
	        return true;

	    if (constraintInfo.isForbidden())
	        return false;

	    UserDataConstraint dataConstraint = constraintInfo.getUserDataConstraint();
	    if (dataConstraint == null || dataConstraint == UserDataConstraint.None)
	    {
	        return true;
	    }

	    SipConnector connector = null;

	    if (request.getConnection() != null)
	    	connector = request.getConnection().getConnector();

	    return true;

	    /* TODO
	    if (dataConstraint == UserDataConstraint.Integral)
	    {
	        if (connector.isIntegral(request))
	            return true;
	        if (connector.getConfidentialPort() > 0)
	        {
	            String url = connector.getIntegralScheme() + "://" + request.getServerName() + ":" + connector.getIntegralPort() + request.getRequestURI();
	            if (request.getQueryString() != null)
	                url += "?" + request.getQueryString();
	            response.setContentLength(0);
	            response.sendRedirect(url);
	        }
	        else
	            response.sendError(Response.SC_FORBIDDEN,"!Integral");

	        request.setHandled(true);
	        return false;
	    }
	    else if (dataConstraint == UserDataConstraint.Confidential)
	    {
	        if (connector.isConfidential(request))
	            return true;

	        if (connector.getConfidentialPort() > 0)
	        {
	            String url = connector.getConfidentialScheme() + "://" + request.getServerName() + ":" + connector.getConfidentialPort()
	                    + request.getRequestURI();
	            if (request.getQueryString() != null)
	                url += "?" + request.getQueryString();

	            response.setContentLength(0);
	            response.sendRedirect(url);
	        }
	        else
	            response.sendError(Response.SC_FORBIDDEN,"!Confidential");

	        request.setHandled(true);
	        return false;

	    }
	    else
	    {
	        throw new IllegalArgumentException("Invalid dataConstraint value: " + dataConstraint);
	    }
	    */

	}

	@Override
	protected boolean isAuthMandatory(SipRequest baseRequest, RoleInfo constraintInfo)
	{
		 if (constraintInfo == null)
	           return false;
	     return constraintInfo.isChecked();
	}

	@Override
	protected boolean checkSipResourcePermissions(SipServletHolder holder, SipRequest request,
			RoleInfo constraintInfo, UserIdentity userIdentity) throws IOException
	{
		if (constraintInfo == null)
        {
            return true;
        }

        if (!constraintInfo.isChecked())
        {
            return true;
        }

        if (constraintInfo.isAnyRole() /*&& request.getAuthType()!=null*/)
            return true;

        for (String role : constraintInfo.getRoles())
        {
            if (userIdentity.isUserInRole(role, null))
                return true;
        }
        return false;
	}

	@Override
	protected boolean isProxyMode(SipRequest baseRequest, RoleInfo constraintInfo)
	{
		if (constraintInfo == null)
            return true;

		return constraintInfo.isProxyMode();
	}

	protected void processConstraintMapping(ConstraintMapping mapping)
    {
		if (mapping.getServletNames() == null)
		{
			for (String method : mapping.getMethods())
				processMapping(null, method, mapping.getConstraint());
		}
		else
		{
			for (String servletName : mapping.getServletNames())
			{
				if (mapping.getMethods() == null)
					processMapping(servletName, null, mapping.getConstraint());
				else
				{
					for (String method : mapping.getMethods())
						processMapping(servletName, method, mapping.getConstraint());
				}
			}
		}
    }

	private void processMapping(String servletName, String method, Constraint constraint)
	{
        Map<String, RoleInfo> mappings = (Map<String, RoleInfo>)_servletsMap.get(servletName);
        if (mappings == null)
        {
            mappings = new HashMap<String, RoleInfo>();
            _servletsMap.put(servletName,mappings);
        }
        RoleInfo allMethodsRoleInfo = mappings.get(null);
        if (allMethodsRoleInfo != null && allMethodsRoleInfo.isForbidden())
            return;

        RoleInfo roleInfo = mappings.get(method);
        if (roleInfo == null)
        {
            roleInfo = new RoleInfo();
            mappings.put(method,roleInfo);
            if (allMethodsRoleInfo != null)
            {
                roleInfo.combine(allMethodsRoleInfo);
            }
        }
        if (roleInfo.isForbidden())
            return;

        boolean forbidden = constraint.isForbidden();
        roleInfo.setForbidden(forbidden);
        if (forbidden)
        {
            if (method == null)
            {
                mappings.clear();
                mappings.put(null,roleInfo);
            }
        }
        else
        {
            UserDataConstraint userDataConstraint = UserDataConstraint.get(constraint.getDataConstraint());
            roleInfo.setUserDataConstraint(userDataConstraint);
            roleInfo.setProxyMode(constraint.isProxyMode());

            boolean checked = constraint.getAuthenticate();
            roleInfo.setChecked(checked);
            if (roleInfo.isChecked())
            {
                if (constraint.isAnyRole())
                {
                    if (_strict)
                    {
                        // * means "all defined roles"
                        for (String role : _roles)
                            roleInfo.addRole(role);
                    }
                    else
                        // * means any role
                        roleInfo.setAnyRole(true);
                }
                else
                {
                    String[] newRoles = constraint.getRoles();
                    for (String role : newRoles)
                    {
                        if (_strict &&!_roles.contains(role))
                            throw new IllegalArgumentException("Attempt to use undeclared role: " + role + ", known roles: " + _roles);
                        roleInfo.addRole(role);
                    }
                }
            }
            if (method == null)
            {
                for (Map.Entry<String, RoleInfo> entry : mappings.entrySet())
                {
                    if (entry.getKey() != null)
                    {
                        RoleInfo specific = entry.getValue();
                        specific.combine(roleInfo);
                    }
                }
            }
        }
	}

	@SuppressWarnings("unchecked")
	@Override
    public void dump(Appendable out,String indent) throws IOException
    {
        dumpThis(out);
        dump(out,indent,Arrays.asList(getBeans(),Collections.singleton(_roles),_servletsMap.entrySet()));
    }
}


text:
try:
    from . import generic as g
except BaseException:
    import generic as g

class CurvatureTest(g.unittest.TestCase):

    def test_gaussian_curvature(self):

        for radius in g.np.linspace(.25, 2.0, 10):
            m = g.trimesh.creation.icosphere(radius=radius)

            gauss = g.trimesh.curvature.discrete_gaussian_curvature_measure(
                mesh=m,
                points=m.vertices,
                radius=radius * 2.0) / (4 * g.np.pi)
            assert g.np.allclose(gauss, 1.0, atol=.01)

        # a torus should have approximately half its vertices with positive
        # curvature, and half with negative
        t = g.get_mesh('torus.STL')
        gauss = g.trimesh.curvature.discrete_gaussian_curvature_measure(
            mesh=t,
            points=t.vertices,
            radius=1.0)
        ratio = float((gauss < 0.0).sum()) / float(len(gauss))
        assert g.np.isclose(ratio, 0.5, atol=.2)

    def test_mean_curvature(self):
        m = g.trimesh.creation.icosphere()
        mean = g.trimesh.curvature.discrete_mean_curvature_measure(
            m,
            m.vertices,
            2.0) / (4 * g.np.pi)
        # Check mean curvature for unit sphere is 1.0
        assert g.np.allclose(mean, 1.0, atol=.01)

    def test_vertex_defect(self):
        # a subdivided box will only have corners and planar regions
        # so all vertex defects should be 0 or 90 degrees
        m = g.trimesh.primitives.Box().subdivide()
        assert g.np.logical_or(g.np.isclose(m.vertex_defects, 0.0),
                               g.np.isclose(m.vertex_defects, g.np.pi / 2.0)).all()

        assert len(m.vertex_defects) == len(m.vertices)

if __name__ == '__main__':
    g.trimesh.util.attach_to_log()
    g.unittest.main()