text:
package com.bxtel.model.dao;

import com.bxtel.model.*;
import com.bxtel.model.model.*;
import dinamica.*;
import dinamica.util.*;
import dinamica.util.StringUtil;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.sql.DataSource;
import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import org.springframework.jdbc.core.*;
import org.springframework.stereotype.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import com.googlecode.ehcache.annotations.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import oracle.sql.ROWID;
import com.bxtel.exception.DAOException;

@Repository(".SmsDAO")
public class .SmsDAO
{

	@Resource
	public JdbcTemplate jdbcTemplate;

	@Resource
	public NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	private static final Log logger = LogFactory.getLog(.SmsDAO.class);

	//@TriggersRemove(cacheName = ".SmsDAO", when = When.AFTER_METHOD_INVOCATION, removeAll = true)
	public .Sms add(.Sms model) throws DAOException  {
		String rowid=addThenReturnRowid(model);
		return  get.SmsByRowId(rowid);
	}

	public String addThenReturnRowid(.Sms model) throws DAOException  {
		model.setCurversion(0L);

		StringBuffer sql = new StringBuffer("insert into .Sms("
				+" .Sms "
				+",.Sms "
				+",.Sms "
				+",.Sms "
				+",.Sms "

		+") values("

					+":.Sms"
					+",:.Sms"
					+",:.Sms"
					+",:.Sms"
					+",:.Sms"
		  + ")" );

		KeyHolder keyHolder = new GeneratedKeyHolder();
		SqlParameterSource sps=new BeanPropertySqlParameterSource(model);
		namedParameterJdbcTemplate.update(sql.toString(), sps,keyHolder);
		oracle.sql.ROWID id=(ROWID) keyHolder.getKeys().get("ROWID");
		return id.stringValue();
	}

	public .Sms get.SmsByRowId(String rowid) throws DAOException {
		StringBuffer sql=new StringBuffer("select t.*,rowid as crowid from .Sms t where rowid='"+rowid+"'");
		List<.Sms> modellist = jdbcTemplate.query(sql.toString(),new BeanPropertyRowMapper(.Sms.class));
		if(modellist!=null && modellist.size()==1)
		{
			return  modellist.get(0);
		}else{
			throw new DAOException("rowid is wrong:"+rowid);
		}
	}

	//@TriggersRemove(cacheName = ".SmsDAO", when = When.AFTER_METHOD_INVOCATION, removeAll = true)
	public int deleteByCoud(.Sms model) {

		StringBuffer sql=new StringBuffer("delete from .Sms where 1=1 ");
		if(model.get.Sms()!=null)
		{
			sql.append(" and .Sms=:.Sms ");
		}
		if(model.get.Sms()!=null)
		{
			sql.append(" and .Sms=:.Sms ");
		}
		if(model.get.Sms()!=null)
		{
			sql.append(" and .Sms=:.Sms ");
		}
		if(model.get.Sms()!=null)
		{
			sql.append(" and .Sms=:.Sms ");
		}
		if(model.get.Sms()!=null)
		{
			sql.append(" and .Sms=:.Sms ");
		}

		SqlParameterSource sps=new BeanPropertySqlParameterSource(model);
		return namedParameterJdbcTemplate.update(sql.toString(), sps);
	}

	//@TriggersRemove(cacheName = ".SmsDAO", when = When.AFTER_METHOD_INVOCATION, removeAll = true)
	public int deleteByExact(.Sms model) throws DAOException  {

		StringBuffer sql=new StringBuffer("delete from .Sms where 1=1 ");
		sql.append(" and .Sms=:.Sms ");
		sql.append(" and .Sms=:.Sms ");
		sql.append(" and .Sms=:.Sms ");
		sql.append(" and .Sms=:.Sms ");
		sql.append(" and .Sms=:.Sms ");

		SqlParameterSource sps=new BeanPropertySqlParameterSource(model);
		return namedParameterJdbcTemplate.update(sql.toString(), sps);
	}

	//@TriggersRemove(cacheName = ".SmsDAO", when = When.AFTER_METHOD_INVOCATION, removeAll = true)
	public int deleteByRowId(String rowid)  throws DAOException  {
		if(StringUtil.isEmptyOrWhitespace(rowid))
		{
			throw new DAOException("rowid is null");
		}
		StringBuffer sql=new StringBuffer("delete from .Sms where rowid='"+rowid+"'");
		return jdbcTemplate.update(sql.toString());
	}

	//@TriggersRemove(cacheName = ".SmsDAO", when = When.AFTER_METHOD_INVOCATION, removeAll = true)
	public int updateExactByRowId(.Sms model)  throws DAOException  {
		if(StringUtil.isEmptyOrWhitespace(model.getCrowid()))
		{
			throw new DAOException("rowid is null");
		}
		StringBuffer sql=new StringBuffer("update  .Sms set ");
						sql.append(".Sms=:.Sms,");
						sql.append(".Sms=:.Sms,");
						sql.append(".Sms=:.Sms,");
						sql.append(".Sms=:.Sms,");
						sql.append(".Sms=:.Sms");
		sql=new StringBuffer(StringUtil.removeLastWith(sql.toString(),","));
		sql.append(" where rowid='"+model.getCrowid()+"'  and curversion=:curversion ");
		SqlParameterSource sps=new BeanPropertySqlParameterSource(model);
		return namedParameterJdbcTemplate.update(sql.toString(), sps);
	}

	//@TriggersRemove(cacheName = ".SmsDAO", when = When.AFTER_METHOD_INVOCATION, removeAll = true)
	public int updateCoudByRowId(.Sms model)  throws DAOException  {
		if(StringUtil.isEmptyOrWhitespace(model.getCrowid()))
		{
			throw new DAOException("rowid is null");
		}
		StringBuffer sql=new StringBuffer("update  .Sms set ");
					if(model.get.Sms()!=null)
					{
						sql.append(".Sms=:.Sms ,");
					}
					if(model.get.Sms()!=null)
					{
						sql.append(".Sms=:.Sms ,");
					}
					if(model.get.Sms()!=null)
					{
						sql.append(".Sms=:.Sms ,");
					}
					if(model.get.Sms()!=null)
					{
						sql.append(".Sms=:.Sms ,");
					}
					if(model.get.Sms()!=null)
					{
						sql.append(".Sms=:.Sms ,");
					}
		sql=new StringBuffer(StringUtil.removeLastWith(sql.toString(),","));
		sql.append(" where rowid='"+model.getCrowid()+"'   and curversion=:curversion ");
		SqlParameterSource sps=new BeanPropertySqlParameterSource(model);
		return namedParameterJdbcTemplate.update(sql.toString(), sps);
	}

	//@TriggersRemove(cacheName = ".SmsDAO", when = When.AFTER_METHOD_INVOCATION, removeAll = true)
	public int updateByCoudAndWhere(.Sms model,.Sms wheremodel)  throws DAOException  {

		boolean haspk=false;

		if(haspk=false)
		{
			throw new DAOException("no primary key ");
		}

		StringBuffer sql=new StringBuffer("update  .Sms set ");
					if(model.get.Sms()!=null)
					{
						sql.append(".Sms=:.Sms ,");
					}
					if(model.get.Sms()!=null)
					{
						sql.append(".Sms=:.Sms ,");
					}
					if(model.get.Sms()!=null)
					{
						sql.append(".Sms=:.Sms ,");
					}
					if(model.get.Sms()!=null)
					{
						sql.append(".Sms=:.Sms ,");
					}
					if(model.get.Sms()!=null)
					{
						sql.append(".Sms=:.Sms ,");
					}

		sql=new StringBuffer(StringUtil.removeLastWith(sql.toString(),","));

		StringBuffer where=new StringBuffer("");
					if(wheremodel.get.Sms()!=null)
					{
						where.append("and .Sms=:.Sms ,");
					}
					if(wheremodel.get.Sms()!=null)
					{
						where.append("and .Sms=:.Sms ,");
					}
					if(wheremodel.get.Sms()!=null)
					{
						where.append("and .Sms=:.Sms ,");
					}
					if(wheremodel.get.Sms()!=null)
					{
						where.append("and .Sms=:.Sms ,");
					}
					if(wheremodel.get.Sms()!=null)
					{
						where.append("and .Sms=:.Sms ,");
					}
		if(where.equals(""))
		{
			throw new DAOException(" must have where condition");
		}
		sql=new StringBuffer(StringUtil.removeLastWith(sql.toString(),","));
		sql.append(" where 1=1  "+where.toString());
		SqlParameterSource sps=new BeanPropertySqlParameterSource(model);
		return namedParameterJdbcTemplate.update(sql.toString(), sps);
	}

	/*
	//@TriggersRemove(cacheName = ".SmsDAO", when = When.AFTER_METHOD_INVOCATION, removeAll = true)
	public void batchInsert(List<.Sms> list)  throws DAOException{

		StringBuffer sql = new StringBuffer("insert into .Sms("
				+" .Sms "
				+",.Sms "
				+",.Sms "
				+",.Sms "
				+",.Sms "

		+") values("

				+"?"
				+",?"
				+",?"
				+",?"
				+",?"
		  + ")" );

		PreparedStatement ps=null;
		Connection conn = null;
		try{

			  conn = DataSourceUtils.getConnection(jdbcTemplate.getDataSource());
			  ps= conn.prepareStatement(sql.toString());
			  for (int i = 0; i < list.size(); i++) {

					ps.setlong(1, list.get(i).get.Sms());
					ps.setjava.lang.String(2, list.get(i).get.Sms());
					ps.setjava.lang.String(3, list.get(i).get.Sms());
					ps.setjava.lang.String(4, list.get(i).get.Sms());
					ps.setjava.lang.String(5, list.get(i).get.Sms());

					ps.addBatch();
					ps.clearParameters();
					if(i%500==0 || i==list.size()-1)
					{
						ps.executeBatch();
					}
			  }
			  ps.close();
		}catch (Exception ex) {
			 ex.printStackTrace();
		}finally{
			JdbcUtils.closeStatement(ps);
			DataSourceUtils.releaseConnection(conn, jdbcTemplate.getDataSource());
		}

	}

	//@TriggersRemove(cacheName = ".SmsDAO", when = When.AFTER_METHOD_INVOCATION, removeAll = true)
	public void batchUpdate(List<.Sms> list)  throws DAOException{

		boolean haspk=false;

		if(haspk=false)
		{
			throw new DAOException("no primary key ");
		}

		StringBuffer sql=new StringBuffer("update  .Sms set ");
						sql.append(".Sms=? ,");
						sql.append(".Sms=? ,");
						sql.append(".Sms=? ,");
						sql.append(".Sms=? ,");
						sql.append(".Sms=? ,");

		if(sql.lastIndexOf(",")==sql.length()-1)
		{
			sql=new StringBuffer(sql.substring(0,sql.length()-2));
		}

		StringBuffer where=new StringBuffer(" where 1=1 ");
		sql.append(where.toString());

		PreparedStatement ps=null;
		Connection conn = null;
		try{

			  conn = DataSourceUtils.getConnection(jdbcTemplate.getDataSource());
			  ps= conn.prepareStatement(sql.toString());
			  for (int i = 0; i < list.size(); i++) {

					ps.setlong(1, list.get(i).get.Sms());
					ps.setjava.lang.String(2, list.get(i).get.Sms());
					ps.setjava.lang.String(3, list.get(i).get.Sms());
					ps.setjava.lang.String(4, list.get(i).get.Sms());
					ps.setjava.lang.String(5, list.get(i).get.Sms());

					ps.addBatch();
					ps.clearParameters();
					if(i%500==0 || i==list.size()-1)
					{
						ps.executeBatch();
					}
			  }
			  ps.close();
		}catch (Exception ex) {
			 ex.printStackTrace();
		}finally{
			JdbcUtils.closeStatement(ps);
			DataSourceUtils.releaseConnection(conn, jdbcTemplate.getDataSource());
		}
	}
	*/

	//@Cacheable(cacheName = ".SmsDAO",keyGenerator = @KeyGenerator (name = "StringCacheKeyGenerator",properties = {@Property( name="useReflection", value="true" ), @Property( name="checkforCycles", value="true" ),@Property( name="includeMethod", value="true" ) }   ))
	public List<.Sms> get.SmsListByCoud(.Sms model,int topN)  throws DAOException  {
		StringBuffer sql=new StringBuffer("select t.*,rowid as crowid from .Sms t where 1=1 ");
		if(model.get.Sms()!=null)
		{
			sql.append(" and .Sms=:.Sms ");
		}
		if(model.get.Sms()!=null)
		{
			sql.append(" and .Sms=:.Sms ");
		}
		if(model.get.Sms()!=null)
		{
			sql.append(" and .Sms=:.Sms ");
		}
		if(model.get.Sms()!=null)
		{
			sql.append(" and .Sms=:.Sms ");
		}
		if(model.get.Sms()!=null)
		{
			sql.append(" and .Sms=:.Sms ");
		}
		if(topN>0)
		{
			sql.append(" and rownum <= "+topN);
		}
		SqlParameterSource sps=new BeanPropertySqlParameterSource(model);
		List<.Sms> modellist = namedParameterJdbcTemplate.query(sql.toString(),sps,new BeanPropertyRowMapper(.Sms.class));
		return modellist;
	}

	public List<.Sms> get.SmsListByCoud(.Sms model)  throws DAOException
	{
		return get.SmsListByCoud(model,-1);
	}

	//@Cacheable(cacheName = ".SmsDAO",keyGenerator = @KeyGenerator (name = "StringCacheKeyGenerator",properties = {@Property( name="useReflection", value="true" ), @Property( name="checkforCycles", value="true" ),@Property( name="includeMethod", value="true" ) }   ))
	public List<.Sms> get.SmsListByExact(.Sms model)  throws DAOException  {
		StringBuffer sql=new StringBuffer("select t.*,rowid as crowid from .Sms t where 1=1 ");
			sql.append(" and .Sms=:.Sms ");
			sql.append(" and .Sms=:.Sms ");
			sql.append(" and .Sms=:.Sms ");
			sql.append(" and .Sms=:.Sms ");
			sql.append(" and .Sms=:.Sms ");

		SqlParameterSource sps=new BeanPropertySqlParameterSource(model);
		List<.Sms> modellist = namedParameterJdbcTemplate.query(sql.toString(),sps,new BeanPropertyRowMapper(.Sms.class));
		return modellist;
	}

	//@Cacheable(cacheName = ".SmsDAO",keyGenerator = @KeyGenerator (name = "StringCacheKeyGenerator",properties = {@Property( name="useReflection", value="true" ), @Property( name="checkforCycles", value="true" ),@Property( name="includeMethod", value="true" ) }   ))
	public List<Map<String, Object>> getListMapByCoud(.Sms model)  throws DAOException  {
		StringBuffer sql=new StringBuffer("select t.*,rowid as crowid  from .Sms  t where 1=1 ");
		if(model.get.Sms()!=null)
		{
			sql.append(" and .Sms=:.Sms ");
		}
		if(model.get.Sms()!=null)
		{
			sql.append(" and .Sms=:.Sms ");
		}
		if(model.get.Sms()!=null)
		{
			sql.append(" and .Sms=:.Sms ");
		}
		if(model.get.Sms()!=null)
		{
			sql.append(" and .Sms=:.Sms ");
		}
		if(model.get.Sms()!=null)
		{
			sql.append(" and .Sms=:.Sms ");
		}

		SqlParameterSource sps=new BeanPropertySqlParameterSource(model);
		List<Map<String, Object>> modellist = namedParameterJdbcTemplate.queryForList(sql.toString(),sps);
		return modellist;
	}

	//@Cacheable(cacheName = ".SmsDAO",keyGenerator = @KeyGenerator (name = "StringCacheKeyGenerator",properties = {@Property( name="useReflection", value="true" ), @Property( name="checkforCycles", value="true" ),@Property( name="includeMethod", value="true" ) }   ))
	public List<Map<String, Object>> getListMapByExact(.Sms model)  throws DAOException  {
		StringBuffer sql=new StringBuffer("select t.*,rowid as crowid  from .Sms t where 1=1 ");
			sql.append(" and .Sms=:.Sms ");
			sql.append(" and .Sms=:.Sms ");
			sql.append(" and .Sms=:.Sms ");
			sql.append(" and .Sms=:.Sms ");
			sql.append(" and .Sms=:.Sms ");

		SqlParameterSource sps=new BeanPropertySqlParameterSource(model);
		List<Map<String, Object>> modellist = namedParameterJdbcTemplate.queryForList(sql.toString(),sps);
		return modellist;
	}

	//@Cacheable(cacheName = ".SmsDAO",keyGenerator = @KeyGenerator (name = "StringCacheKeyGenerator",properties = {@Property( name="useReflection", value="true" ), @Property( name="checkforCycles", value="true" ),@Property( name="includeMethod", value="true" ) }   ))
	public List<.Sms>  getPageListByCound(.Sms model, int pageIndex,int rows)  throws DAOException  {
		StringBuffer sql=new StringBuffer("select t.*,rowid as crowid  from .Sms t where 1=1 ");
		if(model.get.Sms()!=null)
		{
			sql.append(" and .Sms=:.Sms ");
		}
		if(model.get.Sms()!=null)
		{
			sql.append(" and .Sms=:.Sms ");
		}
		if(model.get.Sms()!=null)
		{
			sql.append(" and .Sms=:.Sms ");
		}
		if(model.get.Sms()!=null)
		{
			sql.append(" and .Sms=:.Sms ");
		}
		if(model.get.Sms()!=null)
		{
			sql.append(" and .Sms=:.Sms ");
		}

		String sqlfinal=DBHelper.getPageSqlByPageIndex(sql.toString(),new Integer(pageIndex).toString(),new Integer(rows).toString());

		SqlParameterSource sps=new BeanPropertySqlParameterSource(model);

		List<.Sms> modellist = namedParameterJdbcTemplate.query(sqlfinal,sps,new BeanPropertyRowMapper<.Sms>(.Sms.class));

		return modellist;
	}

	//@Cacheable(cacheName = ".SmsDAO",keyGenerator = @KeyGenerator (name = "StringCacheKeyGenerator",properties = {@Property( name="useReflection", value="true" ), @Property( name="checkforCycles", value="true" ),@Property( name="includeMethod", value="true" ) }   ))
	public List<.Sms>  getPageListByExact(.Sms model, int pageIndex,int rows)   throws DAOException {
		StringBuffer sql=new StringBuffer("select t.*,rowid as crowid  from .Sms t where 1=1 ");
			if(model.get.Sms()!=null)
			{
				sql.append(" and .Sms=:.Sms ");
			}
			if(model.get.Sms()!=null)
			{
				sql.append(" and .Sms=:.Sms ");
			}
			if(model.get.Sms()!=null)
			{
				sql.append(" and .Sms=:.Sms ");
			}
			if(model.get.Sms()!=null)
			{
				sql.append(" and .Sms=:.Sms ");
			}
			if(model.get.Sms()!=null)
			{
				sql.append(" and .Sms=:.Sms ");
			}

		String sqlfinal=DBHelper.getPageSqlByPageIndex(sql.toString(),new Integer(pageIndex).toString(),new Integer(rows).toString());

		SqlParameterSource sps=new BeanPropertySqlParameterSource(model);

		List<.Sms> modellist = namedParameterJdbcTemplate.query(sqlfinal,sps,new BeanPropertyRowMapper<.Sms>(.Sms.class));

		return modellist;
	}

	public List<.Sms>  getPageListBy.SmsList(ArrayList<.Sms> modellist, int pageIndex,int rows) throws DAOException  {
		int startindex=(pageIndex-1)*rows+1;
		int endindex=pageIndex*rows;
		if(endindex>modellist.size()-1)
		{
			modellist.subList(startindex, endindex);
		}else{
			modellist.subList(startindex, modellist.size()-1);
		}
		return modellist;
	}

	public .Sms get.SmsByCoud(.Sms model)  throws DAOException  {
		List<.Sms> modellist =get.SmsListByCoud(model);
		if(modellist!=null&&modellist.size()==1)
		{
			return modellist.get(0);
		}else{
			return null;
		}
	}

	public .Sms get.SmsByExact(.Sms model)  throws DAOException  {
		List<.Sms> modellist =get.SmsListByExact(model);
		if(modellist!=null&&modellist.size()==1)
		{
			return modellist.get(0);
		}else{
			return null;
		}
	}

	public String  getSeq() {
		String sql="select .Sms.nextval as seqid from dual";

		List<Map<String, Object>> resultlist =null;
		try{

			resultlist = jdbcTemplate.queryForList(sql);
			if(resultlist.size()==1){
							Map<String, Object>  map = resultlist.get(0);
							BigDecimal seqid = (BigDecimal) map.get("SEQID");
							return seqid.toString();
			}
		}catch(Exception ex)
		{
			String createseq="create sequence .Sms minvalue 1 maxvalue 999999999999999999999999 start with 1 increment by 1";
			jdbcTemplate.update(createseq);
			resultlist = jdbcTemplate.queryForList(sql);
			if(resultlist.size()==1){
						Map<String, Object>  map = resultlist.get(0);
						BigDecimal seqid = (BigDecimal) map.get("SEQID");
						return seqid.toString();
			}
		}
		return "";
	}

	public int deleteByRowid(String rowid)  throws DAOException  {
		StringBuffer sql=new StringBuffer("delete  from  .Sms  where rowid='"+rowid+"'");
		return jdbcTemplate.update(sql.toString());
	}

}


text:
using Xunit;

namespace Receiver.Tests
{
    public class MapTests
    {
        [Fact]
        public void MapTrack_ReturnsFullyMappedTrackModel()
        {
            // Arrange
            var sut = Arrange.GetMapper();
            var jsonTrack = Arrange.GetJsonTrackState();

            // Act
            var track = sut.MapTrack(jsonTrack);

            // Assert
            Assert.NotNull(track);
            Assert.NotNull(track.Vehicles);
            Assert.NotEmpty(track.Vehicles);
            Assert.Equal(2, track.Vehicles.Count);
            Assert.Equal(jsonTrack.trackName, track.Name);
            Assert.Equal(jsonTrack.lapDist, track.Distance);
        }

        // Map Test idee
        // !!!! Track State, we gaan over States praten, en niet zomaar over losse flying objects. maakt geen sense.
        // .. map the given track json to a track state object
    }
}

redpajama_set_name: RedPajamaGithub


text:
package dagr.tasks.picard

import java.nio.file.Path

import dagr.core.execsystem.{Cores, Memory, ResourceSet}
import dagr.core.tasksystem.VariableResources
import dagr.tasks.DagrDef
import DagrDef.{PathToIntervals, PathToVcf}

import scala.collection.mutable.ListBuffer

/** Runs Picard's CollectVariantCallingMetrics metrics. */
class CollectVariantCallingMetrics(vcf: PathToVcf,
                                   prefix: Path,
                                   dbsnp: PathToVcf,
                                   intervals: Option[PathToIntervals] = None,
                                   dict: Option[Path] = None,
                                   gvcf: Boolean = false,
                                   minThreads: Int = 1,
                                   maxThreads: Int = 32)
  extends PicardTask with VariableResources {

  private val memory = Memory("4G")

  override def pickResources(availableResources: ResourceSet): Option[ResourceSet] = {
    availableResources.subset(minCores = Cores(minThreads), maxCores = Cores(maxThreads), memory = memory)
  }

  override protected def addPicardArgs(buffer: ListBuffer[Any]): Unit = {
    buffer.append("INPUT=" + vcf.toAbsolutePath)
    buffer.append("OUTPUT=" + prefix.toAbsolutePath)
    buffer.append("DBSNP=" + dbsnp.toAbsolutePath)
    intervals.foreach(interval => buffer.append("TARGET_INTERVALS=" + interval.toAbsolutePath))
    dict.foreach(d => buffer.append("SEQUENCE_DICTIONARY=" + d.toAbsolutePath))
    buffer.append("GVCF_INPUT=" + gvcf)
    buffer.append("THREAD_COUNT=" + resources.cores.toInt)
  }
}


text:
<!DOCTYPE html>

		<title>Datatable: Combo Editor</title>
		<link rel="stylesheet" href="../../../codebase/webix.css" type="text/css" charset="utf-8">

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

 Editor with autosuggest

Using Combo editor in grid


text:
include_recipe 'xml::ruby' unless platform_family?('windows')

chef_gem 'fog' do # ~FC009
  version node['rackspacecloud']['fog_version']
  compile_time true if Chef::Resource::ChefGem.method_defined?(:compile_time)
  action :install
end

chef_gem 'mime-types' do
  compile_time true if Chef::Resource::ChefGem.method_defined?(:compile_time)
end

require 'fog'


text:
<md-card>

View OrderItem

{{orderItem.customerOrder.displayName}}

		{{orderItem.qty}}

{{orderItem.product.displayName}}

  <button (click)="goBack()" >Back</button> <button (click)="enableEdit()" >Edit</button>
</md-card>

	<orderItem-edit [orderItem] = "orderItem" ></orderItem-edit>


text:
var assert = require('assert')
var LongModule = require('../')
var mongoose = require('mongoose')
var Schema = mongoose.Schema;
var Long;

describe('Long', function(){
  before(function(){
    Long = LongModule(mongoose);
  })

  it('is a function', function(){
    assert.equal('function', typeof Long);
  })

  it('extends mongoose.Schema.Types', function(){
    assert.ok(Schema.Types.Long);
    assert.equal(Long, Schema.Types.Long);
  })

  it('extends mongoose.Types', function(){
    assert.ok(mongoose.Types.Long);
    assert.equal(mongoose.mongo.Long, mongoose.Types.Long);
  })

  it('can be used in schemas', function(){
    var s = new Schema({ long: Long });
    var long = s.path('long')
    assert.ok(long instanceof mongoose.SchemaType);
    assert.equal('function', typeof long.get);

    var s = new Schema({ long: 'long' });
    var long = s.path('long')
    assert.ok(long instanceof mongoose.SchemaType);
    assert.equal('function', typeof long.get);
  })

  describe('integration', function(){
    var db, S, schema, id;

    before(function(done){
      db = mongoose.createConnection('mongodb://localhost:27017/mlong');
      db.once('open', function () {
        schema = new Schema({ long: Long, name: 'string' });
        S = db.model('Long', schema);
        done();
      });
    })

    after(function(done) {
      db.close(done);
    });

    describe('casts', function(){
      it('numbers', function(){
        var v = 200000000;
        var s = new S({ long: v });
        assert.ok(s.long instanceof mongoose.Types.Long);
        assert.equal(v, s.long.toNumber());

        v = new Number(200000000);
        s = new S({ long: v });
        assert.ok(s.long instanceof mongoose.Types.Long);
        assert.equal(+v, s.long.toNumber());
      })

      it('strings', function(){
        var v = '200000000';
        var s = new S({ long: v});
        assert.ok(s.long instanceof mongoose.Types.Long);
        assert.equal(v, s.long.toString());
      })

      it('null', function(){
        var s = new S({ long: null });
        assert.equal(null, s.long);
      })

      it('mongo.Long', function(){
        var s = new S({ long: new mongoose.Types.Long("90") });
        assert.ok(s.long instanceof mongoose.Types.Long);
        assert.equal(90, s.long.toNumber());
      })

      it('non-castables produce _saveErrors', function(done){
        var schema = new Schema({ long: Long }, { strict: 'throw' });
        var M = db.model('throws', schema);
        var m = new M({ long: [] });
        m.save(function (err) {
          assert.ok(err);
          assert.equal('ValidationError', err.name);
          assert.equal(err.errors['long'].name, 'CastError');
          done();
        });
      })
    })

    it('can be saved', function(done){
      var s = new S({ long: 20 });
      id = s.id;
      s.save(function (err) {
        assert.ifError(err);
        done();
      })
    })

    it('is queryable', function(done){
      S.findById(id, function (err, doc) {
        assert.ifError(err);
        assert.ok(doc.long instanceof mongoose.Types.Long);
        assert.equal(20, doc.long.toNumber());
        done();
      });
    })

    it('can be updated', function(done){
      S.findById(id, function (err, doc) {
        assert.ifError(err);
        doc.long = doc.long.add(mongoose.Types.Long.fromString("10"));
        doc.save(function (err) {
          assert.ifError(err);
          S.findById(id, function (err, doc) {
            assert.ifError(err);
            assert.equal(30, doc.long.toNumber());
            done();
          });
        })
      })
    })

    it('can be required', function(done){
      var s = new Schema({ long: { type: Long, required: true }});
      var M = db.model('required', s);
      var m = new M;
      m.save(function (err) {
        assert.ok(err);
        m.long = 10;
        m.validate(function (err) {
          assert.ifError(err);
          done();
        })
      })
    })

    it('works with update', function(done){
      S.create({ long: 99999 }, function (err, s) {
        assert.ifError(err);
        S.update({ long: s.long, _id: s._id }, { name: 'changed' }, { upsert: true }, function (err) {
          assert.ifError(err);

          S.findById(s._id, function (err, doc) {
            assert.ifError(err);
            assert.equal(99999, doc.long);
            assert.equal('changed', doc.name);
            done();
          })
        });
      });

    })
  })
})


text:
package fc

import (
	"os"
	"testing"
	"time"
)

type fakeFileInfo struct {
	name string
}

func (fi *fakeFileInfo) Name() string {
	return fi.name
}

func (fi *fakeFileInfo) Size() int64 {
	return 0
}

func (fi *fakeFileInfo) Mode() os.FileMode {
	return 777
}

func (fi *fakeFileInfo) ModTime() time.Time {
	return time.Now()
}
func (fi *fakeFileInfo) IsDir() bool {
	return false
}

func (fi *fakeFileInfo) Sys() interface{} {
	return nil
}

type fakeIOHandler struct{}

func (handler *fakeIOHandler) ReadDir(dirname string) ([]os.FileInfo, error) {
	switch dirname {
	case "/dev/disk/by-path/":
		f := &fakeFileInfo{
			name: "pci-0000:41:00.0-fc-0x500a0981891b8dc5-lun-0",
		}
		return []os.FileInfo{f}, nil
	case "/sys/block/":
		f := &fakeFileInfo{
			name: "dm-1",
		}
		return []os.FileInfo{f}, nil
	case "/dev/disk/by-id/":
		f := &fakeFileInfo{
			name: "scsi-3600508b400105e210000900000490000",
		}
		return []os.FileInfo{f}, nil
	}
	return nil, nil
}

func (handler *fakeIOHandler) Lstat(name string) (os.FileInfo, error) {
	return nil, nil
}

func (handler *fakeIOHandler) EvalSymlinks(path string) (string, error) {
	return "/dev/sda", nil
}

func (handler *fakeIOHandler) WriteFile(filename string, data []byte, perm os.FileMode) error {
	return nil
}

func TestSearchDisk(t *testing.T) {
	fakeMounter := fcDiskMounter{
		fcDisk: &fcDisk{
			wwns: []string{"500a0981891b8dc5"},
			lun:  "0",
			io:   &fakeIOHandler{},
		},
	}
	devicePath, error := searchDisk(fakeMounter)
	// if no disk matches input wwn and lun, exit
	if devicePath == "" || error != nil {
		t.Errorf("no fc disk found")
	}
}

func TestSearchDiskWWID(t *testing.T) {
	fakeMounter := fcDiskMounter{
		fcDisk: &fcDisk{
			wwids: []string{"3600508b400105e210000900000490000"},
			io:    &fakeIOHandler{},
		},
	}
	devicePath, error := searchDisk(fakeMounter)
	// if no disk matches input wwid, exit
	if devicePath == "" || error != nil {
		t.Errorf("no fc disk found")
	}
}


text:
//-----------------------------------------------------------------------
// <copyright file="RemotingLifecycleEvent.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2016 Typesafe Inc. <http://www.typesafe.com>
//     Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using Akka.Actor;
using Akka.Event;
using Akka.Util.Internal;

namespace Akka.Remote
{
    /// <summary>
    /// Remote lifecycle events that are published to the <see cref="EventStream"/> when
    /// initialization / connect / disconnect events that occur during network operations
    /// </summary>
    public abstract class RemotingLifecycleEvent
    {
        /// <summary>
        ///     Logs the level.
        /// </summary>
        /// <returns>LogLevel.</returns>
        public abstract LogLevel LogLevel();
    }

    public abstract class AssociationEvent : RemotingLifecycleEvent
    {
        public abstract Address LocalAddress { get; protected set; }
        public abstract Address RemoteAddress { get; protected set; }

        public abstract bool IsInbound { get; protected set; }

        protected string EventName;

        public override string ToString()
        {
            var networkDirection = IsInbound ? "<-" : "->";
            return string.Format("{0} [{1}] {2} {3}", EventName, LocalAddress, networkDirection, RemoteAddress);
        }
    }

    public sealed class AssociatedEvent : AssociationEvent
    {
        public override LogLevel LogLevel()
        {
            return Event.LogLevel.DebugLevel;
        }

        public override Address LocalAddress { get; protected set; }
        public override Address RemoteAddress { get; protected set; }
        public override bool IsInbound { get; protected set; }

        public AssociatedEvent(Address localAddress, Address remoteAddress, bool inbound)
        {
            LocalAddress = localAddress;
            RemoteAddress = remoteAddress;
            IsInbound = inbound;
            EventName = "Associated";
        }
    }

    public sealed class DisassociatedEvent : AssociationEvent
    {
        public override LogLevel LogLevel()
        {
            return Event.LogLevel.DebugLevel;
        }

        public override Address LocalAddress { get; protected set; }
        public override Address RemoteAddress { get; protected set; }
        public override bool IsInbound { get; protected set; }

        public DisassociatedEvent(Address localAddress, Address remoteAddress, bool inbound)
        {
            LocalAddress = localAddress;
            RemoteAddress = remoteAddress;
            IsInbound = inbound;
            EventName = "Disassociated";
        }
    }

    public sealed class AssociationErrorEvent : AssociationEvent
    {
        public AssociationErrorEvent(Exception cause, Address localAddress, Address remoteAddress, bool inbound, LogLevel level)
        {
            LocalAddress = localAddress;
            RemoteAddress = remoteAddress;
            IsInbound = inbound;
            EventName = "AssociationError";
            _level = level;
            Cause = cause;
        }

        public Exception Cause { get; private set; }

        private readonly LogLevel _level;
        public override LogLevel LogLevel()
        {
            return _level;
        }

        public override Address LocalAddress { get; protected set; }
        public override Address RemoteAddress { get; protected set; }
        public override bool IsInbound { get; protected set; }

        public override string ToString()
        {
            return string.Format("{0}: Error [{1}] [{2}]", base.ToString(), Cause.Message, Cause.StackTrace);
        }
    }

    public sealed class RemotingListenEvent : RemotingLifecycleEvent
    {
        public RemotingListenEvent(IList<Address> listenAddresses)
        {
            ListenAddresses = listenAddresses;
        }

        public IList<Address> ListenAddresses { get; private set; }

        public override LogLevel LogLevel()
        {
            return Event.LogLevel.InfoLevel;
        }

        public override string ToString()
        {
            return string.Format("Remoting now listens on addresses: [{0}]",
                ListenAddresses.Select(x => x.ToString()).Join(","));
        }
    }

    public sealed class RemotingShutdownEvent : RemotingLifecycleEvent
    {
        public override LogLevel LogLevel()
        {
            return Event.LogLevel.InfoLevel;
        }

        public override string ToString()
        {
            return "Remoting shut down";
        }
    }

    public sealed class RemotingErrorEvent : RemotingLifecycleEvent
    {
        public RemotingErrorEvent(Exception cause)
        {
            Cause = cause;
        }

        public Exception Cause { get; private set; }

        public override LogLevel LogLevel()
        {
            return Event.LogLevel.ErrorLevel;
        }

        public override string ToString()
        {
            return string.Format("Remoting error: [{0}] [{1}]", Cause.Message, Cause.StackTrace);
        }
    }

    public sealed class QuarantinedEvent : RemotingLifecycleEvent
    {
        public QuarantinedEvent(Address address, int uid)
        {
            Uid = uid;
            Address = address;
        }

        public Address Address { get; private set; }

        public int Uid { get; private set; }

        public override LogLevel LogLevel()
        {
            return Event.LogLevel.WarningLevel;
        }

        public override string ToString()
        {
            return
                string.Format(
                    "Association to [{0}] having UID [{1}] is irrecoverably failed. UID is now quarantined and all " +
                    "messages to this UID will be delivered to dead letters. Remote actorsystem must be restarted to recover " +
                    "from this situation.", Address, Uid);
        }
    }

    /// <summary>
    /// INTERNAL API.
    ///
    /// Used for publishing remote lifecycle events to the <see cref="EventStream"/> of the provided <see cref="ActorSystem"/>.
    /// </summary>
    internal class EventPublisher
    {
        public ActorSystem System { get; private set; }

        public ILoggingAdapter Log { get; private set; }

        public readonly LogLevel LogLevel;

        public EventPublisher(ActorSystem system, ILoggingAdapter log, LogLevel logLevel)
        {
            System = system;
            Log = log;
            LogLevel = logLevel;
        }

        public void NotifyListeners(RemotingLifecycleEvent message)
        {
            System.EventStream.Publish(message);
            if (message.LogLevel() >= LogLevel) Log.Log(message.LogLevel(), message.ToString());
        }
    }
}


text:
module Sequel
  # == Cheatsheet:
  #   class Item < Sequel::Model(:items)
  #     set_schema do
  #       primary_key :id
  #       text :name, :unique => true, :null => false
  #       boolean :active, :default => true
  #       integer :grade
  #
  #       index :grade
  #     end
  #   end
  #
  #   Item.create_table unless Item.table_exists?
  #   Item.create_table!
  #
  #   i = Item.create(:name => 'Shoes', :grade => 0)
  #
  #   Item[1].grade #=> 0
  #
  #   i.set(:grade => 2)
  #   i.grade # => 2
  #
  #   Item[:name => 'Shoes'].grade # => 2
  #
  #   i.grade = 4
  #   Item[1].grade # => 2
  #   i.save
  #   Item[1].grade # => 4
  #
  # == Subsets
  # Subsets are filter mapped to class methods:
  #
  #   class Ticket < Sequel::Model(:tickets)
  #
  #     subset(:pending) { finished_at == nil }
  #     subset(:closed)  { finished_at != nil }
  #
  #     # ...
  #
  #   end
  #
  # Now you can do:
  #
  #   Ticket.pending.each { |ticket| puts ticket.caption }
  #
  # == Advanced filtering methods (or dataset magic)
  # One of the cool features of Sequel::Model is that it acts as a proxy to
  # the underlying dataset, so you can invoke methods on the class instead of
  # on the dataset:
  #
  #   Customer.filter(:name =~ 'Roberts')
  #
  # In the prevailing style of implementing models (which is actually very
  # similar to ActiveRecord models) table-wide operations are defined as
  # class methods:
  #
  #   class Node < Sequel::Model(:nodes)
  #     def self.subtree(path)
  #       filter(:path => Regexp.new("^#{path}(/.+)?$"))
  #     end
  #     def self.alarms
  #       filter {:kind => ALARM}
  #     end
  #     def self.recalculate
  #       exclude(:expression => nil).each {|n| n.calculate}
  #     end
  #   end
  #
  # The recalculate class method calls the exclude method. The exclude
  # call is proxied to the underlying dataset, which lets you call each
  # method separately:
  #
  #   Node.subtree('/test')
  #   Node.alarms
  #   Node.recalculate
  #
  # ... but this will raise a NoMethodError:
  #
  #   Node.subtree('/test').alarms.recalculate
  #
  # It turns out the solution is very simple - instead of defining class
  # methods, define dataset methods:
  #
  #   class Node < Sequel::Model(:nodes)
  #     def dataset.subtree(path)
  #       filter(:path => Regexp.new("^#{path}(/.+)?$"))
  #     end
  #     def dataset.alarms
  #       filter {:kind => ALARM}
  #     end
  #     def dataset.recalculate
  #       exclude(:expression => nil).each {|n| n.calculate}
  #     end
  #   end
  #
  # Now you can mix all of these methods any way you like:
  #
  #   Node.filter {:stamp < Time.now < 3600}.alarms
  #   Node.filter(:project_id => 123).subtree('/abc')
  #   Node.subtree('/test').recalculate
  #   # ...
  #
  # == Schemas
  # You can define your schema in the Model class itself:
  #
  #   class Comment < Sequel::Model(:comments)
  #     set_schema do
  #       primary_key :id
  #       foreign_key :post_id, :table => :posts, :on_delete => :cascade
  #
  #       varchar :name
  #       varchar :email
  #       text :comment
  #     end
  #
  #     # ...
  #
  #   end
  #
  # == Hooks
  # You can setup hooks here:
  # * before_save calls either
  # * before_create with
  # * after_create or if record already exists
  # * before_update with
  # * after_update and finally
  # * after_save
  # ... and here:
  # * before_destroy with
  # * after_destroy
  #
  # ...with:
  #
  #   class Example < Sequel::Model(:hooks)
  #     before_create { self.created_at = Time.now }
  #
  #     # ...
  #   end
  #
  # == Serialization of complexe attributes
  # Sometimes there are datatypes you can't natively map to your db. In this
  # case you can just do serialize:
  #
  #   class Serialized < Sequel::Model(:serialized)
  #     serialize :column1, :format => :yaml    # YAML is the default serialization method
  #     serialize :column2, :format => :marshal # serializes through marshalling
  #
  #     # ...
  #
  #   end
  class Model
    alias_method :model, :class
  end
end

require File.join(File.dirname(__FILE__), 'model/base')
require File.join(File.dirname(__FILE__), 'model/hooks')
require File.join(File.dirname(__FILE__), 'model/record')
require File.join(File.dirname(__FILE__), 'model/schema')
require File.join(File.dirname(__FILE__), 'model/relations')
require File.join(File.dirname(__FILE__), 'model/caching')

module Sequel
  class Model

    # Defines a method that returns a filtered dataset.
    def self.subset(name, *args, &block)
      dataset.meta_def(name) {filter(*args, &block)}
    end

    # Comprehensive description goes here!
    def primary_key_hash(value)
      # stock implementation
      {:id => value}
    end

    # Finds a single record according to the supplied filter, e.g.:
    #
    #   Ticket.find :author => 'Sharon' # => record
    #   Ticket.find {:price}17 # => Dataset
    #
    def self.find(*args, &block)
      dataset.filter(*args, &block).limit(1).first
      # dataset[cond.is_a?(Hash) ? cond : primary_key_hash(cond)]
    end

    def self.[](*args)
      args = args.first if (args.size == 1)
      dataset[(Hash === args) ? args : primary_key_hash(args)]
    end

    # Like find but invokes create with given conditions when record does not
    # exists.
    def self.find_or_create(cond)
      find(cond) || create(cond)
    end

    ############################################################################

    # Like delete_all, but invokes before_destroy and after_destroy hooks if used.
    def self.destroy_all
      has_hooks?(:before_destroy) || has_hooks?(:after_destroy) ? \
        dataset.destroy : dataset.delete
    end
    # Deletes all records.
    def self.delete_all
      dataset.delete
    end

    FIND_BY_REGEXP = /^find_by_(.*)/.freeze
    FILTER_BY_REGEXP = /^filter_by_(.*)/.freeze
    ALL_BY_REGEXP = /^all_by_(.*)/.freeze

    def self.method_missing(m, *args, &block) #:nodoc:
      Thread.exclusive do
        method_name = m.to_s
        if method_name =~ FIND_BY_REGEXP
          c = $1.to_sym
          meta_def(method_name) {|arg| find(c => arg)}
        elsif method_name =~ FILTER_BY_REGEXP
          c = $1.to_sym
          meta_def(method_name) {|arg| filter(c => arg)}
        elsif method_name =~ ALL_BY_REGEXP
          c = $1.to_sym
          meta_def(method_name) {|arg| filter(c => arg).all}
        elsif dataset.respond_to?(m)
          instance_eval("def #{m}(*args, &block); dataset.#{m}(*args, &block); end")
        end
      end
      respond_to?(m) ? send(m, *args, &block) : super(m, *args)
    end

    # Comprehensive description goes here!
    def self.join(*args)
      table_name = dataset.opts[:from].first
      dataset.join(*args).select(table_name.to_sym.ALL)
    end

    # Returns value of attribute.
    def [](field)
      @values[field]
    end
    # Sets value of attribute.
    def []=(field, value)
      @values[field] = value
    end

    # Enumerates through all attributes.
    #
    # === Example:
    #   Ticket.find(7).each { |k, v| puts "#{k} => #{v}" }
    def each(&block)
      @values.each(&block)
    end
    # Returns attribute names.
    def keys
      @values.keys
    end

    # Returns value for <tt>:id</tt> attribute.
    def id
      @values[:id]
    end

    # Compares models by values.
    def ==(obj)
      (obj.class == model) && (obj.values == @values)
    end
    # Compares object by pkey.
    def ===(obj)
      (obj.class == model) && (obj.pkey == pkey)
    end

  end
end


text:
using Newtonsoft.Json;

namespace Box.V2.Models
{
    /// <summary>
    /// Box representation of a notification email object.
    /// </summary>
    public class BoxNotificationEmail : BoxNotificationEmailField
    {
        public const string isConfirmed = "is_confirmed";

        [JsonProperty(PropertyName = isConfirmed)]
        public virtual bool? IsConfirmed { get; private set; }
    }
}


text:
layout: post
title: Working on dotnet core on Mac OS X part 3
date: 2019-12-28T18:29:08+01:00
tags: core dotnet
---

After writing the [previous posts](http://assertfail.gewalli.se/2018/09/05/Working-on-dotnet-core-on-Mac-OS-X-part-2.html) about getting some of the infrastructure working for non Windows systems, I've seen better ways of getting it to work. Instead of using a netfx.props file, you can use a [Directory.Build.props](https://docs.microsoft.com/en-us/visualstudio/msbuild/customize-your-build?view=vs-2019) with platform specific configuration as seen [in for instance FSharp.Compiler.Service](https://github.com/fsharp/FSharp.Compiler.Service/blob/08daf6d5a0abb62c01a475ea442c2996b0e79335/FSharpBuild.Directory.Build.props#L39-L54):

```xml
<Project>

  <!-- mono -->
  <PropertyGroup Condition="'$(OS)' == 'Unix'">
    <MonoRoot Condition="'$(MonoRoot)' == '' and $([MSBuild]::IsOsPlatform('Linux'))">/usr</MonoRoot>
    <MonoRoot Condition="'$(MonoRoot)' == '' and $([MSBuild]::IsOsPlatform('OSX'))">/Library/Frameworks/Mono.framework/Versions/Current</MonoRoot>
    <MonoLibFolder>$(MonoRoot)/lib/mono</MonoLibFolder>
    <MonoPackaging Condition="$(TargetFramework.StartsWith('net4'))">true</MonoPackaging>
    <FrameworkPathOverride Condition="'$(TargetFramework)' == 'net45'">$(MonoLibFolder)/4.5-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(TargetFramework)' == 'net451'">$(MonoLibFolder)/4.5.1-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(TargetFramework)' == 'net452'">$(MonoLibFolder)/4.5.2-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(TargetFramework)' == 'net46'">$(MonoLibFolder)/4.6-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(TargetFramework)' == 'net461'">$(MonoLibFolder)/4.6.1-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(TargetFramework)' == 'net462'">$(MonoLibFolder)/4.6.2-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(TargetFramework)' == 'net47'">$(MonoLibFolder)/4.7-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(TargetFramework)' == 'net471'">$(MonoLibFolder)/4.7.1-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(TargetFramework)' == 'net472'">$(MonoLibFolder)/4.7.2-api</FrameworkPathOverride>
  </PropertyGroup>

</Project>
```

Another stumble has been that the nuget version on Ubuntu [is a bit old](https://stackoverflow.com/a/40209368). There are some ways around this, one easy way is to include a NuGet.config with both v2 and v3 feeds:

```xml
<configuration>
 <packageSources>
    <!--To inherit the global NuGet package sources remove the <clear/> line below -->
    <clear />
    <add key="nuget" value="https://api.nuget.org/v3/index.json" />
    <add key="nuget v2" value="https://www.nuget.org/api/v2" />
 </packageSources>
</configuration>
```


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE620_Unverified_Password_Change__w32_08.c
Label Definition File: CWE620_Unverified_Password_Change__w32.label.xml
Template File: point-flaw-08.tmpl.c
*/
/*
 * @description
 * CWE: 620 Unverified Password Change
 * Sinks: w32NetUserSetInfo
 *    GoodSink: Require old password to set new password using NetUserChangePassword()
 *    BadSink : Set new password without verifying the old one using NetUserSetInfo()
 * Flow Variant: 08 Control flow: if(staticReturnsTrue()) and if(staticReturnsFalse())
 *
 * */

#include "std_testcase.h"

#include <windows.h>
#include <lm.h>
#pragma comment(lib, "netapi32.lib")
#define USERNAME L"cwe620testuser"

/* The two function below always return the same value, so a tool
   should be able to identify that calls to the functions will always
   return a fixed value. */
static int staticReturnsTrue()
{
    return 1;
}

static int staticReturnsFalse()
{
    return 0;
}

#ifndef OMITBAD

void CWE620_Unverified_Password_Change__w32_08_bad()
{
    if(staticReturnsTrue())
    {
        {
            wchar_t newPassword[256];
            USER_INFO_1003 myUserInfo;
            NET_API_STATUS status;
            myUserInfo.usri1003_password = newPassword;
            printWLine(L"Enter new password: ");
            if (fwscanf(stdin, L"%255s", myUserInfo.usri1003_password) != 1)
            {
                myUserInfo.usri1003_password[0] = L'\0';
            }
            /* FLAW: Set password without verifying the old one */
            status = NetUserSetInfo(NULL, USERNAME, 1003, (LPBYTE)&myUserInfo, NULL);
            if(status == NERR_Success)
            {
                printWLine(L"Success!");
            }
            else
            {
                wprintf(L"NetUserSetInfo failed.  Status = %u = 0x%x\n", status, status);
            }
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* good1() uses if(staticReturnsFalse()) instead of if(staticReturnsTrue()) */
static void good1()
{
    if(staticReturnsFalse())
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        {
            wchar_t oldPassword[256];
            wchar_t newPassword[256];
            NET_API_STATUS status;
            printWLine(L"Enter old password: ");
            if (fwscanf(stdin, L"%255s", oldPassword) != 1)
            {
                oldPassword[0] = L'\0';
            }
            printWLine(L"Enter new password: ");
            if (fwscanf(stdin, L"%255s", newPassword) != 1)
            {
                newPassword[0] = L'\0';
            }
            /* FIX: Verify the old password when setting the new password */
            status = NetUserChangePassword(NULL, USERNAME, oldPassword, newPassword);
            if(status == NERR_Success)
            {
                printWLine(L"Success!");
            }
            else
            {
                wprintf(L"NetUserChangePassword failed.  Status = %u = 0x%x\n", status, status);
            }
        }
    }
}

/* good2() reverses the bodies in the if statement */
static void good2()
{
    if(staticReturnsTrue())
    {
        {
            wchar_t oldPassword[256];
            wchar_t newPassword[256];
            NET_API_STATUS status;
            printWLine(L"Enter old password: ");
            if (fwscanf(stdin, L"%255s", oldPassword) != 1)
            {
                oldPassword[0] = L'\0';
            }
            printWLine(L"Enter new password: ");
            if (fwscanf(stdin, L"%255s", newPassword) != 1)
            {
                newPassword[0] = L'\0';
            }
            /* FIX: Verify the old password when setting the new password */
            status = NetUserChangePassword(NULL, USERNAME, oldPassword, newPassword);
            if(status == NERR_Success)
            {
                printWLine(L"Success!");
            }
            else
            {
                wprintf(L"NetUserChangePassword failed.  Status = %u = 0x%x\n", status, status);
            }
        }
    }
}

void CWE620_Unverified_Password_Change__w32_08_good()
{
    good1();
    good2();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE620_Unverified_Password_Change__w32_08_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE620_Unverified_Password_Change__w32_08_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
<?php

namespace Furniture\ProductBundle\Controller;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Criteria;

use Furniture\ProductBundle\Entity\PdpIntellectualRoot;
use Furniture\ProductBundle\Entity\PdpIntellectualCompositeExpression;
use Furniture\ProductBundle\Entity\PdpIntellectualElement;

use Furniture\ProductBundle\Entity\Product;
use Furniture\ProductBundle\Form\Type\PdpIntellectual\PdpIntellectualRootType;
use Furniture\ProductBundle\Generator\PdpIntelligentSchemesGenerator;
use Sylius\Bundle\ResourceBundle\Controller\ResourceController;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ProductPdpIntellectualController extends ResourceController
{
    /**
     * {@inheritDoc}
     */
    public function indexAction(Request $request)
    {
        $this->isGrantedOr403('index');

        $criteria = $this->config->getCriteria();
        $sorting = $this->config->getSorting();

        $repository = $this->getRepository();
        $product = $this->loadProduct($request);

        $criteria['product'] = $product;

        $resources = $this->resourceResolver->getResource(
            $repository,
            'findBy',
            [$criteria, $sorting, $this->config->getLimit()]
        );

        $view = $this
            ->view()
            ->setTemplate($this->config->getTemplate('index.html'))
            ->setTemplateVar($this->config->getPluralResourceName())
            ->setData($resources)
            ->setTemplateData([
                'product' => $product,
                'items'   => $resources,
            ]);

        return $this->handleView($view);
    }

    private function cacheElementsPdpPath($generator){
       $paths = $generator->getPathToElements();
       $cachedStructure = [];
       foreach($paths as $path){
           $pathStructure = [];
           foreach($path as $item){
               echo $item->getId().':'.get_class($item).'<br/>';
               if( $item instanceof PdpIntellectualRoot){
                   $pathStructure[] = [
                       'type' => 'root',
                       'id'   => $item->getId()
                   ];
               }elseif($item instanceof  PdpIntellectualCompositeExpression){
                   $pathStructure[] = [
                       'type'  => $item->getType(),
                       'id'    => $item->getId(),
                       'input_id' => $item->getPdpInput() ? $item->getPdpInput()->getId() : null,
                       'text'  => $item->getAppendText()
                   ];
               }elseif($item instanceof  PdpIntellectualElement){
                   $pathStructure[] = [
                       'type'     => 'element',
                       'id'       => $item->getId(),
                       'input_id' => $item->getInput()->getId(),
                       'text'     => $item->getInput()->getHumanName()
                   ];
                   $cachedStructure[$item->getInput()->getId()] = $pathStructure;
               }
           }
       }

       $pdpInput = $generator->getPdpRoot();
       $pdpInput->setTreePathForInputsJson($cachedStructure);

    }

    /**
     * {@inheritDoc}
     */
    public function createAction(Request $request)
    {
        $this->isGrantedOr403('create');
        $product = $this->loadProduct($request);

        $pdpIntellectualRoot = new PdpIntellectualRoot();
        $pdpIntellectualRoot->setProduct($product);

        $form = $this->createForm(new PdpIntellectualRootType(), $pdpIntellectualRoot);

        if ($request->getMethod() === Request::METHOD_POST) {
            $form->submit($request);

            $treeData = $form->get('tree')->getData();
            $treeData = json_decode($treeData, true);
            $this->get('product.pdp_intellectual.creator')->createFromArray($pdpIntellectualRoot, $treeData);
            $em = $this->get('doctrine.orm.default_entity_manager');

            $validator = $this->get('validator');

            $generator = $this->get('furniture.generator.pdp_product_scheme');
            $generator->setPdpRoot($pdpIntellectualRoot);
            $generator->generate();
            $schemes = $generator->getProductSchemes();

            if ($schemes) {
                $product->setProductSchemes($schemes);
                $violations = $validator->validate($product, null, ['SchemesCreate']);
                if ($violations->count()) {
                    foreach ($violations as $violation) {
                        $form->addError(new FormError($violation->getMessage()));
                    }
                }
            } else {
                $form->addError(new FormError('No schemes generated.'));
            }

            if ($form->isValid() && !$product->hasVariants() && !$product->hasProductVariantsPatterns()) {
                $em->persist($pdpIntellectualRoot);
                $tree = $this->get('product.pdp_intellectual.converter')->convertToArray($pdpIntellectualRoot);
                $pdpIntellectualRoot->setTreeJson($tree);
                $em->flush();

                $this->cacheElementsPdpPath($generator);
                $em->flush();
                $toUrl = $this->generateUrl('furniture_backend_product_pdp_intellectual_index', [
                    'productId' => $product->getId(),
                ]);

                return new RedirectResponse($toUrl);
            } else {
                $form->addError(new FormError('Product already has variants or patterns.'));
            }
        }

        $view = $this
            ->view()
            ->setTemplate($this->config->getTemplate('create.html'))
            ->setTemplateData([
                'product' => $product,
                'form'    => $form->createView(),
            ]);

        return $this->handleView($view);
    }

    /**
     * {@inheritDoc}
     */
    public function updateAction(Request $request)
    {
        $this->isGrantedOr403('update');

        /** @var PdpIntellectualRoot $pdpIntellectualRoot */
        $pdpIntellectualRoot = $this->findOr404($request);
        $product = $this->loadProduct($request);
        $tree = $this->get('product.pdp_intellectual.converter')->convertToArray($pdpIntellectualRoot);

        $newPdpIntellectual = new PdpIntellectualRoot();
        $newPdpIntellectual->setProduct($product);
        $newPdpIntellectual->setName($pdpIntellectualRoot->getName());
        $newPdpIntellectual->setGraphJson($pdpIntellectualRoot->getGraphJson());

        $form = $this->createForm(new PdpIntellectualRootType(), $newPdpIntellectual, ['graph_tree' => $tree]);

        $form->handleRequest($request);

        if ($request->getMethod() === Request::METHOD_POST) {
            $em = $this->get('doctrine.orm.default_entity_manager');

            $treeData = $form->get('tree')->getData();
            $treeData = json_decode($treeData, true);

            $this->get('product.pdp_intellectual.creator')->createFromArray($newPdpIntellectual, $treeData);

            $validator = $this->get('validator');
            $generator = $this->get('furniture.generator.pdp_product_scheme');
            $generator->setPdpRoot($newPdpIntellectual);
            $generator->generate();
            $schemes = $generator->getProductSchemes();

            if ($schemes) {
                $productSchemes = $product->getProductSchemes();

                foreach ($productSchemes as $pScheme) {
                    $pSchemeParts = [];
                    foreach ($pScheme->getProductParts() as $part) {
                        $pSchemeParts[] = $part->getId();
                    }

                    sort($pSchemeParts);
                    $pHash = implode($pSchemeParts);

                    $has = false;
                    foreach ($schemes as $scheme) {
                        $schemeParts = [];
                        foreach ($scheme->getProductParts() as $part) {
                            $schemeParts[] = $part->getId();
                        }

                        sort($schemeParts);
                        $hash = implode($schemeParts);

                        if ($hash === $pHash) {
                            $has = true;
                            $schemes->removeElement($scheme);
                            break;
                        }
                    }

                    if (!$has) {
                        $productSchemes->removeElement($pScheme);
                        $em->remove($pScheme);
                    }
                }

                $schemes = new ArrayCollection(array_merge($productSchemes->toArray(), $schemes->toArray()));
                $product->setProductSchemes($schemes);

                $violations = $validator->validate($product, null, ['SchemesCreate']);

                if ($violations->count()) {
                    foreach ($violations as $violation) {
                        $form->addError(new FormError($violation->getMessage()));
                    }
                }
            } else {
                $form->addError(new FormError('No schemes generated.'));
            }

            if ($form->isValid() && !$product->hasVariants() && !$product->hasProductVariantsPatterns()) {
                // We use transactional because we must remove and add new element.
                $em->transactional(function () use ($pdpIntellectualRoot, $newPdpIntellectual, $em, $generator) {
                    $em->remove($pdpIntellectualRoot);
                    $em->persist($newPdpIntellectual);

                    $tree = $this->get('product.pdp_intellectual.converter')->convertToArray($newPdpIntellectual);
                    $newPdpIntellectual->setTreeJson($tree);
                    $this->cacheElementsPdpPath($generator);
                });

                $toUrl = $this->generateUrl('furniture_backend_product_pdp_intellectual_index', [
                    'productId' => $product->getId(),
                ]);

                return new RedirectResponse($toUrl);
            } else {
                $form->addError(new FormError('Product already has variants or patterns.'));
            }
        }

        $view = $this
            ->view()
            ->setTemplate($this->config->getTemplate('update.html'))
            ->setTemplateData([
                'product'          => $product,
                'pdp_intellectual' => $pdpIntellectualRoot,
                'form'    => $form->createView(),
            ]);

        return $this->handleView($view);
    }

    /**
     * {@inheritDoc}
     */
    public function deleteAction(Request $request)
    {
        $product = $this->loadProduct($request);

        $this->isGrantedOr403('delete');

        $pdpIntelRoor = $this->findOr404($request);
        /** @var Furniture\ProductBundle\Entity\PdpIntellectualRoot $pdpIntelRoor */
        $schemas = $pdpIntelRoor->getProduct()->getProductSchemes();
        $em = $this->get('doctrine.orm.default_entity_manager');

        foreach ($schemas as $schema){
            $em->remove($schema);
        }

        $this->domainManager->delete($this->findOr404($request));

        $toUrl = $this->generateUrl('furniture_backend_product_pdp_intellectual_index', [
            'productId' => $product->getId(),
        ]);

        return new RedirectResponse($toUrl);
    }

    /**
     * Load product
     *
     * @param Request $request
     *
     * @return Product
     */
    private function loadProduct(Request $request)
    {
        $productId = $request->get('productId');

        if (!$productId) {
            throw new NotFoundHttpException('Missing "productId" parameter.');
        }

        $product = $this->get('doctrine.orm.default_entity_manager')
            ->find(Product::class, $productId);

        if (!$product) {
            throw new NotFoundHttpException(sprintf(
                'Not found product with identifier "%s".',
                $productId
            ));
        }

        return $product;
    }
}


text:
namespace CDBurnerHelpers
{
    IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
    {
        CoInitialize (0);

        IDiscMaster* dm;
        IDiscRecorder* result = nullptr;

        if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
                                         CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
                                         IID_IDiscMaster,
                                         (void**) &dm)))
        {
            if (SUCCEEDED (dm->Open()))
            {
                IEnumDiscRecorders* drEnum = nullptr;

                if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
                {
                    IDiscRecorder* dr = nullptr;
                    DWORD dummy;
                    int index = 0;

                    while (drEnum->Next (1, &dr, &dummy) == S_OK)
                    {
                        if (indexToOpen == index)
                        {
                            result = dr;
                            break;
                        }
                        else if (list != nullptr)
                        {
                            BSTR path;

                            if (SUCCEEDED (dr->GetPath (&path)))
                                list->add ((const WCHAR*) path);
                        }

                        ++index;
                        dr->Release();
                    }

                    drEnum->Release();
                }

                if (master == 0)
                    dm->Close();
            }

            if (master != nullptr)
                *master = dm;
            else
                dm->Release();
        }

        return result;
    }
}

//==============================================================================
class AudioCDBurner::Pimpl  : public ComBaseClassHelper <IDiscMasterProgressEvents>,
                              public Timer
{
public:
    Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
      : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
        listener (0), progress (0), shouldCancel (false)
    {
        HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
        jassert (SUCCEEDED (hr));
        hr = discMaster->SetActiveDiscRecorder (discRecorder);
        //jassert (SUCCEEDED (hr));

        lastState = getDiskState();
        startTimer (2000);
    }

    ~Pimpl()  {}

    void releaseObjects()
    {
        discRecorder->Close();
        if (redbook != nullptr)
            redbook->Release();
        discRecorder->Release();
        discMaster->Release();
        Release();
    }

    JUCE_COMRESULT QueryCancel (boolean* pbCancel)
    {
        if (listener != nullptr && ! shouldCancel)
            shouldCancel = listener->audioCDBurnProgress (progress);

        *pbCancel = shouldCancel;

        return S_OK;
    }

    JUCE_COMRESULT NotifyBlockProgress (long nCompleted, long nTotal)
    {
        progress = nCompleted / (float) nTotal;
        shouldCancel = listener != nullptr && listener->audioCDBurnProgress (progress);

        return E_NOTIMPL;
    }

    JUCE_COMRESULT NotifyPnPActivity (void)                              { return E_NOTIMPL; }
    JUCE_COMRESULT NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/)    { return E_NOTIMPL; }
    JUCE_COMRESULT NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/)   { return E_NOTIMPL; }
    JUCE_COMRESULT NotifyPreparingBurn (long /*nEstimatedSeconds*/)      { return E_NOTIMPL; }
    JUCE_COMRESULT NotifyClosingDisc (long /*nEstimatedSeconds*/)        { return E_NOTIMPL; }
    JUCE_COMRESULT NotifyBurnComplete (HRESULT /*status*/)               { return E_NOTIMPL; }
    JUCE_COMRESULT NotifyEraseComplete (HRESULT /*status*/)              { return E_NOTIMPL; }

    class ScopedDiscOpener
    {
    public:
        ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
        ~ScopedDiscOpener()                     { pimpl.discRecorder->Close(); }

    private:
        Pimpl& pimpl;

        JUCE_DECLARE_NON_COPYABLE (ScopedDiscOpener)
    };

    DiskState getDiskState()
    {
        const ScopedDiscOpener opener (*this);

        long type, flags;
        HRESULT hr = discRecorder->QueryMediaType (&type, &flags);

        if (FAILED (hr))
            return unknown;

        if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
            return writableDiskPresent;

        if (type == 0)
            return noDisc;

        return readOnlyDiskPresent;
    }

    int getIntProperty (const LPOLESTR name, const int defaultReturn) const
    {
        ComSmartPtr<IPropertyStorage> prop;
        if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
            return defaultReturn;

        PROPSPEC iPropSpec;
        iPropSpec.ulKind = PRSPEC_LPWSTR;
        iPropSpec.lpwstr = name;

        PROPVARIANT iPropVariant;
        return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
                   ? defaultReturn : (int) iPropVariant.lVal;
    }

    bool setIntProperty (const LPOLESTR name, const int value) const
    {
        ComSmartPtr<IPropertyStorage> prop;
        if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
            return false;

        PROPSPEC iPropSpec;
        iPropSpec.ulKind = PRSPEC_LPWSTR;
        iPropSpec.lpwstr = name;

        PROPVARIANT iPropVariant;
        if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
            return false;

        iPropVariant.lVal = (long) value;
        return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
                && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
    }

    void timerCallback() override
    {
        const DiskState state = getDiskState();

        if (state != lastState)
        {
            lastState = state;
            owner.sendChangeMessage();
        }
    }

    AudioCDBurner& owner;
    DiskState lastState;
    IDiscMaster* discMaster;
    IDiscRecorder* discRecorder;
    IRedbookDiscMaster* redbook;
    AudioCDBurner::BurnProgressListener* listener;
    float progress;
    bool shouldCancel;
};

//==============================================================================
AudioCDBurner::AudioCDBurner (const int deviceIndex)
{
    IDiscMaster* discMaster = nullptr;
    IDiscRecorder* discRecorder = CDBurnerHelpers::enumCDBurners (0, deviceIndex, &discMaster);

    if (discRecorder != nullptr)
        pimpl = new Pimpl (*this, discMaster, discRecorder);
}

AudioCDBurner::~AudioCDBurner()
{
    if (pimpl != nullptr)
        pimpl.release()->releaseObjects();
}

StringArray AudioCDBurner::findAvailableDevices()
{
    StringArray devs;
    CDBurnerHelpers::enumCDBurners (&devs, -1, 0);
    return devs;
}

AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
{
    ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));

    if (b->pimpl == 0)
        b = nullptr;

    return b.release();
}

AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
{
    return pimpl->getDiskState();
}

bool AudioCDBurner::isDiskPresent() const
{
    return getDiskState() == writableDiskPresent;
}

bool AudioCDBurner::openTray()
{
    const Pimpl::ScopedDiscOpener opener (*pimpl);
    return SUCCEEDED (pimpl->discRecorder->Eject());
}

AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
{
    const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
    DiskState oldState = getDiskState();
    DiskState newState = oldState;

    while (newState == oldState && Time::currentTimeMillis() < timeout)
    {
        newState = getDiskState();
        Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
    }

    return newState;
}

Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
{
    Array<int> results;
    const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
    const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };

    for (int i = 0; i < numElementsInArray (speeds); ++i)
        if (speeds[i] <= maxSpeed)
            results.add (speeds[i]);

    results.addIfNotAlreadyThere (maxSpeed);
    return results;
}

bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
{
    if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
        return false;

    pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
    return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
}

int AudioCDBurner::getNumAvailableAudioBlocks() const
{
    long blocksFree = 0;
    pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
    return blocksFree;
}

String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
                            bool performFakeBurnForTesting, int writeSpeed)
{
    pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);

    pimpl->listener = listener;
    pimpl->progress = 0;
    pimpl->shouldCancel = false;

    UINT_PTR cookie;
    HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);

    hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
                                        ejectDiscAfterwards);

    String error;
    if (hr != S_OK)
    {
        const char* e = "Couldn't open or write to the CD device";

        if (hr == IMAPI_E_USERABORT)
            e = "User cancelled the write operation";
        else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
            e = "No Disk present";

        error = e;
    }

    pimpl->discMaster->ProgressUnadvise (cookie);
    pimpl->listener = 0;

    return error;
}

bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
{
    if (audioSource == 0)
        return false;

    ScopedPointer<AudioSource> source (audioSource);

    long bytesPerBlock;
    HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);

    const int samplesPerBlock = bytesPerBlock / 4;
    bool ok = true;

    hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));

    HeapBlock<byte> buffer (bytesPerBlock);
    AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
    int samplesDone = 0;

    source->prepareToPlay (samplesPerBlock, 44100.0);

    while (ok)
    {
        {
            AudioSourceChannelInfo info (&sourceBuffer, 0, samplesPerBlock);
            sourceBuffer.clear();

            source->getNextAudioBlock (info);
        }

        buffer.clear (bytesPerBlock);

        typedef AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian,
                                    AudioData::Interleaved, AudioData::NonConst> CDSampleFormat;

        typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian,
                                    AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat;

        CDSampleFormat left (buffer, 2);
        left.convertSamples (SourceSampleFormat (sourceBuffer.getReadPointer (0)), samplesPerBlock);
        CDSampleFormat right (buffer + 2, 2);
        right.convertSamples (SourceSampleFormat (sourceBuffer.getReadPointer (1)), samplesPerBlock);

        hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);

        if (FAILED (hr))
            ok = false;

        samplesDone += samplesPerBlock;

        if (samplesDone >= numSamples)
            break;
    }

    hr = pimpl->redbook->CloseAudioTrack();
    return ok && hr == S_OK;
}


text:
package mounts // import "github.com/docker/docker/volume/mounts"

import (
	"os"
	"testing"

	"github.com/docker/docker/api/types/mount"
)

type mockFiProvider struct{}

func (mockFiProvider) fileInfo(path string) (exists, isDir bool, err error) {
	dirs := map[string]struct{}{
		`c:\`:                    {},
		`c:\windows\`:            {},
		`c:\windows`:             {},
		`c:\program files`:       {},
		`c:\Windows`:             {},
		`c:\Program Files (x86)`: {},
		`\\?\c:\windows\`:        {},
	}
	files := map[string]struct{}{
		`c:\windows\system32\ntdll.dll`: {},
	}
	if _, ok := dirs[path]; ok {
		return true, true, nil
	}
	if _, ok := files[path]; ok {
		return true, false, nil
	}
	return false, false, nil
}

// always returns the configured error
// this is used to test error handling
type mockFiProviderWithError struct{ err error }

func (m mockFiProviderWithError) fileInfo(path string) (bool, bool, error) {
	return false, false, m.err
}

func TestParseMountSpec(t *testing.T) {
	testDir, err := os.MkdirTemp("", "test-mount-config")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(testDir)
	parser := NewParser()
	cases := []struct {
		input    mount.Mount
		expected MountPoint
	}{
		{mount.Mount{Type: mount.TypeBind, Source: testDir, Target: testDestinationPath, ReadOnly: true}, MountPoint{Type: mount.TypeBind, Source: testDir, Destination: testDestinationPath, Propagation: parser.DefaultPropagationMode()}},
		{mount.Mount{Type: mount.TypeBind, Source: testDir, Target: testDestinationPath}, MountPoint{Type: mount.TypeBind, Source: testDir, Destination: testDestinationPath, RW: true, Propagation: parser.DefaultPropagationMode()}},
		{mount.Mount{Type: mount.TypeBind, Source: testDir + string(os.PathSeparator), Target: testDestinationPath, ReadOnly: true}, MountPoint{Type: mount.TypeBind, Source: testDir, Destination: testDestinationPath, Propagation: parser.DefaultPropagationMode()}},
		{mount.Mount{Type: mount.TypeBind, Source: testDir, Target: testDestinationPath + string(os.PathSeparator), ReadOnly: true}, MountPoint{Type: mount.TypeBind, Source: testDir, Destination: testDestinationPath, Propagation: parser.DefaultPropagationMode()}},
		{mount.Mount{Type: mount.TypeVolume, Target: testDestinationPath}, MountPoint{Type: mount.TypeVolume, Destination: testDestinationPath, RW: true, CopyData: parser.DefaultCopyMode()}},
		{mount.Mount{Type: mount.TypeVolume, Target: testDestinationPath + string(os.PathSeparator)}, MountPoint{Type: mount.TypeVolume, Destination: testDestinationPath, RW: true, CopyData: parser.DefaultCopyMode()}},
	}

	for i, c := range cases {
		t.Logf("case %d", i)
		mp, err := parser.ParseMountSpec(c.input)
		if err != nil {
			t.Error(err)
		}

		if c.expected.Type != mp.Type {
			t.Errorf("Expected mount types to match. Expected: '%s', Actual: '%s'", c.expected.Type, mp.Type)
		}
		if c.expected.Destination != mp.Destination {
			t.Errorf("Expected mount destination to match. Expected: '%s', Actual: '%s'", c.expected.Destination, mp.Destination)
		}
		if c.expected.Source != mp.Source {
			t.Errorf("Expected mount source to match. Expected: '%s', Actual: '%s'", c.expected.Source, mp.Source)
		}
		if c.expected.RW != mp.RW {
			t.Errorf("Expected mount writable to match. Expected: '%v', Actual: '%v'", c.expected.RW, mp.RW)
		}
		if c.expected.Propagation != mp.Propagation {
			t.Errorf("Expected mount propagation to match. Expected: '%v', Actual: '%s'", c.expected.Propagation, mp.Propagation)
		}
		if c.expected.Driver != mp.Driver {
			t.Errorf("Expected mount driver to match. Expected: '%v', Actual: '%s'", c.expected.Driver, mp.Driver)
		}
		if c.expected.CopyData != mp.CopyData {
			t.Errorf("Expected mount copy data to match. Expected: '%v', Actual: '%v'", c.expected.CopyData, mp.CopyData)
		}
	}
}


text:
package eu.lunisolar.magma.func.function.conversion;

import javax.annotation.Nonnull; // NOSONAR
import javax.annotation.Nullable; // NOSONAR
import javax.annotation.concurrent.NotThreadSafe; // NOSONAR
import java.util.Comparator; // NOSONAR
import java.util.Objects; // NOSONAR
import eu.lunisolar.magma.basics.*; //NOSONAR
import eu.lunisolar.magma.basics.builder.*; // NOSONAR
import eu.lunisolar.magma.basics.exceptions.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.aType.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR
import eu.lunisolar.magma.func.IA;
import eu.lunisolar.magma.func.SA;
import eu.lunisolar.magma.func.*; // NOSONAR
import eu.lunisolar.magma.func.tuple.*; // NOSONAR

import java.util.concurrent.*; // NOSONAR
import java.util.function.*; // NOSONAR
import java.util.*; // NOSONAR
import java.lang.reflect.*; // NOSONAR

import eu.lunisolar.magma.func.action.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.bi.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.obj.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.tri.*; // NOSONAR
import eu.lunisolar.magma.func.function.*; // NOSONAR
import eu.lunisolar.magma.func.function.conversion.*; // NOSONAR
import eu.lunisolar.magma.func.function.from.*; // NOSONAR
import eu.lunisolar.magma.func.function.to.*; // NOSONAR
import eu.lunisolar.magma.func.operator.binary.*; // NOSONAR
import eu.lunisolar.magma.func.operator.ternary.*; // NOSONAR
import eu.lunisolar.magma.func.operator.unary.*; // NOSONAR
import eu.lunisolar.magma.func.predicate.*; // NOSONAR
import eu.lunisolar.magma.func.supplier.*; // NOSONAR

/**
 * Non-throwing functional interface (lambda) LCharToLongFunction for Java 8.
 *
 * Type: function
 *
 * Domain (lvl: 1): char a
 *
 * Co-domain: long
 *
 */
@FunctionalInterface
@SuppressWarnings("UnusedDeclaration")
public interface LCharToLongFunction extends MetaFunction, MetaInterface.NonThrowing, Codomain<aLong>, Domain1<aChar> { // NOSONAR

	String DESCRIPTION = "LCharToLongFunction: long applyAsLong(char a)";

	// long applyAsLong(char a) ;
	default long applyAsLong(char a) {
		// return nestingApplyAsLong(a);
		try {
			return this.applyAsLongX(a);
		} catch (Throwable e) { // NOSONAR
			throw Handling.nestCheckedAndThrow(e);
		}
	}

	/**
	 * Implement this, but call applyAsLong(char a)
	 */
	long applyAsLongX(char a) throws Throwable;

	default long tupleApplyAsLong(LCharSingle args) {
		return applyAsLong(args.value());
	}

	/** Function call that handles exceptions according to the instructions. */
	default long handlingApplyAsLong(char a, HandlingInstructions<Throwable, RuntimeException> handling) {
		try {
			return this.applyAsLongX(a);
		} catch (Throwable e) { // NOSONAR
			throw Handler.handleOrNest(e, handling);
		}
	}

	default LCharToLongFunction handling(HandlingInstructions<Throwable, RuntimeException> handling) {
		return a -> handlingApplyAsLong(a, handling);
	}

	default long applyAsLong(char a, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage) {
		try {
			return this.applyAsLongX(a);
		} catch (Throwable e) { // NOSONAR
			throw Handling.wrap(e, factory, newMessage);
		}
	}

	default long applyAsLong(char a, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1) {
		try {
			return this.applyAsLongX(a);
		} catch (Throwable e) { // NOSONAR
			throw Handling.wrap(e, factory, newMessage, param1);
		}
	}

	default long applyAsLong(char a, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2) {
		try {
			return this.applyAsLongX(a);
		} catch (Throwable e) { // NOSONAR
			throw Handling.wrap(e, factory, newMessage, param1, param2);
		}
	}

	default long applyAsLong(char a, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) {
		try {
			return this.applyAsLongX(a);
		} catch (Throwable e) { // NOSONAR
			throw Handling.wrap(e, factory, newMessage, param1, param2, param3);
		}
	}

	default LCharToLongFunction trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage) {
		return a -> applyAsLong(a, factory, newMessage);
	}

	default LCharToLongFunction trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1) {
		return a -> applyAsLong(a, factory, newMessage, param1);
	}

	default LCharToLongFunction trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2) {
		return a -> applyAsLong(a, factory, newMessage, param1, param1);
	}

	default LCharToLongFunction trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) {
		return a -> applyAsLong(a, factory, newMessage, param1, param2, param3);
	}

	default long applyAsLong(char a, @Nonnull ExWF<RuntimeException> factory) {
		try {
			return this.applyAsLongX(a);
		} catch (Throwable e) { // NOSONAR
			throw Handling.wrap(e, factory);
		}
	}

	default LCharToLongFunction trying(@Nonnull ExWF<RuntimeException> factory) {
		return a -> applyAsLong(a, factory);
	}

	default long applyAsLongThen(char a, @Nonnull LToLongFunction<Throwable> handler) {
		try {
			return this.applyAsLongX(a);
		} catch (Throwable e) { // NOSONAR
			Handling.handleErrors(e);
			return handler.applyAsLong(e);
		}
	}

	default LCharToLongFunction tryingThen(@Nonnull LToLongFunction<Throwable> handler) {
		return a -> applyAsLongThen(a, handler);
	}

	/** Function call that handles exceptions by always nesting checked exceptions and propagating the others as is. */
	default long nestingApplyAsLong(char a) {
		try {
			return this.applyAsLongX(a);
		} catch (Throwable e) { // NOSONAR
			throw Handling.nestCheckedAndThrow(e);
		}
	}

	/** Function call that handles exceptions by always propagating them as is, even when they are undeclared checked ones. */
	default long shovingApplyAsLong(char a) {
		try {
			return this.applyAsLongX(a);
		} catch (Throwable e) { // NOSONAR
			throw Handling.shoveIt(e);
		}
	}

	static long shovingApplyAsLong(char a, LCharToLongFunction func) {
		Null.nonNullArg(func, "func");
		return func.shovingApplyAsLong(a);
	}

	static long handlingApplyAsLong(char a, LCharToLongFunction func, HandlingInstructions<Throwable, RuntimeException> handling) { // <-
		Null.nonNullArg(func, "func");
		return func.handlingApplyAsLong(a, handling);
	}

	static long tryApplyAsLong(char a, LCharToLongFunction func) {
		Null.nonNullArg(func, "func");
		return func.nestingApplyAsLong(a);
	}

	static long tryApplyAsLong(char a, LCharToLongFunction func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage) {
		Null.nonNullArg(func, "func");
		return func.applyAsLong(a, factory, newMessage);
	}

	static long tryApplyAsLong(char a, LCharToLongFunction func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1) {
		Null.nonNullArg(func, "func");
		return func.applyAsLong(a, factory, newMessage, param1);
	}

	static long tryApplyAsLong(char a, LCharToLongFunction func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2) {
		Null.nonNullArg(func, "func");
		return func.applyAsLong(a, factory, newMessage, param1, param2);
	}

	static long tryApplyAsLong(char a, LCharToLongFunction func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) {
		Null.nonNullArg(func, "func");
		return func.applyAsLong(a, factory, newMessage, param1, param2, param3);
	}

	static long tryApplyAsLong(char a, LCharToLongFunction func, @Nonnull ExWF<RuntimeException> factory) {
		Null.nonNullArg(func, "func");
		return func.applyAsLong(a, factory);
	}

	static long tryApplyAsLongThen(char a, LCharToLongFunction func, @Nonnull LToLongFunction<Throwable> handler) {
		Null.nonNullArg(func, "func");
		return func.applyAsLongThen(a, handler);
	}

	default long failSafeApplyAsLong(char a, @Nonnull LCharToLongFunction failSafe) {
		try {
			return applyAsLong(a);
		} catch (Throwable e) { // NOSONAR
			Handling.handleErrors(e);
			return failSafe.applyAsLong(a);
		}
	}

	static long failSafeApplyAsLong(char a, LCharToLongFunction func, @Nonnull LCharToLongFunction failSafe) {
		Null.nonNullArg(failSafe, "failSafe");
		if (func == null) {
			return failSafe.applyAsLong(a);
		} else {
			return func.failSafeApplyAsLong(a, failSafe);
		}
	}

	static LCharToLongFunction failSafe(LCharToLongFunction func, @Nonnull LCharToLongFunction failSafe) {
		Null.nonNullArg(failSafe, "failSafe");
		return a -> failSafeApplyAsLong(a, func, failSafe);
	}

	/** Just to mirror the method: Ensures the result is not null */
	default long nonNullApplyAsLong(char a) {
		return applyAsLong(a);
	}

	/** Returns description of the functional interface. */
	@Nonnull
	default String functionalInterfaceDescription() {
		return LCharToLongFunction.DESCRIPTION;
	}

	/** From-To. Intended to be used with non-capturing lambda. */
	public static void fromTo(int min_i, int max_i, char a, @Nonnull LCharToLongFunction func) {
		Null.nonNullArg(func, "func");
		if (min_i <= max_i) {
			for (int i = min_i; i <= max_i; i++) {
				func.applyAsLong(a);
			}
		} else {
			for (int i = min_i; i >= max_i; i--) {
				func.applyAsLong(a);
			}
		}
	}

	/** From-To. Intended to be used with non-capturing lambda. */
	public static void fromTill(int min_i, int max_i, char a, @Nonnull LCharToLongFunction func) {
		Null.nonNullArg(func, "func");
		if (min_i <= max_i) {
			for (int i = min_i; i < max_i; i++) {
				func.applyAsLong(a);
			}
		} else {
			for (int i = min_i; i > max_i; i--) {
				func.applyAsLong(a);
			}
		}
	}

	/** From-To. Intended to be used with non-capturing lambda. */
	public static void times(int max_i, char a, @Nonnull LCharToLongFunction func) {
		if (max_i < 0)
			return;
		fromTill(0, max_i, a, func);
	}

	/** Change function to consumer that ignores output. */
	default LCharConsumer toConsumer() {
		return this::applyAsLong;
	}

	/** Calls domain consumer before main function. */
	default LCharToLongFunction beforeDo(@Nonnull LCharConsumer before) {
		Null.nonNullArg(before, "before");
		return (char a) -> {
			before.accept(a);
			return applyAsLong(a);
		};
	}

	/** Calls codomain consumer after main function. */
	default LCharToLongFunction afterDo(@Nonnull LLongConsumer after) {
		Null.nonNullArg(after, "after");
		return (char a) -> {
			final long retval = applyAsLong(a);
			after.accept(retval);
			return retval;
		};
	}

	/** Creates function that always returns the same value. */
	static LCharToLongFunction constant(long r) {
		return a -> r;
	}

	/** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */
	@Nonnull
	static LCharToLongFunction charToLongFunc(final @Nonnull LCharToLongFunction lambda) {
		Null.nonNullArg(lambda, "lambda");
		return lambda;
	}

	// <editor-fold desc="recursive">

	final class S implements LCharToLongFunction {
		private LCharToLongFunction target = null;
		@Override
		public long applyAsLongX(char a) throws Throwable {
			return target.applyAsLongX(a);
		}
	}

	@Nonnull
	static LCharToLongFunction recursive(final @Nonnull LFunction<LCharToLongFunction, LCharToLongFunction> selfLambda) {
		final S single = new S();
		LCharToLongFunction func = selfLambda.apply(single);
		single.target = func;
		return func;
	}

	// </editor-fold>

	// <editor-fold desc="memento">

	public static M mementoOf(char a, LCharToLongFunction function) {
		var initialValue = function.applyAsLong(a);
		return initializedMementoOf(initialValue, function);
	}

	public static M initializedMementoOf(long initialValue, LCharToLongFunction function) {
		return memento(initialValue, initialValue, function, (m, x1, x2) -> x2);
	}

	public static M deltaOf(char a, LCharToLongFunction function, LLongBinaryOperator deltaFunction) {
		var initialValue = function.applyAsLong(a);
		return initializedDeltaOf(initialValue, function, deltaFunction);
	}

	public static M deltaOf(char a, LCharToLongFunction function) {
		var initialValue = function.applyAsLong(a);
		return initializedDeltaOf(initialValue, function, (x1, x2) -> (x2 - x1));
	}

	public static M initializedDeltaOf(long initialValue, LCharToLongFunction function, LLongBinaryOperator deltaFunction) {
		return memento(initialValue, deltaFunction.applyAsLong(initialValue, initialValue), function, (m, x1, x2) -> deltaFunction.applyAsLong(x1, x2));
	}

	public static M memento(long initialBaseValue, long initialValue, LCharToLongFunction baseFunction, LLongTernaryOperator mementoFunction) {
		return new M(initialBaseValue, initialValue, baseFunction, mementoFunction);
	}

	/**
	 * Implementation that allows to create derivative functions (do not confuse it with math concepts). Very short name is intended to be used with parent (LCharToLongFunction.M)
	 */
	@NotThreadSafe
	final class M implements LCharToLongFunction {

		private final LCharToLongFunction baseFunction;
		private long lastBaseValue;
		private long lastValue;
		private final LLongTernaryOperator mementoFunction;

		private M(long lastBaseValue, long lastValue, LCharToLongFunction baseFunction, LLongTernaryOperator mementoFunction) {
			this.baseFunction = baseFunction;
			this.lastBaseValue = lastBaseValue;
			this.lastValue = lastValue;
			this.mementoFunction = mementoFunction;
		}

		@Override
		public long applyAsLongX(char a) throws Throwable {
			long x1 = lastBaseValue;
			long x2 = lastBaseValue = baseFunction.applyAsLongX(a);

			return lastValue = mementoFunction.applyAsLong(lastValue, x1, x2);
		}

		public long lastValue() {
			return lastValue;
		};

		public long lastBaseValue() {
			return lastBaseValue;
		};
	}

	// </editor-fold>

	@Nonnull
	static LCharToLongFunction charToLongFuncThrowing(final @Nonnull ExF<Throwable> exF) {
		Null.nonNullArg(exF, "exF");
		return a -> {
			throw exF.produce();
		};
	}

	@Nonnull
	static LCharToLongFunction charToLongFuncThrowing(final String message, final @Nonnull ExMF<Throwable> exF) {
		Null.nonNullArg(exF, "exF");
		return a -> {
			throw exF.produce(message);
		};
	}

	static long call(char a, final @Nonnull LCharToLongFunction lambda) {
		Null.nonNullArg(lambda, "lambda");
		return lambda.applyAsLong(a);
	}

	// <editor-fold desc="wrap">

	// </editor-fold>

	// <editor-fold desc="compose (functional)">

	/** Allows to manipulate the domain of the function. */
	@Nonnull
	default LCharToLongFunction compose(@Nonnull final LCharUnaryOperator before) {
		Null.nonNullArg(before, "before");
		return v -> this.applyAsLong(before.applyAsChar(v));
	}

	/** Allows to manipulate the domain of the function. */
	@Nonnull
	default <V> LToLongFunction<V> unboxingCompose(@Nonnull final LToCharFunction<? super V> before) {
		Null.nonNullArg(before, "before");
		return v -> this.applyAsLong(before.applyAsChar(v));
	}

	// </editor-fold>

	// <editor-fold desc="then (functional)">

	/** Combines two functions together in a order. */
	@Nonnull
	default <V> LCharFunction<V> then(@Nonnull LLongFunction<? extends V> after) {
		Null.nonNullArg(after, "after");
		return a -> after.apply(this.applyAsLong(a));
	}

	/** Combines two functions together in a order. */
	@Nonnull
	default LCharToByteFunction thenToByte(@Nonnull LLongToByteFunction after) {
		Null.nonNullArg(after, "after");
		return a -> after.applyAsByte(this.applyAsLong(a));
	}

	/** Combines two functions together in a order. */
	@Nonnull
	default LCharToSrtFunction thenToSrt(@Nonnull LLongToSrtFunction after) {
		Null.nonNullArg(after, "after");
		return a -> after.applyAsSrt(this.applyAsLong(a));
	}

	/** Combines two functions together in a order. */
	@Nonnull
	default LCharToIntFunction thenToInt(@Nonnull LLongToIntFunction after) {
		Null.nonNullArg(after, "after");
		return a -> after.applyAsInt(this.applyAsLong(a));
	}

	/** Combines two functions together in a order. */
	@Nonnull
	default LCharToLongFunction thenToLong(@Nonnull LLongUnaryOperator after) {
		Null.nonNullArg(after, "after");
		return a -> after.applyAsLong(this.applyAsLong(a));
	}

	/** Combines two functions together in a order. */
	@Nonnull
	default LCharToFltFunction thenToFlt(@Nonnull LLongToFltFunction after) {
		Null.nonNullArg(after, "after");
		return a -> after.applyAsFlt(this.applyAsLong(a));
	}

	/** Combines two functions together in a order. */
	@Nonnull
	default LCharToDblFunction thenToDbl(@Nonnull LLongToDblFunction after) {
		Null.nonNullArg(after, "after");
		return a -> after.applyAsDbl(this.applyAsLong(a));
	}

	/** Combines two functions together in a order. */
	@Nonnull
	default LCharUnaryOperator thenToChar(@Nonnull LLongToCharFunction after) {
		Null.nonNullArg(after, "after");
		return a -> after.applyAsChar(this.applyAsLong(a));
	}

	/** Combines two functions together in a order. */
	@Nonnull
	default LCharPredicate thenToBool(@Nonnull LLongPredicate after) {
		Null.nonNullArg(after, "after");
		return a -> after.test(this.applyAsLong(a));
	}

	// </editor-fold>

	// <editor-fold desc="variant conversions">

	// </editor-fold>

	/** Does nothing (LCharToLongFunction) Function */
	public static long doNothing(char a) {
		return Function4U.defaultLong;
	}

	/**
	* For each element (or tuple) from arguments, calls the function and passes the result to consumer.
	* Thread safety, fail-fast, fail-safety of this method is not expected.
	*/
	default <C0> void forEach(IndexedRead<C0, aChar> ia, C0 source, LLongConsumer consumer) {
		int size = ia.size(source);
		LOiToCharFunction<Object> oiFunc0 = (LOiToCharFunction) ia.getter();
		int i = 0;
		for (; i < size; i++) {
			char a = oiFunc0.applyAsChar(source, i);
			consumer.accept(this.applyAsLong(a));
		}
	}

	/**
	* For each element (or tuple) from arguments, calls the function and passes the result to consumer.
	* Thread safety, fail-fast, fail-safety of this method depends highly on the arguments.
	*/
	default <C0, I0> void iterate(SequentialRead<C0, I0, aChar> sa, C0 source, LLongConsumer consumer) {
		Object iterator0 = ((LFunction) sa.adapter()).apply(source);
		LPredicate<Object> testFunc0 = (LPredicate) sa.tester();
		LToCharFunction<Object> nextFunc0 = (LToCharFunction) sa.supplier();
		while (testFunc0.test(iterator0)) {
			char a = nextFunc0.applyAsChar(iterator0);
			consumer.accept(this.applyAsLong(a));
		}
	}

}


text:
/**
 * @ngdoc directive
 * @name refigureApp.directive:uiSrefDisabled
 * @restrict E
 * @description
 * Stops propagation on click to prevent ui-sref links to work
 * Accepts selector as value of attribute to search for
 * @example
 *

 *     test@test.org
 *

 */
(function (angular) {
    'use strict';

    angular
        .module('refigureShared')
        .directive('uiSrefDisabled', Directive);

    function Directive () {
        return {
            restrict: 'A',
            link: function ($scope, $element, $attr) {
                $element.on('click', function (e) {
                    if (!$attr['uiSrefDisabled'] || e.target.matches($attr['uiSrefDisabled'])) {
                        e.stopPropagation();
                    }
                });
            }
        };
    }

    // .matches polyfill for IE (even IE11)
    if (!Element.prototype.matches) {
        Element.prototype.matches =
            Element.prototype.matchesSelector ||
            Element.prototype.mozMatchesSelector ||
            Element.prototype.msMatchesSelector ||
            Element.prototype.oMatchesSelector ||
            Element.prototype.webkitMatchesSelector ||
            function(s) {
                var matches = (this.document || this.ownerDocument).querySelectorAll(s),
                    i = matches.length;
                while (--i >= 0 && matches.item(i) !== this) {}
                return i > -1;
            };
    }

})(window.angular);