text:
package com.github.nfalco79.tools.ant.taskdefs;

import static org.junit.Assert.*;
import static org.ops4j.pax.tinybundles.core.TinyBundles.*;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.apache.commons.io.FileUtils;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Manifest;
import org.apache.tools.ant.taskdefs.Manifest.Attribute;
import org.apache.tools.ant.types.FileSet;
import org.junit.Test;

import com.github.nfalco79.tools.ant.taskdefs.ESA;
import com.github.nfalco79.tools.ant.taskdefs.SubsystemConstants;

import aQute.bnd.osgi.Constants;

public class ESATest {

	private static final String BUNDLE_SYMBOLICNAME = "esa.bundle.test";
	private static final String BUNDLE_VERSION = "1.0.0";

	private File createBundles() throws IOException {
		InputStream is = bundle() //
				.add(ESA.class) //
				.add(ESATest.class) //
				.set(Constants.BUNDLE_MANIFESTVERSION, "2") //
				.set(Constants.BUNDLE_VERSION, BUNDLE_VERSION) //
				.set(Constants.BUNDLE_SYMBOLICNAME, BUNDLE_SYMBOLICNAME) //
				.set(Constants.EXPORT_PACKAGE, ESA.class.getPackage().getName()) //
				.build();

		File bundleFile = File.createTempFile("bundle", ".jar");
		FileUtils.copyInputStreamToFile(is, bundleFile);

		return bundleFile;
	}

	@Test
	public void esa() throws Exception {
		String esaSymbolicName = "org.nfalco.sample";
		String esaVersion = "1.0.0.100";

		File esaFile = File.createTempFile("test", ".esa");
		esaFile.delete();

		Project project = AntUtil.createEmptyProject();

		ESA task = new ESA();
		task.setProject(project);
		task.setDestFile(esaFile);
		task.setSymbolicName(esaSymbolicName);
		task.setVersion(esaVersion);

		File bundle = createBundles();
		FileSet fileSet = new FileSet();
		fileSet.setProject(project);
		fileSet.setFile(bundle);

		task.add(fileSet);
		try {
			task.execute();

			assertTrue(esaFile.exists());
			assertTrue(esaFile.length() > 0);

			ZipFile zf = new ZipFile(esaFile);
			ZipEntry ze = zf.getEntry(bundle.getName());
			assertNotNull(ze);

			ze = zf.getEntry("OSGI-INF/SUBSYSTEM.MF");
			assertNotNull(ze);

			InputStreamReader reader = new InputStreamReader(zf.getInputStream(ze));
			Manifest mf = new Manifest(reader);
			reader.close();

			Attribute attribute = mf.getMainSection().getAttribute(SubsystemConstants.SUBSYSTEM_MANIFEST_VERSION);
			assertNotNull(attribute);
			assertEquals("1.0", attribute.getValue());

			attribute = mf.getMainSection().getAttribute(SubsystemConstants.SUBSYSTEM_SYMBOLIC_NAME);
			assertNotNull(attribute);
			assertEquals(esaSymbolicName, attribute.getValue());

			attribute = mf.getMainSection().getAttribute(SubsystemConstants.SUBSYSTEM_VERSION);
			assertNotNull(attribute);
			assertEquals(esaVersion, attribute.getValue());

			attribute = mf.getMainSection().getAttribute(SubsystemConstants.SUBSYSTEM_TYPE);
			assertNotNull(attribute);
			assertEquals("osgi.subsystem.feature", attribute.getValue());

			attribute = mf.getMainSection().getAttribute(SubsystemConstants.SUBSYSTEM_CONTENT);
			assertNotNull(attribute);
			assertTrue(attribute.getValue().startsWith(BUNDLE_SYMBOLICNAME));
			assertTrue(attribute.getValue().contains("version=\"" + BUNDLE_VERSION + "\""));

			zf.close();
		} finally {
			if (!esaFile.delete()) {
				esaFile.deleteOnExit();
			}
		}
	}
}


text:
[instagram-private-api](../../README.md) / [responses](../../modules/responses.md) / FbsearchRepositoryPlacesResponseHeader_media

# Interface: FbsearchRepositoryPlacesResponseHeader\_media

[responses](../../modules/responses.md).FbsearchRepositoryPlacesResponseHeader_media

redpajama_set_name: RedPajamaGithub


text:
package nl.jpoint.hadoop_sandbox.job;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

/**
 *
 */
public class WordParser implements Tool {

    private Configuration conf;

    @Override
    public int run(String[] args) throws Exception {
        String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
        if (otherArgs.length != 2) {
            System.err.println("Usage: wordcount <in> <out>");
            System.exit(2);
        }

        Job job = new Job(conf, "wordcount");
        job.setJarByClass(WordParser.class);
        job.setMapperClass(Map.class);
        job.setReducerClass(Reduce.class);

        job.setInputFormatClass(TextInputFormat.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        KeyValueTextInputFormat.addInputPath(job, new Path(otherArgs[0]));
        FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
        return job.waitForCompletion(true) ? 0 : 1;
    }

    @Override
    public void setConf(Configuration conf) {
        this.conf = conf;
    }

    @Override
    public Configuration getConf() {
        return conf;
    }

    public static void main(String[] args) throws Exception {
        int res = ToolRunner.run(new Configuration(), new WordParser(), args);
        System.exit(res);
    }

}


text:
namespace sh
{

namespace
{

constexpr const ImmutableString kAngleDecorString("angle_");
// D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT = 128;
const unsigned int kMaxInputResourceSlotCount = 128u;
// If uniform block member's array size is larger than kMinArraySizeUseStructuredBuffer,
// then we translate uniform block to StructuredBuffer for compiling performance.
const unsigned int kMinArraySizeUseStructuredBuffer = 50u;

static const char *UniformRegisterPrefix(const TType &type)
{
    if (IsSampler(type.getBasicType()))
    {
        return "s";
    }
    else
    {
        return "c";
    }
}

static TString InterfaceBlockFieldTypeString(const TField &field,
                                             TLayoutBlockStorage blockStorage,
                                             bool usedStructuredbuffer)
{
    const TType &fieldType                   = *field.type();
    const TLayoutMatrixPacking matrixPacking = fieldType.getLayoutQualifier().matrixPacking;
    ASSERT(matrixPacking != EmpUnspecified);
    const TStructure *structure = fieldType.getStruct();

    if (fieldType.isMatrix())
    {
        // Use HLSL row-major packing for GLSL column-major matrices
        const TString &matrixPackString =
            (matrixPacking == EmpRowMajor ? "column_major" : "row_major");
        return matrixPackString + " " + TypeString(fieldType);
    }
    else if (structure)
    {
        // If uniform block's layout is std140 and translating it to StructuredBuffer,
        // should pack structure in the end, in order to fit API buffer.
        bool forcePackingEnd = usedStructuredbuffer && (blockStorage == EbsStd140);
        // Use HLSL row-major packing for GLSL column-major matrices
        return QualifiedStructNameString(*structure, matrixPacking == EmpColumnMajor,
                                         blockStorage == EbsStd140, forcePackingEnd);
    }
    else
    {
        return TypeString(fieldType);
    }
}

static TString InterfaceBlockStructName(const TInterfaceBlock &interfaceBlock)
{
    return DecoratePrivate(interfaceBlock.name()) + "_type";
}

void OutputUniformIndexArrayInitializer(TInfoSinkBase &out,
                                        const TType &type,
                                        unsigned int startIndex)
{
    out << "{";
    TType elementType(type);
    elementType.toArrayElementType();
    for (unsigned int i = 0u; i < type.getOutermostArraySize(); ++i)
    {
        if (i > 0u)
        {
            out << ", ";
        }
        if (elementType.isArray())
        {
            OutputUniformIndexArrayInitializer(out, elementType,
                                               startIndex + i * elementType.getArraySizeProduct());
        }
        else
        {
            out << (startIndex + i);
        }
    }
    out << "}";
}

}  // anonymous namespace

ResourcesHLSL::ResourcesHLSL(StructureHLSL *structureHLSL,
                             ShShaderOutput outputType,
                             ShCompileOptions compileOptions,
                             const std::vector<ShaderVariable> &uniforms,
                             unsigned int firstUniformRegister)
    : mUniformRegister(firstUniformRegister),
      mUniformBlockRegister(0),
      mSRVRegister(0),
      mUAVRegister(0),
      mSamplerCount(0),
      mStructureHLSL(structureHLSL),
      mOutputType(outputType),
      mCompileOptions(compileOptions),
      mUniforms(uniforms)
{}

void ResourcesHLSL::reserveUniformRegisters(unsigned int registerCount)
{
    mUniformRegister = registerCount;
}

void ResourcesHLSL::reserveUniformBlockRegisters(unsigned int registerCount)
{
    mUniformBlockRegister = registerCount;
}

const ShaderVariable *ResourcesHLSL::findUniformByName(const ImmutableString &name) const
{
    for (size_t uniformIndex = 0; uniformIndex < mUniforms.size(); ++uniformIndex)
    {
        if (name == mUniforms[uniformIndex].name)
        {
            return &mUniforms[uniformIndex];
        }
    }

    return nullptr;
}

unsigned int ResourcesHLSL::assignUniformRegister(const TType &type,
                                                  const ImmutableString &name,
                                                  unsigned int *outRegisterCount)
{
    unsigned int registerIndex;
    const ShaderVariable *uniform = findUniformByName(name);
    ASSERT(uniform);

    if (IsSampler(type.getBasicType()) ||
        (IsImage(type.getBasicType()) && type.getMemoryQualifier().readonly))
    {
        registerIndex = mSRVRegister;
    }
    else if (IsImage(type.getBasicType()))
    {
        registerIndex = mUAVRegister;
    }
    else
    {
        registerIndex = mUniformRegister;
    }

    if (uniform->name == "angle_DrawID" && uniform->mappedName == "angle_DrawID")
    {
        mUniformRegisterMap["gl_DrawID"] = registerIndex;
    }
    else
    {
        mUniformRegisterMap[uniform->name] = registerIndex;
    }

    if (uniform->name == "angle_BaseVertex" && uniform->mappedName == "angle_BaseVertex")
    {
        mUniformRegisterMap["gl_BaseVertex"] = registerIndex;
    }
    else
    {
        mUniformRegisterMap[uniform->name] = registerIndex;
    }

    if (uniform->name == "angle_BaseInstance" && uniform->mappedName == "angle_BaseInstance")
    {
        mUniformRegisterMap["gl_BaseInstance"] = registerIndex;
    }
    else
    {
        mUniformRegisterMap[uniform->name] = registerIndex;
    }

    unsigned int registerCount = HLSLVariableRegisterCount(*uniform, mOutputType);

    if (IsSampler(type.getBasicType()) ||
        (IsImage(type.getBasicType()) && type.getMemoryQualifier().readonly))
    {
        mSRVRegister += registerCount;
    }
    else if (IsImage(type.getBasicType()))
    {
        mUAVRegister += registerCount;
    }
    else
    {
        mUniformRegister += registerCount;
    }
    if (outRegisterCount)
    {
        *outRegisterCount = registerCount;
    }
    return registerIndex;
}

unsigned int ResourcesHLSL::assignSamplerInStructUniformRegister(const TType &type,
                                                                 const TString &name,
                                                                 unsigned int *outRegisterCount)
{
    // Sampler that is a field of a uniform structure.
    ASSERT(IsSampler(type.getBasicType()));
    unsigned int registerIndex                     = mSRVRegister;
    mUniformRegisterMap[std::string(name.c_str())] = registerIndex;
    unsigned int registerCount = type.isArray() ? type.getArraySizeProduct() : 1u;
    mSRVRegister += registerCount;
    if (outRegisterCount)
    {
        *outRegisterCount = registerCount;
    }
    return registerIndex;
}

void ResourcesHLSL::outputHLSLSamplerUniformGroup(
    TInfoSinkBase &out,
    const HLSLTextureGroup textureGroup,
    const TVector<const TVariable *> &group,
    const TMap<const TVariable *, TString> &samplerInStructSymbolsToAPINames,
    unsigned int *groupTextureRegisterIndex)
{
    if (group.empty())
    {
        return;
    }
    unsigned int groupRegisterCount = 0;
    for (const TVariable *uniform : group)
    {
        const TType &type           = uniform->getType();
        const ImmutableString &name = uniform->name();
        unsigned int registerCount;

        // The uniform might be just a regular sampler or one extracted from a struct.
        unsigned int samplerArrayIndex      = 0u;
        const ShaderVariable *uniformByName = findUniformByName(name);
        if (uniformByName)
        {
            samplerArrayIndex = assignUniformRegister(type, name, &registerCount);
        }
        else
        {
            ASSERT(samplerInStructSymbolsToAPINames.find(uniform) !=
                   samplerInStructSymbolsToAPINames.end());
            samplerArrayIndex = assignSamplerInStructUniformRegister(
                type, samplerInStructSymbolsToAPINames.at(uniform), &registerCount);
        }
        groupRegisterCount += registerCount;

        if (type.isArray())
        {
            out << "static const uint " << DecorateVariableIfNeeded(*uniform) << ArrayString(type)
                << " = ";
            OutputUniformIndexArrayInitializer(out, type, samplerArrayIndex);
            out << ";\n";
        }
        else
        {
            out << "static const uint " << DecorateVariableIfNeeded(*uniform) << " = "
                << samplerArrayIndex << ";\n";
        }
    }
    TString suffix = TextureGroupSuffix(textureGroup);
    // Since HLSL_TEXTURE_2D is the first group, it has a fixed offset of zero.
    if (textureGroup != HLSL_TEXTURE_2D)
    {
        out << "static const uint textureIndexOffset" << suffix << " = "
            << (*groupTextureRegisterIndex) << ";\n";
        out << "static const uint samplerIndexOffset" << suffix << " = "
            << (*groupTextureRegisterIndex) << ";\n";
    }
    out << "uniform " << TextureString(textureGroup) << " textures" << suffix << "["
        << groupRegisterCount << "]"
        << " : register(t" << (*groupTextureRegisterIndex) << ");\n";
    out << "uniform " << SamplerString(textureGroup) << " samplers" << suffix << "["
        << groupRegisterCount << "]"
        << " : register(s" << (*groupTextureRegisterIndex) << ");\n";
    *groupTextureRegisterIndex += groupRegisterCount;
}

void ResourcesHLSL::outputHLSLImageUniformIndices(TInfoSinkBase &out,
                                                  const TVector<const TVariable *> &group,
                                                  unsigned int imageArrayIndex,
                                                  unsigned int *groupRegisterCount)
{
    for (const TVariable *uniform : group)
    {
        const TType &type           = uniform->getType();
        const ImmutableString &name = uniform->name();
        unsigned int registerCount  = 0;

        assignUniformRegister(type, name, &registerCount);
        *groupRegisterCount += registerCount;

        if (type.isArray())
        {
            out << "static const uint " << DecorateVariableIfNeeded(*uniform) << ArrayString(type)
                << " = ";
            OutputUniformIndexArrayInitializer(out, type, imageArrayIndex);
            out << ";\n";
        }
        else
        {
            out << "static const uint " << DecorateVariableIfNeeded(*uniform) << " = "
                << imageArrayIndex << ";\n";
        }

        imageArrayIndex += registerCount;
    }
}

void ResourcesHLSL::outputHLSLReadonlyImageUniformGroup(TInfoSinkBase &out,
                                                        const HLSLTextureGroup textureGroup,
                                                        const TVector<const TVariable *> &group,
                                                        unsigned int *groupTextureRegisterIndex)
{
    if (group.empty())
    {
        return;
    }

    unsigned int groupRegisterCount = 0;
    outputHLSLImageUniformIndices(out, group, *groupTextureRegisterIndex, &groupRegisterCount);

    TString suffix = TextureGroupSuffix(textureGroup);
    out << "static const uint readonlyImageIndexOffset" << suffix << " = "
        << (*groupTextureRegisterIndex) << ";\n";
    out << "uniform " << TextureString(textureGroup) << " readonlyImages" << suffix << "["
        << groupRegisterCount << "]"
        << " : register(t" << (*groupTextureRegisterIndex) << ");\n";
    *groupTextureRegisterIndex += groupRegisterCount;
}

void ResourcesHLSL::outputHLSLImageUniformGroup(TInfoSinkBase &out,
                                                const HLSLRWTextureGroup textureGroup,
                                                const TVector<const TVariable *> &group,
                                                unsigned int *groupTextureRegisterIndex)
{
    if (group.empty())
    {
        return;
    }

    unsigned int groupRegisterCount = 0;
    outputHLSLImageUniformIndices(out, group, *groupTextureRegisterIndex, &groupRegisterCount);

    TString suffix = RWTextureGroupSuffix(textureGroup);
    out << "static const uint imageIndexOffset" << suffix << " = " << (*groupTextureRegisterIndex)
        << ";\n";
    out << "uniform " << RWTextureString(textureGroup) << " images" << suffix << "["
        << groupRegisterCount << "]"
        << " : register(u" << (*groupTextureRegisterIndex) << ");\n";
    *groupTextureRegisterIndex += groupRegisterCount;
}

void ResourcesHLSL::outputHLSL4_0_FL9_3Sampler(TInfoSinkBase &out,
                                               const TType &type,
                                               const TVariable &variable,
                                               const unsigned int registerIndex)
{
    out << "uniform " << SamplerString(type.getBasicType()) << " sampler_"
        << DecorateVariableIfNeeded(variable) << ArrayString(type) << " : register(s"
        << str(registerIndex) << ");\n";
    out << "uniform " << TextureString(type.getBasicType()) << " texture_"
        << DecorateVariableIfNeeded(variable) << ArrayString(type) << " : register(t"
        << str(registerIndex) << ");\n";
}

void ResourcesHLSL::outputUniform(TInfoSinkBase &out,
                                  const TType &type,
                                  const TVariable &variable,
                                  const unsigned int registerIndex)
{
    const TStructure *structure = type.getStruct();
    // If this is a nameless struct, we need to use its full definition, rather than its (empty)
    // name.
    // TypeString() will invoke defineNameless in this case; qualifier prefixes are unnecessary for
    // nameless structs in ES, as nameless structs cannot be used anywhere that layout qualifiers
    // are permitted.
    const TString &typeName = ((structure && structure->symbolType() != SymbolType::Empty)
                                   ? QualifiedStructNameString(*structure, false, false, false)
                                   : TypeString(type));

    const TString &registerString =
        TString("register(") + UniformRegisterPrefix(type) + str(registerIndex) + ")";

    out << "uniform " << typeName << " ";

    out << DecorateVariableIfNeeded(variable);

    out << ArrayString(type) << " : " << registerString << ";\n";
}

void ResourcesHLSL::outputAtomicCounterBuffer(TInfoSinkBase &out,
                                              const int binding,
                                              const unsigned int registerIndex)
{
    // Atomic counter memory access is not incoherent
    out << "uniform globallycoherent RWByteAddressBuffer "
        << getAtomicCounterNameForBinding(binding) << " : register(u" << registerIndex << ");\n";
}

void ResourcesHLSL::uniformsHeader(TInfoSinkBase &out,
                                   ShShaderOutput outputType,
                                   const ReferencedVariables &referencedUniforms,
                                   TSymbolTable *symbolTable)
{
    if (!referencedUniforms.empty())
    {
        out << "// Uniforms\n\n";
    }
    // In the case of HLSL 4, sampler uniforms need to be grouped by type before the code is
    // written. They are grouped based on the combination of the HLSL texture type and
    // HLSL sampler type, enumerated in HLSLTextureSamplerGroup.
    TVector<TVector<const TVariable *>> groupedSamplerUniforms(HLSL_TEXTURE_MAX + 1);
    TMap<const TVariable *, TString> samplerInStructSymbolsToAPINames;
    TVector<TVector<const TVariable *>> groupedReadonlyImageUniforms(HLSL_TEXTURE_MAX + 1);
    TVector<TVector<const TVariable *>> groupedImageUniforms(HLSL_RWTEXTURE_MAX + 1);

    TUnorderedMap<int, unsigned int> assignedAtomicCounterBindings;
    unsigned int reservedReadonlyImageRegisterCount = 0, reservedImageRegisterCount = 0;
    for (auto &uniformIt : referencedUniforms)
    {
        // Output regular uniforms. Group sampler uniforms by type.
        const TVariable &variable = *uniformIt.second;
        const TType &type         = variable.getType();

        if (outputType == SH_HLSL_4_1_OUTPUT && IsSampler(type.getBasicType()))
        {
            HLSLTextureGroup group = TextureGroup(type.getBasicType());
            groupedSamplerUniforms[group].push_back(&variable);
        }
        else if (outputType == SH_HLSL_4_0_FL9_3_OUTPUT && IsSampler(type.getBasicType()))
        {
            unsigned int registerIndex = assignUniformRegister(type, variable.name(), nullptr);
            outputHLSL4_0_FL9_3Sampler(out, type, variable, registerIndex);
        }
        else if (outputType == SH_HLSL_4_1_OUTPUT && IsImage(type.getBasicType()))
        {
            if (IsImage2D(type.getBasicType()))
            {
                const ShaderVariable *uniform = findUniformByName(variable.name());
                if (type.getMemoryQualifier().readonly)
                {
                    reservedReadonlyImageRegisterCount +=
                        HLSLVariableRegisterCount(*uniform, mOutputType);
                }
                else
                {
                    reservedImageRegisterCount += HLSLVariableRegisterCount(*uniform, mOutputType);
                }
                continue;
            }
            if (type.getMemoryQualifier().readonly)
            {
                HLSLTextureGroup group = TextureGroup(
                    type.getBasicType(), type.getLayoutQualifier().imageInternalFormat);
                groupedReadonlyImageUniforms[group].push_back(&variable);
            }
            else
            {
                HLSLRWTextureGroup group = RWTextureGroup(
                    type.getBasicType(), type.getLayoutQualifier().imageInternalFormat);
                groupedImageUniforms[group].push_back(&variable);
            }
        }
        else if (outputType == SH_HLSL_4_1_OUTPUT && IsAtomicCounter(type.getBasicType()))
        {
            TLayoutQualifier layout = type.getLayoutQualifier();
            int binding             = layout.binding;
            unsigned int registerIndex;
            if (assignedAtomicCounterBindings.find(binding) == assignedAtomicCounterBindings.end())
            {
                registerIndex                          = mUAVRegister++;
                assignedAtomicCounterBindings[binding] = registerIndex;
                outputAtomicCounterBuffer(out, binding, registerIndex);
            }
            else
            {
                registerIndex = assignedAtomicCounterBindings[binding];
            }
            const ShaderVariable *uniform      = findUniformByName(variable.name());
            mUniformRegisterMap[uniform->name] = registerIndex;
        }
        else
        {
            if (type.isStructureContainingSamplers())
            {
                TVector<const TVariable *> samplerSymbols;
                TMap<const TVariable *, TString> symbolsToAPINames;
                ImmutableStringBuilder namePrefix(kAngleDecorString.length() +
                                                  variable.name().length());
                namePrefix << kAngleDecorString;
                namePrefix << variable.name();
                type.createSamplerSymbols(namePrefix, TString(variable.name().data()),
                                          &samplerSymbols, &symbolsToAPINames, symbolTable);
                for (const TVariable *sampler : samplerSymbols)
                {
                    const TType &samplerType = sampler->getType();

                    if (outputType == SH_HLSL_4_1_OUTPUT)
                    {
                        HLSLTextureGroup group = TextureGroup(samplerType.getBasicType());
                        groupedSamplerUniforms[group].push_back(sampler);
                        samplerInStructSymbolsToAPINames[sampler] = symbolsToAPINames[sampler];
                    }
                    else if (outputType == SH_HLSL_4_0_FL9_3_OUTPUT)
                    {
                        unsigned int registerIndex = assignSamplerInStructUniformRegister(
                            samplerType, symbolsToAPINames[sampler], nullptr);
                        outputHLSL4_0_FL9_3Sampler(out, samplerType, *sampler, registerIndex);
                    }
                    else
                    {
                        ASSERT(outputType == SH_HLSL_3_0_OUTPUT);
                        unsigned int registerIndex = assignSamplerInStructUniformRegister(
                            samplerType, symbolsToAPINames[sampler], nullptr);
                        outputUniform(out, samplerType, *sampler, registerIndex);
                    }
                }
            }
            unsigned int registerIndex = assignUniformRegister(type, variable.name(), nullptr);
            outputUniform(out, type, variable, registerIndex);
        }
    }

    if (outputType == SH_HLSL_4_1_OUTPUT)
    {
        unsigned int groupTextureRegisterIndex = 0;
        // Atomic counters and RW texture share the same resources. Therefore, RW texture need to
        // start counting after the last atomic counter.
        unsigned int groupRWTextureRegisterIndex = mUAVRegister;
        // TEXTURE_2D is special, index offset is assumed to be 0 and omitted in that case.
        ASSERT(HLSL_TEXTURE_MIN == HLSL_TEXTURE_2D);
        for (int groupId = HLSL_TEXTURE_MIN; groupId < HLSL_TEXTURE_MAX; ++groupId)
        {
            outputHLSLSamplerUniformGroup(
                out, HLSLTextureGroup(groupId), groupedSamplerUniforms[groupId],
                samplerInStructSymbolsToAPINames, &groupTextureRegisterIndex);
        }
        mSamplerCount = groupTextureRegisterIndex;

        // Reserve t type register for readonly image2D variables.
        mReadonlyImage2DRegisterIndex = mSRVRegister;
        groupTextureRegisterIndex += reservedReadonlyImageRegisterCount;
        mSRVRegister += reservedReadonlyImageRegisterCount;

        for (int groupId = HLSL_TEXTURE_MIN; groupId < HLSL_TEXTURE_MAX; ++groupId)
        {
            outputHLSLReadonlyImageUniformGroup(out, HLSLTextureGroup(groupId),
                                                groupedReadonlyImageUniforms[groupId],
                                                &groupTextureRegisterIndex);
        }
        mReadonlyImageCount = groupTextureRegisterIndex - mReadonlyImage2DRegisterIndex;
        if (mReadonlyImageCount)
        {
            out << "static const uint readonlyImageIndexStart = " << mReadonlyImage2DRegisterIndex
                << ";\n";
        }

        // Reserve u type register for writable image2D variables.
        mImage2DRegisterIndex = mUAVRegister;
        groupRWTextureRegisterIndex += reservedImageRegisterCount;
        mUAVRegister += reservedImageRegisterCount;

        for (int groupId = HLSL_RWTEXTURE_MIN; groupId < HLSL_RWTEXTURE_MAX; ++groupId)
        {
            outputHLSLImageUniformGroup(out, HLSLRWTextureGroup(groupId),
                                        groupedImageUniforms[groupId],
                                        &groupRWTextureRegisterIndex);
        }
        mImageCount = groupRWTextureRegisterIndex - mImage2DRegisterIndex;
        if (mImageCount)
        {
            out << "static const uint imageIndexStart = " << mImage2DRegisterIndex << ";\n";
        }
    }
}

void ResourcesHLSL::samplerMetadataUniforms(TInfoSinkBase &out, unsigned int regIndex)
{
    // If mSamplerCount is 0 the shader doesn't use any textures for samplers.
    if (mSamplerCount > 0)
    {
        out << "    struct SamplerMetadata\n"
               "    {\n"
               "        int baseLevel;\n"
               "        int internalFormatBits;\n"
               "        int wrapModes;\n"
               "        int padding;\n"
               "        int4 intBorderColor;\n"
               "    };\n"
               "    SamplerMetadata samplerMetadata["
            << mSamplerCount << "] : packoffset(c" << regIndex << ");\n";
    }
}

void ResourcesHLSL::imageMetadataUniforms(TInfoSinkBase &out, unsigned int regIndex)
{
    if (mReadonlyImageCount > 0 || mImageCount > 0)
    {
        out << "    struct ImageMetadata\n"
               "    {\n"
               "        int layer;\n"
               "        uint level;\n"
               "        int2 padding;\n"
               "    };\n";

        if (mReadonlyImageCount > 0)
        {
            out << "    ImageMetadata readonlyImageMetadata[" << mReadonlyImageCount
                << "] : packoffset(c" << regIndex << ");\n";
        }

        if (mImageCount > 0)
        {
            out << "    ImageMetadata imageMetadata[" << mImageCount << "] : packoffset(c"
                << regIndex + mReadonlyImageCount << ");\n";
        }
    }
}

TString ResourcesHLSL::uniformBlocksHeader(
    const ReferencedInterfaceBlocks &referencedInterfaceBlocks)
{
    TString interfaceBlocks;

    for (const auto &blockReference : referencedInterfaceBlocks)
    {
        const TInterfaceBlock &interfaceBlock = *blockReference.second->block;
        const TVariable *instanceVariable     = blockReference.second->instanceVariable;
        if (instanceVariable != nullptr)
        {
            interfaceBlocks += uniformBlockStructString(interfaceBlock);
        }

        // In order to avoid compile performance issue, translate uniform block to structured
        // buffer. anglebug.com/3682.
        if (shouldTranslateUniformBlockToStructuredBuffer(interfaceBlock))
        {
            unsigned int structuredBufferRegister = mSRVRegister;
            if (instanceVariable != nullptr && instanceVariable->getType().isArray())
            {
                unsigned int instanceArraySize =
                    instanceVariable->getType().getOutermostArraySize();
                for (unsigned int arrayIndex = 0; arrayIndex < instanceArraySize; arrayIndex++)
                {
                    interfaceBlocks += uniformBlockWithOneLargeArrayMemberString(
                        interfaceBlock, instanceVariable, structuredBufferRegister + arrayIndex,
                        arrayIndex);
                }
                mSRVRegister += instanceArraySize;
            }
            else
            {
                interfaceBlocks += uniformBlockWithOneLargeArrayMemberString(
                    interfaceBlock, instanceVariable, structuredBufferRegister, GL_INVALID_INDEX);
                mSRVRegister += 1u;
            }
            mUniformBlockRegisterMap[interfaceBlock.name().data()] = structuredBufferRegister;
            mUniformBlockUseStructuredBufferMap[interfaceBlock.name().data()] = true;
            continue;
        }

        unsigned int activeRegister                            = mUniformBlockRegister;
        mUniformBlockRegisterMap[interfaceBlock.name().data()] = activeRegister;

        if (instanceVariable != nullptr && instanceVariable->getType().isArray())
        {
            unsigned int instanceArraySize = instanceVariable->getType().getOutermostArraySize();
            for (unsigned int arrayIndex = 0; arrayIndex < instanceArraySize; arrayIndex++)
            {
                interfaceBlocks += uniformBlockString(interfaceBlock, instanceVariable,
                                                      activeRegister + arrayIndex, arrayIndex);
            }
            mUniformBlockRegister += instanceArraySize;
        }
        else
        {
            interfaceBlocks += uniformBlockString(interfaceBlock, instanceVariable, activeRegister,
                                                  GL_INVALID_INDEX);
            mUniformBlockRegister += 1u;
        }
    }

    return (interfaceBlocks.empty() ? "" : ("// Uniform Blocks\n\n" + interfaceBlocks));
}

TString ResourcesHLSL::shaderStorageBlocksHeader(
    const ReferencedInterfaceBlocks &referencedInterfaceBlocks)
{
    TString interfaceBlocks;

    for (const auto &interfaceBlockReference : referencedInterfaceBlocks)
    {
        const TInterfaceBlock &interfaceBlock = *interfaceBlockReference.second->block;
        const TVariable *instanceVariable     = interfaceBlockReference.second->instanceVariable;

        unsigned int activeRegister                                  = mUAVRegister;
        mShaderStorageBlockRegisterMap[interfaceBlock.name().data()] = activeRegister;

        if (instanceVariable != nullptr && instanceVariable->getType().isArray())
        {
            unsigned int instanceArraySize = instanceVariable->getType().getOutermostArraySize();
            for (unsigned int arrayIndex = 0; arrayIndex < instanceArraySize; arrayIndex++)
            {
                interfaceBlocks += shaderStorageBlockString(
                    interfaceBlock, instanceVariable, activeRegister + arrayIndex, arrayIndex);
            }
            mUAVRegister += instanceArraySize;
        }
        else
        {
            interfaceBlocks += shaderStorageBlockString(interfaceBlock, instanceVariable,
                                                        activeRegister, GL_INVALID_INDEX);
            mUAVRegister += 1u;
        }
    }

    return (interfaceBlocks.empty() ? "" : ("// Shader Storage Blocks\n\n" + interfaceBlocks));
}

TString ResourcesHLSL::uniformBlockString(const TInterfaceBlock &interfaceBlock,
                                          const TVariable *instanceVariable,
                                          unsigned int registerIndex,
                                          unsigned int arrayIndex)
{
    const TString &arrayIndexString = (arrayIndex != GL_INVALID_INDEX ? str(arrayIndex) : "");
    const TString &blockName        = TString(interfaceBlock.name().data()) + arrayIndexString;
    TString hlsl;

    hlsl += "cbuffer " + blockName + " : register(b" + str(registerIndex) +
            ")\n"
            "{\n";

    if (instanceVariable != nullptr)
    {
        hlsl += "    " + InterfaceBlockStructName(interfaceBlock) + " " +
                InterfaceBlockInstanceString(instanceVariable->name(), arrayIndex) + ";\n";
    }
    else
    {
        const TLayoutBlockStorage blockStorage = interfaceBlock.blockStorage();
        hlsl += uniformBlockMembersString(interfaceBlock, blockStorage);
    }

    hlsl += "};\n\n";

    return hlsl;
}

TString ResourcesHLSL::uniformBlockWithOneLargeArrayMemberString(
    const TInterfaceBlock &interfaceBlock,
    const TVariable *instanceVariable,
    unsigned int registerIndex,
    unsigned int arrayIndex)
{
    TString hlsl, typeString;

    const TField &field                    = *interfaceBlock.fields()[0];
    const TLayoutBlockStorage blockStorage = interfaceBlock.blockStorage();
    typeString             = InterfaceBlockFieldTypeString(field, blockStorage, true);
    const TType &fieldType = *field.type();
    if (fieldType.isMatrix())
    {
        if (arrayIndex == GL_INVALID_INDEX || arrayIndex == 0)
        {
            hlsl += "struct matrix" + Decorate(field.name()) + " { " + typeString + " _matrix_" +
                    Decorate(field.name()) + "; };\n";
        }
        typeString = "matrix" + Decorate(field.name());
    }

    if (instanceVariable != nullptr)
    {

        hlsl += "StructuredBuffer <" + typeString + "> " +
                InterfaceBlockInstanceString(instanceVariable->name(), arrayIndex) + "_" +
                Decorate(field.name()) + +" : register(t" + str(registerIndex) + ");\n";
    }
    else
    {
        hlsl += "StructuredBuffer <" + typeString + "> " + Decorate(field.name()) +
                " : register(t" + str(registerIndex) + ");\n";
    }

    return hlsl;
}

TString ResourcesHLSL::shaderStorageBlockString(const TInterfaceBlock &interfaceBlock,
                                                const TVariable *instanceVariable,
                                                unsigned int registerIndex,
                                                unsigned int arrayIndex)
{
    TString hlsl;
    if (instanceVariable != nullptr)
    {
        hlsl += "RWByteAddressBuffer " +
                InterfaceBlockInstanceString(instanceVariable->name(), arrayIndex) +
                ": register(u" + str(registerIndex) + ");\n";
    }
    else
    {
        hlsl += "RWByteAddressBuffer " + Decorate(interfaceBlock.name()) + ": register(u" +
                str(registerIndex) + ");\n";
    }
    return hlsl;
}

TString ResourcesHLSL::InterfaceBlockInstanceString(const ImmutableString &instanceName,
                                                    unsigned int arrayIndex)
{
    if (arrayIndex != GL_INVALID_INDEX)
    {
        return DecoratePrivate(instanceName) + "_" + str(arrayIndex);
    }
    else
    {
        return Decorate(instanceName);
    }
}

TString ResourcesHLSL::uniformBlockMembersString(const TInterfaceBlock &interfaceBlock,
                                                 TLayoutBlockStorage blockStorage)
{
    TString hlsl;

    Std140PaddingHelper padHelper = mStructureHLSL->getPaddingHelper();

    for (unsigned int typeIndex = 0; typeIndex < interfaceBlock.fields().size(); typeIndex++)
    {
        const TField &field    = *interfaceBlock.fields()[typeIndex];
        const TType &fieldType = *field.type();

        if (blockStorage == EbsStd140)
        {
            // 2 and 3 component vector types in some cases need pre-padding
            hlsl += padHelper.prePaddingString(fieldType);
        }

        hlsl += "    " + InterfaceBlockFieldTypeString(field, blockStorage, false) + " " +
                Decorate(field.name()) + ArrayString(fieldType).data() + ";\n";

        // must pad out after matrices and arrays, where HLSL usually allows itself room to pack
        // stuff
        if (blockStorage == EbsStd140)
        {
            const bool useHLSLRowMajorPacking =
                (fieldType.getLayoutQualifier().matrixPacking == EmpColumnMajor);
            hlsl += padHelper.postPaddingString(fieldType, useHLSLRowMajorPacking, false);
        }
    }

    return hlsl;
}

TString ResourcesHLSL::uniformBlockStructString(const TInterfaceBlock &interfaceBlock)
{
    const TLayoutBlockStorage blockStorage = interfaceBlock.blockStorage();

    return "struct " + InterfaceBlockStructName(interfaceBlock) +
           "\n"
           "{\n" +
           uniformBlockMembersString(interfaceBlock, blockStorage) + "};\n\n";
}

bool ResourcesHLSL::shouldTranslateUniformBlockToStructuredBuffer(
    const TInterfaceBlock &interfaceBlock)
{
    const TType &fieldType = *interfaceBlock.fields()[0]->type();

    return (mCompileOptions & SH_DONT_TRANSLATE_UNIFORM_BLOCK_TO_STRUCTUREDBUFFER) == 0 &&
           mSRVRegister < kMaxInputResourceSlotCount && interfaceBlock.fields().size() == 1u &&
           (fieldType.getStruct() != nullptr || fieldType.isMatrix()) &&
           fieldType.getNumArraySizes() == 1u &&
           fieldType.getOutermostArraySize() >= kMinArraySizeUseStructuredBuffer;
}
}  // namespace sh


text:
#import "SUUsingViewController.h"

#import <FacebookSDK/FacebookSDK.h>

#import "SUAppDelegate.h"

@interface SUUsingViewController ()

@property (strong, nonatomic) IBOutlet UILabel *nameLabel;
@property (strong, nonatomic) IBOutlet UILabel *birthdayLabel;
// FBSample logic
// The requestConnection property in this class is used to maintain the current active
// connection with Facebook, used to fetch profile information; and picView displays the
// profile for the current active user
@property (strong, nonatomic) FBRequest *pendingRequest;
@property (strong, nonatomic) IBOutlet FBProfilePictureView *picView;

@end

@implementation SUUsingViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"Using", @"Using");
        self.tabBarItem.image = [UIImage imageNamed:@"first"];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)updateControls {
    SUAppDelegate *appDelegate = (SUAppDelegate *)[[UIApplication sharedApplication]delegate];
    SUUserManager *userManager = appDelegate.userManager;

    if (userManager.currentUserSlot != -1 &&
        userManager.currentSession.isOpen) {
        // There could be a delay while we retrieve user profile. Hide controls until data is there.
        self.nameLabel.hidden = YES;
        self.picView.hidden = YES;
        self.birthdayLabel.hidden = YES;

        // FBSample logic
        // If the session is open, then we attemt to fetch /me, in order to get the user's
        // name and birthday
        FBRequest *me = [[FBRequest alloc] initWithSession:userManager.currentSession
                                                 graphPath:@"me"];
        [me startWithCompletionHandler:^(FBRequestConnection *connection,
                                         // we expect a user as a result, and so are using FBGraphUser protocol
                                         // as our result type; in order to allow us to access first_name and
                                         // birthday with property syntax
                                         NSDictionary<FBGraphUser> *user,
                                         NSError *error) {
            if (me != self.pendingRequest) {
                return;
            }
            self.pendingRequest = nil;

            if (error) {
                NSLog(@"Couldn't get info : %@", error.localizedDescription);
                return;
            }

            self.nameLabel.text = [NSString stringWithFormat:@"Hello, %@!", user.first_name];
            self.picView.profileID = user.id;
            if (user.birthday.length > 0) {
                self.birthdayLabel.text = [NSString stringWithFormat:@"Your birthday is: %@", user.birthday];
            } else {
                self.birthdayLabel.text = @"Your birthday isn't set.";
            }

            self.nameLabel.hidden = NO;
            self.picView.hidden = NO;
            self.birthdayLabel.hidden = NO;
        }];

        self.pendingRequest = me;

    } else {
        self.nameLabel.text = @"No active user. Go to Settings tab to log in!";
        self.nameLabel.hidden = NO;
        self.picView.hidden = YES;
        self.birthdayLabel.hidden = YES;
    }
}

- (void)userDidChange:(NSNotification *)notification {
    [self updateControls];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self updateControls];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(userDidChange:)
                                                 name:@"SUUserManagerUserChanged" object:nil];

    [self updateControls];
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.nameLabel = nil;
    self.birthdayLabel = nil;
    self.picView = nil;

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:@"SUUserManagerUserChanged" object:nil];

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

@end


text:
require 'spec_helper'

describe 'Basic List', type: :feature do
  subject { page }

  context 'when a visitor that is not log in' do
    describe 'GET /' do
      it 'responds successfully' do
        visit dashboard_path
      end
    end

    describe 'GET /whatever' do
      it "redirects to dashboard and inform should be login first" do
        visit '/whatever'
        expect(find('.alert-danger')).to have_content('You need to sign in or sign up before continuing.')
      end
    end

    describe 'GET /user' do
      it "before visit user page should be login first" do
        visit '/user'
        is_expected.to have_content('Log in')
        is_expected.to have_content('Sign up')
      end
    end
  end

  context 'when a user is log in' do
    before(:each) do
      user = FactoryGirl.create(:user)
      login_as(user, scope: :user)
    end

    describe 'GET /typo' do
      it "redirects to dashboard and inform the user the model wasn't found" do

        visit '/whatever'
        expect(find('.alert-danger')).to have_content("Model 'Whatever' could not be found")
      end
    end

    describe 'GET /user list' do
      it "success visit for user list page" do
        visit '/user'

        # Actions
        is_expected.to have_content('Add new')

        # Filter
        is_expected.to have_selector("input[placeholder='Filter']")

        # Columns
        is_expected.to have_content('Name')
        is_expected.to have_content('Email')
        is_expected.to have_content('Given name')
        is_expected.to have_content('Family name')
        is_expected.to have_content('Current Account')
        is_expected.to have_content('Users')
        is_expected.to have_content('Created at')
      end
    end
  end
end


text:
require 'fog/openstack/core'
require 'fog/openstack/common'
require 'fog/openstack/identity'

module Fog
  module Identity
    class OpenStack
      class V3 < Fog::Service
        requires :openstack_auth_url
        recognizes :openstack_auth_token, :openstack_management_url, :persistent,
                   :openstack_service_type, :openstack_service_name, :openstack_tenant,
                   :openstack_endpoint_type, :openstack_region, :openstack_domain_id,
                   :openstack_project_name, :openstack_domain_name,
                   :openstack_user_domain, :openstack_project_domain,
                   :openstack_user_domain_id, :openstack_project_domain_id,
                   :openstack_api_key, :openstack_current_user_id, :openstack_userid, :openstack_username,
                   :current_user, :current_user_id, :current_tenant,
                   :provider, :openstack_identity_prefix

        model_path 'fog/openstack/models/identity_v3'
        model :domain
        collection :domains
        model :endpoint
        collection :endpoints
        model :project
        collection :projects
        model :service
        collection :services
        model :token
        collection :tokens
        model :user
        collection :users
        model :group
        collection :groups
        model :role
        collection :roles
        model :role_assignment
        collection :role_assignments
        model :os_credential
        collection :os_credentials
        model :policy
        collection :policies

        request_path 'fog/openstack/requests/identity_v3'

        request :list_users
        request :get_user
        request :create_user
        request :update_user
        request :delete_user
        request :list_user_groups
        request :list_user_projects
        request :list_groups
        request :get_group
        request :create_group
        request :update_group
        request :delete_group
        request :add_user_to_group
        request :remove_user_from_group
        request :group_user_check
        request :list_group_users
        request :list_roles
        request :list_role_assignments
        request :get_role
        request :create_role
        request :update_role
        request :delete_role
        request :auth_domains
        request :auth_projects
        request :list_domains
        request :get_domain
        request :create_domain
        request :update_domain
        request :delete_domain
        request :list_domain_user_roles
        request :grant_domain_user_role
        request :check_domain_user_role
        request :revoke_domain_user_role
        request :list_domain_group_roles
        request :grant_domain_group_role
        request :check_domain_group_role
        request :revoke_domain_group_role
        request :list_endpoints
        request :get_endpoint
        request :create_endpoint
        request :update_endpoint
        request :delete_endpoint
        request :list_projects
        request :get_project
        request :create_project
        request :update_project
        request :delete_project
        request :list_project_user_roles
        request :grant_project_user_role
        request :check_project_user_role
        request :revoke_project_user_role
        request :list_project_group_roles
        request :grant_project_group_role
        request :check_project_group_role
        request :revoke_project_group_role
        request :list_services
        request :get_service
        request :create_service
        request :update_service
        request :delete_service
        request :token_authenticate
        request :token_validate
        request :token_check
        request :token_revoke
        request :list_os_credentials
        request :get_os_credential
        request :create_os_credential
        request :update_os_credential
        request :delete_os_credential
        request :list_policies
        request :get_policy
        request :create_policy
        request :update_policy
        request :delete_policy

        class Mock
          include Fog::OpenStack::Core
          def initialize(options={})

          end
        end

        def self.get_api_version uri, connection_options={}
          connection = Fog::Core::Connection.new(uri, false, connection_options)
          response = connection.request({
                                            :expects => [200],
                                            :headers => {'Content-Type' => 'application/json',
                                                         'Accept' => 'application/json'},
                                            :method => 'GET'
                                        })

          body = Fog::JSON.decode(response.body)
          version = nil
          unless body['version'].empty?
            version = body['version']['id']
          end
          if version.nil?
            raise Fog::OpenStack::Errors::ServiceUnavailable.new(
                      "No version available at #{uri}")
          end

          version
        end

        class Real
          def self.not_found_class
            Fog::Identity::OpenStack::NotFound
          end
          include Fog::OpenStack::Common

          def initialize(options={})
            initialize_identity options

            @openstack_service_type   = options[:openstack_service_type] || ['identity_v3','identityv3','identity']
            @openstack_service_name   = options[:openstack_service_name]
            @identity_prefix          = options[:openstack_identity_prefix] ? "/#{options[:openstack_identity_prefix]}" : nil

            @connection_options       = options[:connection_options] || {}

            @openstack_endpoint_type  = options[:openstack_endpoint_type] || 'adminURL'

            @openstack_endpoint_path_matches = options[:openstack_endpoint_path_matches] ||= /\/v3/
            authenticate

            @persistent = options[:persistent] || false
            @connection = Fog::Core::Connection.new("#{@scheme}://#{@host}:#{@port}#{@identity_prefix}", @persistent, @connection_options)
          end
        end
      end
    end
  end
end


text:
using System;
using System.Reflection;

namespace Epic.Vectors
{
    internal class TypeKey
    {
        public Type Type { get; }

        public TypeKey(Type type)
        {
            this.Type = type;
            this.GetFriendlyName();
        }

        public string GetFriendlyName()
        {
            var type = Type.GetTypeInfo();

            string friendlyName = type.Name;
            if (type.IsGenericType)
            {
                int iBacktick = friendlyName.IndexOf('`');
                if (iBacktick > 0)
                {
                    friendlyName = friendlyName.Remove(iBacktick);
                }
                friendlyName += "<";
                var a = type.IsGenericType;
                var b = type.IsGenericTypeDefinition;
                Type[] typeParameters = type.GenericTypeArguments;
                if (type.GenericTypeParameters.Length > typeParameters.Length) typeParameters = type.GenericTypeParameters;
                for (int i = 0; i < typeParameters.Length; ++i)
                {
                    string typeParamName = typeParameters[i].Name;
                    friendlyName += (i == 0 ? typeParamName : "," + typeParamName);
                }
                friendlyName += ">";
            }

            return friendlyName;
        }

        public string Identifier => $"{Type.Namespace}.{GetFriendlyName()}";

        protected bool Equals(TypeKey other)
        {
            return string.Equals(this.Identifier, other.Identifier);
        }

        /// <summary>
        /// Determines whether the specified object is equal to the current object.
        /// </summary>
        /// <returns>
        /// true if the specified object  is equal to the current object; otherwise, false.
        /// </returns>
        /// <param name="obj">The object to compare with the current object. </param>
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj))
            {
                return false;
            }
            if (ReferenceEquals(this, obj))
            {
                return true;
            }
            if (obj.GetType() != this.GetType())
            {
                return false;
            }
            return Equals((TypeKey)obj);
        }

        /// <summary>
        /// Serves as the default hash function.
        /// </summary>
        /// <returns>
        /// A hash code for the current object.
        /// </returns>
        public override int GetHashCode()
        {
            return (this.Identifier != null ? this.Identifier.GetHashCode() : 0);
        }

        /// <summary>
        /// Returns a string that represents the current object.
        /// </summary>
        /// <returns>
        /// A string that represents the current object.
        /// </returns>
        public override string ToString()
        {
            return Identifier;
        }
    }
}


text:
typedef enum LazyPDFPopoverArrowDirection: NSUInteger {
    LazyPDFPopoverArrowDirectionUp = 1UL << 0,
    LazyPDFPopoverArrowDirectionDown = 1UL << 1,
    LazyPDFPopoverArrowDirectionLeft = 1UL << 2,
    LazyPDFPopoverArrowDirectionRight = 1UL << 3,
    LazyPDFPopoverNoArrow = 1UL << 4,

    LazyPDFPopoverArrowDirectionVertical = LazyPDFPopoverArrowDirectionUp | LazyPDFPopoverArrowDirectionDown | LazyPDFPopoverNoArrow,
    LazyPDFPopoverArrowDirectionHorizontal = LazyPDFPopoverArrowDirectionLeft | LazyPDFPopoverArrowDirectionRight,

    LazyPDFPopoverArrowDirectionAny = LazyPDFPopoverArrowDirectionUp | LazyPDFPopoverArrowDirectionDown |
    LazyPDFPopoverArrowDirectionLeft | LazyPDFPopoverArrowDirectionRight

} LazyPDFPopoverArrowDirection;

#ifndef LazyPDFPopoverArrowDirectionIsVertical
    #define LazyPDFPopoverArrowDirectionIsVertical(direction)    ((direction) == LazyPDFPopoverArrowDirectionVertical || (direction) == LazyPDFPopoverArrowDirectionUp || (direction) == LazyPDFPopoverArrowDirectionDown || (direction) == LazyPDFPopoverNoArrow)
#endif

#ifndef LazyPDFPopoverArrowDirectionIsHorizontal
#define LazyPDFPopoverArrowDirectionIsHorizontal(direction)    ((direction) == LazyPDFPopoverArrowDirectionHorizontal || (direction) == LazyPDFPopoverArrowDirectionLeft || (direction) == LazyPDFPopoverArrowDirectionRight)
#endif

typedef enum {
    LazyPDFPopoverWhiteTint,
    LazyPDFPopoverBlackTint,
    LazyPDFPopoverLightGrayTint,
    LazyPDFPopoverGreenTint,
    LazyPDFPopoverRedTint,
    LazyPDFPopoverDefaultTint = LazyPDFPopoverBlackTint
} LazyPDFPopoverTint;

@interface LazyPDFPopoverView : UIView

@property(nonatomic,strong) NSString *title;
@property(nonatomic,assign) CGPoint relativeOrigin;
@property(nonatomic,assign) LazyPDFPopoverTint tint;
@property(nonatomic,assign) BOOL draw3dBorder;
@property(nonatomic,assign) BOOL border; //default YES

-(void)setArrowDirection:(LazyPDFPopoverArrowDirection)arrowDirection;
-(LazyPDFPopoverArrowDirection)arrowDirection;

-(void)addContentView:(UIView*)contentView;

@end


text:
import imp
import os
import py_compile
import shutil
import tempfile
import unittest

from test import support, script_helper

class PyCompileTests(unittest.TestCase):

    def setUp(self):
        self.directory = tempfile.mkdtemp()
        self.source_path = os.path.join(self.directory, '_test.py')
        self.pyc_path = self.source_path + 'c'
        self.cache_path = imp.cache_from_source(self.source_path)
        self.cwd_drive = os.path.splitdrive(os.getcwd())[0]
        # In these tests we compute relative paths.  When using Windows, the
        # current working directory path and the 'self.source_path' might be
        # on different drives.  Therefore we need to switch to the drive where
        # the temporary source file lives.
        drive = os.path.splitdrive(self.source_path)[0]
        if drive:
            os.chdir(drive)
        with open(self.source_path, 'w') as file:
            file.write('x = 123\n')

    def tearDown(self):
        shutil.rmtree(self.directory)
        if self.cwd_drive:
            os.chdir(self.cwd_drive)

    def test_absolute_path(self):
        py_compile.compile(self.source_path, self.pyc_path)
        self.assertTrue(os.path.exists(self.pyc_path))
        self.assertFalse(os.path.exists(self.cache_path))

    def test_cache_path(self):
        py_compile.compile(self.source_path)
        self.assertTrue(os.path.exists(self.cache_path))

    def test_cwd(self):
        cwd = os.getcwd()
        os.chdir(self.directory)
        py_compile.compile(os.path.basename(self.source_path),
                           os.path.basename(self.pyc_path))
        os.chdir(cwd)
        self.assertTrue(os.path.exists(self.pyc_path))
        self.assertFalse(os.path.exists(self.cache_path))

    def test_relative_path(self):
        py_compile.compile(os.path.relpath(self.source_path),
                           os.path.relpath(self.pyc_path))
        self.assertTrue(os.path.exists(self.pyc_path))
        self.assertFalse(os.path.exists(self.cache_path))

def test_main():
    support.run_unittest(PyCompileTests)

if __name__ == "__main__":
    test_main()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using VoteWeb.Models;
using VoteWeb.ViewModels;

namespace VoteWeb.Controllers
{
    public class HomeController : BaseController
    {
        public HomeController(VoteWebDBContext _db) : base(_db)
        {
        }

        /// <summary>
        /// 前台展示最新的分页数据
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            HomeIndexViewModel _viewmodel=new HomeIndexViewModel();
            _viewmodel.Pictures=DB.Pictures.Where(x => x.IsDelete == 0 && x.IsDisplay == 1)
                .OrderBy(x => x.CreateTime)
                .ToList();
            _viewmodel.Top10Pictures=DB.Pictures.Where(x=>x.IsDelete==0&&x.IsDisplay==1)
            .OrderByDescending(x=>x.Votes)
            .OrderByDescending(x=>x.CreateTime)
            .Take(10)
            .ToList();
            return View(_viewmodel);
        }

        public IActionResult List(long CategoryID)
        {
            HomeListViewModel _viewmodel = new HomeListViewModel();
            _viewmodel.Pictures = DB.Pictures.Where(x => x.CategoryID == CategoryID && x.IsDelete == 0 && x.IsDisplay == 1)
                .OrderByDescending(x => x.CreateTime)
                .ToList();
            _viewmodel.Top10Pictures = DB.Pictures.Where(x => x.CategoryID == CategoryID && x.IsDelete == 0 && x.IsDisplay == 1)
                .OrderByDescending(x => x.Votes)
                .ThenByDescending(x => x.CreateTime)
                .ToList();
            _viewmodel.RandomPictures= DB.Pictures.Where(x => x.CategoryID == CategoryID && x.IsDelete == 0 && x.IsDisplay == 1)
                .ToList();
            return View(_viewmodel);
        }

        /// <summary>
        /// 图片详情页面
        /// </summary>
        /// <param name="PictureID"></param>
        /// <returns></returns>
        public IActionResult Detail(int PictureID)
        {
            HomeDetailViewModel _viewmodel = new HomeDetailViewModel();
            Picture entity = DB.Pictures
                .SingleOrDefault(x => x.PictureID == PictureID);
            _viewmodel.picture = entity;
            _viewmodel.NewPictures = DB.Pictures
                .Where(x => x.IsDisplay == 1 && x.IsDelete == 0)
                .OrderByDescending(x => x.CreateTime)
                .ToList();
            _viewmodel.SimilarPictures = DB.Pictures
                .Where(x => x.IsDisplay == 1 && x.IsDelete == 0 && x.CategoryID == entity.CategoryID)
                .OrderByDescending(x => x.CreateTime)
                .ToList();
            return View(_viewmodel);
        }

        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }
        public IActionResult Save()
        {

            return View();
        }

        public IActionResult Error()
        {
            return View();
        }
    }
}


text:
package com.ibm.javabasic.research._05_equals;

/**
 *
 * @author  Wang Yuan
 */
public class EqTester {

    /** Creates a new instance of EqResearchMain */
    public EqTester() {
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // We create two instance of the same class with the same initial values. But default equals() function give us wrong result.
        System.out.println("new sth(1, new int) : " + new Something(1, new Integer(3)).equals(new Something(1, new Integer(3))));
        Integer three = new Integer(3);
		System.out.println("new sth(1, three) : " + new Something(1, three).equals(new Something(1, three)));
		System.out.println("new sth(1, null) : " + new Something(1, null).equals(new Something(1, null)));
        System.out.println("new StringBuffer : " + new StringBuffer("a").equals(new StringBuffer("a")));

        // String implements equals very well.
        System.out.println("new StringBuffer.toString : " + new StringBuffer("a").toString().equals(new StringBuffer("a").toString()));
        System.out.println("new StringBuffer.toString == : " + (new StringBuffer("a").toString() == new StringBuffer("a").toString()));
        System.out.println("new String : " + new String("a").equals(new String("a")));
    }

}


text:
#import <Foundation/Foundation.h>

/**
 @warning The CloudantToolkit framework has been deprecated.  Please migrate to https://github.com/cloudant/CDTDatastore

*/
__deprecated
@interface CDTOperation : NSOperation

@end


text:
package moneytracker.deserializers;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import moneytracker.security.SecurityContext;
import moneytracker.model.Tag;
import moneytracker.services.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import java.io.IOException;

public class TagDeserializer extends JsonDeserializer<Tag> {

    @Autowired
    private TagService tagService;

    @Autowired
    private SecurityContext securityContext;

    public TagDeserializer() {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    }

    @Override
    public Tag deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        try {
            return tagService.get(securityContext.getAuthenticatedUser(), jsonParser.getValueAsLong());
        } catch (IOException e) {
            throw new IOException("Unable to parse tag");
        }
    }

}


text:
package com.amazonaws.services.forecast.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.forecast.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * TimeSeriesConditionMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class TimeSeriesConditionMarshaller {

    private static final MarshallingInfo<String> ATTRIBUTENAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("AttributeName").build();
    private static final MarshallingInfo<String> ATTRIBUTEVALUE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("AttributeValue").build();
    private static final MarshallingInfo<String> CONDITION_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Condition").build();

    private static final TimeSeriesConditionMarshaller instance = new TimeSeriesConditionMarshaller();

    public static TimeSeriesConditionMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(TimeSeriesCondition timeSeriesCondition, ProtocolMarshaller protocolMarshaller) {

        if (timeSeriesCondition == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(timeSeriesCondition.getAttributeName(), ATTRIBUTENAME_BINDING);
            protocolMarshaller.marshall(timeSeriesCondition.getAttributeValue(), ATTRIBUTEVALUE_BINDING);
            protocolMarshaller.marshall(timeSeriesCondition.getCondition(), CONDITION_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
//=============================================================================================================

#ifndef FWDTHREADARG_H
#define FWDTHREADARG_H

//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "fwd_global.h"
#include "fwd_types.h"

//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================

#include <Eigen/Core>

//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QSharedPointer>

//=============================================================================================================
// FORWARD DECLARATIONS
//=============================================================================================================

namespace MNELIB
{
    class MneSourceSpaceOld;
}

//=============================================================================================================
// DEFINE NAMESPACE FWDLIB
//=============================================================================================================

namespace FWDLIB
{

//=============================================================================================================
// FORWARD DECLARATIONS
//=============================================================================================================

class FwdCoilSet;

//=============================================================================================================
/**
 * Implements a Forward Thread Argument (Replaces *fwdThreadArg,fwdThreadArgRec; struct of MNE-C compute_forward.c).
 *
 * @brief Filter Thread Argument Description
 */
class FWDSHARED_EXPORT FwdThreadArg
{
public:
    typedef QSharedPointer<FwdThreadArg> SPtr;              /**< Shared pointer type for FwdThreadArg. */
    typedef QSharedPointer<const FwdThreadArg> ConstSPtr;   /**< Const shared pointer type for FwdThreadArg. */

    //=========================================================================================================
    /**
     * Constructs the Forward Thread Argument
     * Refactored: new_fwd_thread_arg (compute_forward.c)
     */
    FwdThreadArg();

    //=========================================================================================================
    /**
     * Destroys the Forward Thread Argument
     * Refactored: free_fwd_thread_arg (compute_forward.c)
     */
    ~FwdThreadArg();

    static FwdThreadArg* create_eeg_multi_thread_duplicate(FwdThreadArg* one, bool bem_model);

    static void free_eeg_multi_thread_duplicate(FwdThreadArg* one,bool bem_model);

    static FwdThreadArg* create_meg_multi_thread_duplicate(FwdThreadArg* one, bool bem_model);

    static void free_meg_multi_thread_duplicate(FwdThreadArg* one,bool bem_model);

public:
    float               **res;             /* Destination for the solution */
    float               **res_grad;        /* Gradient result */
    int                 off;               /* Offset within the result to the first source space vertex solution */
    fwdFieldFunc        field_pot;         /* Computes the field or potential for one dipole orientation */
    fwdVecFieldFunc     vec_field_pot;     /* Computes the field or potential for all dipole orientations */
    fwdFieldGradFunc    field_pot_grad;    /* Computes the gradient of field or potential for one dipole orientation */
    FwdCoilSet          *coils_els;        /* The coil definitions */
    void                *client;           /* Client data for the field computation function */
    MNELIB::MneSourceSpaceOld   *s;                 /* The source space to process */
    int                 fixed_ori;         /* Compute fixed orientation solution? */
    int                 comp;              /* Which component to compute for free orientations */
    int                 stat;

// ### OLD STRUCT ###
//typedef struct {
//    float            **res;             /* Destination for the solution */
//    float            **res_grad;        /* Gradient result */
//    int              off;               /* Offset within the result to the first source space vertex solution */
//    fwdFieldFunc     field_pot;         /* Computes the field or potential for one dipole orientation */
//    fwdVecFieldFunc  vec_field_pot;     /* Computes the field or potential for all dipole orientations */
//    fwdFieldGradFunc field_pot_grad;    /* Computes the gradient of field or potential for one dipole orientation */
//    fwdCoilSet       coils_els;         /* The coil definitions */
//    void             *client;           /* Client data for the field computation function */
//    mneSourceSpace   s;                 /* The source space to process */
//    int              fixed_ori;         /* Compute fixed orientation solution? */
//    int              comp;              /* Which component to compute for free orientations */
//    int              stat;
//} *fwdThreadArg,fwdThreadArgRec;
};

//=============================================================================================================
// INLINE DEFINITIONS
//=============================================================================================================
} // NAMESPACE FWDLIB

#endif // FWDTHREADARG_H


text:
/**
 * @description defines Role model
 *
 * @param {object} sequelize sequelize orm object
 * @param {object} DataTypes Class that contains Sequelize
 *
 * @returns {function} Constructor function that describes
 * Role model and queries that are possible with it
 */
module.exports = (sequelize, DataTypes) => {
  const Role = sequelize.define('Role', {
    title: {
      type: DataTypes.ENUM,
      values: ['admin', 'user'],
      allowNull: false
    }
  });

  Role.associate = (models) => {
    Role.hasMany(models.User, {
      foreignKey: 'roleId',
      sourceKey: 'id',
      onDelete: 'CASCADE'
    });

    Role.hasMany(models.Document, {
      foreignKey: 'roleId',
      sourceKey: 'id',
      onDelete: 'CASCADE'
    });
  };
  return Role;
};


text:
cask 'graphicconverter' do
  version '10.6.0,3058'
  sha256 '42a5d40921caa3831c3057d1fef90e5390552c45f5add06eb733616f45031522'

  # lemkesoft.info was verified as official when first introduced to the cask
  url "https://www.lemkesoft.info/files/graphicconverter/gc#{version.major}_build#{version.after_comma}.zip"
  appcast "https://www.lemkesoft.info/sparkle/graphicconverter/graphicconverter#{version.major}.xml",
          checkpoint: 'a3c5a250c2637613a6fb4548e70b5ea64cd57289eb016bb9c55a1ea775bb3190'
  name 'GraphicConverter'
  homepage 'https://www.lemkesoft.de/en/products/graphicconverter/'

  auto_updates true
  depends_on macos: '>= :mavericks'

  app "GraphicConverter #{version.major}.app"
end


text:
import $ from 'jquery';
import _ from 'underscore';
import { __ } from '~/locale';
import axios from '~/lib/utils/axios_utils';
import Flash from '~/flash';
import { backOff } from '~/lib/utils/common_utils';
import AUTH_METHOD from './constants';

export default class SSHMirror {
  constructor(formSelector) {
    this.backOffRequestCounter = 0;

    this.$form = $(formSelector);

    this.$repositoryUrl = this.$form.find('.js-repo-url');
    this.$knownHosts = this.$form.find('.js-known-hosts');

    this.$sectionSSHHostKeys = this.$form.find('.js-ssh-host-keys-section');
    this.$hostKeysInformation = this.$form.find('.js-fingerprint-ssh-info');
    this.$btnDetectHostKeys = this.$form.find('.js-detect-host-keys');
    this.$btnSSHHostsShowAdvanced = this.$form.find('.btn-show-advanced');
    this.$dropdownAuthType = this.$form.find('.js-mirror-auth-type');

    this.$wellAuthTypeChanging = this.$form.find('.js-well-changing-auth');
    this.$wellPasswordAuth = this.$form.find('.js-well-password-auth');
    this.$wellSSHAuth = this.$form.find('.js-well-ssh-auth');
    this.$sshPublicKeyWrap = this.$form.find('.js-ssh-public-key-wrap');
    this.$regeneratePublicSshKeyButton = this.$wellSSHAuth.find('.js-btn-regenerate-ssh-key');
    this.$regeneratePublicSshKeyModal = this.$wellSSHAuth.find(
      '.js-regenerate-public-ssh-key-confirm-modal',
    );
  }

  init() {
    this.handleRepositoryUrlInput(true);

    this.$repositoryUrl.on('keyup', () => this.handleRepositoryUrlInput());
    this.$knownHosts.on('keyup', e => this.handleSSHKnownHostsInput(e));
    this.$dropdownAuthType.on('change', e => this.handleAuthTypeChange(e));
    this.$btnDetectHostKeys.on('click', e => this.handleDetectHostKeys(e));
    this.$btnSSHHostsShowAdvanced.on('click', e => this.handleSSHHostsAdvanced(e));
    this.$regeneratePublicSshKeyButton.on('click', () =>
      this.$regeneratePublicSshKeyModal.toggle(true),
    );
    $('.js-confirm', this.$regeneratePublicSshKeyModal).on('click', e =>
      this.regeneratePublicSshKey(e),
    );
    $('.js-cancel', this.$regeneratePublicSshKeyModal).on('click', () =>
      this.$regeneratePublicSshKeyModal.toggle(false),
    );
  }

  /**
   * Method to monitor Git Repository URL input
   */
  handleRepositoryUrlInput(forceMatch) {
    const protocol = this.$repositoryUrl.val().split('://')[0];
    const protRegEx = /http|git/;

    // Validate URL and verify if it consists only supported protocols
    if (forceMatch || this.$form.get(0).checkValidity()) {
      const isSsh = protocol === 'ssh';
      // Hide/Show SSH Host keys section only for SSH URLs
      this.$sectionSSHHostKeys.collapse(isSsh ? 'show' : 'hide');
      this.$btnDetectHostKeys.enable();

      // Verify if URL is http, https or git and hide/show Auth type dropdown
      // as we don't support auth type SSH for non-SSH URLs
      const matchesProtocol = protRegEx.test(protocol);
      this.$dropdownAuthType.attr('disabled', matchesProtocol);

      if (forceMatch && isSsh) {
        this.$dropdownAuthType.val(AUTH_METHOD.SSH);
        this.toggleAuthWell(AUTH_METHOD.SSH);
      } else {
        this.$dropdownAuthType.val(AUTH_METHOD.PASSWORD);
        this.toggleAuthWell(AUTH_METHOD.PASSWORD);
      }
    }
  }

  /**
   * Click event handler to detect SSH Host key and fingerprints from
   * provided Git Repository URL.
   */
  handleDetectHostKeys() {
    const projectMirrorSSHEndpoint = this.$form.data('project-mirror-ssh-endpoint');
    const repositoryUrl = this.$repositoryUrl.val();
    const currentKnownHosts = this.$knownHosts.val();
    const $btnLoadSpinner = this.$btnDetectHostKeys.find('.js-spinner');

    // Disable button while we make request
    this.$btnDetectHostKeys.disable();
    $btnLoadSpinner.removeClass('d-none');

    // Make backOff polling to get data
    backOff((next, stop) => {
      axios
        .get(
          `${projectMirrorSSHEndpoint}?ssh_url=${repositoryUrl}&compare_host_keys=${encodeURIComponent(
            currentKnownHosts,
          )}`,
        )
        .then(({ data, status }) => {
          if (status === 204) {
            this.backOffRequestCounter += 1;
            if (this.backOffRequestCounter < 3) {
              next();
            } else {
              stop(data);
            }
          } else {
            stop(data);
          }
        })
        .catch(stop);
    })
      .then(res => {
        $btnLoadSpinner.addClass('d-none');
        // Once data is received, we show verification info along with Host keys and fingerprints
        this.$hostKeysInformation
          .find('.js-fingerprint-verification')
          .collapse(res.host_keys_changed ? 'hide' : 'show');
        if (res.known_hosts && res.fingerprints) {
          this.showSSHInformation(res);
        }
      })
      .catch(({ response }) => {
        // Show failure message when there's an error and re-enable Detect host keys button
        const failureMessage = response.data
          ? response.data.message
          : __('An error occurred while detecting host keys');
        Flash(failureMessage);

        $btnLoadSpinner.addClass('hidden');
        this.$btnDetectHostKeys.enable();
      });
  }

  /**
   * Method to monitor known hosts textarea input
   */
  handleSSHKnownHostsInput() {
    // Strike-out fingerprints and remove verification info if `known hosts` value is altered
    this.$hostKeysInformation.find('.js-fingerprints-list').addClass('invalidate');
    this.$hostKeysInformation.find('.js-fingerprint-verification').collapse('hide');
  }

  /**
   * Click event handler for `Show advanced` button under SSH Host keys section
   */
  handleSSHHostsAdvanced() {
    const $knownHost = this.$sectionSSHHostKeys.find('.js-ssh-known-hosts');
    const toggleShowAdvanced = $knownHost.hasClass('show');

    $knownHost.collapse('toggle');
    this.$btnSSHHostsShowAdvanced.toggleClass('show-advanced', toggleShowAdvanced);
  }

  /**
   * Authentication method dropdown change event listener
   */
  handleAuthTypeChange() {
    const projectMirrorAuthTypeEndpoint = `${this.$form.attr('action')}.json`;
    const $sshPublicKey = this.$sshPublicKeyWrap.find('.ssh-public-key');
    const selectedAuthType = this.$dropdownAuthType.val();

    this.$wellPasswordAuth.collapse('hide');
    this.$wellSSHAuth.collapse('hide');

    // This request should happen only if selected Auth type was SSH
    // and SSH Public key was not present on page load
    if (selectedAuthType === AUTH_METHOD.SSH && !$sshPublicKey.text().trim()) {
      if (!this.$wellSSHAuth.length) return;

      // Construct request body
      const authTypeData = {
        project: {
          ...this.$regeneratePublicSshKeyButton.data().projectData,
        },
      };

      this.$wellAuthTypeChanging.collapse('show');
      this.$dropdownAuthType.disable();

      axios
        .put(projectMirrorAuthTypeEndpoint, JSON.stringify(authTypeData), {
          headers: {
            'Content-Type': 'application/json; charset=utf-8',
          },
        })
        .then(({ data }) => {
          // Show SSH public key container and fill in public key
          this.toggleAuthWell(selectedAuthType);
          this.toggleSSHAuthWellMessage(true);
          this.setSSHPublicKey(data.import_data_attributes.ssh_public_key);

          this.$wellAuthTypeChanging.collapse('hide');
          this.$dropdownAuthType.enable();
        })
        .catch(() => {
          Flash(__('Something went wrong on our end.'));

          this.$wellAuthTypeChanging.collapse('hide');
          this.$dropdownAuthType.enable();
        });
    } else {
      this.toggleAuthWell(selectedAuthType);
      this.$wellSSHAuth.find('.js-ssh-public-key-present').collapse('show');
    }
  }

  /**
   * Method to parse SSH Host keys data and render it
   * under SSH host keys section
   */
  showSSHInformation(sshHostKeys) {
    const $fingerprintsList = this.$hostKeysInformation.find('.js-fingerprints-list');
    let fingerprints = '';
    sshHostKeys.fingerprints.forEach(fingerprint => {
      const escFingerprints = _.escape(fingerprint.fingerprint);
      fingerprints += `<code>${escFingerprints}</code>`;
    });

    this.$hostKeysInformation.collapse('show');
    $fingerprintsList.removeClass('invalidate');
    $fingerprintsList.html(fingerprints);
    this.$sectionSSHHostKeys.find('.js-known-hosts').val(sshHostKeys.known_hosts);
  }

  /**
   * Toggle Auth type information container based on provided `authType`
   */
  toggleAuthWell(authType) {
    this.$wellPasswordAuth.collapse(authType === AUTH_METHOD.PASSWORD ? 'show' : 'hide');
    this.$wellSSHAuth.collapse(authType === AUTH_METHOD.SSH ? 'show' : 'hide');
  }

  /**
   * Toggle SSH auth information message
   */
  toggleSSHAuthWellMessage(sshKeyPresent) {
    this.$sshPublicKeyWrap.collapse(sshKeyPresent ? 'show' : 'hide');
    this.$wellSSHAuth.find('.js-ssh-public-key-present').collapse(sshKeyPresent ? 'show' : 'hide');
    this.$regeneratePublicSshKeyButton.collapse(sshKeyPresent ? 'show' : 'hide');
    this.$wellSSHAuth.find('.js-ssh-public-key-pending').collapse(sshKeyPresent ? 'hide' : 'show');
  }

  /**
   * Sets SSH Public key to Clipboard button and shows it on UI.
   */
  setSSHPublicKey(sshPublicKey) {
    this.$sshPublicKeyWrap.find('.ssh-public-key').text(sshPublicKey);
    this.$sshPublicKeyWrap
      .find('.btn-copy-ssh-public-key')
      .attr('data-clipboard-text', sshPublicKey);
  }

  regeneratePublicSshKey(event) {
    event.preventDefault();

    this.$regeneratePublicSshKeyModal.toggle(false);

    const button = this.$regeneratePublicSshKeyButton;
    const spinner = $('.js-spinner', button);
    const endpoint = button.data('endpoint');
    const authTypeData = {
      project: {
        ...this.$regeneratePublicSshKeyButton.data().projectData,
      },
    };

    button.attr('disabled', 'disabled');
    spinner.removeClass('d-none');

    axios
      .patch(endpoint, authTypeData)
      .then(({ data }) => {
        button.removeAttr('disabled');
        spinner.addClass('d-none');

        this.setSSHPublicKey(data.import_data_attributes.ssh_public_key);
      })
      .catch(() => {
        Flash(_('Unable to regenerate public ssh key.'));
      });
  }

  destroy() {
    this.$repositoryUrl.off('keyup');
    this.$form.find('.js-known-hosts').off('keyup');
    this.$dropdownAuthType.off('change');
    this.$btnDetectHostKeys.off('click');
    this.$btnSSHHostsShowAdvanced.off('click');
    this.$regeneratePublicSshKeyButton.off('click');
    $('.js-confirm', this.$regeneratePublicSshKeyModal).off('click');
    $('.js-cancel', this.$regeneratePublicSshKeyModal).off('click');
  }
}


text:
package biz.paluch.testing.acceptance.pages;

import static com.codeborne.selenide.Selenide.*;

/**
 * @author Mark Paluch
 * @since 26.01.15 11:16
 */
public class BlogPage {

    public void clickEntry(int no) {
        $$("article").get(no).find("h1 a").click();
    }
}


text:
package com.cmendenhall.utils;

import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.Deque;
import java.util.LinkedList;

public class OutputRecorder extends PrintStream {
    private Deque<String> outputStack;

    public OutputRecorder(OutputStream outputStream, boolean b, String s) throws UnsupportedEncodingException {
        super(outputStream, b, s);
        outputStack = new LinkedList<String>();
    }

    private void catchOutput(String output) {
        outputStack.addFirst(output);
    }

    public String popLastOutput() {
        return outputStack.removeFirst();
    }

    public String popFirstOutput() {
        return outputStack.removeLast();
    }

    public String peekLastOutput() {
        return outputStack.peekFirst();
    }

    public String peekFirstOutput() {
        return outputStack.peekLast();
    }

    public void discardLastNStrings(int n) {
        for (int i=0; i < n; i++) {
           popLastOutput();
        }
    }

    public void discardFirstNStrings(int n) {
        for (int i=0; i < n; i++) {
            popFirstOutput();
        }
    }

    public void replayAllForwards() {
        String output = popFirstOutput();
        int i = 0;
        while (output != null) {
            System.out.println("Element " + i + ":");
            System.out.println(output);
            i += 1;
            output = popFirstOutput();
        }
    }

    public void replayAllBackwards() {
        String output = popLastOutput();
        int i = outputStack.size();
        while (output != null) {
            System.out.println("Element " + i + ":");
            System.out.println(output);
            i -= 1;
            output = popLastOutput();
        }
    }

    @Override
    public void println(String output) {
        catchOutput(output);
    }

    @Override
    public void print(String output) {
        catchOutput(output);
    }

}


text:
package org.jboss.resteasy.test.client.proxy.resource;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Link;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import org.jboss.resteasy.specimpl.LinkBuilderImpl;

import java.net.URI;

@Path("test")
public class ResponseObjectResource {

   @GET
   @Produces("text/plain")
   public String get() {
      return "ABC";
   }

   @GET
   @Path("/link-header")
   public Response getWithHeader(@Context UriInfo uri) {
      URI subUri = uri.getAbsolutePathBuilder().path("next-link").build();
      Link link = new LinkBuilderImpl().uri(subUri).rel("nextLink").build();
      return Response.noContent().header("Link", link.toString()).build();
   }

   @GET
   @Produces("text/plain")
   @Path("/link-header/next-link")
   public String getHeaderForward() {
      return "forwarded";
   }
}


text:
<!doctype html>

  <title>

      AutoTame for Bukkit | Drew Higgins

  </title>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta charset="utf-8">

  <link rel="stylesheet" href="/assets/css/main.css">
  <link rel="stylesheet" href="/assets/css/syntax.css">

  <link type="application/atom+xml" rel="alternate" href="/feed.xml" title="Drew Higgins" />

  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Serif:400,400italic,700%7CPT+Sans:400">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Code+Pro">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Quattrocento+Sans">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">

<title>AutoTame for Bukkit | Drew Higgins</title>
<meta name="generator" content="Jekyll v3.6.2" />
<meta property="og:title" content="AutoTame for Bukkit" />
<meta name="author" content="Drew Higgins" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="I've recently been crawling Bukkit's "Plugin Request" forum to find some plugin ideas and sharpen up my Java skills, and yesterday, I made one. It's a simple plugin called AutoTame, and it was suggested by user roumen4." />
<meta property="og:description" content="I've recently been crawling Bukkit's "Plugin Request" forum to find some plugin ideas and sharpen up my Java skills, and yesterday, I made one. It's a simple plugin called AutoTame, and it was suggested by user roumen4." />
<meta property="og:site_name" content="Drew Higgins" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2014-08-01T20:00:00-04:00" />

    Drew Higgins
    high tech, high pizza

      About

      Links

      Archives

  AutoTame for Bukkit

I've recently been crawling Bukkit's "Plugin Request" forum to find some plugin ideas and sharpen up my Java skills, and yesterday, I made one. It's a simple plugin called AutoTame, and it was suggested by user roumen4.

Here's the basic idea for the plugin: whenever a user spawns a wolf with a spawn-egg, the plugin will automatically tame the wolf and set its owner as the player who used the spawn egg.

Here we have an open patch of area:

And when we spawn a wolf, he is automatically tamed to the closest player:

We can change his collar color with /collar <color/random> (random picks a random color)

And if we die (and config.yml is set to do so), our wolves die too:

That's about it! If you want to get the plugin JAR, you can download it here. You can get the source on GitHub as well.

  Written on

  August
  1st
    ,
  2014
  by

    Drew Higgins

Feel free to share!

You may also enjoy:

© 2018 Drew Higgins | Lagrange Jekyll theme by Paul Le.


text:
<?php

/*
 * This file is part of the Silex framework.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Silex\Tests\Provider;

use Pimple\Container;
use Silex\Application;
use Silex\Provider\DoctrineServiceProvider;

/**
 * DoctrineProvider test cases.
 *
 * Fabien Potencier <fabien@symfony.com>
 */
class DoctrineServiceProviderTest extends \PHPUnit_Framework_TestCase
{
    public function testOptionsInitializer()
    {
        $app = new Application();
        $app->register(new DoctrineServiceProvider());

        $this->assertEquals($app['db.default_options'], $app['db']->getParams());
    }

    public function testSingleConnection()
    {
        if (!in_array('sqlite', \PDO::getAvailableDrivers())) {
            $this->markTestSkipped('pdo_sqlite is not available');
        }

        $app = new Application();
        $app->register(new DoctrineServiceProvider(), array(
            'db.options' => array('driver' => 'pdo_sqlite', 'memory' => true),
        ));

        $db = $app['db'];
        $params = $db->getParams();
        $this->assertTrue(array_key_exists('memory', $params));
        $this->assertTrue($params['memory']);
        $this->assertInstanceof('Doctrine\DBAL\Driver\PDOSqlite\Driver', $db->getDriver());
        $this->assertEquals(22, $app['db']->fetchColumn('SELECT 22'));

        $this->assertSame($app['dbs']['default'], $db);
    }

    public function testMultipleConnections()
    {
        if (!in_array('sqlite', \PDO::getAvailableDrivers())) {
            $this->markTestSkipped('pdo_sqlite is not available');
        }

        $app = new Application();
        $app->register(new DoctrineServiceProvider(), array(
            'dbs.options' => array(
                'sqlite1' => array('driver' => 'pdo_sqlite', 'memory' => true),
                'sqlite2' => array('driver' => 'pdo_sqlite', 'path' => sys_get_temp_dir().'/silex'),
            ),
        ));

        $db = $app['db'];
        $params = $db->getParams();
        $this->assertTrue(array_key_exists('memory', $params));
        $this->assertTrue($params['memory']);
        $this->assertInstanceof('Doctrine\DBAL\Driver\PDOSqlite\Driver', $db->getDriver());
        $this->assertEquals(22, $app['db']->fetchColumn('SELECT 22'));

        $this->assertSame($app['dbs']['sqlite1'], $db);

        $db2 = $app['dbs']['sqlite2'];
        $params = $db2->getParams();
        $this->assertTrue(array_key_exists('path', $params));
        $this->assertEquals(sys_get_temp_dir().'/silex', $params['path']);
    }

    public function testLoggerLoading()
    {
        if (!in_array('sqlite', \PDO::getAvailableDrivers())) {
            $this->markTestSkipped('pdo_sqlite is not available');
        }

        $app = new Application();
        $this->assertTrue(isset($app['logger']));
        $this->assertNull($app['logger']);
        $app->register(new DoctrineServiceProvider(), array(
            'dbs.options' => array(
                'sqlite1' => array('driver' => 'pdo_sqlite', 'memory' => true),
            ),
        ));
        $this->assertEquals(22, $app['db']->fetchColumn('SELECT 22'));
        $this->assertNull($app['db']->getConfiguration()->getSQLLogger());
    }

    public function testLoggerNotLoaded()
    {
        if (!in_array('sqlite', \PDO::getAvailableDrivers())) {
            $this->markTestSkipped('pdo_sqlite is not available');
        }

        $app = new Container();
        $app->register(new DoctrineServiceProvider(), array(
            'dbs.options' => array(
                'sqlite1' => array('driver' => 'pdo_sqlite', 'memory' => true),
            ),
        ));
        $this->assertEquals(22, $app['db']->fetchColumn('SELECT 22'));
        $this->assertNull($app['db']->getConfiguration()->getSQLLogger());
    }
}


text:
<?php

/**
 * @file
 * Contains \Drupal\hal\Normalizer\FieldNormalizer.
 */

namespace Drupal\hal\Normalizer;

use Drupal\Component\Utility\NestedArray;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;

/**
 * Converts the Drupal field structure to HAL array structure.
 */
class FieldNormalizer extends NormalizerBase {

  /**
   * The interface or class that this Normalizer supports.
   *
   * @var string
   */
  protected $supportedInterfaceOrClass = 'Drupal\Core\Field\FieldItemListInterface';

  /**
   * Implements \Symfony\Component\Serializer\Normalizer\NormalizerInterface::normalize()
   */
  public function normalize($field, $format = NULL, array $context = array()) {
    $normalized_field_items = array();

    // Get the field definition.
    $entity = $field->getEntity();
    $field_name = $field->getName();
    $field_definition = $field->getFieldDefinition();

    // If this field is not translatable, it can simply be normalized without
    // separating it into different translations.
    if (!$field_definition->isTranslatable()) {
      $normalized_field_items = $this->normalizeFieldItems($field, $format, $context);
    }
    // Otherwise, the languages have to be extracted from the entity and passed
    // in to the field item normalizer in the context. The langcode is appended
    // to the field item values.
    else {
      foreach ($entity->getTranslationLanguages() as $language) {
        $context['langcode'] = $language->getId();
        $translation = $entity->getTranslation($language->getId());
        $translated_field = $translation->get($field_name);
        $normalized_field_items = array_merge($normalized_field_items, $this->normalizeFieldItems($translated_field, $format, $context));
      }
    }

    // Merge deep so that links set in entity reference normalizers are merged
    // into the links property.
    $normalized = NestedArray::mergeDeepArray($normalized_field_items);
    return $normalized;
  }

  /**
   * Implements \Symfony\Component\Serializer\Normalizer\DenormalizerInterface::denormalize()
   */
  public function denormalize($data, $class, $format = NULL, array $context = array()) {
    if (!isset($context['target_instance'])) {
      throw new InvalidArgumentException('$context[\'target_instance\'] must be set to denormalize with the FieldNormalizer');
    }
    if ($context['target_instance']->getParent() == NULL) {
      throw new InvalidArgumentException('The field passed in via $context[\'target_instance\'] must have a parent set.');
    }

    $items = $context['target_instance'];
    $item_class = $items->getItemDefinition()->getClass();
    foreach ($data as $item_data) {
      // Create a new item and pass it as the target for the unserialization of
      // $item_data. Note: if $item_data is about a different language than the
      // default, FieldItemNormalizer::denormalize() will dismiss this item and
      // create a new one for the right language.
      $context['target_instance'] = $items->appendItem();
      $this->serializer->denormalize($item_data, $item_class, $format, $context);
    }

    return $items;

  }

  /**
   * Helper function to normalize field items.
   *
   * @param \Drupal\Core\Field\FieldItemListInterface $field
   *   The field object.
   * @param string $format
   *   The format.
   * @param array $context
   *   The context array.
   *
   * @return array
   *   The array of normalized field items.
   */
  protected function normalizeFieldItems($field, $format, $context) {
    $normalized_field_items = array();
    if (!$field->isEmpty()) {
      foreach ($field as $field_item) {
        $normalized_field_items[] = $this->serializer->normalize($field_item, $format, $context);
      }
    }
    return $normalized_field_items;
  }

}