text:
package org.eclipse.rdf4j.model.base;

import static java.util.Collections.unmodifiableList;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;

import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAmount;
import java.time.temporal.TemporalUnit;
import java.util.List;
import java.util.Map;

/**
 * Component-based temporal amount value.
 *
 * <p>
 * Represents temporal amount values as a collection of {@link ChronoUnit} components.
 * </p>
 *
 * @author Alessandro Bollini
 * @since 3.5.0
 *
 * @apiNote {@link java.time} doesn't include concrete {@link TemporalAmount} classes able to represent XML Schema
 *          duration values including both date and time components.
 */
class ComponentTemporalAmount implements TemporalAmount {

	private final Map<? extends TemporalUnit, Long> components;
	private final List<TemporalUnit> units;

	ComponentTemporalAmount(Map<? extends TemporalUnit, Long> components) {

		this.components = components;

		this.units = unmodifiableList(components.keySet()
				.stream()
				.sorted(comparing(TemporalUnit::getDuration).reversed()) // as per getUnits() specs
				.collect(toList())
		);

	}

	@Override
	public long get(TemporalUnit unit) {
		return components.getOrDefault(unit, 0L);
	}

	@Override
	public List<TemporalUnit> getUnits() {
		return units;
	}

	@Override
	public Temporal addTo(Temporal temporal) {

		Temporal value = temporal;

		for (final Map.Entry<? extends TemporalUnit, Long> component : components.entrySet()) {
			value = value.plus(component.getValue(), component.getKey());
		}

		return value;
	}

	@Override
	public Temporal subtractFrom(Temporal temporal) {

		Temporal value = temporal;

		for (final Map.Entry<? extends TemporalUnit, Long> component : components.entrySet()) {
			value = value.minus(component.getValue(), component.getKey());
		}

		return value;
	}

}

redpajama_set_name: RedPajamaGithub


text:
package fi.harism.cubism;

import java.nio.ByteBuffer;

import android.opengl.Matrix;

public class CubismCube {

	private static ByteBuffer mBufferNormals;
	private static ByteBuffer mBufferNormalsInv;
	private static ByteBuffer mBufferNormalsShadow;
	private static ByteBuffer mBufferVertices;
	private static ByteBuffer mBufferVerticesShadow;
	private static final float SQRT_2 = 1.41421356237f;

	static {
		// Vertex and normal data plus indices arrays.
		final byte[][] CUBEVERTICES = { { -1, 1, 1 }, { -1, -1, 1 },
				{ 1, 1, 1 }, { 1, -1, 1 }, { -1, 1, -1 }, { -1, -1, -1 },
				{ 1, 1, -1 }, { 1, -1, -1 } };
		final byte[][] CUBENORMALS = { { 0, 0, 1 }, { 0, 0, -1 }, { -1, 0, 0 },
				{ 1, 0, 0 }, { 0, 1, 0 }, { 0, -1, 0 } };
		final int[][][] CUBEFILLED = {
				{ { 0, 1, 2, 1, 3, 2 }, { 0 }, { 1 }, { 0, 1, 3, 2 } },
				{ { 6, 7, 4, 7, 5, 4 }, { 1 }, { 0 }, { 6, 7, 5, 4 } },
				{ { 0, 4, 1, 4, 5, 1 }, { 2 }, { 3 }, { 0, 4, 5, 1 } },
				{ { 3, 7, 2, 7, 6, 2 }, { 3 }, { 2 }, { 3, 7, 6, 2 } },
				{ { 4, 0, 6, 0, 2, 6 }, { 4 }, { 5 }, { 4, 0, 2, 6 } },
				{ { 1, 5, 3, 5, 7, 3 }, { 5 }, { 4 }, { 1, 5, 7, 3 } } };

		mBufferVertices = ByteBuffer.allocateDirect(3 * 6 * 6);
		mBufferNormals = ByteBuffer.allocateDirect(3 * 6 * 6);
		mBufferNormalsInv = ByteBuffer.allocateDirect(3 * 6 * 6);
		mBufferVerticesShadow = ByteBuffer.allocateDirect(4 * 6 * 24);
		mBufferNormalsShadow = ByteBuffer.allocateDirect(3 * 6 * 24);

		final byte C = 1, P = 0;
		for (int i = 0; i < CUBEFILLED.length; ++i) {
			for (int j = 0; j < CUBEFILLED[i][0].length; ++j) {
				mBufferVertices.put(CUBEVERTICES[CUBEFILLED[i][0][j]]);
				mBufferNormals.put(CUBENORMALS[CUBEFILLED[i][1][0]]);
				mBufferNormalsInv.put(CUBENORMALS[CUBEFILLED[i][2][0]]);
			}

			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][0]]).put(C);
			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][0]]).put(P);
			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][1]]).put(C);
			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][0]]).put(P);
			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][1]]).put(P);
			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][1]]).put(C);

			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][1]]).put(C);
			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][1]]).put(P);
			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][2]]).put(C);
			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][1]]).put(P);
			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][2]]).put(P);
			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][2]]).put(C);

			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][2]]).put(C);
			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][2]]).put(P);
			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][3]]).put(C);
			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][2]]).put(P);
			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][3]]).put(P);
			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][3]]).put(C);

			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][3]]).put(C);
			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][3]]).put(P);
			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][0]]).put(C);
			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][3]]).put(P);
			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][0]]).put(P);
			mBufferVerticesShadow.put(CUBEVERTICES[CUBEFILLED[i][3][0]]).put(C);

			for (int j = 0; j < 24; ++j) {
				mBufferNormalsShadow.put(CUBENORMALS[CUBEFILLED[i][1][0]]);
			}
		}
		mBufferVertices.position(0);
		mBufferNormals.position(0);
		mBufferNormalsInv.position(0);

		mBufferVertices.position(0);
		mBufferNormals.position(0);
		mBufferNormalsInv.position(0);

		mBufferVerticesShadow.position(0);
		mBufferNormalsShadow.position(0);
	}

	public static ByteBuffer getNormals() {
		return mBufferNormals;
	}

	public static ByteBuffer getNormalsInv() {
		return mBufferNormalsInv;
	}

	public static ByteBuffer getNormalsShadow() {
		return mBufferNormalsShadow;
	}

	public static ByteBuffer getVertices() {
		return mBufferVertices;
	}

	public static ByteBuffer getVerticesShadow() {
		return mBufferVerticesShadow;
	}

	private final float[] mBoundingSphere = new float[4];
	private final float[] mColor = new float[3];
	private final float[] mMatrixModel = new float[16];
	private final float[] mMatrixRotate = new float[16];
	private final float[] mMatrixScale = new float[16];
	private final float[] mMatrixTranslate = new float[16];
	private boolean mRecalculate;

	public CubismCube() {
		Matrix.setIdentityM(mMatrixRotate, 0);
		Matrix.setIdentityM(mMatrixScale, 0);
		Matrix.setIdentityM(mMatrixTranslate, 0);
		Matrix.setIdentityM(mMatrixModel, 0);
		mBoundingSphere[3] = SQRT_2;
	}

	public float[] getBoundingSphere() {
		return mBoundingSphere;
	}

	public float[] getColor() {
		return mColor;
	}

	public float[] getModelM() {
		if (mRecalculate) {
			Matrix.multiplyMM(mMatrixModel, 0, mMatrixRotate, 0, mMatrixScale,
					0);
			Matrix.multiplyMM(mMatrixModel, 0, mMatrixTranslate, 0,
					mMatrixModel, 0);
			mRecalculate = false;
		}
		return mMatrixModel;
	}

	public void setColor(float r, float g, float b) {
		mColor[0] = r;
		mColor[1] = g;
		mColor[2] = b;
	}

	public void setRotate(float rx, float ry, float rz) {
		CubismUtils.setRotateM(mMatrixRotate, rx, ry, rz);
		mRecalculate = true;
	}

	public void setScale(float scale) {
		Matrix.setIdentityM(mMatrixScale, 0);
		Matrix.scaleM(mMatrixScale, 0, scale, scale, scale);
		mBoundingSphere[3] = SQRT_2 * scale;
		mRecalculate = true;
	}

	public void setTranslate(float tx, float ty, float tz) {
		Matrix.setIdentityM(mMatrixTranslate, 0);
		Matrix.translateM(mMatrixTranslate, 0, tx, ty, tz);
		mBoundingSphere[0] = tx;
		mBoundingSphere[1] = ty;
		mBoundingSphere[2] = tz;
		mRecalculate = true;
	}

}


text:
namespace mongocxx {
MONGOCXX_INLINE_NAMESPACE_BEGIN

///
/// Class representing a MongoDB index view.
///
class MONGOCXX_API index_view {
   public:
    index_view(index_view&&) noexcept;
    index_view& operator=(index_view&&) noexcept;

    ~index_view();

    ///
    /// @{
    ///
    /// Returns a cursor over all the indexes.
    ///
    cursor list();

    ///
    /// Returns a cursor over all the indexes.
    ///
    /// @param session
    ///   The mongocxx::client_session with which to perform the list operation.
    ///
    cursor list(const client_session& session);

    ///
    /// @}
    ///

    ///
    /// @{
    ///
    /// Creates an index. A convenience method that calls create_many.
    ///
    /// @param keys
    ///    A document containing the index keys and their corresponding index types.
    /// @param index_options
    ///    A document containing set of options that controls the creation of the index. See
    ///    https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/.
    /// @param options
    ///    Optional arguments for the overall operation, see mongocxx::options::index_view.
    ///
    /// @return
    ///    An optional containing the name of the created index. If and index with the same keys
    ///    already exists, an empty optional is returned.
    ///
    /// @exception
    ///    Throws operation_exception for any errors encountered by the server or if max_time_ms
    ///    option is present and the operation exceeds the time limit.
    ///
    /// @see https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/
    ///
    stdx::optional<std::string> create_one(
        const bsoncxx::document::view_or_value& keys,
        const bsoncxx::document::view_or_value& index_options = {},
        const options::index_view& options = options::index_view{});

    ///
    /// Creates an index. A convenience method that calls create_many.
    ///
    /// @param session
    ///   The mongocxx::client_session with which to perform the operation.
    /// @param keys
    ///    A document containing the index keys and their corresponding index types.
    /// @param index_options
    ///    A document containing set of options that controls the creation of the index. See
    ///    https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/.
    /// @param options
    ///    Optional arguments for the overall operation, see mongocxx::options::index_view.
    ///
    /// @return
    ///    An optional containing the name of the created index. If and index with the same keys
    ///    already exists, an empty optional is returned.
    ///
    /// @exception
    ///    Throws operation_exception for any errors encountered by the server or if max_time_ms
    ///    option is present and the operation exceeds the time limit.
    ///
    /// @see https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/
    ///
    stdx::optional<std::string> create_one(
        const client_session& session,
        const bsoncxx::document::view_or_value& keys,
        const bsoncxx::document::view_or_value& index_options = {},
        const options::index_view& options = options::index_view{});

    ///
    /// @}
    ///

    ///
    /// @{
    ///
    /// Creates an index. A convenience method that calls create_many.
    ///
    /// @param index
    ///    Index_model describing the index being created.
    /// @param options
    ///    Optional arguments for the overall operation, see mongocxx::options::index_view.
    ///
    /// @return
    ///    An optional containing the name of the created index. If and index with the same keys
    ///    already exists, an empty optional is returned.
    ///
    /// @exception
    ///    Throws operation_exception for any errors encountered by the server or if max_time_ms
    ///    option is present and the operation exceeds the time limit.
    ///
    /// @see https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/
    ///
    stdx::optional<std::string> create_one(
        const index_model& index, const options::index_view& options = options::index_view{});

    ///
    /// Creates an index. A convenience method that calls create_many.
    ///
    /// @param session
    ///   The mongocxx::client_session with which to perform the operation.
    /// @param index
    ///    Index_model describing the index being created.
    /// @param options
    ///    Optional arguments for the overall operation, see mongocxx::options::index_view.
    ///
    /// @return
    ///    An optional containing the name of the created index. If and index with the same keys
    ///    already exists, an empty optional is returned.
    ///
    /// @exception
    ///    Throws operation_exception for any errors encountered by the server or if max_time_ms
    ///    option is present and the operation exceeds the time limit.
    ///
    /// @see https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/
    ///
    stdx::optional<std::string> create_one(
        const client_session& session,
        const index_model& index,
        const options::index_view& options = options::index_view{});

    ///
    /// @}
    ///

    ///
    /// @{
    ///
    /// Adds a container of indexes to the collection.
    ///
    /// @param indexes
    ///   std::vector containing index models describing the indexes being created.
    /// @param options
    ///    Optional arguments for the overall operation, see mongocxx::options::index_view.
    ///
    /// @return
    ///    The result document sent back by the server as if the createIndexes command was run from
    ///    the shell.
    ///
    /// @exception
    ///     Throws operation_exception for any errors encountered by the server or if max_time_ms
    ///     option is present and the operation exceeds the time limit.
    ///
    /// @see https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/
    ///
    bsoncxx::document::value create_many(
        const std::vector<index_model>& indexes,
        const options::index_view& options = options::index_view{});

    ///
    /// Adds a container of indexes to the collection.
    ///
    /// @param session
    ///   The mongocxx::client_session with which to perform the operation.
    /// @param indexes
    ///   std::vector containing index models describing the indexes being created.
    /// @param options
    ///    Optional arguments for the overall operation, see mongocxx::options::index_view.
    ///
    /// @return
    ///    The result document sent back by the server as if the createIndexes command was run from
    ///    the shell.
    ///
    /// @exception
    ///     Throws operation_exception for any errors encountered by the server or if max_time_ms
    ///     option is present and the operation exceeds the time limit.
    ///
    /// @see https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/
    ///
    bsoncxx::document::value create_many(
        const client_session& session,
        const std::vector<index_model>& indexes,
        const options::index_view& options = options::index_view{});

    ///
    /// @}
    ///

    ///
    /// @{
    ///
    /// Drops a single index by name.
    ///
    /// @param name
    ///    The name of the index being dropped.
    /// @param options
    ///    Optional arguments for the overall operation, see mongocxx::options::index_view.
    ///
    /// @exception
    ///   Throws operation_exception for any errors encountered by the server or if max_time_ms
    ///   option is present and the operation exceeds the time limit.
    /// @exception
    ///   Throws logic_error if "*" is passed in for the index name.
    ///
    /// @see https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/
    ///
    void drop_one(stdx::string_view name,
                  const options::index_view& options = options::index_view{});

    ///
    /// Drops a single index by name.
    ///
    /// @param session
    ///   The mongocxx::client_session with which to perform the drop.
    /// @param name
    ///    The name of the index being dropped.
    /// @param options
    ///    Optional arguments for the overall operation, see mongocxx::options::index_view.
    ///
    /// @exception
    ///   Throws operation_exception for any errors encountered by the server or if max_time_ms
    ///   option is present and the operation exceeds the time limit.
    /// @exception
    ///   Throws logic_error if "*" is passed in for the index name.
    ///
    /// @see https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/
    ///
    void drop_one(const client_session& session,
                  stdx::string_view name,
                  const options::index_view& options = options::index_view{});

    ///
    /// @}
    ///

    ///
    /// @{
    ///
    /// Attempts to drop a single index from the collection given the keys and options.
    ///
    /// @param keys
    ///    A document containing the index keys and their corresponding index types. If no name
    ///    option is present in the options, a name based on the keys will be used.
    /// @param index_options (optional)
    ///    A document containing set of options used to create the index. Only the name field will
    ///    be used from here, and if it is not included, a name based on they keys will be used.
    /// @param options
    ///    Optional arguments for the overall operation, see mongocxx::options::index_view.
    ///
    /// @exception
    ///   Throws bsoncxx::exception if "name" key is present in options but is not a string.
    /// @exception
    ///   Throws operation_exception for any errors encountered by the server or if max_time_ms
    ///   option is present and the operation exceeds the time limit.
    /// @exception
    ///   Throws logic_error if "*" is passed in for the index name
    ///
    /// @see https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/
    ///
    void drop_one(const bsoncxx::document::view_or_value& keys,
                  const bsoncxx::document::view_or_value& index_options = {},
                  const options::index_view& options = options::index_view{});

    ///
    /// Attempts to drop a single index from the collection given the keys and options.
    ///
    /// @param session
    ///   The mongocxx::client_session with which to perform the drop.
    /// @param keys
    ///    A document containing the index keys and their corresponding index types. If no name
    ///    option is present in the options, a name based on the keys will be used.
    /// @param index_options (optional)
    ///    A document containing set of options used to create the index. Only the name field will
    ///    be used from here, and if it is not included, a name based on they keys will be used.
    /// @param options
    ///    Optional arguments for the overall operation, see mongocxx::options::index_view.
    ///
    /// @exception
    ///   Throws bsoncxx::exception if "name" key is present in options but is not a string.
    /// @exception
    ///   Throws operation_exception for any errors encountered by the server or if max_time_ms
    ///   option is present and the operation exceeds the time limit.
    /// @exception
    ///   Throws logic_error if "*" is passed in for the index name
    ///
    /// @see https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/
    ///
    void drop_one(const client_session& session,
                  const bsoncxx::document::view_or_value& keys,
                  const bsoncxx::document::view_or_value& index_options = {},
                  const options::index_view& options = options::index_view{});

    ///
    /// @}
    ///

    ///
    /// @{
    ///
    /// Attempts to drop a single index from the collection given an index model.
    ///
    /// @param index
    ///    An index model describing the index being dropped.
    /// @param options
    ///    Optional arguments for the overall operation, see mongocxx::options::index_view.
    ///
    /// @exception
    ///   Throws bsoncxx::exception if "name" key is present in options but is not a string.
    /// @exception
    ///   Throws operation_exception for any errors encountered by the server or if max_time_ms
    ///   option is present and the operation exceeds the time limit.
    /// @exception
    ///   Throws logic_error if "*" is passed in for the index name
    ///
    /// @see https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/
    ///
    void drop_one(const index_model& index,
                  const options::index_view& options = options::index_view{});

    ///
    /// Attempts to drop a single index from the collection given an index model.
    ///
    /// @param session
    ///   The mongocxx::client_session with which to perform the drop.
    /// @param index
    ///    An index model describing the index being dropped.
    /// @param options
    ///    Optional arguments for the overall operation, see mongocxx::options::index_view.
    ///
    /// @exception
    ///   Throws bsoncxx::exception if "name" key is present in options but is not a string.
    /// @exception
    ///   Throws operation_exception for any errors encountered by the server or if max_time_ms
    ///   option is present and the operation exceeds the time limit.
    /// @exception
    ///   Throws logic_error if "*" is passed in for the index name
    ///
    /// @see https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/
    ///
    void drop_one(const client_session& session,
                  const index_model& index,
                  const options::index_view& options = options::index_view{});

    ///
    /// @}
    ///

    ///
    /// @{
    ///
    /// Drops all indexes in the collection.
    ///
    /// @param options
    ///    Optional arguments for the overall operation, see mongocxx::options::index_view.
    ///
    /// @exception
    ///   Throws operation_exception for any errors encountered by the server or if max_time_ms
    ///   option is present and the operation exceeds the time limit.
    ///
    /// @see https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/
    ///
    void drop_all(const options::index_view& options = options::index_view{});

    ///
    /// Drops all indexes in the collection.
    ///
    /// @param session
    ///   The mongocxx::client_session with which to perform the drop.
    /// @param options
    ///    Optional arguments for the overall operation, see mongocxx::options::index_view.
    ///
    /// @exception
    ///   Throws operation_exception for any errors encountered by the server or if max_time_ms
    ///   option is present and the operation exceeds the time limit.
    ///
    /// @see https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/
    ///
    void drop_all(const client_session& session,
                  const options::index_view& options = options::index_view{});

    ///
    /// @}
    ///

   private:
    friend class collection;
    class MONGOCXX_PRIVATE impl;

    MONGOCXX_PRIVATE index_view(void* coll, void* client);

    MONGOCXX_PRIVATE impl& _get_impl();

   private:
    std::unique_ptr<impl> _impl;
};

MONGOCXX_INLINE_NAMESPACE_END
}  // namespace mongocxx

#include <mongocxx/config/postlude.hpp>


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="net.lateralview.simplerestclienthandler">

    <application />

</manifest>


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pl.programa.beerquest"
    android:versionCode="1"
    android:versionName="1.00" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="16" />
    <permission
        android:name="pl.programa.beerquest.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="pl.programa.beerquest.permission.C2D_MESSAGE" />
    <!-- App receives GCM messages. -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <!-- Keeps the processor from sleeping when a message is received. -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />

    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_GPS" />
    <uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />

    <supports-screens
        android:anyDensity="true"
        android:largeScreens="true"
        android:normalScreens="true"
        android:resizeable="false"
        android:smallScreens="true"
        android:xlargeScreens="true" />

    <uses-permission android:name="android.permission.VIBRATE" />

    <application
        android:name="pl.programa.beerquest.app.App"
        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:killAfterRestore="true"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Light.NoTitleBar" >
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyBFi-3TiYTqH6DYxsrrMyEBoMM4QqqpaV8" />

        <activity
            android:name="pl.programa.beerquest.LoginActivity"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="adjustResize|stateVisible" >
        </activity>
        <activity
            android:name="pl.programa.beerquest.MainActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="adjustPan" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="pl.programa.beerquest.RecognitionActivity"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
            </intent-filter>
        </activity>
        <activity
            android:name="pl.programa.beerquest.NewQuestActivity"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name="pl.programa.beerquest.QuestInfoActivity"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:screenOrientation="portrait" >
        </activity>
        <receiver
            android:name="com.google.android.gcm.GCMBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

                <category android:name="pl.programa.beerquest" />
            </intent-filter>
        </receiver>

        <service android:name=".GCMIntentService" />

    </application>

</manifest>


text:
<?xml version='1.0' encoding='UTF-8'?>
<DEFECTS><DEFECT><SFA><FILEPATH>c:\somepath\</FILEPATH><FILENAME>test021.cpp</FILENAME><LINE>6</LINE><COLUMN>7</COLUMN></SFA><DEFECTCODE>26006</DEFECTCODE><DESCRIPTION>Possibly incorrect single element annotation on string buffer
PREFAST_NEWLINE
Read overflow using expression '(const void *)b'
PREFAST_NEWLINE
Buffer b is a parameter to this function declared on line 3
PREFAST_NEWLINE
Buffer lengths are from an assumed __inout annotation on the parameter
PREFAST_NEWLINE
Buffer is of length offset(b)`3 + 1 bytes [from annotation valid(elementCount(1)) at c:\somepath\test021.cpp(3)]
PREFAST_NEWLINE
Accessing 11 bytes starting at byte offset 0
PREFAST_NEWLINE
Annotation on function memcpy requires that {parameter 2} is of length >= {parameter 3} bytes
PREFAST_NEWLINE
  where {parameter 2} is (const void *)b; {parameter 3} is 11
PREFAST_NEWLINE
[Annotation _In_(byteCount({parameter 3}))]
PREFAST_NEWLINE

PREFAST_NEWLINE

PREFAST_NEWLINE
Values of variables:
PREFAST_NEWLINE
Pointer b is at offset 0 bytes from the start of the buffer
PREFAST_NEWLINE
</DESCRIPTION><FUNCTION>f</FUNCTION><DECORATED>?f@@YAXPAD@Z</DECORATED><FUNCLINE>3</FUNCLINE><PATH><SFA><FILEPATH>c:\somepath\</FILEPATH><FILENAME>test021.cpp</FILENAME><LINE>3</LINE><COLUMN>5</COLUMN></SFA><SFA><FILEPATH>c:\somepath\</FILEPATH><FILENAME>test021.cpp</FILENAME><LINE>5</LINE><COLUMN>6</COLUMN></SFA><SFA><FILEPATH>c:\somepath\</FILEPATH><FILENAME>test021.cpp</FILENAME><LINE>6</LINE><COLUMN>7</COLUMN></SFA></PATH></DEFECT><DEFECT><SFA><FILEPATH>c:\somepath\</FILEPATH><FILENAME>test021.cpp</FILENAME><LINE>6</LINE><COLUMN>7</COLUMN></SFA><DEFECTCODE>26000</DEFECTCODE><DESCRIPTION>Overflow using expression '(void *)(& a)'
PREFAST_NEWLINE
Buffer accessed is a
PREFAST_NEWLINE
Buffer is of length 10 bytes [size of variable]
PREFAST_NEWLINE
Accessing 11 bytes starting at byte offset 0
PREFAST_NEWLINE
Annotation on function memcpy requires that {parameter 1} is of length >= {parameter 3} bytes
PREFAST_NEWLINE
  where {parameter 1} is (void *)(& a); {parameter 3} is 11
PREFAST_NEWLINE
[Annotation _Out_(byteCount({parameter 3}))]
PREFAST_NEWLINE

PREFAST_NEWLINE
</DESCRIPTION><FUNCTION>f</FUNCTION><DECORATED>?f@@YAXPAD@Z</DECORATED><FUNCLINE>3</FUNCLINE><PATH><SFA><FILEPATH>c:\somepath\</FILEPATH><FILENAME>test021.cpp</FILENAME><LINE>3</LINE><COLUMN>5</COLUMN></SFA><SFA><FILEPATH>c:\somepath\</FILEPATH><FILENAME>test021.cpp</FILENAME><LINE>5</LINE><COLUMN>6</COLUMN></SFA><SFA><FILEPATH>c:\somepath\</FILEPATH><FILENAME>test021.cpp</FILENAME><LINE>6</LINE><COLUMN>7</COLUMN></SFA></PATH></DEFECT></DEFECTS>


text:
require 'spec_helper'

require 'flapjack/data/check'

describe Flapjack::Data::Check, :redis => true do

  let(:half_an_hour) { 30 * 60 }

  let(:check_name)  { 'foo.example.com:PING' }

  let(:redis) { Flapjack.redis }

  it "allows an id that is a UUID" do
    check = Flapjack::Data::Check.new(:id => '20f182fc-6e32-4794-9007-97366d162c51')
    check.valid?
    expect(check.errors).not_to be_nil
    expect(check.errors[:id]).to be_an(Array)
    expect(check.errors[:id]).to be_empty
  end

  it "does not allow an id that is not a UUID" do
    check = Flapjack::Data::Check.new(:id => 'hello')
    check.valid?
    expect(check.errors).not_to be_nil
    expect(check.errors[:id]).to be_an(Array)
    expect(check.errors[:id]).to include('is not a UUID')
  end

  context "maintenance" do

    it "returns that it is not in unscheduled maintenance" do
      Factory.check(:name => check_name, :id => 1)

      check = Flapjack::Data::Check.intersect(:name => check_name).all.first
      expect(check).not_to be_in_unscheduled_maintenance
    end

    it "returns that it is not in scheduled maintenance" do
      Factory.check(:name => check_name, :id => 1)

      check = Flapjack::Data::Check.intersect(:name => check_name).all.first
      expect(check).not_to be_in_scheduled_maintenance
    end

    it "returns its current scheduled maintenance period" do
      Factory.check(:name => check_name, :id => 1)

      t = Time.now

      check = Flapjack::Data::Check.intersect(:name => check_name).all.first
      expect(check.scheduled_maintenance_at(t)).to be_nil

      sm = Flapjack::Data::ScheduledMaintenance.new(:start_time => t,
        :end_time => Time.at(t.to_i + 2400), :summary => 'planned')
      sm.save
      check.add_scheduled_maintenance(sm)

      lsm = Flapjack::Data::ScheduledMaintenance.new(:start_time => Time.at(t.to_i + 3600),
        :end_time => Time.at(t.to_i + 4800), :summary => 'later')
      lsm.save
      check.add_scheduled_maintenance(lsm)

      future = Time.at(t.to_i + 30)

      Delorean.time_travel_to(future)

      expect(check).to be_in_scheduled_maintenance

      csm = check.scheduled_maintenance_at(future)
      expect(csm).not_to be_nil
      expect(csm.summary).to eq('planned')
    end

    it "adds an unscheduled maintenance period" do
      Factory.check(:name => check_name, :id => 1)

      check = Flapjack::Data::Check.intersect(:name => check_name).all.first

      t = Time.now

      usm = Flapjack::Data::UnscheduledMaintenance.new(:start_time => t,
        :end_time => t + 2400, :summary => 'impromptu')
      usm.save
      check.set_unscheduled_maintenance(usm)

      Delorean.time_travel_to( Time.at(t.to_i + 15) )

      expect(check).to be_in_unscheduled_maintenance

      usms = check.unscheduled_maintenances_by_start.all
      expect(usms).to be_an(Array)
      expect(usms.size).to eq(1)
      expect(usms.first.summary).to eq('impromptu')
      usme = check.unscheduled_maintenances_by_end.all
      expect(usme).to be_an(Array)
      expect(usme.size).to eq(1)
      expect(usme.first.summary).to eq('impromptu')
    end

    it "adds an unscheduled maintenance period and ends the current one early", :time => true do
      Factory.check(:name => check_name, :id => 1)

      check = Flapjack::Data::Check.intersect(:name => check_name).all.first

      t = Time.now
      later_t = t.to_i + (15 * 60)
      usm_a = Flapjack::Data::UnscheduledMaintenance.new(:start_time => t,
        :end_time => t.to_i + half_an_hour, :summary => 'scooby')
      usm_a.save
      check.set_unscheduled_maintenance(usm_a)

      Delorean.time_travel_to( Time.at(later_t) )

      usm_b = Flapjack::Data::UnscheduledMaintenance.new(:start_time => later_t,
        :end_time => later_t + half_an_hour, :summary => 'shaggy')
      usm_b.save
      check.set_unscheduled_maintenance(usm_b)

      expect(check).to be_in_unscheduled_maintenance

      usms = check.unscheduled_maintenances_by_start.all
      expect(usms).to be_an(Array)
      expect(usms.size).to eq(2)
      expect(usms.map(&:summary)).to eq(['scooby', 'shaggy'])

      expect(usms.first.end_time.to_i).to eq(later_t)
      expect(usms.last.end_time.to_i).to eq(later_t + half_an_hour)
    end

    it "ends an unscheduled maintenance period", :time => true do
      Factory.check(:name => check_name, :id => 1)

      check = Flapjack::Data::Check.intersect(:name => check_name).all.first

      t = Time.now
      later_t = Time.at(t.to_i + (15 * 60))
      usm_a = Flapjack::Data::UnscheduledMaintenance.new(:start_time => t,
        :end_time => Time.at(t.to_i + half_an_hour), :summary => 'scooby')
      usm_a.save
      check.set_unscheduled_maintenance(usm_a)

      Delorean.time_travel_to( later_t )
      expect(check).to be_in_unscheduled_maintenance
      check.clear_unscheduled_maintenance(later_t)

      Delorean.time_travel_to( Time.at(later_t.to_i + 10) )

      expect(check).not_to be_in_unscheduled_maintenance

      usms = check.unscheduled_maintenances_by_start.all
      expect(usms).to be_an(Array)
      expect(usms.size).to eq(1)
      expect(usms.first.end_time.to_i).to eq(later_t.to_i)
    end

    it "ends a scheduled maintenance period for a future time" do
      Factory.check(:name => check_name, :id => 1)

      check = Flapjack::Data::Check.intersect(:name => check_name).all.first

      t = Time.now

      sm = Flapjack::Data::ScheduledMaintenance.new(:start_time => t.to_i + (60 * 60),
        :end_time => t.to_i + (3 * 60 * 60), :summary => '2 hours')
      sm.save
      check.add_scheduled_maintenance(sm)

      sms = check.scheduled_maintenances_by_start.all
      expect(sms).to be_an(Array)
      expect(sms.size).to eq(1)
      expect(sms.first.summary).to eq('2 hours')

      check.end_scheduled_maintenance(sm, t)
      sms = check.scheduled_maintenances_by_start.all
      expect(sms).to be_an(Array)
      expect(sms).to be_empty
    end

    # maint period starts an hour from now, goes for two hours -- at 30 minutes into
    # it we stop it, and its duration should be 30 minutes
    it "shortens a scheduled maintenance period covering a current time", :time => true do
      Factory.check(:name => check_name, :id => 1)

      check = Flapjack::Data::Check.intersect(:name => check_name).all.first

      t = Time.now
      sm = Flapjack::Data::ScheduledMaintenance.new(:start_time => t.to_i + (60 * 60),
        :end_time => t.to_i + (3 * 60 * 60), :summary => '1 hour')
      sm.save
      check.add_scheduled_maintenance(sm)

      future = Time.at(t.to_i + (90 * 60))

      Delorean.time_travel_to(future)

      check.end_scheduled_maintenance(sm, future)

      sms = check.scheduled_maintenances_by_start.all
      expect(sms).to be_an(Array)
      expect(sms.size).to eq(1)
      expect(sms.first.end_time.to_i).to eq(future.to_i)
    end

    it "does not alter or remove a scheduled maintenance period covering a past time", :time => true do
      Factory.check(:name => check_name, :id => 1)

      check = Flapjack::Data::Check.intersect(:name => check_name).all.first

      t = Time.now
      sm = Flapjack::Data::ScheduledMaintenance.new(:start_time => t.to_i + (60 * 60),
        :end_time => t.to_i + (3 * 60 * 60), :summary => '1 hour')
      sm.save
      check.add_scheduled_maintenance(sm)

      future = Time.at(t.to_i + (6 * (60 * 60)) )

      Delorean.time_travel_to(future)

      check.end_scheduled_maintenance(sm, future)

      sms = check.scheduled_maintenances_by_start.all
      expect(sms).to be_an(Array)
      expect(sms.size).to eq(1)
      expect(sms.first.end_time.to_i).to eq(t.to_i + (3 * 60 * 60))
    end

  end

end


text: Smart and simple tournament organiser


text:
require 'brick_ftp/restful_api'

module BrickFTP
  # To delegate commands.
  #
  # @see BrickFTP::RESTfulAPI
  # @example Call {BrickFTP::RESTfulAPI::ListUser#call}
  #   BrickFTP::Client.new.list_users
  #
  class Client
    attr_reader :base_url, :api_key, :api_client

    # @param [String] base_url
    # @param [String] subdomain (deprecated)
    # @param [String] api_key
    def initialize(base_url: nil, subdomain: nil, api_key: nil)
      if subdomain
        warn('DEPRECATION WARNING: The argument `subdomain:` will be deprecated in a future version.' \
             ' Please use `base_url:` instead.')
      end

      @subdomain = subdomain || ENV['BRICK_FTP_SUBDOMAIN']
      @base_url = base_url || ENV['BRICK_FTP_BASE_URL']
      @api_key = api_key || ENV['BRICK_FTP_API_KEY']
      @api_client = BrickFTP::RESTfulAPI::Client.new(@base_url || @subdomain, @api_key)
    end

    def subdomain
      warn("DEPRECATION WARNING: #{self.class.name}##{__method__} will be deprecated in a future version.")
      @subdomain
    end

    private

    def command_class(symbol)
      name = symbol.to_s.split('_').map(&:capitalize).join
      return unless BrickFTP::RESTfulAPI.const_defined?(name)

      klass = BrickFTP::RESTfulAPI.const_get(name)
      return unless klass < BrickFTP::RESTfulAPI::Command

      klass
    end

    def respond_to_missing?(symbol, include_private)
      return true if command_class(symbol)

      super
    end

    def method_missing(name, *args)
      klass = command_class(name)
      if klass
        dispatch_command(klass, *args)
      else
        super
      end
    end
    ruby2_keywords :method_missing if respond_to?(:ruby2_keywords, true)

    def dispatch_command(klass, *args)
      klass.new(api_client).call(*args)
    end
    ruby2_keywords :dispatch_command if respond_to?(:ruby2_keywords, true)
  end
end


text:
package com.boveybrawlers.AbsoluteCraft.managers;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;

import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import com.boveybrawlers.AbsoluteCraft.ACPlayer;
import com.boveybrawlers.AbsoluteCraft.AbsoluteCraft;

public class PlayerManager {

	public AbsoluteCraft plugin;
	private List<ACPlayer> players = new ArrayList<ACPlayer>();

	public PlayerManager(AbsoluteCraft plugin) {
		this.plugin = plugin;
	}

	/**
	 * Get a list of all players
	 *
	 * @return List of ACPlayers
	 */
	public List<ACPlayer> all() {
		return this.players;
	}

	/**
	 * Add a Player to the players list
	 *
	 * @param player
	 * @return ACPlayer
	 */
	public ACPlayer add(Player player) {
		ACPlayer acPlayer = this.find(player);
		if(acPlayer != null) {
			return acPlayer;
		}

		acPlayer = new ACPlayer(this.plugin);
		acPlayer.setPlayer(player);
		this.players.add(acPlayer);

		return acPlayer;
	}

	/**
	 * Remove an ACPlayer from the players list
	 *
	 * @param player
	 * @return
	 */
	public boolean remove(ACPlayer player) {
		return this.players.remove(player);
	}

	/**
	 * Remove a Player from the players list
	 *
	 * @param player
	 * @return
	 */
	public boolean remove(Player player) {
		ACPlayer acPlayer = this.find(player);
		if(acPlayer != null) {
			return this.players.remove(acPlayer);
		}

		return false;
	}

	/**
	 * Find an ACPlayer by username
	 *
	 * @param username
	 * @return
	 */
	public ACPlayer find(String username) {
		for(ACPlayer player : players) {
			if(player.p.getName().equals(username)) {
				return player;
			}
		}

		return null;
	}

	/**
	 * Find an ACPlayer by Player
	 *
	 * @param player
	 * @return
	 */
	public ACPlayer find(Player player) {
        for(ACPlayer acPlayer : players) {
            OfflinePlayer offP = (OfflinePlayer) acPlayer.getPlayer();
            if(offP.getUniqueId().equals(player.getUniqueId())) {
                return acPlayer;
            }
        }

		return null;
	}

	/**
	 * Find an ACPlayer by CommandSender
	 *
	 * @param sender
	 * @return
	 */
	public ACPlayer find(CommandSender sender) {
		if(sender instanceof Player) {
			return this.find((Player) sender);
		}

		return null;
	}

}


text:
from mfr import settings

config = settings.child('OSF_PROVIDER_CONFIG')

MFR_IDENTIFYING_HEADER = config.get('MFR_IDENTIFYING_HEADER', 'X-Cos-Mfr-Render-Request')
MFR_ACTION_HEADER = config.get('MFR_ACTION_HEADER', 'X-Cos-Mfr-Request-Action')


text:
Please download the Enron email dataset enron.zip, unzip it and then restore it using mongorestore. It should restore to a collection called "messages" in a database called "enron". Note that this is an abbreviated version of the full corpus. There should be 120,477 documents after restore.

Inspect a few of the documents to get a basic understanding of the structure. Enron was an American corporation that engaged in a widespread accounting fraud and subsequently failed.

In this dataset, each document is an email message. Like all Email messages, there is one sender but there can be multiple recipients.

Construct a query to calculate the number of messages sent by Andrew Fastow, CFO, to Jeff Skilling, the president. Andrew Fastow's email addess was andrew.fastow@enron.com. Jeff Skilling's email was jeff.skilling@enron.com.

For reference, the number of email messages from Andrew Fastow to John Lavorato (john.lavorato@enron.com) was 1.

1. 1
2. 3
3. 5
4. 7
5. 9
6. 12

Answer: 1


text:
<?php

namespace Symfony\Component\Process\Pipes;

use Symfony\Component\Process\Process;

/**
 * UnixPipes implementation uses unix pipes as handles.
 *
 * @author Romain Neutron <imprec@gmail.com>
 *
 * @internal
 */
class UnixPipes extends AbstractPipes
{
    private $ttyMode;
    private $ptyMode;
    private $haveReadSupport;

    public function __construct(?bool $ttyMode, bool $ptyMode, mixed $input, bool $haveReadSupport)
    {
        $this->ttyMode = $ttyMode;
        $this->ptyMode = $ptyMode;
        $this->haveReadSupport = $haveReadSupport;

        parent::__construct($input);
    }

    public function __sleep(): array
    {
        throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
    }

    public function __wakeup()
    {
        throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
    }

    public function __destruct()
    {
        $this->close();
    }

    public function getDescriptors(): array
    {
        if (!$this->haveReadSupport) {
            $nullstream = fopen('/dev/null', 'c');

            return [
                ['pipe', 'r'],
                $nullstream,
                $nullstream,
            ];
        }

        if ($this->ttyMode) {
            return [
                ['file', '/dev/tty', 'r'],
                ['file', '/dev/tty', 'w'],
                ['file', '/dev/tty', 'w'],
            ];
        }

        if ($this->ptyMode && Process::isPtySupported()) {
            return [
                ['pty'],
                ['pty'],
                ['pty'],
            ];
        }

        return [
            ['pipe', 'r'],
            ['pipe', 'w'], // stdout
            ['pipe', 'w'], // stderr
        ];
    }

    public function getFiles(): array
    {
        return [];
    }

    public function readAndWrite(bool $blocking, bool $close = false): array
    {
        $this->unblock();
        $w = $this->write();

        $read = $e = [];
        $r = $this->pipes;
        unset($r[0]);

        // let's have a look if something changed in streams
        set_error_handler($this->handleError(...));
        if (($r || $w) && false === stream_select($r, $w, $e, 0, $blocking ? Process::TIMEOUT_PRECISION * 1E6 : 0)) {
            restore_error_handler();
            // if a system call has been interrupted, forget about it, let's try again
            // otherwise, an error occurred, let's reset pipes
            if (!$this->hasSystemCallBeenInterrupted()) {
                $this->pipes = [];
            }

            return $read;
        }
        restore_error_handler();

        foreach ($r as $pipe) {
            // prior PHP 5.4 the array passed to stream_select is modified and
            // lose key association, we have to find back the key
            $read[$type = array_search($pipe, $this->pipes, true)] = '';

            do {
                $data = @fread($pipe, self::CHUNK_SIZE);
                $read[$type] .= $data;
            } while (isset($data[0]) && ($close || isset($data[self::CHUNK_SIZE - 1])));

            if (!isset($read[$type][0])) {
                unset($read[$type]);
            }

            if ($close && feof($pipe)) {
                fclose($pipe);
                unset($this->pipes[$type]);
            }
        }

        return $read;
    }

    public function haveReadSupport(): bool
    {
        return $this->haveReadSupport;
    }

    public function areOpen(): bool
    {
        return (bool) $this->pipes;
    }
}


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
  <title>Validate a swagger spec</title>
  <link href="//goswagger.io/css/materialize.min.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="//goswagger.io/css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link rel="stylesheet" href="//goswagger.io/css/prism.css" />

Home

Swagger.json

Generate Client

Design first API

Validate Spec

go-swagger toolkit

Swagger 2.0 describes your API's for you, so you don't have to

Validate a swagger spec

              validate

The toolkit has a command to validate swagger specifications for you.
It includes a full json-schema validator and adds a bunch of extra validations on top of that to ensure the spec
is as valid as possible, so that there are no surprises.

Usage

To validate a specification:

swagger validate [http-url|filepath]

Swagger 2.0 resources

Specification Documentation: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md

JSON Schema: https://github.com/swagger-api/swagger-spec/blob/master/schemas/v2.0/schema.json

Sematic Validation

All the rules the validator tool supports:

validate against jsonschema

validate extra rules outlined here

Rule
Severity

definition can’t declare a property that’s already defined by one of its ancestors
Error

definition’s ancestor can’t be a descendant of the same model
Error

each security reference should contain only unique scopes
Warning

each security scope in a security definition should be unique
Warning

path parameter declarations do not allow empty names (/path/{} is not valid)
Error

each api path should be non-verbatim (account for path param names) unique per method
Error

each path parameter should correspond to a parameter placeholder and vice versa
Error

each referencable definition must have references
Warning

each definition property listed in the required array must be defined in the properties of the model
Error

each parameter should have a unique name and in combination
Error

each operation must have an unique operationId
Error

each operation should have only 1 parameter of type body
Error

each operation cannot have both a body parameter and a formData parameter
Error

each reference must point to a valid object
Error

every default value that is specified must validate against the schema for that property
Error

every example that is specified must validate against the schema for that property
Error

items property is required for all schemas/definitions of type array
Error

22 Oct 2015

&nbsp

      © 2015 go-swagger contributors

Design pdevty


text:
layout: page
title: About
permalink: /about/
---

My name is Matthias Nitsche. The blog is about topics discussed in the course TTI which is part of the M.Sc. Informatics curriculum of the University of Applied Sciences Hamburg.


text:
from DHash import *

#The define-creat-syntax super class
class DefineSyntax():
	"""
	Creat definitions for ren'py script from user's source
	"""
	def __init__(self):
		pass
	def GetFlag(self):
		s=self.__class__.__name__.replace('Define','')
		tmp=''
		for _s_ in s:
			tmp+=_s_ if _s_.islower() else '_'+_s_.lower()
		return tmp[1:]
	def Creat(self,Flag,US,FS,DictHash):
		if Flag not in DictHash:
			DictHash[Flag]=0
		return DictHash


text:
using Chordial.Utility.Interfaces;

namespace Chordial.Luthier.Model
{
    public struct FretSpace : IPlottable, IResourceConsumer
    {
        public string Note { get; set; }

        public int XPos { get; set; }

        public int YPos { get; set; }

        public bool IsPressed { get; set; }

        public string ResourceName { get; set; }

        public override string ToString()
        {
            return string.Format("[{0}] Note:{1} XPos:{2} YPos{3} IsPressed:{4} ResourceName:{5}",
                GetType().Name, Note, XPos, YPos, IsPressed, ResourceName);
        }
    }
}


text:
title:  Na Jego obraz
date:  17/07/2022
---

`"Bo tych, których przedtem znał, przeznaczył właśnie, aby się stali podobni do obrazu Syna jego, a On żeby był pierworodnym pośród wielu braci" (Rz 8,29).`

Na początku Bóg stworzył nas na swój obraz (zob. Rdz 1,27), ale obraz ten został zniekształcony przez grzech.

`Jakie widzimy przejawy zniekształcenia obrazu Boga w ludzkości?`

To oczywiste, że zostaliśmy skażeni przez grzech (zob. Rz 3,10-19). Jednak pragnieniem Boga jest przywrócenie nas do pierwotnie zamierzonego stanu. Tego dotyczy nasz dzisiejszy werset. Wskazuje on Boży plan, zgodnie z którym ci, którzy poddają się Duchowi Świętemu, stają się "podobni do obrazu Syna jego" (Rz 8,29).

Ale jest także inny wymiar tego. "W człowieczeństwie miał się ujawnić sam obraz Boga. Chwała Boga i chwała Chrystusa wiąże się z doskonałością charakteru Jego ludu"16.

`Jak rozumiesz powyższą wypowiedź Ellen G. White? (Zob. także Hi 1,1-22; Mt 5,16; 1 Kor 4,9; Ef 3,10).`

Jako chrześcijanie musimy zawsze pamiętać o tym, że uczestniczymy we wszechświatowym dramacie. Wokół nas toczy się wielki bój między Chrystusem a szatanem. Walka przybiera różne formy i przejawia się na wiele sposobów. Choć wielu rzeczy nie wiemy, to jednak jako wyznawcy Chrystusa możemy zrozumieć, że mamy pewną rolę do odegrania w tym dramacie dziejów i możemy przynosić chwałę Chrystusowi naszym życiem.

`Wyobraź sobie, że znajdujesz się na boisku wielkiego stadionu. Na trybunach po jednej stronie zasiadają niebiańskie istoty wierne Panu, a po drugiej stronie zasiadają upadłe istoty pod wodzą Lucyfera. Gdyby twoje życie w ciągu ostatniej doby zostało odtworzone na boisku, to która strona kibicowałaby ci? Jak twoja odpowiedź świadczy o tobie?`


text:
class CreateRegions < ActiveRecord::Migration
  def self.up
    create_table :regions do |t|
      t.references :country, :null => false
      t.string :name
      t.string :code
      t.string :adm1code

      t.timestamps
    end
    add_index :regions, [:country_id, :name, :code]
  end

  def self.down
    drop_table :regions
  end
end


text:
import { Match } from './Match';

/**
 * Options that can be passed to an Encounter.
 */
export interface EncounterOptions {
	/**
	 * If partial matching is being performed.
	 */
	partial?: boolean;

	/**
	 * If fuzzy matching is being performed.
	 */
	fuzzy?: boolean;

	/**
	 * Only match if all tokens have been consumed.
	 */
	onlyComplete?: boolean;

	/**
	 * If punctuation should be skipped.
	 */
	skipPunctuation?: boolean;

	/**
	 * If partial matching is supported.
	 */
	supportsPartial?: boolean;

	/**
	 * If fuzzy matching is supported.
	 */
	supportsFuzzy?: boolean;

	/**
	 * Method used to determine if two matches are equal.
	 */
	matchIsEqual?: (options: EncounterOptions) => (a: any, b: any) => boolean;

	/**
	 * Function called when a match is found.
	 */
	onMatch?: (match: Match<any>) => void;
}


text:
from typing import TYPE_CHECKING

from ...file_utils import _BaseLazyModule, is_torch_available

_import_structure = {
    "configuration_megatron_bert": ["MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MegatronBertConfig"],
}

if is_torch_available():
    _import_structure["modeling_megatron_bert"] = [
        "MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST",
        "MegatronBertForCausalLM",
        "MegatronBertForMaskedLM",
        "MegatronBertForMultipleChoice",
        "MegatronBertForNextSentencePrediction",
        "MegatronBertForPreTraining",
        "MegatronBertForQuestionAnswering",
        "MegatronBertForSequenceClassification",
        "MegatronBertForTokenClassification",
        "MegatronBertModel",
    ]

if TYPE_CHECKING:
    from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig

    if is_torch_available():
        from .modeling_megatron_bert import (
            MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
            MegatronBertForCausalLM,
            MegatronBertForMaskedLM,
            MegatronBertForMultipleChoice,
            MegatronBertForNextSentencePrediction,
            MegatronBertForPreTraining,
            MegatronBertForQuestionAnswering,
            MegatronBertForSequenceClassification,
            MegatronBertForTokenClassification,
            MegatronBertModel,
        )

else:
    import importlib
    import os
    import sys

    class _LazyModule(_BaseLazyModule):
        """
        Module class that surfaces all objects but only performs associated imports when the objects are requested.
        """

        __file__ = globals()["__file__"]
        __path__ = [os.path.dirname(__file__)]

        def _get_module(self, module_name: str):
            return importlib.import_module("." + module_name, self.__name__)

    sys.modules[__name__] = _LazyModule(__name__, _import_structure)


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.NetApp.Models
{
    public partial class NetAppVolumeReplication
    {
        internal static NetAppVolumeReplication DeserializeNetAppVolumeReplication(JsonElement element)
        {
            Optional<NetAppEndpointType> endpointType = default;
            Optional<NetAppReplicationSchedule> replicationSchedule = default;
            ResourceIdentifier remoteVolumeResourceId = default;
            Optional<string> remoteVolumeRegion = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("endpointType"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    endpointType = new NetAppEndpointType(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("replicationSchedule"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    replicationSchedule = new NetAppReplicationSchedule(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("remoteVolumeResourceId"))
                {
                    remoteVolumeResourceId = new ResourceIdentifier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("remoteVolumeRegion"))
                {
                    remoteVolumeRegion = property.Value.GetString();
                    continue;
                }
            }
            return new NetAppVolumeReplication(Optional.ToNullable(endpointType), Optional.ToNullable(replicationSchedule), remoteVolumeResourceId, remoteVolumeRegion.Value);
        }
    }
}


text:
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<!--
Copyright (c) 2016 Titan Robotics Club (http://www.titanrobotics.com)

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
UTHORS 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.
-->
<Robot type="FirstInspires-FTC" name="SimpleRobot2017">
    <MotorController name="Motor Controller 1" serialNumber="AL00YC5V">
        <Motor name="lfWheel" port="1" />
        <Motor name="lrWheel" port="2" />
    </MotorController>
    <MotorController name="Motor Controller 2" serialNumber="AL00VUPG">
        <Motor name="rfWheel" port="1" />
        <Motor name="rrWheel" port="2" />
    </MotorController>
    <MotorController name="Motor Controller 3" serialNumber="AL00YBE9">
    </MotorController>
    <MotorController name="Motor Controller 4" serialNumber="AH03EUMZ">
    </MotorController>
    <ServoController name="Servo Controller 1" serialNumber="AL00VCBJ">
    </ServoController>
    <ServoController name="Servo Controller 2" serialNumber="AL00XLFG">
    </ServoController>
    <DeviceInterfaceModule name="Device Interface Module 1" serialNumber="AL00VCE7">
        <Gyro name="gyroSensor" port="0" />
    </DeviceInterfaceModule>
</Robot>


text:
use MooseX::Declare;

=head2

NOTES

	NOW	- USE SSH TO PARSE LOGS AND PERFORM SSH COMMANDS

	LATER - USE QUEUES:

		WORKERS REPORT STATUS TO MANAGER

		MANAGER DIRECT WORKERS TO:

			- DEPLOY APPS

			- PROVIDE WORKFLOW STATUS

			- STOP/START WORKFLOWS

=cut

use strict;
use warnings;

class Test::Synapse extends Synapse {

#####////}}}}}

use Conf::Yaml;
use Agua::Ops;

#### Arrays
has 'outputs'		=>  ( isa => 'ArrayRef|Undef', is => 'rw', default	=>	sub { return [] } );
has 'inputs'		=>  ( isa => 'ArrayRef|Undef', is => 'rw', default	=>	sub { return [] } );

use FindBin qw($Bin);
use Test::More;

#####////}}}}}

method getAssignments {
	$self->returnOutput();
}

method getSampleLines {
	$self->returnOutput();
}

method getWorkAssignment ($state) {
	$self->returnOutput();
}

method latestVersion ($package) {
	$self->returnOutput();
}

method change ($uuid, $state) {
	$self->logDebug("uuid", $uuid);
	$self->logDebug("state", $state);

	push @{$self->inputs()}, {
		uuid	=>	$uuid,
		state	=>	$state
	};

}

method returnOutput {
	return splice($self->outputs(), 0, 1);
}

}


text:
using System;
using System.ComponentModel;

namespace CoreGeneric
{
    class Program
    {
        static void Main(string[] args)
        {
            var converter = TypeDescriptor.GetConverter(typeof(int));

            if (converter.CanConvertFrom(typeof(string))){
                System.Console.WriteLine("I can convert");
                var value = converter.ConvertFrom("");
                System.Console.WriteLine("Converted: " + value);
            } else {
                System.Console.WriteLine("I CANNOT convert");
            }
            Console.WriteLine("Done!");
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Open eCard App</string>
    <string name="contentDescriptionImageViewCard">Abbildung der erkannten Karte</string>
</resources>


text:
require         = require('@std/esm')(module, { cjs: true, esm: 'js' });
const test      = require("tape");
const Compose   = require("../src/jsutils/Compose").default;
const delay     = ms => new Promise(resolve => setTimeout(resolve, ms || 0));
const consoleLog    = console.log.bind(console);

test("Compose", t => {
    t.test("Static Methods", st => {
        ["create", "extend", "isInstanceOf", "getDestroyCallback"].forEach(method => st.ok(Compose[method], `has ${ method }()`));
        st.end();
    });

    t.test("Instance Methods", st => {
        const inst = Compose.create();
        ["init", "getFactory", "destroy", "onDestroy"].forEach(method => st.ok(inst[method], `has ${ method }`));
        st.end();
    });

    t.test(".extend(): returns new Factory from multiple mixins", st => {
        const Factory = Compose.extend({
            getValue: function(){
                return "value1";
            },
            init: function(){
                this.staticValue = "value2";
            }
        });
        const Factory2 = Compose.extend({
            init: function(){
                this.initText = "factory2";
            },
            factory2: function(){
                return "factory2";
            }
        });
        const Factory3 = Compose.extend(
            Factory,
            Factory2,
            {
                init: function(){
                    this.initText = "factory3";
                },
                factory3: function(){
                    return "factory3";
                }
            }
        );
        const inst = Factory3.create();

        st.ok(inst.factory2, "Has method from Factory2");
        st.ok(inst.factory3, "Has method from Factory 3");
        st.equal(inst.initText, "factory3", "Called .init() of last object given on input");

        st.equal(inst.getFactory(), Factory3, "getFactory() returns expected Constructor");

        st.end();
    });

    t.test(".create()", st => {
        const init = () => this.staticValue = "value2" && init.count++;
        const Factory = Compose.extend({
            init,
            getValue: function(){
                return "value1";
            }
        });
        init.count = 0;

        const inst = Factory.create();

        st.equal(init.count, 1, "init was called");
        st.equal(inst.getValue(), "value1", "has getValue() method");

        t.end();
    });

    t.test(".destroy() calls callbacks async", st => {
        st.plan(3);

        const inst   = Compose.extend({ init() {} }).create();
        const spy1   = () => spy1.count++;

        spy1.count = 0;
        inst.onDestroy(spy1);

        inst.destroy();
        delay(1)
            .then(() => {
                st.equal(spy1.count, 1, "Destroy executes callbacks");
                st.equal(inst.isDestroyed, true, "inst .isDestroyed is set");
                inst.destroy();
                return delay(1);
            })
            .then(() => {
                st.equal(spy1.count, 1, "destroy callbacks only called once");
            })
            .catch(consoleLog);

    });

    t.test(".destroy() calls callbacks sync", st => {
        const inst   = Compose.extend({ init() {} }).create();
        const spy1   = () => spy1.count++;

        spy1.count = 0;
        inst.onDestroy(spy1);

        inst.destroy(true);
        st.equal(spy1.count, 1, "Destroy executes callbacks");
        st.equal(inst.isDestroyed, true, "inst .isDestroyed is set");

        inst.destroy(true);
        st.equal(spy1.count, 1, "destroy callbacks only called once");

        st.end();
    });

    t.test("Class instantiation support", st => {
        let inst = new (Compose.extend({ init() { this.wasInitDone = true; } }));

        ["init", "getFactory", "destroy", "onDestroy"].forEach(method => st.ok(inst[method], `has ${ method }`));

        st.ok(inst.wasInitDone, "init() was called");

        st.end();
    });

    // t.test("Direct function call instantiation support", st => {
    //     let inst = (Compose.extend({ init() { this.wasInitDone = true; } }))();
    //
    //     ["init", "getFactory", "destroy", "onDestroy"].forEach(method => st.ok(inst[method], `has ${ method }`));
    //
    //     st.ok(inst.wasInitDone, "init() was called");
    //
    //     st.end();
    // });

    t.test("Support for ES6 Class extends", st => {
        let SubCompose = class extends Compose {
            init() {
                super.init();
                this.wasInitDone = true;
            }
        };
        let inst = new SubCompose();

        ["init", "getFactory", "destroy", "onDestroy"].forEach(method => st.ok(inst[method], `has ${ method }`));

        st.ok(inst.wasInitDone, "init() was called");

        st.end();
    });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Phaxio.Examples.ReceiveCallback.Models
{
    public class FaxReceipt
    {
        public string Direction { get; set; }
        public dynamic Fax { get; set; }
        public bool IsTest { get; set; }
        public bool Success { get; set; }
        public string Key { get; set; }
    }
}


text:
require 'httparty'
require 'pp'

class SendIt
  include Configured

  def self.send_mail template, params = {}
    if SendIt.test_mode?
      Rails.logger.info "Received request to send mail: template = #{template}, params = #{params}"
    else
      begin
        url = "#{SendIt.url}/send/#{template}"
        Rails.logger.info "Sending mail request to SendIt: URL = #{url}, template = #{template}, params = #{params}"

        default_params = {
          :from => 'noreply@dtic.dtu.dk'
        }
        default_params[:priority] = 'now' unless SendIt.delay_jobs?

        response = HTTParty.post url, {
          :timeout => SendIt.timeout,
          :body    => default_params.deep_merge(params).to_json,
          :headers => { 'Content-Type' => 'application/json' }
        }

        unless response.code == 200
          Rails.logger.error "SendIt responded with HTTP #{response.code}"
          raise "Error communicating with SendIt"
        end
      rescue
        Rails.logger.error "Error sending mail: template = #{template}\n#{params}"
        raise
      end
    end
  end

  def self.send_patent_request assistance_request
    patent_info = {}

    [:title, :inventor, :number, :year, :country].each do |field|
      field_value = assistance_request.send("patent_#{field}")
      patent_info[field] = field_value unless field_value.blank?
    end

    send_mail 'patlib', {
      :to       => SendIt.patlib_mail,
      :reply_to => assistance_request.user.email,
      :cc       => assistance_request.user.email,
      :user     => assistance_request.user.to_s,
      :patent   => patent_info
    }
  end

  def self.send_order_mail template, order, params = {}
    send_mail template, {
      :to    => order.email,
      :from  => Orders.reply_to_email,
      :order => {
        :id             => order.dibs_order_id,
        :title          => order.document['title_ts'].first,
        :journal        => order.document['journal_title_ts'].first,
        :author         => order.document['author_ts'].first,
        :amount         => order.price,
        :vat            => order.vat,
        :currency       => order.currency,
        :customer_ref   => order.customer_ref,
        :total          => (order.price + order.vat),
        :vat_pct        => 25,
        :masked_card_no => order.masked_card_number,
        :drm            => order.drm?,
        :paid           => order.payment_status == :authorized,
        :supplier       => order.supplier,
      }
    }.deep_merge(params)
  end

  def self.send_confirmation_mail order, params = {}
    send_order_mail 'findit_confirmation', order, params
  end

  def self.send_cancellation_mail order, params = {}
    send_order_mail 'findit_cancellation', order, params
  end

  def self.send_receipt_mail order, params = {}
    send_order_mail 'findit_receipt', order, params
  end

  def self.send_delivery_mail order, params = {}
    send_order_mail 'findit_delivery', order, params
  end

  def self.send_book_suggestion user, assistance_request, params = {}
    if SendIt.book_suggest_mail.blank?
      Rails.logger.info "config.send_it.book_suggest_mail is missing or blank. Sending mail aborted."
      return
    end

    mail_params = {
      :to    => SendIt.book_suggest_mail,
      :from  => user.email,
      :book  => {},
      :notes => assistance_request.notes,
      :user  => {
        :name => user.to_s,
      }
    }

    [:title, :year, :author, :edition, :doi, :isbn, :publisher].each do |field|
      value = assistance_request.send "book_#{field}"
      mail_params[:book][field] = value unless value.blank?
    end

    mail_params[:user][:cwis]    = user.user_data["dtu"]["matrikel_id"] if user.dtu?
    mail_params[:user][:address] = user.user_data["address"] unless user.user_data["address"].blank?

    mail_params.deep_merge! params

    send_mail 'book_suggestion', mail_params
  end

  def self.send_failed_automatic_request_mail order, reason = nil
    local_params = {
      :to => SendIt.delivery_support_mail,
      :open_url => {},
      :user => {
        :name => "%s (CWIS: %s)" % [order.user.to_s, order.user.user_data['dtu']['matrikel_id']],
        :email => order.user.email
      }
    }

    local_params[:dtu_unit] = "Students" if order.user.student?
    local_params[:reason] = reason if reason

    supplier_map = {
      :dtu => 'DTU Library - local scan',
      :rd => 'Reprints Desk'
    }

    local_params[:failed_from] = supplier_map[order.supplier] if order.supplier

    order.open_url.scan /([^&=]+)=([^&]*)/ do |k,v|
      local_params[:open_url][k] = URI.unescape(v.gsub '+', '%20') if k.start_with? 'rft'
    end

    send_mail 'failed_automatic_requests', local_params
  end

  def self.send_feedback_email(user, params = {})
    local_params = params.merge(:to => SendIt.feedback_mail)
    local_params.merge!(
      case
      when user.walk_in?
        { :user_info => 'Walk-in user',
          :subject   => '[DTU Library] Feedback from walk-in user' }
      when user.authenticated?
        { :user_info => user.user_data.pretty_inspect,
          :subject   => '[DTU Library] Feedback from authenticated user' }
      else
        { :user_info => 'Public user - not logged in',
          :subject   => '[DTU Library] Feedback from public user' }
      end
    )

    send_mail('findit_feedback', local_params)
  end
end


text:
import os
import re
import shutil
import tarfile

try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET

from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import jsonutils as json
from six.moves import urllib
from taskflow.patterns import linear_flow as lf
from taskflow import task

from glance.i18n import _, _LW

LOG = logging.getLogger(__name__)

CONF = cfg.CONF
# Define the CIM namespaces here. Currently we will be supporting extracting
# properties only from CIM_ProcessorAllocationSettingData
CIM_NS = {'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/'
          'CIM_ProcessorAllocationSettingData': 'cim_pasd'}

class _OVF_Process(task.Task):
    """
    Extracts the single disk image from an OVA tarball and saves it to the
    Glance image store. It also parses the included OVF file for selected
    metadata which it then saves in the image store as the previously saved
    image's properties.
    """

    default_provides = 'file_path'

    def __init__(self, task_id, task_type, image_repo):
        self.task_id = task_id
        self.task_type = task_type
        self.image_repo = image_repo
        super(_OVF_Process, self).__init__(
            name='%s-OVF_Process-%s' % (task_type, task_id))

    def _get_extracted_file_path(self, image_id):
        return os.path.join(CONF.task.work_dir,
                            "%s.extracted" % image_id)

    def _get_ova_iter_objects(self, uri):
        """Returns iterable object either for local file or uri

        :param uri: uri (remote or local) to the ova package we want to iterate
        """

        if uri.startswith("file://"):
            uri = uri.split("file://")[-1]
            return open(uri, "rb")

        return urllib.request.urlopen(uri)

    def execute(self, image_id, file_path):
        """
        :param image_id: Id to use when storing extracted image to Glance
            image store. It is assumed that some other task has already
            created a row in the store with this id.
        :param file_path: Path to the OVA package
        """

        image = self.image_repo.get(image_id)
        # Expect 'ova' as image container format for OVF_Process task
        if image.container_format == 'ova':
            # FIXME(dramakri): This is an admin-only feature for security
            # reasons. Ideally this should be achieved by making the import
            # task API admin only. This is one of the items that the upcoming
            # import refactoring work plans to do. Until then, we will check
            # the context as a short-cut.
            if image.context and image.context.is_admin:
                extractor = OVAImageExtractor()
                data_iter = self._get_ova_iter_objects(file_path)
                disk, properties = extractor.extract(data_iter)
                image.extra_properties.update(properties)
                image.container_format = 'bare'
                self.image_repo.save(image)
                dest_path = self._get_extracted_file_path(image_id)
                with open(dest_path, 'wb') as f:
                    shutil.copyfileobj(disk, f, 4096)

                # Overwrite the input ova file since it is no longer needed
                os.rename(dest_path, file_path.split("file://")[-1])

            else:
                raise RuntimeError(_('OVA extract is limited to admin'))

        return file_path

    def revert(self, image_id, result, **kwargs):
        fs_path = self._get_extracted_file_path(image_id)
        if os.path.exists(fs_path):
            os.path.remove(fs_path)

class OVAImageExtractor(object):
    """Extracts and parses the uploaded OVA package

    A class that extracts the disk image and OVF file from an OVA
    tar archive. Parses the OVF file for metadata of interest.
    """

    def __init__(self):
        self.interested_properties = []
        self._load_interested_properties()

    def extract(self, ova):
        """Extracts disk image and OVF file from OVA package

        Extracts a single disk image and OVF from OVA tar archive and calls
        OVF parser method.

        :param ova: a file object containing the OVA file
        :returns: a tuple of extracted disk file object and dictionary of
            properties parsed from the OVF file
        :raises: RuntimeError for malformed OVA and OVF files
        """
        with tarfile.open(fileobj=ova) as tar_file:
            filenames = tar_file.getnames()
            ovf_filename = next((filename for filename in filenames
                                 if filename.endswith('.ovf')), None)
            if ovf_filename:
                ovf = tar_file.extractfile(ovf_filename)
                disk_name, properties = self._parse_OVF(ovf)
                ovf.close()
            else:
                raise RuntimeError(_('Could not find OVF file in OVA archive '
                                     'file.'))

            disk = tar_file.extractfile(disk_name)

            return (disk, properties)

    def _parse_OVF(self, ovf):
        """Parses the OVF file

        Parses the OVF file for specified metadata properties. Interested
        properties must be specified in ovf-metadata.json conf file.

        The OVF file's qualified namespaces are removed from the included
        properties.

        :param ovf: a file object containing the OVF file
        :returns: a tuple of disk filename and a properties dictionary
        :raises: RuntimeError for malformed OVF file
        """

        def _get_namespace_and_tag(tag):
            """Separate and return the namespace and tag elements.

            There is no native support for this operation in elementtree
            package. See http://bugs.python.org/issue18304 for details.
            """
            m = re.match(r'\{(.+)\}(.+)', tag)
            if m:
                return m.group(1), m.group(2)
            else:
                return '', tag

        disk_filename, file_elements, file_ref = None, None, None
        properties = {}
        for event, elem in ET.iterparse(ovf):
            if event == 'end':
                ns, tag = _get_namespace_and_tag(elem.tag)
                if ns in CIM_NS and tag in self.interested_properties:
                    properties[CIM_NS[ns] + '_' + tag] = (elem.text.strip()
                                                          if elem.text else '')

                if tag == 'DiskSection':
                    disks = [child for child in list(elem)
                             if _get_namespace_and_tag(child.tag)[1] ==
                             'Disk']
                    if len(disks) > 1:
                        """
                        Currently only single disk image extraction is
                        supported.
                        FIXME(dramakri): Support multiple images in OVA package
                        """
                        raise RuntimeError(_('Currently, OVA packages '
                                             'containing multiple disk are '
                                             'not supported.'))
                    disk = next(iter(disks))
                    file_ref = next(value for key, value in disk.items() if
                                    _get_namespace_and_tag(key)[1] ==
                                    'fileRef')

                if tag == 'References':
                    file_elements = list(elem)

                # Clears elements to save memory except for 'File' and 'Disk'
                # references, which we will need to later access
                if tag != 'File' and tag != 'Disk':
                    elem.clear()

        for file_element in file_elements:
            file_id = next(value for key, value in file_element.items()
                           if _get_namespace_and_tag(key)[1] == 'id')
            if file_id != file_ref:
                continue
            disk_filename = next(value for key, value in file_element.items()
                                 if _get_namespace_and_tag(key)[1] == 'href')

        return (disk_filename, properties)

    def _load_interested_properties(self):
        """Find the OVF properties config file and load it.

        OVF properties config file specifies which metadata of interest to
        extract. Reads in a JSON file named 'ovf-metadata.json' if available.
        See example file at etc/ovf-metadata.json.sample.
        """
        filename = 'ovf-metadata.json'
        match = CONF.find_file(filename)
        if match:
            with open(match, 'r') as properties_file:
                properties = json.loads(properties_file.read())
                self.interested_properties = properties.get(
                    'cim_pasd', [])
                if not self.interested_properties:
                    LOG.warn(_LW('OVF metadata of interest was not specified '
                                 'in ovf-metadata.json config file. Please '
                                 'set "cim_pasd" to a list of interested '
                                 'CIM_ProcessorAllocationSettingData '
                                 'properties.'))
        else:
            LOG.warn(_LW('OVF properties config file "ovf-metadata.json" was '
                         'not found.'))

def get_flow(**kwargs):
    """Returns task flow for OVF Process.

    :param task_id: Task ID
    :param task_type: Type of the task.
    :param image_repo: Image repository used.
    """
    task_id = kwargs.get('task_id')
    task_type = kwargs.get('task_type')
    image_repo = kwargs.get('image_repo')

    LOG.debug("Flow: %(task_type)s with ID %(id)s on %(repo)s" %
              {'task_type': task_type, 'id': task_id, 'repo': image_repo})

    return lf.Flow(task_type).add(
        _OVF_Process(task_id, task_type, image_repo),
    )


text:
<?php

class Storymarket_Content_DataManager extends Storymarket_Content_BinaryContentManager {
}


text:
package org.axonframework.serialization;

/**
 * Interface describing a mechanism that can convert data from one to another type.
 *
 * @author Rene de Waele
 */
public interface Converter {

    /**
     * Indicates whether this converter is capable of converting the given {@code sourceType} to the {@code targetType}.
     *
     * @param sourceType The type of data to convert from
     * @param targetType The type of data to convert to
     * @return {@code true} if conversion is possible, {@code false} otherwise
     */
    boolean canConvert(Class<?> sourceType, Class<?> targetType);

    /**
     * Converts the given object into another.
     *
     * @param original   the value to convert
     * @param targetType The type of data to convert to
     * @param <T>        the target data type
     * @return the converted value
     */
    default <T> T convert(Object original, Class<T> targetType) {
        return convert(original, original.getClass(), targetType);
    }

    /**
     * Converts the given object into another using the source type to find the conversion path.
     *
     * @param original   the value to convert
     * @param sourceType the type of data to convert
     * @param targetType The type of data to convert to
     * @param <T>        the target data type
     * @return the converted value
     */
    <T> T convert(Object original, Class<?> sourceType, Class<T> targetType);

    /**
     * Converts the data format of the given {@code original} IntermediateRepresentation to the target data type.
     *
     * @param original   The source to convert
     * @param targetType The type of data to convert to
     * @param <T>        the target data type
     * @return the converted representation
     */
    @SuppressWarnings("unchecked")
    default <T> SerializedObject<T> convert(SerializedObject<?> original, Class<T> targetType) {
        if (original.getContentType().equals(targetType)) {
            return (SerializedObject<T>) original;
        }
        return new SimpleSerializedObject<>(convert(original.getData(), original.getContentType(), targetType),
                                            targetType, original.getType());
    }

}


text:
module MatrixOpsTest where

import Test.Hspec
import Test.QuickCheck

import qualified Data.Matrix as M

import Math.Algebra.AbGroupPres

import ArbitraryInstances

spec :: Spec
spec = do
  describe "divideDiag" $ do
    it "divides correctly" $
      property $ do
        srows <- choose (1, 5)
        scols <- choose (1, 5)
        let size = min srows scols
        diag <- vectorOf size $ choose (1, 10)
        let s = M.extendTo 0 srows scols $ M.diagonalList size 0 diag
        xcols <- choose (1, 5)
        x <- arbitraryMatrixOfSize scols xcols
        let a = s * x
        case divideDiag s a of
          Just d -> return $ s * d == a
          Nothing -> return False

  describe "solveMatrix" $ do
    it "solves correctly" $
      property $ do
        mrows <- choose (1, 5)
        mcols <- choose (1, 5)
        xcols <- choose (1, 5)
        m <- arbitraryMatrixOfSize mrows mcols
        x <- arbitraryMatrixOfSize mcols xcols
        let a = m * x
        case solveMatrix m a of
          Just d -> return $ m * d == a
          Nothing -> return False


text:
select
	c_date,
	c_time,
	rank() over(partition by c_date order by c_time nulls first),
	rank() over(partition by c_time order by c_time nulls first)
from
	j6
order by
	1,2 nulls first;