text:
static char *tregist_id =
	"@(#)Copyright (C) 1996-2016 H.Shirouzu		tregist.cpp	Ver0.99";

#include <stdio.h>
#include "tlib.h"

TRegistry::TRegistry(LPCSTR company, LPSTR appName, StrMode mode)
{
	strMode = mode;
	ChangeApp(company, appName);
}

TRegistry::TRegistry(LPCWSTR company, LPCWSTR appName, StrMode mode)
{
	strMode = mode;
	ChangeAppW(company, appName);
}

TRegistry::TRegistry(HKEY top_key, StrMode mode)
{
	topKey = top_key;
	strMode = mode;
}

TRegistry::~TRegistry(void)
{
	while (openCnt > 0) {
		CloseKey();
	}
}

BOOL TRegistry::ChangeApp(LPCSTR company, LPSTR appName, BOOL openOnly)
{
	Wstr	company_w(company, strMode);
	Wstr	appName_w(appName, strMode);

	return	ChangeAppW(company_w.s(), appName_w.s(), openOnly);
}

BOOL TRegistry::ChangeAppW(const WCHAR *company, const WCHAR *appName, BOOL openOnly)
{
	while (openCnt > 0) {
		CloseKey();
	}

	topKey = HKEY_CURRENT_USER;

	WCHAR	wbuf[100];
	swprintf(wbuf, L"software\\%s", company);

	if (appName && *appName) {
		swprintf(wbuf + wcslen(wbuf), L"\\%s", appName);
	}

	return	openOnly ? OpenKeyW(wbuf) : CreateKeyW(wbuf);
}

void TRegistry::ChangeTopKey(HKEY top_key)
{
	while (openCnt > 0)
		CloseKey();

	topKey = top_key;
}

BOOL TRegistry::OpenKey(LPCSTR subKey, BOOL createFlg)
{
	Wstr	subkey_w(subKey, strMode);
	return	OpenKeyW(subKey ? subkey_w.s() : NULL, createFlg);
}

BOOL TRegistry::OpenKeyW(const WCHAR *subKey, BOOL createFlg)
{
	HKEY	parentKey = (openCnt == 0 ? topKey : hKey[openCnt -1]);

	if (openCnt >= MAX_KEYARRAY) {
		return	FALSE;
	}
	DWORD	tmp;
	LONG	status;

	if (createFlg) {
		status = ::RegCreateKeyExW(parentKey, subKey, 0, NULL, REG_OPTION_NON_VOLATILE,
				KEY_ALL_ACCESS|(keyForce64 ? KEY_WOW64_64KEY : 0), NULL, &hKey[openCnt], &tmp);
	}
	else {
		if ((status = ::RegOpenKeyExW(parentKey, subKey, 0,
			KEY_ALL_ACCESS|(keyForce64 ? KEY_WOW64_64KEY : 0), &hKey[openCnt])) != ERROR_SUCCESS)
			status = ::RegOpenKeyExW(parentKey, subKey, 0,
				KEY_READ|(keyForce64 ? KEY_WOW64_64KEY : 0), &hKey[openCnt]);
	}

	if (status == ERROR_SUCCESS)
		return	openCnt++, TRUE;
	else
		return	FALSE;
}

BOOL TRegistry::CloseKey(void)
{
	if (openCnt <= 0) {
		return	FALSE;
	}
	::RegCloseKey(hKey[--openCnt]);

	return	TRUE;
}

BOOL TRegistry::GetInt(LPCSTR subKey, int *val)
{
	return	GetLong(subKey, (long *)val);
}

BOOL TRegistry::GetIntW(const WCHAR *subKey, int *val)
{
	return	GetLongW(subKey, (long *)val);
}

BOOL TRegistry::SetInt(LPCSTR subKey, int val)
{
	return	SetLong(subKey, (long)val);
}

BOOL TRegistry::SetIntW(const WCHAR *subKey, int val)
{
	return	SetLongW(subKey ? subKey : NULL, (long)val);
}

BOOL TRegistry::GetInt64(LPCSTR subKey, int64 *val)
{
	Wstr	subKey_w(subKey, strMode);

	return	GetInt64W(subKey ? subKey_w.s() : NULL, val);
}

BOOL TRegistry::GetInt64W(const WCHAR *subKey, int64 *val)
{
	DWORD	type = REG_QWORD;
	DWORD	dw_size = sizeof(int64);

	return	::RegQueryValueExW(hKey[openCnt -1], subKey, 0, &type, (BYTE *)val, &dw_size)
				== ERROR_SUCCESS;
}

BOOL TRegistry::SetInt64(LPCSTR subKey, int64 val)
{
	Wstr	subKey_w(subKey, strMode);

	return	SetInt64W(subKey ? subKey_w.s() : NULL, val);
}

BOOL TRegistry::SetInt64W(const WCHAR *subKey, int64 val)
{
	return	::RegSetValueExW(hKey[openCnt -1], subKey, 0, REG_QWORD,
			(const BYTE *)&val, sizeof(val)) == ERROR_SUCCESS;
}

BOOL TRegistry::GetLong(LPCSTR subKey, long *val)
{
	Wstr	subKey_w(subKey, strMode);
	return	GetLongW(subKey ? subKey_w.s() : NULL, val);
}

BOOL TRegistry::GetLongW(const WCHAR *subKey, long *val)
{
	DWORD	type = REG_DWORD, dw_size = sizeof(long);

	if (::RegQueryValueExW(hKey[openCnt -1], subKey, 0, &type, (BYTE *)val, &dw_size)
			== ERROR_SUCCESS) {
		return	TRUE;
	}
// 昔の互換性用
	WCHAR	wbuf[100];
	long	size_byte = sizeof(wbuf);

	if (::RegQueryValueW(hKey[openCnt -1], subKey, wbuf, &size_byte) != ERROR_SUCCESS)
		return	FALSE;
	*val = wcstol(wbuf, 0, 10);
	return	TRUE;
}

BOOL TRegistry::SetLong(LPCSTR subKey, long val)
{
	Wstr	subKey_w(subKey, strMode);
	return	SetLongW(subKey ? subKey_w.s() : NULL, val);
}

BOOL TRegistry::SetLongW(const WCHAR *subKey, long val)
{
	return	::RegSetValueExW(hKey[openCnt -1], subKey, 0, REG_DWORD,
			(const BYTE *)&val, sizeof(val)) == ERROR_SUCCESS;
}

BOOL TRegistry::GetStr(LPCSTR subKey, LPSTR str, int size_byte)
{
	Wstr	subKey_w(subKey, strMode);
	Wstr	str_w(size_byte);

	if (!GetStrW(subKey ? subKey_w.s() : NULL, str_w.Buf(), size_byte * 2)) {
		return	FALSE;
	}
	WtoS(str_w.s(), str, size_byte, strMode);
	return	TRUE;
}

BOOL TRegistry::GetStrA(LPCSTR subKey, LPSTR str, int size)
{
	DWORD	type = REG_SZ;

	if (::RegQueryValueExA(hKey[openCnt -1], subKey, 0, &type, (BYTE *)str, (DWORD *)&size) != ERROR_SUCCESS
	&&  ::RegQueryValueA(hKey[openCnt -1], subKey, str, (LPLONG)&size) != ERROR_SUCCESS)
		return	FALSE;

	return	TRUE;
}

BOOL TRegistry::GetStrW(const WCHAR *subKey, WCHAR *str, int size_byte)
{
	DWORD	type = REG_SZ;

	if (::RegQueryValueExW(hKey[openCnt -1], subKey, 0, &type, (BYTE *)str,
			(DWORD *)&size_byte) != ERROR_SUCCESS
	&&  ::RegQueryValueW(hKey[openCnt -1], subKey, str, (LPLONG)&size_byte) != ERROR_SUCCESS)
		return	FALSE;

	return	TRUE;
}

BOOL TRegistry::GetStrMW(const char *subKey, WCHAR *str, int size_byte)
{
	Wstr	subKey_w(subKey, strMode);

	return	GetStrW(subKey ? subKey_w.s() : NULL, str, size_byte);
}

BOOL TRegistry::SetStr(LPCSTR subKey, LPCSTR str)
{
	Wstr	subKey_w(subKey, strMode), str_w(str, strMode);

	return	SetStrW(subKey ? subKey_w.s() : NULL, str_w.s());
}

BOOL TRegistry::SetStrA(LPCSTR subKey, LPCSTR str)
{
	return	::RegSetValueExA(hKey[openCnt -1], subKey, 0, REG_SZ, (const BYTE *)str, (DWORD)strlen(str) +1) == ERROR_SUCCESS;
}

BOOL TRegistry::SetStrW(const WCHAR *subKey, const WCHAR *str)
{
	return	::RegSetValueExW(hKey[openCnt -1], subKey, 0, REG_SZ, (const BYTE *)str,
			(DWORD((wcslen(str) +1) * sizeof(WCHAR)))) == ERROR_SUCCESS;
}

BOOL TRegistry::SetStrMW(const char *subKey, const WCHAR *str)
{
	Wstr	subKey_w(subKey, strMode);

	return	SetStrW(subKey ? subKey_w.s() : NULL, str);
}

BOOL TRegistry::GetByte(LPCSTR subKey, BYTE *data, int *size)
{
	Wstr	subKey_w(subKey, strMode);

	return	GetByteW(subKey ? subKey_w.s() : NULL, data, size);
}

BOOL TRegistry::GetByteW(const WCHAR *subKey, BYTE *data, int *size)
{
	DWORD	type = REG_BINARY;

	return	::RegQueryValueExW(hKey[openCnt -1], subKey, 0, &type,
			(BYTE *)data, (LPDWORD)size) == ERROR_SUCCESS;
}

BOOL TRegistry::SetByte(LPCSTR subKey, const BYTE *data, int size)
{
	Wstr	subKey_w(subKey, strMode);
	return	SetByteW(subKey ? subKey_w.s() : NULL, data, size);
}

BOOL TRegistry::SetByteW(const WCHAR *subKey, const BYTE *data, int size)
{
	return	::RegSetValueExW(hKey[openCnt -1], subKey, 0, REG_BINARY, data, size)
			== ERROR_SUCCESS;
}

BOOL TRegistry::DeleteKey(LPCSTR subKey)
{
	Wstr	subKey_w(subKey, strMode);
	return	DeleteKeyW(subKey ? subKey_w.s() : NULL);
}

BOOL TRegistry::DeleteKeyW(const WCHAR *subKey)
{
	return	::RegDeleteKeyW(hKey[openCnt -1], subKey) == ERROR_SUCCESS;
}

BOOL TRegistry::DeleteValue(LPCSTR subValue)
{
	Wstr	subValue_w(subValue, strMode);
	return	DeleteValueW(subValue ? subValue_w.s() : NULL);
}

BOOL TRegistry::DeleteValueW(const WCHAR *subValue)
{
	return	::RegDeleteValueW(hKey[openCnt -1], subValue) == ERROR_SUCCESS;
}

BOOL TRegistry::EnumKey(DWORD cnt, LPSTR buf, int size)
{
	Wstr	buf_w(size);

	if (!EnumKeyW(cnt, buf_w.Buf(), size)) return FALSE;

	WtoS(buf_w.s(), buf, size, strMode);
	return	TRUE;
}

BOOL TRegistry::EnumKeyW(DWORD cnt, WCHAR *buf, int size)
{
	return	::RegEnumKeyExW(hKey[openCnt -1], cnt, buf, (DWORD *)&size, 0, 0, 0, 0)
			== ERROR_SUCCESS;
}

BOOL TRegistry::EnumValue(DWORD cnt, LPSTR buf, int size, DWORD *type)
{
	Wstr	buf_w(size);

	if (!EnumValueW(cnt, buf_w.Buf(), size, type)) return FALSE;

	WtoS(buf_w.s(), buf, size, strMode);

	return	TRUE;
}

BOOL TRegistry::EnumValueW(DWORD cnt, WCHAR *buf, int size, DWORD *type)
{
	return	::RegEnumValueW(hKey[openCnt -1], cnt, buf, (DWORD *)&size, 0, type, 0, 0)
			== ERROR_SUCCESS;
}

/*
	subKey を指定した場合は subkey を含むキー以下を削除
	subkey が NULL の場合、カレント の配下を削除
*/
BOOL TRegistry::DeleteChildTree(LPCSTR subKey)
{
	Wstr	subKey_w(subKey, strMode);
	return	DeleteChildTreeW(subKey ? subKey_w.s() : NULL);
}

BOOL TRegistry::DeleteChildTreeW(const WCHAR *subKey)
{
	WCHAR	wbuf[256];
	BOOL	ret = TRUE;

	if (subKey && !OpenKeyW(subKey)) {
		return	FALSE;
	}

	while (EnumKeyW(0, wbuf, wsizeof(wbuf)))
	{
		if (!(ret = DeleteChildTreeW(wbuf)))
			break;
	}
	if (subKey)
	{
		CloseKey();
		ret = DeleteKeyW(subKey) ? ret : FALSE;
	}
	else {
		while (EnumValueW(0, wbuf, wsizeof(wbuf)))
		{
			if (!DeleteValueW(wbuf))
			{
				ret = FALSE;
				break;
			}
		}
	}
	return	ret;
}

redpajama_set_name: RedPajamaGithub


text:
package com.tngtech.archunit.exampletest;

import com.tngtech.archunit.base.DescribedPredicate;
import com.tngtech.archunit.core.domain.JavaClass;
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.domain.JavaMember;
import com.tngtech.archunit.core.domain.PackageMatchers;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.example.layers.security.Secured;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import static com.tngtech.archunit.core.domain.JavaClass.Functions.GET_PACKAGE_NAME;
import static com.tngtech.archunit.core.domain.JavaMember.Predicates.declaredIn;
import static com.tngtech.archunit.core.domain.properties.CanBeAnnotated.Predicates.annotatedWith;
import static com.tngtech.archunit.lang.conditions.ArchPredicates.are;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;

@Category(Example.class)
public class ControllerRulesTest {

    private final JavaClasses classes = new ClassFileImporter().importPackages("com.tngtech.archunit.example.layers");

    @Test
    public void controllers_should_only_call_secured_methods() {
        classes()
                .that().resideInAPackage("..controller..")
                .should().onlyCallMethodsThat(areDeclaredInController().or(are(annotatedWith(Secured.class))))
                .check(classes);
    }

    @Test
    public void controllers_should_only_call_secured_constructors() {
        classes()
                .that().resideInAPackage("..controller..")
                .should().onlyCallConstructorsThat(areDeclaredInController().or(are(annotatedWith(Secured.class))))
                .check(classes);
    }

    @Test
    public void controllers_should_only_call_secured_code_units() {
        classes()
                .that().resideInAPackage("..controller..")
                .should().onlyCallCodeUnitsThat(areDeclaredInController().or(are(annotatedWith(Secured.class))))
                .check(classes);
    }

    @Test
    public void controllers_should_only_access_secured_fields() {
        classes()
                .that().resideInAPackage("..controller..")
                .should().onlyAccessFieldsThat(areDeclaredInController().or(are(annotatedWith(Secured.class))))
                .check(classes);
    }

    @Test
    public void controllers_should_only_access_secured_members() {
        classes()
                .that().resideInAPackage("..controller..")
                .should().onlyAccessMembersThat(areDeclaredInController().or(are(annotatedWith(Secured.class))))
                .check(classes);
    }

    private DescribedPredicate<JavaMember> areDeclaredInController() {
        DescribedPredicate<JavaClass> aPackageController = GET_PACKAGE_NAME.is(PackageMatchers.of("..controller..", "java.."))
                .as("a package '..controller..'");
        return are(declaredIn(aPackageController));
    }
}


text:
package de.chrgroth.generictypesystem.model;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * A simple POJO class holding all information about attribute definitions.
 *

 *
id

 *
The id value used for persistence purposes.

 *
name

 *
The attribute name. Used for {@link GenericAttribute#equals(Object)} and {@link GenericAttribute#hashCode()}.

 *
type

 *
The attribute type.

 *
valueType

 *
The attribute value type. Primarily used for list type attributes.

 *
unique

 *
Flag to indicate if this attribute is part of the items unique key.

 *
mandatory

 *
Flag to indicate if this attribute has a mandatory value.

 *
structure

 *
The structure connected to this attribute. Used for attributes with structured type or a list type holding a structured value type.

 *
min

 *
An optional minimum for attribute values. Numeric or value length for string based attribute types.

 *
max

 *
An optional maximum for attribute values. Numeric or value length for string based attribute types.

 *
step

 *
A step value for numeric typed attributes. Primarily used for UI purposes, not used for validaton at all.

 *
pattern

 *
An optional pattern for string based attribute types.

 *
defaultValue

 *
An optional default value.

 *
defaultValueCallback

 *
An optional default value callback script to be executed.

 *
valueProposalDependencies

 *
An optional list of value proposal dependencies, referencing other attribute ids. Primarily used for UI purposes.

 *
unitsId

 *
An optional units id to be used for attribute values.

 *
customProperties

 *
A map holding optional custom properties to be used by concrete projects for simple type attribute extension.

 *

 *
 * @author Christian Groth
 */
public class GenericAttribute {

    private Long id;
    private String name;
    private GenericAttributeType type;
    private GenericAttributeType valueType;
    private boolean unique;
    private boolean mandatory;
    private GenericStructure structure;

    private Double min;
    private Double max;
    private Double step;
    private String pattern;

    private GenericValue<?> defaultValue;
    private String defaultValueCallback;

    private Set<Long> valueProposalDependencies;

    private Long unitsId;

    private Set<String> enumValues;

    private Map<String, GenericValue<?>> customProperties;

    public GenericAttribute() {
        this(null, null, null, null, false, false, null, null, null, null, null, null, null, null, null, null);
    }

    public GenericAttribute(Long id, String name, GenericAttributeType type, GenericAttributeType valueType, boolean unique, boolean mandatory, GenericStructure structure,
            Double min, Double max, Double step, String pattern, GenericValue<?> defaultValue, String defaultValueCallback, Set<Long> valueProposalDependencies, Long unitsId,
            Set<String> enumValues) {
        this.id = id;
        this.name = name;
        this.type = type;
        this.valueType = valueType;
        this.unique = unique;
        this.mandatory = mandatory;
        this.structure = structure;
        this.min = min;
        this.max = max;
        this.step = step;
        this.pattern = pattern;
        this.defaultValue = defaultValue;
        this.defaultValueCallback = defaultValueCallback;
        if (valueProposalDependencies != null) {
            this.valueProposalDependencies = new HashSet<>(valueProposalDependencies);
        }
        this.unitsId = unitsId;
        if (enumValues != null) {
            this.enumValues = new HashSet<>(enumValues);
        }
        customProperties = new HashMap<>();
    }

    /**
     * Returns true if the attributes type returns true for {@link GenericAttributeType#isList()}.
     *
     * @return true if list, false otherwise
     */
    public boolean isList() {
        return type != null && type.isList();
    }

    /**
     * Returns true if {@link #isList()} returns true and the attributes value type return true for {@link GenericAttributeType#isStructure()} or if
     * {@link #isList()} returns false and the attributes type returns true for {@link GenericAttributeType#isStructure()}.
     *
     * @return true if list, false otherwise
     */
    public boolean isStructure() {
        if (isList()) {
            return valueType != null && valueType.isStructure();
        } else {
            return type != null && type.isStructure();
        }
    }

    /**
     * Returns true if the attribute definition is based on units definition.
     *
     * @return true if unit base, false otherwise
     */
    public boolean isUnitBased() {
        return unitsId != null;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public GenericAttributeType getType() {
        return type;
    }

    public void setType(GenericAttributeType type) {
        this.type = type;
    }

    public GenericAttributeType getValueType() {
        return valueType;
    }

    public void setValueType(GenericAttributeType valueType) {
        this.valueType = valueType;
    }

    public boolean isUnique() {
        return unique;
    }

    public void setUnique(boolean unique) {
        this.unique = unique;
    }

    public boolean isMandatory() {
        return mandatory;
    }

    public void setMandatory(boolean mandatory) {
        this.mandatory = mandatory;
    }

    public GenericStructure getStructure() {
        return structure;
    }

    public void setStructure(GenericStructure structure) {
        this.structure = structure;
    }

    public Double getMin() {
        return min;
    }

    public void setMin(Double min) {
        this.min = min;
    }

    public Double getMax() {
        return max;
    }

    public void setMax(Double max) {
        this.max = max;
    }

    public Double getStep() {
        return step;
    }

    public void setStep(Double step) {
        this.step = step;
    }

    public String getPattern() {
        return pattern;
    }

    public void setPattern(String pattern) {
        this.pattern = pattern;
    }

    public GenericValue<?> getDefaultValue() {
        return defaultValue;
    }

    public void setDefaultValue(GenericValue<?> defaultValue) {
        this.defaultValue = defaultValue;
    }

    public String getDefaultValueCallback() {
        return defaultValueCallback;
    }

    public void setDefaultValueCallback(String defaultValueCallback) {
        this.defaultValueCallback = defaultValueCallback;
    }

    public Set<Long> getValueProposalDependencies() {
        return valueProposalDependencies;
    }

    public void setValueProposalDependencies(Set<Long> valueProposalDependencies) {
        this.valueProposalDependencies = valueProposalDependencies;
    }

    public Long getUnitsId() {
        return unitsId;
    }

    public void setUnitsId(Long unitsId) {
        this.unitsId = unitsId;
    }

    public Set<String> getEnumValues() {
        return enumValues;
    }

    public void setEnumValues(Set<String> enumValues) {
        this.enumValues = enumValues;
    }

    public Map<String, GenericValue<?>> getCustomProperties() {
        return customProperties;
    }

    public void setCustomProperties(Map<String, GenericValue<?>> customProperties) {
        this.customProperties = customProperties;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + (name == null ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        GenericAttribute other = (GenericAttribute) obj;
        if (name == null) {
            if (other.name != null) {
                return false;
            }
        } else if (!name.equals(other.name)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "GenericAttribute [id=" + id + ", name=" + name + ", type=" + type + ", valueType=" + valueType + ", unique=" + unique + ", mandatory=" + mandatory + ", structure="
                + structure + ", min=" + min + ", max=" + max + ", step=" + step + ", pattern=" + pattern + ", defaultValue=" + defaultValue + ", defaultValueCallback="
                + defaultValueCallback + ", valueProposalDependencies=" + valueProposalDependencies + ", unitsId=" + unitsId + ", enumValues=" + enumValues + ", customProperties="
                + customProperties + "]";
    }
}


text:
module Spree
  Classification.class_eval do
   # attr_accessible :position
  end
end


text:
class QuadObject: public GameObject
{
public:

	QuadObject();
	~QuadObject();

	void init(Quad *b, float r, Vector3 pos, Vector3 vel, float sp, float s);
	void draw();
	void update(float dt);

	void setPosition (Vector3 pos) {position = pos;}
	Vector3 getPosition() {return position;}
	void setVelocity (Vector3 vel) {velocity = vel;}
	Vector3 getVelocity() {return velocity;}
	void setSpeed(float s) {speed = s;}
	float getSpeed() {return speed;}
	void setRadius(float r) {radius = r; radiusSquared = (scale*r)*(scale*r);}
	void setAngleX(float val);
	float getRadiusSquare() {return radiusSquared;}
	float getRadius() {return radius;}
	Matrix getWorldMatrix() {return world;}
	void setScale(float s) {scale = s; radiusSquared = (s*radius)*(s*radius);}
	float getScale() {return scale;}
	void setActive() {active = true;}
	void setInActive() {active = false;}
	bool getActiveState() {return active;}
	void setMTech(ID3D10EffectTechnique* m){ mTech = m;}
	bool collided(QuadObject *QuadObject);

private:
	Quad *quad;
	Vector3 position;
	Vector3 velocity;
	float speed;
	float radius;
	float radiusSquared;
	bool active;
	Matrix world;
	float scale;
	ID3D10EffectTechnique* mTech;
};

#endif


text:
using System.Text.Encodings.Web;
using System.Text.Json;

#nullable enable

namespace Microsoft.AspNetCore.Http.Json;

/// <summary>
/// Options to configure JSON serialization settings for <see cref="HttpRequestJsonExtensions"/>
/// and <see cref="HttpResponseJsonExtensions"/>.
/// </summary>
public class JsonOptions
{
    internal static readonly JsonSerializerOptions DefaultSerializerOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web)
    {
        // Web defaults don't use the relex JSON escaping encoder.
        //
        // Because these options are for producing content that is written directly to the request
        // (and not embedded in an HTML page for example), we can use UnsafeRelaxedJsonEscaping.
        Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
    };

    // Use a copy so the defaults are not modified.
    /// <summary>
    /// Gets the <see cref="JsonSerializerOptions"/>.
    /// </summary>
    public JsonSerializerOptions SerializerOptions { get; } = new JsonSerializerOptions(DefaultSerializerOptions);
}


text:
package lxtypes_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"testing"
)

func TestLxtypes(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Lxtypes Suite")
}


text:
[![Latest Stable Version](https://poser.pugx.org/johnguild/muffincms/v/stable)](https://packagist.org/packages/johnguild/muffincms)
[![Total Downloads](https://poser.pugx.org/johnguild/muffincms/downloads)](https://packagist.org/packages/johnguild/muffincms)
[![License](https://poser.pugx.org/johnguild/muffincms/license)](https://packagist.org/packages/johnguild/muffincms)

## Requires
 * [Unisharp/Larvelfilemanaer](https://github.com/UniSharp/laravel-filemanager)

## Includes
 * TinyMCE 4
 * Font Awesome 4.7.0
 * [Sweetalert](https://github.com/t4t5/sweetalert)

## Installation
Create your laravel project as you normally do and setup .env

We will be using the laravel authenticable user so run

  ```bash
  php artisan make:auth
  ```

Install and Integrate [Unisharp/Laravelfilemanager](https://github.com/UniSharp/laravel-filemanager)

Install Package :

  ```bash
  composer require johnguild/muffincms
  ```

Edit config/app.php :

 Add Service Provider

  ```php
  Johnguild\Muffincms\MuffincmsServiceProvider::class,
  ```

Publish the package's config, assets, and resources :

  ```bash
  php artisan vendor:publish --tag=muffin_config
  php artisan vendor:publish --tag=muffin_views
  php artisan vendor:publish --tag=muffin_public
  php artisan vendor:publish --tag=muffin_admin --force
  php artisan vendor:publish --tag=muffin_auth --force
  php artisan vendor:publish --tag=muffin_route --force
  ```

Migrate tables :

 Make sure to edit the admin credential in database/migrations/muffin_create_website_admin

 ```php
 php artisan migrate
 ```


text:
package org.hl7.v3;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for Cahitan.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="Cahitan">
 *   <restriction base="{urn:hl7-org:v3}cs">
 *     <enumeration value="x-YAQ"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "Cahitan")
@XmlEnum
public enum Cahitan {

    @XmlEnumValue("x-YAQ")
    X_YAQ("x-YAQ");
    private final String value;

    Cahitan(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static Cahitan fromValue(String v) {
        for (Cahitan c: Cahitan.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }

}


text:
package com.ranli.fallenleavesweather.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.ranli.fallenleavesweather.R;

/**
 * Created by Administrator on 2016/9/26.
 */
public class CustomDialog extends Dialog {
    private Context mContext;
    private Button mButton;
    private TextView mText;

    public CustomDialog(Context context) {
        super(context);
        this.mContext = context;
    }

    public CustomDialog(Context context, int themeResId) {
        super(context, themeResId);
        this.mContext = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.custom_dialog, null);
        this.setContentView(layout);
        mButton = (Button) layout.findViewById(R.id.dialog_button);
        mText = (TextView) layout.findViewById(R.id.dialog_text);
    }

    public void setCustomDialogText(String text) {
        mText.setText(text);
    }

    public void setCustomOnClickListener(View.OnClickListener listenner) {
        mButton.setOnClickListener(listenner);
    }
}


text:
"""Generated protocol buffer code."""
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()

from google.protobuf import descriptor_pb2 as google_dot_protobuf_dot_descriptor__pb2

DESCRIPTOR = _descriptor.FileDescriptor(
  name='go.chromium.org/luci/common/proto/options.proto',
  package='luci',
  syntax='proto2',
  serialized_options=b'Z!go.chromium.org/luci/common/proto',
  create_key=_descriptor._internal_create_key,
  serialized_pb=b'\n/go.chromium.org/luci/common/proto/options.proto\x12\x04luci\x1a google/protobuf/descriptor.proto\"\x1b\n\x08Metadata\x12\x0f\n\x07\x64oc_url\x18\x01 \x01(\t**\n\x11TextPBFieldFormat\x12\x0b\n\x07\x44\x45\x46\x41ULT\x10\x00\x12\x08\n\x04JSON\x10\x01:E\n\rfile_metadata\x12\x1c.google.protobuf.FileOptions\x18\xe4\xbf\x04 \x01(\x0b\x32\x0e.luci.Metadata:P\n\x0etext_pb_format\x12\x1d.google.protobuf.FieldOptions\x18\xe5\xbf\x04 \x01(\x0e\x32\x17.luci.TextPBFieldFormat:7\n\x0elucicfg_ignore\x12\x1d.google.protobuf.FieldOptions\x18\xe6\xbf\x04 \x01(\x08\x42#Z!go.chromium.org/luci/common/proto'
  ,
  dependencies=[google_dot_protobuf_dot_descriptor__pb2.DESCRIPTOR,])

_TEXTPBFIELDFORMAT = _descriptor.EnumDescriptor(
  name='TextPBFieldFormat',
  full_name='luci.TextPBFieldFormat',
  filename=None,
  file=DESCRIPTOR,
  create_key=_descriptor._internal_create_key,
  values=[
    _descriptor.EnumValueDescriptor(
      name='DEFAULT', index=0, number=0,
      serialized_options=None,
      type=None,
      create_key=_descriptor._internal_create_key),
    _descriptor.EnumValueDescriptor(
      name='JSON', index=1, number=1,
      serialized_options=None,
      type=None,
      create_key=_descriptor._internal_create_key),
  ],
  containing_type=None,
  serialized_options=None,
  serialized_start=120,
  serialized_end=162,
)
_sym_db.RegisterEnumDescriptor(_TEXTPBFIELDFORMAT)

TextPBFieldFormat = enum_type_wrapper.EnumTypeWrapper(_TEXTPBFIELDFORMAT)
DEFAULT = 0
JSON = 1

FILE_METADATA_FIELD_NUMBER = 73700
file_metadata = _descriptor.FieldDescriptor(
  name='file_metadata', full_name='luci.file_metadata', index=0,
  number=73700, type=11, cpp_type=10, label=1,
  has_default_value=False, default_value=None,
  message_type=None, enum_type=None, containing_type=None,
  is_extension=True, extension_scope=None,
  serialized_options=None, file=DESCRIPTOR,  create_key=_descriptor._internal_create_key)
TEXT_PB_FORMAT_FIELD_NUMBER = 73701
text_pb_format = _descriptor.FieldDescriptor(
  name='text_pb_format', full_name='luci.text_pb_format', index=1,
  number=73701, type=14, cpp_type=8, label=1,
  has_default_value=False, default_value=0,
  message_type=None, enum_type=None, containing_type=None,
  is_extension=True, extension_scope=None,
  serialized_options=None, file=DESCRIPTOR,  create_key=_descriptor._internal_create_key)
LUCICFG_IGNORE_FIELD_NUMBER = 73702
lucicfg_ignore = _descriptor.FieldDescriptor(
  name='lucicfg_ignore', full_name='luci.lucicfg_ignore', index=2,
  number=73702, type=8, cpp_type=7, label=1,
  has_default_value=False, default_value=False,
  message_type=None, enum_type=None, containing_type=None,
  is_extension=True, extension_scope=None,
  serialized_options=None, file=DESCRIPTOR,  create_key=_descriptor._internal_create_key)

_METADATA = _descriptor.Descriptor(
  name='Metadata',
  full_name='luci.Metadata',
  filename=None,
  file=DESCRIPTOR,
  containing_type=None,
  create_key=_descriptor._internal_create_key,
  fields=[
    _descriptor.FieldDescriptor(
      name='doc_url', full_name='luci.Metadata.doc_url', index=0,
      number=1, type=9, cpp_type=9, label=1,
      has_default_value=False, default_value=b"".decode('utf-8'),
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      serialized_options=None, file=DESCRIPTOR,  create_key=_descriptor._internal_create_key),
  ],
  extensions=[
  ],
  nested_types=[],
  enum_types=[
  ],
  serialized_options=None,
  is_extendable=False,
  syntax='proto2',
  extension_ranges=[],
  oneofs=[
  ],
  serialized_start=91,
  serialized_end=118,
)

DESCRIPTOR.message_types_by_name['Metadata'] = _METADATA
DESCRIPTOR.enum_types_by_name['TextPBFieldFormat'] = _TEXTPBFIELDFORMAT
DESCRIPTOR.extensions_by_name['file_metadata'] = file_metadata
DESCRIPTOR.extensions_by_name['text_pb_format'] = text_pb_format
DESCRIPTOR.extensions_by_name['lucicfg_ignore'] = lucicfg_ignore
_sym_db.RegisterFileDescriptor(DESCRIPTOR)

Metadata = _reflection.GeneratedProtocolMessageType('Metadata', (_message.Message,), {
  'DESCRIPTOR' : _METADATA,
  '__module__' : 'go.chromium.org.luci.common.proto.options_pb2'
  # @@protoc_insertion_point(class_scope:luci.Metadata)
  })
_sym_db.RegisterMessage(Metadata)

file_metadata.message_type = _METADATA
google_dot_protobuf_dot_descriptor__pb2.FileOptions.RegisterExtension(file_metadata)
text_pb_format.enum_type = _TEXTPBFIELDFORMAT
google_dot_protobuf_dot_descriptor__pb2.FieldOptions.RegisterExtension(text_pb_format)
google_dot_protobuf_dot_descriptor__pb2.FieldOptions.RegisterExtension(lucicfg_ignore)

DESCRIPTOR._options = None
# @@protoc_insertion_point(module_scope)


text:
<?xml version="1.0" encoding="iso-8859-1" standalone="no"?>
<comments
  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
  xsi:noNamespaceSchemaLocation='comments.xsd'
  name="Kite_SDK_0.10.0_to_Kite_SDK_0.10.1"
  jdversion="1.1.1">

<!-- This file contains comments for a JDiff report. -->
<!-- It is used only in generating the report, and does not need to ship with the final report. -->

<!-- The id attribute in an identifier element identifies the change as noted in the report. -->
<!-- An id has the form package[.class[.[ctor|method|field].signature]], where [] indicates optional text. -->
<!-- A comment element can have multiple identifier elements, which will -->
<!-- will cause the same text to appear at each place in the report, but -->
<!-- will be converted to separate comments when the comments file is used. -->
<!-- HTML tags in the text field will appear in the report. -->
<!-- You also need to close p HTML elements, used for paragraphs - see the top-level documentation. -->
<comment>
  <identifier id="org.kitesdk.data.partition"/>
  <text>
    InsertCommentsHere
  </text>
</comment>
<comment>
  <identifier id="org.kitesdk.data.partition.DateFormatPartitioner"/>
  <text>
    InsertCommentsHere
  </text>
</comment>
<comment>
  <identifier id="org.kitesdk.data.partition.DateFormatPartitioner.equals_added(java.lang.Object)"/>
  <text>
    InsertCommentsHere
  </text>
</comment>
<comment>
  <identifier id="org.kitesdk.data.partition.DateFormatPartitioner.hashCode_added()"/>
  <text>
    InsertCommentsHere
  </text>
</comment>
<comment>
  <identifier id="org.kitesdk.data.partition.PartitionFunctions"/>
  <text>
    InsertCommentsHere
  </text>
</comment>
<comment>
  <identifier id="org.kitesdk.data.partition.PartitionFunctions.toExpression_added(org.kitesdk.data.FieldPartitioner)"/>
  <text>
    InsertCommentsHere
  </text>
</comment>

</comments>


text:
package com.w11k.lsql.converter.predefined;

import com.w11k.lsql.LSql;
import com.w11k.lsql.converter.Converter;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerConverter extends Converter {

    public AtomicIntegerConverter() {
        super(AtomicInteger.class, Types.INTEGER);
    }

    @Override
    public void setValue(LSql lSql, PreparedStatement ps, int index, Object val) throws SQLException {
        ps.setInt(index, ((AtomicInteger) val).get());
    }

    @Override
    public Object getValue(LSql lSql, ResultSet rs, int index) throws SQLException {
        return new AtomicInteger(rs.getInt(index));
    }

}


text:
static const NSString *simulatorDir = @"/Library/Developer/CoreSimulator";

@implementation SAAManager

- (id)init {
    self = [super init];
    if (self) {
        _listOfSimulatorDevices = [NSMutableArray new];
        _appsArray = [NSMutableArray new];
    }
    return self;
}

#pragma mark - Methods

NSString *RealHomeDirectory() {
    struct passwd *pw = getpwuid(getuid());
    assert(pw);
    return [NSString stringWithUTF8String:pw->pw_dir];
}

- (NSString *)pathOfSimulator {
    return [NSString stringWithFormat:@"%@%@/Devices",RealHomeDirectory(),simulatorDir];
}

- (void)getDevices {
    if (!([[self XcodeVersion] compare:@"6.0" options:NSNumericSearch] != NSOrderedAscending)) {
        NSAlert *noSimulatorAlert = [NSAlert new];
        [noSimulatorAlert addButtonWithTitle:@"Quit"];
        [noSimulatorAlert setMessageText:@"Xcode too old"];
        [noSimulatorAlert setInformativeText:[NSString stringWithFormat:@"SimArchive requires at least version 6.0 of Xcode. You have version %@ installed",[self XcodeVersion]]];
        [noSimulatorAlert setAlertStyle:NSCriticalAlertStyle];
        [noSimulatorAlert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) {
            [[NSApplication sharedApplication] terminate:self];
        }];
        return;
    }

    if (![[NSFileManager defaultManager] fileExistsAtPath:[self pathOfSimulator]]) {
        NSAlert *noSimulatorAlert = [NSAlert new];
        [noSimulatorAlert addButtonWithTitle:@"Quit"];
        [noSimulatorAlert setMessageText:@"iOS Simulator not found"];
        [noSimulatorAlert setInformativeText:@"There appears to be no iOS Simulator installed on this machine. Please install Xcode (Version 6.0 and larger) and start it at least once."];
        [noSimulatorAlert setAlertStyle:NSCriticalAlertStyle];
        [noSimulatorAlert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) {
            [[NSApplication sharedApplication] terminate:self];
        }];
        return;
    }

    [self getValidPlatforms];

    NSArray *devices = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[self pathOfSimulator] error:nil];

    self.listOfVersions = [NSMutableArray new];

    NSInteger index = 0;

    for (NSString *device in devices) {
        BOOL isDir;
        if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@",[self pathOfSimulator],device] isDirectory:&isDir] && isDir) {
            if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@/device.plist",[self pathOfSimulator],device]]) {
                NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@/device.plist",[self pathOfSimulator],device]];

                NSString *version = @"?";
                if ([self string:dict[@"runtime"] matchesRegularExpression:@"(com.apple.CoreSimulator.SimRuntime.)((?:[a-z][a-z]+))(-)(\\d+)(-)(\\d+)"]) {
                    NSString *platform = [self matchingSubstringOfString:dict[@"runtime"] forRegularExpression:@"((?:[a-z][a-z]+))(-)(\\d+)(-)(\\d+)"];
                    version = [platform stringByReplacingOccurrencesOfString:@"iOS-" withString:@"iOS "];
                    version = [version stringByReplacingOccurrencesOfString:@"-" withString:@"."];
                }

                BOOL isiOS7 = NO;
                if ([self string:dict[@"runtime"] matchesRegularExpression:@"(com)(\\.)(apple)(\\.)(CoreSimulator)(\\.)(SimRuntime)(\\.)(iOS)(-)(7)(-)(\\d+)"]) {
                    isiOS7 = YES;
                }
                BOOL validPlatform = NO;
                if ([self.listOfValidPlatforms containsObject:dict[@"runtime"]]) validPlatform = YES;

                if (!isiOS7 && validPlatform) [self.listOfSimulatorDevices addObject:@{@"UDID":dict[@"UDID"],@"name":dict[@"name"],@"runtime":dict[@"runtime"],@"version":version,@"index":@(index),@"iOS7":@(isiOS7)}];

                if (![self.listOfVersions containsObject:version] && !isiOS7 && validPlatform) [self.listOfVersions addObject:version];
            }
            index++;
        }
    }

    if (self.listOfVersions.count == 0) {
        NSAlert *alert = [NSAlert new];
        [alert addButtonWithTitle:@"Quit"];
        [alert setMessageText:@"No valid platforms found"];
        [alert setInformativeText:@"There are no valid platforms available for the Simulator. Please make sure that at least one iOS SDK is available."];
        [alert setAlertStyle:NSCriticalAlertStyle];
        [alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) {
            [[NSApplication sharedApplication] terminate:self];
        }];
        return;
    }

    [self buildVersionMenu];

    NSString *version = self.listOfVersions[0];

    self.listOfSimulatorDevicesInCurrentVersion = [NSMutableArray new];

    for (NSDictionary *dict in self.listOfSimulatorDevices) {
        if ([dict[@"version"] isEqualToString:version]) [self.listOfSimulatorDevicesInCurrentVersion addObject:dict];
    }

    NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
    NSArray *sortDescriptors = [NSArray arrayWithObject:descriptor];
    self.listOfSimulatorDevicesInCurrentVersion = [[self.listOfSimulatorDevicesInCurrentVersion sortedArrayUsingDescriptors:sortDescriptors] mutableCopy];

    [self buildDeviceMenuForIndex:0];
    self.currentDeviceIndex = 0;

    [self refreshApps:nil];
}

- (void)buildVersionMenu {
    NSInteger tag = 0;
    for (NSString *thisVersion in self.listOfVersions) {
        NSMenuItem *newItem = [[NSMenuItem alloc] initWithTitle:thisVersion action:@selector(selectVersion:) keyEquivalent:@""];
        [newItem setTarget:self];
        newItem.tag = tag;
        [self.versionButton.menu addItem:newItem];

        tag++;
    }
}

- (void)buildDeviceMenuForIndex:(NSInteger)index {
    NSString *thisVersion = self.listOfVersions[index];

    [self.deviceButton.menu removeAllItems];

    NSInteger tag = 0;
    for (NSDictionary *device in self.listOfSimulatorDevicesInCurrentVersion) {
        if ([device[@"version"] isEqualToString:thisVersion]) {
            NSMenuItem *newItem = [[NSMenuItem alloc] initWithTitle:device[@"name"] action:@selector(refreshApps:) keyEquivalent:@""];
            [newItem setTarget:self];
            newItem.tag = tag;
            [self.deviceButton.menu addItem:newItem];

            tag++;
        }
    }
}

- (IBAction)selectVersion:(NSMenuItem *)sender {
    NSString *version = self.listOfVersions[sender.tag];

    self.listOfSimulatorDevicesInCurrentVersion = [NSMutableArray new];

    for (NSDictionary *dict in self.listOfSimulatorDevices) {
        if ([dict[@"version"] isEqualToString:version]) [self.listOfSimulatorDevicesInCurrentVersion addObject:dict];
    }

    NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
    NSArray *sortDescriptors = [NSArray arrayWithObject:descriptor];
    self.listOfSimulatorDevicesInCurrentVersion = [[self.listOfSimulatorDevicesInCurrentVersion sortedArrayUsingDescriptors:sortDescriptors] mutableCopy];

    [self buildDeviceMenuForIndex:sender.tag];
    self.currentDeviceIndex = 0;

    [self refreshApps:nil];
}

- (IBAction)refreshApps:(id)sender {

    NSInteger index = 0;

    if ([sender isKindOfClass:[NSMenuItem class]]) {
        index = [(NSMenuItem *)sender tag];
        self.currentDeviceIndex = index;
    }

    [self.appsArray removeAllObjects];

    NSDictionary *device = self.listOfSimulatorDevicesInCurrentVersion[self.currentDeviceIndex];
    self.currentDeviceUDID = device[@"UDID"];

    NSString *appDataDir = [NSString stringWithFormat:@"%@/%@/data/Containers/Data/Application",[self pathOfSimulator],device[@"UDID"]];

    if ([device[@"iOS7"] boolValue]) {
        appDataDir = [NSString stringWithFormat:@"%@/%@/data/Applications",[self pathOfSimulator],device[@"UDID"]];
    }

    NSError *error;

    if (![[NSFileManager defaultManager] fileExistsAtPath:appDataDir]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:appDataDir withIntermediateDirectories:YES attributes:nil error:&error];
    }

    NSMutableDictionary *appData = [NSMutableDictionary new];

    for (NSString *thisAppData in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:appDataDir error:nil]) {
        BOOL isDir;

        if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@",appDataDir,thisAppData] isDirectory:&isDir] && isDir) {
            NSDictionary *metadata = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@/.com.apple.mobile_container_manager.metadata.plist",appDataDir,thisAppData]];
            if (metadata[@"MCMMetadataIdentifier"]) {
                [appData setValue:thisAppData forKey:metadata[@"MCMMetadataIdentifier"]];
            }
        }
    }

    self.currentDeviceDirectory = [NSString stringWithFormat:@"%@/%@/data/Containers/Bundle/Application",[self pathOfSimulator],device[@"UDID"]];

    [self.fileQueue removeAllPaths];
    [self.fileQueue addPath:self.currentDeviceDirectory];

    if (![[NSFileManager defaultManager] fileExistsAtPath:self.currentDeviceDirectory]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:self.currentDeviceDirectory withIntermediateDirectories:YES attributes:nil error:&error];
    }

    // Get installed apps
    NSArray *apps = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.currentDeviceDirectory error:nil];

    for (NSString *theApp in apps) {
        BOOL isDir;
        if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@",self.currentDeviceDirectory,theApp] isDirectory:&isDir] && isDir) {
            NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSString stringWithFormat:@"%@/%@",self.currentDeviceDirectory,theApp] error:nil];
            for (NSString *file in dirContents) {
                if ([file hasSuffix:@".app"]) {
                    NSDictionary *appDict = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@/%@/Info.plist",self.currentDeviceDirectory,theApp,file]];
                    NSString *appname = appDict[@"CFBundleDisplayName"];
                    if (!appname) appname = appDict[@"CFBundleName"];
                    if (!appname) appname = @"Unknown";
                    NSString *version = appDict[@"CFBundleShortVersionString"];
                    if (!version) version = @"?";
                    NSString *bundleIdentifier = appDict[@"CFBundleIdentifier"];
                    if (!bundleIdentifier) bundleIdentifier = @"?";
                    NSString *build = appDict[@"CFBundleVersion"];
                    if (!build) build = @"?";
                    NSString *dataDir = @"none";
                    if (appData[bundleIdentifier]) {
                        dataDir = appData[bundleIdentifier];
                    }

                    NSDictionary *thisApp = @{@"displayName":appname,@"version":version,@"build":build,@"bundleID":bundleIdentifier,@"udid":theApp,@"udid_data":dataDir,@"filename":file};
                    [self.appsArray addObject:thisApp];
                }
            }
        }
    }
    [self.tableView reloadData];
}

- (void)setupManager {
    [[self tableView] registerForDraggedTypes:[NSArray arrayWithObject:(NSString*)kUTTypeFileURL]];
    [self.tableView setTarget:self];
    [self.tableView setDoubleAction:@selector(doubleClick:)];
    self.fileQueue = [VDKQueue new];
    self.fileQueue.delegate = self;
}

- (IBAction)relaunchSimulator:(id)sender {
    NSArray *simulator = [NSRunningApplication runningApplicationsWithBundleIdentifier: @"com.apple.iphonesimulator"];

    if (simulator && simulator.count > 0) {
        int pid = [simulator[0] processIdentifier];

        // Kill it with fire:
        [[NSTask launchedTaskWithLaunchPath:@"/bin/kill" arguments:[NSArray arrayWithObjects:@"-hup",[NSString stringWithFormat:@"%i",pid], nil]] waitUntilExit];

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (![[NSWorkspace sharedWorkspace] launchApplication:[[NSUserDefaults standardUserDefaults] objectForKey:@"simulatorPath"]]) NSLog(@"iOS Simulator failed to launch");
        });
    } else {
        if (![[NSWorkspace sharedWorkspace] launchApplication:[[NSUserDefaults standardUserDefaults] objectForKey:@"simulatorPath"]]) NSLog(@"iOS Simulator failed to launch");
    }
}

- (IBAction)exportApp:(id)sender {

    NSInteger selectedRow = [self.tableView selectedRow];

    if (selectedRow == -1) {
        NSAlert *noRowSelectedAlert = [NSAlert new];
        [noRowSelectedAlert addButtonWithTitle:@"OK"];
        [noRowSelectedAlert setMessageText:@"No app selected"];
        [noRowSelectedAlert setInformativeText:@"Please select an app to export."];
        [noRowSelectedAlert setAlertStyle:NSInformationalAlertStyle];
        [noRowSelectedAlert beginSheetModalForWindow:self.window completionHandler:nil];

        return;
    }

    NSDictionary *appDict = self.appsArray[self.tableView.selectedRow];

    // create the save panel
    NSSavePanel *panel = [NSSavePanel savePanel];
    [panel setNameFieldStringValue:[NSString stringWithFormat:@"%@.simarchive",appDict[@"displayName"]]];
    NSButton *button = [[NSButton alloc] init];
    [button setButtonType:NSSwitchButton];
    button.title = @"Include the App's Document directory";
    [button sizeToFit];
    [panel setAccessoryView:button];
    button.state = NSOffState;
    self.includeDocumentsDirectory = NO;
    [panel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
        if (result == NSFileHandlingPanelOKButton) {
            NSURL *saveURL = [panel URL];

            NSURL *directoryURL = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]] isDirectory:YES];

            NSString *appDataDir = [NSString stringWithFormat:@"%@/%@/data/Containers/Data/Application",[self pathOfSimulator],self.currentDeviceUDID];

            NSError *error = nil;

            NSURL *tempTarget = [directoryURL URLByAppendingPathComponent:@"files"];

            [[NSFileManager defaultManager] createDirectoryAtURL:tempTarget withIntermediateDirectories:YES attributes:nil error:&error];

            if (error) {
                [self showErrorMessageWithTitle:@"An error occured" andMessage:error.description];
                return;
            }

            NSURL *bundleURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@",self.currentDeviceDirectory,appDict[@"udid"]]];

            [[NSFileManager defaultManager] copyItemAtURL:bundleURL toURL:[tempTarget URLByAppendingPathComponent:appDict[@"udid"]] error:&error];

            if (error) {
                [self showErrorMessageWithTitle:@"An error occured" andMessage:error.description];
                return;
            }

            NSString *appdata = @"none";

            if (button.state == NSOnState) {
                if (![appDict[@"udid_data"] isEqualToString:@"none"]) {
                    // include docs
                    NSURL *docsURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@",appDataDir,appDict[@"udid_data"]]];

                    [[NSFileManager defaultManager] copyItemAtURL:docsURL toURL:[tempTarget URLByAppendingPathComponent:appDict[@"udid_data"]] error:&error];

                    if (error) {
                        [self showErrorMessageWithTitle:@"An error occured" andMessage:error.description];
                        return;
                    }
                    appdata = appDict[@"udid_data"];
                }
            }

            NSDictionary *dataDict = @{@"displayName":appDict[@"displayName"],
                                       @"udid":appDict[@"udid"],
                                       @"udid_data":appdata,
                                       @"version":appDict[@"version"],
                                       @"build":appDict[@"build"],
                                       @"bundleID":appDict[@"bundleID"]
                                       };

            [dataDict writeToURL:[tempTarget URLByAppendingPathComponent:@"data.plist"] atomically:NO];

            if ([[NSFileManager defaultManager] fileExistsAtPath:[saveURL path]]) {
                [[NSFileManager defaultManager] removeItemAtURL:saveURL error:&error];
            }

            if (error) {
                [self showErrorMessageWithTitle:@"An error occured" andMessage:error.description];
                return;
            }

            NSURL *tmpFile = [directoryURL URLByAppendingPathComponent:panel.URL.lastPathComponent];

            [self zipFilesInDirectory:[tempTarget path] withTargetFile:[tmpFile path]];

            if (![[NSFileManager defaultManager] fileExistsAtPath:[tmpFile path]]) {
                // Something went wrong

                [[NSFileManager defaultManager] removeItemAtURL:directoryURL error:nil];

                NSAlert *alert = [NSAlert new];
                [alert addButtonWithTitle:@"OK"];
                [alert setMessageText:@"Export unsuccessful"];
                [alert setInformativeText:@"There was an error exporting the app. Please make sure that you have enough disk space on your Mac (at least twice the amount of the app you're trying to export)"];
                [alert setAlertStyle:NSCriticalAlertStyle];
                [alert beginSheetModalForWindow:self.window completionHandler:nil];
                return;
            }

            [[NSFileManager defaultManager] moveItemAtURL:tmpFile toURL:saveURL error:&error];
            if (error) {
                [self showErrorMessageWithTitle:@"An error occured" andMessage:error.description];
                return;
            }
            // cleanup

            [[NSFileManager defaultManager] removeItemAtURL:directoryURL error:&error];
        }
    }];
}

- (BOOL)zipFilesInDirectory:(NSString *)dir withTargetFile:(NSString *)targetFile {

    NSPipe *pipe = [NSPipe pipe];
    NSTask *task = [[NSTask alloc] init];
    task.launchPath = @"/usr/bin/ditto";
    task.arguments = @[@"-c", @"-k", @"--sequesterRsrc", @"--keepParent", dir, targetFile];
    task.standardOutput = pipe;

    [task launch];

    return YES;
}

- (BOOL)unzipFilesInDirectory:(NSString *)file toDirectory:(NSString *)targetDir {
    NSPipe *pipe = [NSPipe pipe];
    NSTask *task = [[NSTask alloc] init];
    task.launchPath = @"/usr/bin/unzip";
    task.arguments = @[@"-d", targetDir, file];
    task.standardOutput = pipe;

    [task launch];

    return YES;
}

- (IBAction)rowSelected:(id)sender {
    NSInteger selectedRow = [sender selectedRow];

    if (selectedRow != -1) {
        self.exportButton.enabled = YES;
        self.exportMenuItem.enabled = YES;
    }
    else {
        self.exportButton.enabled = NO;
        self.exportMenuItem.enabled = NO;
    }
}

- (IBAction)importApp:(id)sender {
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    panel.canChooseDirectories = NO;
    panel.allowsMultipleSelection = NO;
    panel.allowedFileTypes = @[@"simarchive"];
    NSButton *button = [[NSButton alloc] init];
    [button setButtonType:NSSwitchButton];
    button.title = @"Include the App's Document directory";
    [button sizeToFit];
    [panel setAccessoryView:button];
    button.state = NSOffState;
    self.includeDocumentsDirectory = NO;
    [panel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
        if (result == NSFileHandlingPanelOKButton) {
            BOOL copyData = NO;
            if (button.state == NSOnState) copyData = YES;

            [self importAppToCurrentDevice:[panel URL] withDocuments:copyData askForDocs:NO];
        }
    }];
}

- (BOOL)importAppToCurrentDevice:(NSURL *)fileURL withDocuments:(BOOL)documents askForDocs:(BOOL)askForDocs {

    NSError *error;

    NSURL *directoryURL = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]] isDirectory:YES];
    [[NSFileManager defaultManager] createDirectoryAtURL:directoryURL withIntermediateDirectories:YES attributes:nil error:&error];
    NSURL *tempTarget = [directoryURL URLByAppendingPathComponent:@"files"];

    [self unzipFilesInDirectory:[fileURL path] toDirectory:[directoryURL path]];

    if (![[NSFileManager defaultManager] fileExistsAtPath:[tempTarget path]] || ![[NSFileManager defaultManager] fileExistsAtPath:[[tempTarget URLByAppendingPathComponent:@"data.plist"] path]]) {
        // Something went wrong

        [[NSFileManager defaultManager] removeItemAtURL:directoryURL error:nil];

        NSAlert *alert = [NSAlert new];
        [alert addButtonWithTitle:@"OK"];
        [alert setMessageText:@"Import unsuccessful"];
        [alert setInformativeText:@"There was an error importing the app. Please make sure that the file is a SimArchive file and that you have enough disk space on your Mac (at least twice the amount of the archive you're trying to import)."];
        [alert setAlertStyle:NSCriticalAlertStyle];
        [alert beginSheetModalForWindow:self.window completionHandler:nil];
        return NO;
    }

    NSDictionary *appDict = [NSDictionary dictionaryWithContentsOfURL:[tempTarget URLByAppendingPathComponent:@"data.plist"]];
    NSString *bundleIdentifier = appDict[@"bundleID"];

    BOOL sameBundleID = NO;
    NSDictionary *sameBundleDict = [NSDictionary new];

    for (NSDictionary *otherAppDict in self.appsArray) {
        if ([otherAppDict[@"bundleID"] isEqualToString:bundleIdentifier]) {
            sameBundleID = YES;
            sameBundleDict = otherAppDict;
        }
    }

    if (sameBundleID) {
        [[NSFileManager defaultManager] removeItemAtURL:directoryURL error:nil];

        NSAlert *samebundleIDAlert = [NSAlert new];
        [samebundleIDAlert addButtonWithTitle:@"Move to Trash"];
        [samebundleIDAlert addButtonWithTitle:@"Cancel"];
        [samebundleIDAlert setMessageText:@"Duplicate bundle identifier"];
        [samebundleIDAlert setInformativeText:[NSString stringWithFormat:@"An app with the bundle identifier '%@' is already present on this simulator device. Would you like to move the existing app to the Trash and import the new app?",bundleIdentifier]];
        [samebundleIDAlert setAlertStyle:NSCriticalAlertStyle];
        [samebundleIDAlert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) {
            if (returnCode == 1000) {
                // Overwrite
                [self deleteAppWithDict:sameBundleDict];
                [self importAppToCurrentDevice:fileURL withDocuments:documents askForDocs:askForDocs];
            }
        }];
        return NO;
    }

    if (askForDocs) {
        if (![appDict[@"udid_data"] isEqualToString:@"none"]) {
            NSAlert *askForDocs = [NSAlert new];
            [askForDocs addButtonWithTitle:@"Yes, import"];
            [askForDocs addButtonWithTitle:@"No, ignore"];
            [askForDocs setMessageText:@"Import Documents directory?"];
            [askForDocs setInformativeText:@"This app archive includes a Documents directory. Do you want to import it as well?"];
            [askForDocs setAlertStyle:NSInformationalAlertStyle];
            [askForDocs beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) {
                NSError *error;

                NSURL *targetAppDir = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@",self.currentDeviceDirectory,appDict[@"udid"]]];
                NSURL *targetDataDir =  [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@/data/Containers/Data/Application/%@",[self pathOfSimulator],self.currentDeviceUDID,appDict[@"udid_data"]]];

                [[NSFileManager defaultManager] moveItemAtURL:[tempTarget URLByAppendingPathComponent:appDict[@"udid"]] toURL:targetAppDir error:&error];
                if (error) {
                    [self showErrorMessageWithTitle:@"An error occured" andMessage:error.description];
                    return;
                }
                if (returnCode == 1000) {
                    [[NSFileManager defaultManager] moveItemAtURL:[tempTarget URLByAppendingPathComponent:appDict[@"udid_data"]] toURL:targetDataDir error:&error];
                }
                [self refreshApps:nil];
                // cleanup

                [[NSFileManager defaultManager] removeItemAtURL:directoryURL error:&error];
            }];
        } else {
            NSError *error;

            NSURL *targetAppDir = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@",self.currentDeviceDirectory,appDict[@"udid"]]];
            NSURL *targetDataDir =  [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@/data/Containers/Data/Application/%@",[self pathOfSimulator],self.currentDeviceUDID,appDict[@"udid_data"]]];

            [[NSFileManager defaultManager] moveItemAtURL:[tempTarget URLByAppendingPathComponent:appDict[@"udid"]] toURL:targetAppDir error:&error];

            if (error) {
                [self showErrorMessageWithTitle:@"An error occured" andMessage:error.description];
            } else {
                if (documents) {
                    if (![appDict[@"udid_data"] isEqualToString:@"none"]) {
                        [[NSFileManager defaultManager] moveItemAtURL:[tempTarget URLByAppendingPathComponent:appDict[@"udid_data"]] toURL:targetDataDir error:&error];

                        if (error) [self showErrorMessageWithTitle:@"An error occured" andMessage:error.description];
                    }
                }
                [self refreshApps:nil];
            }
            // cleanup

            [[NSFileManager defaultManager] removeItemAtURL:directoryURL error:&error];
        }
    } else {
        NSError *error;

        NSURL *targetAppDir = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@",self.currentDeviceDirectory,appDict[@"udid"]]];
        NSURL *targetDataDir =  [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@/data/Containers/Data/Application/%@",[self pathOfSimulator],self.currentDeviceUDID,appDict[@"udid_data"]]];

        [[NSFileManager defaultManager] moveItemAtURL:[tempTarget URLByAppendingPathComponent:appDict[@"udid"]] toURL:targetAppDir error:&error];

        if (error) {
            [self showErrorMessageWithTitle:@"An error occured" andMessage:error.description];
        } else {
            if (documents) {
                if (![appDict[@"udid_data"] isEqualToString:@"none"]) {
                    [[NSFileManager defaultManager] moveItemAtURL:[tempTarget URLByAppendingPathComponent:appDict[@"udid_data"]] toURL:targetDataDir error:&error];

                    if (error) [self showErrorMessageWithTitle:@"An error occured" andMessage:error.description];

                }
            }
            [self refreshApps:nil];

        }
        // cleanup

        [[NSFileManager defaultManager] removeItemAtURL:directoryURL error:&error];
    }

    return YES;
}

- (BOOL)fileIsAcceptedFileType:(NSURL *)fileURL {
    NSURL *directoryURL = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]] isDirectory:YES];
    [[NSFileManager defaultManager] createDirectoryAtURL:directoryURL withIntermediateDirectories:YES attributes:nil error:nil];

    if ([[fileURL pathExtension] isEqualToString:@"simarchive"]) {
        NSTask *task = [[NSTask alloc] init];
        task.launchPath = @"/usr/bin/unzip";
        task.arguments = @[fileURL, @"\"files/data.plist\"", @"-d", directoryURL];

        [task launch];

        if ([[NSFileManager defaultManager] fileExistsAtPath:[[directoryURL URLByAppendingPathComponent:@"files/data.plist"] path]]) return YES;
    }
    [[NSFileManager defaultManager] removeItemAtURL:directoryURL error:nil];
    return NO;
}

#pragma mark - TableView delegate & data source

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
    return self.appsArray.count;
}

- (NSView *)tableView:(NSTableView *)tableView
   viewForTableColumn:(NSTableColumn *)tableColumn
                  row:(NSInteger)row {

    NSView *result;

    if (result == nil) {
        result = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 200, 30)];
        //result.identifier = @"resultCell";
    }

    NSDictionary *thisApp = self.appsArray[row];
    DSWVerticallyCenteredTextField *textFieldCell = [DSWVerticallyCenteredTextField new];

    NSTextField *name = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 200, 30)];
    [result addSubview:name];
    name.bezelStyle = 0;
    name.cell = textFieldCell;
    name.bordered = NO;
    name.backgroundColor = [NSColor clearColor];
    name.editable = NO;
    name.selectable = NO;

    if (tableColumn == self.nameColumn) {
        name.stringValue = thisApp[@"displayName"];
    } else if (tableColumn == self.versionColumn) {
        name.stringValue = thisApp[@"version"];
    } else if (tableColumn == self.buildColumn) {
            name.stringValue = thisApp[@"build"];
    } else if (tableColumn == self.bundleIdentifierColumn) {
        name.stringValue = thisApp[@"bundleID"];
    }
    return result;
}

- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row {
    return 30.0f;
}

#pragma mark - Drag & Drop

- (NSDragOperation)tableView:(NSTableView *)aTableView validateDrop:(id < NSDraggingInfo >)info proposedRow:(NSInteger)row proposedDropOperation:(NSTableViewDropOperation)operation {
    //get the file URLs from the pasteboard
    NSPasteboard *pasteBoard = info.draggingPasteboard;

    //list the file type UTIs we want to accept
    NSArray *acceptedType = [NSArray arrayWithObject:(NSString*)kUTTypeItem];

    NSArray *urls = [pasteBoard readObjectsForClasses:[NSArray arrayWithObject:[NSURL class]] options:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],NSPasteboardURLReadingFileURLsOnlyKey,acceptedType, NSPasteboardURLReadingContentsConformToTypesKey,
                                               nil]];

    //only allow drag if there is exactly one file
    if (urls.count != 1) return NSDragOperationNone;
   // if (![self fileIsAcceptedFileType:urls[0]]) return NSDragOperationNone;

    return NSDragOperationCopy;
}

- (BOOL)tableView:(NSTableView *)tableView acceptDrop:(id<NSDraggingInfo>)info row:(NSInteger)row dropOperation:(NSTableViewDropOperation)dropOperation {
    NSPasteboard *pboard = [info draggingPasteboard];

    if ( [[pboard types] containsObject:NSURLPboardType] ) {
        NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];

        [self importAppToCurrentDevice:[NSURL fileURLWithPath:files[0]] withDocuments:NO askForDocs:YES];
    }

    return YES;
}

#pragma mark - DoubleClick

- (void)doubleClick:(id)sender {
    NSInteger rowNumber = [self.tableView clickedRow];

    NSString *appDataDir = [NSString stringWithFormat:@"%@/%@/data/Containers/Data/Application",[self pathOfSimulator],self.currentDeviceUDID];

    if (self.appsArray.count > 0 && rowNumber < self.appsArray.count) {
        NSDictionary *appDict = self.appsArray[rowNumber];

        if (appDict) {
            if (![appDict[@"udid_data"] isEqualToString:@"none"]) [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:@[[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@",appDataDir,appDict[@"udid_data"]]]]];
        }
    }
}

#pragma mark - Context Menu and methods

- (NSMenu *)tableView:(NSTableView *)aTableView menuForRows:(NSIndexSet *)rows {
    NSMenu *contextMenu = [NSMenu new];
    contextMenu.autoenablesItems = NO;

    NSMenuItem *showInFinderItem = [[NSMenuItem alloc] initWithTitle:@"Show in Finder" action:@selector(showInFinder:) keyEquivalent:@""];
    showInFinderItem.target = self;
    showInFinderItem.tag = rows.firstIndex;
    [contextMenu addItem:showInFinderItem];

    NSMenuItem *showDocumentsInFinderItem = [[NSMenuItem alloc] initWithTitle:@"Show Documents in Finder" action:@selector(showDocumentsInFinder:) keyEquivalent:@""];
    showDocumentsInFinderItem.target = self;
    showDocumentsInFinderItem.tag = rows.firstIndex;
    [contextMenu addItem:showDocumentsInFinderItem];

    [contextMenu addItem:[NSMenuItem separatorItem]];

    NSMenuItem *deleteAppItem = [[NSMenuItem alloc] initWithTitle:@"Move to Trash" action:@selector(deleteApp:) keyEquivalent:@""];
    deleteAppItem.target = self;
    deleteAppItem.tag = rows.firstIndex;
    [contextMenu addItem:deleteAppItem];

    return contextMenu;
}

- (void)showInFinder:(NSMenuItem *)sender {

    if (self.appsArray.count > 0 && sender.tag < self.appsArray.count) {
        NSDictionary *appDict = self.appsArray[sender.tag];

        if (appDict) {
            if (![appDict[@"udid"] isEqualToString:@"none"]) [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:@[[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@/%@",self.currentDeviceDirectory,appDict[@"udid"],appDict[@"filename"]]]]];
        }
    }
}

- (void)showDocumentsInFinder:(NSMenuItem *)sender {
    NSString *appDataDir = [NSString stringWithFormat:@"%@/%@/data/Containers/Data/Application",[self pathOfSimulator],self.currentDeviceUDID];

    if (self.appsArray.count > 0 && sender.tag < self.appsArray.count) {
        NSDictionary *appDict = self.appsArray[sender.tag];

        if (appDict) {
            if (![appDict[@"udid_data"] isEqualToString:@"none"]) [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:@[[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@",appDataDir,appDict[@"udid_data"]]]]];
        }
    }
}

- (void)deleteApp:(NSMenuItem *)sender {
    if (self.appsArray.count > 0 && sender.tag < self.appsArray.count) {
        NSDictionary *appDict = self.appsArray[sender.tag];

        [self deleteAppWithDict:appDict];
    }
}

- (void)deleteAppWithDict:(NSDictionary *)appDict {
    NSString *appDataDir = [NSString stringWithFormat:@"%@/%@/data/Containers/Data/Application",[self pathOfSimulator],self.currentDeviceUDID];

    if (appDict) {
        [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation
                                                     source:self.currentDeviceDirectory
                                                destination:@""
                                                      files:@[appDict[@"udid"]]
                                                        tag:nil];

        if ([[NSUserDefaults standardUserDefaults] boolForKey:@"includeDocuments"]) {
            [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation
                                                         source:appDataDir
                                                    destination:@""
                                                          files:@[appDict[@"udid_data"]]
                                                            tag:nil];
        }
    }
    [self refreshApps:nil];
}

- (IBAction)openAboutWindow:(id)sender {
    self.aboutWindowController = [DCOAboutWindowController new];
    self.aboutWindowController.appWebsiteURL = [NSURL URLWithString:@"http://fouquet.me/apps/simarchive"];
    self.aboutWindowController.useTextViewForAcknowledgments = YES;
    [self.aboutWindowController showWindow:nil];
}

- (void)showErrorMessageWithTitle:(NSString *)title andMessage:(NSString *)message {
    NSAlert *errorAlert = [NSAlert new];
    [errorAlert addButtonWithTitle:@"OK"];
    [errorAlert setMessageText:title];
    [errorAlert setInformativeText:message];
    [errorAlert setAlertStyle:NSCriticalAlertStyle];
    [errorAlert beginSheetModalForWindow:self.window completionHandler:nil];
}

#pragma mark - Regex helper methods

- (BOOL)string:(NSString *)inputString matchesRegularExpression:(NSString *)regex {
    if (!inputString) return NO;

    return [[NSRegularExpression regularExpressionWithPattern:regex options:NSRegularExpressionCaseInsensitive error:nil] numberOfMatchesInString:inputString options:0 range:NSMakeRange(0, inputString.length)];
}

- (NSString *)matchingSubstringOfString:(NSString *)inputString forRegularExpression:(NSString *)regex {
    if (!inputString) return nil;

    NSRegularExpression *valueRegEx = [NSRegularExpression regularExpressionWithPattern:regex options:NSRegularExpressionCaseInsensitive error:nil];
    NSTextCheckingResult *match = [valueRegEx firstMatchInString:inputString options:0 range:NSMakeRange(0, inputString.length)];

    return [inputString substringWithRange:match.range];
}

#pragma mark - Other

- (NSString *)developerDirectory {
    NSDictionary* env = [[NSProcessInfo processInfo] environment];
    NSString* developerDir = [env objectForKey:@"DEVELOPER_DIR"];
    if ([developerDir length] > 0) {
        return developerDir;
    }

    // Go look for it via xcode-select.
    NSTask* xcodeSelectTask = [[NSTask alloc] init];
    [xcodeSelectTask setLaunchPath:@"/usr/bin/xcode-select"];
    [xcodeSelectTask setArguments:[NSArray arrayWithObject:@"-print-path"]];

    NSPipe* outputPipe = [NSPipe pipe];
    [xcodeSelectTask setStandardOutput:outputPipe];
    NSFileHandle* outputFile = [outputPipe fileHandleForReading];

    [xcodeSelectTask launch];
    NSData* outputData = [outputFile readDataToEndOfFile];
    [xcodeSelectTask terminate];

    NSString* output = [[NSString alloc] initWithData:outputData encoding:NSUTF8StringEncoding];
    output = [output stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if ([output length] == 0) {
        output = nil;
    }
    return output;
}

- (NSString *)XcodeVersion {
    // Go look for it via xcodebuild.
    NSTask* xcodeBuildTask = [[NSTask alloc] init];
    [xcodeBuildTask setLaunchPath:@"/usr/bin/xcodebuild"];
    [xcodeBuildTask setArguments:[NSArray arrayWithObject:@"-version"]];

    NSPipe* outputPipe = [NSPipe pipe];
    [xcodeBuildTask setStandardOutput:outputPipe];
    NSFileHandle* outputFile = [outputPipe fileHandleForReading];

    [xcodeBuildTask launch];
    NSData* outputData = [outputFile readDataToEndOfFile];
    [xcodeBuildTask terminate];

    NSString* output = [[NSString alloc] initWithData:outputData encoding:NSUTF8StringEncoding];
    output = [output stringByTrimmingCharactersInSet:
              [NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if ([output length] == 0) {
        output = nil;
    } else {
        NSArray* parts = [output componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if ([parts count] >= 2) {
            return parts[1];
        }
    }
    return output;
}

- (void)getValidPlatforms {
    NSPipe *pipe = [NSPipe pipe];
    NSFileHandle *file = pipe.fileHandleForReading;
    NSTask *task = [[NSTask alloc] init];
    task.launchPath = [NSString stringWithFormat:@"%@/usr/bin/simctl",[self developerDirectory]];
    task.arguments = @[@"list", @"runtimes"];
    task.standardOutput = pipe;

    [task launch];

    NSData *data = [file readDataToEndOfFile];
    [file closeFile];

    NSMutableArray *fileLines = [[NSMutableArray alloc] initWithArray:[[[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding] componentsSeparatedByString:@"\n"] copyItems: YES];

    self.listOfValidPlatforms = [NSMutableArray new];

    for (NSString *line in fileLines) {
        if ([line containsString:@"com.apple.CoreSimulator.SimRuntime"] && ![line containsString:@"unavailable"]) {
            NSString *output = [self matchingSubstringOfString:line forRegularExpression:@"(com.apple.CoreSimulator.SimRuntime.)((?:[a-z][a-z]+))(-)(\\d+)(-)(\\d+)"];
            [self.listOfValidPlatforms addObject:output];
        }
    }

}

#pragma mark - Folder change notification

- (void)VDKQueue:(VDKQueue *)queue receivedNotification:(NSString *)noteName forPath:(NSString *)fpath {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self refreshApps:nil];
    });
}

@end


text:
// unittest.cpp : Defines the entry point for the DLL application.
//

#include "stdafx.h"
/*
BOOL APIENTRY DllMain( HANDLE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
           )
{
    return TRUE;
}

*/

#include <cppunit/plugin/TestPlugIn.h>
CPPUNIT_PLUGIN_IMPLEMENT();


text: Returns the mesh as a vector of unique ofMeshFaces.


text:
ALL_ELEMENTS="accumulo,datafu,falcon,flume,hadoop,hbase,hive,kafka,knox,mahout,oozie,phoenix,pig,slider,sqoop,tez,zookeeper"

#hadoop,hbase,hive,pig,oozie,zookeeper,accumulo,storm,falcon,falcon-server,knox,phoenix,tez,tez-full,flume,sqoop,mahout"

HDP_VER=2.2.4.2-2
HTTP_BASE="http://public-repo-1.hortonworks.com/HDP/centos6/2.x/updates/2.2.4.2/tars/"

TOOLS_BASE="http://public-repo-1.hortonworks.com/HDP/tools/2.2.0.0/"
COMPANION_FILE_BASE="hdp_manual_install_rpm_helper_files-2.2.0.0.2041"

# DEFAULT_FILES_BASE="https://raw.github.com/dstreev/HDP_1.3.0_Mac_Utils/master/"
# DEFAULT_FILES="etc_default"

LIB_BASE_DIR=/usr/hdp
DEFAULT_DIR=/etc/default

BASE_DIR=$HOME/hadoop
HDFS_BASE_DIR=$BASE_DIR/hdfs-data

MYSQL_ARCHIVE=mysql-connector-java-5.1.31

HADOOP_CONF_DIR=/var/hadoop/local/$HDP_VER

MYSQL_JDBC_JAR=/usr/share/java/

HOSTNAME=localhost

HIVE_DB_NAME=hivemetastore2
HIVE_DB_USER=hive
HIVE_DB_PASSWORD=hive

OOZIE_DB_NAME=oozie2
OOZIE_DB_USER=oozie
OOZIE_DB_PASSWORD=oozie


text:
package org.jclouds.orion.http.filters.create;

import org.jclouds.http.HttpException;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpRequestFilter;
import org.jclouds.orion.blobstore.functions.converters.JSONToOrionSpecificObject;
import org.jclouds.orion.blobstore.functions.converters.OrionSpecificObjectToJSON;
import org.jclouds.orion.domain.OrionSpecificFileMetadata;

import com.google.common.base.Preconditions;
import com.google.inject.Inject;

/**
 * Make Hidden attribute of file attributes true in the request
 *
 * @author Timur
 *
 */
public class CreateHiddenFileFilter implements HttpRequestFilter {

	private final JSONToOrionSpecificObject json2OrionSpecificObj;
	private final OrionSpecificObjectToJSON orionSpecificObject2JSON;

	@Inject
	public CreateHiddenFileFilter(OrionSpecificFileMetadata metadata, JSONToOrionSpecificObject json2OrionSpecificObj,
	      OrionSpecificObjectToJSON orionSpecificObject2JSON) {
		this.json2OrionSpecificObj = Preconditions.checkNotNull(json2OrionSpecificObj, "json2OrionSpecificObjis null");
		this.orionSpecificObject2JSON = Preconditions.checkNotNull(orionSpecificObject2JSON,
		      "orionSpecificObject2JSON is null");
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.jclouds.http.HttpRequestFilter#filter(org.jclouds.http.HttpRequest )
	 */
	@Override
	public HttpRequest filter(HttpRequest request) throws HttpException {
		OrionSpecificFileMetadata metadata;
		metadata = this.json2OrionSpecificObj.apply((String) request.getPayload().getRawContent());
		metadata.getAttributes().setHidden(true);
		request = request.toBuilder().payload(this.orionSpecificObject2JSON.apply(metadata)).build();
		return request;
	}

}


text:
<?php defined('SYSPATH') or die('No direct script access.');

abstract class Controller_Site extends Controller_Template
{
	/**
	 * @var string
	 */
	public $template = 'site/template';

	/**
	 * @var string
	 */
	public $header = 'site/header';

	/**
	 * @var Kohana_View
	 */
	public $view;

	/**
	 * @var string
	 */
	public $footer = 'site/footer';

	/**
	 * Asset helper
	 *
	 * @var Kollection_Asset
	 */
	public $asset;

	/**
	 * before()
	 *
	 * Called before action is called
	 */
	public function before()
	{
		parent::before();

		// Initialize asset
		$config = Kohana::$config->load('asset');

		// Load config by environment
		$this->asset = new Kollection_Asset($config[Kohana::$environment]);

		// Set asset helper to view globally
		View::set_global('asset', $this->asset);

		if ($this->auto_render)
		{
			$this->template->styles = array(
				$this->asset->asset_url('/media/bootstrap/css/bootstrap.min.css') => 'screen, projection',
				$this->asset->asset_url('/media/css/style.css')	=> 'screen, projection'
			);

			$this->template->scripts = array(
				$this->asset->asset_url('/media/js/jquery-1.6.4.min.js')
			);
		}
	}

	/**
	 * after()
	 *
	 * @see system/classes/kohana/controller/Kohana_Controller_Template#after()
	 */
	public function after()
	{
		if ($this->auto_render)
		{
			// template disyplay logic
			$this->template->header = View::factory($this->header);
			$this->template->content = $this->view;

			$this->template->footer = View::factory($this->footer);
		}

		return parent::after();
	}
}


text:
package com.sequenceiq.cloudbreak.core.flow2.chain;

import static com.sequenceiq.cloudbreak.core.flow2.cluster.upscale.ClusterUpscaleEvent.CLUSTER_UPSCALE_TRIGGER_EVENT;
import static com.sequenceiq.cloudbreak.core.flow2.stack.sync.StackSyncEvent.STACK_SYNC_EVENT;
import static com.sequenceiq.cloudbreak.core.flow2.stack.upscale.StackUpscaleEvent.ADD_INSTANCES_EVENT;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import javax.inject.Inject;

import org.springframework.stereotype.Component;

import com.sequenceiq.cloudbreak.cloud.event.Selectable;
import com.sequenceiq.cloudbreak.common.type.ScalingType;
import com.sequenceiq.cloudbreak.core.flow2.event.ClusterScaleTriggerEvent;
import com.sequenceiq.cloudbreak.core.flow2.event.StackAndClusterUpscaleTriggerEvent;
import com.sequenceiq.cloudbreak.core.flow2.event.StackScaleTriggerEvent;
import com.sequenceiq.cloudbreak.core.flow2.event.StackSyncTriggerEvent;
import com.sequenceiq.cloudbreak.domain.Cluster;
import com.sequenceiq.cloudbreak.domain.HostGroup;
import com.sequenceiq.cloudbreak.domain.Stack;
import com.sequenceiq.cloudbreak.service.hostgroup.HostGroupService;
import com.sequenceiq.cloudbreak.service.stack.StackService;

@Component
public class UpscaleFlowEventChainFactory implements FlowEventChainFactory<StackAndClusterUpscaleTriggerEvent> {
    @Inject
    private StackService stackService;

    @Inject
    private HostGroupService hostGroupService;

    @Override
    public String initEvent() {
        return FlowChainTriggers.FULL_UPSCALE_TRIGGER_EVENT;
    }

    @Override
    public Queue<Selectable> createFlowTriggerEventQueue(StackAndClusterUpscaleTriggerEvent event) {
        Stack stack = stackService.getById(event.getStackId());
        Cluster cluster = stack.getCluster();
        Queue<Selectable> flowEventChain = new ConcurrentLinkedQueue<>();
        flowEventChain.add(new StackSyncTriggerEvent(STACK_SYNC_EVENT.event(), event.getStackId(), false, event.accepted()));
        flowEventChain.add(new StackScaleTriggerEvent(ADD_INSTANCES_EVENT.event(), event.getStackId(), event.getInstanceGroup(),
                event.getAdjustment(), event.getHostNames()));
        if (ScalingType.isClusterUpScale(event.getScalingType()) && cluster != null) {
            HostGroup hostGroup = hostGroupService.getByClusterIdAndInstanceGroupName(cluster.getId(), event.getInstanceGroup());
            flowEventChain.add(new ClusterScaleTriggerEvent(CLUSTER_UPSCALE_TRIGGER_EVENT.event(), stack.getId(), hostGroup.getName(),
                    event.getAdjustment()));
        }
        return flowEventChain;
    }
}


text:
@implementation RWTTile

@end


text:
package org.knowm.xdropwizard.resources;

import java.io.IOException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.knowm.xchart.BitmapEncoder;
import org.knowm.xchart.BitmapEncoder.BitmapFormat;
import org.knowm.xchart.QuickChart;
import org.knowm.xchart.XYChart;

/** @author timmolter */
@Path("xchart")
public class XChartResource {

  @GET
  @Path("random.png")
  @Produces("image/png")
  public Response getRandomLineChart() throws IOException {

    XYChart chart =
        QuickChart.getChart(
            "XChart Sample - Random Walk", "X", "Y", null, null, getRandomWalk(105));

    return Response.ok()
        .type("image/png")
        .entity(BitmapEncoder.getBitmapBytes(chart, BitmapFormat.PNG))
        .build();
  }

  private double[] getRandomWalk(int numPoints) {

    double[] y = new double[numPoints];
    for (int i = 1; i < y.length; i++) {
      y[i] = y[i - 1] + Math.random() - .5;
    }
    return y;
  }
}


text:
const puppeteer = require('puppeteer');
const fs = require('fs')

const CRX_PATH = '../web-extension';
const REFERENCE_EBOOK_PATH = 'reference-ebook'
const TEST_RESULT_EBOOK_PATH = 'test-result-ebook'
const TEST_EBOOK_FILE_NAME = 'test.epub'

const testPaths = [

]

puppeteer.launch({
  headless: false,
  args: [
    `--disable-extensions-except=${CRX_PATH}`,
    `--load-extension=${CRX_PATH}`,
    '--user-agent=PuppeteerTestingAgent'
  ]
}).then(async browser => {

    prepareTests()

    await runLocalFullPageTests(browser)
});

async function runLocalFullPageTests(browser) {

    const testedFileName = 'mathjax' //'canvas' //'svg' //'special-chars' // 'p2' //'p1'

    const testUrl = 'file://'+__dirname+'/pages/'+testedFileName+'/page/index.html'
    const resultDownloadPath = './pages/'+testedFileName+'/' + TEST_RESULT_EBOOK_PATH

    const page = await browser.newPage();
    await page._client.send('Page.setDownloadBehavior', {behavior: 'allow', downloadPath: resultDownloadPath});
    await page.setViewport({ width: 1280, height: 800 })
    // await page.goto('https://en.wikipedia.org/wiki/E-book', { waitUntil: 'networkidle0' });
    // await page.goto('file://'+__dirname+'/../pages/p1/E-book - Wikipedia.html', { waitUntil: 'networkidle0' });
    await page.goto(testUrl, { waitUntil: 'networkidle0' });
}

function prepareTests() {
  const testedFileName = 'p1'
  const pathToDelete = './pages/'+testedFileName+'/'+TEST_RESULT_EBOOK_PATH+'/'+TEST_EBOOK_FILE_NAME
  try {
    if (fs.existsSync(pathToDelete)) {
      fs.unlinkSync(pathToDelete)
    }
  } catch(err) {
    console.log('Error while deleting file ', err);
  }
}


text:
class Commentaire < ActiveRecord::Base
  belongs_to :projet
  belongs_to :contributeur
  validates_presence_of :message
end


text:
package org.jboss.hal.resources;

import org.jboss.hal.spi.GinModule;

import com.google.gwt.inject.client.AbstractGinModule;
import com.google.inject.Singleton;

@GinModule
public class ResourcesModule extends AbstractGinModule {

    @Override
    protected void configure() {
        bind(Resources.class).in(Singleton.class);
    }
}


text:
(function($) {

  $.flipbooker = function(imgArr, options) {

    var opts = $.extend(true, {}, $.flipbooker.defaults, options),
        currentIndex = 0,
        $container = $(opts.container),
        image,
        $image,
        $caption,
        imgArrSize = imgArr.length,
        currentImg;

    // set up the container styles
    $container.css({
      'height': opts.height,
      'width': opts.width,
      'position': 'relative',
      'overflow': 'hidden'
    });

    // set up the image element
    image = new Image();
    $image = $(image).appendTo($container);
    $caption = $('<div>').appendTo($container);

    function plugin(){

      // set the image source to the currentImg
      // object's source or image.src value and fit it to the container
      currentImg = imgArr[currentIndex];
      if (currentImg.source) {
        $image[0].src = currentImg.source;
      } else {
        image.src = currentImg.image.src;
      }

      // add the caption text
      if (currentImg.caption) {
        $caption.text(currentImg.caption).addClass('image-cap');

        // apply the appropriate caption position
        applyClasses(currentImg.captionPosition);

      } else {
        $caption.text('').removeClass('image-cap');
      }

      function applyClasses(captionPosition){
        var cases = {
          'Top Left': function($caption){
            $caption.removeClass('cap-bottom cap-right');
            $caption.addClass('cap-top cap-left');
          },
          'Top Right': function($caption){
            $caption.removeClass('cap-bottom cap-left');
            $caption.addClass('cap-top cap-right');
          },
          'Bottom Left': function($caption){
            $caption.removeClass('cap-top cap-right');
            $caption.addClass('cap-bottom cap-left');
          },
          'Bottom Right': function($caption){
            $caption.removeClass('cap-top cap-left');
            $caption.addClass('cap-bottom cap-right');
          },
          _default: function($caption){
            $caption.removeClass('cap-bottom cap-right');
            $caption.addClass('cap-top cap-left');
          }
        };

        if (captionPosition) {
          cases[captionPosition].call(cases, $caption);
        } else {
          cases._default($caption);
        }
      }

      // pause if the currentImg object requests it, otherwise
      // recursively call the function with the normal delay
      if (currentImg.pause) {
        looper = setTimeout(plugin, currentImg.pause);
      } else {
        looper = setTimeout(plugin, opts.delay);
      }

      // move onto the next image object
      currentIndex++;

      // after all images have been cycled through
      if (currentIndex >= imgArrSize) {

        // fire callback and reset the index
        opts.cb.call(this);
        currentIndex = 0;

        // loop?
        if (!opts.loop) {
          $.flipbooker.pause();
        }
      }
    }

    // start the initial loop
    var looper = setTimeout(plugin, opts.delay);

    // listen for events
    $(window).on('pause:flipbooker', function(){
      clearTimeout(looper);
    });
    $(window).on('play:flipbooker', function(){
      looper = setTimeout(plugin, opts.delay);
    });

  };

  // Utilities and defaults
  $.flipbooker.pause = function(){
    $(window).trigger('pause:flipbooker');
  };

  $.flipbooker.play = function(){
    $(window).trigger('play:flipbooker');
  };

  $.flipbooker.defaults = {
    container: '#flipbook',
    loop: true,
    delay: 100,
    height: '400px',
    width: '400px',
    cb: function(){}
  };

}(jQuery));


text:
using Estranged.Lfs.Data;
using Microsoft.Extensions.DependencyInjection;

namespace Estranged.Lfs.Authenticator.BitBucket
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection AddLfsBitBucketAuthenticator(this IServiceCollection services, IBitBucketAuthenticatorConfig config)
        {
            return services.AddSingleton<IAuthenticator, BitBucketAuthenticator>()
                           .AddSingleton<IBitBucketClientFactory, BitBucketClientFactory>()
                           .AddSingleton(config);
        }
    }
}


text:
package com.cloud.agent.api;

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

import org.apache.cloudstack.storage.to.VolumeObjectTO;

public class RestoreVMSnapshotCommand extends VMSnapshotBaseCommand {

    List<VMSnapshotTO> snapshots;
    Map<Long, VMSnapshotTO> snapshotAndParents;

    public RestoreVMSnapshotCommand(String vmName, VMSnapshotTO snapshot, List<VolumeObjectTO> volumeTOs, String guestOSType) {
        super(vmName, snapshot, volumeTOs, guestOSType);
    }

    public List<VMSnapshotTO> getSnapshots() {
            return snapshots;
    }

    public void setSnapshots(List<VMSnapshotTO> snapshots) {
        this.snapshots = snapshots;
    }

    public Map<Long, VMSnapshotTO> getSnapshotAndParents() {
        return snapshotAndParents;
    }

    public void setSnapshotAndParents(Map<Long, VMSnapshotTO> snapshotAndParents) {
        this.snapshotAndParents = snapshotAndParents;
    }

}


text:
import isomorphicFetch from "isomorphic-fetch";

it("should run", () => {
	expect(
		__STATS__.modules.find(m => m.name.includes("isomorphic-fetch")).chunks
	).toHaveLength(1);
});


text:
/*!
 http://www.w3.org/TR/SVG/coords.html#InterfaceSVGPoint

 interface SVGPoint {

 attribute float x setraises(DOMException);
 attribute float y setraises(DOMException);

 SVGPoint matrixTransform(in SVGMatrix matrix);
 };
 */
#import <Foundation/Foundation.h>

#import "SVGMatrix.h"

@interface SVGPoint : NSObject

@property(nonatomic,readonly) float x, y;

-(SVGPoint*) matrixTransform:(SVGMatrix*) matrix;

@end


text:
package com.habosa.dotdotdash;

import android.content.Context;
import android.inputmethodservice.Keyboard;

public class MorseKeyboard extends Keyboard {

    public MorseKeyboard(Context context, int xmlLayoutResId) {
        super(context, xmlLayoutResId);
    }

}


text:
<script src="/js/angular/angular.js"></script>
<script src="/js/angular/angular-route.js"></script>
@yield('additional_angular_js')
<script src="/js/angular/services/AjaxService.js"></script>
<script src="/js/angular/services/TableService.js"></script>
<script src="/js/angular/controllers/TableController.js"></script>
<script src="/js/angular/app.js"></script>
@yield('additional_js')


text:
package libpod

import (
	"github.com/containers/podman/v3/libpod/define"
	"github.com/containers/podman/v3/libpod/layers"
	"github.com/containers/storage/pkg/archive"
	"github.com/pkg/errors"
)

var initInodes = map[string]bool{
	"/dev":               true,
	"/etc/hostname":      true,
	"/etc/hosts":         true,
	"/etc/resolv.conf":   true,
	"/proc":              true,
	"/run":               true,
	"/run/notify":        true,
	"/run/.containerenv": true,
	"/run/secrets":       true,
	"/sys":               true,
	"/etc/mtab":          true,
}

// GetDiff returns the differences between the two images, layers, or containers
func (r *Runtime) GetDiff(from, to string, diffType define.DiffType) ([]archive.Change, error) {
	toLayer, err := r.getLayerID(to, diffType)
	if err != nil {
		return nil, err
	}
	fromLayer := ""
	if from != "" {
		fromLayer, err = r.getLayerID(from, diffType)
		if err != nil {
			return nil, err
		}
	}
	var rchanges []archive.Change
	changes, err := r.store.Changes(fromLayer, toLayer)
	if err == nil {
		for _, c := range changes {
			if initInodes[c.Path] {
				continue
			}
			rchanges = append(rchanges, c)
		}
	}
	return rchanges, err
}

// GetLayerID gets a full layer id given a full or partial id
// If the id matches a container or image, the id of the top layer is returned
// If the id matches a layer, the top layer id is returned
func (r *Runtime) getLayerID(id string, diffType define.DiffType) (string, error) {
	var lastErr error
	if diffType&define.DiffImage == define.DiffImage {
		toImage, _, err := r.libimageRuntime.LookupImage(id, nil)
		if err == nil {
			return toImage.TopLayer(), nil
		}
		lastErr = err
	}

	if diffType&define.DiffContainer == define.DiffContainer {
		toCtr, err := r.store.Container(id)
		if err == nil {
			return toCtr.LayerID, nil
		}
		lastErr = err
	}

	if diffType == define.DiffAll {
		toLayer, err := layers.FullID(r.store, id)
		if err == nil {
			return toLayer, nil
		}
		lastErr = err
	}
	return "", errors.Wrapf(lastErr, "%s not found", id)
}


text:
namespace anl
{
    CImplicitConstant::CImplicitConstant() : m_constant(0){}
    CImplicitConstant::CImplicitConstant(double c) : m_constant(c){}
	CImplicitConstant::~CImplicitConstant(){}

	void CImplicitConstant::setConstant(double c){m_constant=c;}

	double CImplicitConstant::get(double x, double y){return m_constant;}
	double CImplicitConstant::get(double x, double y, double z){return m_constant;}
	double CImplicitConstant::get(double x, double y, double z, double w){return m_constant;}
	double CImplicitConstant::get(double x, double y, double z, double w, double u, double v){return m_constant;}
};


text:
<?php
namespace Cohensive\Upload;

class FileExistsException extends \Exception
{
    /**
     * @var string
     */
    protected $name;

    /**
     * Constructor.
     *
     * @param string     $name
     * @param int        $code
     * @param \Exception $previous
     */
    public function __construct($name, $code = 0, \Exception $previous = null)
    {
        $this->name = $name;

        parent::__construct('File with name ' . $name . ' alreadyExists.', $code, $previous);
    }

    /**
     * Returns input name that was not found
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }
}


text: long longVal = ((long)intVal) << 32; // GOOD


text:
'use strict';

var request = require('request');
var querystring = require('querystring');
var util = require('util');

var RDK_IP = process.env.RDK_IP || '10.4.4.105';
var RDK_PORT = process.env.RDK_PORT || '8888';

// describe('getDayToQuantity Resource', function() {
//     it('tests that getResourceConfig() is setup correctly', function() {
//         var resources = writebackmedoperationaldata._getResourceConfig();

//         expect(resources[8].name).toEqual('daytoquantity');
//         expect(resources[8].path).toEqual('/daytoquantity');
//         expect(resources[8].interceptors).toEqual(['metrics', 'audit', 'operationalDataCheck', 'authentication']);
//         expect(resources[8].healthcheck).toBeDefined();
//     });
// });

describe('call function getDayToQuantity', function() {
    it('calls VistaJS correctly', function() {
        var error;
        var response;
        var body;
        runs(function() {
            // TODO: get the resource URL from the resource directory like acceptance tests.
            var resourcePath = '/resource/writeback/med/daytoquantity';
            var resource = util.format('http://%s:%s%s', RDK_IP, RDK_PORT, resourcePath);
            var parameters = {
                supply: '30',
                dose: '1',
                schedule: 'QDAY',
                duration: '~',
                patientIEN: '3',
                drugIEN: '461'
            };

            parameters.accessCode = 'pu1234';
            parameters.verifyCode = 'pu1234!!';
            parameters.site = '9E7A';
            var url = resource + '?' + querystring.stringify(parameters);
            console.log(url);
            request.get(url, function(myError, myResponse, myBody) {
                error = myError;
                response = myResponse;
                body = myBody;
            });
        });

        waitsFor(function() {
            return error + response + body;
        }, 5000);

        runs(function() {
            expect(error).toBeFalsy();
            expect(response.statusCode).toBe(200);
            expect(body).toBe('30');
        });
    });
});