text:
**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public bool EnableVersioning { get; set; }
```

### Property Value
Type: System.Boolean

## See also
- [ListInstance](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512.ListInstance.md)
- [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512.md)

redpajama_set_name: RedPajamaGithub


text:
alias vim=nvim
alias vi=nvim
export EDITOR=nvim
export GH_EDITOR=nvim


text:
<?php

namespace Reborn\MVC\Controller;

use Auth;
use Reborn\Http\Redirect;

class PrivateController extends PublicController
{
    protected function init()
    {
        parent::init();

        $this->checkAuthentication();
    }

    /**
     * Check the Authentication for Private Controller
     *
     * @return boolean
     **/
    protected function checkAuthentication()
    {
        if (!Auth::check()) {
            return Redirect::to('login');
        } else {
            $this->template->loggedin_user = Auth::getUser();
        }

        return true;
    }
}


text:
<?php

namespace eveg\BiblioBundle\Entity;

/**
 * BiblioFileRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class BiblioFileRepository extends \Doctrine\ORM\EntityRepository
{
	public function getLastFiles($limit)
	{
		$qb = $this->createQueryBuilder('b');

		$qb->select('b')
		   ->orderBy('b.updatedAt', 'DESC')
		   ->setMaxResults($limit);

		return $qb->getQuery()->getResult();
	}

	public function getNbFiles()
	{
		$qb = $this->createQueryBuilder('b');

		$qb->select('COUNT(b)');

		return $qb->getQuery()->getSingleScalarResult();
	}
}


text:
strong {
	color: #359FCF;
}

.Logos a {
	text-decoration: none;
}

.rightS {
	position:relative;
}

.productButtons {
	text-align: center;
}

.productButtons .prodButton {
	margin: 4px auto;
	width: 180px;
}

.productButtons .prodButton img{
	margin: 0px;
}

.prodQty select {
	width:130px;
}

.catSideBar {
	margin-left:20px;
}

.catSideBar ul, .catSideBar li{
	padding: 0px;
	margin: 0px;
	list-style:none;
}

.clear {
	clear: both;
}

.catSideBar{
	margin-left: 20px;
}

.blueBorder { border: 1px solid #1690C8; padding: 10px;}
.prodViewerAddToCartForm  fieldset {margin: 5px;}
.prodViewerAddToCartForm  input[name=qty] {padding: 5px;}

.prodDetail { height: 0px; overflow:hidden; }

address[data-templateid=chkoutBuyerAddressTemplate]{
	width: 300px;
	margin-bottom: 15px;
}
address[data-templateid=chkoutBuyerAddressTemplate] .addressFullname,
address[data-templateid=chkoutBuyerAddressTemplate] .address {
	width: 250px;
}

.hint {
	text-decoration: underline;
	margin: 0px 8px;
}

.signupHeight {
	line-height: 39px;
}

#subscribeFrmFooter .submit {
	margin-top: 10px;
	margin-left: 5px;
}

.addrCreateLabel {
	display: inline-block;
	width: 100px;
}

.shipmentList {
	margin-top: 0px;
}

.ui-widget-content a.trackingLink {
	color: #128EC7;
	text-decoration: underline;
}

.Logos img {
	margin: 0px 55px;
}

.Logos img.bumpDown {
	margin-top: 12px;
}


text:
namespace gl
{
struct ImageIndex;
struct Box;
struct PixelUnpackState;
}

namespace rx
{
class SwapChainD3D;
class RenderTargetD3D;
class ImageD3D;

class TextureStorage : angle::NonCopyable
{
  public:
    TextureStorage() {}
    virtual ~TextureStorage() {}

    virtual int getTopLevel() const = 0;
    virtual bool isRenderTarget() const = 0;
    virtual bool isManaged() const = 0;
    virtual bool supportsNativeMipmapFunction() const = 0;
    virtual int getLevelCount() const = 0;

    virtual gl::Error getRenderTarget(const gl::ImageIndex &index, RenderTargetD3D **outRT) = 0;
    virtual gl::Error generateMipmap(const gl::ImageIndex &sourceIndex, const gl::ImageIndex &destIndex) = 0;

    virtual gl::Error copyToStorage(TextureStorage *destStorage) = 0;
    virtual gl::Error setData(const gl::ImageIndex &index, ImageD3D *image, const gl::Box *destBox, GLenum type,
                              const gl::PixelUnpackState &unpack, const uint8_t *pixelData) = 0;

    // This is a no-op for most implementations of TextureStorage. Some (e.g. TextureStorage11_2D) might override it.
    virtual gl::Error useLevelZeroWorkaroundTexture(bool useLevelZeroTexture) { return gl::Error(GL_NO_ERROR); }
};

}

#endif // LIBANGLE_RENDERER_D3D_TEXTURESTORAGE_H_


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Notizbl. Königl. Bot. Gart. Berlin 1:181. 1896

#### Original name
null

### Remarks
null


text:
import torch
from torch.distributions import constraints

from pyro.contrib.gp.kernels.kernel import Kernel
from pyro.nn.module import PyroParam

class Brownian(Kernel):
    r"""
    This kernel correponds to a two-sided Brownion motion (Wiener process):

        :math:`k(x,z)=\begin{cases}\sigma^2\min(|x|,|z|),& \text{if } x\cdot z\ge 0\\
        0, & \text{otherwise}. \end{cases}`

    Note that the input dimension of this kernel must be 1.

    Reference:

    [1] `Theory and Statistical Applications of Stochastic Processes`,
    Yuliya Mishura, Georgiy Shevchenko
    """

    def __init__(self, input_dim, variance=None, active_dims=None):
        if input_dim != 1:
            raise ValueError("Input dimensional for Brownian kernel must be 1.")
        super().__init__(input_dim, active_dims)

        variance = torch.tensor(1.0) if variance is None else variance
        self.variance = PyroParam(variance, constraints.positive)

    def forward(self, X, Z=None, diag=False):
        if Z is None:
            Z = X
        X = self._slice_input(X)
        if diag:
            return self.variance * X.abs().squeeze(1)

        Z = self._slice_input(Z)
        if X.size(1) != Z.size(1):
            raise ValueError("Inputs must have the same number of features.")

        Zt = Z.t()
        return torch.where(
            X.sign() == Zt.sign(),
            self.variance * torch.min(X.abs(), Zt.abs()),
            X.data.new_zeros(X.size(0), Z.size(0)),
        )


text:
'use strict';
const isset = require('isset');
const {toCamelCase, toSnakeCase} = require('case-converter');  // TODO :: https://github.com/tgriesser/knex/issues/2084
const ValidationError = require('./ValidationError');

module.exports = db => {

  const addTodo = async (name, description, userId) => {
    // TODO :: do real validation?
    if (!isset(name) || !isset(description) || !isset(userId)) {
      throw new ValidationError('All required fields must be filled out.');
    } else {
      return await db.table('todos').insert(toSnakeCase({ name, description, userId }));
    }
  };

  const getTodos = async userId => {
    if (!isset(userId)) {
      throw new ValidationError('User ID must be specified.');
    } else {
      return await db.table('todos').where(toSnakeCase({ userId })).orderBy('id', 'asc');
    }
  };

  const removeTodo = async id => {
    if (!isset(id)) {
      throw new ValidationError('ID must be specified.');
    } else {
      return await db.table('todos').where({ id }).del();
    }
  };

  const updateTodo = async (name, description, id) => {
    // TODO :: do real validation?
    if (!isset(name) || !isset(description) || !isset(id)) {
      throw new ValidationError('All required fields must be filled out.');
    } else {
      return await db.table('todos').where({ id }).update({ name, description });
    }
  };

  return { addTodo, getTodos, removeTodo, updateTodo };

};


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
	<item android:state_pressed="true" android:drawable="@drawable/umeng_fb_gradient_orange" />
	<item android:state_pressed="false" android:drawable="@drawable/umeng_fb_gradient_green" />
</selector>
<!-- From: file:/Users/lucas/dev/workspace/umeng/feedback/umeng-feedback-android/sdk/src/main/res/drawable/umeng_fb_submit_selector.xml -->


text:
package org.gradle.tooling.internal.provider;

public interface PayloadInterface {
    String getValue();
}


text:
//#region License
// *
//The MIT License

//Copyright (c) 2008 Sky Morey

//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:

//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
//*/
//#endregion
//using System;
//namespace Contoso.Practices.DurableBus.Transport
//{
//    public partial class MsmqTransport
//    {
//        public event EventHandler<MessageReceivedEventArgs> MessageReceived;
//        public event EventHandler MessageProcessing;
//        public event EventHandler MessageProcessingFailed;
//        public event EventHandler MessageProcessed;

//        protected virtual bool OnFailedMessageProcessing()
//        {
//            try
//            {
//                var failedMessageProcessing = FailedMessageProcessing;
//                if (failedMessageProcessing != null)
//                    failedMessageProcessing(this, null);
//            }
//            catch (Exception ex) { Logger.Warn("Failed raising 'failed message processing' event.", ex); return false; }
//            return true;
//        }

//        protected virtual bool OnFinishedMessageProcessing()
//        {
//            try
//            {
//                var finishedMessageProcessing = FinishedMessageProcessing;
//                if (finishedMessageProcessing != null)
//                    finishedMessageProcessing(this, null);
//            }
//            catch (Exception ex) { Logger.Error("Failed raising 'finished message processing' event.", ex); return false; }
//            return true;
//        }

//        protected virtual bool OnTransportMessageReceived(TransportMessage m)
//        {
//            try
//            {
//                var transportMessageReceived = TransportMessageReceived;
//                if (transportMessageReceived != null)
//                    transportMessageReceived(this, new MessageReceivedEventArgs(m));
//            }
//            catch (Exception e) { Logger.Warn("Failed raising 'transport message received' event for message with ID=" + m.Id, e); return false; }
//            return true;
//        }
//    }
//}


text:
Ahora vamos a aprender cómo contar el número de documentos
que cumplan con ciertos criterios.

Usa la colección llamada `parrots` de la base de datos llamada
`learnyoumongo` para contar todos los documentos donde`age` sea
mayor que el primer argumento pasado a tu script.

Usando `console.log`, haz que se imprima el número a `stdout`.

-----------------------------------------------------------
## PISTAS

Para contar el número de documentos que cumplan con ciertos criterios,
tenemos que usar la función `collection.count()`.

Por ejemplo:

```js
collection.count({
  name: 'foo'
}, function(err, count) {

})
```

Si tu programa sigue ejecutando sin parar, quizás te olvidaste de cerrar `db`.
Pon `db.close()` en tu programa después de que hayas hecho todo lo necesario.

## Recurso:
* http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#count


text:
declare( 'Ext::ux::panel::GMapPanel', function (use,checkState,__PACKAGE__) {

    use('Ext::ux::api::gMap',function(use){
        Ext.ux.panel.GMapPanel = Ext.extend(Ext.Panel, {

            gMap : undefined,
            gMapEl : undefined,

            gMapOptions : undefined,
            gMapCustomize : undefined,
            gMapCustomizeScope : undefined,

            setCenter : undefined,

            constructor: function(config) {

                Ext.apply(config, {

                }); //eof apply

                this.addEvents('mapready');

				Ext.ux.panel.GMapPanel.superclass.constructor.call(this, config);
            }, //eof constructor

            initComponent: function() {

				Ext.ux.panel.GMapPanel.superclass.initComponent.call(this);
            },

            afterRender : function(){
                Ext.ux.panel.GMapPanel.superclass.afterRender.apply(this, arguments);

                this.gMapEl = Ext.DomHelper.append(this.body,'

',true);
                this.gMap = new GM.Map2(this.gMapEl.dom, this.gMapOptions);

                if (this.setCenter) {
                    this.gMap.setCenter(new GM.LatLng(this.setCenter.lat || 0, this.setCenter.lng || 0), this.setCenter.zoom || 10);
                }
                if (this.gMapCustomize) this.gMapCustomize.call(this.gMapCustomizeScope || window, this.gMap);
				this.fireEvent('mapready');
            },

            onResize : function (w,h) {
                Ext.ux.panel.GMapPanel.superclass.onResize.call(this, w, h);

                if (!w || !h || !this.gMap) return;

                var center = this.gMap.getCenter();
                this.gMap.checkResize();
                this.gMap.setCenter(center);
            },

            setSize : function(w, h, animate) {
                Ext.ux.panel.GMapPanel.superclass.setSize.call(this, w, h, animate);

                if (!w || !h || !this.gMap) return;

                var center = this.gMap.getCenter();
                this.gMap.checkResize();
                this.gMap.setCenter(center);
            }

        }); //eof extend

        Ext.reg('gmappanel', Ext.ux.panel.GMapPanel);
    }); //eof use

}); //eof declare


text:
package org.apache.flink.runtime.memory;

import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.MemorySegment;

import java.io.EOFException;
import java.io.IOException;
import java.io.UTFDataFormatException;

/**
 * The base class for all input views that are backed by multiple memory pages. This base class contains all
 * decoding methods to read data from a page and detect page boundary crossing. The concrete sub classes must
 * implement the methods to provide the next memory page once the boundary is crossed.
 */
public abstract class AbstractPagedInputView implements DataInputView {

	private MemorySegment currentSegment;

	protected final int headerLength;				// the number of bytes to skip at the beginning of each segment

	private int positionInSegment;					// the offset in the current segment

	private int limitInSegment;						// the limit in the current segment before switching to the next

	private byte[] utfByteBuffer;					// reusable byte buffer for utf-8 decoding
	private char[] utfCharBuffer;					// reusable char buffer for utf-8 decoding

	// --------------------------------------------------------------------------------------------
	//                                    Constructors
	// --------------------------------------------------------------------------------------------

	/**
	 * Creates a new view that starts with the given segment. The input starts directly after the header
	 * of the given page. If the header size is zero, it starts at the beginning. The specified initial
	 * limit describes up to which position data may be read from the current segment, before the view must
	 * advance to the next segment.
	 *
	 * @param initialSegment The memory segment to start reading from.
	 * @param initialLimit The position one after the last valid byte in the initial segment.
	 * @param headerLength The number of bytes to skip at the beginning of each segment for the header. This
	 *                     length must be the same for all memory segments.
	 */
	protected AbstractPagedInputView(MemorySegment initialSegment, int initialLimit, int headerLength) {
		this.headerLength = headerLength;
		this.positionInSegment = headerLength;
		seekInput(initialSegment, headerLength, initialLimit);
	}

	/**
	 * Creates a new view that is initially not bound to a memory segment. This constructor is typically
	 * for views that always seek first.
	 *
	 * <p>WARNING: The view is not readable until the first call to either {@link #advance()},
	 * or to {@link #seekInput(MemorySegment, int, int)}.
	 *
	 * @param headerLength The number of bytes to skip at the beginning of each segment for the header.
	 */
	protected AbstractPagedInputView(int headerLength) {
		this.headerLength = headerLength;
	}

	// --------------------------------------------------------------------------------------------
	//                                  Page Management
	// --------------------------------------------------------------------------------------------

	/**
	 * Gets the memory segment that will be used to read the next bytes from. If the segment is exactly exhausted,
	 * meaning that the last byte read was the last byte available in the segment, then this segment will
	 * not serve the next bytes. The segment to serve the next bytes will be obtained through the
	 * {@link #nextSegment(MemorySegment)} method.
	 *
	 * @return The current memory segment.
	 */
	public MemorySegment getCurrentSegment() {
		return this.currentSegment;
	}

	/**
	 * Gets the position from which the next byte will be read. If that position is equal to the current limit,
	 * then the next byte will be read from next segment.
	 *
	 * @return The position from which the next byte will be read.
	 * @see #getCurrentSegmentLimit()
	 */
	public int getCurrentPositionInSegment() {
		return this.positionInSegment;
	}

	/**
	 * Gets the current limit in the memory segment. This value points to the byte one after the last valid byte
	 * in the memory segment.
	 *
	 * @return The current limit in the memory segment.
	 * @see #getCurrentPositionInSegment()
	 */
	public int getCurrentSegmentLimit() {
		return this.limitInSegment;
	}

	/**
	 * The method by which concrete subclasses realize page crossing. This method is invoked when the current page
	 * is exhausted and a new page is required to continue the reading. If no further page is available, this
	 * method must throw an {@link EOFException}.
	 *
	 * @param current The current page that was read to its limit. May be {@code null}, if this method is
	 *                invoked for the first time.
	 * @return The next page from which the reading should continue. May not be {@code null}. If the input is
	 *         exhausted, an {@link EOFException} must be thrown instead.
	 *
	 * @throws EOFException Thrown, if no further segment is available.
	 * @throws IOException Thrown, if the method cannot provide the next page due to an I/O related problem.
	 */
	protected abstract MemorySegment nextSegment(MemorySegment current) throws EOFException, IOException;

	/**
	 * Gets the limit for reading bytes from the given memory segment. This method must return the position
	 * of the byte after the last valid byte in the given memory segment. When the position returned by this
	 * method is reached, the view will attempt to switch to the next memory segment.
	 *
	 * @param segment The segment to determine the limit for.
	 * @return The limit for the given memory segment.
	 */
	protected abstract int getLimitForSegment(MemorySegment segment);

	/**
	 * Advances the view to the next memory segment. The reading will continue after the header of the next
	 * segment. This method uses {@link #nextSegment(MemorySegment)} and {@link #getLimitForSegment(MemorySegment)}
	 * to get the next segment and set its limit.
	 *
	 * @throws IOException Thrown, if the next segment could not be obtained.
	 *
	 * @see #nextSegment(MemorySegment)
	 * @see #getLimitForSegment(MemorySegment)
	 */
	public void advance() throws IOException {
		doAdvance();
	}

	protected void doAdvance() throws IOException {
		// note: this code ensures that in case of EOF, we stay at the same position such that
		// EOF is reproducible (if nextSegment throws a reproducible EOFException)
		this.currentSegment = nextSegment(this.currentSegment);
		this.limitInSegment = getLimitForSegment(this.currentSegment);
		this.positionInSegment = this.headerLength;
	}

	/**
	 * @return header length.
	 */
	public int getHeaderLength() {
		return headerLength;
	}

	/**
	 * Sets the internal state of the view such that the next bytes will be read from the given memory segment,
	 * starting at the given position. The memory segment will provide bytes up to the given limit position.
	 *
	 * @param segment The segment to read the next bytes from.
	 * @param positionInSegment The position in the segment to start reading from.
	 * @param limitInSegment The limit in the segment. When reached, the view will attempt to switch to
	 *                       the next segment.
	 */
	protected void seekInput(MemorySegment segment, int positionInSegment, int limitInSegment) {
		this.currentSegment = segment;
		this.positionInSegment = positionInSegment;
		this.limitInSegment = limitInSegment;
	}

	/**
	 * Clears the internal state of the view. After this call, all read attempts will fail, until the
	 * {@link #advance()} or {@link #seekInput(MemorySegment, int, int)} method have been invoked.
	 */
	protected void clear() {
		this.currentSegment = null;
		this.positionInSegment = this.headerLength;
		this.limitInSegment = headerLength;
	}

	// --------------------------------------------------------------------------------------------
	//                               Data Input Specific methods
	// --------------------------------------------------------------------------------------------

	@Override
	public int read(byte[] b) throws IOException{
		return read(b, 0, b.length);
	}

	@Override
	public int read(byte[] b, int off, int len) throws IOException{
		if (off < 0 || len < 0 || off + len > b.length) {
			throw new IndexOutOfBoundsException();
		}

		int remaining = this.limitInSegment - this.positionInSegment;
		if (remaining >= len) {
			this.currentSegment.get(this.positionInSegment, b, off, len);
			this.positionInSegment += len;
			return len;
		}
		else {
			if (remaining == 0) {
				try {
					advance();
				}
				catch (EOFException eof) {
					return -1;
				}
				remaining = this.limitInSegment - this.positionInSegment;
			}

			int bytesRead = 0;
			while (true) {
				int toRead = Math.min(remaining, len - bytesRead);
				this.currentSegment.get(this.positionInSegment, b, off, toRead);
				off += toRead;
				bytesRead += toRead;

				if (len > bytesRead) {
					try {
						advance();
					}
					catch (EOFException eof) {
						this.positionInSegment += toRead;
						return bytesRead;
					}
					remaining = this.limitInSegment - this.positionInSegment;
				}
				else {
					this.positionInSegment += toRead;
					break;
				}
			}
			return len;
		}
	}

	@Override
	public void readFully(byte[] b) throws IOException {
		readFully(b, 0, b.length);
	}

	@Override
	public void readFully(byte[] b, int off, int len) throws IOException {
		int bytesRead = read(b, off, len);

		if (bytesRead < len){
			throw new EOFException("There is no enough data left in the DataInputView.");
		}
	}

	@Override
	public boolean readBoolean() throws IOException {
		return readByte() == 1;
	}

	@Override
	public byte readByte() throws IOException {
		if (this.positionInSegment < this.limitInSegment) {
			return this.currentSegment.get(this.positionInSegment++);
		}
		else {
			advance();
			return readByte();
		}
	}

	@Override
	public int readUnsignedByte() throws IOException {
		return readByte() & 0xff;
	}

	@Override
	public short readShort() throws IOException {
		if (this.positionInSegment < this.limitInSegment - 1) {
			final short v = this.currentSegment.getShortBigEndian(this.positionInSegment);
			this.positionInSegment += 2;
			return v;
		}
		else if (this.positionInSegment == this.limitInSegment) {
			advance();
			return readShort();
		}
		else {
			return (short) ((readUnsignedByte() << 8) | readUnsignedByte());
		}
	}

	@Override
	public int readUnsignedShort() throws IOException {
		if (this.positionInSegment < this.limitInSegment - 1) {
			final int v = this.currentSegment.getShortBigEndian(this.positionInSegment) & 0xffff;
			this.positionInSegment += 2;
			return v;
		}
		else if (this.positionInSegment == this.limitInSegment) {
			advance();
			return readUnsignedShort();
		}
		else {
			return (readUnsignedByte() << 8) | readUnsignedByte();
		}
	}

	@Override
	public char readChar() throws IOException  {
		if (this.positionInSegment < this.limitInSegment - 1) {
			final char v = this.currentSegment.getCharBigEndian(this.positionInSegment);
			this.positionInSegment += 2;
			return v;
		}
		else if (this.positionInSegment == this.limitInSegment) {
			advance();
			return readChar();
		}
		else {
			return (char) ((readUnsignedByte() << 8) | readUnsignedByte());
		}
	}

	@Override
	public int readInt() throws IOException {
		if (this.positionInSegment < this.limitInSegment - 3) {
			final int v = this.currentSegment.getIntBigEndian(this.positionInSegment);
			this.positionInSegment += 4;
			return v;
		}
		else if (this.positionInSegment == this.limitInSegment) {
			advance();
			return readInt();
		}
		else {
			return (readUnsignedByte() << 24) |
				(readUnsignedByte() << 16) |
				(readUnsignedByte() <<  8) |
					readUnsignedByte();
		}
	}

	@Override
	public long readLong() throws IOException {
		if (this.positionInSegment < this.limitInSegment - 7) {
			final long v = this.currentSegment.getLongBigEndian(this.positionInSegment);
			this.positionInSegment += 8;
			return v;
		}
		else if (this.positionInSegment == this.limitInSegment) {
			advance();
			return readLong();
		}
		else {
			long l = 0L;
			l |= ((long) readUnsignedByte()) << 56;
			l |= ((long) readUnsignedByte()) << 48;
			l |= ((long) readUnsignedByte()) << 40;
			l |= ((long) readUnsignedByte()) << 32;
			l |= ((long) readUnsignedByte()) << 24;
			l |= ((long) readUnsignedByte()) << 16;
			l |= ((long) readUnsignedByte()) <<  8;
			l |= (long) readUnsignedByte();
			return l;
		}
	}

	@Override
	public float readFloat() throws IOException {
		return Float.intBitsToFloat(readInt());
	}

	@Override
	public double readDouble() throws IOException {
		return Double.longBitsToDouble(readLong());
	}

	@Override
	public String readLine() throws IOException {
		final StringBuilder bld = new StringBuilder(32);

		try {
			int b;
			while ((b = readUnsignedByte()) != '\n') {
				if (b != '\r') {
					bld.append((char) b);
				}
			}
		}
		catch (EOFException eofex) {}

		if (bld.length() == 0) {
			return null;
		}

		// trim a trailing carriage return
		int len = bld.length();
		if (len > 0 && bld.charAt(len - 1) == '\r') {
			bld.setLength(len - 1);
		}
		return bld.toString();
	}

	@Override
	public String readUTF() throws IOException {
		final int utflen = readUnsignedShort();

		final byte[] bytearr;
		final char[] chararr;

		if (this.utfByteBuffer == null || this.utfByteBuffer.length < utflen) {
			bytearr = new byte[utflen];
			this.utfByteBuffer = bytearr;
		} else {
			bytearr = this.utfByteBuffer;
		}
		if (this.utfCharBuffer == null || this.utfCharBuffer.length < utflen) {
			chararr = new char[utflen];
			this.utfCharBuffer = chararr;
		} else {
			chararr = this.utfCharBuffer;
		}

		int c, char2, char3;
		int count = 0;
		int chararrCount = 0;

		readFully(bytearr, 0, utflen);

		while (count < utflen) {
			c = (int) bytearr[count] & 0xff;
			if (c > 127) {
				break;
			}
			count++;
			chararr[chararrCount++] = (char) c;
		}

		while (count < utflen) {
			c = (int) bytearr[count] & 0xff;
			switch (c >> 4) {
			case 0:
			case 1:
			case 2:
			case 3:
			case 4:
			case 5:
			case 6:
			case 7:
				/* 0xxxxxxx */
				count++;
				chararr[chararrCount++] = (char) c;
				break;
			case 12:
			case 13:
				/* 110x xxxx 10xx xxxx */
				count += 2;
				if (count > utflen) {
					throw new UTFDataFormatException("malformed input: partial character at end");
				}
				char2 = (int) bytearr[count - 1];
				if ((char2 & 0xC0) != 0x80) {
					throw new UTFDataFormatException("malformed input around byte " + count);
				}
				chararr[chararrCount++] = (char) (((c & 0x1F) << 6) | (char2 & 0x3F));
				break;
			case 14:
				/* 1110 xxxx 10xx xxxx 10xx xxxx */
				count += 3;
				if (count > utflen) {
					throw new UTFDataFormatException("malformed input: partial character at end");
				}
				char2 = (int) bytearr[count - 2];
				char3 = (int) bytearr[count - 1];
				if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) {
					throw new UTFDataFormatException("malformed input around byte " + (count - 1));
				}
				chararr[chararrCount++] = (char) (((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0));
				break;
			default:
				/* 10xx xxxx, 1111 xxxx */
				throw new UTFDataFormatException("malformed input around byte " + count);
			}
		}
		// The number of chars produced may be less than utflen
		return new String(chararr, 0, chararrCount);
	}

	@Override
	public int skipBytes(int n) throws IOException {
		if (n < 0) {
			throw new IllegalArgumentException();
		}

		int remaining = this.limitInSegment - this.positionInSegment;
		if (remaining >= n) {
			this.positionInSegment += n;
			return n;
		}
		else {
			if (remaining == 0) {
				try {
					advance();
				} catch (EOFException eofex) {
					return 0;
				}
				remaining = this.limitInSegment - this.positionInSegment;
			}

			int skipped = 0;
			while (true) {
				int toSkip = Math.min(remaining, n);
				n -= toSkip;
				skipped += toSkip;

				if (n > 0) {
					try {
						advance();
					} catch (EOFException eofex) {
						return skipped;
					}
					remaining = this.limitInSegment - this.positionInSegment;
				}
				else {
					this.positionInSegment += toSkip;
					break;
				}
			}
			return skipped;
		}
	}

	@Override
	public void skipBytesToRead(int numBytes) throws IOException {
		if (numBytes < 0) {
			throw new IllegalArgumentException();
		}

		int remaining = this.limitInSegment - this.positionInSegment;
		if (remaining >= numBytes) {
			this.positionInSegment += numBytes;
		}
		else {
			if (remaining == 0) {
				advance();
				remaining = this.limitInSegment - this.positionInSegment;
			}

			while (true) {
				if (numBytes > remaining) {
					numBytes -= remaining;
					advance();
					remaining = this.limitInSegment - this.positionInSegment;
				}
				else {
					this.positionInSegment += numBytes;
					break;
				}
			}
		}
	}
}


text:
module MonteCarlo
  # Class to run your Monte Carlo experiments
  #
  # @example
  #   experiment = MonteCarlo::Experiment.new
  #   experiment.sample_method = -> { rand(10) }
  #   results = experiment.run
  class Experiment

    # The default number of sample methods to generate
    DEFAULT_TIMES = 10000

    # @!attribute times
    #   @return [#times] the number of samples to generate
    # @!attribute sample_method
    #   @return [#call] a method to generate a sample each time
    # @!attribute computation
    #   @return [#call] a method to turn a random sample to a meaningful result
    # @!attribute setup
    #   @return [#call] a method to run before each iteration
    # @!attribute reset
    #   @return [#call] a method to run after each iteration
    attr_accessor :times, :sample_method, :computation, :setup, :reset

    # Shorthand syntax to run a simple experiment
    #
    # @example
    #   results = MonteCarlo::Experiment.run(100000) { rand(10) }
    #
    # @param times [optional, #times] the number of samples to generate
    # @param block [Block] the method to generate one sample each iteration
    # @raise [MonteCarlo::Errors::NoSampleMethodError] if no block is given
    # @return [MonteCarlo::ExperimentResults]
    def self.run(times = DEFAULT_TIMES, &block)
      experiment = MonteCarlo::Experiment.new(times)
      experiment.sample_method = block
      experiment.run
    end

    # Initialize a new experiment
    #
    # @example
    #   experiment = MonteCarlo::Experiment.new do
    #     times 100000
    #     sample_method { rand(10) }
    #     computation { |sample| sample >= 5  }
    #   end
    #
    #   results = experiment.run
    #
    # @param times [optional, #times] the number of samples to generate
    # @param block [optional, Block] a block to configure the experiment using the {MonteCarlo::ExperimentDSL}
    # @return [MonteCarlo::Experiment]
    def initialize(times = DEFAULT_TIMES, &block)
      @times = times
      raise ArgumentError, "`times` must be a positive integer" unless valid_times?
      MonteCarlo::ExperimentDSL.new(self).instance_eval(&block) if block_given?
    end

    def times=(times)
      @times = times
      raise ArgumentError, "`times` must be a positive integer" unless valid_times?
    end

    # Run the experiment
    #
    # @raise [MonteCarlo::Errors::NoSampleMethodError] if the experiment has no sample method set
    # @return [MonteCarlo::ExperimentResults]
    def run
      if @sample_method.nil?
        raise MonteCarlo::Errors::NoSampleMethodError, 'A sample method for this experiment is not defined'
      end

      results = MonteCarlo::ExperimentResults.new

      @times.times do |index|
        begin
          @setup.call() unless @setup.nil?
          results << run_sample(index)
        ensure
          @reset.call() unless @reset.nil?
        end
      end

      results
    end

    private

    def run_sample(index)
      result = MonteCarlo::Result.new(index)
      result.sample_value = @sample_method.call()
      if @computation.nil?
        result.value = result.sample_value
      else
        result.value = @computation.call(result.sample_value)
      end

      result
    end

    def valid_times?
      @times.is_a?(Integer) && @times > 0
    end

  end
end


text:
import React from 'react';
import Store from './Store';
import * as Actions from './Actions';
import isFunction from 'lodash.isfunction';
import getDefault from './getDefault';
import shallowEqual from 'react/lib/shallowEqual';

const Empty = React.createClass({
  render() {
    return false;
  }
});

const ComponentRouter = React.createClass({
  propTypes: {
    config: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.func]).isRequired,
    children: React.PropTypes.node,
    namespace: React.PropTypes.string.isRequired
  },

  getInitialState() {
    return {
      query: Store.getQuery()
    };
  },

  componentDidMount() {
    this.unsubscribe = Store.subscribe(this.onChange);
    this.checkDefaultParam(this.props);
  },

  componentWillReceiveProps(props) {
    this.checkDefaultParam(props);
  },

  shouldComponentUpdate(newProps, {query = {}}) {
    const config = newProps.config || {};

    return !shallowEqual(newProps, this.props) || !shallowEqual(config,
        this.props.config) || !shallowEqual(query, this.state.query);
  },

  componentWillUnmount() {
    this.unsubscribe();
    Store.dispatch(Actions.removeParam({
      namespace: this.props.namespace}));
  },

  checkDefaultParam(props) {
    const {namespace, config: {[getDefault()]: value}} = props;
    const defaultParams = Store.getDefaultParams();

    if (value && (!defaultParams.hasOwnProperty(namespace) || defaultParams[namespace] !== value)) {
      Store.dispatch(Actions.addDefaultParam({namespace, value}));
    }
  },

  onChange() {
    this.setState({
      query: Store.getQuery()
    });
  },

  render() {
    const {namespace, config, ...props} = this.props;
    const value = namespace in this.state.query ?
      this.state.query[namespace] : config[getDefault()];

    const componentRouter = {
      namespace,
      value,
      keys: [],
      config: {},
      Component: Empty
    };

    // For dynamic values we pass a whole component instead of map of components,
    // so it will effectively have `namespace` only
    if (isFunction(config)) {
      if (!React.Children.count(this.props.children)) {
        // React will render custom component only if it starts from capital letter
        const Child = config;

        return <Child {...props} componentRouter={componentRouter} />;
      }

      // In case of non-empty children, we should pass Component from config
      return React.cloneElement(React.Children.only(this.props.children), {
        ...props,
        componentRouter: {...componentRouter, Component: config}
      });
    }

    const keys = Object.keys(config).filter(key => key !== getDefault());

    if (!React.Children.count(this.props.children)) {
      // React will render custom component only if it starts from capital letter
      const Child = value && config[value] || Empty;

      return <Child {...props} componentRouter={{...componentRouter, keys, config}} />;
    }

    const Component = value && config[value] || Empty;

    // For static values we can pass config, keys and try to find active component
    return React.cloneElement(React.Children.only(this.props.children), {
      ...props,
      componentRouter: {...componentRouter, keys, config, Component}
    });
  }
});

export default ComponentRouter;


text:
<?php
namespace test\j\l;
class b { }


text:
function [ test_pred ] = ClassifyNearestNeighbour( training_data, test_data )
% CLASSIFYNEARESTNEIGHBOUR Classify test data using nearest neighbour in
%                          training data
%
% Single band nearest neighbour classification, multiband images are
% flattened.

    [nPeople, nTraining] = size(training_data);
    nTest = size(test_data, 2);

    test_pred = zeros(nTest, 1);
    for i = 1:nTest
        best_match = -1;
        best_match_strength = -1;
        best_match_example = -1;

        % Find the nearest neighbour to the test image
        for person = 1:nPeople
            for example = 1:nTraining
                image = training_data{person,example};
                match_strength = norm(image(:) - test_data(:,i,:));
                % Replace best match if closer fit
                if match_strength < best_match_strength || best_match_strength == -1
                    best_match = person;
                    best_match_example = example;
                    best_match_strength = match_strength;
                end;
            end;
        end;
        fprintf('Best match for %d is %d at image %d (strength: %.3f)\n',...
            i, best_match, best_match_example, best_match_strength);

        % Random classification for now
        test_pred(i) = best_match;
    end;
end


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

import React from "react"
import { shallow } from "enzyme"
import { ObjectsBulkActions } from "../ObjectsBulkActions"

describe("ObjectsBulkActions", () => {
  it("should render without crashing", () => {
    shallow(<ObjectsBulkActions checkedObjectsCount={0} />)
  })

  it("should show actions when checkObjectsCount is more than 0", () => {
    const wrapper = shallow(<ObjectsBulkActions checkedObjectsCount={1} />)
    expect(wrapper.hasClass("list-actions-toggled")).toBeTruthy()
  })

  it("should call downloadChecked when download button is clicked", () => {
    const downloadChecked = jest.fn()
    const wrapper = shallow(
      <ObjectsBulkActions
        checkedObjectsCount={1}
        downloadChecked={downloadChecked}
      />
    )
    wrapper.find("#download-checked").simulate("click")
    expect(downloadChecked).toHaveBeenCalled()
  })

  it("should call clearChecked when close button is clicked", () => {
    const clearChecked = jest.fn()
    const wrapper = shallow(
      <ObjectsBulkActions checkedObjectsCount={1} clearChecked={clearChecked} />
    )
    wrapper.find("#close-bulk-actions").simulate("click")
    expect(clearChecked).toHaveBeenCalled()
  })

  it("shoud show DeleteObjectConfirmModal when delete-checked button is clicked", () => {
    const wrapper = shallow(<ObjectsBulkActions checkedObjectsCount={1} />)
    wrapper.find("#delete-checked").simulate("click")
    wrapper.update()
    expect(wrapper.find("DeleteObjectConfirmModal").length).toBe(1)
  })

  it("shoud call deleteChecked when Delete is clicked on confirmation modal", () => {
    const deleteChecked = jest.fn()
    const wrapper = shallow(
      <ObjectsBulkActions
        checkedObjectsCount={1}
        deleteChecked={deleteChecked}
      />
    )
    wrapper.find("#delete-checked").simulate("click")
    wrapper.update()
    wrapper.find("DeleteObjectConfirmModal").prop("deleteObject")()
    expect(deleteChecked).toHaveBeenCalled()
    wrapper.update()
    expect(wrapper.find("DeleteObjectConfirmModal").length).toBe(0)
  })
})


text:
export { default as CurrentRefinements } from './CurrentRefinements';
export { default as HierarchicalMenu } from './HierarchicalMenu';
export { default as Hits } from './Hits';
export { default as HitsPerPage } from './HitsPerPage';
export { default as Menu } from './Menu';
export { default as NumericMenu } from './NumericMenu';
export { default as Pagination } from './Pagination';
export { default as PoweredBy } from './PoweredBy';
export { default as RangeInput } from './RangeInput';
export { default as RatingMenu } from './RatingMenu';
export { default as RefinementList } from './RefinementList';
export { default as ClearRefinements } from './ClearRefinements';
export { default as ScrollTo } from './ScrollTo';
export { default as SearchBox } from './SearchBox';
export { default as RelevantSort } from './RelevantSort';
export { default as SortBy } from './SortBy';
export { default as Stats } from './Stats';
export { default as ToggleRefinement } from './ToggleRefinement';


text:
namespace pythonic
{

  namespace numpy
  {
    namespace wrapper
    {
      template <class T>
      bool isposinf(T const &t)
      {
        return nt2::is_inf(t) and nt2::is_positive(t);
      }
    }
#define NUMPY_NARY_FUNC_NAME isposinf
#define NUMPY_NARY_FUNC_SYM wrapper::isposinf
#include "pythonic/types/numpy_nary_expr.hpp"
  }
}

#endif


text:
package ru.job4j.start;

/**
 * Class Item.
 * @author Dinis Saetgareev (dinis0086@mail.ru)
 * @since 11.03.2017
 * @version 1.0
 */
public class Item {
    /**
     * String id - item.
     */
    private String id;
    /**
     * String name - name item.
     */
    private String name;
    /**
     * String desc - description item.
     */
    private String desc;
    /**
     * long create.
     */
    private long create;
    /**
     * String comments - comments item.
     */
    private String comments;

    /**
     * Constructor Item.
     * @param id - String
     * @param name - String
     * @param desc - String
     * @param create - long
     * @param comments - String
     */
    public Item(String id, String name, String desc, long create, String comments) {
        this.id = id;
        this.name = name;
        this.desc = desc;
        this.create = create;
        this.comments = comments;
    }

    /**
     * method getId().
     * @return id - this.id
     */
    public String getId() {
        return this.id;
    }

    /**
     * method setId(String id).
     * @param id - String
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     * method getName().
     * @return name - name item
     */
    public String getName() {
        return this.name;
    }

    /**
     * method setName(String name).
     * @param name - String
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * method getDesc().
     * @return desc - desc item
     */
    public String getDesc() {
        return this.desc;
    }

    /**
     * method setDesc(String desc).
     * @param desc - String
     */
    public void setDesc(String desc) {
        this.desc = desc;
    }

    /**
     * method getCreate().
     * @return create - long
     */
    public long getCreate() {
        return this.create;
    }

    /**
     * method setCreate(long create).
     * @param create - long
     */
    public void setCreate(long create) {
        this.create = create;
    }

    /**
     * method getComments.
     * @return comments - String
     */
    public String getComments() {
        return this.comments;
    }

    /**
     * method setComments(String comments).
     * @param comments - String
     */
    public void setComments(String comments) {
        this.comments = comments;
    }

    /**
     * Override hashCode().
     * @return result - int
     */
    @Override
    public int hashCode() {
        int result = id != null ? id.hashCode() : 0;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (desc != null ? desc.hashCode() : 0);
        result = 31 * result + (int) (create ^ (create >>> 32));
        result = 31 * result + (comments != null ? comments.hashCode() : 0);
        return result;
    }

    /**
     * boolean equals(Object obj).
     * @param item - Item
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        Item other = (Item) obj;
        if (id != other.id) {
            return false;
        }
        if (name != other.name) {
            return false;
        }
        if (desc != other.desc) {
            return false;
        }
        if (create != other.create) {
            return false;
        }
        if (comments != other.comments) {
            return false;
        }
        return true;
    }
}


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

<!-- $Author$ -->
<!-- $Revision$ -->
<!-- $Date$ -->

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
                http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <!-- This file contains all spring bean definitions that all easyrec features need in common -->

    <import resource="classpath:spring/utils/aop/DAO.xml"/>
    <import resource="classpath:spring/web/common/Cache.xml"/>
    <import resource="classpath:spring/utils/aop/MapThrowableToException.xml"/>
    <import resource="classpath:spring/core/PropertyPlaceholderConfigurerEasyrec.xml"/>
    <import resource="classpath:spring/pluginContainer/LogEntryDAO.xml"/>
    <import resource="classpath:spring/pluginContainer/NamedConfigurationDAO.xml"/>
    <import resource="classpath:spring/core/dao/itemDAO.xml"/>
    <import resource="classpath:spring/web/common/dao/assocDAO.xml"/>
    <import resource="classpath:spring/web/common/dao/operatorDAO.xml"/>
    <import resource="classpath:spring/web/common/dao/backtrackingDAO.xml"/>
    <import resource="classpath:spring/web/common/dao/remoteTenantDAO.xml"/>
    <import resource="classpath:spring/web/common/dao/statisticsDAO.xml"/>
    <import resource="classpath:spring/core/dao/ProfileDAO.xml"/>
    <import resource="classpath:spring/web/common/service/itemService.xml"/>
    <import resource="classpath:spring/core/service/ProfileService.xml"/>
    <import resource="classpath:spring/core/service/JSONProfileService.xml"/>
    <import resource="classpath:spring/web/common/service/viewInitializationService.xml"/>
    <import resource="classpath:spring/web/common/service/remoteTenantService.xml"/>
    <import resource="classpath:spring/web/common/service/remoteAssocService.xml"/>
    <import resource="classpath:spring/web/common/service/shopRecommenderService.xml"/>
    <import resource="classpath:spring/web/common/service/namedConfigurationService.xml"/>
    <import resource="classpath:spring/core/common/rankingsCache.xml"/>
    <import resource="classpath:spring/web/common/easyrecSettings.xml"/>
    <import resource="classpath:spring/web/common/easyrec-core.xml"/>
    <import resource="classpath:spring/web/common/easyrec-domain.xml"/>
    <import resource="classpath:spring/web/common/idMapping.xml"/>
    <import resource="classpath:spring/web/common/easyrec-plugins.xml"/>
    <import resource="classpath:spring/web/common/service/displayService.xml"/>

</beans>


text:
A simple class to get Android device information for debugging purposes and send it out by an email intent.

# Usage
* Import the two files MyDeviceInfo.java and MyStorageInfo.java into your project.
* Get device information like this. Call inside an Activity to pass the context and package identifier:

try
{
	MyDeviceInfo info = new MyDeviceInfo(YourActivity.this, "com.example.yourapplication");
	info.sendEmail(MyDeviceInfo.MODE_TXT_INLINE);
}
catch(Exception e)
{
	e.printStackTrace();
}

* sendEmail() takes a flag:
	* MODE_TXT_INLINE inlines the device report.
	* MODE_TXT_ATTACHMENT attaches the report as text file. No special write permissions needed for getExternalCacheDir() call.

* use getReport() to get a string dump.

# Notes
* Build against SDK 24
* Tested on API Level 22

# Known Issues
* Some function used in class MyStorageInfo are deprecated (Jan. 2017).
* Code has become obsolete. You can use [Google Crashlytics](https://firebase.google.com/docs/crashlytics/) to get much better device (and crash) information (March 2018).

# Sample Output (Nexus 4, running Android 5.1.1)

Device information report:

Device Info v1.0.0b3(3)
net.mat8854.prototype 1.0.0b3 (3)
Locale: de_DE

** Device:
Board: MAKO
Brand: google
Device: mako
Model: Nexus 4
Product: occam
TAGS: release-keys

** OS:
Build release 5.1.1, Inc: '2237560'
Display build: LMY48T
Finger print: google/occam/mako:5.1.1/LMY48T/2237560:user/release-keys
Build ID: LMY48T
Time: 1441745481000
Type: user
User: android-build

** Density:
density: 2.0
densityDpi: 320
scaledDensity: 2.0
xdpi: 319.79
ydpi: 318.745

** Density reference:
DENSITY_DEFAULT: 160
DENSITY_LOW: 120
DENSITY_MEDIUM: 160
DENSITY_HIGH: 240

** Screen:
heightPixels: 1184
widthPixels: 768

** Storage:
internal storage = 927MB/ 13,231MB
external storage = 927MB/ 13,231MB

** Features:
FeatureInfo{3ab8f384 android.hardware.sensor.proximity fl=0x0}
FeatureInfo{370a176d android.hardware.sensor.accelerometer fl=0x0}
FeatureInfo{dbd5fa2 android.hardware.faketouch fl=0x0}
FeatureInfo{26114433 android.hardware.usb.accessory fl=0x0}
FeatureInfo{2a93c3f0 android.software.backup fl=0x0}
FeatureInfo{223dbd69 android.hardware.touchscreen fl=0x0}
FeatureInfo{c35d3ee android.hardware.touchscreen.multitouch fl=0x0}
FeatureInfo{3191f08f android.software.print fl=0x0}
FeatureInfo{30092f1c android.hardware.ethernet fl=0x0}
FeatureInfo{bebc725 android.software.voice_recognizers fl=0x0}
FeatureInfo{15af40fa android.hardware.sensor.gyroscope fl=0x0}
FeatureInfo{1cc706ab android.hardware.audio.low_latency fl=0x0}
FeatureInfo{38082108 android.hardware.bluetooth fl=0x0}
FeatureInfo{29b6b0a1 android.hardware.camera.autofocus fl=0x0}
FeatureInfo{2a2072c6 com.google.android.feature.GOOGLE_BUILD fl=0x0}
FeatureInfo{1ded6287 android.hardware.telephony.gsm fl=0x0}
FeatureInfo{d8245b4 android.software.sip.voip fl=0x0}
FeatureInfo{eecb5dd android.hardware.audio.output fl=0x0}
FeatureInfo{20f552 android.hardware.camera.flash fl=0x0}
FeatureInfo{2833a023 android.hardware.camera.front fl=0x0}
FeatureInfo{16d80920 android.hardware.screen.portrait fl=0x0}
FeatureInfo{3b83d2d9 android.hardware.nfc fl=0x0}
FeatureInfo{2e35149e android.software.home_screen fl=0x0}
FeatureInfo{29161b7f android.hardware.microphone fl=0x0}
FeatureInfo{3e04974c android.hardware.bluetooth_le fl=0x0}
FeatureInfo{1ed5c395 android.hardware.sensor.compass fl=0x0}
FeatureInfo{1cd9dcaa android.hardware.touchscreen.multitouch.jazzhand fl=0x0}
FeatureInfo{3f7af09b android.hardware.sensor.barometer fl=0x0}
FeatureInfo{2f89dc38 android.software.app_widgets fl=0x0}
FeatureInfo{a1c0411 android.software.input_methods fl=0x0}
FeatureInfo{d511976 android.hardware.sensor.light fl=0x0}
FeatureInfo{88dfb77 android.software.device_admin fl=0x0}
FeatureInfo{1c1c83e4 android.hardware.camera fl=0x0}
FeatureInfo{eabd04d android.hardware.screen.landscape fl=0x0}
FeatureInfo{12d5702 android.software.managed_users fl=0x0}
FeatureInfo{1e5cd813 android.software.webview fl=0x0}
FeatureInfo{290ffa50 android.hardware.camera.any fl=0x0}
FeatureInfo{3f22449 android.software.connectionservice fl=0x0}
FeatureInfo{e9de14e android.hardware.touchscreen.multitouch.distinct fl=0x0}
FeatureInfo{2432e26f android.hardware.location.network fl=0x0}
FeatureInfo{3b826b7c android.software.sip fl=0x0}
FeatureInfo{312fbc05 android.hardware.wifi.direct fl=0x0}
FeatureInfo{2d7ac45a android.software.live_wallpaper fl=0x0}
FeatureInfo{3cb5368b com.google.android.feature.GOOGLE_EXPERIENCE fl=0x0}
FeatureInfo{a48c368 com.google.android.feature.EXCHANGE_6_2 fl=0x0}
FeatureInfo{16f51381 android.hardware.location.gps fl=0x0}
FeatureInfo{910cc26 android.hardware.nfc.hce fl=0x0}
FeatureInfo{5beb067 android.hardware.wifi fl=0x0}
FeatureInfo{229aae14 android.hardware.location fl=0x0}
FeatureInfo{145e66bd android.hardware.telephony fl=0x0}
FeatureInfo{22ad84b2 glEsVers=3.0 fl=0x0}


text:
using System;
using WebREPL;

[ScriptModule]
internal static class App {

    static App() {
        (new CommandHandler()).Run();
    }
}


text:
package com.wix.mysql.io

import java.io.{InputStream, OutputStream, StringReader}
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger

import org.specs2.mutable.SpecWithJUnit

class TimingOutProcessExecutorTest extends SpecWithJUnit {

  "TimingOutProcessExecutor" should {

    "throw an exception if command does not complete within provided timeout" in {
      new TimingOutProcessExecutor("cmd").waitFor(new FakeProcess(Integer.MAX_VALUE), TimeUnit.MILLISECONDS.toNanos(1000)) must
        throwA[InterruptedException].like { case e => e.getMessage must contain("Timeout of 1 sec exceeded while waiting for 'cmd'")}
    }

    "return process exit code if command does complete within execution bounds" in {
      new TimingOutProcessExecutor("").waitFor(new FakeProcess(3), TimeUnit.MILLISECONDS.toNanos(2000)) mustEqual 0
    }
  }
}

class FakeProcess(val completeAfterNumberOfCalls: Int) extends Process {
  val exitValueInvoctionCounter = new AtomicInteger(completeAfterNumberOfCalls)

  override def exitValue(): Int = {
    exitValueInvoctionCounter.decrementAndGet() match {
      case 0 => 0
      case _ => throw new IllegalThreadStateException()
    }
  }

  override def destroy(): Unit = {}

  override def waitFor(): Int = ???

  override def getOutputStream: OutputStream = ???

  override def getErrorStream: InputStream = new FakeInputStream("err")

  override def getInputStream: InputStream = new FakeInputStream("err")
}

class FakeInputStream(collectedOutput: String) extends InputStream {
  val output = new StringReader(collectedOutput)
  override def read(): Int = output.read()
}


text:
namespace agency
{
namespace experimental
{

// XXX until this thing can resize, call it an array
// XXX probably want to take a single allocator as a parameter instead of two separate allocators
template<class T, template<class> class InnerAlloc = allocator, template<class> class OuterAlloc = allocator>
class tiled_array
{
  public:
    using value_type = T;
    using reference = value_type&;
    using const_reference = const value_type&;
    using size_type = std::size_t;

  private:
    size_type tile_size_;

    using inner_allocator_type = InnerAlloc<T>;
    using inner_container = vector<value_type, inner_allocator_type>;

    using outer_allocator_type = OuterAlloc<inner_container>;
    using outer_container = vector<inner_container, outer_allocator_type>;

    outer_container tiles_;

  public:
    tiled_array() : tile_size_(0), tiles_() {}

    tiled_array(const tiled_array&) = default;

    // constructs a tiled_array with a tile for each allocator
    template<class Range,
             __AGENCY_REQUIRES(
               std::is_constructible<
                 inner_allocator_type,
                 range_value_t<Range>
               >::value
             )>
    tiled_array(size_type n,
                const value_type& val,
                const Range& allocators)
    {
      size_type num_tiles = allocators.size();

      assert(num_tiles > 0 && num_tiles <= all_t::max_tile_count);

      if(n >= allocators.size())
      {
        // equally distribute allocations
        tile_size_ = (n + num_tiles - 1) / num_tiles;
        size_type last_tile_size = n - (tile_size_ * (allocators.size() - 1));

        // construct the full tiles
        auto last_alloc = --allocators.end();
        for(auto alloc = allocators.begin(); alloc != last_alloc; ++alloc)
        {
          tiles_.emplace_back(tile_size_, val, *alloc);
        }

        // construct the last tile
        tiles_.emplace_back(last_tile_size, val, *last_alloc);
      }
      else
      {
        // when there are more allocators than there are elements,
        // just create a tile for each element
        // an alternative would be to create a single tile using the first allocator
        // or choose some minimum tile size
        // we might want a constructor which accepts a tile_size
        tile_size_ = 1;
        auto alloc = allocators.begin();
        for(size_type i = 0; i < n; ++i, ++alloc)
        {
          tiles_.emplace_back(tile_size_, val, *alloc);
        }
      }
    }

    // constructs a tiled_array with a single tile
    tiled_array(size_type n, const value_type& val = value_type())
      : tiled_array(n, val, array<inner_allocator_type,1>{inner_allocator_type()})
    {}

    size_type tile_size() const
    {
      return tile_size_;
    }

  public:
    using all_t = small_untiled_view<outer_container>;

    all_t all()
    {
      return untile(tile_size(), tiles_);
    }

    using const_all_t = small_untiled_view<const outer_container>;

    const_all_t all() const
    {
      return untile(tile_size(), tiles_);
    }

    size_type size() const
    {
      return all().size();
    }

    using iterator = range_iterator_t<all_t>;

    iterator begin()
    {
      return all().begin();
    }

    iterator end()
    {
      return all().end();
    }

    using const_iterator = range_iterator_t<const_all_t>;

    const_iterator begin() const
    {
      return all().begin();
    }

    const_iterator end() const
    {
      return all().end();
    }

    using tiles_view = decltype(agency::experimental::all(std::declval<const outer_container&>()));

    tiles_view tiles() const
    {
      return agency::experimental::all(tiles_);
    }

    const inner_container& tile(size_type i) const
    {
      return tiles()[i];
    }

    reference operator[](size_type i)
    {
      return all()[i];
    }

    const_reference operator[](size_type i) const
    {
      return all()[i];
    }

    void clear()
    {
      tiles_.clear();
    }

    bool operator==(const tiled_array& rhs) const
    {
      return tiles_ == rhs.tiles_;
    }
};

} // end experimental
} // end agency


text:
package com.anttoolkit.hadoop.tasks.yarn.util;

import java.io.*;
import java.util.*;

import org.apache.commons.lang.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.yarn.api.records.*;
import org.apache.hadoop.yarn.conf.*;
import org.apache.hadoop.yarn.logaggregation.*;
import org.apache.hadoop.yarn.util.*;

import org.apache.tools.ant.*;

import com.anttoolkit.general.common.*;

public class LogsHelper
{
	private Configuration conf;
	private String logsFile;
	private String logsDir;

	private PrintStream out;

	public LogsHelper(Configuration conf, String logsFile, String logsDir)
	{
		this.conf = conf;
	}

	public void dumpAContainersLogs(String appId, String containerId,
								   String nodeId, String jobOwner)
			throws IOException
	{
		dumpAContainersLogsForALogType(appId, containerId, nodeId, jobOwner, null);
	}

	public void dumpAContainersLogsForALogType(String appId, String containerId,
											  String nodeId, String jobOwner, List<String> logType)
	{
		boolean foundContainerLogs = false;
		Path remoteAppLogDir = null;

		initContainerLogOutput(containerId);

		try
		{
			String containerString = SystemHelper.doubleLineSeparator + "Container: " + containerId;

			out.println(StringUtils.repeat("=", containerString.length()));
			out.println(containerString);
			out.println(StringUtils.repeat("=", containerString.length()));

			Path remoteRootLogDir = new Path(conf.get(YarnConfiguration.NM_REMOTE_APP_LOG_DIR, YarnConfiguration.DEFAULT_NM_REMOTE_APP_LOG_DIR));

			String suffix = LogAggregationUtils.getRemoteNodeLogDirSuffix(conf);
			remoteAppLogDir = LogAggregationUtils.getRemoteAppLogDir(remoteRootLogDir, ConverterUtils.toApplicationId(appId), jobOwner, suffix);

			RemoteIterator<FileStatus> nodeFiles;
			try
			{
				Path qualifiedLogDir = FileContext.getFileContext(conf).makeQualified(remoteAppLogDir);
				nodeFiles = FileContext.getFileContext(qualifiedLogDir.toUri(), conf).listStatus(remoteAppLogDir);
			}
			catch (FileNotFoundException e)
			{
				throw new BuildException("Remote directory \"" + remoteAppLogDir.toString() + "\" doesn't exist");
			}

			while (nodeFiles.hasNext())
			{
				FileStatus thisNodeFile = nodeFiles.next();
				String fileName = thisNodeFile.getPath().getName();

				if (!fileName.contains(LogAggregationUtils.getNodeString(nodeId)) ||
						!fileName.endsWith(LogAggregationUtils.TMP_FILE_SUFFIX))
				{
					continue;
				}

				AggregatedLogFormat.LogReader reader = null;
				try
				{
					reader = new AggregatedLogFormat.LogReader(conf, thisNodeFile.getPath());
					if (logType == null)
					{
						if (dumpAContainerLogs(containerId, reader, thisNodeFile.getModificationTime()) > -1)
						{
							foundContainerLogs = true;
						}
					}
					else
					{
						if (dumpAContainerLogsForALogType(containerId, reader, thisNodeFile.getModificationTime(), logType) > -1)
						{
							foundContainerLogs = true;
						}
					}
				}
				finally
				{
					if (reader != null)
					{
						reader.close();
					}
				}
			}
		}
		catch (IOException e)
		{
			throw new BuildException("Failed to dump YARN logs for container: " + containerId, e);
		}
		finally
		{
			close();
		}

		if (!foundContainerLogs)
		{
			throw new BuildException("Logs for container " + containerId + " are not present in logs dir: " + remoteAppLogDir.toString());
		}
	}

	public void dumpAllContainersLogs(ApplicationId appId, String appOwner)
			throws IOException
	{
		Path remoteRootLogDir = new Path(conf.get(YarnConfiguration.NM_REMOTE_APP_LOG_DIR, YarnConfiguration.DEFAULT_NM_REMOTE_APP_LOG_DIR));
		String logDirSuffix = LogAggregationUtils.getRemoteNodeLogDirSuffix(conf);

		// TODO Change this to get a list of files from the LAS.
		Path remoteAppLogDir = LogAggregationUtils.getRemoteAppLogDir(remoteRootLogDir, appId, appOwner, logDirSuffix);
		RemoteIterator<FileStatus> nodeFiles;
		try
		{
			Path qualifiedLogDir = FileContext.getFileContext(conf).makeQualified(remoteAppLogDir);
			nodeFiles = FileContext.getFileContext(qualifiedLogDir.toUri(), conf).listStatus(remoteAppLogDir);
		}
		catch (FileNotFoundException e)
		{
			throw new BuildException("Remote directory \"" + remoteAppLogDir.toString() + "\" doesn't exist");
		}

		boolean foundAnyLogs = false;

		while (nodeFiles.hasNext())
		{
			FileStatus thisNodeFile = nodeFiles.next();
			if (thisNodeFile.getPath().getName().endsWith(LogAggregationUtils.TMP_FILE_SUFFIX))
			{
				continue;
			}

			AggregatedLogFormat.LogReader reader = new AggregatedLogFormat.LogReader(conf, thisNodeFile.getPath());

			try
			{
				DataInputStream valueStream;
				AggregatedLogFormat.LogKey key = new AggregatedLogFormat.LogKey();
				valueStream = reader.next(key);

				initContainerLogOutput(key.toString());

				while (valueStream != null)
				{
					String containerString = SystemHelper.doubleLineSeparator + "Container: " + key + " on " + thisNodeFile.getPath().getName();

					out.println(StringUtils.repeat("=", containerString.length()));
					out.println(containerString);
					out.println(StringUtils.repeat("=", containerString.length()));

					while (true)
					{
						try
						{
							AggregatedLogFormat.LogReader.readAContainerLogsForALogType(valueStream, out, thisNodeFile.getModificationTime());
							foundAnyLogs = true;
						}
						catch (EOFException eof)
						{
							break;
						}
					}

					// Next container
					key = new AggregatedLogFormat.LogKey();
					valueStream = reader.next(key);
				}
			}
			finally
			{
				reader.close();
				close();
			}
		}

		if (!foundAnyLogs)
		{
			throw new BuildException("Application remote log dir \"" + remoteAppLogDir.toString() + "\" doesn't have any log files");
		}
	}

	private int dumpAContainerLogs(String containerIdStr,
								  AggregatedLogFormat.LogReader reader,
								  long logUploadedTime)
			throws IOException
	{
		DataInputStream valueStream;
		AggregatedLogFormat.LogKey key = new AggregatedLogFormat.LogKey();
		valueStream = reader.next(key);

		while (valueStream != null && !key.toString().equals(containerIdStr))
		{
			// Next container
			key = new AggregatedLogFormat.LogKey();
			valueStream = reader.next(key);
		}

		if (valueStream == null)
		{
			return -1;
		}

		boolean foundContainerLogs = false;
		while (true)
		{
			try
			{
				AggregatedLogFormat.LogReader.readAContainerLogsForALogType(valueStream, out, logUploadedTime);
				foundContainerLogs = true;
			}
			catch (EOFException e)
			{
				break;
			}
		}

		return foundContainerLogs ? 0 : -1;
	}

	private int dumpAContainerLogsForALogType(String containerIdStr,
											 AggregatedLogFormat.LogReader reader,
											 long logUploadedTime, List<String> logType)
			throws IOException
	{
		DataInputStream valueStream;
		AggregatedLogFormat.LogKey key = new AggregatedLogFormat.LogKey();
		valueStream = reader.next(key);

		while (valueStream != null && !key.toString().equals(containerIdStr))
		{
			// Next container
			key = new AggregatedLogFormat.LogKey();
			valueStream = reader.next(key);
		}

		if (valueStream == null)
		{
			return -1;
		}

		boolean foundContainerLogs = false;
		while (true)
		{
			try
			{
				int result = readContainerLogsForALogType(valueStream, logUploadedTime, logType);
				if (result == 0)
				{
					foundContainerLogs = true;
				}
			}
			catch (EOFException e)
			{
				break;
			}
		}

		if (foundContainerLogs)
		{
			return 0;
		}

		return -1;
	}

	private int readContainerLogsForALogType(DataInputStream valueStream, long logUploadedTime, List<String> logType)
			throws IOException
	{
		byte[] buf = new byte[65535];

		String fileType = valueStream.readUTF();
		String fileLengthStr = valueStream.readUTF();
		long fileLength = Long.parseLong(fileLengthStr);

		if (!logType.contains(fileType))
		{
			long totalSkipped = 0;
			long currSkipped = 0;

			while (currSkipped != -1 && totalSkipped < fileLength)
			{
				currSkipped = valueStream.skip(fileLength - totalSkipped);
				totalSkipped += currSkipped;
			}

			return -1;
		}

		out.print("LogType:");
		out.println(fileType);

		if (logUploadedTime != -1)
		{
			out.print("Log Upload Time:");
			out.println(Times.format(logUploadedTime));
		}

		out.print("LogLength:");
		out.println(fileLengthStr);
		out.println("Log Contents:");

		long curRead = 0;
		long pendingRead = fileLength - curRead;
		int toRead = pendingRead > buf.length ? buf.length : (int) pendingRead;
		int len = valueStream.read(buf, 0, toRead);

		while (len != -1 && curRead < fileLength)
		{
			out.write(buf, 0, len);
			curRead += len;

			pendingRead = fileLength - curRead;
			toRead = pendingRead > buf.length ? buf.length : (int) pendingRead;
			len = valueStream.read(buf, 0, toRead);
		}

		out.println("End of LogType:" + fileType);
		out.println("");
		return 0;
	}

	private void initContainerLogOutput(String containerId)
	{
		close();

		String file = logsFile != null ? logsFile :
				logsDir.trim().replace("\\", "/").endsWith("/") ?
						logsDir + containerId + ".log" :
						logsDir + "/" + containerId + ".log";

		File logFile = new File(file);
		if (logFile.exists() && logFile.isDirectory())
		{
			throw new BuildException("Can't save YARN log content to file '" + file + "' cause directory with the same name already exists");
		}

		try
		{
			if (!logFile.createNewFile())
			{
				throw new BuildException("Failed to create new file '" + file + "' to write YARN log into it");
			}
		}
		catch (Throwable e)
		{
			throw new BuildException("Failed to create new file '" + file + "' to write YARN log into it", e);
		}

		try
		{
			out = new PrintStream(new FileOutputStream(file, true));
		}
		catch (Throwable e)
		{
			throw new BuildException("Failed to get output stream for log file '" + file + "'", e);
		}
	}

	private void close()
	{
		if (out == null)
		{
			return;
		}

		try
		{
			out.close();
		}
		catch (Throwable e)
		{
		}

		out = null;
	}

	protected void finalize() throws Throwable
	{
		super.finalize();
		close();
	}
}


text:
"""TFX template penguin model.

A DNN keras model which uses features defined in features.py and network
parameters defined in constants.py.
"""

from typing import List
from absl import logging
import tensorflow as tf
from tensorflow import keras
import tensorflow_transform as tft
from tensorflow_transform.tf_metadata import schema_utils

from tfx import v1 as tfx
from tfx.experimental.templates.penguin.models import constants
from tfx.experimental.templates.penguin.models import features
from tfx_bsl.public import tfxio

from tensorflow_metadata.proto.v0 import schema_pb2

def _get_tf_examples_serving_signature(model, schema, tf_transform_output):
  """Returns a serving signature that accepts `tensorflow.Example`."""

  if tf_transform_output is None:  # Transform component is not used.

    @tf.function(input_signature=[
        tf.TensorSpec(shape=[None], dtype=tf.string, name='examples')
    ])
    def serve_tf_examples_fn(serialized_tf_example):
      """Returns the output to be used in the serving signature."""
      raw_feature_spec = schema_utils.schema_as_feature_spec(
          schema).feature_spec
      # Remove label feature since these will not be present at serving time.
      raw_feature_spec.pop(features.LABEL_KEY)
      raw_features = tf.io.parse_example(serialized_tf_example,
                                         raw_feature_spec)
      logging.info('serve_features = %s', raw_features)

      outputs = model(raw_features)
      # TODO(b/154085620): Convert the predicted labels from the model using a
      # reverse-lookup (opposite of transform.py).
      return {'outputs': outputs}

  else:  # Transform component exists.
    # We need to track the layers in the model in order to save it.
    # TODO(b/162357359): Revise once the bug is resolved.
    model.tft_layer_inference = tf_transform_output.transform_features_layer()

    @tf.function(input_signature=[
        tf.TensorSpec(shape=[None], dtype=tf.string, name='examples')
    ])
    def serve_tf_examples_fn(serialized_tf_example):
      """Returns the output to be used in the serving signature."""
      raw_feature_spec = tf_transform_output.raw_feature_spec()
      # Remove label feature since these will not be present at serving time.
      raw_feature_spec.pop(features.LABEL_KEY)
      raw_features = tf.io.parse_example(serialized_tf_example,
                                         raw_feature_spec)
      transformed_features = model.tft_layer_inference(raw_features)
      logging.info('serve_transformed_features = %s', transformed_features)

      outputs = model(transformed_features)
      # TODO(b/154085620): Convert the predicted labels from the model using a
      # reverse-lookup (opposite of transform.py).
      return {'outputs': outputs}

  return serve_tf_examples_fn

def _get_transform_features_signature(model, schema, tf_transform_output):
  """Returns a serving signature that applies tf.Transform to features."""

  if tf_transform_output is None:  # Transform component is not used.
    @tf.function(input_signature=[
        tf.TensorSpec(shape=[None], dtype=tf.string, name='examples')
    ])
    def transform_features_fn(serialized_tf_example):
      """Returns the transformed_features to be fed as input to evaluator."""
      raw_feature_spec = schema_utils.schema_as_feature_spec(
          schema).feature_spec
      raw_features = tf.io.parse_example(serialized_tf_example,
                                         raw_feature_spec)
      logging.info('eval_features = %s', raw_features)
      return raw_features
  else:  # Transform component exists.
    # We need to track the layers in the model in order to save it.
    # TODO(b/162357359): Revise once the bug is resolved.
    model.tft_layer_eval = tf_transform_output.transform_features_layer()

    @tf.function(input_signature=[
        tf.TensorSpec(shape=[None], dtype=tf.string, name='examples')
    ])
    def transform_features_fn(serialized_tf_example):
      """Returns the transformed_features to be fed as input to evaluator."""
      raw_feature_spec = tf_transform_output.raw_feature_spec()
      raw_features = tf.io.parse_example(serialized_tf_example,
                                         raw_feature_spec)
      transformed_features = model.tft_layer_eval(raw_features)
      logging.info('eval_transformed_features = %s', transformed_features)
      return transformed_features

  return transform_features_fn

def _input_fn(file_pattern: List[str],
              data_accessor: tfx.components.DataAccessor,
              schema: schema_pb2.Schema,
              label: str,
              batch_size: int = 200) -> tf.data.Dataset:
  """Generates features and label for tuning/training.

  Args:
    file_pattern: List of paths or patterns of input tfrecord files.
    data_accessor: DataAccessor for converting input to RecordBatch.
    schema: A schema proto of input data.
    label: Name of the label.
    batch_size: representing the number of consecutive elements of returned
      dataset to combine in a single batch

  Returns:
    A dataset that contains (features, indices) tuple where features is a
      dictionary of Tensors, and indices is a single Tensor of label indices.
  """
  return data_accessor.tf_dataset_factory(
      file_pattern,
      tfxio.TensorFlowDatasetOptions(batch_size=batch_size, label_key=label),
      schema).repeat()

def _build_keras_model(feature_list: List[str]) -> tf.keras.Model:
  """Creates a DNN Keras model for classifying penguin data.

  Args:
    feature_list: List of feature names.

  Returns:
    A Keras Model.
  """
  # The model below is built with Functional API, please refer to
  # https://www.tensorflow.org/guide/keras/overview for all API options.
  inputs = [keras.layers.Input(shape=(1,), name=f) for f in feature_list]
  d = keras.layers.concatenate(inputs)
  for _ in range(constants.NUM_LAYERS):
    d = keras.layers.Dense(constants.HIDDEN_LAYER_UNITS, activation='relu')(d)
  outputs = keras.layers.Dense(
      constants.OUTPUT_LAYER_UNITS, activation='softmax')(
          d)

  model = keras.Model(inputs=inputs, outputs=outputs)
  model.compile(
      optimizer=keras.optimizers.Adam(constants.LEARNING_RATE),
      loss='sparse_categorical_crossentropy',
      metrics=[keras.metrics.SparseCategoricalAccuracy()])

  model.summary(print_fn=logging.info)
  return model

# TFX Trainer will call this function.
# TODO(step 4): Construct, train and save your model in this function.
def run_fn(fn_args: tfx.components.FnArgs):
  """Train the model based on given args.

  Args:
    fn_args: Holds args used to train the model as name/value pairs.
  """
  if fn_args.transform_output is None:  # Transform is not used.
    tf_transform_output = None
    schema = tfx.utils.parse_pbtxt_file(fn_args.schema_file,
                                        schema_pb2.Schema())
    feature_list = features.FEATURE_KEYS
    label_key = features.LABEL_KEY
  else:
    tf_transform_output = tft.TFTransformOutput(fn_args.transform_output)
    schema = tf_transform_output.transformed_metadata.schema
    feature_list = [features.transformed_name(f) for f in features.FEATURE_KEYS]
    label_key = features.transformed_name(features.LABEL_KEY)

  mirrored_strategy = tf.distribute.MirroredStrategy()
  train_batch_size = (
      constants.TRAIN_BATCH_SIZE * mirrored_strategy.num_replicas_in_sync)
  eval_batch_size = (
      constants.EVAL_BATCH_SIZE * mirrored_strategy.num_replicas_in_sync)

  train_dataset = _input_fn(
      fn_args.train_files,
      fn_args.data_accessor,
      schema,
      label_key,
      batch_size=train_batch_size)
  eval_dataset = _input_fn(
      fn_args.eval_files,
      fn_args.data_accessor,
      schema,
      label_key,
      batch_size=eval_batch_size)

  with mirrored_strategy.scope():
    model = _build_keras_model(feature_list)

  # Write logs to path
  tensorboard_callback = tf.keras.callbacks.TensorBoard(
      log_dir=fn_args.model_run_dir, update_freq='batch')

  model.fit(
      train_dataset,
      steps_per_epoch=fn_args.train_steps,
      validation_data=eval_dataset,
      validation_steps=fn_args.eval_steps,
      callbacks=[tensorboard_callback])

  signatures = {
      'serving_default':
          _get_tf_examples_serving_signature(model, schema,
                                             tf_transform_output),
      'transform_features':
          _get_transform_features_signature(model, schema, tf_transform_output),
  }
  model.save(fn_args.serving_model_dir, save_format='tf', signatures=signatures)


text:
require "spec_helper"

RSpec.describe Git::Cop::Styles::CommitAuthorEmail do
  subject(:cop) { described_class.new commit: commit }

  let(:email) { "test@example.com" }
  let(:status) { instance_double Process::Status, success?: true }
  let(:shell) { class_spy Open3, capture2e: ["", status] }

  let :commit do
    object_double Git::Cop::Commits::Saved.new(sha: "abc", shell: shell), author_email: email
  end

  describe ".id" do
    it "answers class ID" do
      expect(described_class.id).to eq(:commit_author_email)
    end
  end

  describe ".label" do
    it "answers class label" do
      expect(described_class.label).to eq("Commit Author Email")
    end
  end

  describe ".defaults" do
    it "answers defaults" do
      expect(described_class.defaults).to eq(
        enabled: true,
        severity: :error
      )
    end
  end

  describe "#valid?" do
    context "with valid email" do
      let(:email) { "test@example.com" }

      it "answers true" do
        expect(cop.valid?).to eq(true)
      end
    end

    context "with invalid email" do
      let(:email) { "invalid" }

      it "answers false" do
        expect(cop.valid?).to eq(false)
      end
    end
  end

  describe "#issue" do
    let(:issue) { cop.issue }

    context "when valid" do
      it "answers empty hash" do
        expect(issue).to eq({})
      end
    end

    context "when invalid" do
      let(:email) { "invalid" }

      it "answers issue hint" do
        expect(issue[:hint]).to eq(%(Use "<name>@<server>.<domain>" instead of "invalid".))
      end
    end
  end
end


text:
angular.module('bettingApp')
  /* Pass in the dependencies incl. the getBets factory */
  /* Full controller approach is handled in the gulp file via ng-annotate */
  .controller('basketCtrl', function($scope, getBets, $routeParams, $http) {
  getBets.then(function(data) {
      //Success
      /* Set variable for use with front end view */
      $scope.dataError = false;
      /* Pass the response data into a scoped variable for use with views */
      $scope.bets = data;
      /* We want to scope the bet variable to the param/url for each individial bet */
      $scope.bet = $scope.bets[$routeParams.bet_id]
  }, function(response) {
      //Error
      /* Set variable for use with front end view */
      $scope.dataError = true;
  });
  // On click of 'place bet' button, run the following function to post and save bet
    $scope.save = function() {
        // Variable declaration, use the $scope attr to retrieve specific bet information
        var bet_id = $scope.bet.bet_id,
            numerator = $scope.bet.odds.numerator,
            denominator = $scope.bet.odds.denominator,
            /* Stake is not part of initial object, hence we don't need to encase it in the 'bet' scope */
            stake = $scope.stake,
            /* Bet object, which creates the necessary information for the post object */
            betInfo = '{"bet_id":' + bet_id +', "odds":{"numerator":'+ numerator +',"denominator":'+ denominator +'}, "stake":' + stake + '}',
            /* As previous creation was a string, convert it to object valid for the post method */
            jsonObj = JSON.parse(betInfo);
        $http.post("https://bedefetechtest.herokuapp.com/v1/bets", jsonObj).success(function(data, status) {
            /* Set variable for use with front end view */
            $scope.betPlaced = true;
            /* Pass the response data into a scoped variable for use with views */
            $scope.slips = data;
            /* Global variable required to pass through the successful post data into a receipt for the user */
            receipt = $scope.slips;
        }).error(function (data, status) {
            /* Set variable for use with front end view */
            $scope.betPlaced = false;
        });
      };
  });


text:
"""Tests for preprocess.py of the CDC Natality import."""

import os
import unittest
import tempfile
import subprocess

_SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))

class CDCNatality(unittest.TestCase):

    def test_csv(self):
        with tempfile.TemporaryDirectory() as tmp_dir:
            csv_path = os.path.join(tmp_dir, 'cleaned.csv')
            mcf_path = os.path.join(tmp_dir, 'output.mcf')
            preprocess_path = os.path.join(_SCRIPT_PATH, 'preprocess.py')
            config_path = os.path.join(_SCRIPT_PATH, 'state',
                                       '16-20_state.json')
            input_path = os.path.join(_SCRIPT_PATH, 'testdata', 'cleaned_data')

            subprocess.call([
                'python', preprocess_path, f'--input_path={input_path}',
                f'--config_path={config_path}', f'--output_path={tmp_dir}'
            ])

            with open(csv_path, 'r', encoding='utf-8') as f_result:
                test_result = f_result.read()
                expected_csv_path = os.path.join(_SCRIPT_PATH, 'testdata',
                                                 'expected.csv')
                with open(expected_csv_path, 'r',
                          encoding='utf-8') as f_expected:
                    expected_result = f_expected.read()
                self.assertEqual(test_result, expected_result)

            with open(mcf_path, 'r', encoding='utf-8') as f_result:
                test_result = f_result.read()
                expected_mcf_path = os.path.join(_SCRIPT_PATH, 'testdata',
                                                 'output.mcf')
                with open(expected_mcf_path, 'r',
                          encoding='utf-8') as f_expected:
                    expected_result = f_expected.read()
                self.assertEqual(test_result, expected_result)


text:
using System.Collections.Generic;

namespace CrosspostSharp3.Weasyl {
	public class WeasylGallery {
		public IEnumerable<WeasylGallerySubmission> submissions;
		public int? backid;
		public int? nextid;
	}
}


text:
var OneSecond = 1000;
var OneMinute = 60*OneSecond;
var OneHour = 60*OneMinute;
var OneDay = 24*OneHour;
var OneWeek = 7*OneDay;

// Date manipulations
function FormatDateTime( InputDate1, Mode)
{
    // InputDate1 cld be a string
    var InputDate = new Date( InputDate1);
    // was RFC2822
    // RSChange(1224,BW,2014.10.10,"October Week 2 Updated")
    if ( Mode == 1)
        return InputDate.toDateString();
    else
    if ( Mode == 3)
       return InputDate.toTimeString();
    // RSChangeEnd(1224)
    return InputDate.toDateString() + InputDate.toTimeString();
}

function FirstMondayOfYear( Year)
{
    var StartTime = new Date( Year, 0, 1, 7, 0);
    // Next Monday will be first Monday of Month
    var DayInWeek = 1;
    if ( StartTime.getDay() < DayInWeek)
      StartTime.setDate( StartTime.getDate() + ( DayInWeek - StartTime.getDay()));
    else
    if ( StartTime.getDay() > DayInWeek)
      StartTime.setDate( StartTime.getDate() + ( 7 + DayInWeek - StartTime.getDay()));
    return StartTime;
}

function MondayOfYearOrWeek( Year, Week)
{
    var StartTime = FirstMondayOfYear( Year);
    // Next Monday will be first Monday of Month
    var DayInWeek = 1;
    if ( StartTime.getDay() < DayInWeek)
      StartTime.setDate( StartTime.getDate() + ( DayInWeek - StartTime.getDay()));
    else
    if ( StartTime.getDay() > DayInWeek)
      StartTime.setDate( StartTime.getDate() + ( 7 + DayInWeek - StartTime.getDay()));
    // Add weeks
    StartTime.setTime( StartTime.getTime() + ( Week - 1) * OneWeek);
    return StartTime;
}

function WeekOfYear( d1)
{
    var StartTime = FirstMondayOfYear( d1.getFullYear());
    var Weeks = Math.ceil((d1.getTime() - StartTime.getTime()) / OneWeek);
    return Weeks;
}

function RSLNGCst( txt) {return txt;}

function PrintTodayOrYesterdayWithTag( DayToPrint, Day)
{
    return ' ' + Day + ' ';
}

function DocWriteLocalDateDayOnly( d)
{
    // display today and yesterday instead of date
    // Today and Yesterday must be computed in User time
    // recent = less than 2 days
    var DayToPrint = d.toLocaleDateString();
    // Test for today must be done in local time
    var Today = new Date();
    // All arithmetic on Date are only possibleof Time in milliseconds, no helper fcts in API see RI729
    // Being Today in Local time means being between Midnight and next Midnight
    // So we reset Today Hours
    // This is 0 AM
    Today.setHours( 0,0,0,0);
    var OneDayinMilliSecond = 24*60*60*1000;
    if (( d.getTime() >= Today.getTime()) && ( d.getTime() <= Today.getTime() + OneDayinMilliSecond))
    {
        DayToPrint = PrintTodayOrYesterdayWithTag( DayToPrint, RSLNGCst( 'Today'));
    }
    else
    if (( d.getTime() >= Today.getTime() - OneDayinMilliSecond) && ( d.getTime() <= Today.getTime()))
    {
        DayToPrint = PrintTodayOrYesterdayWithTag( DayToPrint, RSLNGCst( 'Yesterday'));
    }
    else
    {
        // Prevent date to be splitted
        var re;
        re = / /g;
        // Tue Oct 23 2009 1:53 PM
        DayToPrint = d.toDateString();
        DayToPrint = DayToPrint.replace( re, " ");
    }
    // I want to highlight recent elements. Not asked by Bruno
    // highlight = use of css class KNVRecentItemsDate
    var Recent = ( ( Today.getTime() + OneDayinMilliSecond - d.getTime()) <= 2*OneDayinMilliSecond);
    if(Recent)
    {
        // RSChange(1224,BW,2014.10.10,"October Week 2 Updated")
        return '' + DayToPrint + '';
        // RSChangeEnd(1224)
    }
    else
    {
        // RSChange(1224,BW,2014.10.10,"October Week 2 Updated")
        return DayToPrint;
        // RSChangeEnd(1224)
    }
}

function DocWriteLocalHourInDay( d)
{
    // The toLocaleTimeString returns the time with seconds as a String
    // There is no API to get the local time without seconds
    // I am using the split method to manipulate the result of toLocaleTimeString
    var TimeString = d.toLocaleTimeString().split(":");
    // TimeString[2] is splitted again to get AM/PM
    // RSChange(1224,BW,2014.10.10,"October Week 2 Updated")
    var TimeString2 = TimeString[2].toString().split(" ");
    return " " + TimeString[0] + ":" + TimeString[1] + " " + TimeString2[1]
    // RSChangeEnd(1224)
}

if (typeof exports !== 'undefined')
{
    exports.FormatDateTime = FormatDateTime;
    exports.FirstMondayOfYear = FirstMondayOfYear;
    exports.MondayOfYearOrWeek = MondayOfYearOrWeek;
    exports.WeekOfYear = WeekOfYear;
    exports.OneSecond = OneSecond;
    exports.OneMinute = OneMinute;
    exports.OneHour = OneHour;
    exports.OneDay = OneDay;
    exports.OneWeek = OneWeek;
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See the LICENSE file in the project root for license information.

namespace Mad2WordLib
{
    public enum MadokoBulletType
    {
        Star,
        Plus,
        Dash
    }
}


text:
#ifndef __GTK_CELL_RENDERER_TEXT_H__
#define __GTK_CELL_RENDERER_TEXT_H__

#include <pango/pango.h>
#include <gtk/gtkcellrenderer.h>

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

#define GTK_TYPE_CELL_RENDERER_TEXT		(gtk_cell_renderer_text_get_type ())
#define GTK_CELL_RENDERER_TEXT(obj)		(G_TYPE_CHECK_INSTANCE_CAST ((obj), GTK_TYPE_CELL_RENDERER_TEXT, GtkCellRendererText))
#define GTK_CELL_RENDERER_TEXT_CLASS(klass)	(G_TYPE_CHECK_CLASS_CAST ((klass), GTK_TYPE_CELL_RENDERER_TEXT, GtkCellRendererTextClass))
#define GTK_IS_CELL_RENDERER_TEXT(obj)		(G_TYPE_CHECK_INSTANCE_TYPE ((obj), GTK_TYPE_CELL_RENDERER_TEXT))
#define GTK_IS_CELL_RENDERER_TEXT_CLASS(klass)	(G_TYPE_CHECK_CLASS_TYPE ((klass), GTK_TYPE_CELL_RENDERER_TEXT))
#define GTK_CELL_RENDERER_TEXT_GET_CLASS(obj)   (G_TYPE_INSTANCE_GET_CLASS ((obj), GTK_TYPE_CELL_RENDERER_TEXT, GtkCellRendererTextClass))

typedef struct _GtkCellRendererText      GtkCellRendererText;
typedef struct _GtkCellRendererTextClass GtkCellRendererTextClass;

struct _GtkCellRendererText
{
  GtkCellRenderer parent;

  /*< private >*/
  gchar *text;
  PangoFontDescription *font;
  gdouble font_scale;
  PangoColor foreground;
  PangoColor background;

  PangoAttrList *extra_attrs;

  PangoUnderline underline_style;

  gint rise;
  gint fixed_height_rows;

  guint strikethrough : 1;

  guint editable  : 1;

  guint scale_set : 1;

  guint foreground_set : 1;
  guint background_set : 1;

  guint underline_set : 1;

  guint rise_set : 1;

  guint strikethrough_set : 1;

  guint editable_set : 1;
  guint calc_fixed_height : 1;
};

struct _GtkCellRendererTextClass
{
  GtkCellRendererClass parent_class;

  void (* edited) (GtkCellRendererText *cell_renderer_text,
		   const gchar         *path,
		   const gchar         *new_text);

  /* Padding for future expansion */
  void (*_gtk_reserved1) (void);
  void (*_gtk_reserved2) (void);
  void (*_gtk_reserved3) (void);
  void (*_gtk_reserved4) (void);
};

GType            gtk_cell_renderer_text_get_type (void);
GtkCellRenderer *gtk_cell_renderer_text_new      (void);

void             gtk_cell_renderer_text_set_fixed_height_from_font (GtkCellRendererText *renderer,
								    gint                 number_of_rows);

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* __GTK_CELL_RENDERER_TEXT_H__ */