text:
using System.Runtime.InteropServices;

namespace WinSCP
{
    [Guid("3BCB18EC-6D98-4BFB-A9C2-893CBD13CDAB")]
    [ClassInterface(Constants.ClassInterface)]
    [ComVisible(true)]
    public sealed class RemovalOperationResult : OperationResultBase
    {
        public RemovalEventArgsCollection Removals { get; private set; }

        internal RemovalOperationResult()
        {
            Removals = new RemovalEventArgsCollection();
        }

        internal void AddRemoval(RemovalEventArgs operation)
        {
            Removals.InternalAdd(operation);
        }
    }
}


text:
<?php

namespace Egulias\EmailValidator\Validation;

use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Exception\InvalidEmail;
use Egulias\EmailValidator\Validation\Error\SpoofEmail;
use \Spoofchecker;

class SpoofCheckValidation implements EmailValidation
{
    /**
     * @var InvalidEmail
     */
    private $error;

    public function isValid($email, EmailLexer $emailLexer)
    {
        $checker = new Spoofchecker();
        $checker->setChecks(Spoofchecker::SINGLE_SCRIPT);

        if ($checker->isSuspicious($email)) {
            $this->error = new SpoofEmail();
        }

        return $this->error === null;
    }

    public function getError()
    {
        return $this->error;
    }

    public function getWarnings()
    {
        return [];
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include <signal.h>

#include "message.h"

namespace shared
{
  namespace protocol
  {
    std::array<std::function<void (net::address const&, std::string const&)>,
               static_cast<size_t>(message::max)> notifiers;

    template <message M>
    static void subscribe()
    {
      using T = typename message_type<M>::type;

      notifiers[static_cast<size_t>(M)] = [](net::address const &a, std::string const &b)
      { pool_t::global().post<event<T>>({ a, deserialize<T>(b) }); };
    }

    void initialize()
    {
      /* TODO: More error/state checking in socket? */
      signal(SIGPIPE, SIG_IGN);

      subscribe<message::ping>();
      subscribe<message::pong>();

      subscribe<message::ask_stat>();
      subscribe<message::tell_stat>();
    }
  }
}


text:
  position: relative;
}

#input {
  margin: 0;
}

#autocomplete {
  position: absolute;
  list-style-type: none;
  border: 1px solid #8080ff;
  background-color: #f0f0ff;
  padding: 0;
  margin: 0;
  display: none;
}

#autocomplete .item {
  padding: 0.25em 0.5em;
  cursor: pointer;
}

#autocomplete .item:hover {
  background-color: #8080ff;
  color: #f0f0ff;
}

#autocomplete .var {
  font-weight: bold;
  font-family: monospace;
}


text:
/**
 * @file   confout.c
 *
 * <JA>
 * @brief  ¥³¥ó¥Ñ¥¤¥ë»þ¤ÎÀßÄê¤ò¥Æ¥¥¹¥È½ÐÎϤ¹¤ë
 * </JA>
 *
 * <EN>
 * @brief  Output compilation time configurations strings.
 * </EN>
 *
 * @author Akinobu LEE
 * @date   Thu Feb 17 15:34:39 2005
 *
 * $Revision: 1.9 $
 *
 */
/*
 * Copyright (c) 1991-2012 Kawahara Lab., Kyoto University
 * Copyright (c) 2000-2005 Shikano Lab., Nara Institute of Science and Technology
 * Copyright (c) 2005-2012 Julius project team, Nagoya Institute of Technology
 * All rights reserved
 */

#include <sent/stddefs.h>
#include <sent/util.h>
#include <sent/ngram2.h>
#include <sent/speech.h>
#include <sent/adin.h>

/**
 * Output version of this libsent library.
 *
 * @param strm [in] file pointer to output
 */
void
confout_version(FILE *strm)
{
  fprintf(strm, "version %s\n", LIBSENT_VERSION);
}

/**
 * Output audio configuration of this libsent library.
 *
 * @param strm [in] file pointer to output
 */
void
confout_audio(FILE *strm)
{
  fprintf(strm, " - Audio input\n");
#ifdef USE_MIC
  fprintf(strm, "    primary A/D-in driver   : %s (%s)\n", AUDIO_API_NAME, AUDIO_API_DESC);
#else
  fprintf(strm, "    primary A/D-in driver   : N/A\n");
#endif
  fprintf(strm, "    available drivers       :");
#ifdef HAS_ALSA
  fprintf(strm, " alsa");
#endif
#ifdef HAS_OSS
  fprintf(strm, " oss");
#endif
#ifdef HAS_ESD
  fprintf(strm, " esd");
#endif
#ifdef HAS_PULSEAUDIO
  fprintf(strm, " pulseaudio");
#endif
#ifdef USE_NETAUDIO
  fprintf(strm, " DATLink/NetAudio");
#endif
  fprintf(strm, "\n");
  fprintf(strm, "    wavefile formats        : %s\n", AUDIO_FORMAT_DESC);
  fprintf(strm, "    max. length of an input : %d samples, %d words\n", MAXSPEECHLEN, MAXSEQNUM);
}

/**
 * Output language model configuration of this libsent library.
 *
 * @param strm [in] file pointer to output
 */
void
confout_lm(FILE *strm)
{
  fprintf(strm, " - Language Model\n");
#ifdef CLASS_NGRAM
  fprintf(strm, "    class N-gram support    : yes\n");
#else
  fprintf(strm, "    class N-gram support    : no\n");
#endif
#ifdef WORDS_INT
  fprintf(strm, "    word id unit            : integer (%d bytes)\n", sizeof(WORD_ID));
#else
  fprintf(strm, "    word id unit            : short (%d bytes)\n", sizeof(WORD_ID));
#endif
}

/**
 * Output acoustic model configuration of this libsent library.
 *
 * @param strm [in] file pointer to output
 */
void
confout_am(FILE *strm)
{
  fprintf(strm, " - Acoustic Model\n");
/*
 * #ifdef MULTIPATH_VERSION
 *   fprintf(strm, "	multi-path HMM handling : yes\n");
 * #else
 *   fprintf(strm, "	multi-path HMM handling : no\n");
 * #endif
 */
  fprintf(strm, "    multi-path treatment    : autodetect\n");
#ifdef ENABLE_MSD
  fprintf(strm, "    MSD-HMM support         : yes\n");
#endif
}

/**
 * Output about linked libraries of this libsent library.
 *
 * @param strm [in] file pointer to output
 */
void
confout_lib(FILE *strm)
{
  fprintf(strm, " - External library\n");
  fprintf(strm, "    file decompression by   : %s\n", GZIP_READING_DESC);
}

/**
 * Output about process handling of this libsent library.
 *
 * @param strm [in] file pointer to output
 */
void
confout_process(FILE *strm)
{
  fprintf(strm, " - Process hangling\n");
#ifdef FORK_ADINNET
  fprintf(strm, "    fork on adinnet input   : yes\n");
#else
  fprintf(strm, "    fork on adinnet input   : no\n");
#endif
}

/**
 * Output all information of this libsent library.
 *
 * @param strm [in] file pointer to output
 */
void
confout(FILE *strm)
{
  confout_version(strm);
  confout_audio(strm);
  confout_lm(strm);
  confout_am(strm);
  confout_lib(strm);
  confout_process(strm);
}


text:
package org.apache.mina.proxy.event;

import org.apache.mina.core.filterchain.IoFilter.NextFilter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * IoSessionEvent.java - Wrapper Class for enqueued events.
 *
 * @author Apache MINA Project
 * @since MINA 2.0.0-M3
 */
public class IoSessionEvent {
    private static final Logger logger = LoggerFactory
            .getLogger(IoSessionEvent.class);

    /**
     * The next filter in the chain.
     */
    private final NextFilter nextFilter;

    /**
     * The session.
     */
    private final IoSession session;

    /**
     * The event type.
     */
    private final IoSessionEventType type;

    /**
     * The idle status if type value is {@link IoSessionEventType#IDLE},
     * null otherwise.
     */
    private IdleStatus status;

    /**
     * Creates an instance of this class when event type differs from
     * {@link IoSessionEventType#IDLE}.
     *
     * @param nextFilter the next filter
     * @param session the session
     * @param type the event type
     */
    public IoSessionEvent(final NextFilter nextFilter, final IoSession session,
            final IoSessionEventType type) {
        this.nextFilter = nextFilter;
        this.session = session;
        this.type = type;
    }

    /**
     * Creates an instance of this class when event type is
     * {@link IoSessionEventType#IDLE}.
     *
     * @param nextFilter the next filter
     * @param session the session
     * @param status the idle status
     */
    public IoSessionEvent(final NextFilter nextFilter, final IoSession session,
            final IdleStatus status) {
        this(nextFilter, session, IoSessionEventType.IDLE);
        this.status = status;
    }

    /**
     * Delivers this event to the next filter.
     */
    public void deliverEvent() {
        logger.debug("Delivering event {}", this);
        deliverEvent(this.nextFilter, this.session, this.type, this.status);
    }

    /**
     * Static method which effectively delivers the specified event to the next filter
     * nextFilter on the session.
     *
     * @param nextFilter the next filter
     * @param session the session on which the event occured
     * @param type the event type
     * @param status the idle status should only be non null only if the event type is
     * {@link IoSessionEventType#IDLE}
     */
    private static void deliverEvent(final NextFilter nextFilter,
            final IoSession session, final IoSessionEventType type,
            final IdleStatus status) {
        switch (type) {
        case CREATED:
            nextFilter.sessionCreated(session);
            break;
        case OPENED:
            nextFilter.sessionOpened(session);
            break;
        case IDLE:
            nextFilter.sessionIdle(session, status);
            break;
        case CLOSED:
            nextFilter.sessionClosed(session);
            break;
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(IoSessionEvent.class
                .getSimpleName());
        sb.append('@');
        sb.append(Integer.toHexString(hashCode()));
        sb.append(" - [ ").append(session);
        sb.append(", ").append(type);
        sb.append(']');
        return sb.toString();
    }

    /**
     * Returns the idle status of the event.
     *
     * @return the idle status of the event
     */
    public IdleStatus getStatus() {
        return status;
    }

    /**
     * Returns the next filter to which the event should be sent.
     *
     * @return the next filter
     */
    public NextFilter getNextFilter() {
        return nextFilter;
    }

    /**
     * Returns the session on which the event occured.
     *
     * @return the session
     */
    public IoSession getSession() {
        return session;
    }

    /**
     * Returns the event type that occured.
     *
     * @return the event type
     */
    public IoSessionEventType getType() {
        return type;
    }
}


text:
from south.db import db
from django.db import models

class Migration:

    needed_by = (
        ("otherfakeapp", "0003_third"),
    )

    def forwards(self):

        db.alter_column("southtest_spam", 'name', models.CharField(max_length=255, null=True))

    def backwards(self):

        db.alter_column("southtest_spam", 'name', models.CharField(max_length=255))

    models = {
        "fakeapp.bug135": {
            'date':  ('models.DateTimeField', [], {'default': 'datetime.datetime(2009, 5, 6, 15, 33, 15, 780013)'}),
        }
    }


text:
var reporter = require('nodeunit').reporters.default;
reporter.run([
'test',
'parser/test',
'plugins/test'
]);


text:
<?php

namespace Appoets\DefaultInstaller\Helpers;

class InstalledFileManager
{
    /**
     * Create installed file.
     *
     * @return int
     */
    public function create()
    {
        file_put_contents(storage_path('installed'), '');
    }

    /**
     * Update installed file.
     *
     * @return int
     */
    public function update()
    {
        return $this->create();
    }
}


text:
package com.intellij.debugger.impl;

import com.intellij.debugger.DebuggerTestCase;
import com.intellij.debugger.engine.DebugProcessImpl;
import com.intellij.debugger.engine.SuspendContextImpl;
import com.intellij.debugger.engine.events.SuspendContextCommandImpl;
import com.intellij.debugger.settings.NodeRendererSettings;
import com.intellij.debugger.ui.impl.watch.DebuggerTree;
import com.intellij.debugger.ui.impl.watch.DebuggerTreeNodeImpl;
import com.intellij.debugger.ui.impl.watch.NodeDescriptorImpl;
import com.intellij.debugger.ui.tree.NodeDescriptor;
import com.intellij.debugger.ui.tree.ValueDescriptor;
import com.intellij.debugger.ui.tree.render.NodeRenderer;
import com.intellij.execution.process.ProcessOutputTypes;
import com.intellij.openapi.util.Pair;
import com.intellij.ui.treeStructure.Tree;
import com.sun.jdi.Value;
import org.jetbrains.annotations.NotNull;

import javax.swing.tree.TreeNode;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public abstract class DescriptorTestCase extends DebuggerTestCase {
  private final List<Pair<NodeDescriptorImpl,List<String>>> myDescriptorLog = new ArrayList<>();

  public DescriptorTestCase() {
    super();
  }

  protected NodeRenderer getToStringRenderer() {
    return NodeRendererSettings.getInstance().getToStringRenderer();
  }

  protected NodeRenderer getMapRenderer() {
    return getAlternateCollectionRenderer("Map");
  }

  private static NodeRenderer getAlternateCollectionRenderer(final String name) {
    final NodeRenderer[] renderers = NodeRendererSettings.getInstance().getAlternateCollectionRenderers();
    for (NodeRenderer renderer : renderers) {
      if (name.equals(renderer.getName())) {
        return renderer;
      }
    }
    return null;
  }

  protected NodeRenderer getMapEntryRenderer() {
    return getAlternateCollectionRenderer("Map.Entry");
  }

  protected NodeRenderer getHexRenderer() {
    return NodeRendererSettings.getInstance().getHexRenderer();
  }

  protected NodeRenderer getCollectionRenderer() {
    return getAlternateCollectionRenderer("Collection");
  }

  @Override
  protected void resume(final SuspendContextImpl suspendContext) {
    final DebugProcessImpl localProcess = suspendContext.getDebugProcess();
    invokeRatherLater(new SuspendContextCommandImpl(suspendContext) {
      @Override
      public void contextAction(@NotNull SuspendContextImpl suspendContext) throws Exception {
        flushDescriptors();
        localProcess.getManagerThread().schedule(localProcess.createResumeCommand(suspendContext, Priority.LOW));
      }
    });
  }

  protected void logDescriptor(final NodeDescriptorImpl descriptor, String text) {
    Pair<NodeDescriptorImpl, List<String>> descriptorText = findDescriptorLog(descriptor);

    if(descriptorText == null) {
      ArrayList<String> allText = new ArrayList<>();
      allText.add(text);
      descriptorText = new Pair<>(descriptor, allText);
      myDescriptorLog.add(descriptorText);
    }
    else {
      List<String> allText = descriptorText.getSecond();
      if(!allText.get(allText.size() - 1).equals(text)) {
        allText.add(text);
      }
    }
  }

  private Pair<NodeDescriptorImpl, List<String>> findDescriptorLog(final NodeDescriptorImpl descriptor) {
    Pair<NodeDescriptorImpl, List<String>> descriptorText = null;
    for (Pair<NodeDescriptorImpl, List<String>> pair : myDescriptorLog) {
      if (pair.getFirst() == descriptor) {
        descriptorText = pair;
        break;
      }
    }
    return descriptorText;
  }

  protected void flushDescriptors() {
    for (Pair<NodeDescriptorImpl, List<String>> aMyDescriptorLog : myDescriptorLog) {
      printDescriptorLog(aMyDescriptorLog);
    }
    myDescriptorLog.clear();
  }

  private void printDescriptorLog(Pair<NodeDescriptorImpl, List<String>> pair) {
    for (String text : pair.getSecond()) {
      print(text, ProcessOutputTypes.SYSTEM);
    }
  }

  @Override
  protected void tearDown() throws Exception {
    try {
      flushDescriptors();
    }
    catch (Throwable e) {
      addSuppressedException(e);
    }
    finally {
      super.tearDown();
    }
  }

  protected void expandAll(final DebuggerTree tree, final Runnable runnable) {
    expandAll(tree, runnable, new HashSet<>(), null);
  }

  protected interface NodeFilter {
    boolean shouldExpand(TreeNode node);
  }

  protected void expandAll(final DebuggerTree tree, final Runnable runnable, final Set<Value> alreadyExpanded, final NodeFilter filter) {
    expandAll(tree, runnable, alreadyExpanded, filter, tree.getDebuggerContext().getSuspendContext());
  }

  protected void expandAll(final Tree tree,
                           final Runnable runnable,
                           final Set<Value> alreadyExpanded,
                           final NodeFilter filter,
                           final SuspendContextImpl context) {
    invokeRatherLater(context, () -> {
      boolean anyCollapsed = false;
      for(int i = 0; i < tree.getRowCount(); i++) {
        final TreeNode treeNode = (TreeNode)tree.getPathForRow(i).getLastPathComponent();
        if(tree.isCollapsed(i) && !treeNode.isLeaf()) {
          NodeDescriptor nodeDescriptor = null;
          if (treeNode instanceof DebuggerTreeNodeImpl) {
            nodeDescriptor = ((DebuggerTreeNodeImpl)treeNode).getDescriptor();
          }
          boolean shouldExpand = filter == null || filter.shouldExpand(treeNode);
          if (shouldExpand) {
            // additional checks to prevent infinite expand
            if (nodeDescriptor instanceof ValueDescriptor) {
              final Value value = ((ValueDescriptor)nodeDescriptor).getValue();
              shouldExpand = !alreadyExpanded.contains(value);
              if (shouldExpand) {
                alreadyExpanded.add(value);
              }
            }
          }
          if (shouldExpand) {
            anyCollapsed = true;
            tree.expandRow(i);
          }
        }
      }

      if (anyCollapsed) {
        expandAll(tree, runnable, alreadyExpanded, filter, context);
      }
      else {
        runnable.run();
      }
    });
  }
}


text:
%% s_scielabMasking
%
% In s_scielabMTF, we calculate the delta E between
% a uniform patch and a targets with different frequencies at 50% contrast.
% Plotting delta E as function of target frequency gives us an MTF
%
% In this script,we keep the frequency and contrast of a background (mask) constant and
% increase the contrast of the target until we reach a fixed delta E value
% (e.g. DE = 5).  We record this as contrast treshold and plot it as a
% function of the background contrast

%
% Copyright Imageval 2012

%%  Initialize ISET and the parameters
ieInit

%%
% List of frequencies to test
fList = [2,4,8,16,32];
nFreq = length(fList);
% List of mask contrasts to test
mList = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, .7, 0.8, 0.9];
nMaskContrast = length(mList);
% List of target contrasts to test
tList = (0.05:0.05:0.2);
nTargetContrast = length(tList);

% Allocate space for the two types of delta E values
dE = ones(nTargetContrast,1);
dES = ones(nTargetContrast,1);

%% fixed parameters
parms.ph = 0; parms.ang= 0;
parms.row = 128; parms.col = 128;
parms.GaborFlag=0;
%% could vary frequency later
parms.freq = fList(2);
%%
maskContrast = 0.8;
parms.contrast = maskContrast;
Mask = sceneCreate('harmonic',parms);
Mask= sceneSet(Mask,'fov',1);
Mask = sceneSet(Mask,'name','Mask');
vcAddAndSelectObject(Mask); sceneWindow;
whiteXYZ    = sceneGet(Mask,'illuminant xyz')* 2;
illuminantE = sceneGet(Mask,'illuminant energy');
wave   = sceneGet(Mask,'wave');
nWave  = sceneGet(Mask,'nwave');
lambda = (1:nWave)/nWave;

% Make a target with same spatial frequency as mask but increase contrast
for ii = 1:nTargetContrast
    parms.contrast = tList(ii);
    Target = sceneCreate('harmonic',parms);
    Target = sceneSet(Target,'fov',1);
    Target = sceneSet(Target,'name','Target');
    uTarget = sceneAdd(Mask,Target,'remove spatial mean');
    uTarget = sceneSet(uTarget,'name','Target + Mask');
    vcAddAndSelectObject(uTarget); sceneWindow;

    % Compute CIELAB difference
    xyz1   = sceneGet(Mask,'xyz');    xyz1(xyz1<0) = 0;
    xyz2   = sceneGet(uTarget,'xyz'); xyz2(xyz2<0) = 0;
    tmp    = deltaEab(xyz1,xyz2,whiteXYZ,'2000');
    dE(ii) = mean(tmp(:));

    % Compute S-CIELAB difference map
    tmp = scielab(xyz1,xyz2,whiteXYZ,scParams);
    dES(ii) = mean(tmp(:));

end

%% Compare delta E values computed the two ways
vcNewGraphWin;
semilogx(tList,dES(:),'-s',tList,dE(:),':o')
set(gca,'ylim',[0 max(dE(:))*1.2])
xlabel('Target Contrast')
ylabel('delta E')
title(sprintf('Frequency = %.2f, Mask Contrast = %0.2f',parms.freq,maskContrast));
grid on
legend('S-CIELAB','CIELAB')

%% End


text:
/* Generated By:JJTree: Do not edit this line. JDMTrapItem.java */

package com.sun.jmx.snmp.IPAcl;

class JDMTrapItem extends SimpleNode {
  protected JDMTrapCommunity comm = null;

  JDMTrapItem(int id) {
    super(id);
  }

  JDMTrapItem(Parser p, int id) {
    super(p, id);
  }

  public static Node jjtCreate(int id) {
      return new JDMTrapItem(id);
  }

  public static Node jjtCreate(Parser p, int id) {
      return new JDMTrapItem(p, id);
  }

  public JDMTrapCommunity getCommunity(){
        return comm;
  }
}


text:
package org.djodjo.tarator.action;

import org.djodjo.tarator.UiController;

/**
 * Interface to implement different swipe types.
 */
public interface Swiper {

  /**
   * The result of the swipe.
   */
  public enum Status {
    /**
     * The swipe action completed successfully.
     */
    SUCCESS,
    /**
     * Injecting the event was a complete failure.
     */
    FAILURE
  }

  /**
   * Swipes from {@code startCoordinates} to {@code endCoordinates} using the given
   * {@code uiController} to send {@link android.view.MotionEvent}s.
   *
   * @param uiController a UiController to use to send MotionEvents to the screen.
   * @param startCoordinates a float[] with x and y co-ordinates of the start of the swipe.
   * @param endCoordinates a float[] with x and y co-ordinates of the end of the swipe.
   * @param precision a float[] with x and y values of precision of the tap.
   * @return The status of the swipe.
   */
  public Status sendSwipe(UiController uiController, float[] startCoordinates,
                          float[] endCoordinates, float[] precision);

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:rs="http://www.openarchives.org/rs/terms/">
    <rs:md capability="resourcelist" modified="{{ MOST_RECENT_BAGGING_DATE }}"/>
{% for location in sitemaps %}<sitemap><loc>{{ location }}</loc></sitemap>{% endfor %}
</sitemapindex>


text:
class I2C:

    def __enter__(self):
        raise NotImplementedError()

    def __exit__(self, exc_type, exc_value, traceback):
        raise NotImplementedError()

    def read(self, address, count):
        raise NotImplementedError()

    def write(self, address, data):
        raise NotImplementedError()

    def transaction(self, address, data, read_len):
        raise NotImplementedError()

class I2CProducer:

    def I2C(self, name, clock=15000, *args, **kwargs):
        raise NotImplementedError()


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

{% block content_block %}

Edit

{% if reports %}
Owner of the File : {{reports.creator}}

    <form id="edit_report" enctype="multipart/form-data"  method="post" action="/reports/edit/{{ reports.name }}/">
            {% csrf_token %}
            File name: <input type="text" name="name" value="{{ reports.name }}" size="30" />

            Keyword: <input type="text" name="keyword" value="{{ reports.name }}" size="30" />

            Short Description: <input type="text" name="description" value="{{ reports.description }}" size="30" />

            Long Description: <input type="text" name="longDescription" value="{{ reports.longDescription }}" size="30" />

            Upload:<input multiple type="file" name="path" size="30"/>
	    {% for file in files %}
	    {{file.path}}Delete

	    {% endfor %}

            {% if reports.private %}
	    Private:<input type="checkbox" name="private" checked="{{ reports.private }}"/>
	    {% else %}
            Private:<input type="checkbox" name="private"/>
            {% endif %}

            {% if is_owner %}
            Folder:  <select name="folder">
            {% if folders %}
            {% for folder in folders %}
            <option value="{{ folder.name }}">{{  folder.name}}</option>
	    {% endfor %}
            {% endif %}
            </select>

            {% endif %}
               {% if reports.encrypted %}

             Encrypted:<input type="checkbox" name="encrypted" checked="{{ reports.encrypted }}"/>

              {% else %}
              Encrypted:<input type="checkbox" name="encrypted"/>

              {% endif %}

              <input type="submit" name="submit" value="Upload Report" />
        </form>

    {% else %}
        There are no reports!

{% endif %}

{% endblock %}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE617_Reachable_Assertion__fgets_43.cpp
Label Definition File: CWE617_Reachable_Assertion.label.xml
Template File: sources-sink-43.tmpl.cpp
*/
/*
 * @description
 * CWE: 617 Reachable Assertion
 * BadSource: fgets Read data from the console using fgets()
 * GoodSource: Number greater than ASSERT_VALUE
 * Sinks:
 *    BadSink : Assert if n is less than or equal to ASSERT_VALUE
 * Flow Variant: 43 Data flow: data flows using a C++ reference from one function to another in the same source file
 *
 * */

#include "std_testcase.h"

#include <assert.h>

#define ASSERT_VALUE 5

#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)

namespace CWE617_Reachable_Assertion__fgets_43
{

#ifndef OMITBAD

static void badSource(int &data)
{
    {
        char inputBuffer[CHAR_ARRAY_SIZE] = "";
        /* POTENTIAL FLAW: Read data from the console using fgets() */
        if (fgets(inputBuffer, CHAR_ARRAY_SIZE, stdin) != NULL)
        {
            /* Convert to int */
            data = atoi(inputBuffer);
        }
        else
        {
            printLine("fgets() failed.");
        }
    }
}

void bad()
{
    int data;
    /* Initialize data */
    data = -1;
    badSource(data);
    /* POTENTIAL FLAW: this assertion could trigger if n <= ASSERT_VALUE */
    assert(data > ASSERT_VALUE);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2BSource(int &data)
{
    /* FIX: Use a value greater than the assert value */
    data = ASSERT_VALUE+1;
}

static void goodG2B()
{
    int data;
    /* Initialize data */
    data = -1;
    goodG2BSource(data);
    /* POTENTIAL FLAW: this assertion could trigger if n <= ASSERT_VALUE */
    assert(data > ASSERT_VALUE);
}

void good()
{
    goodG2B();
}

#endif /* OMITGOOD */

} /* close namespace */

/* Below is the main(). It is only used when building this testcase on
 * its own for testing or for building a binary to use in testing binary
 * analysis tools. It is not used when compiling all the testcases as one
 * application, which is how source code analysis tools are tested.
 */

#ifdef INCLUDEMAIN

using namespace CWE617_Reachable_Assertion__fgets_43; /* so that we can use good and bad easily */

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
<?php
namespace Topxia\Service\MoneyCard;

interface MoneyCardService
{
    /**
    * 输入数组
    * key1: @money 充值的金额
    * key2: @cardPrefix  帐号的前缀
    * key3: @cardLength  帐号的长度
    * key4: @number  生成本批次帐号的数目
    * key5: @note 本次充值的备注
    * key6: @deadline 截止失效日期
    * key7: @passwordLength 密码长度
    *
    * 返回值 array()
    * 本批次充值生成的记录
    **/

    public function createMoneyCard (array $moneyCardData);

	public function getMoneyCard ($id);

    public function getMoneyCardByIds($ids);

    public function getBatch ($id);

	public function searchMoneyCards (array $conditions, array $oderBy, $start, $limit);

    public function searchMoneyCardsCount(array $conditions);

    public function searchBatchs(array $conditions, array $oderBy, $start, $limit);

    public function searchBatchsCount(array $conditions);

    public function lockMoneyCard ($id);

    public function unlockMoneyCard ($id);

    public function deleteMoneyCard ($id);

    public function lockBatch ($id);

    public function unlockBatch ($id);

    public function deleteBatch ($id);

}


text:
title: Clear Xcode
date: "2018-01-31"
path: "/posts/clear-xcode/"
---
Xcode has a tendency to hog precious harddrive space. This post lists some things you can do to clear some of that. I managed to remove 100 GB, which is almost half of my current computer's storage...

### 1. Manage your runtimes
If you have had Xcode installed for a while you have probably accumulated a few iOS runtime versions you no longer support. Go to `~/Library/Developer/CoreSimulator/Profiles/Runtimes` and delete the ones you no longer use.

### 2. Manage your simulators
Using the terminal you are able to list all the installed simulators. In here you might find some devices that aren't available anymore (due to removed runtimes). You list the devices with the following command.
```bash
// List all the device simulators
xcrun simctl list
```
To remove the unavailable devices run the following command. You are also able to delete explicit devices.
```bash
// Remove all unavailable devices
xcrun simctl delete unavailable
```
Lastly you clear all the caches and contents and settings for all devices.
```bash
// Clear contents and settings of all devices
xcrun simctl erase all
```

### 3. Delete derived data
The classic memory hog. You are able to delete this from within Xcode, but if you prefer to do it manually you can go to `~/Library/Developer/Xcode/DerivedData` and purge it.

### 4. Archives
You can clear up the folders in `~/Library/Developer/Xcode/Archives` for apps which you no longer need the dSYM data for debugging.

### 5. Delete iOS/tvOS/watchOS device support
This was a big one for me. The `~/Library/Developer/Xcode/iOS DeviceSupport` folder contains information about all devices you've used during development. This can be removed and will be regenerated once you use the device again.

### 6. Clear logs, snapshot and cache
In `~/Library/Developer/Xcode/` you'll find device log folders. These can be cleared for the ones you don't care about. Same applies for the snapshots folder. Lastly you can clear the Xcode cache which is located at `~/Library/Caches/com.apple.dt.Xcode`.

Happy purging!


text:
/**
 * @file
 *   This file implements ICMPv6.
 */

#include "icmp6.hpp"

#include "common/code_utils.hpp"
#include "common/debug.hpp"
#include "common/instance.hpp"
#include "common/locator_getters.hpp"
#include "common/log.hpp"
#include "common/message.hpp"
#include "net/checksum.hpp"
#include "net/ip6.hpp"

namespace ot {
namespace Ip6 {

RegisterLogModule("Icmp6");

Icmp::Icmp(Instance &aInstance)
    : InstanceLocator(aInstance)
    , mEchoSequence(1)
    , mEchoMode(OT_ICMP6_ECHO_HANDLER_ALL)
{
}

Message *Icmp::NewMessage(uint16_t aReserved)
{
    return Get<Ip6>().NewMessage(sizeof(Header) + aReserved);
}

Error Icmp::RegisterHandler(Handler &aHandler)
{
    return mHandlers.Add(aHandler);
}

Error Icmp::SendEchoRequest(Message &aMessage, const MessageInfo &aMessageInfo, uint16_t aIdentifier)
{
    Error       error = kErrorNone;
    MessageInfo messageInfoLocal;
    Header      icmpHeader;

    messageInfoLocal = aMessageInfo;

    icmpHeader.Clear();
    icmpHeader.SetType(Header::kTypeEchoRequest);
    icmpHeader.SetId(aIdentifier);
    icmpHeader.SetSequence(mEchoSequence++);

    SuccessOrExit(error = aMessage.Prepend(icmpHeader));
    aMessage.SetOffset(0);
    SuccessOrExit(error = Get<Ip6>().SendDatagram(aMessage, messageInfoLocal, kProtoIcmp6));

    LogInfo("Sent echo request: (seq = %d)", icmpHeader.GetSequence());

exit:
    return error;
}

Error Icmp::SendError(Header::Type aType, Header::Code aCode, const MessageInfo &aMessageInfo, const Message &aMessage)
{
    Error   error;
    Headers headers;

    SuccessOrExit(error = headers.ParseFrom(aMessage));
    error = SendError(aType, aCode, aMessageInfo, headers);

exit:
    return error;
}

Error Icmp::SendError(Header::Type aType, Header::Code aCode, const MessageInfo &aMessageInfo, const Headers &aHeaders)
{
    Error             error = kErrorNone;
    MessageInfo       messageInfoLocal;
    Message *         message = nullptr;
    Header            icmp6Header;
    Message::Settings settings(Message::kWithLinkSecurity, Message::kPriorityNet);

    if (aHeaders.GetIpProto() == kProtoIcmp6)
    {
        VerifyOrExit(!aHeaders.GetIcmpHeader().IsError());
    }

    messageInfoLocal = aMessageInfo;

    VerifyOrExit((message = Get<Ip6>().NewMessage(0, settings)) != nullptr, error = kErrorNoBufs);

    // Prepare the ICMPv6 error message. We only include the IPv6 header
    // of the original message causing the error.

    icmp6Header.Clear();
    icmp6Header.SetType(aType);
    icmp6Header.SetCode(aCode);
    SuccessOrExit(error = message->Append(icmp6Header));
    SuccessOrExit(error = message->Append(aHeaders.GetIp6Header()));

    SuccessOrExit(error = Get<Ip6>().SendDatagram(*message, messageInfoLocal, kProtoIcmp6));

    LogInfo("Sent ICMPv6 Error");

exit:
    FreeMessageOnError(message, error);
    return error;
}

Error Icmp::HandleMessage(Message &aMessage, MessageInfo &aMessageInfo)
{
    Error  error = kErrorNone;
    Header icmp6Header;

    SuccessOrExit(error = aMessage.Read(aMessage.GetOffset(), icmp6Header));

    SuccessOrExit(error = Checksum::VerifyMessageChecksum(aMessage, aMessageInfo, kProtoIcmp6));

    if (icmp6Header.GetType() == Header::kTypeEchoRequest)
    {
        SuccessOrExit(error = HandleEchoRequest(aMessage, aMessageInfo));
    }

    aMessage.MoveOffset(sizeof(icmp6Header));

    for (Handler &handler : mHandlers)
    {
        handler.HandleReceiveMessage(aMessage, aMessageInfo, icmp6Header);
    }

exit:
    return error;
}

bool Icmp::ShouldHandleEchoRequest(const MessageInfo &aMessageInfo)
{
    bool rval = false;

    switch (mEchoMode)
    {
    case OT_ICMP6_ECHO_HANDLER_DISABLED:
        rval = false;
        break;
    case OT_ICMP6_ECHO_HANDLER_UNICAST_ONLY:
        rval = !aMessageInfo.GetSockAddr().IsMulticast();
        break;
    case OT_ICMP6_ECHO_HANDLER_MULTICAST_ONLY:
        rval = aMessageInfo.GetSockAddr().IsMulticast();
        break;
    case OT_ICMP6_ECHO_HANDLER_ALL:
        rval = true;
        break;
    }

    return rval;
}

Error Icmp::HandleEchoRequest(Message &aRequestMessage, const MessageInfo &aMessageInfo)
{
    Error       error = kErrorNone;
    Header      icmp6Header;
    Message *   replyMessage = nullptr;
    MessageInfo replyMessageInfo;
    uint16_t    payloadLength;

    // always handle Echo Request destined for RLOC or ALOC
    VerifyOrExit(ShouldHandleEchoRequest(aMessageInfo) || aMessageInfo.GetSockAddr().GetIid().IsLocator());

    LogInfo("Received Echo Request");

    icmp6Header.Clear();
    icmp6Header.SetType(Header::kTypeEchoReply);

    if ((replyMessage = Get<Ip6>().NewMessage(0)) == nullptr)
    {
        LogDebg("Failed to allocate a new message");
        ExitNow();
    }

    payloadLength = aRequestMessage.GetLength() - aRequestMessage.GetOffset() - Header::kDataFieldOffset;
    SuccessOrExit(error = replyMessage->SetLength(Header::kDataFieldOffset + payloadLength));

    replyMessage->WriteBytes(0, &icmp6Header, Header::kDataFieldOffset);
    aRequestMessage.CopyTo(aRequestMessage.GetOffset() + Header::kDataFieldOffset, Header::kDataFieldOffset,
                           payloadLength, *replyMessage);

    replyMessageInfo.SetPeerAddr(aMessageInfo.GetPeerAddr());

    if (!aMessageInfo.GetSockAddr().IsMulticast())
    {
        replyMessageInfo.SetSockAddr(aMessageInfo.GetSockAddr());
    }

    SuccessOrExit(error = Get<Ip6>().SendDatagram(*replyMessage, replyMessageInfo, kProtoIcmp6));

    IgnoreError(replyMessage->Read(replyMessage->GetOffset(), icmp6Header));
    LogInfo("Sent Echo Reply (seq = %d)", icmp6Header.GetSequence());

exit:
    FreeMessageOnError(replyMessage, error);
    return error;
}

} // namespace Ip6
} // namespace ot


text:
using namespace arangodb;
using namespace arangodb::cache;

TEST_CASE("lock stress test", "[cache][!hide][longRunning]") {
  SECTION("test transactionality for mixed workload") {
    RandomGenerator::initialize(RandomGenerator::RandomType::MERSENNE);
    MockScheduler scheduler(4);
    Manager manager(scheduler.ioService(), 32 * 1024 * 1024);
    TransactionalStore store(&manager);
    uint64_t totalDocuments = 1000000;
    uint64_t readBatchSize = 10000;
    uint64_t numBatches = 250;
    size_t readerCount = 24;

    // initial fill
    for (uint64_t i = 1; i <= totalDocuments; i++) {
      store.insert(nullptr, TransactionalStore::Document(i));
    }

    auto readWorker = [&store, totalDocuments,
                       readBatchSize, numBatches]() -> void {
      for (uint64_t batch = 0; batch < numBatches; batch++) {
        auto tx = store.beginTransaction(true);
        for (uint64_t i = 0; i < readBatchSize; i++) {
          uint64_t choice = RandomGenerator::interval(totalDocuments);
          if (choice == 0) {
            choice = 1;
          }

          auto d = store.lookup(tx, choice);
          TRI_ASSERT(!d.empty());
        }
        bool ok = store.commit(tx);
        TRI_ASSERT(ok);
      }
    };

    auto start = std::chrono::high_resolution_clock::now();

    std::vector<std::thread*> threads;
    // dispatch reader threads
    for (size_t i = 0; i < readerCount; i++) {
      threads.push_back(new std::thread(readWorker));
    }

    // join threads
    for (auto t : threads) {
      t->join();
      delete t;
    }

    auto end = std::chrono::high_resolution_clock::now();
    std::cout << "time: " << static_cast<double>((end - start).count()) / 1000000000 << std::endl;

    RandomGenerator::shutdown();
  }
}


text:
'''
Top level package command wrapper, used to translate the os detected by grains
to the correct service manager

.. important::
    If you feel that Salt should be using this module to manage services on a
    minion, and it is using a different module (or gives an error similar to
    *'service.start' is not available*), see :ref:`here
    <module-provider-override>`.
'''

# Import Python libs
from __future__ import absolute_import

# Define the module's virtual name
__virtualname__ = 'service'

def __virtual__():
    '''
    Only work on systems which default to systemd
    '''
    if __grains__['os'] == 'Gentoo':
        return __virtualname__
    return (False, 'The gentoo_service execution module cannot be loaded: '
            'only available on Gentoo systems.')

def get_enabled():
    '''
    Return a list of service that are enabled on boot

    CLI Example:

    .. code-block:: bash

        salt '*' service.get_enabled
    '''
    ret = set()
    lines = __salt__['cmd.run']('rc-update show').splitlines()
    for line in lines:
        if '|' not in line:
            continue
        if 'shutdown' in line:
            continue
        ret.add(line.split('|')[0].strip())
    return sorted(ret)

def get_disabled():
    '''
    Return a set of services that are installed but disabled

    CLI Example:

    .. code-block:: bash

        salt '*' service.get_disabled
    '''
    ret = set()
    lines = __salt__['cmd.run']('rc-update -v show').splitlines()
    for line in lines:
        if '|' not in line:
            continue
        elif 'shutdown' in line:
            continue
        comps = line.split()
        if len(comps) < 3:
            ret.add(comps[0])
    return sorted(ret)

def available(name):
    '''
    Returns ``True`` if the specified service is available, otherwise returns
    ``False``.

    CLI Example:

    .. code-block:: bash

        salt '*' service.available sshd
    '''
    return name in get_all()

def missing(name):
    '''
    The inverse of service.available.
    Returns ``True`` if the specified service is not available, otherwise returns
    ``False``.

    CLI Example:

    .. code-block:: bash

        salt '*' service.missing sshd
    '''
    return name not in get_all()

def get_all():
    '''
    Return all available boot services

    CLI Example:

    .. code-block:: bash

        salt '*' service.get_all
    '''
    return sorted(get_enabled() + get_disabled())

def start(name):
    '''
    Start the specified service

    CLI Example:

    .. code-block:: bash

        salt '*' service.start <service name>
    '''
    cmd = '/etc/init.d/{0} start'.format(name)
    return not __salt__['cmd.retcode'](cmd, python_shell=False)

def stop(name):
    '''
    Stop the specified service

    CLI Example:

    .. code-block:: bash

        salt '*' service.stop <service name>
    '''
    cmd = '/etc/init.d/{0} stop'.format(name)
    return not __salt__['cmd.retcode'](cmd, python_shell=False)

def restart(name):
    '''
    Restart the named service

    CLI Example:

    .. code-block:: bash

        salt '*' service.restart <service name>
    '''
    cmd = '/etc/init.d/{0} restart'.format(name)
    return not __salt__['cmd.retcode'](cmd, python_shell=False)

def status(name, sig=None):
    '''
    Return the status for a service, returns the PID or an empty string if the
    service is running or not, pass a signature to use to find the service via
    ps

    CLI Example:

    .. code-block:: bash

        salt '*' service.status <service name> [service signature]
    '''
    return __salt__['status.pid'](sig if sig else name)

def enable(name, **kwargs):
    '''
    Enable the named service to start at boot

    CLI Example:

    .. code-block:: bash

        salt '*' service.enable <service name>
    '''
    cmd = 'rc-update add {0} default'.format(name)
    return not __salt__['cmd.retcode'](cmd, python_shell=False)

def disable(name, **kwargs):
    '''
    Disable the named service to start at boot

    CLI Example:

    .. code-block:: bash

        salt '*' service.disable <service name>
    '''
    cmd = 'rc-update delete {0} default'.format(name)
    return not __salt__['cmd.retcode'](cmd, python_shell=False)

def enabled(name, **kwargs):
    '''
    Return True if the named service is enabled, false otherwise

    CLI Example:

    .. code-block:: bash

        salt '*' service.enabled <service name>
    '''
    return name in get_enabled()

def disabled(name):
    '''
    Return True if the named service is enabled, false otherwise

    CLI Example:

    .. code-block:: bash

        salt '*' service.disabled <service name>
    '''
    return name in get_disabled()


text:
' Copyright (c) 2015 ZZZ Projects. All rights reserved
' Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods)
' Website: http://www.zzzprojects.com/
' Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927
' All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library

Public Module Extensions_457

	''' <summary>
	'''     Returns an indication whether the specified object is of type .
	''' </summary>
	''' <typeparam name="T">Generic type parameter.</typeparam>
	''' <param name="value">An object.</param>
	''' <returns>true if  is of type ; otherwise, false.</returns>
	<System.Runtime.CompilerServices.Extension> _
	Public Function IsDBNull(Of T As Class)(value As T) As [Boolean]
		Return Convert.IsDBNull(value)
	End Function
End Module


text:
require 'spec_helper'

describe Survey do

  it 'should have many questions' do
    survey1 = Survey.create!
    expect(survey1.questions).to eq []
    question1 = Question.create!(survey: survey1)
    question2 = Question.create!(survey: survey1)
    question3 = Question.create!(survey: survey1)
    survey1.reload
    expect(survey1.questions).to eq [question1,question2,question3]
    question1.reload
    expect(question1.survey).to eq survey1
  end

end


text:
require File.dirname(__FILE__) + '/../../spec_helper'
require File.dirname(__FILE__) + '/fixtures/classes'

describe "Array#select" do
  it "returns a new array of elements for which block is true" do
    [1, 3, 4, 5, 6, 9].select { |i| i % ((i + 1) / 2) == 0}.should == [1, 4, 6]
  end

  it "does not return subclass instance on Array subclasses" do
    ArraySpecs::MyArray[1, 2, 3].select { true }.class.should == Array
  end

  it "properly handles recursive arrays" do
    empty = ArraySpecs.empty_recursive_array
    empty.select { true }.should == empty
    empty.select { false }.should == []

    array = ArraySpecs.recursive_array
    array.select { true }.should == [1, 'two', 3.0, array, array, array, array, array]
    array.select { false }.should == []
  end

end


text:
from rest_framework import permissions, viewsets, status, views
from rest_framework.response import Response

from authentication.models import Account
from authentication.permissions import IsAccountOwner
from authentication.serializers import AccountSerializer

import json

from django.contrib.auth import authenticate, login, logout

class AccountViewSet(viewsets.ModelViewSet):
    lookup_field = 'username'
    queryset = Account.objects.all()
    serializer_class = AccountSerializer

    def get_permissions(self):
        if self.request.method in permissions.SAFE_METHODS:
            return (permissions.AllowAny(),)

        if self.request.method == 'POST':
            return (permissions.AllowAny(),)

        return (permissions.IsAuthenticated(), IsAccountOwner(),)

    def create(self, request):
        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid():
            Account.objects.create_user(**serializer.validated_data)

            return Response(serializer.validated_data, status=status.HTTP_201_CREATED)

        return Response({
            'status': 'Bad request',
            'message': 'Account could not be created with received data.'
        }, status=status.HTTP_400_BAD_REQUEST)

class LoginView(views.APIView):
    def post(self, request, format=None):
        data = json.loads(request.body)

        email = data.get('email', None)
        password = data.get('password', None)

        account = authenticate(email=email, password=password)

        if account is not None:
            if account.is_active:
                login(request, account)

                serialized = AccountSerializer(account)

                return Response(serialized.data)
            else:
                return Response({
                    'status': 'Unauthorized',
                    'message': 'This account has been disabled.'
                }, status=status.HTTP_401_UNAUTHORIZED)
        else:
            return Response({
                'status': 'Unauthorized',
                'message': 'Username/password combination invalid.'
            }, status=status.HTTP_401_UNAUTHORIZED)

class LogoutView(views.APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def post(self, request, format=None):
        logout(request)

        return Response({}, status=status.HTTP_204_NO_CONTENT)


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pgmacdesign.smsverification" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:name=".notusedatm.MyApplication"
        android:theme="@style/MyMaterialTheme"
        >

    <!--
        <activity
            android:name=".myfiles.FirstActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        -->
        <activity
            android:name=".myfiles.MainActivity2"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".myfiles.MainActivity"
            android:label="@string/app_name" >
        </activity>

        <!-- SMS Receiver -->
        <receiver android:name=".myfiles.SmsReceiver">
            <intent-filter android:priority="99999">
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

        <!-- Intent service -->
        <service
            android:name=".notusedatm.HttpService"
            android:exported="false" />

    </application>

</manifest>


text:
CXX=g++
CXXFLAGS=-Wall -c

all: student

student: student.o main.o
	$(CXX) student.o main.o -o student

student.o: student.cpp student.h
	$(CXX) $(CXXFLAGS) student.cpp

main.o: main.cpp student.h
	$(CXX) $(CXXFLAGS) main.cpp

clean:
	rm -rf *.o student


text:
package com.alibaba.rocketmq.client.consumer;

import com.alibaba.rocketmq.client.ClientConfig;
import com.alibaba.rocketmq.client.QueryResult;
import com.alibaba.rocketmq.client.consumer.rebalance.AllocateMessageQueueAveragely;
import com.alibaba.rocketmq.client.consumer.store.OffsetStore;
import com.alibaba.rocketmq.client.exception.MQBrokerException;
import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.client.impl.consumer.DefaultMQPullConsumerImpl;
import com.alibaba.rocketmq.common.MixAll;
import com.alibaba.rocketmq.common.message.MessageDecoder;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.alibaba.rocketmq.common.message.MessageId;
import com.alibaba.rocketmq.common.message.MessageQueue;
import com.alibaba.rocketmq.common.protocol.heartbeat.MessageModel;
import com.alibaba.rocketmq.remoting.RPCHook;
import com.alibaba.rocketmq.remoting.exception.RemotingException;

import java.util.HashSet;
import java.util.Set;

/**
 * Default pulling consumer
 *
 * @author shijia.wxr
 */
public class DefaultMQPullConsumer extends ClientConfig implements MQPullConsumer {
    protected final transient DefaultMQPullConsumerImpl defaultMQPullConsumerImpl;

    /**
     * Do the same thing for the same Group, the application must be set,and
     * guarantee Globally unique
     */
    private String consumerGroup;
    /**
     * Long polling mode, the Consumer connection max suspend time, it is not
     * recommended to modify
     */
    private long brokerSuspendMaxTimeMillis = 1000 * 20;
    /**
     * Long polling mode, the Consumer connection timeout(must greater than
     * brokerSuspendMaxTimeMillis), it is not recommended to modify
     */
    private long consumerTimeoutMillisWhenSuspend = 1000 * 30;
    /**
     * The socket timeout in milliseconds
     */
    private long consumerPullTimeoutMillis = 1000 * 10;
    /**
     * Consumption pattern,default is clustering
     */
    private MessageModel messageModel = MessageModel.CLUSTERING;
    /**
     * Message queue listener
     */
    private MessageQueueListener messageQueueListener;
    /**
     * Offset Storage
     */
    private OffsetStore offsetStore;
    /**
     * Topic set you want to register
     */
    private Set<String> registerTopics = new HashSet<String>();
    /**
     * Queue allocation algorithm
     */
    private AllocateMessageQueueStrategy allocateMessageQueueStrategy = new AllocateMessageQueueAveragely();
    /**
     * Whether the unit of subscription group
     */
    private boolean unitMode = false;

    private int maxReconsumeTimes = 16;

    public DefaultMQPullConsumer() {
        this(MixAll.DEFAULT_CONSUMER_GROUP, null);
    }

    public DefaultMQPullConsumer(final String consumerGroup, RPCHook rpcHook) {
        this.consumerGroup = consumerGroup;
        defaultMQPullConsumerImpl = new DefaultMQPullConsumerImpl(this, rpcHook);
    }

    public DefaultMQPullConsumer(final String consumerGroup) {
        this(consumerGroup, null);
    }

    public DefaultMQPullConsumer(RPCHook rpcHook) {
        this(MixAll.DEFAULT_CONSUMER_GROUP, rpcHook);
    }

    @Override
    public void createTopic(String key, String newTopic, int queueNum) throws MQClientException {
        createTopic(key, newTopic, queueNum, 0);
    }

    @Override
    public void createTopic(String key, String newTopic, int queueNum, int topicSysFlag) throws MQClientException {
        this.defaultMQPullConsumerImpl.createTopic(key, newTopic, queueNum, topicSysFlag);
    }

    @Override
    public long searchOffset(MessageQueue mq, long timestamp) throws MQClientException {
        return this.defaultMQPullConsumerImpl.searchOffset(mq, timestamp);
    }

    @Override
    public long maxOffset(MessageQueue mq) throws MQClientException {
        return this.defaultMQPullConsumerImpl.maxOffset(mq);
    }

    @Override
    public long minOffset(MessageQueue mq) throws MQClientException {
        return this.defaultMQPullConsumerImpl.minOffset(mq);
    }

    @Override
    public long earliestMsgStoreTime(MessageQueue mq) throws MQClientException {
        return this.defaultMQPullConsumerImpl.earliestMsgStoreTime(mq);
    }

    @Override
    public MessageExt viewMessage(String offsetMsgId) throws RemotingException, MQBrokerException,
            InterruptedException, MQClientException {
        return this.defaultMQPullConsumerImpl.viewMessage(offsetMsgId);
    }

    @Override
    public QueryResult queryMessage(String topic, String key, int maxNum, long begin, long end)
            throws MQClientException, InterruptedException {
        return this.defaultMQPullConsumerImpl.queryMessage(topic, key, maxNum, begin, end);
    }

    public AllocateMessageQueueStrategy getAllocateMessageQueueStrategy() {
        return allocateMessageQueueStrategy;
    }

    public void setAllocateMessageQueueStrategy(AllocateMessageQueueStrategy allocateMessageQueueStrategy) {
        this.allocateMessageQueueStrategy = allocateMessageQueueStrategy;
    }

    public long getBrokerSuspendMaxTimeMillis() {
        return brokerSuspendMaxTimeMillis;
    }

    public void setBrokerSuspendMaxTimeMillis(long brokerSuspendMaxTimeMillis) {
        this.brokerSuspendMaxTimeMillis = brokerSuspendMaxTimeMillis;
    }

    public String getConsumerGroup() {
        return consumerGroup;
    }

    public void setConsumerGroup(String consumerGroup) {
        this.consumerGroup = consumerGroup;
    }

    public long getConsumerPullTimeoutMillis() {
        return consumerPullTimeoutMillis;
    }

    public void setConsumerPullTimeoutMillis(long consumerPullTimeoutMillis) {
        this.consumerPullTimeoutMillis = consumerPullTimeoutMillis;
    }

    public long getConsumerTimeoutMillisWhenSuspend() {
        return consumerTimeoutMillisWhenSuspend;
    }

    public void setConsumerTimeoutMillisWhenSuspend(long consumerTimeoutMillisWhenSuspend) {
        this.consumerTimeoutMillisWhenSuspend = consumerTimeoutMillisWhenSuspend;
    }

    public MessageModel getMessageModel() {
        return messageModel;
    }

    public void setMessageModel(MessageModel messageModel) {
        this.messageModel = messageModel;
    }

    public MessageQueueListener getMessageQueueListener() {
        return messageQueueListener;
    }

    public void setMessageQueueListener(MessageQueueListener messageQueueListener) {
        this.messageQueueListener = messageQueueListener;
    }

    public Set<String> getRegisterTopics() {
        return registerTopics;
    }

    public void setRegisterTopics(Set<String> registerTopics) {
        this.registerTopics = registerTopics;
    }

    @Override
    public void sendMessageBack(MessageExt msg, int delayLevel)
            throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
        this.defaultMQPullConsumerImpl.sendMessageBack(msg, delayLevel, null);
    }

    @Override
    public void sendMessageBack(MessageExt msg, int delayLevel, String brokerName)
            throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
        this.defaultMQPullConsumerImpl.sendMessageBack(msg, delayLevel, brokerName);
    }

    @Override
    public Set<MessageQueue> fetchSubscribeMessageQueues(String topic) throws MQClientException {
        return this.defaultMQPullConsumerImpl.fetchSubscribeMessageQueues(topic);
    }

    @Override
    public void start() throws MQClientException {
        this.defaultMQPullConsumerImpl.start();
    }

    @Override
    public void shutdown() {
        this.defaultMQPullConsumerImpl.shutdown();
    }

    @Override
    public void registerMessageQueueListener(String topic, MessageQueueListener listener) {
        synchronized (this.registerTopics) {
            this.registerTopics.add(topic);
            if (listener != null) {
                this.messageQueueListener = listener;
            }
        }
    }

    @Override
    public PullResult pull(MessageQueue mq, String subExpression, long offset, int maxNums)
            throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
        return this.defaultMQPullConsumerImpl.pull(mq, subExpression, offset, maxNums);
    }

    @Override
    public PullResult pull(MessageQueue mq, String subExpression, long offset, int maxNums, long timeout)
            throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
        return this.defaultMQPullConsumerImpl.pull(mq, subExpression, offset, maxNums, timeout);
    }

    @Override
    public void pull(MessageQueue mq, String subExpression, long offset, int maxNums, PullCallback pullCallback)
            throws MQClientException, RemotingException, InterruptedException {
        this.defaultMQPullConsumerImpl.pull(mq, subExpression, offset, maxNums, pullCallback);
    }

    @Override
    public void pull(MessageQueue mq, String subExpression, long offset, int maxNums, PullCallback pullCallback, long timeout)
            throws MQClientException, RemotingException, InterruptedException {
        this.defaultMQPullConsumerImpl.pull(mq, subExpression, offset, maxNums, pullCallback, timeout);
    }

    @Override
    public PullResult pullBlockIfNotFound(MessageQueue mq, String subExpression, long offset, int maxNums)
            throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
        return this.defaultMQPullConsumerImpl.pullBlockIfNotFound(mq, subExpression, offset, maxNums);
    }

    @Override
    public void pullBlockIfNotFound(MessageQueue mq, String subExpression, long offset, int maxNums, PullCallback pullCallback)
            throws MQClientException, RemotingException, InterruptedException {
        this.defaultMQPullConsumerImpl.pullBlockIfNotFound(mq, subExpression, offset, maxNums, pullCallback);
    }

    @Override
    public void updateConsumeOffset(MessageQueue mq, long offset) throws MQClientException {
        this.defaultMQPullConsumerImpl.updateConsumeOffset(mq, offset);
    }

    @Override
    public long fetchConsumeOffset(MessageQueue mq, boolean fromStore) throws MQClientException {
        return this.defaultMQPullConsumerImpl.fetchConsumeOffset(mq, fromStore);
    }

    @Override
    public Set<MessageQueue> fetchMessageQueuesInBalance(String topic) throws MQClientException {
        return this.defaultMQPullConsumerImpl.fetchMessageQueuesInBalance(topic);
    }

    @Override
    public MessageExt viewMessage(String topic, String uniqKey) throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
        try {
            MessageDecoder.decodeMessageId(uniqKey);
            return this.viewMessage(uniqKey);
        } catch (Exception e) {
        }
        return this.defaultMQPullConsumerImpl.queryMessageByUniqKey(topic, uniqKey);
    }

    @Override
    public void sendMessageBack(MessageExt msg, int delayLevel, String brokerName, String consumerGroup)
            throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
        this.defaultMQPullConsumerImpl.sendMessageBack(msg, delayLevel, brokerName, consumerGroup);
    }

    public OffsetStore getOffsetStore() {
        return offsetStore;
    }

    public void setOffsetStore(OffsetStore offsetStore) {
        this.offsetStore = offsetStore;
    }

    public DefaultMQPullConsumerImpl getDefaultMQPullConsumerImpl() {
        return defaultMQPullConsumerImpl;
    }

    public boolean isUnitMode() {
        return unitMode;
    }

    public void setUnitMode(boolean isUnitMode) {
        this.unitMode = isUnitMode;
    }

    public int getMaxReconsumeTimes() {
        return maxReconsumeTimes;
    }

    public void setMaxReconsumeTimes(final int maxReconsumeTimes) {
        this.maxReconsumeTimes = maxReconsumeTimes;
    }
}


text:
package com.hazelcast.ringbuffer.impl;

import com.hazelcast.config.Config;
import com.hazelcast.config.RingbufferConfig;
import com.hazelcast.core.DistributedObject;
import com.hazelcast.internal.partition.FragmentedMigrationAwareService;
import com.hazelcast.internal.partition.IPartitionService;
import com.hazelcast.internal.partition.PartitionMigrationEvent;
import com.hazelcast.internal.partition.PartitionReplicationEvent;
import com.hazelcast.internal.serialization.Data;
import com.hazelcast.internal.serialization.SerializationService;
import com.hazelcast.internal.services.DistributedObjectNamespace;
import com.hazelcast.internal.services.ManagedService;
import com.hazelcast.internal.services.ObjectNamespace;
import com.hazelcast.internal.services.RemoteService;
import com.hazelcast.internal.services.ServiceNamespace;
import com.hazelcast.internal.services.SplitBrainHandlerService;
import com.hazelcast.internal.services.SplitBrainProtectionAwareService;
import com.hazelcast.internal.util.ConstructorFunction;
import com.hazelcast.internal.util.ContextMutexFactory;
import com.hazelcast.internal.util.MapUtil;
import com.hazelcast.partition.strategy.StringPartitioningStrategy;
import com.hazelcast.ringbuffer.impl.operations.MergeOperation;
import com.hazelcast.ringbuffer.impl.operations.ReplicationOperation;
import com.hazelcast.spi.impl.NodeEngine;
import com.hazelcast.spi.impl.NodeEngineImpl;
import com.hazelcast.spi.impl.merge.AbstractContainerMerger;
import com.hazelcast.spi.impl.operationservice.Operation;
import com.hazelcast.spi.merge.RingbufferMergeData;
import com.hazelcast.spi.merge.SplitBrainMergePolicy;
import com.hazelcast.spi.merge.SplitBrainMergeTypes.RingbufferMergeTypes;
import com.hazelcast.splitbrainprotection.SplitBrainProtectionOn;
import com.hazelcast.splitbrainprotection.SplitBrainProtectionService;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import static com.hazelcast.internal.config.ConfigValidator.checkRingbufferConfig;
import static com.hazelcast.internal.partition.MigrationEndpoint.DESTINATION;
import static com.hazelcast.internal.partition.MigrationEndpoint.SOURCE;
import static com.hazelcast.internal.util.ConcurrencyUtil.getOrPutSynchronized;
import static com.hazelcast.internal.util.MapUtil.isNullOrEmpty;
import static com.hazelcast.internal.util.Preconditions.checkNotNull;

/**
 * The SPI Service that deals with the {@link com.hazelcast.ringbuffer.Ringbuffer}.
 */
public class RingbufferService implements ManagedService, RemoteService, FragmentedMigrationAwareService,
        SplitBrainProtectionAwareService, SplitBrainHandlerService {

    /**
     * Prefix of ringbuffers that are created for topics. Using a prefix prevents
     * users accidentally retrieving the ringbuffer.
     */
    public static final String TOPIC_RB_PREFIX = "_hz_rb_";

    /**
     * The ringbuffer service name which defines it in the node engine.
     */
    public static final String SERVICE_NAME = "hz:impl:ringbufferService";

    private static final Object NULL_OBJECT = new Object();

    /**
     * Map from namespace to actual ringbuffer containers. The namespace
     * defines the service and object name which is the owner of the ringbuffer
     * container.
     */
    private final ConcurrentMap<Integer, Map<ObjectNamespace, RingbufferContainer>> containers
            = new ConcurrentHashMap<>();

    private final ConcurrentMap<String, Object> splitBrainProtectionConfigCache = new ConcurrentHashMap<>();
    private final ContextMutexFactory splitBrainProtectionConfigCacheMutexFactory = new ContextMutexFactory();
    private final ConstructorFunction<String, Object> splitBrainProtectionConfigConstructor =
            new ConstructorFunction<String, Object>() {
                @Override
                public Object createNew(String name) {
                    RingbufferConfig config = nodeEngine.getConfig().findRingbufferConfig(name);
                    String splitBrainProtectionName = config.getSplitBrainProtectionName();
                    // The splitBrainProtectionName will be null
                    // if there is no split brain protection
                    // defined for this data structure, but the
                    // SplitBrainProtectionService is active,
                    // due to another data structure with a
                    // split brain protection configuration
                    return splitBrainProtectionName == null ? NULL_OBJECT : splitBrainProtectionName;
                }
            };

    private NodeEngine nodeEngine;
    private SerializationService serializationService;
    private IPartitionService partitionService;
    private SplitBrainProtectionService splitBrainProtectionService;

    public RingbufferService(NodeEngineImpl nodeEngine) {
        init(nodeEngine, null);
    }

    @Override
    public void init(NodeEngine nodeEngine, Properties properties) {
        this.nodeEngine = checkNotNull(nodeEngine, "nodeEngine can't be null");
        this.serializationService = nodeEngine.getSerializationService();
        this.partitionService = nodeEngine.getPartitionService();
        this.splitBrainProtectionService = nodeEngine.getSplitBrainProtectionService();
    }

    // just for testing
    public ConcurrentMap<Integer, Map<ObjectNamespace, RingbufferContainer>> getContainers() {
        return containers;
    }

    @Override
    public DistributedObject createDistributedObject(String objectName, UUID source, boolean local) {
        RingbufferConfig ringbufferConfig = getRingbufferConfig(objectName);
        checkRingbufferConfig(ringbufferConfig, nodeEngine.getSplitBrainMergePolicyProvider());

        return new RingbufferProxy(nodeEngine, this, objectName, ringbufferConfig);
    }

    @Override
    public void destroyDistributedObject(String name, boolean local) {
        destroyContainer(getRingbufferPartitionId(name), getRingbufferNamespace(name));
        nodeEngine.getEventService().deregisterAllListeners(SERVICE_NAME, name);
        splitBrainProtectionConfigCache.remove(name);
    }

    public void destroyContainer(int partitionId, ObjectNamespace namespace) {
        final Map<ObjectNamespace, RingbufferContainer> partitionContainers = containers.get(partitionId);
        if (partitionContainers == null) {
            return;
        }
        partitionContainers.remove(namespace);
    }

    @Override
    public void reset() {
        containers.clear();
    }

    @Override
    public void shutdown(boolean terminate) {
        reset();
    }

    /**
     * Return the ringbuffer containter for the specified {@code namespace}.
     * If there is no ringbuffer container, create it using the {@code config}.
     *
     * @param namespace the ringbuffer container namespace
     * @param config    the ringbuffer config. Used to create the container when the container doesn't exist
     * @return the ringbuffer container
     * @throws NullPointerException if the {@code config} is {@code null}
     */
    @SuppressWarnings("unchecked")
    public <T, E> RingbufferContainer<T, E> getOrCreateContainer(int partitionId, ObjectNamespace namespace,
                                                                 RingbufferConfig config) {
        if (config == null) {
            throw new NullPointerException("Ringbuffer config must not be null when ringbuffer is being created");
        }
        final Map<ObjectNamespace, RingbufferContainer> partitionContainers = getOrCreateRingbufferContainers(partitionId);

        RingbufferContainer<T, E> ringbuffer = partitionContainers.get(namespace);
        if (ringbuffer != null) {
            return ringbuffer;
        }

        ringbuffer = new RingbufferContainer<>(namespace, config, nodeEngine, partitionId);
        ringbuffer.getStore().instrument(nodeEngine);
        partitionContainers.put(namespace, ringbuffer);
        return ringbuffer;
    }

    /**
     * Returns the ringbuffer container if it already exists for the
     * given {@code partitionId} and {@code namespace}. Returns {@code null}
     * if it doesn't exist.
     *
     * @param partitionId the partition ID of the ringbuffer container
     * @param namespace   the namespace of the ringbuffer container
     * @param <T>         the type of items in the ringbuffer container
     * @param <E>         the type of items in the ringbuffer
     * @return the ringbuffer container or {@code null} if it has not been created
     */
    @SuppressWarnings("unchecked")
    public <T, E> RingbufferContainer<T, E> getContainerOrNull(int partitionId, ObjectNamespace namespace) {
        final Map<ObjectNamespace, RingbufferContainer> partitionContainers = containers.get(partitionId);
        return partitionContainers != null ? partitionContainers.get(namespace) : null;
    }

    private Map<ObjectNamespace, RingbufferContainer> getOrCreateRingbufferContainers(int partitionId) {
        final Map<ObjectNamespace, RingbufferContainer> partitionContainer = containers.get(partitionId);
        if (partitionContainer == null) {
            containers.putIfAbsent(partitionId, new HashMap<>());
        }
        return containers.get(partitionId);
    }

    public RingbufferConfig getRingbufferConfig(String name) {
        Config config = nodeEngine.getConfig();
        return config.findRingbufferConfig(getConfigName(name));
    }

    public static ObjectNamespace getRingbufferNamespace(String name) {
        return new DistributedObjectNamespace(SERVICE_NAME, name);
    }

    public int getRingbufferPartitionId(String ringbufferName) {
        Data partitionAwareData = serializationService.toData(ringbufferName, StringPartitioningStrategy.INSTANCE);
        return partitionService.getPartitionId(partitionAwareData);
    }

    public void addRingbuffer(int partitionId, RingbufferContainer ringbuffer, RingbufferConfig config) {
        checkNotNull(ringbuffer, "ringbuffer can't be null");
        ringbuffer.init(config, nodeEngine);
        ringbuffer.getStore().instrument(nodeEngine);
        getOrCreateRingbufferContainers(partitionId).put(ringbuffer.getNamespace(), ringbuffer);
    }

    @Override
    public void beforeMigration(PartitionMigrationEvent partitionMigrationEvent) {
    }

    @Override
    public Operation prepareReplicationOperation(PartitionReplicationEvent event) {
        return prepareReplicationOperation(event, getAllServiceNamespaces(event));
    }

    @Override
    public Operation prepareReplicationOperation(PartitionReplicationEvent event,
                                                 Collection<ServiceNamespace> namespaces) {
        int partitionId = event.getPartitionId();
        Map<ObjectNamespace, RingbufferContainer> partitionContainers = containers.get(partitionId);
        if (isNullOrEmpty(partitionContainers)) {
            return null;
        }

        Map<ObjectNamespace, RingbufferContainer> migrationData = new HashMap<>();
        for (ServiceNamespace namespace : namespaces) {
            ObjectNamespace ns = (ObjectNamespace) namespace;
            RingbufferContainer container = partitionContainers.get(ns);
            if (container != null && container.getConfig().getTotalBackupCount() >= event.getReplicaIndex()) {
                migrationData.put(ns, container);
            }
        }
        if (migrationData.isEmpty()) {
            return null;
        }
        return new ReplicationOperation(migrationData, event.getPartitionId(), event.getReplicaIndex());

    }

    @Override
    public void commitMigration(PartitionMigrationEvent event) {
        if (event.getMigrationEndpoint() == SOURCE) {
            clearRingbuffersHavingLesserBackupCountThan(event.getPartitionId(), event.getNewReplicaIndex());
        }
    }

    @Override
    public void rollbackMigration(PartitionMigrationEvent event) {
        if (event.getMigrationEndpoint() == DESTINATION) {
            clearRingbuffersHavingLesserBackupCountThan(event.getPartitionId(), event.getCurrentReplicaIndex());
        }
    }

    private void clearRingbuffersHavingLesserBackupCountThan(int partitionId, int thresholdReplicaIndex) {
        final Map<ObjectNamespace, RingbufferContainer> partitionContainers = containers.get(partitionId);
        if (partitionContainers == null || partitionContainers.isEmpty()) {
            return;
        }

        final Iterator<Entry<ObjectNamespace, RingbufferContainer>> iterator = partitionContainers.entrySet().iterator();
        while (iterator.hasNext()) {
            final Entry<ObjectNamespace, RingbufferContainer> entry = iterator.next();
            final RingbufferContainer container = entry.getValue();
            if (thresholdReplicaIndex < 0 || container.getConfig().getTotalBackupCount() < thresholdReplicaIndex) {
                iterator.remove();
            }
        }
    }

    @Override
    public Collection<ServiceNamespace> getAllServiceNamespaces(PartitionReplicationEvent event) {
        int partitionId = event.getPartitionId();
        Map<ObjectNamespace, RingbufferContainer> partitionContainers = containers.get(partitionId);

        if (MapUtil.isNullOrEmpty(partitionContainers)) {
            return Collections.EMPTY_LIST;
        }

        Collection<ServiceNamespace> namespaces = Collections.EMPTY_LIST;
        for (RingbufferContainer container : partitionContainers.values()) {
            if (container.getConfig().getTotalBackupCount() < event.getReplicaIndex()) {
                continue;
            }
            if (namespaces == Collections.EMPTY_LIST) {
                namespaces = new LinkedList<>();
            }
            namespaces.add(container.getNamespace());
        }
        return namespaces;
    }

    @Override
    public boolean isKnownServiceNamespace(ServiceNamespace namespace) {
        return namespace instanceof ObjectNamespace;
    }

    @Override
    public String getSplitBrainProtectionName(final String name) {
        Object splitBrainProtectionName = getOrPutSynchronized(splitBrainProtectionConfigCache, name,
                splitBrainProtectionConfigCacheMutexFactory, splitBrainProtectionConfigConstructor);
        return splitBrainProtectionName == NULL_OBJECT ? null : (String) splitBrainProtectionName;
    }

    public void ensureNoSplitBrain(String distributedObjectName,
                                   SplitBrainProtectionOn requiredSplitBrainProtectionPermissionType) {
        splitBrainProtectionService.ensureNoSplitBrain(getSplitBrainProtectionName(distributedObjectName),
                requiredSplitBrainProtectionPermissionType);
    }

    @Override
    public Runnable prepareMergeRunnable() {
        RingbufferContainerCollector collector = new RingbufferContainerCollector(nodeEngine, containers);
        collector.run();
        return new Merger(collector);
    }

    private class Merger
            extends AbstractContainerMerger<RingbufferContainer, RingbufferMergeData, RingbufferMergeTypes> {

        Merger(RingbufferContainerCollector collector) {
            super(collector, nodeEngine);
        }

        @Override
        protected String getLabel() {
            return "ringbuffer";
        }

        @Override
        public void runInternal() {
            for (Entry<Integer, Collection<RingbufferContainer>> entry : collector.getCollectedContainers().entrySet()) {
                int partitionId = entry.getKey();
                Collection<RingbufferContainer> containerList = entry.getValue();
                for (RingbufferContainer container : containerList) {
                    // TODO: add batching (which is a bit complex, since collections don't have a multi-name operation yet
                    SplitBrainMergePolicy<RingbufferMergeData, RingbufferMergeTypes, RingbufferMergeData> mergePolicy
                            = getMergePolicy(container.getConfig().getMergePolicyConfig());

                    sendBatch(partitionId, mergePolicy, container);
                }
            }
        }

        private void sendBatch(int partitionId,
                               SplitBrainMergePolicy<RingbufferMergeData, RingbufferMergeTypes, RingbufferMergeData> mergePolicy,
                               RingbufferContainer mergingContainer) {
            final MergeOperation operation = new MergeOperation(mergingContainer.getNamespace(), mergePolicy,
                    mergingContainer.getRingbuffer());
            invoke(SERVICE_NAME, operation, partitionId);
        }
    }

    private static String getConfigName(String name) {
        if (name.startsWith(TOPIC_RB_PREFIX)) {
            name = name.substring(TOPIC_RB_PREFIX.length());
        }
        return name;
    }
}


text:
goog.provide('ol.VectorImageTile');

goog.require('ol');
goog.require('ol.Tile');
goog.require('ol.TileState');
goog.require('ol.array');
goog.require('ol.dom');
goog.require('ol.events');
goog.require('ol.extent');
goog.require('ol.events.EventType');
goog.require('ol.featureloader');

/**
 * @constructor
 * @extends {ol.Tile}
 * @param {ol.TileCoord} tileCoord Tile coordinate.
 * @param {ol.TileState} state State.
 * @param {string} src Data source url.
 * @param {ol.format.Feature} format Feature format.
 * @param {ol.TileLoadFunctionType} tileLoadFunction Tile load function.
 * @param {ol.TileCoord} urlTileCoord Wrapped tile coordinate for source urls.
 * @param {ol.TileUrlFunctionType} tileUrlFunction Tile url function.
 * @param {ol.tilegrid.TileGrid} sourceTileGrid Tile grid of the source.
 * @param {ol.tilegrid.TileGrid} tileGrid Tile grid of the renderer.
 * @param {Object.<string,ol.VectorTile>} sourceTiles Source tiles.
 * @param {number} pixelRatio Pixel ratio.
 * @param {ol.proj.Projection} projection Projection.
 * @param {function(new: ol.VectorTile, ol.TileCoord, ol.TileState, string,
 *     ol.format.Feature, ol.TileLoadFunctionType)} tileClass Class to
 *     instantiate for source tiles.
 * @param {function(this: ol.source.VectorTile, ol.events.Event)} handleTileChange
 *     Function to call when a source tile's state changes.
 */
ol.VectorImageTile = function(tileCoord, state, src, format, tileLoadFunction,
    urlTileCoord, tileUrlFunction, sourceTileGrid, tileGrid, sourceTiles,
    pixelRatio, projection, tileClass, handleTileChange) {

  ol.Tile.call(this, tileCoord, state);

  /**
   * @private
   * @type {CanvasRenderingContext2D}
   */
  this.context_ = null;

  /**
   * @private
   * @type {ol.FeatureLoader}
   */
  this.loader_;

  /**
   * @private
   * @type {ol.TileReplayState}
   */
  this.replayState_ = {
    dirty: false,
    renderedRenderOrder: null,
    renderedRevision: -1,
    renderedTileRevision: -1
  };

  /**
   * @private
   * @type {Object.<string,ol.VectorTile>}
   */
  this.sourceTiles_ = sourceTiles;

  /**
   * Keys of source tiles used by this tile. Use with {@link #getTile}.
   * @type {Array.<string>}
   */
  this.tileKeys = [];

  /**
   * @type {string}
   */
  this.src_ = src;

  /**
   * @type {ol.TileCoord}
   */
  this.wrappedTileCoord = urlTileCoord;

  /**
   * @type {Array.<ol.EventsKey>}
   */
  this.loadListenerKeys_ = [];

  /**
   * @type {Array.<ol.EventsKey>}
   */
  this.sourceTileListenerKeys_ = [];

  if (urlTileCoord) {
    var extent = tileGrid.getTileCoordExtent(urlTileCoord);
    var resolution = tileGrid.getResolution(tileCoord[0]);
    var sourceZ = sourceTileGrid.getZForResolution(resolution);
    sourceTileGrid.forEachTileCoord(extent, sourceZ, function(sourceTileCoord) {
      var sharedExtent = ol.extent.getIntersection(extent,
          sourceTileGrid.getTileCoordExtent(sourceTileCoord));
      if (ol.extent.getWidth(sharedExtent) / resolution >= 0.5 &&
          ol.extent.getHeight(sharedExtent) / resolution >= 0.5) {
        // only include source tile if overlap is at least 1 pixel
        var sourceTileKey = sourceTileCoord.toString();
        var sourceTile = sourceTiles[sourceTileKey];
        if (!sourceTile) {
          var tileUrl = tileUrlFunction(sourceTileCoord, pixelRatio, projection);
          sourceTile = sourceTiles[sourceTileKey] = new tileClass(sourceTileCoord,
              tileUrl == undefined ? ol.TileState.EMPTY : ol.TileState.IDLE,
              tileUrl == undefined ? '' : tileUrl,
              format, tileLoadFunction);
          this.sourceTileListenerKeys_.push(
              ol.events.listen(sourceTile, ol.events.EventType.CHANGE, handleTileChange));
        }
        sourceTile.consumers++;
        this.tileKeys.push(sourceTileKey);
      }
    }.bind(this));
  }

};
ol.inherits(ol.VectorImageTile, ol.Tile);

/**
 * @inheritDoc
 */
ol.VectorImageTile.prototype.disposeInternal = function() {
  for (var i = 0, ii = this.tileKeys.length; i < ii; ++i) {
    var sourceTileKey = this.tileKeys[i];
    var sourceTile = this.getTile(sourceTileKey);
    sourceTile.consumers--;
    if (sourceTile.consumers == 0) {
      delete this.sourceTiles_[sourceTileKey];
      sourceTile.dispose();
    }
  }
  this.tileKeys.length = 0;
  this.sourceTiles_ = null;
  if (this.state == ol.TileState.LOADING) {
    this.loadListenerKeys_.forEach(ol.events.unlistenByKey);
    this.loadListenerKeys_.length = 0;
  }
  if (this.interimTile) {
    this.interimTile.dispose();
  }
  this.state = ol.TileState.ABORT;
  this.changed();
  this.sourceTileListenerKeys_.forEach(ol.events.unlistenByKey);
  this.sourceTileListenerKeys_.length = 0;
  ol.Tile.prototype.disposeInternal.call(this);
};

/**
 * @return {CanvasRenderingContext2D} The rendering context.
 */
ol.VectorImageTile.prototype.getContext = function() {
  if (!this.context_) {
    this.context_ = ol.dom.createCanvasContext2D();
  }
  return this.context_;
};

/**
 * Get the Canvas for this tile.
 * @return {HTMLCanvasElement} Canvas.
 */
ol.VectorImageTile.prototype.getImage = function() {
  return this.replayState_.renderedTileRevision == -1 ?
      null : this.context_.canvas;
};

/**
 * @return {ol.TileReplayState} The replay state.
 */
ol.VectorImageTile.prototype.getReplayState = function() {
  return this.replayState_;
};

/**
 * @inheritDoc
 */
ol.VectorImageTile.prototype.getKey = function() {
  return this.tileKeys.join('/') + '/' + this.src_;
};

/**
 * @param {string} tileKey Key (tileCoord) of the source tile.
 * @return {ol.VectorTile} Source tile.
 */
ol.VectorImageTile.prototype.getTile = function(tileKey) {
  return this.sourceTiles_[tileKey];
};

/**
 * @inheritDoc
 */
ol.VectorImageTile.prototype.load = function() {
  var leftToLoad = 0;
  var errors = false;
  if (this.state == ol.TileState.IDLE) {
    this.setState(ol.TileState.LOADING);
  }
  if (this.state == ol.TileState.LOADING) {
    this.tileKeys.forEach(function(sourceTileKey) {
      var sourceTile = this.getTile(sourceTileKey);
      if (sourceTile.state == ol.TileState.IDLE) {
        sourceTile.setLoader(this.loader_);
        sourceTile.load();
      } else if (sourceTile.state == ol.TileState.ERROR) {
        errors = true;
      } else if (sourceTile.state == ol.TileState.EMPTY) {
        ol.array.remove(this.tileKeys, sourceTileKey);
      }
      if (sourceTile.state == ol.TileState.LOADING) {
        var key = ol.events.listen(sourceTile, ol.events.EventType.CHANGE, function(e) {
          var state = sourceTile.getState();
          if (state == ol.TileState.LOADED ||
              state == ol.TileState.ERROR) {
            --leftToLoad;
            ol.events.unlistenByKey(key);
            ol.array.remove(this.loadListenerKeys_, key);
            if (state == ol.TileState.ERROR) {
              ol.array.remove(this.tileKeys, sourceTileKey);
              errors = true;
            }
            if (leftToLoad == 0) {
              this.setState(this.tileKeys.length > 0 ?
                  ol.TileState.LOADED : ol.TileState.ERROR);
            }
          }
        }.bind(this));
        this.loadListenerKeys_.push(key);
        ++leftToLoad;
      }
    }.bind(this));
  }
  if (leftToLoad == 0) {
    setTimeout(function() {
      this.setState(this.tileKeys.length > 0 ?
          ol.TileState.LOADED :
          (errors ? ol.TileState.ERROR : ol.TileState.EMPTY));
    }.bind(this), 0);
  }
};

/**
 * Sets the loader for a tile.
 * @param {ol.VectorTile} tile Vector tile.
 * @param {string} url URL.
 */
ol.VectorImageTile.defaultLoadFunction = function(tile, url) {
  var loader = ol.featureloader.loadFeaturesXhr(
      url, tile.getFormat(), tile.onLoad_.bind(tile), tile.onError_.bind(tile));

  tile.setLoader(loader);
};