text:
package org.spongepowered.common.mixin.core.world.chunk.storage;

import com.flowpowered.math.vector.Vector3d;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.entity.item.EntityMinecart;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.AnvilChunkLoader;
import net.minecraft.world.chunk.storage.RegionFileCache;
import net.minecraft.world.storage.ThreadedFileIOBase;
import org.apache.logging.log4j.Logger;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.entity.EntityType;
import org.spongepowered.api.entity.Transform;
import org.spongepowered.api.event.CauseStackManager.StackFrame;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.EventContext;
import org.spongepowered.api.event.cause.EventContextKeys;
import org.spongepowered.api.event.cause.entity.spawn.SpawnTypes;
import org.spongepowered.api.event.entity.ConstructEntityEvent;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import org.spongepowered.common.SpongeImpl;
import org.spongepowered.common.SpongeImplHooks;
import org.spongepowered.common.bridge.world.WorldBridge;
import org.spongepowered.common.bridge.world.chunk.ChunkBridge;
import org.spongepowered.common.bridge.world.chunk.storage.AnvilChunkLoaderBridge;
import org.spongepowered.common.entity.PlayerTracker;
import org.spongepowered.common.event.ShouldFire;
import org.spongepowered.common.registry.type.entity.EntityTypeRegistryModule;
import org.spongepowered.common.util.Constants;
import org.spongepowered.common.util.QueuedChunk;
import org.spongepowered.common.util.VecHelper;
import org.spongepowered.common.util.WorldChunkPos;

import java.io.File;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;

@Mixin(AnvilChunkLoader.class)
public abstract class AnvilChunkLoaderMixin implements AnvilChunkLoaderBridge {

    private ConcurrentLinkedQueue<QueuedChunk> impl$queue = new ConcurrentLinkedQueue<>();
    private final Object impl$lock = new Object();

    @Shadow @Final private static Logger LOGGER;
    @Shadow @Final private Map<ChunkPos, NBTTagCompound> chunksToSave;
    @Shadow @Final private File chunkSaveLocation;
    @Shadow private boolean flushing;

    @Shadow private void writeChunkData(final ChunkPos pos, final NBTTagCompound compound) { } // Shadow

    @Inject(method = "writeChunkToNBT", at = @At(value = "RETURN"))
    private void impl$writeSpongeOwnerNotifierPosTable(final net.minecraft.world.chunk.Chunk chunkIn, final World worldIn,
        final NBTTagCompound compound, final CallbackInfo ci) {
        final ChunkBridge chunk = (ChunkBridge) chunkIn;

        // Add tracked block positions
        if (chunk.bridge$getTrackedShortPlayerPositions().size() > 0 || chunk.bridge$getTrackedIntPlayerPositions().size() > 0) {
            final NBTTagCompound trackedNbt = new NBTTagCompound();
            final NBTTagList positions = new NBTTagList();
            trackedNbt.setTag(Constants.Sponge.SPONGE_BLOCK_POS_TABLE, positions);
            compound.setTag(Constants.Sponge.SPONGE_DATA, trackedNbt);

            for (final Map.Entry<Short, PlayerTracker> mapEntry : chunk.bridge$getTrackedShortPlayerPositions().entrySet()) {
                final Short pos = mapEntry.getKey();
                final int ownerUniqueIdIndex = mapEntry.getValue().ownerIndex;
                final int notifierUniqueIdIndex = mapEntry.getValue().notifierIndex;
                final NBTTagCompound valueNbt = new NBTTagCompound();
                valueNbt.setInteger("owner", ownerUniqueIdIndex);
                valueNbt.setInteger("notifier", notifierUniqueIdIndex);
                valueNbt.setShort("pos", pos);
                positions.appendTag(valueNbt);
            }

            for (final Map.Entry<Integer, PlayerTracker> mapEntry : chunk.bridge$getTrackedIntPlayerPositions().entrySet()) {
                final Integer pos = mapEntry.getKey();
                final int ownerUniqueIdIndex = mapEntry.getValue().ownerIndex;
                final int notifierUniqueIdIndex = mapEntry.getValue().notifierIndex;
                final NBTTagCompound valueNbt = new NBTTagCompound();
                valueNbt.setInteger("owner", ownerUniqueIdIndex);
                valueNbt.setInteger("notifier", notifierUniqueIdIndex);
                valueNbt.setInteger("ipos", pos);
                positions.appendTag(valueNbt);
            }
        }
    }

    @Inject(method = "readChunkFromNBT", at = @At(value = "INVOKE", target = "Lnet/minecraft/nbt/NBTTagCompound;getIntArray(Ljava/lang/String;)[I", shift = At.Shift.BEFORE), locals = LocalCapture.CAPTURE_FAILHARD)
    private void onReadChunkFromNBT(final World worldIn, final NBTTagCompound compound, final CallbackInfoReturnable<net.minecraft.world.chunk.Chunk> ci, final int chunkX,
      final int chunkZ, final net.minecraft.world.chunk.Chunk chunkIn) {
        if (compound.hasKey(Constants.Sponge.SPONGE_DATA)) {
            final Map<Integer, PlayerTracker> trackedIntPlayerPositions = new HashMap<>();
            final Map<Short, PlayerTracker> trackedShortPlayerPositions = new HashMap<>();
            final NBTTagList positions = compound.getCompoundTag(Constants.Sponge.SPONGE_DATA).getTagList(Constants.Sponge.SPONGE_BLOCK_POS_TABLE, 10);
            final ChunkBridge chunk = (ChunkBridge) chunkIn;
            for (int i = 0; i < positions.tagCount(); i++) {
                final NBTTagCompound valueNbt = positions.getCompoundTagAt(i);
                final boolean isShortPos = valueNbt.hasKey("pos");
                final PlayerTracker tracker = new PlayerTracker();
                if (valueNbt.hasKey("owner")) {
                    tracker.ownerIndex = valueNbt.getInteger("owner");
                } else if (valueNbt.hasKey("uuid")) { // Migrate old data, remove in future
                    tracker.ownerIndex = valueNbt.getInteger("uuid");
                }
                if (valueNbt.hasKey("notifier")) {
                    tracker.notifierIndex = valueNbt.getInteger("notifier");
                }

                if (tracker.notifierIndex != -1 || tracker.ownerIndex != -1) {
                    if (isShortPos) {
                        trackedShortPlayerPositions.put(valueNbt.getShort("pos"), tracker);
                    } else {
                        trackedIntPlayerPositions.put(valueNbt.getInteger("ipos"), tracker);
                    }
                }
            }
            chunk.bridge$setTrackedIntPlayerPositions(trackedIntPlayerPositions);
            chunk.bridge$setTrackedShortPlayerPositions(trackedShortPlayerPositions);
        }
    }

    /**
     * @author gabizou - January 30th, 2016
     *
     *         Attempts to redirect EntityList spawning an entity. Forge
     *         rewrites this method to handle it in a different method, so this
     *         will not actually inject in SpongeForge.
     */
    @Redirect(method = "readChunkEntity",
        at = @At(
            value = "INVOKE",
            target = "Lnet/minecraft/world/chunk/storage/AnvilChunkLoader;createEntityFromNBT(Lnet/minecraft/nbt/NBTTagCompound;Lnet/minecraft/world/World;)Lnet/minecraft/entity/Entity;"),
        require = 0,
        expect = 0)
    private static Entity impl$createEntityFromCompound(final NBTTagCompound compound, final World world) {
        if ("Minecart".equals(compound.getString(Constants.Entity.ENTITY_TYPE_ID))) {
            compound.setString(Constants.Entity.ENTITY_TYPE_ID,
                    EntityMinecart.Type.values()[compound.getInteger(Constants.Entity.Minecart.MINECART_TYPE)].getName());
            compound.removeTag(Constants.Entity.Minecart.MINECART_TYPE);
        }
        final Class<? extends Entity> entityClass = SpongeImplHooks.getEntityClass(new ResourceLocation(compound.getString(Constants.Entity.ENTITY_TYPE_ID)));
        if (entityClass == null) {
            return null;
        }
        final EntityType type = EntityTypeRegistryModule.getInstance().getForClass(entityClass);
        if (type == null) {
            return null;
        }
        final NBTTagList positionList = compound.getTagList(Constants.Entity.ENTITY_POSITION, Constants.NBT.TAG_DOUBLE);
        final NBTTagList rotationList = compound.getTagList(Constants.Entity.ENTITY_ROTATION, Constants.NBT.TAG_FLOAT);
        final Vector3d position = new Vector3d(positionList.getDoubleAt(0), positionList.getDoubleAt(1), positionList.getDoubleAt(2));
        final Vector3d rotation = new Vector3d(rotationList.getFloatAt(0), rotationList.getFloatAt(1), 0);
        final Transform<org.spongepowered.api.world.World> transform = new Transform<>((org.spongepowered.api.world.World) world, position, rotation);
        try (final StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
            frame.addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.CHUNK_LOAD);
            final ConstructEntityEvent.Pre event = SpongeEventFactory.createConstructEntityEventPre(frame.getCurrentCause(), type, transform);
            SpongeImpl.postEvent(event);
            if (event.isCancelled()) {
                return null;
            }
            return EntityList.createEntityFromNBT(compound, world);
        }
    }

    @Override
    public boolean bridge$chunkExists(final World world, final int x, final int z) {
        final ChunkPos chunkcoordintpair = new ChunkPos(x, z);

        // Sponge start - Chunk queue improvements
        // if (this.field_193415_c.contains(chunkcoordintpair)) {
        //     for (ChunkPos pendingChunkCoord : this.chunksToSave.keySet()) {
        //         if (pendingChunkCoord.equals(chunkcoordintpair)) {
        //             return true;
        //         }
        //     }
        // }
        if (this.chunksToSave.containsKey(chunkcoordintpair)) {
            return true;
        }
        // Sponge end

        return RegionFileCache.getChunkInputStream(this.chunkSaveLocation, x, z) != null;
    }

    /**
     * @author aikar - February 19th, 2017
     * @reason Chunk queue improvements.
     *
     * @param pos The chunk position to queue
     * @param compound The NBTTagCompound containing chunk data
     */
    @Overwrite
    protected void addChunkToPending(final ChunkPos pos, final NBTTagCompound compound) {
        synchronized (this.impl$lock) {
            this.chunksToSave.put(pos, compound);
        }
        this.impl$queue.add(new QueuedChunk(pos, compound));

        ThreadedFileIOBase.getThreadedIOInstance().queueIO((AnvilChunkLoader) (Object) this);
    }

    /**
     * @author aikar - February 19th, 2017
     * @reason Refactor entire method for chunk queue improvements.
     * @return Whether write was successful
     */
    @Overwrite
    public boolean writeNextIO() {
        final QueuedChunk chunk = this.impl$queue.poll();
        if (chunk == null) {
            if (this.flushing) {
                LOGGER.info("ThreadedAnvilChunkStorage ({}): All chunks are saved", new Object[] {this.chunkSaveLocation.getName()});
            }

            return false;
        } else {
            final ChunkPos chunkpos = chunk.coords;
            boolean lvt_3_1_;

            try {
                // this.field_193415_c.add(chunkpos);
                final NBTTagCompound nbttagcompound = chunk.compound;

                if (nbttagcompound != null) {
                    int attempts = 0;
                    Exception laste = null;
                    while (attempts++ < 5) {
                        try {
                            this.writeChunkData(chunkpos, nbttagcompound);
                            laste = null;
                            break;
                        } catch (final Exception exception) {
                            // LOGGER.error((String)"Failed to save chunk",
                            // (Throwable)exception);
                            laste = exception;
                        }
                        try {
                            Thread.sleep(10);
                        } catch (final InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (laste != null) {
                        laste.printStackTrace();
                    }
                }

                synchronized (this.impl$lock) {
                    if (this.chunksToSave.get(chunkpos) == nbttagcompound) {
                        this.chunksToSave.remove(chunkpos);
                    }
                }
                // Sponge - This will not equal if a newer version is still
                // pending
                lvt_3_1_ = true;
            } finally {
                // this.field_193415_c.remove(chunkpos);
            }

            return lvt_3_1_;
        }
    }

    @Override
    public Path bridge$getWorldDir() {
        return this.chunkSaveLocation.toPath();
    }

    @Redirect(method = "saveChunk", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/chunk/storage/AnvilChunkLoader;addChunkToPending"
            + "(Lnet/minecraft/util/math/ChunkPos;Lnet/minecraft/nbt/NBTTagCompound;)V"))
    private void impl$useWorldChunkPosWhenQueuing(final AnvilChunkLoader anvilChunkLoader, final ChunkPos pos, final NBTTagCompound compound,
            final World worldIn, final Chunk chunkIn) {
        this.addChunkToPending(new WorldChunkPos(((org.spongepowered.api.world.World) worldIn).getUniqueId(), pos.x, pos.z), compound);
    }

    @Inject(method = "writeChunkData", at = @At("RETURN"))
    private void impl$callSaveChunkEventPost(final ChunkPos pos, final NBTTagCompound compound, final CallbackInfo ci) {
        if (ShouldFire.SAVE_CHUNK_EVENT_POST) {
            final Cause cause = Cause.of(EventContext.empty(), Collections.singleton(SpongeImpl.getServer()));
            final Optional<UUID> worldUUID;
            if (pos instanceof WorldChunkPos) {
                worldUUID = Optional.of(((WorldChunkPos) pos).getWorldUUID());
            } else {
                worldUUID = Optional.empty();
            }
            SpongeImpl.postEvent(SpongeEventFactory.createSaveChunkEventPost(cause, VecHelper.toVec3i(pos), worldUUID));
        }
    }
}


text:
package edu.byu.suite.features.classRolls.model;

import android.graphics.Bitmap;
import android.os.Parcel;

import edu.byu.support.ByuParcelable;

public class Student extends ByuParcelable {

	private String personId;
	private String sortName;
	private String preferredName;
	private String classStanding;
	private String emphasis;
	private String email;
	private String phone;
	private String addressLine1;
	private String addressLine2;
	private Bitmap studentImage;

	private Student(Parcel in) {
		personId = in.readString();
		sortName = in.readString();
		preferredName = in.readString();
		classStanding = in.readString();
		emphasis = in.readString();
		email = in.readString();
		phone = in.readString();
		addressLine1 = in.readString();
		addressLine2 = in.readString();
	}

	public static final Creator<Student> CREATOR = new Creator<Student>() {
		@Override
		public Student createFromParcel(Parcel in) {
			return new Student(in);
		}

		@Override
		public Student[] newArray(int size) {
			return new Student[size];
		}
	};

	public String getPersonId() {
		return personId;
	}

	public String getSortName() {
		return sortName;
	}

	public String getFlashCardName() {
		if (preferredName != null)
			return sortName + " (" + preferredName + ") ";
		else {
			return sortName;
		}
	}

	public String getClassStanding() {
		return classStanding;
	}

	public String getEmphasis() {
		return emphasis;
	}

	public String getEmail() {
		return email;
	}

	public String getPhone() {
		return phone;
	}

	public String getAddressLine1() {
		return addressLine1;
	}

	public String getAddressLine2() {
		return addressLine2;
	}

	public Bitmap getStudentImage() {
		return studentImage;
	}

	public void setStudentImage(Bitmap studentImage) {
		this.studentImage = studentImage;
	}

	@Override
	public void writeToParcel(Parcel parcel, int i) {
		parcel.writeString(personId);
		parcel.writeString(sortName);
		parcel.writeString(preferredName);
		parcel.writeString(classStanding);
		parcel.writeString(emphasis);
		parcel.writeString(email);
		parcel.writeString(phone);
		parcel.writeString(addressLine1);
		parcel.writeString(addressLine2);
	}
}

redpajama_set_name: RedPajamaGithub


text:
module Main where

import BasePrelude hiding (assert)
import Data.Default.Class
import Test.QuickCheck.Instances
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.SmallCheck
import Test.Tasty.QuickCheck
import Data.Text (Text)
import qualified Test.QuickCheck as QuickCheck
import qualified Main.Queries as Queries
import qualified XMLQuery as XMLQuery
import qualified XMLQuery.XMLTypes as XMLQueryXMLTypes
import qualified Text.XML as XMLConduit
import qualified Data.XML.Types as XMLTypes

main =
  defaultMain tree

tree =
  testGroup "All tests"
  [
    testCase "sample 1" $
      queryFile Queries.query1 "samples/1.xml" >>=
      \x -> assertEqual (show x) (Right ("Ehrlin, Carl-Johan Forssén", "9788202505929", ["Bøker", "Barnas ARK"])) x
  ]

queryFile :: XMLQuery.Element a -> String -> IO (Either (Maybe Text) a)
queryFile query filename =
  XMLConduit.readFile def filename >>=
  pure . XMLQueryXMLTypes.element query . XMLTypes.documentRoot . XMLConduit.toXMLDocument


text:
import os
import functools

class ChdirStack(object):
    """Stack of current working directories."""

    def __init__(self):
        self.stack = []

    def __len__(self):
        return len(self.stack)

    def push(self, dir):
        """Push cwd on stack and change to 'dir'.
        """
        self.stack.append(os.getcwd())
        os.chdir(dir or os.getcwd())

    def pop(self):
        """Pop dir off stack and change to it.
        """
        if len(self.stack):
            os.chdir(self.stack.pop())

def chdir(method):
    """Decorator executing method in directory 'dir'.
    """
    def wrapper(self, dir, *args, **kw):
        dirstack = ChdirStack()
        dirstack.push(dir)
        try:
            return method(self, dir, *args, **kw)
        finally:
            dirstack.pop()

    return functools.wraps(method)(wrapper)


text:
"""
Flask-MoSession
-----------
Flask-Session provides mongodb based server side session management system for Flask.

"""
from setuptools import setup, find_packages
print find_packages()
setup(
    name='Flask-MoSession',
    version='0.2',
    url='https://github.com/bayazee/flask-mosession',
    license='BSD',
    author='Mehdi Bayazee, Mostafa Rokooie',
    author_email='bayazee@gmail.com, mostafa.rokooie@gmail.com',
    description='Mongodb based server side session management system for Flask',
    long_description=__doc__,
    py_modules=['flask_mosession'],
    packages=find_packages(),
    zip_safe=False,
    platforms='any',
    install_requires=[
        'Flask>=0.9',
        'pycrypto>2.4.1'
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
        'Topic :: Software Development :: Libraries :: Python Modules'
    ],
)


text:
Module Module1

    Sub Main()
        Console.Error.WriteLine("Goodbye, World!")
    End Sub

End Module


text:
{% extends 'layout.html' %}
{% from '_helpers.html' import render_pagination %}
{% block body %}

{{ self.title() }}

  {% block listing_body %}

  {%- for item in pagination.items %}

        {% if g.user %}

          [favorite]

        {% endif %}
        {{
            item.developer.name }} wrote on
          {{ item.pub_date|datetimeformat }}
        {% if item.source == 'forums' %}
          in the forums
        {% elif item.source == 'twitter' %}
          via Twitter
        {% endif %}
        (source):

        {{ item.html_text }}

  {%- endfor %}

  {% if feed_url is defined %}

    Feed

  {% endif %}
  {{ render_pagination(pagination) }}
  {% endblock %}
{% endblock %}


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

#nullable disable

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp
{
    internal sealed partial class CSharpSemanticFacts : ISemanticFacts
    {
        internal static readonly CSharpSemanticFacts Instance = new();

        private CSharpSemanticFacts()
        {
        }

        public bool SupportsImplicitInterfaceImplementation => true;

        public bool ExposesAnonymousFunctionParameterNames => false;

        public bool IsWrittenTo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
            => (node as ExpressionSyntax).IsWrittenTo(semanticModel, cancellationToken);

        public bool IsOnlyWrittenTo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
            => (node as ExpressionSyntax).IsOnlyWrittenTo();

        public bool IsInOutContext(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
            => (node as ExpressionSyntax).IsInOutContext();

        public bool IsInRefContext(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
            => (node as ExpressionSyntax).IsInRefContext();

        public bool IsInInContext(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
            => (node as ExpressionSyntax).IsInInContext();

        public bool CanReplaceWithRValue(SemanticModel semanticModel, SyntaxNode expression, CancellationToken cancellationToken)
            => (expression as ExpressionSyntax).CanReplaceWithRValue(semanticModel, cancellationToken);

        public ISymbol GetDeclaredSymbol(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken)
        {
            var location = token.GetLocation();

            foreach (var ancestor in token.GetAncestors<SyntaxNode>())
            {
                var symbol = semanticModel.GetDeclaredSymbol(ancestor, cancellationToken);
                if (symbol != null)
                {
                    if (symbol is IMethodSymbol { MethodKind: MethodKind.Conversion })
                    {
                        // The token may be part of a larger name (for example, `int` in `public static operator int[](Goo g);`.
                        // So check if the symbol's location encompasses the span of the token we're asking about.
                        if (symbol.Locations.Any(loc => loc.SourceTree == location.SourceTree && loc.SourceSpan.Contains(location.SourceSpan)))
                            return symbol;
                    }
                    else
                    {
                        // For any other symbols, we only care if the name directly matches the span of the token
                        if (symbol.Locations.Contains(location))
                            return symbol;
                    }

                    // We found some symbol, but it defined something else. We're not going to have a higher node defining _another_ symbol with this token, so we can stop now.
                    return null;
                }

                // If we hit an executable statement syntax and didn't find anything yet, we can just stop now -- anything higher would be a member declaration which won't be defined by something inside a statement.
                if (CSharpSyntaxFacts.Instance.IsExecutableStatement(ancestor))
                {
                    return null;
                }
            }

            return null;
        }

        public bool LastEnumValueHasInitializer(INamedTypeSymbol namedTypeSymbol)
        {
            var enumDecl = namedTypeSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax()).OfType<EnumDeclarationSyntax>().FirstOrDefault();
            if (enumDecl != null)
            {
                var lastMember = enumDecl.Members.LastOrDefault();
                if (lastMember != null)
                {
                    return lastMember.EqualsValue != null;
                }
            }

            return false;
        }

        public bool SupportsParameterizedProperties => false;

        public bool TryGetSpeculativeSemanticModel(SemanticModel oldSemanticModel, SyntaxNode oldNode, SyntaxNode newNode, out SemanticModel speculativeModel)
        {
            Debug.Assert(oldNode.Kind() == newNode.Kind());

            var model = oldSemanticModel;
            if (oldNode is not BaseMethodDeclarationSyntax oldMethod || newNode is not BaseMethodDeclarationSyntax newMethod || oldMethod.Body == null)
            {
                speculativeModel = null;
                return false;
            }

            var success = model.TryGetSpeculativeSemanticModelForMethodBody(oldMethod.Body.OpenBraceToken.Span.End, newMethod, out var csharpModel);
            speculativeModel = csharpModel;
            return success;
        }

        public ImmutableHashSet<string> GetAliasNameSet(SemanticModel model, CancellationToken cancellationToken)
        {
            var original = model.GetOriginalSemanticModel();
            if (!original.SyntaxTree.HasCompilationUnitRoot)
            {
                return ImmutableHashSet.Create<string>();
            }

            var root = original.SyntaxTree.GetCompilationUnitRoot(cancellationToken);
            var builder = ImmutableHashSet.CreateBuilder<string>(StringComparer.Ordinal);

            AppendAliasNames(root.Usings, builder);
            AppendAliasNames(root.Members.OfType<BaseNamespaceDeclarationSyntax>(), builder, cancellationToken);

            return builder.ToImmutable();
        }

        private static void AppendAliasNames(SyntaxList<UsingDirectiveSyntax> usings, ImmutableHashSet<string>.Builder builder)
        {
            foreach (var @using in usings)
            {
                if (@using.Alias == null || @using.Alias.Name == null)
                {
                    continue;
                }

                @using.Alias.Name.Identifier.ValueText.AppendToAliasNameSet(builder);
            }
        }

        private void AppendAliasNames(IEnumerable<BaseNamespaceDeclarationSyntax> namespaces, ImmutableHashSet<string>.Builder builder, CancellationToken cancellationToken)
        {
            foreach (var @namespace in namespaces)
            {
                cancellationToken.ThrowIfCancellationRequested();

                AppendAliasNames(@namespace.Usings, builder);
                AppendAliasNames(@namespace.Members.OfType<BaseNamespaceDeclarationSyntax>(), builder, cancellationToken);
            }
        }

        public ForEachSymbols GetForEachSymbols(SemanticModel semanticModel, SyntaxNode forEachStatement)
        {
            if (forEachStatement is CommonForEachStatementSyntax csforEachStatement)
            {
                var info = semanticModel.GetForEachStatementInfo(csforEachStatement);
                return new ForEachSymbols(
                    info.GetEnumeratorMethod,
                    info.MoveNextMethod,
                    info.CurrentProperty,
                    info.DisposeMethod,
                    info.ElementType);
            }
            else
            {
                return default;
            }
        }

        public IMethodSymbol GetGetAwaiterMethod(SemanticModel semanticModel, SyntaxNode node)
        {
            if (node is AwaitExpressionSyntax awaitExpression)
            {
                var info = semanticModel.GetAwaitExpressionInfo(awaitExpression);
                return info.GetAwaiterMethod;
            }

            return null;
        }

        public ImmutableArray<IMethodSymbol> GetDeconstructionAssignmentMethods(SemanticModel semanticModel, SyntaxNode node)
        {
            if (node is AssignmentExpressionSyntax assignment && assignment.IsDeconstruction())
            {
                using var builder = TemporaryArray<IMethodSymbol>.Empty;
                FlattenDeconstructionMethods(semanticModel.GetDeconstructionInfo(assignment), ref builder.AsRef());
                return builder.ToImmutableAndClear();
            }

            return ImmutableArray<IMethodSymbol>.Empty;
        }

        public ImmutableArray<IMethodSymbol> GetDeconstructionForEachMethods(SemanticModel semanticModel, SyntaxNode node)
        {
            if (node is ForEachVariableStatementSyntax @foreach)
            {
                using var builder = TemporaryArray<IMethodSymbol>.Empty;
                FlattenDeconstructionMethods(semanticModel.GetDeconstructionInfo(@foreach), ref builder.AsRef());
                return builder.ToImmutableAndClear();
            }

            return ImmutableArray<IMethodSymbol>.Empty;
        }

        private static void FlattenDeconstructionMethods(DeconstructionInfo deconstruction, ref TemporaryArray<IMethodSymbol> builder)
        {
            var method = deconstruction.Method;
            if (method != null)
            {
                builder.Add(method);
            }

            foreach (var nested in deconstruction.Nested)
            {
                FlattenDeconstructionMethods(nested, ref builder);
            }
        }

        public bool IsPartial(ITypeSymbol typeSymbol, CancellationToken cancellationToken)
        {
            var syntaxRefs = typeSymbol.DeclaringSyntaxReferences;
            return syntaxRefs.Any(n => ((BaseTypeDeclarationSyntax)n.GetSyntax(cancellationToken)).Modifiers.Any(SyntaxKind.PartialKeyword));
        }

        public IEnumerable<ISymbol> GetDeclaredSymbols(
            SemanticModel semanticModel, SyntaxNode memberDeclaration, CancellationToken cancellationToken)
        {
            switch (memberDeclaration)
            {
                case FieldDeclarationSyntax field:
                    return field.Declaration.Variables.Select(
                        v => semanticModel.GetDeclaredSymbol(v, cancellationToken));

                case EventFieldDeclarationSyntax eventField:
                    return eventField.Declaration.Variables.Select(
                        v => semanticModel.GetDeclaredSymbol(v, cancellationToken));

                default:
                    return SpecializedCollections.SingletonEnumerable(
                        semanticModel.GetDeclaredSymbol(memberDeclaration, cancellationToken));
            }
        }

        public IParameterSymbol FindParameterForArgument(SemanticModel semanticModel, SyntaxNode argumentNode, CancellationToken cancellationToken)
            => ((ArgumentSyntax)argumentNode).DetermineParameter(semanticModel, allowParams: false, cancellationToken);

        public ImmutableArray<ISymbol> GetBestOrAllSymbols(SemanticModel semanticModel, SyntaxNode node, SyntaxToken token, CancellationToken cancellationToken)
        {
            if (node == null)
                return ImmutableArray<ISymbol>.Empty;

            return node switch
            {
                AssignmentExpressionSyntax _ when token.Kind() == SyntaxKind.EqualsToken => GetDeconstructionAssignmentMethods(semanticModel, node).As<ISymbol>(),
                ForEachVariableStatementSyntax _ when token.Kind() == SyntaxKind.InKeyword => GetDeconstructionForEachMethods(semanticModel, node).As<ISymbol>(),
                _ => GetSymbolInfo(semanticModel, node, token, cancellationToken).GetBestOrAllSymbols(),
            };
        }

        private static SymbolInfo GetSymbolInfo(SemanticModel semanticModel, SyntaxNode node, SyntaxToken token, CancellationToken cancellationToken)
        {
            switch (node)
            {
                case OrderByClauseSyntax orderByClauseSyntax:
                    if (token.Kind() == SyntaxKind.CommaToken)
                    {
                        // Returning SymbolInfo for a comma token is the last resort
                        // in an order by clause if no other tokens to bind to a are present.
                        // See also the proposal at https://github.com/dotnet/roslyn/issues/23394
                        var separators = orderByClauseSyntax.Orderings.GetSeparators().ToImmutableList();
                        var index = separators.IndexOf(token);
                        if (index >= 0 && (index + 1) < orderByClauseSyntax.Orderings.Count)
                        {
                            var ordering = orderByClauseSyntax.Orderings[index + 1];
                            if (ordering.AscendingOrDescendingKeyword.Kind() == SyntaxKind.None)
                            {
                                return semanticModel.GetSymbolInfo(ordering, cancellationToken);
                            }
                        }
                    }
                    else if (orderByClauseSyntax.Orderings[0].AscendingOrDescendingKeyword.Kind() == SyntaxKind.None)
                    {
                        // The first ordering is displayed on the "orderby" keyword itself if there isn't a
                        // ascending/descending keyword.
                        return semanticModel.GetSymbolInfo(orderByClauseSyntax.Orderings[0], cancellationToken);
                    }

                    return default;
                case QueryClauseSyntax queryClauseSyntax:
                    var queryInfo = semanticModel.GetQueryClauseInfo(queryClauseSyntax, cancellationToken);
                    var hasCastInfo = queryInfo.CastInfo.Symbol != null;
                    var hasOperationInfo = queryInfo.OperationInfo.Symbol != null;

                    if (hasCastInfo && hasOperationInfo)
                    {
                        // In some cases a single clause binds to more than one method. In those cases
                        // the tokens in the clause determine which of the two SymbolInfos are returned.
                        // See also the proposal at https://github.com/dotnet/roslyn/issues/23394
                        return token.IsKind(SyntaxKind.InKeyword) ? queryInfo.CastInfo : queryInfo.OperationInfo;
                    }

                    if (hasCastInfo)
                    {
                        return queryInfo.CastInfo;
                    }

                    return queryInfo.OperationInfo;
                case IdentifierNameSyntax { Parent: PrimaryConstructorBaseTypeSyntax baseType }:
                    return semanticModel.GetSymbolInfo(baseType, cancellationToken);
            }

            //Only in the orderby clause a comma can bind to a symbol.
            if (token.IsKind(SyntaxKind.CommaToken))
            {
                return default;
            }

            return semanticModel.GetSymbolInfo(node, cancellationToken);
        }

        public bool IsInsideNameOfExpression(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
            => (node as ExpressionSyntax).IsInsideNameOfExpression(semanticModel, cancellationToken);

        public ImmutableArray<IMethodSymbol> GetLocalFunctionSymbols(Compilation compilation, ISymbol symbol, CancellationToken cancellationToken)
        {
            using var _ = ArrayBuilder<IMethodSymbol>.GetInstance(out var builder);
            foreach (var syntaxReference in symbol.DeclaringSyntaxReferences)
            {
                var semanticModel = compilation.GetSemanticModel(syntaxReference.SyntaxTree);
                var node = syntaxReference.GetSyntax(cancellationToken);

                foreach (var localFunction in node.DescendantNodes().Where(CSharpSyntaxFacts.Instance.IsLocalFunctionStatement))
                {
                    var localFunctionSymbol = semanticModel.GetDeclaredSymbol(localFunction, cancellationToken);
                    if (localFunctionSymbol is IMethodSymbol methodSymbol)
                    {
                        builder.Add(methodSymbol);
                    }
                }
            }

            return builder.ToImmutable();
        }
    }
}


text:
The game shall begin once there are at least 3 players. The game does not
necessarily end when it is won or even when there are no players.


text:
module AuditProblem
  class Base
    include Mongoid::Document
    field :_id, :type => BSON::ObjectId
    embedded_in :audit, :inverse_of => :audit_problems

    def self.perform(options = {})
      audit = Audit.new(:type => self.to_s)
      audit.started_at   = Time.now
      audit.problems     = run(options)
      audit.completed_at = Time.now
      audit.save!
    end

    def self.run(options = {})
    end

    def self.date_range
      Date.parse('1994-01-01') .. Date.current
    end

    def self.using_object_ids?
      false
    end
  end
end


text:
package co.touchlab.android.threading.tasks.helper;
import android.content.Context;

import co.touchlab.android.threading.errorcontrol.NetworkException;
import co.touchlab.android.threading.errorcontrol.SoftException;
import co.touchlab.android.threading.tasks.persisted.PersistedTask;
import retrofit.RetrofitError;

/**
 * Helper class for using Retrofit and PersistedTask.
 *
 * Created by kgalligan on 4/4/15.
 */
public abstract class RetrofitPersistedTask extends PersistedTask
{
    @Override
    protected final void run(Context context) throws SoftException, Throwable
    {
        try
        {
            runNetwork(context);
        }
        catch(RetrofitError e)
        {
            if(e.getKind() == RetrofitError.Kind.NETWORK)
            {
                throw new NetworkException(e);
            }
        }
    }

    protected  abstract void runNetwork(Context context);

    @Override
    protected boolean handleError(Context context, Throwable e)
    {
        return false;
    }
}


text:
function [J grad] = nnCostFunction(nn_params, ...
                                   input_layer_size, ...
                                   hidden_layer_size, ...
                                   num_labels, ...
                                   X, y, lambda)
%NNCOSTFUNCTION Implements the neural network cost function for a two layer
%neural network which performs classification
%   [J grad] = NNCOSTFUNCTON(nn_params, hidden_layer_size, num_labels, ...
%   X, y, lambda) computes the cost and gradient of the neural network. The
%   parameters for the neural network are "unrolled" into the vector
%   nn_params and need to be converted back into the weight matrices.
%
%   The returned parameter grad should be a "unrolled" vector of the
%   partial derivatives of the neural network.
%

% Reshape nn_params back into the parameters Theta1 and Theta2, the weight matrices
% for our 2 layer neural network
Theta1 = reshape(nn_params(1:hidden_layer_size * (input_layer_size + 1)), ...
                 hidden_layer_size, (input_layer_size + 1));

Theta2 = reshape(nn_params((1 + (hidden_layer_size * (input_layer_size + 1))):end), ...
                 num_labels, (hidden_layer_size + 1));

% Setup some useful variables
m = size(X, 1);

% You need to return the following variables correctly
J = 0;
Theta1_grad = zeros(size(Theta1));
Theta2_grad = zeros(size(Theta2));

% ====================== YOUR CODE HERE ======================
% Instructions: You should complete the code by working through the
%               following parts.
%
% Part 1: Feedforward the neural network and return the cost in the
%         variable J. After implementing Part 1, you can verify that your
%         cost function computation is correct by verifying the cost
%         computed in ex4.m
%
% Part 2: Implement the backpropagation algorithm to compute the gradients
%         Theta1_grad and Theta2_grad. You should return the partial derivatives of
%         the cost function with respect to Theta1 and Theta2 in Theta1_grad and
%         Theta2_grad, respectively. After implementing Part 2, you can check
%         that your implementation is correct by running checkNNGradients
%
%         Note: The vector y passed into the function is a vector of labels
%               containing values from 1..K. You need to map this vector into a
%               binary vector of 1's and 0's to be used with the neural network
%               cost function.
%
%         Hint: We recommend implementing backpropagation using a for-loop
%               over the training examples if you are implementing it for the
%               first time.
%
% Part 3: Implement regularization with the cost function and gradients.
%
%         Hint: You can implement this around the code for
%               backpropagation. That is, you can compute the gradients for
%               the regularization separately and then add them to Theta1_grad
%               and Theta2_grad from Part 2.
%

for i=1:num_labels
    a1 = [ones(m,1) X];
    z2 = a1 * Theta1';
    a2Raw = sigmoid(z2);
    a2 = [ones(m,1) a2Raw];
    z3 = a2 * Theta2';
    a3 = sigmoid(z3);

    yLabel = (y == i);
    hypothesisLabel = a3(:,i);
    term1 = -1 .* yLabel .* log(hypothesisLabel);
    term2 = -1 .* (1 - yLabel) .* log(1 - hypothesisLabel);
    cost = ( 1/m ) * sum(term1 + term2);
    J = J + cost;

    %for t = 1:m
        eyeM = eye(num_labels);
        yM = eyeM(y,:);
        delta3 = a3 - yM;
        theta2NoBias = Theta2(:,2:end);
        delta2 = (delta3 * theta2NoBias) .* sigmoidGradient(z2);
        %delta2 = delta2(2:end);
        D1 = delta2' * a1;
        D2 = delta3' * a2;
        Theta1_grad = (1/m) .* D1;
        Theta2_grad = (1/m) .* D2;
    %end

    tempTheta1 = Theta1;
    tempTheta1(:,1) = zeros(size(Theta1,1),1);
    r1 = lambda/m .* tempTheta1;
    tempTheta2 = Theta2;
    tempTheta2(:,1) = zeros(size(Theta2,1),1);
    r2 = lambda/m .* tempTheta2;
    Theta1_grad = Theta1_grad + r1;
    Theta2_grad = Theta2_grad + r2;
end

th1 = Theta1;
th2 = Theta2;
th1(:,1) = zeros(size(Theta1,1),1);
th2(:,1) = zeros(size(Theta2,1),1);
t1 = sum(sum(th1 .* th1));
t2 = sum(sum(th2 .* th2));
thetaSquared = t1 + t2;
regularizedCost = (lambda / (2*m)) * thetaSquared;
J = J + regularizedCost;

% -------------------------------------------------------------

% =========================================================================

% Unroll gradients
grad = [Theta1_grad(:) ; Theta2_grad(:)];

end


text:
var gov_name_values = gov_names.map ( function(e){return e.gov_name;} );

var substringMatcher = function(strs) {
  return function findMatches(q, cb) {
    var matches, substrRegex;

    // an array that will be populated with substring matches
    matches = [];

    // regex used to determine if a string contains the substring `q`
    substrRegex = new RegExp(q, 'i');

    // iterate through the pool of strings and for any string that
    // contains the substring `q`, add it to the `matches` array
    //var counter=0;
    $.each(strs, function(i, str) {
      if (substrRegex.test(str)) {
        // the typeahead jQuery plugin expects suggestions to a
        // JavaScript object, refer to typeahead docs for more info
        matches.push({ value: str });
        if (matches.length >=10) return false;
      }
    });

    cb(matches);
  };
};

$('.typeahead').typeahead({
  hint: true,
  highlight: true,
  minLength: 1
},
{
  name: 'states',
  displayKey: 'value',
  source: substringMatcher(gov_name_values)
});


text:
import unittest

import pyhelix.accessor as accessor
import pyhelix.helixexec as helixexec
import pyhelix.statemodel as statemodel
import pyhelix.znode as znode

import mockparticipant

class MockStateModel(statemodel.StateModel):
    """
    A state model with nop transitions
    """
    def default_transition_handler(self, message):
        pass

class MockStateModelFactory(statemodel.StateModel):
    """
    A factory for a nop state model
    """
    def create_state_model(self, partition_name):
        """
        Create a MockStateModel

        Args:
            partition_name: The partition

        Returns:
            MockStateModel
        """
        return MockStateModel()

class TestExecutor(unittest.TestCase):
    """
    These test methods ensure proper parsing/handling of messages.
    """
    def setUp(self):
        factories = {'OnlineOffline': MockStateModelFactory()}
        self._p = mockparticipant.MockParticipant(
            'mockcluster', 'localhost', 1234, 'localhost:2181')
        self._p.connect()
        self.executor = helixexec.HelixExecutor(factories, self._p)

    def test_session_id_mismatch(self):
        """
        Test that the executor removes messages with incorrect session ID
        """
        message = znode.get_empty_znode('MY_MESSAGE_ID')
        message['simpleFields']['MSG_TYPE'] = 'STATE_TRANSITION'
        message['simpleFields']['TGT_SESSION_ID'] = 'wrong'
        accessor = self._p.get_accessor()
        keybuilder = accessor.get_key_builder()
        participant_id = self._p.get_participant_id()
        message_id = message['id']
        message_key = keybuilder.message(participant_id, message_id)
        accessor.create(message_key, message)
        self.executor.on_message([message])
        self.assertFalse(accessor.exists(message_key))


text:
extern crate log;
extern crate rand;

pub type CustomFloat = f64;
mod custom_float {
  pub use std::f64::*;
}

#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Time(pub CustomFloat);

pub use bounds::Bounds;
pub use float::FloatOps;
pub use vector::Vector;
pub use particle::{Particle};
pub use bounded_rand::BoundedRand;
pub use cartesian_iter::{Combination2, Combination2Iter};
pub use space::{Collision, Space};
pub use space_vec::SpaceVec;
pub use space_box::SpaceBox;
pub use spacetime::SpaceTime;

mod bounds;
mod float;
mod vector;
mod particle;
mod bounded_rand;
mod cartesian_iter;
mod space;
mod space_box;
mod space_vec;
mod spacetime;


text:
from .proxy_resource import ProxyResource

class LogFile(ProxyResource):
    """Represents a log file.

    Variables are only populated by the server, and will be ignored when
    sending a request.

    :ivar id: Resource ID
    :vartype id: str
    :ivar name: Resource name.
    :vartype name: str
    :ivar type: Resource type.
    :vartype type: str
    :param size_in_kb: Size of the log file.
    :type size_in_kb: long
    :ivar created_time: Creation timestamp of the log file.
    :vartype created_time: datetime
    :ivar last_modified_time: Last modified timestamp of the log file.
    :vartype last_modified_time: datetime
    :param log_file_type: Type of the log file.
    :type log_file_type: str
    :param url: The url to download the log file from.
    :type url: str
    """

    _validation = {
        'id': {'readonly': True},
        'name': {'readonly': True},
        'type': {'readonly': True},
        'created_time': {'readonly': True},
        'last_modified_time': {'readonly': True},
    }

    _attribute_map = {
        'id': {'key': 'id', 'type': 'str'},
        'name': {'key': 'name', 'type': 'str'},
        'type': {'key': 'type', 'type': 'str'},
        'size_in_kb': {'key': 'properties.sizeInKB', 'type': 'long'},
        'created_time': {'key': 'properties.createdTime', 'type': 'iso-8601'},
        'last_modified_time': {'key': 'properties.lastModifiedTime', 'type': 'iso-8601'},
        'log_file_type': {'key': 'properties.type', 'type': 'str'},
        'url': {'key': 'properties.url', 'type': 'str'},
    }

    def __init__(self, *, size_in_kb: int=None, log_file_type: str=None, url: str=None, **kwargs) -> None:
        super(LogFile, self).__init__(, **kwargs)
        self.size_in_kb = size_in_kb
        self.created_time = None
        self.last_modified_time = None
        self.log_file_type = log_file_type
        self.url = url


text:
package com.xianyi.utils;

import android.annotation.TargetApi;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Environment;

import java.io.File;
import java.io.IOException;

public class AudioRecorder {
    private static int SAMPLE_RATE_IN_HZ = 8000;

    final MediaRecorder recorder = new MediaRecorder();
    final String path;

    public AudioRecorder(String path) {
        this.path = sanitizePath(path);
    }

    private String sanitizePath(String path) {
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        if (!path.contains(".")) {
            path += ".amr";
        }
        return Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/xianyi" + System.currentTimeMillis()+path;
    }

    @TargetApi(Build.VERSION_CODES.FROYO)
    public void start() throws IOException {
        String state = Environment.getExternalStorageState();
        if (!state.equals(Environment.MEDIA_MOUNTED)) {
            throw new IOException(
                    "SD Card is not mounted,It is  " + state + ".");
        }
        File directory = new File(path).getParentFile();
        if (!directory.exists() && !directory.mkdirs()) {
            throw new IOException(
                    "Path to file could not be created");
        }
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        recorder.setAudioSamplingRate(SAMPLE_RATE_IN_HZ);
        recorder.setOutputFile(path);
        recorder.prepare();
        recorder.start();
    }

    public void stop() throws IOException {
        recorder.stop();
        recorder.release();
    }

    public int getAmplitude() {
        if (recorder != null) {
            return (recorder.getMaxAmplitude());
        } else
            return 0;
    }

    public String getPath() {
        return path;
    }
}


text:
'''
==================
RBF SVM parameters
==================

This example illustrates the effect of the parameters ``gamma`` and ``C`` of
the Radial Basis Function (RBF) kernel SVM.

Intuitively, the ``gamma`` parameter defines how far the influence of a single
training example reaches, with low values meaning 'far' and high values meaning
'close'. The ``gamma`` parameters can be seen as the inverse of the radius of
influence of samples selected by the model as support vectors.

The ``C`` parameter trades off misclassification of training examples against
simplicity of the decision surface. A low ``C`` makes the decision surface
smooth, while a high ``C`` aims at classifying all training examples correctly
by giving the model freedom to select more samples as support vectors.

The first plot is a visualization of the decision function for a variety of
parameter values on a simplified classification problem involving only 2 input
features and 2 possible target classes (binary classification). Note that this
kind of plot is not possible to do for problems with more features or target
classes.

The second plot is a heatmap of the classifier's cross-validation accuracy as a
function of ``C`` and ``gamma``. For this example we explore a relatively large
grid for illustration purposes. In practice, a logarithmic grid from
:math:`10^{-3}` to :math:`10^3` is usually sufficient. If the best parameters
lie on the boundaries of the grid, it can be extended in that direction in a
subsequent search.

Note that the heat map plot has a special colorbar with a midpoint value close
to the score values of the best performing models so as to make it easy to tell
them appart in the blink of an eye.

The behavior of the model is very sensitive to the ``gamma`` parameter. If
``gamma`` is too large, the radius of the area of influence of the support
vectors only includes the support vector itself and no amount of
regularization with ``C`` will be able to prevent overfitting.

When ``gamma`` is very small, the model is too constrained and cannot capture
the complexity or "shape" of the data. The region of influence of any selected
support vector would include the whole training set. The resulting model will
behave similarly to a linear model with a set of hyperplanes that separate the
centers of high density of any pair of two classes.

For intermediate values, we can see on the second plot that good models can
be found on a diagonal of ``C`` and ``gamma``. Smooth models (lower ``gamma``
values) can be made more complex by selecting a larger number of support
vectors (larger ``C`` values) hence the diagonal of good performing models.

Finally one can also observe that for some intermediate values of ``gamma`` we
get equally performing models when ``C`` becomes very large: it is not
necessary to regularize by limiting the number of support vectors. The radius of
the RBF kernel alone acts as a good structural regularizer. In practice though
it might still be interesting to limit the number of support vectors with a
lower value of ``C`` so as to favor models that use less memory and that are
faster to predict.

We should also note that small differences in scores results from the random
splits of the cross-validation procedure. Those spurious variations can be
smoothed out by increasing the number of CV iterations ``n_iter`` at the
expense of compute time. Increasing the value number of ``C_range`` and
``gamma_range`` steps will increase the resolution of the hyper-parameter heat
map.

'''
# print(__doc__)

import numpy as np
import matplotlib.pyplot as plt
import time
from matplotlib.colors import Normalize

from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_iris
from sklearn.cross_validation import StratifiedShuffleSplit
from sklearn.cross_validation import check_cv
from sklearn.grid_search import GridSearchCV
from sklearn.decomposition import RandomizedPCA

# Utility function to move the midpoint of a colormap to be around
# the values of interest.

class MidpointNormalize(Normalize):

    def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
        self.midpoint = midpoint
        Normalize.__init__(self, vmin, vmax, clip)

    def __call__(self, value, clip=None):
        x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
        return np.ma.masked_array(np.interp(value, x, y))

##############################################################################
# Constants
PCA_COMPONENTS = 150
GRID_SIZE = 13
start = time.time()

# Load the datset
import input_data_svm
datasets = input_data_svm.read_data_sets()

X = np.vstack((datasets.train_set.inputs(), datasets.validation_set.inputs()))
y = np.hstack((datasets.train_set.targets(), datasets.validation_set.targets()))

# X = datasets.train_set.inputs()
# y = datasets.train_set.targets()

X = X[:]
y = y[:]

# Reduce the dimensionality of the dataset
print("Applying PCA to reduce dimensions")
pca = RandomizedPCA(n_components=PCA_COMPONENTS, whiten=True).fit(X)
# eigenfaces = pca.componenets_reshape((PCA_COMPONENTS, h, w))
X = pca.transform(X)
print("Finished PCA preprocessing")

# Normalize the data
scaler = StandardScaler()
X = scaler.fit_transform(X)

##############################################################################
# Train classifiers
#
# For an initial search, a logarithmic grid with basis
# 10 is often helpful. Using a basis of 2, a finer
# tuning can be achieved but at a much higher cost.

print('Start training the model')
C_range = np.logspace(-2, 10, GRID_SIZE)
gamma_range = np.logspace(-9, 3, GRID_SIZE)
param_grid = dict(gamma=gamma_range, C=C_range)
cv = StratifiedShuffleSplit(y, n_iter=5, test_size=0.1, random_state=2015)
grid = GridSearchCV(SVC(), param_grid=param_grid, cv=cv)
grid.fit(X, y)

print("The best parameters are %s with a score of %0.2f"
      % (grid.best_params_, grid.best_score_))
print("This took {} minutes to run".format((time.time() - start)/60))

# plot the scores of the grid
# grid_scores_ contains parameter settings and scores
# We extract just the scores
scores = [x[1] for x in grid.grid_scores_]
scores = np.array(scores).reshape(len(C_range), len(gamma_range))

# Draw heatmap of the validation accuracy as a function of gamma and C
#
# The score are encoded as colors with the hot colormap which varies from dark
# red to bright yellow. As the most interesting scores are all located in the
# 0.92 to 0.97 range we use a custom normalizer to set the mid-point to 0.92 so
# as to make it easier to visualize the small variations of score values in the
# interesting range while not brutally collapsing all the low score values to
# the same color.

plt.figure(figsize=(8, 6))
plt.subplots_adjust(left=.2, right=0.95, bottom=0.15, top=0.95)
plt.imshow(scores, interpolation='nearest', cmap=plt.cm.hot,
           norm=MidpointNormalize(vmin=0.2, midpoint=0.92))
plt.xlabel('gamma')
plt.ylabel('C')
plt.colorbar()
plt.xticks(np.arange(len(gamma_range)), gamma_range, rotation=45)
plt.yticks(np.arange(len(C_range)), C_range)
plt.title('Validation accuracy')
plt.show()


text:
using System;
using System.ComponentModel;
using System.Windows.Forms;
using DotSpatial.Data;

namespace DotSpatial.Symbology.Forms
{
    /// <summary>
    /// CollectionPropertyGrid
    /// </summary>
    public class CollectionPropertyGrid : Form
    {
        #region Events

        /// <summary>
        /// Occurs whenever the apply changes button is clicked, or else when the ok button is clicked.
        /// </summary>
        public event EventHandler ChangesApplied;

        /// <summary>
        /// Occurs whenever the add item is clicked.  This is because the Collection Property Grid
        /// doesn't necessarilly know how to create a default item.  (An alternative would be
        /// to send in a factory, but I think this will work just as well.)
        /// </summary>
        public event EventHandler AddItemClicked;

        #endregion

        private CollectionControl ccItems;
        private DialogButtons dialogButtons1;
        private Panel panel1;
        private PropertyGrid propertyGrid1;
        private SplitContainer splitContainer1;

        #region Private Variables

        /// <summary>
        /// Required designer variable.
        /// </summary>
        private IContainer components = null;

        #endregion

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(CollectionPropertyGrid));
            this.splitContainer1 = new System.Windows.Forms.SplitContainer();
            this.ccItems = new DotSpatial.Symbology.Forms.CollectionControl();
            this.propertyGrid1 = new System.Windows.Forms.PropertyGrid();
            this.panel1 = new System.Windows.Forms.Panel();
            this.dialogButtons1 = new DotSpatial.Symbology.Forms.DialogButtons();
            ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
            this.splitContainer1.Panel1.SuspendLayout();
            this.splitContainer1.Panel2.SuspendLayout();
            this.splitContainer1.SuspendLayout();
            this.panel1.SuspendLayout();
            this.SuspendLayout();
            //
            // splitContainer1
            //
            resources.ApplyResources(this.splitContainer1, "splitContainer1");
            this.splitContainer1.Name = "splitContainer1";
            //
            // splitContainer1.Panel1
            //
            resources.ApplyResources(this.splitContainer1.Panel1, "splitContainer1.Panel1");
            this.splitContainer1.Panel1.Controls.Add(this.ccItems);
            //
            // splitContainer1.Panel2
            //
            resources.ApplyResources(this.splitContainer1.Panel2, "splitContainer1.Panel2");
            this.splitContainer1.Panel2.Controls.Add(this.propertyGrid1);
            //
            // ccItems
            //
            resources.ApplyResources(this.ccItems, "ccItems");
            this.ccItems.Name = "ccItems";
            this.ccItems.SelectedName = null;
            this.ccItems.SelectedObject = null;
            //
            // propertyGrid1
            //
            resources.ApplyResources(this.propertyGrid1, "propertyGrid1");
            this.propertyGrid1.Name = "propertyGrid1";
            //
            // panel1
            //
            resources.ApplyResources(this.panel1, "panel1");
            this.panel1.Controls.Add(this.dialogButtons1);
            this.panel1.Name = "panel1";
            //
            // dialogButtons1
            //
            resources.ApplyResources(this.dialogButtons1, "dialogButtons1");
            this.dialogButtons1.Name = "dialogButtons1";
            //
            // CollectionPropertyGrid
            //
            resources.ApplyResources(this, "$this");
            this.AllowDrop = true;
            this.Controls.Add(this.splitContainer1);
            this.Controls.Add(this.panel1);
            this.Name = "CollectionPropertyGrid";
            this.ShowIcon = false;
            this.ShowInTaskbar = false;
            this.splitContainer1.Panel1.ResumeLayout(false);
            this.splitContainer1.Panel2.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
            this.splitContainer1.ResumeLayout(false);
            this.panel1.ResumeLayout(false);
            this.ResumeLayout(false);
        }

        #endregion

        #region Constructors

        /// <summary>
        /// Creates a new instance of CollectionPropertyGrid
        /// </summary>
        public CollectionPropertyGrid()
        {
            InitializeComponent();
            Configure();
        }

        /// <summary>
        /// Creates a new instance of CollectionPropertyGrid
        /// </summary>
        /// <param name="list">The INamedList to display</param>
        public CollectionPropertyGrid(INamedList list)
        {
            InitializeComponent();
            NamedList = list;
            ccItems.AddClicked += ccItems_AddClicked;
            ccItems.SelectedItemChanged += ccItems_SelectedItemChanged;
            ccItems_SelectedItemChanged(ccItems, EventArgs.Empty);
            ccItems.RemoveClicked += ccItems_RemoveClicked;
            Configure();
        }

        private void Configure()
        {
            dialogButtons1.OkClicked += btnOk_Click;
            dialogButtons1.CancelClicked += btnCancel_Click;
            dialogButtons1.ApplyClicked += btnApply_Click;
        }

        private void ccItems_RemoveClicked(object sender, EventArgs e)
        {
            propertyGrid1.SelectedObject = ccItems.SelectedObject;
        }

        #endregion

        #region Methods

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the tool that connects each item with a string name.
        /// </summary>
        public INamedList NamedList
        {
            get
            {
                if (ccItems != null) return ccItems.ItemNames;
                return null;
            }
            set
            {
                ccItems.ItemNames = value;
            }
        }

        #endregion

        #region Events

        #endregion

        #region Event Handlers

        private void ccItems_AddClicked(object sender, EventArgs e)
        {
            OnAddClicked();
        }

        private void ccItems_SelectedItemChanged(object sender, EventArgs e)
        {
            propertyGrid1.SelectedObject = ccItems.SelectedObject;
        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            OnApplyChanges();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            OnApplyChanges();
            Close();
        }

        #endregion

        #region Protected Methods

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

        /// <summary>
        /// Occurs when the add button is clicked
        /// </summary>
        protected virtual void OnAddClicked()
        {
            if (AddItemClicked != null) AddItemClicked(this, EventArgs.Empty);
        }

        /// <summary>
        /// Fires the ChangesApplied event
        /// </summary>
        protected virtual void OnApplyChanges()
        {
            if (ChangesApplied != null) ChangesApplied(this, EventArgs.Empty);
        }

        #endregion
    }
}


text:
title: jQuery Ajax requests are 'html' not 'js'
author: Justin Ball
layout: post
permalink: "/2010/08/09/jquery-ajax-requests-are-html-not-js/"
tags:
  - "jQuery"
  - "ajax"
  - "jQuery"
  - "Ruby On Rails"
date: '2010-08-09T06:00:00Z'
templateKey: blog-post
path: "/jquery-ajax-requests-are-html-not-js"
description: ''
---

I like jQuery. I use it in all my Rails projects these days. One thing I've struggled with for the longest time is that for some reason all my jQuery ajax requests come through as html not as js.

I thought adding something like this to application.js would fix the problem:

// In application.js
jQuery.ajaxSetup({
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})

That won't save you. This change to Rails prevents the Accept header from being used:
http://github.com/rails/rails/commit/2f4aaed7b3feb3be787a316fab3144c06bb21a27

The trick to fixing this problem comes from a comment in that commit:

# Returns true if the request's "X-Requested-With" header contains
# "XMLHttpRequest". (The Prototype Javascript library sends this header with
# every Ajax request.)

jQuery doesn't send that parameter with each request.  I've written before about modifying the request.
http://www.justinball.comjquery-ajax-get-in-firefox-post-in-internet-explorer

Taking the code from that post I just add a bit more information. Specifically include this line:

  request.setRequestHeader("X-Requested-With", "XMLHttpRequest");

Your setup ends up looking something like this.  Drop this code into application.js and the ajax requests made via JQuery should start showing up as javascript format.

  jQuery(document).ajaxSend(function(event, request, settings) {
    request.setRequestHeader("Accept", "text/javascript");
  	request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    if (settings.type.toUpperCase() == 'GET' || typeof(AUTH_TOKEN) == "undefined") return;
    // settings.data is a serialized string like "foo=bar&baz=boink" (or null)
    settings.data = settings.data || "";
   	if (typeof(AUTH_TOKEN) != "undefined")
    	settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
  });

I'm using the jquery.form plugin so my code ends up looking like this:

function apply_ajax_forms() {
  jQuery('form.ajax').ajaxForm({
    dataType: 'script',
    beforeSend: add_headers
  });
	jQuery('form.ajax').append('<input type="hidden" name="format" value="js" />');
}

Passing the format as a hidden field to Rails ensures that the proper format handler is called.  It isn't the cleanest, but it works reliably and to make a normal form into an ajax form all I need to do is add 'ajax' as a css class.


text:
dojo.provide("dojox.grid._Builder");

dojo.require("dojox.grid.util");
dojo.require("dojo.dnd.Moveable");

(function(){
	var dg = dojox.grid;

	var getTdIndex = function(td){
		return td.cellIndex >=0 ? td.cellIndex : dojo.indexOf(td.parentNode.cells, td);
	};

	var getTrIndex = function(tr){
		return tr.rowIndex >=0 ? tr.rowIndex : dojo.indexOf(tr.parentNode.childNodes, tr);
	};

	var getTr = function(rowOwner, index){
		return rowOwner && ((rowOwner.rows||0)[index] || rowOwner.childNodes[index]);
	};

	var findTable = function(node){
		for(var n=node; n && n.tagName!='TABLE'; n=n.parentNode);
		return n;
	};

	var ascendDom = function(inNode, inWhile){
		for(var n=inNode; n && inWhile(n); n=n.parentNode);
		return n;
	};

	var makeNotTagName = function(inTagName){
		var name = inTagName.toUpperCase();
		return function(node){ return node.tagName != name; };
	};

	var rowIndexTag = dojox.grid.util.rowIndexTag;
	var gridViewTag = dojox.grid.util.gridViewTag;

	// base class for generating markup for the views
	dg._Builder = dojo.extend(function(view){
		if(view){
			this.view = view;
			this.grid = view.grid;
		}
	},{
		view: null,
		// boilerplate HTML
		_table: '<table class="dojoxGridRowTable" border="0" cellspacing="0" cellpadding="0" role="'+(dojo.isFF<3 ? "wairole:" : "")+'presentation"',

		// Returns the table variable as an array - and with the view width, if specified
		getTableArray: function(){
			var html = [this._table];
			if(this.view.viewWidth){
				html.push([' style="width:', this.view.viewWidth, ';"'].join(''));
			}
			html.push('>');
			return html;
		},

		// generate starting tags for a cell
		generateCellMarkup: function(inCell, inMoreStyles, inMoreClasses, isHeader){
			var result = [], html;
			var waiPrefix = dojo.isFF<3 ? "wairole:" : "";
			if(isHeader){
				var sortInfo = inCell.index != inCell.grid.getSortIndex() ? "" : inCell.grid.sortInfo > 0 ? 'aria-sort="ascending"' : 'aria-sort="descending"';
				html = ['<th tabIndex="-1" role="', waiPrefix, 'columnheader"', sortInfo];
			}else{
				html = [' td opener, style
			result.push(html.join(''));
			// SLOT: result[1] => td classes
			result.push('');
			html = ['" idx="', inCell.index, '" style="'];
			if(inMoreStyles && inMoreStyles[inMoreStyles.length-1] != ';'){
				inMoreStyles += ';';
			}
			html.push(inCell.styles, inMoreStyles||'', inCell.hidden?'display:none;':'');
			inCell.unitWidth && html.push('width:', inCell.unitWidth, ';');
			// result[2] => markup
			result.push(html.join(''));
			// SLOT: result[3] => td style
			result.push('');
			html = [ '"' ];
			inCell.attrs && html.push(" ", inCell.attrs);
			html.push('>');
			// result[4] => td postfix
			result.push(html.join(''));
			// SLOT: result[5] => content
			result.push('');
			// result[6] => td closes
			result.push(isHeader?'	':'	');
			return result; // Array
		},

		// cell finding
		isCellNode: function(inNode){
			return Boolean(inNode && inNode!=dojo.doc && dojo.attr(inNode, "idx"));
		},

		getCellNodeIndex: function(inCellNode){
			return inCellNode ? Number(dojo.attr(inCellNode, "idx")) : -1;
		},

		getCellNode: function(inRowNode, inCellIndex){
			for(var i=0, row; row=getTr(inRowNode.firstChild, i); i++){
				for(var j=0, cell; cell=row.cells[j]; j++){
					if(this.getCellNodeIndex(cell) == inCellIndex){
						return cell;
					}
				}
			}
		},

		findCellTarget: function(inSourceNode, inTopNode){
			var n = inSourceNode;
			while(n && (!this.isCellNode(n) || (n.offsetParent && gridViewTag in n.offsetParent.parentNode && n.offsetParent.parentNode[gridViewTag] != this.view.id)) && (n!=inTopNode)){
				n = n.parentNode;
			}
			return n!=inTopNode ? n : null
		},

		// event decoration
		baseDecorateEvent: function(e){
			e.dispatch = 'do' + e.type;
			e.grid = this.grid;
			e.sourceView = this.view;
			e.cellNode = this.findCellTarget(e.target, e.rowNode);
			e.cellIndex = this.getCellNodeIndex(e.cellNode);
			e.cell = (e.cellIndex >= 0 ? this.grid.getCell(e.cellIndex) : null);
		},

		// event dispatch
		findTarget: function(inSource, inTag){
			var n = inSource;
			while(n && (n!=this.domNode) && (!(inTag in n) || (gridViewTag in n && n[gridViewTag] != this.view.id))){
				n = n.parentNode;
			}
			return (n != this.domNode) ? n : null;
		},

		findRowTarget: function(inSource){
			return this.findTarget(inSource, rowIndexTag);
		},

		isIntraNodeEvent: function(e){
			try{
				return (e.cellNode && e.relatedTarget && dojo.isDescendant(e.relatedTarget, e.cellNode));
			}catch(x){
				// e.relatedTarget has permission problem in FF if it's an input: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
				return false;
			}
		},

		isIntraRowEvent: function(e){
			try{
				var row = e.relatedTarget && this.findRowTarget(e.relatedTarget);
				return !row && (e.rowIndex==-1) || row && (e.rowIndex==row.gridRowIndex);
			}catch(x){
				// e.relatedTarget on INPUT has permission problem in FF: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
				return false;
			}
		},

		dispatchEvent: function(e){
			if(e.dispatch in this){
				return this[e.dispatch](e);
			}
		},

		// dispatched event handlers
		domouseover: function(e){
			if(e.cellNode && (e.cellNode!=this.lastOverCellNode)){
				this.lastOverCellNode = e.cellNode;
				this.grid.onMouseOver(e);
			}
			this.grid.onMouseOverRow(e);
		},

		domouseout: function(e){
			if(e.cellNode && (e.cellNode==this.lastOverCellNode) && !this.isIntraNodeEvent(e, this.lastOverCellNode)){
				this.lastOverCellNode = null;
				this.grid.onMouseOut(e);
				if(!this.isIntraRowEvent(e)){
					this.grid.onMouseOutRow(e);
				}
			}
		},

		domousedown: function(e){
			if (e.cellNode)
				this.grid.onMouseDown(e);
			this.grid.onMouseDownRow(e)
		}
	});

	// Produces html for grid data content. Owned by grid and used internally
	// for rendering data. Override to implement custom rendering.
	dg._ContentBuilder = dojo.extend(function(view){
		dg._Builder.call(this, view);
	},dg._Builder.prototype,{
		update: function(){
			this.prepareHtml();
		},

		// cache html for rendering data rows
		prepareHtml: function(){
			var defaultGet=this.grid.get, cells=this.view.structure.cells;
			for(var j=0, row; (row=cells[j]); j++){
				for(var i=0, cell; (cell=row[i]); i++){
					cell.get = cell.get || (cell.value == undefined) && defaultGet;
					cell.markup = this.generateCellMarkup(cell, cell.cellStyles, cell.cellClasses, false);
				}
			}
		},

		// time critical: generate html using cache and data source
		generateHtml: function(inDataIndex, inRowIndex){
			var
				html = this.getTableArray(),
				v = this.view,
				cells = v.structure.cells,
				item = this.grid.getItem(inRowIndex);

			dojox.grid.util.fire(this.view, "onBeforeRow", [inRowIndex, cells]);
			for(var j=0, row; (row=cells[j]); j++){
				if(row.hidden || row.header){
					continue;
				}
				html.push(!row.invisible ? '
' : '
');
				for(var i=0, cell, m, cc, cs; (cell=row[i]); i++){
					m = cell.markup, cc = cell.customClasses = [], cs = cell.customStyles = [];
					// content (format can fill in cc and cs as side-effects)
					m[5] = cell.format(inRowIndex, item);
					// classes
					m[1] = cc.join(' ');
					// styles
					m[3] = cs.join(';');
					// in-place concat
					html.push.apply(html, m);
				}
				html.push('
');
			}
			html.push('
');
			return html.join(''); // String
		},

		decorateEvent: function(e){
			e.rowNode = this.findRowTarget(e.target);
			if(!e.rowNode){return false};
			e.rowIndex = e.rowNode[rowIndexTag];
			this.baseDecorateEvent(e);
			e.cell = this.grid.getCell(e.cellIndex);
			return true; // Boolean
		}
	});

	// Produces html for grid header content. Owned by grid and used internally
	// for rendering data. Override to implement custom rendering.
	dg._HeaderBuilder = dojo.extend(function(view){
		this.moveable = null;
		dg._Builder.call(this, view);
	},dg._Builder.prototype,{
		_skipBogusClicks: false,
		overResizeWidth: 4,
		minColWidth: 1,

		update: function(){
			if(this.tableMap){
				this.tableMap.mapRows(this.view.structure.cells);
			}else{
				this.tableMap = new dg._TableMap(this.view.structure.cells);
			}
		},

		generateHtml: function(inGetValue, inValue){
			var html = this.getTableArray(), cells = this.view.structure.cells;

			dojox.grid.util.fire(this.view, "onBeforeRow", [-1, cells]);
			for(var j=0, row; (row=cells[j]); j++){
				if(row.hidden){
					continue;
				}
				html.push(!row.invisible ? '
' : '
');
				for(var i=0, cell, markup; (cell=row[i]); i++){
					cell.customClasses = [];
					cell.customStyles = [];
					if(this.view.simpleStructure){
						if(cell.headerClasses){
							if(cell.headerClasses.indexOf('dojoDndItem') == -1){
								cell.headerClasses += ' dojoDndItem';
							}
						}else{
							cell.headerClasses = 'dojoDndItem';
						}
						if(cell.attrs){
							if(cell.attrs.indexOf("dndType='gridColumn_") == -1){
								cell.attrs += " dndType='gridColumn_" + this.grid.id + "'";
							}
						}else{
							cell.attrs = "dndType='gridColumn_" + this.grid.id + "'";
						}
					}
					markup = this.generateCellMarkup(cell, cell.headerStyles, cell.headerClasses, true);
					// content
					markup[5] = (inValue != undefined ? inValue : inGetValue(cell));
					// styles
					markup[3] = cell.customStyles.join(';');
					// classes
					markup[1] = cell.customClasses.join(' '); //(cell.customClasses ? ' ' + cell.customClasses : '');
					html.push(markup.join(''));
				}
				html.push('
');
			}
			html.push('
');
			return html.join('');
		},

		// event helpers
		getCellX: function(e){
			var x = e.layerX;
			if(dojo.isMoz){
				var n = ascendDom(e.target, makeNotTagName("th"));
				x -= (n && n.offsetLeft) || 0;
				var t = e.sourceView.getScrollbarWidth();
				if(!dojo._isBodyLtr() && e.sourceView.headerNode.scrollLeft < t)
					x -= t;
				//x -= getProp(ascendDom(e.target, mkNotTagName("td")), "offsetLeft") || 0;
			}
			var n = ascendDom(e.target, function(){
				if(!n || n == e.cellNode){
					return false;
				}
				// Mozilla 1.8 (FF 1.5) has a bug that makes offsetLeft = -parent border width
				// when parent has border, overflow: hidden, and is positioned
				// handle this problem here ... not a general solution!
				x += (n.offsetLeft < 0 ? 0 : n.offsetLeft);
				return true;
			});
			return x;
		},

		// event decoration
		decorateEvent: function(e){
			this.baseDecorateEvent(e);
			e.rowIndex = -1;
			e.cellX = this.getCellX(e);
			return true;
		},

		// event handlers
		// resizing
		prepareResize: function(e, mod){
			do{
				var i = getTdIndex(e.cellNode);
				e.cellNode = (i ? e.cellNode.parentNode.cells[i+mod] : null);
				e.cellIndex = (e.cellNode ? this.getCellNodeIndex(e.cellNode) : -1);
			}while(e.cellNode && e.cellNode.style.display == "none");
			return Boolean(e.cellNode);
		},

		canResize: function(e){
			if(!e.cellNode || e.cellNode.colSpan > 1){
				return false;
			}
			var cell = this.grid.getCell(e.cellIndex);
			return !cell.noresize && cell.canResize();
		},

		overLeftResizeArea: function(e){
			//Bugfix for crazy IE problem (#8807).  IE returns position information for the icon and text arrow divs
			//as if they were still on the left instead of returning the position they were 'float: right' to.
			//So, the resize check ends up checking the wrong adjacent cell.  This checks to see if the hover was over
			//the image or text nodes, then just ignored them/treat them not in scale range.
			if(dojo.isIE){
				var tN = e.target;
				if(dojo.hasClass(tN, "dojoxGridArrowButtonNode") ||
					dojo.hasClass(tN, "dojoxGridArrowButtonChar")){
					return false;
				}
			}

			if(dojo._isBodyLtr()){
				return (e.cellIndex>0) && (e.cellX < this.overResizeWidth) && this.prepareResize(e, -1);
			}
			var t = e.cellNode && (e.cellX < this.overResizeWidth);
			return t;
		},

		overRightResizeArea: function(e){
			//Bugfix for crazy IE problem (#8807).  IE returns position information for the icon and text arrow divs
			//as if they were still on the left instead of returning the position they were 'float: right' to.
			//So, the resize check ends up checking the wrong adjacent cell.  This checks to see if the hover was over
			//the image or text nodes, then just ignored them/treat them not in scale range.
			if(dojo.isIE){
				var tN = e.target;
				if(dojo.hasClass(tN, "dojoxGridArrowButtonNode") ||
					dojo.hasClass(tN, "dojoxGridArrowButtonChar")){
					return false;
				}
			}

			if(dojo._isBodyLtr()){
				return e.cellNode && (e.cellX >= e.cellNode.offsetWidth - this.overResizeWidth);
			}
			return (e.cellIndex>0) && (e.cellX >= e.cellNode.offsetWidth - this.overResizeWidth) && this.prepareResize(e, -1);
		},

		domousemove: function(e){
			//console.log(e.cellIndex, e.cellX, e.cellNode.offsetWidth);
			if(!this.moveable){
				var c = (this.overRightResizeArea(e) ? 'e-resize' : (this.overLeftResizeArea(e) ? 'w-resize' : ''));
				if(c && !this.canResize(e)){
					c = 'not-allowed';
				}
				if(dojo.isIE){
					var t = e.sourceView.headerNode.scrollLeft;
					e.sourceView.headerNode.style.cursor = c || ''; //'default';
					e.sourceView.headerNode.scrollLeft = t;
				}else{
					e.sourceView.headerNode.style.cursor = c || ''; //'default';
				}
				if(c){
					dojo.stopEvent(e);
				}
			}
		},

		domousedown: function(e){
			if(!this.moveable){
				if((this.overRightResizeArea(e) || this.overLeftResizeArea(e)) && this.canResize(e)){
					this.beginColumnResize(e);
				}else{
					this.grid.onMouseDown(e);
					this.grid.onMouseOverRow(e);
				}
				//else{
				//	this.beginMoveColumn(e);
				//}
			}
		},

		doclick: function(e) {
			if(this._skipBogusClicks){
				dojo.stopEvent(e);
				return true;
			}
		},

		// column resizing
		beginColumnResize: function(e){
			this.moverDiv = document.createElement("div");
			dojo.style(this.moverDiv,{position: "absolute", left:0}); // to make DnD work with dir=rtl
			dojo.body().appendChild(this.moverDiv);
			var m = this.moveable = new dojo.dnd.Moveable(this.moverDiv);

			var spanners = [], nodes = this.tableMap.findOverlappingNodes(e.cellNode);
			for(var i=0, cell; (cell=nodes[i]); i++){
				spanners.push({ node: cell, index: this.getCellNodeIndex(cell), width: cell.offsetWidth });
				//console.log("spanner: " + this.getCellNodeIndex(cell));
			}

			var view = e.sourceView;
			var adj = dojo._isBodyLtr() ? 1 : -1;
			var views = e.grid.views.views;
			var followers = [];
			for(var i=view.idx+adj, cView; (cView=views[i]); i=i+adj){
				followers.push({ node: cView.headerNode, left: window.parseInt(cView.headerNode.style.left) });
			}
			var table = view.headerContentNode.firstChild;
			var drag = {
				scrollLeft: e.sourceView.headerNode.scrollLeft,
				view: view,
				node: e.cellNode,
				index: e.cellIndex,
				w: dojo.contentBox(e.cellNode).w,
				vw: dojo.contentBox(view.headerNode).w,
				table: table,
				tw: dojo.contentBox(table).w,
				spanners: spanners,
				followers: followers
			};

			m.onMove = dojo.hitch(this, "doResizeColumn", drag);

			dojo.connect(m, "onMoveStop", dojo.hitch(this, function(){
				this.endResizeColumn(drag);
				if(drag.node.releaseCapture){
					drag.node.releaseCapture();
				}
				this.moveable.destroy();
				delete this.moveable;
				this.moveable = null;
			}));

			view.convertColPctToFixed();

			if(e.cellNode.setCapture){
				e.cellNode.setCapture();
			}
			m.onMouseDown(e);
		},

		doResizeColumn: function(inDrag, mover, leftTop){
			var isLtr = dojo._isBodyLtr();
			var deltaX = isLtr ? leftTop.l : -leftTop.l;
			var w = inDrag.w + deltaX;
			var vw = inDrag.vw + deltaX;
			var tw = inDrag.tw + deltaX;
			if(w >= this.minColWidth){
				for(var i=0, s, sw; (s=inDrag.spanners[i]); i++){
					sw = s.width + deltaX;
					s.node.style.width = sw + 'px';
					inDrag.view.setColWidth(s.index, sw);
					//console.log('setColWidth', '#' + s.index, sw + 'px');
				}
				for(var i=0, f, fl; (f=inDrag.followers[i]); i++){
					fl = f.left + deltaX;
					f.node.style.left = fl + 'px';
				}
				inDrag.node.style.width = w + 'px';
				inDrag.view.setColWidth(inDrag.index, w);
				inDrag.view.headerNode.style.width = vw + 'px';
				inDrag.view.setColumnsWidth(tw);
				if(!isLtr){
					inDrag.view.headerNode.scrollLeft = inDrag.scrollLeft + deltaX;
				}
			}
			if(inDrag.view.flexCells && !inDrag.view.testFlexCells()){
				var t = findTable(inDrag.node);
				t && (t.style.width = '');
			}
		},

		endResizeColumn: function(inDrag){
			dojo.destroy(this.moverDiv);
			delete this.moverDiv;
			this._skipBogusClicks = true;
			var conn = dojo.connect(inDrag.view, "update", this, function(){
				dojo.disconnect(conn);
				this._skipBogusClicks = false;
			});
			setTimeout(dojo.hitch(inDrag.view, "update"), 50);
		}
	});

	// Maps an html table into a structure parsable for information about cell row and col spanning.
	// Used by HeaderBuilder.
	dg._TableMap = dojo.extend(function(rows){
		this.mapRows(rows);
	},{
		map: null,

		mapRows: function(inRows){
			// summary: Map table topography

			//console.log('mapRows');
			// # of rows
			var rowCount = inRows.length;
			if(!rowCount){
				return;
			}
			// map which columns and rows fill which cells
			this.map = [];
			for(var j=0, row; (row=inRows[j]); j++){
				this.map[j] = [];
			}
			for(var j=0, row; (row=inRows[j]); j++){
				for(var i=0, x=0, cell, colSpan, rowSpan; (cell=row[i]); i++){
					while (this.map[j][x]){x++};
					this.map[j][x] = { c: i, r: j };
					rowSpan = cell.rowSpan || 1;
					colSpan = cell.colSpan || 1;
					for(var y=0; y<rowSpan; y++){
						for(var s=0; s<colSpan; s++){
							this.map[j+y][x+s] = this.map[j][x];
						}
					}
					x += colSpan;
				}
			}
			//this.dumMap();
		},

		dumpMap: function(){
			for(var j=0, row, h=''; (row=this.map[j]); j++,h=''){
				for(var i=0, cell; (cell=row[i]); i++){
					h += cell.r + ',' + cell.c + '   ';
				}
				//console.log(h);
			}
		},

		getMapCoords: function(inRow, inCol){
			// summary: Find node's map coords by it's structure coords
			for(var j=0, row; (row=this.map[j]); j++){
				for(var i=0, cell; (cell=row[i]); i++){
					if(cell.c==inCol && cell.r == inRow){
						return { j: j, i: i };
					}
					//else{console.log(inRow, inCol, ' : ', i, j, " : ", cell.r, cell.c); };
				}
			}
			return { j: -1, i: -1 };
		},

		getNode: function(inTable, inRow, inCol){
			// summary: Find a node in inNode's table with the given structure coords
			var row = inTable && inTable.rows[inRow];
			return row && row.cells[inCol];
		},

		_findOverlappingNodes: function(inTable, inRow, inCol){
			var nodes = [];
			var m = this.getMapCoords(inRow, inCol);
			//console.log("node j: %d, i: %d", m.j, m.i);
			var row = this.map[m.j];
			for(var j=0, row; (row=this.map[j]); j++){
				if(j == m.j){ continue; }
				var rw = row[m.i];
				//console.log("overlaps: r: %d, c: %d", rw.r, rw.c);
				var n = (rw?this.getNode(inTable, rw.r, rw.c):null);
				if(n){ nodes.push(n); }
			}
			//console.log(nodes);
			return nodes;
		},

		findOverlappingNodes: function(inNode){
			return this._findOverlappingNodes(findTable(inNode), getTrIndex(inNode.parentNode), getTdIndex(inNode));
		}
	});
})();


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class StoragePerformanceSummary extends DynamicData {
  public int interval;
  public int[] percentile;
  public double[] datastoreReadLatency;
  public double[] datastoreWriteLatency;
  public double[] datastoreVmLatency;
  public double[] datastoreReadIops;
  public double[] datastoreWriteIops;
  public int siocActivityDuration;

  public int getInterval() {
    return this.interval;
  }

  public int[] getPercentile() {
    return this.percentile;
  }

  public double[] getDatastoreReadLatency() {
    return this.datastoreReadLatency;
  }

  public double[] getDatastoreWriteLatency() {
    return this.datastoreWriteLatency;
  }

  public double[] getDatastoreVmLatency() {
    return this.datastoreVmLatency;
  }

  public double[] getDatastoreReadIops() {
    return this.datastoreReadIops;
  }

  public double[] getDatastoreWriteIops() {
    return this.datastoreWriteIops;
  }

  public int getSiocActivityDuration() {
    return this.siocActivityDuration;
  }

  public void setInterval(int interval) {
    this.interval=interval;
  }

  public void setPercentile(int[] percentile) {
    this.percentile=percentile;
  }

  public void setDatastoreReadLatency(double[] datastoreReadLatency) {
    this.datastoreReadLatency=datastoreReadLatency;
  }

  public void setDatastoreWriteLatency(double[] datastoreWriteLatency) {
    this.datastoreWriteLatency=datastoreWriteLatency;
  }

  public void setDatastoreVmLatency(double[] datastoreVmLatency) {
    this.datastoreVmLatency=datastoreVmLatency;
  }

  public void setDatastoreReadIops(double[] datastoreReadIops) {
    this.datastoreReadIops=datastoreReadIops;
  }

  public void setDatastoreWriteIops(double[] datastoreWriteIops) {
    this.datastoreWriteIops=datastoreWriteIops;
  }

  public void setSiocActivityDuration(int siocActivityDuration) {
    this.siocActivityDuration=siocActivityDuration;
  }
}


text:
Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # The test environment is used exclusively to run your application's
  # test suite. You never need to work with it otherwise. Remember that
  # your test database is "scratch space" for the test suite and is wiped
  # and recreated between test runs. Don't rely on the data there!
  config.cache_classes = true

  # Do not eager load code on boot. This avoids loading your whole application
  # just for the purpose of running a single test. If you are using a tool that
  # preloads Rails for running tests, you may have to set it to true.
  config.eager_load = false

  # Configure public file server for tests with Cache-Control for performance.
  config.public_file_server.enabled = true
  config.public_file_server.headers = {
    'Cache-Control' => "public, max-age=#{1.hour.seconds.to_i}"
  }

  # Show full error reports and disable caching.
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false

  # Raise exceptions instead of rendering exception templates.
  config.action_dispatch.show_exceptions = false

  # Disable request forgery protection in test environment.
  config.action_controller.allow_forgery_protection = false
  # config.action_mailer.perform_caching = false

  # Tell Action Mailer not to deliver emails to the real world.
  # The :test delivery method accumulates sent emails in the
  # ActionMailer::Base.deliveries array.
  # config.action_mailer.delivery_method = :test

  config.x.audit = ActiveSupport::Logger.new('/dev/null')
  config.x.audit.level = ActiveSupport::Logger::INFO

  config.log_level = config.keystorm['log_level'].to_sym
  config.logger = ActiveSupport::Logger.new('/dev/null')

  config.logstasher.enabled = true
  config.logstasher.suppress_app_log = false
  config.logstasher.source = 'keystorm'

  # Print deprecation notices to the stderr.
  config.active_support.deprecation = :stderr

  # Raises error for missing translations
  # config.action_view.raise_on_missing_translations = true
end


text:
package com.stefansavev.similaritysearch;

public class SimilarityIndexingEngines {

    public static SimilarityIndexingEngine fastTrees(int numTrees) {
        return new SimilarityIndexingEngine.FastTrees(numTrees);
    }

    public static SimilarityIndexingEngine bruteForce() {
        return new SimilarityIndexingEngine.BruteForce();
    }
}


text:
package org.supler

import org.json4s.JsonAST._
import org.scalatest.{FlatSpec, ShouldMatchers}
import Supler._
import org.json4s.native._

class ApplyTest extends FlatSpec with ShouldMatchers {
  "form" should "apply json values to the entity given" in {
    // given
    case class Person(f1: String, f2: Option[Int], f3: Boolean, f4: Option[String])

    val personForm = form[Person](f => List(
      f.field(_.f1),
      f.field(_.f2),
      f.field(_.f3),
      f.field(_.f4)
    ))

    val jsonInOrder = JObject(
      JField("f1", JString("John")),
      JField("f2", JInt(10)),
      JField("f3", JBool(value = true)),
      JField("f4", JString("Something"))
    )

    val jsonOutOfOrder = JObject(
      JField("f3", JBool(value = true)),
      JField("f2", JInt(10)),
      JField("f4", JString("")),
      JField("f1", JString("John"))
    )

    val jsonPartial = JObject(
      JField("f1", JString("John")),
      JField("f2", JInt(10))
    )

    val p = Person("Mary", None, f3 = false, Some("Nothing"))

    // when
    val p1 = personForm(p).applyJSONValues(jsonInOrder).obj
    val p2 = personForm(p).applyJSONValues(jsonOutOfOrder).obj
    val p3 = personForm(p).applyJSONValues(jsonPartial).obj

    // then
    p1 should be (Person("John", Some(10), f3 = true, Some("Something")))
    p2 should be (Person("John", Some(10), f3 = true, None))
    p3 should be (Person("John", Some(10), f3 = false, Some("Nothing")))
  }

  "form" should "apply null values to an optional and not-optional int fields" in {
    // given
    case class Data(f1: Int, f2: Option[Int])

    val dataForm = form[Data](f => List(
      f.field(_.f1),
      f.field(_.f2)
    ))

    val jsonBothNull = parseJson("""{"f1": null, "f2": null}""")
    val jsonOneNull = parseJson("""{"f1": 20, "f2": null}""")
    val jsonOneMissing = parseJson("""{"f1": 30}""")
    val jsonBothSet = parseJson("""{"f1": 40, "f2": 41}""")

    // when
    val d1 = dataForm(Data(10, Some(11))).applyJSONValues(jsonBothNull).obj
    val d2 = dataForm(Data(10, Some(11))).applyJSONValues(jsonOneNull).obj
    val d3 = dataForm(Data(10, Some(11))).applyJSONValues(jsonOneMissing).obj
    val d4 = dataForm(Data(10, Some(11))).applyJSONValues(jsonBothSet).obj

    // then
    d1 should be (Data(10, None))
    d2 should be (Data(20, None))
    d3 should be (Data(30, Some(11)))
    d4 should be (Data(40, Some(41)))
  }
}


text:
if loadlib ~= nil then
    local open_scse = loadlib("scse.dll", "luaopen_scse")
    open_scse()

    WARN(scse.version())

    # Open io and os libs
    scse.luaopen_io()
end


text:
  Saint-Gorgon est
       un village
       géographiquement positionné dans le département des Vosges en Lorraine. Elle comptait 375 habitants en 2008.

Le nombre d'habitations, à Saint-Gorgon, était réparti en 2011 en deux appartements et 149 maisons soit
 un marché plutôt équilibré.

Si vous pensez emmenager à Saint-Gorgon, vous pourrez facilement trouver une maison à vendre.

À coté de Saint-Gorgon sont positionnées géographiquement les villes de
Sainte-Hélène localisée à 3 km, 456 habitants,
Anglemont située à 6 km, 173 habitants,
Jeanménil située à 3 km, 1 058 habitants,
Housseras située à 4 km, 466 habitants,
Vomécourt localisée à 3 km, 266 habitants,
Fremifontaine localisée à 6 km, 375 habitants,
 entre autres. De plus, Saint-Gorgon est située à seulement 22 km de Épinal.

La ville offre quelques  aménagements, elle dispose, entre autres, de un terrain de sport.