text:
APestBase::APestBase()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

}

// Called when the game starts or when spawned
void APestBase::BeginPlay()
{
	Super::BeginPlay();

}

// Called every frame
void APestBase::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

}

FVector APestBase::GetNavigationDirection()
{
	FVector DirectVector = NavigationTarget - GetActorLocation();
	FVector Indication = DirectVector.GetUnsafeNormal();
	FVector Direction = Indication - FVector::DotProduct(NavigationNormal, Indication) * NavigationNormal;

	return Direction.GetUnsafeNormal();
}

float APestBase::GetNavigationDistance()
{
	return FVector::Dist(NavigationTarget, GetActorLocation());
}

float APestBase::GetNavigationRange(float minimum, float maximum)
{
	return FMath::Clamp((GetNavigationDistance() - minimum) / (maximum - minimum), 0.0f, 1.0f);
}

bool APestBase::GetWeightedAverage(TArray<AActor*> actors, float minimum, float maximum, FVector& average)
{
	average.Set(0.0f, 0.0f, 0.0f);

	float totalWeight = 0.0f;

	for(AActor* actor : actors) {
		float Distance = FVector::Dist(actor->GetActorLocation(), GetActorLocation());

		float weight = 1.0f - FMath::Clamp((Distance - minimum) / (maximum - minimum), 0.0f, 1.0f);

		average += actor->GetActorLocation() * weight;

		totalWeight += weight;
	}

	if(totalWeight > 0.0f) {
		average /= totalWeight;

		return true;
	}
	else {
		return false;
	}
}


text:
/*
w * GridLevelTransfer.h
 *
 *  Created on: Feb 29, 2012
 *      Author: Kristof Unterweger
 */

#ifndef PEANO_APPLICATIONS_PEANOCLAW_GRIDLEVELTRANSFER_H_
#define PEANO_APPLICATIONS_PEANOCLAW_GRIDLEVELTRANSFER_H_

#include "peanoclaw/ParallelSubgrid.h"
#include "peanoclaw/Patch.h"
#include "peanoclaw/records/CellDescription.h"
#include "peanoclaw/records/Data.h"

#include <map>
#include <vector>
#include "peano/utils/Globals.h"
#include "tarch/la/Vector.h"
#include "tarch/la/VectorCompare.h"
#include "tarch/logging/Log.h"
#include "tarch/multicore/BooleanSemaphore.h"

#define DIMENSIONS_PLUS_ONE (DIMENSIONS+1)

namespace peanoclaw {
  class Numerics;
  class Patch;
  class Vertex;

  namespace interSubgridCommunication {
    class GridLevelTransfer;
  }

  namespace tests {
    class GridLevelTransferTest;
  }
}

namespace peano {
    namespace grid {
      class VertexEnumerator;
    }
}

/**
 * In this class all functionality for transferring data
 * up or down through the spacetree is implemented.
 *
 * Every spacetree node is considered to contain a patch. However,
 * since we're implementing a mostly non-overlapping approach, not
 * all of these patches hold valid grid data. But all of them
 * contain time information. So, each patch is thought of spanning
 * a time interval.
 *
 * @see peanoclaw::Patch for further information about this.
 *
 * !!! Virtual Patches
 * There are three possible situations when a virtual patch needs to be created.
 *
 * !! Refined patch along a refinement boundary
 *
 * @image html virtual-patches-conditions-0.png
 *
 * When a patch is refined but has an unrefined neighbor on the same level, it
 * needs to become a virtual patch in this iteration. In this situation at least
 * one vertex needs to be in the state Unrefined (as long as the grid is static).
 * If the grid is not static we are in the next situation.
 *
 * !! Refined patch neighboring a refining patch
 *
 * @image html virtual-patches-conditions-1.png
 *
 * If an already refined patch has a refining neighbor, it needs to become a virtual
 * patch during this grid iteration. In this state at least on adjacent vertex is
 * in the state Refining.
 *
 * !! Erasing patch
 *
 * @image html virtual-patches-conditions-2.png
 *
 * If fine patches are about to be erased, the containing coarse patch needs to
 * become a virtual patch that later will be the new coarse patch at this part
 * of the grid. In this case at least one vertex is in the state Erasing.
 *
 * !! Condition for creating virtual patches
 *
 * In all three cases at least one vertex is in one of the states Unrefined,
 * Refining, Erasing. Thus, at least one vertex is not in the state Refined
 * (Since the check is done in the enterCell event, the states
 * Refinement_Triggered and Erasing_Triggered already have been switched to
 * Refining and Erasing). This is the used condition for determining wether
 * a refined patch should become a virtual one.
 *
 */
class peanoclaw::interSubgridCommunication::GridLevelTransfer {

  private:
    /**
     * Logging device.
     */
    static tarch::logging::Log _log;

    tarch::multicore::BooleanSemaphore _virtualPatchListSemaphore;

    friend class peanoclaw::tests::GridLevelTransferTest;

    typedef peanoclaw::records::Data Data;
    typedef peanoclaw::records::CellDescription CellDescription;
    typedef std::map<tarch::la::Vector<DIMENSIONS_PLUS_ONE,double>, int, tarch::la::VectorCompare<DIMENSIONS_PLUS_ONE> > VirtualSubgridMap;

    /**
     * Virtual patches are overlapping patches to the current processed patch. They are held
     * on each level smaller than the current one, so for each coarser cell that overlaps with
     * the current cell.
     *
     * We use these virtual patches for restricting ghostlayer data upwards in the spacetree.
     */
    //std::vector<int> _virtualPatchDescriptionIndices;
    VirtualSubgridMap _virtualPatchDescriptionIndices;

    /**
     * For each virtual patch in _virtualPatchDescriptionIndices this vector holds the
     * minimum time constraint from the neighbor patches. This can be used to skip restriction
     * steps if the fine patch does not match this time constraint after updating.
     */
//    std::vector<double> _virtualPatchTimeConstraints;

    peanoclaw::Numerics& _numerics;

    /**
     * Stores the maximum number of virtual patches which were held by this GridLevelTransfer
     * object. So, this is the maximum size of _virtualPatchDescriptionIndices during the
     * simulation run.
     */
    int _maximumNumberOfSimultaneousVirtualPatches;

    /**
     * Indicates wether the solver uses dimensional splitting. Thus, the timestepping
     * algorithm only has to take care about the 2d direct neighbors.
     */
    bool _useDimensionalSplitting;

    peanoclaw::statistics::SubgridStatistics& _subgridStatistics;

    /**
     * Vetos the coarsening on adjacent vertices if necessary and
     * triggers the synchronization of subgrids.
     *
     * TODO unterweg dissertation
     */
    void vetoCoarseningIfNecessary (
      Patch&                               patch,
      peanoclaw::Vertex * const            fineGridVertices,
      const peano::grid::VertexEnumerator& fineGridVerticesEnumerator
    );

    /**
     * Retrieves whether a patch surrounded by the given vertices
     * is adjacent to a subdomain residing on a different MPI
     * rank.
     */
    bool isPatchAdjacentToRemoteRank (
      peanoclaw::Vertex * const            fineGridVertices,
      const peano::grid::VertexEnumerator& fineGridVerticesEnumerator
    );

    /**
     * Determines, whether the given subgrid should be turned into a
     * virtual subgrid.
     *
     * TODO unterweg debug
     */
    bool shouldBecomeVirtualSubgrid(
      const Patch&                         fineSubgrid,
      peanoclaw::Vertex * const            fineGridVertices,
      const peano::grid::VertexEnumerator& fineGridVerticesEnumerator,
      bool                                 isInitializing,
      bool                                 isPeanoCellLeaf
    );

    /**
     * Turns the given subgrid into a virtual subgrid and adds it to
     * the list of virtual subgrids for restriction.
     */
    void switchToAndAddVirtualSubgrid(
      Patch& subgrid
    );

    /**
     * Restricts to virtual subgrids that overlap with the current
     * subgrid.
     *
     * While basically this should restrict to all
     * overlapping virtual subgrids for optimization reasons this is
     * not true. Restriction can be omitted if the virtual subgrid
     * (or the part of it that is overlapped by the current subgrid)
     * for sure will not be required in the current grid iteration.
     *
     * This, for example, is true if the timestepping of all
     * affected coarse subgrids will be blocked by the current subgrid.
     *
     * It also is true if no ghostlayer overlaps with the current
     * subgrid.
     *
     * TODO unterweg dissertation Optimierung für Restriktion siehe oben.
     *
     */
    void restrictToOverlappingVirtualSubgrids(
      Patch&           subgrid,
      ParallelSubgrid& fineParallelSubgrid
    );

    /**
     * Fills the surrounding ghostlayers of a virtual subgrid and
     * switches the subgrid to non-virtual, while removing it
     * from the virtual subgrids-list.
     */
    void finalizeVirtualSubgrid(
      Patch&                               subgrid,
      peanoclaw::Vertex * const            fineGridVertices,
      const peano::grid::VertexEnumerator& fineGridVerticesEnumerator,
      bool                                 isPeanoCellLeaf
    );

    tarch::la::Vector<DIMENSIONS_PLUS_ONE, double> createVirtualSubgridKey(
      tarch::la::Vector<DIMENSIONS, double> position,
      int                                   level
    ) const;

  public:
    GridLevelTransfer(
      bool useDimensionalSplitting,
      peanoclaw::Numerics& numerics,
      peanoclaw::statistics::SubgridStatistics& subgridStatistics
    );

    virtual ~GridLevelTransfer();

#ifdef Parallel
    /**
     * Called whenever a patch is merged from a remote MPI rank during
     * master/worker communication.
     *
     * @param cellDescriptionIndex The index for the current patch.
     * @param needsToHoldGridData Indicates whether this patch is supposed to
     * hold grid data. Either as a leaf patch of as a virtual patch.
     */
    void updatePatchStateDuringMergeWithWorker(
      int  localCellDescriptionIndex,
      int  remoteCellDescriptionIndex
    );
#endif

    /**
     * Performs the operations necessary when stepping into a cell.
     */
    void stepDown(
      Patch*                               coarseSubgrid,
      Patch&                               fineSubgrid,
      peanoclaw::Vertex * const            fineGridVertices,
      const peano::grid::VertexEnumerator& fineGridVerticesEnumerator,
      bool                                 isInitializing,
      bool                                 isPeanoCellLeaf
    );

    /**
     * @param isPeanoCellLeaf We need this flag, since during a refinement/coarsening the semantics
     * of Patch::isLeaf() and Cell::isLeaf() may differ. The first describes, wether a patch holds
     * valid grid data and is not virtual, while the latter describes the actual spacetree state of
     * a Peano cell. Hence, for setting the Patch state correctly we here need to know about the
     * state of the containing Peano cell.
     */
    void stepUp(
      Patch*                               coarseSubgrid,
      Patch&                               finePatch,
      ParallelSubgrid&                     fineParallelSubgrid,
      bool                                 isPeanoCellLeaf,
      peanoclaw::Vertex * const            fineGridVertices,
      const peano::grid::VertexEnumerator& fineGridVerticesEnumerator
    );

    /**
     * Restricts the refinement flags from a hanging vertex to the nearest coarse
     * vertex.
     *
     * The policy here is, that if one hanging vertex has a flag set, the appropriate
     * coarse vertices get the flag set as well. A refine-flag overrides a erase-flag.
     */
    void restrictRefinementFlagsToCoarseVertices(
      peanoclaw::Vertex* coarseGridVertices,
      const peano::grid::VertexEnumerator&      coarseGridVerticesEnumerator,
      const peanoclaw::Vertex&       fineGridVertex,
      const tarch::la::Vector<DIMENSIONS,int>&                   localPositionOfHangingNode
    );

    /**
     * Restricts the data of a subgrid that is about to be destroyed
     * to the overlapping coarse subgrid.
     */
    void restrictDestroyedSubgrid(
      const Patch&                         destroyedSubgrid,
      Patch&                               coarseSubgrid,
      peanoclaw::Vertex * const            fineGridVertices,
      const peano::grid::VertexEnumerator& fineGridVerticesEnumerator
    );
};

#endif /* PEANO_APPLICATIONS_PEANOCLAW_GRIDLEVELTRANSFER_H_ */

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.helloworld.yuer.testsdcard.MainActivity">

    <Button
        android:id="@+id/write_sd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="write to sd"/>

    <Button
        android:layout_toRightOf="@id/write_sd"
        android:id="@+id/read_sd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="read from sd"/>
</RelativeLayout>


text:
Welcome to the source folder!

Inside you will find a variety of code in a variety of formats.

* `.php` - Backend code, and basic page generation
* `.js` - JavaScript code, much of it in ES6 format (if there's an `.es6ignore` file, then it's ES5 format)
* `.css` - CSS code
* `.less` - LESS format CSS code (gets compiled in to normal CSS files)
* `.svg` - SVG Images (used as sprites)

## Internal

* [/com/](com/) - Preact.js Components. This is how most of the frontend is done.
* [/internal/](internal/) - Internal Libraries (??)
* [/embed/](embed/) - Code that gets embedded in to (PHP) scripts
* [/main/](main/) - The common Main used across sites
* [/shrub/](shrub/) - The CMS internals.

## Externals

* [/external/](external/) - 3rd party libraries
* [/custom/](custom/) - Modified/customized versions of 3rd party libraries. Will require extra work to upgrade
* [/compat/](compat/) - Compatibility (Polyfills) for modern and upcoming features (Ecmascript, DOM, etc)

## Assets

* [/icons/](icons/) - SVG Icons (baked in to a single file)

## Sites
The data shared across sites is called the **Jammer Core**. Each site is a different interpretation of **Jammer Core**'s data.

* [/public-ludumdare.com/](public-ludumdare.com/) - Ludum Dare (ldjam.com) - Ludum Dare focused View
* [/public-jammer.vg/](public-jammer.vg/) - Jammer (jammer.vg) - Normal View
* [/public-jammer.bio/](public-jammer.bio/) - Jammer.Bio - User Page and Content View (like a portfolio)

Websites may have their own Externals, Components, etc.

## Other
* [/tools/](tools/) - Extra tools used by the toolchain


text:
package bestcompany.moviematcher;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Point;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.lang.reflect.Array;
import java.util.ArrayList;

/**
 * Created by Billy on 2016-04-06.
 */
public class ListViewAdapter extends BaseAdapter {

    private ArrayList<String> in = new ArrayList<>();
    private Activity mActivity;

    public ListViewAdapter(ArrayList<String> info,Activity activity)
    {
        in = info;
        mActivity = activity;
    }

    @Override
    public int getCount() {
        return in.size();
    }

    @Override
    public Object getItem(int position) {
        return in.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View view, ViewGroup parent) {
        final View convertView = LayoutInflater.from(mActivity).inflate(R.layout.list_item, parent, false);
        ViewHolder holder = new ViewHolder(); //Making variable of class type ViewHolder def
        convertView.setTag(holder); //sets the tag

        holder.movieReccomendation = (TextView) convertView.findViewById(R.id.Reccomendationtext);
        holder.movieName = (TextView) convertView.findViewById(R.id.MovieText);
        holder.mapText = (TextView) convertView.findViewById(R.id.LocationText);

        if(position==0)
        {
            holder.movieReccomendation.setText("This is your movie:");
        }

        holder.movieName.setText(in.get(position));

        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //clicking on this leads you to the google maps location
                Intent intent = new Intent(mActivity,MapsActivity.class);
                intent.putExtra("Name",in.get(position));
                mActivity.startActivity(intent);
            }
        });

        // Android functions to determine the screen dimensions.
        Display display = mActivity.getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        // Storing the screen height into an int variable.
        int height = size.y;
        //Sets the height to 1/3 the screensize.
        ViewGroup.LayoutParams params = convertView.getLayoutParams();
        params.height =  (int)Math.round(height*.3198);

        if(in.get(position).contains("Movie"))
        {
            return null;
        }

        return convertView;
    }

    //A view holder that contain the things that need to be changed for every event
    private static class ViewHolder
    {
        TextView movieReccomendation;
        TextView movieName;
        TextView mapText;
    }

}


text:
package alluxio.shell.command;

import alluxio.client.file.FileSystem;
import alluxio.exception.AlluxioException;
import alluxio.shell.AlluxioShellUtils;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.annotation.concurrent.ThreadSafe;

/**
 * Command for print help message for the given command. If there isn't given command, print help
 * messages for all supported commands.
 */
@ThreadSafe
public final class HelpCommand extends AbstractShellCommand {
  private static final HelpFormatter HELP_FORMATTER = new HelpFormatter();

  /**
   * Prints the info about a command to the given print writer.
   *
   * @param command command to print info
   * @param pw where to print the info
   */
  public static void printCommandInfo(ShellCommand command, PrintWriter pw) {
    String description =
        String.format("%s: %s", command.getCommandName(), command.getDescription());
    // TODO(binfan): instead of using a constant, adjust the value according to console width
    int width = HELP_FORMATTER.getWidth();
    HELP_FORMATTER.printWrapped(pw, width, description);
    HELP_FORMATTER.printUsage(pw, width, command.getUsage());
    if (command.getOptions().getOptions().size() > 0) {
      HELP_FORMATTER.printOptions(pw, width, command.getOptions(), HELP_FORMATTER.getLeftPadding(),
          HELP_FORMATTER.getDescPadding());
    }
  }

  /**
   * @param fs the filesystem of Alluxio
   */
  public HelpCommand(FileSystem fs) {
    super(fs);
  }

  @Override
  public String getCommandName() {
    return "help";
  }

  @Override
  public int run(CommandLine cl) throws AlluxioException, IOException {
    String[] args = cl.getArgs();
    SortedSet<String> sortedCmds;
    Map<String, ShellCommand> commands = AlluxioShellUtils.loadCommands(mFileSystem);
    try (PrintWriter pw = new PrintWriter(System.out)) {
      if (args.length == 0) {
        // print help messages for all supported commands.
        sortedCmds = new TreeSet<>(commands.keySet());
        for (String commandName : sortedCmds) {
          ShellCommand command = commands.get(commandName);
          printCommandInfo(command, pw);
          pw.println();
        }
      } else if (commands.containsKey(args[0])) {
        ShellCommand command = commands.get(args[0]);
        printCommandInfo(command, pw);
      } else {
        pw.println(args[0] + " is an unknown command.");
        return -1;
      }
      return 0;
    }
  }

  @Override
  public String getUsage() {
    return "help <command>";
  }

  @Override
  public String getDescription() {
    return "Prints help message for the given command. "
        + "If there isn't given command, prints help messages for all supported commands.";
  }

  @Override
  public boolean validateArgs(String... args) {
    boolean valid = args.length <= getNumOfArgs();
    if (!valid) {
      System.out.println(
          getCommandName() + " takes at most " + getNumOfArgs() + " arguments, " + " not "
              + args.length + "\n");
    }
    return valid;
  }

  @Override
  protected int getNumOfArgs() {
    return 1;
  }

}


text:
/*
 * DocuSign REST API
 *
 * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
 *
 * OpenAPI spec version: v2.1
 * Contact: devcenter@docusign.com
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 */

using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;

namespace DocuSign.eSign.Model
{
    /// <summary>
    /// EnvelopeIdsRequest
    /// </summary>
    [DataContract]
    public partial class EnvelopeIdsRequest :  IEquatable<EnvelopeIdsRequest>, IValidatableObject
    {
        public EnvelopeIdsRequest()
        {
            // Empty Constructor
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="EnvelopeIdsRequest" /> class.
        /// </summary>
        /// <param name="EnvelopeIds">EnvelopeIds.</param>
        /// <param name="TransactionIds"> A list of transaction Id's used to determining the status of envelopes sent asynchronously. See **transactionId** property on envelopes..</param>
        public EnvelopeIdsRequest(List<string> EnvelopeIds = default(List<string>), List<string> TransactionIds = default(List<string>))
        {
            this.EnvelopeIds = EnvelopeIds;
            this.TransactionIds = TransactionIds;
        }

        /// <summary>
        /// Gets or Sets EnvelopeIds
        /// </summary>
        [DataMember(Name="envelopeIds", EmitDefaultValue=false)]
        public List<string> EnvelopeIds { get; set; }
        /// <summary>
        ///  A list of transaction Id's used to determining the status of envelopes sent asynchronously. See **transactionId** property on envelopes.
        /// </summary>
        /// <value> A list of transaction Id's used to determining the status of envelopes sent asynchronously. See **transactionId** property on envelopes.</value>
        [DataMember(Name="transactionIds", EmitDefaultValue=false)]
        public List<string> TransactionIds { get; set; }
        /// <summary>
        /// Returns the string presentation of the object
        /// </summary>
        /// <returns>String presentation of the object</returns>
        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Append("class EnvelopeIdsRequest {\n");
            sb.Append("  EnvelopeIds: ").Append(EnvelopeIds).Append("\n");
            sb.Append("  TransactionIds: ").Append(TransactionIds).Append("\n");
            sb.Append("}\n");
            return sb.ToString();
        }

        /// <summary>
        /// Returns the JSON string presentation of the object
        /// </summary>
        /// <returns>JSON string presentation of the object</returns>
        public string ToJson()
        {
            return JsonConvert.SerializeObject(this, Formatting.Indented);
        }

        /// <summary>
        /// Returns true if objects are equal
        /// </summary>
        /// <param name="obj">Object to be compared</param>
        /// <returns>Boolean</returns>
        public override bool Equals(object obj)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            return this.Equals(obj as EnvelopeIdsRequest);
        }

        /// <summary>
        /// Returns true if EnvelopeIdsRequest instances are equal
        /// </summary>
        /// <param name="other">Instance of EnvelopeIdsRequest to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(EnvelopeIdsRequest other)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            if (other == null)
                return false;

            return
                (
                    this.EnvelopeIds == other.EnvelopeIds ||
                    this.EnvelopeIds != null &&
                    this.EnvelopeIds.SequenceEqual(other.EnvelopeIds)
                ) &&
                (
                    this.TransactionIds == other.TransactionIds ||
                    this.TransactionIds != null &&
                    this.TransactionIds.SequenceEqual(other.TransactionIds)
                );
        }

        /// <summary>
        /// Gets the hash code
        /// </summary>
        /// <returns>Hash code</returns>
        public override int GetHashCode()
        {
            // credit: http://stackoverflow.com/a/263416/677735
            unchecked // Overflow is fine, just wrap
            {
                int hash = 41;
                // Suitable nullity checks etc, of course :)
                if (this.EnvelopeIds != null)
                    hash = hash * 59 + this.EnvelopeIds.GetHashCode();
                if (this.TransactionIds != null)
                    hash = hash * 59 + this.TransactionIds.GetHashCode();
                return hash;
            }
        }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            yield break;
        }
    }
}


text:
cask "netlogo" do
  version "6.3.0"
  sha256 "a595dfdb5382f13ff1da44d9402e8ec3b78c927d12e6b83378da391596ee2b04"

  url "https://ccl.northwestern.edu/netlogo/#{version}/NetLogo-#{version}.dmg"
  name "NetLogo"
  desc "Multi-agent programmable modeling environment"
  homepage "https://ccl.northwestern.edu/netlogo/"

  livecheck do
    url "https://ccl.northwestern.edu/netlogo/oldversions.shtml"
    regex(/NetLogo\s*(\d+(?:\.\d+)+)/i)
  end

  suite "NetLogo #{version}"

  zap trash: [
    "~/Library/Preferences/org.nlogo.netlogo.plist",
    "~/Library/Saved Application State/org.nlogo.NetLogo.savedState",
  ]
end


text:
title: "Geo Trivia 2.0 Released!"
date: 2013-07-11 18:20
author: saguiitay
categories: [Development, Windows Phone]
tags: [Geo Trivia, geography, Trivia, Windows Phone]
redirect_from:
 - /2013-07-11-geo-trivia-2-0-released/
 - /development/geo-trivia-2-0-released/
---
I'm proud to announce that Geo Trivia 2.0 was released, and is available for download in the Marketplace. In addition to the new backend engine,
the new version includes fixes to multiple bugs and performance issues. However, the most exciting change is the addition of image questions - questions
that contains an image, or that their answers are images:

![Geo Trivia Screenshot6]({{site.url}}/images/geo-trivia-screenshot6.png)]

This opens up a complete new set of questions in the game.

Lastly, as usual, I've added even more data in the game - 194 flags and 53 POI images, as well as 6 new types of questions - this means plenty of
new questions! You can download the new versions by clicking the image below:

[![Download Geo Trivia for Windows Phone]({{site.url}}/images/windowsphone_208x67_blu.png "Download Geo Trivia for Windows Phone")](http://www.windowsphone.com/s?appid=e697a777-acdf-4db2-b00e-e957bd387839)


text:
{% extends "base.html" %}

{% load paginator %}
{% load tableheader %}

{% block title %}Datasets · Banana{% endblock title %}

{% block navdatabase %}
Database {{ db_name }}
{% endblock navdatabase %}

{% block content %}

            {% if not dataset_list %}

No datasets are available

            {% else %}

                    {% paginatorizer %}

                            {% tableheader 'id' %}
                            {% tableheader 'description' %}
                            {% tableheader 'rerun' %}
                            {% tableheader 'num_images' 'Number of Images' %}
                            {% tableheader 'process_start_ts' 'Start time' %}
                            {% tableheader 'process_end_ts' 'End time' %}

                        {% for dataset in dataset_list %}

                                {{ dataset.id }}
                                {{ dataset.description }}
                                {{ dataset.rerun }}
                                {{ dataset.num_images }}
                                {{ dataset.process_start_ts }}
                                {{ dataset.process_end_ts }}

                        {% endfor %}

                    {% paginatorizer %}

            {% endif %}

{% endblock content %}


text:
<extension xmlns="http://ns.adobe.com/air/extension/2.5">
    <id>net.rim.BBM</id>
    <versionNumber>1</versionNumber>
    <platforms>
        <platform name="QNX-x86">
            <applicationDeployment>
                <nativeLibrary>nativex86.so</nativeLibrary>
                <initializer>extensionInitializer</initializer>
                <finalizer>extensionFinalizer</finalizer>
            </applicationDeployment>
        </platform>
        <platform name="QNX-ARM">
            <applicationDeployment>
                <nativeLibrary>nativearm.so</nativeLibrary>
                <initializer>extensionInitializer</initializer>
                <finalizer>extensionFinalizer</finalizer>
            </applicationDeployment>
        </platform>
		<platform name="default">
			<applicationDeployment/>
		</platform>
    </platforms>
</extension>


text:
package com.github.dozermapper.core.vo.deepindex;

import com.github.dozermapper.core.vo.BaseTestObject;

public class Pet extends BaseTestObject {
    private String petName;
    private int petAge;
    private Pet[] offSpring;

    public Pet() {
    }

    public Pet(String petName, int petAge) {
        this.petName = petName;
        this.petAge = petAge;
    }

    public Pet(String petName, int petAge, Pet[] offSpring) {
        this.petName = petName;
        this.petAge = petAge;
        this.offSpring = offSpring;
    }

    public Pet[] getOffSpring() {
        return offSpring;
    }

    public void setOffSpring(Pet[] offSpring) {
        this.offSpring = offSpring;
    }

    public int getPetAge() {
        return petAge;
    }

    public void setPetAge(int petAge) {
        this.petAge = petAge;
    }

    public String getPetName() {
        return petName;
    }

    public void setPetName(String petName) {
        this.petName = petName;
    }
}


text:
package main.java;

/**
 * Created by brandon on 3/30/2016 at 4:44 PM as part of the chess project.
 */
public class Chess
{
    public static void main(String[] args)
    {
        //Instantiate the Model, View, and Controller//

        Model model = new Model();
        TextView view = new TextView();
        TextController controller = new TextController();

        controller.setModel(model);
        controller.setView(view);

        model.addObserver(view);

        controller.run();
    }
}


text:
<!DOCTYPE html>

<title>Poem Maker Pro</title>

Enter terms below.

<form method="post" action="/poem">

Plural noun
<input type="text" name="noun1">

Singular noun
<input type="text" name="noun2">

Verb (past tense)
<input type="text" name="verb">

Noun
<input type="text" name="noun3">

<input type="submit">
</form>


text:
#ifndef YAPE_OPIMUL2_HPP
#define YAPE_OPIMUL2_HPP

#include "../BaseInstruction.hpp"

class OpIMUL2 : public BaseInstruction
{
public:
    void Execute() override;
    int GetOpcode() const override;
    bool isConstArgsAllowed() const override;
};

#endif //YAPE_OPIMUL2_HPP


text:
@class HSDViewController;

@interface HSDAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) HSDViewController *viewController;

@end


text:
namespace mojo {
namespace system {

class MOJO_SYSTEM_IMPL_EXPORT WaitSetDispatcher : public Dispatcher {
 public:
  WaitSetDispatcher();
  ~WaitSetDispatcher() override;

  // |Dispatcher| public methods:
  Type GetType() const override;

 private:
  // Internal implementation of Awakable.
  class Waiter;

  struct WaitState {
    scoped_refptr<Dispatcher> dispatcher;
    MojoHandleSignals signals;
    uintptr_t context;
  };

  // |Dispatcher| protected methods:
  void CloseImplNoLock() override;
  void CancelAllAwakablesNoLock() override;
  MojoResult AddAwakableImplNoLock(Awakable* awakable,
                                   MojoHandleSignals signals,
                                   uintptr_t context,
                                   HandleSignalsState* signals_state) override;
  void RemoveAwakableImplNoLock(Awakable* awakable,
                                HandleSignalsState* signals_state) override;
  MojoResult AddWaitingDispatcherImplNoLock(
      const scoped_refptr<Dispatcher>& dispatcher,
      MojoHandleSignals signals,
      uintptr_t context) override;
  MojoResult RemoveWaitingDispatcherImplNoLock(
      const scoped_refptr<Dispatcher>& dispatcher) override;
  MojoResult GetReadyDispatchersImplNoLock(
      UserPointer<uint32_t> count,
      DispatcherVector* dispatchers,
      UserPointer<MojoResult> results,
      UserPointer<uintptr_t> contexts) override;
  HandleSignalsState GetHandleSignalsStateImplNoLock() const override;
  scoped_refptr<Dispatcher> CreateEquivalentDispatcherAndCloseImplNoLock()
      override;

  // Signal that the dispatcher indexed by |context| has been woken up with
  // |result| and is now ready.
  void WakeDispatcher(MojoResult result, uintptr_t context);

  // Map of dispatchers being waited on. Key is a Dispatcher* casted to a
  // uintptr_t, and should be treated as an opaque value and not casted back.
  std::map<uintptr_t, WaitState> waiting_dispatchers_ MOJO_GUARDED_BY(mutex());

  // Separate mutex that can be locked without locking |mutex()|.
  mutable Mutex awoken_mutex_ MOJO_ACQUIRED_AFTER(mutex());
  // List of dispatchers that have been woken up. Any dispatcher in this queue
  // will NOT currently be waited on.
  std::deque<std::pair<uintptr_t, MojoResult>> awoken_queue_
      MOJO_GUARDED_BY(awoken_mutex_);
  // List of dispatchers that have been woken up and retrieved on the last call
  // to |GetReadyDispatchers()|.
  std::deque<uintptr_t> processed_dispatchers_ MOJO_GUARDED_BY(awoken_mutex_);

  // Separate mutex that can be locked without locking |mutex()|.
  Mutex awakable_mutex_ MOJO_ACQUIRED_AFTER(mutex());
  // List of dispatchers being waited on.
  AwakableList awakable_list_ MOJO_GUARDED_BY(awakable_mutex_);

  // Waiter used to wait on dispatchers.
  scoped_ptr<Waiter> waiter_;
};

}  // namespace system
}  // namespace mojo

#endif  // THIRD_PARTY_MOJO_SRC_MOJO_EDK_SYSTEM_WAIT_SET_DISPATCHER_H_


text:
import { Component, Input } from '@angular/core';
import { AllReadyEvent } from "../../pages/events/events";
import { NavController } from "ionic-angular";
import { EventDetailsPage } from "../../pages/eventdetails/eventdetails";
import { DateFilterPipe } from "../../pipes/datefilter/datefilter";

@Component({
  selector: 'event-card',
  templateUrl: 'event-card.html'
})

export class EventCardComponent {

  @Input('event') event: AllReadyEvent;
  private formattedStartDateTime: string;

  constructor(public navCtrl: NavController, public dateFilterPipe: DateFilterPipe) {
    this.dateFilterPipe = new DateFilterPipe();
  }

  ngOnChanges() {
    this.formattedStartDateTime =
      this.dateFilterPipe.transform(this.event.StartDateTime.toString(), null);
  }

  showEventDetails(event: AllReadyEvent) {
    this.navCtrl.push(EventDetailsPage, { event: event });
  }

}


text:
from unittest import defaultTestLoader, TextTestRunner
import sys

suite = defaultTestLoader.discover(start_dir=".")
result = TextTestRunner(verbosity=2, buffer=True).run(suite)
sys.exit(0 if result.wasSuccessful() else 1)


text:
<?= Asset::js('common.js') ?>

スニペット

<?= View::forge('common/message')->render() ?>

			アクションボタン

		 戻る
		 キャンセル
		新規作成
		<button type="submit" class="btn btn-primary create" onclick="return confirm('登録してよろしいでしょうか?')"> 登録</button>
		<button type="submit" class="btn btn-primary create" onclick="return confirm('更新してよろしいでしょうか?')"> 更新</button>
		 削除
		<button type="submit" class="btn btn-default" name="search" value="検索"> 検索</button>
		<button type="submit" class="btn btn-info download"> ダウンロード</button>

			テーブル

					#
					会社名

					01
					GMOシステムコンサルティング株式会社

					02
					GMOシステムコンサルティング株式会社

					03
					GMOシステムコンサルティング株式会社

					04
					GMOシステムコンサルティング株式会社

					05
					GMOシステムコンサルティング株式会社

<form class="form-horizontal" role="form" method="post" enctype="multipart/form-data">

				フォーム

					フォーム(小)

					<input class="form-control" type="text" />

					フォーム(中)

					<input class="form-control" type="text" />

					フォーム(大)

					<input class="form-control" type="text" />

					日付入力

					<input class="form-control" type="text" />

</form>


text:
package com.jeremiq.tictactoe.game.cell;

import com.jeremiq.tictactoe.game.board.BoardMark;
import com.jeremiq.tictactoe.game.board.InvalidMoveException;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class CellTest {
    Cell cell;
    BoardMark X;
    BoardMark O;

    @Before
    public void setUp() throws Exception {
        cell = new Cell();
        X = BoardMark.X;
        O = BoardMark.O;
    }

    @Test(expected = CellOccupiedException.class)
    public void testStateChange() throws Exception {
        assertNotEquals(X, cell.getState());
        cell.setState(X);
        assertEquals(X, cell.getState());
        cell.setState(O);
    }

    @Test
    public void testIsEmpty() throws Exception {
        assertTrue(cell.isEmpty());
        cell.setState(X);
        assertFalse(cell.isEmpty());
    }

}


text:
<?php

namespace Slicer\Event;

/**
 * Class PreCreateUpdateEvent
 *
 * @package Slicer\Event
 */
class PreCreateUpdateEvent extends Event
{
    /** @var  string */
    protected $startHash;
    /** @var  string */
    protected $endHash;

    /**
     * Create new event.
     *
     * @param string $start
     * @param string $end
     */
    public function __construct( $start, $end )
    {
        $this->startHash = $start;
        $this->endHash   = $end;
    }

    /**
     * Get start hash.
     *
     * @return string
     */
    public function getStartHash()
    {
        return $this->startHash;
    }

    /**
     * Set start hash.
     *
     * @param string $startHash
     *
     * @return PreCreateUpdateEvent
     */
    public function setStartHash( $startHash )
    {
        $this->startHash = $startHash;

        return $this;
    }

    /**
     * Get end hash.
     *
     * @return string
     */
    public function getEndHash()
    {
        return $this->endHash;
    }

    /**
     * Set end hash.
     *
     * @param string $endHash
     *
     * @return PreCreateUpdateEvent
     */
    public function setEndHash( $endHash )
    {
        $this->endHash = $endHash;

        return $this;
    }

}


text:
package be.belgif.vocab.resources;

import be.belgif.vocab.helpers.QueryHelper;
import be.belgif.vocab.helpers.QueryHelperFTS;
import be.belgif.vocab.helpers.RDFMediaType;
import be.belgif.vocab.views.VocabSearchView;

import java.util.Optional;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.eclipse.rdf4j.model.Model;
import org.eclipse.rdf4j.repository.Repository;

/**
 * Full text search
 *
 * @author Bart.Hanssens
 */
@Path("/_search")
public class SearchResource extends RdfResource {

	@GET
	@Path("/{vocab}")
	@Produces({RDFMediaType.JSONLD, RDFMediaType.NTRIPLES, RDFMediaType.TURTLE})
	public Model search(@PathParam("type") String vocab, @QueryParam("q") String text) {
		return QueryHelperFTS.getFTS(getRepository(), text, QueryHelper.VOCAB, vocab);
	}

	@GET
	@Path("/{vocab}")
	@Produces({MediaType.TEXT_HTML})
	public VocabSearchView searchHTML(@PathParam("vocab") String vocab,
			@QueryParam("q") String text, @QueryParam("lang") Optional<String> lang) {
		return new VocabSearchView(vocab, search(vocab, text), lang.orElse("en"));
	}

	/**
	 * Constructor
	 *
	 * @param repo RDF triple store
	 */
	public SearchResource(Repository repo) {
		super(repo);
	}
}


text:
using namespace std;

//Compute MC pricing of vanilla options
template<typename T>
void mc_pricer_vanilla(const T& TheOption,
					   const Parameters& r,
					   shared_ptr<PathGeneration>&  ThePaths,
					   unsigned long NumberOfPaths,
					   StatisticsMC& gatherer,
					   StatisticsMC& gatherer_time)
{
	timer t;
	t.start();

	double Expiry(TheOption.GetExpiry());
	//double thisSpot;
	double discounting = exp(-r.Integral(0, Expiry));

	vector<MJArray> args(1);
	args[0] = MJArray(ThePaths->GetSteps());

	for (unsigned long i = 0; i < NumberOfPaths; i++)
	{
		double thisSpot = ThePaths->GetOnePath(args); //cout << thisSpot << " ";
		double thisPayOff = TheOption.OptionPayOff(thisSpot);
		gatherer.DumpOneResult(thisPayOff*discounting);
		gatherer_time.DumpOneResult(t.elapsedTime());
	}

};

//compute price w/o convergence table
template<typename T>
double mc_pricer_vanilla(const T& TheOption,
						 const Parameters& r,
						 shared_ptr<PathGeneration>&  ThePaths,
						 unsigned long NumberOfPaths)
{
	double Expiry(TheOption.GetExpiry());
	//double thisSpot;
	double discounting = exp(-r.Integral(0, Expiry));

	vector<MJArray> args(1);
	args[0] = MJArray(ThePaths->GetSteps());

	double sum(0.0);

	for (unsigned long i = 0; i < NumberOfPaths; i++)
	{
		double thisSpot = ThePaths->GetOnePath(args);
		sum += TheOption.OptionPayOff(thisSpot);
	}

	return sum * discounting / NumberOfPaths;
};

//1.finite difference with MC.
//Bump params

//2. Pathwise with MC.
template<typename T>
double pathwise_mc_delta(const T& TheOption,
						 const Parameters& r,
						 shared_ptr<PathGeneration>&  ThePaths,
						 unsigned long NumberOfPaths)
{
	double Expiry(TheOption.GetExpiry());
	//double thisSpot;
	double discounting = exp(-r.Integral(0, Expiry));

	vector<MJArray> args(1);
	args[0] = MJArray(ThePaths->GetSteps());

	double sum(0.0);

	for (unsigned long i = 0; i < NumberOfPaths; i++)
	{
		double thisSpot = ThePaths->GetOnePath(args);
		double tmp(thisSpot > TheOption.GetStrike() ? 1.0 : 0.0);

		sum += thisSpot / ThePaths->GetSpot() * tmp;
	}

	return sum * discounting / NumberOfPaths;
};

#endif


text:
import { createWrapper, mount } from '@vue/test-utils'
import Vue from 'vue'
import Collapse from './index'
import collapseItem from './collapse-item'

const collapseApp = {
  render(h) {
    return (
      <Collapse accordion={this.accordion} vModel={this.value} ref="collapse">
        <collapseItem title="折叠面板1" name="a" ref="item1">

折叠面板内容1

        </collapseItem>
        <collapseItem
          title="折叠面板2"
          disabled={this.disabled}
          name="b"
          ref="item2"
        >

折叠面板内容2

        </collapseItem>
        <collapseItem title="折叠面板3" name="c" ref="item3">

折叠面板内容3

        </collapseItem>
        <collapseItem title="折叠面板4" name="d">

折叠面板内容4

        </collapseItem>
      </Collapse>
    )
  },
  data() {
    return {
      value: ['a'],
      accordion: true,
      disabled: false
    }
  }
}

const clickItem = item => {
  createWrapper(item).find('.c-collapse-item__header').trigger('click')
}

const isActive = vm => {
  const expandable = createWrapper(vm).find('[aria-expanded]')
  return expandable.element.getAttribute('aria-expanded') === 'true'
}

it('should be accordion mode when accordion is `true`', async () => {
  const wrapper = mount(collapseApp)
  wrapper.setData({ accordion: true, value: [] })
  await Vue.nextTick()
  const { item1, item3 } = wrapper.vm.$refs
  expect(isActive(item1)).toBe(false)
  clickItem(item3)
  await Vue.nextTick()
  expect(isActive(item1)).toBe(false)
  expect(isActive(item3)).toBe(true)
})

it('should respond to keyboard event', async () => {
  const wrapper = mount(collapseApp)
  const items = wrapper.findAll('.c-collapse-item__header')
  const item = items.at(2)
  const isItemActive = wrap =>
    wrap.element.getAttribute(`aria-expanded`) === 'true'
  expect(isItemActive(item)).toBe(false)
  expect(item.element.getAttribute('tabindex')).toBe('0')
  // Used to call `item.element.focus()` first
  // to gain focus so that keyboard event can be triggered.
  // After updating the test library, such step is no longer needed,
  // which is double-edged
  item.trigger('keydown', {
    key: 'Enter'
  })
  await Vue.nextTick()
  expect(isItemActive(item)).toBe(true)
  item.trigger('keydown', {
    key: ' '
  })
  await Vue.nextTick()
  expect(isItemActive(item)).toBe(false)
})

it('should not be accordion mode when accordion is `false`', async () => {
  const wrapper = mount(collapseApp)
  wrapper.setData({ accordion: false, value: ['a', 'b'] })
  await Vue.nextTick()
  const { item1, item2, item3 } = wrapper.vm.$refs

  expect(isActive(item1)).toBe(true)
  expect(isActive(item2)).toBe(true)
  expect(isActive(item3)).toBe(false)
  clickItem(item2)
  await Vue.nextTick()
  clickItem(item3)
  await Vue.nextTick()
  expect(isActive(item1)).toBe(true)
  expect(isActive(item2)).toBe(false)
  expect(isActive(item3)).toBe(true)

  const isActiveNames =
    wrapper.vm.$refs.collapse.value.includes('a') &&
    wrapper.vm.$refs.collapse.value.includes('c')
  expect(isActiveNames).toBeTruthy()
})

it('cannot open when disabled is true', async () => {
  const wrapper = mount(collapseApp)
  const { item1, item2 } = wrapper.vm.$refs
  wrapper.setData({ disabled: true })
  await Vue.nextTick()
  expect(isActive(item1)).toBe(true)
  expect(isActive(item2)).toBe(false)

  clickItem(item1)
  await Vue.nextTick()
  clickItem(item2)
  await Vue.nextTick()
  expect(isActive(item2)).toBe(false)
  const isDisabled = item2.$el.querySelector('.c-collapse-item--disabled')
  expect(isDisabled).toBeTruthy()
})

const collapseApp1 = {
  render(h) {
    return (
      <Collapse ref="collapse">
        <collapseItem name="test">

折叠面板内容1

        </collapseItem>
      </Collapse>
    )
  }
}
it('test value', () => {
  const wrapper = mount(collapseApp1)
  expect(wrapper.findAll('[aria-expanded=true]').length).toBe(0)
})


text:
module PatronusFati::MessageProcessor::Alert
  include PatronusFati::MessageProcessor

  def self.process(obj)
    # Ignore the initial flood of cached data
    return unless PatronusFati.past_initial_flood?

    PatronusFati.event_handler.event(:alert, :new, process_obj(obj))

    nil
  end

  def self.process_obj(obj)
    {
      created_at: obj[:sec],
      type: obj[:header],
      message: obj[:text],

      source: obj[:source],
      destination: obj[:dest],
      other: obj[:other]
    }
  end
end


text:
<?php

namespace phpbb\passwords\driver;

class helper
{
	/**
	* @var \phpbb\config\config
	*/
	protected $config;

	/**
	* base64 alphabet
	* @var string
	*/
	public $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

	/**
	* Construct a driver helper object
	*
	* @param \phpbb\config\config $config phpBB configuration
	*/
	public function __construct(\phpbb\config\config $config)
	{
		$this->config = $config;
	}

	/**
	* Base64 encode hash
	*
	* @param string $input Input string
	* @param int $count Input string length
	*
	* @return string base64 encoded string
	*/
	public function hash_encode64($input, $count)
	{
		$output = '';
		$i = 0;

		do
		{
			$value = ord($input[$i++]);
			$output .= $this->itoa64[$value & 0x3f];

			if ($i < $count)
			{
				$value |= ord($input[$i]) << 8;
			}

			$output .= $this->itoa64[($value >> 6) & 0x3f];

			if ($i++ >= $count)
			{
				break;
			}

			if ($i < $count)
			{
				$value |= ord($input[$i]) << 16;
			}

			$output .= $this->itoa64[($value >> 12) & 0x3f];

			if ($i++ >= $count)
			{
				break;
			}

			$output .= $this->itoa64[($value >> 18) & 0x3f];
		}
		while ($i < $count);

		return $output;
	}

	/**
	* Return unique id
	*
	* @param string $extra Additional entropy
	*
	* @return string Unique id
	*/
	public function unique_id($extra = 'c')
	{
		static $dss_seeded = false;

		$val = $this->config['rand_seed'] . microtime();
		$val = md5($val);
		$this->config['rand_seed'] = md5($this->config['rand_seed'] . $val . $extra);

		if ($dss_seeded !== true && ($this->config['rand_seed_last_update'] < time() - rand(1,10)))
		{
			$this->config->set('rand_seed_last_update', time(), true);
			$this->config->set('rand_seed', $this->config['rand_seed'], true);
			$dss_seeded = true;
		}

		return substr($val, 4, 16);
	}

	/**
	* Get random salt with specified length
	*
	* @param int $length Salt length
	* @param string $rand_seed Seed for random data (optional). For tests.
	*
	* @return string Random salt with specified length
	*/
	public function get_random_salt($length, $rand_seed = '/dev/urandom')
	{
		$random = '';

		if (($fh = @fopen($rand_seed, 'rb')))
		{
			$random = fread($fh, $length);
			fclose($fh);
		}

		if (strlen($random) < $length)
		{
			$random = '';
			$random_state = $this->unique_id();

			for ($i = 0; $i < $length; $i += 16)
			{
				$random_state = md5($this->unique_id() . $random_state);
				$random .= pack('H*', md5($random_state));
			}
			$random = substr($random, 0, $length);
		}
		return $random;
	}

	/**
	 * Compare two strings byte by byte
	 *
	 * @param string $string_a The first string
	 * @param string $string_b The second string
	 *
	 * @return bool True if strings are the same, false if not
	 */
	public function string_compare($string_a, $string_b)
	{
		// Return if input variables are not strings or if length does not match
		if (!is_string($string_a) || !is_string($string_b) || strlen($string_a) != strlen($string_b))
		{
			return false;
		}

		// Use hash_equals() if it's available
		if (function_exists('hash_equals'))
		{
			return hash_equals($string_a, $string_b);
		}

		$difference = 0;

		for ($i = 0; $i < strlen($string_a) && $i < strlen($string_b); $i++)
		{
			$difference |= ord($string_a[$i]) ^ ord($string_b[$i]);
		}

		return $difference === 0;
	}
}


text:
title:  03. C++ Standard Library
date:   2015-11-03
categories: C++
excerpt:
---

# C++ Standard Library
  * defined in the `std::` namespace
  * a collection of classes and functions
  * written in the core language
  * part of the C++ ISO Standard itself
  * Implement by GNU: The GNU Standard C++ Library v3, or libstdc++-v3
    * [GNU libstdc++-v3]
  * Implement by Microsoft:
    * [Visual Studio 2015 C++ Standard Library Reference]
  * Implement by LLVM:
    * [libc++ 3.8 documentation]


text:
require 'linguist/file_blob'

module Linguist
  # A Repository is an abstraction of a Grit::Repo or a basic file
  # system tree. It holds a list of paths pointing to Blobish objects.
  #
  # Its primary purpose is for gathering language statistics across
  # the entire project.
  class Repository
    # Public: Initialize a new Repository from a File directory
    #
    # base_path - A path String
    #
    # Returns a Repository
    def self.from_directory(base_path)
      new Dir["#{base_path}/**/*"].
        select { |f| File.file?(f) }.
        map { |path| FileBlob.new(path, base_path) }
    end

    # Public: Initialize a new Repository
    #
    # enum - Enumerator that responds to `each` and
    #        yields Blob objects
    #
    # Returns a Repository
    def initialize(enum)
      @enum = enum
      @computed_stats = false
      @language = @size = nil
      @sizes = Hash.new { 0 }
    end

    # Public: Returns a breakdown of language stats.
    #
    # Examples
    #
    #   # => { Language['Ruby'] => 46319,
    #          Language['JavaScript'] => 258 }
    #
    # Returns a Hash of Language keys and Integer size values.
    def languages
      compute_stats
      @sizes
    end

    # Public: Get primary Language of repository.
    #
    # Returns a Language
    def language
      compute_stats
      @language
    end

    # Public: Get the total size of the repository.
    #
    # Returns a byte size Integer
    def size
      compute_stats
      @size
    end

    # Internal: Compute language breakdown for each blob in the Repository.
    #
    # Returns nothing
    def compute_stats
      return if @computed_stats

      @enum.each do |blob|
        # Skip files that are likely binary
        next if blob.likely_binary?

        # Skip vendored or generated blobs
        next if blob.vendored? || blob.generated? || blob.language.nil?

        # Only include programming languages and acceptable markup languages
        if blob.language.type == :programming || Language.detectable_markup.include?(blob.language.name)
          @sizes[blob.language.group] += blob.size
        end
      end

      # Compute total size
      @size = @sizes.inject(0) { |s,(_,v)| s + v }

      # Get primary language
      if primary = @sizes.max_by { |(_, size)| size }
        @language = primary[0]
      end

      @computed_stats = true

      nil
    end
  end
end


text:
package me.coley.recaf.ui.controls.text;

import javafx.scene.control.ContextMenu;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import me.coley.recaf.control.gui.GuiController;
import me.coley.recaf.parse.bytecode.ast.*;
import me.coley.recaf.ui.ContextBuilder;
import me.coley.recaf.ui.controls.ActionMenuItem;
import me.coley.recaf.ui.controls.text.selection.*;
import me.coley.recaf.util.LangUtil;
import org.fxmisc.richtext.CodeArea;
import org.fxmisc.richtext.model.TwoDimensional;

import java.util.AbstractMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

import static me.coley.recaf.ui.ContextBuilder.menu;

/**
 * Context menu handler for {@link BytecodeEditorPane}.
 *
 * @author Matt
 */
public class BytecodeContextHandling extends ContextHandling {
	private RootAST root;

	/**
	 * @param controller
	 * 		Controller to use.
	 * @param codeArea
	 * 		Controller to pull info from.
	 */
	public BytecodeContextHandling(GuiController controller, CodeArea codeArea) {
		super(controller, codeArea);
		// Set context selection action
		onContextRequest(selection -> {
			if(selection instanceof ClassSelection) {
				handleClassType((ClassSelection) selection);
			} else if(selection instanceof MemberSelection) {
				handleMemberType((MemberSelection) selection);
			} else if(selection instanceof LabelSelection) {
				handleLabelType((LabelSelection) selection);
			} else if(selection instanceof JumpSelection) {
				handleJumpType((JumpSelection) selection);
			} else if(selection instanceof SwitchSelection) {
				handleSwitchType((SwitchSelection) selection);
			} else if(selection instanceof VariableSelection) {
				handleVariableType((VariableSelection) selection);
			}
		});
	}

	/**
	 * @param ast
	 * 		Analyzed bytecode.
	 */
	public void setAST(RootAST ast) {
		this.root = ast;
	}

	@Override
	protected Object getSelection(TwoDimensional.Position pos) {
		int line = pos.getMajor()+1;
		int offset = pos.getMinor();
		if (root == null)
			return null;
		AST ast = root.getAtLine(line);
		if(ast == null)
			return null;
		// Check for members
		if(ast instanceof MethodInsnAST) {
			MethodInsnAST method = (MethodInsnAST) ast;
			if(offset >= method.getOwner().getStart() && offset <= method.getName().getStart())
				return new ClassSelection(method.getOwner().getType(), false);
			else
				return new MemberSelection(method.getOwner().getType(),
						method.getName().getName(), method.getDesc().getDesc(), false);
		} else if(ast instanceof FieldInsnAST) {
			FieldInsnAST field = (FieldInsnAST) ast;
			if(offset >= field.getOwner().getStart() && offset <= field.getName().getStart())
				return new ClassSelection(field.getOwner().getType(), false);
			else
				return new MemberSelection(field.getOwner().getType(),
						field.getName().getName(), field.getDesc().getDesc(), false);
		}
		// Check for types
		else if(ast instanceof TypeInsnAST) {
			TypeInsnAST type = (TypeInsnAST) ast;
			return new ClassSelection(type.getType().getType(), false);
		}
		// Check for control flow
		else if(ast instanceof LabelAST) {
			LabelAST label = (LabelAST) ast;
			return new LabelSelection(label.getName().getName());
		} else if(ast instanceof JumpInsnAST) {
			JumpInsnAST jump = (JumpInsnAST) ast;
			return new JumpSelection(jump.getLabel().getName());
		} else if(ast instanceof TableSwitchInsnAST) {
			TableSwitchInsnAST swit = (TableSwitchInsnAST) ast;
			Map<String, String> map = new LinkedHashMap<>();
			int value = swit.getRangeMin().getIntValue();
			for(NameAST target : swit.getLabels()) {
				map.put(target.getName(), String.valueOf(value));
				value++;
			}
			return new SwitchSelection(map, swit.getDfltLabel().getName());
		} else if(ast instanceof LookupSwitchInsnAST) {
			LookupSwitchInsnAST swit = (LookupSwitchInsnAST) ast;
			Map<String, String> map = swit.getMapping().entrySet().stream()
					.map(e -> new AbstractMap.SimpleEntry<>(e.getValue().getName(), e.getKey().print()))
					.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> b, LinkedHashMap::new));
			return new SwitchSelection(map, swit.getDfltLabel().getName());
		}
		// Check for variable references
		else if(ast instanceof VarInsnAST) {
			VarInsnAST vari = (VarInsnAST) ast;
			return new VariableSelection(vari.getVariableName().getName());
		}
		return null;
	}

	@Override
	protected Object getCurrentSelection() {
		return null;
	}

	private void handleClassType(ClassSelection selection) {
		codeArea.setContextMenu(menu().controller(controller)
				.declaration(selection.dec)
				.ofClass(selection.name));
	}

	private void handleMemberType(MemberSelection selection) {
		ContextBuilder cb = menu().controller(controller)
				.declaration(selection.dec);
		if (selection.method())
			codeArea.setContextMenu(cb.ofMethod(selection.owner, selection.name, selection.desc));
		else
			codeArea.setContextMenu(cb.ofField(selection.owner, selection.name, selection.desc));
	}

	private void handleLabelType(LabelSelection selection) {
		ContextMenu menu = new ContextMenu();
		Menu refs = new Menu(LangUtil.translate("ui.edit.method.referrers"));
		for (AST ast : root.getChildren()) {
			if ((ast instanceof FlowController && ((FlowController) ast).targets().contains(selection.name)) ||
					(ast instanceof LineInsnAST && ((LineInsnAST) ast).getLabel().getName().equals(selection.name))) {
				MenuItem ref = new ActionMenuItem(ast.getLine() + ": " + ast.print(), () -> {
					int line = ast.getLine() - 1;
					codeArea.moveTo(line, 0);
					codeArea.requestFollowCaret();
				});
				refs.getItems().add(ref);
			}
		}
		if (refs.getItems().isEmpty())
			refs.setDisable(true);
		menu.getItems().add(refs);
		codeArea.setContextMenu(menu);
	}

	private void handleVariableType(VariableSelection selection) {
		ContextMenu menu = new ContextMenu();
		Menu refs = new Menu(LangUtil.translate("ui.edit.method.referrers"));
		for (AST ast : root.getChildren()) {
			if (ast instanceof VarInsnAST && ((VarInsnAST) ast).getVariableName().getName().equals(selection.name)) {
				MenuItem ref = new ActionMenuItem(ast.getLine() + ": " + ast.print(), () -> {
					int line = ast.getLine() - 1;
					codeArea.moveTo(line, 0);
					codeArea.requestFollowCaret();
				});
				refs.getItems().add(ref);
			}
		}
		if (refs.getItems().isEmpty())
			refs.setDisable(true);
		menu.getItems().add(refs);
		codeArea.setContextMenu(menu);
	}

	private void handleJumpType(JumpSelection selection) {
		ContextMenu menu = new ContextMenu();
		MenuItem jump = new ActionMenuItem(LangUtil.translate("ui.edit.method.follow"), () -> {
			for (AST ast : root.getChildren()) {
				if (ast instanceof LabelAST) {
					String name = ((LabelAST) ast).getName().getName();
					if(name.equals(selection.destination)) {
						int line = ast.getLine() - 1;
						codeArea.moveTo(line, 0);
						codeArea.requestFollowCaret();
					}
				}
			}
		});
		menu.getItems().add(jump);
		codeArea.setContextMenu(menu);
	}

	private void handleSwitchType(SwitchSelection selection) {
		ContextMenu menu = new ContextMenu();
		Menu refs = new Menu(LangUtil.translate("ui.edit.method.follow"));
		for(AST ast : root.getChildren()) {
			if(ast instanceof LabelAST) {
				String name = ((LabelAST) ast).getName().getName();
				String key = selection.mappings.get(name);
				if (key == null && name.equals(selection.dflt))
					key = "Default";
				if(key != null) {
					MenuItem ref = new ActionMenuItem(key + ": '" + ast.getLine() + ": " + ast.print() +"'", () -> {
						int line = ast.getLine() - 1;
						codeArea.moveTo(line, 0);
						codeArea.requestFollowCaret();
					});
					refs.getItems().add(ref);
				}
			}
		}
		if(refs.getItems().isEmpty())
			refs.setDisable(true);
		menu.getItems().add(refs);
		codeArea.setContextMenu(menu);
	}
}


text:
public class AnnotationPresentCheckFix {
	@Retention(RetentionPolicy.RUNTIME)  // Annotate the annotation
	public static @interface UntrustedData { }

	@UntrustedData
	public static String getUserData() {
		Scanner scanner = new Scanner(System.in);
		return scanner.nextLine();
	}

	public static void main(String[] args) throws NoSuchMethodException, SecurityException {
		String data = getUserData();
		Method m = AnnotationPresentCheckFix.class.getMethod("getUserData");
		if(m.isAnnotationPresent(UntrustedData.class)) {  // Returns 'true'
			System.out.println("Not trusting data from user.");
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="50dp">

    <Button
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@android:color/holo_orange_light"
        android:gravity="center"
        android:text="Hello World!"
        android:textSize="30sp" />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text"
        android:layout_marginTop="10dp"
        android:background="@android:color/holo_blue_light"
        android:gravity="center"
        android:text="show data"
        android:textSize="30sp" />

</RelativeLayout>


text:
<?php

namespace SM\Bundle\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use SM\Bundle\AdminBundle\Entity\Ciudad;
use SM\Bundle\AdminBundle\Form\Type\CiudadType;

class CiudadController extends Controller
{
    /**
     * Lista y muestra todas las ciudades en forma de paginacion.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $ciudades = $em->getRepository('SMAdminBundle:Ciudad')->findAll();

        // añadimos el paginador
        $paginator = $this->get('knp_paginator');

        $pagination = $paginator->paginate(
            $ciudades,
            $this->get('request')->query->get('page', 1), 10
        );

        return $this->render('SMAdminBundle:Ciudad:index.html.twig', array(
                    'ciudades' => $ciudades,
                    'ciudadesPadinadas' => $pagination
        ));
    }

    /**
     *  Muestra un formulario vacio y crea una nueva ciudad.
     *
     */
    public function newAction()
    {
        $ciudad = new Ciudad();
        $request = $this->getRequest();
        $formulario = $this->createForm(new CiudadType(), $ciudad);

        $formulario->handleRequest($request);

        if ($formulario->isValid())
        {
            $this->get('session')->getFlashBag()->add('success', 'La ciudad ha sido creado correctamente.');

            $em = $this->getDoctrine()->getManager();
            $em->persist($ciudad);
            $em->flush();

            return $this->redirect($this->generateUrl('sm_admin_ciudad_new'));
        }

        return $this->render('SMAdminBundle:Ciudad:new.html.twig', array(
                    'ciudad' => $ciudad,
                    'formulario' => $formulario->createView()
        ));
    }

    /**
     * Muestra un formulario con la información de la ciudad
     * que se desea editar.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();
        $request = $this->getRequest();
        $ciudad = $em->find('SMAdminBundle:Ciudad', $id);

        if (!$ciudad) {
            throw $this->createNotFoundException('No se ha encontrado el ciudad solicitado');
        }

        $formulario = $this->createForm(new CiudadType(), $ciudad, array(
            'action' => $this->generateUrl('sm_admin_ciudad_edit', array('id' => $id)),
            'method' => 'POST',
        ));

        $formulario->handleRequest($request);

        if ($formulario->isValid()) {
            $em->persist($ciudad);
            $em->flush();

            return $this->redirect($this->generateUrl('sm_admin_ciudad'));
        }

        return $this->render('SMAdminBundle:Ciudad:edit.html.twig', array(
                    'ciudad' => $ciudad,
                    'formulario' => $formulario->createView()
        ));
    }

    /**
     * Elimina una ciudad.
     *
     */
    public function deleteAction($id)
    {
        $em = $this->getDoctrine()->getManager();
        $ciudad = $em->find('SMAdminBundle:Ciudad', $id);

        if (!$ciudad) {
            throw $this->createNotFoundException('No se ha encontrado la ciudad solicitado');
        }

        try{
            $em->remove($ciudad);
            $em->flush();
            $this->get('session')->getFlashBag()->add('success', 'Se ha eliminado la ciudad.');
        } catch(\Exception $exc){
            $this->get('session')->getFlashBag()->add('error', 'No se ha podido eliminar la ciudad, tiene ralaciones activas.');
        }

        return $this->redirect($this->generateUrl('sm_admin_ciudad'));
    }

}


text:
<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">

    <title>Kakuro Player</title>

    <canvas id="player" width="0" height="0" style="border:1px solid black; margin-bottom: 0px"></canvas>