text:
using System;

namespace UsbLibrary
{
	///
	/// Base class for report types. Simply wraps a byte buffer.
	///
	public abstract class Report
	{
		#region Member variables
		/// Buffer for raw report bytes
		private byte[] m_arrBuffer;
		/// Length of the report
		private int m_nLength;
		#endregion

		///
		/// Constructor
		///
		/// <param name="oDev">Constructing device</param>
		public Report(HIDDevice oDev)
		{
			// Do nothing
		}

		///
		/// Sets the raw byte array.
		///
		/// <param name="arrBytes">Raw report bytes</param>
		protected void SetBuffer(byte[] arrBytes)
		{
			m_arrBuffer = arrBytes;
			m_nLength = m_arrBuffer.Length;
		}

		///
		/// Accessor for the raw byte buffer
		///
		public byte[] Buffer
		{
			get{return m_arrBuffer;}
            set{this.m_arrBuffer = value; }
		}
		///
		/// Accessor for the buffer length
		///
		public int BufferLength
		{
			get
			{
				return m_nLength;
			}
		}
	}
	///
	/// Defines a base class for output reports. To use output reports, just put the bytes into the raw buffer.
	///
	public abstract class OutputReport : Report
	{
		///
		/// Construction. Setup the buffer with the correct output report length dictated by the device
		///
		/// <param name="oDev">Creating device</param>
		public OutputReport(HIDDevice oDev) : base(oDev)
		{
			SetBuffer(new byte[oDev.OutputReportLength]);
		}
	}
	///
	/// Defines a base class for input reports. To use input reports, use the SetData method and override the
	/// ProcessData method.
	///
	public abstract class InputReport : Report
	{
		///
		/// Construction. Do nothing
		///
		/// <param name="oDev">Creating device</param>
		public InputReport(HIDDevice oDev) : base(oDev)
		{
		}
		///
		/// Call this to set the buffer given a raw input report. Calls an overridable method to
		/// should automatically parse the bytes into meaningul structures.
		///
		/// <param name="arrData">Raw input report.</param>
		public void SetData(byte[] arrData)
		{
			SetBuffer(arrData);
			ProcessData();
		}
		///
		/// Override this to process the input report into something useful
		///
		public abstract void ProcessData();
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>anna steadham: ux researcher</title>

    <link href="../../css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="../../css/2017-portfolio.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
    <link href="http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">

                        About

                        Skills

                        Portfolio

                        Contact

STANDARD GOODS

E-COMMERCE REDESIGN

PROTOTYPE

WIREFRAME

CLIENT: Standard Goods, a lifestyle boutique specializing in product made in North America located in Capitol Hill, Seattle, WA.

ROLE: Information Architect, UX Designer, and Researcher.

TOOLS: Omnigraffle, Optimal Card Sort, Pen & Paper

PROJECT SCOPE: Redesign the desktop e-commerce experience.

DURATION: 2 Week Sprint

Copyright © Anna Steadham 2016

redpajama_set_name: RedPajamaGithub


text:
if(NOT DEFINED CMAKE_INSTALL_PREFIX)
  set(CMAKE_INSTALL_PREFIX "/home/mike/catkin_ws/install")
endif()
string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}")

# Set the install configuration name.
if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)
  if(BUILD_TYPE)
    string(REGEX REPLACE "^[^A-Za-z0-9_]+" ""
           CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}")
  else()
    set(CMAKE_INSTALL_CONFIG_NAME "Release")
  endif()
  message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"")
endif()

# Set the component getting installed.
if(NOT CMAKE_INSTALL_COMPONENT)
  if(COMPONENT)
    message(STATUS "Install component: \"${COMPONENT}\"")
    set(CMAKE_INSTALL_COMPONENT "${COMPONENT}")
  else()
    set(CMAKE_INSTALL_COMPONENT)
  endif()
endif()

# Install shared libraries without execute permission?
if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)
  set(CMAKE_INSTALL_SO_NO_EXE "1")
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/share/teb_local_planner/msg" TYPE FILE FILES
    "/home/mike/catkin_ws/src/teb_local_planner-indigo-devel/msg/ObstacleMsg.msg"
    "/home/mike/catkin_ws/src/teb_local_planner-indigo-devel/msg/TrajectoryPointMsg.msg"
    "/home/mike/catkin_ws/src/teb_local_planner-indigo-devel/msg/TrajectoryMsg.msg"
    "/home/mike/catkin_ws/src/teb_local_planner-indigo-devel/msg/FeedbackMsg.msg"
    )
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/share/teb_local_planner/cmake" TYPE FILE FILES "/home/mike/catkin_ws/build/teb_local_planner-indigo-devel/catkin_generated/installspace/teb_local_planner-msg-paths.cmake")
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/include" TYPE DIRECTORY FILES "/home/mike/catkin_ws/devel/include/teb_local_planner")
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/share/common-lisp/ros" TYPE DIRECTORY FILES "/home/mike/catkin_ws/devel/share/common-lisp/ros/teb_local_planner")
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  execute_process(COMMAND "/usr/bin/python" -m compileall "/home/mike/catkin_ws/devel/lib/python2.7/dist-packages/teb_local_planner")
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib/python2.7/dist-packages" TYPE DIRECTORY FILES "/home/mike/catkin_ws/devel/lib/python2.7/dist-packages/teb_local_planner")
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/include/teb_local_planner" TYPE FILE FILES "/home/mike/catkin_ws/devel/include/teb_local_planner/TebLocalPlannerReconfigureConfig.h")
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib/python2.7/dist-packages/teb_local_planner" TYPE FILE FILES "/home/mike/catkin_ws/devel/lib/python2.7/dist-packages/teb_local_planner/__init__.py")
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  execute_process(COMMAND "/usr/bin/python" -m compileall "/home/mike/catkin_ws/devel/lib/python2.7/dist-packages/teb_local_planner/cfg")
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib/python2.7/dist-packages/teb_local_planner" TYPE DIRECTORY FILES "/home/mike/catkin_ws/devel/lib/python2.7/dist-packages/teb_local_planner/cfg")
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib/pkgconfig" TYPE FILE FILES "/home/mike/catkin_ws/build/teb_local_planner-indigo-devel/catkin_generated/installspace/teb_local_planner.pc")
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/share/teb_local_planner/cmake" TYPE FILE FILES "/home/mike/catkin_ws/build/teb_local_planner-indigo-devel/catkin_generated/installspace/teb_local_planner-msg-extras.cmake")
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/share/teb_local_planner/cmake" TYPE FILE FILES
    "/home/mike/catkin_ws/build/teb_local_planner-indigo-devel/catkin_generated/installspace/teb_local_plannerConfig.cmake"
    "/home/mike/catkin_ws/build/teb_local_planner-indigo-devel/catkin_generated/installspace/teb_local_plannerConfig-version.cmake"
    )
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/share/teb_local_planner" TYPE FILE FILES "/home/mike/catkin_ws/src/teb_local_planner-indigo-devel/package.xml")
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  if(EXISTS "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libteb_local_planner.so" AND
     NOT IS_SYMLINK "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libteb_local_planner.so")
    file(RPATH_CHECK
         FILE "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libteb_local_planner.so"
         RPATH "")
  endif()
  file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib" TYPE SHARED_LIBRARY FILES "/home/mike/catkin_ws/devel/lib/libteb_local_planner.so")
  if(EXISTS "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libteb_local_planner.so" AND
     NOT IS_SYMLINK "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libteb_local_planner.so")
    file(RPATH_CHANGE
         FILE "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libteb_local_planner.so"
         OLD_RPATH "/opt/ros/indigo/lib:"
         NEW_RPATH "")
    if(CMAKE_INSTALL_DO_STRIP)
      execute_process(COMMAND "/usr/bin/strip" "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libteb_local_planner.so")
    endif()
  endif()
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  if(EXISTS "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/teb_local_planner/test_optim_node" AND
     NOT IS_SYMLINK "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/teb_local_planner/test_optim_node")
    file(RPATH_CHECK
         FILE "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/teb_local_planner/test_optim_node"
         RPATH "")
  endif()
  file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib/teb_local_planner" TYPE EXECUTABLE FILES "/home/mike/catkin_ws/devel/lib/teb_local_planner/test_optim_node")
  if(EXISTS "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/teb_local_planner/test_optim_node" AND
     NOT IS_SYMLINK "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/teb_local_planner/test_optim_node")
    file(RPATH_CHANGE
         FILE "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/teb_local_planner/test_optim_node"
         OLD_RPATH "/home/mike/catkin_ws/devel/lib:/opt/ros/indigo/lib:"
         NEW_RPATH "")
    if(CMAKE_INSTALL_DO_STRIP)
      execute_process(COMMAND "/usr/bin/strip" "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/teb_local_planner/test_optim_node")
    endif()
  endif()
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/include/teb_local_planner" TYPE DIRECTORY FILES "/home/mike/catkin_ws/src/teb_local_planner-indigo-devel/include/teb_local_planner/" REGEX "/\\.svn$" EXCLUDE)
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/share/teb_local_planner" TYPE FILE FILES "/home/mike/catkin_ws/src/teb_local_planner-indigo-devel/teb_local_planner_plugin.xml")
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/share/teb_local_planner" TYPE DIRECTORY FILES
    "/home/mike/catkin_ws/src/teb_local_planner-indigo-devel/launch"
    "/home/mike/catkin_ws/src/teb_local_planner-indigo-devel/cfg"
    "/home/mike/catkin_ws/src/teb_local_planner-indigo-devel/scripts"
    REGEX "/\\.svn$" EXCLUDE)
endif()


text:
\+ means a new feature

\# means an improved feature

\! means a fixed issue/bug

## Git HEAD
\+ replay gain is now supported

\+ full FLAC support added, includes downloading, converting, replaygain and tagging

## V1.1.0 - 24.09.09

\+ settings editor

\+ video file can be kept

\+ convert and improvement can now be disabled


text:
using namespace platformer;
const std::string Zombie::texturePath = "Ressources\\Sprites\\MonsterC\\Idle.png";
Zombie::Zombie() :Enemy(texturePath)
{
	typeActuel = typeEnemy::ZOMBIE;
	nbVies = 2;
}
Zombie::~Zombie()
{

}
//incapable d'appeler ces méthodes j'ai supprimer le code
void Zombie::Move()
{

}
void Zombie::init()
{

}


text:
/**
 * demo - panel
 */

$('#w-panel-demo-color-toggle').click(function () {
    $('.demo-panel').toggleClass('wo-alpha');
});


text:
//=============================================================================
// 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.
//=============================================================================

using AngularSkeleton.Domain.Catalog;

namespace AngularSkeleton.DataAccess.Entities.Mappings
{
    /// <summary>
    ///     Mapping for a <see cref="Product" /> entity.
    /// </summary>
    internal class ProductMapping : MappingBase<Product>
    {
        public ProductMapping()
        {
            Property(client => client.Archived).IsRequired();
            Property(client => client.Description).IsOptional();
            Property(client => client.Name).HasMaxLength(100).IsRequired();
            Property(client => client.QuantityAvailable).IsRequired();
        }

        public override string TableName
        {
            get { return Tables.Product; }
        }
    }
}


text:
package nl.vu.cs.dynamite.storage.mapdb;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import nl.vu.cs.ajira.Context;
import nl.vu.cs.ajira.actions.ActionContext;
import nl.vu.cs.ajira.chains.Location;
import nl.vu.cs.ajira.data.types.TInt;
import nl.vu.cs.ajira.data.types.TLong;
import nl.vu.cs.ajira.data.types.Tuple;
import nl.vu.cs.ajira.datalayer.InputLayer;
import nl.vu.cs.ajira.datalayer.TupleIterator;
import nl.vu.cs.ajira.utils.Utils;
import nl.vu.cs.ajira.utils.Utils.BytesComparator;
import nl.vu.cs.dynamite.storage.BTreeInterface;
import nl.vu.cs.dynamite.storage.DBType;
import nl.vu.cs.dynamite.storage.WritingSession;

import org.mapdb.BTreeKeySerializer;
import org.mapdb.BTreeMap;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.HTreeMap;
import org.mapdb.Serializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MapdbLayer extends InputLayer implements BTreeInterface {

	private static class ByteArraySerializer extends BTreeKeySerializer<byte[]> implements Serializer<byte[]>, java.io.Serializable {

		@Override
		public byte[] deserialize(DataInput in, int available) throws IOException {
			int n = in.readByte();
			if (n == -1) {
				return null;
			}
			byte[] b = new byte[n];
			if (n > 0) {
				in.readFully(b);
			}
			return b;
		}

		@Override
		public void serialize(DataOutput out, byte[] b) throws IOException {
			if (b == null) {
				out.writeByte(-1);
			} else {
				out.writeByte(b.length);
				if (b.length > 0) {
					out.write(b);
				}
			}
		}

		@Override
		public void serialize(DataOutput out, int start, int end, Object[] keys) throws IOException {
			for (int i = start; i < end; i++) {
				byte[] b = ((byte[]) keys[i]);
				serialize(out, b);
			}
		}

		@Override
		public Object[] deserialize(DataInput in, int start, int end, int size) throws IOException {
			Object[] ret = new Object[size];
			for (int i = start; i < end; i++) {
				ret[i] = deserialize(in, 0);
			}
			return ret;
		}
	}

	private static final ByteArraySerializer serializer = new ByteArraySerializer();

	private static final BytesComparator cmp = new BytesComparator();

	static final Logger log = LoggerFactory.getLogger(MapdbLayer.class);

	private String inputDir = null;
	private static DB db = null;
	private static BTreeMap<byte[], byte[]> spo = null;
	private static BTreeMap<byte[], byte[]> sop = null;
	private static BTreeMap<byte[], byte[]> pos = null;
	private static BTreeMap<byte[], byte[]> pso = null;
	private static BTreeMap<byte[], byte[]> ops = null;
	private static BTreeMap<byte[], byte[]> osp = null;
	private static BTreeMap<byte[], byte[]> t2n = null;
	private static BTreeMap<byte[], byte[]> n2t = null;

	private boolean compressedKeys;
	private boolean isInitialized = false;

	private static int counter = 0;

	private void init(Context context) throws Exception {
		synchronized(this.getClass()) {
			if (db == null) {
				inputDir = context.getConfiguration().get(DB_INPUT, null);
				if (inputDir == null) {
					throw new Exception("Input directory not found");
				}

				DBMaker maker = DBMaker.newFileDB(new File(inputDir, "MAPDB"))
						.closeOnJvmShutdown().writeAheadLogDisable()
						.asyncFlushDelay(10);
				if (Runtime.getRuntime().maxMemory() < 1L * 1024 * 1024 * 1024) {
					maker = maker.randomAccessFileEnable();
				} else {
					maker = maker.randomAccessFileEnableIfNeeded();
				}
				db = maker.make();
			}
			if (! isInitialized) {
				counter++;
				isInitialized = true;
				compressedKeys = context.getConfiguration().getBoolean(
						COMPRESS_KEYS, false);
				// Check if the database already has a "Config".
				try {
					HTreeMap<String, Boolean> c = db.createHashMap("Config", false, null, null);
					c.put("CompressedKeys", compressedKeys);
					db.commit();
				} catch(IllegalArgumentException e) {
					// Already exists. Look in the "Config" database to see if keys are compressed.
					// Value overrides user-spec.
					HTreeMap<String, Boolean> c = db.getHashMap("Config");
					compressedKeys = c.get("CompressedKeys");
				}

				if (log.isDebugEnabled()) {
					log.debug("Compressed keys: " + compressedKeys);
				}
			}
		}
	}

	@Override
	protected void load(Context context) throws Exception {
		init(context);

		spo = loadDb(context, DBType.SPO);
		sop = loadDb(context, DBType.SOP);
		pos = loadDb(context, DBType.POS);
		pso = loadDb(context, DBType.PSO);
		ops = loadDb(context, DBType.OPS);
		osp = loadDb(context, DBType.OSP);

		if (log.isDebugEnabled()) {
			log.debug("SPO size = " + spo.size());
		}
	}

	@Override
	public void remove(Tuple tuple) {
		byte[] triple = new byte[24];
		long s = ((TLong) tuple.get(0)).getValue();
		long p = ((TLong) tuple.get(1)).getValue();
		long o = ((TLong) tuple.get(2)).getValue();

		int sz = encode(triple, s, p, o);
		if (sz < triple.length) {
			triple = Arrays.copyOf(triple, sz);
		}

		spo.remove(triple);
		sop.remove(triple);
		pos.remove(triple);
		pso.remove(triple);
		ops.remove(triple);
		osp.remove(triple);
	}

	@Override
	public TupleIterator getIterator(Tuple tuple, ActionContext context) {
		long s = ((TLong) tuple.get(0)).getValue();
		long p = ((TLong) tuple.get(1)).getValue();
		long o = ((TLong) tuple.get(2)).getValue();

		// Key to access the entries in the db (initialized to 0)
		byte[] triple = new byte[24];
		// If not entering in any of the branches below, constantBytes remains 0
		int constantBytes = 0;
		DBType dbType = DBType.SPO;
		// o is a variable
		if (o < 0) {
			if (p < 0) {
				if (s >= 0) {
					dbType = DBType.SPO;
					if (compressedKeys) {
						constantBytes = Utils.encodePackedLong(triple, 0, s);
					} else {
						constantBytes = 8;
						Utils.encodeLong(triple, 0, s);
					}
				}
			} else if (s < 0) {
				dbType = DBType.PSO;
				if (compressedKeys) {
					constantBytes = Utils.encodePackedLong(triple, 0, p);
				} else {
					constantBytes = 8;
					Utils.encodeLong(triple, 0, p);
				}
			} else {
				dbType = DBType.SPO;
				if (compressedKeys) {
					constantBytes = Utils.encodePackedLong(triple, 0, s);
					constantBytes = Utils.encodePackedLong(triple,
							constantBytes, p);
				} else {
					constantBytes = 16;
					Utils.encodeLong(triple, 0, s);
					Utils.encodeLong(triple, 8, p);
				}
			}
		}
		// p is a variable
		else if (p < 0) {
			if (s < 0) {
				dbType = DBType.OSP;
				if (compressedKeys) {
					constantBytes = Utils.encodePackedLong(triple, 0, o);
				} else {
					constantBytes = 8;
					Utils.encodeLong(triple, 0, o);
				}
			} else {
				dbType = DBType.OSP;
				if (compressedKeys) {
					constantBytes = Utils.encodePackedLong(triple, 0, o);
					constantBytes = Utils.encodePackedLong(triple,
							constantBytes, s);
				} else {
					constantBytes = 16;
					Utils.encodeLong(triple, 0, o);
					Utils.encodeLong(triple, 8, s);
				}
			}
		}
		// s is a varibale
		else if (s < 0) {
			dbType = DBType.OPS;
			if (compressedKeys) {
				constantBytes = Utils.encodePackedLong(triple, 0, o);
				constantBytes = Utils
						.encodePackedLong(triple, constantBytes, p);
			} else {
				constantBytes = 16;
				Utils.encodeLong(triple, 0, o);
				Utils.encodeLong(triple, 8, p);
			}
		}
		// Completely specified triple
		else {
			dbType = DBType.SPO;
			if (compressedKeys) {
				constantBytes = Utils.encodePackedLong(triple, 0, s);
				constantBytes = Utils
						.encodePackedLong(triple, constantBytes, p);
				constantBytes = Utils
						.encodePackedLong(triple, constantBytes, o);
			} else {
				constantBytes = 24;
				Utils.encodeLong(triple, 0, s);
				Utils.encodeLong(triple, 8, p);
				Utils.encodeLong(triple, 16, o);
			}
		}
		BTreeMap<byte[], byte[]> index = fromDbToObj(dbType);

		TupleIterator itr = null;
		if (tuple.getNElements() == 3) {
			itr = new MapdbIterator(triple, constantBytes, index, dbType,
					compressedKeys);
		} else {
			itr = new MapdbIterator(triple, constantBytes, index, dbType,
					compressedKeys, ((TInt) tuple.get(3)).getValue(),
					((TInt) tuple.get(4)).getValue());
		}
		itr.init(context, "MapDB");
		return itr;
	}

	private BTreeMap<byte[], byte[]> loadDb(Context context, DBType dbType) throws Exception {
		init(context);
		synchronized (MapdbLayer.class) {
			BTreeMap<byte[], byte[]> database = fromDbToObj(dbType);
			if (database == null) {
				try {
					database = db.createTreeMap(fromDbToName(dbType), 64, false, false, serializer, serializer, cmp);
				} catch(IllegalArgumentException e) {
					// it already exists
					database = db.getTreeMap(fromDbToName(dbType));
				}
				initDatabase(dbType, database);
			}
			return database;
		}
	}

	private BTreeMap<byte[], byte[]> fromDbToObj(DBType db) {
		switch (db) {
		case SPO:
			return spo;
		case SOP:
			return sop;
		case POS:
			return pos;
		case PSO:
			return pso;
		case OSP:
			return osp;
		case OPS:
			return ops;
		case T2N:
			return t2n;
		case N2T:
			return n2t;
		}
		return null;
	}

	private String fromDbToName(DBType db) {
		switch (db) {
		case SPO:
			return "spo";
		case SOP:
			return "sop";
		case POS:
			return "pos";
		case PSO:
			return "pso";
		case OSP:
			return "osp";
		case OPS:
			return "ops";
		case T2N:
			return "t2n";
		case N2T:
			return "n2t";
		}
		return null;
	}

	private void initDatabase(DBType type, BTreeMap<byte[], byte[]> database) {
		switch (type) {
		case SPO:
			spo = database;
			break;
		case SOP:
			sop = database;
			break;
		case POS:
			pos = database;
			break;
		case PSO:
			pso = database;
			break;
		case OSP:
			osp = database;
			break;
		case OPS:
			ops = database;
			break;
		case T2N:
			t2n = database;
			break;
		case N2T:
			n2t = database;
			break;
		}
	}

	@Override
	public void releaseIterator(TupleIterator itr, ActionContext context) {
		// Nothing to do
	}

	@Override
	public Location getLocations(Tuple tuple, ActionContext context) {
		// For now it supports only a local machine.
		return Location.THIS_NODE;
	}

	@Override
	public WritingSession openWritingSession(ActionContext context, DBType type) throws Exception {
		BTreeMap<byte[], byte[]> index = loadDb(context.getContext(), type);
		return new MapdbWritingSession(index, db);

	}

	@Override
	public void close() {
		if (! isInitialized) {
			return;
		}
		isInitialized = false;
		synchronized(this.getClass()) {
			counter--;
			if (counter > 0) {
				return;
			}
			spo = null;
			sop = null;
			pos = null;
			pso = null;
			ops = null;
			osp = null;
			t2n = null;
			n2t = null;
			if (db != null) {
				db.commit();
				db.close();
				db = null;
			}
		}
	}

	@Override
	public int encode(byte[] triple, long l1, long l2, long l3) {
		if (compressedKeys) {
			int position = Utils.encodePackedLong(triple, 0, l1);
			position = Utils.encodePackedLong(triple, position, l2);
			position = Utils.encodePackedLong(triple, position, l3);
			return position;
		} else {
			Utils.encodeLong(triple, 0, l1);
			Utils.encodeLong(triple, 8, l2);
			Utils.encodeLong(triple, 16, l3);
			return 24;
		}
	}

	@Override
	public void decreaseOrRemove(Tuple tuple, int count) {
		log.error("Not implemented!!!!", new Throwable());
		System.exit(1);
	}
}


text:
IR14Assignment2
===============

Repository for the masters assignment in the IR course, WiSe2014-2015@OvGU.

The Main class can be found in ir.control>CodeSearch.

The program itself is self-contained and should be easy to use.

Additional documentation regarding the source code, including class diagrams, can be found in the doc folder.


text:
<?php
/**
 * BugFree is free software under the terms of the FreeBSD License.
 *
 * mail notice.
 *
 * @link        http://www.bugfree.org.cn
 * @package     BugFree
 */
/* Init BugFree system. */
require_once("Include/Init.inc.php");
@set_time_limit(0);
@ini_set('memory_limit', -1);

$Where = "AssignedTo != 'Closed' && AssignedTo != 'Active' AND IsDroped = '0' AND BugStatus != 'Closed'";
$OrderBy = 'LastEditedDate DESC';
$Columns = 'BugID,BugSeverity,BugPriority,BugTitle,BugStatus,OpenedBy,AssignedTo,ResolvedBy,Resolution,LastEditedDate';
$BugList = dbGetList('BugInfo',$Columns, $Where, '', $OrderBy);

$UserList = testGetUserList();
foreach($UserList as $UserInfo)
{
    $UserNameList[$UserInfo['UserName']] = $UserInfo['RealName'];
}

$BugList = testSetBugListMultiInfo($BugList, $UserNameList);

foreach($BugList as $BugInfo)
{
    $BugGroupedList[$BugInfo["AssignedTo"]][] = $BugInfo;
}
$UserNameList = @array_keys($BugGroupedList);
$InUserNames = dbCreateIN(sysAddSlash(join(',',$UserNameList)));
$UserList = testGetUserList("UserName {$InUserNames}");

$CssStyle = join("",file($_CFG['RealRootPath'] . "/Css/Mail.css"));
$TPL->assign("CssStyle",$CssStyle);

if($_CFG['BrowserMode'])
{
    $BaseUrl = $_CFG["BaseURL"];
}
else
{
    $BaseUrl = $argv[1];
}
if($BaseUrl == '')
{
    die('Wrong Baseurl');
}
$TPL->assign("BaseUrl", $BaseUrl);

foreach($BugGroupedList as $AssignedTo => $UserBugList)
{
    $TPL->assign("UserBugList",$UserBugList);

    // Get bug list message in html.
    $Message = $TPL->fetch("Notice.tpl");
    $Subject = $_LANG["NoticeBugSubject"] . " ". count($UserBugList);

    // Mail.
    if(!empty($UserList[$AssignedTo]['Email']))
    {
        $To = $UserList[$AssignedTo]['Email'];
        @sysMail($To,'',$Subject,$Message);
    }
}
?>


text:
using Business.Objects.Layer.Interfaces.Startup;

using Dependency.Resolver.Loaders;

using NUnit.Framework;

using Tests.Unit.StructureMapTests.Schedulers;

namespace Tests.Unit.StructureMapTests
{
    public class StructureMapTests
    {
        private DependencyManager _dependencyManager;

        [SetUp]
        public void Setup()
        {
            _dependencyManager = new DependencyManager();
            _dependencyManager.ConfigureStartupDependencies();
        }

        [Test]
        public void TestRecursive_Type_Resolution()
        {
            var runAtStartup = _dependencyManager.Container.GetInstance<IRunAtStartup>();
            runAtStartup.Execute();
        }

        [Test]
        public void Test_ResolutionOfBaseClassDependencies_ThroughDerivedClass()
        {
            InitialiseDependencies();

            foreach (IRunAtStartup task in _dependencyManager.Container.GetAllInstances<IRunAtStartup>())
            {
                task.Execute();
            }
        }

        public void InitialiseDependencies()
        {
            _dependencyManager.Container.EjectAllInstancesOf<IRunAtStartup>();
            _dependencyManager.Container.Configure((cfg =>
            {
                cfg.For<IScheduler>().Use<CustomScheduler>();
                cfg.Scan(scan =>
                {
                    scan.TheCallingAssembly();
                    scan.AddAllTypesOf<IRunAtStartup>();
                });
            }));
        }
    }
}


text:
"""
This script generates tests text-emphasis-line-height-001 ~ 004 except
001z. They test the line height expansion in different directions. This
script outputs a list of all tests it generated in the format of Mozilla
reftest.list to the stdout.
"""

from __future__ import unicode_literals, print_function, absolute_import

TEST_FILE = 'text-emphasis-line-height-{:03}{}.html'
TEST_TEMPLATE = '''<!DOCTYPE html>
<meta charset="utf-8">

<title>CSS Test: text-emphasis line height, {pos}, {wm}, {tag}</title>
<link rel="author" title="Xidorn Quan" href="https://www.upsuper.org">
<link rel="author" title="Mozilla" href="https://www.mozilla.org">
<link rel="help" href="https://drafts.csswg.org/css-text-decor-3/#text-emphasis-position-property">
<meta name="assert" content="text emphasis marks should expand the line height like ruby if necessary">
<link rel="match" href="text-emphasis-line-height-{index:03}-ref.html">

Pass if the emphasis marks are {dir} the black line:

{start}試験テスト{end}
'''

REF_FILE = 'text-emphasis-line-height-{:03}-ref.html'
REF_TEMPLATE='''<!DOCTYPE html>
<meta charset="utf-8">

<title>CSS Reference: text-emphasis line height, {pos}</title>
<link rel="author" title="Xidorn Quan" href="https://www.upsuper.org">
<link rel="author" title="Mozilla" href="https://www.mozilla.org">

Pass if the emphasis marks are {dir} the black line:

<ruby>試<rt>●</rt>験<rt>●</rt>テ<rt>●</rt>ス<rt>●</rt>ト<rt>●</rt></ruby>

'''

STYLE1 = 'line-height: 1; border-{pos}: 1px solid black; ' + \
         'writing-mode: {wm}; text-emphasis-position: {posval};'
STYLE2 = 'text-emphasis: circle;'

TAGS = [
    # (tag, start, end)
    ('div', '
', '
'),
    ('span', '
', '
'),
    ]
POSITIONS = [
    # pos, text-emphasis-position, ruby-position,
    #   writing-modes, dir text
    ('top', 'over right', 'over',
        ['horizontal-tb'], 'below'),
    ('bottom', 'under right', 'under',
        ['horizontal-tb'], 'over'),
    ('right', 'over right', 'over',
        ['vertical-rl', 'vertical-lr'], 'to the left of'),
    ('left', 'over left', 'under',
        ['vertical-rl', 'vertical-lr'], 'to the right of'),
    ]

import string

def write_file(filename, content):
    with open(filename, 'wb') as f:
        f.write(content.encode('UTF-8'))

print("# START tests from {}".format(__file__))
idx = 0
for (pos, emphasis_pos, ruby_pos, wms, dir) in POSITIONS:
    idx += 1
    ref_file = REF_FILE.format(idx)
    content = REF_TEMPLATE.format(pos=pos, dir=dir, wm=wms[0], posval=ruby_pos)
    write_file(ref_file, content)
    suffix = iter(string.ascii_lowercase)
    for wm in wms:
        style1 = STYLE1.format(pos=pos, wm=wm, posval=emphasis_pos)
        for (tag, start, end) in TAGS:
            test_file = TEST_FILE.format(idx, next(suffix))
            content = TEST_TEMPLATE.format(
                pos=pos, wm=wm, tag=tag, index=idx, dir=dir,
                start=start.format(style1=style1, style2=STYLE2), end=end)
            write_file(test_file, content)
            print("== {} {}".format(test_file, ref_file))
print("# END tests from {}".format(__file__))


text:
package org.elasticsearch.xpack.ql;

import org.apache.http.HttpHost;
import org.elasticsearch.Version;

public final class TestNode {

    private final String id;
    private final Version version;
    private final HttpHost publishAddress;

    public TestNode(String id, Version version, HttpHost publishAddress) {
        this.id = id;
        this.version = version;
        this.publishAddress = publishAddress;
    }

    public String getId() {
        return id;
    }

    public HttpHost getPublishAddress() {
        return publishAddress;
    }

    public Version getVersion() {
        return version;
    }

    @Override
    public String toString() {
        return "Node{" + "id='" + id + '\'' + ", version=" + version + '}';
    }
}


text:
DROP TABLE IF EXISTS {{table_name}}_stats;
CREATE TABLE {{table_name}}_stats (
  process_name TEXT PRIMARY KEY,
  min_value REAL,
  max_value REAL,
  avg_value REAL,
  max_delta_value REAL
);

DROP TABLE IF EXISTS {{table_name}}_delta;
CREATE TABLE {{table_name}}_delta AS
WITH rolling_delta AS (
  -- emits one row per ts point
  SELECT
    upid,
    {{table_name}}_val - MIN({{table_name}}_val) OVER win AS delta
  FROM {{table_name}}_span
  WINDOW win AS (
    PARTITION BY upid
    ORDER BY ts
    ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  )
)
SELECT
  upid,
  -- max over all ts
  MAX(delta) AS delta
FROM rolling_delta
GROUP BY 1;

INSERT INTO {{table_name}}_stats
SELECT
  process.name AS process_name,
  MIN(span.{{table_name}}_val) AS min_value,
  MAX(span.{{table_name}}_val) AS max_value,
  SUM(span.{{table_name}}_val * span.dur) / SUM(span.dur) AS avg_value,
  MAX(delta.delta) AS max_delta_value
FROM {{table_name}}_span AS span
JOIN {{table_name}}_delta AS delta USING(upid)
JOIN process USING(upid)
WHERE process.name IS NOT NULL
GROUP BY 1
ORDER BY 1;

DROP VIEW IF EXISTS {{table_name}}_stats_proto;
CREATE VIEW {{table_name}}_stats_proto AS
SELECT
  process_name,
  AndroidMemoryMetric_Counter(
    'min', min_value,
    'max', max_value,
    'avg', avg_value,
    'delta', max_delta_value
  ) AS proto
FROM {{table_name}}_stats;


text:
package io.cloudslang.content.active_directory.entities;

import java.util.List;

public interface GetCompAccountOUInput {
    String getPassword();

    String getUsername();

    String getComputerCommonName();

    String getHost();

    String getRootDistinguishedName();

    String getProtocol();

    Boolean getTrustAllRoots();

    String getTrustKeystore();

    String getTrustPassword();

    String getTimeout();

    String getProxyHost();

    int getProxyPort();

    String getProxyUsername();

    String getProxyPassword();

    String getX509HostnameVerifier();

    String getTlsVersion();

    List<String> getAllowedCiphers();
}


text:
package org.jetbrains.idea.svn.actions;

import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.AbstractVcsHelper;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.VcsDirectoryMapping;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.idea.svn.SvnBundle;
import org.jetbrains.idea.svn.SvnStatusUtil;
import org.jetbrains.idea.svn.SvnUtil;
import org.jetbrains.idea.svn.SvnVcs;

import java.util.Arrays;
import java.util.List;

public class ShareWholeProject extends AnAction implements DumbAware {
  @Override
  public void update(final AnActionEvent e) {
    final MyChecker checker = new MyChecker();
    checker.execute(e);

    final Presentation presentation = e.getPresentation();
    presentation.setEnabled(checker.isEnabled());

    presentation.setVisible(checker.isVisible());
    if (checker.isEnabled()) {
      presentation.setText(SvnBundle.message("action.share.whole.project.text"));
    }
  }

  private static class MyChecker {
    private boolean myEnabled;
    private boolean myVisible;
    private Project myProject;
    private boolean myHadNoMappings;

    public void execute(final AnActionEvent e) {
      final DataContext dataContext = e.getDataContext();
      myProject = PlatformDataKeys.PROJECT.getData(dataContext);
      if (myProject == null || myProject.isDefault()) {
        // remain false
        return;
      }
      final VirtualFile baseDir = myProject.getBaseDir();
      if (baseDir == null) return;

      final ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(myProject);
      final MyCheckResult result = checkMappings(baseDir, vcsManager);

      if (MyCheckResult.disable.equals(result)) return;

      myHadNoMappings = MyCheckResult.notMapped.equals(result);
      if (MyCheckResult.notMapped.equals(result)) {
        // no change list manager working
        if(SvnUtil.seemsLikeVersionedDir(baseDir)) return;
      } else if (SvnStatusUtil.isUnderControl(myProject, baseDir)) {
        return;
      }

      if ((! myHadNoMappings) && (! SvnVcs.getInstance(myProject).getSvnFileUrlMapping().isEmpty())) {
        // there are some versioned dirs under project dir
        return;
      }

      // visible: already checked above
      myVisible = true;
      myEnabled = (! vcsManager.isBackgroundVcsOperationRunning());
    }

    private static enum MyCheckResult {
      disable,
      notMapped,
      rootToSvn
    }

    private static MyCheckResult checkMappings(final VirtualFile baseDir, final ProjectLevelVcsManager vcsManager) {
      final List<VcsDirectoryMapping> mappings = vcsManager.getDirectoryMappings();

      boolean notMapped = true;
      boolean svnMappedToBase = false;
      for (VcsDirectoryMapping mapping : mappings) {
        final String vcs = mapping.getVcs();
        if (vcs != null && vcs.length() > 0) {
          notMapped = false;
          if (SvnVcs.VCS_NAME.equals(vcs)) {
            if (mapping.isDefaultMapping() || baseDir.getPath().equals(mapping.getDirectory())) {
              svnMappedToBase = true;
              break;
            }
          }
        }
      }

      return svnMappedToBase ? MyCheckResult.rootToSvn :
             (notMapped ? MyCheckResult.notMapped : MyCheckResult.disable);
    }

    public boolean isEnabled() {
      return myEnabled;
    }

    public boolean isVisible() {
      return myVisible;
    }

    public Project getProject() {
      return myProject;
    }

    public boolean isHadNoMappings() {
      return myHadNoMappings;
    }
  }

  public void actionPerformed(AnActionEvent e) {
    final MyChecker checker = new MyChecker();
    checker.execute(e);
    if (! checker.isEnabled()) return;

    final Project project = checker.getProject();
    final VirtualFile baseDir = project.getBaseDir();
    if (baseDir == null) return;
    boolean success = false;
    boolean excThrown = false;
    try {
      success = ShareProjectAction.share(project, baseDir);
    } catch (VcsException exc) {
      AbstractVcsHelper.getInstance(project).showError(exc, "Failed to Share Project");
      excThrown = true;
    } finally {
      // if success = false -> either action was cancelled or exception was thrown, so also check for exception
      if (success || excThrown) {
        baseDir.refresh(true, true, new Runnable() {
          public void run() {
            ApplicationManager.getApplication().invokeLater(new Runnable() {
              @Override
              public void run() {
                VcsDirtyScopeManager.getInstance(project).dirDirtyRecursively(project.getBaseDir());
                if (checker.isHadNoMappings() && SvnUtil.seemsLikeVersionedDir(baseDir)) {
                  final ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(project);
                  vcsManager.setDirectoryMappings(Arrays.asList(new VcsDirectoryMapping("", SvnVcs.VCS_NAME)));
                }
              }
            }, ModalityState.NON_MODAL, project.getDisposed());
          }
        });
      }
    }
  }
}


text:
// Copyright (C) 2011 Vicente J. Botet Escriba
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

// <boost/thread/null_mutex>

// class null_mutex;

// template <class Clock, class Duration>
//     bool try_lock_until(const chrono::time_point<Clock, Duration>& abs_time);

#include <boost/thread/null_mutex.hpp>
#include <boost/thread/thread.hpp>
#include <boost/detail/lightweight_test.hpp>

#if defined BOOST_THREAD_USES_CHRONO

boost::null_mutex m;

typedef boost::chrono::steady_clock Clock;
typedef Clock::time_point time_point;
typedef Clock::duration duration;
typedef boost::chrono::milliseconds ms;
typedef boost::chrono::nanoseconds ns;

void f1()
{
  time_point t0 = Clock::now();
  BOOST_TEST(m.try_lock_until(Clock::now() + ms(300) ) == true);
  time_point t1 = Clock::now();
  m.unlock();
  ns d = t1 - t0 ;
  BOOST_TEST(d < ns(5000000)); // within 5ms
}

int main()
{
  {
    m.lock();
    boost::thread t(f1);
    m.unlock();
    t.join();
  }

  return boost::report_errors();
}

#else
#error "Test not applicable: BOOST_THREAD_USES_CHRONO not defined for this platform as not supported"
#endif


text:
#ifndef AML_PRIVATE_H
#define AML_PRIVATE_H

#include <stddef.h>
#include <stdint.h>

/* Utility functions */
unsigned int plat_calc_core_pos(u_register_t mpidr);
void aml_console_init(void);
void aml_setup_page_tables(void);

/* MHU functions */
void aml_mhu_secure_message_start(void);
void aml_mhu_secure_message_send(uint32_t msg);
uint32_t aml_mhu_secure_message_wait(void);
void aml_mhu_secure_message_end(void);
void aml_mhu_secure_init(void);

/* SCPI functions */
void aml_scpi_set_css_power_state(u_register_t mpidr, uint32_t cpu_state,
				  uint32_t cluster_state, uint32_t css_state);
uint32_t aml_scpi_sys_power_state(uint64_t system_state);
void aml_scpi_jtag_set_state(uint32_t state, uint8_t select);
uint32_t aml_scpi_efuse_read(void *dst, uint32_t base, uint32_t size);
void aml_scpi_unknown_thermal(uint32_t arg0, uint32_t arg1,
			      uint32_t arg2, uint32_t arg3);
void aml_scpi_upload_scp_fw(uintptr_t addr, size_t size, int send);
uint32_t aml_scpi_get_chip_id(uint8_t *obuff, uint32_t osize);

/* Peripherals */
void aml_thermal_unknown(void);
uint64_t aml_efuse_read(void *dst, uint32_t offset, uint32_t size);
uint64_t aml_efuse_user_max(void);

#endif /* AML_PRIVATE_H */


text:
using UnityEngine;
using System.Collections;

public class Rotate_VLS : MonoBehaviour
{
    public float speed = 100;
    public Vector3 Axis = new Vector3(0, 0, 1);

	void FixedUpdate ()
    {
        transform.Rotate(Axis * Time.deltaTime * speed);
	}
}


text:
import numpy

from .base import Sequence

class White(Sequence):
    """White sequence."""
    # TODO complete docstring.

    def __init__(self):

        bit_planes = 1  # bit depth of the pictures
        pic_num = 1  # number of pictures
        Sequence.__init__(self, bit_planes, pic_num)

    def get_user_array(self):
        """Get user array"""

        dtype = numpy.uint8
        width, height = self.device.get_resolution()
        size = width * height
        max_ = numpy.iinfo(dtype).max
        dtype = numpy.iinfo(dtype).dtype
        frame = max_ * numpy.ones(size, dtype=dtype)

        return frame


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using FluentAssertions;
using Paramore.Brighter.Core.Tests.CommandProcessors.TestDoubles;
using Paramore.Brighter.Inbox;
using Polly;
using Polly.Registry;
using Microsoft.Extensions.DependencyInjection;
using Paramore.Brighter.Extensions.DependencyInjection;
using Xunit;
using Paramore.Brighter.Inbox.Handlers;

namespace Paramore.Brighter.Core.Tests.CommandProcessors
{
    public class CommandProcessorBuildDefaultInboxSendAsyncTests : IDisposable
    {
        private readonly CommandProcessor _commandProcessor;
        private readonly InMemoryInbox _inbox = new InMemoryInbox();

        public CommandProcessorBuildDefaultInboxSendAsyncTests()
        {
             var handler = new MyCommandHandlerAsync(new Dictionary<string, Guid>());

             var subscriberRegistry = new SubscriberRegistry();
             //This handler has no Inbox attribute
             subscriberRegistry.RegisterAsync<MyCommand, MyCommandHandlerAsync>();

             var container = new ServiceCollection();
             container.AddSingleton<MyCommandHandlerAsync>(handler);
             container.AddSingleton<IAmAnInboxAsync>(_inbox);
             container.AddTransient<UseInboxHandlerAsync<MyCommand>>();

            var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider());

             var retryPolicy = Policy
                .Handle<Exception>()
                .RetryAsync();

             var circuitBreakerPolicy = Policy
                .Handle<Exception>()
                .CircuitBreakerAsync(1, TimeSpan.FromMilliseconds(1));

             var inboxConfiguration = new InboxConfiguration(
                InboxScope.All, //grab all the events
                onceOnly: true, //only allow once
                actionOnExists: OnceOnlyAction.Throw //throw on duplicates (we should  be the only entry after)
            );

           _commandProcessor = new CommandProcessor(
                subscriberRegistry,
                (IAmAHandlerFactoryAsync)handlerFactory,
                new InMemoryRequestContextFactory(),
                new PolicyRegistry
                {
                    { CommandProcessor.RETRYPOLICYASYNC, retryPolicy },
                    { CommandProcessor.CIRCUITBREAKERASYNC, circuitBreakerPolicy }
                },
                inboxConfiguration: inboxConfiguration
                );

        }

        [Fact]
        public async Task WhenInsertingADefaultInboxIntoTheSendPipeline()
        {
            //act
            var command = new MyCommand(){Value = "Inbox Capture"};
            await _commandProcessor.SendAsync(command);

            //assert we are in, and auto-context added us under our name
            var boxed = await _inbox.ExistsAsync<MyCommand>(command.Id, typeof(MyCommandHandlerAsync).FullName, 100);
            boxed.Should().BeTrue();
        }

        public void Dispose()
        {
            _commandProcessor.Dispose();
        }
 }
}


text:
id: require-license
title: require-license
---

Enabling this rule will result in an error being generated if `license` field is missing from the `package.json` file.

## Example .npmpackagejsonlintrc configuration

```json
{
  "rules": {
    "require-license": "error"
  }
}
```

## Rule Details

### *Incorrect* example(s)

```json
{

}
```

### *Correct* example(s)

```json
{
  "license": "MIT"
}
```

## History

* Renamed from license-required to require-license in version 1.0.0
* Introduced in version 0.1.0


text:
using content::BrowserThread;

namespace platform_util {

namespace {

const char kGmailComposeUrl[] =
    "https://mail.google.com/mail/?extsrc=mailto&url=";

void ShowWarningOnOpenOperationResult(Profile* profile,
                                      const base::FilePath& path,
                                      OpenOperationResult result) {
  int message_id = IDS_FILE_BROWSER_ERROR_VIEWING_FILE;
  switch (result) {
    case OPEN_SUCCEEDED:
      return;

    case OPEN_FAILED_PATH_NOT_FOUND:
      message_id = IDS_FILE_BROWSER_ERROR_UNRESOLVABLE_FILE;
      break;

    case OPEN_FAILED_INVALID_TYPE:
      return;

    case OPEN_FAILED_NO_HANLDER_FOR_FILE_TYPE:
      if (path.MatchesExtension(FILE_PATH_LITERAL(".dmg")))
        message_id = IDS_FILE_BROWSER_ERROR_VIEWING_FILE_FOR_DMG;
      else if (path.MatchesExtension(FILE_PATH_LITERAL(".exe")) ||
               path.MatchesExtension(FILE_PATH_LITERAL(".msi")))
        message_id = IDS_FILE_BROWSER_ERROR_VIEWING_FILE_FOR_EXECUTABLE;
      else
        message_id = IDS_FILE_BROWSER_ERROR_VIEWING_FILE;
      break;

    case OPEN_FAILED_FILE_ERROR:
      message_id = IDS_FILE_BROWSER_ERROR_VIEWING_FILE;
      break;
  }

  Browser* browser = chrome::FindTabbedBrowser(profile, false);
  chrome::ShowWarningMessageBox(
      browser ? browser->window()->GetNativeWindow() : nullptr,
      l10n_util::GetStringFUTF16(IDS_FILE_BROWSER_ERROR_VIEWING_FILE_TITLE,
                                 path.BaseName().AsUTF16Unsafe()),
      l10n_util::GetStringUTF16(message_id));
}

}  // namespace

namespace internal {

void DisableShellOperationsForTesting() {
  file_manager::util::DisableShellOperationsForTesting();
}

}  // namespace internal

void ShowItemInFolder(Profile* profile, const base::FilePath& full_path) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  file_manager::util::ShowItemInFolder(
      profile, full_path,
      base::Bind(&ShowWarningOnOpenOperationResult, profile, full_path));
}

void OpenItem(Profile* profile,
              const base::FilePath& full_path,
              OpenItemType item_type,
              const OpenOperationCallback& callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  file_manager::util::OpenItem(
      profile, full_path, item_type,
      callback.is_null()
          ? base::Bind(&ShowWarningOnOpenOperationResult, profile, full_path)
          : callback);
}

void OpenExternal(Profile* profile, const GURL& url) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  // This code should be obsolete since we have default handlers in ChromeOS
  // which should handle this. However - there are two things which make it
  // necessary to keep it in:
  // a.) The user might have deleted the default handler in this session.
  //     In this case we would need to have this in place.
  // b.) There are several code paths which are not clear if they would call
  //     this function directly and which would therefore break (e.g.
  //     "Browser::EmailPageLocation" (to name only one).
  // As such we should keep this code here.
  NavigateParams params(profile, url, ui::PAGE_TRANSITION_LINK);
  params.disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB;

  if (url.SchemeIs("mailto")) {
    std::string string_url = kGmailComposeUrl;
    string_url.append(url.spec());
    params.url = GURL(url);
  }

  Navigate(&params);
}

bool IsBrowserLockedFullscreen(const Browser* browser) {
  aura::Window* window = browser->window()->GetNativeWindow();
  // |window| can be nullptr inside of unit tests.
  if (!window)
    return false;
  return window->GetProperty(ash::kWindowPinTypeKey) ==
         ash::WindowPinType::kTrustedPinned;
}

}  // namespace platform_util


text:
class DefaultController < ApplicationController
  before_filter :get_user

  def get_user
    # a bit of a hack but this grabs the 'other_user' stubbed out in the test and makes @user available to helper methods
    @user = other_user
  end

end


text:
import re,urlparse,json
from liveresolver.modules import client
import urllib

def resolve(url):

    try:
        try:
            referer = urlparse.parse_qs(urlparse.urlparse(url).query)['referer'][0]
            url = url.replace(referer,'').replace('?referer=','').replace('&referer=','')
        except: referer = url

        result = client.request(url,referer=referer)
        url = re.findall('(http://.+?\.m3u8)',result)[0]
        url += '|%s' % urllib.urlencode({'User-Agent': client.agent(), 'Referer': referer})
        return url
    except:
        return


text:
export LANGUAGE=en  # Be sure the commands output English text

head --help

cat /etc/dictionaries-common/words > /tmp/file.txt

head /tmp/file.txt

head -n 20 /tmp/file.txt

wc -l /tmp/file.txt

head -n 100 /tmp/file.txt | wc -l  # 100 lines, from 1st to 100th
head -n -100 /tmp/file.txt | wc -l  # All lines but the last 100 lines, from 1st to 99071th

tail --help

tail /tmp/file.txt  # Last 10 lines

tail -n 20 /tmp/file.txt  # Last 20 lines

tail -n 100 /tmp/file.txt | wc -l  # 100 lines, from 99071th to 99171th
tail -n +101 /tmp/file.txt | wc -l  # All lines from line 101, from 101th to 99171th


text:
from django.contrib.humanize.templatetags.humanize import naturaltime
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_noop

from dimagi.utils.decorators.memoized import memoized

from corehq.apps.groups.models import Group
from corehq.apps.reports import util
from corehq.apps.reports.datatables import DataTablesHeader, DataTablesColumn, DTSortType
from corehq.apps.reports.generic import GenericReportView
from corehq.apps.reports.models import HQUserType
from corehq.apps.reports.standard.cases.basic import CaseListMixin
from corehq.apps.reports.standard.cases.data_sources import CaseDisplay

from .dispatcher import EditDataInterfaceDispatcher

class DataInterface(GenericReportView):
    # overriding properties from GenericReportView
    section_name = ugettext_noop("Data")
    base_template = "reports/standard/base_template.html"
    asynchronous = True
    dispatcher = EditDataInterfaceDispatcher
    exportable = False

    @property
    def default_report_url(self):
        return reverse('data_interfaces_default', args=[self.request.project])

class CaseReassignmentInterface(CaseListMixin, DataInterface):
    name = ugettext_noop("Reassign Cases")
    slug = "reassign_cases"

    report_template_path = 'data_interfaces/interfaces/case_management.html'

    @property
    @memoized
    def all_case_sharing_groups(self):
        return Group.get_case_sharing_groups(self.domain)

    @property
    def headers(self):
        headers = DataTablesHeader(
            DataTablesColumn(mark_safe('Select  all none'), sortable=False, span=2),
            DataTablesColumn(_("Case Name"), span=3, prop_name="name.exact"),
            DataTablesColumn(_("Case Type"), span=2, prop_name="type.exact"),
            DataTablesColumn(_("Owner"), span=2, prop_name="owner_display", sortable=False),
            DataTablesColumn(_("Last Modified"), span=3, prop_name="modified_on"),
        )
        return headers

    @property
    def rows(self):
        checkbox = mark_safe('<input type="checkbox" class="selected-commcare-case" data-caseid="%(case_id)s" data-owner="%(owner)s" data-ownertype="%(owner_type)s" />')
        for row in self.es_results['hits'].get('hits', []):
            case = self.get_case(row)
            display = CaseDisplay(self, case)
            yield [
                checkbox % dict(case_id=case['_id'], owner=display.owner_id, owner_type=display.owner_type),
                display.case_link,
                display.case_type,
                display.owner_display,
                naturaltime(display.parse_date(display.case['modified_on'])),
            ]

    @property
    def report_context(self):
        context = super(CaseReassignmentInterface, self).report_context
        active_users = self.get_all_users_by_domain(user_filter=tuple(HQUserType.all()), simplified=True)
        context.update(
            users=[dict(ownerid=user.user_id, name=user.username_in_report, type="user")
                   for user in active_users],
            groups=[dict(ownerid=group.get_id, name=group.name, type="group")
                    for group in self.all_case_sharing_groups],
            user_ids=self.user_ids,
        )
        return context


text:
PONY_EXTERN_C_BEGIN

bool genopt(compile_t* c, bool pony_specific);
bool target_is_linux(char* triple);
bool target_is_bsd(char* triple);
bool target_is_freebsd(char* triple);
bool target_is_dragonfly(char* triple);
bool target_is_openbsd(char* triple);
bool target_is_macosx(char* triple);
bool target_is_windows(char* triple);
bool target_is_posix(char* triple);
bool target_is_x86(char* triple);
bool target_is_arm(char* triple);
bool target_is_ppc(char* triple);
bool target_is_lp64(char* triple);
bool target_is_llp64(char* triple);
bool target_is_ilp32(char* triple);
bool target_is_native128(char* triple);
bool target_is_bigendian(char* triple);
bool target_is_littleendian(char* triple);

PONY_EXTERN_C_END

#endif


text:
package com.github.monee1988.base.service;

import com.github.monee1988.base.dao.BaseWRDao;
import com.github.monee1988.base.entity.BaseBean;
import com.github.monee1988.mybatis.entity.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by monee1988 on 17-6-9.
 */
public class BaseWRService<T extends BaseBean<T>,DAO extends BaseWRDao<T>>  {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired(required = false)
    protected DAO dao;

    protected T getDataById(String id) {
        return dao.getDataById(id);
    }

    protected List<T> listData(T t){
        return dao.listData(t);
    }

    protected Page<T> findPage(Page<T> page, T t) {

        t.setPage(page);
        page.setList(listData(t));

        return page;
    }

    protected void saveFormData(T t,Long adminId) throws Exception{

        try {
            if(t.isNewData()){
                t.preInsert(adminId);
                dao.saveData(t);
            }else{
                t.preUpdate(adminId);
                dao.updateData(t);;
            }
        } catch (Exception e) {
            logger.error("行程系统->系统异常:" + e.fillInStackTrace());
            throw e;
        }
    }

    protected void deleteDatasByIds(List<String> idList) throws Exception{

        try {
            dao.deleteByIds(idList);
        } catch (Exception e) {
            logger.error("行程系统->系统异常:" + e.fillInStackTrace());
            throw e;
        }
    }

}


text:
package com.levelup.java.io;

import static org.junit.Assert.assertEquals;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.junit.Test;

import com.google.common.base.Charsets;
import com.google.common.io.Files;

/**
 * This java example will demonstrate how to read a file into an {@link ArrayList}.
 *
 * @author Justin Musgrove
 * @see Read file into arraylist
 */
public class ReadFileIntoArrayList {

	private static final Logger logger = Logger
			.getLogger(ReadFileIntoArrayList.class);

	Path worldSeriesWinners = Paths
			.get("src/test/resources/com/levelup/java/io/read-file-into-arraylist.txt")
			.toAbsolutePath();

	@Test
	public void read_file_array_list_java() throws FileNotFoundException {

		InputStream in = new FileInputStream(worldSeriesWinners.toFile());

		BufferedReader reader = new BufferedReader(new InputStreamReader(in));

		List<String> teams = new ArrayList<String>();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				teams.add(line);
			}
		} catch (IOException e) {
			logger.error(e);
		} finally {
			try {
				reader.close();
			} catch (IOException e) {
				logger.error(e);
			}
		}
		assertEquals(10, teams.size());

	}

	@Test
	public void read_file_array_list_java7() throws IOException {

		List<String> teams = java.nio.file.Files.readAllLines(
				worldSeriesWinners, Charset.defaultCharset());

		assertEquals(10, teams.size());
	}

	@Test
	public void read_file_array_list_java8() throws IOException {

		List<String> teams = java.nio.file.Files.lines(worldSeriesWinners)
				.collect(Collectors.toList());

		assertEquals(10, teams.size());

	}

	@Test
	public void read_file_array_list_guava() throws IOException {

		List<String> teams = Files.readLines(worldSeriesWinners.toFile(),
				Charsets.UTF_8);

		assertEquals(10, teams.size());
	}

	@Test
	public void read_file_array_list_apache() throws IOException {

		List<String> teams = FileUtils.readLines(worldSeriesWinners.toFile());

		assertEquals(10, teams.size());
	}

}


text:
'use strict'

const wrapper         = require('./util/result-wrapper'),
      logger          = require('../../../util/logger'),
      timeoutRejector = require('../../../util/promise').timeoutRejector,
      Backendless     = require('backendless'),
      path            = require('path')

const SHUTDOWN_CODE = 32768
const SHUTDOWN_ACTION = 'SHUTDOWN'

const Modes = {
  PRODUCTION : 'PRODUCTION',
  MARKETPLACE: 'MARKETPLACE',
  DEBUG      : 'DEBUG'
}

/**
 * @typedef {Object} InitAppData
 * @property {string} secretKey
 * @property {string} url
 */

/**
 * @typedef {Object} CodeRunnerTask
 * @property {String} id
 * @property {String} ___jsonclass
 * @property {String} applicationId;
 * @property {InitAppData} initAppData;
 * @property {Number} timeout
 * @property {String} relativePath
 * @property {String} codePath
 * @property {String} mode
 */

const executor = module.exports = {}

executor.RMI = 'com.backendless.coderunner.commons.protocol.RequestMethodInvocation'
executor.RAI = 'com.backendless.coderunner.commons.protocol.RequestActionInvocation'
executor.RSI = 'com.backendless.coderunner.commons.protocol.RequestServiceInvocation'

const executors = {
  [executor.RMI]: './invoke-handler',
  [executor.RAI]: './invoke-action',
  [executor.RSI]: './invoke-service'
}

const CACHEABLE_EXECUTORS = [
  executor.RMI,
  executor.RSI,
]

executor.isTaskCacheable = task => {
  return CACHEABLE_EXECUTORS.includes(task.___jsonclass)
}

/**
 * @param {CodeRunnerTask} task
 * @returns {Function} task executor
 */
function getTaskExecutor(task) {
  const taskClass = task.___jsonclass

  if (!executors[taskClass]) {
    throw new Error(`Unknown task [${ taskClass }]`)
  }

  return require(executors[taskClass])
}

function executeTask(task, model) {
  const taskExecutor = getTaskExecutor(task)

  if (task.timeout < 0) {
    return taskExecutor(task, model)
  }

  const timeoutPromise = timeoutRejector(task.timeout, 'Task execution is aborted due to timeout')

  return Promise
    .race([
      taskExecutor(task, model),
      timeoutPromise
    ])
    .then(result => {
      timeoutPromise.cancel()

      return result
    })
}

/**
 * @param {CodeRunnerTask} task
 * @param {Object} opts
 */
function initClientSdk(task, opts) {
  if (task.initAppData) {
    Backendless.serverURL = task.initAppData.url

    if (!Backendless.Config) {
      Backendless.Config = {}
    }

    Object.assign(Backendless.Config, opts.backendless.public)

    Backendless.initApp(task.applicationId, task.initAppData.apiKey || task.initAppData.secretKey)

    if (opts.backendless.forwardableHeaders) {
      applyTransferringHeaders(task, opts.backendless.forwardableHeaders)
    }
  }
}

/**
 * BKNDLSS-27918
 *
 * @param {CodeRunnerTask} task
 * @param {Array<String>} forwardableHeaders
 */
function applyTransferringHeaders(task, forwardableHeaders) {
  const sourceHTTPHeaders = task.invocationContextDto.httpHeaders
  const targetHTTPHeaders = {}

  for (const httpHeaderKey in sourceHTTPHeaders) {
    if (forwardableHeaders[httpHeaderKey.toLowerCase()]) {
      targetHTTPHeaders[httpHeaderKey] = sourceHTTPHeaders[httpHeaderKey]
    }
  }

  const _nativeSend = Backendless.request.send._nativeSend || Backendless.request.send

  Backendless.request.send = function(options) {
    options = options ? { ...options } : {}
    options.headers = options.headers ? { ...targetHTTPHeaders, ...options.headers } : { ...targetHTTPHeaders }

    return _nativeSend.call(this, options)
  }

  Backendless.request.send._nativeSend = _nativeSend
}

/**
 * @param {CodeRunnerTask} task
 * @param {Object} opts
 */
function enrichTask(task, opts) {
  task.codePath = path.resolve(opts.backendless.repoPath, task.applicationId.toLowerCase(), task.relativePath || '')

  //TODO: workaround for http://bugs.backendless.com/browse/BKNDLSS-12041
  if (task.___jsonclass === executor.RMI && task.eventId === SHUTDOWN_CODE) {
    task.___jsonclass = executor.RAI
    task.actionType = SHUTDOWN_ACTION
  }

  task.invocationContextDto = task.invocationContextDto || {}
  task.invocationContextDto.response = {
    headers: task.invocationContextDto.httpResponseHeaders || {},
  }
}

/**
 * @param {CodeRunnerTask} task
 * @param {?Error|ExceptionWrapper|String=} error
 * @param {?*} result
 * @returns {Object} task invocation result in JSON
 */
function wrapResult(task, error, result) {
  if (error) {
    const message = error instanceof timeoutRejector.Error
      ? error.message
      : error.stack || `Error: ${ error.message || error }`

    logger.error(message)
  }

  return wrapper.invocationResult(task.id, task.invocationContextDto, error, result)
}

/**
 * @param {CodeRunnerTask} task
 * @param {Object} opts
 */
const applySandbox = (task, opts) => {
  const sandboxRequired = opts.sandbox && task.mode !== Modes.MARKETPLACE

  if (sandboxRequired) {
    require('./sandbox').apply(task.applicationId)
  }
}

/**
 * @param {InvokeServiceTask|InvokeHandlerTask} task
 * @param {Object} opts
 * @returns {ServerCodeModel}
 */
function getServerCodeModel(task, opts) {
  const ServerCodeModelDescriptor = require('../../model/descriptor')

  opts.scModels = opts.scModels || {}
  opts.scModels[task.codePath] = opts.scModels[task.codePath] || ServerCodeModelDescriptor.load(task.codePath)

  return opts.scModels[task.codePath].getModelForFile(task.provider)
}

/**
 * @param {CodeRunnerTask} task
 * @param {Object} opts
 * @param {ServerCodeModel=} model
 * @returns {Promise.<?string>} task invocation result in JSON (if any)
 */
executor.execute = async function(task, opts, model) {
  let response = null

  try {
    enrichTask(task, opts)
    initClientSdk(task, opts)
    applySandbox(task, opts)

    if (!model && task.provider) {
      model = getServerCodeModel(task, opts)
    }

    response = await executeTask(task, model)

    if (response !== undefined) {
      response = wrapResult(task, null, response)
    }

  } catch (error) {
    if (error instanceof timeoutRejector.Error) {
      task.criticalError = error.message
    }

    response = wrapResult(task, error)
  }

  if (logger.verboseMode) {
    logger.verbose('[TRACE.REQUEST]:', JSON.stringify(task))
    logger.verbose('[TRACE.RESPONSE]:', JSON.stringify(response))
  }

  if (response && !response.exception) {
    response.arguments = response.arguments !== undefined
      ? wrapper.encodeArguments(response.arguments)
      : []
  }

  return JSON.stringify(response)
}


text:
import copy as cp
import random as rd

import numpy as np

# dirty, but easiest: global variables to control the injection and recovery
hard_iter = None
hard_step = None
strategy = None
hard_random = 0.0
hard_stats = []
refdata = None

def hard_fault_injection(S):
    """
    Injects a node failure and recovers using a defined strategy, can be called in the controller

    Args:
        S: the current step data structure
    Returns:
         the step after a node failure

    """

    # name global variables for this routine
    global hard_iter, hard_step, strategy, hard_stats, hard_random, refdata

    # set the seed in the first iteration, using the process number for reproducibility
    if S.status.iter == 1:
        rd.seed(S.status.slot)

    # draw random number and check if we are below our threshold (hard_random gives percentage)
    if strategy == 'NOFAULT':
        doit = rd.random() < hard_random
        if doit:
            hard_stats.append((S.status.slot, S.status.iter, S.time))
    else:
        if refdata is not None:
            # noinspection PyTypeChecker
            doit = np.any(np.all([S.status.slot, S.status.iter, S.time] == refdata, axis=1))
        else:
            doit = False

    # if we set step and iter, inject and recover (if faults are supposed to occur)
    if ((hard_step == S.status.slot and hard_iter == S.status.iter) or doit) and strategy != 'NOFAULT':

        print('things went wrong here: step %i -- iteration %i -- time %e' % (S.status.slot, S.status.iter, S.time))

        # add incident to statistics data type
        hard_stats.append((S.status.slot, S.status.iter, S.time))

        # ok, that's a little bit of cheating... we would need to retrieve the current residual and iteration count
        # from the previous process, but this does not matter here
        res = cp.deepcopy(S.levels[-1].status.residual)
        niter = cp.deepcopy(S.status.iter) - 1
        time = cp.deepcopy(S.time)

        # fault injection, set everything to zero or null or whatever
        S.reset_step()

        for lvl in S.levels:
            lvl.status.time = time

        # recovery
        if strategy == 'SPREAD':
            S = hard_fault_correction_spread(S)
        elif strategy == 'INTERP':
            S = hard_fault_correction_interp(S)
        elif strategy == 'INTERP_PREDICT':
            S = hard_fault_correction_interp_predict(S, res, niter)
        elif strategy == 'SPREAD_PREDICT':
            S = hard_fault_correction_spread_predict(S, res, niter)
        else:
            raise NotImplementedError('recovery strategy not implemented')

    return S

# Here come the recovery strategies

def hard_fault_correction_spread(S):
    """
    do nothing, just get new initial conditions and do sweep predict (copy)
    strategy '1-sided'

    Args:
        S: the current step (no data available)
    Returns:
        S: recovered step
    """

    # get new initial data, either from previous processes or "from scratch"
    if not S.status.first:
        ufirst = S.prev.levels[0].prob.dtype_u(S.prev.levels[0].uend)
    else:
        ufirst = S.levels[0].prob.u_exact(S.time)

    L = S.levels[0]

    # set data
    L.u[0] = L.prob.dtype_u(ufirst)
    # call prediction of the sweeper (copy the values to all nodes)
    L.sweep.predict()
    # compute uend
    L.sweep.compute_end_point()

    # proceed with fine sweep
    S.status.stage = 'IT_FINE_SWEEP'

    return S

def hard_fault_correction_interp(S):
    """
    get new initial conditions from left and uend from right, then interpolate
    strategy '2-sided'

    Args:
        S: the current step (no data available)
    Returns:
        S: recovered step
    """

    # get new initial data, either from previous processes or "from scratch"
    if not S.status.first:
        ufirst = S.prev.levels[0].prob.dtype_u(S.prev.levels[0].uend)
    else:
        ufirst = S.levels[0].prob.u_exact(S.time)

    # if I'm not the last one, get uend from following process
    # otherwise set uend = u0, so that interpolation is a copy
    if not S.status.last:
        ulast = S.next.levels[0].prob.dtype_u(S.next.levels[0].u[0])
    else:
        ulast = ufirst

    L = S.levels[0]

    # set u0, and interpolate the rest
    # evaluate f for each node (fixme: we could try to interpolate here as well)
    L.u[0] = L.prob.dtype_u(ufirst)
    L.f[0] = L.prob.eval_f(L.u[0], L.time)
    for m in range(1, L.sweep.coll.num_nodes + 1):
        L.u[m] = (1 - L.sweep.coll.nodes[m - 1]) * ufirst + L.sweep.coll.nodes[m - 1] * ulast
        L.f[m] = L.prob.eval_f(L.u[m], L.time + L.dt * L.sweep.coll.nodes[m - 1])

    # set fine level to active
    L.status.unlocked = True
    # compute uend
    L.sweep.compute_end_point()

    # proceed with fine sweep
    S.status.stage = 'IT_FINE_SWEEP'

    return S

def hard_fault_correction_spread_predict(S, res, niter):
    """
    get new initial conditions from left, copy data to nodes and correct on coarse level
    strategy '1-sided+corr'

    Args:
        S: the current step (no data available)
        res: the target residual
        niter: the max. number of iteration
    Returns:
        S: recovered step
    """

    # get new initial data, either from previous processes or "from scratch"
    if not S.status.first:
        ufirst = S.prev.levels[0].prob.dtype_u(S.prev.levels[0].uend)
    else:
        ufirst = S.levels[0].prob.u_exact(S.time)

    L = S.levels[0]

    # set u0, and copy
    L.u[0] = L.prob.dtype_u(ufirst)
    L.sweep.predict()

    # transfer to the coarsest level (overwrite values)
    for l in range(1, len(S.levels)):
        S.transfer(source=S.levels[l - 1], target=S.levels[l])

    # compute preliminary residual (just to set it)
    S.levels[-1].status.updated = True
    S.levels[-1].sweep.compute_residual()
    # keep sweeping until either k < niter or the current residual is lower than res (niter, res was stored before
    # fault injection (lazy, should get this from the previous process)
    k = 0
    if res is not None:
        while S.levels[-1].status.residual > res and k < niter:
            k += 1
            print(S.levels[-1].status.residual, res, k)
            S.levels[-1].sweep.update_nodes()
            S.levels[-1].sweep.compute_residual()

    # transfer back to finest level (coarse correction!)
    for l in range(len(S.levels) - 1, 0, -1):
        S.transfer(source=S.levels[l], target=S.levels[l - 1])

    # compute uend
    L.sweep.compute_end_point()

    # proceed with fine sweep
    S.status.stage = 'IT_FINE_SWEEP'

    return S

def hard_fault_correction_interp_predict(S, res, niter):
    """
    get new initial conditions from left and uend from right, interpolate data to nodes and correct on coarse level
    strategy '2-sided+corr'

    Args:
        S: the current step (no data available)
        res: the target residual
        niter: the max. number of iteration
    Returns:
        S: recovered step
    """

    # get new initial data, either from previous processes or "from scratch"
    if not S.status.first:
        ufirst = S.prev.levels[0].prob.dtype_u(S.prev.levels[0].uend)
    else:
        ufirst = S.levels[0].prob.u_exact(S.time)

    # if I'm not the last one, get uend from following process
    # otherwise set uend = u0, so that interpolation is a copy
    if not S.status.last:
        ulast = S.next.levels[0].prob.dtype_u(S.next.levels[0].u[0])
    else:
        ulast = ufirst

    L = S.levels[0]

    # set u0, and interpolate the rest
    # evaluate f for each node (fixme: we could try to interpolate here as well)
    L.u[0] = L.prob.dtype_u(ufirst)
    L.f[0] = L.prob.eval_f(L.u[0], L.time)
    for m in range(1, L.sweep.coll.num_nodes + 1):
        L.u[m] = (1 - L.sweep.coll.nodes[m - 1]) * ufirst + L.sweep.coll.nodes[m - 1] * ulast
        L.f[m] = L.prob.eval_f(L.u[m], L.time + L.dt * L.sweep.coll.nodes[m - 1])

    # set fine level to active
    L.status.unlocked = True

    # transfer to the coarsest level (overwrite values)
    for l in range(1, len(S.levels)):
        S.transfer(source=S.levels[l - 1], target=S.levels[l])

    # compute preliminary residual (just to set it)
    S.levels[-1].status.updated = True
    S.levels[-1].sweep.compute_residual()
    # keep sweeping until either k < niter or the current residual is lower than res (niter, res was stored before
    # fault injection (lazy, should get this from the previous process)
    k = 0
    if res is not None:
        while S.levels[-1].status.residual > res and k < niter:
            k += 1
            print(S.levels[-1].status.residual, res, k)
            S.levels[-1].sweep.update_nodes()
            S.levels[-1].sweep.compute_residual()

    # transfer back to finest level (coarse correction!)
    for l in range(len(S.levels) - 1, 0, -1):
        S.transfer(source=S.levels[l], target=S.levels[l - 1])

    # compute uend
    L.sweep.compute_end_point()

    # proceed with fine sweep
    S.status.stage = 'IT_FINE_SWEEP'

    return S


text:
const footerPrimaryColor = 'rgb(63, 81, 181)';

const footerButton = {
  backgroundColor: footerPrimaryColor,
  height: 56,
  maxWidth: 76,
  borderRadius: 0,
  borderTopWidth: 5,
  borderTopColor: footerPrimaryColor,
};

export default {
  footerContainer: {
    height: 56,
    backgroundColor: 'white',
  },
  footerTab: {
    backgroundColor: footerPrimaryColor,
  },
  footerButton,
  footerButtonActive: {
    ...footerButton,
    borderTopColor: 'white',
  },
  footerButtonSpinning: {
    ...footerButton,
    maxWidth: 68,
  },
  buttonText: {
    fontSize: 10,
    fontWeight: 'bold',
    color: 'white',
  },
  checkInButton: {
    ...footerButton,
    alignSelf: 'center',
    maxWidth: 68,
  },
  checkInButtonIcon: {
    color: 'white',
    fontSize: 30,
  },
};


text:
/**
 * Created by angelina-zf on 16/12/7.
 */
package yeeMiddleware

import (
	"fmt"
	"github.com/agelinazf/yee/yeeNet/yeeWeb/yeeContext"
	"io"
	"runtime"
	"time"
)

//MiddlewareHandlerFunc 中间件函数
type MiddlewareHandlerFunc func(next yeeContext.HandlerFunc) yeeContext.HandlerFunc

//MiddlewareChain 包含了一堆中间件函数
type MiddlewareChain struct {
	middlewareHandlers []MiddlewareHandlerFunc
}

//NewMiddlewareChain 创建一个新的中间件链
func NewMiddlewareChain(handlerArray ...MiddlewareHandlerFunc) *MiddlewareChain {
	chain := new(MiddlewareChain)
	chain.middlewareHandlers = handlerArray
	return chain
}

//Append 添加一个中间件函数到链中
func (chain *MiddlewareChain) Append(fn MiddlewareHandlerFunc) {
	chain.middlewareHandlers = append(chain.middlewareHandlers, fn)
}

//Generate 将链上的全部中间件函数组装到传入的HandlerFunc,并生成成一个HandlerFunc返回
func (chain *MiddlewareChain) Generate(fn yeeContext.HandlerFunc) yeeContext.HandlerFunc {
	for i := len(chain.middlewareHandlers) - 1; i >= 0; i-- {
		fn = chain.middlewareHandlers[i](fn)
	}
	return fn
}

func LogMiddleWare(out io.Writer) MiddlewareHandlerFunc {
	return func(next yeeContext.HandlerFunc) yeeContext.HandlerFunc {
		fn := func(ctx *yeeContext.Context) {
			start := time.Now()
			path := ctx.Request().URL.Path
			next(ctx)
			end := time.Now()
			latency := end.Sub(start)
			clientIP := ctx.IP()
			method := ctx.Request().Method
			statusCode := ctx.StatusCode()
			_, file, line, _ := runtime.Caller(1)
			var short string
			for i := len(file) - 1; i > 0; i-- {
				if file[i] == '/' {
					short = file[i+1:]
					break
				}
			}
			fmt.Fprintf(out, "%s:%d |%v | %3d | %13v | %s | %-7s %s\n",
				short, line,
				end.Format("2006/01/02 - 15:04:05"),
				statusCode,
				latency,
				clientIP,
				method,
				path,
			)
		}
		return fn
	}
}


text:
layout: doc
title: JOSM Vorlagen
permalink: /de/josm/josm-presets/
lang: de
category: josm
---

JOSM Vorlagen
============

> Gereviewt am 2016-09-17

Wenn man JOSM schon etwas länger verwendet, versteht man etwas von Tags und Vorlagen. Jedes Objekt wird durch zwei Dinge definiert - als erstes durch seine Geometrie (ob es ein Punkt, eine Linie oder ein Umriss ist und sein Standort) und zweitens durch seine Attribute in Form von Tags.

Wenn man ein Objekt mittels Vorlagenmenü zeichnet, werden die korrekten Tags automatisch dem Objekt zugeordnet.

Was passiert, wenn man Tags trotz der Verwendung von Vorlagen hinzufügen möchte, die nicht im Menü enthalten sind oder man eigene Tags anpassen möchte?

Hier kann man eigene Menüeinträge zu den Vorlagen hinzufügen. Wir zeigen Ihnen in diesem Abschnitt wie das geht. Das [nächste Kapitel](/de/josm/creating-presets) befasst sich mit der Erstellung eigener Vorlagendateien.

Vorlagen hinzufügen
-----------

Die Menüs und Untermenüs des Vorlagenmenüs sind in Dateien gespeichert, die beschreiben, wie Menüs und Formulare erstellt werden, wenn man auf eine Vorlage klickt und welche Tags einem Objekt hinzugefügt werden, je nachdem wie das Formular ausgefüllt wird.

Vorlagen können entweder von einer Onlinebibliothek aus oder lokal gespeichert und hinzugefügt werden in JOSM.

* Um einen neuen Eintrag dem Vorlagenmenu hinzuzufügen, öffnet man JOSM und geht zu Bearbeiten->Einstellungen.
* Man klickt auf das dritte Tab, das wie ein Gitter über einem Planeten aussieht.

![tagging presets tab][]

* Oben klickt man auf "Tagging Vorlagen".

![tagging presets menu][]

* Man fügt eine Vorlage aus dem Internet hinzu durch Auswahl in der Liste 	zur Linken und durch klicken auf den blauen Pfeil. In diesem Beispiel 	fügen wir die Vorlage "New Tags" hinzu.

![example presets][]

* Man sieht einen neuen Eintrag erscheinen in der Liste auf der rechten Seite.
* Man klickt OK.
* Man startet JOSM neu.
* Man erstellt einen neuen Layer und fügt einen Punkt oder Umriss hinzu.
* Im Vorlagen-Menü gibt es jetzt einen neuen Eintrag am Ende, der verschiedene Möglichkeiten bietet, die in der Standardinstallation nicht enthalten sind.

![additional tags preset][]

* Die meisten Vorlagen sind für recht spezielle Anwendungsfälle aber vielleicht findet sich in der Liste ja etwas passendes.

* Falls man eine angepasste Vorlagendatei bekommen hat, kann man es auf ähnlichem Weg dem Menü hinzufügen. Man kehrt zurück zum Einstellungen Menü und anstatt dass man etwas in der Liste auswählt, klickt man auf den (+) Button oben rechts.

![plus button][]

* Man sucht die Datei und gibt ihr gegebenenfalls einen Namen.
* Man klickt OK.

[tagging presets tab]: /images/josm/tagging-presets-tab.png
[tagging presets menu]: /images/josm/tagging-presets-menu.png
[example presets]: /images/josm/example-presets2.png
[additional tags preset]: /images/josm/new-tags-preset.png
[plus button]: /images/josm/plus-button.png


text:
class RedirectsController < ActionController::Base
  def go
    redirect = Redirect.find_by(source_uri: source_uri)

    if redirect && redirect.enabled?
      redirect.used!
      redirect.working!
      redirect_to redirect.destination_uri, status: redirect.status_code
    else
      render plain: 'No such redirect or disabled.', status: 404
    end
  end

  private

  def source_uri
    "/go/#{params[:slug]}"
  end
end


text:
Return to Search

Loading...


text:
package scalismo.faces.sampling.face.evaluators

import scalismo.faces.FacesTestSuite
import scalismo.faces.image.PixelImage
import scalismo.faces.landmarks.{LandmarkDetectionMap, TLMSLandmark2D}
import scalismo.faces.parameters.RenderParameter
import scalismo.faces.sampling.face.ParametricLandmarksRenderer
import scalismo.faces.sampling.face.evaluators.PointEvaluators.IsotropicGaussianPointEvaluator
import scalismo.geometry._

class LandmarkMapEvaluatorTests extends FacesTestSuite {

  private val rawDetectionMap = PixelImage(20, 20, (x, y) => {
    -0.5 * (Point(x, y) - Point(5, 5)).norm2
  })

  private val detectionMap = LandmarkDetectionMap("testLM", rawDetectionMap)

  private val initParam = RenderParameter.default
  private def lmRenderer(point: Point[_2D]) = new ParametricLandmarksRenderer {
    /** list of all known landmarks */
    override def allLandmarkIds: IndexedSeq[String] = IndexedSeq("testLM")

    /** check if landmark id is known */
    override def hasLandmarkId(lmId: String): Boolean = allLandmarkIds.contains(lmId)

    /** render landmark given by lmId */
    override def renderLandmark(lmId: String, parameter: RenderParameter): Option[TLMSLandmark2D] = {
      Some(TLMSLandmark2D("testLM", point, visible = true))
    }
  }

  describe("A LandmarksDetectionMap") {
    it("provides direct lookup") {
      detectionMap.logValues(5, 5) shouldBe 0.0
    }

    it("can be corrected with error rates of detection") {
      val fp = 0.05
      val fn = 0.07
      val corrected = detectionMap.correctCertaintyForErrorRates(fp, fn)
      math.exp(corrected.logValues(5, 5)) shouldBe 1.0 - fp
      math.exp(corrected.logValues(19, 19)) shouldBe 0.0 + fn
    }
  }

  describe("A LandmarksMapEvaluator") {
    val fp = 0.05
    val fn = 0.07
    val corrected = detectionMap.correctCertaintyForErrorRates(fp, fn)

    val randomPoints = Seq.fill(5){Point(rnd.scalaRandom.nextInt(rawDetectionMap.width), rnd.scalaRandom.nextInt(rawDetectionMap.height))}

    it("provides a constructor for isotropic Gaussian noise models with proper value on strongest detection") {
      val lmNoise = IsotropicGaussianPointEvaluator[_2D](5.0).toDistributionEvaluator(Point2D.origin)
      val lmEval = LandmarkMapEvaluator.withIsotropicGaussianNoise(Seq(corrected), lmRenderer(Point(5, 5)), 5.0)
      lmEval.logValue(initParam) shouldBe (corrected.logValues(5, 5) + lmNoise.logValue(Point2D.origin))
    }

    it("with precalculated noise model returns the proper value for a few points") {
      val lmNoise = IsotropicGaussianPointEvaluator[_2D](2.0)

      def checkPoint(point: Point[_2D]): Unit = {
        val renderer = lmRenderer(point)
        val lmEval = LandmarkMapEvaluator.withIsotropicGaussianNoise(Seq(corrected), renderer, 2.0)
        val explicitValue = { // brute force maximum finder
          corrected.logValues.mapWithIndex{ (v, x, y) =>
            v + lmNoise.logValue(Point(x, y), point)
          }.values.max
        }
        lmEval.logValue(initParam) shouldBe explicitValue +- 1e-10
      }

      // check for 5 random points
      for (pt <- randomPoints)
        checkPoint(pt)
    }

    it("with an explicit noise model returns the proper value for a few points") {
      val lmNoise = IsotropicGaussianPointEvaluator[_2D](2.0)

      def checkPoint(point: Point[_2D]): Unit = {
        val renderer = lmRenderer(point)
        val lmEvalExplicit = LandmarkMapEvaluator.withLandmarksLikelihood(Seq(corrected), renderer, lmNoise)
        val explicitValue = { // brute force maximum finder
          corrected.logValues.mapWithIndex{ (v, x, y) =>
            v + lmNoise.logValue(Point(x, y), point)
          }.values.max
        }
        lmEvalExplicit.logValue(initParam) shouldBe explicitValue +- 1e-10
      }

      // check for 5 random points
      for (pt <- randomPoints)
        checkPoint(pt)
    }
  }
}


text:
<?xml version="1.0" ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<link rel="stylesheet" type="text/css" href="../../../../../scineplex.css">
<title></title>
<link rel="stylesheet" href="../../../../../Active.css" type="text/css" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rev="made" href="mailto:" />

NAME

AFFILIATION

DESCRIPTION

CONFIGURATION

AUTHOR

COPYRIGHT

NAME

Perl::Critic::Policy::BuiltinFunctions::RequireGlobFunction - Use glob q{*}
 instead of <*>.

AFFILIATION

This Policy is part of the core Perl::Critic distribution.

DESCRIPTION

Conway discourages the use of the  <.. > construct for globbing, as it is easily confused with the angle bracket file input operator. Instead, he recommends the use of the glob() function as it makes it much more obvious what you're attempting to do.

    @files = <*.pl>;              # not ok
    @files = glob '*.pl';         # ok

CONFIGURATION

This Policy is not configurable except for the standard options.

AUTHOR

Graham TerMarsch <graham@howlingfrog.com>

COPYRIGHT

Copyright (c) 2005-2011 Graham TerMarsch. All rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_location"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="定位"
        android:textSize="18sp" />

</LinearLayout>