/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*-
 *
 *  Copyright (C) 2006  James Livingston  <doclivingston@gmail.com>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  The Rhythmbox authors hereby grant permission for non-GPL compatible
 *  GStreamer plugins to be used and distributed together with GStreamer
 *  and Rhythmbox. This permission is above and beyond the permissions granted
 *  by the GPL license by which Rhythmbox is covered. If you modify this code
 *  you may extend this exception to your version of the code, but you are not
 *  obligated to do so. If you do not wish to do so, delete this exception
 *  statement from your version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <config.h>

#include "rb-player.h"
#include "rb-player-gst.h"
#include "rb-player-gst-xfade.h"
#include "rb-util.h"

/**
 * RBPlayerPlayType:
 * @RB_PLAYER_PLAY_REPLACE: Replace the existing stream
 * @RB_PLAYER_PLAY_AFTER_EOS: Start the new stream after the current stream ends
 * @RB_PLAYER_PLAY_CROSSFADE: Crossfade between the existing stream and the new stream
 */

/**
 * RBPlayerError:
 * @RB_PLAYER_ERROR_NO_AUDIO: Audio playback not available
 * @RB_PLAYER_ERROR_GENERAL: Nonspecific error
 * @RB_PLAYER_ERROR_INTERNAL: Internal error
 * @RB_PLAYER_ERROR_NOT_FOUND: The resource could not be found
 */

/* Signals */
enum {
	EOS,
	INFO,
	BUFFERING,
	ERROR,
	TICK,
	EVENT,
	PLAYING_STREAM,
	VOLUME_CHANGED,
	IMAGE,
	REDIRECT,
	LAST_SIGNAL
};

static guint signals[LAST_SIGNAL] = { 0 };

/**
 * SECTION:rb-player
 * @short_description: playback backend interface
 * @include: rb-player.h
 *
 * This is the interface implemented by the rhythmbox playback backends.
 * It allows the caller to control playback (open, play, pause, close),
 * seek (set_time), control volume (get_volume, set_volume)
 * and receive playback state information (get_time, various signals).
 *
 * The playback interface allows for multiple streams to be playing (or at
 * least open) concurrently. The caller associates some data with each stream
 * it opens (#rb_player_open), which is included in the paramters with each
 * signal emitted. The caller should not assume that the new stream is playing
 * immediately upon returning from #rb_player_play. Instead, it should use
 * the 'playing-stream' signal to determine that.
 *
 * The player implementation should emit signals for metadata extracted from the
 * stream using the 'info' signal
 *
 * While playing, the player implementation should emit 'tick' signals frequently
 * enough to update an elapsed/remaining time display consistently.  The duration
 * value included in tick signal emissions is used to prepare the next stream before
 * the current stream reaches EOS, so it should be updated for each emission to account
 * for variable bitrate streams that produce inaccurate duration estimates early on.
 *
 * When playing a stream from the network, the player can report buffering status
 * using the 'buffering' signal.  The value included in the signal indicates the
 * percentage of the buffer that has been filled.
 *
 * The 'event' signal can be used to communicate events from the player to the application.
 * For GStreamer-based player implementations, events are triggered by elements in the
 * pipeline posting application messages.  The name of the message becomes the name of the
 * event.
 */

static void
rb_player_interface_init (RBPlayerIface *iface)
{
	/**
	 * RBPlayer::eos:
	 * @player: the #RBPlayer
	 * @stream_data: the data associated with the stream that finished
	 * @early: if %TRUE, the EOS notification should only be used for track changes.
	 *
	 * The 'eos' signal is emitted when a stream finishes, or in some cases, when it
	 * is about to finish (with @early set to %TRUE) to allow for a new track to be
	 * played immediately afterwards.
	 **/
	signals[EOS] =
		g_signal_new ("eos",
			      G_TYPE_FROM_INTERFACE (iface),
			      G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE,
			      G_STRUCT_OFFSET (RBPlayerIface, eos),
			      NULL, NULL,
			      NULL,
			      G_TYPE_NONE,
			      2, G_TYPE_POINTER, G_TYPE_BOOLEAN);

	/**
	 * RBPlayer::info:
	 * @player: the #RBPlayer
	 * @stream_data: the data associated with the stream
	 * @field: the #RBMetaDataField corresponding to the stream info
	 * @value: the value of the stream info field
	 *
	 * The 'info' signal is emitted when a metadata value is found in
	 * the stream.
	 **/
	signals[INFO] =
		g_signal_new ("info",
			      G_TYPE_FROM_INTERFACE (iface),
			      G_SIGNAL_RUN_LAST,
			      G_STRUCT_OFFSET (RBPlayerIface, info),
			      NULL, NULL,
			      NULL,
			      G_TYPE_NONE,
			      3, G_TYPE_POINTER, G_TYPE_INT, G_TYPE_VALUE);

	/**
	 * RBPlayer::error:
	 * @player: the #RBPlayer
	 * @stream_data: the data associated with the stream
	 * @error: description of the error
	 *
	 * The 'error' signal is emitted when an error is encountered
	 * while opening or playing a stream.
	 **/
	signals[ERROR] =
		g_signal_new ("error",
			      G_TYPE_FROM_INTERFACE (iface),
			      G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE,
			      G_STRUCT_OFFSET (RBPlayerIface, error),
			      NULL, NULL,
			      NULL,
			      G_TYPE_NONE,
			      2,
			      G_TYPE_POINTER, G_TYPE_POINTER);

	/**
	 * RBPlayer::tick:
	 * @player: the #RBPlayer
	 * @stream_data: the data associated with the stream
	 * @elapsed: playback position in the stream (in nanoseconds)
	 * @duration: current estimate of the duration of the stream
	 *  (in nanoseconds)
	 *
	 * The 'tick' signal is emitted repeatedly while the stream is
	 * playing. Signal handlers can use this to update UI and to
	 * prepare new streams for crossfade or gapless playback.
	 **/
	signals[TICK] =
		g_signal_new ("tick",
			      G_TYPE_FROM_INTERFACE (iface),
			      G_SIGNAL_RUN_LAST,
			      G_STRUCT_OFFSET (RBPlayerIface, tick),
			      NULL, NULL, NULL,
			      G_TYPE_NONE,
			      3,
			      G_TYPE_POINTER, G_TYPE_INT64, G_TYPE_INT64);

	/**
	 * RBPlayer::buffering:
	 * @player: the #RBPlayer
	 * @stream_data: the data associated with the buffering stream
	 * @progress: buffering percentage
	 *
	 * The 'buffering' signal is emitted while a stream is paused so
	 * that a buffer can be filled.  The progress value typically varies
	 * from 0 to 100, and once it reaches 100, playback resumes.
	 **/
	signals[BUFFERING] =
		g_signal_new ("buffering",
			      G_TYPE_FROM_INTERFACE (iface),
			      G_SIGNAL_RUN_LAST,
			      G_STRUCT_OFFSET (RBPlayerIface, buffering),
			      NULL, NULL,
			      NULL,
			      G_TYPE_NONE,
			      2,
			      G_TYPE_POINTER, G_TYPE_UINT);

	/**
	 * RBPlayer::event:
	 * @player: the #RBPlayer
	 * @stream_data: data associated with the stream
	 * @data: event data
	 *
	 * The 'event' signal provides a means for custom GStreamer
	 * elements to communicate events back to the rest of the
	 * application.  The GStreamer element posts an application
	 * message on the GStreamer bus, which is translated into an
	 * event signal with the detail of the signal set to the name
	 * of the structure found in the message.
	 */
	signals[EVENT] =
		g_signal_new ("event",
			      G_TYPE_FROM_INTERFACE (iface),
			      G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
			      G_STRUCT_OFFSET (RBPlayerIface, event),
			      NULL, NULL,
			      NULL,
			      G_TYPE_NONE,
			      2,
			      G_TYPE_POINTER, G_TYPE_POINTER);

	/**
	 * RBPlayer::playing-stream:
	 * @player: the #RBPlayer
	 * @stream_data: data associated with the stream
	 *
	 * The 'playing-stream' signal is emitted when the main playing stream
	 * changes. It should be used to update the UI to show the new
	 * stream. It can either be emitted before or after #rb_player_play returns,
	 * depending on the player backend.
	 */
	signals[PLAYING_STREAM] =
		g_signal_new ("playing-stream",
			      G_TYPE_FROM_INTERFACE (iface),
			      G_SIGNAL_RUN_LAST,
			      G_STRUCT_OFFSET (RBPlayerIface, playing_stream),
			      NULL, NULL,
			      NULL,
			      G_TYPE_NONE,
			      1,
			      G_TYPE_POINTER);
	/**
	 * RBPlayer::volume-changed:
	 * @player: the #RBPlayer
	 * @volume: the new volume level
	 *
	 * The 'volume-changed' signal is emitted when the output stream volume is
	 * changed externally.
	 */
	signals[VOLUME_CHANGED] =
		g_signal_new ("volume-changed",
			      G_TYPE_FROM_INTERFACE (iface),
			      G_SIGNAL_RUN_LAST,
			      G_STRUCT_OFFSET (RBPlayerIface, volume_changed),
			      NULL, NULL,
			      NULL,
			      G_TYPE_NONE,
			      1,
			      G_TYPE_FLOAT);

	/**
	 * RBPlayer::image:
	 * @player: the #RBPlayer
	 * @stream_data: data associated with the stream
	 * @image: the image extracted from the stream
	 *
	 * The 'image' signal is emitted to provide access to images extracted
	 * from the stream.
	 */
	signals[IMAGE] =
		g_signal_new ("image",
			      G_TYPE_FROM_INTERFACE (iface),
			      G_SIGNAL_RUN_LAST,
			      G_STRUCT_OFFSET (RBPlayerIface, image),
			      NULL, NULL,
			      NULL,
			      G_TYPE_NONE,
			      2,
			      G_TYPE_POINTER, GDK_TYPE_PIXBUF);

	/**
	 * RBPlayer::redirect:
	 * @player: the #RBPlayer
	 * @stream_data: data associated with the stream
	 * @uri: URI to redirect to
	 *
	 * The 'redirect' signal is emitted to indicate when a stream has change URI.
	 */
	signals[REDIRECT] =
		g_signal_new ("redirect",
			      G_TYPE_FROM_INTERFACE (iface),
			      G_SIGNAL_RUN_LAST,
			      G_STRUCT_OFFSET (RBPlayerIface, redirect),
			      NULL, NULL,
			      NULL,
			      G_TYPE_NONE,
			      2,
			      G_TYPE_POINTER, G_TYPE_STRING);
}

GType
rb_player_get_type (void)
{
	static GType our_type = 0;

	if (!our_type) {
		static const GTypeInfo our_info = {
			sizeof (RBPlayerIface),
			NULL,	/* base_init */
			NULL,	/* base_finalize */
			(GClassInitFunc)rb_player_interface_init,
			NULL,	/* class_finalize */
			NULL,	/* class_data */
			0,
			0,
			NULL
		};

		our_type = g_type_register_static (G_TYPE_INTERFACE, "RBPlayer", &our_info, 0);
	}

	return our_type;
}

/**
 * rb_player_open:
 * @player:	a #RBPlayer
 * @uri:	URI to open
 * @stream_data: arbitrary data to associate with the stream
 * @stream_data_destroy: function to call to destroy the stream data
 * @error:	returns error information
 *
 * Prepares a stream for playback.  Depending on the player
 * implementation, this may stop any existing stream being
 * played.  The stream preparation process may continue
 * asynchronously, in which case errors may be reported from
 * #rb_player_play or using the 'error' signal.
 *
 * Return value: TRUE if the stream preparation was not unsuccessful
 */
gboolean
rb_player_open (RBPlayer *player, const char *uri, gpointer stream_data, GDestroyNotify stream_data_destroy, GError **error)
{
	RBPlayerIface *iface = RB_PLAYER_GET_IFACE (player);

	return iface->open (player, uri, stream_data, stream_data_destroy, error);
}

/**
 * rb_player_opened:
 * @player: 	a #RBPlayer
 *
 * Determines whether a stream has been prepared for playback.
 *
 * Return value: TRUE if a stream is prepared for playback
 */
gboolean
rb_player_opened (RBPlayer *player)
{
	RBPlayerIface *iface = RB_PLAYER_GET_IFACE (player);

	return iface->opened (player);
}

/**
 * rb_player_close:
 * @player:	a #RBPlayer
 * @uri:	optionally, the URI of the stream to close
 * @error:	returns error information
 *
 * If a URI is specified, this will close the stream corresponding
 * to that URI and free any resources related resources.  If @uri
 * is NULL, this will close all streams.
 *
 * If no streams remain open after this call, the audio device will
 * be released.
 *
 * Return value: TRUE if a stream was found and closed
 */
gboolean
rb_player_close (RBPlayer *player, const char *uri, GError **error)
{
	RBPlayerIface *iface = RB_PLAYER_GET_IFACE (player);

	return iface->close (player, uri, error);
}

/**
 * rb_player_play:
 * @player:	a #RBPlayer
 * @play_type:  requested playback start type
 * @crossfade:	requested crossfade duration (nanoseconds)
 * @error:	returns error information
 *
 * Starts playback of the most recently opened stream.
 * if @play_type is #RB_PLAYER_PLAY_CROSSFADE, the player
 * may attempt to crossfade the new stream with any existing
 * streams.  If it does this, the it will use @crossfade as the
 * duration of the fade.
 *
 * If @play_type is #RB_PLAYER_PLAY_AFTER_EOS, the player may
 * attempt to start the stream immediately after the current
 * playing stream reaches EOS.  This may or may not result in
 * the phenomemon known as 'gapless playback'.
 *
 * If @play_type is #RB_PLAYER_PLAY_REPLACE, the player will stop any
 * existing stream before starting the new stream. It may do
 * this anyway, regardless of the value of @play_type.
 *
 * The 'playing-stream' signal will be emitted when the new stream
 * is actually playing. This may be before or after control returns
 * to the caller.
 *
 * Return value: %TRUE if playback started successfully
 */
gboolean
rb_player_play (RBPlayer *player, RBPlayerPlayType play_type, gint64 crossfade, GError **error)
{
	RBPlayerIface *iface = RB_PLAYER_GET_IFACE (player);

	return iface->play (player, play_type, crossfade, error);
}

/**
 * rb_player_pause:
 * @player:	a #RBPlayer
 *
 * Pauses playback of the most recently started stream.  Any
 * streams being faded out may continue until the fade is
 * complete.
 */
void
rb_player_pause (RBPlayer *player)
{
	RBPlayerIface *iface = RB_PLAYER_GET_IFACE (player);

	iface->pause (player);
}

/**
 * rb_player_playing:
 * @player:	a #RBPlayer.
 *
 * Determines whether the player is currently playing a stream.
 * A stream is playing if it's not paused or being faded out.
 *
 * Return value: TRUE if playing
 */
gboolean
rb_player_playing (RBPlayer *player)
{
	RBPlayerIface *iface = RB_PLAYER_GET_IFACE (player);

	return iface->playing (player);
}

/**
 * rb_player_set_volume:
 * @player:	a #RBPlayer
 * @volume:	new output volume level
 *
 * Adjusts the output volume level.  This affects all streams.
 * The player may use a hardware volume control to implement
 * this volume adjustment.
 */
void
rb_player_set_volume (RBPlayer *player, float volume)
{
	RBPlayerIface *iface = RB_PLAYER_GET_IFACE (player);

	iface->set_volume (player, volume);
}

/**
 * rb_player_get_volume:
 * @player:	a #RBPlayer
 *
 * Returns the current volume level, between 0.0 and 1.0.
 *
 * Return value: current output volume level
 */
float
rb_player_get_volume (RBPlayer *player)
{
	RBPlayerIface *iface = RB_PLAYER_GET_IFACE (player);

	return iface->get_volume (player);
}

/**
 * rb_player_seekable:
 * @player:	a #RBPlayer
 *
 * Determines whether seeking is supported for the current stream.
 *
 * Return value: TRUE if the current stream is seekable
 */
gboolean
rb_player_seekable (RBPlayer *player)
{
	RBPlayerIface *iface = RB_PLAYER_GET_IFACE (player);

	return iface->seekable (player);
}

/**
 * rb_player_set_time:
 * @player:	a #RBPlayer
 * @newtime:	seek target position in seconds
 *
 * Attempts to seek in the current stream.  The player
 * may ignore this if the stream is not seekable.
 * The seek may take place asynchronously.
 */
void
rb_player_set_time (RBPlayer *player, gint64 newtime)
{
	RBPlayerIface *iface = RB_PLAYER_GET_IFACE (player);

	iface->set_time (player, newtime);
}

/**
 * rb_player_get_time:
 * @player:	a #RBPlayer
 *
 * Returns the current playback for the current stream in nanoseconds.
 *
 * Return value: playback position
 */
gint64
rb_player_get_time (RBPlayer *player)
{
	RBPlayerIface *iface = RB_PLAYER_GET_IFACE (player);

	return iface->get_time (player);
}

/**
 * rb_player_multiple_open:
 * @player:	a #RBPlayer
 *
 * Determines whether the player supports multiple open streams.
 *
 * Return value: TRUE if multiple open is supported
 */
gboolean
rb_player_multiple_open (RBPlayer *player)
{
	RBPlayerIface *iface = RB_PLAYER_GET_IFACE (player);

	if (iface->multiple_open)
		return iface->multiple_open (player);
	else
		return FALSE;
}

/**
 * rb_player_new:
 * @want_crossfade: if TRUE, try to use a backend that supports
 * 		    crossfading and other track transitions.
 * @error:	returns error information
 *
 * Creates a new player object.
 *
 * Return value: (transfer full): new player object.
 */
RBPlayer*
rb_player_new (gboolean want_crossfade, GError **error)
{
	if (want_crossfade)
		return rb_player_gst_xfade_new (error);
	else
		return rb_player_gst_new (error);
}

/**
 * _rb_player_emit_eos:
 * @player: a #RBPlayer implementation
 * @stream_data: data associated with the stream
 * @early: whether this is an early EOS notification
 *
 * Emits the 'eos' signal for a stream.  To be used by
 * implementations only.
 */
void
_rb_player_emit_eos (RBPlayer *player, gpointer stream_data, gboolean early)
{
	g_assert (rb_is_main_thread ());
	g_signal_emit (player, signals[EOS], 0, stream_data, early);
}

/**
 * _rb_player_emit_info:
 * @player: a #RBPlayer implementation
 * @stream_data: data associated with the stream
 * @field: updated metadata field
 * @value: metadata field value
 *
 * Emits the 'info' signal for a stream.  To be used by
 * implementations only.
 */
void
_rb_player_emit_info (RBPlayer *player,
		      gpointer stream_data,
		      RBMetaDataField field,
		      GValue *value)
{
	g_assert (rb_is_main_thread ());
	g_signal_emit (player, signals[INFO], 0, stream_data, field, value);
}

/**
 * _rb_player_emit_buffering:
 * @player: a #RBPlayer implementation
 * @stream_data: data associated with the stream
 * @progress: current buffering progress.
 *
 * Emits the 'buffering' signal for a stream.
 * To be used by implementations only.
 */
void
_rb_player_emit_buffering (RBPlayer *player, gpointer stream_data, guint progress)
{
	g_assert (rb_is_main_thread ());
	g_signal_emit (player, signals[BUFFERING], 0, stream_data, progress);
}

/**
 * _rb_player_emit_error:
 * @player: a #RBPlayer implementation
 * @stream_data: data associated with the stream
 * @error: playback error
 *
 * Emits the 'error' signal for a stream.
 * To be used by implementations only.
 */
void
_rb_player_emit_error (RBPlayer *player, gpointer stream_data, GError *error)
{
	g_assert (rb_is_main_thread ());
	g_signal_emit (player, signals[ERROR], 0, stream_data, error);
}

/**
 * _rb_player_emit_tick:
 * @player: a #RBPlayer implementation
 * @stream_data: data associated with the stream
 * @elapsed: current playback position
 * @duration: current perception of the duration of the stream (-1 if not applicable)
 *
 * Emits the 'tick' signal for a stream.
 * To be used by implementations only.
 */
void
_rb_player_emit_tick (RBPlayer *player, gpointer stream_data, gint64 elapsed, gint64 duration)
{
	g_assert (rb_is_main_thread ());
	g_signal_emit (player, signals[TICK], 0, stream_data, elapsed, duration);
}

/**
 * _rb_player_emit_event:
 * @player: a #RBPlayer implementation
 * @stream_data: data associated with the stream
 * @name: event name
 * @data: event data
 *
 * Emits the 'event' signal for a stream.
 * To be used by implementations only.
 */
void
_rb_player_emit_event (RBPlayer *player, gpointer stream_data, const char *name, gpointer data)
{
	g_assert (rb_is_main_thread ());
	g_signal_emit (player, signals[EVENT], g_quark_from_string (name), stream_data, data);
}

/**
 * _rb_player_emit_playing_stream:
 * @player: a #RBPlayer implementation
 * @stream_data: data associated with the new playing stream
 *
 * Emits the 'playing-stream' signal to indicate the current
 * playing stream has changed.  To be used by implementations only.
 */
void
_rb_player_emit_playing_stream (RBPlayer *player, gpointer stream_data)
{
	g_assert (rb_is_main_thread ());
	g_signal_emit (player, signals[PLAYING_STREAM], 0, stream_data);
}

/**
 * _rb_player_emit_volume_changed:
 * @player: a #RBPlayer implementation
 * @volume: the new volume level
 *
 * Emits the 'volume-changed' signal to indicate the output stream
 * volume has been changed.  To be used by implementations only.
 */
void
_rb_player_emit_volume_changed (RBPlayer *player, float volume)
{
	g_assert (rb_is_main_thread ());
	g_signal_emit (player, signals[VOLUME_CHANGED], 0, volume);
}

/**
 * _rb_player_emit_image:
 * @player: a #RBPlayer implementation
 * @stream_data: data associated with the stream
 * @image: an image extracted from the stream
 *
 * Emits the 'image' signal to notify listeners of an image that
 * has been extracted from the stream.  To be used by implementations only.
 */
void
_rb_player_emit_image (RBPlayer *player, gpointer stream_data, GdkPixbuf *image)
{
	g_assert (rb_is_main_thread ());
	g_signal_emit (player, signals[IMAGE], 0, stream_data, image);
}

/**
 * _rb_player_emit_redirect:
 * @player: a #RBPlayer implementation
 * @stream_data: data associated with the stream
 * @uri: URI to redirect to
 *
 * Emits the 'redirect' signal to notify listeners that the stream has been
 * redirected. To be used by implementations only.
 */
void
_rb_player_emit_redirect (RBPlayer *player, gpointer stream_data, const char *uri)
{
	g_assert (rb_is_main_thread ());
	g_signal_emit (player, signals[REDIRECT], 0, stream_data, uri);
}

GQuark
rb_player_error_quark (void)
{
	static GQuark quark = 0;
	if (!quark)
		quark = g_quark_from_static_string ("rb_player_error");

	return quark;
}

/* This should really be standard. */
#define ENUM_ENTRY(NAME, DESC) { NAME, "" #NAME "", DESC }

GType
rb_player_error_get_type (void)
{
	static GType etype = 0;

	if (etype == 0)	{
		static const GEnumValue values[] = {
			ENUM_ENTRY (RB_PLAYER_ERROR_NO_AUDIO, "no-audio"),
			ENUM_ENTRY (RB_PLAYER_ERROR_GENERAL, "general-error"),
			ENUM_ENTRY (RB_PLAYER_ERROR_INTERNAL, "internal-error"),
			ENUM_ENTRY (RB_PLAYER_ERROR_NOT_FOUND, "not-found"),
			{ 0, 0, 0 }
		};

		etype = g_enum_register_static ("RBPlayerError", values);
	}

	return etype;
}

GType
rb_player_play_type_get_type (void)
{
	static GType etype = 0;

	if (etype == 0)	{
		static const GEnumValue values[] = {
			ENUM_ENTRY (RB_PLAYER_PLAY_REPLACE, "replace"),
			ENUM_ENTRY (RB_PLAYER_PLAY_AFTER_EOS, "start-after-eos"),
			ENUM_ENTRY (RB_PLAYER_PLAY_CROSSFADE, "crossfade"),
			{ 0, 0, 0 }
		};

		etype = g_enum_register_static ("RBPlayerPlayType", values);
	}

	return etype;
}

{'repo_name': 'GNOME/rhythmbox', 'stars': '138', 'repo_language': 'C', 'file_name': 'Makefile.am', 'mime_type': 'text/plain', 'hash': -8024512095112696432, 'source_dataset': 'data'}


detectron2.utils package
========================

detectron2.utils.colormap module
--------------------------------

.. automodule:: detectron2.utils.colormap
    :members:
    :undoc-members:
    :show-inheritance:

detectron2.utils.comm module
----------------------------

.. automodule:: detectron2.utils.comm
    :members:
    :undoc-members:
    :show-inheritance:

detectron2.utils.events module
------------------------------

.. automodule:: detectron2.utils.events
    :members:
    :undoc-members:
    :show-inheritance:

detectron2.utils.logger module
------------------------------

.. automodule:: detectron2.utils.logger
    :members:
    :undoc-members:
    :show-inheritance:

detectron2.utils.registry module
--------------------------------

.. automodule:: detectron2.utils.registry
    :members:
    :undoc-members:
    :show-inheritance:

detectron2.utils.video\_visualizer module
-----------------------------------------

.. automodule:: detectron2.utils.video_visualizer
    :members:
    :undoc-members:
    :show-inheritance:

detectron2.utils.visualizer module
----------------------------------

.. automodule:: detectron2.utils.visualizer
    :members:
    :undoc-members:
    :show-inheritance:

{'repo_name': 'conansherry/detectron2', 'stars': '118', 'repo_language': 'Python', 'file_name': 'test_boxes.py', 'mime_type': 'text/x-python', 'hash': -4084974527125206375, 'source_dataset': 'data'}


#include_next <pthread.h>

#ifndef _ISOMAC
/* Prototypes repeated instead of using __typeof because pthread.h is
   included in C++ tests, and declaring functions with __typeof and
   __THROW doesn't work for C++.  */
extern int __pthread_barrier_init (pthread_barrier_t *__restrict __barrier,
				 const pthread_barrierattr_t *__restrict
				 __attr, unsigned int __count)
     __THROW __nonnull ((1));
extern int __pthread_barrier_wait (pthread_barrier_t *__barrier)
     __THROWNL __nonnull ((1));

/* This function is called to initialize the pthread library.  */
extern void __pthread_initialize (void) __attribute__ ((weak));
#endif

{'repo_name': 'bminor/glibc', 'stars': '400', 'repo_language': 'C', 'file_name': 'check_fds.c', 'mime_type': 'text/x-c', 'hash': -3713693958595108752, 'source_dataset': 'data'}


"use strict";

var isValidFormat = RegExp.prototype.test.bind(/^[a-z0-9]+$/);

module.exports = function (t, a) {
	a(typeof t(), "string");
	a.ok(t().length > 7);
	a.not(t({ isUnique: true }), t({ isUnique: true }));
	a.ok(isValidFormat(t()));
	a(t({ length: 1 }).length, 1);
	a(t({ length: 100 }).length, 100);
	a(t({ length: 0 }), "");
};

{'repo_name': 'pythonzhichan/django-beginners-guide', 'stars': '216', 'repo_language': 'HTML', 'file_name': 'profiles_settings.xml', 'mime_type': 'text/plain', 'hash': 7346837871664976659, 'source_dataset': 'data'}


/*******************************************************************************
 * Copyright (c) 2019 Eclipse RDF4J contributors.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Distribution License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/org/documents/edl-v10.php.
 *******************************************************************************/
package org.eclipse.rdf4j.federated.server;

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

import org.eclipse.rdf4j.federated.endpoint.Endpoint;
import org.eclipse.rdf4j.federated.endpoint.EndpointFactory;
import org.eclipse.rdf4j.federated.repository.ConfigurableSailRepository;
import org.eclipse.rdf4j.federated.repository.ConfigurableSailRepositoryFactory;
import org.eclipse.rdf4j.http.protocol.Protocol;
import org.eclipse.rdf4j.repository.RepositoryException;
import org.eclipse.rdf4j.repository.RepositoryResolver;
import org.eclipse.rdf4j.repository.config.RepositoryConfig;
import org.eclipse.rdf4j.repository.config.RepositoryConfigException;
import org.eclipse.rdf4j.repository.http.HTTPRepository;
import org.eclipse.rdf4j.repository.manager.RemoteRepositoryManager;
import org.eclipse.rdf4j.repository.sail.config.SailRepositoryConfig;
import org.eclipse.rdf4j.sail.memory.config.MemoryStoreConfig;

/**
 * An embedded http server for SPARQL query testing. Initializes a memory store repository for each specified
 * reposiotoryId.
 *
 * @author Andreas Schwarte
 */
public class SPARQLEmbeddedServer extends EmbeddedServer implements Server {

	protected final List<String> repositoryIds;
	// flag to indicate whether a remote repository or SPARQL repository endpoint shall be used
	private final boolean useRemoteRepositoryEndpoint;

	/**
	 * The {@link RepositoryResolver} supplied at runtime by {@link FedXRepositoryResolverBean}
	 */
	private RepositoryResolver repositoryResolver;
	/**
	 * The data directory populated at runtime
	 */
	private final File dataDir;

	/**
	 * @param repositoryIds
	 */
	public SPARQLEmbeddedServer(File dataDir, List<String> repositoryIds, boolean useRemoteRepositoryEndpoint) {
		super();
		this.dataDir = dataDir;
		this.repositoryIds = repositoryIds;
		this.useRemoteRepositoryEndpoint = useRemoteRepositoryEndpoint;
	}

	/**
	 * @return the url to the repository with given id
	 */
	public String getRepositoryUrl(String repoId) {
		return Protocol.getRepositoryLocation(getServerUrl(), repoId);
	}

	/**
	 * @return the server url
	 */
	public String getServerUrl() {
		return "http://" + HOST + ":" + PORT + CONTEXT_PATH;
	}

	@Override
	public void start()
			throws Exception {
		System.setProperty("org.eclipse.rdf4j.appdata.basedir", dataDir.getAbsolutePath());

		super.start();

		repositoryResolver = FedXRepositoryResolverBean.getRepositoryResolver();

		createTestRepositories();
	}

	@Override
	public void stop()
			throws Exception {
		RemoteRepositoryManager repoManager = RemoteRepositoryManager.getInstance(getServerUrl());
		try {
			repoManager.init();
			for (String repId : repositoryIds) {
				repoManager.removeRepository(repId);
			}
		} finally {
			repoManager.shutDown();
		}

		super.stop();
	}

	/**
	 * @throws RepositoryException
	 */
	private void createTestRepositories()
			throws RepositoryException, RepositoryConfigException {

		RemoteRepositoryManager repoManager = RemoteRepositoryManager.getInstance(getServerUrl());
		try {
			repoManager.init();

			// create a memory store for each provided repository id
			for (String repId : repositoryIds) {
				MemoryStoreConfig memStoreConfig = new MemoryStoreConfig();
				SailRepositoryConfig sailRepConfig = new ConfigurableSailRepositoryFactory.ConfigurableSailRepositoryConfig(
						memStoreConfig);
				RepositoryConfig repConfig = new RepositoryConfig(repId, sailRepConfig);

				repoManager.addRepositoryConfig(repConfig);
			}
		} finally {
			repoManager.shutDown();
		}

	}

	@Override
	public void initialize(int nRepositories) throws Exception {
		try {
			start();
		} catch (Exception e) {
			stop();
			throw e;
		}

		for (int i = 1; i <= nRepositories; i++) {
			HTTPRepository r = new HTTPRepository(getRepositoryUrl("endpoint" + i));
			r.init();
			r.shutDown();
		}
	}

	@Override
	public void shutdown() throws Exception {
		stop();
	}

	@Override
	public Endpoint loadEndpoint(int i) throws Exception {
		return useRemoteRepositoryEndpoint ? EndpointFactory.loadRemoteRepository(getServerUrl(), "endpoint" + i)
				: EndpointFactory.loadSPARQLEndpoint("http://endpoint" + i, getRepositoryUrl("endpoint" + i));
	}

	/**
	 *
	 * @param i the index of the repository, starting with 1
	 * @return the repository
	 */
	@Override
	public ConfigurableSailRepository getRepository(int i) {
		String repositoryId = repositoryIds.get(i - 1);
		return (ConfigurableSailRepository) repositoryResolver.getRepository(repositoryId);
	}

	public File getDataDir() {
		return dataDir;
	}

	public RepositoryResolver getRepositoryResolver() {
		return repositoryResolver;
	}
}

{'repo_name': 'eclipse/rdf4j', 'stars': '209', 'repo_language': 'Java', 'file_name': 'package-use.html', 'mime_type': 'text/html', 'hash': -3325709953638628730, 'source_dataset': 'data'}


/*
 * This program source code file is part of KiCad, a free EDA CAD application.
 *
 * Copyright (C) 2004 Jean-Pierre Charras, jaen-pierre.charras@gipsa-lab.inpg.com
 * Copyright (C) 2004-2020 KiCad Developers, see change_log.txt for contributors.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, you may find one here:
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * or you may search the http://www.gnu.org website for the version 2 license,
 * or you may write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

#ifndef LIB_TEXT_H
#define LIB_TEXT_H

#include <eda_text.h>
#include <lib_item.h>

/**
 * Define a symbol library graphical text item.
 * <p>
 * This is only a graphical text item.  Field text like the reference designator,
 * symbol value, etc. are not LIB_TEXT items.  See the #LIB_FIELD class for the
 * field item definition.
 * </p>
 */
class LIB_TEXT : public LIB_ITEM, public EDA_TEXT
{
    void print( RENDER_SETTINGS* aSettings, const wxPoint& aOffset, void* aData,
                const TRANSFORM& aTransform ) override;

public:
    LIB_TEXT( LIB_PART* aParent );

    // Do not create a copy constructor.  The one generated by the compiler is adequate.

    ~LIB_TEXT() { }

    wxString GetClass() const override
    {
        return wxT( "LIB_TEXT" );
    }

    wxString GetTypeName() override
    {
        return _( "Text" );
    }

    void ViewGetLayers( int aLayers[], int& aCount ) const override;

    bool HitTest( const wxPoint& aPosition, int aAccuracy = 0 ) const override;

    bool HitTest( const EDA_RECT& aRect, bool aContained, int aAccuracy = 0 ) const override
    {
        return TextHitTest( aRect, aContained, aAccuracy );
    }

    int GetPenWidth() const override;

    void GetMsgPanelInfo( EDA_DRAW_FRAME* aFrame, std::vector<MSG_PANEL_ITEM>& aList ) override;

    const EDA_RECT GetBoundingBox() const override;

    void BeginEdit( const wxPoint aStartPoint ) override;
    void CalcEdit( const wxPoint& aPosition ) override;

    void Offset( const wxPoint& aOffset ) override;

    void MoveTo( const wxPoint& aPosition ) override;

    wxPoint GetPosition() const override { return EDA_TEXT::GetTextPos(); }

    void MirrorHorizontal( const wxPoint& aCenter ) override;
    void MirrorVertical( const wxPoint& aCenter ) override;
    void Rotate( const wxPoint& aCenter, bool aRotateCCW = true ) override;

    void NormalizeJustification( bool inverse );

    void Plot( PLOTTER* aPlotter, const wxPoint& aOffset, bool aFill,
               const TRANSFORM& aTransform ) override;

    int GetWidth() const override { return GetTextThickness(); }
    void SetWidth( int aWidth ) override { SetTextThickness( aWidth ); }

    wxString GetSelectMenuText( EDA_UNITS aUnits ) const override;

    BITMAP_DEF GetMenuImage() const override;

    EDA_ITEM* Clone() const override;

private:

    /**
     * @copydoc LIB_ITEM::compare()
     *
     * The text specific sort order is as follows:
     *      - Text string, case insensitive compare.
     *      - Text horizontal (X) position.
     *      - Text vertical (Y) position.
     *      - Text width.
     *      - Text height.
     */
    int compare( const LIB_ITEM& aOther,
            LIB_ITEM::COMPARE_FLAGS aCompareFlags = LIB_ITEM::COMPARE_FLAGS::NORMAL ) const override;
};

#endif    // LIB_TEXT_H

{'repo_name': 'KiCad/kicad-source-mirror', 'stars': '802', 'repo_language': 'C', 'file_name': 'complex_hierarchy.kicad_pro', 'mime_type': 'text/plain', 'hash': -71127878823818457, 'source_dataset': 'data'}


//====== Copyright © 1996-2007, Valve Corporation, All rights reserved. ===========================

// STATIC: "FLASHLIGHT"					"0..1"
// STATIC: "LIGHTWARPTEXTURE"			"0..1"

// STATIC: "SPHERETEXKILLCOMBO"			"0..1"					[ps20b]
// STATIC: "SPHERETEXKILLCOMBO"			"0..1"					[ps30]

// STATIC: "RAYTRACESPHERE"				"0..1"					[ps20b]
// STATIC: "RAYTRACESPHERE"				"0..1"					[ps30]

// STATIC: "FLASHLIGHTDEPTHFILTERMODE"	"0..2"					[ps20b] [PC]
// STATIC: "FLASHLIGHTDEPTHFILTERMODE"	"0..2"					[ps30]  [PC]
// STATIC: "FLASHLIGHTDEPTHFILTERMODE"	"0..0"					[ps20b] [XBOX]

// DYNAMIC: "NUM_LIGHTS"				"0..2"					[ps20]
// DYNAMIC: "NUM_LIGHTS"				"0..4"					[ps20b]
// DYNAMIC: "NUM_LIGHTS"				"0..4"					[ps30]

// DYNAMIC: "FLASHLIGHTSHADOWS"			"0..1"					[ps20b]
// DYNAMIC: "FLASHLIGHTSHADOWS"			"0..1"					[ps30]

// We don't use other lights when doing the flashlight
// SKIP: ( $FLASHLIGHT != 0 ) && ( $NUM_LIGHTS > 0 )

// We don't care about flashlight depth unless the flashlight is on
// SKIP: ( $FLASHLIGHT == 0 ) && ( $FLASHLIGHTSHADOWS == 1 )	[ps20b]
// SKIP: ( $FLASHLIGHT == 0 ) && ( $FLASHLIGHTSHADOWS == 1 )	[ps30]

// SKIP: ( $RAYTRACESPHERE == 0 ) && ( $SPHERETEXKILLCOMBO == 1 )	[ps30]
// SKIP: ( $RAYTRACESPHERE == 0 ) && ( $SPHERETEXKILLCOMBO == 1 )	[ps20b]

// Debug 2.0 shader locally
//#ifdef SHADER_MODEL_PS_2_B
//#undef SHADER_MODEL_PS_2_B
//#define SHADER_MODEL_PS_2_0
//#endif

// Includes =======================================================================================
#include "common_flashlight_fxc.h"
#include "shader_constant_register_map.h"

// Texture Samplers ===============================================================================
sampler g_tCorneaSampler				: register( s0 );
sampler g_tIrisSampler					: register( s1 );
sampler g_tEyeReflectionCubemapSampler	: register( s2 );
sampler g_tEyeAmbientOcclSampler		: register( s3 );
sampler g_tLightwarpSampler				: register( s4 ); // 1D texture for TF NPR lighting

sampler g_tFlashlightCookieSampler		: register( s5 );
sampler g_tFlashlightDepthSampler		: register( s6 );
sampler g_tRandomRotationSampler		: register( s7 );

// Shaders Constants and Globals ==================================================================
const float4 g_vPackedConst0			: register( c0 );
#define g_flDilationFactor				g_vPackedConst0.x
#define g_flGlossiness					g_vPackedConst0.y
#define g_flAverageAmbient				g_vPackedConst0.z
#define g_flCorneaBumpStrength			g_vPackedConst0.w

const float3 g_vEyeOrigin				: register( c1 );
const float4 g_vIrisProjectionU			: register( c2 );
const float4 g_vIrisProjectionV			: register( c3 );
const float4 g_vCameraPosition			: register( c4 );
const float3 g_cAmbientOcclColor		: register( c5 );

const float4 g_vPackedConst6			: register( c6 );
#define g_flEyeballRadius    g_vPackedConst6.y //0.51f
//#define g_bRaytraceSphere    g_vPackedConst6.z //1.0f
#define g_flParallaxStrength g_vPackedConst6.w //0.25f

// Flashlight constants
const float4 g_vFlashlightAttenuationFactors	: register( c7 ); // FarZ in w
const float3 g_vFlashlightPos					: register( c8 );
const float4 g_vShadowTweaks					: register( c9 );
const float4 g_ShaderControls					: register( c10 );
#define g_fPixelFogType							g_ShaderControls.x

const float4 g_FogParams						: register( PSREG_FOG_PARAMS );

PixelShaderLightInfo g_sLightInfo[3]			: register( PSREG_LIGHT_INFO_ARRAY ); // 2 registers each - 6 registers total

// Interpolated values ============================================================================
struct PS_INPUT
{
	float4 vAmbientOcclUv_fallbackCorneaUv	: TEXCOORD0;
	float4 cVertexLight						: TEXCOORD1; // w is used for the flashlight pass
	float4 vTangentViewVector				: TEXCOORD2; // Tangent view vector (Note: w is used for flashlight pass)
	float4 vWorldPosition_ProjPosZ			: TEXCOORD3;
	float3 vWorldNormal						: TEXCOORD4; // World-space normal
	float3 vWorldTangent					: TEXCOORD5; // World-space tangent
	float4 vLightFalloffCosine01			: TEXCOORD6; // Light falloff and cosine terms for first two local lights
	float4 vLightFalloffCosine23			: TEXCOORD7; // Light falloff and cosine terms for next two local lights

	float3 vWorldBinormal					: COLOR0;	// World-space normal
};

// Ray sphere intersect returns distance along ray to intersection ================================
float IntersectRaySphere ( float3 cameraPos, float3 ray, float3 sphereCenter, float sphereRadius)
{
	float3 dst = cameraPos.xyz - sphereCenter.xyz;
	float B = dot(dst, ray);
	float C = dot(dst, dst) - (sphereRadius * sphereRadius);
	float D = B*B - C;
	return (D > 0) ? (-B - sqrt(D)) : 0;
}

// Calculate both types of Fog and lerp to get result
float CalcPixelFogFactorConst( float fPixelFogType, const float4 fogParams, const float flEyePosZ, const float flWorldPosZ, const float flProjPosZ )
{
	float fRangeFog = CalcRangeFog( flProjPosZ, fogParams.x, fogParams.z, fogParams.w );
	float fHeightFog = CalcWaterFogAlpha( fogParams.y, flEyePosZ, flWorldPosZ, flProjPosZ, fogParams.w );
	return lerp( fRangeFog, fHeightFog, fPixelFogType );
}

// Blend both types of Fog and lerp to get result
float3 BlendPixelFogConst( const float3 vShaderColor, float pixelFogFactor, const float3 vFogColor, float fPixelFogType )
{
	pixelFogFactor = saturate( pixelFogFactor );
	float3 fRangeResult = lerp( vShaderColor.rgb, vFogColor.rgb, pixelFogFactor * pixelFogFactor ); //squaring the factor will get the middle range mixing closer to hardware fog
	float3 fHeightResult = lerp( vShaderColor.rgb, vFogColor.rgb, saturate( pixelFogFactor ) );
	return lerp( fRangeResult, fHeightResult, fPixelFogType );
}

float4 FinalOutputConst( const float4 vShaderColor, float pixelFogFactor, float fPixelFogType, const int iTONEMAP_SCALE_TYPE )
{
	float4 result = vShaderColor;
	if( iTONEMAP_SCALE_TYPE == TONEMAP_SCALE_LINEAR )
	{
		result.rgb *= LINEAR_LIGHT_SCALE;
	}
	else if( iTONEMAP_SCALE_TYPE == TONEMAP_SCALE_GAMMA )
	{
		result.rgb *= GAMMA_LIGHT_SCALE;
	}

	result.rgb = BlendPixelFogConst( result.rgb, pixelFogFactor, g_LinearFogColor.rgb, fPixelFogType );
	result.rgb = SRGBOutput( result.rgb ); //SRGB in pixel shader conversion

	return result;
}

// Main ===========================================================================================
float4 main( PS_INPUT i ) : COLOR
{
	// Set bools to compile out code
	bool bFlashlight = ( FLASHLIGHT != 0 ) ? true : false;
	bool bDoDiffuseWarp = LIGHTWARPTEXTURE ? true : false;
	int nNumLights = FLASHLIGHT ? 1 : NUM_LIGHTS;	// Flashlight is considered one light, otherwise, use numlights combo

#if !defined( SHADER_MODEL_PS_2_0 )
	bool bRayCast = RAYTRACESPHERE ? true : false;
	bool bRayCastTexKill = SPHERETEXKILLCOMBO ? true : false;
#endif

	float flFlashlightNDotL = i.vTangentViewVector.w;
	float4 vFlashlightTexCoord = { 0.0f, 0.0f, 0.0f, 0.0f };
	if ( bFlashlight )
	{
		vFlashlightTexCoord.xyzw = i.cVertexLight.xyzw; // This was hidden in this interpolator
		i.cVertexLight.rgba = float4( 0.0f, 0.0f, 0.0f, 0.0f );
	}

	// Interpolated vectors
	float3 vWorldNormal = i.vWorldNormal.xyz;
	float3 vWorldTangent = i.vWorldTangent.xyz;
	float3 vWorldBinormal = ( i.vWorldBinormal.xyz * 2.0f ) - 1.0f; // normalize( cross( vWorldNormal.xyz, vWorldTangent.xyz ) );

	float3 vTangentViewVector = i.vTangentViewVector.xyz;

	// World position
	float3 vWorldPosition = i.vWorldPosition_ProjPosZ.xyz;

	// World view vector to pixel
	float3 vWorldViewVector = normalize( vWorldPosition.xyz - g_vCameraPosition.xyz );

	//=================//
	// TF NPR lighting //
	//=================//
	if ( bDoDiffuseWarp )
	{
		// Replace the interpolated vertex light
		if ( bFlashlight == true )
		{
			// Deal with this below in the flashlight section
		}
		else
		{
			if ( nNumLights > 0 )
			{
				float3 cWarpedLight = 2.0f * tex1D( g_tLightwarpSampler, i.vLightFalloffCosine01.z ).rgb;
				i.cVertexLight.rgb += i.vLightFalloffCosine01.x * PixelShaderGetLightColor( g_sLightInfo, 0 ) * cWarpedLight.rgb;
			}

			if ( nNumLights > 1 )
			{
				float3 cWarpedLight = 2.0f * tex1D( g_tLightwarpSampler, i.vLightFalloffCosine01.w ).rgb;
				i.cVertexLight.rgb += i.vLightFalloffCosine01.y * PixelShaderGetLightColor( g_sLightInfo, 1 ) * cWarpedLight.rgb;
			}

			if ( nNumLights > 2 )
			{
				float3 cWarpedLight = 2.0f * tex1D( g_tLightwarpSampler, i.vLightFalloffCosine23.z ).rgb;
				i.cVertexLight.rgb += i.vLightFalloffCosine23.x * PixelShaderGetLightColor( g_sLightInfo, 2 ) * cWarpedLight.rgb;
			}

			if ( nNumLights > 3 )
			{
				float3 cWarpedLight = 2.0f * tex1D( g_tLightwarpSampler, i.vLightFalloffCosine23.w ).rgb;
				i.cVertexLight.rgb += i.vLightFalloffCosine23.y * PixelShaderGetLightColor( g_sLightInfo, 3 ) * cWarpedLight.rgb;
			}
		}
	}

	//==========================================================================================================//
	// Ray cast against sphere representing eyeball to reduce artifacts from non-spherical morphed eye geometry //
	//==========================================================================================================//
#if !defined( SHADER_MODEL_PS_2_0 )
	if ( bRayCast )
	{
		float fSphereRayCastDistance = IntersectRaySphere( g_vCameraPosition.xyz, vWorldViewVector.xyz, g_vEyeOrigin.xyz, g_flEyeballRadius );
		vWorldPosition.xyz = g_vCameraPosition.xyz + ( vWorldViewVector.xyz * fSphereRayCastDistance );
		if (fSphereRayCastDistance == 0)
		{
			if ( bRayCastTexKill )
				clip(-1); // texkill to get a better silhouette
			vWorldPosition.xyz = g_vEyeOrigin.xyz + ( vWorldNormal.xyz * g_flEyeballRadius );
		}
	}
#endif

	//=================================//
	// Generate sphere and cornea uv's //
	//=================================//
#if !defined( SHADER_MODEL_PS_2_0 )
	float2 vCorneaUv; // Note: Cornea texture is a cropped version of the iris texture
	vCorneaUv.x = dot( g_vIrisProjectionU, float4( vWorldPosition, 1.0f ) );
	vCorneaUv.y = dot( g_vIrisProjectionV, float4( vWorldPosition, 1.0f ) );
	float2 vSphereUv = ( vCorneaUv.xy * 0.5f ) + 0.25f;
#else // ps_20
	float2 vCorneaUv = i.vAmbientOcclUv_fallbackCorneaUv.wz; // Note: Cornea texture is a cropped version of the iris texture
	float2 vSphereUv = ( vCorneaUv.xy * 0.5f ) + 0.25f;
#endif

	//=================================//
	// Hacked parallax mapping on iris //
	//=================================//
	float fIrisOffset = tex2D( g_tCorneaSampler, vCorneaUv.xy ).b;

#if !defined( SHADER_MODEL_PS_2_0 )
	float2 vParallaxVector = ( ( vTangentViewVector.xy * fIrisOffset * g_flParallaxStrength ) / ( 1.0f - vTangentViewVector.z ) ); // Note: 0.25 is a magic number
	vParallaxVector.x = -vParallaxVector.x; //Need to flip x...not sure why.
	//vParallaxVector.x *= -1.0; //Need to flip x...not sure why.
	//vParallaxVector = 0.0f; //Disable parallax for debugging
#else // Disable parallax effect in 2.0 version
	float2 vParallaxVector = { 0.0f, 0.0f };
#endif

	float2 vIrisUv = vSphereUv.xy - vParallaxVector.xy;

	// Note: We fetch from this texture twice right now with different uv's for the color and alpha
	float2 vCorneaNoiseUv = vSphereUv.xy + ( vParallaxVector.xy * 0.5 );
	float fCorneaNoise = tex2D( g_tIrisSampler, vCorneaNoiseUv.xy ).a;

	//===============//
	// Cornea normal //
	//===============//
	// Sample 2D normal from texture
	float3 vCorneaTangentNormal = { 0.0, 0.0, 1.0 };
	float4 vCorneaSample = tex2D( g_tCorneaSampler, vCorneaUv.xy );
	vCorneaTangentNormal.xy = vCorneaSample.rg - 0.5f; // Note: This scales the bump to 50% strength

	// Scale strength of normal
	vCorneaTangentNormal.xy *= g_flCorneaBumpStrength;

	// Add in surface noise and imperfections (NOTE: This should be baked into the normal map!)
	vCorneaTangentNormal.xy += fCorneaNoise * 0.1f;

	// Normalize tangent vector
#if !defined( SHADER_MODEL_PS_2_0 )
	// Since this isn't used later in 2.0, skip the normalize to save shader instructions
	vCorneaTangentNormal.xyz = normalize( vCorneaTangentNormal.xyz );
#endif

	// Transform into world space
	float3 vCorneaWorldNormal = Vec3TangentToWorldNormalized( vCorneaTangentNormal.xyz, vWorldNormal.xyz, vWorldTangent.xyz, vWorldBinormal.xyz );

	//============//
	// Flashlight //
	//============//
	float3 vFlashlightVector = { 0.0f, 0.0f, 0.0f };
	float3 cFlashlightColorFalloff = { 0.0f, 0.0f, 0.0f };
	if ( bFlashlight == true )
	{
		// Flashlight vector
		vFlashlightVector.xyz = normalize( g_vFlashlightPos.xyz - i.vWorldPosition_ProjPosZ.xyz );

		// Distance attenuation for flashlight and to fade out shadow over distance
		float3 vDelta = g_vFlashlightPos.xyz - i.vWorldPosition_ProjPosZ.xyz;
		float flDistSquared = dot( vDelta, vDelta );
		float flDist = sqrt( flDistSquared );
		float flFlashlightAttenuation = dot( g_vFlashlightAttenuationFactors.xyz, float3( 1.0f, 1.0f/flDist, 1.0f/flDistSquared ) );

		// Flashlight cookie
#if !defined( SHADER_MODEL_PS_2_0 )
		float3 vProjCoords = vFlashlightTexCoord.xyz / vFlashlightTexCoord.w;
		float3 cFlashlightCookieColor = tex2D( g_tFlashlightCookieSampler, vProjCoords );
#else
		float3 cFlashlightCookieColor = tex2Dproj( g_tFlashlightCookieSampler, vFlashlightTexCoord.xyzw );
#endif

		// Shadow depth map
#if FLASHLIGHTSHADOWS && !defined( SHADER_MODEL_PS_2_0 )
		int nShadowLevel = FLASHLIGHTDEPTHFILTERMODE;
		float flShadow = DoFlashlightShadow( g_tFlashlightDepthSampler, g_tRandomRotationSampler, vProjCoords, float2(0,0), nShadowLevel, g_vShadowTweaks, false );
		float flAttenuated = lerp( flShadow, 1.0f, g_vShadowTweaks.y );		// Blend between fully attenuated and not attenuated
		flShadow = lerp( flAttenuated, flShadow, flFlashlightAttenuation ); // Blend between shadow and above, according to light attenuation
		cFlashlightCookieColor *= flShadow; // Apply shadow term to cookie color
#endif

		// Flashlight color intensity (needs to be multiplied by global flashlight color later)
		cFlashlightColorFalloff.rgb = flFlashlightAttenuation * cFlashlightCookieColor.rgb;

		// Add this into the interpolated lighting
		if ( bDoDiffuseWarp )
		{
			//float3 cWarpedLight = 2.0f * tex1D( g_tLightwarpSampler, flFlashlightNDotL ).rgb;
			//i.cVertexLight.rgb += cFlashlightColorFalloff.rgb * cFlashlightColor.rgb * cWarpedLight.rgb;
			i.cVertexLight.rgb += cFlashlightColorFalloff.rgb * cFlashlightColor.rgb * flFlashlightNDotL; // No light warp for now
		}
		else
		{
			i.cVertexLight.rgb += cFlashlightColorFalloff.rgb * cFlashlightColor.rgb * flFlashlightNDotL;
		}
	}

	//==============//
	// Dilate pupil //
	//==============//
#if !defined( SHADER_MODEL_PS_2_0 )
	vIrisUv.xy -= 0.5f; // Center around (0,0)
	float fPupilCenterToBorder = saturate( length( vIrisUv.xy ) / 0.2f ); //Note: 0.2 is the uv radius of the iris
	float fPupilDilateFactor = g_flDilationFactor; // This value should be between 0-1
	vIrisUv.xy *= lerp (1.0f, fPupilCenterToBorder, saturate( fPupilDilateFactor ) * 2.5f - 1.25f );
	vIrisUv.xy += 0.5f;
#endif

	//============//
	// Iris color //
	//============//
	float4 cIrisColor = tex2D( g_tIrisSampler, vIrisUv.xy );

	//==========================//
	// Iris lighting highlights //
	//==========================//
	float3 cIrisLighting = float3( 0.0f, 0.0f, 0.0f );

#if !defined( SHADER_MODEL_PS_2_0 )
	// Mask off everything but the iris pixels
	float fIrisHighlightMask = tex2D( g_tCorneaSampler, vCorneaUv.xy ).a;

	// Generate the normal
	float3 vIrisTangentNormal = vCorneaTangentNormal.xyz;
	vIrisTangentNormal.xy *= -2.5f; // I'm not normalizing on purpose

	for ( int j=0; j < nNumLights; j++ )
	{
		// World light vector
		float3 vWorldLightVector;
		if ( ( j == 0 ) && ( bFlashlight == true ) )
			vWorldLightVector = vFlashlightVector.xyz;
		else
			vWorldLightVector = PixelShaderGetLightVector( i.vWorldPosition_ProjPosZ.xyz, g_sLightInfo, j );

		// Tangent light vector
		float3 vTangentLightVector = Vec3WorldToTangent( vWorldLightVector.xyz, vWorldNormal.xyz, vWorldTangent.xyz, vWorldBinormal.xyz );

		// Adjust the tangent light vector to generate the iris lighting
		float3 tmpv = -vTangentLightVector.xyz;
		tmpv.xy *= -0.5f; //Flatten tangent view
		tmpv.z = max( tmpv.z, 0.5f ); //Clamp z of tangent view to help maintain highlight
		tmpv.xyz = normalize( tmpv.xyz );

		// Core iris lighting math
		float fIrisFacing = pow( abs( dot( vIrisTangentNormal.xyz, tmpv.xyz ) ), 6.0f ) * 0.5f; // Yes, 6.0 and 0.5 are magic numbers

		// Cone of darkness to darken iris highlights when light falls behind eyeball past a certain point
		float flConeOfDarkness = pow( 1.0f - saturate( ( -vTangentLightVector.z - 0.25f ) / 0.75f ), 4.0f );
		//float flConeOfDarkness = pow( 1.0f - saturate( ( -dot( vIrisTangentNormal.xyz, vTangentLightVector.xyz ) - 0.15f ) / 0.85f ), 8.0f );

		// Tint by iris color and cone of darkness
		float3 cIrisLightingTmp = fIrisFacing * fIrisHighlightMask * flConeOfDarkness;

		// Attenuate by light color and light falloff
		if ( ( j == 0 ) && ( bFlashlight == true ) )
			cIrisLightingTmp.rgb *= cFlashlightColorFalloff.rgb * cFlashlightColor.rgb;
		else if ( j == 0 )
			cIrisLightingTmp.rgb *= i.vLightFalloffCosine01.x * PixelShaderGetLightColor( g_sLightInfo, 0 );
		else if ( j == 1 )
			cIrisLightingTmp.rgb *= i.vLightFalloffCosine01.y * PixelShaderGetLightColor( g_sLightInfo, 1 );
		else if ( j == 2 )
			cIrisLightingTmp.rgb *= i.vLightFalloffCosine23.x * PixelShaderGetLightColor( g_sLightInfo, 2 );
		else
			cIrisLightingTmp.rgb *= i.vLightFalloffCosine23.y * PixelShaderGetLightColor( g_sLightInfo, 3 );

		// Sum into final variable
		cIrisLighting.rgb += cIrisLightingTmp.rgb;
	}

	// Add slight view dependent iris lighting based on ambient light intensity to enhance situations with no local lights (0.5f is to help keep it subtle)
	cIrisLighting.rgb += saturate( dot( vIrisTangentNormal.xyz, -vTangentViewVector.xyz ) ) * g_flAverageAmbient * fIrisHighlightMask * 0.5f;
#else
	// Else, intensify light over cornea to simulate the brightening that happens above
	cIrisLighting.rgb += i.cVertexLight.rgb * vCorneaSample.a;
#endif

	//===================//
	// Ambient occlusion //
	//===================//
	float3 cAmbientOcclFromTexture = tex2D( g_tEyeAmbientOcclSampler, i.vAmbientOcclUv_fallbackCorneaUv.xy ).rgb;
	float3 cAmbientOcclColor = lerp( g_cAmbientOcclColor, 1.0f, cAmbientOcclFromTexture.rgb ); // Color the ambient occlusion
	i.cVertexLight.rgb *= cAmbientOcclColor.rgb;

	//==========================//
	// Reflection from cube map //
	//==========================//
	float3 vCorneaReflectionVector = reflect ( vWorldViewVector.xyz, vCorneaWorldNormal.xyz );

	//float3 cReflection = ENV_MAP_SCALE * texCUBE( g_tEyeReflectionCubemapSampler, vCorneaReflectionVector.xyz ).rgb;
	float3 cReflection = g_flGlossiness * texCUBE( g_tEyeReflectionCubemapSampler, vCorneaReflectionVector.xyz ).rgb;

	// Hack: Only add in half of the env map for the flashlight pass. This looks reasonable.
	if ( bFlashlight )
	{
		cReflection.rgb *= 0.5f;
	}

	//===========================//
	// Glint specular highlights //
	//===========================//
	float3 cSpecularHighlights = 0.0f;
	if ( bFlashlight )
	{
		cSpecularHighlights.rgb += pow( saturate( dot( vCorneaReflectionVector.xyz, vFlashlightVector.xyz ) ), 128.0f ) * cFlashlightColorFalloff.rgb * cFlashlightColor.rgb;
	}
	else // no flashlight
	{
		if ( nNumLights > 0 )
			cSpecularHighlights.rgb += pow( saturate( dot( vCorneaReflectionVector.xyz, PixelShaderGetLightVector( i.vWorldPosition_ProjPosZ.xyz, g_sLightInfo, 0 ) ) ), 128.0f ) * i.vLightFalloffCosine01.x * PixelShaderGetLightColor( g_sLightInfo, 0 );

		if ( nNumLights > 1 )
			cSpecularHighlights.rgb += pow( saturate( dot( vCorneaReflectionVector.xyz, PixelShaderGetLightVector( i.vWorldPosition_ProjPosZ.xyz, g_sLightInfo, 1 ) ) ), 128.0f ) * i.vLightFalloffCosine01.y * PixelShaderGetLightColor( g_sLightInfo, 1 );

		if ( nNumLights > 2 )
			cSpecularHighlights.rgb += pow( saturate( dot( vCorneaReflectionVector.xyz, PixelShaderGetLightVector( i.vWorldPosition_ProjPosZ.xyz, g_sLightInfo, 2 ) ) ), 128.0f ) * i.vLightFalloffCosine23.x * PixelShaderGetLightColor( g_sLightInfo, 2 );

		if ( nNumLights > 3 )
			cSpecularHighlights.rgb += pow( saturate( dot( vCorneaReflectionVector.xyz, PixelShaderGetLightVector( i.vWorldPosition_ProjPosZ.xyz, g_sLightInfo, 3 ) ) ), 128.0f ) * i.vLightFalloffCosine23.y * PixelShaderGetLightColor( g_sLightInfo, 3 );
	}

	//===============//
	// Combine terms //
	//===============//
	float4 result;

	// Unlit iris, pupil, and sclera color
	result.rgb = cIrisColor.rgb;

	// Add in slight cornea noise to help define raised cornea layer for close-ups
	result.rgb += fCorneaNoise * 0.1f;

	// Diffuse light (Vertex lighting + extra iris caustic lighting)
	result.rgb *= i.cVertexLight.rgb + cIrisLighting.rgb;

	// Environment map
	result.rgb += cReflection.rgb * i.cVertexLight.rgb;

	// Local light glints
	result.rgb += cSpecularHighlights.rgb;

	// Set alpha to 1.0 by default
	result.a = 1.0;

#if !defined( SHADER_MODEL_PS_2_0 )
	float fogFactor = CalcPixelFogFactorConst( g_fPixelFogType, g_FogParams, g_vCameraPosition.z, i.vWorldPosition_ProjPosZ.z, i.vWorldPosition_ProjPosZ.w );
	return FinalOutputConst( result, fogFactor, g_fPixelFogType, TONEMAP_SCALE_LINEAR );
#else
	float fogFactor = CalcPixelFogFactor( PIXEL_FOG_TYPE_NONE, g_FogParams, g_vCameraPosition.z, i.vWorldPosition_ProjPosZ.z, i.vWorldPosition_ProjPosZ.w );
	return FinalOutput( result, fogFactor, PIXEL_FOG_TYPE_NONE, TONEMAP_SCALE_LINEAR );
#endif

}

{'repo_name': 'NicknineTheEagle/TF2-Base', 'stars': '137', 'repo_language': 'C++', 'file_name': 'gameinfo.txt', 'mime_type': 'text/plain', 'hash': 7948377948007478440, 'source_dataset': 'data'}


# Maven 插件参考手册

## 启动一个简易注册中心

以指定的9099端口启动一个简易注册中心 [^1]：

```sh
mvn dubbo:registry -Dport=9099
```

## 生成demo服务提供者应用

生成指定接口和版本的服务提供者应用：

```sh
mvn dubbo:create -Dapplication=xxx -Dpackage=com.alibaba.xxx -Dservice=XxxService,YyyService -Dversion=1.0.0
```

[^1]: 如果端口不指定，默认端口为 9090

{'repo_name': 'apache/dubbo-website', 'stars': '345', 'repo_language': 'JavaScript', 'file_name': 'dubbo.xsd', 'mime_type': 'text/xml', 'hash': 807442214291381641, 'source_dataset': 'data'}


(**************************************************************************)
(*                                                                        *)
(*                                 OCaml                                  *)
(*                                                                        *)
(*                       Pierre Chambart, OCamlPro                        *)
(*           Mark Shinwell and Leo White, Jane Street Europe              *)
(*                                                                        *)
(*   Copyright 2013--2016 OCamlPro SAS                                    *)
(*   Copyright 2014--2016 Jane Street Group LLC                           *)
(*                                                                        *)
(*   All rights reserved.  This file is distributed under the terms of    *)
(*   the GNU Lesser General Public License version 2.1, with the          *)
(*   special exception on linking described in the file LICENSE.          *)
(*                                                                        *)
(**************************************************************************)

[@@@ocaml.warning "+a-4-9-30-40-41-42"]

(** Utility functions for the Flambda intermediate language. *)

(** Access functions *)

(** [find_declaration f decl] raises [Not_found] if [f] is not in [decl]. *)
val find_declaration :
  Closure_id.t -> Flambda.function_declarations -> Flambda.function_declaration

(** [find_declaration_variable f decl] raises [Not_found] if [f] is not in
    [decl]. *)
val find_declaration_variable :
  Closure_id.t -> Flambda.function_declarations -> Variable.t

(** [find_free_variable v clos] raises [Not_found] if [c] is not in [clos]. *)
val find_free_variable :
  Var_within_closure.t -> Flambda.set_of_closures -> Variable.t

(** Utility functions *)

val function_arity : Flambda.function_declaration -> int

(** Variables "bound by a closure" are those variables free in the
    corresponding function's body that are neither:
    - bound as parameters of that function; nor
    - bound by the [let] binding that introduces the function declaration(s).
    In particular, if [f], [g] and [h] are being introduced by a
    simultaneous, possibly mutually-recursive [let] binding then none of
    [f], [g] or [h] are bound in any of the closures for [f], [g] and [h].
*)
val variables_bound_by_the_closure :
  Closure_id.t -> Flambda.function_declarations -> Variable.Set.t

(** If [can_be_merged f1 f2] is [true], it is safe to merge switch
    branches containing [f1] and [f2]. *)
val can_be_merged : Flambda.t -> Flambda.t -> bool

val description_of_toplevel_node : Flambda.t -> string

(* Given an expression, freshen all variables within it, and form a function
   whose body is the resulting expression.  The variables specified by
   [params] will become the parameters of the function; the closure will be
   identified by [id].  [params] must only reference variables that are
   free variables of [body]. *)
(* CR-soon mshinwell: consider improving name and names of arguments
   lwhite: the params restriction seems odd, perhaps give a reason
   in the comment. *)
val make_closure_declaration
   : is_classic_mode:bool
  -> id:Variable.t
  -> body:Flambda.t
  -> params:Parameter.t list
  -> stub:bool
  -> Flambda.t

val toplevel_substitution
   : Variable.t Variable.Map.t
  -> Flambda.expr
  -> Flambda.expr

val toplevel_substitution_named
   : Variable.t Variable.Map.t
  -> Flambda.named
  -> Flambda.named

(** [bind [var1, expr1; ...; varN, exprN] body] binds using
    [Immutable] [Let] expressions the given [(var, expr)] pairs around the
    body. *)
val bind
   : bindings:(Variable.t * Flambda.named) list
  -> body:Flambda.t
  -> Flambda.t

val name_expr
    : name:Internal_variable_names.t
   -> Flambda.named
   -> Flambda.t

val name_expr_from_var
    : var:Variable.t
   -> Flambda.named
   -> Flambda.t

val initialize_symbols
   : Flambda.program
  -> (Symbol.t * Tag.t * Flambda.t list) list

val imported_symbols : Flambda.program -> Symbol.Set.t

val needed_import_symbols : Flambda.program -> Symbol.Set.t

val introduce_needed_import_symbols : Flambda.program -> Flambda.program

val root_symbol : Flambda.program -> Symbol.t

(** Returns [true] iff the given term might raise the given static
    exception. *)
val might_raise_static_exn : Flambda.named -> Static_exception.t -> bool

(** Creates a map from closure IDs to set_of_closure IDs by iterating over
    all sets of closures in the given program. *)
val make_closure_map
   : Flambda.program
  -> Set_of_closures_id.t Closure_id.Map.t

(** The definitions of all constants that have been lifted out to [Let_symbol]
    or [Let_rec_symbol] constructions. *)
val all_lifted_constants
   : Flambda.program
  -> (Symbol.t * Flambda.constant_defining_value) list

(** Like [all_lifted_constant_symbols], but returns a map instead of a list. *)
val all_lifted_constants_as_map
   : Flambda.program
  -> Flambda.constant_defining_value Symbol.Map.t

(** The identifiers of all constant sets of closures that have been lifted out
    to [Let_symbol] or [Let_rec_symbol] constructions. *)
val all_lifted_constant_sets_of_closures
   : Flambda.program
  -> Set_of_closures_id.Set.t

val all_lifted_constant_closures : Flambda.program -> Closure_id.Set.t

(** All sets of closures in the given program (whether or not bound to a
    symbol.) *)
val all_sets_of_closures : Flambda.program -> Flambda.set_of_closures list

val all_sets_of_closures_map
   : Flambda.program
  -> Flambda.set_of_closures Set_of_closures_id.Map.t

(* CR-someday pchambart: A more general version of this function might
   take a [named] instead of a symbol and be called with
   [Read_symbol_field (symbol, 0)]. *)
val substitute_read_symbol_field_for_variables
   : (Symbol.t * int list) Variable.Map.t
  -> Flambda.t
  -> Flambda.t

(** For the compilation of switch statements. *)
module Switch_storer : sig
  val mk_store : unit -> (Flambda.t, unit) Switch.t_store
end

(** Within a set of function declarations there is a set of function bodies,
    each of which may (or may not) reference one of the other functions in
    the same set.  Initially such intra-set references are by [Var]s (known
    as "fun_var"s) but if the function is lifted by [Lift_constants] then the
    references will be translated to [Symbol]s.  This means that optimization
    passes that need to identify whether a given "fun_var" (i.e. a key in the
    [funs] map in a value of type [function_declarations]) is used in one of
    the function bodies need to examine the [free_symbols] as well as the
    [free_variables] members of [function_declarations].  This function makes
    that process easier by computing all used "fun_var"s in the bodies of
    the given set of function declarations, including the cases where the
    references are [Symbol]s.  The returned value is a map from "fun_var"s
    to the "fun_var"s (if any) used in the body of the function associated
    with that "fun_var".
*)
val fun_vars_referenced_in_decls
   : Flambda.function_declarations
  -> closure_symbol:(Closure_id.t -> Symbol.t)
  -> Variable.Set.t Variable.Map.t

(** Computes the set of closure_id in the set of closures that are
    required used (transitively) the entry_point *)
val closures_required_by_entry_point
   : entry_point:Closure_id.t
  -> closure_symbol:(Closure_id.t -> Symbol.t)
  -> Flambda.function_declarations
  -> Variable.Set.t

val all_functions_parameters : Flambda.function_declarations -> Variable.Set.t

val all_free_symbols : Flambda.function_declarations -> Symbol.Set.t

val contains_stub : Flambda.function_declarations -> bool

(* Ensure that projection information is suitably erased from
   free_vars and specialised_args if we have deleted the variable being
   projected from. *)
val clean_projections
   : which_variables : Flambda.specialised_to Variable.Map.t
  -> Flambda.specialised_to Variable.Map.t

val projection_to_named : Projection.t -> Flambda.named

type specialised_to_same_as =
  | Not_specialised
  | Specialised_and_aliased_to of Variable.Set.t

(** For each parameter in a given set of function declarations and the usual
    specialised-args mapping, determine which other parameters are specialised
    to the same variable as that parameter.
    The result is presented as a map from [fun_vars] to lists, corresponding
    componentwise to the usual [params] list in the corresponding function
    declaration. *)
val parameters_specialised_to_the_same_variable
   : function_decls:Flambda.function_declarations
  -> specialised_args:Flambda.specialised_to Variable.Map.t
  -> specialised_to_same_as list Variable.Map.t

{'repo_name': 'ocaml-multicore/ocaml-multicore', 'stars': '505', 'repo_language': 'OCaml', 'file_name': 'typeopt.ml', 'mime_type': 'text/plain', 'hash': 598504674023931928, 'source_dataset': 'data'}


/*
 * Copyright (c) 2001-2017, Zoltan Farkas All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * Additionally licensed with:
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.spf4j.recyclable.impl;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.junit.Assert;
import org.junit.Test;
import org.spf4j.base.ReferenceType;
import org.spf4j.recyclable.SizedRecyclingSupplier;

/**
 *
 * @author zoly
 */
@SuppressFBWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON")
public class SizedThreadLocalRecyclingSupplierTest {

  @Test
  @SuppressFBWarnings({"PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS",
    "UTAO_JUNIT_ASSERTION_ODDITIES_USE_ASSERT_EQUALS"})
  public void testSupplier() {
    SizedThreadLocalRecyclingSupplier<byte[]> supplier = new SizedThreadLocalRecyclingSupplier<>(
            new SizedRecyclingSupplier.Factory<byte[]>() {

      @Override
      @SuppressFBWarnings("SUA_SUSPICIOUS_UNINITIALIZED_ARRAY")
      public byte[] create(final int size) {
        return new byte[size];
      }

      @Override
      public int size(final byte[] object) {
        return object.length;
      }
    }, ReferenceType.SOFT);

    byte[] get = supplier.get(8000);
    supplier.recycle(get);
    byte[] get2 = supplier.get(8000);
    supplier.recycle(get2);
    Assert.assertTrue(get == get2);

    get = supplier.get(8000);
    get2 = supplier.get(8000);
    Assert.assertTrue(get != get2);
    supplier.recycle(get);
    supplier.recycle(get2);

    get = supplier.get(4000);
    Assert.assertEquals(8000, get.length);
    supplier.recycle(get);

    get = supplier.get(10000);
    Assert.assertEquals(10000, get.length);
    supplier.recycle(get);

    get = supplier.get(8000);
    get2 = supplier.get(8000);
    Assert.assertTrue(get.length == 10000 || get2.length == 10000);

  }

}

{'repo_name': 'zolyfarkas/spf4j', 'stars': '176', 'repo_language': 'Java', 'file_name': 'TestTimeSourceTest.java', 'mime_type': 'text/x-java', 'hash': -3217160440780576068, 'source_dataset': 'data'}


# -*- coding: utf-8 -*-
"""
From directory of zips to ?
"""
import os
import re
import glob
import json
import logging
import zipfile
from functools import lru_cache

import click
import pandas as pd

STOREPATH = 'data/store.h5'

def dd_fp_to_span(fp):
    """dd_YYYY-MM_YYYY-MM.txt -> YYYY-MM_YYY-MM"""
    return os.path.basename(fp).split('dd_')[-1].split('.')[0]

def span_to_dd_key(span):
    "2008-01_2008-12 -> /dds/2008_01_2008_12"
    return '/dds/dd{}'.format(span.replace('-', '_'))

def dd_key_to_span(key):
    "/dds/2008_01_2008_12 -> 2008-01_2008-12"
    parts = key.lstrip('/').lstrip('dds/dd').split('_')
    return '-'.join(parts[:2]) + '_' + '-'.join(parts[2:])

def parse_dd(fp):
    """
    filepath to DataFrame with columns
        field, width, description, start, end
    """
    expr = re.compile(r'[\x0c]{0,1}(\w+)\*?[\s\t]*(\d{1,2})[\s\t]*(.*?)'
                      r'[\s\t]*\(*(\d+)\s*[\-–]\s*(\d+)\)*\s*$')
    with open(fp) as f:
        lines = (expr.match(x) for x in f)
        matches = filter(None, lines)
        groups = (x.groups() for x in matches)

        df = (pd.DataFrame(list(groups),
                           columns=['field', 'width', 'desc', 'start', 'end'])
                .convert_objects(convert_numeric=True))
    return df

def store_dd(dd, span):
    dd.to_hdf('data/store.h5', span_to_dd_key(span))

@lru_cache(1)
def _make_dd_map():
    with pd.HDFStore('data/store.h5') as store:
        keys = filter(lambda x: x.startswith('/dds'), store.keys())
        dds = map(dd_key_to_span, keys)
        d = {}
        for dd in dds:
            start, end = dd.split('_')
            for month in pd.period_range(start=start, end=end, freq='M'):
                d[month.strftime('%Y-%m')] = dd
    return d

def month_to_dd(month):
    key = month_to_dd_key(month)
    with pd.HDFStore('data/store.h5') as store:
        return store.select(key)

def month_to_dd_key(month):
    d = _make_dd_map()
    key = span_to_dd_key(d[month])
    return key

# -------
# Monthly
# -------

# Naming

def zip_fp_to_month(fp):
    return os.path.basename(fp).split(".")[0]

def month_to_hdf_key(month):
    "2015-01 -> monthly/2015_01"
    try:
        month = month.strftime('%Y-%m')
    except AttributeError:
        pass
    return "/monthly/m{}".format(month.replace('-', '_'))

def hdf_key_to_month(key):
    "[/]monthly/2015_01 -> 2015-01"
    return key.lstrip('/').lstrip('monthly/m').replace('_', '-')

# extracting

def extract(fp):
    z = zipfile.ZipFile(fp)
    assert len(z.namelist()) == 1
    name = z.namelist()[0]
    data_fp = z.extract(name, path='data')
    return data_fp

def parse_monthly(fp, cache=True, nrows=None):
    with open('interesting.json') as f:
        col_map = json.load(f)
        month = zip_fp_to_month(fp)
        hdf_key = month_to_hdf_key(month)
        dd_key = month_to_dd_key(month)
        span = dd_key_to_span(dd_key)
        cm = col_map[span]

    if cache:
        with pd.HDFStore('data/store.h5') as store:
            if hdf_key in store:
                return None

    data_fp = extract(fp)
    try:
        dd = month_to_dd(month)
        subset = dd.loc[dd.field.isin(cm.keys())]
        names = list(subset.field)
        colspecs = (subset[['start', 'end']]
                    .assign(start=lambda df: df.start - 1)
                    .values.tolist())
        # TALK: run through with subset first (nrows=100)

        df = (pd.read_fwf(data_fp, colspecs=colspecs, names=names,
                          usecols=names, nrows=nrows)
                .rename(columns=cm)
                .sort(['mis']))
        key = month_to_hdf_key(month)
        with pd.HDFStore(STOREPATH) as store:
            store.append(key, df, format='table', data_columns=True)
    except:
        os.remove(data_fp)
        raise
    os.remove(data_fp)

def filter_working_years(df):
    """
    Only those aged 18 - 65
    """
    return df.query('18 <= age <= 65')

def run_dd():
    dds = iter(glob.glob('dds/*.txt'))
    for fp in dds:
        span = dd_fp_to_span(fp)
        dd = parse_dd(fp)
        store_dd(dd, span)
        print(span, end='\r')

def run_monthly(cache=True, nrows=None):
    zips = iter(glob.glob('data/*.zip'))
    for fp in zips:
        parse_monthly(fp, cache=cache, nrows=nrows)
        print(fp, end='\r')

@click.command()
@click.option('--job-type', type=click.Choice(['all', 'dd', 'monthly']))
@click.option('--cache/--no-cache', default=True)
@click.option('--nrows', default=None, type=int)
def run(job_type, cache, nrows=None):

    if job_type == 'dd':
        run_dd()
    elif job_type == 'monthly':
        run_monthly(nrows=nrows)
    elif job_type == 'all':
        print("Running dd")
        run_dd()
        print("Running monthly")
        run_monthly(nrows=nrows)

if __name__ == '__main__':
    run()

{'repo_name': 'TomAugspurger/PyDataSeattle', 'stars': '107', 'repo_language': 'Jupyter Notebook', 'file_name': 'run.py', 'mime_type': 'text/x-python', 'hash': 6744492481265538775, 'source_dataset': 'data'}


999
dxfrw 0.5.10
0
SECTION
2
HEADER
9
$ACADVER
1
AC1021
9
$HANDSEED
5
20000
9
$DWGCODEPAGE
3
ANSI_1252
9
$INSBASE
10
0
20
0
30
0
9
$EXTMIN
10
0
20
0
30
0
9
$EXTMAX
10
0
20
0
30
0
9
$LIMMIN
10
0
20
0
9
$LIMMAX
10
420
20
297
9
$ORTHOMODE
70
0
9
$LTSCALE
40
1
9
$TEXTSTYLE
7
STANDARD
9
$CLAYER
8
0
9
$DIMASZ
40
2.5
9
$DIMLFAC
40
1
9
$DIMSCALE
40
1
9
$DIMEXO
40
0.625
9
$DIMEXE
40
1.25
9
$DIMTXT
40
2.5
9
$DIMTSZ
40
0
9
$DIMAUNIT
70
0
9
$DIMADEC
70
0
9
$DIMLUNIT
70
2
9
$DIMSTYLE
2
STANDARD
9
$DIMGAP
40
0.625
9
$DIMTIH
70
0
9
$LUNITS
70
2
9
$LUPREC
70
4
9
$AUNITS
70
0
9
$AUPREC
70
2
9
$SPLINESEGS
70
8
9
$SNAPSTYLE
70
0
9
$PINSBASE
10
0
20
0
30
0
9
$PLIMMIN
10
0
20
0
9
$PLIMMAX
10
210
20
297
9
$INSUNITS
70
0
9
$PSVPSCALE
40
1
0
ENDSEC
0
SECTION
2
CLASSES
0
ENDSEC
0
SECTION
2
TABLES
0
TABLE
2
VPORT
5
8
330
0
100
AcDbSymbolTable
70
1
0
VPORT
5
31
330
2
100
AcDbSymbolTableRecord
100
AcDbViewportTableRecord
2
*ACTIVE
70
0
10
0
20
0
11
1
21
1
12
153.75
22
71.125
13
0
23
0
14
10
24
10
15
10
25
10
16
0
26
0
36
1
17
0
27
0
37
0
40
154.75
41
2.06785137318
42
50
43
0
44
0
50
0
51
0
71
0
72
100
73
1
74
3
75
0
76
1
77
0
78
0
281
0
65
1
110
0
120
0
130
0
111
1
121
0
131
0
112
0
122
1
132
0
79
0
146
0
348
10020
60
7
61
5
292
1
282
1
141
0
142
0
63
250
421
3358443
0
ENDTAB
0
TABLE
2
LTYPE
5
5
330
0
100
AcDbSymbolTable
70
4
0
LTYPE
5
14
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
ByBlock
70
0
3

72
65
73
0
40
0
0
LTYPE
5
15
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
ByLayer
70
0
3

72
65
73
0
40
0
0
LTYPE
5
16
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
Continuous
70
0
3
Solid line
72
65
73
0
40
0
0
LTYPE
5
32
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
DOT
70
0
3
Dot . . . . . . . . . . . . . . . . . . . . . .
72
65
73
2
40
6.35
49
0
74
0
49
-6.35
74
0
0
LTYPE
5
33
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
DOT2
70
0
3
Dot (.5x) .....................................
72
65
73
2
40
3.175
49
0
74
0
49
-3.175
74
0
0
LTYPE
5
34
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
DOTX2
70
0
3
Dot (2x) .  .  .  .  .  .  .  .  .  .  .  .  .
72
65
73
2
40
12.7
49
0
74
0
49
-12.7
74
0
0
LTYPE
5
35
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
DASHED
70
0
3
Dot . . . . . . . . . . . . . . . . . . . . . .
72
65
73
2
40
19.05
49
12.7
74
0
49
-6.35
74
0
0
LTYPE
5
36
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
DASHED2
70
0
3
Dashed (.5x) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
72
65
73
2
40
9.525
49
6.35
74
0
49
-3.175
74
0
0
LTYPE
5
37
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
DASHEDX2
70
0
3
Dashed (2x) ____  ____  ____  ____  ____  ___
72
65
73
2
40
38.1
49
25.4
74
0
49
-12.7
74
0
0
LTYPE
5
38
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
DASHDOT
70
0
3
Dash dot __ . __ . __ . __ . __ . __ . __ . __
72
65
73
4
40
25.4
49
12.7
74
0
49
-6.35
74
0
49
0
74
0
49
-6.35
74
0
0
LTYPE
5
39
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
DASHDOT2
70
0
3
Dash dot (.5x) _._._._._._._._._._._._._._._.
72
65
73
4
40
12.7
49
6.35
74
0
49
-3.175
74
0
49
0
74
0
49
-3.175
74
0
0
LTYPE
5
3A
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
DASHDOTX2
70
0
3
Dash dot (2x) ____  .  ____  .  ____  .  ___
72
65
73
4
40
50.8
49
25.4
74
0
49
-12.7
74
0
49
0
74
0
49
-12.7
74
0
0
LTYPE
5
3B
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
DIVIDE
70
0
3
Divide ____ . . ____ . . ____ . . ____ . . ____
72
65
73
6
40
31.75
49
12.7
74
0
49
-6.35
74
0
49
0
74
0
49
-6.35
74
0
49
0
74
0
49
-6.35
74
0
0
LTYPE
5
3C
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
DIVIDE2
70
0
3
Divide (.5x) __..__..__..__..__..__..__..__.._
72
65
73
6
40
15.875
49
6.35
74
0
49
-3.175
74
0
49
0
74
0
49
-3.175
74
0
49
0
74
0
49
-3.175
74
0
0
LTYPE
5
3D
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
DIVIDEX2
70
0
3
Divide (2x) ________  .  .  ________  .  .  _
72
65
73
6
40
63.5
49
25.4
74
0
49
-12.7
74
0
49
0
74
0
49
-12.7
74
0
49
0
74
0
49
-12.7
74
0
0
LTYPE
5
3E
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
BORDER
70
0
3
Border __ __ . __ __ . __ __ . __ __ . __ __ .
72
65
73
6
40
44.45
49
12.7
74
0
49
-6.35
74
0
49
12.7
74
0
49
-6.35
74
0
49
0
74
0
49
-6.35
74
0
0
LTYPE
5
3F
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
BORDER2
70
0
3
Border (.5x) __.__.__.__.__.__.__.__.__.__.__.
72
65
73
6
40
22.225
49
6.35
74
0
49
-3.175
74
0
49
6.35
74
0
49
-3.175
74
0
49
0
74
0
49
-3.175
74
0
0
LTYPE
5
40
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
BORDERX2
70
0
3
Border (2x) ____  ____  .  ____  ____  .  ___
72
65
73
6
40
88.9
49
25.4
74
0
49
-12.7
74
0
49
25.4
74
0
49
-12.7
74
0
49
0
74
0
49
-12.7
74
0
0
LTYPE
5
41
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
CENTER
70
0
3
Center ____ _ ____ _ ____ _ ____ _ ____ _ ____
72
65
73
4
40
50.8
49
31.75
74
0
49
-6.35
74
0
49
6.35
74
0
49
-6.35
74
0
0
LTYPE
5
42
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
CENTER2
70
0
3
Center (.5x) ___ _ ___ _ ___ _ ___ _ ___ _ ___
72
65
73
4
40
28.575
49
19.05
74
0
49
-3.175
74
0
49
3.175
74
0
49
-3.175
74
0
0
LTYPE
5
43
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
CENTERX2
70
0
3
Center (2x) ________  __  ________  __  _____
72
65
73
4
40
101.6
49
63.5
74
0
49
-12.7
74
0
49
12.7
74
0
49
-12.7
74
0
0
ENDTAB
0
TABLE
2
LAYER
5
2
330
0
100
AcDbSymbolTable
70
1
0
LAYER
5
10
330
2
100
AcDbSymbolTableRecord
100
AcDbLayerTableRecord
2
0
70
0
62
7
6
CONTINUOUS
370
0
390
F
0
ENDTAB
0
TABLE
2
STYLE
5
3
330
0
100
AcDbSymbolTable
70
3
0
STYLE
5
44
330
2
100
AcDbSymbolTableRecord
100
AcDbTextStyleTableRecord
2
Standard
70
0
40
0
41
1
50
0
71
0
42
1
3
txt
4

0
ENDTAB
0
TABLE
2
VIEW
5
6
330
0
100
AcDbSymbolTable
70
0
0
ENDTAB
0
TABLE
2
UCS
5
7
330
0
100
AcDbSymbolTable
70
0
0
ENDTAB
0
TABLE
2
APPID
5
9
330
0
100
AcDbSymbolTable
70
1
0
APPID
5
12
330
9
100
AcDbSymbolTableRecord
100
AcDbRegAppTableRecord
2
ACAD
70
0
0
ENDTAB
0
TABLE
2
DIMSTYLE
5
A
330
0
100
AcDbSymbolTable
70
1
100
AcDbDimStyleTable
71
1
0
DIMSTYLE
105
45
330
A
100
AcDbSymbolTableRecord
100
AcDbDimStyleTableRecord
2
Standard
70
0
40
1
41
2.5
42
0.625
43
0.38
44
1.25
45
0
46
0
47
0
48
0
140
2.5
141
0.09
142
0
143
25.4
144
1
145
0
146
1
147
0.625
148
0
71
0
72
0
73
0
74
1
75
0
76
0
77
0
78
0
79
0
170
0
171
2
172
0
173
0
174
0
175
0
176
0
177
0
178
0
179
0
271
4
272
4
273
2
274
2
275
0
276
0
277
2
278
46
279
0
280
0
281
0
282
0
283
1
284
0
285
0
286
0
288
0
289
3
340
Standard
341

371
-2
372
-2
0
ENDTAB
0
TABLE
2
BLOCK_RECORD
5
1
330
0
100
AcDbSymbolTable
70
2
0
BLOCK_RECORD
5
1F
330
1
100
AcDbSymbolTableRecord
100
AcDbBlockTableRecord
2
*Model_Space
70
0
280
1
281
0
0
BLOCK_RECORD
5
1E
330
1
100
AcDbSymbolTableRecord
100
AcDbBlockTableRecord
2
*Paper_Space
70
0
280
1
281
0
0
ENDTAB
0
ENDSEC
0
SECTION
2
BLOCKS
0
BLOCK
5
20
330
1F
100
AcDbEntity
8
0
100
AcDbBlockBegin
2
*Model_Space
70
0
10
0
20
0
30
0
3
*Model_Space
1

0
ENDBLK
5
21
330
1F
100
AcDbEntity
8
0
100
AcDbBlockEnd
0
BLOCK
5
1C
330
1B
100
AcDbEntity
8
0
100
AcDbBlockBegin
2
*Paper_Space
70
0
10
0
20
0
30
0
3
*Paper_Space
1

0
ENDBLK
5
1D
330
1F
100
AcDbEntity
8
0
100
AcDbBlockEnd
0
ENDSEC
0
SECTION
2
ENTITIES
0
LWPOLYLINE
5
46
100
AcDbEntity
8
0
6
CONTINUOUS
62
7
370
70
100
AcDbPolyline
90
7
70
1
43
0
10
-4.041452
20
7
10
0
20
0
10
0
20
4.62
10
25.958548
20
4.62
10
25.958548
20
9.38
10
0
20
9.38
10
0
20
14
0
ENDSEC
0
SECTION
2
OBJECTS
0
DICTIONARY
5
C
330
0
100
AcDbDictionary
281
1
3
ACAD_GROUP
350
D
0
DICTIONARY
5
D
330
C
100
AcDbDictionary
281
1
0
ENDSEC
0
EOF

{'repo_name': 'LibreCAD/LibreCAD', 'stars': '1875', 'repo_language': 'C++', 'file_name': 'dividedlg.h', 'mime_type': 'text/x-c++', 'hash': 4018190062947128968, 'source_dataset': 'data'}


//
//  ASCellNode+Internal.h
//  Texture
//
//  Copyright (c) Facebook, Inc. and its affiliates.  All rights reserved.
//  Changes after 4/13/2017 are: Copyright (c) Pinterest, Inc.  All rights reserved.
//  Licensed under Apache 2.0: http://www.apache.org/licenses/LICENSE-2.0
//

#import <AsyncDisplayKit/ASCellNode.h>

NS_ASSUME_NONNULL_BEGIN

@class ASCollectionElement;

@protocol ASCellNodeInteractionDelegate <NSObject>

/**
 * Notifies the delegate that a specified cell node invalidates it's size what could result into a size change.
 *
 * @param node A node informing the delegate about the relayout.
 */
- (void)nodeDidInvalidateSize:(ASCellNode *)node;

/*
 * Methods to be called whenever the selection or highlight state changes
 * on ASCellNode. UIKit internally stores these values to update reusable cells.
 */

- (void)nodeSelectedStateDidChange:(ASCellNode *)node;
- (void)nodeHighlightedStateDidChange:(ASCellNode *)node;

@end

@interface ASCellNode ()

@property (nonatomic, weak) id <ASCellNodeInteractionDelegate> interactionDelegate;

/*
 * Back-pointer to the containing scrollView instance, set only for visible cells.  Used for Cell Visibility Event callbacks.
 */
@property (nonatomic, weak) UIScrollView *scrollView;

- (void)__setSelectedFromUIKit:(BOOL)selected;
- (void)__setHighlightedFromUIKit:(BOOL)highlighted;

/**
 * @note This could be declared @c copy, but since this is only settable internally, we can ensure
 *   that it's always safe simply to retain it, and copy if needed. Since @c UICollectionViewLayoutAttributes
 *   is always mutable, @c copy is never "free" like it is for e.g. NSString.
 */
@property (nullable, nonatomic) UICollectionViewLayoutAttributes *layoutAttributes;

@property (weak, nullable) ASCollectionElement *collectionElement;

@property (nonatomic, readonly) BOOL shouldUseUIKitCell;

@end

@class ASWrapperCellNode;

typedef CGSize (^ASSizeForItemBlock)(ASWrapperCellNode *node, CGSize collectionSize);
typedef UICollectionViewCell * _Nonnull(^ASCellForItemBlock)(ASWrapperCellNode *node);
typedef UICollectionReusableView * _Nonnull(^ASViewForSupplementaryBlock)(ASWrapperCellNode *node);

@interface ASWrapperCellNode : ASCellNode

@property (nonatomic, readonly) ASSizeForItemBlock sizeForItemBlock;
@property (nonatomic, readonly) ASCellForItemBlock cellForItemBlock;
@property (nonatomic, readonly) ASViewForSupplementaryBlock viewForSupplementaryBlock;

@end

NS_ASSUME_NONNULL_END

{'repo_name': 'TextureGroup/Texture', 'stars': '6559', 'repo_language': 'Objective-C++', 'file_name': 'Overview.md', 'mime_type': 'text/plain', 'hash': 4020929033232773601, 'source_dataset': 'data'}


/**
 * QUnit v1.11.0 - A JavaScript Unit Testing Framework
 *
 * http://qunitjs.com
 *
 * Copyright 2012 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

/** Font Family and Sizes */

#qunit-tests, #qunit-header, #qunit-banner, #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult {
  font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif;
}

#qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult, #qunit-tests li { font-size: small; }
#qunit-tests { font-size: smaller; }

/** Resets */

#qunit-tests, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult, #qunit-modulefilter {
  margin: 0;
  padding: 0;
}

/** Header */

#qunit-header {
  padding: 0.5em 0 0.5em 1em;

  color: #8699a4;
  background-color: #0d3349;

  font-size: 1.5em;
  line-height: 1em;
  font-weight: normal;

  border-radius: 5px 5px 0 0;
  -moz-border-radius: 5px 5px 0 0;
  -webkit-border-top-right-radius: 5px;
  -webkit-border-top-left-radius: 5px;
}

#qunit-header a {
  text-decoration: none;
  color: #c2ccd1;
}

#qunit-header a:hover,
#qunit-header a:focus {
  color: #fff;
}

#qunit-testrunner-toolbar label {
  display: inline-block;
  padding: 0 .5em 0 .1em;
}

#qunit-banner {
  height: 5px;
}

#qunit-testrunner-toolbar {
  padding: 0.5em 0 0.5em 2em;
  color: #5E740B;
  background-color: #eee;
  overflow: hidden;
}

#qunit-userAgent {
  padding: 0.5em 0 0.5em 2.5em;
  background-color: #2b81af;
  color: #fff;
  text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px;
}

#qunit-modulefilter-container {
  float: right;
}

/** Tests: Pass/Fail */

#qunit-tests {
  list-style-position: inside;
}

#qunit-tests li {
  padding: 0.4em 0.5em 0.4em 2.5em;
  border-bottom: 1px solid #fff;
  list-style-position: inside;
}

#qunit-tests.hidepass li.pass, #qunit-tests.hidepass li.running  {
  display: none;
}

#qunit-tests li strong {
  cursor: pointer;
}

#qunit-tests li a {
  padding: 0.5em;
  color: #c2ccd1;
  text-decoration: none;
}
#qunit-tests li a:hover,
#qunit-tests li a:focus {
  color: #000;
}

#qunit-tests li .runtime {
  float: right;
  font-size: smaller;
}

.qunit-assert-list {
  margin-top: 0.5em;
  padding: 0.5em;

  background-color: #fff;

  border-radius: 5px;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
}

.qunit-collapsed {
  display: none;
}

#qunit-tests table {
  border-collapse: collapse;
  margin-top: .2em;
}

#qunit-tests th {
  text-align: right;
  vertical-align: top;
  padding: 0 .5em 0 0;
}

#qunit-tests td {
  vertical-align: top;
}

#qunit-tests pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}

#qunit-tests del {
  background-color: #e0f2be;
  color: #374e0c;
  text-decoration: none;
}

#qunit-tests ins {
  background-color: #ffcaca;
  color: #500;
  text-decoration: none;
}

/*** Test Counts */

#qunit-tests b.counts                       { color: black; }
#qunit-tests b.passed                       { color: #5E740B; }
#qunit-tests b.failed                       { color: #710909; }

#qunit-tests li li {
  padding: 5px;
  background-color: #fff;
  border-bottom: none;
  list-style-position: inside;
}

/*** Passing Styles */

#qunit-tests li li.pass {
  color: #3c510c;
  background-color: #fff;
  border-left: 10px solid #C6E746;
}

#qunit-tests .pass                          { color: #528CE0; background-color: #D2E0E6; }
#qunit-tests .pass .test-name               { color: #366097; }

#qunit-tests .pass .test-actual,
#qunit-tests .pass .test-expected           { color: #999999; }

#qunit-banner.qunit-pass                    { background-color: #C6E746; }

/*** Failing Styles */

#qunit-tests li li.fail {
  color: #710909;
  background-color: #fff;
  border-left: 10px solid #EE5757;
  white-space: pre;
}

#qunit-tests > li:last-child {
  border-radius: 0 0 5px 5px;
  -moz-border-radius: 0 0 5px 5px;
  -webkit-border-bottom-right-radius: 5px;
  -webkit-border-bottom-left-radius: 5px;
}

#qunit-tests .fail                          { color: #000000; background-color: #EE5757; }
#qunit-tests .fail .test-name,
#qunit-tests .fail .module-name             { color: #000000; }

#qunit-tests .fail .test-actual             { color: #EE5757; }
#qunit-tests .fail .test-expected           { color: green;   }

#qunit-banner.qunit-fail                    { background-color: #EE5757; }

/** Result */

#qunit-testresult {
  padding: 0.5em 0.5em 0.5em 2.5em;

  color: #2b81af;
  background-color: #D2E0E6;

  border-bottom: 1px solid white;
}
#qunit-testresult .module-name {
  font-weight: bold;
}

/** Fixture */

#qunit-fixture {
  position: absolute;
  top: -10000px;
  left: -10000px;
  width: 1000px;
  height: 1000px;
}

{'repo_name': 'bgrins/bindWithDelay', 'stars': '149', 'repo_language': 'JavaScript', 'file_name': 'qunit.js', 'mime_type': 'text/plain', 'hash': 3020478263669852652, 'source_dataset': 'data'}


<?xml version="1.0"?>
<!-- Do not remove this test for UTF-8: if “Ω” doesn’t appear as greek uppercase omega letter enclosed in quotation marks, you should use an editor that supports UTF-8, not this one. -->
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
  <metadata>
    <id>googlechrome-zenhub</id>
    <version>1.0.0</version>
    <title>ZenHub for GitHub</title>
    <authors>zenhub</authors>
    <owners>chocolatey-community,gep13</owners>
    <projectUrl>https://chrome.google.com/webstore/detail/zenhub-for-github/ogcgkffhplmphkaahpmffcafajaocjbd</projectUrl>
    <iconUrl>https://lh3.googleusercontent.com/t1YTSCMqAqg71faORFTtQ6hy2zCO5S43q6UQcjh3xZ7roSCuOtepxgAKXzJ8EwUef6Hpt0Ociw=s26-h26-e365-rw</iconUrl>
    <projectSourceUrl>https://www.zenhub.com/</projectSourceUrl>
    <docsUrl>https://www.zenhub.com/documentation/more-than-a-github-issue-tracker</docsUrl>
    <packageSourceUrl>https://github.com/chocolatey/chocolatey-coreteampackages/tree/master/manual/googlechrome-extensions/googlechrome-zenhub</packageSourceUrl>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <licenseUrl>https://www.zenhub.com/pricing</licenseUrl>
    <description>
####PACKAGING NOTE: This installs no software. It installs a registry key for the extension that Chrome will see and then ask you for permission to enable the extension if you are in Chrome or on the next run. Chrome will install the latest version of the extension. The mentioned version is the version at time of packaging, you can ignore it. Chrome will handle updates to the extension.

ZenHub tracks work where the work actually happens – GitHub. Managers get deeper insights than ever before, and developers stay focused in the environment they know and love.
    </description>
    <summary>
Build your team's ultimate GitHub workflow.
    </summary>
    <tags>freeware github chrome extension zenhub admin</tags>
    <releaseNotes>
https://www.zenhub.com/blog/tag/new-feature/
    </releaseNotes>
    <dependencies>
      <dependency id="googlechrome" version="10.0.0" />
    </dependencies>
  </metadata>
  <files>
    <file src="tools\**" target="tools" />
  </files>
</package>

{'repo_name': 'chocolatey-community/chocolatey-coreteampackages', 'stars': '257', 'repo_language': 'PowerShell', 'file_name': 'chocolateyInstall.ps1', 'mime_type': 'text/plain', 'hash': -5218892564409862526, 'source_dataset': 'data'}


<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="GradleMigrationSettings" migrationVersion="1" />
  <component name="GradleSettings">
    <option name="linkedExternalProjectsSettings">
      <GradleProjectSettings>
        <option name="delegatedBuild" value="false" />
        <option name="testRunner" value="PLATFORM" />
        <option name="distributionType" value="DEFAULT_WRAPPED" />
        <option name="externalProjectPath" value="$PROJECT_DIR$" />
        <option name="modules">
          <set>
            <option value="$PROJECT_DIR$" />
            <option value="$PROJECT_DIR$/LanSongSDK" />
            <option value="$PROJECT_DIR$/app" />
          </set>
        </option>
        <option name="resolveModulePerSourceSet" value="false" />
      </GradleProjectSettings>
    </option>
  </component>
</project>

{'repo_name': 'LanSoSdk/LanSoEditor_advance', 'stars': '154', 'repo_language': 'Java', 'file_name': 'cache.properties', 'mime_type': 'text/plain', 'hash': -3616626492855053007, 'source_dataset': 'data'}


# GuiMenuSetIcon

Sets an icon for a specified menu.

```c++
void GuiMenuSetIcon(int hMenu, const ICONDATA* icon)
```

## Parameters

`hMenu` Menu handle from a previously-added menu or from the main menu.

`icon`

## Return Value

This function does not return a value.

## Example

```c++
ICONDATA rocket;
rocket.data = icon_rocket;
rocket.size = sizeof(icon_rocket);
hNewMenuEntry = GuiMenuAddEntry(hMenu, &szMenuEntryText);
GuiMenuSetIcon(hMenuDisasm,&rocket);

```

## Related functions

- [GuiMenuAdd](./GuiMenuAdd.md)
- [GuiMenuAddEntry](./GuiMenuAddEntry.md)
- [GuiMenuAddSeparator](./GuiMenuAddSeparator.md)
- [GuiMenuClear](./GuiMenuClear.md)
- [GuiMenuSetEntryIcon](./GuiMenuSetEntryIcon.md)

Note: Plugin developers should make use of the plugin functions provided:

- [\_plugin\_menuadd](../../plugins/API/menuadd.rst)
- [\_plugin\_menuaddentry](../../plugins/API/menuaddentry.rst)
- [\_plugin\_menuaddseparator](../../plugins/API/menuaddseparator.rst)
- [\_plugin\_menuclear](../../plugins/API/menuclear.rst)
- [\_plugin\_menuentryseticon](../../plugins/API/menuentryseticon.rst)
- [\_plugin\_menuseticon](../../plugins/API/menuseticon.rst)

{'repo_name': 'x64dbg/docs', 'stars': '974', 'repo_language': 'Python', 'file_name': 'janssonlicense.md', 'mime_type': 'text/plain', 'hash': 2640174958843208466, 'source_dataset': 'data'}


"""Fixer for 'raise E, V, T'

raise         -> raise
raise E       -> raise E
raise E, V    -> raise E(V)
raise E, V, T -> raise E(V).with_traceback(T)
raise E, None, T -> raise E.with_traceback(T)

raise (((E, E'), E''), E'''), V -> raise E(V)
raise "foo", V, T               -> warns about string exceptions

CAVEATS:
1) "raise E, V" will be incorrectly translated if V is an exception
   instance. The correct Python 3 idiom is

        raise E from V

   but since we can't detect instance-hood by syntax alone and since
   any client code would have to be changed as well, we don't automate
   this.
"""
# Author: Collin Winter

# Local imports
from .. import pytree
from ..pgen2 import token
from .. import fixer_base
from ..fixer_util import Name, Call, Attr, ArgList, is_tuple

class FixRaise(fixer_base.BaseFix):

    BM_compatible = True
    PATTERN = """
    raise_stmt< 'raise' exc=any [',' val=any [',' tb=any]] >
    """

    def transform(self, node, results):
        syms = self.syms

        exc = results["exc"].clone()
        if exc.type == token.STRING:
            msg = "Python 3 does not support string exceptions"
            self.cannot_convert(node, msg)
            return

        # Python 2 supports
        #  raise ((((E1, E2), E3), E4), E5), V
        # as a synonym for
        #  raise E1, V
        # Since Python 3 will not support this, we recurse down any tuple
        # literals, always taking the first element.
        if is_tuple(exc):
            while is_tuple(exc):
                # exc.children[1:-1] is the unparenthesized tuple
                # exc.children[1].children[0] is the first element of the tuple
                exc = exc.children[1].children[0].clone()
            exc.prefix = u" "

        if "val" not in results:
            # One-argument raise
            new = pytree.Node(syms.raise_stmt, [Name(u"raise"), exc])
            new.prefix = node.prefix
            return new

        val = results["val"].clone()
        if is_tuple(val):
            args = [c.clone() for c in val.children[1:-1]]
        else:
            val.prefix = u""
            args = [val]

        if "tb" in results:
            tb = results["tb"].clone()
            tb.prefix = u""

            e = exc
            # If there's a traceback and None is passed as the value, then don't
            # add a call, since the user probably just wants to add a
            # traceback. See issue #9661.
            if val.type != token.NAME or val.value != u"None":
                e = Call(exc, args)
            with_tb = Attr(e, Name(u'with_traceback')) + [ArgList([tb])]
            new = pytree.Node(syms.simple_stmt, [Name(u"raise")] + with_tb)
            new.prefix = node.prefix
            return new
        else:
            return pytree.Node(syms.raise_stmt,
                               [Name(u"raise"), Call(exc, args)],
                               prefix=node.prefix)

{'repo_name': 'QB64Team/qb64', 'stars': '212', 'repo_language': 'C', 'file_name': 'license_freetype_ftl.txt', 'mime_type': 'text/plain', 'hash': 2709331226637358808, 'source_dataset': 'data'}