text:
namespace Castle.DynamicProxy.Generators.Emitters
{
	using System;
	using System.Collections.Generic;
	using System.Diagnostics;
	using System.Linq;
	using System.Reflection;

	public static class TypeUtil
	{
		public static FieldInfo[] GetAllFields(this Type type)
		{
			if (type == null)
			{
				throw new ArgumentNullException("type");
			}

			if (type.IsClass == false)
			{
				throw new ArgumentException(string.Format("Type {0} is not a class type. This method supports only classes", type));
			}

			var fields = new List<FieldInfo>();
			var currentType = type;
			while (currentType != typeof(object))
			{
				Debug.Assert(currentType != null);
				var currentFields = currentType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
				fields.AddRange(currentFields);
				currentType = currentType.BaseType;
			}

			return fields.ToArray();
		}

		/// <summary>
		///   Returns list of all unique interfaces implemented given types, including their base interfaces.
		/// </summary>
		/// <param name = "types"></param>
		/// <returns></returns>
		public static ICollection<Type> GetAllInterfaces(params Type[] types)
		{
			if (types == null)
			{
				return Type.EmptyTypes;
			}

			var dummy = new object();
			// we should move this to HashSet once we no longer support .NET 2.0
			IDictionary<Type, object> interfaces = new Dictionary<Type, object>();
			foreach (var type in types)
			{
				if (type == null)
				{
					continue;
				}

				if (type.IsInterface)
				{
					interfaces[type] = dummy;
				}

				foreach (var @interface in type.GetInterfaces())
				{
					interfaces[@interface] = dummy;
				}
			}

			return Sort(interfaces.Keys);
		}

		public static ICollection<Type> GetAllInterfaces(this Type type)
		{
			return GetAllInterfaces(new[] { type });
		}

		public static Type GetClosedParameterType(this AbstractTypeEmitter type, Type parameter)
		{
			if (parameter.IsGenericTypeDefinition)
			{
				return parameter.GetGenericTypeDefinition().MakeGenericType(type.GetGenericArgumentsFor(parameter));
			}

			if (parameter.IsGenericType)
			{
				var arguments = parameter.GetGenericArguments();
				if (CloseGenericParametersIfAny(type, arguments))
				{
					return parameter.GetGenericTypeDefinition().MakeGenericType(arguments);
				}
			}

			if (parameter.IsGenericParameter)
			{
				return type.GetGenericArgument(parameter.Name);
			}

			if (parameter.IsArray)
			{
				var elementType = GetClosedParameterType(type, parameter.GetElementType());
				return elementType.MakeArrayType();
			}

			if (parameter.IsByRef)
			{
				var elementType = GetClosedParameterType(type, parameter.GetElementType());
				return elementType.MakeByRefType();
			}

			return parameter;
		}

		public static bool IsFinalizer(this MethodInfo methodInfo)
		{
			return string.Equals("Finalize", methodInfo.Name) && methodInfo.GetBaseDefinition().DeclaringType == typeof(object);
		}

		public static bool IsGetType(this MethodInfo methodInfo)
		{
			return methodInfo.DeclaringType == typeof(object) && string.Equals("GetType", methodInfo.Name, StringComparison.OrdinalIgnoreCase);
		}

		public static bool IsMemberwiseClone(this MethodInfo methodInfo)
		{
			return methodInfo.DeclaringType == typeof(object) && string.Equals("MemberwiseClone", methodInfo.Name, StringComparison.OrdinalIgnoreCase);
		}

		public static void SetStaticField(this Type type, string fieldName, BindingFlags additionalFlags, object value)
		{
			var flags = additionalFlags | BindingFlags.Static | BindingFlags.SetField;

			try
			{
				type.InvokeMember(fieldName, flags, null, null, new[] { value });
			}
			catch (MissingFieldException e)
			{
				throw new ProxyGenerationException(
					string.Format(
						"Could not find field named '{0}' on type {1}. This is likely a bug in DynamicProxy. Please report it.",
						fieldName,
						type), e);
			}
			catch (TargetException e)
			{
				throw new ProxyGenerationException(
					string.Format(
						"There was an error trying to set field named '{0}' on type {1}. This is likely a bug in DynamicProxy. Please report it.",
						fieldName,
						type), e);
			}
			catch (TargetInvocationException e) // yes, this is not documented in MSDN. Yay for documentation
			{
				if ((e.InnerException is TypeInitializationException) == false)
				{
					throw;
				}
				throw new ProxyGenerationException(
					string.Format(
						"There was an error in static constructor on type {0}. This is likely a bug in DynamicProxy. Please report it.",
						type), e);
			}
		}

		public static MemberInfo[] Sort(MemberInfo[] members)
		{
			var sortedMembers = new MemberInfo[members.Length];
			Array.Copy(members, sortedMembers, members.Length);
			Array.Sort(sortedMembers, (l, r) => string.Compare(l.Name, r.Name, StringComparison.OrdinalIgnoreCase));
			return sortedMembers;
		}

		private static bool CloseGenericParametersIfAny(AbstractTypeEmitter emitter, Type[] arguments)
		{
			var hasAnyGenericParameters = false;
			for (var i = 0; i < arguments.Length; i++)
			{
				var newType = GetClosedParameterType(emitter, arguments[i]);
				if (!ReferenceEquals(newType, arguments[i]))
				{
					arguments[i] = newType;
					hasAnyGenericParameters = true;
				}
			}
			return hasAnyGenericParameters;
		}

		private static Type[] Sort(IEnumerable<Type> types)
		{
			var array = types.ToArray();
			//NOTE: is there a better, stable way to sort Types. We will need to revise this once we allow open generics
			Array.Sort(array, (l, r) => string.Compare(l.AssemblyQualifiedName, r.AssemblyQualifiedName, StringComparison.OrdinalIgnoreCase));
			return array;
		}
	}
}


text:
package com.plugplayer.plugplayer.upnp;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.cybergarage.upnp.Action;
import org.cybergarage.upnp.AllowedValueRange;
import org.cybergarage.upnp.Device;
import org.cybergarage.upnp.Service;
import org.cybergarage.upnp.StateVariable;
import org.cybergarage.upnp.UPnP;
import org.cybergarage.xml.Node;
import org.cybergarage.xml.Parser;
import org.cybergarage.xml.ParserException;

import android.app.Activity;
import android.content.SharedPreferences;
import android.util.Log;

import com.plugplayer.plugplayer.activities.MainActivity;
import com.plugplayer.plugplayer.activities.SettingsEditor;
import com.plugplayer.plugplayer.utils.StateList;
import com.plugplayer.plugplayer.utils.StateMap;

public class UPNPRenderer extends Renderer
{
	protected boolean WDTVLive = false;
	private transient boolean nostop = false;
	private transient boolean noplay = false;
	protected transient boolean noplayevent = false;
	private transient boolean supportsSeek = false;

	private static final int lastcount = 5;

	public static final String STATENAME = "UPNPRenderer";

	private transient int lasttime[] = new int[lastcount];

	protected transient Service avtransportService;
	protected transient Service renderingControlService;
	protected int maxVolume = 100;

	// private boolean resubscribeAfterPlay = false;

	public UPNPRenderer()
	{
		super();
		playMode = PlayMode.Normal;

		final SharedPreferences preferences = MainActivity.me.getSharedPreferences( SettingsEditor.ADVANCED_SETTINGS, Activity.MODE_PRIVATE );
		nostop = preferences.getBoolean( SettingsEditor.IGNORE_STOP, false );
		noplayevent = preferences.getBoolean( SettingsEditor.IGNORE_PLAY, false );
	}

	public static UPNPRenderer createDevice( Device dev )
	{
		Service avtransportService = dev.getService( "urn:schemas-upnp-org:service:AVTransport:1" );
		Service renderingControlService = dev.getService( "urn:schemas-upnp-org:service:RenderingControl:1" );

		if ( avtransportService != null && renderingControlService != null )
		{
			UPNPRenderer renderer = new UPNPRenderer();
			renderer.updateServices( dev );

			try
			{
				if ( !dev.getIconList().isEmpty() )
					renderer.setIconURL( dev.getAbsoluteURL( dev.getIcon( 0 ).getURL() ) );

				if ( "WD TV HD Live".equals( dev.getModelName() ) )
					renderer.WDTVLive = true;
				else
					renderer.WDTVLive = false;
			}
			catch ( Exception e )
			{
				e.printStackTrace();
			}

			try
			{
				StateVariable volume = renderingControlService.getStateVariable( "Volume" );
				if ( volume != null && volume.hasAllowedValueRange() )
				{
					AllowedValueRange range = volume.getAllowedValueRange();
					renderer.maxVolume = Integer.parseInt( range.getMaximum() );
				}

				return renderer;
			}
			catch ( Exception e )
			{
				e.printStackTrace();
			}
		}

		return null;
	}

	@Override
	public void updateServices( Device dev )
	{
		avtransportService = dev.getService( "urn:schemas-upnp-org:service:AVTransport:1" );
		renderingControlService = dev.getService( "urn:schemas-upnp-org:service:RenderingControl:1" );

		setUDN( dev.getUDN() );
		setLocation( dev.getLocation() );
		setOriginalName( dev.getFriendlyName() );

		// Some devices don't have a valid renderingcontrol.xml
		// Use PlugPlayers instead!
		try
		{
			renderingControlService.getServiceStateTable();
		}
		catch ( Exception e )
		{
			try
			{
				File webDir = new File( MainActivity.me.getFilesDir() + "/web" );
				renderingControlService.loadSCPD( new File( webDir + "/RenderingControl.xml" ) );
			}
			catch ( ParserException e1 )
			{
				e1.printStackTrace();
			}
		}

		try
		{
			avtransportService.getServiceStateTable();
		}
		catch ( Exception e )
		{
			try
			{
				File webDir = new File( MainActivity.me.getFilesDir() + "/web" );
				avtransportService.loadSCPD( new File( webDir + "/AVTransport.xml" ) );
			}
			catch ( ParserException e1 )
			{
				e1.printStackTrace();
			}
		}

		// resubscribeAfterPlay = "Royal Philips Electronics".equals( dev.getManufacture() );
		noplay = "Royal Philips Electronics".equals( dev.getManufacture() );

		PlugPlayerControlPoint.getInstance().controlPoint.addDevice( dev.getRootNode() );
	}

	@Override
	public void toState( StateMap state )
	{
		super.toState( state );

		state.setName( STATENAME );

		state.setValue( "WDTVLive", WDTVLive );
		state.setValue( "maxVolume", maxVolume );

		StateList playlistState = new StateList();
		for ( Item item : playlist )
		{
			StateMap itemState = new StateMap();
			item.toState( itemState );
			playlistState.add( itemState );
		}
		state.setList( "playlist", playlistState );
	}

	@Override
	public void fromState( StateMap state )
	{
		super.fromState( state );

		WDTVLive = state.getValue( "WDTVLive", false );
		maxVolume = state.getValue( "maxVolume", 100 );

		StateList playlistState = state.getList( "playlist" );
		for ( StateMap itemState : playlistState )
		{
			Item item = Item.createFromState( itemState );
			playlist.add( item );
		}
	}

	public static UPNPRenderer createFromState( StateMap state )
	{
		UPNPRenderer rval = new UPNPRenderer();
		rval.fromState( state );
		return rval;
	}

	@Override
	public void setActive( boolean active, boolean hardStop )
	{
		if ( active == getActive() )
			return;

		if ( active )
		{
			supportsSeek = false;

			// Set the current volume
			volume = getCurrentVolume();
			emitVolumeChanged( volume );

			// Figure out what is currently playing and notify listeners
			updateCurrentTrack();

			controlPoint.subscribe( this, avtransportService );

			if ( renderingControlService != null )
				controlPoint.subscribe( this, renderingControlService );
		}
		else
		{
			System.out.println( "will usubscribe, hardStop = " + hardStop );
			if ( !hardStop )
				controlPoint.unsubscribe( this, avtransportService );

			if ( renderingControlService != null && !hardStop )
				controlPoint.unsubscribe( this, renderingControlService );
			System.out.println( "did usubscribe, hardStop = " + hardStop );
		}

		super.setActive( active, hardStop );
	}

	@Override
	protected void updateCurrentTimeStamp()
	{
		if ( noplay && !WDTVLive )
		{
			PlayState currentPlayState = getTransportState();
			if ( currentPlayState != getPlayState() )
			{
				playState = currentPlayState;
				emitPlayStateChanged( playState );
			}
		}

		int time = getCurrentTime();

		if ( WDTVLive && time > getCurrentSeconds() && getPlayState() != PlayState.Playing )
		{
			PlayState currentPlayState = getTransportState();
			if ( currentPlayState != getPlayState() )
			{
				playState = currentPlayState;
				emitPlayStateChanged( playState );
			}
		}

		setCurrentSeconds( time );
	}

	private PlayState getTransportState()
	{
		PlayState newPlayState = PlayState.NoMedia;

		Action getTransportInfo = avtransportService.getAction( "GetTransportInfo" );
		getTransportInfo.setArgumentValue( "InstanceID", 0 );

		if ( getTransportInfo.postControlAction() )
		{
			String state = getTransportInfo.getArgumentValue( "CurrentTransportState" );
			if ( state != null )
			{
				if ( state.equals( "STOPPED" ) || state.equals( "NO_MEDIA_PRESENT" ) )
					newPlayState = PlayState.Stopped;
				else if ( state.equals( "PLAYING" ) )
					newPlayState = PlayState.Playing;
				else if ( state.equals( "TRANSITIONING" ) )
					newPlayState = PlayState.Transitioning;
				else if ( state.equals( "PAUSED_PLAYBACK" ) )
					newPlayState = PlayState.Paused;
			}
		}
		else
		{
			handleError( getTransportInfo );
		}

		return newPlayState;
	}

	protected int getCurrentTime()
	{
		int rval = -1;
		Action getPositionInfo = avtransportService.getAction( "GetPositionInfo" );
		getPositionInfo.setArgumentValue( "InstanceID", 0 );

		if ( getPositionInfo.postControlAction() == true )
		{
			String secstr = getPositionInfo.getArgumentValue( "RelTime" );
			if ( secstr != null )
			{
				rval = secsFromString( secstr );

				if ( nostop )
				{
					if ( getPlayState() == PlayState.Playing && (rval > 0 || rval < lasttime[lastcount - 1]) )
					{
						int i = 0;
						for ( ; i < lastcount; ++i )
							if ( rval != lasttime[i] )
								break;

						if ( i == lastcount || (rval < lasttime[lastcount - 1] && rval < lasttime[lastcount - 2]) )
						{
							for ( i = 0; i < lastcount; ++i )
								lasttime[i] = -i;

							if ( hasNext() )
							{
								// [self performSelectorOnMainThread:@selector(next) withObject:NULL waitUntilDone:true];
								next();
								play();
							}
						}
						else
						{
							for ( i = 0; i < lastcount - 1; ++i )
								lasttime[i] = lasttime[i + 1];

							lasttime[lastcount - 1] = rval;
						}
					}
				}
			}

			String totalstr = getPositionInfo.getArgumentValue( "TrackDuration" );
			if ( totalstr != null )
			{
				int total = secsFromString( totalstr );

				if ( total > 0 )
					setTotalSeconds( total );
			}
		}
		else
		{
			handleError( getPositionInfo );
		}

		return rval;
	}

	private String getCurrentTransportActions()
	{
		String rval = "";

		try
		{
			Action getCurrentTransportActions = avtransportService.getAction( "GetCurrentTransportActions" );
			getCurrentTransportActions.setArgumentValue( "InstanceID", 0 );

			if ( getCurrentTransportActions.postControlAction() )
			{
				rval = getCurrentTransportActions.getArgumentValue( "Actions" );
			}
			else
			{
				handleError( getCurrentTransportActions );
			}
		}
		catch ( Exception e )
		{

		}

		return rval;
	}

	private void updateCurrentTrack()
	{
		String currentMetadata = getCurrentMetadata();
		setPlayState( getTransportState() );

		// GetCurrentTransportActions
		String transportActions = getCurrentTransportActions();
		if ( transportActions != null && transportActions.length() > 0 )
			supportsSeek = transportActions.contains( "Seek" );

		Item item = new Item();
		item.setMetadata( currentMetadata );

		String currentURL = item.getMaxResResourceURL();
		if ( currentURL == null || currentURL.length() == 0 )
			return;

		// Try to match by resource URL
		for ( int i = 0; i < getPlaylistEntryCount(); ++i )
		{
			Item existingItem = getPlaylistEntry( i );
			if ( existingItem.getMaxResResourceURL().equals( currentURL ) )
			{
				currentTrack = i;
				emitTrackNumberChanged( currentTrack );
				return;
			}
		}

		// That failed; try to match by?

		// Isn't currently in the list, so add it.
		int last = getPlaylistEntryCount();
		playlist.add( last, item );
		emitPlaylistChanged();
		currentTrack = last;
		emitTrackNumberChanged( currentTrack );
	}

	private String getCurrentMetadata()
	{
		String rval = null;
		try
		{
			Action getPositionInfo = avtransportService.getAction( "GetPositionInfo" );
			getPositionInfo.setArgumentValue( "InstanceID", 0 );
			if ( getPositionInfo.postControlAction() == true )
			{
				rval = getPositionInfo.getArgumentValue( "TrackMetaData" );
				// String uri = getPositionInfo.getArgumentValue( "TrackURI" );
			}
			else
			{
				handleError( getPositionInfo );
			}
		}
		catch ( Exception e )
		{
			e.printStackTrace();
		}
		return rval;
	}

	protected float getCurrentVolume()
	{
		float rval = 0;

		if ( renderingControlService == null )
		{
			handleError( "No Renderering Control service" );
			return 0f;
		}

		Action getVolume = renderingControlService.getAction( "GetVolume" );

		if ( getVolume == null )
		{
			handleError( "No GetVolume action" );
			return 0f;
		}

		getVolume.setArgumentValue( "InstanceID", 0 );
		getVolume.setArgumentValue( "Channel", "Master" );

		if ( getVolume.postControlAction() == true )
		{
			try
			{
				String volString = getVolume.getArgumentValue( "CurrentVolume" );
				if ( volString != null )
					rval = Integer.parseInt( volString ) / (float)maxVolume;
			}
			catch ( Exception e )
			{
				Log.w( MainActivity.appName, "Bad Volumne", e );
			}
		}
		else
		{
			handleError( getVolume );
		}

		return rval;
	}

	@Override
	public boolean hasNext()
	{
		int count = getPlaylistEntryCount();

		if ( playMode == PlayMode.Shuffle )
			return count > 0;
		else if ( playMode == PlayMode.RepeatOne )
			return count > 0;
		else if ( playMode == PlayMode.RepeatAll )
			return count > 0;

		// playMode == PlayMode_Normal
		return currentTrack < (count - 1) && count != 0;
	}

	@Override
	public int nextTrackNumber()
	{
		int count = getPlaylistEntryCount();

		if ( playMode == PlayMode.Shuffle )
			return (int)Math.floor( Math.random() * count );
		else if ( playMode == PlayMode.RepeatOne )
			return currentTrack;
		else if ( playMode == PlayMode.RepeatAll )
			return (currentTrack + 1) % count;

		// // playMode == PlayMode_Normal
		return currentTrack + 1;
	}

	@Override
	public void next()
	{
		if ( !hasNext() )
			return;

		int index = nextTrackNumber();

		if ( index == currentTrack )
			setTrackNumber( index );

		setTrackNumber( index );
	}

	@Override
	public boolean hasPrev()
	{
		int count = getPlaylistEntryCount();
		return (currentTrack > 0 || currentSeconds > 2) && count != 0;
	}

	@Override
	public int prevTrackNumber()
	{
		if ( currentSeconds > 2 )
			return currentTrack;
		else
			return currentTrack - 1;
	}

	@Override
	public void prev()
	{
		if ( !hasPrev() )
			return;

		int index = prevTrackNumber();

		// To make sure setTrackNumber 'sticks'
		currentTrack = -1;
		setTrackNumber( index );
	}

	@Override
	public void play()
	{
		Action play = avtransportService.getAction( "Play" );
		play.setArgumentValue( "InstanceID", 0 );
		play.setArgumentValue( "Speed", 1 );

		if ( play.postControlAction() == true )
		{
			// We never set the state to playing ourselves;
			if ( noplayevent )
				setPlayState( PlayState.Playing );
		}
		else
		{
			handleError( play );
		}
	}

	@Override
	public void pause()
	{
		Action pause = avtransportService.getAction( "Pause" );
		pause.setArgumentValue( "InstanceID", 0 );

		if ( pause.postControlAction() == true )
		{
			setPlayState( PlayState.Paused );
		}
		else
		{
			handleError( pause );
		}
	}

	@Override
	public void stop()
	{
		Action stop = avtransportService.getAction( "Stop" );
		stop.setArgumentValue( "InstanceID", 0 );

		if ( stop.postControlAction() == true )
		{
			// We never set the state to stopped ourselves;
			// setPlayState( PlayState.Stopped );
		}
		else
		{
			handleError( stop );
		}
	}

	PlayState playState = PlayState.NoMedia;

	@Override
	public PlayState getPlayState()
	{
		return playState;
	}

	@Override
	public void setPlayState( PlayState newState )
	{
		playState = newState;

		emitPlayStateChanged( newState );
	}

	int currentSeconds;

	@Override
	public int getCurrentSeconds()
	{
		return currentSeconds;
	}

	private void setCurrentSeconds( int secs )
	{
		currentSeconds = secs;

		emitTimeStampChanged( currentSeconds );
	}

	private int totalSeconds;

	@Override
	public int getTotalSeconds()
	{
		return totalSeconds;
	}

	private void setTotalSeconds( int totalSeconds )
	{
		this.totalSeconds = totalSeconds;
	}

	PlayMode playMode = PlayMode.Normal;

	@Override
	public void setPlayMode( PlayMode mode )
	{
		while ( mode == PlayMode.Unsupported || mode == PlayMode.Random || mode == PlayMode.Direct1 || mode == PlayMode.Intro )
			mode = mode.next();

		playMode = mode;

		emitPlayModeChanged( mode );
	}

	@Override
	public PlayMode getPlayMode()
	{
		return playMode;
	}

	private transient int currentTrack = -1;

	@Override
	public void setTrackNumber( int newTrackNumber )
	{
		if ( currentTrack == newTrackNumber || newTrackNumber < -1 || newTrackNumber >= getPlaylistEntryCount() )
			return;

		currentTrack = newTrackNumber;

		emitTrackNumberChanged( newTrackNumber );

		Item entry = getPlaylistEntry( getTrackNumber() );

		if ( entry == null )
			return;

		// NOTE: setTransportURI will set the state to "STOPPED"; at least on
		// most renderers
		// So, we set the current state to "STOPPED" ahead of time, so that
		// listeners don't get notified
		// XXXX Do we need to only call this for some renderers?!
		PlayState origState = getPlayState();
		playState = PlayState.Stopped;
		stop();
		setCurrentSeconds( 0 );

		int secs = -1;
		try
		{
			Parser parser = UPnP.getXMLParser();
			Node metaDoc = parser.parse( entry.getMetadata() ).getNode( 0 );
			String duration = getNodeAttribute( metaDoc, "res", "duration" );
			secs = secsFromString( duration );
		}
		catch ( Exception e )
		{
		}
		setTotalSeconds( secs );

		// String metadata = entry.getMetadata();
		String metadata = entry.generateExternalMetadata( AndroidServer.getBaseURL() );

		// XXX TODO: Get node.toString() to output namespaces
		// try
		// {
		// Parser parser = UPnP.getXMLParser();
		// Node metadoc = parser.parse( metadata );
		// for ( int i = 0; i < metadoc.getNode( 0 ).getNNodes(); ++i )
		// {
		// Node child = metadoc.getNode( 0 ).getNode( i );
		// if ( child.getName().equals( "desc" ) || child.getName().equals( "upnp:toc" ) )
		// {
		// metadoc.getNode( 0 ).removeNode( child );
		// i--;
		// }
		// // else if (child.getNamespace().equals( "pv") )
		// }
		//
		// // if( [[NSUserDefaults standardUserDefaults] boolForKey:@"filter_res"]
		// // {
		//
		// // XXX This is wrong. Instead of pulling them all out, we should pick
		// // which one to send based on mimetype
		// // XXX This should be done base on .resourceURL which should figure out
		// // which is the right one.
		//
		// // items = ixmlDocument_getElementsByTagName( metadoc, "res" );
		// // for( int i = 1; i < ixmlNodeList_length( items ); ++i )
		// // {
		// // IXML_Node *child = ixmlNodeList_item( items, i );
		// // ixmlNode_removeChild( ixmlNode_getFirstChild( (IXML_Node*)metadoc ),
		// // child, NULL );
		// // }
		// // ixmlNodeList_free( items );
		// // }
		//
		// metadata = metadoc.toString();
		// }
		// catch ( ParserException e2 )
		// {
		// e2.printStackTrace();
		// }

		String url = entry.getMaxResResourceURL();

		if ( nostop )
		{
			for ( int i = 0; i < lastcount; ++i )
				lasttime[i] = -i;
		}

		if ( WDTVLive )
		{
			supportsSeek = true;
			nostop = true;
		}

		// if ( WDTVLive )
		try
		{
			Thread.sleep( (int)(0.25 * 1000) );
		}
		catch ( InterruptedException e1 )
		{
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		Action setTransportURI = avtransportService.getAction( "SetAVTransportURI" );
		setTransportURI.setArgumentValue( "InstanceID", 0 );
		setTransportURI.setArgumentValue( "CurrentURI", url );
		setTransportURI.setArgumentValue( "CurrentURIMetaData", metadata );

		if ( setTransportURI.postControlAction() == true )
		{
		}
		else
		{
			handleError( setTransportURI );
		}

		// if ( WDTVLive )
		try
		{
			Thread.sleep( (int)(0.25 * 1000) );
		}
		catch ( InterruptedException e )
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if ( origState == PlayState.Playing )
			play();
		else
			playState = origState;

		// new Timer().schedule( new TimerTask()
		// {
		// @Override
		// public void run()
		// {
		// // Try to force re-subscribe after we starting playing.
		// if ( resubscribeAfterPlay && getActive() )
		// {
		// setActive( false );
		// setActive( true );
		// }
		// }
		// }, 1500 );
	}

	@Override
	public int getTrackNumber()
	{
		return currentTrack;
	}

	protected float volume = 0.0f;

	@Override
	public float getVolume()
	{
		return volume;
	}

	@Override
	public void setVolume( float newVolume )
	{
		if ( volume == newVolume )
			return;

		if ( WDTVLive && newVolume < 0.01f )
		{
			// setMute( true );
			newVolume = 0.01f;
			return;
		}

		if ( renderingControlService == null )
		{
			handleError( "No Renderering Control service" );
			return;
		}

		Action setVolume = renderingControlService.getAction( "SetVolume" );

		if ( setVolume == null )
			return;

		setVolume.setArgumentValue( "InstanceID", 0 );
		setVolume.setArgumentValue( "Channel", "Master" );
		setVolume.setArgumentValue( "DesiredVolume", (int)(maxVolume * newVolume) );

		if ( setVolume.postControlAction() == true )
		{
			volume = newVolume;
			emitVolumeChanged( volume );
		}
		else
		{
			handleError( setVolume );
		}
	}

	@Override
	public void volumeInc()
	{
		float inc = 1.0f / maxVolume;

		float tmp = getVolume() + inc;
		setVolume( Math.min( 1.0f, tmp ) );
	}

	@Override
	public void volumeDec()
	{
		float inc = 1.0f / maxVolume;

		float tmp = getVolume() - inc;
		setVolume( Math.max( 0.0f, tmp ) );
	}

	boolean mute = false;

	@Override
	public boolean isMute()
	{
		return mute;
	}

	@Override
	public void setMute( boolean newMute )
	{
		if ( mute == newMute )
			return;

		if ( renderingControlService == null )
		{
			handleError( "No Renderering Control service" );
			return;
		}

		Action setMute = renderingControlService.getAction( "SetMute" );

		if ( setMute == null )
			return;

		setMute.setArgumentValue( "InstanceID", 0 );
		setMute.setArgumentValue( "Channel", "Master" );
		setMute.setArgumentValue( "DesiredMute", newMute ? "true" : "false" );

		if ( setMute.postControlAction() == true )
		{
			mute = newMute;

			if ( mute )
				emitVolumeChanged( 0 );
			else
				emitVolumeChanged( volume );
		}
		else
		{
			handleError( setMute );
		}
	}

	protected final List<Item> playlist = new ArrayList<Item>();

	@Override
	public void insertPlaylistEntry( Item newEntry, int index )
	{
		if ( index < 0 )
			index = 0;

		if ( index > playlist.size() )
			index = playlist.size();

		playlist.add( index, newEntry );

		if ( index <= currentTrack )
			currentTrack++;

		emitPlaylistChanged();
	}

	protected void insertPlaylistEntry( Item newEntry, int index, boolean emitChange )
	{
		if ( index < 0 )
			index = 0;

		if ( index > playlist.size() )
			index = playlist.size();

		playlist.add( index, newEntry );

		if ( index <= currentTrack )
			currentTrack++;

		if ( emitChange )
			emitPlaylistChanged();
	}

	@Override
	public void removePlaylistEntry( int index )
	{
		if ( index < 0 || index >= playlist.size() )
			return;

		playlist.remove( index );

		if ( index < currentTrack )
			currentTrack--;

		emitPlaylistChanged();
	}

	@Override
	public void movePlaylistEntry( int fromIndex, int toIndex )
	{
		Item fromItem = playlist.get( fromIndex );
		playlist.remove( fromIndex );
		playlist.add( toIndex, fromItem );

		if ( fromIndex < currentTrack && toIndex >= currentTrack )
			currentTrack--;
		else if ( fromIndex > currentTrack && toIndex <= currentTrack )
			currentTrack++;
		else if ( fromIndex == currentTrack )
			currentTrack = toIndex;

		emitPlaylistChanged();
	}

	@Override
	public void removePlaylistEntries( int index, int count )
	{
		if ( index < 0 || index + count > playlist.size() )
			return;

		for ( int i = 0; i < count; ++i )
		{
			playlist.remove( index );

			if ( index < currentTrack )
				currentTrack--;
		}

		emitPlaylistChanged();
	}

	@Override
	public Item getPlaylistEntry( int index )
	{
		if ( index < 0 || index >= playlist.size() )
			return null;

		return playlist.get( index );
	}

	@Override
	public int getPlaylistEntryCount()
	{
		return playlist.size();
	}

	@Override
	public void eventNotifyReceived( String uuid, long seq, String varName, String value )
	{
		if ( !varName.equals( "LastChange" ) )
			return;

		try
		{
			Parser parser = UPnP.getXMLParser();
			Node innerDoc = parser.parse( value ).getNode( 0 );

			if ( innerDoc == null )
				return;

			String state = getNodeAttribute( innerDoc, "TransportState", "val" );
			if ( state != null )
			{
				PlayState newPlayState = PlayState.NoMedia;

				if ( state.equals( "STOPPED" ) || state.equals( "NO_MEDIA_PRESENT" ) )
					newPlayState = PlayState.Stopped;
				else if ( state.equals( "PLAYING" ) )
					newPlayState = PlayState.Playing;
				else if ( state.equals( "TRANSITIONING" ) )
					newPlayState = PlayState.Transitioning;
				else if ( state.equals( "PAUSED_PLAYBACK" ) )
					newPlayState = PlayState.Paused;
				else
					Log.w( MainActivity.appName, "Unknown State:" + state );

				Log.d( MainActivity.appName, "Got New State: " + newPlayState + "; current state: " + getPlayState() );

				if ( newPlayState != PlayState.Transitioning && getPlayState() != newPlayState )
				{
					if ( getPlayState() == PlayState.Playing && newPlayState == PlayState.Stopped )
						next();

					if ( newPlayState != PlayState.Stopped || !nostop )
						setPlayState( newPlayState );
				}
			}

			if ( !isVolumeChanging() )
			{
				String volume = getNodeAttribute( innerDoc, "Volume", "val" );
				if ( volume != null )
				{
					float v = Integer.parseInt( volume ) / (float)maxVolume;
					if ( v != getVolume() )
					{
						this.volume = v;
						emitVolumeChanged( v );
					}
				}
			}
			String transportActions = getNodeAttribute( innerDoc, "CurrentTransportActions", "val" );
			if ( transportActions != null && transportActions.length() > 0 )
			{
				boolean newSeek = transportActions.contains( "Seek" );

				if ( !supportsSeek && newSeek )
				{
					supportsSeek = newSeek;
					emitTrackNumberChanged( getTrackNumber() );
				}
			}
		}
		catch ( Exception e )
		{
		}
	}

	@Override
	public boolean supportsSeek()
	{
		return supportsSeek;
	}

	@Override
	public boolean seekToSecond( int second )
	{
		int hour = second / 3600;
		int min = (second - hour * 3600) / 60;
		int sec = second - hour * 3600 - min * 60;

		String secString = String.format( "%02d:%02d:%02d", hour, min, sec );

		Action seek = avtransportService.getAction( "Seek" );
		seek.setArgumentValue( "InstanceID", 0 );
		seek.setArgumentValue( "Unit", "REL_TIME" );
		seek.setArgumentValue( "Target", secString );

		if ( seek.postControlAction() == true )
		{
			if ( nostop )
			{
				for ( int i = 0; i < lastcount; ++i )
					lasttime[i] = -i;
			}

			return true;
		}
		else
		{
			// supportsSeek = false;
			handleError( seek );
			return false;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
import netCDF4
import numpy as np
import sys, unittest, os, tempfile

FILE_NAME = tempfile.NamedTemporaryFile(suffix='.nc', delete=False).name
ATT1 = '\u03a0\u03a3\u03a9'
ATT2 = 'x\xb0'
ATT3 = ['\u03a0', '\u03a3', '\u03a9']
DIM_NAME = 'x\xb0'
VAR_NAME = 'Andr\xe9'

class UnicodeTestCase(unittest.TestCase):

    def setUp(self):
        self.file = FILE_NAME
        f = netCDF4.Dataset(self.file,'w')
        f.attribute1 = ATT1
        f.attribute2 = ATT2
        f.attribute3 = ATT3
        d = f.createDimension(DIM_NAME, None)
        v = f.createVariable(VAR_NAME, np.float64, (DIM_NAME,))
        f.close()

    def tearDown(self):
        # Remove the temporary files
        os.remove(self.file)

    def runTest(self):
        """testing unicode"""
        f  = netCDF4.Dataset(self.file, 'r')
        d = f.dimensions[DIM_NAME]
        v = f.variables[VAR_NAME]
        # check accessing individual attributes.
        assert f.attribute1 == ATT1
        assert f.attribute2 == ATT2
        #assert f.attribute3 == ''.join(ATT3)
        # behavior changed issue 770
        assert f.attribute3 == ATT3
        f.close()

if __name__ == '__main__':
    unittest.main()


text:
/* global require, module */
'use strict';

var fs    = require('fs');
var p     = require('../preprocessors');
var chalk = require('chalk');

var Project      = require('../models/project');
var cleanBaseURL = require('../utilities/clean-base-url');

var preprocessJs  = p.preprocessJs;
var preprocessCss = p.preprocessCss;
var isType        = p.isType;

var preprocessTemplates = p.preprocessTemplates;

var preprocessMinifyCss = p.preprocessMinifyCss;

var replace     = require('broccoli-string-replace');
var compileES6  = require('broccoli-es6-concatenator');
var pickFiles   = require('./custom-static-compiler');
var jshintTrees = require('broccoli-jshint');
var concatFiles = require('broccoli-concat');
var remove      = require('broccoli-file-remover');

var upstreamMergeTrees  = require('broccoli-merge-trees');

var unwatchedTree    = require('broccoli-unwatched-tree');
var uglifyJavaScript = require('broccoli-uglify-js');

var assign        = require('lodash-node/modern/objects/assign');
var defaults      = require('lodash-node/modern/objects/defaults');
var merge         = require('lodash-node/modern/objects/merge');
var path          = require('path');
var ES3SafeFilter = require('broccoli-es3-safe-recast');

function mergeTrees(inputTree, options) {
  var tree = upstreamMergeTrees(inputTree, options);

  tree.description = options && options.description;

  return tree;
}

module.exports = EmberApp;

function EmberApp(options) {
  options = options || {};

  this.project = options.project || Project.closestSync(process.cwd());

  this.env  = process.env.EMBER_ENV || 'development';
  this.name = options.name || this.project.name();

  this.registry = options.registry || p.setupRegistry(this);

  var isProduction = this.env === 'production';

  this.tests   = options.hasOwnProperty('tests')   ? options.tests   : !isProduction;
  this.hinting = options.hasOwnProperty('hinting') ? options.hinting : !isProduction;

  this.bowerDirectory = 'bower_components';

  if (fs.existsSync(path.join(this.project.root, '.bowerrc'))) {
    this.bowerDirectory = JSON.parse(fs.readFileSync(path.join(this.project.root, '.bowerrc'))).directory;
  }

  if (process.env.EMBER_CLI_TEST_COMMAND) {
    this.tests = true;
  }

  this.options = merge(options, {
    es3Safe: true,
    wrapInEval: !isProduction,
    minifyCSS: {
      enabled: true,
      options: { relativeTo: 'app/styles' }
    },
    minifyJS: {
      enabled: true,
      options: {
        mangle: true,
        compress: true
      }
    },
    loader: this.bowerDirectory + '/loader/loader.js',
    trees: {},
    jshintrc: {},
    getEnvJSON: this.project.require(options.environment || './config/environment'),
    vendorFiles: {}
  }, defaults);

  this.vendorFiles = merge(options.vendorFiles, {
    'loader.js': this.bowerDirectory + '/loader/loader.js',
    'jquery.js': this.bowerDirectory + '/jquery/dist/jquery.js',
    'handlebars.js': {
      development: this.bowerDirectory + '/handlebars/handlebars.js',
      production:  this.bowerDirectory + '/handlebars/handlebars.runtime.js'
    },
    'ember.js': {
      development: this.bowerDirectory + '/ember/ember.js',
      production:  this.bowerDirectory + '/ember/ember.prod.js'
    },
    'app-shims.js': [
      this.bowerDirectory + '/ember-cli-shims/app-shims.js', {
        exports: {
          ember: ['default']
        }
      }
    ],
    'ember-resolver.js': [
      this.bowerDirectory + '/ember-resolver/dist/modules/ember-resolver.js', {
        exports: {
          'ember/resolver': ['default']
        }
      }
    ],
    'ember-load-initializers.js': [
      this.bowerDirectory + '/ember-load-initializers/ember-load-initializers.js', {
        exports: {
          'ember/load-initializers': ['default']
        }
      }
    ]
  }, defaults);

  this.options.trees = merge(this.options.trees, {
    app:       'app',
    tests:     'tests',

    // these are contained within app/ no need to watch again
    styles:    unwatchedTree('app/styles'),
    templates: unwatchedTree('app/templates'),

    // do not watch vendor/ or bower's default directory by default
    vendor: this.unwatchedVendorTrees(),
  }, defaults);

  this.options.jshintrc = merge(this.options.jshintrc, {
    app: this.project.root,
    tests: path.join(this.project.root,  'tests'),
  }, defaults);

  this.importWhitelist         = {};
  this.legacyFilesToAppend     = [];
  this.vendorStaticStyles      = [];
  this.otherAssetPaths         = [];
  this._importTrees            = [];
  this.legacyTestFilesToAppend = [];
  this.vendorTestStaticStyles  = [];

  this.trees = this.options.trees;

  this.populateLegacyFiles();
  this._notifyAddonIncluded();
}

EmberApp.prototype.unwatchedVendorTrees = function() {
  var _this = this;
  var trees = ['vendor', this.bowerDirectory + ''].reduce(function(trees, treePath) {
    if (fs.existsSync(path.join(_this.project.root, treePath))) {
      trees.push(unwatchedTree(treePath));
    }

    return trees;
  }, []);

  return mergeTrees(trees);
};

EmberApp.prototype._notifyAddonIncluded = function() {
  this.initializeAddons();
  this.project.addons.forEach(function(addon) {
    if (addon.included) {
      addon.included(this);
    }
  }, this);
};

EmberApp.prototype.initializeAddons = function() {
  this.project.initializeAddons();
};

EmberApp.prototype.addonTreesFor = function(type) {
  return this.project.addons.map(function(addon) {
    if (addon.treeFor) {
      return addon.treeFor(type);
    }
  }, this).filter(Boolean);
};

EmberApp.prototype.addonPostprocessTree = function(type, tree) {
  var workingTree = tree;

  this.project.addons.forEach(function(addon) {
    if (addon.postprocessTree) {
      workingTree = addon.postprocessTree(type, workingTree);
    }
  });

  return workingTree;
};

EmberApp.prototype.populateLegacyFiles = function () {
  var name;
  for (name in this.vendorFiles) {
    var args = this.vendorFiles[name];

    if (args === null) { continue; }

    this.import.apply(this, [].concat(args));
  }
};

EmberApp.prototype.index = function() {
  var files = [
    'index.html'
  ];

  var index = pickFiles(this.trees.app, {
    srcDir: '/',
    files: files,
    destDir: '/'
  });

  return injectENVJson(this.options.getEnvJSON, this.env, index, files);
};

EmberApp.prototype.testIndex = function() {
  var index = pickFiles(this.trees.tests, {
    srcDir: '/',
    files: ['index.html'],
    destDir: '/tests'
  });

  return injectENVJson(this.options.getEnvJSON, this.env, index, [
    'tests/index.html'
  ]);
};

EmberApp.prototype.publicFolder = function() {
  return 'public';
};

EmberApp.prototype.removeStylesAndTemplates = function(tree) {
  return remove(tree, {
    paths: ['styles', 'templates']
  });
};

EmberApp.prototype._appWithoutStylesAndTemplates = function() {
  if (this._appWithoutStylesAndTemplatesTree) {
    return this._appWithoutStylesAndTemplatesTree;
  }

  return this._appWithoutStylesAndTemplatesTree = this.removeStylesAndTemplates(this.trees.app);
};

EmberApp.prototype._processedAppTree = function() {
  var addonTrees = this.addonTreesFor('app');
  var mergedApp  = mergeTrees(addonTrees.concat(this._appWithoutStylesAndTemplates()), {
    overwrite: true,
    description: 'TreeMerger (app)'
  });

  var mergedAppWithoutStylesAndTemplates = this.removeStylesAndTemplates(mergedApp);

  return pickFiles(mergedAppWithoutStylesAndTemplates, {
    srcDir: '/',
    destDir: this.name
  });
};

EmberApp.prototype._processedTemplatesTree = function() {
  var addonTrees      = this.addonTreesFor('templates');
  var mergedTemplates = mergeTrees(addonTrees.concat(this.trees.templates), {
    overwrite: true,
    description: 'TreeMerger (templates)'
  });

  var standardTemplates = pickFiles(mergedTemplates, {
    srcDir: '/',
    destDir: this.name + '/templates'
  });

  var podTemplates = pickFiles(this.trees.app, {
    srcDir: '/',
    files: ['**/template.*'],
    destDir: this.name + '/',
    allowEmpty: true
  });

  return preprocessTemplates(mergeTrees([standardTemplates, podTemplates]), {
    registry: this.registry
  });
};

EmberApp.prototype._processedTestsTree = function() {
  var addonTrees  = this.addonTreesFor('test-support');
  var mergedTests = mergeTrees(addonTrees.concat(this.trees.tests), {
    overwrite: true,
    description: 'TreeMerger (tests)'
  });

  return pickFiles(mergedTests, {
    srcDir: '/',
    destDir: this.name + '/tests'
  });
};

EmberApp.prototype._processedVendorTree = function() {
  if(this._cachedVendorTree) {
    return this._cachedVendorTree;
  }

  var addonTrees   = mergeTrees(this.addonTreesFor('addon'));
  addonTrees = mergeTrees([
    concatFiles(addonTrees, { inputFiles: ['*.css'], outputFile: '/addons.css', allowNone: true }),
    concatFiles(addonTrees, { inputFiles: ['*.js'],  outputFile: '/addons.js',  allowNone: true })
  ].concat(this.addonTreesFor('vendor')), {
    overwrite: true
  });

  var mergedVendor = mergeTrees(this._importTrees.concat(addonTrees, this.trees.vendor), {
    overwrite: true,
    description: 'TreeMerger (vendor)'
  });

  this._cachedVendorTree = pickFiles(mergedVendor, {
    srcDir: '/',
    destDir: 'vendor/'
  });
  return this._cachedVendorTree;
};

EmberApp.prototype.appAndDependencies = function() {
  var app       = this._processedAppTree();
  var templates = this._processedTemplatesTree();

  if (this.options.es3Safe) {
    app = new ES3SafeFilter(app);
  }

  var vendor          = this._processedVendorTree();
  var preprocessedApp = preprocessJs(app, '/', this.name, {
    registry: this.registry
  });

  var sourceTrees = [ vendor, preprocessedApp, templates ];

  if (this.tests) {
    var tests  = this._processedTestsTree();
    var preprocessedTests = preprocessJs(tests, '/tests', this.name, {
      registry: this.registry
    });

    sourceTrees.push(preprocessedTests);

    if (this.hinting) {
      var jshintedApp = jshintTrees(this._appWithoutStylesAndTemplates(), {
        jshintrcPath: this.options.jshintrc.app,
        description: 'JSHint - App'
      });

      var jshintedTests = jshintTrees(tests, {
        jshintrcPath: this.options.jshintrc.tests,
        description: 'JSHint - Tests'
      });

      jshintedApp = pickFiles(jshintedApp, {
        srcDir: '/',
        destDir: this.name + '/tests/'
      });

      jshintedTests = pickFiles(jshintedTests, {
        srcDir: '/',
        destDir: this.name + '/tests/'
      });

      sourceTrees.push(jshintedApp);
      sourceTrees.push(jshintedTests);
    }
  }

  var emberCLITree = pickFiles(unwatchedTree(__dirname), {
    files: ['loader.js'],
    srcDir: '/',
    destDir: '/assets/ember-cli/'
  });

  sourceTrees.push(emberCLITree);

  return mergeTrees(sourceTrees, {
    overwrite: true,
    description: 'TreeMerger (appAndDependencies)'
  });
};

EmberApp.prototype.javascript = function() {
  var applicationJs       = this.appAndDependencies();
  var legacyFilesToAppend = this.legacyFilesToAppend;

  var es6 = compileES6(applicationJs, {
    loaderFile: 'assets/ember-cli/loader.js',
    ignoredModules: Object.keys(this.importWhitelist),
    inputFiles: [
      this.name + '/**/*.js'
    ],
    wrapInEval: this.options.wrapInEval,
    outputFile: '/assets/' + this.name + '.js',
  });

  var vendor = concatFiles(applicationJs, {
    inputFiles: legacyFilesToAppend.concat(['vendor/addons.js']),
    outputFile: '/assets/vendor.js',
    separator: '\n;'
  });

  var vendorAndApp = mergeTrees([vendor, es6]);

  if (this.env === 'production' && this.options.minifyJS.enabled === true) {
    var options = this.options.minifyJS.options || {};
    return uglifyJavaScript(vendorAndApp, options);
  } else {
    return vendorAndApp;
  }
};

EmberApp.prototype.styles = function() {
  var addonTrees = this.addonTreesFor('styles');
  var vendor = this._processedVendorTree();
  var styles = pickFiles(this.trees.styles, {
    srcDir: '/',
    destDir: '/app/styles'
  });

  var trees = [vendor].concat(addonTrees);
  trees.push(styles);

  var stylesAndVendor = mergeTrees(trees, {
    description: 'TreeMerger (stylesAndVendor)'
  });

  var processedStyles = preprocessCss(stylesAndVendor, '/app/styles', '/assets', {
    registry: this.registry
  });
  var vendorStyles    = concatFiles(stylesAndVendor, {
    inputFiles: this.vendorStaticStyles.concat(['vendor/addons.css']),
    outputFile: '/assets/vendor.css',
    description: 'concatFiles - vendorStyles'
  });

  if (this.env === 'production' && this.options.minifyCSS.enabled === true) {
    var options = this.options.minifyCSS.options || {};
    options.registry = this.registry;
    processedStyles = preprocessMinifyCss(processedStyles, options);
    vendorStyles    = preprocessMinifyCss(vendorStyles, options);
  }

  return mergeTrees([
      processedStyles,
      vendorStyles
    ], {
      description: 'styles'
    });
};

EmberApp.prototype.testFiles = function() {
  var vendor = this._processedVendorTree();

  var testJs = concatFiles(vendor, {
    inputFiles: this.legacyTestFilesToAppend,
    outputFile: '/assets/test-support.js'
  });

  var testCss = concatFiles(vendor, {
    inputFiles: this.vendorTestStaticStyles,
    outputFile: '/assets/test-support.css'
  });

  var testemPath = path.join(__dirname, 'testem');
  testemPath = path.dirname(testemPath);

  var testemTree = pickFiles(unwatchedTree(testemPath), {
      files: ['testem.js'],
      srcDir: '/',
      destDir: '/'
    });

  if (this.options.fingerprint && this.options.fingerprint.exclude) {
    this.options.fingerprint.exclude.push('testem');
  }

  var testLoader = pickFiles(this.trees.vendor, {
    files: ['test-loader.js'],
    srcDir: '/ember-cli-test-loader',
    destDir: '/assets/'
  });

  var sourceTrees = [
    testJs,
    testCss,
    testLoader,
    testemTree
  ];

  return mergeTrees(sourceTrees, {
      overwrite: true,
      description: 'TreeMerger (testFiles)'
    });
};

EmberApp.prototype.otherAssets = function() {
  var vendor = this._processedVendorTree();
  var otherAssetTrees = this.otherAssetPaths.map(function (path) {
    return pickFiles(vendor, {
      srcDir: path.src,
      files: [path.file],
      destDir: path.dest
    });
  });
  return mergeTrees(otherAssetTrees, {
    description: 'TreeMerger (otherAssetTrees)'
  });
};

EmberApp.prototype.import = function(asset, options) {
  var assetPath;

  if (typeof asset === 'object') {
    assetPath = asset[this.env] || asset.development;
  } else {
    assetPath = asset;
  }

  if (!assetPath) {
    return;
  }

  assetPath = assetPath.replace(new RegExp('^'+this.bowerDirectory), 'vendor');

  if (assetPath.split('/').length < 2) {
    console.log(chalk.red('Using `app.import` with a file in the root of `vendor/` causes a significant performance penalty. Please move `'+ assetPath + '` into a subdirectory.'));
  }

  options = defaults(options || {}, {
    type: 'vendor'
  });

  if (/[\*\,]/.test(assetPath)) {
    throw new Error('You must pass a file path (without glob pattern) to `app.import`.  path was: `' + assetPath + '`');
  }

  var directory    = path.dirname(assetPath);
  var subdirectory = directory.replace(/^vendor\//, '');
  var extension    = path.extname(assetPath);
  var basename     = path.basename(assetPath);

  if (!extension) {
    throw new Error('You must pass a file to `app.import`. For directories specify them to the constructor under the `trees` option.');
  }

  if (fs.existsSync(directory) && this._importTrees.indexOf(directory) === -1) {
    var assetTree = pickFiles(directory, {
      srcDir: '/',
      destDir: subdirectory
    });

    this._importTrees.push(assetTree);
  }

  if (isType(assetPath, 'js', {registry: this.registry})) {
    if(options.type === 'vendor') {
      this.legacyFilesToAppend.push(assetPath);
    } else {
      this.legacyTestFilesToAppend.push(assetPath);
    }

    this.importWhitelist = assign(this.importWhitelist, options.exports || {});
  } else if (extension === '.css') {
    if(options.type === 'vendor') {
      this.vendorStaticStyles.push(assetPath);
    } else {
      this.vendorTestStaticStyles.push(assetPath);
    }
  } else {
    var destDir = options.destDir;
    if (destDir === '') {
      destDir = '/';
    }
    this.otherAssetPaths.push({
      src: directory,
      file: basename,
      dest: destDir || subdirectory
    });
  }
};

EmberApp.prototype.toArray = function() {
  var sourceTrees = [
    this.index(),
    this.javascript(),
    this.styles(),
    this.otherAssets()
  ];

  var publicFolder = this.publicFolder();
  if (fs.existsSync(publicFolder)) {
    sourceTrees.push(publicFolder);
  }

  if (this.tests) {
    sourceTrees = sourceTrees.concat(this.testIndex(), this.testFiles());
  }

  return sourceTrees;
};

EmberApp.prototype.toTree = function(additionalTrees) {
  var tree = mergeTrees(this.toArray().concat(additionalTrees || []), {
    overwrite: true,
    description: 'TreeMerger (allTrees)'
  });

  return this.addonPostprocessTree('all', tree);
};

function injectENVJson(fn, env, tree, files) {
  // TODO: real templating
  var envJsonString = function(){
    return JSON.stringify(fn(env));
  };

  var baseTag = function(){
    var envJSON      = fn(env);
    var baseURL      = cleanBaseURL(envJSON.baseURL);
    var locationType = envJSON.locationType;

    if (locationType === 'hash' || locationType === 'none') {
      return '';
    }

    if (baseURL) {
      return '<base href="' + baseURL + '">';
    } else {
      return '';
    }
  };

  return replace(tree, {
    files: files,
    patterns: [{
      match: /\{\{ENV\}\}/g,
      replacement: envJsonString
    },
    {
      match: /\{\{BASE_TAG\}\}/g,
      replacement: baseTag
    }]
  });
}


text:
package com.mishiranu.dashchan.ui.navigator.adapter;

import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import chan.util.StringUtils;
import com.mishiranu.dashchan.content.database.ChanDatabase;
import com.mishiranu.dashchan.util.ListViewUtils;
import com.mishiranu.dashchan.widget.CursorAdapter;
import com.mishiranu.dashchan.widget.SimpleViewHolder;
import com.mishiranu.dashchan.widget.ViewFactory;

public class UserBoardsAdapter extends CursorAdapter<ChanDatabase.BoardCursor, RecyclerView.ViewHolder> {
	public interface Callback extends ListViewUtils.SimpleCallback<ChanDatabase.BoardItem> {}

	private final Callback callback;
	private final ChanDatabase.BoardItem boardItem = new ChanDatabase.BoardItem();

	public UserBoardsAdapter(Callback callback) {
		this.callback = callback;
	}

	private ChanDatabase.BoardItem copyItem(int position) {
		return boardItem.update(moveTo(position)).copy();
	}

	@NonNull
	@Override
	public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
		return ListViewUtils.bind(new SimpleViewHolder(ViewFactory.makeTwoLinesListItem(parent, 0).view),
				true, this::copyItem, callback);
	}

	@Override
	public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
		ChanDatabase.BoardItem boardItem = this.boardItem.update(moveTo(position));
		ViewFactory.TwoLinesViewHolder viewHolder = (ViewFactory.TwoLinesViewHolder) holder.itemView.getTag();
		viewHolder.text1.setText(StringUtils.formatBoardTitle("", boardItem.boardName, boardItem.extra1));
		if (!StringUtils.isEmpty(boardItem.extra2)) {
			viewHolder.text2.setVisibility(View.VISIBLE);
			viewHolder.text2.setText(boardItem.extra2);
		} else {
			viewHolder.text2.setVisibility(View.GONE);
		}
	}
}


text:
package com.foilen.smalltools.tools;

import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class SpaceConverterToolsTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void testConvertBytes_allNumbers() {
        Assert.assertEquals(1023456789000000L, SpaceConverterTools.convertToBytes("1023456789 m"));
    }

    @Test
    public void testConvertBytes_bytes() {
        Assert.assertEquals(85L, SpaceConverterTools.convertToBytes("85"));
        Assert.assertEquals(85L, SpaceConverterTools.convertToBytes("85b"));
        Assert.assertEquals(85L, SpaceConverterTools.convertToBytes("85B"));
        Assert.assertEquals(85L, SpaceConverterTools.convertToBytes("85 B"));
        Assert.assertEquals(85L, SpaceConverterTools.convertToBytes("85 b"));
    }

    @Test
    public void testConvertBytes_gibibytes() {
        Assert.assertEquals(91268055040L, SpaceConverterTools.convertToBytes("85gib"));
        Assert.assertEquals(91268055040L, SpaceConverterTools.convertToBytes("85 giB"));
    }

    @Test
    public void testConvertBytes_gigabytes() {
        Assert.assertEquals(85000000000L, SpaceConverterTools.convertToBytes("85g"));
        Assert.assertEquals(85000000000L, SpaceConverterTools.convertToBytes("85 g"));
        Assert.assertEquals(85000000000L, SpaceConverterTools.convertToBytes("85 gB"));
    }

    @Test
    public void testConvertBytes_invalid_char() {
        thrown.expectMessage("% is an invalid space");
        SpaceConverterTools.convertToBytes("%");
    }

    @Test
    public void testConvertBytes_invalid_number() {
        thrown.expectMessage("kb is an invalid space");
        SpaceConverterTools.convertToBytes("kb");
    }

    @Test
    public void testConvertBytes_invalid_unit() {
        thrown.expectMessage("75J is an invalid space");
        SpaceConverterTools.convertToBytes("75J");
    }

    @Test
    public void testConvertBytes_kibibytes() {
        Assert.assertEquals(87040L, SpaceConverterTools.convertToBytes("85kib"));
        Assert.assertEquals(87040L, SpaceConverterTools.convertToBytes("85 kiB"));
    }

    @Test
    public void testConvertBytes_kilobytes() {
        Assert.assertEquals(85000L, SpaceConverterTools.convertToBytes("85k"));
        Assert.assertEquals(85660L, SpaceConverterTools.convertToBytes("85.66k"));
        Assert.assertEquals(85000L, SpaceConverterTools.convertToBytes("85 k"));
        Assert.assertEquals(85000L, SpaceConverterTools.convertToBytes("85\t k"));
        Assert.assertEquals(85000L, SpaceConverterTools.convertToBytes("85 kB"));
    }

    @Test
    public void testConvertBytes_mebibytes() {
        Assert.assertEquals(89128960L, SpaceConverterTools.convertToBytes("85mib"));
        Assert.assertEquals(89128960L, SpaceConverterTools.convertToBytes("85 miB"));
        Assert.assertEquals(89128960L, SpaceConverterTools.convertToBytes("85    miB   "));
    }

    @Test
    public void testConvertBytes_megabytes() {
        Assert.assertEquals(85000000L, SpaceConverterTools.convertToBytes("85m"));
        Assert.assertEquals(85000000L, SpaceConverterTools.convertToBytes("85 m"));
        Assert.assertEquals(85000000L, SpaceConverterTools.convertToBytes("85 mB"));
    }

    @Test
    public void testConvertBytes_tebibytes() {
        Assert.assertEquals(93458488360960L, SpaceConverterTools.convertToBytes("85tib"));
        Assert.assertEquals(93458488360960L, SpaceConverterTools.convertToBytes("85 tiB"));
    }

    @Test
    public void testConvertBytes_terabytes() {
        Assert.assertEquals(85000000000000L, SpaceConverterTools.convertToBytes("85t"));
        Assert.assertEquals(85000000000000L, SpaceConverterTools.convertToBytes("85 t"));
        Assert.assertEquals(85000000000000L, SpaceConverterTools.convertToBytes("85 tB"));
    }

    @Test
    public void testConvertToBiggestBUnit_Exact() {
        Assert.assertEquals("0B", SpaceConverterTools.convertToBiggestBUnit(0L));
        Assert.assertEquals("1B", SpaceConverterTools.convertToBiggestBUnit(1L));
        Assert.assertEquals("1K", SpaceConverterTools.convertToBiggestBUnit(1000L));
        Assert.assertEquals("1M", SpaceConverterTools.convertToBiggestBUnit(1000000L));
        Assert.assertEquals("1G", SpaceConverterTools.convertToBiggestBUnit(1000000000L));
        Assert.assertEquals("1T", SpaceConverterTools.convertToBiggestBUnit(1000000000000L));
    }

    @Test
    public void testConvertToBiggestBUnit_NoDecimal() {
        Assert.assertEquals("85B", SpaceConverterTools.convertToBiggestBUnit(85L));
        Assert.assertEquals("85K", SpaceConverterTools.convertToBiggestBUnit(85000L));
        Assert.assertEquals("85G", SpaceConverterTools.convertToBiggestBUnit(85000000000L));
        Assert.assertEquals("85T", SpaceConverterTools.convertToBiggestBUnit(85000000000000L));
    }

    @Test
    public void testConvertToBiggestBUnit_OneDecimal() {
        Assert.assertEquals("8.5K", SpaceConverterTools.convertToBiggestBUnit(8500L));
        Assert.assertEquals("8.5G", SpaceConverterTools.convertToBiggestBUnit(8500000000L));
        Assert.assertEquals("8.5T", SpaceConverterTools.convertToBiggestBUnit(8500000000000L));
    }

    @Test
    public void testConvertToBiggestBUnit_TwoDecimal() {
        Assert.assertEquals("8.51K", SpaceConverterTools.convertToBiggestBUnit(8510L));
        Assert.assertEquals("8.51G", SpaceConverterTools.convertToBiggestBUnit(8510000000L));
        Assert.assertEquals("8.51T", SpaceConverterTools.convertToBiggestBUnit(8510000000000L));
    }

    @Test
    public void testConvertToBiggestBUnit_TwoDecimal_Bigger() {
        Assert.assertEquals("8.51K", SpaceConverterTools.convertToBiggestBUnit(8512L));
        Assert.assertEquals("8.51G", SpaceConverterTools.convertToBiggestBUnit(8512000000L));
        Assert.assertEquals("8.51T", SpaceConverterTools.convertToBiggestBUnit(8512000000000L));
    }

    @Test
    public void testConvertToBiggestBUnit_TwoDecimal_Bigger_Higher() {
        Assert.assertEquals("8.52K", SpaceConverterTools.convertToBiggestBUnit(8517L));
        Assert.assertEquals("8.52G", SpaceConverterTools.convertToBiggestBUnit(8517000000L));
        Assert.assertEquals("8.52T", SpaceConverterTools.convertToBiggestBUnit(8517000000000L));
    }

    @Test
    public void testConvertToBiggestBUnit_TwoDecimal_With_0() {
        Assert.assertEquals("8.01K", SpaceConverterTools.convertToBiggestBUnit(8010L));
        Assert.assertEquals("8.01G", SpaceConverterTools.convertToBiggestBUnit(8010000000L));
        Assert.assertEquals("8.01T", SpaceConverterTools.convertToBiggestBUnit(8010000000000L));
    }

}


text:
module FormationsHelper
end


text:
#ifndef OPENSIM_PATH_ACTUATOR_H_
#define OPENSIM_PATH_ACTUATOR_H_

#include <OpenSim/Common/PropertyObj.h>
#include <OpenSim/Common/PropertyDbl.h>
#include "Actuator.h"
#include "GeometryPath.h"

//=============================================================================
//=============================================================================

namespace OpenSim {

class Coordinate;
class ForceSet;
class Model;

/**
 * This is the base class for actuators that apply controllable tension along
 * a geometry path. %PathActuator has no states; the control is simply the
 * tension to be applied along a geometry path (i.e. tensionable rope).
 *
 * @author Ajay Seth
 */
class OSIMSIMULATION_API PathActuator : public Actuator {
OpenSim_DECLARE_CONCRETE_OBJECT(PathActuator, Actuator);
public:
//=============================================================================
// PROPERTIES
//=============================================================================
    /** @name Property declarations
    These are the serializable properties associated with the %PathActuator
    class. Note that objects derived from this class inherit these
    properties. **/
    /**@{**/
    OpenSim_DECLARE_UNNAMED_PROPERTY(GeometryPath,
		"The set of points defining the path of the muscle.");
    OpenSim_DECLARE_PROPERTY(optimal_force, double,
        "The maximum force this actuator can produce.");
    /**@}**/

//=============================================================================
// PUBLIC METHODS
//=============================================================================
	PathActuator();

    // default destructor, copy constructor, copy assignment

	//--------------------------------------------------------------------------
	// GET AND SET
	//--------------------------------------------------------------------------
	// Path
	GeometryPath& updGeometryPath() { return upd_GeometryPath(); }
	const GeometryPath& getGeometryPath() const
    {   return get_GeometryPath(); }
	virtual bool hasGeometryPath() const { return true;};

	// OPTIMAL FORCE
	void setOptimalForce(double aOptimalForce);
	double getOptimalForce() const;

	// Length and Speed of actuator
	virtual double getLength(const SimTK::State& s) const;
	virtual double getLengtheningSpeed(const SimTK::State& s) const;

	// Power: Since lengthening is positive and tension always shortens, positive power
	// is when muscle is shortening under tension.
	virtual double getPower(const SimTK::State& s) const
    {   return -getForce(s)*getSpeed(s); }

	// STRESS
	virtual double getStress( const SimTK::State& s ) const;

    // Convenience method to add PathPoints
	 /** Note that this function does not maintain the State and so should be used only
		before a valid State is created */
	 void addNewPathPoint( const std::string& proposedName, OpenSim::Body& aBody,
						   const SimTK::Vec3& aPositionOnBody);

	//--------------------------------------------------------------------------
	// APPLICATION
	//--------------------------------------------------------------------------
	virtual void computeForce( const SimTK::State& state,
							   SimTK::Vector_<SimTK::SpatialVec>& bodyForces,
							   SimTK::Vector& mobilityForces) const;

	//--------------------------------------------------------------------------
	// COMPUTATIONS
	//--------------------------------------------------------------------------
	virtual double computeActuation( const SimTK::State& s) const;
	virtual double computeMomentArm( const SimTK::State& s, Coordinate& aCoord) const;

	//--------------------------------------------------------------------------
	// XML
	//--------------------------------------------------------------------------
	virtual void updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber=-1);

	//--------------------------------------------------------------------------
	// SCALING
	//--------------------------------------------------------------------------
	virtual void preScale(const SimTK::State& s, const ScaleSet& aScaleSet);
	virtual void scale(const SimTK::State& s, const ScaleSet& aScaleSet);
	virtual void postScale(const SimTK::State& s, const ScaleSet& aScaleSet);

	//--------------------------------------------------------------------------
	// Visible Object Support
	//--------------------------------------------------------------------------
	virtual const VisibleObject* getDisplayer() const;
	virtual void updateDisplayer(const SimTK::State& s) const;

protected:
    /** Override this method if you would like to calculate a color for use when
    the %PathActuator's path is displayed in the visualizer. You do not have
    to invoke the base class ("Super") method, just replace it completely. This
    method will be invoked during realizeDynamics() so the supplied \a state has
    already been realized through Stage::Velocity and you can access time,
    position, and velocity dependent quantities. You must \e not attempt to
    realize the passed-in \a state any further since we are already in the
    middle of realizing here. Return SimTK::Vec3(SimTK::NaN) if you want to
    leave the color unchanged (that's what the base class implementation does).

    @param[in] state
        A SimTK::State already realized through Stage::Velocity. Do not
        attempt to realize it any further.
    @returns
        The desired color for the path as an RGB vector with each
        component ranging from 0 to 1, or NaN to indicate that the color
        should not be changed. **/
    virtual SimTK::Vec3 computePathColor(const SimTK::State& state) const;

    /** Extension of parent class method; derived classes may extend further. **/
	void connectToModel(Model& aModel) OVERRIDE_11;
    /** Extension of parent class method; derived classes may extend further. **/
    void realizeDynamics(const SimTK::State& state) const OVERRIDE_11;

private:
	void setNull();
	void constructProperties();

//=============================================================================
};	// END of class PathActuator

}; //namespace
//=============================================================================
//=============================================================================

#endif // OPENSIM_PATH_ACTUATOR_H_


text:
namespace minigo {

// Holds game-specific options.
// Holds the full history of a game.
class Game {
 public:
  struct Options {
    float resign_threshold = -0.95;

    // We use a separate resign_enabled flag instead of setting the
    // resign_threshold to -1 for games where resignation is diabled. This
    // enables us to report games where the eventual winner would have
    // incorrectly resigned early, had resignations been enabled.
    bool resign_enabled = true;

    float komi = kDefaultKomi;

    // If true, repeated calls to AddMove with the same Color and Coord will
    // be ignored. This should be set to true when two separate MctsPlayer
    // instances are playing (because they both make AddMove calls to the same
    // Game object), and set to false for self-play where a single MctsPlayer
    // plays both back and white.
    bool ignore_repeated_moves = false;

    friend std::ostream& operator<<(std::ostream& os, const Options& options);
  };

  struct Move {
    Color color;

    Coord c = Coord::kInvalid;

    float Q;

    // Comments associated with the move.
    std::string comment;

    // Models evaluated when performing tree search.
    std::vector<std::string> models;

    std::array<float, kNumMoves> search_pi;

    // Stones on the board before the move was played.
    // This is used to build training features after a selfplay game has
    // finished.
    Position::Stones stones;
  };

  enum class GameOverReason {
    kBothPassed,
    kOpponentResigned,
    kMoveLimitReached,
  };

  static std::string FormatScore(float score);

  Game(std::string black_name, std::string white_name, const Options& options);

  void NewGame();

  void AddComment(const std::string& comment);

  void AddMove(Color color, Coord c, const Position::Stones& stones,
               std::string comment, float Q,
               const std::array<float, kNumMoves>& search_pi,
               std::vector<std::string> models);

  void UndoMove();

  void SetGameOverBecauseOfPasses(float score);

  void SetGameOverBecauseOfResign(Color winner);

  void SetGameOverBecauseMoveLimitReached(float score);

  // Returns up to the last `num_moves` of moves that lead up to the requested
  // `move`, including the move itself.
  // If `move < num_moves`, history will be truncated to the first `move` moves.
  void GetStoneHistory(int move, int num_moves,
                       std::vector<const Position::Stones*>* history) const;

  // Get information on the bleakest move for a completed game, if the game has
  // history and was played with resign disabled. This only makes sense if
  // resign was disabled (if resign was enabled, bleakest-move calculation is
  // not relevant, since quitters don't know how bad it could have been.)
  //
  // Returns true if the bleakest move was found and returned; false otherwise.
  // Q is returned from the winners perspective, which means we don't have to
  // reference the result to transform this into a sortable list of evaluations.
  // &q is the bleakest move from the perspective of the winner, i.e., negative.
  bool FindBleakestMove(int* move, float* q) const;

  const Options& options() const { return options_; }
  const std::string& black_name() const { return black_name_; }
  const std::string& white_name() const { return white_name_; }
  bool game_over() const { return game_over_; }
  GameOverReason game_over_reason() const {
    MG_CHECK(game_over());
    return game_over_reason_;
  }
  float result() const {
    MG_CHECK(game_over());
    return result_;
  }
  const std::string& result_string() const {
    MG_CHECK(game_over());
    return result_string_;
  }
  const std::string& comment() const { return comment_; }

  int num_moves() const { return static_cast<int>(moves_.size()); }
  const Move* GetMove(int i) {
    MG_CHECK(i >= 0 && i < num_moves());
    return moves_[i].get();
  }

  const std::vector<std::unique_ptr<Move>>& moves() const { return moves_; }

 private:
  const Options options_;
  const std::string black_name_;
  const std::string white_name_;
  bool game_over_ = false;
  GameOverReason game_over_reason_;
  float result_;
  std::string result_string_;
  std::string comment_;
  std::vector<std::unique_ptr<Move>> moves_;
};

}  // namespace minigo

#endif  // CC_GAME_H_


text:
import { Component } from '@angular/core';
import { DocumentationSectionComponent } from '../../../../../decorators/documentation-section-component';

@Component({
    selector: 'uxd-css-typography-case-usage-guidelines',
    templateUrl: './case-usage-guidelines.component.html'
})
@DocumentationSectionComponent('CssCaseUsageGuidelinesComponent')
export class CssCaseUsageGuidelinesComponent {

}


text:
export default {
  handler: (canvas) => {
    let trueSize = (property) => parseInt(getComputedStyle(canvas)[property], 10);

    let colorSelector = (event) => {
      let rgba = canvas.ctx.getImageData(
        event.offsetX / trueSize('width') * canvas.width,
        event.offsetY / trueSize('height') * canvas.height,
        1, 1
      ).data.slice(-4);

      let color = 'rgba(' + rgba.join(',') + ')';

      document.body.style.backgroundColor = color;
    };

    return colorSelector;
  }
};


text:
/* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.component.openstack.glance;

import java.util.Map;

import org.apache.camel.CamelContext;
import org.apache.camel.spi.ExtendedPropertyConfigurerGetter;
import org.apache.camel.spi.PropertyConfigurerGetter;
import org.apache.camel.spi.ConfigurerStrategy;
import org.apache.camel.spi.GeneratedPropertyConfigurer;
import org.apache.camel.util.CaseInsensitiveMap;
import org.apache.camel.support.component.PropertyConfigurerSupport;

/**
 * Generated by camel build tools - do NOT edit this file!
 */
@SuppressWarnings("unchecked")
public class GlanceComponentConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {

    @Override
    public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
        GlanceComponent target = (GlanceComponent) obj;
        switch (ignoreCase ? name.toLowerCase() : name) {
        case "autowiredenabled":
        case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true;
        case "lazystartproducer":
        case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
        default: return false;
        }
    }

    @Override
    public Class<?> getOptionType(String name, boolean ignoreCase) {
        switch (ignoreCase ? name.toLowerCase() : name) {
        case "autowiredenabled":
        case "autowiredEnabled": return boolean.class;
        case "lazystartproducer":
        case "lazyStartProducer": return boolean.class;
        default: return null;
        }
    }

    @Override
    public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
        GlanceComponent target = (GlanceComponent) obj;
        switch (ignoreCase ? name.toLowerCase() : name) {
        case "autowiredenabled":
        case "autowiredEnabled": return target.isAutowiredEnabled();
        case "lazystartproducer":
        case "lazyStartProducer": return target.isLazyStartProducer();
        default: return null;
        }
    }
}


text:
CatarseMoip::Engine.routes.draw do
  namespace :payment do
    resources :moip, only: [] do
      member do
        match :pay
      end
    end
  end
end


text:
package me.heaton.profun.week6

import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class MnemonicTest extends FunSuite {

  test("read file") {
    assert(Mnemonic.words contains "Scala")
  }

  test("char -> code") {
    assert(Mnemonic.charCode('A') === '2')
  }

  test("word to code") {
    assert(Mnemonic.wordCode("Java") === "5282")
  }

  test("words from nums") {
    assert(Mnemonic.wordsForNum("5282") contains "Java")
    assert(Mnemonic.wordsForNum("72252") contains "Scala")
  }

  test("encode 7225247386") {
    assert(Mnemonic.encode("7225247386") contains List("Scala", "is", "fun"))
  }

  test("describe encode last step") {
    val lastStep = Set(List("is", "fun")) map ("Scala" :: _)
    assert(lastStep === Set(List("Scala", "is", "fun")))
  }

  test("translate 7225247386") {
    assert(Mnemonic.translate("7225247386") contains "Scala is fun")
  }

}


text:
import { jest } from "@jest/globals";
import { join } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { fileURLToPath } from "node:url";

import config from "@argos-ci/config";
import type {
  Build,
  Repository,
  Screenshot,
  ScreenshotBucket,
  ScreenshotDiff,
} from "@argos-ci/database/models";
import { factory, useDatabase } from "@argos-ci/database/testing";
import { quitAmqp } from "@argos-ci/job-core";
import { s3 as getS3, upload } from "@argos-ci/storage";
import type { S3Client } from "@argos-ci/storage";

import { computeScreenshotDiff } from "./computeScreenshotDiff.js";

const __dirname = fileURLToPath(new URL(".", import.meta.url));

describe("#computeScreenshotDiff", () => {
  useDatabase();
  jest.setTimeout(10000);

  let s3: S3Client;
  let baseBucket: ScreenshotBucket;
  let build: Build;
  let compareBucket: ScreenshotBucket;
  let screenshotDiff: ScreenshotDiff;

  beforeAll(async () => {
    s3 = getS3();
    await upload({
      s3,
      Bucket: config.get("s3.screenshotsBucket"),
      Key: "penelope.jpg",
      inputPath: join(__dirname, "__fixtures__", "penelope.jpg"),
    });
    await upload({
      s3,
      Bucket: config.get("s3.screenshotsBucket"),
      Key: "penelope-argos.jpg",
      inputPath: join(__dirname, "__fixtures__", "penelope-argos.jpg"),
    });
  });

  beforeEach(async () => {
    const repository = await factory.create<Repository>("Repository", {
      token: "xx",
    });
    compareBucket = await factory.create<ScreenshotBucket>("ScreenshotBucket", {
      name: "test-bucket",
      branch: "test-branch",
      repositoryId: repository.id,
    });
    baseBucket = await factory.create<ScreenshotBucket>("ScreenshotBucket", {
      name: "base-bucket",
      branch: "master",
      repositoryId: repository.id,
    });
    build = await factory.create<Build>("Build", {
      baseScreenshotBucketId: baseBucket.id,
      compareScreenshotBucketId: compareBucket.id,
      repositoryId: repository.id,
    });
  });

  afterAll(async () => {
    await delay(500);
    await quitAmqp();
  });

  describe("with two different screenshots", () => {
    beforeEach(async () => {
      const compareScreenshot = await factory.create<Screenshot>("Screenshot", {
        name: "penelope",
        s3Id: "penelope-argos.jpg",
        screenshotBucketId: compareBucket.id,
      });
      const baseScreenshot = await factory.create<Screenshot>("Screenshot", {
        name: "penelope",
        s3Id: "penelope.jpg",
        screenshotBucketId: baseBucket.id,
      });
      screenshotDiff = await factory.create<ScreenshotDiff>("ScreenshotDiff", {
        buildId: build.id,
        baseScreenshotId: baseScreenshot.id,
        compareScreenshotId: compareScreenshot.id,
        jobStatus: "pending",
        validationStatus: "unknown",
      });
    });

    it('should update result and notify "diff-detected"', async () => {
      await computeScreenshotDiff(screenshotDiff, {
        s3,
        bucket: config.get("s3.screenshotsBucket"),
      });

      await screenshotDiff.reload();
      expect(screenshotDiff.score! > 0).toBe(true);
      expect(typeof screenshotDiff.s3Id === "string").toBe(true);
      // expect(pushBuildNotification).toBeCalledWith({
      //   buildId: build.id,
      //   type: "diff-detected",
      // });
    });
  });

  describe("with two same screenshots", () => {
    beforeEach(async () => {
      const compareScreenshot = await factory.create<Screenshot>("Screenshot", {
        name: "penelope",
        s3Id: "penelope.jpg",
        screenshotBucketId: compareBucket.id,
      });
      const baseScreenshot = await factory.create<Screenshot>("Screenshot", {
        name: "penelope",
        s3Id: "penelope.jpg",
        screenshotBucketId: baseBucket.id,
      });
      screenshotDiff = await factory.create<ScreenshotDiff>("ScreenshotDiff", {
        buildId: build.id,
        baseScreenshotId: baseScreenshot.id,
        compareScreenshotId: compareScreenshot.id,
        jobStatus: "pending",
        validationStatus: "unknown",
      });
    });

    it('should not update result and notify "no-diff-detected"', async () => {
      await computeScreenshotDiff(screenshotDiff, {
        s3,
        bucket: config.get("s3.screenshotsBucket"),
      });

      await screenshotDiff.reload();
      expect(screenshotDiff.score).toBe(0);
      expect(screenshotDiff.s3Id).toBe(null);
      // expect(pushBuildNotification).toBeCalledWith({
      //   buildId: build.id,
      //   type: "no-diff-detected",
      // });
    });
  });
});


text:
package com.gxq;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class AdApplicationTests {

	@Test
	public void contextLoads() {
	}

}


text:
<?php

namespace Modules\Content\PassThroughs\ContentBlock;

use Modules\Content\Models\ContentBlock;
use Modules\Content\Modules\Widget;
use Modules\Content\PassThroughs\PassThrough;

class Config extends PassThrough
{
    /**
     * @var ContentBlock
     */
    private $contentBlock;

    /**
     * HasPermissionTo constructor.
     *
     * @param ContentBlock $contentBlock
     */
    public function __construct(ContentBlock $contentBlock)
    {
        $this->contentBlock = $contentBlock;
    }

    /**
     * @param $name
     * @return mixed
     */
    public function __get($name)
    {
        return array_get($this->all(), $name);
    }

    /**
     * @return mixed
     */
    public function all()
    {
        $widget = widgets()->where('key', $this->contentBlock->widget)->first();
        $config = $widget ? $widget->config : [];

        return $config;
    }

}


text:
LSysDashboard::LSysDashboard(QWidget *parent, QString id, bool horizontal) : LPPlugin(parent, id, horizontal){
  upTimer = new QTimer(this);
    upTimer->setInterval(10000); //10 second update ping
    connect(upTimer, SIGNAL(timeout()), this, SLOT(updateIcon()));
  button = new QToolButton(this);
    button->setAutoRaise(true);
    button->setToolButtonStyle(Qt::ToolButtonIconOnly);
    button->setPopupMode(QToolButton::DelayedPopup); //make sure it runs the update routine first
    connect(button, SIGNAL(clicked()), this, SLOT(openMenu()));
    this->layout()->setContentsMargins(0,0,0,0);
    this->layout()->addWidget(button);
  menu = new QMenu(this);
    connect(menu, SIGNAL(aboutToHide()), this, SIGNAL(MenuClosed()));
  sysmenu = new LSysMenuQuick(this);
    connect(sysmenu, SIGNAL(CloseMenu()), this, SLOT(closeMenu()) );
  mact = new QWidgetAction(this);
    mact->setDefaultWidget(sysmenu);
    menu->addAction(mact);
  button->setMenu(menu);
  QTimer::singleShot(0,this, SLOT(OrientationChange())); //Update icons/sizes
}

LSysDashboard::~LSysDashboard(){

}

// ========================
//    PRIVATE FUNCTIONS
// ========================
void LSysDashboard::updateIcon(bool force){
  //For the visual, show battery state only if important
  static bool batcharging = false;
  QPixmap pix;
  button->setToolTip(tr("System Dashboard"));
  if(LOS::hasBattery()){
    int bat = LOS::batteryCharge();
    bool charging = LOS::batteryIsCharging();
    //Set the icon as necessary
      if(charging && !batcharging){
	//Charging and just plugged in
	if(bat < 15){ button->setIcon( LXDG::findIcon("battery-charging-low","") ); QTimer::singleShot(5000, this, SLOT(resetIcon()));}
	else if(bat < 30){ button->setIcon( LXDG::findIcon("battery-charging-caution","") ); QTimer::singleShot(5000, this, SLOT(resetIcon()));}
	else if(force || button->icon().isNull()){ resetIcon(); }
      }else if(!charging){
        //Not charging (critical level or just unplugged)
	if(bat<5){ button->setIcon( LXDG::findIcon("battery-missing","") ); }
	else if(bat < 15){ button->setIcon( LXDG::findIcon("battery-low","") ); QTimer::singleShot(5000, this, SLOT(resetIcon())); }
	else if(bat < 30 && batcharging){ button->setIcon( LXDG::findIcon("battery-caution","") ); QTimer::singleShot(5000, this, SLOT(resetIcon()));}
	else if(bat < 50 && batcharging){ button->setIcon( LXDG::findIcon("battery-040","")); QTimer::singleShot(5000, this, SLOT(resetIcon()));}
	else if(bat < 70 && batcharging){ button->setIcon( LXDG::findIcon("battery-060","")); QTimer::singleShot(5000, this, SLOT(resetIcon()));}
	else if(bat < 90 && batcharging){ button->setIcon( LXDG::findIcon("battery-080","")); QTimer::singleShot(5000, this, SLOT(resetIcon()));}
	else if(batcharging){ button->setIcon( LXDG::findIcon("battery-100","")); QTimer::singleShot(5000, this, SLOT(resetIcon()));}
	else if(force || button->icon().isNull()){ resetIcon(); }
      }else if(force || button->icon().isNull()){
	//Otherwise just use the default icon
	resetIcon();
      }
    //Save the values for comparison later
    batcharging = charging;
    if( !upTimer->isActive() ){ upTimer->start(); } //only use the timer if a battery is present

  // No battery - just use/set the normal icon
  }else if(force || button->icon().isNull()){
    resetIcon();
    if(upTimer->isActive() ){ upTimer->stop(); } //no battery available - no refresh timer needed
  }

}

void LSysDashboard::resetIcon(){
  button->setIcon( LXDG::findIcon("onboard-panel","arrow-down-drop-circle"));
}

void LSysDashboard::openMenu(){
  sysmenu->UpdateMenu();
  button->showMenu();
}

void LSysDashboard::closeMenu(){
  menu->hide();
}


text:
"""
Error constants to be returned from our API endpoints.
Should be replicated in the frontend constants.js for the ERROR_CONSTANTS object.
"""
# 400 error based constants
USERNAME_ALREADY_EXISTS = "USERNAME_ALREADY_EXISTS"
USER_ALREADY_IN_GROUP_IN_CLASS = "USER_ALREADY_IN_GROUP_IN_CLASS"
MISSING_PASSWORD = "MISSING_PASSWORD"
MAX_LENGTH = "MAX_LENGTH"
INVALID = "INVALID"
UNIQUE = "UNIQUE"
INVALID_NETWORK_LOCATION_FORMAT = "INVALID_NETWORK_LOCATION_FORMAT"
NETWORK_LOCATION_NOT_FOUND = "NETWORK_LOCATION_NOT_FOUND"
INVALID_KDP_REGISTRATION_TOKEN = "INVALID_KDP_REGISTRATION_TOKEN"
# 401 error constants
INVALID_CREDENTIALS = "INVALID_CREDENTIALS"
# 404 error constants
NOT_FOUND = "NOT_FOUND"
FACILITY_DOES_NOT_EXIST = "FACILITY_DOES_NOT_EXIST"
# 403 error constants
PERMISSION_DENIED = "PERMISSION_DENIED"
NOT_AUTHENTICATED = "NOT_AUTHENTICATED"


text:
package me.vilsol.nmswrapper.wraps.unparsed;

import me.vilsol.nmswrapper.*;
import me.vilsol.nmswrapper.reflections.*;
import me.vilsol.nmswrapper.wraps.*;

@ReflectiveClass(name = "ItemMultiTexture")
public class NMSItemMultiTexture extends NMSItemBlock {

    public NMSItemMultiTexture(Object nmsObject){
        super(nmsObject);
    }

    public NMSItemMultiTexture(String nmsName, Object[] paramTypes, Object[] params) {
        super(nmsName, paramTypes, params);
    }

    /**
     * TODO Find correct name
     * @see net.minecraft.server.v1_9_R1.ItemMultiTexture#e_(net.minecraft.server.v1_9_R1.ItemStack)
     */
    @ReflectiveMethod(name = "e_", types = {NMSItemStack.class})
    public String e_(NMSItemStack itemStack){
        return (String) NMSWrapper.getInstance().exec(nmsObject, itemStack);
    }

    /**
     * @see net.minecraft.server.v1_9_R1.ItemMultiTexture#filterData(int)
     */
    @ReflectiveMethod(name = "filterData", types = {int.class})
    public int filterData(int i){
        return (int) NMSWrapper.getInstance().exec(nmsObject, i);
    }

}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Linq;
using Xunit;

namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
    public class TupleTests : ExpressionCompilerTestBase
    {
        [Fact]
        public void Literal()
        {
            var source =
@"class C
{
    static void M()
    {
        (int, int) o;
    }
}";
            var comp = CreateCompilationWithMscorlib(source, new[] { ValueTupleRef }, options: TestOptions.DebugDll);
            WithRuntimeInstance(comp, runtime =>
            {
                var context = CreateMethodContext(runtime, "C.M");
                var testData = new CompilationTestData();
                string error;
                var result = context.CompileExpression("(A: 1, B: 2)", out error, testData);
                Assert.Null(error);
                ReadOnlyCollection<byte> customTypeInfo;
                var customTypeInfoId = result.GetCustomTypeInfo(out customTypeInfo);
                ReadOnlyCollection<byte> dynamicFlags;
                ReadOnlyCollection<string> tupleElementNames;
                CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
                Assert.Equal(new[] { "A", "B" }, tupleElementNames);
                var methodData = testData.GetMethodData("<>x.<>m0");
                var method = methodData.Method;
                Assert.True(method.ReturnType.IsTupleType);
                Assert.NotNull(GetTupleElementNamesAttributeIfAny(method));
                methodData.VerifyIL(
@"{
  // Code size        8 (0x8)
  .maxstack  2
  .locals init (System.ValueTuple<int, int> V_0) //o
  IL_0000:  ldc.i4.1
  IL_0001:  ldc.i4.2
  IL_0002:  newobj     ""System.ValueTuple<int, int>..ctor(int, int)""
  IL_0007:  ret
}");
            });
        }

        [Fact]
        public void TupleElementNamesAttribute_NotAvailable()
        {
            var source =
@"namespace System
{
    public struct ValueTuple<T1, T2>
    {
        public T1 Item1;
        public T2 Item2;
        public ValueTuple(T1 _1, T2 _2)
        {
            Item1 = _1;
            Item2 = _2;
        }
    }
}
class C
{
    static void M()
    {
        (int, int) o;
    }
}";
            var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
            WithRuntimeInstance(comp, runtime =>
            {
                var context = CreateMethodContext(runtime, "C.M");
                var testData = new CompilationTestData();
                string error;
                var result = context.CompileExpression("(A: 1, B: 2)", out error, testData);
                Assert.Null(error);
                ReadOnlyCollection<byte> customTypeInfo;
                var customTypeInfoId = result.GetCustomTypeInfo(out customTypeInfo);
                Assert.Null(customTypeInfo);
                var methodData = testData.GetMethodData("<>x.<>m0");
                var method = methodData.Method;
                Assert.True(method.ReturnType.IsTupleType);
                Assert.Null(GetTupleElementNamesAttributeIfAny(method));
                methodData.VerifyIL(
@"{
  // Code size        8 (0x8)
  .maxstack  2
  .locals init (System.ValueTuple<int, int> V_0) //o
  IL_0000:  ldc.i4.1
  IL_0001:  ldc.i4.2
  IL_0002:  newobj     ""System.ValueTuple<int, int>..ctor(int, int)""
  IL_0007:  ret
}");
            });
        }

        [Fact]
        public void Local()
        {
            var source =
@"class C
{
    static void M()
    {
        (int A\u1234, int \u1234B) o = (1, 2);
    }
}";
            var comp = CreateCompilationWithMscorlib(source, new[] { ValueTupleRef }, options: TestOptions.DebugDll);
            WithRuntimeInstance(comp, runtime =>
            {
                var context = CreateMethodContext(runtime, "C.M");
                var testData = new CompilationTestData();
                var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
                string typeName;
                var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
                Assert.Equal(1, locals.Count);
                ReadOnlyCollection<byte> customTypeInfo;
                var customTypeInfoId = locals[0].GetCustomTypeInfo(out customTypeInfo);
                ReadOnlyCollection<byte> dynamicFlags;
                ReadOnlyCollection<string> tupleElementNames;
                CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
                Assert.Equal(new[] { "A\u1234", "\u1234B" }, tupleElementNames);
                var method = testData.Methods.Single().Value.Method;
                Assert.NotNull(GetTupleElementNamesAttributeIfAny(method));
                Assert.True(method.ReturnType.IsTupleType);
                VerifyLocal(testData, typeName, locals[0], "<>m0", "o", expectedILOpt:
string.Format(@"{{
  // Code size        2 (0x2)
  .maxstack  1
  .locals init ((int A{0}, int {0}B) V_0) //o
  IL_0000:  ldloc.0
  IL_0001:  ret
}}", '\u1234'));
                locals.Free();
            });
        }

        [Fact]
        public void Constant()
        {
            var source =
@"class A<T>
{
     internal class B<U>
    {
    }
}
class C
{
    static (object, object) F;
    static void M()
    {
        const A<(int, int A)>.B<(object B, object)>[] c = null;
    }
}";
            var comp = CreateCompilationWithMscorlib(source, new[] { ValueTupleRef }, options: TestOptions.DebugDll);
            WithRuntimeInstance(comp, runtime =>
            {
                var context = CreateMethodContext(runtime, "C.M");
                var testData = new CompilationTestData();
                var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
                string typeName;
                var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
                Assert.Equal(1, locals.Count);
                ReadOnlyCollection<byte> customTypeInfo;
                var customTypeInfoId = locals[0].GetCustomTypeInfo(out customTypeInfo);
                ReadOnlyCollection<byte> dynamicFlags;
                ReadOnlyCollection<string> tupleElementNames;
                CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
                Assert.Equal(new[] { null, "A", "B", null }, tupleElementNames);
                var method = (MethodSymbol)testData.Methods.Single().Value.Method;
                Assert.NotNull(GetTupleElementNamesAttributeIfAny(method));
                var returnType = method.ReturnType;
                Assert.False(returnType.IsTupleType);
                Assert.True(returnType.ContainsTuple());
                VerifyLocal(testData, typeName, locals[0], "<>m0", "c", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:
@"{
  // Code size        2 (0x2)
  .maxstack  1
  IL_0000:  ldnull
  IL_0001:  ret
}");
                locals.Free();
            });
        }

        [Fact]
        public void DeclareLocal()
        {
            var source =
@"class C
{
    static void M()
    {
        var x = (1, 2);
    }
}";
            var comp = CreateCompilationWithMscorlib(source, new[] { ValueTupleRef }, options: TestOptions.DebugDll);
            WithRuntimeInstance(comp, runtime =>
            {
                var context = CreateMethodContext(runtime, "C.M");
                var testData = new CompilationTestData();
                string error;
                ResultProperties resultProperties;
                ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
                var result = context.CompileExpression(
                    "(int A, int B) y = x;",
                    DkmEvaluationFlags.None,
                    NoAliases,
                    DebuggerDiagnosticFormatter.Instance,
                    out resultProperties,
                    out error,
                    out missingAssemblyIdentities,
                    EnsureEnglishUICulture.PreferredOrNull,
                    testData);
                Assert.Null(error);
                Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
                ReadOnlyCollection<byte> customTypeInfo;
                var customTypeInfoId = result.GetCustomTypeInfo(out customTypeInfo);
                ReadOnlyCollection<byte> dynamicFlags;
                ReadOnlyCollection<string> tupleElementNames;
                CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
                Assert.Null(tupleElementNames);
                var methodData = testData.GetMethodData("<>x.<>m0");
                var method = methodData.Method;
                Assert.Null(GetTupleElementNamesAttributeIfAny(method));
                methodData.VerifyIL(
@"{
  // Code size       60 (0x3c)
  .maxstack  6
  .locals init (System.ValueTuple<int, int> V_0) //x
  IL_0000:  ldtoken    ""System.ValueTuple<int, int>""
  IL_0005:  call       ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
  IL_000a:  ldstr      ""y""
  IL_000f:  ldstr      ""108766ce-df68-46ee-b761-0dcb7ac805f1""
  IL_0014:  newobj     ""System.Guid..ctor(string)""
  IL_0019:  ldc.i4.5
  IL_001a:  newarr     ""byte""
  IL_001f:  dup
  IL_0020:  ldtoken    ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=5 <PrivateImplementationDetails>.362A905A18EA2A18A9EB2574618C490DE8A1F5C3""
  IL_0025:  call       ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
  IL_002a:  call       ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
  IL_002f:  ldstr      ""y""
  IL_0034:  call       ""(int A, int B) Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<(int A, int B)>(string)""
  IL_0039:  ldloc.0
  IL_003a:  stind.ref
  IL_003b:  ret
}");
            });
        }

        [WorkItem(13589, "https://github.com/dotnet/roslyn/issues/13589")]
        [Fact]
        public void Alias()
        {
            var source =
@"class C
{
    static (int, int) F;
    static void M()
    {
    }
}";
            var comp = CreateCompilationWithMscorlib(source, new[] { ValueTupleRef }, options: TestOptions.DebugDll);
            WithRuntimeInstance(comp, runtime =>
            {
                var context = CreateMethodContext(
                    runtime,
                    "C.M");
                // (int A, (int, int D) B)[] t;
                var aliasElementNames = new ReadOnlyCollection<string>(new[] { "A", "B", null, "D" });
                var alias = new Alias(
                    DkmClrAliasKind.Variable,
                    "t",
                    "t",
                    "System.ValueTuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.ValueTuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51]][], System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51",
                    CustomTypeInfo.PayloadTypeId,
                    CustomTypeInfo.Encode(null, aliasElementNames));
                var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
                string typeName;
                var diagnostics = DiagnosticBag.GetInstance();
                var testData = new CompilationTestData();
                context.CompileGetLocals(
                    locals,
                    argumentsOnly: false,
                    aliases: ImmutableArray.Create(alias),
                    diagnostics: diagnostics,
                    typeName: out typeName,
                    testData: testData);
                diagnostics.Verify();
                diagnostics.Free();
                Assert.Equal(locals.Count, 1);
                ReadOnlyCollection<byte> customTypeInfo;
                var customTypeInfoId = locals[0].GetCustomTypeInfo(out customTypeInfo);
                ReadOnlyCollection<byte> dynamicFlags;
                ReadOnlyCollection<string> tupleElementNames;
                CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
                Assert.Equal(aliasElementNames, tupleElementNames);
                var method = testData.Methods.Single().Value.Method;
                Assert.NotNull(GetTupleElementNamesAttributeIfAny(method));
                var returnType = (TypeSymbol)method.ReturnType;
                Assert.False(returnType.IsTupleType);
                Assert.True(((ArrayTypeSymbol)returnType).ElementType.IsTupleType);
                VerifyLocal(testData, typeName, locals[0], "<>m0", "t", expectedILOpt:
@"{
  // Code size       16 (0x10)
  .maxstack  1
  IL_0000:  ldstr      ""t""
  IL_0005:  call       ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
  IL_000a:  castclass  ""(int A, (int, int D) B)[]""
  IL_000f:  ret
}");
                locals.Free();
            });
        }
    }
}