text:
# Threading Support for Byebug

## Motivation

Having a fully featured stable debugger is important for most programming
languages. It makes the language more attractive for beginners and for users
coming from other languages, because it's a very adequate tool not only for bug
fixing but also just for playing around with a language's features or studying
code not written by ourselves. With this in mind, the main purpose of Byebug
since it was started was to make it an atractive tool for beginners (I was
actually a Ruby beginner during the initial development phase of Byebug so I
was making heavy use of my own tool too).

The main features supported by Byebug are:

* Breaking. Pause the program at some event or specified instruction, to examine
the current state. Related commands: `break`, `catch`, `condition`, `delete`,
`enable`, `disable`.

* Analyzing. Studying program status at a certain point during its execution
(including right after termination). Specifically, we can:
  - Inspect and move around the backtrace (`backtrace`, `up`, `down` and
    `frame` commands).
  - Have a basic REPL functionality, evaluating custom code (`eval`, `irb`,
    `pry`, `method`, `pp`, `ps`, `putl`, `var` commands).
  - Look and change the program's source code (`edit`, `list`, `info` commands).

* Stepping: Running your program one line or instruction at a time, or until
specific points in the program are reached. Related commands: `step`, `next`,
`continue`, `finish`, `kill`, `quit`, `restart`.

* Tracking: Keeping track of the different values of your variables or the
different lines executed by your program. Related commands: `display`,
`undisplay`, `tracevar`, `untracevar`, `set linetrace`.

This features have been working very well as long as the debugged program would
have no multiple Ruby threads, but would just not work when the program would
use different threads. Notice that this would affect developers making use of
threads, but was also affecting users not necessarily knowing anything about
threads, because very well know libraries out there transparently make use of
them (for example, `capybara-webkit` or Ruby's stdlib `Timeout` module).

So Byebug needed a way to debug multithreaded programs that was both:

* Reliable: no deadlock, no killed threads when they are not related to user's
code.

* Useful: allow debugging issues with multithreaded programs. To do that, we
would need to provide the user with the ability to stop/resume specific threads,
list active threads and switch between threads.

This is what this grant is about.

## The feature

The addition of threading support to Byebug's debugger allows users to properly
debug programs making use of Ruby's threads. This includes listing active
threads and their statuses, switching execution to specific threads and
temporarily pausing/resuming threads.

To try out the feature, you might want to use a real application (a Rails app
for example) using threads or just follow the sample session about threads
included in Byebug's Guide. See [here](
https://github.com/deivid-rodriguez/byebug/blob/master/GUIDE.md#threading-support)
for details.

The feature is also fully tested. You can clone _byebug_'s repo and then run

```shell
    bundle install # Install dependencies
    rake compile # Compile the C-extension
    ruby -w -Ilib test/test_helper.rb test/commands/thread_test.rb
```

This is the list of available commands and a short explanation of its usage:

* _thread list_: Lists threads. This is equivalent to Ruby's `Thread.list`, but
it has the following format:
  - A mark '+' for the current thread.
  - A mark '$' for a stopped thread.
  - An internal `id` for the thread, specific to Byebug.
  - Ruby's id and status for the thread, in the format
    `#<Thread:0x0123456789ABCD (run|sleep)>`. In Ruby 2.2.x, also the file and
    line number where the thread is defined are included. This feature is very
    useful to correctly identify threads, because otherwise the only way to tell
    which thread is which is from the order they are defined.
  - Current file and line number location of the thread's execution, in the
    format `file:line`.

* _thread current_: Shows the `thread list` entry for the current thread, just
like the `frame` command shows the current frame whereas the `backtrace`
command shows the whole backtrace.

* _thread stop_: Allows the user to temporarily stop the execution of a thread.
This is useful when we want to focus on debugging specific threads and want to
make sure some other thread stays unchanged, or if we want our main thread to
"wait for us" and don't finish until we tell it to.

* _thread resume_: Allows resuming threads previously stopped with `thread
stop`. It can be used to resume normal program execution, once we've introduced
a change that could fix our issue, for example.

* _thread switch_: Switches current thread and context to another thread. After
issuing this command, execution will be stopped in a different place in the
source code and we'll get a different backtrace. The target thread can't be in
the sleeping state so we might have to issue the `thread resume` command before
running this command.

## The implementation

The TracePoint API was not well suited for this feature. It includes a
`THREAD_BEGIN` and a `THREAD_END` events, but they are generated when the
execution is first delegated to the thread and not when the thread is created.
We want the threads to be available to the user (in a "sleep" state) from their
creation, so we need to resort to "other trickery".

### Mantaining a global thread list

Byebug mantains a global hash table of active threads which is constructed
dinamically as TracePoint API events are received. Every time an event is
processed, we look for a thread matching the current thread in our threads
table and we set up that context to be the current context (when we talk about
"context" in Byebug we mean the program's state in a specific moment during its
execution). If the thread is not found (first event of the thread), we create a
new entry in the table. This is done by the `thread_context_lookup` method in
`threads.c`.

Periodically, the table is cleaned up of dead threads, using the
`cleanup_dead_threads` method in `threads.c`. This method needs to make use of
Ruby because the C-extension API does not seem to have utilities to check for
thread status. This might be a big performance penalty for programs using a big
number of threads, so at some point we might want to either have a
`rb_thread_status` method available to C-extensions, or add a workaround inside
Byebug such as not cleaning the threads table for every event but only every
"N" events, where "N" is big enough so this cleanup is not a performance
bottleneck anymore. Nevertheless, I've tried latest byebug with some Rails apps
and haven't noticed any performance issues.

### Thread syncronization

The biggest challenge of implementing threading in Byebug has been this one.
While our user is stopping at his Byebug prompt, the scheduler can (and does)
schedule different threads to be run, so TracePoint API events are generated
for other threads. We want everything halted while the user is in control so
we need to lock the processing of this events until the user gives control back
to the debugger. To do that we've used a global lock in the C-extension, that
ensures that a single TracePoint API event is processed at the same time.

At the beginning of the processing of every event, we call the `acquire_lock`
method that will either:

* Obtain the global lock if it's free (or the current thread already has
it because the previous event was also from the same thread). In this case, the
event is processed normally.
* Go to sleep and pass execution on to another thread if the lock is currently
being hold by another thread. Notice that we need to specifically call
`rb_thread_stop` here because C-extensions are not preemptive in the sense that
the scheduler won't automatically switch thread execution while in a
C-extension just like it does when running "regular Ruby code". So if we don't
call `rb_thread_stop`, the execution will just deadlock here.

At the end of the processing of every event, we call the `release_lock` method
that will release the lock and pass on the execution to another thread (that
will probably be halted in `acquire_lock` and will be able to pass through once
the lock is released.

### Specifics of some commands

#### thread list

We currently manually syncronize our thread list with the one given by Ruby (
`Thread.list`) when this command is executed, but once this feature is well
tested we can probably get rid of that check and just trust our table that
should always be up to date and exactly the same as `Thread.list`.

#### thread stop

To implement this command, we needed to add some global flags. A function
`rb_thread_stop` is available for C-extensions to stop the current thread, but
when the user issues this command, the target thread is not the current thread
so we can't directly use that method as it doesn't accept a target thread
argument. Instead, we set a global flag, `CTX_FL_SUSPEND` and check that in
`acquire_lock` to prevent thread execution. So even if the global lock is free,
we never delegate execution to the suspended thread.

#### thread resume

The only specific comment about the implementation of this command is the
`CTX_FL_WAS_RUNNING` flag. This flag is used to remember the thread's status
when a thread was suspended so the `thread resume` command can correctly
restore it. It `CTX_FL_WAS_RUNNING` is set when we run `thread resume` we need
to call `rb_thread_wakeup` to restore the "running" status.

#### thread switch

This command was a bit problematic. Users will probably expect nothing to be run
when they issue this command, just a "context change". However, we actually need
to let program's execution to succesfully achieve the context change, so that
the new "current thread" is the one we are switching to and we can properly show
backtrace and file location information for the new thread.

So the idea here is to force the scheduler to inmediately delegate execution
control to the target thread so that the next TracePoint API event generated
belongs to that thread and we can inmediately stop execution again without
running anything else. To achieve this, `thread switch` does the following:

* Saves the target thread in a global `next_thread` variable.
* Sets a breakpoint for the next event to be receive.
* Releases the user prompt and gives control back to the debugger.

To make this work, we need to change the way we `release_lock` after every
event has been processed. We needn't just release the lock but also force the
scheduler the give control to the thread specified by `next_thread`. To
implement this, we add a double linked list where we mantain the list of
threads whose execution is being hold by Byebug's global lock. Threads are
added to this list in `acquire_lock` and removed in `release_lock`. In the
`release_lock` method we pop `next_thread` from the list if `next_thread` is
set or _any_ thread otherwise. Then we call `rb_thread_run` on the popped
thread to delegate control to that thread.

### Byebug's REPL and threads

Byebug's debugger includes a REPL aside from it's built-in commands. Anything
that's not recognized as a Byebug command will be automatically evaluated as
Ruby code. This has proven to be a very useful feature for users to the point
the some people consider Byebug as an `irb` or `pry` alternative.

The new threading feature would not play nice with the REPL when the command to
be evaluated included thread stuff. Users would get either a 'No threads alive.
deadlock?' error or a proper deadlock. For an example of this issues, have a
look at [here](https://github.com/deivid-rodriguez/byebug/issues/115).

This would happen because `byebug`'s global lock wouldn't be released before
evaluating stuff, so if an evaluated command created new threads or switched to
previously created threads, we would get a deadlock because those threads
wouldn't be able to run because thread execution would be hold by Byebug's
current thread.

To solve this issues, we exposed to Ruby a couple of methods `Byebug.lock` and
`Byebug.unlock` to would call `acquire_lock` and `release_lock`, and then
implemented the following method:

```ruby
def allowing_other_threads
  Byebug.unlock
  res = yield
  Byebug.lock
  res
end
```

and call it before evaluating anything in Byebug's prompt. This solved issues
when evaluating stuff from the user's prompt.

## The code

After the explanation of the current implementation, I think we've gone through
every bit of code relating to threads. I copy the relevant file `threads.c` in
the C-extension for completeness.

```c
#include <byebug.h>

/* Threads table class */
static VALUE cThreadsTable;

/* If not Qnil, holds the next thread that must be run */
VALUE next_thread = Qnil;

/* To allow thread syncronization, we must stop threads when debugging */
VALUE locker = Qnil;

static int
t_tbl_mark_keyvalue(st_data_t key, st_data_t value, st_data_t tbl)
{
  UNUSED(tbl);

  rb_gc_mark((VALUE) key);

  if (!value)
    return ST_CONTINUE;

  rb_gc_mark((VALUE) value);

  return ST_CONTINUE;
}

static void
t_tbl_mark(void *data)
{
  threads_table_t *t_tbl = (threads_table_t *) data;
  st_table *tbl = t_tbl->tbl;

  st_foreach(tbl, t_tbl_mark_keyvalue, (st_data_t) tbl);
}

static void
t_tbl_free(void *data)
{
  threads_table_t *t_tbl = (threads_table_t *) data;

  st_free_table(t_tbl->tbl);
  xfree(t_tbl);
}

/*
*  Creates a numeric hash whose keys are the currently active threads and
*  whose values are their associated contexts.
*/
VALUE
create_threads_table(void)
{
  threads_table_t *t_tbl;

  t_tbl = ALLOC(threads_table_t);
  t_tbl->tbl = st_init_numtable();
  return Data_Wrap_Struct(cThreadsTable, t_tbl_mark, t_tbl_free, t_tbl);
}

/*
*  Checks a single entry in the threads table.
*
*  If it has no associated context or the key doesn't correspond to a living
*  thread, the entry is removed from the thread's list.
*/
static int
check_thread_i(st_data_t key, st_data_t value, st_data_t data)
{
  UNUSED(data);

  if (!value)
    return ST_DELETE;

  if (!is_living_thread((VALUE) key))
    return ST_DELETE;

  return ST_CONTINUE;
}

/*
*  Checks whether a thread is either in the running or sleeping state.
*/
int
is_living_thread(VALUE thread)
{
  VALUE status = rb_funcall(thread, rb_intern("status"), 0);

  if (NIL_P(status) || status == Qfalse)
    return 0;

  if (rb_str_cmp(status, rb_str_new2("run")) == 0
      || rb_str_cmp(status, rb_str_new2("sleep")) == 0)
    return 1;

  return 0;
}

/*
*  Checks threads table for dead/finished threads.
*/
void
cleanup_dead_threads(void)
{
  threads_table_t *t_tbl;

  Data_Get_Struct(threads, threads_table_t, t_tbl);
  st_foreach(t_tbl->tbl, check_thread_i, 0);
}

/*
* Looks up a context in the threads table. If not present, it creates it.
*/
void
thread_context_lookup(VALUE thread, VALUE * context)
{
  threads_table_t *t_tbl;

  Data_Get_Struct(threads, threads_table_t, t_tbl);

  if (!st_lookup(t_tbl->tbl, thread, context) || !*context)
  {
    *context = context_create(thread);
    st_insert(t_tbl->tbl, thread, *context);
  }
}

/*
* Holds thread execution while another thread is active.
*
* Thanks to this, all threads are "frozen" while the user is typing commands.
*/
void
acquire_lock(debug_context_t * dc)
{
  while ((!NIL_P(locker) && locker != rb_thread_current())
        || CTX_FL_TEST(dc, CTX_FL_SUSPEND))
  {
    add_to_locked(rb_thread_current());
    rb_thread_stop();

    if (CTX_FL_TEST(dc, CTX_FL_SUSPEND))
      CTX_FL_SET(dc, CTX_FL_WAS_RUNNING);
  }

  locker = rb_thread_current();
}

/*
* Releases our global lock and passes execution on to another thread, either
* the thread specified by +next_thread+ or any other thread if +next_thread+
* is nil.
*/
void
release_lock(void)
{
  VALUE thread;

  cleanup_dead_threads();

  locker = Qnil;

  if (NIL_P(next_thread))
    thread = pop_from_locked();
  else
  {
    remove_from_locked(next_thread);
    thread = next_thread;
  }

  if (thread == next_thread)
    next_thread = Qnil;

  if (!NIL_P(thread) && is_living_thread(thread))
    rb_thread_run(thread);
}

/*
*  call-seq:
*    Byebug.unlock -> nil
*
*  Unlocks global switch so other threads can run.
*/
static VALUE
Unlock(VALUE self)
{
  UNUSED(self);

  release_lock();

  return locker;
}

/*
*  call-seq:
*    Byebug.lock -> Thread.current
*
*  Locks global switch to reserve execution to current thread exclusively.
*/
static VALUE
Lock(VALUE self)
{
  debug_context_t *dc;
  VALUE context;

  UNUSED(self);

  if (!is_living_thread(rb_thread_current()))
    rb_raise(rb_eRuntimeError, "Current thread is dead!");

  thread_context_lookup(rb_thread_current(), &context);
  Data_Get_Struct(context, debug_context_t, dc);

  acquire_lock(dc);

  return locker;
}

/*
*
*    Document-class: ThreadsTable
*
*    == Sumary
*
*    Hash table holding currently active threads and their associated contexts
*/
void
Init_threads_table(VALUE mByebug)
{
  cThreadsTable = rb_define_class_under(mByebug, "ThreadsTable", rb_cObject);

  rb_define_module_function(mByebug, "unlock", Unlock, 0);
  rb_define_module_function(mByebug, "lock", Lock, 0);
}
```

## Future work

With the tasks performed in this grant, threading support is finished. The next
tasks will be to make sure the feature is working fine for our users and fix any
issues that might come up.

Regarding Byebug as a whole, the idea is that the next major release will
include a full rewrite / review of remote debugging support, and will make sure
that editor plugins or graphical debuggers can easily use byebug under the hood.


text:
ConVar	ai_debug_eventresponses( "ai_debug_eventresponses", "0", FCVAR_NONE, "Set to 1 to see all NPC response events trigger, and which NPCs choose to respond to them." );

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CNPCEventResponseSystem g_NPCEventResponseSystem( "CNPCEventResponseSystem" );

CNPCEventResponseSystem *NPCEventResponse()
{
	return &g_NPCEventResponseSystem;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPCEventResponseSystem::LevelInitPreEntity( void )
{
	m_ActiveEvents.Purge();
	m_flNextEventPoll = 0;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPCEventResponseSystem::TriggerEvent( const char *pResponse, bool bForce, bool bCancelScript )
{
	m_flNextEventPoll = gpGlobals->curtime;

	// Find the event by name
	int iIndex = m_ActiveEvents.Find( pResponse );
	if ( iIndex == m_ActiveEvents.InvalidIndex() )
	{
		storedevent_t newEvent;
		newEvent.flEventTime = gpGlobals->curtime;
		newEvent.flNextResponseTime = 0;
		newEvent.bForce = bForce;
		newEvent.bCancelScript = bCancelScript;
		newEvent.bPreventExpiration = false;
		m_ActiveEvents.Insert( pResponse, newEvent );

		if ( ai_debug_eventresponses.GetBool() )
		{
			Msg( "NPCEVENTRESPONSE: (%.2f) Trigger fired for event named: %s\n", gpGlobals->curtime, pResponse );
		}
	}
	else
	{
		// Update the trigger time
		m_ActiveEvents[iIndex].flEventTime = gpGlobals->curtime;
		m_ActiveEvents[iIndex].bForce = bForce;
		m_ActiveEvents[iIndex].bCancelScript = bCancelScript;

		if ( ai_debug_eventresponses.GetBool() )
		{
			Msg( "NPCEVENTRESPONSE: (%.2f) Trigger resetting already-active event firing named: %s\n", gpGlobals->curtime, pResponse );
		}
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPCEventResponseSystem::FrameUpdatePreEntityThink()
{
 	if ( !m_ActiveEvents.Count() || !AI_IsSinglePlayer() || !UTIL_GetLocalPlayer() )
		return;

	if ( m_flNextEventPoll > gpGlobals->curtime )
		return;
	m_flNextEventPoll = gpGlobals->curtime + 0.2;

	// Move through all events, removing expired ones and finding NPCs for active ones.
	for ( int i = m_ActiveEvents.First(); i != m_ActiveEvents.InvalidIndex(); )
	{
 		float flTime = m_ActiveEvents[i].flEventTime;
		const char *pResponse = m_ActiveEvents.GetElementName(i);

		// Save off the next index so we can safely remove this one
		int iNext = m_ActiveEvents.Next(i);

		// Should it have expired by now?
		if ( !m_ActiveEvents[i].bPreventExpiration && (flTime + NPCEVENTRESPONSE_GIVEUP_TIME) < gpGlobals->curtime )
		{
			if ( ai_debug_eventresponses.GetBool() )
			{
				Msg( "NPCEVENTRESPONSE: (%.2f) Removing expired event named: %s\n", gpGlobals->curtime, pResponse );
			}

			m_ActiveEvents.RemoveAt(i);
		}
		else if ( m_ActiveEvents[i].flNextResponseTime < gpGlobals->curtime )
		{
			// If we've fired once, and our current event should expire now, then expire.
			if ( m_ActiveEvents[i].bPreventExpiration && (flTime + NPCEVENTRESPONSE_GIVEUP_TIME) < gpGlobals->curtime )
			{
				if ( ai_debug_eventresponses.GetBool() )
				{
					Msg( "NPCEVENTRESPONSE: (%.2f) Removing expired fired event named: %s\n", gpGlobals->curtime, pResponse );
				}

				m_ActiveEvents.RemoveAt(i);
			}
			else
			{
				float flNearestDist = NPCEVENTRESPONSE_DISTANCE_SQR;
				CAI_BaseNPC *pNearestNPC = NULL;
				Vector vecPlayerCenter = UTIL_GetLocalPlayer()->WorldSpaceCenter();

				// Try and find the nearest NPC to the player
				CAI_BaseNPC **ppAIs = g_AI_Manager.AccessAIs();
				for ( int j = 0; j < g_AI_Manager.NumAIs(); j++ )
				{
					if ( ppAIs[j]->CanRespondToEvent( pResponse ))
					{
						float flDistToPlayer = ( vecPlayerCenter - ppAIs[j]->WorldSpaceCenter()).LengthSqr();
						if ( flDistToPlayer < flNearestDist )
						{
							flNearestDist = flDistToPlayer;
							pNearestNPC = ppAIs[j];
						}
					}
				}

				// Found one?
				if ( pNearestNPC )
				{
					if ( pNearestNPC->RespondedTo( pResponse, m_ActiveEvents[i].bForce, m_ActiveEvents[i].bCancelScript ) )
					{
						// Don't remove the response yet. Leave it around until the refire time has expired.
						// This stops repeated firings of the same concept from spamming the NPCs.
						m_ActiveEvents[i].bPreventExpiration = true;
						m_ActiveEvents[i].flNextResponseTime = gpGlobals->curtime + NPCEVENTRESPONSE_REFIRE_TIME;

						if ( ai_debug_eventresponses.GetBool() )
						{
							Msg( "NPCEVENTRESPONSE: (%.2f) Event '%s' responded to by NPC '%s'. Refire available at: %.2f\n", gpGlobals->curtime, pResponse, pNearestNPC->GetDebugName(), m_ActiveEvents[i].flNextResponseTime );
						}

						// Don't issue multiple responses at once
						return;
					}
				}
			}
		}

		i = iNext;
	}
}

//---------------------------------------------------------------------------------------------
// Entity version for mapmaker to hook into the system
//---------------------------------------------------------------------------------------------
class CNPCEventResponseSystemEntity : public CBaseEntity
{
	DECLARE_CLASS( CNPCEventResponseSystemEntity, CBaseEntity );
public:
	DECLARE_DATADESC();

	void	Spawn();
	void 	InputTriggerResponseEvent( inputdata_t &inputdata );
	void 	InputForceTriggerResponseEvent( inputdata_t &inputdata );
	void 	InputForceTriggerResponseEventNoCancel( inputdata_t &inputdata );
};

LINK_ENTITY_TO_CLASS( ai_npc_eventresponsesystem, CNPCEventResponseSystemEntity );

BEGIN_DATADESC( CNPCEventResponseSystemEntity )
	DEFINE_INPUTFUNC( FIELD_STRING,	"TriggerResponseEvent",	InputTriggerResponseEvent ),
	DEFINE_INPUTFUNC( FIELD_STRING,	"ForceTriggerResponseEvent", InputForceTriggerResponseEvent ),
	DEFINE_INPUTFUNC( FIELD_STRING,	"ForceTriggerResponseEventNoCancel", InputForceTriggerResponseEventNoCancel ),
END_DATADESC()

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPCEventResponseSystemEntity::Spawn( void )
{
	// Invisible, non solid.
	AddSolidFlags( FSOLID_NOT_SOLID );
	AddEffects( EF_NODRAW );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPCEventResponseSystemEntity::InputTriggerResponseEvent( inputdata_t &inputdata )
{
	NPCEventResponse()->TriggerEvent( inputdata.value.String(), false, false );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPCEventResponseSystemEntity::InputForceTriggerResponseEvent( inputdata_t &inputdata )
{
	NPCEventResponse()->TriggerEvent( inputdata.value.String(), true, true );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPCEventResponseSystemEntity::InputForceTriggerResponseEventNoCancel( inputdata_t &inputdata )
{
	NPCEventResponse()->TriggerEvent( inputdata.value.String(), true, false );
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Oro\Bundle\ActionBundle\Tests\Unit\Extension;

use Oro\Bundle\ActionBundle\Button\ButtonContext;
use Oro\Bundle\ActionBundle\Button\ButtonInterface;
use Oro\Bundle\ActionBundle\Button\ButtonSearchContext;
use Oro\Bundle\ActionBundle\Button\OperationButton;
use Oro\Bundle\ActionBundle\Exception\UnsupportedButtonException;
use Oro\Bundle\ActionBundle\Extension\OperationButtonProviderExtension;
use Oro\Bundle\ActionBundle\Helper\ContextHelper;
use Oro\Bundle\ActionBundle\Model\ActionData;
use Oro\Bundle\ActionBundle\Model\Criteria\OperationFindCriteria;
use Oro\Bundle\ActionBundle\Model\Operation;
use Oro\Bundle\ActionBundle\Model\OperationDefinition;
use Oro\Bundle\ActionBundle\Model\OperationRegistry;
use Oro\Bundle\ActionBundle\Model\OptionsAssembler;
use Oro\Bundle\ActionBundle\Provider\RouteProviderInterface;
use Oro\Bundle\ActionBundle\Tests\Unit\Stub\StubButton;

use Oro\Component\ConfigExpression\ContextAccessor;

class OperationButtonProviderExtensionTest extends \PHPUnit_Framework_TestCase
{
    const ENTITY_CLASS = 'stdClass';
    const ENTITY_ID = 42;
    const ROUTE_NAME = 'test_route_name';
    const EXECUTION_ROUTE_NAME = 'test_execution_route_name';
    const FORM_DIALOG_ROUTE_NAME = 'test_form_dialog_route_name';
    const FORM_PAGE_ROUTE_NAME = 'test_form_page_route_name';
    const DATAGRID_NAME = 'test_datagrid_name';
    const REFERRER_URL = '/test/referrer/utl';
    const GROUP = 'test_group';

    /** @var OperationButtonProviderExtension */
    protected $extension;

    /** @var \PHPUnit_Framework_MockObject_MockObject|ContextHelper */
    protected $contextHelper;

    /** @var \PHPUnit_Framework_MockObject_MockObject|OperationRegistry */
    protected $operationRegistry;

    /** @var \PHPUnit_Framework_MockObject_MockObject|RouteProviderInterface */
    protected $routeProvider;

    /** @var OptionsAssembler|\PHPUnit_Framework_MockObject_MockObject|RouteProviderInterface */
    protected $optionsAssembler;

    /** @var ContextAccessor|\PHPUnit_Framework_MockObject_MockObject|RouteProviderInterface */
    protected $contextAccessor;

    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        $this->operationRegistry = $this->getMockBuilder(OperationRegistry::class)
            ->disableOriginalConstructor()
            ->getMock();
        $this->contextHelper = $this->getMockBuilder(ContextHelper::class)->disableOriginalConstructor()->getMock();

        $this->routeProvider = $this->createMock(RouteProviderInterface::class);

        $this->routeProvider->expects($this->any())
            ->method('getExecutionRoute')
            ->willReturn(self::EXECUTION_ROUTE_NAME);

        $this->routeProvider->expects($this->any())
            ->method('getFormDialogRoute')
            ->willReturn(self::FORM_DIALOG_ROUTE_NAME);

        $this->routeProvider->expects($this->any())
            ->method('getFormPageRoute')
            ->willReturn(self::FORM_PAGE_ROUTE_NAME);

        $this->optionsAssembler = $this->createMock(OptionsAssembler::class);
        $this->optionsAssembler->expects($this->any())
            ->method('assemble')
            ->willReturnCallback(function (array $options) {
                return $options;
            });

        $this->contextAccessor = $this->createMock(ContextAccessor::class);

        $this->extension = new OperationButtonProviderExtension(
            $this->operationRegistry,
            $this->contextHelper,
            $this->routeProvider,
            $this->optionsAssembler,
            $this->contextAccessor
        );
    }

    /**
     * {@inheritdoc}
     */
    protected function tearDown()
    {
        unset($this->extension, $this->contextHelper, $this->operationRegistry, $this->routeProvider);
    }

    /**
     * @dataProvider findDataProvider
     *
     * @param array $operations
     * @param ButtonSearchContext $buttonSearchContext
     * @param array $expected
     */
    public function testFind(array $operations, ButtonSearchContext $buttonSearchContext, array $expected)
    {
        $this->assertOperationRegistryMethodsCalled($operations, $buttonSearchContext);
        $this->assertContextHelperCalled();

        $this->assertEquals($expected, $this->extension->find($buttonSearchContext));
    }

    /**
     * @return array
     */
    public function findDataProvider()
    {
        $operation1 = $this->createOperationMock('operation1', true);
        $operationSubstitution = $this->createOperationMock('operation_substitution', true, true);
        $operationNotAvailable = $this->createOperationMock('operation_not_available', false);

        $buttonSearchContext = $this->createButtonSearchContext();

        $buttonContext1 = $this->createButtonContext($buttonSearchContext);
        $buttonContext2 = $this->createButtonContext($buttonSearchContext, true);

        $actionData = new ActionData();

        return [
            'array' => [
                'operations' => [
                    'operation1' => $operation1,
                    'operation_not_available' => $operationNotAvailable,
                    'original_operation_name' => $operationSubstitution
                ],
                'buttonSearchContext' => $buttonSearchContext,
                'expected' => [
                    new OperationButton('operation1', $operation1, $buttonContext1, $actionData),
                    new OperationButton(
                        'operation_not_available',
                        $operationNotAvailable,
                        $buttonContext1,
                        $actionData
                    ),
                    new OperationButton(
                        'original_operation_name',
                        $operationSubstitution,
                        $buttonContext2,
                        $actionData
                    ),
                ]
            ],
            'not available' => [
                'operations' => ['operation_not_available' => $operationNotAvailable],
                'buttonSearchContext' => $buttonSearchContext,
                'expected' => [
                    new OperationButton(
                        'operation_not_available',
                        $operationNotAvailable,
                        $buttonContext1,
                        $actionData
                    )
                ]
            ]
        ];
    }

    /**
     * @dataProvider isAvailableDataProvider
     *
     * @param ButtonInterface $button
     * @param bool $expected
     */
    public function testIsAvailable(ButtonInterface $button, $expected)
    {
        $this->assertContextHelperCalled((int)($button instanceof OperationButton));
        $this->assertEquals($expected, $this->extension->isAvailable($button, $this->createButtonSearchContext()));
    }

    /**
     * @return array
     */
    public function isAvailableDataProvider()
    {
        $operationButtonAvailable = $this->createOperationButton(true);
        $operationButtonNotAvailable = $this->createOperationButton(false);

        return [
            'available' => [
                'button' => $operationButtonAvailable,
                'expected' => true
            ],
            'not available' => [
                'button' => $operationButtonNotAvailable,
                'expected' => false
            ]
        ];
    }

    public function testIsAvailableException()
    {
        $this->assertContextHelperCalled(0);

        $stubButton = new StubButton();

        $this->expectException(UnsupportedButtonException::class);
        $this->expectExceptionMessage(
            'Button Oro\Bundle\ActionBundle\Tests\Unit\Stub\StubButton is not supported by ' .
            'Oro\Bundle\ActionBundle\Extension\OperationButtonProviderExtension. Can not determine availability'
        );

        $this->extension->isAvailable($stubButton, $this->createButtonSearchContext());
    }

    public function testSupports()
    {
        $this->assertTrue($this->extension->supports($this->createOperationButton()));
        $this->assertFalse($this->extension->supports($this->createMock(ButtonInterface::class)));
    }

    /**
     * @param string $name
     * @param bool $isAvailable
     * @param bool $withForm
     * @return Operation|\PHPUnit_Framework_MockObject_MockObject
     */
    private function createOperationMock($name, $isAvailable = false, $withForm = false)
    {
        $operation = $this->getMockBuilder(Operation::class)->disableOriginalConstructor()->getMock();
        $definition = new OperationDefinition();
        $operation->expects($this->any())->method('getName')->willReturn($name);
        $operation->expects($this->any())->method('isAvailable')->willReturn($isAvailable);
        $operation->expects($this->any())->method('isEnabled')->willReturn(true);
        $operation->expects($this->any())->method('hasForm')->willReturn($withForm);
        $operation->expects($this->any())->method('getDefinition')->willReturn($definition);

        return $operation;
    }

    /**
     * @param bool $isOperationAvailable
     *
     * @return OperationButton
     */
    private function createOperationButton($isOperationAvailable = false)
    {
        $buttonSearchContext = $this->createButtonSearchContext();
        $buttonContext = $this->createButtonContext($buttonSearchContext);
        $data = new ActionData();

        $name = uniqid('operation_', true);

        return new OperationButton(
            $name,
            $this->createOperationMock($name, $isOperationAvailable),
            $buttonContext,
            $data
        );
    }

    /**
     * @return ButtonSearchContext
     */
    private function createButtonSearchContext()
    {
        $buttonSearchContext = new ButtonSearchContext();

        return $buttonSearchContext->setRouteName(self::ROUTE_NAME)
            ->setEntity(self::ENTITY_CLASS, self::ENTITY_ID)
            ->setDatagrid(self::DATAGRID_NAME)
            ->setGroup(self::GROUP)
            ->setReferrer(self::REFERRER_URL);
    }

    /**
     * @param ButtonSearchContext $buttonSearchContext
     * @param bool $isForm
     *
     * @return ButtonContext
     */
    private function createButtonContext(ButtonSearchContext $buttonSearchContext, $isForm = false)
    {
        $context = new ButtonContext();
        $context->setUnavailableHidden(true)
            ->setDatagridName($buttonSearchContext->getDatagrid())
            ->setEntity($buttonSearchContext->getEntityClass(), $buttonSearchContext->getEntityId())
            ->setRouteName($buttonSearchContext->getRouteName())
            ->setGroup($buttonSearchContext->getGroup())
            ->setExecutionRoute(self::EXECUTION_ROUTE_NAME);

        if ($isForm) {
            $context->setFormDialogRoute(self::FORM_DIALOG_ROUTE_NAME);
            $context->setFormPageRoute(self::FORM_PAGE_ROUTE_NAME);
        }

        return $context;
    }

    /**
     * @param array $operations
     * @param ButtonSearchContext $buttonSearchContext
     */
    private function assertOperationRegistryMethodsCalled(array $operations, ButtonSearchContext $buttonSearchContext)
    {
        $this->operationRegistry->expects($this->once())
            ->method('find')
            ->with(OperationFindCriteria::createFromButtonSearchContext($buttonSearchContext))
            ->willReturn($operations);
    }

    /**
     * @param int $callsCount
     */
    private function assertContextHelperCalled($callsCount = 1)
    {
        $this->contextHelper->expects($this->exactly($callsCount))
            ->method('getActionData')
            ->willReturn(new ActionData());
    }
}


text:
using MuJoCo

############################################################# mujoco startup

val = mj.activate("/home/klowrey/.mujoco/mjkey.txt")
println("Acivation: $val")

modelfile = joinpath(dirname(@__FILE__), "humanoid.xml")
pm = mj.loadXML(modelfile, C_NULL)

if pm == nothing
   println("Bad load")
   quit()
end

pd = mj.makeData(pm)

m = unsafe_load(pm)
d = unsafe_load(pd)

#for i=1:100
#   mj.step(pm, pd)
#end

function data(pd, field::Symbol, value)
   d = unsafe_load(pd) # memory copy, without pointers
   setfield!(d, field, value)
end

function data(pd, field::Symbol)
   d = unsafe_load(pd) # memory copy, without pointers
   return getfield(d, field)
end

# function for struct infos
#structinfo(T) = [(fieldoffset(T,i), fieldname(T,i), fieldtype(T,i)) for i = 1:nfields(T)]
structinfo(T) = Dict(fieldname(T,i)=>(fieldoffset(T,i),  fieldtype(T,i)) for i = 1:nfields(T))

dinfo = structinfo(mj.Data)
minfo = structinfo(mj.Model)
oinfo = structinfo(mj.Option)

optionoffset = minfo[:opt][1] # bit offset
viscosityoffset = oinfo[:viscosity][1] # bit offset

# sets viscosity in model.options
#unsafe_store!(convert(Ptr{mjtNum}, (pm + optionoffset + viscosityoffset)), 1234.5678)

mtypes = [fieldtype(mj.Model, i) for i=1:nfields(mj.Model)]
dtypes = [fieldtype(mj.Data, i) for i=1:nfields(mj.Data)]

# BROKEN::
function update_model(m::mjModel, field::Symbol, val::mjtNum)
   setfield!(m, field, val)
   return m
end
function update_model(m::mjModel, field::Symbol, val::Integer)
   setfield!(m, field, convert(Cint, val))
   return m
end

# convert to macro?
#function update_model(pm::Ptr{mjModel}, field::Symbol, val::Integer)
#   f_off, f_type = minfo[field] # get offset & type
#   #@assert f_type == typeof(val)
#   # pointer math in julia is bytes, not of type offsets
#   unsafe_store!(convert(Ptr{f_type}, (pm + f_off)), convert(Cint, val))
#end

# pointer math in julia is bytes, not of type size
function update_model(pm::Ptr{mjModel}, offset::Integer, val::Integer)
   unsafe_store!(convert(Ptr{Cint}, (pm + offset)), convert(Cint, val))
end
function update_model(pm::Ptr{mjtNum}, offset::Integer, val::mjtNum)
   unsafe_store!(convert(Ptr{mjtNum}, (pm + offset)), val)
end

function update_model(pm::Ptr{mjModel}, field::Symbol, val::Union{Integer, mjtNum})
   f_off, f_type = minfo[field] # get offset & type
   @assert f_type == typeof(val) || f_type == typeof(convert(Cint, val))

   update_model(pm, f_off, convert(f_type, val)) # so that we can write ints
end

function mutatemodel!(pm)
   m = unsafe_load(pm)
   update_model(m, :nq, 222)
   unsafe_store!(pm, m)
end

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

function bad_map_data(pd::Ptr{mj.Data})
   # FUCKING NOPE
   c_data = unsafe_load(pd)
   mydata = unsafe_load( Ptr{jlData}(Libc.malloc(sizeof(jlData))) ) # make our data
   mydata.d = pd

   ptr_fields = intersect( fieldnames(jlData), fieldnames(mj.Data) )

   for f in ptr_fields
      #qpos = unsafe_wrap(Array, d.qpos, m.nq)
      mydata.f = unsafe_wrap(Array, c_data.f, f_size[f])
   end
end

function map_data(pm::Ptr{mjModel}, pd::Ptr{mj.Data})
   c_data = unsafe_load(pd)
   #mydata = unsafe_load( Ptr{jlData}(Libc.malloc(sizeof(jlData))) ) # make our data
   #mydata.d = pd
   args = Array{Any}(1)
   args[1] = pd

   ptr_fields = intersect( fieldnames(jlData), fieldnames(mjData) )

   f_size = mj.getdatasize(unsafe_load(pm), unsafe_load(pd))

   for f in ptr_fields
      push!(args, unsafe_wrap(Array, getfield(c_data, f), f_size[f]) )
   end
   return jlData(args...)
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>get_test_property — CMake 3.8.2 Documentation</title>

    <link rel="stylesheet" href="../_static/cmake.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="if" href="if.html" />
    <link rel="prev" title="get_target_property" href="get_target_property.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.8.2 Documentation »

cmake-commands(7) »

get_test_property¶

Get a property of the test.

get_test_property(test property VAR)

Get a property from the test.  The value of the property is stored in
the variable VAR.  If the test or property is not found, VAR will
be set to “NOTFOUND”.  For a list of standard properties you can type
cmake --help-property-list.

See also the more general get_property() command.

Previous topic

get_target_property

Next topic

if

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Navigation

          index

          next |

          previous |

    CMake »

    3.8.2 Documentation »

cmake-commands(7) »

        © Copyright 2000-2017 Kitware, Inc. and Contributors.
      Created using Sphinx 1.5.2.


text:
<!doctype html>

    <title>Code coverage report for src/components/Login.vue</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../prettify.css" />
    <link rel="stylesheet" href="../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      all files / src/components/ Login.vue

        0%
        Statements
        0/27

        0%
        Branches
        0/12

        0%
        Functions
        0/2

        0%
        Lines
        0/27

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134

<template>
  <div class="container container-table">
      <div class="row vertical-10p">
        <div class="container">
          <img src="/static/img/logo.png" class="center-block logo">
          <div class="text-center col-md-4 col-sm-offset-4">
            <!-- login form -->
            <form class="ui form loginForm"  @submit.prevent="checkCreds">

              <div class="input-group">
                <span class="input-group-addon"><i class="fa fa-envelope"></i></span>
                <input class="form-control" name="username" placeholder="Username" type="text" v-model="username">
              </div>

              <div class="input-group">
                <span class="input-group-addon"><i class="fa fa-lock"></i></span>
                <input class="form-control" name="password" placeholder="Password" type="password" v-model="password">
              </div>
              <button type="submit" v-bind:class="'btn btn-primary btn-lg ' + loading">Submit</button>
            </form>

            <!-- errors -->
            <div v-if=response class="text-red"><p>{{response}}</p></div>
          </div>
        </div>
      </div>
  </div>
</template>

<script>
import api from '../api'

export default {
  name: 'Login',
  data (router) {
    return {
      section: 'Login',
      loading: '',
      username: '',
      password: '',
      response: ''
    }
  },
  methods: {
    checkCreds () {
      const {username, password} = this

      this.toggleLoading()
      this.resetResponse()
      this.$store.commit('TOGGLE_LOADING')

      /* Making API call to authenticate a user */
      api.request('post', '/login', {email: username, password})
      .then(response => {
        this.toggleLoading()

        var data = response.data
        /* Checking if error object was returned from the server */
        if (data.error) {
          var errorName = data.error.name
          if (errorName) {
            this.response = errorName === 'InvalidCredentialsError'
            ? 'Username/Password incorrect. Please try again.'
            : errorName
          } else {
            this.response = data.error
          }

          return
        }

        /* Setting user in the state and caching record to the localStorage */
        if (data.user) {
          var token = 'Bearer ' + data.token

          this.$store.commit('SET_USER', data.user)
          this.$store.commit('SET_TOKEN', token)

          this.$ls.set('user', data.user)
          this.$ls.set('token', token)

          this.$router.push(data.redirect ? data.redirect : '/')
        }
      })
      .catch(error => {
        this.$store.commit('TOGGLE_LOADING')
        console.log(error)

        this.response = 'Server appears to be offline'
        this.toggleLoading()
      })
    },
    toggleLoading () {
      this.loading = (this.loading === '') ? 'loading' : ''
    },
    resetResponse () {
      this.response = ''
    }
  }
}
</script>

<style>
html, body, .container-table {
  height: 100%;
  background-color: #282B30 !important;
}
.container-table {
    display: table;
    color: white;
}
.vertical-center-row {
    display: table-cell;
    vertical-align: middle;
}
.vertical-20p {
  padding-top: 20%;
}
.vertical-10p {
  padding-top: 10%;
}
.logo {
  width: 15em;
  padding: 3em;
}
.loginForm .input-group {
  padding-bottom: 1em;
  height: 4em;
}
.input-group input {
  height: 4em;
}
</style>

  Code coverage
  generated by istanbul at Mon Oct 30 2017 14:34:10 GMT-0700 (PDT)


text:
package org.brutusin.fleadb.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.DoubleField;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.facet.FacetField;
import org.apache.lucene.index.IndexableField;
import org.brutusin.commons.Pair;
import org.brutusin.json.ValidationException;
import org.brutusin.json.util.LazyJsonNode;
import org.brutusin.json.spi.JsonCodec;
import org.brutusin.json.spi.JsonNode;
import org.brutusin.json.spi.JsonSchema;
import org.brutusin.fleadb.DocTransformer;
import org.brutusin.fleadb.Schema;
import org.brutusin.json.spi.Expression;

/**
 *
 * @author Ignacio del Valle Alles idelvall@brutusin.org
 */
public class JsonTransformer implements DocTransformer<JsonNode> {

    private static final FieldType NON_INDEXED_TYPE = new FieldType();
    private static final String OBJECT_FIELD_NAME = "$json";

    static {
        NON_INDEXED_TYPE.setIndexed(false);
        NON_INDEXED_TYPE.setStored(true);
    }

    private final Schema schema;
    private final JsonSchema jsonSchema;

    public JsonTransformer(Schema schema) {
        this.schema = schema;
        try {
            if (schema != null) {
                this.jsonSchema = schema.getJSONSChema();
            } else {
                this.jsonSchema = null;
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public Pair<Document, List<FacetField>> entityToDocument(JsonNode jsonNode) {
        if (jsonNode == null) {
            return null;
        }
        try {
            jsonSchema.validate(jsonNode);
        } catch (ValidationException e) {
            throw new RuntimeException("Error transforming entity: " + jsonNode, e);
        }
        Document doc = new Document();
        doc.add(new Field(OBJECT_FIELD_NAME, jsonNode.toString(), NON_INDEXED_TYPE));
        Pair<Document, List<FacetField>> ret = new Pair<Document, List<FacetField>>();
        ret.setElement1(doc);
        Pair<List<IndexableField>, List<FacetField>> indexTerms = getIndexTerms(jsonNode);
        ret.setElement2(indexTerms.getElement2());

        List<IndexableField> indexFields = indexTerms.getElement1();
        for (IndexableField field : indexFields) {
            doc.add(field);
        }
        return ret;
    }

    private Pair<List<IndexableField>, List<FacetField>> getIndexTerms(JsonNode jsonNode) {
        Pair<List<IndexableField>, List<FacetField>> ret = new Pair<List<IndexableField>, List<FacetField>>();
        final List<IndexableField> indexFields = new ArrayList<IndexableField>();
        ret.setElement1(indexFields);
        final List<FacetField> facets = new ArrayList<FacetField>();
        ret.setElement2(facets);

        Map<String, JsonNode.Type> fields = this.schema.getIndexFields();

        for (Map.Entry<String, JsonNode.Type> entry : fields.entrySet()) {
            String indexField = entry.getKey();
            Expression exp = JsonCodec.getInstance().compile(indexField);
            JsonNode projectedNode = exp.projectNode(jsonNode);
            if (projectedNode != null) {
                addLuceneIndexFields(indexField, indexFields, projectedNode, exp.projectSchema(jsonSchema));
            }
        }

        Map<String, Boolean> facetFields = this.schema.getFacetFields();
        for (String facetField : facetFields.keySet()) {
            Expression exp = JsonCodec.getInstance().compile(facetField);
            JsonNode projectedNode = exp.projectNode(jsonNode);
            if (projectedNode != null) {
                addLuceneFacets(facetField, facets, projectedNode);
            }
        }
        return ret;
    }

    private void addLuceneFacets(String facetField, List<FacetField> list, JsonNode node) {
        JsonNode.Type type = node.getNodeType();
        if (type == JsonNode.Type.ARRAY) {
            for (int i = 0; i < node.getSize(); i++) {
                addLuceneFacets(facetField, list, node.get(i));
            }
        } else if (type == JsonNode.Type.OBJECT) {
            Iterator<String> properties = node.getProperties();
            while (properties.hasNext()) {
                String propName = properties.next();
                list.add(new FacetField(facetField, propName));
            }
        } else if (type == JsonNode.Type.STRING) {
            list.add(new FacetField(facetField, node.asString()));
        } else if (type == JsonNode.Type.BOOLEAN) {
            list.add(new FacetField(facetField, node.asString()));
        } else {
            throw new UnsupportedOperationException("Node type " + type + " not supported for facet field " + facetField);
        }
    }

    private void addLuceneIndexFields(String indexField, List<IndexableField> list, JsonNode node, JsonSchema nodeSchema) {
        JsonNode.Type type = nodeSchema.getSchemaType();
        if (type == JsonNode.Type.ARRAY) {
            for (int i = 0; i < node.getSize(); i++) {
                addLuceneIndexFields(indexField, list, node.get(i), nodeSchema.getItemSchema());
            }
        } else if (type == JsonNode.Type.OBJECT) {
            Iterator<String> properties = node.getProperties();
            while (properties.hasNext()) {
                String propName = properties.next();
                // Index property key for object nodes
                list.add(new StringField(indexField, propName, Field.Store.NO));
            }
        } else if (type == JsonNode.Type.STRING) {
            list.add(new StringField(indexField, node.asString(), Field.Store.NO));
        } else if (type == JsonNode.Type.BOOLEAN) {
            list.add(new StringField(indexField, node.asString(), Field.Store.NO));
        } else if (type == JsonNode.Type.INTEGER) {
            list.add(new LongField(indexField, node.asLong(), Field.Store.NO));
        } else if (type == JsonNode.Type.NUMBER) {
            list.add(new DoubleField(indexField, node.asDouble(), Field.Store.NO));
        } else {
            throw new UnsupportedOperationException("Node type " + type + " not supported for index field " + indexField);
        }
    }

    public JsonNode documentToEntity(Document doc) {
        return new LazyJsonNode(doc.get(OBJECT_FIELD_NAME));
    }
}


text:
package com.llb.nature.fragment;

import java.util.ArrayList;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;

import com.llb.nature.R;
import com.llb.nature.adapter.WebApp2GridviewAdapter;
import com.llb.nature.domain.WebAppItem2Bean;

public class WebApp2Fragment extends Fragment{
	private View view=null;
	private ArrayList<WebAppItem2Bean> list;
	private WebApp2GridviewAdapter adapter;
	private GridView gridView;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		list=new ArrayList<WebAppItem2Bean>();
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if(view==null){
			view=inflater.inflate(R.layout.webapp2_fragment,null);
			gridView=(GridView) view.findViewById(R.id.gridview);

			initList();
			adapter=new WebApp2GridviewAdapter(view.getContext(), list);
		}
		ViewGroup parent = (ViewGroup) view.getParent();
		if(parent!=null){
			parent.removeView(view);//先移除
		}

		gridView.setAdapter(adapter);

		return view;
	}
	private void initList() {
		// TODO Auto-generated method stub
		for(int i=0;i<8;i++){
			list.add(new WebAppItem2Bean("图片url","游戏", "暗黑世界、神魔仙界、植物大战僵尸", 0));
		}
	}
}


text:
package com.tapglue.android.entities;

import com.google.gson.annotations.SerializedName;

public class Connection {
    @SerializedName("user_to_id_string")
    private final String userToId;
    @SerializedName("user_from_id_string")
    private String userFromId;
    @SerializedName("type")
    private final Type type;
    @SerializedName("state")
    private final String state;
    private transient User userTo;
    private transient User userFrom;

    public Connection(User userTo, Type type, State state) {
        this.userTo = userTo;
        this.userToId = userTo.getId();
        this.type = type;
        this.state = state.toString().toLowerCase();
    }

    public User getUserTo() {
        return userTo;
    }

    public void setUserFrom(User userFrom) {
        this.userFrom = userFrom;
    }

    public void setUserTo(User userTo) {
        this.userTo = userTo;
    }

    public User getUserFrom() {
        return userFrom;
    }

    public String getUserToId() {
        return userToId;
    }

    public String getUserFromId() {
        return userFromId;
    }

    public Type getType() {
        return this.type;
    }

    public enum Type {
        @SerializedName("follow")
        FOLLOW,
        @SerializedName("friend")
        FRIEND;

        @Override
        public String toString() {
            return this.name().toLowerCase();
        }
    }
    public enum State {
        PENDING, CONFIRMED, REJECTED
    }
}


text:
<!DOCTYPE html>

<html>

<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="../style/styles.css">
   <script src="styles/style.js"> </script>

  <title>Thesis Work</title>
</head>

<?php include '../includes/header.php';?>

<body>

Thesis Work

</body>

<?php include '../includes/footer.php';?>

</html>


text:
module HBaseMetrics
  VERSION = "0.0.3"
end


text:
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/**
 * Provides requestAnimationFrame in a cross browser way.
 * http://paulirish.com/2011/requestanimationframe-for-smart-animating/
 */

if ( !window.requestAnimationFrame ) {

	window.requestAnimationFrame = ( function() {

		return window.webkitRequestAnimationFrame ||
		window.mozRequestAnimationFrame ||
		window.oRequestAnimationFrame ||
		window.msRequestAnimationFrame ||
		function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element ) {

			window.setTimeout( callback, 1000 / 60 );

		};

	} )();

}

},{}]},{},[1])


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Monosporium griseum Rabenh.

### Remarks
null


text:
namespace TileMapEditor.Forms
{
    partial class frm_OutputPictureMap
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.txtWidth = new System.Windows.Forms.NumericUpDown();
            this.label8 = new System.Windows.Forms.Label();
            this.txtHeight = new System.Windows.Forms.NumericUpDown();
            this.label7 = new System.Windows.Forms.Label();
            this.txtOutputPath = new TileMapEditor.Controls.ControlsEx.PromptTextBox();
            this.btnBrowse = new System.Windows.Forms.Button();
            this.label4 = new System.Windows.Forms.Label();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.label3 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.cbbFormat = new System.Windows.Forms.ComboBox();
            this.btnConfirm = new System.Windows.Forms.Button();
            this.btnCancel = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.txtWidth)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.txtHeight)).BeginInit();
            this.groupBox1.SuspendLayout();
            this.SuspendLayout();
            //
            // txtWidth
            //
            this.txtWidth.Location = new System.Drawing.Point(74, 80);
            this.txtWidth.Maximum = new decimal(new int[] {
            9999,
            0,
            0,
            0});
            this.txtWidth.Minimum = new decimal(new int[] {
            1,
            0,
            0,
            0});
            this.txtWidth.Name = "txtWidth";
            this.txtWidth.Size = new System.Drawing.Size(80, 21);
            this.txtWidth.TabIndex = 19;
            this.txtWidth.Value = new decimal(new int[] {
            1,
            0,
            0,
            0});
            //
            // label8
            //
            this.label8.AutoSize = true;
            this.label8.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.label8.Location = new System.Drawing.Point(39, 85);
            this.label8.Name = "label8";
            this.label8.Size = new System.Drawing.Size(29, 12);
            this.label8.TabIndex = 18;
            this.label8.Text = "宽度";
            //
            // txtHeight
            //
            this.txtHeight.Location = new System.Drawing.Point(74, 107);
            this.txtHeight.Maximum = new decimal(new int[] {
            9999,
            0,
            0,
            0});
            this.txtHeight.Minimum = new decimal(new int[] {
            1,
            0,
            0,
            0});
            this.txtHeight.Name = "txtHeight";
            this.txtHeight.Size = new System.Drawing.Size(80, 21);
            this.txtHeight.TabIndex = 21;
            this.txtHeight.Value = new decimal(new int[] {
            1,
            0,
            0,
            0});
            //
            // label7
            //
            this.label7.AutoSize = true;
            this.label7.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.label7.Location = new System.Drawing.Point(39, 111);
            this.label7.Name = "label7";
            this.label7.Size = new System.Drawing.Size(29, 12);
            this.label7.TabIndex = 20;
            this.label7.Text = "高度";
            //
            // txtOutputPath
            //
            this.txtOutputPath.ForeColor = System.Drawing.Color.Gray;
            this.txtOutputPath.Location = new System.Drawing.Point(74, 26);
            this.txtOutputPath.Name = "txtOutputPath";
            this.txtOutputPath.PromptText = "";
            this.txtOutputPath.Size = new System.Drawing.Size(234, 21);
            this.txtOutputPath.TabIndex = 8;
            //
            // btnBrowse
            //
            this.btnBrowse.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btnBrowse.Font = new System.Drawing.Font("微软雅黑", 7.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.btnBrowse.Location = new System.Drawing.Point(314, 25);
            this.btnBrowse.Name = "btnBrowse";
            this.btnBrowse.Size = new System.Drawing.Size(37, 22);
            this.btnBrowse.TabIndex = 5;
            this.btnBrowse.Text = "浏览";
            this.btnBrowse.UseVisualStyleBackColor = true;
            //
            // label4
            //
            this.label4.AutoSize = true;
            this.label4.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.label4.Location = new System.Drawing.Point(15, 30);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(53, 12);
            this.label4.TabIndex = 1;
            this.label4.Text = "导出位置";
            //
            // groupBox1
            //
            this.groupBox1.Controls.Add(this.label3);
            this.groupBox1.Controls.Add(this.label2);
            this.groupBox1.Controls.Add(this.label1);
            this.groupBox1.Controls.Add(this.txtHeight);
            this.groupBox1.Controls.Add(this.txtWidth);
            this.groupBox1.Controls.Add(this.label7);
            this.groupBox1.Controls.Add(this.cbbFormat);
            this.groupBox1.Controls.Add(this.label4);
            this.groupBox1.Controls.Add(this.txtOutputPath);
            this.groupBox1.Controls.Add(this.label8);
            this.groupBox1.Controls.Add(this.btnBrowse);
            this.groupBox1.Location = new System.Drawing.Point(6, 8);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(361, 140);
            this.groupBox1.TabIndex = 27;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "导出设置";
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.label3.Location = new System.Drawing.Point(155, 111);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(41, 12);
            this.label3.TabIndex = 24;
            this.label3.Text = "(像素)";
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.label2.Location = new System.Drawing.Point(155, 85);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(41, 12);
            this.label2.TabIndex = 23;
            this.label2.Text = "(像素)";
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.label1.Location = new System.Drawing.Point(15, 58);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(53, 12);
            this.label1.TabIndex = 22;
            this.label1.Text = "图片格式";
            //
            // cbbFormat
            //
            this.cbbFormat.FormattingEnabled = true;
            this.cbbFormat.Items.AddRange(new object[] {
            "PNG",
            "BMP",
            "JPEG"});
            this.cbbFormat.Location = new System.Drawing.Point(74, 54);
            this.cbbFormat.Name = "cbbFormat";
            this.cbbFormat.Size = new System.Drawing.Size(121, 20);
            this.cbbFormat.TabIndex = 9;
            //
            // btnConfirm
            //
            this.btnConfirm.Location = new System.Drawing.Point(211, 154);
            this.btnConfirm.Name = "btnConfirm";
            this.btnConfirm.Size = new System.Drawing.Size(75, 23);
            this.btnConfirm.TabIndex = 28;
            this.btnConfirm.Text = "确 定";
            this.btnConfirm.UseVisualStyleBackColor = true;
            //
            // btnCancel
            //
            this.btnCancel.Location = new System.Drawing.Point(292, 154);
            this.btnCancel.Name = "btnCancel";
            this.btnCancel.Size = new System.Drawing.Size(75, 23);
            this.btnCancel.TabIndex = 29;
            this.btnCancel.Text = "取 消";
            this.btnCancel.UseVisualStyleBackColor = true;
            //
            // frm_OutputPictureMap
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(373, 181);
            this.Controls.Add(this.btnCancel);
            this.Controls.Add(this.btnConfirm);
            this.Controls.Add(this.groupBox1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "frm_OutputPictureMap";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "图片格式导出地图";
            ((System.ComponentModel.ISupportInitialize)(this.txtWidth)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.txtHeight)).EndInit();
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.NumericUpDown txtWidth;
        private System.Windows.Forms.Label label8;
        private System.Windows.Forms.NumericUpDown txtHeight;
        private System.Windows.Forms.Label label7;
        private TileMapEditor.Controls.ControlsEx.PromptTextBox txtOutputPath;
        private System.Windows.Forms.Button btnBrowse;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.ComboBox cbbFormat;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button btnConfirm;
        private System.Windows.Forms.Button btnCancel;
    }
}


text:
<?php

namespace SMW\Tests\Cache;

use SMW\Cache\FixedInMemoryCache;

/**
 * @covers \SMW\Cache\FixedInMemoryCache
 *
 * @group SMW
 * @group SMWExtension
 *
 * @license GNU GPL v2+
 * @since 2.1
 *
 * @author mwjames
 */
class FixedInMemoryCacheTest extends \PHPUnit_Framework_TestCase {

	public function testCanConstruct() {

		$this->assertInstanceOf(
			'\SMW\Cache\FixedInMemoryCache',
			new FixedInMemoryCache()
		);
	}

	public function testItemRemoval() {

		$instance = new FixedInMemoryCache( 5 );

		$instance->save( 'foo', array( 'foo' ) );
		$instance->save( 42, null );

		$this->assertTrue( $instance->contains( 'foo' ) );
		$this->assertTrue( $instance->contains( 42 ) );

		$stats = $instance->getStats();
		$this->assertEquals(
			2,
			$stats['count']
		);

		$instance->delete( 'foo' );

		$this->assertFalse( $instance->contains( 'foo' ) );
		$this->assertFalse( $instance->delete( 'foo' ) );

		$stats = $instance->getStats();
		$this->assertEquals(
			1,
			$stats['count']
		);
	}

	public function testLeastRecentlyUsedShiftForLimitedCacheSize() {

		$instance = new FixedInMemoryCache( 5 );
		$instance->save( 'berlin', array( 'berlin' ) );

		$this->assertEquals(
			array( 'berlin' ),
			$instance->fetch( 'berlin' )
		);

		foreach ( array( 'paris', 'london', '東京', '北京', 'new york' ) as $city ) {
			$instance->save( $city, array( $city ) );
		}

		// 'paris' was added and removes 'berlin' from the cache
		$this->assertFalse( $instance->fetch( 'berlin' ) );

		$stats = $instance->getStats();
		$this->assertEquals(
			5,
			$stats['count']
		);

		// 'paris' moves to the top (last postion as most recently used) and
		// 'london' becomes the next LRU candidate
		$this->assertEquals(
			array( 'paris' ),
			$instance->fetch( 'paris' )
		);

		$instance->save( 'rio', 'rio' );
		$this->assertFalse( $instance->fetch( 'london' ) );

		// 東京 would be the next LRU slot but setting it again will move it to MRU
		// and push 北京 into the next LRU position
		$instance->save( '東京', '東京' );

		$instance->save( 'sidney', 'sidney' );
		$this->assertFalse( $instance->fetch( '北京' ) );

		$stats = $instance->getStats();
		$this->assertEquals(
			5,
			$stats['count']
		);
	}

}


text:
all:

ELFFILE=$(shell ls /tmp/arduino_build_*/*elf -tr | tail -n 1)
ESP32BINDIR=$(wildcard $(HOME)/.arduino15/packages/esp32/tools/xtensa-esp32-elf-gcc/*/bin/)

PREFIX=$(ESP32BINDIR)/xtensa-esp32-elf-
GDB=$(PREFIX)gdb
OBJDUMP=$(PREFIX)objdump
NM=$(PREFIX)nm

OPENOCD=/opt/openocd/default-esp32/src/openocd
OPENOCDSCRIPTS=/opt/openocd/default-esp32/tcl

gdbx:
	$(GDB) $(ELFFILE)

gdb:
	killall -9 openocd || exit 0
	$(OPENOCD) --search $(OPENOCDSCRIPTS) -f interface/ftdi/olimex-arm-usb-tiny-h.cfg  -f board/esp32-solo-1.cfg -c "adapter_khz 1000" & disown
	sleep 2
	$(GDB) $(ELFFILE) -ex "target remote :3333" -ex "set remotetimeout 6000"  -ex "set remote hardware-watchpoint-limit 2" -ex "mon reset halt" -ex "flushregs" -ex "thb app_main" -ex "c"
	killall -9 openocd || exit 0

#	$(OPENOCD) --search $(OPENOCDSCRIPTS) -f interface/ftdi/olimex-arm-usb-tiny-h.cfg  -f board/esp-wroom-32.cfg -c "adapter_khz 1000" & disown

#target remote :3333
#set remote hardware-watchpoint-limit 2
#mon reset halt
#flushregs
#thb app_main
#c

lst:
	$(OBJDUMP) -C -d -h $(ELFFILE) > target.lst

nm:
	$(NM) -C $(ELFFILE) | sort > target.nm


text:
package com.googlecode.totallylazy.predicates;

import com.googlecode.totallylazy.functions.Function1;
import com.googlecode.totallylazy.Callers;

import java.util.HashSet;
import java.util.Set;

public class UniquePredicate<T, S> extends LogicalPredicate<T> {
    private final Function1<? super T, ? extends S> callable;
    private final Set<S> valuesSeen = new HashSet<S>();

    public UniquePredicate(Function1<? super T, ? extends S> callable) {
        this.callable = callable;
    }

    @Override
    public boolean matches(T other) {
        return valuesSeen.add(Callers.call(callable, other));
    }
}


text:
<me.yugy.github.reveallayout.RevealLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/reveal_layout"
                tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Use this layout on api 18+ devices because of the hardware acceleration issue"
        android:background="#0099cc"
        android:gravity="center"
        android:textSize="32sp"
        android:textColor="#FFF"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="At last, enjoy it!"
        android:background="#aa66cc"
        android:gravity="center"
        android:textSize="32sp"
        android:textColor="#FFF"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="ClickToToggleViews"
        android:background="#669900"
        android:gravity="center"
        android:textSize="32sp"
        android:textColor="#FFF"
        />

</me.yugy.github.reveallayout.RevealLayout>


text:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <SwitchPreference
        android:key="allergens_palm_oil"
        android:id="@+id/pref_key_palm_oil"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:title="@string/txt_allergens_palm_oil"
        android:summaryOff="Off"
        android:summaryOn ="On"
        android:defaultValue="false"
        android:icon="@drawable/ic_palm"
        />

    <SwitchPreference
        android:key="allergens_gluten"
        android:id="@+id/pref_key_gluten"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:title="@string/txt_allergens_gluten"
        android:summaryOff="Off"
        android:summaryOn ="On"
        android:defaultValue="false"
        android:icon="@drawable/ic_gluten"
        />

    <SwitchPreference
        android:key="allergens_eggs"
        android:id="@+id/pref_key_eggs"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:title="@string/txt_allergens_eggs"
        android:summaryOff="@string/txt_off"
        android:summaryOn ="@string/txt_on"
        android:defaultValue="false"
        android:icon="@drawable/ic_egg"
        />

    <SwitchPreference
        android:key="allergens_fish"
        android:id="@+id/pref_key_fish"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:title="@string/txt_allergens_fish"
        android:summaryOff="@string/txt_off"
        android:summaryOn ="@string/txt_on"
        android:defaultValue="false"
        android:icon="@drawable/ic_fish"
        />

    <SwitchPreference
        android:key="allergens_soy"
        android:id="@+id/pref_key_soy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:title="@string/txt_allergens_soy"
        android:summaryOff="@string/txt_off"
        android:summaryOn ="@string/txt_on"
        android:defaultValue="false"
        android:icon="@drawable/ic_soybean"
        />

    <SwitchPreference
        android:key="allergens_milk"
        android:id="@+id/pref_key_milk"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:title="@string/txt_allergens_milk"
        android:summaryOff="@string/txt_off"
        android:summaryOn ="@string/txt_on"
        android:defaultValue="false"
        android:icon="@drawable/ic_milk"
        />

    <SwitchPreference
        android:key="allergens_nuts"
        android:id="@+id/pref_key_nuts"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:title="@string/txt_allergens_nuts"
        android:summaryOff="@string/txt_off"
        android:summaryOn ="@string/txt_on"
        android:defaultValue="false"
        android:icon="@drawable/ic_peanut"
        />

</PreferenceScreen>


text:
declare namespace ಠ_ಠ.clutz.namespace {
  interface I {
  }
}
declare namespace ಠ_ಠ.clutz.namespace.I {
  interface InnerR {
    foo : boolean ;
  }
}
declare module 'goog:namespace.I' {
  import alias = ಠ_ಠ.clutz.namespace.I;
  export default alias;
}
declare namespace ಠ_ಠ.clutz.namespace {
  interface R {
    foo : boolean ;
    optionalFoo ? : boolean ;
  }
}
declare module 'goog:namespace.R' {
  import alias = ಠ_ಠ.clutz.namespace.R;
  export default alias;
}
declare namespace ಠ_ಠ.clutz {
  interface externR {
    foo : boolean ;
  }
}


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'db/snapshot'


text:
(function(global, fam) {
  'use strict';

  var JoypadsBase = {
    getIdentifier: function() { return 'JoypadsBase'; },
    getButtons: function() {
      return [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
    },
    getAssignments: function() {
      return [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
    },
    applyAssignments: function(settings) {},
    detectButton: function(index, target, callback) {},
  };

  // A, B, select, start, up, down, left, right
  var DEFAULT_BUTTON_CODES = [
    // 1P
    90, 88, 65, 83, 38, 40, 37, 39,
    // 2P (not assigned yet)
    0, 0, 0, 0, 0, 0, 0, 0,
  ];

  var KeyboardJoypads = fam.extend(function(target) {
    this.target = this.setTarget(target);
    this.buttonCodes_ = DEFAULT_BUTTON_CODES;
    this.keys_ = [];
    for (var i = 0; i < 16; ++i)
      this.keys_[this.buttonCodes_[i]] = 0;
  }, JoypadsBase);

  KeyboardJoypads.prototype.setTarget = function(target) {
    this.target = target;
    var self = this;
    this.target.addEventListener('keydown', function(e) {
      self.keys_[e.keyCode] = 1;
      e.preventDefault();
    });
    this.target.addEventListener('keyup', function(e) {
      self.keys_[e.keyCode] = 0;
      e.preventDefault();
    });
  };

  KeyboardJoypads.prototype.getIdentifier = function() {
    return 'KeyboardJoypads';
  }

  KeyboardJoypads.prototype.getButtons = function() {
    var buttons = [];
    for (var i = 0; i < 16; ++i)
      buttons[i] = this.keys_[this.buttonCodes_[i]];
    return buttons;
  };

  KeyboardJoypads.prototype.getAssignments = function() {
    return this.buttonCodes_.map(function(code) {
      return '' + code;
    });
  };

  KeyboardJoypads.prototype.applyAssignments = function(settings) {
    for (var i = 0; i < 16; ++i)
      this.buttonCodes_[i] = parseInt(settings[i]);
  };

  KeyboardJoypads.prototype.detectButton = function(index, target, callback) {
    var handler = (function(e) {
      // Don't assign tab and shift
      if (e.keyCode == 9 || e.keyCode == 16)
        return;

      e.target.removeEventListener('keydown', handler);
      this.buttonCodes_[index] = e.keyCode;
      callback(index, e.keyCode);
      e.preventDefault();
    }).bind(this);

    target.addEventListener('keydown', handler);
    return;
  };

  fam.KeyboardJoypads = KeyboardJoypads;

  var AXES = ['[UP]', '[DOWN]', '[LEFT]', '[RIGHT]'];

  // TODO(bashi): Support multiple gamepads
  var GamepadsBase = {
    init: function(index) {
      this.buttons_ = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
      this.padIndex_ = index;
      this.buttonMappings_ = [0,1,2,3];

      this.settingButtonIndex_ = -1;
      this.settingCallback_ = function() {};
      this.settingLoop_ = (function() {
        var index = this.settingButtonIndex_;
        var callback = this.settingCallback_;
        var pad = this.pad();
        if (index >= 0 && pad) {
          for (var i = 0; i < pad.buttons.length; ++i) {
            if (pad.buttons[i] <= 0)
              continue;

            this.settingButtonIndex_ = -1;
            this.settingCallback_ = function() {};
            setTimeout(function () { callback(index, 'button-' + i); }, 200);
            return;
          }
          window.requestAnimationFrame(this.settingLoop_);
        }
      }).bind(this);
    },
    getIdentifier: function() { return 'JoypadsBase'; },
    getButtons: function() {
      var pad = this.pad();
      // TODO(bashi): Support disconnection.
      if (!pad) {
        fam.log('cannot find: ' + this.padIndex_);
        return this.buttons_;
      }
      // A, B, select, start, up, down, left, right
      for (var i = 0; i < 4; ++i)
        this.buttons_[i] = pad.buttons[this.buttonMappings_[i]];
      this.buttons_[4] = pad.axes[1] < -0.5;
      this.buttons_[5] = pad.axes[1] > 0.5;
      this.buttons_[6] = pad.axes[0] < -0.5;
      this.buttons_[7] = pad.axes[0] > 0.5;

      return this.buttons_;
    },
    getAssignments: function() {
      var assignments = this.buttonMappings_.map(function(b) {
        return 'button-' + b;
      });
      return assignments.concat(AXES);
    },
    applyAssignments: function(assignments) {
      var pad = this.pad();
      if (!pad)
        return;
      assignments = assignments.slice(0, 4)
        .map(function(i) { return parseInt(i.replace('button-', '')); })
        .filter(function(i) { return i >= 0 && i < pad.buttons.length; });
      if (assignments.length != 4)
        return;
      this.buttonMappings_ = assignments;
    },
    detectButton: function(index, target, callback) {
      // Don't support axes assignment
      if (index > 3) {
        setTimeout(function() { callback(index, AXES[index-4]); }, 200);
        return;
      }

      this.settingButtonIndex_ = index;
      this.settingCallback_ = callback;
      window.requestAnimationFrame(this.settingLoop_);
      return;
    },
  };

  var ChromeGamepad = fam.extend(function(index) {
    this.pad = function() { return navigator.webkitGetGamepads()[this.padIndex_]; };
    this.init(index);
  }, GamepadsBase);

  ChromeGamepad.prototype.getIdentifier = function() {
    return 'ChromeGamepad';
  };

  var detectChromeGamepad = function(callback) {
    if (!navigator || !navigator.webkitGetGamepads)
      return;
    var numGamepads = navigator.webkitGetGamepads().length;
    for (var i = 0; i < numGamepads; ++i) {
      if (navigator.webkitGetGamepads()[i]) {
        var gamepad = new ChromeGamepad(i);
        callback(gamepad);
        return;
      }
    }
    requestAnimationFrame(detectChromeGamepad);
  };

  var mozGamepads = {};

  var MozGamepad = fam.extend(function(index) {
    this.pad = function() { return mozGamepads[this.padIndex_]; };
    this.init(index);
  }, GamepadsBase);

  MozGamepad.prototype.getIdentifier = function() {
    return 'MozGamepad';
  };

  // TODO(bashi): Support disconnection
  var detectMozGamepad = function(callback) {
    window.addEventListener('MozGamepadConnected', function(e) {
      console.log(e);
      mozGamepads[e.gamepad.index] = e.gamepad;
      callback(new MozGamepad(e.gamepad.index));
    });
  };

  fam.detectGamepad =
    navigator.userAgent.indexOf('Firefox') > 0 ? detectMozGamepad : detectChromeGamepad;
})(this, this.fam = this.fam || {});


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

		<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
		<title>PMD Java 5.2.2 Reference Package net.sourceforge.pmd.lang.java.symboltable</title>
		<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="style" />

        	net.sourceforge.pmd.lang.java.symboltable

Classes

            	AcceptanceTest

            	ApplierTest

            	ClassScopeTest

            	GlobalScopeTest

            	ImageFinderFunctionTest

            	LocalScopeTest

            	MethodNameDeclarationTest

            	MethodScopeTest

            	MyFunction

            	NameOccurrencesTest

            	STBBaseTst

            	ScopeCreationVisitorTest

            	SimpleTypedNameDeclarationTest

            	SourceFileScopeTest

            	TypeSetTest

            	VariableNameDeclarationTest

            	VariableUsageFinderFunctionTest


text:
package distribution

import (
	"fmt"

	"github.com/Sirupsen/logrus"
	"github.com/docker/docker/api"
	"github.com/docker/docker/distribution/metadata"
	"github.com/docker/docker/distribution/xfer"
	"github.com/docker/docker/image"
	"github.com/docker/docker/pkg/progress"
	"github.com/docker/docker/reference"
	"github.com/docker/docker/registry"
	"github.com/docker/engine-api/types"
	"golang.org/x/net/context"
)

// ImagePullConfig stores pull configuration.
type ImagePullConfig struct {
	// MetaHeaders stores HTTP headers with metadata about the image
	MetaHeaders map[string][]string
	// AuthConfig holds authentication credentials for authenticating with
	// the registry.
	AuthConfig *types.AuthConfig
	// ProgressOutput is the interface for showing the status of the pull
	// operation.
	ProgressOutput progress.Output
	// RegistryService is the registry service to use for TLS configuration
	// and endpoint lookup.
	RegistryService *registry.Service
	// ImageEventLogger notifies events for a given image
	ImageEventLogger func(id, name, action string)
	// MetadataStore is the storage backend for distribution-specific
	// metadata.
	MetadataStore metadata.Store
	// ImageStore manages images.
	ImageStore image.Store
	// ReferenceStore manages tags.
	ReferenceStore reference.Store
	// DownloadManager manages concurrent pulls.
	DownloadManager *xfer.LayerDownloadManager
}

// Puller is an interface that abstracts pulling for different API versions.
type Puller interface {
	// Pull tries to pull the image referenced by `tag`
	// Pull returns an error if any, as well as a boolean that determines whether to retry Pull on the next configured endpoint.
	//
	Pull(ctx context.Context, ref reference.Named) error
}

// newPuller returns a Puller interface that will pull from either a v1 or v2
// registry. The endpoint argument contains a Version field that determines
// whether a v1 or v2 puller will be created. The other parameters are passed
// through to the underlying puller implementation for use during the actual
// pull operation.
func newPuller(endpoint registry.APIEndpoint, repoInfo *registry.RepositoryInfo, imagePullConfig *ImagePullConfig) (Puller, error) {
	switch endpoint.Version {
	case registry.APIVersion2:
		return &v2Puller{
			V2MetadataService: metadata.NewV2MetadataService(imagePullConfig.MetadataStore),
			endpoint:          endpoint,
			config:            imagePullConfig,
			repoInfo:          repoInfo,
		}, nil
	case registry.APIVersion1:
		return &v1Puller{
			v1IDService: metadata.NewV1IDService(imagePullConfig.MetadataStore),
			endpoint:    endpoint,
			config:      imagePullConfig,
			repoInfo:    repoInfo,
		}, nil
	}
	return nil, fmt.Errorf("unknown version %d for registry %s", endpoint.Version, endpoint.URL)
}

// Pull initiates a pull operation. image is the repository name to pull, and
// tag may be either empty, or indicate a specific tag to pull.
func Pull(ctx context.Context, ref reference.Named, imagePullConfig *ImagePullConfig) error {
	// Resolve the Repository name from fqn to RepositoryInfo
	repoInfo, err := imagePullConfig.RegistryService.ResolveRepository(ref)
	if err != nil {
		return err
	}

	// makes sure name is not empty or `scratch`
	if err := validateRepoName(repoInfo.Name()); err != nil {
		return err
	}

	endpoints, err := imagePullConfig.RegistryService.LookupPullEndpoints(repoInfo)
	if err != nil {
		return err
	}

	var (
		lastErr error

		// discardNoSupportErrors is used to track whether an endpoint encountered an error of type registry.ErrNoSupport
		// By default it is false, which means that if a ErrNoSupport error is encountered, it will be saved in lastErr.
		// As soon as another kind of error is encountered, discardNoSupportErrors is set to true, avoiding the saving of
		// any subsequent ErrNoSupport errors in lastErr.
		// It's needed for pull-by-digest on v1 endpoints: if there are only v1 endpoints configured, the error should be
		// returned and displayed, but if there was a v2 endpoint which supports pull-by-digest, then the last relevant
		// error is the ones from v2 endpoints not v1.
		discardNoSupportErrors bool

		// confirmedV2 is set to true if a pull attempt managed to
		// confirm that it was talking to a v2 registry. This will
		// prevent fallback to the v1 protocol.
		confirmedV2 bool
	)
	for _, endpoint := range endpoints {
		if confirmedV2 && endpoint.Version == registry.APIVersion1 {
			logrus.Debugf("Skipping v1 endpoint %s because v2 registry was detected", endpoint.URL)
			continue
		}
		logrus.Debugf("Trying to pull %s from %s %s", repoInfo.Name(), endpoint.URL, endpoint.Version)

		puller, err := newPuller(endpoint, repoInfo, imagePullConfig)
		if err != nil {
			lastErr = err
			continue
		}
		if err := puller.Pull(ctx, ref); err != nil {
			// Was this pull cancelled? If so, don't try to fall
			// back.
			fallback := false
			select {
			case <-ctx.Done():
			default:
				if fallbackErr, ok := err.(fallbackError); ok {
					fallback = true
					confirmedV2 = confirmedV2 || fallbackErr.confirmedV2
					err = fallbackErr.err
				}
			}
			if fallback {
				if _, ok := err.(registry.ErrNoSupport); !ok {
					// Because we found an error that's not ErrNoSupport, discard all subsequent ErrNoSupport errors.
					discardNoSupportErrors = true
					// append subsequent errors
					lastErr = err
				} else if !discardNoSupportErrors {
					// Save the ErrNoSupport error, because it's either the first error or all encountered errors
					// were also ErrNoSupport errors.
					// append subsequent errors
					lastErr = err
				}
				continue
			}
			logrus.Debugf("Not continuing with error: %v", err)
			return err
		}

		imagePullConfig.ImageEventLogger(ref.String(), repoInfo.Name(), "pull")
		return nil
	}

	if lastErr == nil {
		lastErr = fmt.Errorf("no endpoints found for %s", ref.String())
	}

	return lastErr
}

// writeStatus writes a status message to out. If layersDownloaded is true, the
// status message indicates that a newer image was downloaded. Otherwise, it
// indicates that the image is up to date. requestedTag is the tag the message
// will refer to.
func writeStatus(requestedTag string, out progress.Output, layersDownloaded bool) {
	if layersDownloaded {
		progress.Message(out, "", "Status: Downloaded newer image for "+requestedTag)
	} else {
		progress.Message(out, "", "Status: Image is up to date for "+requestedTag)
	}
}

// validateRepoName validates the name of a repository.
func validateRepoName(name string) error {
	if name == "" {
		return fmt.Errorf("Repository name can't be empty")
	}
	if name == api.NoBaseImageSpecifier {
		return fmt.Errorf("'%s' is a reserved name", api.NoBaseImageSpecifier)
	}
	return nil
}


text:
using namespace hyperion;

int main()
{
	QString homeDir = getenv("RASPILIGHT_HOME");

	const QString schemaFile = homeDir + "/hyperion.schema.json";
	const QString configFile = homeDir + "/hyperion.config.json";

	QJsonObject config;
	if (QJsonFactory::load(schemaFile, configFile, config) < 0)
	{
		std::cerr << "UNABLE TO LOAD CONFIGURATION" << std::endl;
		return -1;
	}

	const LedString ledString = Hyperion::createLedString(config["leds"], Hyperion::createColorOrder(config["device"].toObject()));

	const ColorRgb testColor = {64, 123, 12};

	Image<ColorRgb> image(64, 64, testColor);
	ImageToLedsMap map(64, 64, 0, 0, ledString.leds());

	std::vector<ColorRgb> ledColors(ledString.leds().size());
	map.getMeanLedColor(image, ledColors);

	std::cout << "[";
	for (const ColorRgb & color : ledColors)
	{
		std::cout << color;
	}
	std::cout << "]" << std::endl;

	return 0;
}


text:
#import <Foundation/NSObject.h>

@class WebFrame, NSMutableArray, DOMElement, DOMHTMLInputElement, NSMutableDictionary;

@interface FormAutoFiller : NSObject {
	WebFrame* _frame;
	DOMElement* _form;
	int _formType;
	DOMHTMLInputElement* _usernameElement;
	DOMHTMLInputElement* _passwordElement;
	NSMutableArray* _autoFilledControls;
	NSMutableDictionary* _fieldsFilledFromAB;
	NSMutableArray* _continuationFields;
	BOOL _hasAutoFilled;
}
+(id)autoFillerForFrame:(id)frame form:(id)form create:(BOOL)create;
+(id)matchForControl:(id)control rep:(id)rep fieldLabels:(id)labels useFieldName:(BOOL)name foundByPageScan:(BOOL*)scan;
+(id)abMatchInFrame:(id)frame form:(id)form fieldName:(id)name;
+(BOOL)isContinuationField:(id)field inFrame:(id)frame form:(id)form;
+(void)recordABMatch:(id)match inFrame:(id)frame form:(id)form fieldName:(id)name;
+(void)clearAutoFillStateForFrame:(id)frame;
+(void)clearAutoFilledTextField:(id)field inFrame:(id)frame form:(id)form;
+(int)indexOfItemInSelectElement:(id)selectElement forSynonyms:(id)synonyms;
+(id)radioButtonGroupContaining:(id)containing inFormElements:(id)formElements;
+(int)indexOfItemInRadioButtonGroup:(id)radioButtonGroup forSynonyms:(id)synonyms;
+(id)fieldNameForAutoFillOfControl:(id)control rep:(id)rep respectHTMLAutocompleteAttribute:(BOOL)attribute;
-(id)init;
-(void)dealloc;
-(id)visibleControlsInForm;
-(void)_scanElements;
-(int)formType;
-(id)usernameElement;
-(id)passwordElement;
-(int)_itemInSelectElement:(id)selectElement forMatch:(id)match;
-(id)_decomposeStreetAddress:(id)address style:(int)style;
-(void)_insertABValue:(id)value inTextFieldElement:(id)textFieldElement match:(id)match fieldName:(id)name;
-(int)_reflectMultiFieldMatch:(id)match inControls:(id)controls currIndex:(unsigned)index fieldName:(id)name isPhoneNumber:(BOOL)number;
-(int)_reflectAutoFillMatch:(id)match inControls:(id)controls currIndex:(int)index fieldName:(id)name;
-(BOOL)hasAutoFilled;
-(BOOL)autoFill;
-(void)autoFillAddressStartingAtControl:(id)control match:(id)match;
-(int)autoFillPhoneOrZipStartingAtControl:(id)control match:(id)match;
-(void)recordABMatch:(id)match fieldName:(id)name;
-(void)recordABContinuationField:(id)field;
-(void)clearAutoFilledTextField:(id)field;
@end


text:
<!DOCTYPE html>
<iframe src="{{location[scheme]}}://{{domains[www2]}}:{{ports[http][0]}}{{location[path]}}/../EventListener-incumbent-global-subsubframe.sub.html"></iframe>
<script>
  document.domain = "{{host}}";
  onmessage = function(e) {
    if (e.data == "start") {
      frames[0].document.body.addEventListener("click", frames[0].getTheListener());
      frames[0].postMessage("sendclick", "*");
    } else {
      parent.postMessage(e.data, "*");
    }
  }
</script>


text:
package model

import (
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/utils"

	"strings"
)

type BatchStartServersOption struct {
	// 云服务器ID列表

	Servers []ServerId `json:"servers"`
}

func (o BatchStartServersOption) String() string {
	data, err := utils.Marshal(o)
	if err != nil {
		return "BatchStartServersOption struct{}"
	}

	return strings.Join([]string{"BatchStartServersOption", string(data)}, " ")
}


text:
class SpheroPwn::ChannelRecorder
  # @param {Channel} the channel being recorded
  # @param {String} recording_path the file where the recording will be saved
  def initialize(channel, recording_path)
    @channel = channel
    @file = File.open recording_path, 'wt'

    @is_receiving = false
  end

  # @see {Channel#recv_bytes}
  def recv_bytes(count)
    bytes = @channel.recv_bytes count
    return bytes if bytes.nil?

    unless @is_receiving
      @file.write '<'
      @is_receiving = true
    end
    log_bytes bytes
    @file.flush

    bytes
  end

  # @see {Channel#send_bytes}
  def send_bytes(bytes)
    if @is_receiving
      @file.write "\n"
      @is_receiving = false
    end

    @file.write '>'
    log_bytes bytes
    @file.write "\n"
    @file.flush

    @channel.send_bytes bytes
    self
  end

  # @see {Channel#close}
  def close
    if @is_receiving
      @file.write "\n"
    end
    @file.close
    @channel.close
    self
  end

  # @param {String} bytes the bytes to be written to the output file
  def log_bytes(bytes)
    unless bytes.empty?
      @file.write bytes.unpack('C*').map { |byte| ' %02X' % byte }.join('')
    end
  end
  private :log_bytes
end