text:
package org.apache.dubbo.common.utils;

import org.junit.Test;

import java.util.ArrayList;
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 static org.apache.dubbo.common.utils.CollectionUtils.isEmpty;
import static org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty;
import static org.apache.dubbo.common.utils.CollectionUtils.toMap;
import static org.apache.dubbo.common.utils.CollectionUtils.toStringMap;
import static java.util.Collections.emptyList;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

public class CollectionUtilsTest {
    @Test
    public void testSort() throws Exception {
        List<Integer> list = new ArrayList<Integer>();
        list.add(100);
        list.add(10);
        list.add(20);

        List<Integer> expected = new ArrayList<Integer>();
        expected.add(10);
        expected.add(20);
        expected.add(100);

        assertEquals(expected, CollectionUtils.sort(list));
    }

    @Test
    public void testSortNull() throws Exception {
        assertNull(CollectionUtils.sort(null));

        assertTrue(CollectionUtils.sort(new ArrayList<Integer>()).isEmpty());
    }

    @Test
    public void testSortSimpleName() throws Exception {
        List<String> list = new ArrayList<String>();
        list.add("aaa.z");
        list.add("b");
        list.add(null);
        list.add("zzz.a");
        list.add("c");
        list.add(null);

        List<String> sorted = CollectionUtils.sortSimpleName(list);
        assertNull(sorted.get(0));
        assertNull(sorted.get(1));
    }

    @Test
    public void testSortSimpleNameNull() throws Exception {
        assertNull(CollectionUtils.sortSimpleName(null));

        assertTrue(CollectionUtils.sortSimpleName(new ArrayList<String>()).isEmpty());
    }

    @Test
    public void testSplitAll() throws Exception {
        assertNull(CollectionUtils.splitAll(null, null));
        assertNull(CollectionUtils.splitAll(null, "-"));

        assertTrue(CollectionUtils.splitAll(new HashMap<String, List<String>>(), "-").isEmpty());

        Map<String, List<String>> input = new HashMap<String, List<String>>();
        input.put("key1", Arrays.asList("1:a", "2:b", "3:c"));
        input.put("key2", Arrays.asList("1:a", "2:b"));
        input.put("key3", null);
        input.put("key4", new ArrayList<String>());

        Map<String, Map<String, String>> expected = new HashMap<String, Map<String, String>>();
        expected.put("key1", CollectionUtils.toStringMap("1", "a", "2", "b", "3", "c"));
        expected.put("key2", CollectionUtils.toStringMap("1", "a", "2", "b"));
        expected.put("key3", null);
        expected.put("key4", new HashMap<String, String>());

        assertEquals(expected, CollectionUtils.splitAll(input, ":"));
    }

    @Test
    public void testJoinAll() throws Exception {
        assertNull(CollectionUtils.joinAll(null, null));
        assertNull(CollectionUtils.joinAll(null, "-"));

        Map<String, List<String>> expected = new HashMap<String, List<String>>();
        expected.put("key1", Arrays.asList("1:a", "2:b", "3:c"));
        expected.put("key2", Arrays.asList("1:a", "2:b"));
        expected.put("key3", null);
        expected.put("key4", new ArrayList<String>());

        Map<String, Map<String, String>> input = new HashMap<String, Map<String, String>>();
        input.put("key1", CollectionUtils.toStringMap("1", "a", "2", "b", "3", "c"));
        input.put("key2", CollectionUtils.toStringMap("1", "a", "2", "b"));
        input.put("key3", null);
        input.put("key4", new HashMap<String, String>());

        Map<String, List<String>> output = CollectionUtils.joinAll(input, ":");
        for (Map.Entry<String, List<String>> entry : output.entrySet()) {
            if (entry.getValue() == null)
                continue;
            Collections.sort(entry.getValue());
        }

        assertEquals(expected, output);
    }

    @Test
    public void testJoinList() throws Exception {
        List<String> list = Arrays.asList();
        assertEquals("", CollectionUtils.join(list, "/"));

        list = Arrays.asList("x");
        assertEquals("x", CollectionUtils.join(list, "-"));

        list = Arrays.asList("a", "b");
        assertEquals("a/b", CollectionUtils.join(list, "/"));
    }

    @Test
    public void testMapEquals() throws Exception {
        assertTrue(CollectionUtils.mapEquals(null, null));
        assertFalse(CollectionUtils.mapEquals(null, new HashMap<String, String>()));
        assertFalse(CollectionUtils.mapEquals(new HashMap<String, String>(), null));

        assertTrue(CollectionUtils.mapEquals(CollectionUtils.toStringMap("1", "a", "2", "b"), CollectionUtils.toStringMap("1", "a", "2", "b")));
        assertFalse(CollectionUtils.mapEquals(CollectionUtils.toStringMap("1", "a"), CollectionUtils.toStringMap("1", "a", "2", "b")));
    }

    @Test
    public void testStringMap1() throws Exception {
        assertThat(toStringMap("key", "value"), equalTo(Collections.singletonMap("key", "value")));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testStringMap2() throws Exception {
        toStringMap("key", "value", "odd");
    }

    @Test
    public void testToMap1() throws Exception {
        assertTrue(CollectionUtils.toMap().isEmpty());

        Map<String, Integer> expected = new HashMap<String, Integer>();
        expected.put("a", 1);
        expected.put("b", 2);
        expected.put("c", 3);

        assertEquals(expected, CollectionUtils.toMap("a", 1, "b", 2, "c", 3));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testToMap2() throws Exception {
        toMap("a", "b", "c");
    }

    @Test
    public void testIsEmpty() throws Exception {
        assertThat(isEmpty(null), is(true));
        assertThat(isEmpty(new HashSet()), is(true));
        assertThat(isEmpty(emptyList()), is(true));
    }

    @Test
    public void testIsNotEmpty() throws Exception {
        assertThat(isNotEmpty(singleton("a")), is(true));
    }
}


text:
package org.jenkinsci.plugins.spoontrigger.commands.turbo;

import com.google.common.base.Optional;
import hudson.util.ArgumentListBuilder;
import org.jenkinsci.plugins.spoontrigger.commands.FilterOutputCommand;
import org.jenkinsci.plugins.spoontrigger.utils.Patterns;

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

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static org.jenkinsci.plugins.spoontrigger.Messages.REQUIRE_PRESENT_S;
import static org.jenkinsci.plugins.spoontrigger.Messages.REQUIRE_SINGLE_WORD_SP;

public final class PushCommand extends FilterOutputCommand {

    private PushCommand(ArgumentListBuilder argumentList) {
        super(argumentList);
    }

    public static CommandBuilder builder() {
        return new CommandBuilder();
    }

    public static final class CommandBuilder {

        private Optional<String> imageName = Optional.absent();
        private Optional<String> remoteImageName = Optional.absent();

        public CommandBuilder image(String image) {
            checkArgument(Patterns.isSingleWord(image), REQUIRE_SINGLE_WORD_SP, "image", image);

            this.imageName = Optional.of(image.trim());
            return this;
        }

        public CommandBuilder remoteImage(String image) {
            checkArgument(Patterns.isSingleWord(image), REQUIRE_SINGLE_WORD_SP, "image", image);

            this.remoteImageName = Optional.of(image.trim());
            return this;
        }

        public PushCommand build() {
            checkState(this.imageName.isPresent(), REQUIRE_PRESENT_S, "image");

            ArgumentListBuilder args = new ArgumentListBuilder(SPOON_CLIENT, "push", this.imageName.get());
            if (this.remoteImageName.isPresent()) {
                args.add(this.remoteImageName.get());
            }

            return new PushCommand(args);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * Get Enumeration over Java HashSet Example
 * This java example shows how to get Enumeration over Java HashSet using
 * enumeration method of Collections class. This example also shows how to
 * enumerate through elements of Java HashSet.
 *
 * @author Keeyana Jones <keeyanajones@yahoo.com>
 *
 **/
package javaproject.collections;

import java.util.Enumeration;
import java.util.HashSet;
import java.util.Collections;

public class GetEnumerationOverHashSet {

    public static void main(String[] args) {
        // create a HashSet object
        HashSet hashSet = new HashSet();

        // Add elements to HashSet
        hashSet.add("A");
        hashSet.add("B");
        hashSet.add("D");
        hashSet.add("E");
        hashSet.add("F");

        /**
         * Get Enumeration over Java HashSet object using,
         * static Enumeration enumeration(Collection c) method of
         * Collections class.
         *
         * This method returns the enumeration object over the specified
         * Collection.
         **/
        // get the Enumeration object
        Enumeration e = Collections.enumeration(hashSet);

        // enumerate through the HashSet elements
        System.out.println("Enumerating through Java HashSet");
        while(e.hasMoreElements())
            System.out.println(e.nextElement());
    }
}


text:
@implementation NetworkState
+ (void)WithSuccessBlock:(successBlock)success {
    [[self sharedManager] startMonitoring];
    [[self sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == 0) {
            success(false);
        }else if (status == 1){
            success(true);
        }else if (status == 2){
            success(true);
        }
    }];
}
@end


text:
url: /appliance/custom-domains
section: appliance
---

# Custom Domains

Beginning with Appliance Build 5XXX, you may configure custom domains using the Management Dashboard.

Custom domains allow you to expose one or more arbitrary DNS names for a tenant. Conventionally, Auth0 uses a three-part domain name for access, and it is the third portion of the domain name that varies depending on the tenant.

The root tenant authority (RTA) is a special domain that is configured when the cluster is first set up. It is a privileged tenant from which certain manage operations for the cluster are available. The RTA is sometimes called the configuration domain, and all users that have access to the Management Dashboard belong to an application in the RTA.

> All tenant domain names derive from the root tenant authority, and any changes to this will result in the deletion of all tenants.

### Use Example

Suppose that your RTA is `config.example.com`. From this point on, all of your new tenants' domain names must derive from the base name, `example.com`:

```text
site1.example.com
site2.example.com
```

However, you might want to expose other domain names to your end users, such as:

* `auth.site2.com`
* `auth.site1.com`
* `auth.site1.example.com`

You may do so by utilizing the Appliance's custom domains feature, which sets the domain used for authentication endpoints.

## Certificates Required for Custom Domains

Custom domains map one or more external DNS to a tenant that follows the standard naming convention.

Suppose that we have a tenant with the following domain:

`auth.example.com`

Suppose that we want the following domains to map to `auth.example.com`:

```text
auth.site1.example.com
auth.site2.com
```

Each of the custom domains (in this example, there are two) has its own certificate, which is stored separately.

## Configuring Custom Domains

You may configure custom domains for your tenants via the [custom domains set-up area](/appliance/dashboard/tenants#custom-domains) of the [tenants page in the Appliance configuration area](/appliance/dashboard/tenants).


text:
namespace StockSharp.Messages
{
	using System;
	using System.Linq;
	using System.Runtime.Serialization;

	/// <summary>
	/// The message contains information about strategy type.
	/// </summary>
	[DataContract]
	[Serializable]
	public class StrategyTypeMessage : Message, IOriginalTransactionIdMessage
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="StrategyTypeMessage"/>.
		/// </summary>
		public StrategyTypeMessage()
			: base(MessageTypes.StrategyType)
		{
		}

		/// <summary>
		/// Strategy type ID.
		/// </summary>
		[DataMember]
		public string StrategyTypeId { get; set; }

		/// <summary>
		/// Strategy name.
		/// </summary>
		[DataMember]
		public string StrategyName { get; set; }

		/// <inheritdoc />
		[DataMember]
		public long OriginalTransactionId { get; set; }

		/// <summary>
		/// Assembly.
		/// </summary>
		[DataMember]
		public byte[] Assembly { get; set; }

		/// <inheritdoc />
		public override string ToString()
		{
			return base.ToString() + $",Id={StrategyTypeId},Name={StrategyName},Asm={Assembly?.Length}";
		}

		/// <summary>
		/// Create a copy of <see cref="StrategyTypeMessage"/>.
		/// </summary>
		/// <returns>Copy.</returns>
		public override Message Clone()
		{
			return CopyTo(new StrategyTypeMessage());
		}

		/// <summary>
		/// Copy the message into the <paramref name="destination" />.
		/// </summary>
		/// <param name="destination">The object, to which copied information.</param>
		/// <returns>The object, to which copied information.</returns>
		protected StrategyTypeMessage CopyTo(StrategyTypeMessage destination)
		{
			base.CopyTo(destination);

			destination.StrategyName = StrategyName;
			destination.StrategyTypeId = StrategyTypeId;
			destination.OriginalTransactionId = OriginalTransactionId;
			destination.Assembly = Assembly?.ToArray();

			return destination;
		}
	}
}


text:
package org.elasticsearch.client.security;

import org.elasticsearch.common.Strings;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.EqualsHashCodeTestUtils;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;

public class InvalidateTokenRequestTests extends ESTestCase {

    public void testInvalidateAccessToken() {
        String token = "Tf01rrAymdUjxMY4VlG3gV3gsFFUWxVVPrztX+4uhe0=";
        final InvalidateTokenRequest request = InvalidateTokenRequest.accessToken(token);
        assertThat(request.getAccessToken(), equalTo(token));
        assertThat(request.getRefreshToken(), nullValue());
        assertThat(Strings.toString(request), equalTo("{\"token\":\"Tf01rrAymdUjxMY4VlG3gV3gsFFUWxVVPrztX+4uhe0=\"}"));
    }

    public void testInvalidateRefreshToken() {
        String token = "4rE0YPT/oHODS83TbTtYmuh8";
        final InvalidateTokenRequest request = InvalidateTokenRequest.refreshToken(token);
        assertThat(request.getAccessToken(), nullValue());
        assertThat(request.getRefreshToken(), equalTo(token));
        assertThat(Strings.toString(request), equalTo("{\"refresh_token\":\"4rE0YPT/oHODS83TbTtYmuh8\"}"));
    }

    public void testInvalidateRealmTokens() {
        String realmName = "native";
        final InvalidateTokenRequest request = InvalidateTokenRequest.realmTokens(realmName);
        assertThat(request.getAccessToken(), nullValue());
        assertThat(request.getRefreshToken(), nullValue());
        assertThat(request.getRealmName(), equalTo(realmName));
        assertThat(request.getUsername(), nullValue());
        assertThat(Strings.toString(request), equalTo("{\"realm_name\":\"native\"}"));
    }

    public void testInvalidateUserTokens() {
        String username = "user";
        final InvalidateTokenRequest request = InvalidateTokenRequest.userTokens(username);
        assertThat(request.getAccessToken(), nullValue());
        assertThat(request.getRefreshToken(), nullValue());
        assertThat(request.getRealmName(), nullValue());
        assertThat(request.getUsername(), equalTo(username));
        assertThat(Strings.toString(request), equalTo("{\"username\":\"user\"}"));
    }

    public void testInvalidateUserTokensInRealm() {
        String username = "user";
        String realmName = "native";
        final InvalidateTokenRequest request = new InvalidateTokenRequest(null, null, realmName, username);
        assertThat(request.getAccessToken(), nullValue());
        assertThat(request.getRefreshToken(), nullValue());
        assertThat(request.getRealmName(), equalTo(realmName));
        assertThat(request.getUsername(), equalTo(username));
        assertThat(Strings.toString(request), equalTo("""
            {"realm_name":"native","username":"user"}"""));
    }

    public void testEqualsAndHashCode() {
        final String token = randomAlphaOfLength(8);
        final boolean accessToken = randomBoolean();
        final InvalidateTokenRequest request = accessToken
            ? InvalidateTokenRequest.accessToken(token)
            : InvalidateTokenRequest.refreshToken(token);
        final EqualsHashCodeTestUtils.MutateFunction<InvalidateTokenRequest> mutate = r -> {
            int randomCase = randomIntBetween(1, 4);
            switch (randomCase) {
                case 1:
                    return InvalidateTokenRequest.refreshToken(randomAlphaOfLength(5));
                case 2:
                    return InvalidateTokenRequest.accessToken(randomAlphaOfLength(5));
                case 3:
                    return InvalidateTokenRequest.realmTokens(randomAlphaOfLength(5));
                case 4:
                    return InvalidateTokenRequest.userTokens(randomAlphaOfLength(5));
                default:
                    return new InvalidateTokenRequest(null, null, randomAlphaOfLength(5), randomAlphaOfLength(5));
            }
        };
        EqualsHashCodeTestUtils.checkEqualsAndHashCode(
            request,
            r -> new InvalidateTokenRequest(r.getAccessToken(), r.getRefreshToken()),
            mutate
        );
    }
}


text:
package com.sparkweb.validation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sparkweb.i18n.ResourceBundleLocator;
import com.sparkweb.validation.constraint.Required;

/**
 * JavaBean验证器
 *
 * @author yswang
 * @version 1.0
 */
public final class BeanValidator
{
	/**
	 * 验证JavaBean
	 *
	 * @param bean 需要验证的JavaBean对象
	 * @param fields 需要可能指定验证的Bean字段
	 * @return 验证结果
	 */
	@SuppressWarnings("unchecked")
	public final static <T> ConstraintViolation<T>[] validate(T bean, String...fields)
	{
		if(bean == null)
		{
			throw new ValidationException("Validated JavaBean object can not be null!");
		}

		if(bean.getClass() == Object.class)
		{
			return new ConstraintViolation[0];
		}

		FieldContext[] fieldContexts = ValidationContextCache.getConstraintFieldContexts(bean.getClass());
		if(fieldContexts == null || fieldContexts.length == 0)
		{
			return new ConstraintViolation[0];
		}

		// 对指定的field进行提取
		FieldContext[] needFieldContexts = null;
		if(fields != null && fields.length > 0)
		{
			needFieldContexts = new FieldContext[fields.length];
			int i = 0;
			boolean fExist = false; // 检测指定的field是否存在于给定的Bean中

			for(String f : fields)
			{
				if(f == null || f.trim().length() == 0)
				{
					continue;
				}

				fExist = false;
				for(FieldContext fc : fieldContexts)
				{
					if(fc.getField().getName().equals(f))
					{
						needFieldContexts[i++] = fc;
						fExist = true;
						break;
					}
				}

				if(!fExist)
				{
					throw new ValidationException("The field `"+ f +"` is not exists in constraint fields of `"+ bean.getClass().getName() +"`!");
				}
			}

			// 指定的field都为null或空,则指定无效,验证全部
			if(i == 0)
			{
				needFieldContexts = fieldContexts;
			}
		}
		else {
			needFieldContexts = fieldContexts;
		}

		List<ConstraintViolation<T>> violations = new ArrayList<ConstraintViolation<T>>(needFieldContexts.length);
		ConstraintViolation<T> fcv = null;

		for(FieldContext fc : needFieldContexts)
		{
			fcv = validateFieldContext(bean, fc);

			if(fcv != null)
			{
				violations.add(fcv);
			}
		}

		return violations.toArray(new ConstraintViolation[violations.size()]);
	}

	/**
	 * 验证字段值
	 *
	 * @param bean
	 * @return
	 */
	private final static <T> ConstraintViolation<T> validateFieldContext(T bean, FieldContext fc)
	{
		if(fc == null)
		{
			return null;
		}

		ConstraintViolation<T> violation = null;

		Object fieldValue = getFieldValue(bean, fc.getFieldMethod());

		// 首先验证其是否是Required
		Annotation requiredConstraint = fc.getRequiredConstraint();
		if(requiredConstraint != null)
		{
			violation = validateField(bean, fc.getField(), fieldValue, requiredConstraint);
			if(violation != null)
			{
				return violation;
			}
		}

		// 验证其它规则
		for(Annotation otherConstraint : fc.getConstraints())
		{
			// 不再处理Required
			if(otherConstraint.annotationType() == Required.class)
			{
				continue;
			}

			violation = validateField(bean, fc.getField(), fieldValue, otherConstraint);
			if(violation != null)
			{
				return violation;
			}
		}

		return null;
	}

	private final static <T> ConstraintViolation<T> validateField(T bean, Field field, Object fieldValue, Annotation constraintAnno)
	{
		boolean isValid = true;
		// 获取该注解验证规则上的所有验证器,并依次进行调用验证
		ConstraintValidator[] validators = ValidationContextCache.getConstraintValidators(constraintAnno);
		if(validators == null || validators.length == 0)
		{
			return null;
		}

		for(ConstraintValidator validator : validators)
		{
			if(validator == null)
			{
				continue;
			}

			isValid &= validator.isValid(bean, fieldValue, constraintAnno, field);
			if(!isValid)
			{
				return new ConstraintViolation<T>(bean, field.getName(), fieldValue, getMessage(constraintAnno));
			}
		}

		return null;
	}

	private final static <T> Object getFieldValue(T bean, Method fieldMethod)
	{
		if(fieldMethod == null)
		{
			return null;
		}

		try
		{
			return fieldMethod.invoke(bean);
		} catch(Exception e)
		{
			return null;
		}
	}

	private final static String getMessage(Annotation constraintAnno)
	{
		String msg = invokeAnnotationMethod(constraintAnno, "message");
		if(msg == null || msg.length() == 0)
		{
			return "";
		}

		String _msg = ValidationResourceBundle.getBundleMessage(msg);
		if(_msg != null && _msg.trim().length() > 0)
		{
			msg = _msg;
		}

		String[] params = ResourceBundleLocator.parseStringParameters(msg);
		if(params == null || params.length == 0)
		{
			return msg;
		}

		Map<String, String> valueMap = new HashMap<String, String>(params.length);
		for(String param : params)
		{
			valueMap.put(param, invokeAnnotationMethod(constraintAnno, param));
		}

		return ResourceBundleLocator.formatString(msg, valueMap);
	}

	private final static String invokeAnnotationMethod(Annotation constraintAnno, String methodName)
	{
		Method method = null;
		try
		{
			method = constraintAnno.annotationType().getDeclaredMethod(methodName, (Class<?>[]) null);
			// 跳过java的安全检查,提升反射调用性能
			method.setAccessible(true);

			if(Modifier.isPublic(method.getModifiers()))
			{
				return method.invoke(constraintAnno, (Object[]) null).toString();
			}

		} catch(SecurityException e)
		{
			e.printStackTrace();
		} catch(NoSuchMethodException e)
		{
			e.printStackTrace();
		} catch(IllegalArgumentException e)
		{
			e.printStackTrace();
		} catch(IllegalAccessException e)
		{
			e.printStackTrace();
		} catch(InvocationTargetException e)
		{
			e.printStackTrace();
		}

		return null;
	}

	// 私有构造器,不允许外部new
	private BeanValidator() {
		throw new IllegalAccessError("New instance of BeanValidator is not allowed!");
	}

}


text:
attribution-sujet
=================

Site Web pour gerer l'attribution de sujets


text:
<?php
/**
 * @link       http://zoopcommerce.github.io/common
 * @package    Zoop
 * @license    MIT
 */
namespace Zoop\Common\User;

/**
 * May be used in conjunction with the IdentityInterface to give an identity roles
 *
 * @since   1.0
 * @author  Tim Roediger <superdweebie@gmail.com>
 */
interface RoleAwareUserInterface
{
    /**
     * Set all the roles for a identity - overwrites all existing
     *
     * @param array $roles array of strings
     */
    public function setRoles(array $roles);

    /**
     * Get the complete roles array
     *
     * @return array
     */
    public function getRoles();

    /**
     * Add a single role
     *
     * @param string $role
     */
    public function addRole($role);

    /**
     * Remove a single role
     *
     * @param string $role
     */
    public function removeRole($role);

    /**
     * Check if an identity has the supplied role
     *
     * @param string $role
     * @return boolean
     */
    public function hasRole($role);
}


text:
layout: docs
header: true
seotitle: Annotation Lab | John Snow Labs
title: Annotation Lab Release Notes 3.3.0
permalink: /docs/en/alab/annotation_labs_releases/release_notes_3_3_0
key: docs-licensed-release-notes
modify_date: 2022-06-21
show_nav: true
sidebar:
    nav: annotation-lab
---

## 3.3.0

Release date: **21-06-2022**

We are very excited to announce the release of Annotation Lab v3.3.0 which includes a highly requested new feature for displaying the confidence scores for NER preannotations as well as the ability to filter preannotations by confidence. Also, benchmarking data can now be checked for some of the models on the Models Hub page. This version also includes IAA charts for Visual NER Projects, upgrades of the Spark NLP libraries and fixes for some of the identified Common Vulnerabilities and Exposures (CVEs). Below are more details on the release content.

### Highlights

- Confidence Scores for Preannotations, When running preannotations on a Text project, one extra piece of information is now present for the automatic annotations - the confidence score. This score is used to show the confidence the model has for each of the labeled chunks. It is calculated based on the benchmarking information of the model used to preannotate and on the score of each prediction. The confidence score is available when working on Named Entity Recognition, Relation, Assertion, and Classification projects and is also generated when using NER Rules. On the Labeling screen, when selecting the Prediction widget, users can see that all preannotation in the Results section now have a score assigned to them.
- IAA charts are now available for Visual NER Projects, IAA (Inter-Annotator Agreement) charts were available only for text-based projects. With this release, Annotation Lab supports IAA charts for Visual NER project as well.
- Auto-save completions, the work of annotators is automatically saved behind the scenes. This way, the user does not risk losing his/her work in case of unforeseen events and does not have to frequently hit the Save/Update button.
- Improvement of UX for Active Learning, information about the previously triggered Active learning is displayed along with the number of completions required for the next training. Also when the conditions that trigger active learning for a project using a healthcare model are met and all available licenses are in use, an error message appears on the Training and Active Learning page informing the user to make room for the new training server
- Support for BertForSequenceClassification and MedicalBertForSequenceClassification models, From this version on, support was added for BertForTokenClassification, MedicalBertForTokenClassifier, BertForSequenceClassification and MedicalBertForSequenceClassification.
- Upgraded Spark NLP and Spark NLP for Health Care v3.5.3 and Spark OCR v3.13.0. With this we have also updated the list of supported models into the Models Hub page.

## Versions

3.3.1

3.3.0

3.2.0

3.1.1

3.1.0

3.0.1

3.0.0

2.8.0

2.7.2

2.7.1

2.7.0

2.6.0

2.5.0

2.4.0

2.3.0

2.2.2

2.1.0

2.0.1


text:
package com.appdirect.sdk.credentials;

import static com.appdirect.sdk.appmarket.Credentials.invalidCredentials;

import java.util.Map;

import com.appdirect.sdk.appmarket.Credentials;
import com.appdirect.sdk.appmarket.DeveloperSpecificAppmarketCredentialsSupplier;

/**
 * Creates an in-memory cache of (developer key ⟶ developer secret) pairs from a string of the following format:
 * <p>
 * devKey1:devPassword1,devKey2:devPassTwo
 * @deprecated will be replaced by {@link SourceBackedCredentialsSupplier}
 */
@Deprecated
public class StringBackedCredentialsSupplier implements DeveloperSpecificAppmarketCredentialsSupplier {
	private final Map<String, String> allowedCredentials;

	public StringBackedCredentialsSupplier(String rawAllowedCredentials) {
		this.allowedCredentials = MapBuilderUtils.fromCommaDelimitedKeyValuePairs(rawAllowedCredentials);
	}

	@Override
	public Credentials getConsumerCredentials(String consumerKey) {
		String secret = allowedCredentials.get(consumerKey);
		return secret == null ? invalidCredentials() : new Credentials(consumerKey, secret);
	}
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../openssl_sys/constant.X509_V_ERR_NO_EXPLICIT_POLICY.html">

Redirecting to ../../openssl_sys/constant.X509_V_ERR_NO_EXPLICIT_POLICY.html...


text:
//
//  constants.h
//  Shan.Net
//
//  Created by Sung Han Park on 2017. 3. 16..
//  Copyright © 2017 Sung Han Park. All rights reserved.
//

#ifndef shan_net_constants_h
#define shan_net_constants_h

namespace shan {
namespace net {

class protocol {
public:
	class tcp {};
	class udp {};
};

enum class ip {
	v4,
	v6
};

const int DEFAULT_BACKLOG = asio::socket_base::max_connections;
const uint16_t ANY_PORT = 0;

using streambuf_pool = util::static_pool<util::streambuf>;

#ifdef SHAN_NET_SSL_ENABLE
enum ssl_method {
	SSLV2         = asio::ssl::context::method::sslv2,         // Generic SSL version 2.
	SSLV2_CLIENT  = asio::ssl::context::method::sslv2_client,  // SSL version 2 client.
	SSLV2_SERVER  = asio::ssl::context::method::sslv2_server,  // SSL version 2 server.
	SSLV3         = asio::ssl::context::method::sslv3,         // Generic SSL version 3.
	SSLV3_CLIENT  = asio::ssl::context::method::sslv3_client,  // SSL version 3 client.
	SSLV3_SERVER  = asio::ssl::context::method::sslv3_server,  // SSL version 3 server.
	TLSV1         = asio::ssl::context::method::tlsv1,         // Generic TLS version 1.
	TLSV1_CLIENT  = asio::ssl::context::method::tlsv1_client,  // TLS version 1 client.
	TLSV1_SERVER  = asio::ssl::context::method::tlsv1_server,  // TLS version 1 server.
	SSLV23        = asio::ssl::context::method::sslv23,        // Generic SSL/TLS.
	SSLV23_CLIENT = asio::ssl::context::method::sslv23_client, // SSL/TLS client.
	SSLV23_SERVER = asio::ssl::context::method::sslv23_server, // SSL/TLS server.
	TLSV11        = asio::ssl::context::method::tlsv11,        // Generic TLS version 1.1.
	TLSV11_CLIENT = asio::ssl::context::method::tlsv11_client, // TLS version 1.1 client.
	TLSV11_SERVER = asio::ssl::context::method::tlsv11_server, // TLS version 1.1 server.
	TLSV12        = asio::ssl::context::method::tlsv12,        // Generic TLS version 1.2.
	TLSV12_CLIENT = asio::ssl::context::method::tlsv12_client, // TLS version 1.2 client.
	TLSV12_SERVER = asio::ssl::context::method::tlsv12_server  // TLS version 1.2 server.
};

using ssl_option = unsigned long;
enum {
	DEF_OPT       = asio::ssl::context::default_workarounds, // Implement various bug workarounds.
	SINGLE_DH_USE = asio::ssl::context::single_dh_use,       // Always create a new key when using tmp_dh parameters.
	NO_SSLV2      = asio::ssl::context::no_sslv2,            // Disable SSL v2.
	NO_SSLV3      = asio::ssl::context::no_sslv3,            // Disable SSL v3.
	NO_TLSV1      = asio::ssl::context::no_tlsv1,            // Disable TLS v1.
	NO_TLSV1_1    = asio::ssl::context::no_tlsv1_1,          // Disable TLS v1.1.
	NO_TLSV1_2    = asio::ssl::context::no_tlsv1_2,          // Disable TLS v1.2.
//	NO_COMPRESSION = asio::ssl::context::no_compression      // Disable compression. Compression is disabled by default.
};

enum ssl_verify_mode {
	VERIFY_NONE                 = asio::ssl::context::verify_none,                 // No verification.
	VERIFY_PEER                 = asio::ssl::context::verify_peer,                 // Verify the peer.
	VERIFY_FAIL_IF_NO_PEER_CERT = asio::ssl::context::verify_fail_if_no_peer_cert, // Fail verification if the peer has no certificate. Ignored unless VERIFY_PEER is set.
	VERIFY_CLIENT_ONCE          = asio::ssl::context::verify_client_once           // Do not request client certificate on renegotiation. Ignored unless VERIFY_PEER is set.
};

enum ssl_file_format {
	ASN1 = asio::ssl::context::file_format::asn1, // ASN.1 file.
	PEM  = asio::ssl::context::file_format::pem,  // PEM file.
};

enum ssl_password_purpose {
	FOR_READING, // The password is needed for reading/decryption.
	FOR_WRITING // The password is needed for writing/encryption.
};

using verify_callback = bool(bool preverified, X509_STORE_CTX* ctx);
using password_callback = std::string(std::size_t max_length, ssl_password_purpose purpose);
#endif

} // namespace net
} // namespace shan

#endif /* shan_net_constants_h */


text:
namespace sl
{
	ShaderLibrary::ShaderLibrary(const std::string& script)
	{
		std::string fullPath = Locator::world->m_scriptFolderPath + script;
		Locator::lua->script(Locator::virtualFS->openAsString(fullPath));
		sol::table shaders = Locator::lua->get<sol::table>("shaders");

		if (!shaders.empty())
		{
			// Iterate over each shader in the lua table and construct it in place.
			shaders.for_each([this](std::pair<sol::object, sol::object> pair)
			{
				m_resourceMap.emplace(entt::HashedString(pair.first.as<const char*>()), pair.second.as<sol::table>());
			});
		}
		else
		{
			LOG_S(WARNING) << "Loaded empty shader table for script: " << script;
		}
	}

	ShaderLibrary::~ShaderLibrary()
	{
		// See clean().
		clean();
	}

	void ShaderLibrary::clean()
	{
		// Shader objects are wrapped in classes so destructors handle cleaning of object data.
		m_resourceMap.clear();
	}
}


text:
module TemplateHelper

  def build_template(nbr_phases = 0, nbr_sections = 0, nbr_questions = 0)
    template = create(:template, phases: nbr_phases)

    template.phases.each do |phase|
      nbr_sections.times do
        section = create(:section, phase: phase)
        nbr_questions.times do
          create(:question, section: section)
        end
      end
    end
    template
  end

end


text:
require 'rubygems'
require 'rubyhaze'

class Person1

  java_import 'com.hazelcast.nio.DataSerializable'
  include DataSerializable

  attr_accessor :name, :age

  def initialize(name, age)
    self.name, self.age = name, age
  end

  def write_data(output)
    output.write_utf name
    output.write_int age
  end

  def read_data(input)
    self.name = input.read_utf
    self.age = input.read_int
  end

end

class Person2

  java_import 'java.io.Serializable'
  include Serializable

  attr_accessor :name, :age

  def initialize(name, age)
    self.name, self.age = name, age
  end

  def write_object(output)
    output.write_utf name
    output.write_int age
  end

  def read_object(input)
    self.name = input.read_utf
    self.age = input.read_int
  end

end

def lbl(msg)
  puts "-"*120
  puts msg
end

lbl "Creating distributed hash..."
hash = RubyHaze::Hash[:test]

lbl "Creating person 1 [com.hazelcast.nio.DataSerializable]"
p1 = Person1.new "Tester1", 30
lbl "Person 1 : #{p1.inspect}"
lbl "Creating person 2 [java.io.Serializable]"
p2 = Person2.new "Tester2", 40
lbl "Person 2 : #{p2.inspect}"

lbl "Saving person 1"
hash[:p1] = p1
lbl "Saving person 2"
hash[:p2] = p2

lbl "Retrieving person 1b"
p1b = hash[:p1]
lbl "Person 1b : #{p1b.inspect}"
lbl "Retrieving person 2b"
p2b = hash[:p2]
lbl "Person 2b : #{p2b.inspect}"

lbl "THE END"


text:
package com.github.xdcrafts.swarm.util;

/**
 * Utility functions for arrays.
 */
public final class ArrayUtils {

    private ArrayUtils() {
    }

    /**
     * Just wrapper for infinite argument semantics.
     * @param <T> values type
     * @param ts variadic parameters
     * @return array of type T
     */
    public static <T> T[] asArray(T... ts) {
        return ts;
    }
}


text: Rails.application.config.session_store :active_record_store, :key => '_monsoon-dashboard_session'


text: module.exports = "I am simple lib.";


text:
//Tarun Nimmagadda
//The University of Texas, Austin

//This file defines the RNDF structure as specified by the DARPA
//specification.  It parses the RNDF file into the RNDF data structure

#include <cstdio>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>
#include <cstdlib>
#include <conversions.h>
#include <epsilon.h>
#include <rndf_visualizer/RNDF.h>

#include <limits.h>
#include <stdio.h>

#define DEFAULT_LANE_WIDTH 3
#define DEFAULT_SPOT_WIDTH 3
#define DEFAULT_LANE_SPEED mph2mps(30)

enum RNDF_PARSE_STATE {COMMENT, GENERAL, SEGMENTS, LANES,
		       ZONES, PERIMETER, PARKING_SPOT, UNKNOWN};

enum MDF_PARSE_STATE {MDF_COMMENT, MDF_GENERAL, MDF_CHECKPOINTS,
		      MDF_SPEEDLIMITS, MDF_UNKNOWN};

template <class T>
void change_state(T& previous_state, T& current_state, const T new_state){
  previous_state = current_state;
  current_state = new_state;
};

RNDF::RNDF(std::string rndfname, bool verbose)
{
  number_of_segments = number_of_zones = -1;
  is_valid=true;

  std::ifstream rndf_file;
  rndf_file.open(rndfname.c_str());
  if (!rndf_file)
    {
      std::cout << "Error opening RNDF \"" << rndfname << "\"";
      is_valid = false;
      return;
    }

  //Parser State
  line_number = 0;
  RNDF_PARSE_STATE state = UNKNOWN, previous_state = UNKNOWN;

  Segment temp_segment;
  Lane temp_lane;
  Zone temp_zone;
  Perimeter temp_perimeter;
  Spot temp_spot;
  //Clear temp variables
  temp_segment.clear();
  temp_lane.clear();
  temp_zone.clear();
  temp_perimeter.clear();
  temp_spot.clear();

  std::string lineread;
  while(getline(rndf_file, lineread)) // Read line by line
    {
      line_number++;
      uint real_characters=0;

      for (uint ind=0; ind < lineread.length(); ind++)
	if (lineread[ind] != '\r' &&
	    lineread[ind] != '\t' &&
	    lineread[ind] != ' ')
	  real_characters++;

      //Blank lines
      if (real_characters == 0) {
	if (verbose)
	  printf("%d: Blank Line\n",line_number);
	continue;
      }

      std::string token;
      char token_char [lineread.size()+1];
      char temp_char [lineread.size()+1];

      //Read in one line
      sscanf(lineread.c_str(), "%s", token_char);
      token.assign(token_char);

      //      printf("Token: |%s|\n", token.c_str());

      if (state != COMMENT){
	if (token.compare("RNDF_name") == 0)
	  change_state(previous_state, state, GENERAL);
	else if (token.compare("segment") == 0)
	  change_state(previous_state, state, SEGMENTS);
	else if (token.compare("lane") == 0)
	  change_state(previous_state, state, LANES);
	else if (token.compare("zone") == 0)
	  change_state(previous_state, state, ZONES);
	else if (token.compare("perimeter") == 0)
	  change_state(previous_state, state, PERIMETER);
	else if (token.compare("spot") == 0)
	  change_state(previous_state, state, PARKING_SPOT);
	else if (token.find("/*") != std::string::npos)
	  change_state(previous_state, state, COMMENT);
      }

      bool valid=true;
      switch (state){
      case COMMENT:
	if (verbose)
	  printf("%d: COMMENT: %s\n", line_number, lineread.c_str());
	if (lineread.find("*/") != std::string::npos)
	  state = previous_state;
	break;
      case GENERAL:
	//RNDF_NAME
	if (token.compare("RNDF_name") == 0)
	  filename =
	    parse_string(lineread, std::string("RNDF_name"),
			 line_number, valid, verbose);
	//NUM_SEGMENTS
	else if (token.compare("num_segments") == 0){
	  number_of_segments =
	    parse_integer(lineread, std::string("num_segments"),
			  line_number, valid, verbose);
	  if (number_of_segments <= 0) valid = false;
	}
	//NUM_ZONES
	else if (token.compare("num_zones") == 0){
	  number_of_zones =
	    parse_integer(lineread, std::string("num_zones"),
			  line_number, valid, verbose);
	  if (number_of_zones < 0) valid = false;
	}
	//FORMAT_VERSION
	else if (token.compare("format_version") == 0)
	  format_version =
	    parse_string(lineread, std::string("format_version"),
			 line_number, valid, verbose);
	//CREATION_DATE
	else if (token.compare("creation_date") == 0)
	  creation_date =
	    parse_string(lineread, std::string("creation_date"),
			 line_number, valid, verbose);
	//END_FILE
	else if (token.compare("end_file") == 0){
	  if (!isvalid())
	    valid = false;
	  else if (verbose)
	    printf("%d: RNDF file has finished parsing\n", line_number);
	}
	//printf("Token: |%s|\n", token.c_str());
	else {
	  printf("%d: Unexpected token\n", line_number);
	  valid=false;
	}
	break;
      case SEGMENTS:
	//SEGMENT
	if(token.compare("segment") == 0){
	  temp_segment.segment_id =
	    parse_integer(lineread, std::string("segment"),
			  line_number, valid, verbose);
	  if (temp_segment.segment_id <= 0) valid = false;
	}
	//NUM_LANES
	else if(token.compare("num_lanes") == 0){
	  temp_segment.number_of_lanes =
	    parse_integer(lineread, std::string("num_lanes"),
			  line_number, valid, verbose);
	  if (temp_segment.number_of_lanes <= 0) valid = false;
	}
	//SEGMENT_NAME
	else if(token.compare("segment_name") == 0)
	  temp_segment.segment_name =
	    parse_string(lineread, std::string("segment_name"),
			 line_number, valid, verbose);
	//END_SEGMENT
	else if(token.compare("end_segment") == 0){
	  if (!temp_segment.isvalid())
	    valid = false;
	  else{
	  	if(alreadyExists(temp_segment)) {
	  		std::cerr << "Error. Duplicate segment. Id: " << temp_segment.segment_id << std::endl;
			valid = false;
	  	}
	  	else{
		    segments.push_back(temp_segment);
		    if (verbose)
		      printf("%d: segment has ended\n", line_number);
		    change_state(previous_state, state, GENERAL);
		    temp_segment.clear();
	  	}
	  }
	}
	else{
	  printf("%d: Unexpected token\n", line_number);
	  valid=false;
	}
	break;
      case LANES:
	//LANE
	if(token.compare("lane") == 0){
	  sprintf(temp_char, "lane %d.%%d", temp_segment.segment_id);
	  if (sscanf(lineread.c_str(), temp_char, &temp_lane.lane_id) == 1){
	    if (verbose)
	      printf("%d: Lane number is %d\n",
		     line_number, temp_lane.lane_id);
	  }
	  else valid=false;
	  if (temp_lane.lane_id <= 0) valid = false;
	}
	//NUM_WAYPOINTS
	else if(token.compare("num_waypoints") == 0){
	  temp_lane.number_of_waypoints =
	    parse_integer(lineread, std::string("num_waypoints"),
			  line_number, valid, verbose);
	  if (temp_lane.number_of_waypoints <= 0) valid = false;
	}
	//LANE_WIDTH
	else if(token.compare("lane_width") == 0){
	  temp_lane.lane_width =
	    parse_integer(lineread, std::string("lane_width"),
			  line_number, valid, verbose);
	  if (temp_lane.lane_width <= 0) valid = false;
	}
	//LEFT_BOUNDARY
	else if(token.compare("left_boundary") == 0){
	  temp_lane.left_boundary =
	    parse_boundary(lineread, valid);
	  if (verbose)
	    printf("%d: left boundary type is %d\n",
		   line_number, temp_lane.left_boundary);
	}
	//RIGHT_BOUNDARY
	else if(token.compare("right_boundary") == 0){
	  temp_lane.right_boundary =
	    parse_boundary(lineread, valid);
	  if (verbose)
	    printf("%d: right boundary type is %d\n",
		   line_number, temp_lane.right_boundary);
	}
	//CHECKPOINT
	else if(token.compare("checkpoint") == 0){
	  Checkpoint checkpoint(lineread, temp_segment.segment_id,
				temp_lane.lane_id, line_number, valid, verbose);
	  if(alreadyExists(temp_lane, checkpoint)) {
		std::cerr << "Error. Duplicate checkpoint. Id: " << temp_segment.segment_id << temp_lane.lane_id << checkpoint.waypoint_id << std::endl;
		valid = false;
	  }
	  else {
	  	temp_lane.checkpoints.push_back(checkpoint);
	  }
	}
	//STOP
	else if(token.compare("stop") == 0){
	  Stop stop(lineread, temp_segment.segment_id,
		    temp_lane.lane_id, line_number, valid, verbose);
	  if(alreadyExists(temp_lane, stop)) {
		std::cerr << "Error. Duplicate stop. Id: " << temp_segment.segment_id << temp_lane.lane_id << stop.waypoint_id << std::endl;
		valid = false;
	  }
	  else{
	  	temp_lane.stops.push_back(stop);
	  }
	}
	//EXIT
	else if(token.compare("exit") == 0){
	  Exit exit(lineread, temp_segment.segment_id,
		    temp_lane.lane_id, line_number, valid, verbose);
	  if(alreadyExists(temp_lane, exit)) {
		std::cerr << "Error. Duplicate exit. Id: " << temp_segment.segment_id << temp_lane.lane_id << std::endl;
		valid = false;
	  }
	  else{
	  	temp_lane.exits.push_back(exit);
	  }
	}
	//END_LANE
	else if(token.compare("end_lane") == 0){
	  if(temp_lane.number_of_waypoints != (int)temp_lane.waypoints.size())
	    printf("Number of waypoints in lane does not match num_waypoints\n");
	  if (!temp_lane.isvalid())
	    valid = false;
	  else{
	  	if(alreadyExists(temp_segment, temp_lane)) {
	  		std::cerr << "Error. Duplicate lane. Id: " << temp_segment.segment_id << "." << temp_lane.lane_id << std::endl;
			valid = false;
	  	}
	  	else {
		    temp_segment.lanes.push_back(temp_lane);
		    if (verbose)
		      printf("%d: lane has ended\n", line_number);
		    change_state(previous_state, state, SEGMENTS);
		    temp_lane.clear();
	  	}
	  }
	}

	//NO TOKEN
	else{
	  //WAYPOINT
	  sprintf(temp_char, "%d.%d.", temp_segment.segment_id,
		  temp_lane.lane_id);
	  if(token.find(temp_char) != std::string::npos ){
	    LL_Waypoint wp(lineread, temp_segment.segment_id,
			   temp_lane.lane_id, line_number, valid, verbose);
	    if(alreadyExists(temp_lane, wp)){
	  		std::cerr << "Error. Duplicate waypoint. Id: " << temp_segment.segment_id << "." << temp_lane.lane_id << "." << wp.waypoint_id << std::endl;
			valid = false;
	    }
	    else {
	    	temp_lane.waypoints.push_back(wp);
	    }
	  }
	  else{
	    printf("%d: Unexpected token\n", line_number);
	    valid=false;
	  }
	}
	break;
      case ZONES:
	//ZONE
	if(token.compare("zone") == 0){
	  temp_zone.zone_id =
	    parse_integer(lineread, std::string("zone"),
			  line_number, valid, verbose);
	  if (temp_zone.zone_id <= 0) valid = false;

	}
	//NUM_SPOTS
	else if(token.compare("num_spots") == 0){
	  temp_zone.number_of_parking_spots =
	    parse_integer(lineread, std::string("num_spots"),
			  line_number, valid, verbose);
	  if (temp_zone.number_of_parking_spots < 0) valid = false;
	}
	//ZONE_NAME
	else if(token.compare("zone_name") == 0)
	  temp_zone.zone_name =
	    parse_string(lineread, std::string("zone_name"),
			 line_number, valid, verbose);
	//END_ZONE
	else if(token.compare("end_zone") == 0){
	  if(!temp_zone.isvalid())
	    valid = false;
	  else{
	  	if(alreadyExists(temp_zone)) {
	  		std::cerr << "Duplicate zone. Id: " << temp_zone.zone_id << std::endl;
	  		valid = false;
	  	}
	  	else {
		    zones.push_back(temp_zone);
		    if (verbose)
		      printf("%d: zone has ended\n", line_number);
		    change_state(previous_state, state, GENERAL);
		    temp_zone.clear();
	  	}
	  }
	}
	else {
	  printf("%d: Unexpected token\n", line_number);
	  valid=false;
	}
	break;
      case PERIMETER:
	//PERIMETER
	if(token.compare("perimeter") == 0){
	  sprintf(temp_char,"perimeter %d.%%d" , temp_zone.zone_id);
	  if (sscanf(lineread.c_str(), temp_char,
		     &temp_perimeter.perimeter_id) == 1){
	    if (verbose)
	      printf("%d: Perimeter id is %d\n",
		     line_number, temp_perimeter.perimeter_id);
	  }
	  else valid=false;
	  if (temp_perimeter.perimeter_id != 0)
	    valid = false;
	}
	//NUM_PERIMETER_POINTS
	else if(token.compare("num_perimeterpoints") == 0){
	  temp_perimeter.number_of_perimeterpoints =
	    parse_integer(lineread, std::string("num_perimeterpoints"),
			  line_number, valid, verbose);
	  if (temp_perimeter.number_of_perimeterpoints <= 0)
	    valid = false;
	}
	//EXIT
	else if(token.compare("exit") == 0){
	  Exit exit(lineread, temp_zone.zone_id, 0, line_number, valid,
		    verbose);
	  temp_perimeter.exits_from_perimeter.push_back(exit);
	}
	//END_PERIMETER
	else if(token.compare("end_perimeter") == 0){
	  if(!temp_perimeter.isvalid())
	    valid = false;
	  else{
	    temp_zone.perimeter = temp_perimeter;
	    if (verbose)
	      printf("%d: perimeter has ended\n", line_number);
	    change_state(previous_state, state, ZONES);
	    temp_perimeter.clear();
	  }
	}
	else{
	  //WAYPOINT
	  sprintf(temp_char, "%d.%d.", temp_zone.zone_id, 0);
	  if(token.find(temp_char) != std::string::npos ){
	    LL_Waypoint wp(lineread, temp_zone.zone_id, 0, line_number,
			   valid, verbose);
	    temp_perimeter.perimeterpoints.push_back(wp);
	  }
	  else valid=false;
	}
	break;
      case PARKING_SPOT:
	//SPOT
	if(token.compare("spot") == 0){
	  sprintf(temp_char,"spot %d.%%d" , temp_zone.zone_id);
	  if (sscanf(lineread.c_str(), temp_char, &temp_spot.spot_id) == 1){
	    if (verbose)
	      printf("%d: Spot id is %d\n", line_number, temp_spot.spot_id);
	  }
	  else valid=false;
	  if (temp_spot.spot_id <= 0) valid = false;
	}
	//SPOT_WIDTH
	else if(token.compare("spot_width") == 0){
	  temp_spot.spot_width =
	    parse_integer(lineread, std::string("spot_width"),
			  line_number, valid, verbose);
	  if (temp_spot.spot_width <= 0) valid = false;
	}
	//CHECKPOINT
	else if(token.compare("checkpoint") == 0)
	  temp_spot.checkpoint = Checkpoint(lineread, temp_zone.zone_id,
					    temp_spot.spot_id,
					    line_number, valid, verbose);
	//END_SPOT
	else if(token.compare("end_spot") == 0){
	  if(!temp_spot.isvalid())
	    valid = false;
	  else{
	  	if(alreadyExists(temp_zone, temp_spot)) {
	  		std::cerr << "Error. Duplicate Spot. Id: " << temp_zone.zone_id << "." << temp_spot.spot_id << std::endl;
	  		valid = false;
	  	}
	  	else {
		    temp_zone.spots.push_back(temp_spot);
		    if (verbose)
		      printf("%d: spot has ended\n", line_number);
		    change_state(previous_state, state, ZONES);
		    temp_spot.clear();
	  	}
	  }
	}
	else{
	  //WAYPOINT
	  sprintf(temp_char, "%d.%d.", temp_zone.zone_id, temp_spot.spot_id);
	  if(token.find(temp_char) != std::string::npos ){
	    LL_Waypoint wp(lineread, temp_zone.zone_id,
			   temp_spot.spot_id, line_number, valid, verbose);
	    temp_spot.waypoints.push_back(wp);
	  }
	  else{
	    printf("%d: Unexpected token\n", line_number);
	    valid=false;
	  }
	}
	break;
      case UNKNOWN:
	printf("%d: Unexpected token\n", line_number);
	valid=false;
      }
      if (!valid) {
	is_valid=false;
	print_error_message(line_number, token);
	return;
      }
    }
  prep_graph();
  if (verbose) printf("Parser Finishes\n");
}

bool RNDF::alreadyExists(Segment &segment) {
	for(uint i = 0; i < segments.size(); i++) {
		Segment &seg = segments[i];
		if(seg.segment_id == segment.segment_id) {
			return true;
		}
	}
	return false;
}
bool RNDF::alreadyExists(Segment &parentSegment, Lane &lane) {
	for(uint i = 0; i < parentSegment.lanes.size(); i ++) {
		Lane &ln = parentSegment.lanes[i];
		if(ln.lane_id == lane.lane_id) {
			return true;
		}
	}
	return false;
}
bool RNDF::alreadyExists(Lane &parentLane, LL_Waypoint &waypoint) {
	for(uint i = 0; i < parentLane.waypoints.size(); i ++) {
		LL_Waypoint &wp = parentLane.waypoints[i];
		if(wp.waypoint_id == waypoint.waypoint_id) {
			return true;
		}
	}
	return false;
}
bool RNDF::alreadyExists(Zone &zone, Spot &spot) {
	for(uint i = 0; i < zone.spots.size(); i ++) {
		Spot &sp = zone.spots[i];
		if(sp.spot_id == spot.spot_id) {
			return true;
		}
	}
	return false;
}
bool RNDF::alreadyExists(Zone &zone) {
	for(uint i = 0; i < zones.size(); i ++) {
		Zone &zn = zones[i];
		if(zn.zone_id == zone.zone_id) {
			return true;
		}
	}
	return false;
}
bool RNDF::alreadyExists(Lane &parentLane, Checkpoint &checkpoint) {
	for(uint i = 0; i < parentLane.checkpoints.size(); i ++) {
		Checkpoint &cp = parentLane.checkpoints[i];
		if(cp.waypoint_id == checkpoint.waypoint_id) {
			return true;
		}
	}
	return false;
}
bool RNDF::alreadyExists(Lane &parentLane, Stop &stop) {
	for(uint i = 0; i < parentLane.stops.size(); i ++) {
		Stop &sp = parentLane.stops[i];
		if(sp.waypoint_id == stop.waypoint_id) {
			return true;
		}
	}
	return false;
}
bool RNDF::alreadyExists(Lane &parentLane, Exit &exit) {
	for(uint i = 0; i < parentLane.exits.size(); i ++) {
		Exit &ex = parentLane.exits[i];
		if(ex.start_point == exit.start_point &&
			ex.end_point == exit.end_point) {
			return true;
		}
	}
	return false;
}

MDF::MDF(std::string mdfname, bool verbose)
{
  verbose=verbose;

  is_valid=true;

  if (verbose) printf("MDF Parser Begins\n");

  std::ifstream mdf_file;
  mdf_file.open(mdfname.c_str());
  if (!mdf_file){
    printf("Error in opening MDF file\n");
    is_valid=false;
    return;
  }

  //Parser State
  line_number = 0;
  MDF_PARSE_STATE state = MDF_UNKNOWN, previous_state = MDF_UNKNOWN;

  std::string lineread;
  while(getline(mdf_file, lineread) ) // Read line by line
    {

      line_number++;

      uint real_characters=0;

      for (uint ind=0; ind < lineread.length(); ind++)
	if (lineread[ind] != '\r' &&
	    lineread[ind] != '\t' &&
	    lineread[ind] != ' ')
	  real_characters++;

      //Blank lines
      if (real_characters == 0) {
	if (verbose)
	  printf("%d: Blank Line\n",line_number);
	continue;
      }

      std::string token;
      char token_char [lineread.size()+1];
      // char temp_char [lineread.size()+1];

      //Read in one line
      sscanf(lineread.c_str(), "%s", token_char);
      token.assign(token_char);

      if (state != MDF_COMMENT){
	if (token.compare("MDF_name") == 0)
	  change_state(previous_state, state, MDF_GENERAL);
	else if (token.compare(0, 11, "checkpoints") == 0)
	  change_state(previous_state, state, MDF_CHECKPOINTS);
	else if (token.compare(0, 12, "speed_limits") == 0)
	  change_state(previous_state, state, MDF_SPEEDLIMITS);
	else if (token.find("/*") != std::string::npos)
	  change_state(previous_state, state, MDF_COMMENT);
      }

      bool valid=true;
      switch (state){
      case MDF_COMMENT:
	if (verbose)
	  printf("%d: COMMENT: %s\n", line_number, lineread.c_str());
	if (lineread.find("*/") != std::string::npos)
	  state = previous_state;
	break;
      case MDF_GENERAL:
	if (token.compare("MDF_name") == 0)
	  filename =
	    parse_string(lineread, std::string("MDF_name"),
			 line_number, valid, verbose);
	else if (token.compare("RNDF") == 0)
	  RNDF_name =
	    parse_string(lineread, std::string("RNDF"),
			 line_number, valid, verbose);
	else if (token.compare("format_version") == 0)
	  format_version =
	    parse_string(lineread, std::string("format_version"),
			 line_number, valid, verbose);
	else if (token.compare("creation_date") == 0)
	  creation_date =
	    parse_string(lineread, std::string("creation_date"),
			 line_number, valid, verbose);
	else if (token.compare("end_file") == 0){
	  if (!isvalid()){
	    printf("%d: MDF Properties are not valid\n", line_number);
	    valid = false;
	  }
	  if (verbose)
	    printf("%d: MDF file has finished parsing\n", line_number);
	}
	else{
	  printf("%d: Unexpected token\n", line_number);
	  valid=false;
	}
	break;
      case MDF_SPEEDLIMITS:
	if(token.compare(0, 12, "speed_limits") == 0){
	  if (verbose)
	    printf("%d: Speed Limits\n", line_number);
	}
	else if(token.compare(0, 16, "num_speed_limits") == 0){
	  number_of_speedlimits =
	    parse_integer(lineread, std::string("num_speed_limits"),
			  line_number, valid, verbose);
	  if (number_of_speedlimits <= 0) valid = false;
	}
	else if(token.compare("end_speed_limits") == 0){
	  if (number_of_speedlimits != (int) speed_limits.size())
	    printf("Number of Speed Limits do not match num_speedlimits\n");
	  else if (verbose)
	    printf("%d: End of Speed Limits\n", line_number);
	  change_state(previous_state, state, MDF_GENERAL);
	}
	else{
	  Speed_Limit speedlimit(lineread, line_number, valid, verbose);
	  if (valid) speed_limits.push_back(speedlimit);
	  else {
	    printf("%d: Unexpected token\n", line_number);
	    valid = false;
	  }
	}
	break;
      case MDF_CHECKPOINTS:
	if(token.compare(0, 11, "checkpoints") == 0){
	  if (verbose)
	    printf("%d: Checkpoints\n", line_number);
	}
	else if(token.compare("num_checkpoints") == 0){
	  number_of_checkpoints =
	    parse_integer(lineread, std::string("num_checkpoints"),
			  line_number, valid, verbose);
	  if (number_of_checkpoints <= 0) valid = false;
	}
	else if(token.compare("end_checkpoints") == 0){
	  if (number_of_checkpoints != (int) checkpoint_ids.size())
	    printf("Number of Checkpoints do not match num_checkpoints\n");
	  else if (verbose)
	    printf("%d: Checkpoints have ended\n", line_number);
	  change_state(previous_state, state, MDF_GENERAL);
	}
	//NO TOKEN
	else{
	  //CHECKPOINT
	  int checkpoint_id =
	    parse_integer(lineread, line_number, valid, verbose);
	  if (valid) checkpoint_ids.push_back(checkpoint_id);
	  else {
	    printf("%d: Unexpected token\n", line_number);
	    valid = false;
	  }
	  if (checkpoint_id <= 0) valid = false;
	}
	break;
      case MDF_UNKNOWN:
	printf("%d: COULD NOT PARSE: %s\n", line_number, lineread.c_str());
	valid = false;
      }
      if (!valid) {
	is_valid=false;
	print_error_message(line_number, token);
	return;
      }
    }

  if (verbose) printf("MDF Parser Finishes\n");

}

Lane_marking RNDF::parse_boundary(std::string line, bool& valid){
  Lane_marking boundary_type = UNDEFINED;
  char temp_char [line.size()+1];
  if (!sscanf(line.c_str(), "%*s %s", temp_char) == 1)
    valid = false;
  if (strcmp(temp_char, "double_yellow") == 0)
    boundary_type = DOUBLE_YELLOW;
  else if (strcmp(temp_char, "solid_yellow") == 0)
    boundary_type = SOLID_YELLOW;
  else if (strcmp(temp_char, "solid_white") == 0)
    boundary_type = SOLID_WHITE;
  else if (strcmp(temp_char, "broken_white") == 0)
    boundary_type = BROKEN_WHITE;
  else
    valid=false;
  return boundary_type;

};

Checkpoint::Checkpoint(std::string line, int x, int y,
		       int line_number, bool& valid, bool verbose) {
  char temp_char [line.size()+1];
  sprintf(temp_char,"checkpoint %d.%d.%%d %%d" ,x, y);
  if (sscanf(line.c_str(), temp_char, &waypoint_id, &checkpoint_id) == 2 &&
      isvalid()){
    if (verbose){
      printf("%d: ", line_number);
      print();
    }
  }
  else{
    //    clear();
    valid=false;
  }
};

LL_Waypoint::LL_Waypoint(std::string line, int x, int y,
			 int line_number, bool& valid, bool verbose) {

  char temp_char [line.size()+1];
  sprintf(temp_char, "%d.%d.%%d %%lf %%lf", x, y);
  if(sscanf(line.c_str(), temp_char, &waypoint_id, &ll.latitude, &ll.longitude) == 3 && isvalid()){
    if (verbose) {
      printf("%d: ", line_number);
      print();
    }
  }
  else{
    //    clear();
    valid=false;
  }
};

Exit::Exit(std::string line, int x, int y, int line_number, bool& valid,
	   bool verbose) {

  char temp_char [line.size()+1];
  sprintf(temp_char,"exit %d.%d.%%d %%d.%%d.%%d", x, y);
  start_point.segment_id = x;
  start_point.lane_id = y;
  if (sscanf(line.c_str(), temp_char, &start_point.waypoint_id,
	     &end_point.segment_id, &end_point.lane_id,
	     &end_point.waypoint_id) == 4  && isvalid()){
    if (verbose){
      printf("%d: ", line_number);
      print();
    }
  }
  else{
    //    clear();
    //    start_point.segment_id = x;
    //    start_point.lane_id = y;
    valid=false;
  }
};

Speed_Limit::Speed_Limit(std::string line, int line_number, bool& valid,
			 bool verbose){
  if (sscanf(line.c_str(), "%d %d %d", &id, &min_speed, &max_speed) == 3 && isvalid()){
    if (verbose){
      printf("%d: ", line_number);
      print();
    }
  }
  else{
    //    clear();
    valid=false;
  }
};

Stop::Stop(std::string line, int x, int y,
	   int line_number, bool& valid, bool verbose){
  //  clear()
  char temp_char [line.size()+1];
  sprintf(temp_char,"stop %d.%d.%%d" , x, y);
  if (sscanf(line.c_str(), temp_char, &waypoint_id) == 1 && isvalid()){
    if (verbose)
      printf("%d: Stop at Waypoint %d\n",
	     line_number, waypoint_id);
  }
  else{
    //    clear();
    valid=false;
  }
};

std::string parse_string(std::string line, std::string token,
			 int line_number, bool& valid, bool verbose){
  char temp_char [line.size()+1];
  temp_char[0]='\0';
  if (sscanf(line.c_str(), "%*s %s", temp_char)){
    if (verbose)
      printf("%d: %s is %s\n", line_number, token.c_str(), temp_char);
  }
  else
    valid=false;

  return std::string(temp_char);
};

//WITH STRING TOKEN
int parse_integer(std::string line, std::string token,
		  int line_number, bool& valid, bool verbose){
  int integer = INT_MIN;
  if (sscanf(line.c_str(), "%*s %d", &integer) == 1){
    if (verbose)
      printf("%d: %s is %d\n", line_number, token.c_str(), integer);
  }
  else
    valid=false;

  if (integer == INT_MIN) valid = false;
  return integer;
};

//WITHOUT TOKEN
int parse_integer(std::string line, int line_number, bool& valid,
		  bool verbose){
  int integer = INT_MIN;
  if (sscanf(line.c_str(), "%d", &integer) == 1){
    if (verbose)
      printf("%d: %d\n", line_number, integer);
  }
  else
    valid=false;
  if (integer == INT_MIN) valid = false;
  return integer;
};

void Lane::clear(){
  waypoints.clear();
  checkpoints.clear();
  stops.clear();
  exits.clear();
  left_boundary = right_boundary = UNDEFINED;
  lane_id = number_of_waypoints = INT_MIN;
  lane_width = 0;
};

void Segment::clear(){
  lanes.clear();
  segment_name = std::string("default");
  segment_id = number_of_lanes = INT_MIN;
};

void Zone::clear(){
  zone_id = number_of_parking_spots = INT_MIN;
  zone_name = std::string("default");
  perimeter.clear();
  spots.clear();
};

void Spot::clear(){
  spot_id = INT_MIN;
  spot_width = 0;
  checkpoint.clear();
  waypoints.clear();
};

void Perimeter::clear(){
  perimeter_id = number_of_perimeterpoints = INT_MIN;
  exits_from_perimeter.clear();
  perimeterpoints.clear();

};

void RNDF::print(){

  if (!is_valid) {
    printf("RNDF not valid\n");
    return;
  }

  printf("RNDF name is %s\n", filename.c_str());
  printf("Number of segments is %d\n", number_of_segments);
  printf("Number of zones is %d\n", number_of_zones);
  printf("format version is %s\n", format_version.c_str());
  printf("creation date is %s\n", creation_date.c_str());
  print_vector(segments);
  print_vector(zones);
};

void MDF::print(){

  if (!is_valid) {
    printf("MDF not valid\n");
    return;
  }

  printf("MDF name is %s\n", filename.c_str());
  printf("RNDF name is %s\n", RNDF_name.c_str());
  printf("format version is %s\n", format_version.c_str());
  printf("creation date is %s\n", creation_date.c_str());
  printf("Number of checkpoints is %d\n", number_of_checkpoints);
  std::vector<int>::iterator i;
  for(i = checkpoint_ids.begin(); i != checkpoint_ids.end(); i++)
    printf("Checkpoint id: %d\n", *i);

  printf("Number of speedlimits is %d\n", number_of_speedlimits);
  print_vector(speed_limits);
};

void Segment::print(){

  printf("Segment number is %d\n", segment_id);
  printf("Number of Lanes in Segment %d\n", number_of_lanes);
  printf("segment name is %s\n", segment_name.c_str());
  print_vector(lanes);
};

void Lane::print(){

  printf("Lane number is %d\n", lane_id);
  printf("Number of Waypoints in lane %d\n", number_of_waypoints);
  printf("Width of lane %d\n", lane_width);
  printf("left boundary type is %d\n", left_boundary);
  printf("right boundary type is %d\n", right_boundary);
  print_vector(checkpoints);
  print_vector(stops);
  print_vector(exits);
  print_vector(waypoints);
};

void Exit::print(){

  printf("Exit from ");
  start_point.print();

  printf(" to ");
  end_point.print();

  printf("\n");
};

void Spot::print(){

  printf("Spot id is %d\n", spot_id);
  printf("Spot width is %d\n", spot_width);
  printf("Spot Checkpoint is: ");
  checkpoint.print();
  printf("Spot - First waypoint: ");
  waypoints[0].print_without_newline();
  printf(",Second waypoint: ");
  waypoints[1].print_without_newline();
  printf("\n");
};

void Zone::print(){

  printf("Zone number is %d\n", zone_id);
  printf("Number of parking spots is %d\n",
	 number_of_parking_spots); //integer >= 0
  printf("Zone name is %s\n", zone_name.c_str()); //Designate the
  //zone, such as
  //"North_Parking_Lot"
  perimeter.print();
  print_vector(spots);
};

void Perimeter::print(){

  printf("Perimeter id is %d\n", perimeter_id); //integer ALWAYS 0

  printf("Number of perimeter points is %d\n", number_of_perimeterpoints);
  print_vector(exits_from_perimeter);
  print_vector(perimeterpoints);
};

void Speed_Limit::print(){

  printf("Speed Limit id: %d", id); //integer > 0
  printf(", min_speed is %d", min_speed); //integer >= 0
  printf(", max_speed is %d\n", max_speed); //integer >= 0
}

template <class T>
void print_vector (std::vector<T> vec) {
  typename std::vector<T>::iterator i;
  for(i = vec.begin(); i != vec.end(); i++)
    i->print();
};

void RNDF::prep_graph(){

  int index = 0;
  std::vector<Segment>::iterator si;
  std::vector<Lane>::iterator li;
  std::vector<LL_Waypoint>::iterator wi;
  std::vector<Checkpoint>::iterator ci;
  std::vector<Stop>::iterator stops_i;
  std::vector<Exit>::iterator exits_i;
  std::vector<Zone>::iterator zones_i;
  std::vector<Spot>::iterator spots_i;
  std::vector<Perimeter_Point>::iterator peri_i;
  std::vector<WayPointNode>::iterator wpni;
  std::vector<ElementID>::iterator eid_i;

  //-----VERTICES-------
  for(si = segments.begin(); si != segments.end(); si++){
    for(li = si->lanes.begin(); li != si->lanes.end(); li++){
      for(wi = li->waypoints.begin(); wi != li->waypoints.end(); wi++){
	WayPointNode wpn;
	wpn.ll = wi->ll;
	if (li->lane_width == 0)
	  wpn.lane_width = DEFAULT_LANE_WIDTH;
	else wpn.lane_width = feet2meters(li->lane_width);
	wpn.id = ElementID(si->segment_id, li->lane_id, wi->waypoint_id);
	wpn.index = index;
	index++;
	id_map[wpn.id] = (wpn);
      }
    }
  }

  //Goal waypoints, no orientation required
  for(zones_i = zones.begin(); zones_i != zones.end(); zones_i++){
    for(spots_i = zones_i->spots.begin();
	spots_i != zones_i->spots.end(); spots_i++){
      for(wi = spots_i->waypoints.begin();
	  wi != spots_i->waypoints.end(); wi++){
	WayPointNode wpn;
	wpn.ll = wi->ll;
	wpn.id = ElementID(zones_i->zone_id, spots_i->spot_id,
			   wi->waypoint_id);
	if (spots_i->checkpoint.waypoint_id == wi->waypoint_id){
	  wpn.is_goal = true;
	  wpn.checkpoint_id = spots_i->checkpoint.checkpoint_id;
	}
	else wpn.is_goal = false;
	wpn.is_spot = true;
	if (spots_i->spot_width == 0)
	  wpn.lane_width = DEFAULT_SPOT_WIDTH;
	else wpn.lane_width = feet2meters(spots_i->spot_width);
	wpn.is_stop = wpn.is_exit = wpn.is_entry = false;
	wpn.index = index;
	index++;
	id_map[wpn.id] = (wpn);
      }
    }
  }

  //Perimeter waypoints, no orientation required
  for(zones_i = zones.begin(); zones_i != zones.end(); zones_i++){
    for(peri_i = zones_i->perimeter.perimeterpoints.begin();
	peri_i != zones_i->perimeter.perimeterpoints.end(); peri_i++){
      WayPointNode wpn;
      wpn.ll = peri_i->ll;
      wpn.id = ElementID(zones_i->zone_id, zones_i->perimeter.perimeter_id,
			 peri_i->waypoint_id);
      wpn.is_perimeter = true;
      wpn.lane_width = DEFAULT_LANE_WIDTH;
      wpn.is_stop = wpn.is_exit = wpn.is_entry = false;
      wpn.index = index;
      index++;
      id_map[wpn.id] = (wpn);
    }
  }

  //Entry and exit waypoints, no orientation required
  for(zones_i = zones.begin(); zones_i != zones.end(); zones_i++){
    for(exits_i = zones_i->perimeter.exits_from_perimeter.begin();
	exits_i != zones_i->perimeter.exits_from_perimeter.end(); exits_i++){
      ElementID id_start (exits_i->start_point.segment_id,
			  exits_i->start_point.lane_id,
			  exits_i->start_point.waypoint_id);
      ElementID id_end (exits_i->end_point.segment_id,
			exits_i->end_point.lane_id,
			exits_i->end_point.waypoint_id);
      if (id_map.find(id_start) == id_map.end() ||
	  id_map.find(id_end) == id_map.end()) {
	exit_error(*exits_i);
	is_valid=false;
	return;
      }
      id_map[id_start].is_exit = true;
      id_map[id_end].is_entry = true;
    }
  }

  for(si = segments.begin(); si != segments.end(); si++){
    for(li = si->lanes.begin(); li != si->lanes.end(); li++){
      for(ci = li->checkpoints.begin(); ci != li->checkpoints.end(); ci++){
	ElementID id (si->segment_id, li->lane_id, ci->waypoint_id);
	if (id_map.find(id) == id_map.end()) {
	  checkpoint_error(si->segment_id, li->lane_id, ci->waypoint_id);
	  is_valid=false;
	  return;
	}
	id_map[id].checkpoint_id = ci->checkpoint_id;
	id_map[id].is_goal = false;
      }

      for(stops_i = li->stops.begin(); stops_i != li->stops.end(); stops_i++){
	ElementID id (si->segment_id, li->lane_id, stops_i->waypoint_id);
	if (id_map.find(id) == id_map.end()) {
	  stop_error(si->segment_id, li->lane_id, stops_i->waypoint_id);
	  is_valid=false;
	  return;
	}
	id_map[id].is_stop = true;
      }

      for(exits_i = li->exits.begin(); exits_i != li->exits.end(); exits_i++){
	ElementID id_start (exits_i->start_point.segment_id,
			    exits_i->start_point.lane_id,
			    exits_i->start_point.waypoint_id);
	ElementID id_end (exits_i->end_point.segment_id,
			  exits_i->end_point.lane_id,
			  exits_i->end_point.waypoint_id);
	if (id_map.find(id_start) == id_map.end() || id_map.find(id_end) ==
	    id_map.end()) {
	  exit_error(*exits_i);
	  is_valid=false;
	  return;
	}
	id_map[id_start].is_exit = true;
	id_map[id_end].is_entry = true;
      }
    }
  }

  //-----EDGES-------
  //-----LANES
  for(si = segments.begin(); si != segments.end(); si++){
    for(li = si->lanes.begin(); li != si->lanes.end(); li++){
      for(wi = li->waypoints.begin(); wi != li->waypoints.end() -1; wi++){
	ElementID id_start (si->segment_id, li->lane_id, wi->waypoint_id);
	ElementID id_end (si->segment_id, li->lane_id, (wi+1)->waypoint_id);
	if (id_map.find(id_start) == id_map.end() ||
	    id_map.find(id_end) == id_map.end()) {
	  exit_error(*exits_i);
	  is_valid=false;
	  return;
	}
	edges.push_back( WayPointEdge(id_map[id_start], id_map[id_end],
				      li->left_boundary,
				      li->right_boundary, false));
      }
    }
  }
  //-----EXITS
  for(si = segments.begin(); si != segments.end(); si++){
    for(li = si->lanes.begin(); li != si->lanes.end(); li++){
      for(exits_i = li->exits.begin(); exits_i != li->exits.end(); exits_i++){
	ElementID id_start (exits_i->start_point.segment_id,
			    exits_i->start_point.lane_id,
			    exits_i->start_point.waypoint_id);
	ElementID id_end (exits_i->end_point.segment_id,
			  exits_i->end_point.lane_id,
			  exits_i->end_point.waypoint_id);
	if (id_map.find(id_start) == id_map.end() ||
	    id_map.find(id_end) == id_map.end()) {
	  exit_error(*exits_i);
	  is_valid=false;
	  return;
	}
	if (id_start.seg==id_end.seg &&
	    id_start.lane==id_end.lane &&
	    id_start.pt+1==id_end.pt)
	  for (uint i=0; i<edges.size(); i++)
	    {
	      if (edges.at(i).startnode_index==id_map[id_start].index &&
		  edges.at(i).endnode_index==id_map[id_end].index)
		{
		  edges.at(i).is_exit=true;
		  break;
		}
	    }
	else
	  edges.push_back(WayPointEdge(id_map[id_start], id_map[id_end],
				       li->left_boundary,
				       li->right_boundary, true));
      }
    }
  }

  //-----ZONES
  std::vector<ElementID> zone_exits;
  for(zones_i = zones.begin(); zones_i != zones.end(); zones_i++){
    for(exits_i = zones_i->perimeter.exits_from_perimeter.begin();
	exits_i != zones_i->perimeter.exits_from_perimeter.end(); exits_i++){
      ElementID id_start (exits_i->start_point.segment_id,
			  exits_i->start_point.lane_id,
			  exits_i->start_point.waypoint_id);
      ElementID id_end (exits_i->end_point.segment_id,
			exits_i->end_point.lane_id,
			exits_i->end_point.waypoint_id);
      if (id_map.find(id_start) == id_map.end() ||
	  id_map.find(id_end) == id_map.end()) {
	exit_error(*exits_i);
	is_valid=false;
	return;
      }
      edges.push_back( WayPointEdge(id_map[id_start], id_map[id_end],
				    UNDEFINED, UNDEFINED, true));
      zone_exits.push_back(id_map[id_start].id);
    }
  }

  //HANDLING EDGES FROM ZONE START TO ZONE END
  id_to_waypoint_map::iterator node_itr, node_itr2;
  for(node_itr = id_map.begin(); node_itr != id_map.end(); node_itr++){
    //If the node is an entry
    if (node_itr->second.is_entry && node_itr->second.is_perimeter) {
      for(node_itr2 = id_map.begin(); node_itr2 != id_map.end(); node_itr2++){
	if (node_itr2->second.id!=node_itr->second.id && node_itr2->second.is_perimeter &&
	    node_itr2->second.is_exit)
	  //Check if they are in the same zone
	  if(node_itr2->second.id.seg == node_itr->second.id.seg &&
	     node_itr2->second.id.pt != node_itr->second.id.pt) {
	    edges.push_back(WayPointEdge(node_itr->second, node_itr2->second,
					 UNDEFINED, UNDEFINED, false));
	  }
      }
    }
  }
  for(node_itr = id_map.begin(); node_itr != id_map.end(); node_itr++){
    if (node_itr->second.is_exit || node_itr->second.is_entry)
      for(node_itr2 = id_map.begin(); node_itr2 != id_map.end(); node_itr2++){
	if (node_itr2->second.id != node_itr->second.id)
	  if (node_itr2->second.is_spot)
	    if ((node_itr->second.id.seg ==
		 node_itr2->second.id.seg) &&
		(node_itr2->second.id.pt==1))
	      {
		if (node_itr->second.is_exit)
		  edges.push_back( WayPointEdge(node_itr2->second, node_itr->second,
						UNDEFINED, UNDEFINED, false));
		if (node_itr->second.is_entry)
		  edges.push_back
		    (WayPointEdge(node_itr->second, node_itr2->second,
				  UNDEFINED, UNDEFINED, false));
	      }

      }
  }

  for(node_itr = id_map.begin(); node_itr != id_map.end(); node_itr++){
    //If the node is an entry
    if (node_itr->second.is_spot)
      for(node_itr2 = id_map.begin(); node_itr2 != id_map.end(); node_itr2++){
	if (node_itr2->second.id != node_itr->second.id)
	  if (node_itr2->second.is_spot) {
	    if ((node_itr->second.id.seg==
		 node_itr2->second.id.seg) &&
		(node_itr->second.id.lane==
		 node_itr2->second.id.lane) &&
		(node_itr->second.id.pt==1) &&
		(node_itr2->second.id.pt==2))
	      {
		edges.push_back( WayPointEdge(node_itr->second, node_itr2->second,
					      UNDEFINED, UNDEFINED, false));
		edges.push_back( WayPointEdge(node_itr2->second, node_itr->second,
					      UNDEFINED, UNDEFINED, false));
	      }
	    if ((node_itr->second.id.seg==
		 node_itr2->second.id.seg) &&
		(node_itr->second.id.lane!=
		 node_itr2->second.id.lane) &&
		(node_itr->second.id.pt==1) &&
		(node_itr2->second.id.pt==1))
	      {
		edges.push_back( WayPointEdge(node_itr->second, node_itr2->second,
					      UNDEFINED, UNDEFINED, false));
		edges.push_back( WayPointEdge(node_itr2->second, node_itr->second,
					      UNDEFINED, UNDEFINED, false));
	      }
	  }
      }
  }
}

/** Populate graph from RNDF parser data.
 *
 * Copies all nodes from the way-point map to an array in the
 * graph. Includes edges via a pointer copy.
 */
void RNDF::populate_graph(Graph& graph)
{
  graph.nodes_size = id_map.size();
  graph.nodes = new WayPointNode[graph.nodes_size];
  id_to_waypoint_map::iterator node_itr;
  for(node_itr = id_map.begin(); node_itr != id_map.end(); node_itr++){
    graph.nodes[(node_itr->second).index] = (node_itr->second);
  }

  graph.edges_size = edges.size();
  graph.edges = edges;
  /*
    std::vector<WayPointEdge>::iterator edge_itr;
  int edge_index = 0;
  for(edge_itr = edges.begin(); edge_itr != edges.end(); edge_itr++){
    graph.edges[edge_index] = (*edge_itr);
    edge_index++;
  }
  */
}

//ISSUE: What should the SpeedLimits of Exits be
bool MDF::add_speed_limits(Graph& graph){
  std::vector<Speed_Limit>::iterator itr;
  int num_speed_limits = (int)speed_limits.size();
  int matches = 0;
  Speed_Limit matched, current;

  for (uint i = 0; i < graph.edges_size; i++){
    graph.edges[i].speed_min = 0.0;
    graph.edges[i].speed_max = DEFAULT_LANE_SPEED;
  }

  for(itr = speed_limits.begin(); itr != speed_limits.end(); itr++){
    current = *itr;
    for (uint i = 0; i < graph.edges_size; i++){
      int index = graph.edges[i].startnode_index;
      //      assert(index < graph.nodes_size);

      if(graph.nodes[index].id.seg == itr->id){
	if (itr->min_speed < Epsilon::speed)
	  graph.edges[i].speed_min = 0.0;
	else
	  graph.edges[i].speed_min = mph2mps(itr->min_speed);

	if (itr->max_speed < Epsilon::speed)
	  graph.edges[i].speed_max = fmax(graph.edges[i].speed_min,
					  DEFAULT_LANE_SPEED);
	else
	  graph.edges[i].speed_max = fmax(graph.edges[i].speed_min,
					  mph2mps(itr->max_speed));

	if (!(matched == current)){
	  matches++;
	  matched = current;
	}
      }
    }
  }

#if 0
  for (uint i = 0; i < graph.edges_size; i++){
    std::cerr << graph.nodes[graph.edges[i].startnode_index].id.seg
	      <<" "<<graph.edges[i].speed_min<<" "
	      <<graph.edges[i].speed_max<<std::endl;
  }
#endif

  if (matches == num_speed_limits)
    return true;
  else{
    //printf("[%d] != [%d]\n", matches, num_speed_limits);
    return false;
  }
}

void exit_error(Exit& ex){

  printf("ERROR: In Exit from %d.%d.%d to %d.%d.%d.",
	 ex.start_point.segment_id, ex.start_point.lane_id,
	 ex.start_point.waypoint_id,
	 ex.end_point.segment_id, ex.end_point.lane_id,
	 ex.end_point.waypoint_id);
  printf("  One of the WayPoints is not defined.\n");
}

void stop_error(int seg, int lane, int way){

  printf("ERROR: In Stop %d.%d.%d - The WayPoint is not defined\n",
	 seg, lane, way);
}

void checkpoint_error(int seg, int lane, int way){

  printf("ERROR: In Checkpoint %d.%d.%d - The WayPoint is not defined\n",
	 seg, lane, way);
}

void print_error_message(int line_number, std::string token){
  printf("%d: Invalid %s\n", line_number, token.c_str());
}


text:
"""A module containing helper functions."""

import functools
from typing import Callable

NEG_INF = (
    -100000.0
)  # A large negative value to use as -inf for numerical stability reasons

def cached_property(func: Callable) -> property:
    """Customized cached property decorator

    Args:
        func: Member function to be decorated

    Returns:
        Decorated cached property
    """
    return property(functools.lru_cache(None)(func))


text:
package io.crate.planner.operators;

import static io.crate.planner.operators.LogicalPlannerTest.isPlan;
import static org.junit.Assert.assertThat;

import java.io.IOException;

import org.junit.Before;
import org.junit.Test;

import io.crate.test.integration.CrateDummyClusterServiceUnitTest;
import io.crate.testing.SQLExecutor;

public class OuterJoinRewriteTest extends CrateDummyClusterServiceUnitTest {

    private SQLExecutor sqlExecutor;

    @Before
    public void setup() throws IOException {
        sqlExecutor = SQLExecutor.builder(clusterService)
            .addTable("create table t1 (x int)")
            .addTable("create table t2 (x int)")
            .build();
    }

    @Test
    public void testFilterAndOuterJoinIsRewrittenToInnerJoinIfFilterEliminatesNullRow() {
        var plan = sqlExecutor.logicalPlan(
            "SELECT * FROM t1 LEFT JOIN t2 ON t1.x = t2.x " +
            "WHERE t2.x = '10'"
        );
        var expectedPlan =
            "NestedLoopJoin[INNER | (x = x)]\n" +
            "  ├ Collect[doc.t1 | [x] | true]\n" +
            "  └ Collect[doc.t2 | [x] | (x = 10)]";
        assertThat(plan, isPlan(expectedPlan));
    }

    @Test
    public void testFilterAndOuterJoinIsNotRewrittenToInnerJoinIfFilterDoesNot() {
        var plan = sqlExecutor.logicalPlan(
            "SELECT * FROM t1 LEFT JOIN t2 ON t1.x = t2.x " +
            "WHERE coalesce(t2.x, 10) = 10"
        );
        var expectedPlan =
            "Filter[(coalesce(x, 10) = 10)]\n" +
            "  └ NestedLoopJoin[LEFT | (x = x)]\n" +
            "    ├ Collect[doc.t1 | [x] | true]\n" +
            "    └ Collect[doc.t2 | [x] | true]";
        assertThat(plan, isPlan(expectedPlan));
    }

    @Test
    public void testFilterOnLeftOuterJoinIsPartiallyPushedDownToTheLeftSide() {
        var plan = sqlExecutor.logicalPlan(
            "SELECT * FROM t1 LEFT JOIN t2 ON t1.x = t2.x " +
            "WHERE coalesce(t2.x, 10) = 10 AND t1.x > 5"
        );
        var expectedPlan =
            "Filter[(coalesce(x, 10) = 10)]\n" +
            "  └ NestedLoopJoin[LEFT | (x = x)]\n" +
            "    ├ Collect[doc.t1 | [x] | (x > 5)]\n" +
            "    └ Collect[doc.t2 | [x] | true]";
        assertThat(plan, isPlan(expectedPlan));
    }

    @Test
    public void testFilterOnRightOuterJoinIsPartiallyPushedDownToTheRightSide() {
        var plan = sqlExecutor.logicalPlan(
            "SELECT * FROM t1 RIGHT JOIN t2 ON t1.x = t2.x " +
            "WHERE coalesce(t1.x, 10) = 10 AND t2.x > 5"
        );
        var expectedPlan =
            "Filter[(coalesce(x, 10) = 10)]\n" +
            "  └ NestedLoopJoin[RIGHT | (x = x)]\n" +
            "    ├ Collect[doc.t1 | [x] | true]\n" +
            "    └ Collect[doc.t2 | [x] | (x > 5)]";
        assertThat(plan, isPlan(expectedPlan));
    }

    @Test
    public void testFilterOnFullOuterJoinIsPartiallyPushedDownToTheRightSide() {
        var plan = sqlExecutor.logicalPlan(
            "SELECT * FROM t1 FULL OUTER JOIN t2 ON t1.x = t2.x " +
            "WHERE coalesce(t1.x, 10) = 10 AND t2.x > 5"
        );
        var expectedPlan =
            "Filter[((coalesce(x, 10) = 10) AND (x > 5))]\n" +
            "  └ NestedLoopJoin[FULL | (x = x)]\n" +
            "    ├ Collect[doc.t1 | [x] | true]\n" +
            "    └ Collect[doc.t2 | [x] | (x > 5)]";
        assertThat(plan, isPlan(expectedPlan));
    }
}


text:
<?php
require __DIR__ . '/includes/form-messages.inc.php';

/*
 * If this page is rendered without an result variable
 * available, just create one ourselves.
 */
if (!isset($result)) {
    $result = new Dto_FormResult('notsubmitted');
} # if

if ((isset($lastformaction) && ($lastformaction == 'exportfilters'))) {
	$this->sendContentTypeHeader('xml');
	Header('Content-Disposition: attachment; filename="spotwebfilters.xml"');

	echo $result->getData('filters');
	return ;
} # if

if ((isset($lastformaction) && ($lastformaction == 'importfilters'))) {
    if ($result->isSuccess()) {
	    $tplHelper->redirect($http_referer);
    } # if
} # if

/*
 * Render the JSON or the form
 */
if (showResults($result)) {
    return ;
} # if

/*
 * Retrieve a list of icons available
 */
$filterIcons = $tplHelper->getFilterIcons();

/*
 * If the user did not submit the form yet, make
 * sure we add some data to the template
 */
if (!$result->isSubmitted()) {
	# Determine whether this an edit of an existing filter or adding a new one
	$isNew = (isset($data['isnew']));

	# Retrieve the requested filter
	if ((!$isNew) && (isset($data['filterid']))) {
		$filter = $tplHelper->getUserFilter($data['filterid']);
	} else {
		$filter = array('id' => 9999, 'title' => '', 'icon' => '');
	} # if

?>

	<fieldset>
		<form class="editfilterform" name="editfilterform" action="<?php echo $tplHelper->makeEditFilterAction(); ?>" method="post">
			<input type="hidden" name="editfilterform[xsrfid]" value="<?php echo $tplHelper->generateXsrfCookie('editfilterform'); ?>">
<?php if (!$isNew) { ?>
			<input type="hidden" name="filterid" value="<?php echo (int) $filter['id']; ?>">
<?php } else {  ?>
			<input type="hidden" name="filterid" value="9999">
			<input type="hidden" name="editfilterform[tree]" value="<?php echo (isset($search['tree']) ? htmlspecialchars($search['tree'], ENT_QUOTES, "UTF-8") : ""); ?>" />
			<input type="hidden" name="editfilterform[valuelist]" value="<?php echo htmlspecialchars(implode('&', array_map('urlencode', (isset($search['value']) ?$search['value'] : array()) )), ENT_QUOTES, "UTF-8"); ?>" />
			<input type="hidden" name="editfilterform[sorton]" value="<?php echo htmlspecialchars($sortby, ENT_QUOTES, "UTF-8"); ?>" />
			<input type="hidden" name="editfilterform[sortorder]" value="<?php echo htmlspecialchars($sortdir, ENT_QUOTES, "UTF-8"); ?>" />
<?php } ?>

<?php echo _('Name'); ?>

				<input type="text" name="editfilterform[title]" value="<?php echo htmlspecialchars($filter['title']); ?>" />

<?php echo _('Icon'); ?>

				<select name="editfilterform[icon]">
<?php
				foreach($filterIcons as $icon => $desc) {
					echo "<option " . ($filter['icon'] == $icon ? 'selected="selected"' : '') . "value='" . $icon . "'>" . $desc . "</option>";
				} # foreach
?>
				</select>

<?php echo _('Notify me when this filter has new spots?'); ?>

				<input type="checkbox" name="editfilterform[enablenotify]" value="1" <?php if ((isset($filter['enablenotify'])) && ($filter['enablenotify'])) { echo ' checked="checked" '; } ?> />

<?php if ($isNew) { ?>
				<input class="smallGreyButton" type="submit" name="editfilterform[submitaddfilter]" value="<?php echo _('Add'); ?>">
<?php } else { ?>
				<input class="smallGreyButton" type="submit" name="editfilterform[submitchangefilter]" value="<?php echo _('Change'); ?>">
				<input class="smallGreyButton" type="submit" name="editfilterform[submitremovefilter]" value="<?php echo _('Delete'); ?>">
<?php } ?>

		</form>
	</fieldset>
<?php
	} # if not only  xml


text:
class Alerter::NotificationType < ActiveRecord::Base
  self.table_name = :alerter_notification_types

  attr_accessible :name if Alerter.protected_attributes?

  #belongs_to :message
  has_many :preferences
  has_many :messages
  before_save :check_notification_type

  validates_uniqueness_of :name

  protected
  def check_notification_type
    raise 'Notification type is not allowed' unless Alerter.available_notification_types.include?(self.name)
  end

end


text:
<?php

namespace Mac\AdminBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class MacAdminBundle extends Bundle
{
}


text:
#include "stdafx.h"

#include "lz4Helper.h"
#include "lz4.h"
#include "lz4hc.h"

namespace lz4 {
	array<Byte>^ LZ4Helper::Custom::Compress(array<Byte>^ input, int inputOffset, int inputLength, int passes)
	{
		if (input == nullptr) {
			throw gcnew ArgumentNullException("input");
		}
		else if (inputOffset < 0) {
			throw gcnew ArgumentOutOfRangeException("inputOffset");
		}
		else if (inputLength <= 0) {
			throw gcnew ArgumentOutOfRangeException("inputLength");
		}
		else if (inputOffset + inputLength > input->Length) {
			throw gcnew ArgumentOutOfRangeException("inputOffset+inputLength");
		}
		else if (passes < 1 || passes > 2) {
			throw gcnew ArgumentOutOfRangeException("passes");
		}

		int bufferSize = LZ4_compressBound(inputLength);
		int offset = 0;
		array<Byte>^ result = gcnew array<Byte>(bufferSize + 10);
		if (passes == 1) {
			result[0] = 1; // 1 pass
			offset = inputLength;
			int i;
			for (i = 0; offset && i < 8; i++) {
				result[2 + i] = (offset & 0xff);
				offset >>= 8;
			}
			if (offset != 0) {
				throw gcnew NotSupportedException("input too large");
			}
			result[1] = i;
			offset = 2 + i;
		}

		pin_ptr<Byte> inputPtr = &input[inputOffset];
		byte* inputBytePtr = inputPtr;
		pin_ptr<Byte> outputPtr = &result[offset];
		byte* outputBytePtr = outputPtr;

		int compressedSize = LZ4_compress_default((char*)inputBytePtr, (char*)outputBytePtr, inputLength, bufferSize);
		if (compressedSize <= 0)
		{
			throw gcnew Exception("Compression failed");
		}

		if (passes == 1) {
			array<Byte>^ slimResult = gcnew array<Byte>(compressedSize + offset);
			Buffer::BlockCopy(result, 0, slimResult, 0, compressedSize + offset);
			return slimResult;
		}

		int bufferSize2 = LZ4_compressBound(compressedSize);
		array<Byte>^ result2 = gcnew array<Byte>(bufferSize2 + 10);
		result2[0] = 2; // 2 pass
		offset = inputLength;
		int i;
		for (i = 0; offset && i < 8; i++) {
			result2[2 + i] = (offset & 0xff);
			offset >>= 8;
		}
		if (offset != 0) {
			throw gcnew NotSupportedException("input too large");
		}

		result2[1] = i;
		offset = 2 + i;

		inputPtr = &result[0];
		inputBytePtr = inputPtr;
		outputPtr = &result2[offset];
		outputBytePtr = outputPtr;

		int compressedSize2 = LZ4_compress_HC((char *)inputBytePtr, (char *)outputBytePtr, compressedSize, bufferSize2, 0);

		array<Byte>^ slimResult = gcnew array<Byte>(compressedSize2 + offset);
		Buffer::BlockCopy(result2, 0, slimResult, 0, compressedSize2 + offset);
		return slimResult;
	}

	array<Byte>^ LZ4Helper::Custom::Decompress(array<Byte>^ input, int inputOffset, int inputLength)
	{
		if (input == nullptr) {
			throw gcnew ArgumentNullException("input");
		}
		else if (inputOffset < 0) {
			throw gcnew ArgumentOutOfRangeException("inputOffset");
		}
		else if (inputLength < 3) {
			throw gcnew ArgumentOutOfRangeException("inputLength");
		}
		else if (inputOffset + inputLength > input->Length) {
			throw gcnew ArgumentOutOfRangeException("inputOffset+inputLength");
		}

		int passes = input[0];
		int sizeOfSize = input[1];
		if (sizeOfSize > 8 || inputLength < (2 + (int)sizeOfSize) || !(passes == 1 || passes == 2)) {
			throw gcnew Exception("Invalid data");
		}

		int fileSize = 0;
		for (int i = 0; i < sizeOfSize; i++) {
			fileSize += (((byte)input[2 + i]) << (8 * i));
		}

		if (fileSize < 0)
		{
			throw gcnew Exception("Invalid data");
		}

		int bufferSize1 = fileSize;
		if (passes == 2) {
			bufferSize1 = LZ4_compressBound(fileSize);
		}

		array<Byte>^ result = gcnew array<Byte>(bufferSize1);

		pin_ptr<Byte> inputPtr = &input[2 + sizeOfSize];
		byte* inputBytePtr = inputPtr;
		pin_ptr<Byte> outputPtr = &result[0];
		byte* outputBytePtr = outputPtr;

		int bufferSize2 = LZ4_decompress_safe((char *)inputBytePtr, (char *)outputBytePtr, inputLength - 2 - sizeOfSize, bufferSize1);
		if (bufferSize2 <= 0)
		{
			throw gcnew Exception("Decompression failed");
		}

		if (passes == 1)
		{
			array<Byte>^ slimResult = gcnew array<Byte>(bufferSize2);
			Buffer::BlockCopy(result, 0, slimResult, 0, bufferSize2);
			return slimResult;
		}

		array<Byte>^ result2 = gcnew array<Byte>(fileSize);

		inputPtr = &result[0];
		inputBytePtr = inputPtr;
		outputPtr = &result2[0];
		outputBytePtr = outputPtr;

		int bufferSize3 = LZ4_decompress_safe((char *)inputBytePtr, (char *)outputBytePtr, bufferSize2, fileSize);
		if (bufferSize3 <= 0)
		{
			throw gcnew Exception("Decompression failed");
		}

		array<Byte>^ slimResult = gcnew array<Byte>(bufferSize3);
		Buffer::BlockCopy(result2, 0, slimResult, 0, bufferSize3);
		return slimResult;
	}

	array<Byte>^ LZ4Helper::Frame::Compress(array<Byte>^ input, int inputOffset, int inputLength, LZ4FrameBlockMode blockMode, LZ4FrameBlockSize blockSize, LZ4FrameChecksumMode checksumMode, Nullable<long long> maxFrameSize, bool highCompression)
	{
		if (input == nullptr) {
			throw gcnew ArgumentNullException("input");
		}
		else if (inputOffset < 0) {
			throw gcnew ArgumentOutOfRangeException("inputOffset");
		}
		else if (inputLength <= 0) {
			throw gcnew ArgumentOutOfRangeException("inputLength");
		}
		else if (inputOffset + inputLength > input->Length) {
			throw gcnew ArgumentOutOfRangeException("inputOffset+inputLength");
		}

		MemoryStream^ ms = nullptr;
		array<Byte>^ result;
		try
		{
			ms = gcnew MemoryStream();
			LZ4Stream^ lz4 = nullptr;
			try
			{
				lz4 = LZ4Stream::CreateCompressor(ms, LZ4StreamMode::Write, blockMode, blockSize, checksumMode, maxFrameSize, highCompression, true);
				lz4->Write(input, inputOffset, inputLength);
			}
			finally
			{
				if (lz4 != nullptr) { delete lz4; }
			}
			result = ms->ToArray();
		}
		finally
		{
			if (ms != nullptr) { delete ms; }
		}

		return result;
	}

	array<Byte>^ LZ4Helper::Frame::Decompress(array<Byte>^ input, int inputOffset, int inputLength)
	{
		if (input == nullptr) {
			throw gcnew ArgumentNullException("input");
		}
		else if (inputOffset < 0) {
			throw gcnew ArgumentOutOfRangeException("inputOffset");
		}
		else if (inputLength < 3) {
			throw gcnew ArgumentOutOfRangeException("inputLength");
		}
		else if (inputOffset + inputLength > input->Length) {
			throw gcnew ArgumentOutOfRangeException("inputOffset+inputLength");
		}

		MemoryStream ^ms = nullptr;
		array<Byte>^ result;
		try
		{
			ms = gcnew MemoryStream();
			LZ4Stream^ lz4 = nullptr;
			try
			{
				lz4 = LZ4Stream::CreateDecompressor(ms, LZ4StreamMode::Write, true);
				lz4->Write(input, inputOffset, inputLength);
			}
			finally
			{
				if (lz4 != nullptr) { delete lz4; }
			}
			result = ms->ToArray();
		}
		finally
		{
			if (ms != nullptr) { delete ms; }
		}

		return result;
	}
}


text:
export function CrowdIntegrationDao(RESOURCE, ArtifactoryDaoFactory) {
    return ArtifactoryDaoFactory()
            .setDefaults({method: 'POST'})
            .setPath(RESOURCE.CROWD)
            .setCustomActions({
                'test': {
                    method: 'POST',
                    path: RESOURCE.CROWD + "/test",
                    notifications: true
                },
                'refresh': {
                    method: 'POST',
                    path: RESOURCE.CROWD + "/refresh/:name",
                    params: {name: '@name'},
                    notifications: true
                },
                'import': {
                    method: 'POST',
                    path: RESOURCE.CROWD + "/import",
                    notifications: true
                }
            })
            .getInstance();
}


text:
import $ from 'jquery'

import { getAbortEverything } from '../app/initialization'
import {
  getSaveStreetIncomplete,
  setSaveStreetIncomplete
} from '../streets/xhr'

const NON_BLOCKING_AJAX_REQUEST_TIME = [10, 500, 1000, 5000, 10000]
const NON_BLOCKING_AJAX_REQUEST_BACKOFF_RANGE = 60000

const NO_CONNECTION_MESSAGE_TIMEOUT = 10000

let nonblockingAjaxRequests = []
let nonblockingAjaxRequestTimer = 0

const noConnectionMessage = {
  visible: false,
  timerId: -1,

  schedule: function () {
    if (noConnectionMessage.timerId === -1) {
      // TODO const
      noConnectionMessage.timerId =
        window.setTimeout(noConnectionMessage.show, NO_CONNECTION_MESSAGE_TIMEOUT)
    }
  },

  show: function () {
    document.querySelector('#no-connection-message').classList.add('visible')
    document.body.classList.add('no-connection-message-visible')
  },

  hide: function () {
    window.clearTimeout(noConnectionMessage.timerId)
    noConnectionMessage.timerId = -1

    document.querySelector('#no-connection-message').classList.remove('visible')
    document.body.classList.remove('no-connection-message-visible')
  }
}

window.addEventListener('stmx:everything_loaded', function () {
  document.querySelector('#no-connection-try-again').addEventListener('pointerdown', nonblockingAjaxTryAgain)
  window.addEventListener('beforeunload', onWindowBeforeUnload)
})

export function newNonblockingAjaxRequest (request, allowToClosePage, doneFunc, errorFunc, maxRetries) {
  nonblockingAjaxRequestTimer = 0

  var signature = getAjaxRequestSignature(request)

  removeNonblockingAjaxRequest(signature)
  nonblockingAjaxRequests.push({
    request: request,
    allowToClosePage: allowToClosePage,
    doneFunc: doneFunc,
    errorFunc: errorFunc,
    inProgress: false,
    signature: signature,
    tryCount: 0,
    maxRetries: maxRetries
  })

  scheduleNextNonblockingAjaxRequest()
}

export function getNonblockingAjaxRequestCount () {
  return nonblockingAjaxRequests.length
}

function getAjaxRequestSignature (request) {
  return request.type + ' ' + request.url
}

function nonblockingAjaxTryAgain () {
  noConnectionMessage.hide()

  nonblockingAjaxRequestTimer = 0

  scheduleNextNonblockingAjaxRequest()
}

function sendNextNonblockingAjaxRequest () {
  if (getAbortEverything()) {
    return
  }

  if (getNonblockingAjaxRequestCount()) {
    noConnectionMessage.schedule()

    var request = null

    request = nonblockingAjaxRequests[0]

    if (request) {
      if (!request.inProgress) {
        request.inProgress = true

        $.ajax(request.request).done(function (data) {
          successNonblockingAjaxRequest(data, request)
        }).fail(function (data) {
          errorNonblockingAjaxRequest(data, request)
        })
      }
    }

    scheduleNextNonblockingAjaxRequest()
  }
}

// also needed by window_unload
function scheduleNextNonblockingAjaxRequest () {
  if (getNonblockingAjaxRequestCount()) {
    let time
    if (nonblockingAjaxRequestTimer < NON_BLOCKING_AJAX_REQUEST_TIME.length) {
      time = NON_BLOCKING_AJAX_REQUEST_TIME[nonblockingAjaxRequestTimer]
    } else {
      time = Math.floor(Math.random() * NON_BLOCKING_AJAX_REQUEST_BACKOFF_RANGE)
    }

    window.setTimeout(sendNextNonblockingAjaxRequest, time)

    nonblockingAjaxRequestTimer++
  } else {
    setSaveStreetIncomplete(false)
  }
}

function removeNonblockingAjaxRequest (signature) {
  for (var i in nonblockingAjaxRequests) {
    if (nonblockingAjaxRequests[i].signature === signature) {
      nonblockingAjaxRequests.splice(i, 1)
      break
    }
  }
}

function errorNonblockingAjaxRequest (data, request) {
  // Do not execute the error function immediately if there is
  // a directive to retry a certain number of times first.
  if (request.errorFunc && !request.maxRetries) {
    request.errorFunc(data)
  }

  request.tryCount++
  request.inProgress = false

  // Abort resending if the max number of tries has been hit.
  if (request.maxRetries && request.tryCount >= request.maxRetries) {
    nonblockingAjaxRequestTimer = 0
    noConnectionMessage.hide()
    removeNonblockingAjaxRequest(request.signature)
    if (request.errorFunc) {
      request.errorFunc(data)
    }
  }
}

function successNonblockingAjaxRequest (data, request) {
  nonblockingAjaxRequestTimer = 0

  noConnectionMessage.hide()

  removeNonblockingAjaxRequest(request.signature)

  if (request.doneFunc) {
    request.doneFunc(data)
  }

  scheduleNextNonblockingAjaxRequest()
}

// Non-blocking AJAX requests are checked to see if any are
// in progress before a window is unloaded

function checkIfChangesSaved () {
  // don't do for settings deliberately

  if (getAbortEverything()) {
    return
  }

  var showWarning = false

  if (getSaveStreetIncomplete()) {
    showWarning = true
  } else {
    for (var i in nonblockingAjaxRequests) {
      if (!nonblockingAjaxRequests[i].allowToClosePage) {
        showWarning = true
      }
    }
  }

  if (showWarning) {
    nonblockingAjaxRequestTimer = 0
    scheduleNextNonblockingAjaxRequest()

    return 'Your changes have not been saved yet. Please return to the page, check your Internet connection, and wait a little while to allow the changes to be saved.'
  }
}

function onWindowBeforeUnload () {
  var text = checkIfChangesSaved()
  if (text) {
    return text
  }
}