text:
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PcapDotNet.Packets.Ethernet;
using PcapDotNet.Packets.Icmp;
using PcapDotNet.Packets.IpV4;
using PcapDotNet.Packets.TestUtils;
using PcapDotNet.TestUtils;

namespace PcapDotNet.Packets.Test
{
    /// <summary>
    /// Summary description for IcmpTests
    /// </summary>
    [TestClass]
    [ExcludeFromCodeCoverage]
    public class IcmpTests
    {
        /// <summary>
        /// Gets or sets the test context which provides
        /// information about and functionality for the current test run.
        /// </summary>
        public TestContext TestContext { get; set; }

        #region Additional test attributes
        //
        // You can use the following additional attributes as you write your tests:
        //
        // Use ClassInitialize to run code before running the first test in the class
        // [ClassInitialize()]
        // public static void MyClassInitialize(TestContext testContext) { }
        //
        // Use ClassCleanup to run code after all tests in a class have run
        // [ClassCleanup()]
        // public static void MyClassCleanup() { }
        //
        // Use TestInitialize to run code before running each test
        // [TestInitialize()]
        // public void MyTestInitialize() { }
        //
        // Use TestCleanup to run code after each test has run
        // [TestCleanup()]
        // public void MyTestCleanup() { }
        //
        #endregion

        [TestMethod]
        public void RandomIcmpTest()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = new MacAddress("00:01:02:03:04:05"),
                                                  Destination = new MacAddress("A0:A1:A2:A3:A4:A5")
                                              };

            int seed = new Random().Next();
            Console.WriteLine("Seed: " + seed);
            Random random = new Random(seed);

            for (int i = 0; i != 2000; ++i)
            {
                IpV4Layer ipV4Layer = random.NextIpV4Layer(null);
                ipV4Layer.HeaderChecksum = null;
                Layer ipLayer = random.NextBool() ? (Layer)ipV4Layer : random.NextIpV6Layer(IpV4Protocol.InternetControlMessageProtocol, false);

                IcmpLayer icmpLayer = random.NextIcmpLayer();
                icmpLayer.Checksum = null;
                if (icmpLayer.MessageType == IcmpMessageType.DestinationUnreachable &&
                    icmpLayer.MessageTypeAndCode != IcmpMessageTypeAndCode.DestinationUnreachableFragmentationNeededAndDoNotFragmentSet)
                {
                    ((IcmpDestinationUnreachableLayer)icmpLayer).NextHopMaximumTransmissionUnit = 0;
                }

                IEnumerable<ILayer> icmpPayloadLayers = random.NextIcmpPayloadLayers(icmpLayer);

                int icmpPayloadLength = icmpPayloadLayers.Select(layer => layer.Length).Sum();

                switch (icmpLayer.MessageType)
                {
                    case IcmpMessageType.ParameterProblem:
                        if (icmpPayloadLength % 4 != 0)
                            icmpPayloadLayers = icmpPayloadLayers.Concat(new[] {new PayloadLayer {Data = random.NextDatagram(4 - icmpPayloadLength % 4)}});
                        icmpPayloadLength = icmpPayloadLayers.Select(layer => layer.Length).Sum();
                        IcmpParameterProblemLayer icmpParameterProblemLayer = (IcmpParameterProblemLayer)icmpLayer;
                        icmpParameterProblemLayer.Pointer = (byte)(icmpParameterProblemLayer.Pointer % icmpPayloadLength);
                        icmpParameterProblemLayer.OriginalDatagramLength = icmpPayloadLength - icmpPayloadLayers.First().Length;
                        break;

                    case IcmpMessageType.SecurityFailures:
                        ((IcmpSecurityFailuresLayer)icmpLayer).Pointer %= (ushort)icmpPayloadLength;
                        break;
                }

                PacketBuilder packetBuilder = new PacketBuilder(new ILayer[] { ethernetLayer, ipLayer, icmpLayer }.Concat(icmpPayloadLayers));

                Packet packet = packetBuilder.Build(DateTime.Now);
                Assert.IsTrue(packet.IsValid, "IsValid");

                byte[] buffer = (byte[])packet.Buffer.Clone();
                buffer.Write(ethernetLayer.Length + ipLayer.Length, random.NextDatagram(icmpLayer.Length));
                Packet illegalPacket = new Packet(buffer, DateTime.Now, packet.DataLink);
                Assert.IsFalse(illegalPacket.IsValid, "IsInvalid");
                if (illegalPacket.Ethernet.Ip.Icmp is IcmpUnknownDatagram)
                {
                    byte[] icmpBuffer = new byte[illegalPacket.Ethernet.Ip.Icmp.ExtractLayer().Length];
                    ILayer layer = illegalPacket.Ethernet.Ip.Icmp.ExtractLayer();
                    layer.Write(icmpBuffer,0,icmpBuffer.Length, null,null);
                    layer.Finalize(icmpBuffer,0,icmpBuffer.Length,null);
                    MoreAssert.AreSequenceEqual(illegalPacket.Ethernet.Ip.Icmp.ToArray(),
                                    icmpBuffer);

                    Assert.AreEqual(illegalPacket,
                                    PacketBuilder.Build(DateTime.Now, ethernetLayer, ipLayer, illegalPacket.Ethernet.Ip.Icmp.ExtractLayer()));
                }

                // Ethernet
                ethernetLayer.EtherType = ipLayer == ipV4Layer ? EthernetType.IpV4 : EthernetType.IpV6;
                Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");
                ethernetLayer.EtherType = EthernetType.None;

                // IP.
                if (ipLayer == ipV4Layer)
                {
                    // IPv4.
                    ipV4Layer.Protocol = IpV4Protocol.InternetControlMessageProtocol;
                    ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.IpV4.ExtractLayer()).HeaderChecksum;
                    Assert.AreEqual(ipV4Layer, packet.Ethernet.IpV4.ExtractLayer());
                    ipV4Layer.HeaderChecksum = null;
                    Assert.AreEqual(ipV4Layer.Length, packet.Ethernet.IpV4.HeaderLength);
                    Assert.IsTrue(packet.Ethernet.IpV4.IsHeaderChecksumCorrect);
                    Assert.AreEqual(ipV4Layer.Length + icmpLayer.Length + icmpPayloadLength,
                                    packet.Ethernet.IpV4.TotalLength);
                    Assert.AreEqual(IpV4Datagram.DefaultVersion, packet.Ethernet.IpV4.Version);
                }
                else
                {
                    // IPv6.
                    Assert.AreEqual(ipLayer, packet.Ethernet.IpV6.ExtractLayer());
                }

                // ICMP
                IcmpDatagram actualIcmp = packet.Ethernet.Ip.Icmp;
                IcmpLayer actualIcmpLayer = (IcmpLayer)actualIcmp.ExtractLayer();
                icmpLayer.Checksum = actualIcmpLayer.Checksum;
                Assert.AreEqual(icmpLayer, actualIcmpLayer);
                Assert.AreEqual(icmpLayer.GetHashCode(), actualIcmpLayer.GetHashCode());
                if (actualIcmpLayer.MessageType != IcmpMessageType.RouterSolicitation)
                {
                    Assert.AreNotEqual(random.NextIcmpLayer(), actualIcmpLayer);
                    IcmpLayer otherIcmpLayer = random.NextIcmpLayer();
                    Assert.AreNotEqual(otherIcmpLayer.GetHashCode(), actualIcmpLayer.GetHashCode());
                }
                Assert.IsTrue(actualIcmp.IsChecksumCorrect);
                Assert.AreEqual(icmpLayer.MessageType, actualIcmp.MessageType);
                Assert.AreEqual(icmpLayer.CodeValue, actualIcmp.Code);
                Assert.AreEqual(icmpLayer.MessageTypeAndCode, actualIcmp.MessageTypeAndCode);
                Assert.AreEqual(packet.Length - ethernetLayer.Length - ipLayer.Length - IcmpDatagram.HeaderLength, actualIcmp.Payload.Length);
                Assert.IsNotNull(icmpLayer.ToString());

                switch (packet.Ethernet.Ip.Icmp.MessageType)
                {
                    case IcmpMessageType.RouterSolicitation:
                    case IcmpMessageType.SourceQuench:
                    case IcmpMessageType.TimeExceeded:
                        Assert.AreEqual<uint>(0, actualIcmp.Variable);
                        break;

                    case IcmpMessageType.DestinationUnreachable:
                    case IcmpMessageType.ParameterProblem:
                    case IcmpMessageType.Redirect:
                    case IcmpMessageType.ConversionFailed:
                    case IcmpMessageType.Echo:
                    case IcmpMessageType.EchoReply:
                    case IcmpMessageType.Timestamp:
                    case IcmpMessageType.TimestampReply:
                    case IcmpMessageType.InformationRequest:
                    case IcmpMessageType.InformationReply:
                    case IcmpMessageType.RouterAdvertisement:
                    case IcmpMessageType.AddressMaskRequest:
                    case IcmpMessageType.AddressMaskReply:
                        break;
                    case IcmpMessageType.TraceRoute:
                        Assert.AreEqual(((IcmpTraceRouteLayer)icmpLayer).OutboundHopCount == 0xFFFF, ((IcmpTraceRouteDatagram)actualIcmp).IsOutbound);
                        break;
                    case IcmpMessageType.DomainNameRequest:
                    case IcmpMessageType.SecurityFailures:
                        break;

                    case IcmpMessageType.DomainNameReply:
                    default:
                        throw new InvalidOperationException("Invalid icmpMessageType " + packet.Ethernet.Ip.Icmp.MessageType);

                }
            }
        }

        [TestMethod]
        public void IcmpRouterAdvertisementEntryTest()
        {
            Random random = new Random();
            IcmpRouterAdvertisementEntry entry1 = new IcmpRouterAdvertisementEntry(random.NextIpV4Address(), random.Next());
            IcmpRouterAdvertisementEntry entry2 = new IcmpRouterAdvertisementEntry(random.NextIpV4Address(), random.Next());

            Assert.AreEqual(entry1, entry1);
            Assert.AreEqual(entry1.GetHashCode(), entry1.GetHashCode());
            Assert.AreNotEqual(entry1, entry2);
            Assert.AreNotEqual(entry1.GetHashCode(), entry2.GetHashCode());
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)]
        public void IcmpDatagramCreateDatagramNullBufferTest()
        {
            Assert.IsNotNull(IcmpDatagram.CreateDatagram(null, 0, 0));
            Assert.Fail();
        }

        [TestMethod]
        public void IcmpDatagramCreateDatagramBadOffsetTest()
        {
            Assert.IsInstanceOfType(IcmpDatagram.CreateDatagram(new byte[0], -1, 0), typeof(IcmpUnknownDatagram));
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentOutOfRangeException), AllowDerivedTypes = false)]
        public void IcmpParameterProblemLayerOriginalDatagramLengthNotRound()
        {
            Layer layer = new IcmpParameterProblemLayer {OriginalDatagramLength = 6};
            Assert.IsNotNull(layer);
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentOutOfRangeException), AllowDerivedTypes = false)]
        public void IcmpParameterProblemLayerOriginalDatagramLengthTooBig()
        {
            Layer layer = new IcmpParameterProblemLayer { OriginalDatagramLength = 2000 };
            Assert.IsNotNull(layer);
        }
    }
}


text:
"""
Extension that generates configuration files for the Tox test automation tool.
"""
from __future__ import absolute_import

from ..templates import tox as tox_ini
from ..api import Extension
from ..api import helpers

class Tox(Extension):
    """Generate Tox configuration file"""
    def activate(self, actions):
        """Activate extension

        Args:
            actions (list): list of actions to perform

        Returns:
            list: updated list of actions
        """
        return self.register(
            actions,
            self.add_files,
            after='define_structure')

    def add_files(self, struct, opts):
        """Add .tox.ini file to structure

        Args:
            struct (dict): project representation as (possibly) nested
                :obj:`dict`.
            opts (dict): given options, see :obj:`create_project` for
                an extensive list.

        Returns:
            struct, opts: updated project representation and options
        """
        files = {
            'tox.ini': (tox_ini(opts), helpers.NO_OVERWRITE)
        }

        return helpers.merge(struct, {opts['project']: files}), opts

redpajama_set_name: RedPajamaGithub


text:
package com.facebook.react.modules.core;

import javax.annotation.Nullable;

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.concurrent.atomic.AtomicBoolean;

import android.util.SparseArray;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.common.SystemClock;
import com.facebook.react.devsupport.interfaces.DevSupportManager;
import com.facebook.react.jstasks.HeadlessJsTaskContext;
import com.facebook.react.jstasks.HeadlessJsTaskEventListener;
import com.facebook.react.module.annotations.ReactModule;

/**
 * Native module for JS timer execution. Timers fire on frame boundaries.
 */
@ReactModule(name = Timing.NAME)
public final class Timing extends ReactContextBaseJavaModule implements LifecycleEventListener,
  HeadlessJsTaskEventListener {

  protected static final String NAME = "Timing";

  // These timing contants should be kept in sync with the ones in `JSTimers.js`.
  // The minimum time in milliseconds left in the frame to call idle callbacks.
  private static final float IDLE_CALLBACK_FRAME_DEADLINE_MS = 1.f;
  // The total duration of a frame in milliseconds, this assumes that devices run at 60 fps.
  // TODO: Lower frame duration on devices that are too slow to run consistently
  // at 60 fps.
  private static final float FRAME_DURATION_MS = 1000.f / 60.f;

  private final DevSupportManager mDevSupportManager;

  private static class Timer {
    private final int mCallbackID;
    private final boolean mRepeat;
    private final int mInterval;
    private long mTargetTime;

    private Timer(
        int callbackID,
        long initialTargetTime,
        int duration,
        boolean repeat) {
      mCallbackID = callbackID;
      mTargetTime = initialTargetTime;
      mInterval = duration;
      mRepeat = repeat;
    }
  }

  private class TimerFrameCallback extends ChoreographerCompat.FrameCallback {

    // Temporary map for constructing the individual arrays of timers to call
    private @Nullable WritableArray mTimersToCall = null;

    /**
     * Calls all timers that have expired since the last time this frame callback was called.
     */
    @Override
    public void doFrame(long frameTimeNanos) {
      if (isPaused.get() && !isRunningTasks.get()) {
        return;
      }

      long frameTimeMillis = frameTimeNanos / 1000000;
      synchronized (mTimerGuard) {
        while (!mTimers.isEmpty() && mTimers.peek().mTargetTime < frameTimeMillis) {
          Timer timer = mTimers.poll();
          if (mTimersToCall == null) {
            mTimersToCall = Arguments.createArray();
          }
          mTimersToCall.pushInt(timer.mCallbackID);
          if (timer.mRepeat) {
            timer.mTargetTime = frameTimeMillis + timer.mInterval;
            mTimers.add(timer);
          } else {
            mTimerIdsToTimers.remove(timer.mCallbackID);
          }
        }
      }

      if (mTimersToCall != null) {
        getReactApplicationContext().getJSModule(JSTimers.class).callTimers(mTimersToCall);
        mTimersToCall = null;
      }

      mReactChoreographer.postFrameCallback(ReactChoreographer.CallbackType.TIMERS_EVENTS, this);
    }
  }

  private class IdleFrameCallback extends ChoreographerCompat.FrameCallback {

    @Override
    public void doFrame(long frameTimeNanos) {
      if (isPaused.get() && !isRunningTasks.get()) {
        return;
      }

      // If the JS thread is busy for multiple frames we cancel any other pending runnable.
      if (mCurrentIdleCallbackRunnable != null) {
        mCurrentIdleCallbackRunnable.cancel();
      }

      mCurrentIdleCallbackRunnable = new IdleCallbackRunnable(frameTimeNanos);
      getReactApplicationContext().runOnJSQueueThread(mCurrentIdleCallbackRunnable);

      mReactChoreographer.postFrameCallback(ReactChoreographer.CallbackType.IDLE_EVENT, this);
    }
  }

  private class IdleCallbackRunnable implements Runnable {
    private volatile boolean mCancelled = false;
    private final long mFrameStartTime;

    public IdleCallbackRunnable(long frameStartTime) {
      mFrameStartTime = frameStartTime;
    }

    @Override
    public void run() {
      if (mCancelled) {
        return;
      }

      long frameTimeMillis = mFrameStartTime / 1000000;
      long timeSinceBoot = SystemClock.uptimeMillis();
      long frameTimeElapsed = timeSinceBoot - frameTimeMillis;
      long time = SystemClock.currentTimeMillis();
      long absoluteFrameStartTime = time - frameTimeElapsed;

      if (FRAME_DURATION_MS - (float) frameTimeElapsed < IDLE_CALLBACK_FRAME_DEADLINE_MS) {
        return;
      }

      boolean sendIdleEvents;
      synchronized (mIdleCallbackGuard) {
        sendIdleEvents = mSendIdleEvents;
      }

      if (sendIdleEvents) {
        getReactApplicationContext().getJSModule(JSTimers.class)
            .callIdleCallbacks(absoluteFrameStartTime);
      }

      mCurrentIdleCallbackRunnable = null;
    }

    public void cancel() {
      mCancelled = true;
    }
  }

  private final Object mTimerGuard = new Object();
  private final Object mIdleCallbackGuard = new Object();
  private final PriorityQueue<Timer> mTimers;
  private final SparseArray<Timer> mTimerIdsToTimers;
  private final AtomicBoolean isPaused = new AtomicBoolean(true);
  private final AtomicBoolean isRunningTasks = new AtomicBoolean(false);
  private final TimerFrameCallback mTimerFrameCallback = new TimerFrameCallback();
  private final IdleFrameCallback mIdleFrameCallback = new IdleFrameCallback();
  private final ReactChoreographer mReactChoreographer;
  private @Nullable IdleCallbackRunnable mCurrentIdleCallbackRunnable;
  private boolean mFrameCallbackPosted = false;
  private boolean mFrameIdleCallbackPosted = false;
  private boolean mSendIdleEvents = false;

  public Timing(ReactApplicationContext reactContext, DevSupportManager devSupportManager) {
    super(reactContext);
    mDevSupportManager = devSupportManager;
    // We store timers sorted by finish time.
    mTimers = new PriorityQueue<Timer>(
        11, // Default capacity: for some reason they don't expose a (Comparator) constructor
        new Comparator<Timer>() {
          @Override
          public int compare(Timer lhs, Timer rhs) {
            long diff = lhs.mTargetTime - rhs.mTargetTime;
            if (diff == 0) {
              return 0;
            } else if (diff < 0) {
              return -1;
            } else {
              return 1;
            }
          }
        });
    mTimerIdsToTimers = new SparseArray<>();
    mReactChoreographer = ReactChoreographer.getInstance();
  }

  @Override
  public void initialize() {
    getReactApplicationContext().addLifecycleEventListener(this);
    HeadlessJsTaskContext headlessJsTaskContext =
      HeadlessJsTaskContext.getInstance(getReactApplicationContext());
    headlessJsTaskContext.addTaskEventListener(this);
  }

  @Override
  public void onHostPause() {
    isPaused.set(true);
    clearFrameCallback();
    maybeIdleCallback();
  }

  @Override
  public void onHostDestroy() {
    clearFrameCallback();
    maybeIdleCallback();
  }

  @Override
  public void onHostResume() {
    isPaused.set(false);
    // TODO(5195192) Investigate possible problems related to restarting all tasks at the same
    // moment
    setChoreographerCallback();
    maybeSetChoreographerIdleCallback();
  }

  @Override
  public void onHeadlessJsTaskStart(int taskId) {
    if (!isRunningTasks.getAndSet(true)) {
      setChoreographerCallback();
      maybeSetChoreographerIdleCallback();
    }
  }

  @Override
  public void onHeadlessJsTaskFinish(int taskId) {
    HeadlessJsTaskContext headlessJsTaskContext =
      HeadlessJsTaskContext.getInstance(getReactApplicationContext());
    if (!headlessJsTaskContext.hasActiveTasks()) {
      isRunningTasks.set(false);
      clearFrameCallback();
      maybeIdleCallback();
    }
  }

  @Override
  public void onCatalystInstanceDestroy() {
    clearFrameCallback();
    clearChoreographerIdleCallback();
    HeadlessJsTaskContext headlessJsTaskContext =
      HeadlessJsTaskContext.getInstance(getReactApplicationContext());
    headlessJsTaskContext.removeTaskEventListener(this);
  }

  private void maybeSetChoreographerIdleCallback() {
    synchronized (mIdleCallbackGuard) {
      if (mSendIdleEvents) {
        setChoreographerIdleCallback();
      }
    }
  }

  private void maybeIdleCallback() {
    if (isPaused.get() && !isRunningTasks.get()) {
      clearFrameCallback();
    }
  }

  private void setChoreographerCallback() {
    if (!mFrameCallbackPosted) {
      mReactChoreographer.postFrameCallback(
          ReactChoreographer.CallbackType.TIMERS_EVENTS,
          mTimerFrameCallback);
      mFrameCallbackPosted = true;
    }
  }

  private void clearFrameCallback() {
    HeadlessJsTaskContext headlessJsTaskContext =
      HeadlessJsTaskContext.getInstance(getReactApplicationContext());
    if (mFrameCallbackPosted && isPaused.get() &&
      !headlessJsTaskContext.hasActiveTasks()) {
      mReactChoreographer.removeFrameCallback(
          ReactChoreographer.CallbackType.TIMERS_EVENTS,
          mTimerFrameCallback);
      mFrameCallbackPosted = false;
    }
  }

  private void setChoreographerIdleCallback() {
    if (!mFrameIdleCallbackPosted) {
      mReactChoreographer.postFrameCallback(
          ReactChoreographer.CallbackType.IDLE_EVENT,
          mIdleFrameCallback);
      mFrameIdleCallbackPosted = true;
    }
  }

  private void clearChoreographerIdleCallback() {
    if (mFrameIdleCallbackPosted) {
      mReactChoreographer.removeFrameCallback(
          ReactChoreographer.CallbackType.IDLE_EVENT,
          mIdleFrameCallback);
      mFrameIdleCallbackPosted = false;
    }
  }

  @Override
  public String getName() {
    return NAME;
  }

  @ReactMethod
  public void createTimer(
      final int callbackID,
      final int duration,
      final double jsSchedulingTime,
      final boolean repeat) {
    long deviceTime = SystemClock.currentTimeMillis();
    long remoteTime = (long) jsSchedulingTime;

    // If the times on the server and device have drifted throw an exception to warn the developer
    // that things might not work or results may not be accurate. This is required only for
    // developer builds.
    if (mDevSupportManager.getDevSupportEnabled()) {
      long driftTime = Math.abs(remoteTime - deviceTime);
      if (driftTime > 60000) {
        getReactApplicationContext().getJSModule(JSTimers.class)
          .emitTimeDriftWarning(
            "Debugger and device times have drifted by more than 60s. Please correct this by " +
            "running adb shell \"date `date +%m%d%H%M%Y.%S`\" on your debugger machine.");
      }
    }

    // Adjust for the amount of time it took for native to receive the timer registration call
    long adjustedDuration = Math.max(0, remoteTime - deviceTime + duration);
    if (duration == 0 && !repeat) {
      WritableArray timerToCall = Arguments.createArray();
      timerToCall.pushInt(callbackID);
      getReactApplicationContext().getJSModule(JSTimers.class)
        .callTimers(timerToCall);
      return;
    }

    long initialTargetTime = SystemClock.nanoTime() / 1000000 + adjustedDuration;
    Timer timer = new Timer(callbackID, initialTargetTime, duration, repeat);
    synchronized (mTimerGuard) {
      mTimers.add(timer);
      mTimerIdsToTimers.put(callbackID, timer);
    }
  }

  @ReactMethod
  public void deleteTimer(int timerId) {
    synchronized (mTimerGuard) {
      Timer timer = mTimerIdsToTimers.get(timerId);
      if (timer == null) {
        return;
      }
      mTimerIdsToTimers.remove(timerId);
      mTimers.remove(timer);
    }
  }

  @ReactMethod
  public void setSendIdleEvents(final boolean sendIdleEvents) {
    synchronized (mIdleCallbackGuard) {
      mSendIdleEvents = sendIdleEvents;
    }

    UiThreadUtil.runOnUiThread(new Runnable() {
      @Override
      public void run() {
        synchronized (mIdleCallbackGuard) {
          if (sendIdleEvents) {
            setChoreographerIdleCallback();
          } else {
            clearChoreographerIdleCallback();
          }
        }
      }
    });
  }
}


text:
import 'chrome://resources/cr_elements/md_select.css.js';
import 'chrome://resources/cr_elements/cr_shared_style.css.js';
import 'chrome://resources/cr_elements/cr_shared_vars.css.js';
import 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';

const styleMod = document.createElement('dom-module');
styleMod.innerHTML = `{__html_template__}`;
styleMod.register('os-feedback-shared');


text:
package org.simpleflatmapper.reflect.test.instantiator;

import org.junit.Test;
import org.simpleflatmapper.reflect.getter.ConstantGetter;
import org.simpleflatmapper.reflect.instantiator.GetterBiInstantiator;
import org.simpleflatmapper.reflect.instantiator.GetterInstantiator;

import static org.junit.Assert.assertEquals;

public class GetterBiInstantiatorTest {

    @Test
    public void test() throws Exception {
        Object o = new Object();
        GetterBiInstantiator<Object,Object, Object> getterInstantiator = new GetterBiInstantiator<Object, Object,Object>(
                new ConstantGetter<Object, Object>(o)
        );

        assertEquals(o, getterInstantiator.newInstance(null, null));
    }
}


text: Prebid.js TestCase1


text:
namespace extensions {

const char kSerialConnectionNotFoundError[] = "Serial connection not found";

// static
bool SerialConnection::DoesPortExist(const StringSet& name_set,
                                     const std::string& port_name) {
  return name_set.count(port_name) == 1;
}

}  // namespace extensions


text:
Template.departments.helpers({
    departments: function () {
        var departments = [];

        var users = Meteor.users.find({_id: {$ne: Meteor.userId()}}).fetch();
        var groupDepartment = _.groupBy(users, function (user) {
            return user.profile.department;
        });

        for (var key in groupDepartment) {
            var department = {
                department: key,
                members: groupDepartment[key]
            };
            departments.push(department);
        }

        return departments;
    },
    withUser: function () {
        return Session.get('withUser');
    },
    unreadMessagesCount: function (fromUserId) {
        var unreadMessageCount = Messages.find({
            fromUserId: fromUserId,
            toUserId: Meteor.userId(),
            read: false
        }).count();

        return unreadMessageCount > 99 ? "99+" : unreadMessageCount;
    }
});

Template.departments.events({
    'click a': function (e, t) {
        e.preventDefault();

        var clickedItem = $(e.target);
        var withUserId = clickedItem.attr('id');

        var withUser = Meteor.users.findOne(withUserId);
        Session.set('withUser', withUser);
    }
});


text:
/**
 * @file RArray_Blocks.c
 * @brief Block category to RArray operations.
 * @author Kucheruavyu Ilya (kojiba@protonmail.com)
 * @date 9/29/2015
 * @par Ukraine Kharkiv
 *
 *//*
 *  _         _ _ _
 * | |       (_|_) |
 * | | _____  _ _| |__   __ _
 * | |/ / _ \| | | '_ \ / _` |
 * |   < (_) | | | |_) | (_| |
 * |_|\_\___/| |_|_.__/ \__,_|
 *          _/ |
 *         |__/
 */

#include "RArray_Blocks.h"

#ifdef RAY_BLOCKS_ON

#ifdef RAY_ARRAY_THREAD_SAFE
    #define arrayMutex         (RMutex*)(const RMutex*)(&((const RArray* )object)->mutex) // warning removes
    #define RMutexLockArray()   RMutexLock(arrayMutex)
    #define RMutexUnlockArray() RMutexUnlock(arrayMutex)
#else
    // sets empty
    #define arrayMutex
    #define RMutexLockArray(some)
    #define RMutexUnlockArray(some)
#endif

#define incrementFreePlaces() --object->count; \
                              ++object->freePlaces

#define swapElementsAtIndexes(index1, index2) pointer temp = object->array[index1]; \
                                              object->array[index1] = object->array[index2]; \
                                              object->array[index2] = temp

method(void, deleteWithBlock, RArray), REnumerateBlock enumerator) {
    if(object->count != 0
       && enumerator != nil) {
        size_t iterator;
        RMutexLockArray();
        forAll(iterator, object->count) {
            if(enumerator(object->array[iterator], iterator)) {
                if(object->destructorDelegate != nil) {
                    object->destructorDelegate(object->array[iterator]);
                }
                $(object, m(shift, RArray)), yes, makeRRange(iterator, 1));
                break;
            }
        }
        RMutexUnlockArray();
    } elseWarning(
            RWarning1("RArray. deleteWithBlock. Array is empty (size = %zu) or enumerator nil.", object, object->count)
    );
}

method(void, deleteFastWithBlock, RArray), REnumerateBlock enumerator) {
    size_t iterator;
    printDebugTrace();
    if(enumerator != nil) {
        RMutexLockArray();
        if (object->destructorDelegate != nil) {
            for (iterator = 0; iterator < object->count;) {
                if (enumerator(object->array[iterator], iterator)) {
                    object->destructorDelegate(object->array[iterator]);
                    object->array[iterator] = object->array[object->count - 1];
                    incrementFreePlaces();
                    --iterator;
                } else {
                    ++iterator;
                }
            }
        } else {
            for (iterator = 0; iterator < object->count;) {
                if (enumerator(object->array[iterator], iterator)) {
                    object->array[iterator] = object->array[object->count - 1];
                    incrementFreePlaces();
                    --iterator;
                } else {
                    ++iterator;
                }
            }
        }
        RMutexUnlockArray();
    } elseWarning(
            RWarning("RArray. deleteWithBlock. Block is nil.", object)
    );
}

method(RArray *, subarrayWithBlock, RArray), REnumerateBlock enumerator) {
    size_t  iterator;
    RArray *result = nil;
    printDebugTrace();
    if(enumerator != nil) {
        result = makeRArray();
        if(result != nil) {
            result->destructorDelegate = object->destructorDelegate;
            result->printerDelegate    = object->printerDelegate;

            RMutexLockArray();
            forAll(iterator, object->count) {
                if (enumerator(object->array[iterator], iterator)) {
                    $(result, m(addObject, RArray)), object->array[iterator]);
                }
            }
            RMutexUnlockArray();
            $(result, m(sizeToFit, RArray)));
        } elseError(
                RError("RArray. subarrayWithBlock. Cant allocate result array." , object);
        );
    } elseWarning(
            RWarning("RArray. subarrayWithBlock. Block for enumerating is nil." , object);
    );
    return result;
}

method(RFindResult, enumerateWithBlock, RArray), REnumerateBlock enumerator) {
    size_t iterator;
    RFindResult result;
    result.index  = object->count;
    result.object = nil;
    printDebugTrace();
    if(enumerator != nil) {
        RMutexLockArray();
        forAll(iterator, object->count) {
            if(!enumerator(object->array[iterator], iterator)) {
                break;
            }
        }

        if(iterator != object->count) {
            result.index = iterator;
            result.object = object->array[iterator];
        }
        RMutexUnlockArray();
    } elseWarning(
            RWarning("RArray. enumerateWithBlock. Enumerator block is nil.", object)
    );

    return result;
}

method(void, quickSortWithBlock, RArray), size_t first, size_t last, byte (^comparator)(pointer, pointer)) {
    RMutexLockArray(); // may be locked many times
#ifdef RAY_SHORT_DEBUG
    static size_t number = 0;
    RPrintf("RArray quickSortWithBlock of %p recursive #%lu\n", object, number);
    ++number;
#endif

    if (last > first) {
        pointer pivot = object->array[first];
        size_t left = first;
        size_t right = last;
        while (left < right) {
            if (comparator(object->array[left], pivot) == no) {
                left += 1;
            } else {
                right -= 1;
                // swap
                swapElementsAtIndexes(left, right);
            }
        }

        left -= 1;

        // swap
        swapElementsAtIndexes(first, left);

        $(object, m(quickSortWithBlock, RArray)), first, left, comparator);
        $(object, m(quickSortWithBlock, RArray)), right, last, comparator);
    }
    RMutexUnlockArray();
}

#endif


text:
class AddIndexOnCiBuildsUpdatedAt < ActiveRecord::Migration
  include Gitlab::Database::MigrationHelpers

  # Set this constant to true if this migration requires downtime.
  DOWNTIME = false

  disable_ddl_transaction!

  def up
    add_concurrent_index :ci_builds, :updated_at
  end

  def down
    remove_concurrent_index :ci_builds, :updated_at if index_exists?(:ci_builds, :updated_at)
  end
end


text:
<meta charset="utf-8">

<title>SpringBar</title>

<link href="springbar.css" rel="stylesheet" type="text/css"/>

A Nice Message Bar Example

Veggies sunt bona vobis, proinde vos postulo esse magis pea sprouts wakame broccoli rabe collard greens aubergine sea lettuce turnip bush tomato horseradish silver beet asparagus seakale.

Green bean silver beet wattle seed tomato chicory broccoli rabe water chestnut courgette asparagus lentil. Beetroot epazote grape endive pea sprouts radish kakadu plum broccoli chicory komatsuna ricebean. Gourd green bean gram water spinach endive water chestnut soko. Celery jícama zucchini lettuce gumbo black-eyed pea maize caulie lentil fava bean broccoli rabe pea sprouts dulse artichoke. Cress mung bean beet greens shallot celery quandong. Turnip greens onion asparagus carrot soybean swiss chard caulie bunya nuts rock melon tomatillo bok choy tatsoi cress courgette sweet pepper. Okra desert raisin jícama asparagus grape spinach mung bean catsear wattle seed collard greens sorrel arugula burdock cabbage avocado celtuce gourd kakadu plum. Water spinach cress aubergine shallot komatsuna radish.

Wattle seed bitterleaf water chestnut nori caulie jícama chickpea napa cabbage burdock komatsuna green bean courgette mung bean catsear. Rock melon bell pepper parsnip desert raisin bunya nuts caulie garbanzo plantain fava bean kombu napa cabbage endive seakale komatsuna arugula turnip tomatillo. Zucchini mustard arugula water spinach caulie ricebean yarrow garbanzo salad celery gourd swiss chard turnip artichoke.

Plantain eggplant chard yarrow green bean taro corn. Peanut radish pea sprouts bamboo shoot sea lettuce courgette turnip arugula jícama corn cucumber pumpkin leek bell pepper collard greens pea. Seakale garlic mustard groundnut epazote radicchio silver beet. Cucumber avocado beet greens sweet pepper amaranth nori salsify wakame scallion chard tigernut gumbo garlic rock melon radish water chestnut salad. Bamboo shoot spring onion parsnip yarrow jícama eggplant courgette turnip celery salsify wattle seed azuki bean napa cabbage. Gourd sierra leone bologi chard broccoli rabe zucchini azuki bean horseradish welsh onion gourd spinach plantain cress quandong mung bean courgette bush tomato. Courgette bush tomato beetroot chicory water spinach catsear chickweed melon gram salad kakadu plum. Garbanzo gourd bamboo shoot garlic chickweed watercress.

Corn kombu pea sprouts coriander chickweed sea lettuce water spinach broccoli courgette burdock parsley garlic kakadu plum. Cress gram garlic sierra leone bologi maize mustard swiss chard leek cabbage lentil komatsuna courgette horseradish water chestnut sorrel lettuce. Horseradish cabbage onion aubergine tatsoi sierra leone bologi cucumber lettuce sweet pepper.


text:
<?php

use Doctrine\DBAL\Cache\QueryCacheProfile;
use Pinboard\Utils\IDNaConvert;
use Pinboard\Utils\Utils;

$index = $app['controllers_factory'];

$index->get('/', function() use ($app) {

    $result = array();
    $params = array(
        'created_at' => date('Y-m-d H:00:00', strtotime('-1 day')),
    );

    $hostsRegexp = Utils::getUserAccessHostsRegexp($app);
    $hostsWhere = '';

    if ($hostsRegexp != '.*') {
        $hostsRegexp = is_array($hostsRegexp) ? $hostsRegexp : array($hostsRegexp);
        $hostsWhere = " AND (a.server_name REGEXP '" . implode("' OR a.server_name REGEXP '", $hostsRegexp) . "')";
    }

    $sql = '
        SELECT
            a.server_name,
            sum(a.req_count) as req_count,
            avg(a.req_per_sec) as req_per_sec,
            (
                SELECT
                    count(*)
                FROM
                    ipm_status_details b
                WHERE
                    a.server_name = b.server_name AND b.created_at > :created_at
            )
            as error_count
        FROM
            ipm_report_by_hostname_and_server a
        WHERE
            a.created_at > :created_at' . $hostsWhere . '
        GROUP BY
            a.server_name
    ';

    $stmt = $app['db']->executeCacheQuery($sql, $params, array(), new QueryCacheProfile(60 * 60));
    $result['servers'] = $stmt->fetchAll();
    $stmt->closeCursor();

    $idn = new IDNaConvert(array('idn_version' => 2008));

    $total = array(
        'req_count' => 0,
        'error_count' => 0,
    );
    foreach($result['servers'] as &$item) {
        if (stripos($item['server_name'], 'xn--') !== false) {
            $item['server_name'] = $idn->decode($item['server_name']);
        }

        $item['req_per_sec'] = number_format($item['req_per_sec'], 3, ',', '');

        $total['req_count'] += $item['req_count'];
        $total['error_count'] += $item['error_count'];
    }

    $result['total'] = $total;

    return $app['twig']->render('index.html.twig', $result);
})
->bind('index');

return $index;


text:
package actions

import (
	"sync"

	"github.com/FireEater64/clockwork-go"
	log "github.com/cihub/seelog"
)

var clock *clockwork.Clockwork

func SendSMS(recipient string, message string) {
	checkClockwork()
	toSend := clockwork.SMS{To: recipient, Message: message}
	messageResponse := clock.SendSMS(toSend)
	if messageResponse.SMSResult[0].ErrorMessage != "" {
		log.Warnf("Error sending SMS to %s: %s", recipient, messageResponse.SMSResult[0].ErrorMessage)
	}
}

func SendSMSMultiple(recipients []string, message string) {
	for _, recipient := range recipients {
		SendSMS(recipient, message)
	}
}

func SendSMSAsync(recipient string, message string) *sync.WaitGroup {
	wg := sync.WaitGroup{}
	wg.Add(1)
	defer wg.Done()
	go SendSMS(recipient, message)
	return &wg
}

func SendSMSMultipleAsync(recipients []string, message string) *sync.WaitGroup {
	wg := sync.WaitGroup{}
	wg.Add(len(recipients))

	for _, recipient := range recipients {
		go func(recipient string, message string) {
			defer wg.Done()
			SendSMS(recipient, message)
		}(recipient, message)
	}

	return &wg
}

func checkClockwork() {
	if clock == nil {
		clock = clockwork.NewClockwork(configuration.ClockworkAPIKey)
	}
}


text:
package org.keycloak.representations.info;

import org.keycloak.common.Profile;

import java.util.LinkedList;
import java.util.List;

/**
 * @author Stian Thorgersen
 */
public class ProfileInfoRepresentation {

    private String name;
    private List<String> disabledFeatures;

    public static ProfileInfoRepresentation create() {
        ProfileInfoRepresentation info = new ProfileInfoRepresentation();

        info.name = Profile.getName();
        info.disabledFeatures = new LinkedList<>();
        for (Profile.Feature f : Profile.getDisabledFeatures()) {
            info.disabledFeatures.add(f.name());
        }

        return info;
    }

    public String getName() {
        return name;
    }

    public List<String> getDisabledFeatures() {
        return disabledFeatures;
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Fusicolla phragmitis P. Karst.

### Remarks
null


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M14,19V5H18V19ZM6,19V5H10V19Z"/>
</vector>


text:
static void	delete_bundle(t_bundle *bundle)
{
	if (!bundle)
		return ;
	for (int i = 0; i < bundle->idcount; i++)
	{
		free(bundle->matches[i]);
	}
	free(bundle->matches);
	free(bundle->matches_counts);
	for (int i = 0; i < bundle->cellcount; i++)
		free(bundle->cells[i]);
	free(bundle->cells);
	free(bundle->cell_sizes);
	free(bundle->ids);
	free(bundle->local_counts);
	free(bundle->locals);
	free(bundle);
}

static void *debundle_thread(void *param)
{
	t_worker	*worker;
	t_workunit  *workunit;

	worker = (t_worker *)param;
	while (1)
	{
		if (sem_wait(worker->ready_for_bundle) < 0)
			printf("BNDL- sem_wait failed with err:%d\n", errno);
		if (sem_wait(worker->debundle_sem) < 0)
		    printf("BNDL- sem_wait failed with err:%d\n", errno);
		if (DEBUG)
			printf("BNDL- debundling\n");
		t_bundle *bundle = queue_pop(&worker->bundle_queue);
		printf("this bundle has %d workunits in it\n", bundle->idcount);
		while(bundle->index < bundle->idcount)
		{
			queue_enqueue(&worker->todo_work, queue_create_new(kick_bundle(bundle)));
			sem_post(worker->calc_thread_sem);
		}
		printf("bundle is spent\n");
		delete_bundle(bundle);
		if (DEBUG)
			printf("BNDL- finished debundling %d workunits\n", bundle->idcount);
	}
	return (0);
}

void launch_debundle_thread(t_worker *worker)
{
	worker->debundle_thread = (pthread_t *)calloc(1, sizeof(pthread_t));
	pthread_create(worker->debundle_thread, NULL, debundle_thread, worker);
}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>All Classes (SBT Compiler Maven Plugin 1.0.0-beta5 API)</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

AbstractSBTCompileMojo

MavenCompilerLogger

SBTAddManagedSourcesMojo

SBTAddScalaSourcesMojo

SBTCompileMojo

SBTTestCompileMojo


text:
/**
 * The default is to use a file path string. It implies use of the template method.
 * For any other config an object { file:.., method:.., template:.. } can be used
 */

const faker = require('@faker-js/faker');

const { stringHashCode } = require('../utils');

const cypressFiles = {
  common: [
    {
      templates: ['cypress.config.ts', 'cypress-audits.config.ts'],
    },
  ],
  clientTestFw: [
    {
      path: generator => generator.cypressFolder,
      templates: [
        '.eslintrc.json',
        'fixtures/integration-test.png',
        'plugins/index.ts',
        'e2e/administration/administration.cy.ts',
        'e2e/lighthouse.audits.ts',
        'support/commands.ts',
        'support/navbar.ts',
        'support/index.ts',
        'support/entity.ts',
        'support/management.ts',
        'tsconfig.json',
      ],
    },
    {
      condition: generator => !generator.authenticationTypeOauth2,
      path: generator => generator.cypressFolder,
      templates: ['e2e/account/login-page.cy.ts'],
    },
    {
      condition: generator => !generator.authenticationTypeOauth2 && !generator.databaseTypeNo && !generator.applicationTypeMicroservice,
      path: generator => generator.cypressFolder,
      templates: [
        'e2e/account/register-page.cy.ts',
        'e2e/account/settings-page.cy.ts',
        'e2e/account/password-page.cy.ts',
        'e2e/account/reset-password-page.cy.ts',
      ],
    },
    {
      condition: generator => generator.authenticationTypeOauth2,
      path: generator => generator.cypressFolder,
      templates: ['support/oauth2.ts'],
    },
  ],
  coverage: [
    {
      condition: generator => generator.cypressCoverage,
      path: generator => generator.cypressFolder,
      templates: ['plugins/global.d.ts'],
    },
  ],
};

module.exports = {
  writeFiles,
  files: cypressFiles,
};

function writeFiles() {
  return {
    writeFiles() {
      faker.seed(stringHashCode(this.jhipsterConfig.baseName || 'jhipsterSample'));
      this.faker = faker;
      return this.writeFiles({ sections: cypressFiles });
    },
  };
}


text:
<?php

namespace Gtt\ThriftGenerator\Dumper;

use Gtt\ThriftGenerator\Dumper\Exception\DumpException;
use Gtt\ThriftGenerator\Generator\NamespacedComplexTypeFilenameGenerator;

/**
 * Dumps complex type definitions grouped by namespace
 *
 * @author fduch <alex.medwedew@gmail.com>
 */
class NamespacedComplexTypeDumper extends AbstractFilesystemDumper
{
    /**
     * Namespace of complex types definition need to be dumped
     *
     * @var string
     */
    protected $namespace;

    /**
     * Complex types definition
     *
     * @var string
     */
    protected $complexTypesDefinition;

    /**
     * Sets namespace of complex types need to be dumped
     *
     * @param string $namespace namespace
     *
     * @return $this
     */
    public function setNamespace($namespace)
    {
        $this->namespace = $namespace;

        return $this;
    }

    /**
     * Returns namespace of complex types need to be dumped
     *
     * @return string
     */
    public function getNamespace()
    {
        return $this->namespace;
    }

    /**
     * Sets complex types definition
     *
     * @param string $definition definition
     *
     * @return $this
     */
    public function setComplexTypesDefinition($definition)
    {
        $this->complexTypesDefinition = $definition;

        return $this;
    }

    /**
     * Returns complex types definition
     *
     * @return string
     */
    public function getComplexTypesDefinition()
    {
        return $this->complexTypesDefinition;
    }

    /**
     * {@inheritdoc}
     */
    public function dump()
    {
        if (is_null($this->namespace)) {
            throw new DumpException("Complex types namespace is not specified");
        }
        if (is_null($this->outputDir) || !is_dir($this->outputDir) || !is_writable($this->outputDir)) {
            throw new DumpException("Output dir is not specified, not exists or not writable");
        }
        if (is_null($this->complexTypesDefinition)) {
            throw new DumpException("Complex types definition content is not specified");
        }

        $filenameGenerator = $this->getFilenameGenerator();
        $complexTypesPath  = $this->outputDir.DIRECTORY_SEPARATOR.$filenameGenerator->generate();

        $this->dumpFile($complexTypesPath, $this->complexTypesDefinition);
    }

    /**
     * Creates and returns complex type filename generator
     *
     * @return NamespacedComplexTypeFilenameGenerator
     */
    protected function getFilenameGenerator()
    {
        $filenameGenerator = new NamespacedComplexTypeFilenameGenerator();
        $filenameGenerator->setNamespace($this->namespace);

        return $filenameGenerator;
    }
}


text:
var http = require('http');
var async = require('async');
var assert = require('assert');
var child_process = require('child_process');

var child = null;
var running = false;
var port = 0;
var runner = null;

function startChild(timeout) {
    if (timeout == null) {
        timeout = 30;
    }
    port = 15000 + Math.floor(Math.random() * 5000);
    running = true;
    child = child_process.fork("test/" + runner + ".js", [port, timeout]);
    child.on('disconnect', function () {
        running = false;
    });
}

function advanceClock(seconds) {
    assert(running);
    child.send({
        clock: seconds
    });
}

function advanceClockAsync(seconds) {
    return function (cb) {
        assert(running);
        child.send({
            clock: seconds
        });
        cb();
    };
}

function assertRunning(cb) {
    child.once('message', function () {
        assert(running);
        cb();
    });
    child.send({
        ping: true
    });
}

function assertExits(cb) {
    return function (err) {
        if (err) {
            return cb(err);
        }
        // Should end
        child.once('disconnect', cb);
    };
}

function pokeServer(cb) {
    http.get('http://localhost:' + port, function (res) {
        assert.equal(res.statusCode, 200);
        cb();
    });
}

function runTests() {
    it("Should quit after a certain amount of time", function (done) {
        startChild();
        assertRunning(function () {
            advanceClock(30);
            child.once('disconnect', done);
        });
    });

    it("Should reset stay alive period when a request comes in", function (done) {
        startChild();
        async.series([
            assertRunning,
            advanceClockAsync(16),
            // Should still be running, send call:
            assertRunning,
            pokeServer,
            assertRunning,
            // Move the clock forward, 32 seconds after start
            advanceClockAsync(16),

            // Should still be running if the interval has been reset
            assertRunning,
            advanceClockAsync(16)
        ], assertExits(done));
    });

    it("Can customize timeout period", function (done) {
        // Default test runner has 30 seconds timeout. We've tested above that it
        // stays alive for 16 seconds. Let's try 5.
        startChild(5);
        async.series([
            assertRunning,
            advanceClockAsync(4),
            assertRunning,
            advanceClockAsync(2)
        ], assertExits(done));
    });
}

runner = 'runner';
describe("Plain HTTP server", runTests);

runner = 'express-runner';
describe("Express", runTests);


text:
using UnityEngine;
using System.Collections;

public enum AN_LicenseStatusCode {
	RESULT_ALLOW,
	RESULT_DONTALLOW,
	RESULT_ERROR,
}


text:
#include "CLucene/StdHeader.h"
#include "RangeFilter.h"

CL_NS_DEF(search)
CL_NS_USE(index)
CL_NS_USE(util)
CL_NS_USE(document)

RangeFilter::RangeFilter( const TCHAR* fieldName, const TCHAR* lowerTerm, const TCHAR* upperTerm, bool includeLower, bool includeUpper )
{
	this->field = STRDUP_TtoT(fieldName);
	if ( lowerTerm != NULL )
		this->lowerValue = STRDUP_TtoT(lowerTerm);
	else
		this->lowerValue = NULL;
	if ( upperTerm != NULL )
		this->upperValue = STRDUP_TtoT(upperTerm);
	else
		this->upperValue = NULL;
	this->includeLower = includeLower;
	this->includeUpper = includeUpper;
}

/**
 * Constructs a filter for field fieldName matching
 * less than or equal to upperTerm.
 */
RangeFilter* RangeFilter::Less( TCHAR* fieldName, TCHAR* upperTerm ) {
	return new RangeFilter( fieldName, NULL, upperTerm, false, true );
}

/**
* Constructs a filter for field fieldName matching
* more than or equal to lowerTerm.
*/
RangeFilter* RangeFilter::More( TCHAR* fieldName, TCHAR* lowerTerm ) {
	return new RangeFilter( fieldName, lowerTerm, NULL, true, false );
}

RangeFilter::~RangeFilter()
{
	_CLDELETE_CARRAY( lowerValue );
	_CLDELETE_CARRAY( field );
	_CLDELETE_CARRAY( upperValue );
}

RangeFilter::RangeFilter( const RangeFilter& copy ) :
	field( STRDUP_TtoT(copy.field) ),
	lowerValue( STRDUP_TtoT(copy.lowerValue) ),
	upperValue( STRDUP_TtoT(copy.upperValue) ),
	includeLower( copy.includeLower ),
	includeUpper( copy.includeUpper )
{
}

Filter* RangeFilter::clone() const {
	return _CLNEW RangeFilter(*this );
}

TCHAR* RangeFilter::toString()
{
	size_t len = (field ? _tcslen(field) : 0) + (lowerValue ? _tcslen(lowerValue) : 0) + (upperValue ? _tcslen(upperValue) : 0) + 8;
	TCHAR* ret = _CL_NEWARRAY( TCHAR, len );
	ret[0] = 0;
	_sntprintf( ret, len, _T("%s: [%s-%s]"), field, (lowerValue?lowerValue:_T("")), (upperValue?upperValue:_T("")) );

	return ret;
}

/** Returns a BitSet with true for documents which should be permitted in
search results, and false for those that should not. */
BitSet* RangeFilter::bits( IndexReader* reader )
{
	BitSet* bts = _CLNEW BitSet( reader->maxDoc() );
	Term* term = NULL;

	Term* t = _CLNEW Term( field, (lowerValue ? lowerValue : _T("")), false );
	TermEnum* enumerator = reader->terms( t );	// get enumeration of all terms after lowerValue
	_CLDECDELETE( t );

	if( enumerator->term(false) == NULL ) {
		_CLDELETE( enumerator );
		return bts;
	}

	bool checkLower = false;
	if( !includeLower ) // make adjustments to set to exclusive
		checkLower = true;

	TermDocs* termDocs = reader->termDocs();

	try
	{
		do
		{
			term = enumerator->term();

			if( term == NULL || _tcscmp(term->field(), field) )
				break;

			if( !checkLower || lowerValue == NULL || _tcscmp(term->text(), lowerValue) > 0 )
			{
				checkLower = false;
				if( upperValue != NULL )
				{
					int compare = _tcscmp( upperValue, term->text() );

					/* if beyond the upper term, or is exclusive and
					 * this is equal to the upper term, break out */
					if( (compare < 0) || (!includeUpper && compare == 0) )
						break;
				}

				termDocs->seek( enumerator->term(false) );
				while( termDocs->next() ) {
					bts->set( termDocs->doc() );
				}
			}

			_CLDECDELETE( term );
		}
		while( enumerator->next() );
	}
	_CLFINALLY
	(
		_CLDECDELETE( term );
		termDocs->close();
		_CLVDELETE( termDocs );
		enumerator->close();
		_CLDELETE( enumerator );
	);

	return bts;
}

CL_NS_END


text:
<?php

declare(strict_types=1);

namespace Billogram\Model\Invoice;

use Billogram\Model\CreatableFromArray;
use Billogram\Model\Item\BaseItem;
use Billogram\Model\Item\Bookkeeping;

/**
 * @author Ibrahim Hizeoui <ibrahimhizeoui@gmail.com>
 */
class Item extends BaseItem implements CreatableFromArray
{
    /**
     * @var int count
     */
    private $count;

    /**
     * @var int
     */
    private $discount;

    /**
     * @return int
     */
    public function getCount(): int
    {
        return $this->count;
    }

    /**
     * @param int $count
     *
     * @return Item
     */
    public function withCount(int $count)
    {
        $new = clone $this;
        $new->count = $count;

        return $new;
    }

    /**
     * @return int
     */
    public function getDiscount(): int
    {
        return $this->discount;
    }

    /**
     * @param int $discount
     *
     * @return Item
     */
    public function withDiscount(int $discount)
    {
        $new = clone $this;
        $new->discount = $discount;

        return $new;
    }

    public function toArray()
    {
        $data = parent::toArray();
        if (null !== $this->count) {
            $data['count'] = $this->count;
        }
        if (null !== $this->discount) {
            $data['discount'] = $this->discount;
        }

        return $data;
    }

    public static function createFromArray(array $data)
    {
        $item = new self();
        $item->count = $data['count'] ?? null;
        $item->discount = $data['discount'] ?? null;
        $item->itemNo = $data['item_no'] ?? null;
        $item->title = $data['title'] ?? null;
        $item->description = $data['description'] ?? null;
        $item->price = $data['price'] ?? null;
        $item->vat = $data['vat'] ?? null;
        $item->unit = $data['unit'] ?? null;
        $item = $item->withBookkeeping(Bookkeeping::createFromArray($data['bookkeeping'])) ?? null;

        return $item;
    }
}


text:
"use strict";
import ItemTags = require('./ItemTags');

interface ThemeTags { [theme: string]: ItemTags; }
export = ThemeTags;


text:
<ng-form name="forms.containerSelect">

        <input
          type="checkbox"
          ng-model="containers[container.name]"
          ng-required="required && !containerSelected">
        {{container.name}}

        from image
        {{container.image}}

    {{helpText}}

      You must select at least one container.

</ng-form>


text:
using std::ostringstream; using std::string; using std::hex;
using std::vector; using std::ifstream; using std::ofstream;
using std::runtime_error;

#include "small_set.h"
#include "timeops.h"

#ifndef ANDROID
#include <RInside.h>
using Rcpp::as;

#include "r_singleton.h"

void
StatsDistributionBinned::initRInside()
{
    R = get_rinside_instance();
    R->parseEvalQ("library(histogram)");

    ostringstream oss;
    oss << "samples_" << hex << this;
    r_samples_name = oss.str();
}
#endif

#include "debug.h"

class NoRInsideOnAndroid : public runtime_error {
  public:
    NoRInsideOnAndroid() :
        runtime_error("Can't auto-determine histogram bins on Android. (no R)") {}
};

StatsDistributionBinned::StatsDistributionBinned(bool weighted_error_)
    : all_samples(weighted_error_), weighted_error(weighted_error_)
{
#ifdef ANDROID
    throw NoRInsideOnAndroid();
#else
    initRInside();
    preset_breaks = false;
#endif
}

StatsDistributionBinned::StatsDistributionBinned(vector<double> new_breaks,
                                                 bool weighted_error_)
    : all_samples(weighted_error_), weighted_error(weighted_error_)
{
    setBreaks(new_breaks);

    assertValidHistogram();
}

void
StatsDistributionBinned::setBreaks(const vector<double>& new_breaks)
{
    preset_breaks = true;
    breaks = new_breaks;
    counts.resize(breaks.size() + 1, 0);
    bin_weights.resize(breaks.size() + 2, 0.0);
    mids.clear();
    mids.push_back(0.0);
    for (size_t i = 0; i < breaks.size() - 1; ++i) {
        double mid = (breaks[i] + breaks[i+1]) / 2.0;
        mids.push_back(mid);
    }
    mids.push_back(0.0);
}

// construct a regular histogram with num_bins bins ranging from min to max.
// e.g. min=0, max=10, num_bins=4 results in
//      breaks: [0, 2.5, 5, 7.5, 10], the endpoints of 4 bins.
StatsDistributionBinned::StatsDistributionBinned(double min, double max, size_t num_bins,
                                                 bool weighted_error_)
    : all_samples(weighted_error_), weighted_error(weighted_error_)
{
    vector<double> new_breaks;
    double width = (max - min) / num_bins;
    for (size_t i = 0; i <= num_bins; ++i) {
        new_breaks.push_back(min + i * width);
    }
    setBreaks(new_breaks);
}

StatsDistributionBinned *
StatsDistributionBinned::create(Estimator *estimator, bool weighted_error_)
{
    if (estimator && estimator->hasRangeHints()) {
        EstimatorRangeHints hints = estimator->getRangeHints();
        return new StatsDistributionBinned(hints.min, hints.max, hints.num_bins, weighted_error_);
    } else {
        ASSERT(false); // must have range hints to create histogram. (may change; probably not)
        return new StatsDistributionBinned(weighted_error_);
    }
}

void
StatsDistributionBinned::addValue(double value)
{
    all_samples.addValue(value);
    addToHistogram(value);
    if (shouldRebin()) {
        calculateBins();
    }
}

double
StatsDistributionBinned::getProbability(double value)
{
    if (binsAreSet()) {
        return probabilityAtIndex(getIndex(value));
    } else {
        return all_samples.getProbability(value);
    }
}

double
StatsDistributionBinned::getBinnedValue(double value)
{
    if (binsAreSet()) {
        return mids[getIndex(value)];
    } else {
        return value;
    }
}

double
StatsDistributionBinned::getValueAtIndex(size_t index)
{
    ASSERT(index >= 0 && index < mids.size());
    return mids[index];
}

double
StatsDistributionBinned::probabilityAtIndex(size_t index)
{
    ASSERT(index < counts.size());
    if (weighted_error) {
        return bin_weights[index] / total_bin_weights;
    } else {
        return (double(counts[index]) / all_samples_sorted.size());
    }
}

double
StatsDistributionBinned::Iterator::probability()
{
    return probability(index);
}

inline double
StatsDistributionBinned::Iterator::probability(size_t pos)
{
    return distribution->probabilityAtIndex(pos);
}

inline double
StatsDistributionBinned::Iterator::value()
{
    return at(index);
}

inline double
StatsDistributionBinned::Iterator::at(size_t pos)
{
    return distribution->mids[pos];
}

inline void
StatsDistributionBinned::Iterator::advance()
{
    if (index < (int) distribution->mids.size()) {
        ++index;
    }
}

inline bool
StatsDistributionBinned::Iterator::isDone()
{
    return (index == (int) distribution->mids.size());
}

inline void
StatsDistributionBinned::Iterator::reset()
{
    index = 0;
}

inline int
StatsDistributionBinned::Iterator::position()
{
    return index;
}

inline int
StatsDistributionBinned::Iterator::totalCount()
{
    return (int) distribution->mids.size();
}

StatsDistributionBinned::Iterator::Iterator(StatsDistributionBinned *d)
{
    distribution = d;
    index = 0;
}

StatsDistribution::Iterator *
StatsDistributionBinned::makeNewIterator()
{
    if (breaks.empty()) {
        return all_samples.getIterator();
    } else {
        return new StatsDistributionBinned::Iterator(this);
    }
}

void mark_timepoint(const char *msg)
{
    static std::string last_msg;
    static struct timeval last_timestamp = {0, 0};

    struct timeval now;
    TIME(now);

    if (last_msg.length() > 0) {
        struct timeval diff;
        TIMEDIFF(last_timestamp, now, diff);
        fprintf(stderr, "%s took %lu.%06lu seconds\n",
                last_msg.c_str(), diff.tv_sec, diff.tv_usec);
    }
    if (msg) {
        last_msg.assign(msg);
    } else {
        last_msg.assign("");
    }
    last_timestamp = now;
}

void StatsDistributionBinned::calculateBins()
{
#ifdef ANDROID
    throw NoRInsideOnAndroid();
#else
    assertValidHistogram();

    vector<double> samples(all_samples_sorted.begin(), all_samples_sorted.end());
    std::set<double> unique_samples(samples.begin(), samples.end());
    if (unique_samples.size() <= 1) {
        // R's histogram function blows up if I pass a vector of one value
        // try again next sample
        return;
    }

    R->assign(samples, r_samples_name);
    //R->parseEval(string("print(") + r_samples_name + string(")"));

    //mark_timepoint("calling histogram()");
    ostringstream oss;
    oss << "histogram::histogram(" << r_samples_name << ", verbose=FALSE, plot=FALSE)";
    Rcpp::List hist_result = R->parseEval(oss.str());
    //mark_timepoint(NULL);

    breaks = as<vector<double> >(hist_result["breaks"]);
    vector<double> tmp_mids = as<vector<double> >(hist_result["mids"]);
    vector<int> tmp_counts = as<vector<int> >(hist_result["counts"]);
    //fprintf(stderr, "histogram with %zu bins\n", tmp_counts.size());

    mids.assign(1, 0.0);
    mids.insert(mids.end(), tmp_mids.begin(), tmp_mids.end());
    mids.push_back(0.0);

    counts.assign(tmp_counts.size() + 2, 0);
    bin_weights.resize(tmp_counts.size() + 2, 0.0);
    for (double sample : samples) {
        size_t index = getIndex(sample);
        updateBin(index, sample);
    }

    // tails are now empty, because all the data fits in the bins.

    oss.str("");
    oss << "remove(" << r_samples_name << ")";
    R->parseEvalQ(oss.str());

    assertValidHistogram();

    //printHistogram();
#endif
}

void
StatsDistributionBinned::printHistogram()
{
    fprintf(stderr, "breaks   ltail  |");
    for (size_t i = 0; i < breaks.size(); ++i) {
        fprintf(stderr, "%-8.3f|", breaks[i]);
    }
    fprintf(stderr, "rtail\n");

    fprintf(stderr, "counts   %5d   ", counts[0]);
    for (size_t i = 1; i < counts.size(); ++i) {
        fprintf(stderr, "%8d ", counts[i]);
    }
    fprintf(stderr, "\n");

    fprintf(stderr, "mids     %5f   ", mids[0]);
    for (size_t i = 1; i < mids.size(); ++i) {
        fprintf(stderr, "%8f ", mids[i]);
    }
    fprintf(stderr, "\n");
}

bool
StatsDistributionBinned::binsAreSet()
{
    // because I shouldn't be making histograms without range hints anymore.
    ASSERT(!breaks.empty());

    return (!breaks.empty());
}

bool
StatsDistributionBinned::shouldRebin()
{
    return (!preset_breaks && (all_samples_sorted.size() % histogram_threshold) == 0);
}

void
StatsDistributionBinned::addToHistogram(double value)
{
    // breaks:   0   1   2   3   ...
    // mids:   0   1   2   3   4 ...
    // counts: 0   1   2   3   4 ...

    // if a value falls between breaks n and n+1,
    //  lower_bound returns n+1.
    // When the value is within the histogram, this returns something
    //  between 1 and n.
    // When the value is less than the first break,
    //  it returns position 0, which points to the "left tail" bin.
    // When the value is greater than the last break,
    //  it returns position numbins+1, which points to the "right tail" bin.

    assertValidHistogram();

    if (binsAreSet()) {
        size_t index = getIndex(value);
        updateBin(index, value);
    } else {
        // no histogram yet; ignore.
    }
    all_samples_sorted.insert(value);

    assertValidHistogram();
}

size_t
StatsDistributionBinned::getIndex(double value)
{
    vector<double>::iterator pos =
        lower_bound(breaks.begin(), breaks.end(), value);
    size_t index = int(pos - breaks.begin());
    return index;
}

void
StatsDistributionBinned::updateBin(int index, double value)
{
    if (index == 0 || index == (int) breaks.size()) {
        addToTail(index, value);
    } else {
        counts[index]++;
    }
    if (weighted_error) {
        updateBinWeights(index);
    }
}

#include "error_weight_params.h"
using instruments::NEW_SAMPLE_WEIGHT;
using instruments::update_ewma;

void
StatsDistributionBinned::updateBinWeights(int new_sample_bin)
{
    total_bin_weights = 0.0;
    for (size_t i = 0; i < counts.size(); ++i) {
        //
        if (counts[i] > 0) {
            if ((int) i == new_sample_bin) {
                // new sample increases the weight on its bin
                bin_weights[i] = NEW_SAMPLE_WEIGHT;
            } else {
                // aging sample decreases the weight on its bin
                // (a sample N iterations old has weight (NEW_SAMPLE_WEIGHT ^ N),
                //  same as with the all-samples version)
                bin_weights[i] *= NEW_SAMPLE_WEIGHT;
            }
        }
        total_bin_weights += bin_weights[i];
    }
}

void
StatsDistributionBinned::assertValidHistogram()
{
    if (!breaks.empty()) {
        ASSERT((breaks.size() + 1) == mids.size());
        ASSERT((breaks.size() + 1) == counts.size());

        int total_counts = 0;
        for (size_t i = 1; i < breaks.size(); ++i) {
            ASSERT(breaks[i-1] <= mids[i]);
            ASSERT(breaks[i] > mids[i]);

            total_counts += counts[i];
        }

        ASSERT(counts[0] == 0 || mids[0] <= breaks[0]);
        ASSERT(counts[counts.size()-1] == 0 ||
               mids[mids.size()-1] > breaks[breaks.size()-1]);

        total_counts += counts[0];
        total_counts += counts[counts.size() - 1];
        ASSERT(total_counts == (int) all_samples_sorted.size());
    }
}

void
StatsDistributionBinned::addToTail(int index, double value)
{
    int& count = counts[index];
    double& mid = mids[index];

    double sum = (count * mid);
    count++;
    mid = (sum + value) / count;
}

void
StatsDistributionBinned::appendToFile(const string& name, ofstream& out)
{
    throw runtime_error("NOT IMPLEMENTED");
}

string
StatsDistributionBinned::restoreFromFile(ifstream& in)
{
    throw runtime_error("NOT IMPLEMENTED");
}


text:
                        任务名称:{{task.name}}-{{appId}}

                        <button class="btn btn-default btn-sm" type="button" ng-click="showCustomDetail(appId)">客户详细信息</button>
                        <button class="btn btn-success btn-sm" type="submit" ng-disabled="form.$invalid"  ng-click="commmitTelInterviewTask()">提交任务</button>
                        <button class="btn btn-default btn-sm" type="button"  ng-click="back()">返回上级</button>

    <ng-form  name="form" novalidate ng-cloak="">

                <uib-tabset>
                    <uib-tab index="0">
                        <uib-tab-heading>
                            电话回访信息
                        </uib-tab-heading>
                        <form class="container-fluid m-t-md form-horizontal">

                        </form>
                    </uib-tab>

                    <uib-tab index="3"  select="queryWorkflowProcessResult(taskId)">
                        <uib-tab-heading>
                            流程流转记录
                        </uib-tab-heading>

                    </uib-tab>
                </uib-tabset>

    </ng-form>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<title>R: round</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="R.css">

round {SparkR}	R Documentation

round

Description

Returns the value of the column e rounded to 0 decimal places using HALF_UP rounding mode.

Usage

## S4 method for signature 'Column'
round(x)

Arguments

x

Column to compute on.

Note

round since 1.5.0

See Also

Other math_funcs: acos,
acos,Column-method; asin,
asin,Column-method; atan2,
atan2,Column-method; atan,
atan,Column-method; bin,
bin, bin,Column-method;
bround, bround,
bround,Column-method; cbrt,
cbrt, cbrt,Column-method;
ceil, ceil,
ceil,Column-method, ceiling,
ceiling,Column-method; conv,
conv,
conv,Column,numeric,numeric-method;
corr, corr,
corr, corr,Column-method,
corr,SparkDataFrame-method;
cosh, cosh,Column-method;
cos, cos,Column-method;
covar_pop, covar_pop,
covar_pop,characterOrColumn,characterOrColumn-method;
cov, cov, cov,
cov,SparkDataFrame-method,
cov,characterOrColumn-method,
covar_samp, covar_samp,
covar_samp,characterOrColumn,characterOrColumn-method;
expm1, expm1,Column-method;
exp, exp,Column-method;
factorial,
factorial,Column-method;
floor, floor,Column-method;
hex, hex,
hex,Column-method; hypot,
hypot, hypot,Column-method;
log10, log10,Column-method;
log1p, log1p,Column-method;
log2, log2,Column-method;
log, log,Column-method;
pmod, pmod,
pmod,Column-method; rint,
rint, rint,Column-method;
shiftLeft, shiftLeft,
shiftLeft,Column,numeric-method;
shiftRightUnsigned,
shiftRightUnsigned,
shiftRightUnsigned,Column,numeric-method;
shiftRight, shiftRight,
shiftRight,Column,numeric-method;
sign, sign,Column-method,
signum, signum,
signum,Column-method; sinh,
sinh,Column-method; sin,
sin,Column-method; sqrt,
sqrt,Column-method; tanh,
tanh,Column-method; tan,
tan,Column-method; toDegrees,
toDegrees,
toDegrees,Column-method;
toRadians, toRadians,
toRadians,Column-method;
unhex, unhex,
unhex,Column-method

Examples

## Not run: round(df$c)

[Package SparkR version 2.1.0 Index]


text:
module NgpVan
  # Custom error class for rescuing from NgpVan errors.
  class Error < StandardError
    attr_reader :body, :response, :status, :errors

    # rubocop:disable Metrics/MethodLength, Metrics/AbcSize,
    # rubocop:disable Style/CyclomaticComplexity
    # Returns a NgpVan::Error subclass, depending on status and
    # response message.
    #
    # @param [Hash] response HTTP response
    # @return [NgpVan::Error]
    def self.from_response(response)
      status = response[:status].to_i

      error_klass =
        case status
        when 400 then NgpVan::BadRequest
        when 401 then NgpVan::Unauthorized
        when 403 then NgpVan::Forbidden
        when 405 then NgpVan::MethodNotAllowed
        when 406 then NgpVan::NotAcceptable
        when 408 then NgpVan::RequestTimeout
        when 409 then NgpVan::Conflict
        when 413 then NgpVan::RequestEntityTooLarge
        when 415 then NgpVan::UnsupportedMediaType
        when 422 then NgpVan::UnprocessableEntity
        when 429 then NgpVan::TooManyRequests
        when 404 then NgpVan::NotFound
        when 400..499 then NgpVan::ClientError
        when 500 then NgpVan::InternalServerError
        when 501 then NgpVan::NotImplemented
        when 502 then NgpVan::BadGateway
        when 503 then NgpVan::ServiceUnavailable
        when 504 then NgpVan::GatewayTimeout
        when 500..599 then NgpVan::ServerError
        end

      error_klass.new(response) if error_klass
    end

    def initialize(response = nil)
      @response = response
      @body = ::JSON.parse(response[:body])
      @status = response[:status]
      @errors = body.delete('errors')

      super(build_error)
    end

    private

    def build_error
      return nil if response.nil?

      {
        status: status,
        errors: errors
      }
    end
  end

  # Errors in the 400-499 range
  class ClientError < Error; end

  # 400 Bad request
  class BadRequest < ClientError; end

  # 401 Unauthorized
  class Unauthorized < ClientError; end

  # 403 Forbidden
  class Forbidden < ClientError; end

  # 404 Not found
  class NotFound < ClientError; end

  # 405 Method not allowed
  class MethodNotAllowed < ClientError; end

  # 406 Not acceptable
  class NotAcceptable < ClientError; end

  # 408 Request timeout
  class RequestTimeout < ClientError; end

  # 409 Conflict
  class Conflict < ClientError; end

  # 413 Request entity too large
  class RequestEntityTooLarge < ClientError; end

  # 415 Unsupported media type
  class UnsupportedMediaType < ClientError; end

  # 422 Unprocessable entity
  class UnprocessableEntity < ClientError; end

  # 429 Too many requests
  class TooManyRequests < ClientError; end

  # Errors in the 500-599 range
  class ServerError < Error; end

  # 500 Internal server error
  class InternalServerError < ServerError; end

  # 501 Not implemented
  class NotImplemented < ServerError; end

  # 502 Bad gateway
  class BadGateway < ServerError; end

  # 503 Service unavailable
  class ServiceUnavailable < ServerError; end

  # 504 Gateway timeout
  class GatewayTimeout < ServerError; end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Class: Tracking</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href=".././rdoc-style.css" type="text/css" media="screen" />

          Class
          Tracking

            In:

                app/models/tracking.rb

            Parent:

                ActiveRecord::Base

Methods

      page_find
      per_page

Public Class methods

          page_find(page = 1)

[Source]

    # File app/models/tracking.rb, line 11
11:     def page_find(page = 1)
12:       paginate(:page => page, :order => "trackings.created_at desc")
13:     end

          per_page()

[Source]

   # File app/models/tracking.rb, line 9
9:     def per_page; 25 end

[Validate]


text:
using System.Collections.Generic;

namespace Unplugged.Segy
{
    public interface ITrace
    {
        ITraceHeader Header { get; }
        IList<float> Values { get; }
    }
}


text:
// Copyright 2014 by PeopleWare n.v..
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.DirectoryServices;
using System.Linq;
using System.Text;

namespace PPWCode.Util.OddsAndEnds.II.ActiveDirectory
{
    ///
    ///     Helper class for active directory.
    ///
    public class AdSearch
    {
        private readonly string m_DomainName;

        ///
        ///     The constructor.
        ///
        /// <param name="domainName">The name of domain.</param>
        public AdSearch(string domainName)
        {
            Contract.Requires(!string.IsNullOrEmpty(domainName));
            Contract.Ensures(DomainName == domainName);

            m_DomainName = domainName;
        }

        ///
        ///     The name of domain.
        ///
        public string DomainName
        {
            get { return m_DomainName; }
        }

        ///
        ///     This function parses the domain out of an user-account.
        ///
        /// <param name="userAccount">A user account has following format: DOMAIN\UserName.</param>
        /// <returns>The domain of an user account.</returns>
        /// <example>
        ///
        /// var domainName = AdSearch.GetDomainFromUserAccount(@"PPWDEV\jjanssenss");
        /// Console.WriteLine(domainName);
        ///
        ///     result: PPWDEV.
        /// </example>
        public static string GetDomainFromUserAccount(string userAccount)
        {
            Contract.Requires(!string.IsNullOrEmpty(userAccount));
            Contract.Requires(userAccount.Length > 2);
            Contract.Requires(userAccount.ToCharArray().Count(c => c == '\\') == 1);
            Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));

            StringBuilder sb = new StringBuilder(userAccount.Length);
            int i = 0;
            while (i < userAccount.Length && userAccount[i] != '\\')
            {
                sb.Append(userAccount[i++]);
            }

            return sb.ToString();
        }

        ///
        ///     This function parses the UserName out of an user account.
        ///
        /// <param name="userAccount">A user account with the following format: DOMAIN\UserName.</param>
        /// <returns>The user name for the given <paramref name="userAccount">account</paramref>.</returns>
        /// <example>
        ///
        /// var userName = AdSearch.GetAccountNameFromUserAccount(@"PPWDEV\JJANSSENS");
        /// Console.WriteLine(userName);
        ///
        ///     result: JJANSSENS.
        /// </example>
        public static string GetAccountNameFromUserAccount(string userAccount)
        {
            Contract.Requires(!string.IsNullOrEmpty(userAccount));
            Contract.Requires(userAccount.Length > 2);
            Contract.Requires(userAccount.ToCharArray().Count(c => c == '\\') == 1);
            Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));

            return userAccount.Replace(GetDomainFromUserAccount(userAccount) + @"\", string.Empty);
        }

        private DirectoryEntry GetDirectoryEntry()
        {
            DirectoryEntry de = new DirectoryEntry
                                {
                                    Path = string.Format(@"LDAP://DC={0},DC=local", m_DomainName),
                                    AuthenticationType = AuthenticationTypes.Secure,
                                };
            return de;
        }

        ///
        ///     List all available properties of an SAM Account.
        ///
        /// <param name="userAccount">A user account with the following format: DOMAIN\UserName.</param>
        /// <returns>A list with all available properties on the given <paramref name="userAccount">account</paramref>.</returns>
        public IEnumerable<string> AvailableProperties(string userAccount)
        {
            Contract.Requires(!string.IsNullOrEmpty(userAccount));
            Contract.Requires(userAccount.Length > 2);
            Contract.Requires(userAccount.ToCharArray().Count(c => c == '\\') == 1);
            Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);

            using (DirectoryEntry directoryEntry = GetDirectoryEntry())
            {
                string account = GetAccountNameFromUserAccount(userAccount);

                using (DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry))
                {
                    directorySearcher.Filter = string.Format("(SAMAccountName={0})", account);
                    SearchResult result = directorySearcher.FindOne();
                    return result != null && result.Properties != null && result.Properties.PropertyNames != null
                               ? result.Properties.PropertyNames.OfType<string>()
                               : Enumerable.Empty<string>();
                }
            }
        }

        ///
        ///     Gets the value for a specified property name of a SAM account.
        ///
        /// <param name="userAccount">A user account with the following format: DOMAIN\UserName.</param>
        /// <param name="propertyName">
        ///     A valid property name. The list of valid properties
        ///     can be found using <see cref="AvailableProperties" />.
        /// </param>
        /// <returns>
        ///     The value for the given <paramref name="propertyName" /> belonging to the given
        ///     <paramref name="userAccount" />.
        /// </returns>
        public ResultPropertyValueCollection GetProperty(string userAccount, string propertyName)
        {
            Contract.Requires(!string.IsNullOrEmpty(userAccount));
            Contract.Requires(userAccount.Length > 2);
            Contract.Requires(userAccount.ToCharArray().Count(c => c == '\\') == 1);
            Contract.Requires(!string.IsNullOrEmpty(propertyName));

            using (DirectoryEntry directoryEntry = GetDirectoryEntry())
            {
                using (DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry))
                {
                    string accountName = GetAccountNameFromUserAccount(userAccount);
                    directorySearcher.Filter = string.Format("(SAMAccountName={0})", accountName);
                    directorySearcher.PropertiesToLoad.Add(propertyName);
                    SearchResult result = directorySearcher.FindOne();
                    return result != null
                               ? result.Properties[propertyName]
                               : null;
                }
            }
        }

        ///
        ///     Checks whether a given user exists.
        ///
        /// <param name="userAccount">A user account with the following format: DOMAIN\UserName.</param>
        /// <returns>A boolean indication whether the given <paramref name="userAccount" /> exists.</returns>
        public bool UserExists(string userAccount)
        {
            Contract.Requires(!string.IsNullOrEmpty(userAccount));
            Contract.Requires(userAccount.Length > 2);
            Contract.Requires(userAccount.ToCharArray().Count(c => c == '\\') == 1);

            using (DirectoryEntry directoryEntry = GetDirectoryEntry())
            {
                using (DirectorySearcher directorySearcher = new DirectorySearcher())
                {
                    directorySearcher.SearchRoot = directoryEntry;
                    string accountName = GetAccountNameFromUserAccount(userAccount);
                    directorySearcher.Filter = string.Format("(&(objectClass=user)(SAMAccountName={0}))", accountName);
                    SearchResultCollection results = directorySearcher.FindAll();
                    return results.Count > 0;
                }
            }
        }

        ///
        ///     Gets the display name property of a SAM-account.
        ///
        /// <param name="userAccount">A user account with the following format: DOMAIN\UserName.</param>
        /// <returns>The display name for the given <paramref name="userAccount" />.</returns>
        public string FindName(string userAccount)
        {
            Contract.Requires(!string.IsNullOrEmpty(userAccount));
            Contract.Requires(userAccount.Length > 2);
            Contract.Requires(userAccount.ToCharArray().Count(c => c == '\\') == 1);
            Contract.Ensures(Contract.Result<string>() != null);

            ResultPropertyValueCollection result = GetProperty(userAccount, @"displayName");
            return result != null && result.Count > 0
                       ? result[0].ToString()
                       : string.Empty;
        }

        ///
        ///     Gets the email address of a SAM-account.
        ///
        /// <param name="userAccount">A user account with the following format: DOMAIN\UserName.</param>
        /// <returns>The email address for the given <paramref name="userAccount" />.</returns>
        public string FindEmail(string userAccount)
        {
            Contract.Requires(!string.IsNullOrEmpty(userAccount));
            Contract.Requires(userAccount.Length > 2);
            Contract.Requires(userAccount.ToCharArray().Count(c => c == '\\') == 1);
            Contract.Ensures(Contract.Result<string>() != null);

            ResultPropertyValueCollection result = GetProperty(userAccount, @"mail");
            return result != null && result.Count > 0
                       ? result[0].ToString()
                       : string.Empty;
        }
    }
}


text:
#ifndef TLINEARBINNING_H
#define TLINEARBINNING_H

class TArrayD;

#include <exception>
#include <Rtypes.h>
#include <TBinning.h>

/**
 * @class TLinearBinning
 * @brief Class creating a linear binning, used in the histogram manager
 * @author Markus Fasel
 * @ingroup Histmanager
 * @since May 31st, 2016
 *
 * This class creates a linear binning. For this the user must provide
 * - A minimum
 * - A maximum
 * - The number of bins
 *
 * The information can be set either in the constructor
 *
 * ~~~{.cxx}
 * TLinearBinning mybinning(100, -10., 10.);
 * ~~~
 *
 * or using the set function
 *
 * ~~~{.cxx}
 * TLinearBinning mybinning;
 * mybinning.Set(100, -10, 10);
 * ~~~
 *
 * The binning can be converted to a TArrayD which contains the bin edges in increasing order:
 *
 * ~~~{.cxx}
 * TArrayD binlimits;
 * mybinning.CreateBinEdges(binlimits);
 * ~~~
 *
 * @note In case the binning is used together with the THistManager the last step is done by the
 * THistManager and does not need to be performed by the user.
 */
class TLinearBinning : public TBinning{
public:

  /**
   * @class LimitsNotSetException
   * @brief Exception indicating that the limits are not set
   * @author Markus Fasel <markus.fasel@cern.ch>, Lawrence Berkeley National Laboratory
   * @ingroup Histmanager
   * @since May 31st, 2016
   *
   * Dummy exception thrown in case the limits are not set. Only creating error message
   */
  class LimitsNotSetException : public std::exception{
  public:

    /**
     * Constructor
     */
    LimitsNotSetException() {}

    /**
     * Destructor
     */
    virtual ~LimitsNotSetException() throw() {}

    /**
     * Creating error message that the limits for the binning are not set
     * @return Error message specifying that the limits for the binning are not set
     */
    virtual const char *what() const throw() { return "Limits needed for the linear binning are not set."; }
  };

  /**
   * Constructor
   */
  TLinearBinning();

  /**
   * Constructor, defining the limits and the number of bins
   * @param[in] nbins Number of bins
   * @param[in] min Minimum bin edge of the binning
   * @param[in] max Maximum bin edge of the binning
   */
  TLinearBinning(Int_t nbins, Double_t min, Double_t max);

  /**
   * Destructor
   */
  virtual ~TLinearBinning() {}

  /**
   * Implementation of the copy function for the linear binning class
   * @return Copy of this binning with the exact same bin edges
   */
  virtual TBinning *MakeCopy() const;

  /**
   * Set the binning with minimum, maximum and number of bins
   * @param[in] nbins Number of bins
   * @param[in] min Minimum of the binning
   * @param[in] max Maximum of the binning
   */
  inline void Set(Int_t nbins, Double_t min, Double_t max);

  /**
   * Converting the linear binning in a set of bin edges
   * @param binedges
   */
  virtual void CreateBinEdges(TArrayD &binedges) const;

private:
  Int_t                                 fNbins;     ///< Number of bins
  Double_t                              fMinimum;   ///< Minimum of the binning
  Double_t                              fMaximum;   ///< Maximum of the binning
  Bool_t                                fLimitsSet; ///< Switch indicating that the binning is initialized
};

void TLinearBinning::Set(Int_t nbins, Double_t min, Double_t max){
  fMinimum = min;
  fMaximum = max;
  fNbins = nbins;
  fLimitsSet = true;
}

#endif /* TLINEARBINNING_H */


text:
/**
 * PortfolioController
 *
 * @Controller(name="investment.PortfolioController")
 */

module.exports = PortfolioController;

function PortfolioController() {

}


text:
package phaser

import (
	"github.com/gopherjs/gopherjs/js"

)

// Particles Phaser.Particles is the Particle Manager for the game. It is called during the game update loop and in turn updates any Emitters attached to it.
type Particles struct {
    *js.Object
}

// NewParticles Phaser.Particles is the Particle Manager for the game. It is called during the game update loop and in turn updates any Emitters attached to it.
func NewParticles(game *Game) *Particles {
    return &Particles{js.Global.Get("Phaser").Get("Particles").New(game)}
}
// NewParticlesI Phaser.Particles is the Particle Manager for the game. It is called during the game update loop and in turn updates any Emitters attached to it.
func NewParticlesI(args ...interface{}) *Particles {
    return &Particles{js.Global.Get("Phaser").Get("Particles").New(args)}
}

// Particles Binding conversion method to Particles point
func ToParticles(jsStruct interface{}) *Particles {
    if object, ok := jsStruct.(*js.Object); ok {
		return &Particles{Object: object}
	}
	return nil
}

// Game A reference to the currently running Game.
func (self *Particles) Game() *Game{
    return &Game{self.Object.Get("game")}
}

// SetGameA A reference to the currently running Game.
func (self *Particles) SetGameA(member *Game) {
    self.Object.Set("game", member)
}

// Emitters Internal emitters store.
func (self *Particles) Emitters() interface{}{
    return self.Object.Get("emitters")
}

// SetEmittersA Internal emitters store.
func (self *Particles) SetEmittersA(member interface{}) {
    self.Object.Set("emitters", member)
}

// ID -
func (self *Particles) ID() int{
    return self.Object.Get("ID").Int()
}

// SetIDA -
func (self *Particles) SetIDA(member int) {
    self.Object.Set("ID", member)
}

// Add Adds a new Particle Emitter to the Particle Manager.
func (self *Particles) Add(emitter *Emitter) *Emitter{
    return &Emitter{self.Object.Call("add", emitter)}
}

// AddI Adds a new Particle Emitter to the Particle Manager.
func (self *Particles) AddI(args ...interface{}) *Emitter{
    return &Emitter{self.Object.Call("add", args)}
}

// Remove Removes an existing Particle Emitter from the Particle Manager.
func (self *Particles) Remove(emitter *Emitter) {
    self.Object.Call("remove", emitter)
}

// RemoveI Removes an existing Particle Emitter from the Particle Manager.
func (self *Particles) RemoveI(args ...interface{}) {
    self.Object.Call("remove", args)
}

// Update Called by the core game loop. Updates all Emitters who have their exists value set to true.
func (self *Particles) Update() {
    self.Object.Call("update")
}

// UpdateI Called by the core game loop. Updates all Emitters who have their exists value set to true.
func (self *Particles) UpdateI(args ...interface{}) {
    self.Object.Call("update", args)
}


text:
require 'spec_helper'
module Alf
  module Types
    describe Tuple, "rename" do

      let(:tuple){ Tuple(:id => 1, :name => "Alf") }

      subject{ tuple.rename(:name => :first_name) }

      it { should eq(Tuple(:id => 1, :first_name => "Alf")) }

    end
  end
end


text:
'use strict'

/* ------------------------------------------------------------- */

module.exports = (function () {
  var instance = new Map();

  (function () {
    var models = require('./models');
    models.properties(function (rows) {
      rows.forEach(function (property) {
        instance[property.NAME] = property.VALUE;
      });
    });
  })();

  return {
    getInstance: function () {
      return instance;
    }
  }
})();

/* ------------------------------------------------------------- */


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

<title>L-Index</title>
<meta name="date" content="2016-08-20">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I J L M N O P R S T U V W X Y Z

L

LABEL_HEIGHT - Static variable in interface edu.ucsd.sbrg.escher.utilities.EscherOptions

With this option you can specify the height of the bounding box of text
 labels.

LABEL_WIDTH - Static variable in interface edu.ucsd.sbrg.escher.utilities.EscherOptions

This option defines the width of bounding boxes for text labels.

LAYOUT_ID - Static variable in interface edu.ucsd.sbrg.escher.utilities.EscherOptions

In contrast to the name, this identifier does not have to be
 human-readable.

LAYOUT_NAME - Static variable in interface edu.ucsd.sbrg.escher.utilities.EscherOptions

This should be a human-readable name for the layout that is to be
 created.

layouts - Variable in class edu.ucsd.sbrg.escher.converters.SBML2Escher

List of layouts exported from the SBML document.

A B C D E F G H I J L M N O P R S T U V W X Y Z

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
<?xml version="1.0" encoding="utf-8"?>
<!--Generated by crowdin.com-->
<!--
     Copyright (C) 2012-2015 The CyanogenMod Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
  <string name="show_status_bar_icon_title">Exibir ícone</string>
  <string name="show_status_bar_icon_summary">Exibir um ícone na barra de status quando um alarme for definido</string>
  <string name="alarm_increasing_volume">Volume crescente</string>
  <string name="profile_description">Perfil <xliff:g xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2" id="profile">%s</xliff:g></string>
  <string name="profile_no_selected">Nenhum perfil selecionado</string>
  <string name="menu_item_add">Adicionar</string>
  <string name="cities_add_city_title">Adicionar cidade</string>
  <string name="cities_add_city_city">Cidade:</string>
  <string name="cities_add_city_timezone">Fuso horário:</string>
  <string name="cities_add_city_gps_cd">Toque para localizar sua cidade atual</string>
  <string name="cities_add_loading">Carregando\2026</string>
  <string name="cities_add_searching">Buscando\2026</string>
  <string name="cities_add_gps_no_results">A busca com GPS não retornou nenhum local</string>
  <string name="cities_add_gps_not_available">GPS não está disponível</string>
  <string name="cities_add_already_exists">A cidade já existe no banco de dados</string>
  <string name="cities_add_city_failed">Não foi possível criar a cidade</string>
  <string name="cities_delete_city_title">Excluir cidade</string>
  <string name="cities_delete_city_msg">Você deseja excluir <xliff:g xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2" id="city">%s</xliff:g>?</string>
  <string name="cities_delete_city_failed">Não foi possível excluir a cidade</string>
  <string name="volume_buttons_summary">Pressionar os botões do volume vai <xliff:g id="action">%s</xliff:g></string>
  <string name="flip_action_title">Ação de virar</string>
  <string name="flip_action_summary" product="tablet">Virar o tablet irá <xliff:g id="action">%s</xliff:g></string>
  <string name="flip_action_summary" product="default">Virar o telefone irá <xliff:g id="action">%s</xliff:g></string>
  <string name="shake_action_title">Ação de agitar</string>
  <string name="shake_action_summary" product="tablet">Agitar o tablet irá <xliff:g id="action">%s</xliff:g></string>
  <string name="shake_action_summary" product="default">Agitar o telefone irá <xliff:g id="action">%s</xliff:g></string>
  <string name="action_summary_snooze">ignora o alarme</string>
  <string name="action_summary_dismiss">suspender o alarme</string>
  <string name="action_summary_do_nothing">Fazer nada</string>
  <string name="alarm_picker_title">Escolher tipo de alarme</string>
  <string name="alarm_type_ringtone">Toque</string>
  <string name="alarm_type_playlist">Lista de reprodução</string>
  <string name="alarm_type_random">Aleatório</string>
  <string name="warn_silent_alarm_title">Volume do alarme está silenciado</string>
  <string name="alarm_select">Selecione o alarme</string>
  <string name="alarm_select_ringtone">Toque de telefone</string>
  <string name="alarm_select_external">Música</string>
  <string name="ringtone_default">Toque padrão</string>
  <string name="take_persistent_grant_uri_permission_failed_msg">Falha ao conceder permissão persistente para o toque</string>
  <string name="menu_item_widget_settings">Configurações do widget</string>
  <string name="activity_not_found">Atividade não encontrada!</string>
</resources>