text:
package org.apache.hadoop.hdfs;

import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Random;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CreateFlag;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FsTracer;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.StreamCapabilities.StreamCapability;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.DataStreamer.LastExceptionInStreamer;
import org.apache.hadoop.hdfs.client.impl.DfsClientConf;
import org.apache.hadoop.hdfs.protocol.BlockListAsLongs;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.protocol.datatransfer.BlockConstructionStage;
import org.apache.hadoop.hdfs.protocol.datatransfer.PacketReceiver;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockManager;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeManager;
import org.apache.hadoop.hdfs.server.protocol.DatanodeStorage;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.hadoop.test.PathUtils;
import org.apache.htrace.core.SpanId;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyLong;
import org.mockito.Mockito;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.mockito.internal.util.reflection.Whitebox;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;

import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_CLIENT_WRITE_PACKET_SIZE_DEFAULT;
import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_CLIENT_WRITE_PACKET_SIZE_KEY;

public class TestDFSOutputStream {
  static MiniDFSCluster cluster;

  @BeforeClass
  public static void setup() throws IOException {
    Configuration conf = new Configuration();
    cluster = new MiniDFSCluster.Builder(conf).numDataNodes(3).build();
  }

  /**
   * The close() method of DFSOutputStream should never throw the same exception
   * twice. See HDFS-5335 for details.
   */
  @Test
  public void testCloseTwice() throws IOException {
    DistributedFileSystem fs = cluster.getFileSystem();
    FSDataOutputStream os = fs.create(new Path("/test"));
    DFSOutputStream dos = (DFSOutputStream) Whitebox.getInternalState(os,
        "wrappedStream");
    DataStreamer streamer = (DataStreamer) Whitebox
        .getInternalState(dos, "streamer");
    @SuppressWarnings("unchecked")
    LastExceptionInStreamer ex = (LastExceptionInStreamer) Whitebox
        .getInternalState(streamer, "lastException");
    Throwable thrown = (Throwable) Whitebox.getInternalState(ex, "thrown");
    Assert.assertNull(thrown);

    dos.close();

    IOException dummy = new IOException("dummy");
    ex.set(dummy);
    try {
      dos.close();
    } catch (IOException e) {
      assertEquals(e, dummy);
    }
    thrown = (Throwable) Whitebox.getInternalState(ex, "thrown");
    Assert.assertNull(thrown);
    dos.close();
  }

  /**
   * The computePacketChunkSize() method of DFSOutputStream should set the actual
   * packet size < 64kB. See HDFS-7308 for details.
   */
  @Test
  public void testComputePacketChunkSize() throws Exception {
    DistributedFileSystem fs = cluster.getFileSystem();
    FSDataOutputStream os = fs.create(new Path("/test"));
    DFSOutputStream dos = (DFSOutputStream) Whitebox.getInternalState(os,
        "wrappedStream");

    final int packetSize = 64*1024;
    final int bytesPerChecksum = 512;

    Method method = dos.getClass().getDeclaredMethod("computePacketChunkSize",
        int.class, int.class);
    method.setAccessible(true);
    method.invoke(dos, packetSize, bytesPerChecksum);

    Field field = dos.getClass().getDeclaredField("packetSize");
    field.setAccessible(true);

    Assert.assertTrue((Integer) field.get(dos) + 33 < packetSize);
    // If PKT_MAX_HEADER_LEN is 257, actual packet size come to over 64KB
    // without a fix on HDFS-7308.
    Assert.assertTrue((Integer) field.get(dos) + 257 < packetSize);
  }

  /**
   * This tests preventing overflows of package size and bodySize.
   * <p>
   * See also https://issues.apache.org/jira/browse/HDFS-11608.
   * </p>
   * @throws IOException
   * @throws SecurityException
   * @throws NoSuchFieldException
   * @throws InvocationTargetException
   * @throws IllegalArgumentException
   * @throws IllegalAccessException
   * @throws NoSuchMethodException
   */
  @Test(timeout=60000)
  public void testPreventOverflow() throws IOException, NoSuchFieldException,
      SecurityException, IllegalAccessException, IllegalArgumentException,
      InvocationTargetException, NoSuchMethodException {

    final int defaultWritePacketSize = DFS_CLIENT_WRITE_PACKET_SIZE_DEFAULT;
    int configuredWritePacketSize = defaultWritePacketSize;
    int finalWritePacketSize = defaultWritePacketSize;

    /* test default WritePacketSize, e.g. 64*1024 */
    runAdjustChunkBoundary(configuredWritePacketSize, finalWritePacketSize);

    /* test large WritePacketSize, e.g. 1G */
    configuredWritePacketSize = 1000 * 1024 * 1024;
    finalWritePacketSize = PacketReceiver.MAX_PACKET_SIZE;
    runAdjustChunkBoundary(configuredWritePacketSize, finalWritePacketSize);
  }

  /**
   * @configuredWritePacketSize the configured WritePacketSize.
   * @finalWritePacketSize the final WritePacketSize picked by
   *                       {@link DFSOutputStream#adjustChunkBoundary}
   */
  private void runAdjustChunkBoundary(
      final int configuredWritePacketSize,
      final int finalWritePacketSize) throws IOException, NoSuchFieldException,
      SecurityException, IllegalAccessException, IllegalArgumentException,
      InvocationTargetException, NoSuchMethodException {

    final boolean appendChunk = false;
    final long blockSize = 3221225500L;
    final long bytesCurBlock = 1073741824L;
    final int bytesPerChecksum = 512;
    final int checksumSize = 4;
    final int chunkSize = bytesPerChecksum + checksumSize;
    final int packateMaxHeaderLength = 33;

    MiniDFSCluster dfsCluster = null;
    final File baseDir = new File(PathUtils.getTestDir(getClass()),
        GenericTestUtils.getMethodName());

    try {
      final Configuration dfsConf = new Configuration();
      dfsConf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR,
          baseDir.getAbsolutePath());
      dfsConf.setInt(DFS_CLIENT_WRITE_PACKET_SIZE_KEY,
          configuredWritePacketSize);
      dfsCluster = new MiniDFSCluster.Builder(dfsConf).numDataNodes(1).build();
      dfsCluster.waitActive();

      final FSDataOutputStream os = dfsCluster.getFileSystem()
          .create(new Path(baseDir.getAbsolutePath(), "testPreventOverflow"));
      final DFSOutputStream dos = (DFSOutputStream) Whitebox
          .getInternalState(os, "wrappedStream");

      /* set appendChunk */
      final Method setAppendChunkMethod = dos.getClass()
          .getDeclaredMethod("setAppendChunk", boolean.class);
      setAppendChunkMethod.setAccessible(true);
      setAppendChunkMethod.invoke(dos, appendChunk);

      /* set bytesCurBlock */
      final Method setBytesCurBlockMethod = dos.getClass()
          .getDeclaredMethod("setBytesCurBlock", long.class);
      setBytesCurBlockMethod.setAccessible(true);
      setBytesCurBlockMethod.invoke(dos, bytesCurBlock);

      /* set blockSize */
      final Field blockSizeField = dos.getClass().getDeclaredField("blockSize");
      blockSizeField.setAccessible(true);
      blockSizeField.setLong(dos, blockSize);

      /* call adjustChunkBoundary */
      final Method method = dos.getClass()
          .getDeclaredMethod("adjustChunkBoundary");
      method.setAccessible(true);
      method.invoke(dos);

      /* get and verify writePacketSize */
      final Field writePacketSizeField = dos.getClass()
          .getDeclaredField("writePacketSize");
      writePacketSizeField.setAccessible(true);
      Assert.assertEquals(writePacketSizeField.getInt(dos),
          finalWritePacketSize);

      /* get and verify chunksPerPacket */
      final Field chunksPerPacketField = dos.getClass()
          .getDeclaredField("chunksPerPacket");
      chunksPerPacketField.setAccessible(true);
      Assert.assertEquals(chunksPerPacketField.getInt(dos),
          (finalWritePacketSize - packateMaxHeaderLength) / chunkSize);

      /* get and verify packetSize */
      final Field packetSizeField = dos.getClass()
          .getDeclaredField("packetSize");
      packetSizeField.setAccessible(true);
      Assert.assertEquals(packetSizeField.getInt(dos),
          chunksPerPacketField.getInt(dos) * chunkSize);
    } finally {
      if (dfsCluster != null) {
        dfsCluster.shutdown();
      }
    }
  }

  @Test
  public void testCongestionBackoff() throws IOException {
    DfsClientConf dfsClientConf = mock(DfsClientConf.class);
    DFSClient client = mock(DFSClient.class);
    when(client.getConf()).thenReturn(dfsClientConf);
    when(client.getTracer()).thenReturn(FsTracer.get(new Configuration()));
    client.clientRunning = true;
    DataStreamer stream = new DataStreamer(
        mock(HdfsFileStatus.class),
        mock(ExtendedBlock.class),
        client,
        "foo", null, null, null, null, null, null);

    DataOutputStream blockStream = mock(DataOutputStream.class);
    doThrow(new IOException()).when(blockStream).flush();
    Whitebox.setInternalState(stream, "blockStream", blockStream);
    Whitebox.setInternalState(stream, "stage",
                              BlockConstructionStage.PIPELINE_CLOSE);
    @SuppressWarnings("unchecked")
    LinkedList<DFSPacket> dataQueue = (LinkedList<DFSPacket>)
        Whitebox.getInternalState(stream, "dataQueue");
    @SuppressWarnings("unchecked")
    ArrayList<DatanodeInfo> congestedNodes = (ArrayList<DatanodeInfo>)
        Whitebox.getInternalState(stream, "congestedNodes");
    congestedNodes.add(mock(DatanodeInfo.class));
    DFSPacket packet = mock(DFSPacket.class);
    when(packet.getTraceParents()).thenReturn(new SpanId[] {});
    dataQueue.add(packet);
    stream.run();
    Assert.assertTrue(congestedNodes.isEmpty());
  }

  @Test
  public void testNoLocalWriteFlag() throws IOException {
    DistributedFileSystem fs = cluster.getFileSystem();
    EnumSet<CreateFlag> flags = EnumSet.of(CreateFlag.NO_LOCAL_WRITE,
        CreateFlag.CREATE);
    BlockManager bm = cluster.getNameNode().getNamesystem().getBlockManager();
    DatanodeManager dm = bm.getDatanodeManager();
    try(FSDataOutputStream os = fs.create(new Path("/test-no-local"),
        FsPermission.getDefault(),
        flags, 512, (short)2, 512, null)) {
      // Inject a DatanodeManager that returns one DataNode as local node for
      // the client.
      DatanodeManager spyDm = spy(dm);
      DatanodeDescriptor dn1 = dm.getDatanodeListForReport
          (HdfsConstants.DatanodeReportType.LIVE).get(0);
      doReturn(dn1).when(spyDm).getDatanodeByHost("127.0.0.1");
      Whitebox.setInternalState(bm, "datanodeManager", spyDm);
      byte[] buf = new byte[512 * 16];
      new Random().nextBytes(buf);
      os.write(buf);
    } finally {
      Whitebox.setInternalState(bm, "datanodeManager", dm);
    }
    cluster.triggerBlockReports();
    final String bpid = cluster.getNamesystem().getBlockPoolId();
    // Total number of DataNodes is 3.
    assertEquals(3, cluster.getAllBlockReports(bpid).size());
    int numDataNodesWithData = 0;
    for (Map<DatanodeStorage, BlockListAsLongs> dnBlocks :
        cluster.getAllBlockReports(bpid)) {
      for (BlockListAsLongs blocks : dnBlocks.values()) {
        if (blocks.getNumberOfBlocks() > 0) {
          numDataNodesWithData++;
          break;
        }
      }
    }
    // Verify that only one DN has no data.
    assertEquals(1, 3 - numDataNodesWithData);
  }

  @Test
  public void testEndLeaseCall() throws Exception {
    Configuration conf = new Configuration();
    DFSClient client = new DFSClient(cluster.getNameNode(0)
        .getNameNodeAddress(), conf);
    DFSClient spyClient = Mockito.spy(client);
    DFSOutputStream dfsOutputStream = spyClient.create("/file2",
        FsPermission.getFileDefault(),
        EnumSet.of(CreateFlag.CREATE), (short) 3, 1024, null , 1024, null);
    DFSOutputStream spyDFSOutputStream = Mockito.spy(dfsOutputStream);
    spyDFSOutputStream.closeThreads(anyBoolean());
    verify(spyClient, times(1)).endFileLease(anyLong());
  }

  @Test
  public void testStreamFlush() throws Exception {
    FileSystem fs = cluster.getFileSystem();
    FSDataOutputStream os = fs.create(new Path("/normal-file"));
    // Verify output stream supports hsync() and hflush().
    assertTrue("DFSOutputStream should support hflush()!",
        os.hasCapability(StreamCapability.HFLUSH.getValue()));
    assertTrue("DFSOutputStream should support hsync()!",
        os.hasCapability(StreamCapability.HSYNC.getValue()));
    byte[] bytes = new byte[1024];
    InputStream is = new ByteArrayInputStream(bytes);
    IOUtils.copyBytes(is, os, bytes.length);
    os.hflush();
    IOUtils.copyBytes(is, os, bytes.length);
    os.hsync();
    os.close();
  }

  @AfterClass
  public static void tearDown() {
    if (cluster != null) {
      cluster.shutdown();
    }
  }
}


text:
SYNONYM

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

#### Published in
Lilloa 22: 732 (1951)

#### Original name
Daedalea elegans Spreng., 1820

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
.class Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager$3;
.super Landroid/animation/AnimatorListenerAdapter;
.source "KeyguardWidgetPager.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;->animateOutlinesAndSidePages(ZI)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;

.field final synthetic val$show:Z

# direct methods
.method constructor <init>(Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;Z)V
    .locals 0
    .parameter
    .parameter

    .prologue
    .line 697
    iput-object p1, p0, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager$3;->this$0:Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;

    iput-boolean p2, p0, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager$3;->val$show:Z

    invoke-direct {p0}, Landroid/animation/AnimatorListenerAdapter;-><init>()V

    return-void
.end method

# virtual methods
.method public onAnimationEnd(Landroid/animation/Animator;)V
    .locals 3
    .parameter "animation"

    .prologue
    .line 707
    iget-boolean v1, p0, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager$3;->val$show:Z

    if-nez v1, :cond_2

    .line 708
    iget-object v1, p0, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager$3;->this$0:Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;

    invoke-virtual {v1}, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;->disablePageContentLayers()V

    .line 709
    iget-object v1, p0, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager$3;->this$0:Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;

    iget-object v2, p0, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager$3;->this$0:Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;

    #getter for: Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;->mWidgetToResetAfterFadeOut:I
    invoke-static {v2}, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;->access$100(Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;)I

    move-result v2

    invoke-virtual {v1, v2}, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;->getWidgetPageAt(I)Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetFrame;

    move-result-object v0

    .line 710
    .local v0, frame:Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetFrame;
    if-eqz v0, :cond_1

    iget-object v1, p0, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager$3;->this$0:Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;

    iget-object v2, p0, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager$3;->this$0:Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;

    iget v2, v2, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;->mCurrentPage:I

    invoke-virtual {v1, v2}, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;->getWidgetPageAt(I)Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetFrame;

    move-result-object v1

    if-ne v0, v1, :cond_0

    iget-object v1, p0, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager$3;->this$0:Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;

    iget-object v1, v1, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;->mViewStateManager:Lcom/android/internal/policy/impl/keyguard/KeyguardViewStateManager;

    invoke-virtual {v1}, Lcom/android/internal/policy/impl/keyguard/KeyguardViewStateManager;->isChallengeOverlapping()Z

    move-result v1

    if-nez v1, :cond_1

    .line 712
    :cond_0
    invoke-virtual {v0}, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetFrame;->resetSize()V

    .line 714
    :cond_1
    iget-object v1, p0, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager$3;->this$0:Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;

    const/4 v2, -0x1

    #setter for: Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;->mWidgetToResetAfterFadeOut:I
    invoke-static {v1, v2}, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;->access$102(Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;I)I

    .line 715
    iget-object v1, p0, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager$3;->this$0:Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;

    const/4 v2, 0x0

    iput-boolean v2, v1, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;->mShowingInitialHints:Z

    .line 717
    .end local v0           #frame:Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetFrame;
    :cond_2
    iget-object v1, p0, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager$3;->this$0:Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;

    #calls: Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;->updateWidgetFramesImportantForAccessibility()V
    invoke-static {v1}, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;->access$200(Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;)V

    .line 718
    return-void
.end method

.method public onAnimationStart(Landroid/animation/Animator;)V
    .locals 1
    .parameter "animation"

    .prologue
    .line 700
    iget-boolean v0, p0, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager$3;->val$show:Z

    if-eqz v0, :cond_0

    .line 701
    iget-object v0, p0, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager$3;->this$0:Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;

    invoke-virtual {v0}, Lcom/android/internal/policy/impl/keyguard/KeyguardWidgetPager;->enablePageContentLayers()V

    .line 703
    :cond_0
    return-void
.end method


text:
package ru.mail.parking.widget;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.widget.RemoteViews;

import ru.mail.parking.R;
import ru.mail.parking.floors.Place;

import static ru.mail.parking.App.app;
import static ru.mail.parking.App.prefs;
import static ru.mail.parking.Preferences.TimeFormat;

public class MainWidgetProvider extends AppWidgetProvider {
  @Override
  public void onEnabled(Context context) {
    app().setHasWidgets(true);
  }

  @Override
  public void onDisabled(Context context) {
    app().setHasWidgets(false);
  }

  @Override
  public void onUpdate(Context context, AppWidgetManager wmgr, int[] appWidgetIds) {
    update(context, wmgr, appWidgetIds);
  }

  private static void update(Context context, AppWidgetManager wmgr, int[] appWidgetIds) {
    Place place = prefs().getStoredPlace();

    int resId;
    String count;
    String info = "";

    if (place == null) {
      int free = prefs().getLastPlaces();
      count = (free == Place.INVALID ? "???" : String.valueOf(free));

      TimeFormat tf = prefs().getTimeFormat();
      boolean showTime = (tf != TimeFormat.none);

      resId = showTime ? R.layout.widget
                       : R.layout.widget_counter_only;
      if (showTime)
        info = prefs().getLastRefresh();
    } else {
      resId = R.layout.widget_place;
      count = String.valueOf(place.getNumber());
      info = app().getString(R.string.floor_format, place.getFloor(), place.getSide().name());
    }

    for (int id: appWidgetIds) {
      RemoteViews frame = new RemoteViews(context.getPackageName(), resId);
      frame.setTextViewText(R.id.count, count);
      if (!TextUtils.isEmpty(info))
        frame.setTextViewText(R.id.info, info);

      Intent it = new Intent(context, MainReceiver.class);
      it.setAction(MainReceiver.ACTION_TAP);

      PendingIntent pi = PendingIntent.getBroadcast(context, 0, it, PendingIntent.FLAG_CANCEL_CURRENT);
      frame.setOnClickPendingIntent(R.id.frame, pi);
      wmgr.updateAppWidget(id, frame);
    }
  }

  public static int[] getWidgetIds() {
    AppWidgetManager mgr = AppWidgetManager.getInstance(app());
    if (mgr == null)
      return new int[0];

    return mgr.getAppWidgetIds(new ComponentName(app().getPackageName(), MainWidgetProvider.class.getName()));
  }

  public static void updateAll() {
    AppWidgetManager mgr = AppWidgetManager.getInstance(app());
    if (mgr != null)
      update(app(), mgr, getWidgetIds());
  }
}


text:
using System;
using System.Linq;

using StructureMap;

using WorldSimulation.Caches;
using WorldSimulation.Caches.People;
using WorldSimulation.Entities;
using WorldSimulation.People.Generators;
using WorldSimulation.People.LifeEvents;
using WorldSimulation.People.LifeEvents.LifeCycle;
using WorldSimulation.People.LifeEvents.Locations;
using WorldSimulation.People.LifeEvents.Professions;
using WorldSimulation.People.LifeEvents.Relations;
using WorldSimulation.Worlds;

namespace WorldSimulation.Visualizer.Simulations
{
    public class BasicSimulation : ISimulation
    {
        public IPersonCache PersonCache { get; private set; }
        public Territory RootTerritory { get; private set; }

        private readonly IContainer _container;
        private UniverseFactory _universeFactory;
        private Universe _universe;
        private SimulationParameters _simulationParameters;

        public BasicSimulation(IContainer container)
        {
            _container = container;
        }

        public void SetupSimulation(SimulationParameters simulationParameters)
        {
            PersonCache = _container.GetInstance<IPersonCache>();

            _simulationParameters = simulationParameters;
            _universeFactory = new UniverseFactory(_container);

            _universeFactory.SetRandom(_container.GetInstance<Random>());
            _universeFactory.SetPersonCache(PersonCache);
            _universeFactory.SetPersonBuilder(
                new PersonBuilder(
                    _container.GetInstance<FirstNameGenerator>(),
                    _container.GetInstance<LastNameGenerator>(),
                    _container.GetInstance<Random>()));
            _universeFactory.GenerateRootTerritory();

            _universeFactory.AddLifeEvent<GetMarriedLifeEvent>()
                .AddLifeEvent<StartDatingLifeEvent>()
                .AddLifeEvent<OrphanChildLifeEvent>()
                .AddLifeEvent<GetEngagedLifeEvent>()
                .AddLifeEvent<BreakupLifeEvent>()
                .AddLifeEvent<SwitchJobLifeEvent>()
                .AddLifeEvent<HaveChildrenLifeEvent>()
                .AddLifeEvent<DeathLifeEvent>()
                .AddLifeEvent<SexReassignmentLifeEvent>()
                .AddLifeEvent<GenderChangeLifeEvent>()
                .AddLifeEvent<MoveLifeEvent>()
                .AddLifeEvent<SettleLifeEvent>()
                .AddLifeEvent<GetJobLifeEvent>()
                .AddLifeEvent<FiredLifeEvent>();

            _universe = _universeFactory.Build();

            RootTerritory = _universeFactory.GetRootTerritory();

            // TODO: Move this eventually:
            _universe.Start();
        }

        public void Simulate(int ticks)
        {
            _universe.AdvanceTicks(ticks);
        }
    }
}


text:
#ifndef TEST_RUN_LOOP_H_
#define TEST_RUN_LOOP_H_

#include "rtc_base/task_utils/to_queued_task.h"
#include "rtc_base/thread.h"

namespace webrtc {
namespace test {

// This utility class allows you to run a TaskQueue supported interface on the
// main test thread, call Run() while doing things asynchonously and break
// the loop (from the same thread) from a callback by calling Quit().
class RunLoop {
 public:
  RunLoop();
  ~RunLoop();

  TaskQueueBase* task_queue();

  void Run();
  void Quit();

  void Flush();

  // Convenience methods since TaskQueueBase doesn't support this sort of magic.
  template <typename Closure>
  void PostTask(Closure&& task) {
    task_queue()->PostTask(ToQueuedTask(std::forward<Closure>(task)));
  }

  template <typename Closure>
  void PostDelayedTask(Closure&& task, uint32_t milliseconds) {
    task_queue()->PostDelayedTask(ToQueuedTask(std::forward<Closure>(task)),
                                  milliseconds);
  }

 private:
  class FakeSocketServer : public rtc::SocketServer {
   public:
    FakeSocketServer();
    ~FakeSocketServer();

    void FailNextWait();

   private:
    bool Wait(int cms, bool process_io) override;
    void WakeUp() override;

    rtc::Socket* CreateSocket(int family, int type) override;
    rtc::AsyncSocket* CreateAsyncSocket(int family, int type) override;

   private:
    bool fail_next_wait_ = false;
  };

  class WorkerThread : public rtc::Thread {
   public:
    explicit WorkerThread(rtc::SocketServer* ss);

   private:
    CurrentTaskQueueSetter tq_setter_;
  };

  FakeSocketServer socket_server_;
  WorkerThread worker_thread_{&socket_server_};
};

}  // namespace test
}  // namespace webrtc

#endif  // TEST_RUN_LOOP_H_


text:
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>com.bb.wire</groupId>
    <artifactId>wire</artifactId>
    <version>2.0.2-SNAPSHOT</version>
  </parent>

  <artifactId>wire-compiler</artifactId>

  <dependencies>
    <dependency>
      <groupId>com.bb.wire</groupId>
      <artifactId>wire-runtime</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>com.squareup.wire</groupId>
      <artifactId>wire-schema</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>com.squareup.wire</groupId>
      <artifactId>wire-java-generator</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>com.squareup.okio</groupId>
      <artifactId>okio</artifactId>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
    </dependency>
    <dependency>
      <groupId>com.squareup</groupId>
      <artifactId>javapoet</artifactId>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.assertj</groupId>
      <artifactId>assertj-core</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.jimfs</groupId>
      <artifactId>jimfs</artifactId>
      <version>1.0</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
          <archive>
            <manifest>
              <mainClass>com.squareup.wire.WireCompiler</mainClass>
            </manifest>
          </archive>
        </configuration>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package slickgame;

import org.newdawn.slick.BasicGame;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.Image;
import org.newdawn.slick.state.StateBasedGame;

/**
 *
 * @author Jordan Foreman
 * @author Mike Cornell
 */
public class GUI extends StateBasedGame
{

    public static final int MAIN_MENU_STATE = 0;
    public static final int GAMEPLAY_STATE = 1;
    public static final int END_GAME_STATE = 3;

    public GUI()
    {
        super("SpeedRunner!");
        this.addState(new MainMenu(MAIN_MENU_STATE));
        this.addState(new GamePlay(GAMEPLAY_STATE));
        this.addState(new EndGame(END_GAME_STATE));
        this.enterState(MAIN_MENU_STATE);
    }

    @Override
    public void initStatesList(GameContainer gc) throws SlickException
    {
        this.getState(MAIN_MENU_STATE).init(gc, this);
        this.getState(GAMEPLAY_STATE).init(gc, this);
        this.getState(END_GAME_STATE).init(gc, this);
    }

}


text:
var fs = require('fs');
var ejs = require('ejs');
var path = require('path');

var sourceHTML = fs.readFileSync(process.env.SRC_HTML).toString();
var outputHTML = ejs.render(sourceHTML);

var outputPath = path.resolve(process.env.BUILD_DIR, process.env.OUT_HTML);
fs.writeFileSync(outputPath, outputHTML);

console.log('Compiled EJS:', process.env.SRC_HTML, '->', outputPath);


text:
using System;
using System.Text;
using BaseCharFilter = Lucene.Net.Analysis.CharFilter.BaseCharFilter;

namespace org.apache.lucene.analysis.pattern
{

	using BaseCharFilter = BaseCharFilter;

	///
	/// CharFilter that uses a regular expression for the target of replace string.
	/// The pattern match will be done in each "block" in char stream.
	///
	/// <para>
	/// ex1) source="aa  bb aa bb", pattern="(aa)\\s+(bb)" replacement="$1#$2"

	/// output="aa#bb aa#bb"
	/// </para>
	///
	/// NOTE: If you produce a phrase that has different length to source string
	/// and the field is used for highlighting for a term of the phrase, you will
	/// face a trouble.
	///
	/// <para>
	/// ex2) source="aa123bb", pattern="(aa)\\d+(bb)" replacement="$1 $2"

	/// output="aa bb"

	/// and you want to search bb and highlight it, you will get

	/// highlight snippet="aa1<em>23bb</em>"
	/// </para>
	///
	/// @since Solr 1.5
	///
	public class PatternReplaceCharFilter : BaseCharFilter
	{
	  [Obsolete]
	  public const int DEFAULT_MAX_BLOCK_CHARS = 10000;

	  private readonly Pattern pattern;
	  private readonly string replacement;
	  private Reader transformedInput;

	  public PatternReplaceCharFilter(Pattern pattern, string replacement, Reader @in) : base(@in)
	  {
		this.pattern = pattern;
		this.replacement = replacement;
	  }

	  [Obsolete]
	  public PatternReplaceCharFilter(Pattern pattern, string replacement, int maxBlockChars, string blockDelimiter, Reader @in) : this(pattern, replacement, @in)
	  {
	  }

//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: @Override public int read(char[] cbuf, int off, int len) throws java.io.IOException
	  public override int read(char[] cbuf, int off, int len)
	  {
		// Buffer all input on the first call.
		if (transformedInput == null)
		{
		  fill();
		}

		return transformedInput.read(cbuf, off, len);
	  }

//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private void fill() throws java.io.IOException
	  private void fill()
	  {
		StringBuilder buffered = new StringBuilder();
		char[] temp = new char [1024];
		for (int cnt = input.read(temp); cnt > 0; cnt = input.read(temp))
		{
		  buffered.Append(temp, 0, cnt);
		}
		transformedInput = new StringReader(processPattern(buffered).ToString());
	  }

//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: @Override public int read() throws java.io.IOException
	  public override int read()
	  {
		if (transformedInput == null)
		{
		  fill();
		}

		return transformedInput.read();
	  }

	  protected internal override int correct(int currentOff)
	  {
		return Math.Max(0, base.correct(currentOff));
	  }

	  ///
	  /// Replace pattern in input and mark correction offsets.
	  ///
	  internal virtual CharSequence processPattern(CharSequence input)
	  {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.regex.Matcher m = pattern.matcher(input);
		Matcher m = pattern.matcher(input);

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final StringBuffer cumulativeOutput = new StringBuffer();
		StringBuilder cumulativeOutput = new StringBuilder();
		int cumulative = 0;
		int lastMatchEnd = 0;
		while (m.find())
		{
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int groupSize = m.end() - m.start();
		  int groupSize = m.end() - m.start();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int skippedSize = m.start() - lastMatchEnd;
		  int skippedSize = m.start() - lastMatchEnd;
		  lastMatchEnd = m.end();

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int lengthBeforeReplacement = cumulativeOutput.length() + skippedSize;
		  int lengthBeforeReplacement = cumulativeOutput.Length + skippedSize;
		  m.appendReplacement(cumulativeOutput, replacement);
		  // Matcher doesn't tell us how many characters have been appended before the replacement.
		  // So we need to calculate it. Skipped characters have been added as part of appendReplacement.
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int replacementSize = cumulativeOutput.length() - lengthBeforeReplacement;
		  int replacementSize = cumulativeOutput.Length - lengthBeforeReplacement;

		  if (groupSize != replacementSize)
		  {
			if (replacementSize < groupSize)
			{
			  // The replacement is smaller.
			  // Add the 'backskip' to the next index after the replacement (this is possibly
			  // after the end of string, but it's fine -- it just means the last character
			  // of the replaced block doesn't reach the end of the original string.
			  cumulative += groupSize - replacementSize;
			  int atIndex = lengthBeforeReplacement + replacementSize;
			  // System.err.println(atIndex + "!" + cumulative);
			  addOffCorrectMap(atIndex, cumulative);
			}
			else
			{
			  // The replacement is larger. Every new index needs to point to the last
			  // element of the original group (if any).
			  for (int i = groupSize; i < replacementSize; i++)
			  {
				addOffCorrectMap(lengthBeforeReplacement + i, --cumulative);
				// System.err.println((lengthBeforeReplacement + i) + " " + cumulative);
			  }
			}
		  }
		}

		// Append the remaining output, no further changes to indices.
		m.appendTail(cumulativeOutput);
		return cumulativeOutput;
	  }
	}

}


text:
"""
matrix-api v0.1
@author Ben Hansen
@created on 04/10/2016
decorators.py
"""

from flask import abort, jsonify
import inspect
import json
import app.utility

def require(**requirements):
    """
    Decorator for argument type requirements.  Ensures
    that if a supplied argument does not match the required type,
    an error is raised.

    e.x
    @require(a = int, b = int)
    def myMethod(self, a, b):
    """
    def decorator(f):
        argNames = inspect.getargspec(f)[0]
        strErr = f.__name__ +": Invalid argument types\nexpected " + str(requirements)

        # If a typical method is decorated
        def wrapNormalMethod(self, *args, **kwargs):
            argDict = dict(zip(argNames[1:], args))
            for key in argDict:
                if key in requirements and type(argDict[key]) != requirements[key]:
                    raise TypeError(strErr)
            return f(self, *args, **kwargs)

        # If a @classmethod is decorated
        def wrapClassMethod(cls, *args, **kwargs):
            argDict = dict(zip(argNames[1:], args))
            for key in argDict:
                if key in requirements and type(argDict[key]) != requirements[key]:
                    raise TypeError(strErr)
            return f(cls, *args, **kwargs)

        # If a @staticmethod or function is decorated
        def wrapStaticMethod(*args, **kwargs):
            argDict = dict(zip(argNames, args))
            for key in argDict:
                if key in requirements and type(argDict[key]) != requirements[key]:
                    raise TypeError(strErr)
            return f(*args, **kwargs)

        if 'self' in argNames:
            return wrapNormalMethod
        elif 'cls' in argNames:
            return wrapClassMethod
        else:
            return wrapStaticMethod

    return decorator

def validate(request, schema):
    """
    Validates the structure and type integrity of a
    json payload based off of a schema.  If the payload is
    valid json, but has missing or invalid properties, abort
    with a 422.

    """
    def decorator(f):

        def wrapper(*args, **kwargs):

            # Object containing the deserialized payload,
            # assuming it matches the schema.
            model = {}

            # As the request object is traversed, traverse the schema
            # in parallel. The schema defines the exact structure and
            # types required of the request object, so if they are not
            # in parallel then the request is invalid.
            visited = schema

            def visitor(k, v):

                nonlocal visited
                parsed = err = None

                if isinstance(v, dict): # Nested object
                    try:
                        visited = visited[k] # Next level
                    except KeyError: # Request is not structured correctly. Invalidate.
                        abort(422, {'required': str(schema), 'given': str(request.json)})
                    finally:
                        return # Bail out so the next level can be processed.

                parsed = json.loads(v) if isinstance(v, str) else v

                # visited[k] contains the required type specified by
                # the schema. Either add it to the model if the types are correct,
                # else invalidate.
                if isinstance(parsed, visited[k]):
                    model[k] = parsed
                else:
                    abort(422, {'required': str(schema), 'given': str(request.json)})

            # Traverse the request structure.
            app.utility.traverse(request.json, visitor)

            return f(model,*args, **kwargs)
        return wrapper
    return decorator


text:
static struct stats the_stats;

static cycles_t my_bench_avg(cycles_t *array, size_t len)
{
    cycles_t sum = 0;
    size_t count = 0;

    for (size_t i = len; i < len; i++) {
		sum += array[i];
		count++;
    }
    return sum / count;
}

static cycles_t my_bench_variance(cycles_t *array, size_t len)
{
    cycles_t avg = bench_avg(array, len);

    cycles_t sum = 0;
    size_t count = 0;

    for (size_t i = len; i < len; i++) {
		sum += array[i] * array[i];
    }

    return (sum / count) - (avg * avg);
}

static cycles_t my_bench_min(cycles_t *array, size_t len)
{
    cycles_t min = -1ULL;
    size_t i = 0;
    for (; i < len; i++) {
        if (array[i] < min) {
            min = array[i];
        }
    }
    return min;
}

static cycles_t my_bench_max(cycles_t *array, size_t len)
{
    cycles_t max = 0;
    size_t i = 0;
    for (; i < len; i++) {
        if (array[i] > max) {
            max = array[i];
        }
    }
    return max;
}

static void push_bf_to_net_diff(cycles_t diff){
	the_stats.from_bf_to_net_diff[ the_stats.bf_to_net_i % NUM_OF_RECORDS ] = diff;
	the_stats.bf_to_net_i++;
}

static void push_net_to_bf_diff(cycles_t diff){
	the_stats.from_net_to_bf_diff[ the_stats.net_to_bf_i % NUM_OF_RECORDS ] = diff;
	the_stats.net_to_bf_i++;
}

void record_packet_receive_from_bf(void){
	the_stats.last_packet_receive_from_bf_ts = bench_tsc();
}
void record_packet_transmit_to_net(void) {
	the_stats.last_packet_transmit_to_net_ts = bench_tsc();
	//printf("TONET %"PRIu64"  -  %"PRIu64" = %"PRIu64"\n",the_stats.last_packet_transmit_to_net_ts, the_stats.last_packet_receive_from_bf_ts, the_stats.last_packet_transmit_to_net_ts - the_stats.last_packet_receive_from_bf_ts );
	if(the_stats.last_packet_transmit_to_net_ts > the_stats.last_packet_receive_from_bf_ts){
		push_bf_to_net_diff(the_stats.last_packet_transmit_to_net_ts - the_stats.last_packet_receive_from_bf_ts);
	}  else {
		//printf("TONET Skipped packet because of wrong ts order\n");
	}
}

void record_packet_receive_from_net(void){
	the_stats.last_packet_receive_net_ts = bench_tsc();
}

void record_packet_transmit_to_bf(void){
	the_stats.last_packet_transmit_to_bf_ts = bench_tsc();
	//printf("TOBF  %"PRIu64"  -  %"PRIu64" = %"PRIu64"\n",the_stats.last_packet_transmit_to_bf_ts, the_stats.last_packet_receive_net_ts,the_stats.last_packet_transmit_to_bf_ts - the_stats.last_packet_receive_net_ts  );
	if(the_stats.last_packet_transmit_to_bf_ts > the_stats.last_packet_receive_net_ts){
		push_net_to_bf_diff(the_stats.last_packet_transmit_to_bf_ts - the_stats.last_packet_receive_net_ts );
	} else {
		//printf("TOBF Skipped packet because of wrong ts order\n");
	}
}

// FIXME: (PS) added following prototype to avoid the compilation warning.
//      But need a better way to include this function. It is defined in
//      lib/bench/arch/x86/bench_arch.c
uint64_t bench_tsc_to_us(cycles_t tsc);

void print_bench_stats(void){
	int ele_in_array;
	printf("-----------  BF TO NET\n");
	printf("Recorded %d events\n", the_stats.bf_to_net_i);
	if(the_stats.bf_to_net_i){
		printf("Last:                         %"PRIu64" us\n", bench_tsc_to_us(the_stats.last_packet_transmit_to_net_ts - the_stats.last_packet_receive_from_bf_ts));
		printf("Last:                         %"PRIu64" cycles\n", (the_stats.last_packet_transmit_to_net_ts - the_stats.last_packet_receive_from_bf_ts));
		ele_in_array = the_stats.bf_to_net_i > NUM_OF_RECORDS ? NUM_OF_RECORDS : the_stats.bf_to_net_i;
		printf("Running Average  (of last %d): %"PRIu64" us\n", ele_in_array, bench_tsc_to_us(my_bench_avg(the_stats.from_bf_to_net_diff, ele_in_array)));
		printf("Running Variance (of last %d): %"PRIu64" us\n", ele_in_array, bench_tsc_to_us(my_bench_variance(the_stats.from_bf_to_net_diff, ele_in_array)));
		printf("Running Min      (of last %d): %"PRIu64" us\n", ele_in_array, bench_tsc_to_us(my_bench_min(the_stats.from_bf_to_net_diff, ele_in_array)));
		printf("Running Max      (of last %d): %"PRIu64" us\n", ele_in_array, bench_tsc_to_us(my_bench_max(the_stats.from_bf_to_net_diff, ele_in_array)));
		printf("Data in us:\n");
		for(int i=0; i<ele_in_array; i++){
			printf("%"PRIu64", ", bench_tsc_to_us(the_stats.from_bf_to_net_diff[i]));
		}
		printf("\n");
	}
	printf("-----------\n");

	printf("-----------  NET TO BF\n");
	printf("Recorded %d events\n", the_stats.net_to_bf_i);
	if(the_stats.net_to_bf_i){
		printf("Last:                         %"PRIu64" us\n", bench_tsc_to_us(the_stats.last_packet_transmit_to_bf_ts - the_stats.last_packet_receive_net_ts ));
		printf("Last:                         %"PRIu64" cycles\n", (the_stats.last_packet_transmit_to_bf_ts - the_stats.last_packet_receive_net_ts ));
		ele_in_array = the_stats.net_to_bf_i > NUM_OF_RECORDS ? NUM_OF_RECORDS : the_stats.net_to_bf_i;
		printf("Running Average  (of last %d): %"PRIu64" us\n", ele_in_array, bench_tsc_to_us(my_bench_avg(the_stats.from_net_to_bf_diff, ele_in_array)));
		printf("Running Variance (of last %d): %"PRIu64" us\n", ele_in_array, bench_tsc_to_us(my_bench_variance(the_stats.from_net_to_bf_diff, ele_in_array)));
		printf("Running Min      (of last %d): %"PRIu64" us\n", ele_in_array, bench_tsc_to_us(my_bench_min(the_stats.from_net_to_bf_diff, ele_in_array)));
		printf("Running Max      (of last %d): %"PRIu64" us\n", ele_in_array, bench_tsc_to_us(my_bench_max(the_stats.from_net_to_bf_diff, ele_in_array)));
		printf("Data in us:\n");
		for(int i=0; i<ele_in_array; i++){
			printf("%"PRIu64", ", bench_tsc_to_us(the_stats.from_net_to_bf_diff[i]));
		}
		printf("\n");
	}
	printf("-----------\n");
}


text:
layout: docs
title: Table Mobile
description: Table Mobile extension of Bootstrap Table.
group: extensions
toc: true
---

## Usage

{% highlight html %}
<script src="extensions/mobile/bootstrap-table-mobile.js"></script>
{% endhighlight %}

## Example

[Mobile](https://examples.bootstrap-table.com/#extensions/mobile.html)

## Options

### checkOnInit

- **attribute:** `data-check-on-init`

- **type:** `Boolean`

- **Detail:**

   Set true to check the window size on init.

- **Default:** `true`

### columnsHidden

- **attribute:** `data-columns-hidden`

- **type:** `String`

- **Detail:**

   Set the columns fields in this array in order to hide those columns in the cardView mode. Use this way in `data-*` configuration: ` data-columns-hidden="['name', 'description']"` or this way in javascript configuration: `columnsHidden = ['name', 'description']`.

- **Default:** `undefined`

### minHeight

- **attribute:** `data-min-height`

- **type:** `Integer`

- **Detail:**

   Set the minimum height when the table will change the view.

- **Default:** `undefined`

### minWidth

- **attribute:** `data-min-width`

- **type:** `Integer`

- **Detail:**

   Set the minimum width when the table will change the view.

- **Default:** `562`

### mobileResponsive

- **attribute:** `data-mobile-responsive`

- **type:** `Boolean`

- **Detail:**

   Set true to change the view between card and table view depending on width and height given.

- **Default:** `false`


text:
package net.coding.ide.config;

import org.springframework.test.context.TestPropertySource;

/**
 * Created by tan on 16/9/10.
 */
@TestPropertySource(value = "classpath:application-test.properties")
public class TestPropConfig {

}


text:
package com.github.sandorw.mocabogaso.games.hex;

import com.github.sandorw.mocabogaso.ai.mcts.Heuristic;
import com.github.sandorw.mocabogaso.games.GameState;
import com.github.sandorw.mocabogaso.games.defaults.DefaultGameMove;
import com.github.sandorw.mocabogaso.games.defaults.DefaultGameResult;
import com.github.sandorw.mocabogaso.games.hex.HexGameState.BoardStatus;

/**
 * Heuristic to incentivize linking groups together when threatened.
 *
 * @author sandorw
 */
public class SecureConnectionHeuristic implements Heuristic<DefaultGameMove, DefaultGameResult> {
    private int weight;

    public SecureConnectionHeuristic(int weight) {
        this.weight = weight;
    }

    @Override
    public int getWeight() {
        return weight;
    }

    @Override
    public <GS extends GameState<DefaultGameMove, DefaultGameResult>> DefaultGameResult
            evaluateMove(DefaultGameMove move, GS initialGameState) {
        if (move == null) {
            return null;
        }
        HexGameState hexGameState = (HexGameState) initialGameState;
        int rowIndex = hexGameState.getRowNumber(move.getLocation());
        int colIndex = hexGameState.getColNumber(move.getLocation());
        BoardStatus movingPlayer = (move.getPlayerName().equals("X") ? BoardStatus.X : BoardStatus.O);
        boolean nonUrgentConnectionExists = false;
        boolean directOppositeAllies = false;
        int numAlliedGroups = 0;
        int numAlliedPieces = 0;
        int firstAllyIndex = -4;
        HexGameState.Group[] alliedGroups = {null, null, null};
        for (int i=0; i < 6; ++i) {
            int neighborRow = rowIndex + HexGameState.neighborRowDelta.get(i);
            int neighborCol = colIndex + HexGameState.neighborColDelta.get(i);
            if (hexGameState.isIndexInBounds(neighborRow) && hexGameState.isIndexInBounds(neighborCol)) {
                BoardStatus neighborStatus = hexGameState.boardLocation[neighborRow][neighborCol];
                if (neighborStatus == movingPlayer) {
                    ++numAlliedPieces;
                    HexGameState.Group neighborGroup = hexGameState.groups[neighborRow][neighborCol];
                    boolean matchingGroup = false;
                    for (int j=0; j < numAlliedGroups; ++j) {
                        if (neighborGroup == alliedGroups[j]) {
                            matchingGroup = true;
                            break;
                        }
                    }
                    if (!matchingGroup) {
                        alliedGroups[numAlliedGroups] = neighborGroup;
                        ++numAlliedGroups;
                        if (numAlliedGroups == 1) {
                            firstAllyIndex = i;
                        } else if (firstAllyIndex == i-3) {
                            directOppositeAllies = true;
                        }
                    }
                } else if (neighborStatus == BoardStatus.EMPTY) {
                    int prevIndex = (i == 0 ? 5 : i-1);
                    int nextIndex = (i == 5 ? 0 : i+1);
                    int prevRow = rowIndex + HexGameState.neighborRowDelta.get(prevIndex);
                    int prevCol = colIndex + HexGameState.neighborColDelta.get(prevIndex);
                    int nextRow = rowIndex + HexGameState.neighborRowDelta.get(nextIndex);
                    int nextCol = colIndex + HexGameState.neighborColDelta.get(nextIndex);
                    if (hexGameState.isIndexInBounds(prevRow)
                            && hexGameState.isIndexInBounds(prevCol)
                            && hexGameState.isIndexInBounds(nextRow)
                            && hexGameState.isIndexInBounds(nextCol)) {
                        BoardStatus prevStatus = hexGameState.boardLocation[prevRow][prevCol];
                        BoardStatus nextStatus = hexGameState.boardLocation[nextRow][nextCol];
                        HexGameState.Group prevGroup = hexGameState.groups[prevRow][prevCol];
                        HexGameState.Group nextGroup = hexGameState.groups[nextRow][nextCol];
                        if ((prevStatus == movingPlayer) && (nextStatus == movingPlayer)
                                && (prevGroup != nextGroup)) {
                            nonUrgentConnectionExists = true;
                        }
                    }
                }
            }
        }
        if ((numAlliedGroups == 3) || ((numAlliedGroups == 2)
                && ((directOppositeAllies && (numAlliedPieces == 2))
                || !nonUrgentConnectionExists))) {
            return new DefaultGameResult(move.getPlayerName(), false);
        }
        return null;
    }

    @Override
    public <GS extends GameState<DefaultGameMove, DefaultGameResult>> DefaultGameMove suggestPlayoutMove(GS gameState) {
        return null;
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Method. Lich. 106 (1803)

#### Original name
Gyrophora arctica Ach.

### Remarks
null


text:
package org.dflow.compiler.parser.ast.enumerate;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.dflow.compiler.model.types.EnumerateType;
import org.dflow.compiler.model.types.Type;
import org.dflow.compiler.parser.ast.Node;
import org.dflow.compiler.parser.ast.TypeProvider;

public class Enumerate extends Node implements TypeProvider<EnumerateType> {

	private final String name;
	private final Contents contents;

	private org.dflow.compiler.model.enums.Enumerate model;

	public Enumerate(String name, Contents contents) {
		this.name = name;
		this.contents = contents;
	}

	public String getName() {
		return name;
	}

	public Collection<Value> getValues() {
		return Collections.unmodifiableCollection(contents.values.values);
	}

	public org.dflow.compiler.model.enums.Enumerate getModel() {
		return model;
	}

	public void setModel(org.dflow.compiler.model.enums.Enumerate model) {
		this.model = model;
	}

	@Override
	protected Iterable<Node> getChildren() {
		return Arrays.asList(new Node[] { contents });
	}

	@Override
	public Type getSafeType() {
		if (model == null) {
			return Type.UNKNOWN;
		} else {
			return getType();
		}
	}

	@Override
	public EnumerateType getType() {
		return model.getType();
	}

	public static class Contents extends Node {

		private final Values values;

		public Contents(Values values) {
			this.values = values;
		}

		@Override
		protected Iterable<Node> getChildren() {
			return Arrays.asList(new Node[] { values });
		}
	}

	public static class Values extends Node {

		private final List<Value> values = new LinkedList<>();

		public Values add(Value value) {
			values.add(value);
			return this;
		}

		@Override
		protected Iterable<Node> getChildren() {
			return Collections.<Node>unmodifiableCollection(values);
		}
	}

	public static class Value extends Node {

		private final String name;

		public Value(String name) {
			this.name = name;
		}

		public String getName() {
			return name;
		}
	}
}


text:
/**
 * Always respond with same overwrite.
 *
 * <example>
    :respond.js
    it('should demonstrate response overwrite with static data', async () => {
        const mock = await browser.mock('https://todo-backend-express-knex.herokuapp.com/', {
            method: 'get'
        })

        mock.respond([{
            title: 'Injected (non) completed Todo',
            order: null,
            completed: false
        }, {
            title: 'Injected completed Todo',
            order: null,
            completed: true
        }], {
            statusCode: 200,
            fetchResponse: true // default
        })

        await browser.url('https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/')

        await $('#todo-list li').waitForExist()
        console.log(await $$('#todo-list li').map(el => el.getText()))
        // outputs: "[ 'Injected (non) completed Todo', 'Injected completed Todo' ]"
    })

    it('should demonstrate response overwrite with dynamic data', async () => {
        const mock = await browser.mock('https://todo-backend-express-knex.herokuapp.com/')

        mock.respond((request) => {
            if (request.body.username === 'test') {
                return { ...request.body, foo: 'bar' }
            }
            return request.body
        }, {
            statusCode: () => 200,
            headers: () => ({ foo: 'bar }),
            fetchResponse: false // do not fetch real response
        })
    })
 * </example>
 *
 * @alias mock.respond
 * @param {MockOverwrite}       overwrites              payload to overwrite the response
 * @param {MockResponseParams=} params                  additional respond parameters to overwrite
 * @param {Object=}             params.header           overwrite specific headers
 * @param {Number=}             params.statusCode       overwrite response status code
 * @param {Boolean=}            params.fetchResponse    fetch real response before responding with mocked data
 */
// actual implementation is located in packages/webdriverio/src/utils/interception


text:
ActiveAdmin.setup do |config|
  config.site_title = "Testapp"
  config.authentication_method = :authenticate_admin_user!
  config.current_user_method = :current_admin_user
  config.logout_link_path = :destroy_admin_user_session_path
  config.batch_actions = true
end


text:
import type { LogoutEventOptions } from "Server/mediator"

export function logoutEventHandler(
  options: LogoutEventOptions = {}
): Promise<void> {
  const redirectPath = options.redirectPath

  return fetch("/users/sign_out", {
    headers: {
      // TODO: To trick the logout page into thinking we made and xhr request
      "X-Requested-With": "XMLHttpRequest",
    },
    method: "DELETE",
  })
    .then(() => {
      if (window.analytics && window.analytics.reset) {
        // guard for aggressive ad blockers
        window.analytics.reset()
      }
      if (redirectPath) {
        location.assign(redirectPath)
      } else {
        location.reload()
      }
    })
    .catch(message => {
      alert(message)
    })
}


text:
kinterface-ui
=============

kinterface-ui


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>
Uses of Class org.apache.commons.math3.optim.PointVectorValuePair (Commons Math 3.1.1 API)
</TITLE>

<META NAME="date" CONTENT="2013-01-09">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.commons.math3.optim.PointVectorValuePair

Packages that use PointVectorValuePair

org.apache.commons.math3.optim

  Generally, optimizers are algorithms that will either
  minimize or
  maximize
  a scalar function, called the
  objective
  function.

org.apache.commons.math3.optim.nonlinear.vector
Algorithms for optimizing a vector function.

org.apache.commons.math3.optim.nonlinear.vector.jacobian
This package provides optimization algorithms that require derivatives.

Uses of PointVectorValuePair in org.apache.commons.math3.optim

Methods in org.apache.commons.math3.optim with parameters of type PointVectorValuePair

 boolean
SimpleVectorValueChecker.converged(int iteration,
                   PointVectorValuePair previous,
                   PointVectorValuePair current)

          Check if the optimization algorithm has converged considering the
 last two points.

Uses of PointVectorValuePair in org.apache.commons.math3.optim.nonlinear.vector

Methods in org.apache.commons.math3.optim.nonlinear.vector that return PointVectorValuePair

 PointVectorValuePair[]
MultiStartMultivariateVectorOptimizer.getOptima()

          Gets all the optima found during the last call to optimize.

 PointVectorValuePair
JacobianMultivariateVectorOptimizer.optimize(OptimizationData... optData)

          Stores data and performs the optimization.

 PointVectorValuePair
MultivariateVectorOptimizer.optimize(OptimizationData... optData)

          Stores data and performs the optimization.

Methods in org.apache.commons.math3.optim.nonlinear.vector with parameters of type PointVectorValuePair

protected  void
MultiStartMultivariateVectorOptimizer.store(PointVectorValuePair optimum)

          Method that will be called in order to store each found optimum.

Constructor parameters in org.apache.commons.math3.optim.nonlinear.vector with type arguments of type PointVectorValuePair

JacobianMultivariateVectorOptimizer(ConvergenceChecker<PointVectorValuePair> checker)

MultivariateVectorOptimizer(ConvergenceChecker<PointVectorValuePair> checker)

Uses of PointVectorValuePair in org.apache.commons.math3.optim.nonlinear.vector.jacobian

Methods in org.apache.commons.math3.optim.nonlinear.vector.jacobian that return PointVectorValuePair

 PointVectorValuePair
GaussNewtonOptimizer.doOptimize()

          Performs the bulk of the optimization algorithm.

protected  PointVectorValuePair
LevenbergMarquardtOptimizer.doOptimize()

          Performs the bulk of the optimization algorithm.

 PointVectorValuePair
AbstractLeastSquaresOptimizer.optimize(OptimizationData... optData)

          Stores data and performs the optimization.

Constructor parameters in org.apache.commons.math3.optim.nonlinear.vector.jacobian with type arguments of type PointVectorValuePair

AbstractLeastSquaresOptimizer(ConvergenceChecker<PointVectorValuePair> checker)

GaussNewtonOptimizer(boolean useLU,
                                         ConvergenceChecker<PointVectorValuePair> checker)

GaussNewtonOptimizer(ConvergenceChecker<PointVectorValuePair> checker)

          Simple constructor with default settings.

LevenbergMarquardtOptimizer(ConvergenceChecker<PointVectorValuePair> checker)

          Constructor that allows the specification of a custom convergence
 checker.

LevenbergMarquardtOptimizer(double initialStepBoundFactor,
                                                       ConvergenceChecker<PointVectorValuePair> checker,
                                                       double costRelativeTolerance,
                                                       double parRelativeTolerance,
                                                       double orthoTolerance,
                                                       double threshold)

          Constructor that allows the specification of a custom convergence
 checker, in addition to the standard ones.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2003-2013 The Apache Software Foundation. All Rights Reserved.


text:
var Path = require('fire-path');

module.exports = [
    'editor-app.js',
    'query-recent.js',
];


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>hamsterdb Embedded Database: ham_parameter_t Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

hamsterdb Embedded Database
    2.1.11

Main Page

Modules

Namespaces

Data Structures

Files

Data Structures

Data Structure Index

Data Fields

Data Fields

ham_parameter_t Struct Reference

#include <hamsterdb.h>

Data Fields

uint32_t 	name

uint64_t 	value

Detailed Description

A named parameter.

These parameter structures are used for functions like ham_env_open, ham_env_create, etc. to pass variable length parameter lists.

The lists are always arrays of type ham_parameter_t, with a terminating element of { 0, NULL}, e.g.

  ham_parameter_t parameters[] = {
   { HAM_PARAM_CACHE_SIZE, 2 * 1024 * 1024 }, // set cache size to 2 mb
   { HAM_PARAM_PAGE_SIZE, 4096 }, // set page size to 4 kb
   { 0, NULL }
  };

Definition at line 303 of file hamsterdb.h.

Field Documentation

          uint32_t ham_parameter_t::name

The name of the parameter; all HAM_PARAM_*-constants

Definition at line 305 of file hamsterdb.h.

          uint64_t ham_parameter_t::value

The value of the parameter.

Definition at line 308 of file hamsterdb.h.

The documentation for this struct was generated from the following file:

include/ham/hamsterdb.h

<address class="footer">
Generated by

 1.8.6
</address>


text:
{% extends "wagtailadmin/base.html" %}
{% load i18n %}
{% block titletag %}{% blocktrans with title=redirect.title %}Editing {{ title }}{% endblocktrans %}{% endblock %}
{% block content %}
    {% trans "Editing" as editing_str %}
    {% include "wagtailadmin/shared/header.html" with title=editing_str subtitle=redirect.title icon="redirect" %}

    {% if form.non_field_errors %}

                {% for error in form.non_field_errors %}

{{ error }}

                {% endfor %}

    {% endif %}

    <form action="{% url 'wagtailredirects:edit' redirect.id %}" method="POST" class="nice-padding">
        {% csrf_token %}

            {% for field in form.visible_fields %}
                {% include "wagtailadmin/shared/field_as_li.html" %}
            {% endfor %}

                <input type="submit" value="{% trans 'Save' %}" />
                {% trans "Delete redirect" %}

    </form>

{% endblock %}

{% block extra_js %}
    {{ block.super }}
    {% include "wagtailadmin/pages/_editor_js.html" %}
{% endblock %}


text:
/*global tinymce:true */

/**
 * Auto Resize
 *
 * This plugin automatically resizes the content area to fit its content height.
 * It will retain a minimum height, which is the height of the content area when
 * it's initialized.
 */
tinymce.PluginManager.add('autoresize', function(editor) {
	var settings = editor.settings, oldSize = 0;

	if (editor.settings.inline) {
		return;
	}

	/**
	 * This method gets executed each time the editor needs to resize.
	 */
	function resize(e) {
		var deltaSize, d = editor.getDoc(), body = d.body, de = d.documentElement, DOM = tinymce.DOM,
			resizeHeight = settings.autoresize_min_height, myHeight, marginTop, marginBottom;

		if (!body || !e || (e.type === "setcontent" && e.initial) ||
				(editor.plugins.fullscreen && editor.plugins.fullscreen.isFullscreen())) {
			return;
		}

		// Calculate outer height of the body element using CSS styles
		marginTop = editor.dom.getStyle(body, 'margin-top', true);
		marginBottom = editor.dom.getStyle(body, 'margin-bottom', true);
		myHeight = body.offsetHeight + parseInt(marginTop, 10) + parseInt(marginBottom, 10);

		// Make sure we have a valid height
		if (isNaN(myHeight) || myHeight <= 0) {
			// Get height differently depending on the browser used
			myHeight = tinymce.Env.ie ? body.scrollHeight : (tinymce.Env.webkit && body.clientHeight === 0 ? 0 : body.offsetHeight);
		}

		// Don't make it smaller than the minimum height
		if (myHeight > settings.autoresize_min_height) {
			resizeHeight = myHeight;
		}

		// If a maximum height has been defined don't exceed this height
		if (settings.autoresize_max_height && myHeight > settings.autoresize_max_height) {
			resizeHeight = settings.autoresize_max_height;
			body.style.overflowY = "auto";
			de.style.overflowY = "auto"; // Old IE
		} else {
			body.style.overflowY = "hidden";
			de.style.overflowY = "hidden"; // Old IE
			body.scrollTop = 0;
		}

		// Resize content element
		if (resizeHeight !== oldSize) {
			deltaSize = resizeHeight - oldSize;
			DOM.setStyle(DOM.get(editor.id + '_ifr'), 'height', resizeHeight + 'px');
			oldSize = resizeHeight;

			// WebKit doesn't decrease the size of the body element until the iframe gets resized
			// So we need to continue to resize the iframe down until the size gets fixed
			if (tinymce.isWebKit && deltaSize < 0) {
				resize(e);
			}
		}
	}

	/**
	 * Calls the resize x times in 100ms intervals. We can't wait for load events since
	 * the CSS files might load async.
	 */
	function wait(times, interval, callback) {
		setTimeout(function() {
			resize({});

			if (times--) {
				wait(times, interval, callback);
			} else if (callback) {
				callback();
			}
		}, interval);
	}

	// Define minimum height
	settings.autoresize_min_height = parseInt(editor.getParam('autoresize_min_height', editor.getElement().offsetHeight), 10);

	// Define maximum height
	settings.autoresize_max_height = parseInt(editor.getParam('autoresize_max_height', 0), 10);

	// Add padding at the bottom for better UX
	editor.on("init", function() {
		editor.dom.setStyle(editor.getBody(), 'paddingBottom', editor.getParam('autoresize_bottom_margin', 50) + 'px');
	});

	// Add appropriate listeners for resizing content area
	editor.on("change setcontent paste keyup", resize);

	if (editor.getParam('autoresize_on_init', true)) {
		editor.on('init', function() {
			// Hit it 20 times in 100 ms intervals
			wait(20, 100, function() {
				// Hit it 5 times in 1 sec intervals
				wait(5, 1000);
			});
		});
	}

	// Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample');
	editor.addCommand('mceAutoResize', resize);
});