text:
	#define DISABLESTEAMWORKS
#endif

#if !DISABLESTEAMWORKS

using System.Runtime.InteropServices;
using IntPtr = System.IntPtr;

namespace Steamworks {
	public static class SteamNetworkingUtils {
		/// <summary>
		/// <para> Efficient message sending</para>
		/// <para>/ Allocate and initialize a message object.  Usually the reason</para>
		/// <para>/ you call this is to pass it to ISteamNetworkingSockets::SendMessages.</para>
		/// <para>/ The returned object will have all of the relevant fields cleared to zero.</para>
		/// <para>/</para>
		/// <para>/ Optionally you can also request that this system allocate space to</para>
		/// <para>/ hold the payload itself.  If cbAllocateBuffer is nonzero, the system</para>
		/// <para>/ will allocate memory to hold a payload of at least cbAllocateBuffer bytes.</para>
		/// <para>/ m_pData will point to the allocated buffer, m_cbSize will be set to the</para>
		/// <para>/ size, and m_pfnFreeData will be set to the proper function to free up</para>
		/// <para>/ the buffer.</para>
		/// <para>/</para>
		/// <para>/ If cbAllocateBuffer=0, then no buffer is allocated.  m_pData will be NULL,</para>
		/// <para>/ m_cbSize will be zero, and m_pfnFreeData will be NULL.  You will need to</para>
		/// <para>/ set each of these.</para>
		/// </summary>
		public static IntPtr AllocateMessage(int cbAllocateBuffer) {
			InteropHelp.TestIfAvailableClient();
			return NativeMethods.ISteamNetworkingUtils_AllocateMessage(CSteamAPIContext.GetSteamNetworkingUtils(), cbAllocateBuffer);
		}

		/// <summary>
		/// <para> Access to Steam Datagram Relay (SDR) network</para>
		/// <para> Initialization and status check</para>
		/// <para>/ If you know that you are going to be using the relay network (for example,</para>
		/// <para>/ because you anticipate making P2P connections), call this to initialize the</para>
		/// <para>/ relay network.  If you do not call this, the initialization will</para>
		/// <para>/ be delayed until the first time you use a feature that requires access</para>
		/// <para>/ to the relay network, which will delay that first access.</para>
		/// <para>/</para>
		/// <para>/ You can also call this to force a retry if the previous attempt has failed.</para>
		/// <para>/ Performing any action that requires access to the relay network will also</para>
		/// <para>/ trigger a retry, and so calling this function is never strictly necessary,</para>
		/// <para>/ but it can be useful to call it a program launch time, if access to the</para>
		/// <para>/ relay network is anticipated.</para>
		/// <para>/</para>
		/// <para>/ Use GetRelayNetworkStatus or listen for SteamRelayNetworkStatus_t</para>
		/// <para>/ callbacks to know when initialization has completed.</para>
		/// <para>/ Typically initialization completes in a few seconds.</para>
		/// <para>/</para>
		/// <para>/ Note: dedicated servers hosted in known data centers do *not* need</para>
		/// <para>/ to call this, since they do not make routing decisions.  However, if</para>
		/// <para>/ the dedicated server will be using P2P functionality, it will act as</para>
		/// <para>/ a "client" and this should be called.</para>
		/// </summary>
		public static void InitRelayNetworkAccess() {
			InteropHelp.TestIfAvailableClient();
			NativeMethods.ISteamNetworkingUtils_InitRelayNetworkAccess(CSteamAPIContext.GetSteamNetworkingUtils());
		}

		/// <summary>
		/// <para>/ Fetch current status of the relay network.</para>
		/// <para>/</para>
		/// <para>/ SteamRelayNetworkStatus_t is also a callback.  It will be triggered on</para>
		/// <para>/ both the user and gameserver interfaces any time the status changes, or</para>
		/// <para>/ ping measurement starts or stops.</para>
		/// <para>/</para>
		/// <para>/ SteamRelayNetworkStatus_t::m_eAvail is returned.  If you want</para>
		/// <para>/ more details, you can pass a non-NULL value.</para>
		/// </summary>
		public static ESteamNetworkingAvailability GetRelayNetworkStatus(out SteamRelayNetworkStatus_t pDetails) {
			InteropHelp.TestIfAvailableClient();
			return NativeMethods.ISteamNetworkingUtils_GetRelayNetworkStatus(CSteamAPIContext.GetSteamNetworkingUtils(), out pDetails);
		}

		/// <summary>
		/// <para> "Ping location" functions</para>
		/// <para> We use the ping times to the valve relays deployed worldwide to</para>
		/// <para> generate a "marker" that describes the location of an Internet host.</para>
		/// <para> Given two such markers, we can estimate the network latency between</para>
		/// <para> two hosts, without sending any packets.  The estimate is based on the</para>
		/// <para> optimal route that is found through the Valve network.  If you are</para>
		/// <para> using the Valve network to carry the traffic, then this is precisely</para>
		/// <para> the ping you want.  If you are not, then the ping time will probably</para>
		/// <para> still be a reasonable estimate.</para>
		/// <para> This is extremely useful to select peers for matchmaking!</para>
		/// <para> The markers can also be converted to a string, so they can be transmitted.</para>
		/// <para> We have a separate library you can use on your app's matchmaking/coordinating</para>
		/// <para> server to manipulate these objects.  (See steamdatagram_gamecoordinator.h)</para>
		/// <para>/ Return location info for the current host.  Returns the approximate</para>
		/// <para>/ age of the data, in seconds, or -1 if no data is available.</para>
		/// <para>/</para>
		/// <para>/ It takes a few seconds to initialize access to the relay network.  If</para>
		/// <para>/ you call this very soon after calling InitRelayNetworkAccess,</para>
		/// <para>/ the data may not be available yet.</para>
		/// <para>/</para>
		/// <para>/ This always return the most up-to-date information we have available</para>
		/// <para>/ right now, even if we are in the middle of re-calculating ping times.</para>
		/// </summary>
		public static float GetLocalPingLocation(out SteamNetworkPingLocation_t result) {
			InteropHelp.TestIfAvailableClient();
			return NativeMethods.ISteamNetworkingUtils_GetLocalPingLocation(CSteamAPIContext.GetSteamNetworkingUtils(), out result);
		}

		/// <summary>
		/// <para>/ Estimate the round-trip latency between two arbitrary locations, in</para>
		/// <para>/ milliseconds.  This is a conservative estimate, based on routing through</para>
		/// <para>/ the relay network.  For most basic relayed connections, this ping time</para>
		/// <para>/ will be pretty accurate, since it will be based on the route likely to</para>
		/// <para>/ be actually used.</para>
		/// <para>/</para>
		/// <para>/ If a direct IP route is used (perhaps via NAT traversal), then the route</para>
		/// <para>/ will be different, and the ping time might be better.  Or it might actually</para>
		/// <para>/ be a bit worse!  Standard IP routing is frequently suboptimal!</para>
		/// <para>/</para>
		/// <para>/ But even in this case, the estimate obtained using this method is a</para>
		/// <para>/ reasonable upper bound on the ping time.  (Also it has the advantage</para>
		/// <para>/ of returning immediately and not sending any packets.)</para>
		/// <para>/</para>
		/// <para>/ In a few cases we might not able to estimate the route.  In this case</para>
		/// <para>/ a negative value is returned.  k_nSteamNetworkingPing_Failed means</para>
		/// <para>/ the reason was because of some networking difficulty.  (Failure to</para>
		/// <para>/ ping, etc)  k_nSteamNetworkingPing_Unknown is returned if we cannot</para>
		/// <para>/ currently answer the question for some other reason.</para>
		/// <para>/</para>
		/// <para>/ Do you need to be able to do this from a backend/matchmaking server?</para>
		/// <para>/ You are looking for the "game coordinator" library.</para>
		/// </summary>
		public static int EstimatePingTimeBetweenTwoLocations(ref SteamNetworkPingLocation_t location1, ref SteamNetworkPingLocation_t location2) {
			InteropHelp.TestIfAvailableClient();
			return NativeMethods.ISteamNetworkingUtils_EstimatePingTimeBetweenTwoLocations(CSteamAPIContext.GetSteamNetworkingUtils(), ref location1, ref location2);
		}

		/// <summary>
		/// <para>/ Same as EstimatePingTime, but assumes that one location is the local host.</para>
		/// <para>/ This is a bit faster, especially if you need to calculate a bunch of</para>
		/// <para>/ these in a loop to find the fastest one.</para>
		/// <para>/</para>
		/// <para>/ In rare cases this might return a slightly different estimate than combining</para>
		/// <para>/ GetLocalPingLocation with EstimatePingTimeBetweenTwoLocations.  That's because</para>
		/// <para>/ this function uses a slightly more complete set of information about what</para>
		/// <para>/ route would be taken.</para>
		/// </summary>
		public static int EstimatePingTimeFromLocalHost(ref SteamNetworkPingLocation_t remoteLocation) {
			InteropHelp.TestIfAvailableClient();
			return NativeMethods.ISteamNetworkingUtils_EstimatePingTimeFromLocalHost(CSteamAPIContext.GetSteamNetworkingUtils(), ref remoteLocation);
		}

		/// <summary>
		/// <para>/ Convert a ping location into a text format suitable for sending over the wire.</para>
		/// <para>/ The format is a compact and human readable.  However, it is subject to change</para>
		/// <para>/ so please do not parse it yourself.  Your buffer must be at least</para>
		/// <para>/ k_cchMaxSteamNetworkingPingLocationString bytes.</para>
		/// </summary>
		public static void ConvertPingLocationToString(ref SteamNetworkPingLocation_t location, out string pszBuf, int cchBufSize) {
			InteropHelp.TestIfAvailableClient();
			IntPtr pszBuf2 = Marshal.AllocHGlobal(cchBufSize);
			NativeMethods.ISteamNetworkingUtils_ConvertPingLocationToString(CSteamAPIContext.GetSteamNetworkingUtils(), ref location, pszBuf2, cchBufSize);
			pszBuf = InteropHelp.PtrToStringUTF8(pszBuf2);
			Marshal.FreeHGlobal(pszBuf2);
		}

		/// <summary>
		/// <para>/ Parse back SteamNetworkPingLocation_t string.  Returns false if we couldn't understand</para>
		/// <para>/ the string.</para>
		/// </summary>
		public static bool ParsePingLocationString(string pszString, out SteamNetworkPingLocation_t result) {
			InteropHelp.TestIfAvailableClient();
			using (var pszString2 = new InteropHelp.UTF8StringHandle(pszString)) {
				return NativeMethods.ISteamNetworkingUtils_ParsePingLocationString(CSteamAPIContext.GetSteamNetworkingUtils(), pszString2, out result);
			}
		}

		/// <summary>
		/// <para>/ Check if the ping data of sufficient recency is available, and if</para>
		/// <para>/ it's too old, start refreshing it.</para>
		/// <para>/</para>
		/// <para>/ Please only call this function when you *really* do need to force an</para>
		/// <para>/ immediate refresh of the data.  (For example, in response to a specific</para>
		/// <para>/ user input to refresh this information.)  Don't call it "just in case",</para>
		/// <para>/ before every connection, etc.  That will cause extra traffic to be sent</para>
		/// <para>/ for no benefit. The library will automatically refresh the information</para>
		/// <para>/ as needed.</para>
		/// <para>/</para>
		/// <para>/ Returns true if sufficiently recent data is already available.</para>
		/// <para>/</para>
		/// <para>/ Returns false if sufficiently recent data is not available.  In this</para>
		/// <para>/ case, ping measurement is initiated, if it is not already active.</para>
		/// <para>/ (You cannot restart a measurement already in progress.)</para>
		/// <para>/</para>
		/// <para>/ You can use GetRelayNetworkStatus or listen for SteamRelayNetworkStatus_t</para>
		/// <para>/ to know when ping measurement completes.</para>
		/// </summary>
		public static bool CheckPingDataUpToDate(float flMaxAgeSeconds) {
			InteropHelp.TestIfAvailableClient();
			return NativeMethods.ISteamNetworkingUtils_CheckPingDataUpToDate(CSteamAPIContext.GetSteamNetworkingUtils(), flMaxAgeSeconds);
		}

		/// <summary>
		/// <para> List of Valve data centers, and ping times to them.  This might</para>
		/// <para> be useful to you if you are use our hosting, or just need to measure</para>
		/// <para> latency to a cloud data center where we are running relays.</para>
		/// <para>/ Fetch ping time of best available relayed route from this host to</para>
		/// <para>/ the specified data center.</para>
		/// </summary>
		public static int GetPingToDataCenter(SteamNetworkingPOPID popID, out SteamNetworkingPOPID pViaRelayPoP) {
			InteropHelp.TestIfAvailableClient();
			return NativeMethods.ISteamNetworkingUtils_GetPingToDataCenter(CSteamAPIContext.GetSteamNetworkingUtils(), popID, out pViaRelayPoP);
		}

		/// <summary>
		/// <para>/ Get *direct* ping time to the relays at the data center.</para>
		/// </summary>
		public static int GetDirectPingToPOP(SteamNetworkingPOPID popID) {
			InteropHelp.TestIfAvailableClient();
			return NativeMethods.ISteamNetworkingUtils_GetDirectPingToPOP(CSteamAPIContext.GetSteamNetworkingUtils(), popID);
		}

		/// <summary>
		/// <para>/ Get number of network points of presence in the config</para>
		/// </summary>
		public static int GetPOPCount() {
			InteropHelp.TestIfAvailableClient();
			return NativeMethods.ISteamNetworkingUtils_GetPOPCount(CSteamAPIContext.GetSteamNetworkingUtils());
		}

		/// <summary>
		/// <para>/ Get list of all POP IDs.  Returns the number of entries that were filled into</para>
		/// <para>/ your list.</para>
		/// </summary>
		public static int GetPOPList(out SteamNetworkingPOPID list, int nListSz) {
			InteropHelp.TestIfAvailableClient();
			return NativeMethods.ISteamNetworkingUtils_GetPOPList(CSteamAPIContext.GetSteamNetworkingUtils(), out list, nListSz);
		}

		/// <summary>
		/// <para> Misc</para>
		/// <para>/ Fetch current timestamp.  This timer has the following properties:</para>
		/// <para>/</para>
		/// <para>/ - Monotonicity is guaranteed.</para>
		/// <para>/ - The initial value will be at least 24*3600*30*1e6, i.e. about</para>
		/// <para>/   30 days worth of microseconds.  In this way, the timestamp value of</para>
		/// <para>/   0 will always be at least "30 days ago".  Also, negative numbers</para>
		/// <para>/   will never be returned.</para>
		/// <para>/ - Wraparound / overflow is not a practical concern.</para>
		/// <para>/</para>
		/// <para>/ If you are running under the debugger and stop the process, the clock</para>
		/// <para>/ might not advance the full wall clock time that has elapsed between</para>
		/// <para>/ calls.  If the process is not blocked from normal operation, the</para>
		/// <para>/ timestamp values will track wall clock time, even if you don't call</para>
		/// <para>/ the function frequently.</para>
		/// <para>/</para>
		/// <para>/ The value is only meaningful for this run of the process.  Don't compare</para>
		/// <para>/ it to values obtained on another computer, or other runs of the same process.</para>
		/// </summary>
		public static SteamNetworkingMicroseconds GetLocalTimestamp() {
			InteropHelp.TestIfAvailableClient();
			return (SteamNetworkingMicroseconds)NativeMethods.ISteamNetworkingUtils_GetLocalTimestamp(CSteamAPIContext.GetSteamNetworkingUtils());
		}

		/// <summary>
		/// <para>/ Set a function to receive network-related information that is useful for debugging.</para>
		/// <para>/ This can be very useful during development, but it can also be useful for troubleshooting</para>
		/// <para>/ problems with tech savvy end users.  If you have a console or other log that customers</para>
		/// <para>/ can examine, these log messages can often be helpful to troubleshoot network issues.</para>
		/// <para>/ (Especially any warning/error messages.)</para>
		/// <para>/</para>
		/// <para>/ The detail level indicates what message to invoke your callback on.  Lower numeric</para>
		/// <para>/ value means more important, and the value you pass is the lowest priority (highest</para>
		/// <para>/ numeric value) you wish to receive callbacks for.</para>
		/// <para>/</para>
		/// <para>/ The value here controls the detail level for most messages.  You can control the</para>
		/// <para>/ detail level for various subsystems (perhaps only for certain connections) by</para>
		/// <para>/ adjusting the configuration values k_ESteamNetworkingConfig_LogLevel_Xxxxx.</para>
		/// <para>/</para>
		/// <para>/ Except when debugging, you should only use k_ESteamNetworkingSocketsDebugOutputType_Msg</para>
		/// <para>/ or k_ESteamNetworkingSocketsDebugOutputType_Warning.  For best performance, do NOT</para>
		/// <para>/ request a high detail level and then filter out messages in your callback.  This incurs</para>
		/// <para>/ all of the expense of formatting the messages, which are then discarded.  Setting a high</para>
		/// <para>/ priority value (low numeric value) here allows the library to avoid doing this work.</para>
		/// <para>/</para>
		/// <para>/ IMPORTANT: This may be called from a service thread, while we own a mutex, etc.</para>
		/// <para>/ Your output function must be threadsafe and fast!  Do not make any other</para>
		/// <para>/ Steamworks calls from within the handler.</para>
		/// </summary>
		public static void SetDebugOutputFunction(ESteamNetworkingSocketsDebugOutputType eDetailLevel, FSteamNetworkingSocketsDebugOutput pfnFunc) {
			InteropHelp.TestIfAvailableClient();
			NativeMethods.ISteamNetworkingUtils_SetDebugOutputFunction(CSteamAPIContext.GetSteamNetworkingUtils(), eDetailLevel, pfnFunc);
		}

		/// <summary>
		/// <para> Fake IP</para>
		/// <para> Useful for interfacing with code that assumes peers are identified using an IPv4 address</para>
		/// <para>/ Return true if an IPv4 address is one that might be used as a "fake" one.</para>
		/// <para>/ This function is fast; it just does some logical tests on the IP and does</para>
		/// <para>/ not need to do any lookup operations.</para>
		/// </summary>
		public static bool IsFakeIPv4(uint nIPv4) {
			InteropHelp.TestIfAvailableClient();
			return NativeMethods.ISteamNetworkingUtils_IsFakeIPv4(CSteamAPIContext.GetSteamNetworkingUtils(), nIPv4);
		}

		public static ESteamNetworkingFakeIPType GetIPv4FakeIPType(uint nIPv4) {
			InteropHelp.TestIfAvailableClient();
			return NativeMethods.ISteamNetworkingUtils_GetIPv4FakeIPType(CSteamAPIContext.GetSteamNetworkingUtils(), nIPv4);
		}

		/// <summary>
		/// <para>/ Get the real identity associated with a given FakeIP.</para>
		/// <para>/</para>
		/// <para>/ On failure, returns:</para>
		/// <para>/ - k_EResultInvalidParam: the IP is not a FakeIP.</para>
		/// <para>/ - k_EResultNoMatch: we don't recognize that FakeIP and don't know the corresponding identity.</para>
		/// <para>/</para>
		/// <para>/ FakeIP's used by active connections, or the FakeIPs assigned to local identities,</para>
		/// <para>/ will always work.  FakeIPs for recently destroyed connections will continue to</para>
		/// <para>/ return results for a little while, but not forever.  At some point, we will forget</para>
		/// <para>/ FakeIPs to save space.  It's reasonably safe to assume that you can read back the</para>
		/// <para>/ real identity of a connection very soon after it is destroyed.  But do not wait</para>
		/// <para>/ indefinitely.</para>
		/// </summary>
		public static EResult GetRealIdentityForFakeIP(ref SteamNetworkingIPAddr fakeIP, out SteamNetworkingIdentity pOutRealIdentity) {
			InteropHelp.TestIfAvailableClient();
			return NativeMethods.ISteamNetworkingUtils_GetRealIdentityForFakeIP(CSteamAPIContext.GetSteamNetworkingUtils(), ref fakeIP, out pOutRealIdentity);
		}

		/// <summary>
		/// <para> Set and get configuration values, see ESteamNetworkingConfigValue for individual descriptions.</para>
		/// <para> Shortcuts for common cases.  (Implemented as inline functions below)</para>
		/// <para> Set global callbacks.  If you do not want to use Steam's callback dispatch mechanism and you</para>
		/// <para> want to use the same callback on all (or most) listen sockets and connections, then</para>
		/// <para> simply install these callbacks first thing, and you are good to go.</para>
		/// <para> See ISteamNetworkingSockets::RunCallbacks</para>
		/// <para>/ Set a configuration value.</para>
		/// <para>/ - eValue: which value is being set</para>
		/// <para>/ - eScope: Onto what type of object are you applying the setting?</para>
		/// <para>/ - scopeArg: Which object you want to change?  (Ignored for global scope).  E.g. connection handle, listen socket handle, interface pointer, etc.</para>
		/// <para>/ - eDataType: What type of data is in the buffer at pValue?  This must match the type of the variable exactly!</para>
		/// <para>/ - pArg: Value to set it to.  You can pass NULL to remove a non-global setting at this scope,</para>
		/// <para>/   causing the value for that object to use global defaults.  Or at global scope, passing NULL</para>
		/// <para>/   will reset any custom value and restore it to the system default.</para>
		/// <para>/   NOTE: When setting pointers (e.g. callback functions), do not pass the function pointer directly.</para>
		/// <para>/   Your argument should be a pointer to a function pointer.</para>
		/// </summary>
		public static bool SetConfigValue(ESteamNetworkingConfigValue eValue, ESteamNetworkingConfigScope eScopeType, IntPtr scopeObj, ESteamNetworkingConfigDataType eDataType, IntPtr pArg) {
			InteropHelp.TestIfAvailableClient();
			return NativeMethods.ISteamNetworkingUtils_SetConfigValue(CSteamAPIContext.GetSteamNetworkingUtils(), eValue, eScopeType, scopeObj, eDataType, pArg);
		}

		/// <summary>
		/// <para>/ Set a configuration value, using a struct to pass the value.</para>
		/// <para>/ (This is just a convenience shortcut; see below for the implementation and</para>
		/// <para>/ a little insight into how SteamNetworkingConfigValue_t is used when</para>
		/// <para>/ setting config options during listen socket and connection creation.)</para>
		/// <para>/ Get a configuration value.</para>
		/// <para>/ - eValue: which value to fetch</para>
		/// <para>/ - eScopeType: query setting on what type of object</para>
		/// <para>/ - eScopeArg: the object to query the setting for</para>
		/// <para>/ - pOutDataType: If non-NULL, the data type of the value is returned.</para>
		/// <para>/ - pResult: Where to put the result.  Pass NULL to query the required buffer size.  (k_ESteamNetworkingGetConfigValue_BufferTooSmall will be returned.)</para>
		/// <para>/ - cbResult: IN: the size of your buffer.  OUT: the number of bytes filled in or required.</para>
		/// </summary>
		public static ESteamNetworkingGetConfigValueResult GetConfigValue(ESteamNetworkingConfigValue eValue, ESteamNetworkingConfigScope eScopeType, IntPtr scopeObj, out ESteamNetworkingConfigDataType pOutDataType, IntPtr pResult, ref ulong cbResult) {
			InteropHelp.TestIfAvailableClient();
			return NativeMethods.ISteamNetworkingUtils_GetConfigValue(CSteamAPIContext.GetSteamNetworkingUtils(), eValue, eScopeType, scopeObj, out pOutDataType, pResult, ref cbResult);
		}

		/// <summary>
		/// <para>/ Get info about a configuration value.  Returns the name of the value,</para>
		/// <para>/ or NULL if the value doesn't exist.  Other output parameters can be NULL</para>
		/// <para>/ if you do not need them.</para>
		/// </summary>
		public static string GetConfigValueInfo(ESteamNetworkingConfigValue eValue, out ESteamNetworkingConfigDataType pOutDataType, out ESteamNetworkingConfigScope pOutScope) {
			InteropHelp.TestIfAvailableClient();
			return InteropHelp.PtrToStringUTF8(NativeMethods.ISteamNetworkingUtils_GetConfigValueInfo(CSteamAPIContext.GetSteamNetworkingUtils(), eValue, out pOutDataType, out pOutScope));
		}

		/// <summary>
		/// <para>/ Iterate the list of all configuration values in the current environment that it might</para>
		/// <para>/ be possible to display or edit using a generic UI.  To get the first iterable value,</para>
		/// <para>/ pass k_ESteamNetworkingConfig_Invalid.  Returns k_ESteamNetworkingConfig_Invalid</para>
		/// <para>/ to signal end of list.</para>
		/// <para>/</para>
		/// <para>/ The bEnumerateDevVars argument can be used to include "dev" vars.  These are vars that</para>
		/// <para>/ are recommended to only be editable in "debug" or "dev" mode and typically should not be</para>
		/// <para>/ shown in a retail environment where a malicious local user might use this to cheat.</para>
		/// </summary>
		public static ESteamNetworkingConfigValue IterateGenericEditableConfigValues(ESteamNetworkingConfigValue eCurrent, bool bEnumerateDevVars) {
			InteropHelp.TestIfAvailableClient();
			return NativeMethods.ISteamNetworkingUtils_IterateGenericEditableConfigValues(CSteamAPIContext.GetSteamNetworkingUtils(), eCurrent, bEnumerateDevVars);
		}

		/// <summary>
		/// <para> String conversions.  You'll usually access these using the respective</para>
		/// <para> inline methods.</para>
		/// </summary>
		public static void SteamNetworkingIPAddr_ToString(ref SteamNetworkingIPAddr addr, out string buf, uint cbBuf, bool bWithPort) {
			InteropHelp.TestIfAvailableClient();
			IntPtr buf2 = Marshal.AllocHGlobal((int)cbBuf);
			NativeMethods.ISteamNetworkingUtils_SteamNetworkingIPAddr_ToString(CSteamAPIContext.GetSteamNetworkingUtils(), ref addr, buf2, cbBuf, bWithPort);
			buf = InteropHelp.PtrToStringUTF8(buf2);
			Marshal.FreeHGlobal(buf2);
		}

		public static bool SteamNetworkingIPAddr_ParseString(out SteamNetworkingIPAddr pAddr, string pszStr) {
			InteropHelp.TestIfAvailableClient();
			using (var pszStr2 = new InteropHelp.UTF8StringHandle(pszStr)) {
				return NativeMethods.ISteamNetworkingUtils_SteamNetworkingIPAddr_ParseString(CSteamAPIContext.GetSteamNetworkingUtils(), out pAddr, pszStr2);
			}
		}

		public static ESteamNetworkingFakeIPType SteamNetworkingIPAddr_GetFakeIPType(ref SteamNetworkingIPAddr addr) {
			InteropHelp.TestIfAvailableClient();
			return NativeMethods.ISteamNetworkingUtils_SteamNetworkingIPAddr_GetFakeIPType(CSteamAPIContext.GetSteamNetworkingUtils(), ref addr);
		}

		public static void SteamNetworkingIdentity_ToString(ref SteamNetworkingIdentity identity, out string buf, uint cbBuf) {
			InteropHelp.TestIfAvailableClient();
			IntPtr buf2 = Marshal.AllocHGlobal((int)cbBuf);
			NativeMethods.ISteamNetworkingUtils_SteamNetworkingIdentity_ToString(CSteamAPIContext.GetSteamNetworkingUtils(), ref identity, buf2, cbBuf);
			buf = InteropHelp.PtrToStringUTF8(buf2);
			Marshal.FreeHGlobal(buf2);
		}

		public static bool SteamNetworkingIdentity_ParseString(out SteamNetworkingIdentity pIdentity, string pszStr) {
			InteropHelp.TestIfAvailableClient();
			using (var pszStr2 = new InteropHelp.UTF8StringHandle(pszStr)) {
				return NativeMethods.ISteamNetworkingUtils_SteamNetworkingIdentity_ParseString(CSteamAPIContext.GetSteamNetworkingUtils(), out pIdentity, pszStr2);
			}
		}
	}
}

#endif // !DISABLESTEAMWORKS


text:
package com.github.skrethel.simple.config.retrofit.exception;

public class WriteException extends Exception {

	public WriteException() {
	}

	public WriteException(String message) {
		super(message);
	}

	public WriteException(String message, Throwable cause) {
		super(message, cause);
	}

	public WriteException(Throwable cause) {
		super(cause);
	}
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

require('./lib/test-env.js');
const awsMocks = require('./lib/aws-mocks.js'); //eslint-disable-line
const mongoose = require('mongoose');
const Promise = require('bluebird');
const expect = require('chai').expect;
const request = require('superagent');
const User = require('../model/user.js');
const debug = require('debug')('decor8:basic-auth-route-test');

const serverToggle = require('./lib/server-toggle.js');
const server = require('../server.js');

mongoose.Promise = Promise;

const url = `http://localhost:${process.env.PORT}`;

const exampleUser = {
  username: 'Cayla Zabel',
  password: 'isacodeboss',
  email: 'example@email.com'
};

describe('User Tests', function(){
  before( done => {
    serverToggle.serverOn(server, done);
  });
  after( done => {
    serverToggle.serverOff(server, done);
  });
  describe('Post /api/signup', function(){
    describe('With a valid body', function(){
      after(done => {
        User.remove({})
        .then(() => done())
        .catch(done);
      });
      it('should return a token', done => {
        debug('Singup Post');
        request.post(`${url}/api/signup`)
        .send(exampleUser)
        .end((err, res) => {
          if(err) return done(err);
          expect(res.status).to.equal(200);
          expect(res.text).to.be.a('string');
          done();
        });
      });
    });
  });
  describe('Get /api/signin', function(){
    describe('With a valid body', function(){
      before(done => {
        let user = new User(exampleUser);
        user.generatePasswordHash(exampleUser.password)
        .then(user => user.save())
        .then(user => {
          this.tempUser = user;
          done();
        })
        .catch(done);
      });
      after(done => {
        User.remove({})
        .then(() => done())
        .catch(done);
      });
      it('should return a token', done => {
        debug('Signin Get');
        request.get(`${url}/api/signin`)
        .auth('Cayla Zabel', 'isacodeboss')
        .end((err, res) => {
          if (err) return done(err);
          expect(res.status).to.equal(200);
          done();
        });
      });
    });
    describe('Without authorization', function(){
      before(done => {
        let user = new User(exampleUser);
        user.generatePasswordHash(exampleUser.password)
        .then(user => user.save())
        .then(user => {
          this.tempUser = user;
          done();
        })
        .catch(done);
      });
      after(done => {
        User.remove({})
        .then(() => done())
        .catch(done);
      });
      it('should return a token', done => {
        debug('Signin Get');
        request.get(`${url}/api/signin`)
        .end((err, res) => {
          expect(res.status).to.equal(401);
          done();
        });
      });
    });
    describe('Without Basic in authorization', function(){
      before(done => {
        let user = new User(exampleUser);
        user.generatePasswordHash(exampleUser.password)
        .then(user => user.save())
        .then(user => {
          this.tempUser = user;
          done();
        })
        .catch(done);
      });
      after(done => {
        User.remove({})
        .then(() => done())
        .catch(done);
      });
      it('should return a token', done => {
        debug('Signin Get');
        request.get(`${url}/api/signin`)
        .set({
          Authorization: `${this.tempToken}`
        })
        .end((err, res) => {
          expect(res.status).to.equal(401);
          done();
        });
      });
    });
    describe('Without Username in  authorization', function(){
      before(done => {
        let user = new User(exampleUser);
        user.generatePasswordHash(exampleUser.password)
        .then(user => user.save())
        .then(user => {
          this.tempUser = user;
          done();
        })
        .catch(done);
      });
      after(done => {
        User.remove({})
        .then(() => done())
        .catch(done);
      });
      it('should return a token', done => {
        debug('Signin Get');
        request.get(`${url}/api/signin`)
        .set({
          Authorization: 'Basic Random Text'
        })
        .end((err, res) => {
          expect(res.status).to.equal(401);
          done();
        });
      });
    });
    describe('With Username authorizationbut not password', function(){
      before(done => {
        let user = new User(exampleUser);
        user.generatePasswordHash(exampleUser.password)
        .then(user => user.save())
        .then(user => {
          this.tempUser = user;
          done();
        })
        .catch(done);
      });
      after(done => {
        User.remove({})
        .then(() => done())
        .catch(done);
      });
      it('should return a token', done => {
        debug('Signin Get');
        request.get(`${url}/api/signin`)
        .set({
          Authorization: 'Basic username:'
        })
        .end((err, res) => {
          expect(res.status).to.equal(401);
          done();
        });
      });
    });
  });
  describe('Get /', function(){
    describe('I wouldnt know how to error this', function(){
      it('should return a message', done => {
        request.get(`${url}/`)
        .end((err, res) => {
          expect(res.text).to.equal('This is working!!');
          done();
        });
      });
    });
  });
});


text:
<?php

namespace TypedPHP\Optional;

class None
{
    /**
     * @param string $method
     * @param array  $parameters
     *
     * @return $this
     */
    public function __call($method, $parameters)
    {
        return $this;
    }

    /**
     * @param mixed $then
     *
     * @return null
     */
    public function value(callable $then = null)
    {
        return null;
    }

    /**
     * @param mixed $then
     *
     * @return $this
     */
    public function none(callable $then = null)
    {
        $then();
        return $this;
    }
}


text:
 /**
 */
#include "PosAndEM.h"
#include "posand-support.h"

PosAndEM::PosAndEM() {
}

PosAndEM::~PosAndEM() {
}

bool PosAndEM::run(Globals* g, const vector<string>& args) {
  bool success=true;

	if (args.size() != 6) {
		cerr << "Wrong number of arguments: need 6" << endl;
		throw UnexpectedException();
	}

  int shipnum = atoi(args[0].c_str());
  int linenum = atoi(args[1].c_str());
  string line_num_type = string(args[2]);
  bool aggregate = bool(atoi(args[3].c_str()));
  //bool smart = bool(atoi(args[4].c_str()));
  bool smart = true;
  bool parallel = bool(atoi(args[4].c_str()));
  int testnum = atoi(args[5].c_str());

	system("./flushCache");

  StopWatch stopWatch;
  stopWatch.start();

  ROSAM* am = new ROSAM("LMSHIPDATERLE", 1);
  RLEDataSource* shipdate2 = new RLEDataSource(am, false);

  DataSource* quant1 = getLineNumDS(line_num_type);

  Predicate* pred2 = new Predicate(Predicate::OP_LESS_THAN);
  pred2->setRHS(shipnum);

  Predicate* pred3 = new Predicate(Predicate::OP_LESS_THAN);
  pred3->setRHS(linenum);

  Operator* srcs[2]={shipdate2,quant1};
  Predicate* preds[2]={pred2,pred3};
  int indexes[2]={0,1};
  Filter* filter = new Filter(srcs, 2, preds, 2, indexes);

  // For smart filtering
  if (smart) {
  	filter->makeSmart();
  }

  if (parallel)
    filter->setDoParallel();

  EMHashSum* emha = NULL;
  if (aggregate) {
  	emha = new EMHashSum(filter, 0, 1, 2);
  	emha->setHashFunction(new IdentityHashFunction(11000));
  	emha->setHashTableSize(11000);
  }
  char* temp8 = new char[128];
  sprintf(temp8, "test%dPosAndEMshipnum%dlinenum%d.out", testnum, shipnum, linenum);
  //BlockPrinter* bPrint=new BlockPrinter(srcs, numCols, 2, temp8);
  //bPrint->printColumns();

  SBlock* sb;
  SPair* p;
  int nseen = 0;
  //int* temp;
  std::ofstream outstream;
  outstream.open(temp8);
  Operator* tupSrc = aggregate ? static_cast<Operator*>(emha) : static_cast<Operator*>(filter);

  //SBlockPrinter* bPrint1 = NULL;
  //bPrint1=new SBlockPrinter(tupSrc, 3, temp8);
  //bPrint1->printColumns();
  while ((sb = tupSrc->getNextSValBlock(0))) {
    while (sb->hasNext()) {
      p = sb->getNext();
      //temp = (int*)(p->value);
      //for (int i=0; i < 1; i++) {
      //outstream << temp[1] << ",";
      //}
      //outstream << temp[2] << endl;
      ++nseen;
    }
  }
  outstream.close();
  string smartstr = parallel ? "parallel" : "pipelined";
  printEndOfTest("PosAndEM-" + smartstr, testnum, shipnum, linenum, line_num_type, aggregate, nseen, stopWatch.stop());
  return success;
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Persistance
</TITLE>

<META NAME="keywords" CONTENT="org.cidrz.webapp.dynasite.logic.Persistance class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.cidrz.webapp.dynasite.logic

Class Persistance

java.lang.Object
  org.cidrz.webapp.dynasite.logic.Persistance

All Implemented Interfaces:
javax.servlet.Filter

public class Persistance
extends java.lang.Object
implements javax.servlet.Filter

Filter which manages a ThreadLocal hibernate session.  Obtain the session
 by calling Persistance.getSession().  Define the JNDI name of the
 hibernate session factory as an init param to the filter in your web.xml.

Author:

Jeff Schnitzer

Field Summary

protected static net.sf.hibernate.SessionFactory
factory

static java.lang.String
HIBERNATE_FACTORY_JNDI_DEFAULT

          Default value if no init param is set.

static java.lang.String
HIBERNATE_FACTORY_JNDI_PARAM

          Filter init param which defines the JNDI name for the hibernate factory

protected static java.lang.ThreadLocal
hibernateHolder

          Holds the current hibernate session, if one has been created.

Constructor Summary

Persistance()

Method Summary

 void
destroy()

 void
doFilter(javax.servlet.ServletRequest request,
         javax.servlet.ServletResponse response,
         javax.servlet.FilterChain chain)

static net.sf.hibernate.Session
getSession()

          ONLY ever call this method from within the context of a servlet request
 (specifically, one that has been associated with this filter).

static net.sf.hibernate.SessionFactory
getSessionFactory()

 void
init(javax.servlet.FilterConfig filterConfig)

static void
rollback(net.sf.hibernate.Transaction tx)

          This is a simple method to reduce the amount of code that needs
 to be written every time hibernate is used.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

HIBERNATE_FACTORY_JNDI_PARAM

public static final java.lang.String HIBERNATE_FACTORY_JNDI_PARAM

Filter init param which defines the JNDI name for the hibernate factory

See Also:
Constant Field Values

HIBERNATE_FACTORY_JNDI_DEFAULT

public static final java.lang.String HIBERNATE_FACTORY_JNDI_DEFAULT

Default value if no init param is set.

See Also:
Constant Field Values

hibernateHolder

protected static java.lang.ThreadLocal hibernateHolder

Holds the current hibernate session, if one has been created.

factory

protected static net.sf.hibernate.SessionFactory factory

Constructor Detail

Persistance

public Persistance()

Method Detail

init

public void init(javax.servlet.FilterConfig filterConfig)
          throws javax.servlet.ServletException

Specified by:
init in interface javax.servlet.Filter

Throws:

javax.servlet.ServletException

doFilter

public void doFilter(javax.servlet.ServletRequest request,
                     javax.servlet.ServletResponse response,
                     javax.servlet.FilterChain chain)
              throws java.io.IOException,
                     javax.servlet.ServletException

Specified by:
doFilter in interface javax.servlet.Filter

Throws:

java.io.IOException

javax.servlet.ServletException

getSession

public static net.sf.hibernate.Session getSession()
                                           throws net.sf.hibernate.HibernateException

ONLY ever call this method from within the context of a servlet request
 (specifically, one that has been associated with this filter).  If you
 want a Hibernate session at some other time, call getSessionFactory()
 and open/close the session yourself.

Returns:
an appropriate Session object

Throws:

net.sf.hibernate.HibernateException

getSessionFactory

public static net.sf.hibernate.SessionFactory getSessionFactory()

Returns:
the hibernate session factory

rollback

public static void rollback(net.sf.hibernate.Transaction tx)

This is a simple method to reduce the amount of code that needs
 to be written every time hibernate is used.

destroy

public void destroy()

Specified by:
destroy in interface javax.servlet.Filter

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
  Remaucourt est
       un village
       géographiquement positionné dans le département des Ardennes en Champagne-Ardenne. On dénombrait 156 habitants en 2008.

À proximité de Remaucourt sont positionnées géographiquement les villes de
Seraincourt à 2 km, 242 habitants,
Hauteville située à 5 km, 115 habitants,
Doumely-Bégny localisée à 5 km, 94 habitants,
Givron à 5 km, 79 habitants,
Chappes localisée à 2 km, 92 habitants,
Lucquy située à 2 km, 524 habitants,
 entre autres. De plus, Remaucourt est située à seulement quatorze km de Rethel.

Le nombre de logements, à Remaucourt, était réparti en 2011 en trois appartements et 73 maisons soit
 un marché relativement équilibré.

Si vous envisagez de demenager à Remaucourt, vous pourrez facilement trouver une maison à vendre.


text:
namespace boost {
namespace compute {

/// \class dynamic_bitset
/// \brief The dynamic_bitset class contains a resizable bit array.
///
/// For example, to create a dynamic-bitset with space for 1000 bits on the
/// device:
/// \code
/// boost::compute::dynamic_bitset<> bits(1000, queue);
/// \endcode
///
/// The Boost.Compute \c dynamic_bitset class provides a STL-like API and is
/// modeled after the \c boost::dynamic_bitset class from Boost.
///
/// \see \ref vector "vector<T>"
template<class Block = ulong_, class Alloc = buffer_allocator<Block> >
class dynamic_bitset
{
public:
    typedef Block block_type;
    typedef Alloc allocator_type;
    typedef vector<Block, Alloc> container_type;
    typedef typename container_type::size_type size_type;

    BOOST_STATIC_CONSTANT(size_type, bits_per_block = sizeof(block_type) * CHAR_BIT);
    BOOST_STATIC_CONSTANT(size_type, npos = static_cast<size_type>(-1));

    /// Creates a new dynamic bitset with storage for \p size bits. Initializes
    /// all bits to zero.
    dynamic_bitset(size_type size, command_queue &queue)
        : m_bits(size / sizeof(block_type), queue.get_context()),
          m_size(size)
    {
        // initialize all bits to zero
        reset(queue);
    }

    /// Creates a new dynamic bitset as a copy of \p other.
    dynamic_bitset(const dynamic_bitset &other)
        : m_bits(other.m_bits),
          m_size(other.m_size)
    {
    }

    /// Copies the data from \p other to \c *this.
    dynamic_bitset& operator=(const dynamic_bitset &other)
    {
        if(this != &other){
            m_bits = other.m_bits;
            m_size = other.m_size;
        }

        return *this;
    }

    /// Destroys the dynamic bitset.
    ~dynamic_bitset()
    {
    }

    /// Returns the size of the dynamic bitset.
    size_type size() const
    {
        return m_size;
    }

    /// Returns the number of blocks to store the bits in the dynamic bitset.
    size_type num_blocks() const
    {
        return m_bits.size();
    }

    /// Returns the maximum possible size for the dynamic bitset.
    size_type max_size() const
    {
        return m_bits.max_size() * bits_per_block;
    }

    /// Returns \c true if the dynamic bitset is empty (i.e. \c size() == \c 0).
    bool empty() const
    {
        return size() == 0;
    }

    /// Returns the number of set bits (i.e. '1') in the bitset.
    size_type count(command_queue &queue) const
    {
        ulong_ count = 0;
        transform_reduce(
            m_bits.begin(),
            m_bits.end(),
            &count,
            popcount<block_type>(),
            plus<ulong_>(),
            queue
        );
        return static_cast<size_type>(count);
    }

    /// Resizes the bitset to contain \p num_bits. If the new size is greater
    /// than the current size the new bits are set to zero.
    void resize(size_type num_bits, command_queue &queue)
    {
        // resize bits
        const size_type current_block_count = m_bits.size();
        m_bits.resize(num_bits * bits_per_block, queue);

        // fill new block with zeros (if new blocks were added)
        const size_type new_block_count = m_bits.size();
        if(new_block_count > current_block_count){
            fill_n(
                m_bits.begin() + current_block_count,
                new_block_count - current_block_count,
                block_type(0),
                queue
            );
        }

        // store new size
        m_size = num_bits;
    }

    /// Sets the bit at position \p n to \c true.
    void set(size_type n, command_queue &queue)
    {
        set(n, true, queue);
    }

    /// Sets the bit at position \p n to \p value.
    void set(size_type n, bool value, command_queue &queue)
    {
        const size_type bit = n % bits_per_block;
        const size_type block = n / bits_per_block;

        // load current block
        block_type block_value;
        copy_n(m_bits.begin() + block, 1, &block_value, queue);

        // update block value
        if(value){
            block_value |= (size_type(1) << bit);
        }
        else {
            block_value &= ~(size_type(1) << bit);
        }

        // store new block
        copy_n(&block_value, 1, m_bits.begin() + block, queue);
    }

    /// Returns \c true if the bit at position \p n is set (i.e. '1').
    bool test(size_type n, command_queue &queue)
    {
        const size_type bit = n % (sizeof(block_type) * CHAR_BIT);
        const size_type block = n / (sizeof(block_type) * CHAR_BIT);

        block_type block_value;
        copy_n(m_bits.begin() + block, 1, &block_value, queue);

        return block_value & (size_type(1) << bit);
    }

    /// Flips the value of the bit at position \p n.
    void flip(size_type n, command_queue &queue)
    {
        set(n, !test(n, queue), queue);
    }

    /// Returns \c true if any bit in the bitset is set (i.e. '1').
    bool any(command_queue &queue) const
    {
        return any_of(
            m_bits.begin(), m_bits.end(), lambda::_1 != block_type(0), queue
        );
    }

    /// Returns \c true if all of the bits in the bitset are set to zero.
    bool none(command_queue &queue) const
    {
        return !any(queue);
    }

    /// Sets all of the bits in the bitset to zero.
    void reset(command_queue &queue)
    {
        fill(m_bits.begin(), m_bits.end(), block_type(0), queue);
    }

    /// Sets the bit at position \p n to zero.
    void reset(size_type n, command_queue &queue)
    {
        set(n, false, queue);
    }

    /// Empties the bitset (e.g. \c resize(0)).
    void clear()
    {
        m_bits.clear();
    }

    /// Returns the allocator used to allocate storage for the bitset.
    allocator_type get_allocator() const
    {
        return m_bits.get_allocator();
    }

private:
    container_type m_bits;
    size_type m_size;
};

} // end compute namespace
} // end boost namespace

#endif // BOOST_COMPUTE_CONTAINER_DYNAMIC_BITSET_HPP


text:
/*
 * string.h
 *
 * Definitions for memory and string functions.
 */

#ifndef _STRING_H_
#define	_STRING_H_

#include "_ansi.h"
#include <sys/reent.h>
#include <sys/cdefs.h>
#include <sys/features.h>

#define __need_size_t
#define __need_NULL
#include <stddef.h>

#if __POSIX_VISIBLE >= 200809
#include <xlocale.h>
#endif

#if __BSD_VISIBLE
#include <strings.h>
#endif

_BEGIN_STD_C

void *	 memchr (const void *, int, size_t);
int 	 memcmp (const void *, const void *, size_t);
void *	 memcpy (void *__restrict, const void *__restrict, size_t);
void *	 memmove (void *, const void *, size_t);
void *	 memset (void *, int, size_t);
char 	*strcat (char *__restrict, const char *__restrict);
char 	*strchr (const char *, int);
int	 strcmp (const char *, const char *);
int	 strcoll (const char *, const char *);
char 	*strcpy (char *__restrict, const char *__restrict);
size_t	 strcspn (const char *, const char *);
char 	*strerror (int);
size_t	 strlen (const char *);
char 	*strncat (char *__restrict, const char *__restrict, size_t);
int	 strncmp (const char *, const char *, size_t);
char 	*strncpy (char *__restrict, const char *__restrict, size_t);
char 	*strpbrk (const char *, const char *);
char 	*strrchr (const char *, int);
size_t	 strspn (const char *, const char *);
char 	*strstr (const char *, const char *);
#ifndef _REENT_ONLY
char 	*strtok (char *__restrict, const char *__restrict);
#endif
size_t	 strxfrm (char *__restrict, const char *__restrict, size_t);

#if __POSIX_VISIBLE >= 200809
int	 strcoll_l (const char *, const char *, locale_t);
char	*strerror_l (int, locale_t);
size_t	 strxfrm_l (char *__restrict, const char *__restrict, size_t, locale_t);
#endif
#if __MISC_VISIBLE || __POSIX_VISIBLE
char 	*strtok_r (char *__restrict, const char *__restrict, char **__restrict);
#endif
#if __BSD_VISIBLE
int	 timingsafe_bcmp (const void *, const void *, size_t);
int	 timingsafe_memcmp (const void *, const void *, size_t);
#endif
#if __MISC_VISIBLE || __POSIX_VISIBLE
void *	 memccpy (void *__restrict, const void *__restrict, int, size_t);
#endif
#if __GNU_VISIBLE
void *	 mempcpy (void *, const void *, size_t);
void *	 memmem (const void *, size_t, const void *, size_t);
void *	 memrchr (const void *, int, size_t);
void *	 rawmemchr (const void *, int);
#endif
#if __POSIX_VISIBLE >= 200809
char 	*stpcpy (char *__restrict, const char *__restrict);
char 	*stpncpy (char *__restrict, const char *__restrict, size_t);
#endif
#if __GNU_VISIBLE
char	*strcasestr (const char *, const char *);
char 	*strchrnul (const char *, int);
#endif
#if __MISC_VISIBLE || __POSIX_VISIBLE >= 200809 || __XSI_VISIBLE >= 4
char 	*strdup (const char *);
#endif
char 	*_strdup_r (struct _reent *, const char *);
#if __POSIX_VISIBLE >= 200809
char 	*strndup (const char *, size_t);
#endif
char 	*_strndup_r (struct _reent *, const char *, size_t);

/* There are two common strerror_r variants.  If you request
   _GNU_SOURCE, you get the GNU version; otherwise you get the POSIX
   version.  POSIX requires that #undef strerror_r will still let you
   invoke the underlying function, but that requires gcc support.  */
#if __GNU_VISIBLE
char	*strerror_r (int, char *, size_t);
#elif __POSIX_VISIBLE >= 200112
# ifdef __GNUC__
int	strerror_r (int, char *, size_t)
#ifdef __ASMNAME
             __asm__ (__ASMNAME ("__xpg_strerror_r"))
#endif
  ;
# else
int	__xpg_strerror_r (int, char *, size_t);
#  define strerror_r __xpg_strerror_r
# endif
#endif

/* Reentrant version of strerror.  */
char *	_strerror_r (struct _reent *, int, int, int *);

#if __BSD_VISIBLE
size_t	strlcat (char *, const char *, size_t);
size_t	strlcpy (char *, const char *, size_t);
#endif
#if __POSIX_VISIBLE >= 200809
size_t	 strnlen (const char *, size_t);
#endif
#if __BSD_VISIBLE
char 	*strsep (char **, const char *);
#endif
#if __BSD_VISIBLE
char    *strnstr(const char *, const char *, size_t) __pure;
#endif

#if __MISC_VISIBLE
char	*strlwr (char *);
char	*strupr (char *);
#endif

#ifndef DEFS_H	/* Kludge to work around problem compiling in gdb */
char	*strsignal (int __signo);
#endif

#ifdef __CYGWIN__
int	strtosigno (const char *__name);
#endif

#if __GNU_VISIBLE
int	 strverscmp (const char *, const char *);
#endif

#if __GNU_VISIBLE && defined(__GNUC__)
#define strdupa(__s) \
	(__extension__ ({const char *__sin = (__s); \
			 size_t __len = strlen (__sin) + 1; \
			 char * __sout = (char *) __builtin_alloca (__len); \
			 (char *) memcpy (__sout, __sin, __len);}))
#define strndupa(__s, __n) \
	(__extension__ ({const char *__sin = (__s); \
			 size_t __len = strnlen (__sin, (__n)) + 1; \
			 char *__sout = (char *) __builtin_alloca (__len); \
			 __sout[__len-1] = '\0'; \
			 (char *) memcpy (__sout, __sin, __len-1);}))
#endif /* __GNU_VISIBLE && __GNUC__ */

/* There are two common basename variants.  If you do NOT #include <libgen.h>
   and you do

     #define _GNU_SOURCE
     #include <string.h>

   you get the GNU version.  Otherwise you get the POSIX versionfor which you
   should #include <libgen.h>i for the function prototype.  POSIX requires that
   #undef basename will still let you invoke the underlying function.  However,
   this also implies that the POSIX version is used in this case.  That's made
   sure here. */
#if __GNU_VISIBLE && !defined(basename)
# define basename basename
char	*__nonnull ((1)) basename (const char *) __asm__(__ASMNAME("__gnu_basename"));
#endif

#include <sys/string.h>

_END_STD_C

#if __SSP_FORTIFY_LEVEL > 0
#include <ssp/string.h>
#endif

#endif /* _STRING_H_ */


text:
#ifndef RUBY_OPENCV_CVCHAIN_H
#define RUBY_OPENCV_CVCHAIN_H
#include "opencv.h"

#define __NAMESPACE_BEGIN_CVCHAIN namespace cCvChain {
#define __NAMESPACE_END_CVCHAIN }

__NAMESPACE_BEGIN_OPENCV
__NAMESPACE_BEGIN_CVCHAIN

VALUE rb_class();

void define_ruby_class();

VALUE rb_allocate(VALUE klass);

VALUE rb_initialize(int argc, VALUE *argv, VALUE self);
VALUE rb_origin(VALUE self);
VALUE rb_set_origin(VALUE self, VALUE origin);
VALUE rb_codes(VALUE self);
VALUE rb_points(VALUE self);
VALUE rb_approx_chains(int argc, VALUE *argv, VALUE self);

VALUE new_object();

__NAMESPACE_END_CVCHAIN

inline CvChain*
CVCHAIN(VALUE object){
  CvChain *ptr;
  Data_Get_Struct(object, CvChain, ptr);
  return ptr;
}

__NAMESPACE_END_OPENCV

#endif // RUBY_OPENCV_CVCHAIN_H


text:
package reflect

import (
	"testing"
)

func TestAssertEqualType(t *testing.T) {
	t1 := &Type{
		Name:    "Int",
		Package: "types",
		Star:    true,
	}
	t2 := &Type{
		Name:    "String",
		Package: "types",
		Star:    true,
	}
	if err := AssertEqualType(t1, t1); err != nil {
		t.Errorf("Nil is expected when input parameters are identical, got error instead: %s.", err)
	}
	if err := AssertEqualType(t1, nil); err == nil {
		t.Errorf("Error is expected when one of the types is nil while another is not. Got nil.")
	}
	if err := AssertEqualType(t1, t2); err == nil {
		t.Errorf("Error expected as %#v != %#v. Got nil.", t1, t2)
	}
}

func TestAssertEqualArg(t *testing.T) {
	if err := AssertEqualArg(&Arg{}, nil); err == nil {
		t.Errorf("One of the arguments if nil, while another is not. Error expected, got nil.")
	}

	if err := AssertEqualArg(&Arg{Name: "arg1"}, &Arg{Name: "arg2"}); err == nil {
		t.Errorf("Arguments have different names. Error expected, got nil.")
	}

	if err := AssertEqualArg(&Arg{Name: "arg", Tag: "1"}, &Arg{Name: "arg", Tag: "2"}); err == nil {
		t.Errorf("Arguments have different tags. Error expected, got nil.")
	}

	a := &Arg{
		Name: "page",
		Type: &Type{
			Name: "int",
		},
	}
	if err := AssertEqualArg(a, a); err != nil {
		t.Errorf("Equal arguments, nil expected. Got %s.", err)
	}
}

func TestAssertEqualArgs(t *testing.T) {
	a1 := Args{
		{
			Name: "arg2",
			Type: &Type{
				Name: "type2",
			},
		},
		{
			Name: "arg1",
			Type: &Type{
				Name: "type1",
			},
		},
	}
	a2 := Args{
		{
			Name: "arg1",
			Type: &Type{
				Name: "type1",
			},
		},
	}
	if err := AssertEqualArgs(a1, a2); err == nil {
		t.Errorf("Argument slices have different length. Error expected, got nil.")
	}
	if err := AssertEqualArgs(Args{a1[0]}, a2); err == nil {
		t.Errorf("Arguments are different. Error expected, got nil.")
	}
	if err := AssertEqualArgs(a1, a1); err != nil {
		t.Errorf("Nil expected, argument slices are equal. Got error: %s.", err)
	}
}

func TestAssertEqualFunc(t *testing.T) {
	if err := AssertEqualFunc(&Func{}, nil); err == nil {
		t.Error("One of the funcs is nil while another is not. Error expected, got nil.")
	}
	if err := AssertEqualFunc(nil, nil); err != nil {
		t.Errorf("Both functions are nil. Nil expected, got error: %s.", err)
	}
	if err := AssertEqualFunc(&Func{Name: "f1"}, &Func{Name: "f2"}); err == nil {
		t.Error("Functions have different names. Error expected, got nil.")
	}
	if err := AssertEqualFunc(&Func{Name: "f", File: "x1"}, &Func{Name: "f", File: "x2"}); err == nil {
		t.Error("Functions are from different files. Error expected, got nil.")
	}
	if err := AssertEqualFunc(&Func{Comments: Comments{}}, &Func{}); err == nil {
		t.Error("Functions have different comments. Error expected, got nil.")
	}
	if err := AssertEqualFunc(&Func{Recv: &Arg{}}, &Func{}); err == nil {
		t.Error("Functions have different receivers. Error expected, got nil.")
	}
	if err := AssertEqualFunc(&Func{Params: Args{{}}}, &Func{}); err == nil {
		t.Error("Functions have different parameters. Error expected, got nil.")
	}
	if err := AssertEqualFunc(&Func{}, &Func{}); err != nil {
		t.Errorf("Functions are identical. Nil expected, got error: %s.", err)
	}
}

func TestAssertEqualFuncs(t *testing.T) {
	fs1 := Funcs{
		{
			Name: "f2",
			File: "test.go",
		},
		{
			Name: "f1",
			File: "test.go",
		},
	}
	fs2 := Funcs{
		{
			Name: "f1",
			File: "test.go",
		},
	}
	if err := AssertEqualFuncs(fs1, fs2); err == nil {
		t.Error("Functions have different length. Error expected, got nil.")
	}
	if err := AssertEqualFuncs(Funcs{fs1[0]}, fs2); err == nil {
		t.Error("Functions are different. Error expected, got nil.")
	}
	if err := AssertEqualFuncs(fs1, fs1); err != nil {
		t.Errorf("Function lists are identical. Nil expected, got %s.", err)
	}
}

func TestAssertEqualStruct(t *testing.T) {
	if err := AssertEqualStruct(&Struct{}, nil); err == nil {
		t.Error("One of the structures is nil while another is not. Error expected, got nil.")
	}
	if err := AssertEqualStruct(nil, nil); err != nil {
		t.Errorf("Both structures are nil. Nil expected, got error: %s.", err)
	}
	if err := AssertEqualStruct(&Struct{Name: "s1"}, &Struct{Name: "s2"}); err == nil {
		t.Error("Structs have different names. Error expected, got nil.")
	}
	if err := AssertEqualStruct(&Struct{Name: "s", File: "s1"}, &Struct{Name: "s", File: "s2"}); err == nil {
		t.Error("Structs are from different files. Error expected, got nil.")
	}
	if err := AssertEqualStruct(&Struct{Comments: Comments{}}, &Struct{}); err == nil {
		t.Error("Structs have different comments. Error expected, got nil.")
	}
	if err := AssertEqualStruct(&Struct{Name: "f"}, &Struct{Name: "f"}); err != nil {
		t.Errorf("Structs are equal to each other. Nil expected, got error: %s.", err)
	}
}

func TestAssertEqualStructs(t *testing.T) {
	ss1 := Structs{
		{
			Name: "s2",
			File: "f2",
		},
		{
			Name: "s1",
			File: "f1",
		},
	}
	ss2 := Structs{
		{
			Name: "s1",
			File: "f1",
		},
	}
	if err := AssertEqualStructs(ss1, ss2); err == nil {
		t.Errorf("Lists of structs have different lengths. Error expected, got nil.")
	}
	if err := AssertEqualStructs(Structs{ss1[0]}, ss2); err == nil {
		t.Errorf("Lists are different. Error expected, got nil.")
	}
	if err := AssertEqualStructs(ss1, ss1); err != nil {
		t.Errorf("Lists of structs are identical. Nil expected, got error: %s.", err)
	}
}

func TestAssertEqualMethods(t *testing.T) {
	ms1 := Methods{
		"App": Funcs{
			{
				Name: "f1",
				File: "app.go",
			},
		},
		"Controller": Funcs{
			{
				Name: "f1",
				File: "app.go",
			},
		},
	}
	ms2 := Methods{
		"App": Funcs{
			{
				Name: "f1",
				File: "app.go",
			},
		},
	}
	if err := AssertEqualMethods(ms1, ms2); err == nil {
		t.Errorf("Methods groups have different length. Error expected, got nil.")
	}
	if err := AssertEqualMethods(Methods{"Controller": ms1["Controller"]}, ms2); err == nil {
		t.Errorf("Methods are different. Error expected, got nil.")
	}
	if err := AssertEqualMethods(ms1, ms1); err != nil {
		t.Errorf("Methods are identical. Nil expected, got error: %s.", err)
	}
}

func TestAssertEqualPkg(t *testing.T) {
	if err := AssertEqualPkg(&Package{}, nil); err == nil {
		t.Error("One of the packages is nil while another is not. Error expected, got nil.")
	}
	if err := AssertEqualPkg(nil, nil); err != nil {
		t.Errorf("Both packages are nil. Nil expected, got error: %s.", err)
	}
	if err := AssertEqualPkg(&Package{Name: "p1"}, &Package{Name: "p2"}); err == nil {
		t.Error("Packages have different names. Error expected, got nil.")
	}
	if err := AssertEqualPkg(&Package{Name: "p", Imports: Imports{"x": map[string]string{}}}, &Package{Name: "p"}); err == nil {
		t.Error("Packages have imports. Error expected, got nil.")
	}
	if err := AssertEqualPkg(&Package{Name: "p", Structs: Structs{{}}}, &Package{Name: "p"}); err == nil {
		t.Error("Packages have different structs. Error expected, got nil.")
	}
	if err := AssertEqualPkg(&Package{Name: "p", Funcs: Funcs{{}}}, &Package{Name: "p"}); err == nil {
		t.Error("Packages have different functions. Error expected, got nil.")
	}
	if err := AssertEqualPkg(&Package{Name: "p"}, &Package{Name: "p"}); err != nil {
		t.Errorf("Packages are identical. Nil expected, got error: %s.", err)
	}
}


text:
(function(root) {
  root.App = {
    // A component is a top level backbone view
    // and it gets automatically instantiated in main
    Components: {},
    // coffee classes go here
    Views: {},
    Models: {},
    Collections: {},
    Templates: {},
    // awesome sauce
    Dispatch: _.clone(Backbone.Events)
  }
})(window);


text:
package org.apache.isis.core.metamodel.facets.object.notpersistable.notpersistableannot;

import org.apache.isis.applib.annotation.NotPersistable;
import org.apache.isis.core.metamodel.facetapi.FacetHolder;
import org.apache.isis.core.metamodel.facets.object.notpersistable.NotPersistableFacetImpl;

public class NotPersistableFacetAnnotation extends NotPersistableFacetImpl {

    public NotPersistableFacetAnnotation(final NotPersistable.By value, final FacetHolder holder) {
        super(value, holder);
    }

}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.8"/>
<title>Assimp: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Assimp
    v3.1.1 (June 2014)

Main Page

Related Pages

Namespaces

Classes

Files

Class List

Class Index

Class Hierarchy

Class Members

Assimp

Exporter

ExportFormatEntry

Assimp::Exporter::ExportFormatEntry Member List

This is the complete list of members for Assimp::Exporter::ExportFormatEntry, including all inherited members.

ExportFormatEntry(const char *pId, const char *pDesc, const char *pExtension, fpExportFunc pFunction, unsigned int pEnforcePP=0u)	Assimp::Exporter::ExportFormatEntry	inline

ExportFormatEntry()	Assimp::Exporter::ExportFormatEntry	inline

mDescription	Assimp::Exporter::ExportFormatEntry

mEnforcePP	Assimp::Exporter::ExportFormatEntry

mExportFunction	Assimp::Exporter::ExportFormatEntry

<address class="footer">
Generated on Wed Feb 18 2015 13:46:03 for Assimp by

 1.8.8
</address>


text:
package main

// Stdlib
import "fmt"
import "log"
import "flag"
import "time"
import "strconv"
import "strings"
import "net/http"
import "net/http/httputil"

func RequestDumpHandler(resp http.ResponseWriter, req *http.Request) {
	request_dump, err := httputil.DumpRequest(req, true)

	t := time.Now()
	fmt.Printf("[%s] %s, with dump:\n", t.Format(time.StampMilli), req.URL.String())

	if err == nil {
		fmt.Printf("---\n")
		fmt.Printf("%s", request_dump)
		fmt.Printf("---\n")
		resp.Write([]byte("Request received\n"))
	} else {
		fmt.Printf("Request unable to be output\n")
		resp.Write([]byte("Could not handle request\n"))
	}
}

func HttpResponseCodeHandler(resp http.ResponseWriter, req *http.Request) {
	parts := strings.Split(req.URL.Path, "/")

	if len(parts) == 3 && len(parts[2]) > 0 {
		if i, err := strconv.Atoi(parts[2]); err == nil {
			resp.WriteHeader(i)
		} else {
			resp.Write([]byte(fmt.Sprintf("Unable to parse int from '%s'\n", parts[2])))
		}
	} else {
		resp.Write([]byte("Format for response-code manipulation is: '/code/{CODE}'\n"))
	}

	t := time.Now()
	fmt.Printf("[%s] %s\n", t.Format(time.StampMilli), req.URL.String())
}

func main() {
	addr := flag.String("address", "", "the address to bind to. Default is 0.0.0.0")
	port := flag.String("port", "8080", "the local port to bind to")

	flag.Parse()

	http.HandleFunc("/code/", HttpResponseCodeHandler)
	http.HandleFunc("/", RequestDumpHandler)

	fmt.Printf("httpecho starting up on %s:%s...\n", *addr, *port)
	log.Fatal(http.ListenAndServe(fmt.Sprintf("%s:%s", *addr, *port), nil))
}


text:
package de.flapdoodle.guava;

public abstract class Logics {

  private Logics() {
      // no instance
  }

  public static boolean xor(boolean a, boolean b) {
      return (a & !b) || (b & !a);
  }

  public static boolean xor(Object a, Object b) {
      return xor(a!=null, b!=null);
  }
}


text:
class RemoveCompanyIdFromJobVacancies < ActiveRecord::Migration
  def change
    remove_column :job_vacancies, :company_id
  end
end


text:
using System.Collections.Generic;
using ElectronicInvoice.Produce.Helper;
using NUnit.Framework;

namespace ElectronicInvoiceTests.Infrastructure.Helper
{
    [TestFixture]
    public class JsonConfigTest
    {
        [Test]
        public void JsonFileTest()
        {
            string GovAppId = "GovAppId123";
            string GovAPIKey = "GovAPIKey123";
            string IsMockAPI = "IsMockAPI123";

            Dictionary<string, string> apiUrlTable = new Dictionary<string, string>()
            {
                {"ApiURL1","ApiURL1"},
                {"ApiURL2","ApiURL2"},
                {"ApiURL3","ApiURL3"}
            };

            string JsonData = @"{
	""GovAppId"":""GovAppId123"",
	""GovAPIKey"":""GovAPIKey123"",
	""IsMockAPI"":""IsMockAPI123"",
	""ApiURLTable"":{
		""ApiURL1"":""ApiURL1"",
		""ApiURL2"":""ApiURL2"",
		""ApiURL3"":""ApiURL3""
	}
}";
            JsonConfig config = new JsonConfig(JsonData);
            var actApiUrlTable = config.GetApiURLTable();

            Assert.AreEqual(config.GovAppId, GovAppId);
            Assert.AreEqual(config.GovAPIKey, GovAPIKey);
            Assert.AreEqual(config.IsMockAPI, IsMockAPI);
            Assert.AreEqual(actApiUrlTable["ApiURL1"], apiUrlTable["ApiURL1"]);
            Assert.AreEqual(actApiUrlTable["ApiURL2"], apiUrlTable["ApiURL2"]);
            Assert.AreEqual(actApiUrlTable["ApiURL3"], apiUrlTable["ApiURL3"]);
        }
    }
}


text:
namespace media {

class AudioFramesImpl;
class CdmAllocator;
class CdmFileIO;
class CdmWrapper;

// Called when the CDM needs a FileIO object from the host to do file IO
// operations. Returns NULL if a FileIO object cannot be obtained. Once a
// valid FileIO object is returned, |client| must be valid until
// FileIO::Close() is called. The CDM can call this method multiple times
// to operate on different files.
using CreateCdmFileIOCB =
    base::Callback<std::unique_ptr<CdmFileIO>(cdm::FileIOClient* client)>;

class MEDIA_EXPORT CdmAdapter : public ContentDecryptionModule,
                                public CdmContext,
                                public Decryptor,
                                NON_EXPORTED_BASE(public cdm::Host_8) {
 public:
  // Create the CDM using |cdm_path| and initialize it using |key_system| and
  // |cdm_config|. |allocator| is to be used whenever the CDM needs memory
  // and to create VideoFrames. |file_io_provider| is to be used whenever the
  // CDM needs access to the file system. Callbacks will be used for events
  // generated by the CDM. |cdm_created_cb| will be called when the CDM is
  // loaded and initialized.
  static void Create(
      const std::string& key_system,
      const base::FilePath& cdm_path,
      const CdmConfig& cdm_config,
      std::unique_ptr<CdmAllocator> allocator,
      const CreateCdmFileIOCB& create_cdm_file_io_cb,
      const SessionMessageCB& session_message_cb,
      const SessionClosedCB& session_closed_cb,
      const SessionKeysChangeCB& session_keys_change_cb,
      const SessionExpirationUpdateCB& session_expiration_update_cb,
      const CdmCreatedCB& cdm_created_cb);

  // ContentDecryptionModule implementation.
  void SetServerCertificate(const std::vector<uint8_t>& certificate,
                            std::unique_ptr<SimpleCdmPromise> promise) final;
  void CreateSessionAndGenerateRequest(
      CdmSessionType session_type,
      EmeInitDataType init_data_type,
      const std::vector<uint8_t>& init_data,
      std::unique_ptr<NewSessionCdmPromise> promise) final;
  void LoadSession(CdmSessionType session_type,
                   const std::string& session_id,
                   std::unique_ptr<NewSessionCdmPromise> promise) final;
  void UpdateSession(const std::string& session_id,
                     const std::vector<uint8_t>& response,
                     std::unique_ptr<SimpleCdmPromise> promise) final;
  void CloseSession(const std::string& session_id,
                    std::unique_ptr<SimpleCdmPromise> promise) final;
  void RemoveSession(const std::string& session_id,
                     std::unique_ptr<SimpleCdmPromise> promise) final;
  CdmContext* GetCdmContext() final;

  // CdmContext implementation.
  Decryptor* GetDecryptor() final;
  int GetCdmId() const final;

  // Decryptor implementation.
  void RegisterNewKeyCB(StreamType stream_type,
                        const NewKeyCB& key_added_cb) final;
  void Decrypt(StreamType stream_type,
               const scoped_refptr<DecoderBuffer>& encrypted,
               const DecryptCB& decrypt_cb) final;
  void CancelDecrypt(StreamType stream_type) final;
  void InitializeAudioDecoder(const AudioDecoderConfig& config,
                              const DecoderInitCB& init_cb) final;
  void InitializeVideoDecoder(const VideoDecoderConfig& config,
                              const DecoderInitCB& init_cb) final;
  void DecryptAndDecodeAudio(const scoped_refptr<DecoderBuffer>& encrypted,
                             const AudioDecodeCB& audio_decode_cb) final;
  void DecryptAndDecodeVideo(const scoped_refptr<DecoderBuffer>& encrypted,
                             const VideoDecodeCB& video_decode_cb) final;
  void ResetDecoder(StreamType stream_type) final;
  void DeinitializeDecoder(StreamType stream_type) final;

  // cdm::Host_8 implementation.
  cdm::Buffer* Allocate(uint32_t capacity) override;
  void SetTimer(int64_t delay_ms, void* context) override;
  cdm::Time GetCurrentWallTime() override;
  void OnResolveNewSessionPromise(uint32_t promise_id,
                                  const char* session_id,
                                  uint32_t session_id_size) override;
  void OnResolvePromise(uint32_t promise_id) override;
  void OnRejectPromise(uint32_t promise_id,
                       cdm::Error error,
                       uint32_t system_code,
                       const char* error_message,
                       uint32_t error_message_size) override;
  void OnSessionMessage(const char* session_id,
                        uint32_t session_id_size,
                        cdm::MessageType message_type,
                        const char* message,
                        uint32_t message_size,
                        const char* legacy_destination_url,
                        uint32_t legacy_destination_url_size) override;
  void OnSessionKeysChange(const char* session_id,
                           uint32_t session_id_size,
                           bool has_additional_usable_key,
                           const cdm::KeyInformation* keys_info,
                           uint32_t keys_info_count) override;
  void OnExpirationChange(const char* session_id,
                          uint32_t session_id_size,
                          cdm::Time new_expiry_time) override;
  void OnSessionClosed(const char* session_id,
                       uint32_t session_id_size) override;
  void OnLegacySessionError(const char* session_id,
                            uint32_t session_id_size,
                            cdm::Error error,
                            uint32_t system_code,
                            const char* error_message,
                            uint32_t error_message_size) override;
  void SendPlatformChallenge(const char* service_id,
                             uint32_t service_id_size,
                             const char* challenge,
                             uint32_t challenge_size) override;
  void EnableOutputProtection(uint32_t desired_protection_mask) override;
  void QueryOutputProtectionStatus() override;
  void OnDeferredInitializationDone(cdm::StreamType stream_type,
                                    cdm::Status decoder_status) override;
  cdm::FileIO* CreateFileIO(cdm::FileIOClient* client) override;

 private:
  CdmAdapter(const std::string& key_system,
             const CdmConfig& cdm_config,
             std::unique_ptr<CdmAllocator> allocator,
             const CreateCdmFileIOCB& create_cdm_file_io_cb,
             const SessionMessageCB& session_message_cb,
             const SessionClosedCB& session_closed_cb,
             const SessionKeysChangeCB& session_keys_change_cb,
             const SessionExpirationUpdateCB& session_expiration_update_cb);
  ~CdmAdapter() final;

  // Load the CDM using |cdm_path| and initialize it. |promise| is resolved if
  // the CDM is successfully loaded and initialized, rejected otherwise.
  void Initialize(const base::FilePath& cdm_path,
                  std::unique_ptr<media::SimpleCdmPromise> promise);

  // Create an instance of the |key_system| CDM contained in |cdm_path|.
  // Caller owns the returned pointer. On error (unable to load, does not
  // support |key_system|, does not support an supported interface, etc.)
  // NULL will be returned.
  CdmWrapper* CreateCdmInstance(const std::string& key_system,
                                const base::FilePath& cdm_path);

  // Helper for SetTimer().
  void TimerExpired(void* context);

  // Converts audio data stored in |audio_frames| into individual audio
  // buffers in |result_frames|. Returns true upon success.
  bool AudioFramesDataToAudioFrames(
      std::unique_ptr<AudioFramesImpl> audio_frames,
      Decryptor::AudioFrames* result_frames);

  // Keep a reference to the CDM.
  base::ScopedNativeLibrary library_;

  // Used to keep track of promises while the CDM is processing the request.
  CdmPromiseAdapter cdm_promise_adapter_;

  std::unique_ptr<CdmWrapper> cdm_;
  std::string key_system_;
  CdmConfig cdm_config_;

  // Callbacks for firing session events.
  SessionMessageCB session_message_cb_;
  SessionClosedCB session_closed_cb_;
  SessionKeysChangeCB session_keys_change_cb_;
  SessionExpirationUpdateCB session_expiration_update_cb_;

  // Callbacks for deferred initialization.
  DecoderInitCB audio_init_cb_;
  DecoderInitCB video_init_cb_;

  // Callbacks for new keys added.
  NewKeyCB new_audio_key_cb_;
  NewKeyCB new_video_key_cb_;

  // Keep track of video frame natural size from the latest configuration
  // as the CDM doesn't provide it.
  gfx::Size natural_size_;

  // Keep track of audio parameters.
  int audio_samples_per_second_;
  ChannelLayout audio_channel_layout_;

  std::unique_ptr<CdmAllocator> allocator_;
  CreateCdmFileIOCB create_cdm_file_io_cb_;

  scoped_refptr<base::SingleThreadTaskRunner> task_runner_;

  // NOTE: Weak pointers must be invalidated before all other member variables.
  base::WeakPtrFactory<CdmAdapter> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(CdmAdapter);
};

}  // namespace media

#endif  // MEDIA_CDM_CDM_ADAPTER_H_


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

using System.Linq;
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;

namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
    internal partial class TaggerEventSources
    {
        private class ParseOptionChangedEventSource : AbstractWorkspaceTrackingTaggerEventSource
        {
            public ParseOptionChangedEventSource(ITextBuffer subjectBuffer, TaggerDelay delay)
                : base(subjectBuffer, delay)
            {
            }

            protected override void ConnectToWorkspace(Workspace workspace)
            {
                workspace.WorkspaceChanged += OnWorkspaceChanged;
            }

            protected override void DisconnectFromWorkspace(Workspace workspace)
            {
                workspace.WorkspaceChanged -= OnWorkspaceChanged;
            }

            private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e)
            {
                if (e.Kind == WorkspaceChangeKind.ProjectChanged)
                {
                    var oldProject = e.OldSolution.GetProject(e.ProjectId);
                    var newProject = e.NewSolution.GetProject(e.ProjectId);

                    if (!object.Equals(oldProject.ParseOptions, newProject.ParseOptions))
                    {
                        var workspace = e.NewSolution.Workspace;
                        var documentIds = workspace.GetRelatedDocumentIds(SubjectBuffer.AsTextContainer());

                        if (documentIds.Any(d => d.ProjectId == e.ProjectId))
                        {
                            this.RaiseChanged();
                        }
                    }
                }
            }
        }
    }
}


text:
import React from "react";
import classes from "./LongSGonksList.module.css";
import LongSGonkRow from "./LongSGonkRow/LongSGonkRow";
import ErrorMessage from "../../ErrorMessage/ErrorMessage";

const LongSGonksList = (props) => {
  if (props.investments === undefined) {
    return <ErrorMessage>investments</ErrorMessage>;
  }

  const investmentRows = props.investments.map((investment) => {
    return (
      <LongSGonkRow
        key={investment.id}
        searchTerm={investment.searchItem}
        buyInDate={investment.dateInvestedMilliSeconds}
        amountInvested={investment.amtInvested}
        currentValue={investment.currentValue}
        investmentId={investment.id}
        updateInfo={props.updateInfo}
      ></LongSGonkRow>
    );
  });
  return (

Search Term

Buy-in Date

Amount Invested

Current Value

Net Difference

{investmentRows}

  );
};

export default LongSGonksList;


text:
'use strict';

// Auctionitems controller
angular.module('auctionitems').controller('AuctionitemsController', ['$scope', '$http', '$stateParams', '$location', 'Authentication', 'Auctionitems',
	function($scope, $http, $stateParams, $location, Authentication, Auctionitems) {
		$scope.authentication = Authentication;
		// Create new Auctionitem
		$scope.create = function() {
			// Create new Auctionitem object
			var auctionitem = new Auctionitems ({
				name: this.name,
				description: this.description,
			 	location: this.location,
			 	buyer_name: this.buyer_name,
			 	current_bid: this.current_bid,
			 	buy_it_now: this.buy_it_now,
			 	reserve_price: this.reserve_price,
			 	auction_ended: this.auction_ended,
			 	image: this.image,
			 	category: this.category,
			 	auction_ended: this.auction_ended
			});

			// Redirect after save
			auctionitem.$save(function(response) {
				$location.path('auctionitems/' + response.id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Auctionitem
		$scope.remove = function(auctionitem) {
			if ( auctionitem ) {
				auctionitem.$remove();

				for (var i in $scope.auctionitems) {
					if ($scope.auctionitems [i] === auctionitem) {
						$scope.auctionitems.splice(i, 1);
					}
				}
			} else {
				$scope.auctionitem.$remove(function() {
					$location.path('auctionitems');
				});
			}
		};

		// Update existing Auctionitem
		$scope.update = function() {
			var auctionitem = $scope.auctionitem;

			auctionitem.$update(function() {
				$location.path('#!/auctionitems/' + auctionitem.id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Auctionitems
		$scope.find = function() {
			$scope.auctionitems = Auctionitems.query();
		};

		// Find existing Auctionitem
		$scope.findOne = function() {
			$scope.auctionitem = Auctionitems.get({
				auctionitemId: $stateParams.auctionitemId
			});
		};

		$scope.bid = function(bid) {
			var bidder = $scope.authentication.user.username;
			console.log(Auctionitems)
			console.log("Bidder", bidder);
			var auctionitem = $scope.auctionitem;
			console.log(auctionitem);
			if(bidder == auctionitem.buyer_name) {
				alert("You are the highest bidder, you dumby!");
				auctionitem.$bid(function() {
					$location.path('auctionitems/' + auctionitem.id);
				});
				return;
			}

			if(bid >= 1.05 * auctionitem.current_bid) {

				auctionitem.current_bid = bid;
				auctionitem.buyer_name = bidder;
				alert("You are the highest Bidder!");
				auctionitem.$bid(function() {
					$location.path('auctionitems/' + auctionitem.id);
				});
			} else {
				alert("Your bid is not high enough!");
				auctionitem.$bid(function() {
					$location.path('auctionitems/' + auctionitem.id);
				});
			}
		};

		$scope.search = function(searchTerm) {
			var auctionitem = $scope.auctionitem;
			$scope.search = searchTerm;
			alert("Search starting");
			auctionitem.$search(function() {
				$location.path('asearch');
			});
		};

		// Get all reviews for selected auction item
		$scope.auctionreviews = function(id) {
			var item = $scope.item;
			console.log($stateParams.auctionitemId);
			var auction_id = $stateParams.auctionitemId;
			var params = {
				itemid: auction_id
			}
			$http.get('/auctionreview?auctionid=' + auction_id).success(function(data, status, headers, config){
				console.log(data);
				$scope.auctionreviews = data;
			}).error(function(data, status, headers, config) {
				alert('error');
			});
		};

		$scope.findAllCategories = function() {
			$http.get('/categories').success(function(data, status, headers, config) {
				console.log(data);
				$scope.categories = data;
			}).error(function(data, status, headers, config) {
				alert('error');
			});
		};
	}
]);


text:
package org.wso2.carbon.esb.mediator.test.foreach;

import org.apache.axis2.AxisFault;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException;
import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;
import org.wso2.esb.integration.common.utils.ESBIntegrationTest;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Test for fix ESBJAVA-5122. Message flow includes a call mediator to fetch data and then
 * iterate over elements using foreach mediator. When done, after all elements are iterated,
 * message flow goes to beginning of the flow, making ESB iterate infinitely over.
 */
public class testInfiniteLoopingWithCallMediatorTestCase extends ESBIntegrationTest {

    @BeforeClass(alwaysRun = true)
    public void deployArtifacts() throws Exception {
        super.init();
        loadESBConfigurationFromClasspath("/artifacts/ESB/mediatorconfig/foreach/"
                + "foreach_test_message_flow_with_call.xml");
    }

    /**
     * Send a empty SOAP message and see if we get expected reply.
     *
     * @throws AxisFault                    in case of an axis2 level issue when sending
     * @throws MalformedURLException        in case of url is malformed
     * @throws AutomationFrameworkException in case of any other test suite level issue
     */
    @Test(groups = "wso2.esb", description = "Test call mediator with foreach mediator has expected message flow")
    public void testForeachMediatorMessageFlow() throws AxisFault, MalformedURLException, AutomationFrameworkException {
        Map<String, String> requestHeader = new HashMap<>();
        requestHeader.put("Content-type", "text/xml");
        requestHeader.put("SOAPAction", "urn:mediate");
        String message = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap"
                + ".org/soap/envelope/\">\n"
                + "   <soapenv:Header/>\n"
                + "   <soapenv:Body/>\n"
                + "</soapenv:Envelope>";

        HttpResponse response = HttpRequestUtil.
                doPost(new URL(getProxyServiceURLHttp("acceptProxy")), message, requestHeader);

        Assert.assertTrue(response.getData().contains("<company>wso2</company>"), "Expected response was not"
                + " received. Got " + response.getData());
    }

    @AfterClass(alwaysRun = true)
    public void stop() throws Exception {
        super.cleanup();
    }
}


text:
var express = require('express');
var expressValidator = require('express-validator');
var path = require('path');
var favicon = require('serve-favicon');
var fs = require('fs');
var logger;
var morgan = require('morgan');
var winston = require('winston');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var stylus = require('stylus');
var i18n = require('i18n');
var helmet = require('helmet');
var csrf = require('csurf');
var passport = require('passport');
var flash = require('connect-flash');
var session = require('express-session');
var methodOverride = require('method-override');
var utils = require('./utils');
var config = exports.config = require('./config');
var mail = exports.mail = require('./utils/mailer.js');
var anyandgo = exports.anyandgo = {};

// Anyandgo
anyandgo.models = [];

// Error
process.on('uncaughtException', function(err) {
      console.log("Exception", err.stack);
});

// Express
var app = exports.app = express();

app.set("envflag", config.envflag || process.env.NODE_ENV);
app.set("autologin", config.autologin || {});

// Setup vars
app.use(function(req, res, next){
  res.locals.envflag = config.envflag || process.env.NODE_ENV;
  res.locals.autologin = config.autologin || {};
  // Analytics
  if (config.analytics && config.analytics.enabled) {
    res.locals.tracking = config.analytics.tracking;
  }
  next();
});

// Database Connection
var dbConex = exports.dbConex = utils.dbConnection(config.db.domain,config.db.name,config.db.user,config.db.pass);

// DB Fixtures
if (config.fixtures && config.fixtures === "enabled") {
// Load Fixtures
require('./fixtures');
}

// Security
if (config.security && config.security === "enabled") {
    app.use(helmet());
    app.use(helmet.hidePoweredBy({ setTo: 'PHP 4.2.0' }));
    app.use(helmet.noSniff());
    app.use(helmet.frameguard('deny'));
}

// i18n setup
i18n.configure({
  // setup some locales: other locales default to en silently
  locales:[
      //global:translation:start
      //global:translation:end
      'en-us',
      'es-ar'],
  // sets a custom cookie name to parse locale settings from  - defaults to NULL
  cookie: 'lang',
  // where to store json files - defaults to './locales' relative to modules directory
  directory: __dirname + '/locales',
  defaultLocale: 'es-ar'
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// stylus setup
app.use('/css', stylus.middleware({
  src: __dirname + '/views/stylus',
  dest: __dirname + '/public/css',
  compile: function (str, path) {
    return stylus(str)
      .set('filename', path)
      .set('compress', true);
  }
}));

// app.use(favicon(__dirname + '/public/img/favicon.ico'));

// Logs
// [Predefined Formats](https://github.com/expressjs/morgan#predefined-formats)
var loggerConfigs = {
    levels: { HTTP: 0, debug: 1, info: 2, warn: 3, error: 3 },
    colors: { HTTP: 'blue', debug: 'white', info: 'green', warn: 'yellow', error: 'red' }
};
winston.addColors(loggerConfigs.colors);

if (typeof config.app.logs !== 'undefined' && config.app.logs.enabled) {
    // create a write stream (in append mode)
    //var accessLogStream = fs.createWriteStream(__dirname + '/' + config.app.logs.file, {flags: 'a'});

    logger = new winston.Logger({
        levels: loggerConfigs.levels,
        transports: [
            new winston.transports.File({
                name: 'file-log',
                level: 'HTTP',
                filename: __dirname + '/' + config.app.logs.file,
                handleExceptions: false,
                json: true,
                maxsize: 5242880, //5MB
                maxFiles: 5,
                colorize: false
            }),
            new winston.transports.Console({
                name: 'console-log',
                level: 'HTTP',
                handleExceptions: false,
                json: false,
                colorize: true
            })
        ],
        exitOnError: false
    });

    logger.stream = {
      write: function(message, encoding){
          logger.log("HTTP",message.slice(0, -1));
      }
    };

    // setup the logger
    app.use(morgan(config.app.logs.format || 'dev', {stream: logger.stream }));
    // remember to see the log:
    // $ touch access.log
    // $ tail -f access.log
} else {
    //app.use(logger('dev'));

    logger = new winston.Logger({
        levels: loggerConfigs.levels,
        transports: [
            new winston.transports.Console({
                name: 'console-log',
                level: 'HTTP',
                handleExceptions: false,
                json: false,
                colorize: true
            })
        ],
        exitOnError: false
    });

    logger.stream = {
      write: function(message, encoding){
          logger.log("HTTP",message.slice(0, -1));
      }
    };

    // setup the logger
    app.use(morgan('dev', {stream: logger.stream }));
}
exports.logger = logger;
// Log example
logger.info("Starting anyandgo...");
logger.info("For more information visit http://anyandgo.io/ ");

app.use(bodyParser.json());
app.use(expressValidator());
app.use(bodyParser.urlencoded({
  extended: true
}));
// method override + restify settings
// https://www.npmjs.org/package/express-restify-mongoose
app.use(methodOverride());
app.use(cookieParser());

app.use(express.static(path.join(__dirname, 'public')));
// i18n init parses req for language headers, cookies, etc.
app.use(i18n.init);
// Passport
app.use(session({ secret: 'secret', saveUninitialized: true, resave: true })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

// CSRF Security
// http://stackoverflow.com/questions/23997572/error-misconfigured-csrf-express-js-4
if (config.csrf && config.csrf === "enabled") {
    //app.use(csrf({ cookie: { key: 'XSRF-TOKEN' } }));
    app.use(csrf());
    // Angular
    // https://github.com/expressjs/csurf/issues/13
    // AngularJS looks for a cookie named "XSRF-TOKEN" and sets the header as "X-XSRF-TOKEN"
    /*
    app.use(function (req, res, next) {
      res.cookie('XSRF-TOKEN', req.csrfToken());
      next();
    });
    */
    app.use(function (req, res) {
        var token = req.csrfToken();
        // angular
        res.cookie('XSRF-TOKEN', req.csrfToken());
        // field
        res.locals._csrf = req.csrfToken();
        res.locals.csrf_form_html = '<input type="hidden" name="_csrf" value="' + req.csrfToken() + '" >';
        req.next();
    });
    // error handler
    app.use(function (err, req, res, next) {
      if (err.code !== 'EBADCSRFTOKEN') return next(err);

      // handle CSRF token errors here
      res.status(403);
      res.send('sorry your request was invalid');
    });
}

// used to serialize the user for the session
passport.serializeUser(function(user, done) {
    console.log(user);
    done(null, user);
});

// used to deserialize the user
passport.deserializeUser(function(user, done) {
    done(null, user);
});

// Interceptors
app.use(function(req, res, next) {
    res.locals.user = req.user;
    res.locals.flash = req.flash();
    next();
});

// Routes
require('./routes/auth');
require('./routes/main');

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err,
            title: 'error'
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {},
        title: 'error'
    });
});

module.exports = app;


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

/* EventTimes.cs --
 * Ars Magna project, http://arsmagna.ru
 * -------------------------------------------------------
 * Status: poor
 */

#region Using directives

using System.Xml.Serialization;

using JetBrains.Annotations;

using ManagedIrbis.Mapping;

using MoonSharp.Interpreter;

using Newtonsoft.Json;

#endregion

namespace ManagedIrbis.EventDb
{
    /// <summary>
    /// Время мероприятия. Поле 31.
    /// </summary>
    [PublicAPI]
    [MoonSharpUserData]
    public sealed class EventTimes
    {
        #region Constants

        /// <summary>
        /// Known subfield codes.
        /// </summary>
        public const string KnownCodes = "ab";

        /// <summary>
        /// Field tag.
        /// </summary>
        public const int Tag = 31;

        #endregion

        #region Properties

        /// <summary>
        /// Время проведения от... Подполе a.
        /// </summary>
        [CanBeNull]
        [SubField('a')]
        [XmlAttribute("from")]
        [JsonProperty("from", NullValueHandling = NullValueHandling.Ignore)]
        public string From { get; set; }

        /// <summary>
        /// Время проведения до ... Подполе b.
        /// </summary>
        [CanBeNull]
        [SubField('b')]
        [XmlAttribute("till")]
        [JsonProperty("till", NullValueHandling = NullValueHandling.Ignore)]
        public string Till { get; set; }

        /// <summary>
        /// Associated <see cref="RecordField"/>.
        /// </summary>
        [CanBeNull]
        [XmlIgnore]
        [JsonIgnore]
        public RecordField Field { get; set; }

        /// <summary>
        /// Arbitrary user data.
        /// </summary>
        [CanBeNull]
        [XmlIgnore]
        [JsonIgnore]
        public object UserData { get; set; }

        #endregion

        #region Public methods

        /// <summary>
        /// Parse the field.
        /// </summary>
        [CanBeNull]
        public static EventTimes Parse
            (
                [CanBeNull] RecordField field
            )
        {
            if (ReferenceEquals(field, null))
            {
                return null;
            }

            EventTimes result = new EventTimes
            {
                From = field.GetFirstSubFieldValue('a'),
                Till = field.GetFirstSubFieldValue('b'),
                Field = field
            };

            return result;
        }

        #endregion
    }
}


text:
/*global Polymer*/
(function () {
  'use strict';

  require.config({
    paths: {
      'pathfinding-visualiser': 'src/pathfinding-visualiser',
      'core': 'src/core',
      'canvas-helper': 'src/canvas-helper',
      'map': 'src/map',
      'map-node': 'src/map-node',
      'binary-heap': '../js-data-structures/lib/binary-heap',
      'fibonacci-heap': '../js-data-structures/lib/fibonacci-heap',
      'a-star-common': 'src/algorithms/a-star-common',
      'a-star-heap': 'src/algorithms/a-star-heap',
      'a-star-array': 'src/algorithms/a-star-array',
      'a-star-binary-heap': 'src/algorithms/a-star-binary-heap',
      'a-star-fibonacci-heap': 'src/algorithms/a-star-fibonacci-heap',
      'dijkstra-common': 'src/algorithms/dijkstra-common',
      'dijkstra-heap': 'src/algorithms/dijkstra-heap',
      'dijkstra-binary-heap': 'src/algorithms/dijkstra-binary-heap',
      'dijkstra-fibonacci-heap': 'src/algorithms/dijkstra-fibonacci-heap'
    }
  });

  require([
    'pathfinding-visualiser',
    'a-star-array',
    'a-star-binary-heap',
    'a-star-fibonacci-heap',
    'dijkstra-binary-heap',
    'dijkstra-fibonacci-heap'
  ], function (pathfindingVisualiser, aStarArray, aStarBinaryHeap, aStarFibonacciHeap,
        dijkstraBinaryHeap, dijkstraFibonacciHeap) {
    var me;
    var algorithms = {
      'a-star-array': aStarArray,
      'a-star-binary-heap': aStarBinaryHeap,
      'a-star-fibonacci-heap': aStarFibonacciHeap,
      'dijkstra-binary-heap': dijkstraBinaryHeap,
      'dijkstra-fibonacci-heap': dijkstraFibonacciHeap
    };

    Polymer({
      is: 'pathfinding-visualiser',

      ready: function () {
        me = this;
        pathfindingVisualiser.init(this.$.canvas);
        this.algorithmChange('a-star-binary-heap');
        this.generateMap();
        var element = this;
        this.$.canvas.addEventListener('click', function (e) {
          pathfindingVisualiser.setGoalToMouse(e);
          element.run();
        });
        this.$.sidebar.clearHandler = this.clear;
        this.$.sidebar.generateHandler = this.generateMap;
        this.$.sidebar.runHandler = this.run;
        this.$.sidebar.toggleDialogHandler = this.toggleDialog;
        this.$.sidebar.onAlgorithmChange = this.algorithmChange;
      },

      algorithmChange: function (name) {
        pathfindingVisualiser.setAlgorithm(algorithms[name]);
      },

      clear: function () {
        me.$.summary.clear();
        pathfindingVisualiser.clear();
      },

      generateMap: function () {
        me.$.summary.clear();
        pathfindingVisualiser.generateMap(
          me.$.sidebar.mapScale,
          me.$.sidebar.obstacleDensity,
          me.$.sidebar.obstacleSize);
      },

      run: function () {
        if (me.$.sidebar.isRunDisabled()) {
          return;
        }
        me.$.sidebar.setRunDisabled(true);
        var getSpeed = !me.$.sidebar.animationEnabled ? undefined : function () {
          return me.$.sidebar.speedMax - me.$.sidebar.speed + 1;
        };
        pathfindingVisualiser.run(function (result) {
          me.$.summary.show(result);
          me.$.sidebar.setRunDisabled(false);
        }, getSpeed);
      }

    });
  });
})();