text:
import pcs
import payload

class ipv4frag(pcs.packets.payload):
    """A fragment of an IPv4 datagram awaiting reassembly."""

class ipv4sar(object):
    """An IPv4 reassembler."""

    def __init__(self):
        """Construct an ipv4sar object."""
        self.flows = {}

    def reassemble(self, chain, index = None):
        """Attempt to reassemble an IP datagram.

           chain - an IPv4 datagram which may need reassembly.
           index - a hint to the location of the IPv4 header in the chain,
                   otherwise this method looks for the first IPv4 header.

           This method accepts datagrams which don't need reassembly,
           to make it easy to use the reassembler in an expect() loop.
           In that case we just return the datagram.

           Returns a tuple of (chain, num, flushed).
           chain - the reassembled chain, or None if no reassembly done.
           num - the number of fragments used to produce chain
           flushed - the number of fragments garbage collected this pass."""

        # Perform garbage collection pass.
        gc = self.garbage_collect()

        # Locate the IPv4 header in the chain.
        ip = None
        if index is not None:
            ip = chain.packets[index]
            assert isinstance(ip, pcs.packets.ipv4), \
                   "No IPv4 header present in chain."
        else:
            ip = chain.find_first_of(pcs.packets.ipv4)
            assert ip is not None, "No IPv4 header present in chain."

        # If packet is DF or no more fragments expected, don't do anything.
        if (ip.ip_flags & IP_DF):
            return (None, 0, gc)
        if not (ip.ip_flags & IP_MF) and ip.ip_off == 0:
            return (None, 0, gc)

        # Look for this datagram in reassembly queue.
        # If not found, create a new ipv4frag from the payload
        # and create a new queue for this datagram.
        # XXX need to keep old IP header around.
        flowtuple = (ip.id, ip.protocol, ip.src, ip.dst)
        if not flowtuple in self.flows:
            payload = chain.collate_following(ip)
            self.flows[flowtuple] = [ ipv4frag(payload) ]
            return (None, 0, gc)

        # We need to walk the reassembly queue and check we have
        # enough fragments.
        # XXX ordered collections?

        assert False, "Unfinished code."
        return (None, 0, gc)

    def garbage_collect(self):
        """Garbage collect any old entries in the reassembly queue.
           Return the number of fragments """
        return 0

    def ipopt_copied(optno):
        """Given an IPv4 option number, return True if it should be copied
           into any fragments beyond the first fragment of a datagram."""
        return (optno & 0x80) != 0

    def make_fragment_header(ip):
        """Given an IPv4 header possibly with options, return a copy of the
           header which should be used for subsequent fragments."""
        from copy import deepcopy
        # We work on the object representation, NOT the bytes themselves here.
        oldopts = ip.options._options
        newopts = []
        optlen = 0         # in bits
        for opt in nip.options._options:
            # Skip EOLs and NOPs.
            # XXX May break legacy multicast tunnel LSRR alignment.
            if isinstance(opt, pcs.Field):
                continue
            assert isinstance(opt, pcs.TypeLengthValueField)
            if ipopt_copied(opt.type.value):
                newopts.append(opt)
            optlen += opt.width
        # Align options to 32 bits.
        assert optlen <= 44, "IPv4 option space cannot exceed 44 bytes."
        remaining = optlen % 32
        while remaining > 0:
            newopts.append(pcs.Field("eol", 8, default=IPOPT_EOL))
        nip = deepcopy(ip)
        nip.options._options = newopts
        nip.encode()
        assert len(nip.getbytes()) <= 64, "IPv4 header cannot exceed 64 bytes."
        return nip

    def fragment(chain, mtu, index = None):
        """Static method to: fragment a Chain containing an IPv4 header
           and payload to fit into the given MTU.
           It is assumed the caller already accounted for any outer
           encapsulation. The ip_off and flags in chain are ignored.
           Length fields and checksums are NOT calculated.

           index - points to IPv4 header in chain (optional)
           return: a list of Chains containing the fragments, or
                   None if ip had the DF bit set."""

        # Locate the IPv4 header in the chain.
        ip = None
        if index is not None:
            ip = chain.packets[index]
            assert isinstance(ip, pcs.packets.ipv4), \
                   "No IPv4 header present in chain."
        else:
            ip = chain.find_first_of(pcs.packets.ipv4)
            assert ip is not None, "No IPv4 header present in chain."

        # If DF is set, game over.
        if ip.ip_flags & IP_DF:
            return None

        # Collate the payload to be fragmented and calculate its length.
        tmpbytes = chain.collate_following(ip)
        remaining = len(tmpbytes)

        # If existing IP header and payload fit within MTU, no need to
        # do any further work. Otherwise we must fragment it. This
        # doesn't take the headers in front into account, so we'll
        # assume the caller did.
        if mtu >= len(ip.getbytes()) + remaining:
            return [chain]

        # Take a deep copy of the IP header, and construct the
        # fragmentation headers.
        from copy import deepcopy
        fip = deepcopy(ip)		# first IP fragment header
        fip.ip_flags = IP_MF
        assert (len(fip.getbytes()) % 4) == 0, \
               "First IPv4 fragment header not on 4-byte boundary."

        sip = make_fragment_header(fip)	# template IP fragment header
        sip.ip_flags = IP_MF
        assert (len(fip.getbytes()) % 4) == 0, \
               "Subsequent IPv4 fragment header not on 4-byte boundary."

        result = []			# The fragments w/o other headers.

        # The first fragment needs to be calculated separately as it
        # may have a different set of IP options.
        off = 0
        rmtu = mtu - len(fip.getbytes())
        assert rmtu >= 8, "Insufficient MTU for first IPv4 fragment."
        rmtu -= rmtu % 8

        fip.ip_off = 0
        result.append(Chain([fip, ipv4frag(bytes=tmpbytes[:rmtu])]))
        off += rmtu
        remaining -= rmtu

        # Subsequent fragments use a template header. The minimum length
        # of a fragment's payload is 8 bytes. ip_off measures 64-bit words,
        # so each fragment must be on an 8-byte boundary.
        rmtu = mtu - len(sip.getbytes())
        assert rmtu >= 8, "Insufficient MTU for subsequent IPv4 fragments."
        rmtu -= rmtu % 8
        while remaining >= rmtu:
            sip.ip_off = off >> 3
            result.append(Chain([deepcopy(sip), \
                                 ipv4frag(bytes=tmpbytes[off:rmtu])]))
            off += rmtu
            remaining -= rmtu

        # If MF is set in the original packet, then MF is set in all
        # the fragments.
        # If MF is not set in the original packet, then MF is set in
        # every fragment except the last.
        if remaining > 0:
            sip.ip_off = off >> 3
            if not (ip.ip_flags & IP_MF):
                sip.ip_flags = 0
            result.append(Chain([deepcopy(sip), \
                                 ipv4frag(bytes=tmpbytes[off:remaining])]))
            off += remaining
            remaining -= remaining
        assert off == len(tmpbytes), "Did not fragment entire payload."
        assert remaining == 0, "Did not fragment entire payload."

        return result

    ipopt_copied = staticmethod(ipopt_copied)
    make_fragment_header = staticmethod(make_fragment_header)
    fragment = staticmethod(fragment)


text:
package workbench.sql.macros;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import workbench.util.StringUtil;

/**
 * A list of macros combined into a group.
 *

 * A MacroGroup defines a sort order which is essentially maintained
 * through the GUI.
 *

 * Groups can be hidden from the menu.
 *
 * @author Thomas Kellerer
 */
public class MacroGroup
	implements Sortable
{
	private String name;
	private List<MacroDefinition> macros = new ArrayList<>();
	private int sortOrder;
	private boolean modified = false;
	private boolean showInMenu = true;
	private boolean showInPopup = true;

	public MacroGroup()
	{
	}

	public MacroGroup(String groupName)
	{
		this.name = groupName;
	}

	public boolean isVisibleInMenu()
	{
		return showInMenu;
	}

	public void setVisibleInMenu(boolean flag)
	{
		this.modified = modified || flag != showInMenu;
		this.showInMenu = flag;
	}

	public boolean isVisibleInPopup()
	{
		return showInPopup;
	}

  public void setVisibleInPopup(boolean flag)
  {
    this.modified = modified || flag != showInPopup;
    this.showInPopup = flag;
  }

  @Override
  public int getSortOrder()
  {
    return sortOrder;
  }

  @Override
  public void setSortOrder(int order)
  {
    this.modified = modified || sortOrder != order;
    this.sortOrder = order;
  }

  @Override
  public String toString()
  {
    return name;
  }

  public String getName()
  {
    return name;
  }

  public void setName(String macroName)
  {
    modified = modified || StringUtil.stringsAreNotEqual(name, macroName);
    name = macroName;
  }

	public synchronized void addMacro(MacroDefinition macro)
	{
		macros.add(macro);
		applySort();
		modified = true;
	}

	/**
	 * Sorts the macros by name.
	 */
	public synchronized void sortByName()
	{
    Comparator<MacroDefinition> comp = new Comparator<MacroDefinition>()
    {
      @Override
      public int compare(MacroDefinition o1, MacroDefinition o2)
      {
        if (o1 == null && o2 == null) return 0;
        if (o1 == null) return -1;
        if (o2 == null) return 1;
        return o1.getName().compareToIgnoreCase(o2.getName());
      }
    };

    Collections.sort(macros, comp);
    for (int i=0; i < macros.size(); i++)
    {
      macros.get(i).setSortOrder(i);
    }
  }

	/**
	 * Synchronizes the sort order of each macro with the
	 * order of the List in which the macros are stored.
	 */
	public synchronized void applySort()
	{
		Collections.sort(macros, new Sorter());
		for (int i=0; i < macros.size(); i++)
		{
			macros.get(i).setSortOrder(i);
		}
	}

  /**
   * Returns those macros that are set to "display in menu" (i.e. where MacroDefinition.isVisibleInMenu()
   * returns true.
   *

   * This ignores the isVisibleInMenu() setting of this group.
   *
   * @see #getVisibleMacroSize()
   * @see MacroDefinition#isVisibleInMenu() ()
   */
  public synchronized List<MacroDefinition> getVisibleMacros()
  {
    List<MacroDefinition> result = new ArrayList<>(macros.size());
    for (MacroDefinition macro : macros)
    {
      if (macro.isVisibleInMenu())
      {
        result.add(macro);
      }
    }
    return result;
  }

	/**
	 * Returns those macros that should be shown in the "Macro Popup" window.
	 * returns true.
	 *

	 * This ignores the isVisibleInMenu() setting of this group.
	 *
	 * @see #getVisibleMacroSize()
	 * @see MacroDefinition#isVisibleInPopup()
	 */
	public synchronized List<MacroDefinition> getMacrosForPopup()
	{
		List<MacroDefinition> result = new ArrayList<>(macros.size());
		for (MacroDefinition macro : macros)
		{
			if (macro.isVisibleInPopup())
			{
				result.add(macro);
			}
		}
		return result;
	}

	/**
	 * Sets the list of macros for this group.
	 *
	 * This method is only here to make the class serializable for the XMLEncoder and should
	 * not be used directly.
	 *
	 * @param newMacros
	 */
	public synchronized void setMacros(List<MacroDefinition> newMacros)
	{
		macros.clear();
		macros.addAll(newMacros);
		applySort();
		modified = false;
	}

	public synchronized List<MacroDefinition> getMacros()
	{
		return macros;
	}

	public synchronized void removeMacro(MacroDefinition macro)
	{
		macros.remove(macro);
		modified = true;
	}

	/**
	 * Creates a deep copy of this group.
	 * For each macro definition that is part of this group, a copy
	 * is created and added to the list of macros of the copy.
	 *
	 * The copy will be marked as "not modified" (i.e. isModified() will
	 * return false on the copy), even if this group is modified.
	 *
	 * @return a deep copy of this group
	 * @see MacroDefinition#createCopy()
	 */
	public MacroGroup createCopy()
	{
		MacroGroup copy = new MacroGroup();
		copy.name = this.name;
		copy.sortOrder = this.sortOrder;
		copy.showInMenu = this.showInMenu;
		copy.showInPopup = this.showInPopup;
		copy.modified = false;
		for (MacroDefinition def : macros)
		{
			copy.macros.add(def.createCopy());
		}
		return copy;
	}

	/**
	 * Checks if this group has been modified.
	 *
	 * Returns true if any attribute of this group has been changed
	 * or if any MacroDefinition in this group has been changed.
	 *
	 * @return true, if this group or any Macro has been modified
	 * @see MacroDefinition#isModified()
	 */
	public boolean isModified()
	{
		if (modified) return true;
		for (MacroDefinition macro : macros)
		{
			if (macro.isModified()) return true;
		}
		return false;
	}

	/**
	 * Resets the internal modified flag and on all macros that are in this group.
	 *
	 * After a call to this method, isModified() will return false;
	 */
	public void resetModified()
	{
		modified = false;
		for (MacroDefinition macro : macros)
		{
			macro.resetModified();
		}
	}

	/**
	 * Returns the number of macros in this groups that should be displayed in the menu.
	 *
	 * This returns a non-zero count even if isVisibleInMenu() returns false!
	 * @see #getVisibleMacros()
	 */
	public int getVisibleMacroSize()
	{
		int size = 0;
		for (MacroDefinition def : macros)
		{
			if (def.isVisibleInMenu()) size ++;
		}
		return size;
	}

	public int getSize()
	{
		return macros.size();
	}

	@Override
	public boolean equals(Object obj)
	{
		if (obj == null)
		{
			return false;
		}
		if (getClass() != obj.getClass())
		{
			return false;
		}
		final MacroGroup other = (MacroGroup) obj;
		if ((this.name == null) ? (other.name != null) : !this.name.equalsIgnoreCase(other.name))
		{
			return false;
		}
		return true;
	}

	@Override
	public int hashCode()
	{
		int hash = 7;
		hash = 19 * hash + (this.name != null ? this.name.toLowerCase().hashCode() : 0);
		return hash;
	}

}

redpajama_set_name: RedPajamaGithub


text:
package com.hendrix.erdos.algorithms;

import com.hendrix.erdos.exceptions.AlgorithmException;
import com.hendrix.erdos.exceptions.NotDirectedAcyclicGraphException;
import com.hendrix.erdos.types.IVertex;
import com.hendrix.erdos.graphs.IDirectedGraph;

import java.util.LinkedList;

/**
 * computes a Topological Sort of input Graph G
 * @author Tomer Shalev
 */
public class TopologicalSort extends AbstractGraphAlgorithm<LinkedList<IVertex>, IDirectedGraph> {

    public TopologicalSort(IDirectedGraph graph_input) {
        super(graph_input, "TopologicalSort");
    }

    /**
     *
     * @return a {@code LinkedList} that represents the {@code topological order}.
     *
     * @throws NotDirectedAcyclicGraphException if there are cycles
     */
    @Override
    public LinkedList<IVertex> applyAlgorithm() throws NotDirectedAcyclicGraphException{
        if(_graph_input==null)
            throw new AlgorithmException("_graph_input==null", this);

        sort();

        return _result_algorithm;
    }

    protected void sort()
    {
        DFS.DepthFirstForest dff = new DFS(_graph_input).applyAlgorithm();

        if(dff.isFlagContainsCycle())
            throw new NotDirectedAcyclicGraphException(this);

        _result_algorithm = dff.get_F_SORTED();
    }

}


text:
#include "RenderQuadComponent.h"
#include "SceneObject.h"
#include "Renderer.h"
#include "Utils.h"

namespace af
{
    RenderQuadComponent::RenderQuadComponent(const Points& points,
                                             const DrawablePtr& drawable,
                                             int zOrder)
    : RenderComponent(zOrder),
      drawable_(drawable),
      prevAngle_(0.0f),
      cookie_(0)
    {
        assert(points.size() == 4);

        if (points.size() != 4) {
            throw std::runtime_error("RenderQuadComponent: points.size() != 4");
        }

        std::copy(points.begin(), points.end(), points_);
    }

    RenderQuadComponent::~RenderQuadComponent()
    {
    }

    void RenderQuadComponent::accept(ComponentVisitor& visitor)
    {
        visitor.visitRenderComponent(shared_from_this());
    }

    void RenderQuadComponent::update(float dt)
    {
        if ((parent()->smoothPos() == prevPos_) &&
            (parent()->smoothAngle() == prevAngle_)) {
            return;
        }

        b2AABB aabb = updateVertices();

        b2AABB combinedAABB;

        combinedAABB.Combine(prevAABB_, aabb);

        b2Vec2 displacement = parent()->smoothPos() - prevPos_;

        manager()->moveAABB(cookie_, combinedAABB, displacement);

        prevPos_ = parent()->smoothPos();
        prevAngle_ = parent()->smoothAngle();
        prevAABB_ = aabb;
    }

    void RenderQuadComponent::render(const std::vector<void*>& parts)
    {
        RenderSimple rop = renderer.renderTriangles(drawable_->image().texture());

        rop.addVertices(&vertices_[0], 6);
        rop.addTexCoords(drawable_->image().texCoords(), 6);

        rop.finish();
    }

    void RenderQuadComponent::onRegister()
    {
        prevPos_ = parent()->smoothPos();
        prevAngle_ = parent()->smoothAngle();
        prevAABB_ = updateVertices();
        cookie_ = manager()->addAABB(this, prevAABB_, NULL);
    }

    void RenderQuadComponent::onUnregister()
    {
        manager()->removeAABB(cookie_);
    }

    b2AABB RenderQuadComponent::updateVertices()
    {
        const b2Transform& xf = parent()->getSmoothTransform();
        b2Vec2 tmp[4];

        vertices_.clear();

        for (size_t i = 0; i < sizeof(points_)/sizeof(points_[0]); ++i) {
            tmp[i] = b2Mul(xf, points_[i]);
            appendTriangles(vertices_, tmp[i].x, tmp[i].y);
        }

        return computeAABB(&tmp[0], sizeof(tmp)/sizeof(tmp[0]));
    }
}


text:
#ifndef INCLUDE_odb_h__
#define INCLUDE_odb_h__

#include "git2/odb.h"
#include "git2/oid.h"
#include "git2/types.h"

#include "vector.h"
#include "cache.h"
#include "posix.h"
#include "filter.h"

#define GIT_OBJECTS_DIR "objects/"
#define GIT_OBJECT_DIR_MODE 0777
#define GIT_OBJECT_FILE_MODE 0444

/* DO NOT EXPORT */
typedef struct {
	void *data;			/**< Raw, decompressed object data. */
	size_t len;			/**< Total number of bytes in data. */
	git_otype type;		/**< Type of this object. */
} git_rawobj;

/* EXPORT */
struct git_odb_object {
	git_cached_obj cached;
	void *buffer;
};

/* EXPORT */
struct git_odb {
	git_refcount rc;
	git_vector backends;
	git_cache own_cache;
};

/*
 * Hash a git_rawobj internally.
 * The `git_rawobj` is supposed to be previously initialized
 */
int git_odb__hashobj(git_oid *id, git_rawobj *obj);

/*
 * Format the object header such as it would appear in the on-disk object
 */
int git_odb__format_object_header(char *hdr, size_t n, git_off_t obj_len, git_otype obj_type);
/*
 * Hash an open file descriptor.
 * This is a performance call when the contents of a fd need to be hashed,
 * but the fd is already open and we have the size of the contents.
 *
 * Saves us some `stat` calls.
 *
 * The fd is never closed, not even on error. It must be opened and closed
 * by the caller
 */
int git_odb__hashfd(git_oid *out, git_file fd, size_t size, git_otype type);

/*
 * Hash an open file descriptor applying an array of filters
 * Acts just like git_odb__hashfd with the addition of filters...
 */
int git_odb__hashfd_filtered(
	git_oid *out, git_file fd, size_t len, git_otype type, git_filter_list *fl);

/*
 * Hash a `path`, assuming it could be a POSIX symlink: if the path is a
 * symlink, then the raw contents of the symlink will be hashed. Otherwise,
 * this will fallback to `git_odb__hashfd`.
 *
 * The hash type for this call is always `GIT_OBJ_BLOB` because symlinks may
 * only point to blobs.
 */
int git_odb__hashlink(git_oid *out, const char *path);

/*
 * Generate a GIT_ENOTFOUND error for the ODB.
 */
int git_odb__error_notfound(const char *message, const git_oid *oid);

/*
 * Generate a GIT_EAMBIGUOUS error for the ODB.
 */
int git_odb__error_ambiguous(const char *message);

/*
 * Attempt to read object header or just return whole object if it could
 * not be read.
 */
int git_odb__read_header_or_object(
	git_odb_object **out, size_t *len_p, git_otype *type_p,
	git_odb *db, const git_oid *id);

/* fully free the object; internal method, DO NOT EXPORT */
void git_odb_object__free(void *object);

#endif


text:
package git4idea.commands;

import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * The listener of {@link git4idea.commands.GitLineHandler} which watches Git output and detects some message in console,
 * captures the following list of files and stops saving them when another message occurs.
 *
 * For example, the situation, when local changes would be overwritten by checkout.
 *
 * @see GitSimpleEventDetector
 * @author Kirill Likhodedov
 */
public class GitMessageWithFilesDetector implements GitLineHandlerListener {

  private final Event myEvent;
  private final VirtualFile myRoot;

  protected final Set<String> myAffectedFiles = new HashSet<>();
  protected boolean myMessageDetected;
  private boolean myFilesAreDisplayed;

  public GitMessageWithFilesDetector(@NotNull Event event, @NotNull VirtualFile root) {
    myEvent = event;
    myRoot = root;
  }

  @Override
  public void onLineAvailable(@NotNull String line, @NotNull Key outputType) {
    if (line.contains(myEvent.getMessageStartMarker())) {
      myMessageDetected = true;
      myFilesAreDisplayed = true;
    }
    else if (line.contains(myEvent.getMessageEndMarker())) {
      myFilesAreDisplayed = false;
    }
    else if (myFilesAreDisplayed) {
      myAffectedFiles.add(line.trim());
    }
  }

  @Override
  public void processTerminated(int exitCode) {
  }

  @Override
  public void startFailed(Throwable exception) {
  }

  /**
   * @return if the error "Your local changes to the following files would be overwritten by checkout" has happened.
   */
  public boolean wasMessageDetected() {
    return myMessageDetected;
  }

  /**
   * @return the set of files (maybe empty) that would be overwritten by checkout, as told by Git.
   */
  @NotNull
  public Set<String> getRelativeFilePaths() {
    return myAffectedFiles;
  }

  @NotNull
  public Collection<VirtualFile> getFiles() {
    Collection<VirtualFile> files = new ArrayList<>(myAffectedFiles.size());
    for (String affectedFile : myAffectedFiles) {
      VirtualFile file = myRoot.findFileByRelativePath(FileUtil.toSystemIndependentName(affectedFile));
      if (file != null) {
        files.add(file);
      }
    }
    return files;
  }

  public static class Event {
    private final String myMessageStartMarker;
    private final String myMessageEndMarker;

    Event(String messageStartMarker, String messageEndMarker) {
      myMessageStartMarker = messageStartMarker;
      myMessageEndMarker = messageEndMarker;
    }

    public String getMessageStartMarker() {
      return myMessageStartMarker;
    }

    public String getMessageEndMarker() {
      return myMessageEndMarker;
    }
  }

}


text:
package implementer

import (
	"fmt"

	"github.com/nuagenetworks/nuage-kubernetes/nuagekubemon/pkg/policyapi/policies"
	"github.com/nuagenetworks/vspk-go/vspk"
)

func (implementer *PolicyImplementer) processDefaultPolicy(policy *policies.NuagePolicy) error {

	enterprise, err := implementer.getEnterprise(policy.Enterprise)
	if err != nil || enterprise == nil {
		return fmt.Errorf("Problem fetching the enterprise")
	}

	domain, err := implementer.getDomain(enterprise, policy.Domain)
	if err != nil || domain == nil {
		return fmt.Errorf("Problem fetching the domain")
	}

	ingressACL, egressACL := createACLTemplates(policy)

	var ingressACLEnteries []*vspk.IngressACLEntryTemplate
	var egressACLEnteries []*vspk.EgressACLEntryTemplate
	var aclerr error
	if ingressACLEnteries, egressACLEnteries, aclerr = implementer.getACLEntriesFromPolicy(policy); aclerr != nil {
		return aclerr
	}

	var policyTransac policyTransaction
	policyTransac.err = startpolicyTransaction(domain)

	if policyTransac.err != nil {
		return fmt.Errorf("Unable to start policy transaction %+v", policyTransac.err)
	}

	defer endpolicyTransaction(domain, &policyTransac)

	policyTransac.err = domain.CreateIngressACLTemplate(ingressACL)
	if policyTransac.err != nil {
		return fmt.Errorf("Unable to create Ingress ACL template %+v", policyTransac.err)
	}

	policyTransac.err = domain.CreateEgressACLTemplate(egressACL)
	if policyTransac.err != nil {
		return fmt.Errorf("Unable to create Egress ACL template %+v", policyTransac.err)
	}

	for _, ingressACLEntry := range ingressACLEnteries {
		policyTransac.err = ingressACL.CreateIngressACLEntryTemplate(ingressACLEntry)
		if policyTransac.err != nil {
			return fmt.Errorf("Unable to create ingress ACL entry %+v %+v", policyTransac.err, ingressACLEntry)
		}
	}

	for _, egressACLEntry := range egressACLEnteries {
		policyTransac.err = egressACL.CreateEgressACLEntryTemplate(egressACLEntry)
		if policyTransac.err != nil {
			return fmt.Errorf("Unable to create egress ACL entry %+v %+v", policyTransac.err, egressACLEntry)
		}
	}

	policyTransac.err = nil
	return nil
}

// ImplementPolicy implements a Nuage policy
func (implementer *PolicyImplementer) ImplementPolicy(policy *policies.NuagePolicy) error {

	if policy.Type != policies.Default {
		return fmt.Errorf("Invalid policy")
	}

	switch policy.PolicyElements.(type) {
	case []policies.DefaultPolicyElement:
		return implementer.processDefaultPolicy(policy)
	default:
		return fmt.Errorf("Invalid policy elements")
	}
}


text:
"use strict";
const index_1 = require("./index");
module.exports = index_1.default;


text:
<?php

/** @var $installer Mage_Catalog_Model_Resource_Setup */
$installer = $this;
$connection = $installer->getConnection();

$priceIndexerTables = array(
    'bundle/price_indexer_idx',
    'bundle/price_indexer_tmp',
);

$optionsPriceIndexerTables = array(
    'bundle/option_indexer_idx',
    'bundle/option_indexer_tmp',
);

$selectionPriceIndexerTables = array(
    'bundle/selection_indexer_idx',
    'bundle/selection_indexer_tmp',
);

foreach ($priceIndexerTables as $table) {
    $connection->addColumn($installer->getTable($table), 'group_price', array(
        'type'      => Varien_Db_Ddl_Table::TYPE_DECIMAL,
        'length'    => '12,4',
        'comment'   => 'Group price',
    ));
    $connection->addColumn($installer->getTable($table), 'base_group_price', array(
        'type'      => Varien_Db_Ddl_Table::TYPE_DECIMAL,
        'length'    => '12,4',
        'comment'   => 'Base Group Price',
    ));
    $connection->addColumn($installer->getTable($table), 'group_price_percent', array(
        'type'      => Varien_Db_Ddl_Table::TYPE_DECIMAL,
        'length'    => '12,4',
        'comment'   => 'Group Price Percent',
    ));
}

foreach (array_merge($optionsPriceIndexerTables, $selectionPriceIndexerTables) as $table) {
    $connection->addColumn($installer->getTable($table), 'group_price', array(
        'type'      => Varien_Db_Ddl_Table::TYPE_DECIMAL,
        'length'    => '12,4',
        'comment'   => 'Group price',
    ));
}

foreach ($optionsPriceIndexerTables as $table) {
    $connection->addColumn($installer->getTable($table), 'alt_group_price', array(
        'type'      => Varien_Db_Ddl_Table::TYPE_DECIMAL,
        'length'    => '12,4',
        'comment'   => 'Alt Group Price',
    ));
}

$applyTo = explode(',', $installer->getAttribute(Mage_Catalog_Model_Product::ENTITY, 'group_price', 'apply_to'));
if (!in_array('bundle', $applyTo)) {
    $applyTo[] = 'bundle';
    $installer->updateAttribute(Mage_Catalog_Model_Product::ENTITY, 'group_price', 'apply_to', implode(',', $applyTo));
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ColumnFamilyStoreMBean (apache-cassandra API)</title>
<meta name="date" content="2014-11-05">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.cassandra.db

Interface ColumnFamilyStoreMBean

All Known Implementing Classes:

ColumnFamilyStore

public interface ColumnFamilyStoreMBean

The MBean interface for ColumnFamilyStore

Method Summary

Methods

Modifier and Type
Method and Description

long
estimateKeys()

void
forceMajorCompaction()

force a major compaction of this column family

long
getBloomFilterDiskSpaceUsed()

Deprecated.

long
getBloomFilterFalsePositives()

Deprecated.

double
getBloomFilterFalseRatio()

Deprecated.

java.util.List<java.lang.String>
getBuiltIndexes()

Returns a list of the names of the built column indexes for current store

java.lang.String
getColumnFamilyName()

java.lang.String
getCompactionStrategyClass()

Gets the compaction strategy class name

java.util.Map<java.lang.String,java.lang.String>
getCompressionParameters()

Get the compression parameters

double
getCompressionRatio()

Deprecated.

double
getDroppableTombstoneRatio()

Get the ratio of droppable tombstones to real columns (and non-droppable tombstones)

long[]
getEstimatedColumnCountHistogram()

Deprecated.

long[]
getEstimatedRowSizeHistogram()

Deprecated.

long[]
getLifetimeReadLatencyHistogramMicros()

Deprecated.

long[]
getLifetimeWriteLatencyHistogramMicros()

Deprecated.

double
getLiveCellsPerSlice()

Deprecated.

long
getLiveDiskSpaceUsed()

Deprecated.

int
getLiveSSTableCount()

Deprecated.

int
getMaximumCompactionThreshold()

Gets the maximum number of sstables in queue before compaction kicks off

long
getMaxRowSize()

Deprecated.

long
getMeanRowSize()

Deprecated.

long
getMemtableColumnsCount()

Deprecated.

long
getMemtableDataSize()

Deprecated.

int
getMemtableSwitchCount()

Deprecated.

int
getMinimumCompactionThreshold()

Gets the minimum number of sstables in queue before compaction kicks off

long
getMinRowSize()

Deprecated.

int
getPendingTasks()

Deprecated.

long
getReadCount()

Deprecated.

long
getRecentBloomFilterFalsePositives()

Deprecated.

double
getRecentBloomFilterFalseRatio()

Deprecated.

long[]
getRecentReadLatencyHistogramMicros()

Deprecated.

double
getRecentReadLatencyMicros()

Deprecated.

long[]
getRecentSSTablesPerReadHistogram()

Deprecated.

long[]
getRecentWriteLatencyHistogramMicros()

Deprecated.

double
getRecentWriteLatencyMicros()

Deprecated.

int[]
getSSTableCountPerLevel()

java.util.List<java.lang.String>
getSSTablesForKey(java.lang.String key)

Returns a list of filenames that contain the given key on this node

long[]
getSSTablesPerReadHistogram()

Deprecated.

double
getTombstonesPerSlice()

Deprecated.

long
getTotalDiskSpaceUsed()

Deprecated.

long
getTotalReadLatencyMicros()

Deprecated.

long
getTotalWriteLatencyMicros()

Deprecated.

int
getUnleveledSSTables()

long
getWriteCount()

Deprecated.

boolean
isAutoCompactionDisabled()

void
loadNewSSTables()

Scan through Keyspace/ColumnFamily's data directory
 determine which SSTables should be loaded and load them

void
setCompactionStrategyClass(java.lang.String className)

Sets the compaction strategy by class name

void
setCompactionThresholds(int minThreshold,
                       int maxThreshold)

Sets the maximum and maximum number of SSTables in queue before compaction kicks off

void
setCompressionParameters(java.util.Map<java.lang.String,java.lang.String> opts)

Set the compression parameters

void
setCrcCheckChance(double crcCheckChance)

Set new crc check chance

void
setMaximumCompactionThreshold(int threshold)

Sets the maximum number of sstables in queue before compaction kicks off

void
setMinimumCompactionThreshold(int threshold)

Sets the minimum number of sstables in queue before compaction kicks off

long
trueSnapshotsSize()

Method Detail

getColumnFamilyName

java.lang.String getColumnFamilyName()

Returns:

the name of the column family

getMemtableDataSize

@Deprecated
long getMemtableDataSize()

Deprecated.

Returns the total amount of data stored in the memtable, including
 column related overhead.

Returns:

The size in bytes.

See Also:

ColumnFamilyMetrics.memtableOnHeapSize

getMemtableColumnsCount

@Deprecated
long getMemtableColumnsCount()

Deprecated.

Returns the total number of columns present in the memtable.

Returns:

The number of columns.

See Also:

ColumnFamilyMetrics.memtableColumnsCount

getMemtableSwitchCount

@Deprecated
int getMemtableSwitchCount()

Deprecated.

Returns the number of times that a flush has resulted in the
 memtable being switched out.

Returns:

the number of memtable switches

See Also:

ColumnFamilyMetrics.memtableSwitchCount

getRecentSSTablesPerReadHistogram

@Deprecated
long[] getRecentSSTablesPerReadHistogram()

Deprecated.

Returns:

a histogram of the number of sstable data files accessed per read: reading this property resets it

See Also:

ColumnFamilyMetrics.recentSSTablesPerRead

getSSTablesPerReadHistogram

@Deprecated
long[] getSSTablesPerReadHistogram()

Deprecated.

Returns:

a histogram of the number of sstable data files accessed per read

See Also:

ColumnFamilyMetrics.sstablesPerReadHistogram

getReadCount

@Deprecated
long getReadCount()

Deprecated.

Returns:

the number of read operations on this column family

See Also:

ColumnFamilyMetrics.readLatency

getTotalReadLatencyMicros

@Deprecated
long getTotalReadLatencyMicros()

Deprecated.

Returns:

total read latency (divide by getReadCount() for average)

See Also:

ColumnFamilyMetrics.readLatency

getLifetimeReadLatencyHistogramMicros

@Deprecated
long[] getLifetimeReadLatencyHistogramMicros()

Deprecated.

Returns:

an array representing the latency histogram

See Also:

ColumnFamilyMetrics.readLatency

getRecentReadLatencyHistogramMicros

@Deprecated
long[] getRecentReadLatencyHistogramMicros()

Deprecated.

Returns:

an array representing the latency histogram

See Also:

ColumnFamilyMetrics.readLatency

getRecentReadLatencyMicros

@Deprecated
double getRecentReadLatencyMicros()

Deprecated.

Returns:

average latency per read operation since the last call

See Also:

ColumnFamilyMetrics.readLatency

getWriteCount

@Deprecated
long getWriteCount()

Deprecated.

Returns:

the number of write operations on this column family

See Also:

ColumnFamilyMetrics.writeLatency

getTotalWriteLatencyMicros

@Deprecated
long getTotalWriteLatencyMicros()

Deprecated.

Returns:

total write latency (divide by getReadCount() for average)

See Also:

ColumnFamilyMetrics.writeLatency

getLifetimeWriteLatencyHistogramMicros

@Deprecated
long[] getLifetimeWriteLatencyHistogramMicros()

Deprecated.

Returns:

an array representing the latency histogram

See Also:

ColumnFamilyMetrics.writeLatency

getRecentWriteLatencyHistogramMicros

@Deprecated
long[] getRecentWriteLatencyHistogramMicros()

Deprecated.

Returns:

an array representing the latency histogram

See Also:

ColumnFamilyMetrics.writeLatency

getRecentWriteLatencyMicros

@Deprecated
double getRecentWriteLatencyMicros()

Deprecated.

Returns:

average latency per write operation since the last call

See Also:

ColumnFamilyMetrics.writeLatency

getPendingTasks

@Deprecated
int getPendingTasks()

Deprecated.

Returns:

the estimated number of tasks pending for this column family

See Also:

ColumnFamilyMetrics.pendingFlushes

getLiveSSTableCount

@Deprecated
int getLiveSSTableCount()

Deprecated.

Returns:

the number of SSTables on disk for this CF

See Also:

ColumnFamilyMetrics.liveSSTableCount

getLiveDiskSpaceUsed

@Deprecated
long getLiveDiskSpaceUsed()

Deprecated.

Returns:

disk space used by SSTables belonging to this CF

See Also:

ColumnFamilyMetrics.liveDiskSpaceUsed

getTotalDiskSpaceUsed

@Deprecated
long getTotalDiskSpaceUsed()

Deprecated.

Returns:

total disk space used by SSTables belonging to this CF, including obsolete ones waiting to be GC'd

See Also:

ColumnFamilyMetrics.totalDiskSpaceUsed

forceMajorCompaction

void forceMajorCompaction()
                          throws java.util.concurrent.ExecutionException,
                                 java.lang.InterruptedException

force a major compaction of this column family

Throws:

java.util.concurrent.ExecutionException

java.lang.InterruptedException

getMinRowSize

@Deprecated
long getMinRowSize()

Deprecated.

Returns:

the size of the smallest compacted row

See Also:

ColumnFamilyMetrics.minRowSize

getMaxRowSize

@Deprecated
long getMaxRowSize()

Deprecated.

Returns:

the size of the largest compacted row

See Also:

ColumnFamilyMetrics.maxRowSize

getMeanRowSize

@Deprecated
long getMeanRowSize()

Deprecated.

Returns:

the average row size across all the sstables

See Also:

ColumnFamilyMetrics.meanRowSize

getBloomFilterFalsePositives

@Deprecated
long getBloomFilterFalsePositives()

Deprecated.

See Also:

ColumnFamilyMetrics.bloomFilterFalsePositives

getRecentBloomFilterFalsePositives

@Deprecated
long getRecentBloomFilterFalsePositives()

Deprecated.

See Also:

ColumnFamilyMetrics.recentBloomFilterFalsePositives

getBloomFilterFalseRatio

@Deprecated
double getBloomFilterFalseRatio()

Deprecated.

See Also:

ColumnFamilyMetrics.bloomFilterFalseRatio

getRecentBloomFilterFalseRatio

@Deprecated
double getRecentBloomFilterFalseRatio()

Deprecated.

See Also:

ColumnFamilyMetrics.recentBloomFilterFalseRatio

getBloomFilterDiskSpaceUsed

@Deprecated
long getBloomFilterDiskSpaceUsed()

Deprecated.

See Also:

ColumnFamilyMetrics.bloomFilterDiskSpaceUsed

getMinimumCompactionThreshold

int getMinimumCompactionThreshold()

Gets the minimum number of sstables in queue before compaction kicks off

setMinimumCompactionThreshold

void setMinimumCompactionThreshold(int threshold)

Sets the minimum number of sstables in queue before compaction kicks off

getMaximumCompactionThreshold

int getMaximumCompactionThreshold()

Gets the maximum number of sstables in queue before compaction kicks off

setCompactionThresholds

void setCompactionThresholds(int minThreshold,
                           int maxThreshold)

Sets the maximum and maximum number of SSTables in queue before compaction kicks off

setMaximumCompactionThreshold

void setMaximumCompactionThreshold(int threshold)

Sets the maximum number of sstables in queue before compaction kicks off

setCompactionStrategyClass

void setCompactionStrategyClass(java.lang.String className)

Sets the compaction strategy by class name

Parameters:

className - the name of the compaction strategy class

getCompactionStrategyClass

java.lang.String getCompactionStrategyClass()

Gets the compaction strategy class name

getCompressionParameters

java.util.Map<java.lang.String,java.lang.String> getCompressionParameters()

Get the compression parameters

setCompressionParameters

void setCompressionParameters(java.util.Map<java.lang.String,java.lang.String> opts)

Set the compression parameters

Parameters:

opts - map of string names to values

setCrcCheckChance

void setCrcCheckChance(double crcCheckChance)

Set new crc check chance

isAutoCompactionDisabled

boolean isAutoCompactionDisabled()

getTombstonesPerSlice

@Deprecated
double getTombstonesPerSlice()

Deprecated.

Number of tombstoned cells retreived during the last slicequery

getLiveCellsPerSlice

@Deprecated
double getLiveCellsPerSlice()

Deprecated.

Number of live cells retreived during the last slicequery

estimateKeys

long estimateKeys()

getEstimatedRowSizeHistogram

@Deprecated
long[] getEstimatedRowSizeHistogram()

Deprecated.

See Also:

ColumnFamilyMetrics.estimatedRowSizeHistogram

getEstimatedColumnCountHistogram

@Deprecated
long[] getEstimatedColumnCountHistogram()

Deprecated.

See Also:

ColumnFamilyMetrics.estimatedColumnCountHistogram

getCompressionRatio

@Deprecated
double getCompressionRatio()

Deprecated.

See Also:

ColumnFamilyMetrics.compressionRatio

getBuiltIndexes

java.util.List<java.lang.String> getBuiltIndexes()

Returns a list of the names of the built column indexes for current store

Returns:

list of the index names

getSSTablesForKey

java.util.List<java.lang.String> getSSTablesForKey(java.lang.String key)

Returns a list of filenames that contain the given key on this node

Parameters:

key -

Returns:

list of filenames containing the key

loadNewSSTables

void loadNewSSTables()

Scan through Keyspace/ColumnFamily's data directory
 determine which SSTables should be loaded and load them

getUnleveledSSTables

int getUnleveledSSTables()

Returns:

the number of SSTables in L0.  Always return 0 if Leveled compaction is not enabled.

getSSTableCountPerLevel

int[] getSSTableCountPerLevel()

Returns:

sstable count for each level. null unless leveled compaction is used.
         array index corresponds to level(int[0] is for level 0, ...).

getDroppableTombstoneRatio

double getDroppableTombstoneRatio()

Get the ratio of droppable tombstones to real columns (and non-droppable tombstones)

Returns:

ratio

trueSnapshotsSize

long trueSnapshotsSize()

Returns:

the size of SSTables in "snapshots" subdirectory which aren't live anymore

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2014 The Apache Software Foundation


text:
SRC=term2048
VENV=./venv
BINPREFIX=$(VENV)/bin/

PIP=$(BINPREFIX)pip

COVERFILE:=.coverage
COVERAGE_REPORT:=report -m

PY_VERSION:=$(subst ., ,$(shell python --version 2>&1 | cut -d' ' -f2))
PY_VERSION_MAJOR:=$(word 1,$(PY_VERSION))
PY_VERSION_MINOR:=$(word 2,$(PY_VERSION))
PY_VERSION_SHORT:=$(PY_VERSION_MAJOR).$(PY_VERSION_MINOR)

ifdef TRAVIS_PYTHON_VERSION
PY_VERSION_SHORT:=$(TRAVIS_PYTHON_VERSION)
endif

.DEFAULT: check-versions
.PHONY: check check-versions stylecheck covercheck

deps: $(VENV)
	$(PIP) install -r requirements.txt
ifeq ($(PY_VERSION_SHORT),2.6)
	$(PIP) install -r py26-requirements.txt
endif
ifeq ($(PY_VERSION_MAJOR),2)
	$(PIP) install wsgiref==0.1.2
endif

$(VENV):
	virtualenv --python python2 $@

check: deps
	$(BINPREFIX)python tests/test.py

check-versions: deps
	$(BINPREFIX)tox

stylecheck: deps
	$(BINPREFIX)pep8 $(SRC)

covercheck: deps
	$(BINPREFIX)coverage run --source=term2048 tests/test.py
	$(BINPREFIX)coverage $(COVERAGE_REPORT)

coverhtml:
	@$(MAKE) COVERAGE_REPORT=html BINPREFIX=$(BINPREFIX) covercheck
	@echo '--> open htmlcov/index.html'

clean:
	rm -f *~ */*~
	rm -f $(COVERFILE)

sdist: deps check-versions
	$(BINPREFIX)python setup.py sdist

publish: deps check-versions
	$(BINPREFIX)python setup.py sdist upload


text:
import Router from 'koa-router'
import feedController from '../controllers/feedController'

const router = new Router()

router.post('/', feedController.create)
router.get('/', feedController.listAll)

router.put('/:id', feedController.subscribe)
router.get('/:id', feedController.list)
router.delete('/:id', feedController.unsubscribe)

export default router


text:
/**
 * @author Anatoly F. Bondarenko
 */

/**
 * Created on 28.02.2005
 */
package org.apache.harmony.jpda.tests.jdwp.ObjectReference;

import org.apache.harmony.jpda.tests.framework.jdwp.CommandPacket;
import org.apache.harmony.jpda.tests.framework.jdwp.JDWPCommands;
import org.apache.harmony.jpda.tests.framework.jdwp.JDWPConstants;
import org.apache.harmony.jpda.tests.framework.jdwp.ReplyPacket;
import org.apache.harmony.jpda.tests.framework.jdwp.Value;
import org.apache.harmony.jpda.tests.jdwp.share.JDWPSyncTestCase;
import org.apache.harmony.jpda.tests.share.JPDADebuggeeSynchronizer;

/**
 * JDWP Unit test for ObjectReference.GetValues command .
 */
public class GetValuesTest extends JDWPSyncTestCase {

    static final String thisCommandName = "ObjectReference::GetValues command";
    static final String debuggeeSignature = "Lorg/apache/harmony/jpda/tests/jdwp/ObjectReference/GetValuesDebuggee;";

    protected String getDebuggeeClassName() {
        return "org.apache.harmony.jpda.tests.jdwp.ObjectReference.GetValuesDebuggee";
    }

    /**
     * This test exercises ObjectReference.GetValues command.
     * <BR>The test starts GetValuesDebuggee class, gets objectID
     * as value of static field of this class which (field) represents checked object.
     * Then for this objectID test executes ObjectReference::GetValues command for special
     * set of fieldIDs and checks that command returns expected jdwpTags for all checked
     * fields and expected values for primitive fields.
     */
    public void testGetValues001() {
        String thisTestName = "testGetValues001";
        logWriter.println("==> " + thisTestName + " for " + thisCommandName + ": START...");
        synchronizer.receiveMessage(JPDADebuggeeSynchronizer.SGNL_READY);

        long refTypeID = getClassIDBySignature(debuggeeSignature);

        logWriter.println("=> Debuggee class = " + getDebuggeeClassName());
        logWriter.println("=> referenceTypeID for Debuggee class = " + refTypeID);

        String checkedFieldNames[] = {
                "getValuesDebuggeeObject",

                "intField",
                "longField",
                "objectField",
                "stringArrayField",
                "objectArrayField",
                "threadField",
                "threadGroupField",
                "classField",
                "classLoaderField",
                "stringField",
        };
        long checkedFieldIDs[] = checkFields(refTypeID, checkedFieldNames);
        int checkedFieldsNumber = checkedFieldNames.length;

        logWriter.println
        ("=> Send ReferenceType::GetValues command and and get ObjectID to check...");

        CommandPacket getValuesCommand = new CommandPacket(
                JDWPCommands.ReferenceTypeCommandSet.CommandSetID,
                JDWPCommands.ReferenceTypeCommandSet.GetValuesCommand);
        getValuesCommand.setNextValueAsReferenceTypeID(refTypeID);
        getValuesCommand.setNextValueAsInt(1);
        getValuesCommand.setNextValueAsFieldID(checkedFieldIDs[0]);

        ReplyPacket getValuesReply = debuggeeWrapper.vmMirror.performCommand(getValuesCommand);
        getValuesCommand = null;
        checkReplyPacket(getValuesReply, "ReferenceType::GetValues command");

        int returnedValuesNumber = getValuesReply.getNextValueAsInt();
        logWriter.println("=> Returned values number = " + returnedValuesNumber);
        assertEquals("Invalid number of values,", 1, returnedValuesNumber);

        Value checkedObjectFieldValue = getValuesReply.getNextValueAsValue();
        byte checkedObjectFieldTag = checkedObjectFieldValue.getTag();
        logWriter.println("=> Returned field value tag for checked object= " + checkedObjectFieldTag
            + "(" + JDWPConstants.Tag.getName(checkedObjectFieldTag) + ")");
        assertEquals("Invalid value tag for checked object,", JDWPConstants.Tag.OBJECT_TAG, checkedObjectFieldTag
                , JDWPConstants.Tag.getName(JDWPConstants.Tag.OBJECT_TAG)
                , JDWPConstants.Tag.getName(checkedObjectFieldTag));

        long checkedObjectID = checkedObjectFieldValue.getLongValue();
        logWriter.println("=> Returned checked ObjectID = " + checkedObjectID);
        logWriter.println("=> CHECK: send " + thisCommandName + " for this ObjectID and check reply...");

        CommandPacket checkedCommand = new CommandPacket(
                JDWPCommands.ObjectReferenceCommandSet.CommandSetID,
                JDWPCommands.ObjectReferenceCommandSet.GetValuesCommand);
        checkedCommand.setNextValueAsObjectID(checkedObjectID);
        checkedCommand.setNextValueAsInt(checkedFieldsNumber-1);
        int fieldIndex = 1; // !!!
        for (; fieldIndex < checkedFieldsNumber; fieldIndex++) {
            checkedCommand.setNextValueAsFieldID(checkedFieldIDs[fieldIndex]);
        }

        ReplyPacket checkedReply = debuggeeWrapper.vmMirror.performCommand(checkedCommand);
        checkedCommand = null;
        checkReplyPacket(checkedReply, thisCommandName);

        returnedValuesNumber = checkedReply.getNextValueAsInt();
        logWriter.println("=> Returned values number = " + returnedValuesNumber);
        assertEquals("Invalid number of values,", checkedFieldsNumber - 1, returnedValuesNumber);

        byte expectedFieldTags[] = {
                0, // dummy
                JDWPConstants.Tag.INT_TAG,
                JDWPConstants.Tag.LONG_TAG,
                JDWPConstants.Tag.OBJECT_TAG,
                JDWPConstants.Tag.ARRAY_TAG,
                JDWPConstants.Tag.ARRAY_TAG,
                JDWPConstants.Tag.THREAD_TAG,
                JDWPConstants.Tag.THREAD_GROUP_TAG,
                JDWPConstants.Tag.CLASS_OBJECT_TAG,
                JDWPConstants.Tag.CLASS_LOADER_TAG,
                JDWPConstants.Tag.STRING_TAG,
        };

        logWriter.println("=> CHECK for returned values...");
        fieldIndex = 1; // !!!
        for (; fieldIndex < checkedFieldsNumber; fieldIndex++) {
            Value fieldValue = checkedReply.getNextValueAsValue();
            byte fieldTag = fieldValue.getTag();
            logWriter.println
            ("\n=> Check for returned value for field: " + checkedFieldNames[fieldIndex] + " ...");
            logWriter.println("=> Returned value tag = " + fieldTag
                + "(" + JDWPConstants.Tag.getName(fieldTag) + ")");

            assertEquals("Invalid value tag is returned,", expectedFieldTags[fieldIndex], fieldTag
                    , JDWPConstants.Tag.getName(expectedFieldTags[fieldIndex])
                    , JDWPConstants.Tag.getName(fieldTag));

            switch ( fieldTag ) {
            case JDWPConstants.Tag.INT_TAG:
                int intValue = fieldValue.getIntValue();
                logWriter.println("=> Returned value = " + intValue);
                // here expected value = 9999 (staticIntField)
                int expectedIntValue = 9999;
                assertEquals("Invalid int value,", expectedIntValue, intValue);
                break;
            case JDWPConstants.Tag.LONG_TAG:
                long longValue = fieldValue.getLongValue();
                logWriter.println("=> Returned value = " + longValue);
                // here expected value = 999999 (staticLongField)
                long expectedLongValue = 999999;
                assertEquals("Invalid long value,", expectedLongValue, longValue);
                break;
            case JDWPConstants.Tag.STRING_TAG:
            case JDWPConstants.Tag.OBJECT_TAG:
            case JDWPConstants.Tag.ARRAY_TAG:
            case JDWPConstants.Tag.THREAD_TAG:
            case JDWPConstants.Tag.THREAD_GROUP_TAG:
            case JDWPConstants.Tag.CLASS_OBJECT_TAG:
            case JDWPConstants.Tag.CLASS_LOADER_TAG:
                long objectIDValue = fieldValue.getLongValue();
                logWriter.println("=> ObjectId value = " + objectIDValue);
                break;
            }
        }

        assertAllDataRead(checkedReply);

        logWriter.println
        ("=> CHECK PASSED: All expected field values are got and have expected attributes");

        synchronizer.sendMessage(JPDADebuggeeSynchronizer.SGNL_CONTINUE);
        logWriter.println("==> " + thisTestName + " for " + thisCommandName + ": FINISH");
    }

    public static void main(String[] args) {
        junit.textui.TestRunner.run(GetValuesTest.class);
    }
}


text: Polymer('paper-menu-button-overlay-container', {});


text:
const Discord = require("discord.js");

module.exports = {

    reply: function (message, msg) {

        message.reply(msg, {split: true})
    },

    say: function (bot, msg) {

        bot.sendMessage(msg);
    }
}


text:
package fi.pelam.javafxactor

import javafx.util.Callback

import akka.actor.Actor

import scala.collection.mutable

class ControllerFactory extends Callback[Class[_], AnyRef] {

  val controllerMap = mutable.Map[Class[_], Actor]()

  def register(controller: Actor): Unit = {
    controllerMap(controller.getClass) = controller
  }

  override def call(param: Class[_]): AnyRef = controllerMap(param)

}


text:
package river

import (
	"io/ioutil"
	"time"

	"github.com/BurntSushi/toml"
	"github.com/juju/errors"
)

// SourceConfig is the configs for source
type SourceConfig struct {
	Schema string   `toml:"schema"`
	Tables []string `toml:"tables"`
}

// Config is the configuration
type Config struct {
	MyAddr     string `toml:"my_addr"`
	MyUser     string `toml:"my_user"`
	MyPassword string `toml:"my_pass"`
	MyCharset  string `toml:"my_charset"`

	ESHttps    bool   `toml:"es_https"`
	ESAddr     string `toml:"es_addr"`
	ESUser     string `toml:"es_user"`
	ESPassword string `toml:"es_pass"`

	StatAddr string `toml:"stat_addr"`
	StatPath string `toml:"stat_path"`

	ServerID uint32 `toml:"server_id"`
	Flavor   string `toml:"flavor"`
	DataDir  string `toml:"data_dir"`

	DumpExec       string `toml:"mysqldump"`
	SkipMasterData bool   `toml:"skip_master_data"`

	Sources []SourceConfig `toml:"source"`

	Rules []*Rule `toml:"rule"`

	BulkSize int `toml:"bulk_size"`

	FlushBulkTime TomlDuration `toml:"flush_bulk_time"`

	SkipNoPkTable bool `toml:"skip_no_pk_table"`
}

// NewConfigWithFile creates a Config from file.
func NewConfigWithFile(name string) (*Config, error) {
	data, err := ioutil.ReadFile(name)
	if err != nil {
		return nil, errors.Trace(err)
	}

	return NewConfig(string(data))
}

// NewConfig creates a Config from data.
func NewConfig(data string) (*Config, error) {
	var c Config

	_, err := toml.Decode(data, &c)
	if err != nil {
		return nil, errors.Trace(err)
	}

	return &c, nil
}

// TomlDuration supports time codec for TOML format.
type TomlDuration struct {
	time.Duration
}

// UnmarshalText implementes TOML UnmarshalText
func (d *TomlDuration) UnmarshalText(text []byte) error {
	var err error
	d.Duration, err = time.ParseDuration(string(text))
	return err
}


text:
@implementation ABPhotoModel

+(instancetype)photoModelWithName:(NSString *)name image:(UIImage *)image {
    ABPhotoModel *model = [ABPhotoModel new];

    model.name = name;
    model.image = image;

    return model;
}

@end


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syll. fung. (Abellini) 5: 833 (1887)

#### Original name
Agaricus rimulincola Rabenh., 1851

### Remarks
null


text:
'use strict';

var invariant = require('invariant');

class NavigationEventPool {
  _list: Array<any>;

  constructor() {
    this._list = [];
  }

  get(type: string, target: Object, data: any): NavigationEvent {
    var event;
    if (this._list.length > 0) {
      event = this._list.pop();
      event.constructor.call(event, type, target, data);
    } else {
      event = new NavigationEvent(type, target, data);
    }
    return event;
  }

  put(event: NavigationEvent) {
    this._list.push(event);
  }
}

var _navigationEventPool = new NavigationEventPool();

class NavigationEvent {
  _data: any;
  _defaultPrevented: boolean;
  _propagationStopped: boolean;
  _disposed: boolean;
  _target: ?Object;
  _type: ?string;

  static pool(type: string, target: Object, data: any): NavigationEvent {
    return _navigationEventPool.get(type, target, data);
  }

  constructor(type: string, target: Object, data: any) {
    this._type = type;
    this._target = target;
    this._data = data;
    this._defaultPrevented = false;
    this._disposed = false;
    this._propagationStopped = false;
  }

  /* $FlowFixMe - get/set properties not yet supported */
  get type(): string {
    return this._type;
  }

  /* $FlowFixMe - get/set properties not yet supported */
  get target(): Object {
    return this._target;
  }

  /* $FlowFixMe - get/set properties not yet supported */
  get data(): any {
    return this._data;
  }

  /* $FlowFixMe - get/set properties not yet supported */
  get defaultPrevented(): boolean {
    return this._defaultPrevented;
  }

  preventDefault(): void {
    this._defaultPrevented = true;
  }

  stopPropagation(): void {
    this._propagationStopped = true;
  }

  stop(): void {
    this.preventDefault();
    this.stopPropagation();
  }

  isPropagationStopped(): boolean {
    return this._propagationStopped;
  }

  /**
   * Dispose the event.
   * NavigationEvent shall be disposed after being emitted by
   * `NavigationEventEmitter`.
   */
  dispose(): void {
    invariant(!this._disposed, 'NavigationEvent is already disposed');
    this._disposed = true;

    // Clean up.
    this._type = null;
    this._target = null;
    this._data = null;
    this._defaultPrevented = false;

    // Put this back to the pool to reuse the instance.
    _navigationEventPool.put(this);
  }
}

module.exports = NavigationEvent;


text:
using Light.DataContracts;
using Light.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Light.Repositories
{
    /// <summary>
    /// RepositoryBase for reader and writer
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    public abstract class Repository<TEntity> where TEntity : Entity, new()
    {
        internal DbContext _context;
        internal DbSet<TEntity> _set;
        public Repository(IDbContextContract context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            _context = context as DbContext;
            _set = _context.Set<TEntity>();
        }
    }
}


text:
@implementation AVAsset (VideoUrlCoverImage)

- (NSURL *)imageUrlWithUUID:(NSString *)uuid
{
    AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:self];
    imageGenerator.appliesPreferredTrackTransform = YES;
    CMTime startTime = kCMTimeZero;
    CMTime actualTime;
    NSError *error = nil;
    CGImageRef videoImage = [imageGenerator copyCGImageAtTime:startTime actualTime:&actualTime error:&error];
    UIImage *image = nil;
    if (videoImage != NULL) {
        image = [UIImage imageWithCGImage:videoImage];
    } else {
        image = [UIImage imageNamed:@"default_video_cover"];
    }
    NSData *jpgData = UIImageJPEGRepresentation(image, 0.9f);
    NSString *outPutFilepath = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:uuid];
    [jpgData writeToFile:outPutFilepath atomically:NO];
    NSURL *resultUrl = [NSURL fileURLWithPath:outPutFilepath isDirectory:NO];
    return resultUrl;
}

@end


text:
import os
import sys

def splitfasta(input_file, output_dir):
    outputs = {}

    while True:
        description = input_file.readline()
        if not len(description):
            return
        sequence = input_file.readline()
        if not len(sequence):
            return

        assert description.startswith('>'), 'Error: Incomplete format'
        id = description[1:].split()[0]
        assert '_' in id, 'Error: Input fasta file must be processed by split_libraries.py'

        id = id[:id.rfind('_')]
        if id not in outputs:
            outputs[id] = open(os.path.join(output_dir, id + '.fasta'), 'w')

        outputs[id].write(description)
        outputs[id].write(sequence)

if __name__ == '__main__':
    if len(sys.argv) < 3:
        print('Usage: %s [input fasta file] [output directory]')
        sys.exit()

    if not os.path.exists(sys.argv[2]):
        os.mkdir(sys.argv[2])
    elif os.path.isfile(sys.argv[2]):
        print('Error: %s already exists' % sys.argv[2])
        sys.exit()

    with open(sys.argv[1], 'r') as f:
        splitfasta(f, sys.argv[2])


text:
    <button type="button" class="close" data-dismiss="alert">×</button>
    Exito!
Datos actualizados.

    <button type="button" class="close" data-dismiss="alert">×</button>
    Error!

    <form name="form" class="form-horizontal" ng-submit="submit()">
        <fieldset>
            <legend>Datos personales</legend>

                    Nombre:

                        <input type="text" name="name" class="form-control" id="name"
                               placeholder="Nombre" required="required" ng-model="user.name"/>

                    Email:

                        <input type="email" name="email" class="form-control" id="email"
                               placeholder="Email" ng-model="user.email"/>

                    Administrador

                        <input type="checkbox" name="admin" class="form-control" id="admin"
                               placeholder="Administrador" disabled="disabled"
                               ng-model="user.admin"/>

                    Trabajador

                        <input type="checkbox" name="worker" class="form-control" id="worker"
                               placeholder="Trabajador" disabled="disabled"
                               ng-model="user.worker"/>

                    Vendedor

                        <input type="checkbox" name="seller" class="form-control" id="seller"
                               placeholder="Vendedor" disabled="disabled"
                               ng-model="user.seller"/>

                    Cliente

                        <input type="checkbox" name="client" class="form-control" id="client"
                               placeholder="Cliente" disabled="disabled"
                               ng-model="user.client"/>

                    <button ng-disabled="form.$invalid" type="submit" class="btn btn-primary btn-raised">Actualizar
                        datos
                    </button>

        </fieldset>
    </form>


text:
<?php
//============================================================+
// File name   : example_014.php
// Begin       : 2008-03-04
// Last Update : 2008-10-29
//
// Description : Example 014 for TCPDF class
//               Javascript Form and user rights
//
// Author: Nicola Asuni
//
// (c) Copyright:
//               Nicola Asuni
//               Tecnick.com s.r.l.
//               Via Della Pace, 11
//               09044 Quartucciu (CA)
//               ITALY
//               www.tecnick.com
//               info@tecnick.com
//============================================================+

require_once('../config/lang/eng.php');
require_once('../tcpdf.php');

// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true);

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor("Nicola Asuni");
$pdf->SetTitle("TCPDF Example 014");
$pdf->SetSubject("TCPDF Tutorial");
$pdf->SetKeywords("TCPDF, PDF, example, test, guide");

// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);

// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

//set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

//set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

//set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

//set some language-dependent strings
$pdf->setLanguageArray($l);

//initialize document
$pdf->AliasNbPages();

// add a page
$pdf->AddPage();

// ---------------------------------------------------------

// set font
$pdf->SetFont("helvetica", "BI", 20);

// Release User's Rights For PDF reader.
// This is required to display and fill form fields on PDF Readers.
$pdf->setUserRights();

/*
Caution: the generated PDF works only with Acrobat Reader 5.1.
It is possible to create text fields, combo boxes, check boxes and buttons. Fields are created at the current position and are given a name. This name allows to manipulate them via JavaScript in order to perform some validation for instance.
Upon field creation, an associative array can be passed to set a number of properties, among which:
	rect: Position and size of field on page.
	borderStyle: Rectangle border appearance.
	strokeColor: Color of bounding rectangle.
	lineWidth: Width of the edge of the surrounding rectangle.
	rotation: Rotation of field in 90-degree increments.
	fillColor: Background color of field (gray, transparent, RGB, or CMYK).
	userName: Short description of field that appears on mouse-over.
	readonly: Whether the user may change the field contents.
	doNotScroll: Whether text fields may scroll.
	display: Whether visible or hidden on screen or in print.
	textFont: Text font.
	textColor: Text color.
	textSize: Text size.
	richText: Rich text.
	richValue: Text.
	comb: Text comb format.
	multiline: Text multiline.
	charLimit: Text limit to number of characters.
	fileSelect: Text file selection format.
	password: Text password format.
	alignment: Text layout in text fields.
	buttonAlignX: X alignment of icon on button face.
	buttonAlignY: Y alignment of icon on button face.
	buttonFitBounds: Relative scaling of an icon to fit inside a button face.
	buttonScaleHow: Relative scaling of an icon to fit inside a button face.
	buttonScaleWhen: Relative scaling of an icon to fit inside a button face.
	highlight: Appearance of a button when pushed.
	style: Glyph style for checkbox and radio buttons.
	numItems: Number of items in a combo box or list box.
	editable: Whether the user can type in a combo box.
	multipleSelection: Whether multiple list box items may be selected.
Colors can be chosen in the following list (case sensitive): black white red green blue cyan magenta yellow dkGray gray ltGray or be in the form #RRGGBB.
*/

$pdf->Cell(0,5,'Subscription form',0,1,'C');
$pdf->Ln(10);
$pdf->SetFont('','',12);

//First name
$pdf->Cell(35,5,'First name:');
$pdf->TextField('firstname',50,5,array('strokeColor'=>'ltGray'));
$pdf->Ln(6);

//Last name
$pdf->Cell(35,5,'Last name:');
$pdf->TextField('lastname',50,5,array('strokeColor'=>'ltGray'));
$pdf->Ln(6);

//Gender
$pdf->Cell(35,5,'Gender:');
$pdf->ComboBox('gender',10,5,array('','M','F'),array('strokeColor'=>'ltGray'));
$pdf->Ln(6);

//Drink
$pdf->Cell(35,5,'Drink:');
$pdf->RadioButton('drink',5,false);
$pdf->Cell(35,5,'Water');
$pdf->Ln(6);
$pdf->Cell(35,5,'');
$pdf->RadioButton('drink',5,false);
$pdf->Cell(35,5,'Beer');
$pdf->Ln(6);
$pdf->Cell(35,5,'');
$pdf->RadioButton('drink',5,false);
$pdf->Cell(35,5,'Wine');
// set export values
$pdf->IncludeJS("fdrink.exportValues=[\"Water\", \"Beer\", \"Wine\"];\n");
// check the second radiobutton
$pdf->IncludeJS("fdrink.checkThisBox(1,true);\n");
$pdf->Ln(10);

//Gender
$pdf->Cell(35,5,'List:');
$pdf->ListBox('listbox',60,15,array('','item1','item2','item3','item4','item5','item6','item7'), array('multipleSelection'=>'true'));
$pdf->Ln(20);

//Adress
$pdf->Cell(35,5,'Address:');
$pdf->TextField('address',60,18,array('multiline'=>true,'strokeColor'=>'ltGray'));
$pdf->Ln(19);

//E-mail
$pdf->Cell(35,5,'E-mail:');
$pdf->TextField('email',50,5,array('strokeColor'=>'ltGray'));
$pdf->Ln(6);

//Newsletter
$pdf->Cell(35,5,'Receive our',0,1);
$pdf->Cell(35,5,'newsletter:');
$pdf->CheckBox('newsletter',5,true);
$pdf->Ln(10);

//Date of the day (determined and formatted by JS)
$pdf->Write(5,'Date: ');
$pdf->TextField('date',30,5);
$pdf->IncludeJS("getField('date').value=util.printd('dd/mm/yyyy',new Date());\n");
$pdf->Ln();
$pdf->Write(5,'Signature:');
$pdf->Ln(3);

//Button to validate and print
$pdf->SetX(95);
$pdf->Button('print',20,8,'Print','Print()',array('textColor'=>'yellow','fillColor'=>'#FF5050'));

//Form validation functions
$pdf->IncludeJS("
function CheckField(name,message) {
	var f = getField(name);
	if(f.value == '') {
	    app.alert(message);
	    f.setFocus();
	    return false;
	}
	return true;
}

function Print() {
	//Validation
	if(!CheckField('firstname','First name is mandatory'))
		return;
	if(!CheckField('lastname','Last name is mandatory'))
		return;
	if(!CheckField('gender','Gender is mandatory'))
		return;
	if(!CheckField('address','Address is mandatory'))
		return;
	//Print
	print();
}
");

// ---------------------------------------------------------

//Close and output PDF document
$pdf->Output("example_014.pdf", "I");

//============================================================+
// END OF FILE
//============================================================+
?>


text:
<?php

namespace Google\AdsApi\AdManager\v202202;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class AdSpotFillType
{
    const REQUIRED = 'REQUIRED';
    const OPTIONAL = 'OPTIONAL';
    const UNKNOWN = 'UNKNOWN';

}


text:
<?php

/* @var $installer Mage_Core_Model_Resource_Setup */
$installer = $this;
$installer->startSetup();
$installer->getConnection()->addColumn(
    $installer->getTable('core_email_template'), 'template_styles', "text AFTER `template_text`"
);
$installer->endSetup();


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>
    /// AdminMessage
    /// </summary>
    [DataContract]
    public partial class AdminMessage :  IEquatable<AdminMessage>, IValidatableObject
    {
        public AdminMessage()
        {
            // Empty Constructor
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AdminMessage" /> class.
        /// </summary>
        /// <param name="BaseMessage">BaseMessage.</param>
        /// <param name="MoreInformation">MoreInformation.</param>
        public AdminMessage(string BaseMessage = default(string), string MoreInformation = default(string))
        {
            this.BaseMessage = BaseMessage;
            this.MoreInformation = MoreInformation;
        }

        /// <summary>
        /// Gets or Sets BaseMessage
        /// </summary>
        [DataMember(Name="baseMessage", EmitDefaultValue=false)]
        public string BaseMessage { get; set; }
        /// <summary>
        /// Gets or Sets MoreInformation
        /// </summary>
        [DataMember(Name="moreInformation", EmitDefaultValue=false)]
        public string MoreInformation { 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 AdminMessage {\n");
            sb.Append("  BaseMessage: ").Append(BaseMessage).Append("\n");
            sb.Append("  MoreInformation: ").Append(MoreInformation).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 AdminMessage);
        }

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

            return
                (
                    this.BaseMessage == other.BaseMessage ||
                    this.BaseMessage != null &&
                    this.BaseMessage.Equals(other.BaseMessage)
                ) &&
                (
                    this.MoreInformation == other.MoreInformation ||
                    this.MoreInformation != null &&
                    this.MoreInformation.Equals(other.MoreInformation)
                );
        }

        /// <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.BaseMessage != null)
                    hash = hash * 59 + this.BaseMessage.GetHashCode();
                if (this.MoreInformation != null)
                    hash = hash * 59 + this.MoreInformation.GetHashCode();
                return hash;
            }
        }

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


text:
require 'test/unit'
require 'tk'
require File.expand_path('../../lib/flowtag.rb', __FILE__)


text:
using System;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Threading;

namespace vtortola.Redis
{
    internal sealed class BasicLoadBasedSelector : ILoadBasedSelector
    {
        Int32 _last;

        internal BasicLoadBasedSelector(Int32 initialValue = 0)
        {
            _last = initialValue - 1;
        }

        // balances load, chosing the first with 0 load, or the one with less load
        public T Select<T>(T[] elements) where T : ILoadMeasurable
        {
            Contract.Assert(elements.Any(), "Cannot select ILoadMeasurable element from an empty list.");

            T minElement = default(T);
            var minValue = Int32.MaxValue;
            unchecked
            {
                var last = Interlocked.Increment(ref _last);
                for (int i = 0; i < elements.Length; i++)
                {
                    var index = Math.Abs((last + i) % elements.Length);
                    var load = elements[index].CurrentLoad;
                    if (load == 0)
                    {
                        return elements[index];
                    }
                    else if (load < minValue)
                    {
                        minValue = load;
                        minElement = elements[index];
                    }
                }
            }
            return minElement;
        }
    }
}


text:
import logging

from rest_framework.permissions import BasePermission

from media_management_api.media_service.models import CourseUser, UserProfile

logger = logging.getLogger(__name__)

SAFE_METHODS = ("GET", "HEAD", "OPTIONS")

class IsCourseUserAuthenticated(BasePermission):
    def has_permission(self, request, view):
        """
        This is generally called by the check_permissions() method on an APIView to determine
        if a request should be permitted. It is called after authentication, but prior to invoking
        the method on the view.

        Returns True if the user is authenticated, otherwise False.
        """
        has_perm = bool(request.user and request.user.is_authenticated)
        logger.info(
            "user %s has_permission for request [%s %s] => %s"
            % (
                request.user.id if request.user else None,
                request.method,
                request.path,
                has_perm,
            )
        )
        return has_perm

    def has_object_permission(self, request, view, object):
        """
        This is generally called by the check_object_permissions() method on an APIView to determine
        if the request should be permitted for a given object.

        Note that this is not called automatically, unless the view is a GenericAPIView
        and the get_object() method is used.

        Returns True if the user has permission to modify the object, otherwise returns False.
        """
        has_perm = self._has_object_permission(request, view, object)
        logger.info(
            "user %s has_object_permission for object [%s] request [%s %s] => %s"
            % (request.user.id, object, request.method, request.path, has_perm)
        )
        return has_perm

    def _has_object_permission(self, request, view, object):
        """
        Returns True if the user is a superuser, otherwise it depends on the request method and
        whether the user is a member of the course and whether they are an admin or not in that course.
        """
        user = request.user
        if user.is_superuser or user.is_staff:
            return True

        try:
            user_profile = user.profile
        except UserProfile.DoesNotExist:
            logger.exception("User profile missing for user: %s" % user)
            return False

        # Allow members of the course to access any read-only or "safe" method
        # but require admin permission to make any changes (e.g. POST, PUT, PATCH, DELETE)
        users_qs = CourseUser.objects.filter(user_profile=user_profile, course=object)
        has_perm = False
        if request.method in SAFE_METHODS:
            has_perm = users_qs.exists()
        else:
            has_perm = users_qs.filter(is_admin=True).exists()
        return has_perm


text:
using LionFire.Persistence;
using LionFire.Structures;

namespace LionFire.Instantiating
{
    public interface IPidRoot : INotifyOnSaving
    {
        KeyKeeperShort KeyKeeper { get; }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>João de Mio</logradouro><bairro>Portão</bairro><cidade>Curitiba</cidade><uf>PR</uf><cep>81070230</cep></feed>


text:
package org.apache.ignite.internal.processors.query.h2.twostep.msg;

import java.nio.ByteBuffer;
import org.apache.ignite.internal.GridKernalContext;
import org.apache.ignite.plugin.extensions.communication.MessageReader;
import org.apache.ignite.plugin.extensions.communication.MessageWriter;
import org.h2.value.Value;
import org.h2.value.ValueInt;

/**
 * H2 Integer.
 */
public class GridH2Integer extends GridH2ValueMessage {
    /** */
    private int x;

    /**
     *
     */
    public GridH2Integer() {
        // No-op.
    }

    /**
     * @param val Value.
     */
    public GridH2Integer(Value val) {
        assert val.getType() == Value.INT : val.getType();

        x = val.getInt();
    }

    /** {@inheritDoc} */
    @Override public Value value(GridKernalContext ctx) {
        return ValueInt.get(x);
    }

    /** {@inheritDoc} */
    @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
        writer.setBuffer(buf);

        if (!super.writeTo(buf, writer))
            return false;

        if (!writer.isHeaderWritten()) {
            if (!writer.writeHeader(directType(), fieldsCount()))
                return false;

            writer.onHeaderWritten();
        }

        switch (writer.state()) {
            case 0:
                if (!writer.writeInt("x", x))
                    return false;

                writer.incrementState();

        }

        return true;
    }

    /** {@inheritDoc} */
    @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
        reader.setBuffer(buf);

        if (!reader.beforeMessageRead())
            return false;

        if (!super.readFrom(buf, reader))
            return false;

        switch (reader.state()) {
            case 0:
                x = reader.readInt("x");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

        }

        return reader.afterMessageRead(GridH2Integer.class);
    }

    /** {@inheritDoc} */
    @Override public byte directType() {
        return -8;
    }

    /** {@inheritDoc} */
    @Override public byte fieldsCount() {
        return 1;
    }

    /** {@inheritDoc} */
    @Override public boolean equals(Object obj) {
        return obj == this || (obj != null && obj.getClass() == GridH2Integer.class && x == ((GridH2Integer)obj).x);

    }

    /** {@inheritDoc} */
    @Override public int hashCode() {
        return x;
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return String.valueOf(x);
    }
}


text:
'use strict'

var crypto = require('crypto'),
	a = getRandomString(1000),
	similarity, b, t, ct

console.log(['% simi', 'avg ct=', 'avg ===', 'md ct=', 'md ==='].join('\t'))
for (similarity = 0; similarity <= 100; similarity += 2) {
	b = getSimiliarString(a, similarity / 100)
	t = stat(function () {
		return compare(a, b, 1e5)
	}, 100)
	ct = stat(function () {
		return constantCompare(a, b, 1e3)
	}, 100)
	console.log([similarity, ct.avg, t.avg, ct.median, t.median].join('\t'))
}

/**
 * @param {number} length
 * @returns {string}
 */
function getRandomString(length) {
	return crypto.pseudoRandomBytes(Math.ceil(3 * length / 4)).toString('base64').substr(0, length)
}

/**
 * Generate another string that has the same prefix and length as another one
 * @param {string} base
 * @param {number} relation A number from 0 (not equal at all) to 1 (equal strings)
 * @param {string}
 */
function getSimiliarString(base, relation) {
	var length = Math.round(base.length * relation),
		r = '',
		i, str
	do {
		str = getRandomString(base.length - length)
	} while (str && str[0] === base[length])
	for (i = 0; i < length; i++) {
		r += base[i] // substr(...) seems to be optimized
	}
	return r + str
}

/**
 * Compute a==b n times
 * @param {string} a
 * @param {string} b
 * @param {number} n
 * @returns {number} The time per comparison (in ns)
 */
function compare(a, b, n) {
	var n2 = n,
		then = Date.now()
	while (n2--) {
		a === b
	}
	return (Date.now() - then) * 1e6 / n
}

/**
 * Compute a==b n times with a constant algorithm
 * @param {string} a
 * @param {string} b
 * @param {number} n
 * @returns {number} The time per comparison (in ns)
 */
function constantCompare(a, b, n) {
	var n2 = n,
		then = Date.now(),
		eq = false,
		len, i
	while (n2--) {
		len = Math.max(a.length, b.length)
		for (i = 0; i < len; i++) {
			if (a.length >= i && b.length >= i && a[i] !== b[i]) {
				eq = false
			}
		}
	}
	return (Date.now() - then) * 1e6 / n
}

/**
 * Make a statistical experiment on fn
 * @param {Function} fn A function that receives nothing and returns a number
 * @param {number} n Number of probes to takes
 * @returns {{avg: number, median: number}}
 */
function stat(fn, n) {
	var n2 = n,
		times = [],
		sum = 0,
		t, avg, median
	while (n2--) {
		t = fn()
		sum += t
		times.push(t)
	}
	avg = sum / n
	times.sort(function (a, b) {
		return a - b
	})
	median = times[Math.floor(times.length / 2)]
	if (times.length % 2 === 0) {
		median = (median + times[times.length / 2 - 1]) / 2
	}
	return {
		avg: avg,
		median: median
	}
}


text:
package com.theisenp.vicarious.logger;

import twitter4j.Status;
import twitter4j.StatusUpdate;

/**
 * Implementation of {@link TweetLogger} that prints tweets to the console
 *
 * @author patrick.theisen
 */
public class ConsoleTweetLogger implements TweetLogger {

	// Constants
	private static final String MESSAGE_HEADER = "Handled tweet %d from @%s:";
	private static final String MESSAGE_ORIGINAL = "\t[original]: %s";
	private static final String MESSAGE_RESPONSE = "\t[response]: %s";

	@Override
	public void log(Status original, StatusUpdate response) {
		logHeader(original);
		logOriginal(original);
		logResponse(response);
	}

	/**
	 * Prints a message header
	 *
	 * @param original
	 * The original tweet
	 */
	private static void logHeader(Status original) {
		long id = original.getId();
		String user = original.getUser().getScreenName();
		String message = String.format(MESSAGE_HEADER, id, user);
		System.out.println(message);
	}

	/**
	 * Prints an original tweet
	 *
	 * @param original
	 * The original tweet
	 */
	private static void logOriginal(Status original) {
		String text = original.getText();
		String message = String.format(MESSAGE_ORIGINAL, text);
		System.out.println(message);
	}

	/**
	 * Prints a response tweet
	 *
	 * @param response
	 * The response tweet
	 */
	private static void logResponse(StatusUpdate response) {
		String text = response.getStatus();
		String message = String.format(MESSAGE_RESPONSE, text);
		System.out.println(message);
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Macrophoma neriicola Severini

### Remarks
null


text:
package main

import (
	"fmt"
	"io"
	"sync"
	"time"
)

const rootPartitionToken = "root"

type Partition struct {
	Token          string
	StartTimestamp time.Time
	RecordSequence string
	Parents        []*Partition
}

func (p *Partition) ShortenToken() string {
	length := 20
	if len(p.Token) < 20 {
		length = len(p.Token)
	}
	return p.Token[0:length]
}

// Assert that PartitionVisualizer implements Consumer.
var _ Consumer = (*PartitionVisualizer)(nil)

type PartitionVisualizer struct {
	partitions map[string]*Partition
	mu         sync.Mutex
	out        io.Writer
}

func NewPartitionVisualizer(out io.Writer) *PartitionVisualizer {
	partitions := make(map[string]*Partition)
	// Root partition.
	partitions[rootPartitionToken] = &Partition{Token: rootPartitionToken}
	return &PartitionVisualizer{
		partitions: partitions,
		out:        out,
	}
}

func (v *PartitionVisualizer) Consume(partitionToken string, result *ReadResult) error {
	v.mu.Lock()
	defer v.mu.Unlock()

	for _, changeRecord := range result.ChangeRecords {
		for _, partitionRecord := range changeRecord.ChildPartitionsRecords {
			for _, childPartition := range partitionRecord.ChildPartitions {
				token := childPartition.Token
				if _, ok := v.partitions[token]; ok {
					continue
				}

				var parents []*Partition
				for _, parentToken := range childPartition.ParentPartitionTokens {
					parent, ok := v.partitions[parentToken]
					// It's possible that parent partition is not included in the specified time range.
					if !ok {
						parent = &Partition{
							Token: parentToken,
						}
						v.partitions[parentToken] = parent
					}
					parents = append(parents, parent)
				}
				if len(parents) == 0 {
					parents = append(parents, v.partitions[rootPartitionToken])
				}

				childPartition := &Partition{
					Token:          token,
					StartTimestamp: partitionRecord.StartTimestamp,
					RecordSequence: partitionRecord.RecordSequence,
					Parents:        parents,
				}
				v.partitions[token] = childPartition
			}
		}
	}
	return nil
}

func (v *PartitionVisualizer) Draw() {
	fmt.Fprintf(v.out, "digraph {\n")
	fmt.Fprintf(v.out, "  node [shape=record];\n")
	for _, partition := range v.partitions {
		t := partition.ShortenToken()
		fmt.Fprintf(v.out, `  "%s" [label="{token|start_timestamp|record_sequence}|{{%s}|{%s}|{%s}}"];`, t, t, partition.StartTimestamp.Format(time.RFC3339), partition.RecordSequence)
		fmt.Fprintln(v.out, "")
	}
	for _, partition := range v.partitions {
		for _, parent := range partition.Parents {
			fmt.Fprintf(v.out, `  "%s" -> "%s"`, parent.ShortenToken(), partition.ShortenToken())
			fmt.Fprintln(v.out, "")
		}
	}
	fmt.Fprintf(v.out, "}\n")
}


text:
<?php

namespace Minsal\sifdaBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Minsal\sifdaBundle\Entity\Catalogo;
use Minsal\sifdaBundle\Form\CatalogoType;

/**
 * Catalogo controller.
 *
 * @Route("/sifda/catalogo")
 */
class CatalogoController extends Controller
{

    /**
     * Lists all Catalogo entities.
     *
     * @Route("/", name="sifda_catalogo")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('MinsalsifdaBundle:Catalogo')->findAll();

        return array(
            'entities' => $entities,
        );
    }
    /**
     * Creates a new Catalogo entity.
     *
     * @Route("/", name="sifda_catalogo_create")
     * @Method("POST")
     * @Template("MinsalsifdaBundle:Catalogo:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new Catalogo();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('sifda_catalogo_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a form to create a Catalogo entity.
     *
     * @param Catalogo $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Catalogo $entity)
    {
        $form = $this->createForm(new CatalogoType(), $entity, array(
            'action' => $this->generateUrl('sifda_catalogo_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new Catalogo entity.
     *
     * @Route("/new", name="sifda_catalogo_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Catalogo();
        $form   = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a Catalogo entity.
     *
     * @Route("/{id}", name="sifda_catalogo_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MinsalsifdaBundle:Catalogo')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Catalogo entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing Catalogo entity.
     *
     * @Route("/{id}/edit", name="sifda_catalogo_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MinsalsifdaBundle:Catalogo')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Catalogo entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
    * Creates a form to edit a Catalogo entity.
    *
    * @param Catalogo $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Catalogo $entity)
    {
        $form = $this->createForm(new CatalogoType(), $entity, array(
            'action' => $this->generateUrl('sifda_catalogo_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Actualizar'));

        return $form;
    }
    /**
     * Edits an existing Catalogo entity.
     *
     * @Route("/{id}", name="sifda_catalogo_update")
     * @Method("PUT")
     * @Template("MinsalsifdaBundle:Catalogo:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MinsalsifdaBundle:Catalogo')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Catalogo entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('sifda_catalogo_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a Catalogo entity.
     *
     * @Route("/{id}", name="sifda_catalogo_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('MinsalsifdaBundle:Catalogo')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Catalogo entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

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

    /**
     * Creates a form to delete a Catalogo entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('sifda_catalogo_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Eliminar'))
            ->getForm()
        ;
    }
}


text:
package org.dashbuilder.client.navigation.event;

/**
 * Event fired when a perspective plugin is either added, renamed or deleted.
 */
public class PerspectivePluginsChangedEvent {

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>sakai-login-authn-tool</display-name>
    <description>sakai-login-authn-tool</description>

    <filter>
        <filter-name>sakai.request</filter-name>
        <filter-class>org.sakaiproject.util.RequestFilter</filter-class>
        <init-param>
            <param-name>context</param-name>
            <param-value>portal</param-value>
        </init-param>
   </filter>

    <filter-mapping>
        <filter-name>sakai.request</filter-name>
        <servlet-name>sakai.portal.authn</servlet-name>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
    </filter-mapping>

    <servlet>
    	<servlet-name>sakai.portal.authn</servlet-name>
        <servlet-class>org.sakaiproject.login.tool.AuthnPortal</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>sakai.portal.authn</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

</web-app>