text:
package io.reactivex.netty.channel;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.channel.embedded.EmbeddedChannel;
import io.reactivex.netty.channel.BackpressureManagingHandler.BytesWriteInterceptor;
import io.reactivex.netty.channel.BackpressureManagingHandler.RequestReadIfRequiredEvent;
import io.reactivex.netty.channel.BackpressureManagingHandler.State;
import io.reactivex.netty.test.util.InboundRequestFeeder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.mockito.Mockito;
import rx.Observable;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;

public class BackpressureManagingHandlerTest {

    @Rule
    public final HandlerRule handlerRule = new HandlerRule();

    @Test(timeout = 60000)
    public void testExactDemandAndSupply() throws Exception {
        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.Buffering));

        final String msg1 = "hello1";
        final String msg2 = "hello2";
        handlerRule.feedMessagesForRead(msg1, msg2); /*Exact supply*/

        handlerRule.channel.config().setMaxMessagesPerRead(2); /*Send all msgs in one iteration*/
        handlerRule.requestMessages(2); /*Exact demand*/

        assertThat("Unexpected read requested count.", handlerRule.getReadRequestedCount(), is(1));
        handlerRule.assertMessagesReceived(msg1, msg2);

        /*Since, the demand is met (requested 2 and got 2) , we move to buffering.*/
        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.Buffering));
    }

    @Test(timeout = 60000)
    public void testExactDemandAndSupplyMultiRequests() throws Exception {
        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.Buffering));

        final String msg1 = "hello1";
        final String msg2 = "hello2";
        handlerRule.feedMessagesForRead(msg1, msg2); /*Exact supply*/

        handlerRule.channel.config().setMaxMessagesPerRead(2); /*Send all msgs in one iteration*/
        handlerRule.requestMessages(2); /*Exact demand*/

        assertThat("Unexpected read requested count.", handlerRule.getReadRequestedCount(), is(1));
        handlerRule.assertMessagesReceived(msg1, msg2);

        /*Since, the demand is met (requested 2 and got 2) , we move to buffering.*/
        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.Buffering));

        handlerRule.resetReadCount();
        assertThat("Unexpected read requested count post reset.", handlerRule.getReadRequestedCount(), is(0));

        handlerRule.handler.reset();

        final String msg3 = "hello3";
        handlerRule.feedMessagesForRead(msg3);

        /*No demand, no read fired*/
        assertThat("Unexpected read requested count post reset.", handlerRule.getReadRequestedCount(), is(0));
        handlerRule.assertMessagesReceived();

        handlerRule.requestMessages(1);

        /*Read on demand*/
        assertThat("Unexpected read requested count.", handlerRule.getReadRequestedCount(), is(1));
        handlerRule.assertMessagesReceived(msg3);

        /*Since, the demand is met (requested 3 and got 3) , we move to buffering.*/
        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.Reading));
    }

    @Test(timeout = 60000)
    public void testMoreDemand() throws Exception {
        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.Buffering));

        final String msg1 = "hello1";
        final String msg2 = "hello2";
        handlerRule.feedMessagesForRead(msg1, msg2); /*less supply*/

        handlerRule.channel.config().setMaxMessagesPerRead(2); /*Send all msgs in one iteration*/
        handlerRule.requestMessages(4); /*More demand*/

        /*One read for start and one when the supply completed but demand exists.*/
        assertThat("Unexpected read requested count.", handlerRule.getReadRequestedCount(), is(2));
        handlerRule.assertMessagesReceived(msg1, msg2);

        /*Since, the demand is not met (requested 4 but got 2) , stay in read requested.*/
        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.ReadRequested));
    }

    @Test(timeout = 60000)
    public void testMoreSupply() throws Exception {
        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.Buffering));

        final String msg1 = "hello1";
        final String msg2 = "hello2";
        final String msg3 = "hello3";
        handlerRule.feedMessagesForRead(msg1, msg2, msg3); /*more supply*/

        handlerRule.channel.config().setMaxMessagesPerRead(3); /*Send all msgs in one iteration*/
        handlerRule.requestMessages(2); /*less demand*/

        /*One read for start.*/
        assertThat("Unexpected read requested count.", handlerRule.getReadRequestedCount(), is(1));
        handlerRule.assertMessagesReceived(msg1, msg2);

        /*Since, the demand was met (requested 2 and got 2) , but the supply was more (3), we should be buffering.*/
        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.Buffering));
        assertThat("Unexpected buffer size.", handlerRule.handler.getBuffer(), hasSize(1));
        assertThat("Unexpected buffer contents.", handlerRule.handler.getBuffer(), contains((Object) msg3));
        assertThat("Unexpected buffer read index.", handlerRule.handler.getCurrentBufferIndex(), is(0));
    }

    @Test(timeout = 60000)
    public void testBufferDrainSingleIteration() throws Exception {
        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.Buffering));

        final String msg1 = "hello1";
        final String msg2 = "hello2";
        final String msg3 = "hello3";
        handlerRule.feedMessagesForRead(msg1, msg2, msg3); /*more supply*/

        handlerRule.channel.config().setMaxMessagesPerRead(3); /*Send all msgs in one iteration & cause buffer*/
        handlerRule.requestMessages(2); /*less demand*/

        /*One read for start.*/
        assertThat("Unexpected read requested count.", handlerRule.getReadRequestedCount(), is(1));
        handlerRule.assertMessagesReceived(msg1, msg2);

        /*Since, the demand was met (requested 2 and got 2) , but the supply was more (3), we should be buffering.*/
        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.Buffering));
        assertThat("Unexpected buffer size.", handlerRule.handler.getBuffer(), hasSize(1));
        assertThat("Unexpected buffer contents.", handlerRule.handler.getBuffer(), contains((Object) msg3));
        assertThat("Unexpected buffer read index.", handlerRule.handler.getCurrentBufferIndex(), is(0));

        handlerRule.resetReadCount();
        assertThat("Unexpected read requested count post reset.", handlerRule.getReadRequestedCount(), is(0));

        handlerRule.handler.reset();

        handlerRule.requestMessages(1); /*Should come from the buffer.*/

        assertThat("Unexpected read requested when expected to be fed from buffer.",
                   handlerRule.getReadRequestedCount(), is(0));
        handlerRule.assertMessagesReceived(msg3);

        /*Since, the demand is now met (requested 3 and got 3) , we move to buffering.*/
        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.Buffering));
        assertThat("Unexpected buffer size.", handlerRule.handler.getBuffer(), is(nullValue()));
        assertThat("Unexpected buffer read index.", handlerRule.handler.getCurrentBufferIndex(), is(0));
    }

    @Test(timeout = 60000)
    public void testBufferDrainMultiIteration() throws Exception {
        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.Buffering));

        final String msg1 = "hello1";
        final String msg2 = "hello2";
        final String msg3 = "hello3";
        final String msg4 = "hello4";
        handlerRule.feedMessagesForRead(msg1, msg2, msg3, msg4); /*more supply*/

        handlerRule.channel.config().setMaxMessagesPerRead(4); /*Send all msgs in one iteration & cause buffer*/
        handlerRule.requestMessages(2); /*less demand*/

        /*One read for start.*/
        assertThat("Unexpected read requested count.", handlerRule.getReadRequestedCount(), is(1));
        handlerRule.assertMessagesReceived(msg1, msg2);

        /*Since, the demand was met (requested 2 and got 2) , but the supply was more (4), we should be buffering.*/
        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.Buffering));
        assertThat("Unexpected buffer size.", handlerRule.handler.getBuffer(), hasSize(2));
        assertThat("Unexpected buffer contents.", handlerRule.handler.getBuffer(), contains((Object) msg3, msg4));
        assertThat("Unexpected buffer read index.", handlerRule.handler.getCurrentBufferIndex(), is(0));

        /*Reset read state before next read*/
        handlerRule.resetReadCount();
        assertThat("Unexpected read requested count post reset.", handlerRule.getReadRequestedCount(), is(0));
        handlerRule.handler.reset();

        handlerRule.requestMessages(1); /*Should come from the buffer.*/

        assertThat("Unexpected read requested when expected to be fed from buffer.",
                   handlerRule.getReadRequestedCount(), is(0));
        handlerRule.assertMessagesReceived(msg3);

        /*Since, the demand is now met (requested 3 and got 3) , we move to buffering.*/
        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.Buffering));
        /*Buffer does not change till it has data*/
        assertThat("Unexpected buffer size.", handlerRule.handler.getBuffer(), hasSize(2));
        /*Buffer reader index changes till it has data*/
        assertThat("Unexpected buffer read index.", handlerRule.handler.getCurrentBufferIndex(), is(1));

        /*Reset read state before next read*/
        handlerRule.resetReadCount();
        assertThat("Unexpected read requested count post reset.", handlerRule.getReadRequestedCount(), is(0));
        handlerRule.handler.reset();

        handlerRule.requestMessages(1); /*Should come from the buffer.*/

        assertThat("Unexpected read requested when expected to be fed from buffer.",
                   handlerRule.getReadRequestedCount(), is(0));
        handlerRule.assertMessagesReceived(msg4);

        /*Since, the demand is now met (requested 4 and got 4) , we move to buffering.*/
        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.Buffering));
        assertThat("Unexpected buffer size.", handlerRule.handler.getBuffer(), is(nullValue()));
        assertThat("Unexpected buffer read index.", handlerRule.handler.getCurrentBufferIndex(), is(0));
    }

    @Test(timeout = 60000)
    public void testBufferDrainWithMoreDemand() throws Exception {
        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.Buffering));

        final String msg1 = "hello1";
        final String msg2 = "hello2";
        final String msg3 = "hello3";
        handlerRule.feedMessagesForRead(msg1, msg2, msg3); /*more supply*/

        handlerRule.channel.config().setMaxMessagesPerRead(3); /*Send all msgs in one iteration & cause buffer*/
        handlerRule.requestMessages(2); /*less demand*/

        /*One read for start.*/
        assertThat("Unexpected read requested count.", handlerRule.getReadRequestedCount(), is(1));
        handlerRule.assertMessagesReceived(msg1, msg2);

        /*Since, the demand was met (requested 2 and got 2) , but the supply was more (3), we should be buffering.*/
        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.Buffering));
        assertThat("Unexpected buffer size.", handlerRule.handler.getBuffer(), hasSize(1));
        assertThat("Unexpected buffer contents.", handlerRule.handler.getBuffer(), contains((Object) msg3));
        assertThat("Unexpected buffer read index.", handlerRule.handler.getCurrentBufferIndex(), is(0));

        handlerRule.resetReadCount();
        assertThat("Unexpected read requested count post reset.", handlerRule.getReadRequestedCount(), is(0));

        handlerRule.handler.reset();

        handlerRule.requestMessages(2); /*Should come from the buffer.*/

        /*Since demand can not be fulfilled by the buffer, a read should be requested.*/
        assertThat("Unexpected read requested.", handlerRule.getReadRequestedCount(), is(1));
        handlerRule.assertMessagesReceived(msg3);

        /*Since, the demand is now met (requested 3 and got 3) , we move to buffering.*/
        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.ReadRequested));
        assertThat("Unexpected buffer size.", handlerRule.handler.getBuffer(), is(nullValue()));
        assertThat("Unexpected buffer read index.", handlerRule.handler.getCurrentBufferIndex(), is(0));
    }

    @Test(timeout = 60000)
    public void testBufferDrainOnRemove() throws Exception {
        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.Buffering));

        final ByteBuf msg1 = Unpooled.buffer().writeBytes("hello1".getBytes());
        final ByteBuf msg2 = Unpooled.buffer().writeBytes("hello2".getBytes());
        handlerRule.feedMessagesForRead(msg1, msg2); /*More supply then demand*/

        handlerRule.channel.config().setMaxMessagesPerRead(2); /*Send all msgs in one iteration and cause buffer*/
        handlerRule.requestMessages(1); /*Less demand*/

        assertThat("Unexpected read requested count.", handlerRule.getReadRequestedCount(), is(1));
        handlerRule.assertMessagesReceived(msg1);

        /*Since, the demand is met (requested 1 and got 1) , we move to buffering.*/
        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.Buffering));
        assertThat("Unexpected buffer size.", handlerRule.handler.getBuffer(), hasSize(1));
        assertThat("Unexpected buffer contents.", handlerRule.handler.getBuffer(), contains((Object) msg2));
        assertThat("Unexpected buffer read index.", handlerRule.handler.getCurrentBufferIndex(), is(0));

        handlerRule.channel.close(); // Should remove handler.
        handlerRule.channel.runPendingTasks();

        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.Stopped));
        assertThat("Unexpected buffer size.", handlerRule.handler.getBuffer(), is(nullValue()));
        assertThat("Unexpected buffer read index.", handlerRule.handler.getCurrentBufferIndex(), is(0));
        assertThat("Buffered item not released.", msg2.refCnt(), is(0));
    }

    @Test(timeout = 60000)
    public void testDiscardReadWhenStopped() throws Exception {
        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.Buffering));

        handlerRule.channel.close(); // Should remove handler.
        handlerRule.channel.runPendingTasks();

        assertThat("Unexpected handler state.", handlerRule.handler.getCurrentState(), is(State.Stopped));

        final ByteBuf msg = Unpooled.buffer().writeBytes("Hello".getBytes());
        handlerRule.handler.channelRead(Mockito.mock(ChannelHandlerContext.class), msg);

        assertThat("Message not released when stopped.", msg.refCnt(), is(0));
    }

    @Test(timeout = 60000)
    public void testWriteWithBufferingHandler() throws Exception {
        BufferingHandler bufferingHandler = new BufferingHandler();
        handlerRule.channel.pipeline()
                           .addBefore(BytesWriteInterceptor.WRITE_INSPECTOR_HANDLER_NAME, "buffering-handler",
                                      bufferingHandler);

        final String[] dataToWrite = {"Hello1", "Hello2"};

        handlerRule.channel.writeAndFlush(Observable.from(dataToWrite));/*Using Observable.from() to enable backpressure.*/

        assertThat("Messages written to the channel, inspite of buffering", handlerRule.channel.outboundMessages(),
                   is(empty()));

        /*Inspite of the messages, not reaching the channel, the extra demand should be generated and the buffering
        handler should contain all messages.*/
        assertThat("Unexpected buffer size in buffering handler.", bufferingHandler.buffer, hasSize(2));
    }

    public static class HandlerRule extends ExternalResource {

        private MockBackpressureManagingHandler handler;
        private EmbeddedChannel channel;
        private InboundRequestFeeder inboundRequestFeeder;

        @Override
        public Statement apply(final Statement base, Description description) {
            return new Statement() {
                @Override
                public void evaluate() throws Throwable {
                    inboundRequestFeeder = new InboundRequestFeeder();
                    channel = new EmbeddedChannel();
                    String bpName = "backpressure-manager";
                    channel.pipeline().addFirst(bpName,
                                                handler = new MockBackpressureManagingHandler(bpName));
                    channel.pipeline().addBefore(bpName, "primitive-converter", PrimitiveConversionHandler.INSTANCE);
                    channel.pipeline().addFirst(inboundRequestFeeder);
                    channel.config().setAutoRead(false);
                    base.evaluate();
                }
            };
        }

        public void assertMessagesReceived(Object... expected) {
            final List<Object> msgsReceived = handler.getMsgsReceived();

            if (null != expected && expected.length > 0) {
                assertThat("Unexpected messages received count.", msgsReceived, hasSize(expected.length));
                assertThat("Unexpected messages received.", msgsReceived, contains(expected));
            } else {
                assertThat("Unexpected messages received.", msgsReceived, is(empty()));
            }
        }

        public int resetReadCount() {
            return inboundRequestFeeder.resetReadRequested();
        }

        public int getReadRequestedCount() {
            return inboundRequestFeeder.getReadRequestedCount();
        }

        public void requestMessages(long requested) throws Exception {
            handler.incrementRequested(requested);
            channel.pipeline().fireUserEventTriggered(new RequestReadIfRequiredEvent() {
                @Override
                protected boolean shouldReadMore(ChannelHandlerContext ctx) {
                    return true;
                }
            });
            channel.runPendingTasks();
        }

        public void feedMessagesForRead(Object... msgs) {
            inboundRequestFeeder.addToTheFeed(msgs);
        }
    }

    private static class MockBackpressureManagingHandler extends BackpressureManagingHandler {

        private final List<Object> msgsReceived = new ArrayList<>();
        private final AtomicLong requested = new AtomicLong();

        protected MockBackpressureManagingHandler(String thisHandlerName) {
            super(thisHandlerName);
        }

        @Override
        protected void newMessage(ChannelHandlerContext ctx, Object msg) {
            requested.decrementAndGet();
            msgsReceived.add(msg);
        }

        @Override
        protected boolean shouldReadMore(ChannelHandlerContext ctx) {
            return requested.get() > 0;
        }

        public List<Object> getMsgsReceived() {
            return msgsReceived;
        }

        public void reset() {
            msgsReceived.clear();
            requested.set(0);
        }

        public void incrementRequested(long requested) {
            this.requested.addAndGet(requested);
        }
    }

    private static class BufferingHandler extends ChannelOutboundHandlerAdapter {

        private final List<Object> buffer = new ArrayList<>();

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            buffer.add(msg);
        }
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Nasturtium semipinnatifidum Hook.

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
package logstash

// Result contains the result of a Logstash execution.
type Result struct {
	// Success indicates whether the execution was successful,
	// i.e. whether the Logstash process terminated with a zero
	// exit status.
	Success bool

	// Events contains a slice of the events emitted from
	// Logstash.
	Events []Event

	// Log contains the contents of the Logstash log file.
	Log string

	// Output contains stdout and stderr output (if any) of
	// the Logstash process. If the process fails during
	// initialization clues can probably be found here.
	Output string
}

// ParallelResult contains the results of a parallel Logstash execution,
// where multiple test cases are run in parallel via unix domain sockets.
type ParallelResult struct {
	// Success indicates whether the execution was successful,
	// i.e. whether the Logstash process terminated with a zero
	// exit status.
	Success bool

	// Events contains a slice of the events emitted from
	// Logstash.
	Events [][]Event

	// Log contains the contents of the Logstash log file.
	Log string

	// Output contains stdout and stderr output (if any) of
	// the Logstash process. If the process fails during
	// initialization clues can probably be found here.
	Output string
}

// Event represents a Logstash event, i.e. basically a JSON document.
type Event map[string]interface{}


text:
""" Simulate Burgers' Equation
Simple advection-diffusion equation.
"""
from phi.flow import *

velocity = CenteredGrid(Noise(vector=2), extrapolation.PERIODIC, x=64, y=64, bounds=Box(x=200, y=100)) * 2

# @jit_compile  # for PyTorch, TensorFlow and Jax
def burgers_step(v, dt=1.):
    v = diffuse.explicit(v, 0.1, dt=dt)
    v = advect.semi_lagrangian(v, v, dt=dt)
    return v

for _ in view(play=False, framerate=10, namespace=globals()).range():
    velocity = burgers_step(velocity)


text:
using BookReviews.Infrastructure;
using BookReviews.UI.Attributes;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BookReviews.UI.ViewModels.AccountsManagment.DeleteAccount
{
    public class DeleteAccountViewModel
    {
        [Required]
        public string AccountEmail { get; set; }

        private bool deletePermanently = false;
        public bool DeletePermanently { get { return deletePermanently; } set { deletePermanently = value; } }
    }
}


text:
package org.apache.hadoop.hbase.mapreduce;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.ScannerCallable;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.client.metrics.ScanMetrics;
import org.apache.hadoop.hbase.DoNotRetryIOException;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.mapreduce.Counter;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.util.StringUtils;

import org.apache.hadoop.hbase.shaded.com.google.common.annotations.VisibleForTesting;

/**
 * Iterate over an HBase table data, return (ImmutableBytesWritable, Result)
 * pairs.
 */
@InterfaceAudience.Public
public class TableRecordReaderImpl {
  public static final String LOG_PER_ROW_COUNT
    = "hbase.mapreduce.log.scanner.rowcount";

  private static final Log LOG = LogFactory.getLog(TableRecordReaderImpl.class);

  // HBASE_COUNTER_GROUP_NAME is the name of mapreduce counter group for HBase
  @VisibleForTesting
  static final String HBASE_COUNTER_GROUP_NAME = "HBase Counters";
  private ResultScanner scanner = null;
  private Scan scan = null;
  private Scan currentScan = null;
  private Table htable = null;
  private byte[] lastSuccessfulRow = null;
  private ImmutableBytesWritable key = null;
  private Result value = null;
  private TaskAttemptContext context = null;
  private Method getCounter = null;
  private long numRestarts = 0;
  private long numStale = 0;
  private long timestamp;
  private int rowcount;
  private boolean logScannerActivity = false;
  private int logPerRowCount = 100;

  /**
   * Restart from survivable exceptions by creating a new scanner.
   *
   * @param firstRow  The first row to start at.
   * @throws IOException When restarting fails.
   */
  public void restart(byte[] firstRow) throws IOException {
    currentScan = new Scan(scan);
    currentScan.withStartRow(firstRow);
    currentScan.setScanMetricsEnabled(true);
    if (this.scanner != null) {
      if (logScannerActivity) {
        LOG.info("Closing the previously opened scanner object.");
      }
      this.scanner.close();
    }
    this.scanner = this.htable.getScanner(currentScan);
    if (logScannerActivity) {
      LOG.info("Current scan=" + currentScan.toString());
      timestamp = System.currentTimeMillis();
      rowcount = 0;
    }
  }

  /**
   * In new mapreduce APIs, TaskAttemptContext has two getCounter methods
   * Check if getCounter(String, String) method is available.
   * @return The getCounter method or null if not available.
   * @throws IOException
   */
  protected static Method retrieveGetCounterWithStringsParams(TaskAttemptContext context)
  throws IOException {
    Method m = null;
    try {
      m = context.getClass().getMethod("getCounter",
        new Class [] {String.class, String.class});
    } catch (SecurityException e) {
      throw new IOException("Failed test for getCounter", e);
    } catch (NoSuchMethodException e) {
      // Ignore
    }
    return m;
  }

  /**
   * Sets the HBase table.
   *
   * @param htable  The {@link org.apache.hadoop.hbase.HTableDescriptor} to scan.
   */
  public void setHTable(Table htable) {
    Configuration conf = htable.getConfiguration();
    logScannerActivity = conf.getBoolean(
      ScannerCallable.LOG_SCANNER_ACTIVITY, false);
    logPerRowCount = conf.getInt(LOG_PER_ROW_COUNT, 100);
    this.htable = htable;
  }

  /**
   * Sets the scan defining the actual details like columns etc.
   *
   * @param scan  The scan to set.
   */
  public void setScan(Scan scan) {
    this.scan = scan;
  }

  /**
   * Build the scanner. Not done in constructor to allow for extension.
   *
   * @throws IOException
   * @throws InterruptedException
   */
  public void initialize(InputSplit inputsplit,
      TaskAttemptContext context) throws IOException,
      InterruptedException {
    if (context != null) {
      this.context = context;
      getCounter = retrieveGetCounterWithStringsParams(context);
    }
    restart(scan.getStartRow());
  }

  /**
   * Closes the split.
   *
   *
   */
  public void close() {
    if (this.scanner != null) {
      this.scanner.close();
    }
    try {
      this.htable.close();
    } catch (IOException ioe) {
      LOG.warn("Error closing table", ioe);
    }
  }

  /**
   * Returns the current key.
   *
   * @return The current key.
   * @throws IOException
   * @throws InterruptedException When the job is aborted.
   */
  public ImmutableBytesWritable getCurrentKey() throws IOException,
      InterruptedException {
    return key;
  }

  /**
   * Returns the current value.
   *
   * @return The current value.
   * @throws IOException When the value is faulty.
   * @throws InterruptedException When the job is aborted.
   */
  public Result getCurrentValue() throws IOException, InterruptedException {
    return value;
  }

  /**
   * Positions the record reader to the next record.
   *
   * @return true if there was another record.
   * @throws IOException When reading the record failed.
   * @throws InterruptedException When the job was aborted.
   */
  public boolean nextKeyValue() throws IOException, InterruptedException {
    if (key == null) key = new ImmutableBytesWritable();
    if (value == null) value = new Result();
    try {
      try {
        value = this.scanner.next();
        if (value != null && value.isStale()) numStale++;
        if (logScannerActivity) {
          rowcount ++;
          if (rowcount >= logPerRowCount) {
            long now = System.currentTimeMillis();
            LOG.info("Mapper took " + (now-timestamp)
              + "ms to process " + rowcount + " rows");
            timestamp = now;
            rowcount = 0;
          }
        }
      } catch (IOException e) {
        // do not retry if the exception tells us not to do so
        if (e instanceof DoNotRetryIOException) {
          throw e;
        }
        // try to handle all other IOExceptions by restarting
        // the scanner, if the second call fails, it will be rethrown
        LOG.info("recovered from " + StringUtils.stringifyException(e));
        if (lastSuccessfulRow == null) {
          LOG.warn("We are restarting the first next() invocation," +
              " if your mapper has restarted a few other times like this" +
              " then you should consider killing this job and investigate" +
              " why it's taking so long.");
        }
        if (lastSuccessfulRow == null) {
          restart(scan.getStartRow());
        } else {
          restart(lastSuccessfulRow);
          scanner.next();    // skip presumed already mapped row
        }
        value = scanner.next();
        if (value != null && value.isStale()) numStale++;
        numRestarts++;
      }
      if (value != null && value.size() > 0) {
        key.set(value.getRow());
        lastSuccessfulRow = key.get();
        return true;
      }

      updateCounters();
      return false;
    } catch (IOException ioe) {
      if (logScannerActivity) {
        long now = System.currentTimeMillis();
        LOG.info("Mapper took " + (now-timestamp)
          + "ms to process " + rowcount + " rows");
        LOG.info(ioe);
        String lastRow = lastSuccessfulRow == null ?
          "null" : Bytes.toStringBinary(lastSuccessfulRow);
        LOG.info("lastSuccessfulRow=" + lastRow);
      }
      throw ioe;
    }
  }

  /**
   * If hbase runs on new version of mapreduce, RecordReader has access to
   * counters thus can update counters based on scanMetrics.
   * If hbase runs on old version of mapreduce, it won't be able to get
   * access to counters and TableRecorderReader can't update counter values.
   * @throws IOException
   */
  private void updateCounters() throws IOException {
    ScanMetrics scanMetrics = scanner.getScanMetrics();
    if (scanMetrics == null) {
      return;
    }

    updateCounters(scanMetrics, numRestarts, getCounter, context, numStale);
  }

  protected static void updateCounters(ScanMetrics scanMetrics, long numScannerRestarts,
      Method getCounter, TaskAttemptContext context, long numStale) {
    // we can get access to counters only if hbase uses new mapreduce APIs
    if (getCounter == null) {
      return;
    }

    try {
      for (Map.Entry<String, Long> entry:scanMetrics.getMetricsMap().entrySet()) {
        Counter ct = (Counter)getCounter.invoke(context,
            HBASE_COUNTER_GROUP_NAME, entry.getKey());

        ct.increment(entry.getValue());
      }
      ((Counter) getCounter.invoke(context, HBASE_COUNTER_GROUP_NAME,
          "NUM_SCANNER_RESTARTS")).increment(numScannerRestarts);
      ((Counter) getCounter.invoke(context, HBASE_COUNTER_GROUP_NAME,
          "NUM_SCAN_RESULTS_STALE")).increment(numStale);
    } catch (Exception e) {
      LOG.debug("can't update counter." + StringUtils.stringifyException(e));
    }
  }

  /**
   * The current progress of the record reader through its data.
   *
   * @return A number between 0.0 and 1.0, the fraction of the data read.
   */
  public float getProgress() {
    // Depends on the total number of tuples
    return 0;
  }

}


text:
import Ember from 'ember';

const computed = Ember.computed;
const observer = Ember.observer;
const get = Ember.get;
const run = Ember.run;

export default Ember.Component.extend({
  classNames: ['ember-tether-tooltip'],
  target: null,
  position: null,
  content: null,
  classes: 'ember-tether-tooltip-content',

  tooltipTarget: computed('target', function() {
    let t = get(this, 'target');
    if (Ember.View.detectInstance(t)) {
      t = t.element;
    } else if (Ember.$(t)) {
      t = Ember.$(t)[0];
    }
    return t;
  }),

  tooltipContent: computed('content', function() {
    let c = get(this, 'content');
    if (get(this, 'template') && this.element) {
      c = this.element.innerHTML;
    }
    return c;
  }),

  toggle: function() {
    this._tetherTooltip.toggle();
  },

  didInsertElement: function() {
    this.addTetherTooltip();
  },

  willDestroyElement: function() {
    var tetherTooltip = this._tetherTooltip;
    run.schedule('render', () => {
      this.removeTetherTooltip(tetherTooltip);
    });
  },

  tetherTooltipDidChange: observer(
    'target',
    'position',
    'content',
    'classes',
    function() {
      var tetherTooltip = this._tetherTooltip;
      run.schedule('render', () => {
        this.removeTetherTooltip(tetherTooltip);
        this.addTetherTooltip();
      });
    }
  ),

  addTetherTooltip: function() {
    this._tetherTooltip = new Tooltip(this._tetherTooltipOptions());
  },

  removeTetherTooltip: function(tetherTooltip) {
    tetherTooltip.destroy();
  },

  _tetherTooltipOptions: function() {
    const options = {
      target: get(this, 'tooltipTarget') ,
      content: get(this, 'tooltipContent')
    };

    [ 'position',
      'classes'
    ].forEach((k) => {
      const v = get(this, k);
      if (!Ember.isNone(v)) {
        options[k] = v;
      }
    });
    return options;
  }
});


text:
//  Copyright © 2021 650 Industries. All rights reserved.

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

typedef void (^ABI42_0_0EXUpdatesErrorBlock) (NSError *error);
typedef void (^ABI42_0_0EXUpdatesSuccessBlock) (NSDictionary * _Nullable manifest);
typedef void (^ABI42_0_0EXUpdatesProgressBlock) (NSUInteger successfulAssetCount, NSUInteger failedAssetCount, NSUInteger totalAssetCount);
/**
 * Called when a manifest has been downloaded. The return value indicates whether or not to
 * continue downloading the update described by this manifest. Returning `NO` will abort the
 * load, and the success block will be immediately called with a nil `manifest`.
 */
typedef BOOL (^ABI42_0_0EXUpdatesManifestBlock) (NSDictionary *manifest);

/**
 * Protocol for modules that depend on expo-updates for loading production updates but do not want
 * to depend on expo-updates or delegate control to the singleton ABI42_0_0EXUpdatesAppController.
 */
@protocol ABI42_0_0EXUpdatesExternalInterface

@property (nonatomic, weak) id bridge;

- (NSURL *)launchAssetURL;

- (void)reset;

- (void)fetchUpdateWithConfiguration:(NSDictionary *)configuration
                          onManifest:(ABI42_0_0EXUpdatesManifestBlock)manifestBlock
                            progress:(ABI42_0_0EXUpdatesProgressBlock)progressBlock
                             success:(ABI42_0_0EXUpdatesSuccessBlock)successBlock
                               error:(ABI42_0_0EXUpdatesErrorBlock)errorBlock;

@end

NS_ASSUME_NONNULL_END


text:
module App.Input where

import Graphics.UI.GLFW
import Control.Monad

{- Defining -}
data InputState = InputState { _keysPressed         :: [Key]
                             , _mousePosition       :: (Double, Double)
                             , _mouseButtonsPressed :: [MouseButton]
                             , _windowSize          :: (Int, Int)
                             } deriving (Show, Eq )

data InputEvent = KeyButtonDown Key
                | KeyButtonUp Key
                | MouseButtonDown MouseButton
                | MouseButtonUp MouseButton
                | MouseMovedTo (Double, Double)
                | WindowSizeChangedTo (Int, Int)
                deriving (Show, Eq)

data Input = Input { _inputState :: InputState
                   , _inputEvents       :: [InputEvent]
                   } deriving (Show, Eq)

emptyInput :: Input
emptyInput = Input { _inputEvents = []
                   , _inputState = emptyInputState
                   }

emptyInputState :: InputState
emptyInputState = InputState { _keysPressed = []
                             , _mousePosition = (0,0)
                             , _mouseButtonsPressed = []
                             , _windowSize = (0,0)
                             }

{- Events -}
-- | Returns the current input state and any input events that occurred
-- between the current and previous states.
getInput :: Window   -- ^ The window.
         -> Input    -- ^ The previous input state.
         -> IO Input -- ^ The new input state and any input events.
getInput win (Input s _) = do
    pollEvents
    (keys, buttons, position, (w, h)) <- getCurrentInput win
    let events'     = keyEvents++buttonEvents++moveEvents++winEvents
        keyEvents   = getKeyEventsBetween (_keysPressed s) keys
        buttonEvents= getButtonEventsBetween (_mouseButtonsPressed s) buttons
        moveEvents  = [ MouseMovedTo position | position /= _mousePosition s ]
        winEvents   = if winSize == _windowSize s then [] else [WindowSizeChangedTo winSize]
        winSize     = (fromIntegral w, fromIntegral h)
    return $ Input (InputState keys position buttons winSize) events'

getKeyEventsBetween :: [Key] -> [Key] -> [InputEvent]
getKeyEventsBetween = makeEventsBetween (KeyButtonDown, KeyButtonUp)

getButtonEventsBetween :: [MouseButton] -> [MouseButton] -> [InputEvent]
getButtonEventsBetween = makeEventsBetween (MouseButtonDown, MouseButtonUp)

makeEventsBetween :: Eq a1 => (a1 -> a, a1 -> a) -> [a1] -> [a1] -> [a]
makeEventsBetween (addC, removeC) from to = fmap addC added ++ fmap removeC removed
    where added   = [ x | x <- from++to, x `notElem` from, x `elem` to ]
          removed = [ x | x <- from++to, x `notElem` to, x `elem` from ]

getCurrentInput :: Window -> IO ([Key], [MouseButton], (Double, Double), (Int, Int))
getCurrentInput w = do
    buttons  <- getButtonsPressed w
    position <- getCursorPos w
    keys     <- getKeysPressed w
    winSize  <- getWindowSize w
    return (keys, buttons, position, winSize)

getButtonsPressed :: Window -> IO [MouseButton]
getButtonsPressed w = listOfPolledInputPressed (mouseButtonIsPressed w) mouseButtonsUsed

mouseButtonIsPressed :: Window -> MouseButton -> IO Bool
mouseButtonIsPressed w = fmap (==MouseButtonState'Pressed) . getMouseButton w

getKeysPressed :: Window -> IO [Key]
getKeysPressed w = listOfPolledInputPressed (keyIsPressed w) keysUsed

keyIsPressed :: Window -> Key -> IO Bool
keyIsPressed w = fmap (\k -> k == KeyState'Pressed || k == KeyState'Repeating) . getKey w

listOfPolledInputPressed :: Show a => (a -> IO Bool) -> [a] -> IO [a]
listOfPolledInputPressed fPoll = foldM (\acc a -> do
    isPressed <- fPoll a
    return $ if isPressed
             then a:acc
             else acc) []

keysUsed :: [Key]
keysUsed = addKey Key'Space []
    where addKey Key'Menu ks = Key'Menu:ks
          addKey key      ks = addKey (succ key) (key:ks)

mouseButtonsUsed :: [MouseButton]
mouseButtonsUsed = [ MouseButton'1 ]


text:
<?cs include:"doctype.cs" ?>
<?cs include:"macros.cs" ?>
<?cs set:resources="true" ?>

<?cs include:"head_tag.cs" ?>
<?cs include:"header.cs" ?>

<?cs var:page.title ?>

The file containing the source code shown below is located in the corresponding directory in <sdk>/platforms/android-<version>/samples/...

<?cs var:fileContents ?>

<?cs include:"footer.cs" ?>

<?cs include:"trailer.cs" ?>


text:
<?php

namespace frontend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\AkkProgramJurulatih;

/**
 * AkkProgramJurulatihSearch represents the model behind the search form about `app\models\AkkProgramJurulatih`.
 */
class AkkProgramJurulatihSearch extends AkkProgramJurulatih
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['akk_program_jurulatih_id', 'peningkatan_kerjaya_jurulatih_id'], 'integer'],
            [['nama_program', 'tarikh_program', 'tempat_program', 'kod_kursus', 'tahap', 'jurulatih'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = AkkProgramJurulatih::find()
                ->joinWith(['refAkkProgramJurulatihPeserta']);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'akk_program_jurulatih_id' => $this->akk_program_jurulatih_id,
            'peningkatan_kerjaya_jurulatih_id' => $this->peningkatan_kerjaya_jurulatih_id,
            //'tarikh_program' => $this->tarikh_program,
        ]);

        $query->andFilterWhere(['like', 'nama_program', $this->nama_program])
            ->andFilterWhere(['like', 'tempat_program', $this->tempat_program])
            ->andFilterWhere(['like', 'kod_kursus', $this->kod_kursus])
            ->andFilterWhere(['like', 'tahap', $this->tahap])
                ->andFilterWhere(['like', 'tarikh_program', $this->tarikh_program])
                ->andFilterWhere(['like', 'tbl_akk_program_jurulatih_peserta.jurulatih', $this->jurulatih]);

        return $dataProvider;
    }
}


text:
We renamed this module to [@webex/react-redux-spark-metrics](https://www.npmjs.com/package/@webex/react-redux-spark-metrics). Please install it instead.

## License

© 2016-2020 Cisco and/or its affiliates. All Rights Reserved.


text:
class EffectivePagesRoutingConstraint
  def self.matches?(request)
    id = request.path_parameters[:id] || '/'
    Effective::Page.find(id).present? rescue false
  end
end

EffectivePages::Engine.routes.draw do
  scope :module => 'effective' do
    scope '/edit' do
      get '(/*id)' => "pages#edit", :as => :edit_effective_page
      put '(/*id)' => 'pages#update', :as => :update_effective_page
    end

    get '*id' => "pages#show", :constraints => EffectivePagesRoutingConstraint, :as => :effective_page
  end
end


text:
fixture.exe: fixture.cpp
	g++ -o fixture.exe fixture.cpp


text:
Sitio web de la Asociación de Robótica (ASROB) UC3M

Web alojada actualmente en http://asrob-uc3m.github.io

Author original de esta plantilla actual: [David Estevez](https://github.com/David-Estevez)

## Cómo servir en localhost

Es útil servir en `localhost` para modificar el sitio web y ver los cambios localmente.

1. Desde la raíz del proyecto, ejecuta el siguiente comando (que es universal para todos los proyectos basados en [jekyll](https://jekyllrb.com/)):

   ```bash
   bundle exec jekyll serve
   ```

1. Ahora puedes navegar por el sitio en la ubicación predeterminada: http://127.0.0.1:4000

## Cómo subir cambios a GitHub

Este proyecto se gestiona como cualquier proyecto en [GitHub](https://www.github.com). Puedes usar [Git](https://git-scm.com) o incluso la interfaz web de GitHub, en las que puede encontrar muchos tutoriales en línea. Los siguientes puntos son específicos del mecanismo [GitHub Pages](https://pages.github.com) utilizado y su [configuración actual](https://github.com/corolab/corolab.github.io/settings) :

1. **No subas** la carpeta `_site/` ni el archivo `Gemfile.lock`. Se generan automáticamente de forma local y lo mismo debería suceder en los servidores de las páginas de GitHub.

1. Es seguro `git push` a cualquier rama upstream, pero recuerda que lo que está en `master` es lo que realmente se renderizará como el sitio web.

## Cómo editar la web

Esta sección contiene la información necesaria para añadir o modificar contenidos
de la web.

### Configurando la información de la web

El archivo `_config.yml` contiene los parámateros básicos de configuración de la
web, así como otros parámetros avanzados.

#### Configuración básica

El apartado `society` contiene la información básica sobre la asociación:

 * `name`: nombre completo de la asociación
 * `short_name`: nombre corto o siglas de la asociación
 * `email`: email de contacto

#### Configuración de Redes Sociales

El apartado `society.social` contiene la información sobre las distintas redes
sociales de la asociación. En él se pueden eliminar o añadir nuevas redes sociales.

Una red social tiene los siguientes parámetros:

 * `id`: identificador de la red social (google-plus, flickr, dribbble, pinterest,
    instagram, tumblr, linkedin, etc). Para el correo usaremos `envelope`.
 * `name`: nombre de la red social.
 * `url`: url al perfil de la asociación en dicha red social.

#### Configuración de Responsables

El apartado `society.management` contiene la información sobre los distintos
responsables de la asociación. En él se pueden modificar los responsables. Cada
responsable tiene un nombre, un correo de contacto y un link a una web de su
elección asociados.

El apartado `society.management.social` corresponde a los Responsables de Redes
Sociales, y puede contener más de una entrada.

#### Configuración de la sección *Enlaces importantes*

El apartado `more_info` contiene la información de la sección *Enlaces importantes*
de la web. En caso de que hubiese que añadir, eliminar o modificar algún enlace,
basta con editar esta sección. Cada enlace tiene los siguientes parámetros:

 * `title`: título del enlace.
 * `description`: texto que acompaña al enlace.
 * `url`: url del enlace.
 * `picture`: imagen que acompaña al enlace. Lo ideal es que esta imagen sea de
 **318x180px** para mantener la estética de la web.

#### Configuración de la sección *Más enlaces importantes*

El apartado `other_info` contiene la información de la sección *Más enlaces importantes*
de la web. En caso de que hubiese que añadir, eliminar o modificar algún enlace,
basta con editar esta sección. Cada enlace tiene los siguientes parámetros:

 * `name`: título del enlace.
 * `url`: url del enlace.

#### Configuración de colaboradores

El apartado `collaborations` contiene la información de las entidades que colaboran
con la asociación. En caso de que hubiese que añadir, eliminar o modificar algún
colaborador, basta con editar esta sección. Cada colaborador tiene los siguientes parámetros:

 * `name`: nombre del colaborador.
 * `url`: enlace a la web del colaborador.
 * `picture`: logo del colaborador.

### Modificar *About*

La sección *About* muestra información genérica sobre la asociación. Esta información
se encuentra en el archivo `_posts/2017-05-27-about.markdown` en formato markdown.

### Añadir o modificar *grupos de trabajo*

La información sobre los *grupos de trabajo* se almacena en archivos markdown en
 las carpetas `_workgroups` (para *grupos de trabajo activos*) o `_old_workgroups`
  (para *antiguos grupos de trabajo*). A cada *grupo de trabajo* le corresponde un
archivo. Dentro de cada archivo encontramos una serie de parámetros que modificar
para modificar la información del *grupo de trabajo*:

  * `type`: tipo de archivo (**no modificar**, debe ser `workgroup`).
  * `layout`: plantilla que se le aplicará a este archivo (**no modificar**, debe
    ser `workgroup`).
  * `workgroup_id`: nombre corto, en minúsculas y sin espacios que designa a este
    grupo. Si se necesitan varias palabras es recomendable separarlas con `_`
    (por ejemplo: `printer_one`).
  * `name`: nombre del grupo. Si el grupo tiene siglas, este sería un buen sitio
    para ponerlas (por ejemplo: `G.A.M.E`).
  * `subtitle`: pequeña descripción del grupo (una línea máximo). Si el grupo tiene
    siglas, este sería un buen sitio para poner lo que significan (por ejemplo:
    `Group for Arcade Machine Experimentation`) [opcional].
  * `description`: descripción breve (un párrafo) que aparecerá en la portada de
    la web.
  * `url_wiki`: enlace a la página correpondiente al *grupo de trabajo activo*
  en la wiki [opcional].
  * `url_telegram,`: enlace al grupo de telegram del *grupo de trabajo activo*
  [opcional].
  * `url_playlist`: enlace a la lista de reproducciones de YouTube del *grupo de trabajo activo*
  [opcional].
  * `picture`: thumbnail que aparecerá en la portada de la web. Lo ideal es que
  esta imagen sea de **700x300px** para mantener la estética de la web.
  * `picture_full`: imagen que aparecerá en la página de dicho grupo. Lo ideal es
  que esta imagen sea de **750x500px** para mantener la estética de la web.
  * `manager`: nombre del responsable del *grupo de trabajo activo*.
  * `manager_email`: email del responsable del *grupo de trabajo activo*.
  * `keys_info`: información acerca de quién tiene qué llaves dentro del *grupo de trabajo activo*.
  * `next_meeting`: información sobre la próxima reunión del *grupo de trabajo
  activo*. Por ejemplo: "Miércoles 4 a las 17h en aula 1.0.B06" o "Todos los
  Martes de 15:00 a 16:00 en 1.0.B06" [opcional].
  * `next_meeting_doodle`: link al doodle para decidir el horario del *grupo de
  trabajo activo* [opcional].
  * `active`: indica si el *grupo de trabajo* está activo o no (true o false).

La descripción completa del grupo, que aparecerá en la página de dicho grupo, se
incluye como texto en formato markdown después de la zona reservada a los parámetros.

### Añadir o modificar *proyectos*

La información sobre los *proyectos* se almacena en la carpeta
`_projects` en archivos markdown. A cada proyecto le corresponde un
archivo. Dentro de cada archivo encontramos una serie de parámetros que modificar
para modificar la información del *proyecto*:

 * `type`: tipo de archivo (**no modificar**, debe ser `project`).
 * `layout`: plantilla que se le aplicará a este archivo (**no modificar**, debe
  ser `project`).
 * `parent`: *grupo de trabajo activo* al que pertenece el proyecto. El valor
  debe coincidir con el valor del `workgroup_id` de algún *grupo de trabajo activo*.
 * `name`: nombre del proyecto.
 * `subtitle`: pequeña descripción del grupo (una línea máximo).
 * `description`: descripción corta (un párrafo) que aparecerá en la página del
  *grupo de trabajo activo*.
 * `url_wiki`: enlace a la página correspondiente al *proyecto* en la wiki. [opcional]
 * `url_github`: enlace al repositorio del *proyecto* en GitHub. [opcional]
 * `picture`: thumbnail que aparecerá en la página del *grupo de trabajo activo*.
  Lo ideal es que esta imagen sea de **318x180px** para mantener la estética de
  la web.
 * `picture_full`: imagen que aparecerá en la página de dicho proyecto. Lo ideal
  es que esta imagen sea de **900x300px** para mantener la estética de la web.
 * `status`: estado del proyecto. Los valores posibles son: "activo", "terminado",
 "abandonado" o "proyecto futuro".

 La descripción completa del proyecto, que aparecerá en la página de dicho
 proyecto, se incluye como texto en formato markdown después de la zona reservada
 a los parámetros.

### Añadir o modificar *noticias*

La información sobre los *noticias* se almacena en la carpeta
`_news` en archivos markdown. A cada noticia le corresponde un
archivo. Aunque por el momento sólo aparece el titular de la noticia en la portada
de la web, en el futuro se podrá redactar una noticia completa y visualizarla en
la web. Dentro de cada archivo encontramos una serie de parámetros que modificar
para modificar la información de la noticia:

 * `type`: tipo de archivo (**no modificar**, debe ser `news`).
 * `title`: título de la noticia.
 * `description`: breve descripción de la noticia (una línea máximo).
 * `picture`: imagen que aparecerá en la portada de la web. Lo ideal es que
 esta imagen sea de **1280x720px** para mantener la estética de la web.

### Añadir o modificar *premios y trofeos*

La información sobre los *premios y trofeos* se almacena en la carpeta
`_awards` en archivos markdown. A cada premio le corresponde un
archivo. Dentro de cada archivo encontramos una serie de parámetros que modificar
para modificar la información del premio:

 * `name`: Nombre del premio o competición.
 * `date`: Fecha en la que fue concedido el premio.
 * `place`: Puesto o posición en la competición.
 * `link`: Enlace a la web del premio o competición.
 * `team`: Incluye los miembros del equipo al que le fue concedido el premio.
 cada miembro tiene los siguiente parámetros:
    * `name`: nombre del miembro.
    * `link`: link  a una web del miembro [opcional].

La descripción el premio o competición, que aparecerá en la página de premios y
trofeos, se incluye como texto en formato markdown después de la zona reservada
a los parámetros.

### Redirecciones a Doodle

Es posible generar una página fija que redireccione al Doodle semanal que se ha configurado para cierto *grupo de trabajo activo*. Para ello, hay que añadir un archivo markdown a la carpeta `_redirects`, que contenga los siguientes parámetros:

* `workgroup_id`: *grupo de trabajo activo* al que pertenece el proyecto. El valor
 debe coincidir con el valor del `workgroup_id` de algún *grupo de trabajo activo*.
* `layout`: plantilla que se le aplicará a este archivo (**no modificar**, debe
 ser `redirect_to_doodle`).

## Atribuciones

Esta web se inspiró en las siguientes plantillas:

 * [1 Col Portfolio](https://blackrockdigital.github.io/startbootstrap-1-col-portfolio/)
 * [Portfolio Item](https://blackrockdigital.github.io/startbootstrap-portfolio-item/)
 * [One Page Wonder](https://startbootstrap.com/template-overviews/one-page-wonder/)


text:
module TweetToToot
  class Runner
    attr_accessor :handles, :sleep_time, :logger

    def initialize(mastodon, twitter, handles = nil, sleep_time = 3600)
      @mastodon   = mastodon
      @twitter    = twitter
      @handles    = ENV["TWITTER_HANDLES_TO_TOOT"].split(", ")
      @sleep_time = sleep_time
      @logger     = Logger.new(STDOUT)
    end

    def format_message(handle, text)
      "@#{handle}: #{text.gsub(/\n/, " ")}\n#{ENV["HASHTAGS"]}"
    end

    # The main worker method
    def run
      begin
        loop do
          handles.each do |handle|
            @twitter.tweets_for(handle).each do |tweet|
              message = format_message(handle, tweet.text)

              @mastodon.toot(message)

              logger.info "Tooted: #{message.gsub(/\n/, " ")}"
            end
          end

          sleep sleep_time
        end
      rescue Exception
        # Persist the last tweets we tooted
        @twitter.save_last_tweets
        logger.info "Interrupted, saving last tweets..."
      end
    end
  end
end


text:
import { List, Map } from 'immutable'

const handlers = {}

// See: https://github.com/cognitect/transit-js/wiki/Getting-Started#reading-custom-types
export function addTransitReadHandler (tag, handler) {
  handlers[tag] = handler
}

export default {
  handlers,
  // See: https://github.com/cognitect/transit-js/wiki/Getting-Started#customizing-map--array-decoding
  arrayBuilder: {
    init (node) { return List().asMutable() },
    add (ret, val, node) { return ret.push(val) },
    finalize (ret, node) { return ret.asImmutable() },
    fromArray (arr, node) { return List.from(arr) }
  },
  mapBuilder: {
    init (node) { return Map().asMutable() },
    add (ret, key, val, node) { return ret.set(key, val) },
    finalize (ret, node) { return ret.asImmutable() }
  }
}


text:
using System.Collections.Generic;
using System.Linq;
using GZipTest.Application.Commands;
using GZipTest.Application.Compression;
using GZipTest.Application.Context;
using GZipTest.Application.Files;
using GZipTest.Application.Interfaces;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace GZipTestTests.Application.Commands
{
    [TestClass]
    public class DecompressChunkCommandTests
    {
        [TestMethod]
        public void TestDecompressOneChunk()
        {
            var originalBytes = new List<byte>()
                .Concat(Constants.GZipDefaultHeader)
                .Concat(new byte[] {0x00, 0x01, 0x02}).ToArray();

            var compressor = new GZipCompressor();
            var inputHolder = new FileChunkHolder();
            var outputHolder = new FileChunkHolder();

            inputHolder.Add(0, originalBytes);
            Assert.AreEqual(1, inputHolder.Count());
            Assert.AreEqual(0, outputHolder.Count());

            var command = new DecompressChunkCommand(0, inputHolder, outputHolder, compressor);
            command.Execute();

            Assert.AreEqual(0, inputHolder.Count());
            Assert.AreEqual(1, outputHolder.Count());
            CollectionAssert.AreEqual(new byte[0], outputHolder.Get(0));
        }

        [TestMethod]
        public void TestDecompressSeveralChunks()
        {
            var originalByteChunks = new List<byte[]>(3)
            {
                new List<byte>().Concat(Constants.GZipDefaultHeader).Concat(new byte[] {0x00, 0x01, 0x02}).ToArray(),
                new List<byte>().Concat(Constants.GZipDefaultHeader).Concat(new byte[] {0x05, 0x06, 0x07}).ToArray(),
                new List<byte>().Concat(Constants.GZipDefaultHeader).Concat(new byte[] {0x0A, 0x0B, 0x0C}).ToArray()
            };

            var compressor = new GZipCompressor();
            var inputHolder = new FileChunkHolder();
            var outputHolder = new FileChunkHolder();

            inputHolder.Add(0, originalByteChunks[0]);
            inputHolder.Add(1, originalByteChunks[1]);
            inputHolder.Add(2, originalByteChunks[2]);
            Assert.AreEqual(originalByteChunks.Count, inputHolder.Count());
            Assert.AreEqual(0, outputHolder.Count());

            var commands = new List<ICommand>(3)
            {
                new DecompressChunkCommand(0, inputHolder, outputHolder, compressor),
                new DecompressChunkCommand(1, inputHolder, outputHolder, compressor),
                new DecompressChunkCommand(2, inputHolder, outputHolder, compressor)
            };
            foreach (var command in commands)
                command.Execute();

            Assert.AreEqual(0, inputHolder.Count());
            Assert.AreEqual(originalByteChunks.Count, outputHolder.Count());
            CollectionAssert.AreEqual(new byte[0], outputHolder.Get(0));
            CollectionAssert.AreEqual(new byte[0], outputHolder.Get(1));
            CollectionAssert.AreEqual(new byte[0], outputHolder.Get(2));
        }
    }
}


text:
"""
Build and execute metaquast command for a run folder over contig files that
match a given pattern.
"""

from __future__ import print_function

import sys
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter as ADHF
from fnmatch import fnmatch
from os import path, walk
from subprocess import check_call

def find(pattern, folder):
    result = []
    for root, dirs, files in walk(folder):
        for name in files:
            if fnmatch(name, pattern):
                result.append(path.join(root, name))
    return result

def main(folder, ref, output_dir, contig_thresholds, min_contig, pattern, threads):
    # find the files
    contigs = find(pattern, folder)

    # in case this gets run in the wrong directory
    if len(contigs) < 1:
        sys.exit("No contig files were found using %s." % pattern)
    elif len(contigs) > 50:
        sys.exit("Found too many contig files to run quast.")

    # build the labels
    # assumes file names are separated by '_' and sample name comes first
    sep = '_'
    labels = [path.basename(c).split(sep, 1)[0] for c in contigs]

    # run metaquast
    cmd = ("quast.py -f -o {out} -R {ref} -M {min_contig} -T {cpus} "
        "-l {labels} -t {thresholds} {fastas}").format(out=output_dir,
        ref=ref, min_contig=min_contig, cpus=threads, labels=','.join(labels),
        thresholds=contig_thresholds, fastas=' '.join(contigs))
    check_call(cmd, shell=True)

    # combine reports into single tsv
    combined_report = path.join(output_dir, 'report_combined.tsv')
    report = path.join(output_dir, 'report.tsv')
    misassembly_report = path.join(output_dir, 'contigs_reports', 'misassemblies_report.tsv')
    unaligned_report = path.join(output_dir, 'contigs_reports', 'unaligned_report.tsv')

    with open(combined_report, 'w') as com_rep, open(report, 'r') as rep:

        [print(line.strip("\r\n"), file=com_rep) for line in rep]

        if path.exists(misassembly_report):
            with open(misassembly_report, 'r') as mis_rep:
                [print(line.strip("\r\n"), file=com_rep) for i, line in enumerate(mis_rep) if i > 0]

        if path.exists(unaligned_report):
            with open(unaligned_report, 'r') as una_rep:
                [print(line.strip("\r\n"), file=com_rep) for i, line in enumerate(una_rep) if i > 0]

if __name__ == '__main__':
    p = ArgumentParser(description=__doc__, formatter_class=ADHF)
    p.add_argument('folder',
        help='a parent directory containing contig fastas within its tree')
    p.add_argument('ref', help='reference fasta')
    p.add_argument('-o', '--output-dir', default='quast',
        help='quast output directory')
    p.add_argument('--contig-thresholds', default='2000,3000,5000',
        help='contig length thresholds')
    p.add_argument('--min-contig', default=2000,
        help='lower threshold for contig length')
    # might be more useful if this accepted multiple patterns
    p.add_argument('-p', '--pattern', default='*all_contigs.fasta',
        help='file search pattern to use from input-dir')
    p.add_argument('--threads', default=10, help='processing threads')
    args = vars(p.parse_args())
    main(**args)


text:
namespace content {

ServiceWorkerRegistration::ServiceWorkerRegistration(const GURL& pattern,
                                                     const GURL& script_url,
                                                     int64 registration_id)
    : pattern_(pattern),
      script_url_(script_url),
      registration_id_(registration_id),
      is_shutdown_(false) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
}

ServiceWorkerRegistration::~ServiceWorkerRegistration() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  DCHECK(is_shutdown_);
}

void ServiceWorkerRegistration::Shutdown() {
  DCHECK(!is_shutdown_);
  if (active_version_)
    active_version_->Shutdown();
  active_version_ = NULL;
  if (pending_version_)
    pending_version_->Shutdown();
  pending_version_ = NULL;
  is_shutdown_ = true;
}

ServiceWorkerRegistrationInfo ServiceWorkerRegistration::GetInfo() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  return ServiceWorkerRegistrationInfo(
      script_url(),
      pattern(),
      active_version_ ? active_version_->GetInfo() : ServiceWorkerVersionInfo(),
      pending_version_ ? pending_version_->GetInfo()
                       : ServiceWorkerVersionInfo());
}

void ServiceWorkerRegistration::ActivatePendingVersion() {
  active_version_->SetStatus(ServiceWorkerVersion::DEACTIVATED);
  active_version_->Shutdown();
  active_version_ = pending_version_;
  // TODO(kinuko): This should be set to ACTIVATING until activation finishes.
  active_version_->SetStatus(ServiceWorkerVersion::ACTIVE);
  pending_version_ = NULL;
}

}  // namespace content


text:
/*
 * Probing flash chips with QINFO records.
 * (C) 2008 Korolev Alexey <akorolev@infradead.org>
 * (C) 2008 Vasiliy Leonenko <vasiliy.leonenko@gmail.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/interrupt.h>

#include <linux/mtd/xip.h>
#include <linux/mtd/map.h>
#include <linux/mtd/pfow.h>
#include <linux/mtd/qinfo.h>

static int lpddr_chip_setup(struct map_info *map, struct lpddr_private *lpddr);
struct mtd_info *lpddr_probe(struct map_info *map);
static struct lpddr_private *lpddr_probe_chip(struct map_info *map);
static int lpddr_pfow_present(struct map_info *map,
			struct lpddr_private *lpddr);

static struct qinfo_query_info qinfo_array[] = {
	/* General device info */
	{0, 0, "DevSizeShift", "Device size 2^n bytes"},
	{0, 3, "BufSizeShift", "Program buffer size 2^n bytes"},
	/* Erase block information */
	{1, 1, "TotalBlocksNum", "Total number of blocks"},
	{1, 2, "UniformBlockSizeShift", "Uniform block size 2^n bytes"},
	/* Partition information */
	{2, 1, "HWPartsNum", "Number of hardware partitions"},
	/* Optional features */
	{5, 1, "SuspEraseSupp", "Suspend erase supported"},
	/* Operation typical time */
	{10, 0, "SingleWordProgTime", "Single word program 2^n u-sec"},
	{10, 1, "ProgBufferTime", "Program buffer write 2^n u-sec"},
	{10, 2, "BlockEraseTime", "Block erase 2^n m-sec"},
	{10, 3, "FullChipEraseTime", "Full chip erase 2^n m-sec"},
};

static long lpddr_get_qinforec_pos(struct map_info *map, char *id_str)
{
	int qinfo_lines = sizeof(qinfo_array)/sizeof(struct qinfo_query_info);
	int i;
	int bankwidth = map_bankwidth(map) * 8;
	int major, minor;

	for (i = 0; i < qinfo_lines; i++) {
		if (strcmp(id_str, qinfo_array[i].id_str) == 0) {
			major = qinfo_array[i].major & ((1 << bankwidth) - 1);
			minor = qinfo_array[i].minor & ((1 << bankwidth) - 1);
			return minor | (major << bankwidth);
		}
	}
	printk(KERN_ERR"%s qinfo id string is wrong! \n", map->name);
	BUG();
	return -1;
}

static uint16_t lpddr_info_query(struct map_info *map, char *id_str)
{
	unsigned int dsr, val;
	int bits_per_chip = map_bankwidth(map) * 8;
	unsigned long adr = lpddr_get_qinforec_pos(map, id_str);
	int attempts = 20;

	/* Write a request for the PFOW record */
	map_write(map, CMD(LPDDR_INFO_QUERY),
			map->pfow_base + PFOW_COMMAND_CODE);
	map_write(map, CMD(adr & ((1 << bits_per_chip) - 1)),
			map->pfow_base + PFOW_COMMAND_ADDRESS_L);
	map_write(map, CMD(adr >> bits_per_chip),
			map->pfow_base + PFOW_COMMAND_ADDRESS_H);
	map_write(map, CMD(LPDDR_START_EXECUTION),
			map->pfow_base + PFOW_COMMAND_EXECUTE);

	while ((attempts--) > 0) {
		dsr = CMDVAL(map_read(map, map->pfow_base + PFOW_DSR));
		if (dsr & DSR_READY_STATUS)
			break;
		udelay(10);
	}

	val = CMDVAL(map_read(map, map->pfow_base + PFOW_COMMAND_DATA));
	return val;
}

static int lpddr_pfow_present(struct map_info *map, struct lpddr_private *lpddr)
{
	map_word pfow_val[4];

	/* Check identification string */
	pfow_val[0] = map_read(map, map->pfow_base + PFOW_QUERY_STRING_P);
	pfow_val[1] = map_read(map, map->pfow_base + PFOW_QUERY_STRING_F);
	pfow_val[2] = map_read(map, map->pfow_base + PFOW_QUERY_STRING_O);
	pfow_val[3] = map_read(map, map->pfow_base + PFOW_QUERY_STRING_W);

	if (!map_word_equal(map, CMD('P'), pfow_val[0]))
		goto out;

	if (!map_word_equal(map, CMD('F'), pfow_val[1]))
		goto out;

	if (!map_word_equal(map, CMD('O'), pfow_val[2]))
		goto out;

	if (!map_word_equal(map, CMD('W'), pfow_val[3]))
		goto out;

	return 1;	/* "PFOW" is found */
out:
	printk(KERN_WARNING"%s: PFOW string at 0x%lx is not found \n",
					map->name, map->pfow_base);
	return 0;
}

static int lpddr_chip_setup(struct map_info *map, struct lpddr_private *lpddr)
{

	lpddr->qinfo = kmalloc(sizeof(struct qinfo_chip), GFP_KERNEL);
	if (!lpddr->qinfo) {
		printk(KERN_WARNING "%s: no memory for LPDDR qinfo structure\n",
				map->name);
		return 0;
	}
	memset(lpddr->qinfo, 0, sizeof(struct qinfo_chip));

	/* Get the ManuID */
	lpddr->ManufactId = CMDVAL(map_read(map, map->pfow_base + PFOW_MANUFACTURER_ID));
	/* Get the DeviceID */
	lpddr->DevId = CMDVAL(map_read(map, map->pfow_base + PFOW_DEVICE_ID));
	/* read parameters from chip qinfo table */
	lpddr->qinfo->DevSizeShift = lpddr_info_query(map, "DevSizeShift");
	lpddr->qinfo->TotalBlocksNum = lpddr_info_query(map, "TotalBlocksNum");
	lpddr->qinfo->BufSizeShift = lpddr_info_query(map, "BufSizeShift");
	lpddr->qinfo->HWPartsNum = lpddr_info_query(map, "HWPartsNum");
	lpddr->qinfo->UniformBlockSizeShift =
				lpddr_info_query(map, "UniformBlockSizeShift");
	lpddr->qinfo->SuspEraseSupp = lpddr_info_query(map, "SuspEraseSupp");
	lpddr->qinfo->SingleWordProgTime =
				lpddr_info_query(map, "SingleWordProgTime");
	lpddr->qinfo->ProgBufferTime = lpddr_info_query(map, "ProgBufferTime");
	lpddr->qinfo->BlockEraseTime = lpddr_info_query(map, "BlockEraseTime");
	return 1;
}
static struct lpddr_private *lpddr_probe_chip(struct map_info *map)
{
	struct lpddr_private lpddr;
	struct lpddr_private *retlpddr;
	int numvirtchips;

	if ((map->pfow_base + 0x1000) >= map->size) {
		printk(KERN_NOTICE"%s Probe at base (0x%08lx) past the end of"
				"the map(0x%08lx)\n", map->name,
				(unsigned long)map->pfow_base, map->size - 1);
		return NULL;
	}
	memset(&lpddr, 0, sizeof(struct lpddr_private));
	if (!lpddr_pfow_present(map, &lpddr))
		return NULL;

	if (!lpddr_chip_setup(map, &lpddr))
		return NULL;

	/* Ok so we found a chip */
	lpddr.chipshift = lpddr.qinfo->DevSizeShift;
	lpddr.numchips = 1;

	numvirtchips = lpddr.numchips * lpddr.qinfo->HWPartsNum;
	retlpddr = kmalloc(sizeof(struct lpddr_private) +
			numvirtchips * sizeof(struct flchip), GFP_KERNEL);
	if (!retlpddr)
		return NULL;

	memset(retlpddr, 0, sizeof(struct lpddr_private) +
				numvirtchips * sizeof(struct flchip));
	memcpy(retlpddr, &lpddr, sizeof(struct lpddr_private));

	retlpddr->numchips = numvirtchips;
	retlpddr->chipshift = retlpddr->qinfo->DevSizeShift -
				__ffs(retlpddr->qinfo->HWPartsNum);

	return retlpddr;
}

struct mtd_info *lpddr_probe(struct map_info *map)
{
	struct mtd_info *mtd = NULL;
	struct lpddr_private *lpddr;

	/* First probe the map to see if we havecan open PFOW here */
	lpddr = lpddr_probe_chip(map);
	if (!lpddr)
		return NULL;

	map->fldrv_priv = lpddr;
	mtd = lpddr_cmdset(map);
	if (mtd) {
		if (mtd->size > map->size) {
			printk(KERN_WARNING "Reducing visibility of %ldKiB chip"
				"to %ldKiB\n", (unsigned long)mtd->size >> 10,
				(unsigned long)map->size >> 10);
			mtd->size = map->size;
		}
		return mtd;
	}

	kfree(lpddr->qinfo);
	kfree(lpddr);
	map->fldrv_priv = NULL;
	return NULL;
}

static struct mtd_chip_driver lpddr_chipdrv = {
	.probe		= lpddr_probe,
	.name		= "qinfo_probe",
	.module		= THIS_MODULE
};

static int __init lpddr_probe_init(void)
{
	register_mtd_chip_driver(&lpddr_chipdrv);
	return 0;
}

static void __exit lpddr_probe_exit(void)
{
	unregister_mtd_chip_driver(&lpddr_chipdrv);
}

module_init(lpddr_probe_init);
module_exit(lpddr_probe_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Vasiliy Leonenko <vasiliy.leonenko@gmail.com>");
MODULE_DESCRIPTION("Driver to probe qinfo flash chips");


text:
import datetime
import json

from bunch import bunchify

from .exceptions import APIError

def _get_value(val):
    if isinstance(val, datetime.datetime):
        return val.isoformat()
    return val

class Resource(object):

    def __init__(self, api_client, store_id):
        self.store_id = store_id
        self._http_client = api_client

    def _make_request(self, resource, **kwargs):
        response = self._http_client.make_request(self.store_id, resource, **kwargs)

        if response.status_code not in [200, 201]:
            raise APIError('{}. {}'.format(response.reason, response.text),
                           response.status_code)
        return response

class ListResource(Resource):

    def get(self, id):
        return bunchify(json.loads(self._make_request(self.resource_name, resource_id=str(id)).content))

    def list(self, filters={}, fields={}):
        """
        Get the list of customers for a store.
        """
        extra = {k:_get_value(v) for k,v in filters.items()}
        if fields:
            extra['fields'] = fields
        return bunchify(json.loads(self._make_request(self.resource_name, extra=extra).content))

    def add(self, resource_dict):
        return bunchify(json.loads(self._make_request(self.resource_name, data=resource_dict, verb='post').text))

    def update(self, resource_update_dict):
        res_id = str(resource_update_dict['id'])
        return bunchify(json.loads(self._make_request(self.resource_name, resource_id=res_id, data=resource_update_dict, verb='put').text))

class ListSubResource(ListResource):

    def __init__(self, resource, resource_id, subresource):
        super(ListSubResource, self).__init__(resource._http_client, resource.store_id)
        self.resource_name = resource.resource_name
        self.resource_id = resource_id
        self.subresource = subresource

    def get(self, id):
        return bunchify(json.loads(self._make_request(
            self.resource_name,
            resource_id=str(self.resource_id),
            subresource=self.subresource,
            subresource_id=str(id)).content)
        )

    def list(self, filters={}, fields={}):
        """
        Get the list of customers for a store.
        """
        extra = {k:_get_value(v) for k,v in filters.items()}
        if fields:
            extra['fields'] = fields
        return bunchify(json.loads(self._make_request(
            self.resource_name,
            resource_id=str(self.resource_id),
            subresource=self.subresource,
            extra=extra).content)
        )

    def add(self, subresource_dict):
        raise NotImplementedError('Sub resource add is not yet supported.')

    def update(self, subresource_update_dict):
        raise NotImplementedError('Sub resource update is not yet supported.')


text:
var express = require('express');
var webhookServer = require('../lib/server')();

var port = process.env.PORT || 3000;

var app = express();

app.get('/', function (req, res) {
  res.send('Express response');
});

app.use('/webhook', webhookServer.mountAsMiddleware);

var server = app.listen(port, function () {
  console.log('Started on port ' + port);
});

webhookServer.on('ContentManagement.ContentType.publish', function (req) {
  console.log('A content type was published!');
});

webhookServer.on('ContentManagement.ContentType.unpublish', function (req) {
  console.log('A content type was unpublished!');
});

webhookServer.on('ContentManagement.Entry.publish', function (req) {
  console.log('An entry was published!');
});

webhookServer.on('ContentManagement.Entry.unpublish', function (req) {
  console.log('An entry was unpublished!');
});

webhookServer.on('ContentManagement.Asset.publish', function (req) {
  console.log('An asset was published!');
});

webhookServer.on('ContentManagement.Asset.unpublish', function (req) {
  console.log('An asset was unpublished!');
});


text: - Remove implicit Fix embedding in tests.


text:
/* Warning: This file is automatically generated by AX-RadioLAB.
	Manual changes are overwritten! */

#include "../COMMON/axradio.h"

const struct axradio_address __code remoteaddr = {
	{ 0x32, 0x34, 0x00, 0x00}
};
const struct axradio_address_mask __code localaddr = {
	{ 0x33, 0x34, 0x00, 0x00},
	{ 0x00, 0x00, 0x00, 0x00}
};

const uint8_t __code framing_insert_counter = 0;
const uint8_t __code framing_counter_pos = 6;

const uint16_t __code lposckfiltmax = 0x20c4;

const uint16_t __code lpxosc_settlingtime = 3000;


text:
 {-# LANGUAGE PackageImports #-}
  module GHC.IO.Handle.FD (module M) where
  import "base" GHC.IO.Handle.FD as M


text:
package org.apache.hadoop.hbase.client;

import org.apache.hadoop.hbase.classification.InterfaceAudience;

import java.io.IOException;

/**
 * A Callable<T> that will be retried.  If {@link #call(ResponseHandler)} invocation throws exceptions,
 * we will call {@link #throwable(Throwable, boolean)} with whatever the exception was.
 *
 * @param <T>
 */
@InterfaceAudience.Private
public interface AsyncRetryingCallable<T> {
  /**
   * Prepare by setting up any connections to servers, etc., ahead of {@link #call(ResponseHandler)} invocation.
   *
   * @param reload Set this to true if need to requery locations (usually set on second invocation
   *               to {@link #call(ResponseHandler)} )} or whatever
   * @throws IOException e
   */
  void prepare(final boolean reload) throws IOException;

  /**
   * Called when {@link #call(ResponseHandler)} throws an exception and we are going to retry; take action to
   * make it so we succeed on next call (clear caches, do relookup of locations, etc.).
   *
   * @param t
   * @param retrying True if we are in retrying mode (we are not in retrying mode when max
   *                 retries == 1; we ARE in retrying mode if retries > 1 even when we are the last attempt)
   */
  void throwable(final Throwable t, boolean retrying);

  /**
   * @return Some details from the implementation that we would like to add to a terminating
   * exception; i.e. a fatal exception is being thrown ending retries and we might like to add
   * more implementation-specific detail on to the exception being thrown.
   */
  String getExceptionMessageAdditionalDetail();

  /**
   * @param pause before retry
   * @param tries count of tries
   * @return Suggestion on how much to sleep between retries
   */
  long sleep(final long pause, final int tries);

  /**
   * Computes a result, or throws an exception if unable to do so.
   *
   * @param handler handler for computed result
   */
  public void call(final ResponseHandler<T> handler);
}


text:
/** Croatian translation */
jQuery(function($) {
    $.ui.dialog.wiquery.regional['hr'] = {
      okButton: 'U redu',
      cancelButton: 'Odustani',
      questionTitle: 'Pitanje',
      waitTitle: 'Please wait',
      errorTitle: 'Greška',
      warningTitle: 'Upozorenje'
    };
});


text:
import avsc from 'avsc';
import { getLogger } from '../activity';
import { clickToClickRecord } from './clickReader';
import * as avro from './avro';

jest.mock('@google-cloud/pubsub', () => {
	const publish = jest.fn(() => Promise.resolve('okay!'));
	const main = jest.fn(() => ({
		topic: jest.fn(() => ({
			publisher: () => ({
				publish,
			}),
		})),
	}));
	main.publish = publish; // hook to make publish calls visible to calling test
	return main;
});

describe('serializers.avro', () => {
	it('encodes record of provided schema', () => {
		const schema = {
			type: 'record',
			fields: [
				{ name: 'requestId', type: 'string' },
				{ name: 'timestamp', type: 'string' },
			],
		};
		const serializer = avro.serializers.avro(schema);
		const data = {
			requestId: 'foo',
			timestamp: new Date().getTime().toString(),
		};
		const serialized = serializer(data);

		// parse stringified object
		const valObj = JSON.parse(serialized);
		// create a new buffer from that string
		const avroBuffer = Buffer.from(valObj.record, 'base64');
		// get the avro-encoded record
		const recordedInfo = avsc.parse(schema).fromBuffer(avroBuffer);
		expect(recordedInfo).toEqual(data);
	});
});

describe('deserializers.avro', () => {
	it('decodes an encoded record of provided schema', () => {
		const schema = {
			type: 'record',
			fields: [
				{ name: 'requestId', type: 'string' },
				{ name: 'timestamp', type: 'string' },
			],
		};
		const data = {
			requestId: 'foo',
			timestamp: new Date().getTime().toString(),
		};

		const serializer = avro.serializers.avro(schema);
		const deserializer = avro.deserializers.avro(schema);
		const serialized = serializer(data);
		const deserialized = deserializer(serialized);
		expect(deserialized).toEqual(data);
	});
});

describe('Activity tracking', () => {
	const request = {
		id: 'foo',
		headers: {},
		state: {},
		log() {},
		server: { settings: { app: { api: {} } } },
	};
	const trackInfo = getLogger('WEB')(request, {
		memberId: 1234,
		trackId: 'foo',
		sessionId: 'bar', // not part of v3 spec
		url: 'asdf',
		viewName: 'foo view',
		subViewName: 'foo subview',
	});

	it('encodes chapinEnvelope output from getLogger', () => {
		const serialized = avro.serializers.awsactivity(trackInfo);

		// // parse stringified object
		const valObj = JSON.parse(serialized);
		// // create a new buffer from that string
		const avroBuffer = Buffer.from(valObj.data, 'base64');
		// // get the avro-encoded record
		const recordedInfo = avsc.parse(avro.schemas.activity).fromBuffer(avroBuffer);
		delete recordedInfo.timestamp;
		expect(recordedInfo).toMatchSnapshot();
	});
});

describe('Click tracking', () => {
	const request = {
		id: 'foo',
		state: {},
		server: { settings: { app: { api: {} } } },
	};
	const click = {
		timestamp: new Date(0).toISOString(),
		lineage: 'div#foo',
		linkText: 'hello world',
		coords: [23, 45],
		elementName: 'test',
		containerName: 'test-container',
	};

	it('encodes chapinEnvelope output from clickToClickRecord', () => {
		const trackInfo = clickToClickRecord(request)(click);
		const serialized = avro.serializers.awsclick(trackInfo);

		// parse stringified object
		const valObj = JSON.parse(serialized);
		// create a new buffer from that string
		const avroBuffer = Buffer.from(valObj.data, 'base64');
		// get the avro-encoded record
		const recordedInfo = avsc.parse(avro.schemas.click).fromBuffer(avroBuffer);
		const expectedTrackedInfo = {
			...trackInfo,
			tag: '', // not used in our click data - defaults to empty string
			serverTime: '', // not used in our click data - defaults to empty string
			viewId: null,
			eventRef: null, // not used in our click data (web-next or chapstick)
			eventSource: null, // not used in our click data (web-next or chapstick)
		};
		expect(recordedInfo).toEqual(expectedTrackedInfo);
	});
});


text:
package seedu.taskmanager.logic.parser;

import static seedu.taskmanager.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.taskmanager.commons.util.CommonStringUtil.EMPTY_STRING;

import seedu.taskmanager.commons.exceptions.IllegalValueException;
import seedu.taskmanager.logic.commands.Command;
import seedu.taskmanager.logic.commands.IncorrectCommand;
import seedu.taskmanager.logic.commands.SetNotificationCommand;
import seedu.taskmanager.model.task.TaskDate;

// @@author A0140538J
/**
 * Parses input arguments and creates a new SetNotificationCommand object
 */
public class SetNotificationCommandParser {

    private static final String CURRENT_TIME = "now";

    /**
     * Parses the given {@code String} of arguments in the context of the SetNotificationCommand and returns a
     * SetNotificationCommand object for execution.
     */
    public Command parse(String arg) {

        assert arg != null;

        String modifiedArg = arg.trim();

        if (modifiedArg.equals(EMPTY_STRING)) {
            return new IncorrectCommand(
                    String.format(MESSAGE_INVALID_COMMAND_FORMAT, SetNotificationCommand.MESSAGE_USAGE));
        }

        TaskDate currentDate;
        TaskDate date;

        try {
            currentDate = DateTimeUtil.parseDateTime(CURRENT_TIME);
            date = DateTimeUtil.parseDateTime(modifiedArg);
        } catch (IllegalValueException ive) {
            return new IncorrectCommand(ive.getMessage());
        }

        if (date.getTaskDate().before(currentDate.getTaskDate())) {
            return new IncorrectCommand(
                    String.format(MESSAGE_INVALID_COMMAND_FORMAT, SetNotificationCommand.MESSAGE_USAGE));
        }

        return new SetNotificationCommand(modifiedArg);
    }

}


text:
import Colors from '../../../src/variables';
import Grid, {GridItem} from '../../../src/Grid';
import Page from '../Page';
import React from 'react';
import Switch from '../../../src/Switch';
import TextField from '../../../src/TextField';

class SwitchDocs extends React.Component {
  constructor(props) {
    super(props);
    this.onControlPanel = this.onControlPanel.bind(this);
    this.state = {
      checked: true,
      disabled: false,
      label: 'Switch Label',
      labelId: 'foobar',
      primaryColor: Colors.$primary,
      switch1: false,
      switch2: true,
      switch3: true,
      switch4: false,
      switch5: true
    };
  }

  onControlPanel(key, value) {
    this.setState({[key]: value});
  }

  render() {
    const {checked, disabled, label, labelId, primaryColor} = this.state;
    return (
      <Page
        componentName="Switch"
        buildYourOwn={
          <div style={{flex: 1}}>
            <Switch
              onChange={e => (this.onControlPanel('checked', e.target.checked))}
              disabled={disabled}
              label={label}
              labelId={labelId}
              checked={checked}
              primaryColor={primaryColor}
              style={{justifyContent: 'center'}}
            />
          </div>
        }
        buildYourOwnControlPanel={[
          <Switch
            onChange={e => (this.onControlPanel('checked', e.target.checked))}
            checked={checked}
            label="checked"
          />,
          <Switch
            onChange={e => (this.onControlPanel('disabled', e.target.checked))}
            checked={disabled}
            label="disabled"
          />,
          <TextField
            onChange={e => (this.onControlPanel('label', e.target.value))}
            label="label"
            value={label}
          />,
          <TextField
            onChange={e => (this.onControlPanel('labelId', e.target.value))}
            label="labelId"
            value={labelId}
          />,
          <TextField
            onChange={e => (this.onControlPanel('primaryColor', e.target.value))}
            label="primaryColor"
            value={primaryColor}
          />
        ]}
        examples={
          <Grid>
            <GridItem xs={6} md={3}>
              <Switch
                onChange={e => (this.onControlPanel('switch1', e.target.checked))}
                checked={this.state.switch1}
                label={'Switch #1'}
              />
            </GridItem>
            <GridItem xs={6} md={3}>
              <Switch
                onChange={e => (this.onControlPanel('switch2', e.target.checked))}
                checked={this.state.switch2}
                label={'Switch #2'}
              />
            </GridItem>
            <GridItem xs={6} md={3}>
              <Switch
                onChange={e => (this.onControlPanel('switch3', e.target.checked))}
                checked={this.state.switch3}
                label={'Custom Color'}
                primaryColor={Colors.$orange700}
              />
            </GridItem>
            <GridItem xs={6} md={3}>
              <Switch
                onChange={e => (this.onControlPanel('switch4', e.target.checked))}
                checked={this.state.switch4}
                label={'Disabled off'}
                disabled
              />
            </GridItem>
            <GridItem xs={6} md={3}>
              <Switch
                onChange={e => (this.onControlPanel('switch5', e.target.checked))}
                checked={this.state.switch5}
                label={'Disabled on'}
                disabled
              />
            </GridItem>
          </Grid>
        }
      />
    );
  }
}

export default SwitchDocs;


text:
/**
 */
package org.mobadsl.semantic.model.moba.impl;

import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.mobadsl.semantic.model.moba.MobaDto;
import org.mobadsl.semantic.model.moba.MobaPackage;
import org.mobadsl.semantic.model.moba.MobaRESTPayloadDefinition;
import org.mobadsl.semantic.model.moba.MobaTransportSerializationType;

/**
 *
 * An implementation of the model object 'REST Payload Definition'.
 *
 *

 * The following features are implemented:
 *

 *

 *
{@link org.mobadsl.semantic.model.moba.impl.MobaRESTPayloadDefinitionImpl#getDto Dto}

 *
{@link org.mobadsl.semantic.model.moba.impl.MobaRESTPayloadDefinitionImpl#isArray Array}

 *
{@link org.mobadsl.semantic.model.moba.impl.MobaRESTPayloadDefinitionImpl#getSerializationType Serialization Type}

 *

 *
 * @generated
 */
public class MobaRESTPayloadDefinitionImpl extends MinimalEObjectImpl.Container implements MobaRESTPayloadDefinition {
	/**
	 * The cached value of the '{@link #getDto() Dto}' reference.
	 *
	 *
	 * @see #getDto()
	 * @generated
	 * @ordered
	 */
	protected MobaDto dto;

	/**
	 * The default value of the '{@link #isArray() Array}' attribute.
	 *
	 *
	 * @see #isArray()
	 * @generated
	 * @ordered
	 */
	protected static final boolean ARRAY_EDEFAULT = false;

	/**
	 * The cached value of the '{@link #isArray() Array}' attribute.
	 *
	 *
	 * @see #isArray()
	 * @generated
	 * @ordered
	 */
	protected boolean array = ARRAY_EDEFAULT;

	/**
	 * The cached value of the '{@link #getSerializationType() Serialization Type}' reference.
	 *
	 *
	 * @see #getSerializationType()
	 * @generated
	 * @ordered
	 */
	protected MobaTransportSerializationType serializationType;

	/**
	 *
	 *
	 * @generated
	 */
	protected MobaRESTPayloadDefinitionImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return MobaPackage.Literals.MOBA_REST_PAYLOAD_DEFINITION;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public MobaDto getDto() {
		if (dto != null && dto.eIsProxy()) {
			InternalEObject oldDto = (InternalEObject)dto;
			dto = (MobaDto)eResolveProxy(oldDto);
			if (dto != oldDto) {
				if (eNotificationRequired())
					eNotify(new ENotificationImpl(this, Notification.RESOLVE, MobaPackage.MOBA_REST_PAYLOAD_DEFINITION__DTO, oldDto, dto));
			}
		}
		return dto;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public MobaDto basicGetDto() {
		return dto;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setDto(MobaDto newDto) {
		MobaDto oldDto = dto;
		dto = newDto;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, MobaPackage.MOBA_REST_PAYLOAD_DEFINITION__DTO, oldDto, dto));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public boolean isArray() {
		return array;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setArray(boolean newArray) {
		boolean oldArray = array;
		array = newArray;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, MobaPackage.MOBA_REST_PAYLOAD_DEFINITION__ARRAY, oldArray, array));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public MobaTransportSerializationType getSerializationType() {
		if (serializationType != null && serializationType.eIsProxy()) {
			InternalEObject oldSerializationType = (InternalEObject)serializationType;
			serializationType = (MobaTransportSerializationType)eResolveProxy(oldSerializationType);
			if (serializationType != oldSerializationType) {
				if (eNotificationRequired())
					eNotify(new ENotificationImpl(this, Notification.RESOLVE, MobaPackage.MOBA_REST_PAYLOAD_DEFINITION__SERIALIZATION_TYPE, oldSerializationType, serializationType));
			}
		}
		return serializationType;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public MobaTransportSerializationType basicGetSerializationType() {
		return serializationType;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setSerializationType(MobaTransportSerializationType newSerializationType) {
		MobaTransportSerializationType oldSerializationType = serializationType;
		serializationType = newSerializationType;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, MobaPackage.MOBA_REST_PAYLOAD_DEFINITION__SERIALIZATION_TYPE, oldSerializationType, serializationType));
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case MobaPackage.MOBA_REST_PAYLOAD_DEFINITION__DTO:
				if (resolve) return getDto();
				return basicGetDto();
			case MobaPackage.MOBA_REST_PAYLOAD_DEFINITION__ARRAY:
				return isArray();
			case MobaPackage.MOBA_REST_PAYLOAD_DEFINITION__SERIALIZATION_TYPE:
				if (resolve) return getSerializationType();
				return basicGetSerializationType();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case MobaPackage.MOBA_REST_PAYLOAD_DEFINITION__DTO:
				setDto((MobaDto)newValue);
				return;
			case MobaPackage.MOBA_REST_PAYLOAD_DEFINITION__ARRAY:
				setArray((Boolean)newValue);
				return;
			case MobaPackage.MOBA_REST_PAYLOAD_DEFINITION__SERIALIZATION_TYPE:
				setSerializationType((MobaTransportSerializationType)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case MobaPackage.MOBA_REST_PAYLOAD_DEFINITION__DTO:
				setDto((MobaDto)null);
				return;
			case MobaPackage.MOBA_REST_PAYLOAD_DEFINITION__ARRAY:
				setArray(ARRAY_EDEFAULT);
				return;
			case MobaPackage.MOBA_REST_PAYLOAD_DEFINITION__SERIALIZATION_TYPE:
				setSerializationType((MobaTransportSerializationType)null);
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case MobaPackage.MOBA_REST_PAYLOAD_DEFINITION__DTO:
				return dto != null;
			case MobaPackage.MOBA_REST_PAYLOAD_DEFINITION__ARRAY:
				return array != ARRAY_EDEFAULT;
			case MobaPackage.MOBA_REST_PAYLOAD_DEFINITION__SERIALIZATION_TYPE:
				return serializationType != null;
		}
		return super.eIsSet(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public String toString() {
		if (eIsProxy()) return super.toString();

		StringBuffer result = new StringBuffer(super.toString());
		result.append(" (array: ");
		result.append(array);
		result.append(')');
		return result.toString();
	}

} //MobaRESTPayloadDefinitionImpl


text:
package com.sangupta.pry.site;

import com.sangupta.jerry.db.DatabaseBasicOperationsService;

/**
 *
 * @author sangupta
 *
 */
public interface SiteService extends DatabaseBasicOperationsService<Site, String> {

	Site getOrAdd(String readLine);

}


text:
#endregion

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.IO;

namespace FickleFrostbite.FIT
{
   ///
   /// Implements the PowerZone profile message.
   ///
   public class PowerZoneMesg : Mesg
   {
      #region Fields
      #endregion

      #region Constructors
      public PowerZoneMesg() : base(Profile.mesgs[Profile.PowerZoneIndex])
      {
      }

      public PowerZoneMesg(Mesg mesg) : base(mesg)
      {
      }
      #endregion // Constructors

      #region Methods
      ///
      /// Retrieves the MessageIndex field
      /// <returns>Returns nullable ushort representing the MessageIndex field</returns>
      public ushort? GetMessageIndex()
      {
         return (ushort?)GetFieldValue(254, 0, Fit.SubfieldIndexMainField);
      }

      ///
      /// Set MessageIndex field
      /// <param name="messageIndex_">Nullable field value to be set</param>
      public void SetMessageIndex(ushort? messageIndex_)
      {
         SetFieldValue(254, 0, messageIndex_, Fit.SubfieldIndexMainField);
      }

      ///
      /// Retrieves the HighValue field
      /// Units: watts
      /// <returns>Returns nullable ushort representing the HighValue field</returns>
      public ushort? GetHighValue()
      {
         return (ushort?)GetFieldValue(1, 0, Fit.SubfieldIndexMainField);
      }

      ///
      /// Set HighValue field
      /// Units: watts
      /// <param name="highValue_">Nullable field value to be set</param>
      public void SetHighValue(ushort? highValue_)
      {
         SetFieldValue(1, 0, highValue_, Fit.SubfieldIndexMainField);
      }

      ///
      /// Retrieves the Name field
      /// <returns>Returns byte[] representing the Name field</returns>
      public byte[] GetName()
      {
         return (byte[])GetFieldValue(2, 0, Fit.SubfieldIndexMainField);
      }

      ///
      /// Retrieves the Name field
      /// <returns>Returns String representing the Name field</returns>
      public String GetNameAsString()
      {
         return Encoding.UTF8.GetString((byte[])GetFieldValue(2, 0, Fit.SubfieldIndexMainField));
      }

      ///
      /// Set Name field
      /// <returns>Returns String representing the Name field</returns>
      public void SetName(String name_)
      {
         SetFieldValue(2, 0, System.Text.Encoding.UTF8.GetBytes(name_), Fit.SubfieldIndexMainField);
      }

      ///
      /// Set Name field
      /// <param name="name_">field value to be set</param>
      public void SetName(byte[] name_)
      {
         SetFieldValue(2, 0, name_, Fit.SubfieldIndexMainField);
      }

      #endregion // Methods
   } // Class
} // namespace


text:
<?php
use yii\helpers\Html;

//$this->registerJsFile('https://api-maps.yandex.ru/2.1/?lang=ru_RU');
$this->registerJsFile('@web/js/yandex-map.js');
$this->registerJsFile('@web/js/dots.js', ['depends' => '\yii\web\JqueryAsset']);

$this->registerCssFile('@web/css/component.css');
$this->registerCssFile('@web/css/default.css');
$this->registerJsFile('@web/js/classie.js');
$this->registerJsFile('@web/js/modernizr.custom.js');
$this->registerJsFile('@web/js/menu.js', ['depends' => '\yii\web\JqueryAsset']);
?>

<div id="map" style="width: 100vw;
  height: 100vh;
  position: fixed;
  overflow: auto; padding-bottom:60px">
</div>


text:
class SocketServer : public QObject
{
    Q_OBJECT
public:
    explicit SocketServer(QObject *parent = 0);
    ~SocketServer();

signals:

public slots:
};

#endif // SOCKETSERVER_H