text:
#include <common.h>
#include <asm/io.h>
#include <mvmfp.h>
#include <asm/arch/mfp.h>

/*
 * mfp_config
 *
 * On most of Marvell SoCs (ex. ARMADA100) there is Multi-Funtion-Pin
 * configuration registers to configure each GPIO/Function pin on the
 * SoC.
 *
 * This function reads the array of values for
 * MFPR_X registers and programms them into respective
 * Multi-Function Pin registers.
 * It supports - Alternate Function Selection programming.
 *
 * Whereas,
 * The Configureation value is constructed using MFP()
 * array consists of 32bit values as defined in MFP(xx,xx..) macro
 */
void mfp_config(u32 *mfp_cfgs)
{
	u32 *p_mfpr = NULL;
	u32 cfg_val, val;

	do {
		cfg_val = *mfp_cfgs++;
		/* exit if End of configuration table detected */
		if (cfg_val == MFP_EOC)
			break;

		p_mfpr = (u32 *)(MV_MFPR_BASE
				+ MFP_REG_GET_OFFSET(cfg_val));

		/* Write a mfg register as per configuration */
		val = 0;
		if (cfg_val & MFP_VALUE_MASK)
			val |= cfg_val & MFP_VALUE_MASK;

		writel(val, p_mfpr);
	} while (1);
	/*
	 * perform a read-back of any MFPR register to make sure the
	 * previous writings are finished
	 */
	readl(p_mfpr);
}


text:
class INDrawable
{
private:

public:

    virtual void draw(sf::RenderWindow *window) const = 0;
};

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Tests.Framework.Integration;
using Tests.Framework.ManagedElasticsearch;
using Tests.Framework.ManagedElasticsearch.Clusters;

namespace Tests.Framework.Profiling
{
	internal abstract class ProfileFactory<TAttribute> : IProfileFactory where TAttribute : ProfilingAttribute
	{
		private IEnumerable<ProfiledClass> _profiledClasses;

		protected ProfileFactory(string sdkPath,
			string outputPath,
			ClusterBase cluster,
			Assembly assembly,
			IColoredWriter output)
		{
			Name = this.GetType().Name.Replace("ProfileFactory", string.Empty).ToLowerInvariant();
			SdkPath = sdkPath;
			OutputPath = Path.Combine(outputPath, Name);
			Cluster = cluster;
			Assembly = assembly;
			Output = output;
		}

		private string Name { get; }

		protected Assembly Assembly { get; }

		protected ClusterBase Cluster { get; }

		protected IColoredWriter Output { get; }

		protected string OutputPath { get; }

		protected IEnumerable<ProfiledClass> ProfiledClasses
		{
			get
			{
				if (_profiledClasses == null)
				{
					_profiledClasses = Assembly
						.GetTypes()
						.Where(t => t.IsPublic() && t.IsClass())
						.Where(t => t.GetMethods(BindingFlags.Instance | BindingFlags.Public)
							.Any(m => m.GetCustomAttribute<TAttribute>() != null))
						.Select(t =>
						{
							var setup = t.GetMethods(BindingFlags.Instance | BindingFlags.Public)
								.Where(m => m.GetCustomAttribute<ProfilingSetupAttribute>() != null)
								.Select(m => new ProfiledMethod(m, m.GetCustomAttribute<ProfilingSetupAttribute>()))
								.FirstOrDefault();

							var methods = t.GetMethods(BindingFlags.Instance | BindingFlags.Public)
								.Where(m => m.GetCustomAttribute<TAttribute>() != null)
								.Select(m => new ProfiledMethod(m, m.GetCustomAttribute<TAttribute>()));

							return new ProfiledClass(t, setup, methods);
						});
				}

				return _profiledClasses;
			}
		}

		protected string SdkPath { get; }

		public void Run(ProfileConfiguration configuration)
		{
			foreach (var profiledClass in ProfiledClasses
				.Where(c => !configuration.ClassNames.Any() || configuration.ClassNames.Contains(c.Name))
				.Where(c => c.Methods.Any(m => !m.IsAsync)))
			{
				var instance = profiledClass.CreateInstance(Cluster);

				if (profiledClass.SetupMethod != null)
				{
					var setup = profiledClass.SetupMethod.Compile(instance);
					Output.WriteLine(ConsoleColor.Green, $"Running setup for {profiledClass.Type.Name}");
					setup();
				}

				foreach (var profiledMethod in profiledClass.Methods.Where(m => !m.IsAsync))
				{
					var resultsDirectory = Path.Combine(OutputPath, profiledClass.Type.Name, profiledMethod.MethodInfo.Name);
					var action = profiledMethod.Compile(instance);

					Output.WriteLine(
						ConsoleColor.Green,
						$"{Name} profiling {profiledClass.Type.Name}.{profiledMethod.MethodInfo.Name}");

					using (BeginProfiling(resultsDirectory))
					{
						for (int i = 0; i < profiledMethod.Attribute.Iterations; i++)
						{
							action();
						}
					}
				}
			}
		}

		public async Task RunAsync(ProfileConfiguration configuration)
		{
			foreach (var profiledClass in ProfiledClasses
				.Where(c => !configuration.ClassNames.Any() || configuration.ClassNames.Contains(c.Name))
				.Where(c => c.Methods.Any(m => m.IsAsync)))
			{
				var instance = profiledClass.CreateInstance(Cluster);

				if (profiledClass.SetupMethod != null)
				{
					var setup = profiledClass.SetupMethod.Compile(instance);
					Output.WriteLine(ConsoleColor.Green, $"Running setup for {profiledClass.Type.Name}");
					setup();
				}

				foreach (var profiledMethod in profiledClass.Methods.Where(m => m.IsAsync))
				{
					var resultsDirectory = Path.Combine(OutputPath, profiledClass.Type.Name, profiledMethod.MethodInfo.Name);
					var thunk = profiledMethod.CompileAsync(instance);

					Output.WriteLine(
						ConsoleColor.Green,
						$"{Name} profiling {profiledClass.Type.Name}.{profiledMethod.MethodInfo.Name}");

					using (BeginProfiling(resultsDirectory))
					{
						for (int i = 0; i < profiledMethod.Attribute.Iterations; i++)
						{
							await thunk().ConfigureAwait(false);
						}
					}
				}
			}
		}

		protected abstract IDisposable BeginProfiling(string resultsDirectory);
	}
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Orchis chevallieriana E.G.Camus

### Remarks
null


text:
#include "master.hpp"

/*
	Windows argument parsing ported to work on
	int main(int argc, wchar_t **argv).

	Based on MinGW's public domain char** version.
*/

VM_C_API int parse_tokens(wchar_t *string, wchar_t ***tokens, int length)
{
	/* Extract whitespace- and quotes- delimited tokens from the given string
	   and put them into the tokens array. Returns number of tokens
	   extracted. Length specifies the current size of tokens[].
	   THIS METHOD MODIFIES string.  */

	const wchar_t *whitespace = L" \t\r\n";
	wchar_t *tokenEnd = 0;
	const wchar_t *quoteCharacters = L"\"\'";
	wchar_t *end = string + wcslen(string);

	if (string == NULL)
		return length;

	while (1)
	{
		const wchar_t *q;
		/* Skip over initial whitespace.  */
		string += wcsspn(string, whitespace);
		if (*string == '\0')
			break;

		for (q = quoteCharacters; *q; ++q)
		{
			if (*string == *q)
				break;
		}
		if (*q)
		{
			/* Token is quoted.  */
			wchar_t quote = *string++;
			tokenEnd = wcschr(string, quote);
			/* If there is no endquote, the token is the rest of the string.  */
			if (!tokenEnd)
				tokenEnd = end;
		}
		else
		{
			tokenEnd = string + wcscspn(string, whitespace);
		}

		*tokenEnd = '\0';

		{
			wchar_t **new_tokens;
			int newlen = length + 1;
			new_tokens = (wchar_t **)realloc (*tokens, sizeof (wchar_t**) * newlen);
			if (!new_tokens)
			{
				/* Out of memory.  */
				return -1;
			}

			*tokens = new_tokens;
			(*tokens)[length] = string;
			length = newlen;
		}
		if (tokenEnd == end)
			break;
		string = tokenEnd + 1;
	}
	return length;
}

VM_C_API void parse_args(int *argc, wchar_t ***argv, wchar_t *cmdlinePtrW)
{
	int cmdlineLen = 0;

	if (!cmdlinePtrW)
		cmdlineLen = 0;
	else
		cmdlineLen = wcslen(cmdlinePtrW);

	/* gets realloc()'d later */
	*argc = 0;
	*argv = (wchar_t **)malloc (sizeof (wchar_t**));

	if (!*argv)
		ExitProcess(1);

#ifdef WINCE
	wchar_t cmdnameBufW[MAX_UNICODE_PATH];

	/* argv[0] is the path of invoked program - get this from CE.  */
	cmdnameBufW[0] = 0;
	GetModuleFileNameW(NULL, cmdnameBufW, sizeof (cmdnameBufW)/sizeof (cmdnameBufW[0]));

	(*argv)[0] = wcsdup(cmdnameBufW);
	if(!(*argv[0]))
		ExitProcess(1);
	/* Add one to account for argv[0] */
	(*argc)++;
#endif

	if (cmdlineLen > 0)
	{
		wchar_t *string = wcsdup(cmdlinePtrW);
		if(!string)
			ExitProcess(1);
		*argc = parse_tokens(string, argv, *argc);
		if (*argc < 0)
			ExitProcess(1);
	}
	(*argv)[*argc] = 0;
	return;
}

int WINAPI WinMain(
	HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPWSTR lpCmdLine,
	int nCmdShow)
{
	int __argc;
	wchar_t **__argv;
	factor::parse_args(&__argc, &__argv, lpCmdLine);
	factor::init_globals();
	factor::start_standalone_factor(__argc,(LPWSTR*)__argv);

	// memory leak from malloc, wcsdup
	return 0;
}


text:
declare
    l_table_count NUMBER;
begin

    select count(1)
    into l_table_count
    from user_tables
    where table_name = 'WORD_TRANSLATION';

    if l_table_count = 0
    then

        execute immediate '
        create table word_translation(
            word_german varchar2(512),
            word_en varchar2(512)
        )';

    end if;

end;
/

--GDB DEFINITION
delete from word_translation;
load word_translation raw/GDB_DEFINITION.csv

begin

    for trnsl in (
        select *
        from word_translation
    )
    loop

        update GDB_DEFINITION
        set german_description = trnsl.word_en
        where german_description = trnsl.word_german;

    end loop;

end;
/

--GDB_GER_FS_ANIMAL_FARMING - SPECIES
delete from word_translation;
load word_translation raw/GDB_ANIMAL_FARMING_SPECIES.csv

begin

    for trnsl in (
        select *
        from word_translation
    )
    loop

        update GDB_GER_FS_ANIMAL_FARMING
        set species = trnsl.word_en
        where species = trnsl.word_german;

    end loop;

end;
/

--GDB_GER_FS_ANIMAL_FARMING - FEDERAL_STATE
delete from word_translation;
load word_translation raw/GDB_ANIMAL_FARMING_STATE.csv

begin

    for trnsl in (
        select *
        from word_translation
    )
    loop

        update GDB_GER_FS_ANIMAL_FARMING
        set FEDERAL_STATE = trnsl.word_en
        where FEDERAL_STATE = trnsl.word_german;

    end loop;

end;
/

--GDB_GER_FS_POPULATION_FUTURE - DEF
delete from word_translation;
load word_translation raw/GDB_POPULATION_FUTURE_DEF.csv

begin

    for trnsl in (
        select *
        from word_translation
    )
    loop

        update GDB_GER_FS_POPULATION_FUTURE
        set definition = trnsl.word_en
        where definition = trnsl.word_german;

    end loop;

end;
/

--GDB_GER_FS_POPULATION_FUTURE - GENDER
delete from word_translation;
load word_translation raw/GDB_POPULATION_FUTURE_GENDER.csv

begin

    for trnsl in (
        select *
        from word_translation
    )
    loop

        update GDB_GER_FS_POPULATION_FUTURE
        set population_by_gender = trnsl.word_en
        where population_by_gender = trnsl.word_german;

    end loop;

end;
/

--GDB_GER_HOSPITAL_INFO - CATEGORY
delete from word_translation;
load word_translation raw/GDB_HOSPITAL_INFO_CAT.csv

begin

    for trnsl in (
        select *
        from word_translation
    )
    loop

        update GDB_GER_HOSPITAL_INFO
        set category = trnsl.word_en
        where category = trnsl.word_german;

    end loop;

end;
/

--GDB_GER_HOSPITAL_INFO - CATEGORY_TYP
delete from word_translation;
load word_translation raw/GDB_HOSPITAL_INFO_CAT_TYP.csv

begin

    for trnsl in (
        select *
        from word_translation
    )
    loop

        update GDB_GER_HOSPITAL_INFO
        set category_typ = trnsl.word_en
        where category_typ = trnsl.word_german;

    end loop;

end;
/
exit


text:
casper.echo( "OC-110: tavutettu sana jakautuu oikein kahdeksi highlight boksiksi" );

var settings     = require('./settings');
var mytests      = require('./mytests');

casper.start(settings.defaultPageUrl);

casper.then(function() {
    this.test.assertExists('#editor');
});

casper.waitForText( "Pienet");

casper.then(function() {

    // place cursor on 'kultahanhet'
    var newCursor = this.evaluate( function () {
        require('editor').view.cMirror.setCursor(15,50);
        return require('editor').view.cMirror.getCursor();
    });

    this.test.assertEqual(newCursor.line,15, "cursor move line");
    this.test.assertEqual(newCursor.ch,50, "cursor move ch");

});

casper.waitFor(function() {

    var expectedBoundss = [
        { left:373, top:640, width:78, height:26},
        { left:-367, top:686, width:110, height:27}
    ];
    if (casper.exists(".highlight-box")) {

        for (var i in expectedBoundss) {
            var eb = expectedBoundss[i];
            var n = i + 1;
            var selector = ".highlight-box:nth-of-type("+n+")";
            var b = casper.exists(selector) ?
                casper.getElementBounds(selector) :
                {};

            if (mytests.cmpObjects(b,eb)) {
                this.test.assert(true, "Got correct highlight box after click");
                return true;
            }
        }
    }

    return false

});

casper.run(function() {
    this.test.done();
});


text:
#import "SBIconView.h"

#import "_UISettingsKeyObserver-Protocol.h"

@class SBFolderSettings;

@interface SBFolderIconView : SBIconView <_UISettingsKeyObserver>
{
    SBFolderSettings *_folderSettings;
}

+ (_Bool)canShowUpdatedMark;
- (id)_folderIconImageView;
- (void)settings:(id)arg1 changedValueForKey:(id)arg2;
- (void)_updateAdaptiveColors;
- (void)_applyEditingStateAnimated:(_Bool)arg1;
- (void)cleanupAfterFloatyFolderCrossfade;
- (void)setFloatyFolderCrossfadeFraction:(double)arg1;
- (void)prepareToCrossfadeWithFloatyFolderView:(id)arg1 allowFolderInteraction:(_Bool)arg2;
- (void)removeDropGlow;
- (void)showDropGlow:(_Bool)arg1;
- (void)prepareDropGlow;
- (void)setBackgroundAndIconGridImageAlpha:(double)arg1;
- (void)setIconGridImageAlpha:(double)arg1;
- (double)grabDurationForEvent:(id)arg1;
- (_Bool)allowsTapWhileEditing;
- (id)description;
- (id)folder;
- (void)scrollToGapOrTopIfFullOfPage:(unsigned long long)arg1 animated:(_Bool)arg2;
- (void)scrollToTopOfPage:(unsigned long long)arg1 animated:(_Bool)arg2;
- (void)scrollToFirstGapAnimated:(_Bool)arg1;
- (void)scrollToTopOfFirstPageAnimated:(_Bool)arg1;
- (struct CGRect)visibleImageRelativeFrameForMiniIconAtIndex:(unsigned long long)arg1;
- (struct CGRect)frameForMiniIconAtIndex:(unsigned long long)arg1;
- (unsigned long long)lastVisibleMiniIconIndex;
- (unsigned long long)centerVisibleMiniIconIndex;
- (unsigned long long)firstVisibleMiniIconIndex;
- (unsigned long long)visibleMiniIconListIndex;
- (unsigned long long)visibleMiniIconCount;
- (id)iconBackgroundView;
- (id)dropGlow;
- (void)setIcon:(id)arg1;
- (id)folderIcon;
- (void)dealloc;
- (id)initWithFrame:(struct CGRect)arg1;

@end


text:
var express = require('express');
var router = express.Router();

var Recipe = require('./models/recipe');

// Home page
router.get('/', function(req, res){
  res.json({message: 'Hello'});
});

// Recipe request
router.route('/recipes').get(function(req, res) {
  Recipe.find(function(err, recipes) {
    if (err) {
      console.log(err);
      res.json({
        message: 'Error getting recipes',
        code: 1
      });
    }
    res.json(recipes);
  });
});

// Recipe add
router.route('/recipes').post(function(req, res) {
  var recipe = new Recipe();

  // TODO validation
  recipe.name = req.body.name;
  recipe.prepTime = req.body.prepTime;
  recipe.cookTime = req.body.cookTime;
  recipe.ingredients = req.body.ingredients;
  recipe.directions = req.body.directions;
  recipe.tags = req.body.tags;

  recipe.save(function(err) {
    if (err) {
      console.log(err);
      res.json({messge: 'Error saving recipe'});
    }
    res.json({message: 'Added recipe'});
  });
});

module.exports = router;


text:
class PrefRegistrySimple;

namespace base {
class TickClock;
}

namespace chromeos {
namespace system {

// Schedules and executes automatic reboots.
//
// Automatic reboots may be scheduled for any number of reasons. Currently, the
// following are implemented:
// * When Chrome OS has applied a system update, a reboot may become necessary
//   to complete the update process. If the policy to automatically reboot after
//   an update is enabled, a reboot is scheduled at that point.
// * If an uptime limit is set through policy, a reboot is scheduled when the
//   device's uptime reaches the limit. Time spent sleeping counts as uptime as
//   well.
//
// When the time of the earliest scheduled reboot is reached, the reboot is
// requested. The reboot is performed immediately unless one of the following
// reasons inhibits it:
// * If the login screen is being shown: Reboots are inhibited while the user is
//   interacting with the screen (determined by checking whether there has been
//   any user activity in the past 60 seconds).
// * If a session is in progress: Reboots are inhibited until the session ends,
//   the browser is restarted or the device is suspended.
//
// If reboots are inhibited, a 24 hour grace period is started. The reboot
// request is carried out the moment none of the inhibiting criteria apply
// anymore (e.g. the user becomes idle on the login screen, the user logs exits
// a session, the user suspends the device). If reboots remain inhibited for the
// entire grace period, a reboot is unconditionally performed at its end.
//
// Note: Currently, automatic reboots are only enabled while the login screen is
// being shown or a kiosk app session is in progress. This will change in the
// future and the policy will always apply, regardless of whether a session of
// any particular type is in progress or not. http://crbug.com/244972
//
// Reboots may be scheduled and canceled at any time. This causes the time at
// which a reboot should be requested and the grace period that follows it to
// be recalculated.
//
// Reboots are scheduled in terms of device uptime. The current uptime is read
// from /proc/uptime. The time at which a reboot became necessary to finish
// applying an update is stored in /var/run/chrome/update_reboot_needed_uptime,
// making it persist across browser restarts and crashes. Placing the file under
// /var/run ensures that it gets cleared automatically on every boot.
class AutomaticRebootManager : public PowerManagerClient::Observer,
                               public UpdateEngineClient::Observer,
                               public ui::UserActivityObserver,
                               public content::NotificationObserver {
 public:
  // The current uptime and the uptime at which an update was applied and a
  // reboot became necessary (if any). Used to pass this information from the
  // blocking thread pool to the UI thread.
  struct SystemEventTimes {
    SystemEventTimes();
    SystemEventTimes(const base::TimeDelta& uptime,
                     const base::TimeDelta& update_reboot_needed_uptime);

    bool has_boot_time;
    base::TimeTicks boot_time;

    bool has_update_reboot_needed_time;
    base::TimeTicks update_reboot_needed_time;
  };

  explicit AutomaticRebootManager(scoped_ptr<base::TickClock> clock);
  ~AutomaticRebootManager() override;

  AutomaticRebootManagerObserver::Reason reboot_reason() const {
    return reboot_reason_;
  }
  bool reboot_requested() const { return reboot_requested_; }

  void AddObserver(AutomaticRebootManagerObserver* observer);
  void RemoveObserver(AutomaticRebootManagerObserver* observer);

  // PowerManagerClient::Observer:
  void SuspendDone(const base::TimeDelta& sleep_duration) override;

  // UpdateEngineClient::Observer:
  void UpdateStatusChanged(const UpdateEngineClient::Status& status) override;

  // ui::UserActivityObserver:
  void OnUserActivity(const ui::Event* event) override;

  // content::NotificationObserver:
  void Observe(int type,
               const content::NotificationSource& source,
               const content::NotificationDetails& details) override;

  static void RegisterPrefs(PrefRegistrySimple* registry);

 private:
  friend class AutomaticRebootManagerBasicTest;

  // Finishes initialization. Called after the |system_event_times| have been
  // loaded in the blocking thread pool.
  void Init(const SystemEventTimes& system_event_times);

  // Reschedules the reboot request, start and end of the grace period. Reboots
  // immediately if the end of the grace period has already passed.
  void Reschedule();

  // Requests a reboot.
  void RequestReboot();

  // Called whenever the status of the criteria inhibiting reboots may have
  // changed. Reboots immediately if a reboot has actually been requested and
  // none of the criteria inhibiting it apply anymore. Otherwise, does nothing.
  // If |ignore_session|, a session in progress does not inhibit reboots.
  void MaybeReboot(bool ignore_session);

  // Reboots immediately.
  void Reboot();

  // A clock that can be mocked in tests to fast-forward time.
  scoped_ptr<base::TickClock> clock_;

  PrefChangeRegistrar local_state_registrar_;

  content::NotificationRegistrar notification_registrar_;

  // Fires when the user has been idle on the login screen for a set amount of
  // time.
  scoped_ptr<base::OneShotTimer<AutomaticRebootManager> >
      login_screen_idle_timer_;

  // The time at which the device was booted, in |clock_| ticks.
  bool have_boot_time_;
  base::TimeTicks boot_time_;

  // The time at which an update was applied and a reboot became necessary to
  // complete the update process, in |clock_| ticks.
  bool have_update_reboot_needed_time_;
  base::TimeTicks update_reboot_needed_time_;

  // The reason for the reboot request. Updated whenever a reboot is scheduled.
  AutomaticRebootManagerObserver::Reason reboot_reason_;

  // Whether a reboot has been requested.
  bool reboot_requested_;

  // Timers that start and end the grace period.
  scoped_ptr<base::OneShotTimer<AutomaticRebootManager> > grace_start_timer_;
  scoped_ptr<base::OneShotTimer<AutomaticRebootManager> > grace_end_timer_;

  base::ObserverList<AutomaticRebootManagerObserver, true> observers_;

  base::WeakPtrFactory<AutomaticRebootManager> weak_ptr_factory_;

  DISALLOW_COPY_AND_ASSIGN(AutomaticRebootManager);
};

}  // namespace system
}  // namespace chromeos

#endif  // CHROME_BROWSER_CHROMEOS_SYSTEM_AUTOMATIC_REBOOT_MANAGER_H_


text:
package city.restaurant.tanner;

import java.awt.Point;

import city.restaurant.tanner.interfaces.TannerRestaurantCustomer;

public class Table
{
	Point position;
	int tableNumber;
	public TannerRestaurantCustomer occupant;

	public Table(int tn, int xPos, int yPos)
	{
		position = new Point(xPos,yPos);
		tableNumber = tn;
		occupant = null;
		TannerRestaurant.tableMap.put(tn, this);
	}

	//Getters
	public Point getPosition()
	{
		return position;
	}
}


text:
package com.github.nithril;

/**
 * Created by nlabrot on 19/05/15.
 */
public class Holder {
    public static final int NB = 16384-1;
    public static WrappedPackedObject packedObject = new WrappedPackedObject(new int[NB]);

    public static int value = 1;

    public static int get(){
        return (value++)&NB;
    }

}


text:
#include <nccl.h>
#include <stdint.h>
#include <ostream>
#include <string>

#include "paddle/fluid/framework/executor.h"
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/threadpool.h"
#include "paddle/fluid/operators/detail/grpc_client.h"
#include "paddle/fluid/operators/detail/grpc_server.h"
#include "paddle/fluid/platform/nccl_helper.h"

namespace paddle {
namespace operators {

class GenNCCLIdOp : public framework::OperatorBase {
 public:
  GenNCCLIdOp(const std::string& type, const framework::VariableNameMap& inputs,
              const framework::VariableNameMap& outputs,
              const framework::AttributeMap& attrs)
      : OperatorBase(type, inputs, outputs, attrs) {}

  void RunImpl(const framework::Scope& scope,
               const platform::Place& dev_place) const override {
    platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance();
    // put nccl id in CPUPlace
    auto& dev_ctx = *pool.Get(platform::CPUPlace());
    int trainer_id = Attr<int>("trainer_id");
    framework::Scope& local_scope = scope.NewScope();

    if (trainer_id == 0) {
      GenerateAndSend(&local_scope, dev_ctx);
    } else {
      GetIdByServer(&local_scope, dev_ctx);
    }
  }

 private:
  void GenerateAndSend(framework::Scope* scope,
                       const platform::DeviceContext& dev_ctx) const {
    auto var = scope->FindVar(NCCL_ID_VARNAME);
    PADDLE_ENFORCE_NOT_NULL(var);
    auto id = var->GetMutable<ncclUniqueId>();
    PADDLE_ENFORCE(platform::dynload::ncclGetUniqueId(id));

    std::vector<std::string> endpoint_list =
        Attr<std::vector<std::string>>("endpoint_list");
    detail::RPCClient client;
    for (auto& ep : endpoint_list) {
      VLOG(3) << "sending nccl id to " << ep;
      client.AsyncSendVariable(ep, dev_ctx, *scope, NCCL_ID_VARNAME);
    }
    client.Wait();
    VLOG(3) << "sending completed...";
  }

  void GetIdByServer(framework::Scope* scope,
                     const platform::DeviceContext& dev_ctx) const {
    std::string endpoint = Attr<std::string>("endpoint");
    // NOTE: Can not use unique_ptr here because the default
    // deleter will call GRPC Server's base class's dtor and
    // that will cause a wired crash.
    detail::AsyncGRPCServer rpc_service(endpoint, true);
    framework::ProgramDesc empty_program;
    framework::Executor executor(dev_ctx.GetPlace());
    rpc_service.SetScope(scope);
    rpc_service.SetDevCtx(&dev_ctx);
    rpc_service.SetProgram(&empty_program);
    rpc_service.SetExecutor(&executor);

    std::thread server_thread(
        std::bind(&detail::AsyncGRPCServer::RunSyncUpdate, &rpc_service));
    rpc_service.SetCond(0);
    VLOG(3) << "start getting nccl id from trainer 0...";
    auto recv = rpc_service.Get();
    VLOG(3) << "got nccl id and stop server...";
    rpc_service.ShutDown();
    VLOG(3) << "rpc server stopped";
    server_thread.join();
  }
};

class GenNCCLIdOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddOutput("NCCLID", "Raw variable contains a NCCL UniqueId instaces.");
    AddComment(R"DOC(
GenNCCLId operator

For trainer 0: generate a new UniqueId and send it to all the other trainers.
For trainer 1~n: start a gRPC server to get the UniqueId, once got, stop the server.
)DOC");
    AddAttr<std::string>("endpoint",
                         "(string), e.g. 127.0.0.1:6175 "
                         "current listen endpoint");
    AddAttr<std::vector<std::string>>(
        "endpoint_list",
        "['trainer1_ip:port', 'trainer2_ip:port', ...] "
        "list of trainer endpoints start from trainer 1")
        .SetDefault({});
    AddAttr<int>("trainer_id",
                 "(int default 0) "
                 "The index of the trainer in distributed training.")
        .SetDefault(0);
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OPERATOR(gen_nccl_id, ops::GenNCCLIdOp, ops::GenNCCLIdOpMaker);


text:
package org.kuali.kra.institutionalproposal.home;

import org.kuali.coeus.sys.framework.model.KcPersistableBusinessObjectBase;

import java.sql.Date;

public class InstitutionalProposalLog extends KcPersistableBusinessObjectBase {

    private static final long serialVersionUID = 1L;

    private String proposalNumber;

    private Integer proposalTypeCode;

    private String title;

    private String piId;

    private String piName;

    private boolean nonMitPersonFlag;

    private String leadUnit;

    private String sponsorCode;

    private String sponsorName;

    private boolean logStatus;

    private String comments;

    private Date deadlineDate;

    public InstitutionalProposalLog() {
    }

    public String getProposalNumber() {
        return proposalNumber;
    }

    public void setProposalNumber(String proposalNumber) {
        this.proposalNumber = proposalNumber;
    }

    public Integer getProposalTypeCode() {
        return proposalTypeCode;
    }

    public void setProposalTypeCode(Integer proposalTypeCode) {
        this.proposalTypeCode = proposalTypeCode;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPiId() {
        return piId;
    }

    public void setPiId(String piId) {
        this.piId = piId;
    }

    public String getPiName() {
        return piName;
    }

    public void setPiName(String piName) {
        this.piName = piName;
    }

    public boolean getNonMitPersonFlag() {
        return nonMitPersonFlag;
    }

    public void setNonMitPersonFlag(boolean nonMitPersonFlag) {
        this.nonMitPersonFlag = nonMitPersonFlag;
    }

    public String getLeadUnit() {
        return leadUnit;
    }

    public void setLeadUnit(String leadUnit) {
        this.leadUnit = leadUnit;
    }

    public String getSponsorCode() {
        return sponsorCode;
    }

    public void setSponsorCode(String sponsorCode) {
        this.sponsorCode = sponsorCode;
    }

    public String getSponsorName() {
        return sponsorName;
    }

    public void setSponsorName(String sponsorName) {
        this.sponsorName = sponsorName;
    }

    public boolean getLogStatus() {
        return logStatus;
    }

    public void setLogStatus(boolean logStatus) {
        this.logStatus = logStatus;
    }

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }

    public Date getDeadlineDate() {
        return deadlineDate;
    }

    public void setDeadlineDate(Date deadlineDate) {
        this.deadlineDate = deadlineDate;
    }
}


text:
prec=4

read_state () {
	onto_name=$(cat "$state_dir"/onto_name) &&
	end=$(cat "$state_dir"/end) &&
	msgnum=$(cat "$state_dir"/msgnum)
}

continue_merge () {
	test -d "$state_dir" || die "$state_dir directory does not exist"

	unmerged=$(git ls-files -u)
	if test -n "$unmerged"
	then
		echo "You still have unmerged paths in your index"
		echo "did you forget to use git add?"
		die "$resolvemsg"
	fi

	cmt=$(cat "$state_dir/current")
	if ! git diff-index --quiet --ignore-submodules HEAD --
	then
		if ! git commit ${gpg_sign_opt:+"$gpg_sign_opt"} --no-verify -C "$cmt"
		then
			echo "Commit failed, please do not call \"git commit\""
			echo "directly, but instead do one of the following: "
			die "$resolvemsg"
		fi
		if test -z "$GIT_QUIET"
		then
			printf "Committed: %0${prec}d " $msgnum
		fi
		echo "$cmt $(git rev-parse HEAD^0)" >> "$state_dir/rewritten"
	else
		if test -z "$GIT_QUIET"
		then
			printf "Already applied: %0${prec}d " $msgnum
		fi
	fi
	test -z "$GIT_QUIET" &&
	GIT_PAGER='' git log --format=%s -1 "$cmt"

	# onto the next patch:
	msgnum=$(($msgnum + 1))
	echo "$msgnum" >"$state_dir/msgnum"
}

call_merge () {
	msgnum="$1"
	echo "$msgnum" >"$state_dir/msgnum"
	cmt="$(cat "$state_dir/cmt.$msgnum")"
	echo "$cmt" > "$state_dir/current"
	hd=$(git rev-parse --verify HEAD)
	cmt_name=$(git symbolic-ref HEAD 2> /dev/null || echo HEAD)
	eval GITHEAD_$cmt='"${cmt_name##refs/heads/}~$(($end - $msgnum))"'
	eval GITHEAD_$hd='$onto_name'
	export GITHEAD_$cmt GITHEAD_$hd
	if test -n "$GIT_QUIET"
	then
		GIT_MERGE_VERBOSITY=1 && export GIT_MERGE_VERBOSITY
	fi
	test -z "$strategy" && strategy=recursive
	# If cmt doesn't have a parent, don't include it as a base
	base=$(git rev-parse --verify --quiet $cmt^)
	eval 'git-merge-$strategy' $strategy_opts $base ' -- "$hd" "$cmt"'
	rv=$?
	case "$rv" in
	0)
		unset GITHEAD_$cmt GITHEAD_$hd
		return
		;;
	1)
		git rerere $allow_rerere_autoupdate
		die "$resolvemsg"
		;;
	2)
		echo "Strategy: $strategy failed, try another" 1>&2
		die "$resolvemsg"
		;;
	*)
		die "Unknown exit code ($rv) from command:" \
			"git-merge-$strategy $cmt^ -- HEAD $cmt"
		;;
	esac
}

finish_rb_merge () {
	move_to_original_branch
	if test -s "$state_dir"/rewritten
	then
		git notes copy --for-rewrite=rebase <"$state_dir"/rewritten
		hook="$(git rev-parse --git-path hooks/post-rewrite)"
		test -x "$hook" && "$hook" rebase <"$state_dir"/rewritten
	fi
	say All done.
}

# The whole contents of this file is run by dot-sourcing it from
# inside a shell function.  It used to be that "return"s we see
# below were not inside any function, and expected to return
# to the function that dot-sourced us.
#
# However, older (9.x) versions of FreeBSD /bin/sh misbehave on such a
# construct and continue to run the statements that follow such a "return".
# As a work-around, we introduce an extra layer of a function
# here, and immediately call it after defining it.
git_rebase__merge () {

case "$action" in
continue)
	read_state
	continue_merge
	while test "$msgnum" -le "$end"
	do
		call_merge "$msgnum"
		continue_merge
	done
	finish_rb_merge
	return
	;;
skip)
	read_state
	git rerere clear
	msgnum=$(($msgnum + 1))
	while test "$msgnum" -le "$end"
	do
		call_merge "$msgnum"
		continue_merge
	done
	finish_rb_merge
	return
	;;
esac

mkdir -p "$state_dir"
echo "$onto_name" > "$state_dir/onto_name"
write_basic_state

msgnum=0
for cmt in $(git rev-list --reverse --no-merges "$revisions")
do
	msgnum=$(($msgnum + 1))
	echo "$cmt" > "$state_dir/cmt.$msgnum"
done

echo 1 >"$state_dir/msgnum"
echo $msgnum >"$state_dir/end"

end=$msgnum
msgnum=1

while test "$msgnum" -le "$end"
do
	call_merge "$msgnum"
	continue_merge
done

finish_rb_merge

}
# ... and then we call the whole thing.
git_rebase__merge


text:
import * as _ from "lodash";
import {Form} from "@enhavo/vue-form/model/Form";
import {Theme} from "@enhavo/vue-form/form/Theme";
import {FormVisitorInterface} from "@enhavo/vue-form/form/FormVisitor";
import {RootForm} from "@enhavo/vue-form/model/RootForm";

export class FormFactory
{
    private visitors: Array<FormVisitorInterface> = [];

    public create(data: object, visitors: FormVisitorInterface|Array<FormVisitorInterface>|Theme = null, parent: Form = null)
    {
        let form = parent === null ? new RootForm() : new Form();

        form = _.extend(form, data);
        form.parent = parent;

        for (let key in form.children) {
            form.children[key] = this.createFormData(form.children[key]);
            form.children[key].parent = form;
        }

        let applyVisitors = [];
        for (let visitor of this.visitors) {
            if (applyVisitors.indexOf(visitor) === -1) {
                applyVisitors.push(visitor);
            }
        }

        if (visitors) {
            if (visitors instanceof Theme) {
                visitors = visitors.getVisitors();
            }

            for (let visitor of this.getVisitors(visitors)) {
                if (applyVisitors.indexOf(visitor) === -1) {
                    applyVisitors.push(visitor);
                }
            }
        }

        applyVisitors = applyVisitors.sort((a: FormVisitorInterface, b: FormVisitorInterface) => {
            return b.getPriority() - a.getPriority();
        })

        form = this.applyVisitors(form, applyVisitors);

        let root =  <RootForm>form.getRoot();
        for (let applyVisitor of applyVisitors) {
            if (root.visitors.indexOf(applyVisitor) == -1) {
                root.visitors.push(applyVisitor);
            }
        }

        return form;
    }

    private createFormData(form: Form)
    {
        form = _.assign(new Form(), form);
        for (let key in form.children) {
            form.children[key] = this.createFormData(form.children[key]);
            form.children[key].parent = form;
        }
        return form;
    }

    public addVisitor(visitor: FormVisitorInterface)
    {
        this.visitors.push(visitor);
    }

    public addVisitors(visitors: Array<FormVisitorInterface>)
    {
        for (let visitor of visitors) {
            this.addVisitor(visitor);
        }
    }

    public addTheme(theme: Theme)
    {
        this.addVisitors(theme.getVisitors());
    }

    private getVisitors(visitors: FormVisitorInterface|Array<FormVisitorInterface> = null): Array<FormVisitorInterface>
    {
        let applyVisitors = [];

        if (Array.isArray(visitors)) {
            for (let visitor of visitors) {
                applyVisitors.push(visitor);
            }
        } else {
            applyVisitors.push(visitors);
        }

        return applyVisitors;
    }

    private applyVisitors(form: Form, visitors: Array<FormVisitorInterface>): Form
    {
        form = this.updateComponent(form, visitors);
        for (let key in form.children) {
            form.children[key] = this.applyVisitors(form.children[key], visitors);
        }
        return form;
    }

    private updateComponent(form: Form, visitors: Array<FormVisitorInterface>): Form
    {
        let applicableVisitors = [];
        for (let visitor of visitors) {
            if (visitor.supports(form)) {
                applicableVisitors.push(visitor);
            }
        }

        for (let applicableVisitor of applicableVisitors) {
            let returnForm = applicableVisitor.apply(form);
            if (returnForm) {
                form = returnForm;
            }
        }

        return form;
    }
}


text:
<?php
namespace Neos\FluidAdaptor\Core\Widget;

use Neos\Flow\Http\Response;
use Neos\Flow\Mvc\ActionRequest;
use Neos\Flow\Mvc\Exception\ForwardException;
use Neos\Flow\Mvc\Exception\InfiniteLoopException;
use Neos\Flow\Mvc\Exception\StopActionException;
use Neos\Flow\ObjectManagement\DependencyInjection\DependencyProxy;
use Neos\FluidAdaptor\Core\ViewHelper\AbstractViewHelper;
use Neos\FluidAdaptor\Core\ViewHelper\Facets\ChildNodeAccessInterface;
use TYPO3Fluid\Fluid\Core\Compiler\TemplateCompiler;
use TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\RootNode;
use TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\ViewHelperNode;

/**
 * @api
 */
abstract class AbstractWidgetViewHelper extends AbstractViewHelper implements ChildNodeAccessInterface
{
    /**
     * @var boolean
     */
    protected $escapeOutput = false;

    /**
     * The Controller associated to this widget.
     * This needs to be filled by the individual subclass using
     * property injection.
     *
     * @var AbstractWidgetController
     * @api
     */
    protected $controller;

    /**
     * If set to TRUE, it is an AJAX widget.
     *
     * @var boolean
     * @api
     */
    protected $ajaxWidget = false;

    /**
     * If set to FALSE, this widget won't create a session (only relevant for AJAX widgets).
     *
     * You then need to manually add the serialized configuration data to your links, by
     * setting "includeWidgetContext" to TRUE in the widget link and URI ViewHelpers.
     *
     * @var boolean
     * @api
     */
    protected $storeConfigurationInSession = true;

    /**
     * @var AjaxWidgetContextHolder
     */
    private $ajaxWidgetContextHolder;

    /**
     * @var WidgetContext
     */
    private $widgetContext;

    /**
     * @param AjaxWidgetContextHolder $ajaxWidgetContextHolder
     * @return void
     */
    public function injectAjaxWidgetContextHolder(AjaxWidgetContextHolder $ajaxWidgetContextHolder)
    {
        $this->ajaxWidgetContextHolder = $ajaxWidgetContextHolder;
    }

    /**
     * @param WidgetContext $widgetContext
     * @return void
     */
    public function injectWidgetContext(WidgetContext $widgetContext)
    {
        $this->widgetContext = $widgetContext;
    }

    /**
     * Registers the widgetId viewhelper
     *
     * @return void
     */
    public function initializeArguments()
    {
        $this->registerArgument('widgetId', 'string', 'Unique identifier of the widget instance');
    }

    /**
     * Initialize the arguments of the ViewHelper, and call the render() method of the ViewHelper.
     *
     * @return string the rendered ViewHelper.
     */
    public function initializeArgumentsAndRender()
    {
        $this->validateArguments();
        $this->initialize();
        $this->initializeWidgetContext();

        return $this->callRenderMethod();
    }

    /**
     * Initialize the Widget Context, before the Render method is called.
     *
     * @return void
     */
    private function initializeWidgetContext()
    {
        if ($this->ajaxWidget === true) {
            if ($this->storeConfigurationInSession === true) {
                $this->ajaxWidgetContextHolder->store($this->widgetContext);
            }
            $this->widgetContext->setAjaxWidgetConfiguration($this->getAjaxWidgetConfiguration());
        }

        $this->widgetContext->setNonAjaxWidgetConfiguration($this->getNonAjaxWidgetConfiguration());
        $this->initializeWidgetIdentifier();

        $controllerObjectName = ($this->controller instanceof DependencyProxy) ? $this->controller->_getClassName() : get_class($this->controller);
        $this->widgetContext->setControllerObjectName($controllerObjectName);
    }

    /**
     * Stores the syntax tree child nodes in the Widget Context, so they can be
     * rendered with <f:widget.renderChildren> lateron.
     *
     * @param array $childNodes The SyntaxTree Child nodes of this ViewHelper.
     * @return void
     */
    public function setChildNodes(array $childNodes)
    {
        $rootNode = new RootNode();

        foreach ($childNodes as $childNode) {
            $rootNode->addChildNode($childNode);
        }
        $this->widgetContext->setViewHelperChildNodes($rootNode, $this->renderingContext);
    }

    /**
     * Generate the configuration for this widget. Override to adjust.
     *
     * @return array
     * @api
     */
    protected function getWidgetConfiguration()
    {
        return $this->arguments;
    }

    /**
     * Generate the configuration for this widget in AJAX context.
     *
     * By default, returns getWidgetConfiguration(). Should become API later.
     *
     * @return array
     */
    protected function getAjaxWidgetConfiguration()
    {
        return $this->getWidgetConfiguration();
    }

    /**
     * Generate the configuration for this widget in non-AJAX context.
     *
     * By default, returns getWidgetConfiguration(). Should become API later.
     *
     * @return array
     */
    protected function getNonAjaxWidgetConfiguration()
    {
        return $this->getWidgetConfiguration();
    }

    /**
     * Initiate a sub request to $this->controller. Make sure to fill $this->controller
     * via Dependency Injection.
     * @return Response the response of this request.
     * @throws Exception\InvalidControllerException
     * @throws Exception\MissingControllerException
     * @throws InfiniteLoopException
     * @throws StopActionException
     * @api
     */
    protected function initiateSubRequest()
    {
        if ($this->controller instanceof DependencyProxy) {
            $this->controller->_activateDependency();
        }
        if (!($this->controller instanceof AbstractWidgetController)) {
            throw new Exception\MissingControllerException('initiateSubRequest() can not be called if there is no controller inside $this->controller. Make sure to add the @Neos\Flow\Annotations\Inject annotation in your widget class.', 1284401632);
        }

        /** @var $subRequest ActionRequest */
        $subRequest = $this->objectManager->get(ActionRequest::class, $this->controllerContext->getRequest());
        /** @var $subResponse Response */
        $subResponse = $this->objectManager->get(Response::class, $this->controllerContext->getResponse());

        $this->passArgumentsToSubRequest($subRequest);
        $subRequest->setArgument('__widgetContext', $this->widgetContext);
        $subRequest->setArgumentNamespace('--' . $this->widgetContext->getWidgetIdentifier());

        $dispatchLoopCount = 0;
        while (!$subRequest->isDispatched()) {
            if ($dispatchLoopCount++ > 99) {
                throw new InfiniteLoopException('Could not ultimately dispatch the widget request after '  . $dispatchLoopCount . ' iterations.', 1380282310);
            }
            $widgetControllerObjectName = $this->widgetContext->getControllerObjectName();
            if ($subRequest->getControllerObjectName() !== '' && $subRequest->getControllerObjectName() !== $widgetControllerObjectName) {
                throw new Exception\InvalidControllerException(sprintf('You are not allowed to initiate requests to different controllers from a widget.' . chr(10) . 'widget controller: "%s", requested controller: "%s".', $widgetControllerObjectName, $subRequest->getControllerObjectName()), 1380284579);
            }
            $subRequest->setControllerObjectName($this->widgetContext->getControllerObjectName());
            try {
                $this->controller->processRequest($subRequest, $subResponse);
            } catch (StopActionException $exception) {
                if ($exception instanceof ForwardException) {
                    $subRequest = $exception->getNextRequest();
                    continue;
                }
                /** @var $parentResponse Response */
                $parentResponse = $this->controllerContext->getResponse();
                $parentResponse
                    ->setStatus($subResponse->getStatusCode())
                    ->setContent($subResponse->getContent())
                    ->setHeader('Location', $subResponse->getHeader('Location'));
                throw $exception;
            }
        }
        return $subResponse;
    }

    /**
     * Pass the arguments of the widget to the sub request.
     *
     * @param ActionRequest $subRequest
     * @return void
     */
    private function passArgumentsToSubRequest(ActionRequest $subRequest)
    {
        $arguments = $this->controllerContext->getRequest()->getPluginArguments();
        $widgetIdentifier = $this->widgetContext->getWidgetIdentifier();

        $controllerActionName = 'index';
        if (isset($arguments[$widgetIdentifier])) {
            if (isset($arguments[$widgetIdentifier]['@action'])) {
                $controllerActionName = $arguments[$widgetIdentifier]['@action'];
                unset($arguments[$widgetIdentifier]['@action']);
            }
            $subRequest->setArguments($arguments[$widgetIdentifier]);
        }
        if ($subRequest->getControllerActionName() === null) {
            $subRequest->setControllerActionName($controllerActionName);
        }
    }

    /**
     * The widget identifier is unique on the current page, and is used
     * in the URI as a namespace for the widget's arguments.
     *
     * @return string the widget identifier for this widget
     * @return void
     */
    private function initializeWidgetIdentifier()
    {
        $widgetIdentifier = ($this->hasArgument('widgetId') ? $this->arguments['widgetId'] : strtolower(str_replace('\\', '-', get_class($this))));
        $this->widgetContext->setWidgetIdentifier($widgetIdentifier);
    }

    /**
     * Resets the ViewHelper state by creating a fresh WidgetContext
     *
     * @return void
     */
    public function resetState()
    {
        if ($this->ajaxWidget) {
            $this->widgetContext = $this->objectManager->get(WidgetContext::class);
        }
    }

    /**
     * @param string $argumentsName
     * @param string $closureName
     * @param string $initializationPhpCode
     * @param ViewHelperNode $node
     * @param TemplateCompiler $compiler
     * @return string
     */
    public function compile($argumentsName, $closureName, &$initializationPhpCode, ViewHelperNode $node, TemplateCompiler $compiler)
    {
        $compiler->disable();
        return "''";
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Hierarchy Module Test Suite</title>

  <link rel="stylesheet" href="../libs/qunit/qunit.css" media="screen">

<select id='alpha'>
  <option value="">--Select--</option>
  <option value="10">ade</option>
  <option value="11">amp</option>
  <option value="12">ark</option>
</select>

<select id='bravo'>
  <option value="">--Select--</option>
  <option value="20">bee</option>
  <option value="21">bit</option>
  <option value="22">bun</option>
</select>

<select id='charlie'>
  <option value="">--Select--</option>
  <option value="30">can</option>
  <option value="31">cry</option>
  <option value="32">cut</option>
</select>

<select id='delta'>
  <option value="">--Select--</option>
  <option value="40">dot</option>
  <option value="41">dry</option>
  <option value="42">dub</option>
</select>


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.messagebus;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * A session which supports receiving, forwarding and acknowledging messages. An intermediate session is expected
 * to either forward or acknowledge every message received.
 *
 * @author Simon Thoresen Hult
 */
public final class IntermediateSession implements MessageHandler, ReplyHandler, Connectable {

    private final AtomicBoolean destroyed = new AtomicBoolean(false);
    private final String name;
    private final boolean broadcastName;
    private final MessageHandler msgHandler;
    private final ReplyHandler replyHandler;
    private final MessageBus mbus;

    /**
     * This constructor is declared package private since only MessageBus is supposed to instantiate it.
     *
     * @param mbus   The message bus that created this instance.
     * @param params The parameter object for this session.
     */
    IntermediateSession(MessageBus mbus, IntermediateSessionParams params) {
        this.mbus = mbus;
        this.name = params.getName();
        this.broadcastName = params.getBroadcastName();
        this.msgHandler = params.getMessageHandler();
        this.replyHandler= params.getReplyHandler();
    }

    /**
     * Sets the destroyed flag to true. The very first time this method is called, it cleans up all its dependencies.
     * Even if you retain a reference to this object, all of its content is allowed to be garbage collected.
     *
     * @return true if content existed and was destroyed
     */
    public boolean destroy() {
        if (!destroyed.getAndSet(true)) {
            close();
            return true;
        }
        return false;
    }

    /**
     * This method unregisters this session from message bus, effectively disabling any more messages from being
     * delivered to the message handler. After unregistering, this method calls {@link com.yahoo.messagebus.MessageBus#sync()}
     * to ensure that there are no threads currently entangled in the handler.
     *
     * This method will deadlock if you call it from the message or reply handler.
     */
    public void close() {
        mbus.unregisterSession(name, broadcastName);
        mbus.sync();
    }

    /**
     * Forwards a routable to the next hop in its route. This method will never block.
     * @param routable the routable to forward.
     */
    public void forward(Routable routable) {
        if (routable instanceof Reply) {
            Reply reply = (Reply)routable;
            ReplyHandler handler = reply.popHandler();
            handler.handleReply(reply);
        } else {
            routable.pushHandler(this);
            mbus.handleMessage((Message)routable);
        }
    }

    /** Returns the message handler of this session */
    public MessageHandler getMessageHandler() {
        return msgHandler;
    }

    /**
     * Returns the reply handler of this session.
     *
     * @return The reply handler.
     */
    public ReplyHandler getReplyHandler() {
        return replyHandler;
    }

    /**
     * Returns the connection spec string for this session. This returns a combination of the owning message bus' own
     * spec string and the name of this session.
     */
    public String getConnectionSpec() {
        return mbus.getConnectionSpec() + "/" + name;
    }

    /** Returns the name of this session */
    public String getName() {
        return name;
    }

    @Override
    public void handleMessage(Message msg) {
        msgHandler.handleMessage(msg);
    }

    @Override
    public void handleReply(Reply reply) {
        if (destroyed.get()) {
            reply.discard();
        } else {
            replyHandler.handleReply(reply);
        }
    }

    @Override
    public void connect() {
        mbus.connect(name, broadcastName);
    }

    @Override public void disconnect() { close(); }

}


text:
function q = rop_f(a)
% ROP_F  Forward rates of progress for all reactions.
% q = rop_f(a)
%
%    See also: :mat:func:`rop_r`, :mat:func:`rop_net`, :mat:func:`rop`
%
% :param a:
%     Instance of class :mat:func:`Kinetics` (or another
%     object deriving from Kinetics)
%     for which forward rates of progress are desired.
% :return:
%     Returns a column vector of the forward rates of progress
%     for all reactions. If this function
%     is called with no output argument, a bar graph is produced.
%

q = kinetics_get(a.id, 11, 0);
if nargout == 0
    figure
    set(gcf, 'Name', 'Rates of Progress')
    bar(q)
    xlabel('Reaction Number')
    ylabel('Forward Rate of Progress [kmol/m^3]')
    title('Forward Rates of Progress')
end


text:
int main(void)
{
    size_t failedTestCount = 0;
    RUN_TEST_SUITE(iothub_ut, failedTestCount);
    return failedTestCount;
}


text:
require 'furnish/provisioners/api'
require 'furnish/ip'
require 'set'

module Furnish # :nodoc:
  module Provisioner # :nodoc:
    #
    # The AutoIP provisioner is used to create IP addresses for other systems
    # that allow them as direct input, such as VirtualBox VMs. The expectation
    # is that this will be chained to another provisioner who would accept it
    # as input during startup.
    #
    class AutoIP < API
      ##
      # :attr: ip
      #
      # A Furnish::IP registry object. If a subnet is not assigned to this
      # object (see Furnish::IP#new), ArgumentError will be raised when
      # attempting to generate IP addresses.
      #
      furnish_property :ip, "A Furnish::IP registry object", Furnish::IP

      ##
      # :attr: number_of_addresses
      #
      # An integer value specifying the number of addresses to allocate at
      # provisioning time.
      #
      furnish_property :number_of_addresses, "An integer indicating the number of addresses to generate", Integer

      configure_startup do
        accepts_from_any true
        yields :ips, "Set of strings of recorded IP addresses", Set
      end

      configure_shutdown do
        accepts_from_any true
      end

      ##
      # Create the provisioner, requires :ip be passed and referring to a
      # Furnish::IP object with subnet semantics (see Furnish::IP#new), and
      # :number_of_addresses can also be supplied or will default to 1.
      def initialize(args)
        super

        unless ip
          raise ArgumentError, "A Furnish::IP object must be provided"
        end

        unless ip.subnet
          raise ArgumentError, "The Furnish::IP object must have a subnet associated"
        end

        @number_of_addresses ||= 1
      end

      ##
      # Allocate addresses and forward them on to the next provisioner. Uses
      # the provisioner group name as the key for the address set. Fills key
      # :ips with a Set of IP addresses.
      def startup(args={})
        @controlled_ips = Set.new

        number_of_addresses.times do
          this_ip = ip.unused_ip(furnish_group_name)
          @controlled_ips.add(this_ip)
        end

        return({ :ips => ip.group_items(furnish_group_name) })
      end

      ##
      # Release the IP addresses back to the allocator. Only releases the IPs
      # that were allocated by this specific provisioner. Destroys the group if
      # it's empty after releasing.
      #
      def shutdown(args={ })
        if @controlled_ips
          ip.remove_from_group(furnish_group_name, @controlled_ips)
        end

        if ip.group_items(furnish_group_name).empty?
          ip.decommission_group(furnish_group_name)
        end

        return { }
      end

      ##
      # Display the allocated addresses for this group.
      def report
        ip.group_items(furnish_group_name).to_a rescue []
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="net.sourceforge.servestream"
	android:versionName="0.6.2"
	android:versionCode="74"
	android:installLocation="auto">

	<uses-sdk
	    android:targetSdkVersion="17"
	    android:minSdkVersion="8" />

	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
	<uses-permission android:name="android.permission.INTERNET" />
	<uses-permission android:name="android.permission.READ_PHONE_STATE" />
	<uses-permission android:name="android.permission.VIBRATE"/>
	<uses-permission android:name="android.permission.WAKE_LOCK" />
	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
	<uses-permission android:name="android.permission.BROADCAST_STICKY" />

	<application
		android:icon="@drawable/ic_launcher"
		android:label="@string/app_name"
		android:allowBackup="true"
		android:backupAgent=".service.BackupAgent"
		android:killAfterRestore="true"
		android:theme="@style/Theme.ServeStream.Dark" >

		<meta-data
		    android:name="com.google.android.backup.api_key"
    		android:value="AEdPqrEAAAAIWcqt9c_ET5W0EpBB9ZCQGbBhfrOetXL6t6Cdwg" />

        <provider
            android:name=".provider.MediaProvider"
            android:authorities="net.sourceforge.servestream.provider.Media"
            android:exported="false" />

        <provider
            android:name=".alarm.AlarmProvider"
            android:authorities="net.sourceforge.servestream"
            android:exported="false" />

		<activity
		    android:name=".activity.MainActivity"
		    android:launchMode="singleTop" >
			<intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
			<intent-filter>
  				<action android:name="android.intent.action.SEND" />
  				<category android:name="android.intent.category.DEFAULT" />
  				<data android:mimeType="text/plain" />
			</intent-filter>
			<intent-filter>
				<action android:name="android.intent.action.VIEW" />
				<category android:name="android.intent.category.BROWSABLE" />
				<category android:name="android.intent.category.DEFAULT" />
				<data android:mimeType="net.sourceforge.servestream/*" />
			</intent-filter>
			<intent-filter>
				<action android:name="android.intent.action.VIEW" />
				<category android:name="android.intent.category.BROWSABLE" />
				<category android:name="android.intent.category.DEFAULT" />
				<data android:scheme="http" />
				<data android:host="*" />
				<data android:mimeType="audio/*" />
				<data android:mimeType="video/*" />
				<data android:mimeType="audio/x-mpegurl" />
        		<data android:mimeType="audio/x-scpls" />
        		<data android:mimeType="video/x-ms-asf" />
			</intent-filter>
			<intent-filter>
				<action android:name="android.intent.action.VIEW" />
				<category android:name="android.intent.category.BROWSABLE" />
				<category android:name="android.intent.category.DEFAULT" />
				<data android:scheme="http" />
				<data android:host="*" />
				<data android:pathPattern=".*\\.m3u" />
				<data android:pathPattern=".*\\.pls" />
				<data android:pathPattern=".*\\.asx" />
			</intent-filter>
			<intent-filter>
        		<action android:name="android.intent.action.VIEW" />
        		<category android:name="android.intent.category.DEFAULT" />
        		<data android:scheme="file" />
        		<data android:mimeType="audio/x-mpegurl" />
        		<data android:mimeType="audio/x-scpls" />
        		<data android:mimeType="video/x-ms-asf" />
    		</intent-filter>
		</activity>

		<activity
            android:name=".activity.AboutActivity"
            android:label="@string/about_pref" >
        </activity>
		<activity
            android:name=".activity.AddUrlActivity"
            android:configChanges="keyboardHidden|orientation"
            android:label="@string/add_new_url_label"
            android:windowSoftInputMode="adjustResize" >
        </activity>
		<activity
		    android:name=".activity.NowPlayingActivity"
			android:label="@string/now_playing_label" >
		</activity>
		<activity
            android:name=".activity.OrganizeUrlsActivity"
            android:configChanges="orientation"
            android:label="@string/organize_urls_label" >
        </activity>
		<activity
            android:name=".activity.PreferenceActivity"
            android:configChanges="keyboardHidden|orientation"
            android:label="@string/settings_label" >
        </activity>
		<activity
		    android:name=".activity.ShortcutActivity" >
			<intent-filter>
				<action android:name="android.intent.action.CREATE_SHORTCUT" />
				<category android:name="android.intent.category.DEFAULT" />
			</intent-filter>
		</activity>
		<activity
		    android:name=".activity.StreamEditorActivity"
			android:configChanges="keyboardHidden|orientation" >
		</activity>

		<service
		    android:name=".service.MediaPlaybackService"
			android:description="@string/media_service_desc" />

        <activity
            android:name=".activity.MediaPlayerActivity"
            android:label="@string/media_player_label"
            android:launchMode="singleTop"
            android:exported="false" >
            <intent-filter>
                <action android:name="net.sourceforge.servestream.PLAYBACK_VIEWER" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <receiver
            android:name=".receiver.MediaButtonIntentReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.MEDIA_BUTTON" />
                <action android:name="android.media.AUDIO_BECOMING_NOISY" />
            </intent-filter>
        </receiver>

        <receiver
            android:name=".service.AppWidgetOneProvider" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>
            <meta-data android:name="android.appwidget.provider" android:resource="@xml/appwidget_one" />
        </receiver>

        <receiver
            android:name=".receiver.SimpleLastfmScrobblerReceiver"
            android:exported="false" >
            <intent-filter>
                <action android:name="net.sourceforge.servestream.playbackstarted" />
                <action android:name="net.sourceforge.servestream.playstatechanged" />
                <action android:name="net.sourceforge.servestream.playbackcomplete" />
                <action android:name="net.sourceforge.servestream.metachanged" />
            </intent-filter>
        </receiver>

        <receiver
            android:name=".receiver.ScrobbleDroidReceiver"
            android:exported="false" >
            <intent-filter>
                <action android:name="net.sourceforge.servestream.playbackstarted" />
                <action android:name="net.sourceforge.servestream.playstatechanged" />
                <action android:name="net.sourceforge.servestream.playbackcomplete" />
                <action android:name="net.sourceforge.servestream.metachanged" />
            </intent-filter>
        </receiver>

		<!-- Alarm Activities -->

        <activity android:name=".activity.AlarmClockActivity"
                android:label="@string/alarm_clock_label"
                android:taskAffinity=""
                android:excludeFromRecents="true"
                android:configChanges="orientation|keyboardHidden|keyboard|navigation"
                android:exported="false" />

        <activity
            android:name=".activity.SetAlarmActivity"
            android:label="@string/set_alarm_label"
            android:configChanges="orientation|keyboardHidden|keyboard|navigation" />

        <activity
            android:name=".alarm.AlarmAlert"
        	android:excludeFromRecents="true"
        	android:launchMode="singleInstance"
        	android:taskAffinity=""
       		android:configChanges="orientation|keyboardHidden|keyboard|navigation"/>

        <!-- This activity is basically the same as AlarmAlert but with a more
             generic theme. It also shows as full screen (with status bar) but
             with the wallpaper background. -->
        <activity
            android:name=".alarm.AlarmAlertFullScreen"
            android:excludeFromRecents="true"
            android:theme="@android:style/Theme.Wallpaper.NoTitleBar"
            android:launchMode="singleInstance"
            android:taskAffinity=""
            android:configChanges="orientation|keyboardHidden|keyboard|navigation" />

        <receiver
            android:name=".alarm.AlarmReceiver"
            android:exported="false" >
            <intent-filter>
                <action android:name="net.sourceforge.servestream.ALARM_ALERT" />
                <action android:name="net.sourceforge.servestream.ALARM_KILLED" />
                <action android:name="net.sourceforge.servestream.CANCEL_SNOOZE" />
            </intent-filter>
        </receiver>

        <!-- This service receives the same intent as AlarmReceiver but it does
             not respond to the same broadcast. The AlarmReceiver will receive
             the alert broadcast and will start this service with the same
             intent. The service plays the alarm alert and vibrates the device.
             This allows the alert to continue playing even if another activity
             causes the AlarmAlert activity to pause. -->
        <service
            android:name=".alarm.AlarmKlaxon"
			android:description="@string/alarm_klaxon_service_desc"
			android:exported="false" >
            <intent-filter>
                <action android:name="net.sourceforge.servestream.ALARM_ALERT" />
            </intent-filter>
        </service>

		<!-- End Alarm Activities -->

	</application>

</manifest>


text:
package activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import app.coolweather.com.coolweather.R;
import model.City;
import model.CoolWeatherDB;
import model.County;
import model.Province;
import util.HttpCallbackListener;
import util.HttpUtil;
import util.Utility;

/**
 * Created by Administrator on 2016/4/7.
 */
public class ChooseAreaActivity extends Activity {
    public static final int LEVEL_PROVINCE = 0;
    public static final int LEVEL_CITY = 1;
    public static final int LEVEL_COUNTY = 2;
    private ProgressDialog progressDialog;
    private TextView titleText;
    private ListView listView;
    private ArrayAdapter<String> adapter;
    private CoolWeatherDB coolWeatherDB;
    private List<String> dataList = new ArrayList<String>();
    /**
     * 省列表
     */
    private List<Province> provinceList;
    /**
     * 市列表
     */
    private List<City> cityList;
    /**
     * 县列表
     */
    private List<County> countyList;
    /**
     * 选中的省份
     */
    private Province selectedProvince;
    /**
     * 选中的城市
     */
    private City selectedCity;
    /**
     * 当前选中的级别
     */
    private int currentLevel;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.choose_area);
        listView = (ListView) findViewById(R.id.list_view);
        titleText = (TextView) findViewById(R.id.title_text);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList);
        listView.setAdapter(adapter);
        coolWeatherDB = CoolWeatherDB.getInstance(this);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int index, long arg3) {
                if (currentLevel == LEVEL_PROVINCE) {
                    selectedProvince = provinceList.get(index);
                    queryCities();
                } else if (currentLevel == LEVEL_CITY) {
                    selectedCity = cityList.get(index);
                    queryCounties();
                }
            }
        });
        queryProvinces();//加载省级数据
    }

    /**
     * 查询全国所有的省,优先从数据库中查询,如果没有查询到再去服务器上查询
     */
    private void queryProvinces() {
        provinceList = coolWeatherDB.loadProvinces();
        if (provinceList.size() > 0) {
            dataList.clear();
            for (Province province : provinceList) {
                dataList.add(province.getProvinceName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            titleText.setText("中国");
            currentLevel = LEVEL_PROVINCE;
        } else {
            queryFromServer(null, "province");
        }
    }

    /**
     * 查询选中省内所有的市。优先从数据库中查询,如果没有查询到再去服务器上查询
     */
    private void queryCities() {
        cityList = coolWeatherDB.loadCities(selectedProvince.getId());
        if (cityList.size() > 0) {
            dataList.clear();
            for (City city : cityList) {
                dataList.add(city.getCityName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            titleText.setText(selectedProvince.getProvinceName());
            currentLevel = LEVEL_CITY;
        } else {
            queryFromServer(selectedProvince.getProvinceCode(), "city");
        }
    }

    /**
     * 查询选中市内所有的县,优先从数据库中查询,如果没有查询到再去服务器上查询
     */
    private void queryCounties() {
        countyList = coolWeatherDB.loadCounties(selectedCity.getId());
        if (countyList.size() > 0) {
            dataList.clear();
            for (County county : countyList) {
                dataList.add(county.getCountyName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            titleText.setText(selectedCity.getCityName());
            currentLevel = LEVEL_COUNTY;
        } else {
            queryFromServer(selectedCity.getCityCode(), "county");
        }
    }

    /*
    根据传入的代号和类型从服务器上查询市县数据
     */
    private void queryFromServer(final String code, final String type) {
        String address;
        if (!TextUtils.isEmpty(code)) {
            address = "http://www.weather.com.cn/data/list3/city" + code + ".xml";
        } else {
            address = "http://www.weather.com.cn/data/list3/city.xml";
        }
        showProgressDialog();
        HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                boolean result = false;
                if ("province".equals(type)) {
                    result = Utility.handleProvincesResponse(coolWeatherDB,response);
                } else if ("city".equals(type)) {
                    result = Utility.handleCitiesResponse(coolWeatherDB, response, selectedProvince.getId());
                } else if ("county".equals(type)) {
                    result = Utility.handleCountiesResponse(coolWeatherDB, response, selectedCity.getId());
                }
                if (result) {
                    //通过runOnUiThread()方法回到主线程处理逻辑
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            closeProgressDialog();
                            if ("province".equals(type)) {
                                queryProvinces();
                                ;
                            } else if ("city".equals(type)) {
                                queryCities();
                            } else if ("county".equals(type)) {
                                queryCities();
                            }
                        }
                    });
                }
            }

            @Override
            public void onError(Exception e) {
                //通过runOnUiTheread 方法回到主线程处理逻辑
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeProgressDialog();
                        Toast.makeText(ChooseAreaActivity.this, "加载失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    /**
     * 显示进度对话框
     */
    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("正在加载...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }
    /**
     * 关闭进度对话框
     */
    private void closeProgressDialog(){
        if(progressDialog!=null){
            progressDialog.dismiss();
        }
    }
    /**
     * 捕获Back按键,根据当前的级别来判断,此时应该返回市列表、省列表、还是直接输出
     */
    public void onBackPressed(){
        if(currentLevel==LEVEL_COUNTY){
            queryCities();
        }else if (currentLevel==LEVEL_CITY){
            queryProvinces();
        }else{
            finish();
        }
    }
}


text:
import sys, os, cv, cv2, math, glob, csv
import numpy as np
import scipy as sp
from scipy import signal
from PIL import Image, ImageOps
from collections import Counter
from ssim import SSIM
from ssim.utils import get_gaussian_kernel
from scipy.stats import norm

import networkx as nx

def AABBOverlap(rect1, rect2, printIt = False):

	#Rectangle defined by rect1
	r1left = int(rect1[0])
	r1right = r1left + int(rect1[1])
	r1bottom = int(rect1[2])
	r1top = r1bottom + int(rect1[3])

	#Rectangle defined by rect2
	r2left = int(rect2[0])
	r2right = r2left + int(rect2[1])
	r2bottom = int(rect2[2])
	r2top = r2bottom + int(rect2[3])
	distanceThreshold = 2
	if  (r1left - r2right <  distanceThreshold and r2left -  r1right <  distanceThreshold  and
		r1bottom - r2top < distanceThreshold and r2bottom-r1top < distanceThreshold) :
		left = abs(r1left - r2right)
		right = abs(r1right-r2left)
		up = abs(r1top-r2bottom)
		down = abs(r1bottom-r2top)
		if down < left and down < right and down < up:
			return 'down'
		if up < left and up < right:
			return 'up'
		if  left < right:
			return 'left'
		return 'right'

	else:
		return False

if __name__ == '__main__':
	FFMPEG_BIN = "ffmpeg" # Use on Linux ans Mac OS
	#FFMPEG_BIN = "ffmpeg.exe" # Use on Windows

	import yaml
	inputfile = sys.argv[1]
	with open(inputfile,'rb') as f:
		inputfile = yaml.load(f)

	spritesDirectory = inputfile['spritesDirectory']
	frameInformation = inputfile['frameCSV']

	folder = inputfile['frameFolder']
	distanceScale = inputfile['distanceScale']
	creationCost = inputfile['creationCost']
	deletionCost = inputfile['deletionCost']
	missGate = inputfile['missGate']
	minTrackLength = inputfile['minTrackLength']
	movingProbThreshold = inputfile['movingProbThreshold']
	edgeGuard = inputfile['edgeGuard']

	for frameFile in glob.glob(folder+"*.png"):
		frameImage = cv2.imread(frameFile)
		break

	directory = "./"+spritesDirectory+"/"

	sprites = {}
	for filename in glob.glob(directory+"*.png"):
		sprite_gray =ImageOps.grayscale(Image.open(filename))
		sprites[filename] = sprite_gray

	gaussian_kernel_sigma = 1.5
	gaussian_kernel_width = 11
	gaussian_kernel_1d = get_gaussian_kernel(gaussian_kernel_width, gaussian_kernel_sigma)

	matching = {}
	maxVal = float('-inf')
	for sprite1 in sprites:
		matching[sprite1]  = {}
		for sprite2 in sprites:
			matching[sprite1][sprite2] = SSIM(sprites[sprite1], gaussian_kernel_1d).ssim_value(sprites[sprite2])#np.max(sp.signal.correlate2d(sprites[sprite1],sprites[sprite2]))
			if matching[sprite1][sprite2] > maxVal:
				maxVal = matching[sprite1][sprite2]

	for s1 in matching:
		for s2 in matching[s1]:
			matching[s1][s2] /= maxVal
			#print s1, s2, matching[s1][s2]

	frames = []
	with open(frameInformation) as frameData:
		categories = frameData.readline().rstrip().split(',')
		curFrame = -1
		frame = None
		for line in frameData:
			dat = line.rstrip().split(',')
			if int(dat[0]) != curFrame:
				if frame:
					frames.append(frame)
				curFrame = int(dat[0])
				frame = []
			frame.append(dat)
	frames.append(frame)
	tracks = {}
	curTrack = 0
	ids2Track = {}
	activeTracks = []
	trackMisses = {}
	xs = []
	ys = []
	import os.path
	import pickle
	fname = frameInformation + '_{}{}{}{}.pkl'.format(distanceScale,creationCost,deletionCost,missGate)
	if os.path.isfile(fname):
		tracks = pickle.load( open(fname, "rb" ) )
		for tID, track in tracks.items():
			for pt in track:
				xs.append(pt[2])
				ys.append(pt[3])
	else:
		for spC,ci in zip(frames[0],range(len(frames[0]))):
			sprite =spC[1]
			x = float(spC[2])
			y = float(spC[3])
			track = [(0,sprite,x,y)]
			ids2Track[(0,ci)] = curTrack
			tracks[curTrack] = track
			trackMisses[curTrack] = 0
			activeTracks.append(curTrack)
			curTrack += 1
			xs.append(x)
			ys.append(y)
		scaleValue = 1.0/norm.pdf(0,scale=distanceScale)
		powValue = 1.0
		for fID in range(1,len(frames)):
			sys.stderr.write('{}\n'.format(float(fID)/float(len(frames))))
			pID = fID - 1
			G = nx.DiGraph()
			for trackID in activeTracks:
				trackWeight = pow(min(1,creationCost+float(1+len(tracks[trackID]))/minTrackLength),powValue)
				lastPt = tracks[trackID][-1]
				sprite1 = lastPt[1]
				x1 = lastPt[2]
				y1 = lastPt[3]
				G.add_edge('p{}'.format(trackID),'c{}Deletion'.format(trackID),weight=deletionCost)
				for spC,ci in zip(frames[fID],range(len(frames[fID]))):
					sprite2 =spC[1]
					if   matching[directory+sprite1][directory+sprite2] > 0.1 :
						x2 = float(spC[2])
						y2 = float(spC[3])
						xs.append(x2)
						ys.append(y2)
						if abs(x2-x1) < sprites[directory+sprite1].size[0]*2 and abs(y2-y1) < sprites[directory+sprite1].size[1]*2:
							px = norm.pdf(x1-x2,scale=distanceScale)*scaleValue
							py = norm.pdf(y1-y2,scale=distanceScale)*scaleValue
							weight = px*py*trackWeight* pow(matching[directory+sprite1][directory+sprite2],0.5)

							G.add_edge('p{}'.format(trackID),'c{}'.format(ci),weight=weight)

			for spC,ci in zip(frames[fID],range(len(frames[fID]))):
				G.add_edge('c{}Creation'.format(ci),'c{}'.format(ci),weight=creationCost)
			match = nx.algorithms.max_weight_matching(G)
			'''
			G = nx.DiGraph()
			for spP,pi in zip(frames[pID],range(len(frames[pID]))):
				print spP
				for spC,ci in zip(frames[fID],range(len(frames[fID]))):
					sprite1 =spP[1]
					sprite2 =spC[1]
					x1 = float(spP[2])
					y1 = float(spP[3])
					x2 = float(spC[2])
					y2 = float(spC[3])
					px = norm.pdf(x1-x2,scale=distanceScale)/norm.pdf(0,scale=distanceScale)
					py = norm.pdf(y1-y2,scale=distanceScale)/norm.pdf(0,scale=distanceScale)
					weight = matching[directory+sprite1][directory+sprite2]*px*py

					G.add_edge('p{}'.format(pi),'c{}'.format(ci),weight=weight)

			for spP,pi in zip(frames[pID],range(len(frames[pID]))):
				G.add_edge('p{}'.format(pi),'c{}Deletion'.format(pi),weight=deletionCost)
			for spC,ci in zip(frames[fID],range(len(frames[fID]))):
				G.add_edge('c{}Creation'.format(ci),'c{}'.format(ci),weight=creationCost)
			match = nx.algorithms.max_weight_matching(G)
			'''
			alreadySeen = set()
			for p1,p2 in match.items():

				if p1 in alreadySeen or p2 in alreadySeen:
					continue
				alreadySeen.add(p1)
				alreadySeen.add(p2)
				if 'p' in p2 or 'Creation' in p2:
					temp = p2
					p2 = p1
					p1 = temp
				if 'Creation' in p1 :
					track = []
					#ids2Track[(fID,int(p2[1:]))] = curTrack
					tracks[curTrack] = track
					x = float(frames[fID][int(p2[1:])][2])
					y = float(frames[fID][int(p2[1:])][3])
					track.append((fID,frames[fID][int(p2[1:])][1],x,y))
					tracks[curTrack] = track
					activeTracks.append(curTrack)
					trackMisses[curTrack] = 0
					curTrack += 1

				elif 'Deletion' in p2:
					#trackID = ids2Track[(pID,int(p1[1:]))]
					trackID = int(p1[1:])
					trackMisses[trackID] += 1
					if trackMisses[trackID] > missGate:
						activeTracks.remove(trackID)
					else:
						track = tracks[trackID]
						pt = list(track[-1])
						pt[0] = fID
						pt.append('coast')
						pt = tuple(pt)
						track.append(pt)
				else:
					x = float(frames[fID][int(p2[1:])][2])
					y = float(frames[fID][int(p2[1:])][3])
					#trackID = ids2Track[(pID,int(p1[1:]))]
					trackID = int(p1[1:])
					#ids2Track[(fID,int(p2[1:]))] = trackID
					track = tracks[trackID]
					track.append((fID, frames[fID][int(p2[1:])][1],x,y))
					trackMisses[trackID] = 0
		pickle.dump(tracks, open( fname, "wb" ) )

	#if the end of a track is coasting, go to the last actual point in the track as the end of the track
	for trackID, track in tracks.items():
		lastIndex = len(track)
		for ii in range(len(track)-1,-1,-1):
			if track[ii][-1] != 'coast':
				lastIndex = ii+1
				break
		track = track[:lastIndex]
		tracks[trackID] = track

	timeTracks = {}
	for trackID, track in tracks.items():
		timeTracks[trackID] = {}
		for state in track:
			timeTracks[trackID][state[0]] = state
	events = {}
	timeline = {}

	for trackID, track in tracks.items():
		for state in track:
			time = state[0]
			if time not in timeline:
				timeline[time] = []
			timeline[time].append(trackID)
	trackVelocities = {}
	lastTime = -1
	for time in range(0,len(frames)):
		prevTime = time-1
		if len(timeline[time]) > 0:
			lastTime = time
		for trackID in timeline[time]:
			cx = timeTracks[trackID][time][2]
			cy = timeTracks[trackID][time][3]
			px = cx
			py = cy
			if prevTime in timeTracks[trackID]:
				px = timeTracks[trackID][prevTime][2]
				py = timeTracks[trackID][prevTime][3]
			vx = cx-px
			vy = cy-py

			if trackID not in trackVelocities:
				trackVelocities[trackID] = {}
			trackVelocities[trackID][time] = (vx,vy)

	for time in range(1,len(frames)):
		vxs = []
		vys = []
		for trackID in timeline[time]:
			vxs.append(trackVelocities[trackID][time][0])
			vys.append(trackVelocities[trackID][time][1])
		medX = Counter(vxs).most_common(1)[0][0]
		medY = Counter(vys).most_common(1)[0][0]
		#medX = np.median(np.array(vxs))
		#medY = np.median(np.array(vys))
		for trackID in timeline[time]:
			#print (medX,medY),trackVelocities[trackID][time],(trackVelocities[trackID][time][0]-medX,trackVelocities[trackID][time][1]-medY )
			trackVelocities[trackID][time] = (trackVelocities[trackID][time][0]-medX,trackVelocities[trackID][time][1]-medY )
	trackVelocities2 = {}
	window = inputfile['velMedianWindow']
	window = range(-(window/2),1+window/2) #[-2,-1,0,edgeGuard]

	for track in trackVelocities:
		trackVelocities2[track] = {}

		for time in trackVelocities[track]:
			vxs = []
			vys = []
			for offset in window:
				if time-offset in trackVelocities[track]:
					vxs.append(trackVelocities[track][time-offset][0])
					vys.append(trackVelocities[track][time-offset][1])

			rollingvx = np.median(np.array(vxs))
			rollingvy = np.median(np.array(vys))
			trackVelocities2[track][time] = (rollingvx,rollingvy)

	trackVelocities = trackVelocities2

	probabilityOfMoving = {}
	for trackID, track in tracks.items():
		for state in track:
			time = state[0]
			sprite = state[1]
			if sprite not in probabilityOfMoving:
				probabilityOfMoving[sprite] = {'Y':0,'N':0}
			if abs(trackVelocities[trackID][time][0]) > 0 or abs(trackVelocities[trackID][time][1]) > 0:
				probabilityOfMoving[sprite]['Y'] += 1
			else:
				probabilityOfMoving[sprite]['N'] += 1
	for sprite in probabilityOfMoving:
		#print sprite,float(probabilityOfMoving[sprite]['Y'])/float(probabilityOfMoving[sprite]['Y']+probabilityOfMoving[sprite]['N'])
		probabilityOfMoving[sprite] = float(probabilityOfMoving[sprite]['Y'])/float(probabilityOfMoving[sprite]['Y']+probabilityOfMoving[sprite]['N'])

	minX = 0
	minY = 0
	maxX = frameImage.shape[1]
	maxY = frameImage.shape[0]
	with open(fname+'Velocities','wb') as velfile:
		for trackID, track in tracks.items():
			for state in track:
				velfile.write('{},{},{},{},{}\n'.format(state[0],state[2],state[3],trackVelocities[trackID][state[0]][0],trackVelocities[trackID][state[0]][1]))

	causes = {}
	opposite = {'left':'right',
				'right':'left',
				'up':'down',
				'down':'up'}
	for trackID, track in tracks.items():
		if len(track) > minTrackLength:
			for state in track:
				time = state[0]
				width =  sprites[directory+state[1]].size[0]
				height = sprites[directory+state[1]].size[1]
				rect1 = (state[2],width,state[3],height)
				for otherTrack in timeline[time]:
					if otherTrack != trackID:
						otherState = timeTracks[otherTrack][time]
						otherWidth =  sprites[directory+otherState[1]].size[0]
						otherHeight = sprites[directory+otherState[1]].size[1]
						rect2 = (otherState[2],otherWidth,otherState[3],otherHeight)
						overlap = AABBOverlap(rect1,rect2)
						if overlap:
							if time not in causes:
								causes[time] = set()
							causes[time].add((trackID,otherTrack,overlap))
							causes[time].add((otherTrack,trackID,opposite[overlap]))
	for trackID, track in tracks.items():
		if len(track) > minTrackLength:
			if track[0][0] != 0:
				width = edgeGuard*sprites[directory+track[0][1]].size[0]
				height = edgeGuard*sprites[directory+track[0][1]].size[1]
				if abs(track[0][2]-minX) > width and abs(track[0][2]-maxX) > width and abs(track[0][3]-minY) > height and abs(track[0][3]-maxY) > height:
					if track[0][0] not in events:
						events[track[0][0]] = []
					events[track[0][0]].append( ('C',track[0][1]))

			width = edgeGuard*sprites[directory+track[-1][1]].size[0]
			height = edgeGuard*sprites[directory+track[-1][1]].size[1]
			if  track[-1][0] != lastTime:
				if abs(track[-1][2]-minX) > width and abs(track[-1][2]-maxX) > width and abs(track[-1][3]-minY) > height and abs(track[-1][3]-maxY) > height:
					if track[-1][0]+1 not in events:
						events[track[-1][0]+1] = []
					events[track[-1][0]+1].append( ('D',track[-1][1]))
			prevState = None
			prevTime = None
			for state in track:

				time = state[0]
				if prevState and prevState != state[1]:
					if time not in events:
						events[time] = []
					events[time].append(('S',prevState,state[1]))
				if probabilityOfMoving[state[1]] > movingProbThreshold:
					if prevTime:
						vx = trackVelocities[trackID][time][0]
						vy = trackVelocities[trackID][time][1]
						pvx = trackVelocities[trackID][prevTime][0]
						pvy = trackVelocities[trackID][prevTime][1]
						#print time,state[1],pvx,pvy,vx,vy
						if np.sign(vx) != np.sign(pvx) and abs(pvx) > 0 and vx == 0.0:
							if time not in events:
								events[time] = []
							events[time].append(('VX',state[1]))
						if np.sign(vy) != np.sign(pvy) and abs(pvy) > 0 and vy == 0 :
							if time not in events:
								events[time] = []
							events[time].append(('VY',state[1]))

				prevState = state[1]
				prevTime = time
	#print events
	collisionWindow = 2
	for time in range(1,len(frames)):
		if time in causes:
			for cause in causes[time]:
				causeStr = (timeTracks[cause[0]][time][1],timeTracks[cause[1]][time][1],cause[2])
				noGood = False
				for offset in range(1,collisionWindow):
					if time-offset in causes:
						for otherCause in causes[time-offset]:
							if cause == otherCause:
								noGood = True
							otherCauseStr = (timeTracks[otherCause[0]][time-offset][1],timeTracks[otherCause[1]][time-offset][1],otherCause[2])
							if causeStr == otherCauseStr:
								noGood = True
				if not noGood:
					print time,timeTracks[cause[0]][time][1],timeTracks[cause[1]][time][1],cause[2]
			if (time) in events:
				for event in events[time]:
					eventStr = ''
					for e in event:
						eventStr += '{} '.format(e)
					print time, eventStr
	#for track,ii in zip(tracks,range(len(tracks))):
	#	for state in track:
	#		print ii, state


text:
require './spec/spec_helper'

module Jiragit

  describe Vault do

    let!(:vault) { described_class.new('.testvault') }
    let(:item) { Tag.new(type: 'label') }
    let(:related_item) { Tag.new(type: 'label2') }
    let(:another_related_item) { Tag.new(type: 'label3') }
    let(:a_third_related_item) { Tag.new(type: 'label4') }
    let(:unrelated_item) { Tag.new(type: 'label5') }

    after do
      File.delete('.testvault')
    end

    it "should create a vault file" do
      expect(File.exists?('.testvault')).to be true
    end

    it "should add items" do
      vault.create
      vault.add(item)
      expect(vault.include?(item)).to be true
    end

    it "should relate items" do
      vault.create
      vault.relate(item, related_item)
      vault.add(unrelated_item)
      expect(vault.include?(item)).to be true
      expect(vault.include?(related_item)).to be true
      expect(vault.related?(item, related_item)).to be true
      expect(vault.include?(unrelated_item)).to be true
      expect(vault.related?(item,unrelated_item)).to be false
    end

    it "should relate multiple items" do
      vault.create
      vault.relate(item, related_item, another_related_item)
      vault.add(unrelated_item)
      expect(vault.include?(item)).to be true
      expect(vault.include?(related_item)).to be true
      expect(vault.related?(item, related_item)).to be true
      expect(vault.include?(another_related_item)).to be true
      expect(vault.related?(item, another_related_item)).to be true
      expect(vault.include?(unrelated_item)).to be true
      expect(vault.related?(item, unrelated_item)).to be false
    end

    it "should store relations without self reference" do
      vault.create
      vault.relate(item, related_item, another_related_item)
      expect(vault.relations(item)).not_to include item
      expect(vault.relations(item)).to include related_item
      expect(vault.relations(item)).to include another_related_item
    end

    it "should build relation chains across one item" do
      vault.create
      chain = [item, related_item, another_related_item]
      vault.relate(item, related_item)
      vault.relate(related_item, another_related_item)
      expect(vault.relation_chain(item, another_related_item)).to eq chain
      expect(vault.distally_related?(item, another_related_item)).to eq true
      expect(vault.distally_related?(another_related_item, item)).to eq true
      expect(vault.distally_related?(item, unrelated_item)).to eq false
    end

    it "should build relation chains across more than one item" do
      vault.create
      chain = [item, related_item, another_related_item, a_third_related_item]
      vault.relate(item, related_item)
      vault.relate(related_item, another_related_item)
      vault.relate(another_related_item, a_third_related_item)
      expect(vault.relation_chain(item, a_third_related_item)).to eq chain
      expect(vault.distally_related?(item, a_third_related_item)).to eq true
      expect(vault.distally_related?(a_third_related_item, item)).to eq true
      expect(vault.distally_related?(item, unrelated_item)).to eq false
    end

    it "should save and load thousand items in less than a tenth of a second" do
      vault.create
      1000.times.each do |i|
        tag1 = Tag.new(jira: "PA-#{i}")
        tag2 = Tag.new(branch: "my-feature-branch-#{i}")
        vault.relate(tag1, tag2)
      end

      start_time = Time.now.to_f
      vault.save
      vault.load
      end_time = Time.now.to_f
      expect(end_time - start_time).to be < 0.1
    end

  end

end


text:
module Fog
  module Compute
    class VcloudDirector
      class Real
        require 'fog/vcloud_director/generators/compute/org_vdc_network'

        # Create an Org vDC network.
        #
        # This operation is asynchronous and returns a task that you can
        # monitor to track the progress of the request.
        #
        # Produce media type(s):
        # application/vnd.vmware.vcloud.orgVdcNetwork+xml
        # Output type:
        # OrgVdcNetworkType
        #
        # @param [String] vdc_id Object identifier of the vDC
        # @param [String] name   The name of the entity.
        # @param [Hash] options
        # @option options [String] :Description Optional description.
        # @option options [Hash] :Configuration Network configuration.
        # @option options [Hash] :EdgeGateway  EdgeGateway that connects this
        #   Org vDC network. Applicable only for routed networks.
        # @option options [Hash] :ServiceConfig Specifies the service
        #   configuration for an isolated Org vDC networks.
        # @option options [Boolean] :IsShared True if this network is shared
        #   to multiple Org vDCs.
        #   * :Configuration<~Hash>: NetworkConfigurationType
        #     * :IpScopes<~Hash>:
        #       * :IpScope<~Hash>:
        #         * :IsInherited<~Boolean>: ?
        #         * :Gateway<~String>: IP address of gw
        #         * :Netmask<~String>: Subnet mask of network
        #         * :Dns1<~String>: Primary DNS server.
        #         * :Dns2<~String>: Secondary DNS server.
        #         * :DnsSuffix<~String>: DNS suffix.
        #         * :IsEnabled<~String>: Indicates if subnet is enabled or not.
        #                                Default value is True.
        #         * :IpRanges<~Array>: IP ranges used for static pool allocation
        #                             in the network. Array of Hashes of:
        #                               * :StartAddress - start IP in range
        #                               * :EndAddress - end IP in range
        #   * :EdgeGateway<~Hash>: EdgeGateway that connects this Org vDC
        #                          network. Applicable only for routed networks.
        #   * :ServiceConfig<~Hash>: Specifies the service configuration for an
        #                            isolated network
        #
        # @return [Excon::Response]
        #   * body<~Hash>:
        #
        # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-CreateOrgVdcNetwork.html
        # @since vCloud API version 5.1
        def post_create_org_vdc_network(vdc_id, name, options={})
          body = Fog::Generators::Compute::VcloudDirector::OrgVdcNetwork.new(options.merge(:name => name)).generate_xml

          request(
            :body    => body,
            :expects => 201,
            :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.orgVdcNetwork+xml'},
            :method  => 'POST',
            :parser  => Fog::ToHashDocument.new,
            :path    => "admin/vdc/#{vdc_id}/networks"
          )
        end
      end

      class Mock
        def post_create_org_vdc_network(vdc_id, name, options={})
          unless data[:vdcs][vdc_id]
            raise Fog::Compute::VcloudDirector::Forbidden.new(
              "No access to entity \"(com.vmware.vcloud.entity.vdc:#{vdc_id})\"."
            )
          end

          type = 'network'
          id = uuid

          # Description
          # Configuration
          #   IpScopes
          #     IpScope
          #       IsInherited
          #       Gateway
          #       Netmask
          #       Dns1
          #       Dns2
          #       DnsSuffix
          #       IsEnabled
          #       IpRanges
          #         IpRange
          #           StartAddress
          #           EndAddress
          #   FenceMode
          # EdgeGateway
          # IsShared

          network_body = {
            :name           => name,
            :vdc            => vdc_id,
          }

          [:Description, :IsShared].each do |key|
            network_body[key] = options[key] if options.key?(key)
          end

          if options.key?(:EdgeGateway)
            network_body[:EdgeGateway] =
              options[:EdgeGateway][:href].split('/').last
          end

          if configuration = options[:Configuration]
            if ip_scopes = configuration[:IpScopes]
              if ip_scope = ip_scopes[:IpScope]
                [:IsInherited, :Gateway, :Netmask,
                  :Dns1, :Dns2, :DnsSuffix, :IsEnabled].each do |key|
                    network_body[key] = ip_scope[key] if ip_scope.key?(key)
                end
                if ip_ranges = ip_scope[:IpRanges]
                  network_body[:IpRanges] = []
                  ip_ranges.each do |ipr|
                    network_body[:IpRanges] << {
                      :StartAddress => ipr[:IpRange][:StartAddress],
                      :EndAddress   => ipr[:IpRange][:EndAddress]
                    }
                  end
                end
              end
            end
            network_body[:FenceMode] = configuration[:FenceMode] if ip_scope.key?(:FenceMode)
          end

          owner = {
            :href => make_href("#{type}/#{id}"),
            :type => "application/vnd.vmware.vcloud.#{type}+xml"
          }
          task_id = enqueue_task(
            "Adding #{type} #{name} (#{id})", 'CreateOrgVdcNetwork', owner,
            :on_success => lambda do
              data[:networks][id] = network_body
            end
          )

          body = {
            :xmlns => xmlns,
            :xmlns_xsi => xmlns_xsi,
            :xsi_schemaLocation => xsi_schema_location,
            :href => make_href("admin/network/#{id}"),
            :name => name,
            :id => "urn:vcloud:network:#{id}",
            :type => "application/vnd.vmware.vcloud.orgVdcNetwork+xml",
            :Link => [
              {:rel=>"up", :type=>"application/vnd.vmware.vcloud.vdc+xml", :href=>make_href("vdc/#{vdc_id}")},
              {:rel=>"down", :type=>"application/vnd.vmware.vcloud.metadata+xml", :href=>make_href("admin/network/#{id}/metadata")},
              {:rel=>"down", :type=>"application/vnd.vmware.vcloud.allocatedNetworkAddress+xml", :href=>make_href("admin/network/#{id}/allocatedAddresses/")},
            ],
          }.merge(options)

          body[:Tasks] = {
            :Task => task_body(task_id)
          }

          Excon::Response.new(
            :status => 201,
            :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"},
            :body => body
          )
        end
      end
    end
  end
end