text:
#include "vixen.h"
#pragma optimize ("", off)	// VS2012 hangs during code generation if this file is optimized

namespace Vixen {
static const TCHAR* opnames[] = { TEXT("SetScene") };

const TCHAR** World3D::DoNames = opnames;

VX_IMPLEMENT_CLASSID(World3D, World, VX_World3D);

VX_IMPLEMENT_CLASSID(SceneLoader, FileLoader, VX_Loader);

/*****
 *
 *	Forces all of the built-in classes to be referenced.
 *	(If we don't do this, the entries in the classes table are not
 *	initialized unless the caller explicity references the classes.
 *	This doesn't work if you are reading in a binary file with classes
 *	in it that your program hasn't referenced)
 *
 ****/
World3D::World3D() : World()
{
	REGISTER_CLASS(Appearance);
	REGISTER_CLASS(Scene);
	REGISTER_CLASS(Shape);
	REGISTER_CLASS(TriMesh);
	REGISTER_CLASS(Texture);
	REGISTER_CLASS(Light);
	REGISTER_CLASS(Camera);
	REGISTER_CLASS(Material);
	REGISTER_CLASS(Sampler);
	REGISTER_CLASS(Deformer);
	REGISTER_CLASS(Skin);
	REGISTER_CLASS(Skeleton);
	REGISTER_CLASS(MeshAnimator);

	RawInput = false;
	WinRect.Set(0,0,0,0);
	Scene::Debug = 0;
}

bool World3D::OnInit()
{
//
// Initialize loader, messenger and observations
//
	Messenger*	disp = m_Messenger;
	FileLoader*	load = m_LoadQueue;

	if (load == NULL)
	{
		m_LoadQueue = load = new SceneLoader;
		SetFileName(m_FileName);
	}
	if (disp == NULL)
		m_Messenger = disp = new BufMessenger;
	if (!World::OnInit())
		return false;
	Matrix::GetIdentity();
	vixen_debug.precision(3);
//
// Initialize system event names
//
	Event::SetName(Event::LOAD_SCENE, TEXT("LoadScene"));
	Event::SetName(Event::MOUSE, TEXT("Mouse"));
	Event::SetName(Event::KEY, TEXT("Key"));
	Event::SetName(Event::START, TEXT("Start"));
	Event::SetName(Event::STOP, TEXT("Stop"));
	Event::SetName(Event::RESET, TEXT("Reset"));
	Event::SetName(Event::PICK, TEXT("Pick"));
	Event::SetName(Event::NOPICK, TEXT("NoPick"));
	Event::SetName(Event::SELECT, TEXT("Select"));
	Event::SetName(Event::DESELECT, TEXT("DeSelect"));
	Event::SetName(Event::SET_TIME, TEXT("SetTime"));
	Event::SetName(Event::NAVIGATE, TEXT("Navigate"));
	Event::SetName(Event::NAVINPUT, TEXT("NavInput"));
	Event::SetName(Event::ATTACH_SCENE, TEXT("AttachScene"));
	Event::SetName(Event::ENTER, TEXT("Enter"));
	Event::SetName(Event::LEAVE, TEXT("Leave"));
	Event::SetName(Event::MIDI, TEXT("Midi"));
	Event::SetName(Event::EXEC, TEXT("Exec"));
	Event::SetName(Event::SCENE_CHANGE, TEXT("SceneChange"));
	Event::SetName(Event::SAVE_SCREEN, TEXT("SaveScreen"));
	Event::SetName(Event::CONNECT, TEXT("Connect"));
	Event::SetName(Event::ERROR, TEXT("Error"));
	Event::SetName(Event::TRI_HIT, TEXT("TriHit"));
	Event::SetName(Event::TRACK, TEXT("Track"));
	Event::SetName(Event::SCENE_INIT, TEXT("SceneInit"));
//
// Initialize system event types
//
	Event::SetDataTypes(Event::LOAD_SCENE, TEXT("SO"));
	Event::SetDataTypes(Event::MOUSE, TEXT("FFI"));
	Event::SetDataTypes(Event::KEY, TEXT("II"));
	Event::SetDataTypes(Event::START, NULL);
	Event::SetDataTypes(Event::STOP, NULL);
	Event::SetDataTypes(Event::RESET, NULL);
	Event::SetDataTypes(Event::PICK, TEXT("O"));
	Event::SetDataTypes(Event::NOPICK, NULL);
	Event::SetDataTypes(Event::SELECT, TEXT("O"));
	Event::SetDataTypes(Event::DESELECT, TEXT("O"));
	Event::SetDataTypes(Event::SET_TIME, TEXT("I"));
	Event::SetDataTypes(Event::SCENE_CHANGE, TEXT("OI"));
	Event::SetDataTypes(Event::COLLIDE, TEXT("I"));
	Event::SetDataTypes(Event::NAVIGATE, TEXT("IFFFFFFFFFFF"));
	Event::SetDataTypes(Event::NAVINPUT, TEXT("FFFII"));
	Event::SetDataTypes(Event::ATTACH_SCENE, NULL);
	Event::SetDataTypes(Event::ENTER, TEXT("OOFFF"));
	Event::SetDataTypes(Event::LEAVE, TEXT("OOFFF"));
	Event::SetDataTypes(Event::MIDI, TEXT("II"));
	Event::SetDataTypes(Event::EXEC, TEXT("SSI"));
	Event::SetDataTypes(Event::SAVE_SCREEN, TEXT("SS"));
	Event::SetDataTypes(Event::CONNECT, TEXT("I"));
	Event::SetDataTypes(Event::ERROR, TEXT("IIS"));
	Event::SetDataTypes(Event::TRI_HIT, TEXT("OFFFFII"));
	Event::SetDataTypes(Event::TRACK, TEXT("IIIFFFFFFFS"));
//
// Initialize file types
//
	load->SetFileFunc(TEXT("vix"), &SceneLoader::ReadScene, Event::LOAD_SCENE);
//	load->SetFileFunc(TEXT("bvh"), &BVHLoader::ReadAnim, Event::LOAD_SCENE);
	load->SetFileFunc(TEXT("scp"), &FileLoader::ReadText, Event::LOAD_TEXT);
	load->SetFileFunc(TEXT("txt"), &FileLoader::ReadText, Event::LOAD_TEXT);
	load->SetFileFunc(TEXT("cso"), &FileLoader::ReadBinary, Event::LOAD_DATA);
	load->SetFileFunc(TEXT("bmp"), &Bitmap::ReadFile, Event::LOAD_IMAGE);
	load->SetFileFunc(TEXT("txf"), &Bitmap::ReadFile, Event::LOAD_IMAGE);
	load->SetFileFunc(TEXT("png"), &Bitmap::ReadFile, Event::LOAD_IMAGE);
	load->SetFileFunc(TEXT("jpg"), &Bitmap::ReadFile, Event::LOAD_IMAGE);
	load->SetFileFunc(TEXT("dds"), &Bitmap::ReadFile, Event::LOAD_IMAGE);
	load->SetFileFunc(TEXT("tga"), &Bitmap::ReadFile, Event::LOAD_IMAGE);
	load->SetFileFunc(TEXT("tif"), &Bitmap::ReadFile, Event::LOAD_IMAGE);
	load->SetFileFunc(TEXT("sgi"), &Bitmap::ReadFile, Event::LOAD_IMAGE);
	m_Messenger->t_NoLog = false;			// enable transaction logging
	Bitmap::Startup();
	disp->Observe(this, Event::KEY, NULL);
	disp->Observe(this, Event::MOUSE, NULL);
	disp->Observe(this, Event::SCENE_CHANGE, NULL);
	disp->Observe(this, Event::ATTACH_SCENE, NULL);
	disp->Observe(this, Event::LOAD_SCENE, NULL);
	disp->Observe(this, Event::ERROR, NULL);
	MakeLock();
	return true;
}

/*!
 * @fn Scene* World3D::NewScene(Window win, Scene* inscene)
 * @param win	window to associate with the display scene
 *				if NULL, no window is bound to scene
 *
 * Class factory for the display scene. This function
 * is called once by the framework at startup to instantiate
 * a scene bound to a display (or capable of multi-threaded
 * operation). Usually, this scene is used throughout for
 * communicating with the display device. Changing the
 * current scene causes the existing display scene to
 * reference a new simulation tree and scene graph.
 *
 * Each port of the scene manager supplies a version of NewScene that
 * constructs a display scene bound to the appropriate device.
 * If you supply your own implementation for World3D::NewScene,
 * the library version will not be used. You may want to do this
 * to enable multi-threaded rendering.
 *
 * @return pointer to an empty display scene attached to the window
 *
 * @see World3D::SetScene Scene World3D::MakeScene
 */
Scene* World3D::NewScene(Window win, Scene* inscene)
{
#ifdef VX_NOTHREAD
	Scene*		display_scene = (Scene*) GetScene(win);
	Scene*		scene = inscene;

	if (display_scene)
	{
		if (scene == NULL)
			scene =  new Scene(*display_scene);
		display_scene->Append(scene);
		return scene;
	}
	if (scene == NULL)
		inscene = scene = new Scene(Renderer::CreateRenderer());
#else
	DualScene* display_scene = (DualScene*) GetScene(win);
	DualScene*	scene;
	if (display_scene)
	{
		if (inscene)
		{
			display_scene->Append(inscene);
			return inscene;
		}
		else
		{
			scene =  new DualScene(*display_scene);
			display_scene->Append(scene);
			return scene;
		}
	}
	if (inscene == NULL)
	{
		scene = new DualScene(Renderer::CreateRenderer());
		scene->SetNumThreads(0);
		inscene = scene;
	}
#endif
	inscene->SetOptions(Scene::CLEARALL | Scene::STATESORT | Scene::DOUBLEBUFFER);
	return inscene;
}

void World3D::OnExit()
{
	m_Scenes.Empty();
	World::OnExit();
	Bitmap::Shutdown();
	if (Matrix::s_IdentityMatrix)			// clean up identity matrix
	{
		Matrix::s_IdentityMatrix->Delete();
		Matrix::s_IdentityMatrix = NULL;
	}
	Scene::Shutdown();
}

/*!
 * @fn Scene *World3D::GetScene(Window win) const
 * @param win	Window to get the scene for. if NULL, the first
 *				scene created is returned
 *
 * @return scene associated with the given window.
 *
 * @see Scene::Get World3D::SetScene
 */
Scene *World3D::GetScene(Window win) const
{
	int n = (int) m_Scenes.GetSize();
	for (int i = 0; i <  n; ++i)
	{
		Scene* scene = (Scene*) (SharedObj*) m_Scenes[i];
		if (scene && (scene->GetWindow() == win))
			return scene;
	}
	if ((win != Window(NULL)) || (n <= 0))
		return NULL;
// NOLA: m_Scenes[0] does not work the same as GetAt(0) with Intel Compiler
//	return (Scene*) (SharedObj*) m_Scenes[0];
	return (Scene*) (SharedObj*) m_Scenes.GetAt(0);
}

void World3D::AddScene(Scene *newscene, Window win)
{
	ObjectLock	lock(this);
	int n = (int) m_Scenes.GetSize();
	for (int i = 0; i < n; ++i)
	{
		Scene* scene = (Scene*) (SharedObj*) m_Scenes[i];
		if (scene == newscene)
			return;
		if (scene && (scene->GetWindow() == win))
		{
			m_Scenes.SetAt(i, newscene);
			return;
		}
	}
// NOLA: m_Scene.Append(newscene) does not work with Intel compiler
	m_Scenes.SetAt(n, newscene);
	VX_ASSERT(GetScene() == newscene);
}

bool World3D::KillScene(Scene *scene)
{
	ObjectLock	lock(this);
	for (intptr i = 0; i < m_Scenes.GetSize(); ++i)
		if (m_Scenes.GetAt(i) == scene)
		{
			m_Scenes.RemoveAt(i);
			--i;
		}
	if (m_Scenes.GetSize() > 0)
		return false;
	return true;
}

/*!
 * @fn bool World3D::Run(Window arg)
 * @param arg	window handle to use for primary display scene
 *
 * Adds a new window to the world and makes the primary display scene
 * for the window which starts up display thread(s).
 * If the application has been given a filename, the specified
 * content file is loaded.
 *
 * This routine is not automatically called by the system, it must be initiated
 * by application code.
 *
 * @return \b true if window and scene successfully made, else \b false
 *
 * @see Scene::SetWindow World::SetFileName World::Run World3D::MakeScene
 */
bool World3D::Run(Window arg)
{
	Window	win = arg;
	Scene*	scene = GetScene(win);	// get scene for this window
	int		nscenes = (int) m_Scenes.GetSize();
	ObjRef	inscene;
	Event*	ev;

	if (scene == NULL)					// no scene for input window?
		scene = GetScene(0);			// was any scene created?
	if (scene)							// make sure the scene has a window
	{
		if (scene->GetWindow() == 0)
			scene->SetWindow(win);		// start scene threads
	}
	else								// no scene
	{
		scene = NewScene(win);			// make a new scene
		if (scene == NULL)				// can't make a scene?
			return false;
		if (win && !scene->SetWindow(win))
		{
			scene->Delete();
			return false;
		}
	}
	ev = new Event(Event::SCENE_INIT, sizeof(ObjRef), scene);
	ev->Log();
	World::Run(arg);					// save the window handle
	if (DoAsyncLoad && m_FileName[0])	// load a content file?
	{
		SetFileName(m_FileName);
		return LoadAsync(m_FileName, scene);
	}
	inscene = MakeScene();				// blocking load
	if (!inscene.IsNull())
	{
		LoadSceneEvent* event = new LoadSceneEvent(Event::LOAD_SCENE);
		event->Object = inscene;
		event->Sender = scene;
		event->FileName = m_FileName;
		event->Log();
		return true;
	}
	m_Messenger->Flush();
	m_Messenger->Load();				// process any error events
	return false;
}

/*!
 * @fn void World3D::Stop()
 *
 * Initiates shutdown of all loading and display threads for all
 * scenes attached to this world. This routine does not return until
 * all loading, scene traversal and rendering threads have stopped.
 *
 * @see World3D::Run World::Stop
 */
void World3D::Stop()
{
	/*
	 * Lock around streaming only. We don't want to hold a lock
	 * when shutting the system down.
	 */
	{
		VX_STREAM_BEGIN( s )
			*s << OP(VX_World3D, WORLD_Stop) << this;
		VX_STREAM_END( );
	}

	Scene*		scene;
	int			nscenes = (int) m_Scenes.GetSize();

	for (int i = 0; i < nscenes; ++i)
	{
		scene = (Scene*) (SharedObj*) m_Scenes[i];
		if (scene)								// have another scene?
			scene->SetWindow(NULL);				// stop its display
	}
	OnExit();
}

/*!
 *@fn void World3D::SetScene(Scene *scene, Window win)
 * @param scene	New scene to display, NULL turns off display
 * @param win	Window whose scene to update. If NULL, the first
 *				scene created is updated
 *
 * The display scene associated with the input window is set
 * to reference the input scene (which is not used further
 * and is not garbage collected).
 * If the application has no display scene, nothing is done.
 * If the input scene is NULL, the display scene is removed
 * from the application and freed.
 *
 * This routine is called from the display thread to change the current scene.
 * If it is called directly from another thread, the command is logged by
 * the messenger and deferred until the start of the next frame.
 *
 * @see World3D::MakeScene World3D::NewScene
 */
void World3D::SetScene(Scene *scene, Window win)
{
	VX_STREAM_ASYNC_BEGIN(s)
		*s << OP(VX_World3D, WORLD3D_SetScene) << this << scene << int64(win);
	VX_STREAM_ASYNC_END();

	Scene*	display_scene;

	if (win == Window(NULL))
		display_scene = (Scene*) (SharedObj*) m_Scenes[0];
	else
	{
		for (intptr i = 0; i < m_Scenes.GetSize(); ++i)
		{
			display_scene = (Scene*) (SharedObj*) m_Scenes[i];
			if (display_scene->GetWindow() == win)
				break;
		}
	}
	if (display_scene == NULL)
		return;
	MergeLoaderDict(scene);
	display_scene->Copy(scene);
	SceneEvent* e = new SceneEvent(Event::SCENE_CHANGE, scene, display_scene);
	e->WindowHandle = (intptr) win;
	e->Log();
}

void World3D::AttachScene(Scene *scene)
{
	Scene*	display_scene;

	ObjectLock	lock(this);
	if (m_Scenes.GetSize() <= 0)
		return;
	display_scene = (Scene*) (SharedObj*) m_Scenes.GetAt(0);
	if ((display_scene == NULL) || (scene == display_scene))
		return;
	display_scene->Copy(scene);
}

/*!
 * @fn Scene* World3D::MakeScene(const TCHAR* filename)
 * @param filename	Name of file to load. if non-null, this file
 *					will be loaded. If not, the application filename
 *					defined by World::SetFileName is tried.
 *
 * Called by the framework at startup to establish
 * the initial scene to display. The input argument
 * has the name of the file or directory specified on the
 * command line. The default implementation tries to load
 * the input as a .Vixen binary file and returns a
 * 	scene from the file if it can find one.
 *
 * MakeScene will issue a blocking read that waits until all
 * of the geometry and associated textures have been loaded.
 * If you want to load an entire scene from a file and
 * replace the current scene, the LoadAsync function will do
 * this without blocking, but it does not return the scene
 * so you cannot do further updates after loading it.
 *
 * @return scene read from input file or NULL if scene cannot be loaded
 *
 * @see World3D::SetScene Scene World3D::NewScene World::LoadAsync
 */
Scene* World3D::MakeScene(const TCHAR* filename)
{
	if (filename == NULL)
	{
		filename = m_FileName;
		if (filename == NULL)
			return NULL;
	}
	if (*filename)
		m_LoadQueue->ReadFile(filename, NULL);
	return NULL;
}

/*!
 *@fn Event* World3D::MakeEvent(int code)
 * @param code	Event code to make event for, the default MakeEvent understands
 *				Event::MOUSE, Event::KEY and EVENT_Load. For other events, the
 *				default behavior is to create an event and initialize the
 *				code only.
 *
 * Class factory for all the events handled by this world.
 * When an event is produced by an object, its code and data
 * are logged to the current messenger and then dispatched to all
 * the observers of that event code. This function creates an
 * empty event class for the input event code. If you define
 * your own event class and override any functions, you must also
 * override MakeEvent to ensure that the system can construct the right
 * event class to handle your new event code.
 *
 * @return pointer to event constructed or NULL on error
 *
 * @see Messenger::Observe SharedObj::OnEvent Event
 */
Event* World3D::MakeEvent(int code)
{
	Event*	e;

	switch (code)
	{
		case Event::ERROR:			e = new ErrorEvent; break;
		case Event::MOUSE:			e = new MouseEvent; break;
		case Event::KEY:			e = new KeyEvent; break;
		case Event::NAVINPUT:		e = new NavInputEvent; break;
		case Event::NAVIGATE:		e = new NavigateEvent; break;
		case Event::SET_TIME:		e = new FrameEvent; break;
		case Event::SCENE_CHANGE:	e = new SceneEvent(code); break;
		case Event::EXEC:
		case Event::LOAD_IMAGE:
		case Event::LOAD_SCENE:		e = new LoadSceneEvent(code); break;
		case Event::LOAD_TEXT:		e = new LoadTextEvent; break;
		case Event::LOAD_DATA:		e = new LoadDataEvent; break;
		case Event::ENTER:
		case Event::LEAVE:			e = new TriggerEvent(code); break;
		case Event::TRACK:			e = new TrackEvent(code); break;
		case Event::PICK:
		case Event::NOPICK:
		case Event::SELECT:
		case Event::DESELECT:		e = new PickEvent(code); break;
		default:					e = new Event(code); break;
	}
	return e;
}

/*!
 * @fn bool World3D::OnEvent(Event* event)
 * @param event	event to process
 *
 * Default application event handler which responds to mouse, keyboard and
 * load events (codes Event::MOUSE, Event::KEY, EVENT_Load). Override this
 * function if you want the application to respond to other events.
 * Note that if you add your own event, you may have to override
 * World3D::MakeEvent if your new event type needs special initialization.
 *
 * @return \b true if event successfully handled, \b false if event not understood
 *
 * @see Event SharedObj::OnEvent World3D:MakeEvent Messenger::Observe
 */
bool World3D::OnEvent(Event* e)
{
	SceneEvent*	se;
	LoadSceneEvent*	le;
	Scene*		scene;

	switch (e->Code)
	{
		case Event::LOAD_SCENE:
		le = (LoadSceneEvent*) e;
		scene = (Scene*) (SharedObj*) le->Object;

		if (scene && scene->IsClass(VX_Scene) && le->Sender->IsClass(VX_Scene))
			SetScene(scene, ((Scene*) (SharedObj*) le->Sender)->GetWindow());
		else
			MergeLoaderDict(scene);
		break;

		case Event::ATTACH_SCENE:
		se = (SceneEvent*) e;
		scene = (Scene*) (SharedObj*) se->Sender;
		if (scene)
		{
			VX_ASSERT(scene->IsClass(VX_Scene));
			AttachScene(scene);
		}
		break;

		default:
		return false;
	}
	return true;
}

/*
 * Merge dictionary for loaded scene with the display scene's dictionary
 */
bool World3D::MergeLoaderDict(Scene* scene)
{
	Messenger*		stream = m_Messenger;
	NameTable*		curdict = stream->GetNameDict();
	NameTable*		newdict;
	SceneLoader*	load = GetLoader();
	const TCHAR*	name = scene->GetName();

	if (name)
	{
		newdict = load->GetSceneDict(name);
		if (newdict)
			curdict->Merge(*newdict);
		load->SetSceneDict(name, NULL);
		return true;
	}
	return false;
}

bool World3D::Do(Messenger& s, int op)
{
	int32	win;
	SharedObj*	scene;

	switch (op)
	{
		case WORLD3D_SetScene:
		s >> scene >> win;
		VX_ASSERT(scene && scene->IsClass(VX_Scene));
		SetScene((Scene*) scene, Window(win));
		break;

		default:
		return World::Do(s, op);
	}
#ifdef _DEBUG
	if (s.Debug)
		endl(vixen_debug << ClassName() << "::"
					   << World3D::DoNames[op - WORLD3D_SetScene]
					   << " " << this);
#endif
	return true;
}

/*!
 * @fn bool SceneLoader::ReadScene(const TCHAR* filename, Core::Stream* instream, LoadEvent* event)
 * @param filename	name of scene file to load.
 * @param instream	stream to use for reading.
 * @param event		event to initialize if load is successful.
 *
 * Called by the loader to load a scene file.
 * ReadScene will issue a blocking read that waits until all
 * of the geometry and associated textures have been loaded.
 * If you want to load an entire scene from a file and
 * replace the current scene, the SceneLoader::Load function will do
 * this without blocking.
 *
 * @return \b true if load was successful, else \b false
 *
 * @see World::LoadAsync FileLoader::Load
 */
bool SceneLoader::ReadScene(const TCHAR* filename, Core::Stream* instream, LoadEvent* ev)
{
	LoadSceneEvent* event = (LoadSceneEvent*) ev;
	TCHAR			filebase[VX_MaxPath];
	TCHAR			dir[VX_MaxPath];
	Scene*			inscene = (Scene*) (SharedObj*) event->Object;
	size_t			len;
	FileMessenger	scenemaker;
	NameTable*		scenedict;
	const Model*	sceneroot;
	const Engine*	simroot;
	Messenger*		disp = GetMessenger();

	event->Code = Event::LOAD_SCENE;
	if (event->Sender.IsNull())
		event->Sender = GetMainScene();
	if (inscene)							// scene already loaded?
		return true;
	instream->ParseDirectory(filename, filebase, dir);
	instream->SetDirectory(dir);			// establish base directory
	len = STRLEN(filebase);
	scenemaker.SetInStream(instream);
	if (!scenemaker.Load())					// cannot load file?
		return false;						// no input scene
	instream->SetDirectory(NULL);
/*
 * Save the file scene's dictionary.
 * Closing the scene loader will delete this dictionary but we want to keep
 * it to merge with the display scene's dictionary later.
 */
	scenedict = scenemaker.GetNameDict();
	World3D::Get()->GetLoader()->SetSceneDict(filebase, scenedict);
/*
 * Define names in the current display scene's global dictionary for the
 * scene in the file, the simulation tree root and the scene graph
 */
	STRCAT(filebase, TEXT(".scene"));				// find the scene
	inscene = (Scene*) (SharedObj*) scenemaker.Find(filebase);
	if (inscene == NULL)							// found a scene?
	{
		STRCPY(filebase + len, TEXT(".simroot"));
		simroot = (const Engine*) scenemaker.Find(filebase);
		STRCPY(filebase + len, TEXT(".root"));
		sceneroot = (const Model*) scenemaker.Find(filebase);
		if (sceneroot != NULL)						// found object called filebase.root?
		{
			if (sceneroot->IsClass(VX_Model))		// we have a model
			{
				STRCPY(filebase + len, TEXT(".scene"));
				inscene = new Scene();				// make a new scene
				inscene->SetName(filebase);
				inscene->SetModels(sceneroot);		// attach the scene root
				inscene->SetEngines(simroot);		// attach the simulation root
			}
			else									// not a model?
			{
				event->Object = sceneroot;
				VX_TRACE(FileLoader::Debug, ("SceneLoader::ReadScene %s\n", (const char *) filebase));
				scenemaker.Close();
				return true;
			}
		}
		else if (simroot != NULL)
		{
			STRCPY(filebase + len, TEXT(".scene"));
			inscene = new Scene();				// make a new scene
			inscene->SetName(filebase);
			inscene->SetEngines(simroot);		// attach the simulation root
		}
		else
		{
			VX_ERROR(("SceneLoader::ReadScene %s ERROR: cannot find root\n", (const TCHAR*) filebase), false);
		}
		disp->Define(filebase, inscene);
	}
	else
	{
		sceneroot = ((Scene*) inscene)->GetModels();
		simroot = ((Scene*) inscene)->GetEngines();
	}
	VX_TRACE(FileLoader::Debug, ("SceneLoader::ReadScene %s\n", (const char *) filebase));
/*
 * Define simulation tree and scene tree root names in the global dictionary
 */
	const TCHAR* name;

	if (sceneroot)
	{
		name = sceneroot->GetName();
		if (name)
			disp->Define(name, sceneroot);
	}
	if (simroot)
	{
		name = simroot->GetName();
		if (name)
			disp->Define(name, simroot);
	}
	event->Object = inscene;
	scenemaker.Close();
	return true;
}

/*!
 * @fn NameTable* SceneLoader::GetSceneDict(const TCHAR* scenename) const
 * @param scenename	string name of scene, if NULL the last loaded scene dictionary is used
 *
 * Returns the dictionary for the specified scene. These dictionaries
 * are typically temporary and remain only until the scene load
 * event has been handled by an observer. The loader maintains these dictionaries
 * so that application code may look up objects by name while processing
 * a load event.
 *
 * @return dictionary if found or NULL if it does not exist
 *
 * @see SceneLoader::SetSceneDict
 */
NameTable* SceneLoader::GetSceneDict(const TCHAR* scenename) const
{
	TCHAR			namebuf[VX_MaxPath];
	ObjRef*		dictptr;
	TCHAR*			p;
	NameProp		np;

	STRCPY(namebuf, scenename);
	p = STRRCHR(namebuf, TEXT('.'));
	if (p)
		STRCPY(p, TEXT(".dict"));
	else
		STRCAT(namebuf, TEXT(".dict"));
	np = namebuf;
	dictptr = m_FileDict.Find(np);
	if (dictptr == NULL)
		return NULL;
	return (NameTable*) (SharedObj*) *dictptr;
}

/*!
 * @fn void SceneLoader::SetSceneDict(const TCHAR* scenename, NameTable* dict)
 * @param scenename	string name of scene
 * @param dict		dictionary to associate with the scene.
 *
 * Saves the dictionary under the scene's name. These dictionaries
 * are typically temporary and remain only until the scene load
 * event has been handled. The loader keeps them so that the
 * application may look up objects by name while processing
 * a load event.
 *
 * Setting the scene dictionary to NULL is the best way to get rid
 * of a scene file when it is no longer being referenced.
 *
 * @see SceneLoader::GetSceneDict
 */
void SceneLoader::SetSceneDict(const TCHAR* scenename, NameTable* dict)
{
	TCHAR		namebuf[VX_MaxPath];
	TCHAR*		p;
	NameProp	np;
	ObjectLock	lock(this);

	STRCPY(namebuf, scenename);
	p = STRRCHR(namebuf, TEXT('.'));
	if (p)
		STRCPY(p, TEXT(".dict"));
	else
		STRCAT(namebuf, TEXT(".dict"));
	np = namebuf;
	if (dict)
	{
		m_FileDict.Set(np, dict);
		m_LastDict = dict;
		dict->MakeLock();
	}
	else
	{
		if (m_LastDict)
			m_LastDict->KillLock();
		m_LastDict = NULL;
		m_FileDict.Remove(np);
	}
}

/*!
 * @fn SharedObj* SceneLoader::Find(const TCHAR* objname, const TCHAR* scenename)
 * @param objname	string name of object to retrieve, cannot be NULL
 * @param scenename	string name of scene, if NULL last scene loaded is used
 *
 * Finds the object with the given name in the dictionary for the
 * specified scene. Only named objects from scene files loaded but not
 * yet merged with the display scene are accessible.
 * If you are retrieving an object and it is within a hierarchy in the loaded file,
 * you must remove it from that hierarchy before you can put it into another.
 *
 * @return pointer to object found or NULL if object not there
 *
 * @see Messenger::Find
 */
SharedObj* SceneLoader::Find(const TCHAR* objname, const TCHAR* scenename)
{
	NameTable*	dict = m_LastDict;
	ObjRef*		ref;
	ObjectLock	lock(this);
	size_t		n;

	if (scenename)
		dict = GetSceneDict(scenename);
	if (dict == NULL)
		return NULL;
	if (objname == NULL)
		return NULL;
	n = STRLEN(objname);
	if ((objname[0] != '*') &&			// not a wildcard search?
		(objname[n - 1] != '*'))
		ref = dict->Find(objname);
	else
		ref = dict->FindWild(objname);
	if (ref)
		return *ref;
	return NULL;
}

/*!
 * @fn ObjArray* SceneLoader::FindAll(const TCHAR* objname, const TCHAR* scenename)
 * @param objname	string name of objects to retrieve. Only the objects whose names
 *					match this name (using "*" as a wildcard) are returned.
 * @param scenename	string name of scene, if NULL last scene loaded is used
 *
 * Asterisk is used as a special character which will match
 * anything. For example, "*ABC" will match any name that
 * ends in "ABC" and "ABC*" matches any name beginning with "ABC".
 * To match any name containing ABC, including at the beginning
 * or end, use "*ABC*".
 *
 * Only named objects from scene files loaded but not
 * yet merged with the display scene are accessible.
 *
 * @return array of objects found or NULL if no matches
 *
 * @see Messenger::FindAll SharedObj::SetName
 */
ObjArray* SceneLoader::FindAll(const TCHAR* objname, const TCHAR* scenename)
{
	NameTable*	dict = m_LastDict;

	if (scenename)
		dict = GetSceneDict(scenename);
	if (dict == NULL)
		return NULL;
	return dict->FindAll(objname);
}

/*!
 * @fn void SceneLoader::Unload(const TCHAR* filename)
 * @param filename	name of file to unload.
 *
 * When the loader loads a file, it caches the file objects in
 * memory so they can be used in simulation (even if they
 * are not displayed). This function frees the cached objects
 * if the file which are not being used in the scene.
 *
 * @see FileLoader::Load FileLoader::Unload
 */
void SceneLoader::Unload(const TCHAR* filename)
{
	TCHAR			basename[VX_MaxPath];
	Core::Stream::ParseDirectory(filename, basename);

	Messenger*		stream = GetMessenger();
	Core::String	lookfor(basename);
	ObjectLock		lock(this);
	ObjRef*			oref = m_FileDict.Find(filename);

	lookfor += "*";
	if (stream && oref)
	{
		SharedObj*			obj = (SharedObj*) *oref;
		TCHAR			namebuf[VX_MaxPath];
		const TCHAR*	name;

		if (obj)
		{
			name = obj->GetName();
			if (name)						// remove it's dictionary
			{
				STRCPY(namebuf, name);
				STRCPY(STRRCHR(namebuf, TEXT('.')), TEXT(".dict"));
				m_FileDict.Remove(NameProp(namebuf));
			}
			stream->Detach(obj);
			stream->DetachAll(lookfor, obj);
		}
	}
	FileLoader::Unload(filename);
}

void SceneLoader::Kill()
{
	m_LastDict = NULL;
	FileLoader::Kill();
}
}	// end Vixen


text:
/**
 * Module dependencies
 */
var path = require('path');
var fs = require('fs');
var util = require('util');
var child_process = require('child_process');
var mkpath = require('mkpath');
var minimatch = require('minimatch');
var Nightwatch = require('../index.js');
var Logger = require('../lib/logger.js');
var Reporter = require('./reporters/junit.js');

module.exports = new (function() {
  'use strict';
  var seleniumProcess = null;
  var globalresults = {
    passed : 0,
    failed : 0,
    errors : 0,
    skipped : 0,
    tests : 0,
    errmessages : [],
    modules : {}
  };

  function runModule(module, opts, moduleName, callback) {
    var client = Nightwatch.client(opts);
    var keys   = Object.keys(module);
    var tests  = [];
    var setUp;
    var tearDown;
    var testresults = {
      passed : 0,
      failed : 0,
      errors : 0,
      skipped : 0,
      tests : 0,
      steps : keys.slice(0)
    };

    module.client = client;

    if (keys.indexOf('setUp') > -1) {
      setUp = function(clientFn) {
        module.setUp(module.client);
        clientFn();
      };
      keys.splice(keys.indexOf('setUp'), 1);
      testresults.steps.splice(testresults.steps.indexOf('setUp'), 1);
    } else {
      setUp = function(callback) {callback();};
    }

    if (keys.indexOf('tearDown') > -1) {
      tearDown = function(clientFn) {
        module.tearDown();
        clientFn();
      };
      keys.splice(keys.indexOf('tearDown'), 1);
      testresults.steps.splice(testresults.steps.indexOf('tearDown'), 1);

    } else {
      tearDown = function(callback) {callback();};
    }

    function next() {
      if (keys.length) {
        var key = keys.shift();
        if (typeof module[key] != 'function') {
          next();
          return;
        }

        console.log('\nRunning: ', Logger.colors.green(key));
        var test = wrapTest(setUp, tearDown, module[key], module, function onComplete(results, errors) {
          globalresults.modules[moduleName][key] = {
            passed  : results.passed,
            failed  : results.failed,
            errors  : results.errors,
            skipped : results.skipped,
            tests   : [].concat(results.tests)
          };

          if (Array.isArray(errors) && errors.length) {
            globalresults.errmessages = globalresults.errmessages.concat(errors);
          }

          testresults.passed += results.passed;
          testresults.failed += results.failed;
          testresults.errors += results.errors;
          testresults.skipped += results.skipped;
          testresults.tests += results.tests.length;
          if (this.client.terminated) {
            callback(null, testresults);
          } else {
            setTimeout(next, 0);
          }
        });

        var error = false;
        try {
          test(client);
        } catch (err) {
          globalresults.errmessages.push(err.message);
          console.log(Logger.colors.red('\nAn error occured while running the test:'));
          console.log(err.stack);
          testresults.errors++;
          client.terminate();
          error = true;
          callback(err, testresults);
        }

        if (!error) {
          client.start();
        }

      } else {
        callback(null, testresults);
      }
    }

    setTimeout(next, 0);
  }

  function printResults(testresults) {
    if (testresults.passed > 0 && testresults.errors === 0 && testresults.failed === 0) {
      console.log(Logger.colors.green('\nOK. ' + testresults.passed, Logger.colors.background.black), 'total assertions passed.');
    } else {
      var skipped = '';
      if (testresults.skipped) {
        skipped = ' and ' + Logger.colors.blue(testresults.skipped) + ' skipped.';
      }
      console.log(Logger.colors.light_red('\nTEST FAILURE:'), Logger.colors.red(testresults.errors + testresults.failed) +
      ' assertions failed, ' + Logger.colors.green(testresults.passed) + ' passed' + skipped);
    }
  }

  function wrapTest(setUp, tearDown, fn, context, onComplete) {
    return function (client) {
      context.client = client;
      var clientFn = function () {
        client.once('queue:finished', function(results, errors) {
          tearDown.call(context, function() {
            onComplete.call(context, results, errors);
          });
        });

        return fn.call(context, client);
      };

      setUp.call(context, clientFn);
    };
  }

  function runFiles(paths, cb, opts) {
    var extensionPattern = /\.js$/;
    if (paths.length == 1 && extensionPattern.test(paths[0])) {
      paths[0] = paths[0].replace(extensionPattern, '');
      return cb(null, paths);
    }

    paths.forEach(function(p) {
      walk(p, function(err, list) {
        if (err) {
          return cb(err);
        }
        list.sort();

        var modules = list.filter(function (filePath) {
          var filename = filePath.split('/').slice(-1)[0];
          return opts.filter ?
            minimatch(filename, opts.filter) :
            extensionPattern.exec(filePath);
        });

        modules = modules.map(function (filename) {
          return filename.replace(extensionPattern, '');
        });

        cb(null, modules);
      }, opts);
    });
  }

  function walk(dir, done, opts) {
    var results = [];
    fs.readdir(dir, function(err, list) {
      if (err) {
        return done(err);
      }
      var pending = list.length;

      if (pending === 0) {
        return done(null, results);
      }

      list.forEach(function(file) {
        file = [dir, file].join('/');

        fs.stat(file, function(err, stat) {
          if (stat && stat.isDirectory()) {
            var dirName = file.split('/').slice(-1)[0];
            if (opts.skipgroup && opts.skipgroup.indexOf(dirName) > -1) {
              pending = pending-1;
            } else {
              walk(file, function(err, res) {
                results = results.concat(res);
                pending = pending-1;
                if (!pending) {
                  done(null, results);
                }
              }, opts);
            }
          } else {
            results.push(file);
            pending = pending-1;

            if (!pending) {
              done(null, results);
            }
          }
        });
      });
    });
  }

  this.run = function runner(files, opts, aditional_opts, finishCallback) {
    var start = new Date().getTime();
    var modules = {};
    var curModule;
    var paths;
    finishCallback = finishCallback || function() {};

    if (typeof files == 'string') {
      paths = [files];
    } else {
      paths = files.map(function (p) {
        return path.join(process.cwd(), p);
      });
    }

    if (paths.length === 0) {
      throw new Error('No tests to run.');
    }
    runFiles(paths, function runTestModule(err, fullpaths) {
      if (!fullpaths || fullpaths.length === 0) {
        Logger.warn('No tests defined!');
        console.log('using source folder', paths);
        return;
      }

      var module;
      var modulePath = fullpaths.shift();
      try {
        module = require(modulePath);
      } catch (err) {
        finishCallback(err);
        throw err;
      }

      var moduleName = modulePath.split(path.sep).pop();
      globalresults.modules[moduleName] = [];
      console.log('\n' + Logger.colors.cyan('[ ' + moduleName + ' module ]'));

      runModule(module, opts, moduleName, function(err, testresults) {
        globalresults.passed += testresults.passed;
        globalresults.failed += testresults.failed;
        globalresults.errors += testresults.errors;
        globalresults.skipped += testresults.skipped;
        globalresults.tests += testresults.tests;

        if (fullpaths.length) {
          setTimeout(function() {
            runTestModule(err, fullpaths);
          }, 0);
        } else {
          if (testresults.tests != globalresults.tests || testresults.steps.length > 1) {
            printResults(globalresults);
          }

          var output = aditional_opts.output_folder;
          if (output === false) {
            finishCallback(null);
          } else {
            mkpath(output, function(err) {
              if (err) {
                console.log(Logger.colors.yellow('Output folder doesn\'t exist and cannot be created.'));
                console.log(err.stack);
                finishCallback(null);
                return;
              }

              Reporter.save(globalresults, output, function(err) {
                if (err) {
                  console.log(Logger.colors.yellow('Warning: Failed to save report file to folder: ' + output));
                  console.log(err.stack);
                }
                finishCallback(null);
              });
            });
          }
        }
      });
    }, opts);
  };

})();

redpajama_set_name: RedPajamaGithub


text:
.. _dev_hooks:

Hooks in Path Simulators
========================

.. note::
    Hooks are a beta feature. Details of the API may change, and hooks
    may be removed/significantly modified in future major versions.

In order to provide more flexibility, there are certain points where a
developer can modify the functionality of a path simulator. We refer to
these as "hooks." You can create your own hooks by making a subclass of
:class:`.PathSimulatorHook`.  That class has 4 methods (which default to
no-ops) that you can override to add the desired functionality:

* ``before_simulation``: This performs any setup, such as a initialization
  of the hook itself, before the simulation starts.
* ``before_step``: This runs before each step. It is primarily for progress
  reporting.
* ``after_step`` This runs after each step. It can perform on-the-fly
  analysis of the results from a simulation step, and can adjust the
  behavior of the simulation based on those results.
* ``after_simulation``: This runs at the end of the simulation.

An instance of a subclass of :class:`.PathSimulatorHook` can be attached to
the simulator with ``simulator.attach_hook(hook)``.

Step info
---------

Each simulation type provides a more detailed breakdown of the step
progress, which is provided to both the ``before_step`` and ``after_step``
methods. This is a tuple, the exact contents of which depend on the specific
simulation type.

For a :class:`.ShootFromSnapshotsSimualtion`, such as a
:class:`.CommittorSimulation`, this is the 4-tuple ``(snap, n_snaps, step,
n_steps)`` where ``snap`` is the snapshot number, ``step`` is the step
number within that snapshot, and ``n_snaps`` and ``n_steps`` are the total
number of each, respectively.

Simulation state
----------------

The ``before_step`` and ``after_step`` stages receive a ``state`` variable,
which represents the current state of the simulation. The specific nature of
this again depends on the specific simulation type. For a
:class:`.ShootFromSnapshotsSimulation`, this will be the current initial
snapshot.

Internal state of hooks
-----------------------

If a hook needs to update some sort of internal state over the course of a
simulation, that should be done as part of the ``after_step`` stage. The
``after_step`` method should also return any state that needs to be
preserved. This should be in the form of a dictionary.


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Green Building Architecture ">
<meta name="keywords" content="Green Building, Environment, Safety, Consulting, Better World, Helping Human Being">
<meta name="author" content="Ashutosh Prateek">
<meta name="Charset" content="UTF-8">
<meta name="Rating" content="General">
<meta name="Distribution" content="Local">
<meta name="Robots" content="INDEX,FOLLOW">
<meta name="copyright" content="Copyright e-nvirogreen - 2017">
<title>e-nvirogreen</title>
<link rel="stylesheet" href="../css/components.css">
<link rel="stylesheet" href="../css/icons.css">
<link rel="stylesheet" href="../css/responsee.css">
<link rel="stylesheet" href="../owl-carousel/owl.carousel.css">
<link rel="stylesheet" href="../owl-carousel/owl.theme.css">

<link rel="stylesheet" href="../css/template-style.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,300,700,800&subset=latin,latin-ext" rel="stylesheet" type="text/css">

Blog

Coming Soon


text:
self.addEventListener('activate', event => {
  event.waitUntil(self.registration.navigationPreload.enable());
});

self.addEventListener('fetch', event => {
  const params = new URL(event.request.url).searchParams;

  if (event.request.mode == 'navigate') {
    if (params.has('navpreload_or_offline')) {
      event.respondWith((async () => {
        try {
          return await event.preloadResponse;
        } catch (e) {
          return new Response("Hello Offline page");
        }
      })());
    } else {
      event.respondWith(event.preloadResponse);
    }
  }
});


text:
module AtozList
  module ActsAsAtozList
    extend ActiveSupport::Concern

    included do
    end

    module ClassMethods
      def acts_as_atoz_list(options = {})
        include AtozList::ActsAsAtozList::LocalInstanceMethods
      end
    end

    module LocalInstanceMethods
      def print_test_message
        "Hello world!"
      end

      def create_atoz_links(items, field)
        atoz_letters = grab_link_letters(items, field)
        atoz_links = generate_html_links(atoz_letters)
      end

      def grab_link_letters(items, field)
        letters = []
        items.each do |item|
          value = item.send("#{field}")
          letters << value.chars.first.upcase unless letters.include? value.chars.first.upcase
        end
        letters
      end
    end

  end
end

ActionController::Base.send :include, AtozList::ActsAsAtozList


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// This test makes sure that about:privatebrowsing does not appear zoomed in
// if there is already a zoom site pref for about:blank (bug 487656).

function test() {
  // initialization
  let pb = Cc["@mozilla.org/privatebrowsing;1"].
           getService(Ci.nsIPrivateBrowsingService);
  waitForExplicitFinish();

  let tabBlank = gBrowser.selectedTab;
  let blankBrowser = gBrowser.getBrowserForTab(tabBlank);
  blankBrowser.addEventListener("load", function() {
    blankBrowser.removeEventListener("load", arguments.callee, true);

    // change the zoom on the blank page
    FullZoom.enlarge();
    isnot(ZoomManager.zoom, 1, "Zoom level for about:blank should be changed");

    // enter private browsing mode
    pb.privateBrowsingEnabled = true;
    let tabAboutPB = gBrowser.selectedTab;
    let browserAboutPB = gBrowser.getBrowserForTab(tabAboutPB);
    browserAboutPB.addEventListener("load", function() {
      browserAboutPB.removeEventListener("load", arguments.callee, true);
      setTimeout(function() {
        // make sure the zoom level is set to 1
        is(ZoomManager.zoom, 1, "Zoom level for about:privatebrowsing should be reset");
        finishTest();
      }, 0);
    }, true);
  }, true);
  blankBrowser.loadURI("about:blank");
}

function finishTest() {
  let pb = Cc["@mozilla.org/privatebrowsing;1"].
           getService(Ci.nsIPrivateBrowsingService);
  // leave private browsing mode
  pb.privateBrowsingEnabled = false;
  let tabBlank = gBrowser.selectedTab;
  let blankBrowser = gBrowser.getBrowserForTab(tabBlank);
  blankBrowser.addEventListener("load", function() {
    blankBrowser.removeEventListener("load", arguments.callee, true);

    executeSoon(function() {
      // cleanup
      FullZoom.reset();
      finish();
    });
  }, true);
}


text:
package kstarchoi.lib.recyclerview.builder.typefree;

import android.support.annotation.LayoutRes;
import android.util.SparseArray;
import android.util.SparseIntArray;

import java.util.List;

/**
 * @author Gwangseong Choi
 * @since 2018-09-22
 */

final class ViewBindHelper {

    private final SparseArray<ViewBinderImpl> viewBinderImplSparseArray = new SparseArray<>();
    private final SparseIntArray layoutResSparseArray = new SparseIntArray();

    void put(@LayoutRes int layoutRes, ViewBinder<?> viewBinder) {
        ViewBinderImpl<?> viewBinderImpl = new ViewBinderImpl<>(viewBinder);
        String name = String.format("ViewBinder<%s>", viewBinderImpl.getDataTypeName());
        int viewType = viewBinderImpl.getViewType();
        AssertionHelper.notExist(name, viewType, viewBinderImplSparseArray);

        viewBinderImplSparseArray.put(viewType, viewBinderImpl);
        layoutResSparseArray.put(viewType, layoutRes);
    }

    int getLayoutRes(int viewType) {
        return layoutResSparseArray.get(viewType);
    }

    int getViewType(Object data) {
        return ViewBinderImpl.getViewType(data);
    }

    ViewBinderImpl<?> getViewBinderImpl(Object data) {
        return viewBinderImplSparseArray.get(getViewType(data));
    }

    void checkBoundDataType(Object data, Object... dataArray) {
        AssertionHelper.bound(data.getClass().getName(), getViewType(data),
                viewBinderImplSparseArray);

        for (Object aData : dataArray) {
            AssertionHelper.bound(aData.getClass().getName(), getViewType(aData),
                    viewBinderImplSparseArray);
        }
    }

    void checkBoundDataType(List<?> dataList) {
        for (Object aData : dataList) {
            AssertionHelper.bound(aData.getClass().getName(), getViewType(aData),
                    viewBinderImplSparseArray);
        }
    }
}


text:
layout: post
episodeNumber: 42
title: Raygun
guest: John-Daniel Trask
date: 2015-02-09
audioUrl: https://static.msdevshow.com/episodes/msdevshow_0042.mp3
guestImage: john-daniel-trask.jpg
---

### News

 - [Google Chrome will prevent your monitors from sleeping](https://code.google.com/p/chromium/issues/detail?id=179007)
  - [Carl's Monitor GitHub repo](https://github.com/caschw/Monitor)
 - [Office "Touch" for Windows](http://winsupersite.com/office/office-touch-windows-outclass-version-ipad)
 - [Cloud Platform Roadmap](http://www.microsoft.com/en-us/server-cloud/roadmap/)
 - [Date and time formatting for humans](http://thechangelog.com/date-time-formatting-humans/)
 - [HP Stream 7 Signature Edition Tablet drops to \$79 at the Microsoft Store](http://www.windowscentral.com/hp-stream-7-signature-edition-tablet-drops-79-microsoft-store)
 - [Raspberry Pi 2](http://www.raspberrypi.org/products/raspberry-pi-2-model-b/)
  - [Camera Flash](http://gizmodo.com/raspberry-pi-2-loses-its-shit-when-you-blast-it-with-a-1684727655)

### John-Daniel Trask

 - [@traskjd](https://twitter.com/traskjd)
 - [jdtrask.com](http://jdtrask.com/)
 - [Mindscape](http://www.mindscapehq.com/)
 - [Raygun](https://raygun.io/)

### Azure Pick of the Week

 - [Azure Media Services to help stream the big game](http://azure.microsoft.com/blog/2015/01/30/azure-media-services-to-help-stream-the-big-game/)

### App of the Week

 - [Realarm](http://www.windowsphone.com/s?appid=26cad058-fc9a-4967-95f0-4e83c09de99e)


text:
package cadeia.responsabilidade;

import cadeia.responsabilidade.caixa.*;
import cadeia.responsabilidade.fronteira.*;

/**
 *
 * @author douglas
 */
public class Main {
  public static void main( String[] args ) {
    String name = "João";
    Integer valorSaque;

    IAtmHandler c100 = new Cash100Handler();
    IAtmHandler c50 = new Cash50Handler();
    IAtmHandler c20 = new Cash20Handler();
    IAtmHandler c10 = new Cash10Handler();
    IAtmHandler c5 = new Cash5Handler();
    IAtmHandler c2 = new Cash2Handler();

    c100.setNextHandler( c50 );
    c50.setNextHandler( c20 );
    c20.setNextHandler( c10 );
    c10.setNextHandler( c5 );
    c5.setNextHandler( c2 );

    valorSaque = Entrada.leInt( "Qual o valor do saque? " );

    if ( valorSaque == 0 || valorSaque == 1 || valorSaque == 3 ) {
      Saida.println( "Impossível sacar R$ " + valorSaque + ",00 com as notas disponíveis." );
    } else {
      Saida.println( name + " sacou:" );
      c100.processHandler( valorSaque );
    }
  }
}


text:
(function(){
	var windowLoadCompleted = false;
	jQuery(window).load(function() {

		// Prevent from being triggered again
		if (windowLoadCompleted) {
			return;
		}

		windowLoadCompleted = true;

		// Only proceed if qTranslate is loaded
		if (typeof qTranslateConfig != 'object' || typeof qTranslateConfig.qtx != 'object') {
			return;
		}

		// Enable the language switching buttons
		qTranslateConfig.qtx.enableLanguageSwitchingButtons('block');

		// Add display hooks to ACF metaboxes
		jQuery('.acf-postbox h3 span').each(function() {
			this.id = _.uniqueId('acf-postbox-h3-span');
			qTranslateConfig.qtx.addDisplayHookById(this.id);
		});

		// Ensure that translation of standard field types is enabled
		if (!window.acf_qtranslate_translate_standard_field_types) {
			return;
		}

		// Selectors for supported field types
		var field_types = {
			text:      'input:text',
			textarea:  'textarea',
			wysiwyg:   '.wp-editor-area',
		};

		// Remove content hooks from ACF Fields
		jQuery('.acf-postbox .acf-field').find('.qtranxs-translatable').each(function() {
			qTranslateConfig.qtx.removeContentHook(this);
		});

		// Setup field types
		jQuery.each(field_types, function(field_type, selector) {

			// Add content hooks for existing fields
			acf.get_fields({ type: field_type }).each(function() {
				var form = jQuery(this).closest('form').get(0);
				var field = jQuery(this).find(selector).get(0);
				qTranslateConfig.qtx.addContentHookC(field, form);
			});

			// Watch and add content hooks when new fields are added
			acf.add_action('append_field/type=' + field_type, function($el) {
				var form = $el.closest('form').get(0);
				var field = $el.find(selector).get(0);
				qTranslateConfig.qtx.addContentHookC(field, form);

				if (jQuery(field).hasClass('wp-editor-area')) {
					qTranslateConfig.qtx.addContentHooksTinyMCE();

					// We must manually trigger load event so that the
					// loadTinyMceHooks function which calls setEditorHooks is executed
					var loadEvent = document.createEvent('UIEvents');
					loadEvent.initEvent('load',false,false,window);
					window.dispatchEvent(loadEvent);
				}

				// Run at higher integer priority than the default in case the ACF handlers
				// change the id of the underlying input
			}, 100);

		});

		qTranslateConfig.qtx.addContentHooksTinyMCE();

		// Watch and remove content hooks when fields are removed
		// however ACF removes the elements from the DOM early so
		// we must hook into handler and perform updates there
		var _hooked_repeater_remove = acf.fields.repeater.remove;
		acf.fields.repeater.remove = function(event) {
			var row = event.$el.closest('.acf-row');
			row.find(_.toArray(field_types).join(',')).filter('.qtranxs-translatable').each(function() {
				qTranslateConfig.qtx.removeContentHook(this);
			});
			// call the original handler
			_hooked_repeater_remove.call(this, event);
		};

	});

})();


text:
using System;
using System.Collections.Generic;
using Azure.Core;

namespace Azure.Analytics.Synapse.Artifacts.Models
{
    /// <summary> Information about a pipeline run. </summary>
    public partial class PipelineRun
    {
        /// <summary> Initializes a new instance of PipelineRun. </summary>
        internal PipelineRun()
        {
            Parameters = new ChangeTrackingDictionary<string, string>();
            AdditionalProperties = new ChangeTrackingDictionary<string, object>();
        }

        /// <summary> Initializes a new instance of PipelineRun. </summary>
        /// <param name="runId"> Identifier of a run. </param>
        /// <param name="runGroupId"> Identifier that correlates all the recovery runs of a pipeline run. </param>
        /// <param name="isLatest"> Indicates if the recovered pipeline run is the latest in its group. </param>
        /// <param name="pipelineName"> The pipeline name. </param>
        /// <param name="parameters"> The full or partial list of parameter name, value pair used in the pipeline run. </param>
        /// <param name="invokedBy"> Entity that started the pipeline run. </param>
        /// <param name="lastUpdated"> The last updated timestamp for the pipeline run event in ISO8601 format. </param>
        /// <param name="runStart"> The start time of a pipeline run in ISO8601 format. </param>
        /// <param name="runEnd"> The end time of a pipeline run in ISO8601 format. </param>
        /// <param name="durationInMs"> The duration of a pipeline run. </param>
        /// <param name="status"> The status of a pipeline run. </param>
        /// <param name="message"> The message from a pipeline run. </param>
        /// <param name="additionalProperties"> Additional Properties. </param>
        internal PipelineRun(string runId, string runGroupId, bool? isLatest, string pipelineName, IReadOnlyDictionary<string, string> parameters, PipelineRunInvokedBy invokedBy, DateTimeOffset? lastUpdated, DateTimeOffset? runStart, DateTimeOffset? runEnd, int? durationInMs, string status, string message, IReadOnlyDictionary<string, object> additionalProperties)
        {
            RunId = runId;
            RunGroupId = runGroupId;
            IsLatest = isLatest;
            PipelineName = pipelineName;
            Parameters = parameters;
            InvokedBy = invokedBy;
            LastUpdated = lastUpdated;
            RunStart = runStart;
            RunEnd = runEnd;
            DurationInMs = durationInMs;
            Status = status;
            Message = message;
            AdditionalProperties = additionalProperties;
        }

        /// <summary> Identifier of a run. </summary>
        public string RunId { get; }
        /// <summary> Identifier that correlates all the recovery runs of a pipeline run. </summary>
        public string RunGroupId { get; }
        /// <summary> Indicates if the recovered pipeline run is the latest in its group. </summary>
        public bool? IsLatest { get; }
        /// <summary> The pipeline name. </summary>
        public string PipelineName { get; }
        /// <summary> The full or partial list of parameter name, value pair used in the pipeline run. </summary>
        public IReadOnlyDictionary<string, string> Parameters { get; }
        /// <summary> Entity that started the pipeline run. </summary>
        public PipelineRunInvokedBy InvokedBy { get; }
        /// <summary> The last updated timestamp for the pipeline run event in ISO8601 format. </summary>
        public DateTimeOffset? LastUpdated { get; }
        /// <summary> The start time of a pipeline run in ISO8601 format. </summary>
        public DateTimeOffset? RunStart { get; }
        /// <summary> The end time of a pipeline run in ISO8601 format. </summary>
        public DateTimeOffset? RunEnd { get; }
        /// <summary> The duration of a pipeline run. </summary>
        public int? DurationInMs { get; }
        /// <summary> The status of a pipeline run. </summary>
        public string Status { get; }
        /// <summary> The message from a pipeline run. </summary>
        public string Message { get; }
        /// <summary> Additional Properties. </summary>
        public IReadOnlyDictionary<string, object> AdditionalProperties { get; }
    }
}


text:
namespace Google.Cloud.Logging.V2.Snippets
{
    // [START logging_v2_generated_MetricsServiceV2_DeleteLogMetric_sync]
    using Google.Cloud.Logging.V2;

    public sealed partial class GeneratedMetricsServiceV2ClientSnippets
    {
        /// <summary>Snippet for DeleteLogMetric</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void DeleteLogMetricRequestObject()
        {
            // Create client
            MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create();
            // Initialize request argument(s)
            DeleteLogMetricRequest request = new DeleteLogMetricRequest
            {
                MetricNameAsLogMetricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]"),
            };
            // Make the request
            metricsServiceV2Client.DeleteLogMetric(request);
        }
    }
    // [END logging_v2_generated_MetricsServiceV2_DeleteLogMetric_sync]
}


text:
import java.util.*;

public class Test {
    private boolean b;

    public void test() {
        whi<caret>le (b);
    }
}


text:
import os
import sys
import time
import getpass
import numpy as np
from scipy import sparse
from collections import defaultdict
from matplotlib import pyplot as plt
from sklearn.externals import joblib
from sklearn.ensemble import RandomForestClassifier

sys.path.append("/home/%s/Documents/chembl/data_files/" % getpass.getuser())
import chembl_input as ci

# the newly picked out 15 targets, include 9 targets from 5 big group, and 6 targets from others.
target_list = ["CHEMBL279", "CHEMBL203", # Protein Kinases
               "CHEMBL217", "CHEMBL253", # GPCRs (Family A)
               "CHEMBL235", "CHEMBL206", # Nuclear Hormone Receptors
               "CHEMBL240", "CHEMBL4296", # Voltage Gated Ion Channels
               "CHEMBL4805", # Ligand Gated Ion Channels
               "CHEMBL204", "CHEMBL244", "CHEMBL4822", "CHEMBL340", "CHEMBL205", "CHEMBL4005" # Others
              ]

target_list = ["CHEMBL206", "CHEMBL217", "CHEMBL235", "CHEMBL240",
               "CHEMBL253", "CHEMBL4296",
              ]

def virtual_screening(target):
  # input dataset
  d = ci.DatasetVS(target)
  # read saved rf clf model
  clf = joblib.load("model_files/rf_%s.m" % target)
  # pred file
  pred_dir = "pred_files/%s" % target
  if not os.path.exists(pred_dir):
    os.mkdir(pred_dir)
  for part_num in range(13):
    t0 = time.time()
    pred_path = os.path.join(pred_dir, "vs_pubchem_%d.pred" % part_num)
    predfile = open(pred_path, "w")
    fp_dir = "/raid/xiaotaw/pubchem/fp_files/%d" % part_num
    for i in range(part_num * 10000000 + 1, (part_num + 1) * 10000000, 25000):
      fp_fn = os.path.join(fp_dir, "Compound_{:0>9}_{:0>9}.apfp".format(i, i + 24999))
      if os.path.exists(fp_fn):
        d.reset(fp_fn)
        features = d.features_dense
        pred = clf.predict_proba(features)
        for id_, pred_v in zip(d.pubchem_id, pred[:, 1]):
          predfile.write("%s\t%f\n" % (id_, pred_v))
        #print("%s\t%d\n" % (fp_fn, pred.shape[0]))
    t1 = time.time()
    print("%s %d: %.3f" %(target, part_num, t1-t0))

def analyse(target):
  vs_pred_file = "pred_files/%s/vs_pubchem.pred" % (target)
  if not os.path.exists(vs_pred_file):
    os.system("cat pred_files/%s/vs_pubchem_*.pred > pred_files/%s/vs_pubchem.pred" % (target, target))
  aa = np.genfromtxt(vs_pred_file, delimiter="\t")
  a = aa[:, 1]
  test_pred_file = "pred_files/test_%s.pred" % (target)
  bb = np.genfromtxt(test_pred_file, delimiter="\t", usecols=[1,2])
  b = bb[:, 0][bb[:, 1].astype(bool)]
  x = []
  y = []
  for i in range(10):
    mark = (i + 1) / 20.0
    xi = 1.0 * (b > mark).sum() / b.shape[0]
    yi = (a > mark).sum()
    x.append(xi)
    y.append(yi)
  plt.plot(x, y, "*")
  plt.xlabel("pos yeild rate")
  plt.ylabel("vs pubchem false pos")
  plt.savefig("pred_files/%s/analyse.png" % (target))

target = target_list[int(sys.argv[1])]
virtual_screening(target)
analyse(target)

"""
for target in target_list:
  virtual_screening(target)
  #analyse(target)
"""


text:
<!--
    Copyright 2019 Google LLC

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<resources>
    <!-- [CHAR_LIMIT=100] -->
    <string name="app_name">Kerberos Authenticator</string>
    <!-- [CHAR_LIMIT=100] -->
    <string name="title">Active Directory Credentials</string>
    <!-- [CHAR_LIMIT=100] -->
    <string name="username">Username</string>
    <!-- [CHAR_LIMIT=300] -->
    <string name="username_description">An AD username that has privileges to access the website secure with SPNEGO (should be a regular user, not admin).</string>
    <!-- [CHAR_LIMIT=100] -->
    <string name="password">Password</string>
    <!-- [CHAR_LIMIT=300] -->
    <string name="password_description">AD password associated with this account.</string>
    <!-- [CHAR_LIMIT=100] -->
    <string name="ad_domain">Active Directory Domain</string>
    <!-- [CHAR_LIMIT=300] -->
    <string name="ad_domain_description">The organization's Active Directory domain.</string>
    <!-- [CHAR_LIMIT=100] -->
    <string name="service_principal">AD Controller</string>
    <!-- [CHAR_LIMIT=300] -->
    <string name="service_principal_description">hostname of the Active Directory server (not FQDN).</string>
    <!-- Name of the managed configuration field for controlling debugging -->
    <!-- [CHAR_LIMIT=100] -->
    <string name="sensitive_debug_data">Sensitive Debug Data</string>
    <!-- Description of the managed configuration field for controlling debugging -->
    <!-- [CHAR_LIMIT=300] -->
    <string name="sensitive_debug_data_description">Whether to emit debugging statements that include credentials.</string>
    <!-- [CHAR_LIMIT=100] -->
    <string name="account_type" translatable="false">com.goog.afw.KerberosAuthenticator</string>
    <!-- [CHAR_LIMIT=20] -->
    <string name="ok_btn">Dismiss</string>
    <!-- [CHAR_LIMIT=100] -->
    <string name="login_btn">LOGIN</string>
    <!-- [CHAR_LIMIT=100] -->
    <string name="last_user_auth_time">N/A</string>
    <!-- [CHAR_LIMIT=50] -->
    <string name="last_user_auth_text">Last user authentication</string>
    <!-- [CHAR_LIMIT=50] -->
    <string name="last_service_auth_time">N/A</string>
    <!-- [CHAR_LIMIT=50] -->
    <string name="last_service_auth_text">Last service authentication</string>
    <!-- [CHAR_LIMIT=50] -->
    <string name="version_error">Unknown Version</string>
    <!-- [CHAR_LIMIT=100] -->
    <string name="adding_account_unsupported_title">
        User-added accounts are not supported
    </string>
    <!-- [CHAR_LIMIT=50] -->
    <string name="adding_account_missing_config_title">
        Account configuration is missing
    </string>
    <!-- [CHAR_LIMIT=50] -->
    <string name="adding_account_unsupported_text">
        To add Active Directory account details to your managed device, please contact your IT administrator.
    </string>
    <!-- [CHAR_LIMIT=10] -->
    <string name="subtitle_user_creds" translatable="false">%1$s@%2$s</string>
    <!-- [CHAR_LIMIT=50] -->
    <string name="not_available">N/A</string>
    <!-- [CHAR_LIMIT=20] -->
    <string name="valid">Valid</string>
    <!-- [CHAR_LIMIT=20] -->
    <string name="from">from</string>
    <!-- [CHAR_LIMIT=15] -->
    <string name="until">until</string>
    <!-- [CHAR_LIMIT=100] -->
    <string name="enter_pw">Enter Password</string>
</resources>


text:
@protocol CNKeyDescriptor;
@class NSString;
@class NSDateComponents;
@class NSArray;
@class NSData;
@class NSPredicate;

typedef NS_ENUM(NSInteger, CNContactType) { CNContactTypePerson, CNContactTypeOrganization };

typedef NS_ENUM(NSInteger, CNContactSortOrder) {
    CNContactSortOrderNone,
    CNContactSortOrderUserDefault,
    CNContactSortOrderGivenName,
    CNContactSortOrderFamilyName
};

CONTACTS_EXPORT NSString* const CNContactPropertyNotFetchedExceptionName;
CONTACTS_EXPORT NSString* const CNContactIdentifierKey;
CONTACTS_EXPORT NSString* const CNContactNamePrefixKey;
CONTACTS_EXPORT NSString* const CNContactGivenNameKey;
CONTACTS_EXPORT NSString* const CNContactMiddleNameKey;
CONTACTS_EXPORT NSString* const CNContactFamilyNameKey;
CONTACTS_EXPORT NSString* const CNContactPreviousFamilyNameKey;
CONTACTS_EXPORT NSString* const CNContactNameSuffixKey;
CONTACTS_EXPORT NSString* const CNContactNicknameKey;
CONTACTS_EXPORT NSString* const CNContactPhoneticGivenNameKey;
CONTACTS_EXPORT NSString* const CNContactPhoneticMiddleNameKey;
CONTACTS_EXPORT NSString* const CNContactPhoneticFamilyNameKey;
CONTACTS_EXPORT NSString* const CNContactOrganizationNameKey;
CONTACTS_EXPORT NSString* const CNContactDepartmentNameKey;
CONTACTS_EXPORT NSString* const CNContactJobTitleKey;
CONTACTS_EXPORT NSString* const CNContactBirthdayKey;
CONTACTS_EXPORT NSString* const CNContactNonGregorianBirthdayKey;
CONTACTS_EXPORT NSString* const CNContactNoteKey;
CONTACTS_EXPORT NSString* const CNContactImageDataKey;
CONTACTS_EXPORT NSString* const CNContactThumbnailImageDataKey;
CONTACTS_EXPORT NSString* const CNContactImageDataAvailableKey;
CONTACTS_EXPORT NSString* const CNContactTypeKey;
CONTACTS_EXPORT NSString* const CNContactPhoneNumbersKey;
CONTACTS_EXPORT NSString* const CNContactEmailAddressesKey;
CONTACTS_EXPORT NSString* const CNContactPostalAddressesKey;
CONTACTS_EXPORT NSString* const CNContactDatesKey;
CONTACTS_EXPORT NSString* const CNContactUrlAddressesKey;
CONTACTS_EXPORT NSString* const CNContactRelationsKey;
CONTACTS_EXPORT NSString* const CNContactSocialProfilesKey;
CONTACTS_EXPORT NSString* const CNContactInstantMessageAddressesKey;

CONTACTS_EXPORT_CLASS
@interface CNContact : NSObject <NSCopying, NSMutableCopying, NSSecureCoding>
@property (readonly, copy, nonatomic) NSString* identifier STUB_PROPERTY;
@property (readonly, nonatomic) CNContactType contactType STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSDateComponents* birthday STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSDateComponents* nonGregorianBirthday STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSArray* dates STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSString* namePrefix STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSString* givenName STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSString* middleName STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSString* familyName STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSString* previousFamilyName STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSString* nameSuffix STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSString* nickname STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSString* phoneticGivenName STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSString* phoneticMiddleName STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSString* phoneticFamilyName STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSString* organizationName STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSString* departmentName STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSString* jobTitle STUB_PROPERTY;
+ (NSString*)localizedStringForKey:(NSString*)key STUB_METHOD;
+ (id<CNKeyDescriptor>)descriptorForAllComparatorKeys STUB_METHOD;
+ (NSComparator)comparatorForNameSortOrder:(CNContactSortOrder)sortOrder STUB_METHOD;
@property (readonly, copy, nonatomic) NSArray* socialProfiles STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSArray* phoneNumbers STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSArray* urlAddresses STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSArray* postalAddresses STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSArray* emailAddresses STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSString* note STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSData* imageData STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSData* thumbnailImageData STUB_PROPERTY;
@property (readonly, nonatomic) BOOL imageDataAvailable STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSArray* contactRelations STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSArray* instantMessageAddresses STUB_PROPERTY;
- (BOOL)isKeyAvailable:(NSString*)key STUB_METHOD;
- (BOOL)areKeysAvailable:(NSArray*)keyDescriptors STUB_METHOD;
+ (NSPredicate*)predicateForContactsMatchingName:(NSString*)name STUB_METHOD;
+ (NSPredicate*)predicateForContactsWithIdentifiers:(NSArray*)identifiers STUB_METHOD;
+ (NSPredicate*)predicateForContactsInGroupWithIdentifier:(NSString*)groupIdentifier STUB_METHOD;
+ (NSPredicate*)predicateForContactsInContainerWithIdentifier:(NSString*)containerIdentifier STUB_METHOD;
@end


text:
// @(#) $Id: TwoWayNode.java,v 1.10 2007/07/01 02:38:46 chalin Exp $

// Copyright (C) 1998, 1999 Iowa State University

// This file is part of JML

// JML is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2, or (at your option)
// any later version.

// JML is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with JML; see the file COPYING.  If not, write to
// the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.

// Author:  Clyde Ruby

package org.jmlspecs.samples.list.node;

//@ refine "TwoWayNode.jml";

public class TwoWayNode extends OneWayNode { // Doubly Linked Node

    // data members

    protected /*@ nullable @*/ TwoWayNode prevNode_;

    public TwoWayNode() {
	super();
	prevNode_ = null;
    }
    public TwoWayNode(/*@ nullable @*/ Object ent) {
	super(ent);
	prevNode_ = null;
    }
    public void insertAfter(/*@ nullable @*/ Object newEntry) {
	nextNode_ = new TwoWayNode(newEntry, this, (TwoWayNode)nextNode_);
    }
    public void removeNextNode() {
	if (nextNode_ != null) {
	    TwoWayNode nextNextNode = (TwoWayNode) nextNode_.getNextNode();

	    // remove the current links
	    // the next line is needed in case nextNode_ is aliased
	    ((TwoWayNode) nextNode_).linkTo(null);

	    this.linkTo(nextNextNode);
	}
    }
    public /*@ pure nullable @*/ TwoWayNode getPrevNode() {
	return prevNode_;
    }
    public void insertBefore(/*@ nullable @*/ Object newEntry) {
	prevNode_ = new TwoWayNode(newEntry, prevNode_, this);
    }
    public String toString() {
	String str = "";
	str += stringOfPrevEntries(((TwoWayNode)this).getPrevNode());
	str += " || ";
	str += stringOfEntries(this);
	return str;
    }

    /** The first invocation of this method should be with curr ==
     * prevNode_. If this is done, then the string returned will be a
     * concatentation of all nodes prior to this node up to and excluding the
     * end of the chain or this, which ever is reached first (i.e. this method
     * will terminate even for circular lists).
     */
    protected /*@ pure @*/ String stringOfPrevEntries(
                                      /*@ nullable @*/ TwoWayNode curr)
    {
	if (curr == null
	    // the following disjunct prevents infinite recursion
	    || curr == this) {
	    return "";
	}
	return stringOfPrevEntries(curr.getPrevNode())
	    + curr.getEntry() + ", ";
    }
    public Object clone() {
	if (nextNode_ == null) {
	    if (prevNode_ == null) {
		return new TwoWayNode(getEntry());
	    } else {
		return new TwoWayNode(getEntry(),
				      prevNode_.clonePrevious(), null);
	    }
	} else {
	    if (prevNode_ == null) {
		return new TwoWayNode(getEntry(), null,
				      ((TwoWayNode)nextNode_).cloneNext());
	    } else {
		return new TwoWayNode(getEntry(),
				      prevNode_.clonePrevious(),
				      ((TwoWayNode)nextNode_).cloneNext());
	    }
	}
    }
    protected /*@ pure @*/ TwoWayNode cloneNext() {
	if (nextNode_ == null) {
	    return new TwoWayNode(getEntry());
	} else {
	    return new TwoWayNode(getEntry(), null,
			      ((TwoWayNode)nextNode_).cloneNext());
	}
    }
    protected /*@ pure @*/ TwoWayNode clonePrevious() {
	if (prevNode_ == null) {
	    return new TwoWayNode(getEntry());
	} else {
	    return new TwoWayNode(getEntry(), prevNode_.clonePrevious(), null);
	}
    }
    private /*@ helper @*/ void linkTo(/*@ nullable @*/ TwoWayNode nxtNode) {
	if (nextNode_ != null) {
	    // needed in case nextNode_ is aliased

	    ((TwoWayNode)nextNode_).prevNode_ = null;
	}
	if (nxtNode != null) {
	    // has to be done here or in a private helper method
	    // so the invariant holds!
	    nxtNode.prevNode_ = this;
	}
	nextNode_ = nxtNode;
    }
    protected TwoWayNode(/*@ nullable @*/ Object ent,
                         /*@ nullable @*/ TwoWayNode prvNode,
                         /*@ nullable @*/ TwoWayNode nxtNode)
    {
	this(ent);
	if (prvNode != null) {
	    prvNode.linkTo(this);
	}
	if (nxtNode != null) {
	    this.linkTo(nxtNode);
	}
    }
}


text:
//
//  Cacheable.h
//  Save a Selfie
//
//  Created by Stephen Fox on 15/02/2016.
//  Copyright © 2016 Stephen Fox. All rights reserved.
//

#import <UIKit/UIKit.h>

/**
 This protocol is typically implemented when an
 object wants to provide they're own custom caching
 implementation when given the choice.
*/
@protocol Cacheable <NSObject>

- (void) cacheObjects: (NSArray<NSObject*>*) objects;

@end


text:
<plugin name='codenarc' version='1.6' grailsVersion='2.4 > *'>
  <author>Chris Mair</author>
  <authorEmail>chrismair@users.sourceforge.net</authorEmail>
  <title>CodeNarc plugin</title>
  <description>Runs CodeNarc static analysis rules for Groovy source.</description>
  <documentation>http://grails.org/plugin/codenarc</documentation>
  <type>CodenarcGrailsPlugin</type>
  <resources />
</plugin>


text:
/*
 * NaCl semaphore type (Linux)
 */
#ifndef NATIVE_CLIENT_SRC_TRUSTED_PLATFORM_LINUX_NACL_SEMAPHORE_H_
#define NATIVE_CLIENT_SRC_TRUSTED_PLATFORM_LINUX_NACL_SEMAPHORE_H_

#include <semaphore.h>

struct NaClSemaphore {
  sem_t sem_obj;
};

#endif  /* NATIVE_CLIENT_SRC_TRUSTED_PLATFORM_LINUX_NACL_SEMAPHORE_H_ */


text:
#ifndef BLOCK_H
#define BLOCK_H

#define BLOCKLEN 		8
#define SINGLEKEY		BLOCKLEN
#define DOUBLEKEY		BLOCKLEN*2
#define TRIPLEKEY		BLOCKLEN*3
#define MAXDECTAB 		BLOCKLEN*2
#define MAXDATVAL 		BLOCKLEN*2
#define MINPINLENGTH 	4
#define MAXPINLENGTH 	6
#define ERRSTABLK		100

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
//
//
#ifdef __cplusplus
}
#endif

#endif  /* ! IBM3624_H */


text:
namespace media {

namespace {

SkColorType GetCompatibleSurfaceColorType(GrGLenum format) {
  switch (format) {
    case GL_RGBA8:
      return kRGBA_8888_SkColorType;
    case GL_RGB565:
      return kRGB_565_SkColorType;
    case GL_RGBA16F:
      return kRGBA_F16_SkColorType;
    case GL_RGB8:
      return kRGB_888x_SkColorType;
    case GL_RGB10_A2:
      return kRGBA_1010102_SkColorType;
    case GL_RGBA4:
      return kARGB_4444_SkColorType;
    case GL_SRGB8_ALPHA8:
      return kRGBA_8888_SkColorType;
    default:
      NOTREACHED();
      return kUnknown_SkColorType;
  }
}

GrGLenum GetSurfaceColorFormat(GrGLenum format, GrGLenum type) {
  if (format == GL_RGBA) {
    if (type == GL_UNSIGNED_BYTE)
      return GL_RGBA8;
    if (type == GL_UNSIGNED_SHORT_4_4_4_4)
      return GL_RGBA4;
  }
  if (format == GL_RGB) {
    if (type == GL_UNSIGNED_BYTE)
      return GL_RGB8;
    if (type == GL_UNSIGNED_SHORT_5_6_5)
      return GL_RGB565;
  }
  return format;
}

void DrawYUVImageToSkSurface(const VideoFrame* video_frame,
                             sk_sp<SkImage> image,
                             sk_sp<SkSurface> surface,
                             bool use_visible_rect) {
  if (!use_visible_rect) {
    surface->getCanvas()->drawImage(image, 0, 0);
  } else {
    // Draw the planar SkImage to the SkSurface wrapping the WebGL texture.
    // Using drawImageRect to draw visible rect from video frame to dst texture.
    const gfx::Rect& visible_rect = video_frame->visible_rect();
    const SkRect src_rect =
        SkRect::MakeXYWH(visible_rect.x(), visible_rect.y(),
                         visible_rect.width(), visible_rect.height());
    const SkRect dst_rect =
        SkRect::MakeWH(visible_rect.width(), visible_rect.height());
    surface->getCanvas()->drawImageRect(image, src_rect, dst_rect,
                                        SkSamplingOptions(), nullptr,
                                        SkCanvas::kStrict_SrcRectConstraint);
  }

  surface->flushAndSubmit();
}

}  // namespace

VideoFrameYUVConverter::VideoFrameYUVConverter() = default;
VideoFrameYUVConverter::~VideoFrameYUVConverter() = default;

bool VideoFrameYUVConverter::IsVideoFrameFormatSupported(
    const VideoFrame& video_frame) {
  return std::get<0>(VideoFrameYUVMailboxesHolder::VideoPixelFormatToSkiaValues(
             video_frame.format())) != SkYUVAInfo::PlaneConfig::kUnknown;
}

bool VideoFrameYUVConverter::ConvertYUVVideoFrameNoCaching(
    const VideoFrame* video_frame,
    viz::RasterContextProvider* raster_context_provider,
    const gpu::MailboxHolder& dest_mailbox_holder,
    absl::optional<GrParams> gr_params) {
  VideoFrameYUVConverter converter;
  return converter.ConvertYUVVideoFrame(video_frame, raster_context_provider,
                                        dest_mailbox_holder, gr_params);
}

bool VideoFrameYUVConverter::ConvertYUVVideoFrame(
    const VideoFrame* video_frame,
    viz::RasterContextProvider* raster_context_provider,
    const gpu::MailboxHolder& dest_mailbox_holder,
    absl::optional<GrParams> gr_params) {
  DCHECK(video_frame);
  DCHECK(IsVideoFrameFormatSupported(*video_frame))
      << "VideoFrame has an unsupported YUV format " << video_frame->format();
  DCHECK(!video_frame->coded_size().IsEmpty())
      << "|video_frame| must have an area > 0";
  DCHECK(raster_context_provider);

  if (!holder_)
    holder_ = std::make_unique<VideoFrameYUVMailboxesHolder>();

  if (raster_context_provider->GrContext()) {
    return ConvertFromVideoFrameYUVWithGrContext(
        video_frame, raster_context_provider, dest_mailbox_holder,
        gr_params.value_or(GrParams()));
  }

  // The RasterInterface path does not support flip_y or use_visible_rect.
  if (gr_params) {
    DCHECK(!gr_params->flip_y);
    DCHECK(!gr_params->use_visible_rect);
  }

  auto* ri = raster_context_provider->RasterInterface();
  DCHECK(ri);
  ri->WaitSyncTokenCHROMIUM(dest_mailbox_holder.sync_token.GetConstData());

  gpu::Mailbox mailboxes[SkYUVAInfo::kMaxPlanes]{};
  holder_->VideoFrameToMailboxes(video_frame, raster_context_provider,
                                 mailboxes);
  ri->ConvertYUVAMailboxesToRGB(dest_mailbox_holder.mailbox,
                                holder_->yuva_info().yuvColorSpace(), nullptr,
                                holder_->yuva_info().planeConfig(),
                                holder_->yuva_info().subsampling(), mailboxes);
  return true;
}

void VideoFrameYUVConverter::ReleaseCachedData() {
  holder_.reset();
}

bool VideoFrameYUVConverter::ConvertFromVideoFrameYUVWithGrContext(
    const VideoFrame* video_frame,
    viz::RasterContextProvider* raster_context_provider,
    const gpu::MailboxHolder& dest_mailbox_holder,
    const GrParams& gr_params) {
  gpu::raster::RasterInterface* ri = raster_context_provider->RasterInterface();
  DCHECK(ri);
  ri->WaitSyncTokenCHROMIUM(dest_mailbox_holder.sync_token.GetConstData());
  GLuint dest_tex_id =
      ri->CreateAndConsumeForGpuRaster(dest_mailbox_holder.mailbox);
  if (dest_mailbox_holder.mailbox.IsSharedImage()) {
    ri->BeginSharedImageAccessDirectCHROMIUM(
        dest_tex_id, GL_SHARED_IMAGE_ACCESS_MODE_READWRITE_CHROMIUM);
  }

  // Rendering YUV textures to SkSurface by dst texture
  GrDirectContext* gr_context = raster_context_provider->GrContext();
  DCHECK(gr_context);
  // TODO(crbug.com/674185): We should compare the DCHECK vs when
  // UpdateLastImage calls this function.
  DCHECK(IsVideoFrameFormatSupported(*video_frame));

  // Create SkSurface with dst texture.
  GrGLTextureInfo result_gl_texture_info{};
  result_gl_texture_info.fID = dest_tex_id;
  result_gl_texture_info.fTarget = dest_mailbox_holder.texture_target;
  result_gl_texture_info.fFormat =
      GetSurfaceColorFormat(gr_params.internal_format, gr_params.type);

  int result_width = gr_params.use_visible_rect
                         ? video_frame->visible_rect().width()
                         : video_frame->coded_size().width();
  int result_height = gr_params.use_visible_rect
                          ? video_frame->visible_rect().height()
                          : video_frame->coded_size().height();

  GrBackendTexture result_texture(result_width, result_height, GrMipMapped::kNo,
                                  result_gl_texture_info);

  // Use the same SkColorSpace for the surface and image, so that no color space
  // conversion is performed.
  auto source_and_dest_color_space = SkColorSpace::MakeSRGB();

  // Use dst texture as SkSurface back resource.
  auto surface = SkSurface::MakeFromBackendTexture(
      gr_context, result_texture,
      gr_params.flip_y ? kBottomLeft_GrSurfaceOrigin : kTopLeft_GrSurfaceOrigin,
      1, GetCompatibleSurfaceColorType(result_gl_texture_info.fFormat),
      source_and_dest_color_space, nullptr);

  // Terminate if surface cannot be created.
  bool result = false;
  if (surface) {
    auto image = holder_->VideoFrameToSkImage(
        video_frame, raster_context_provider, source_and_dest_color_space);
    if (image) {
      result = true;
      DrawYUVImageToSkSurface(video_frame, image, surface,
                              gr_params.use_visible_rect);
    } else {
      DLOG(ERROR) << "Failed to create YUV SkImage";
    }
  } else {
    DLOG(ERROR) << "Failed to create SkSurface";
  }

  // Release textures to guarantee |holder_| doesn't hold read access on
  // textures it doesn't own.
  holder_->ReleaseTextures();

  if (dest_mailbox_holder.mailbox.IsSharedImage())
    ri->EndSharedImageAccessDirectCHROMIUM(dest_tex_id);
  ri->DeleteGpuRasterTexture(dest_tex_id);

  return result;
}

}  // namespace media


text:
/**
 * \file
 * \brief Arch specific CPU declarations
 */

/*
 * Copyright (c) 2010, ETH Zurich.
 * All rights reserved.
 *
 * This file is distributed under the terms in the attached LICENSE file.
 * If you do not find this file, copies can be found by writing to:
 * ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
 */

#ifndef ARCH_X86_64_BARRELFISH_KPI_CPU_H
#define ARCH_X86_64_BARRELFISH_KPI_CPU_H

/// This CPU supports lazy FPU context switching
#define FPU_LAZY_CONTEXT_SWITCH

/*
 * Entries in the Interrupt Descriptor Table (IDT)
 */
#define IDT_DE          0       /* #DE: Divide Error */
#define IDT_DB          1       /* #DB: Debug */
#define IDT_NMI         2       /* Nonmaskable External Interrupt */
#define IDT_BP          3       /* #BP: Breakpoint */
#define IDT_OF          4       /* #OF: Overflow */
#define IDT_BR          5       /* #BR: Bound Range Exceeded */
#define IDT_UD          6       /* #UD: Undefined/Invalid Opcode */
#define IDT_NM          7       /* #NM: No Math Coprocessor */
#define IDT_DF          8       /* #DF: Double Fault */
#define IDT_FPUGP       9       /* Coprocessor Segment Overrun */
#define IDT_TS          10      /* #TS: Invalid TSS */
#define IDT_NP          11      /* #NP: Segment Not Present */
#define IDT_SS          12      /* #SS: Stack Segment Fault */
#define IDT_GP          13      /* #GP: General Protection Fault */
#define IDT_PF          14      /* #PF: Page Fault */
#define IDT_MF          16      /* #MF: FPU Floating-Point Error */
#define IDT_AC          17      /* #AC: Alignment Check */
#define IDT_MC          18      /* #MC: Machine Check */
#define IDT_XF          19      /* #XF: SIMD Floating-Point Exception */

#endif


text:
using System;
using System.Net;
using Moq;
using NUnit.Framework;
using OctoNet.Services;
using OctoNet.Tests.Helpers;
using OctoNet.Web;

namespace OctoNet.Tests.Services
{
    [TestFixture]
    public class UserServiceTests
    {
        [Test]
        public void IsFollowingAsync_ShouldCallbackWithError_WhenResponseIsSomeRandomError()
        {
            var mockResponse = new Mock<IGitHubResponse<object>>(MockBehavior.Strict);
            var mockClient = new Mock<IGitHubClient>(MockBehavior.Strict);
            mockResponse.Setup(r => r.ErrorException)
                .Returns(new Exception());
            mockResponse.Setup(r => r.StatusCode)
                .Returns(HttpStatusCode.Forbidden);
            var expectedException = new GitHubException(mockResponse.Object,
                                                        ErrorType.Unauthorized);
            mockClient.Setup(c => c.CallApiAsync(It.IsAny<GitHubRequest>(),
                                                 It.IsAny<Action<IGitHubResponse<object>>>(),
                                                 It.IsAny<Action<GitHubException>>()))
                .Callback<GitHubRequest,
                    Action<IGitHubResponse<object>>,
                    Action<GitHubException>>((req, c, e) => { e(expectedException); })
                .Returns(TestHelpers.CreateTestHandle());
            var userService = new UserService(mockClient.Object);

            GitHubException actualException = null;
            userService.IsFollowingAsync("akilb",
                                         c => { },
                                         e => actualException = e);

            Assert.AreSame(expectedException, actualException);
        }

        [Test]
        public void IsFollowingAsync_ShouldCallbackWithFalse_WhenResponseIsNotFound()
        {
            var mockResponse = new Mock<IGitHubResponse<object>>(MockBehavior.Strict);
            var mockClient = new Mock<IGitHubClient>(MockBehavior.Strict);
            mockResponse.Setup(r => r.ErrorException)
                .Returns(new Exception());
            mockResponse.Setup(r => r.StatusCode)
                .Returns(HttpStatusCode.NotFound);
            mockClient.Setup(c => c.CallApiAsync(It.IsAny<GitHubRequest>(),
                                                 It.IsAny<Action<IGitHubResponse<object>>>(),
                                                 It.IsAny<Action<GitHubException>>()))
                .Callback<GitHubRequest,
                    Action<IGitHubResponse<object>>,
                    Action<GitHubException>>(
                        (req, c, e) => { e(new GitHubException(mockResponse.Object, ErrorType.ResourceNotFound)); })
                .Returns(TestHelpers.CreateTestHandle());
            var userService = new UserService(mockClient.Object);

            bool isFollowing = true;
            userService.IsFollowingAsync("akilb",
                                         fl => isFollowing = fl,
                                         e => { });

            Assert.IsFalse(isFollowing);
        }

        [Test]
        public void IsFollowingAsync_ShouldCallbackWithTrue_WhenResponseIsNoContent()
        {
            var mockResponse = new Mock<IGitHubResponse<object>>(MockBehavior.Strict);
            var mockClient = new Mock<IGitHubClient>(MockBehavior.Strict);
            mockResponse.Setup(r => r.ErrorException)
                .Returns(new Exception());
            mockResponse.Setup(r => r.StatusCode)
                .Returns(HttpStatusCode.NoContent);
            mockClient.Setup(c => c.CallApiAsync(It.IsAny<GitHubRequest>(),
                                                 It.IsAny<Action<IGitHubResponse<object>>>(),
                                                 It.IsAny<Action<GitHubException>>()))
                .Callback<GitHubRequest,
                    Action<IGitHubResponse<object>>,
                    Action<GitHubException>>(
                        (req, c, e) => { e(new GitHubException(mockResponse.Object, ErrorType.Unknown)); })
                .Returns(TestHelpers.CreateTestHandle());
            var userService = new UserService(mockClient.Object);

            bool isFollowing = false;
            userService.IsFollowingAsync("akilb",
                                         fl => isFollowing = fl,
                                         e => { });

            Assert.IsTrue(isFollowing);
        }
    }
}


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

    <item android:state_enabled="false" android:color="@color/normal_text_color_disabled"/>
    <item android:color="@color/normal_text_color"/>

</selector>


text:
<package>
  <description brief="agent">

     agent

  </description>
  <author>teichman</author>
  <license>BSD</license>
  <review status="unreviewed" notes=""/>
  <url>http://ros.org/wiki/agent</url>

  <depend package="roscpp"/>

  <export>
    <cpp cflags="-I${prefix}/include" lflags="-Wl,-rpath,${prefix}/lib -L${prefix}/lib `rosboost-cfg --lflags thread` -lagent" />
  </export>

</package>