text:
/**
 * @file
 *
 * @brief A proxy class for CUDA streams, providing access to
 * all Runtime API calls involving their use and management.
 *
 * @note : Missing functionality: Stream attributes; stream capturing.
 */
#pragma once
#ifndef CUDA_API_WRAPPERS_STREAM_HPP_
#define CUDA_API_WRAPPERS_STREAM_HPP_

#include <cuda/api/current_context.hpp>
#include <cuda/api/current_device.hpp>
#include <cuda/api/error.hpp>
#include <cuda/api/kernel_launch.hpp>
#include <cuda/api/memory.hpp>
#include <cuda/api/miscellany.hpp>
#include <cuda/api/types.hpp>

#include <cuda_runtime_api.h>
#include <cuda.h>

#include <string>
#include <memory>
#include <utility>
#include <tuple>
#include <algorithm>

namespace cuda {

class device_t;
class event_t;
class stream_t;

namespace stream {

// Use this for the second argument to create_on_current_device()
enum : bool {
	implicitly_synchronizes_with_default_stream = true,
	no_implicit_synchronization_with_default_stream = false,
	sync = implicitly_synchronizes_with_default_stream,
	async = no_implicit_synchronization_with_default_stream,
	blocking = sync,
	nonblocking = async,
};

enum wait_condition_t : unsigned {
	greater_or_equal_to            = CU_STREAM_WAIT_VALUE_GEQ,
	geq                            = CU_STREAM_WAIT_VALUE_GEQ,

	equality                       = CU_STREAM_WAIT_VALUE_EQ,
	equals                         = CU_STREAM_WAIT_VALUE_EQ,

	nonzero_after_applying_bitmask = CU_STREAM_WAIT_VALUE_AND,
	one_bits_overlap               = CU_STREAM_WAIT_VALUE_AND,
	bitwise_and                    = CU_STREAM_WAIT_VALUE_AND,

	zero_bits_overlap              = CU_STREAM_WAIT_VALUE_NOR,
	bitwise_nor                    = CU_STREAM_WAIT_VALUE_NOR,
} ;

#if CUDA_VERSION >= 11000
/**
 * Possible synchronization behavior of a host thread when performing a synchronous action
 * on a stream (in particular, synchronizing with a stream).
 */
enum synchronization_policy_t : typename ::std::underlying_type<CUsynchronizationPolicy>::type {
	/**
	 * @todo Figure out what this default actually is!
	 */
	automatic = CU_SYNC_POLICY_AUTO,

	/**
	 * @brief Keep control and spin-check for result availability
	 *
	 * Instruct CUDA to actively spin when waiting for the stream to
	 * complete pending actions. This can decrease latency when waiting
	 * for the device, but may lower the performance of other CPU threads
	 * working in parallel.
	 */
	spin      = CU_SYNC_POLICY_SPIN,

	/**
	 * @brief Yield control while waiting for results.
	 *
	 * Instruct CUDA to yield its thread when waiting for the stream
	 * to complete pending actions. This can increase latency when
	 * waiting for the device, but can increase the performance of other
	 * CPU threads performing work in parallel.
	 *
	 */
	yield     = CU_SYNC_POLICY_YIELD,

	/**
	 * @brief Block the thread until the stream has concluded pending actions.
	 *
	 * Instruct CUDA to block the CPU thread on a synchronization
	 * primitive when waiting for the stream to finish work.
	 */
	block  = CU_SYNC_POLICY_BLOCKING_SYNC
};
#endif // CUDA_VERSION >= 11000

namespace detail_ {

::std::string identify(const stream_t& stream);

inline handle_t create_raw_in_current_context(
	bool          synchronizes_with_default_stream,
	priority_t    priority = stream::default_priority
)
{
	unsigned int flags = (synchronizes_with_default_stream == sync) ?
		CU_STREAM_DEFAULT : CU_STREAM_NON_BLOCKING;
	handle_t new_stream_handle;
	auto status = cuStreamCreateWithPriority(&new_stream_handle, flags, priority);
		// We could instead have used an equivalent Driver API call:
		// cuStreamCreateWithPriority(cuStreamCreateWithPriority(&new_stream_handle, flags, priority);
	throw_if_error_lazy(status, "Failed creating a new stream in " + detail_::identify(new_stream_handle));
	return new_stream_handle;
}

#if CUDA_VERSION >= 9020
inline context::handle_t context_handle_of(stream::handle_t stream_handle)
{
	context::handle_t handle;
	auto result = cuStreamGetCtx(stream_handle, &handle);
	throw_if_error_lazy(result, "Failed obtaining the context of " + cuda::detail_::ptr_as_hex(stream_handle));
	return handle;
}
#endif // CUDA_VERSION >= 9020

/**
 * @brief Obtains the device ID with which a stream with a given ID is associated
 *
 * @note No guarantees are made if the input stream handle is the default stream's.
 *
 * @param stream_handle a stream handle, other than the default stream for any
 * device or context
 * @return the identifier of the device for which the stream was created.
 */
inline device::id_t device_id_of(stream::handle_t stream_handle);

inline void record_event_in_current_context(
	device::id_t       current_device_id,
	context::handle_t  current_context_handle_,
	stream::handle_t   stream_handle,
	event::handle_t    event_handle);

} // namespace detail_

/**
 * @brief Wrap an existing stream in a @ref stream_t instance.
 *
 * @note This is a named constructor idiom, existing of direct access to the ctor
 * of the same signature, to emphasize that a new stream is _not_ created.
 *
 * @param id ID of the device for which the stream is defined
 * @param context_handle handle of the context in which the stream was created
 * @param stream_handle handle of the pre-existing stream
 * @param take_ownership When set to `false`, the stream
 * will not be destroyed along with the wrapper; use this setting
 * when temporarily working with a stream existing irrespective of
 * the current context and outlasting it. When set to `true`,
 * the proxy class will act as it does usually, destroying the stream
 * when being destructed itself.
 * @return an instance of the stream proxy class, with the specified
 * device-stream combination.
 */
stream_t wrap(
	device::id_t       device_id,
	context::handle_t  context_handle,
	handle_t           stream_handle,
	bool               take_ownership = false,
	bool               hold_pc_refcount_unit = false) noexcept;

namespace detail_ {

// Providing the same signature to multiple CUDA driver calls, to allow
// uniform templated use of all of them
template<typename T>
CUresult wait_on_value(CUstream stream_handle, CUdeviceptr address, T value, unsigned int flags);

// Providing the same signature to multiple CUDA driver calls, to allow
// uniform templated use of all of them
template<typename T>
CUresult write_value(CUstream stream_handle, CUdeviceptr address, T value, unsigned int flags);

} // namespace detail_

} // namespace stream

inline void synchronize(const stream_t& stream);

/**
 * @brief Proxy class for a CUDA stream
 *
 * @note a stream is specific to a context, and thus also specific to a device.
 *
 * @note This class is a "reference type", not a "value type". Therefore, making changes
 * to properties of the stream is a const-respecting operation on this class.
 */
class stream_t {

public: // type definitions

	enum : bool {
		doesnt_synchronizes_with_default_stream  = false,
		does_synchronize_with_default_stream     = true,
	};

public: // const getters
	/// The raw CUDA handle for a stream which this class wraps
	stream::handle_t   handle() const noexcept  { return handle_; }

	/// The raw CUDA handle for the context in which the represented stream is defined.
	context::handle_t  context_handle()  const noexcept { return context_handle_; }

	/// The raw CUDA ID for the device w.r.t. which the stream is defined
	device::id_t       device_id()       const noexcept { return device_id_; }

	/// The device w.r.t. which the stream is defined.
	device_t           device()    const noexcept;

	/// The context in which this stream was defined.
	context_t          context()   const noexcept;

	/// True if this wrapper is responsible for telling CUDA to destroy the stream upon the wrapper's own destruction
	bool               is_owning() const noexcept { return owning; }

public: // other non-mutators

	/**
	 * When true, work running in the created stream may run concurrently with
	 * work in stream 0 (the NULL stream), and there is no implicit
	 * synchronization performed between it and stream 0.
	 */
	bool synchronizes_with_default_stream() const
	{
		unsigned int flags;
		auto status = cuStreamGetFlags(handle_, &flags);
			// Could have used the equivalent Driver API call,
			// cuStreamGetFlags(handle_, &flags);
		throw_if_error_lazy(status, "Failed obtaining flags for a stream in "
				+ context::detail_::identify(context_handle_, device_id_));
		return flags & CU_STREAM_NON_BLOCKING;
	}

	stream::priority_t priority() const
	{
		int the_priority;
		auto status = cuStreamGetPriority(handle_, &the_priority);
			// Could have used the equivalent Runtime API call:
			// cuStreamGetPriority(handle_, &the_priority);
		throw_if_error_lazy(status, "Failed obtaining priority for a stream in "
			+ context::detail_::identify(context_handle_, device_id_));
		return the_priority;
	}

	/**
	 * Determines whether all work on this stream has been completed
	 *
	 * @note having work is _not_ the same as being busy executing that work!
	 *
	 * @todo What if there are incomplete operations, but they're all waiting on
	 * something on another queue? Should the queue count as "busy" then?
	 *
	 * @return true if there is still work pending, false otherwise
	 */
	bool has_work_remaining() const
	{
		context::current::detail_::scoped_override_t set_context_for_this_scope(context_handle_);
		auto status = cuStreamQuery(handle_);
			// Could have used the equivalent runtime API call:
			// cuStreamQuery(handle_);
		switch(status) {
		case CUDA_SUCCESS:
			return false;
		case CUDA_ERROR_NOT_READY:
			return true;
		default:
			throw cuda::runtime_error(static_cast<cuda::status::named_t>(status),
				"unexpected stream status for " + stream::detail_::identify(handle_, device_id_));
		}
	}

	/**
	 * The opposite of @ref has_work()
	 *
	 * @return true if there is no work pending, false if all
	 * previously-scheduled work has been completed
	 */
	bool is_clear() const { return !has_work_remaining(); }

	/**
	 * An alias for @ref is_clear() - to conform to how the CUDA runtime
	 * API names this functionality
	 */
	bool query() const { return is_clear(); }

protected: // static methods

	/**
	 * A function used internally by this class as the host function to call directly; see
	 * @ref enqueue_t::host_function_call - but only with CUDA version 10.0 and later.
	 *
	 * @param stream_handle the ID of the stream for which a host function call was triggered - this
	 * will be passed by the CUDA runtime
	 * @param stream_wrapper_members_and_callable a tuple, containing the information necessary to
	 * recreate the wrapper with which the callback is associated, without any additional CUDA API calls -
	 * plus the callable which was passed to @ref enqueue_t::host_function_call, and which the programmer
	 * actually wants to be called.
	 */
	template <typename Callable>
	static void CUDART_CB stream_launched_host_function_adapter(void * stream_wrapper_members_and_callable)
	{
		using tuple_type = ::std::tuple<device::id_t, context::handle_t , stream::handle_t, Callable>;
		auto* tuple_ptr = reinterpret_cast<tuple_type *>(stream_wrapper_members_and_callable);
		auto unique_ptr_to_tuple = ::std::unique_ptr<tuple_type>{tuple_ptr}; // Ensures deletion when we leave this function.
		auto device_id        = ::std::get<0>(*unique_ptr_to_tuple.get());
		auto context_handle   = ::std::get<1>(*unique_ptr_to_tuple.get());
		auto stream_handle        = ::std::get<2>(*unique_ptr_to_tuple.get());
		const auto& callable  = ::std::get<3>(*unique_ptr_to_tuple.get());
		callable( stream_t{device_id, context_handle, stream_handle, do_not_take_ownership} );
	}

	/**
	 * @brief A function to @ref `host_function_launch_adapter`, for use with the old-style CUDA Runtime API call,
	 * which passes more arguments to the callable - and calls the host function even on device failures.
	 *
	 * @param stream_handle the ID of the stream for which a host function call was triggered - this
	 * will be passed by the CUDA runtime
	 * @note status indicates the status the CUDA status when the host function call is triggered; anything
	 * other than @ref `cuda::status::success` means there's been a device error previously - but
	 * in that case, we won't invoke the callable, as such execution is deprecated; see:
	 * https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__STREAM.html#group__CUDART__STREAM
	 * @param device_id_and_callable a pair-value, containing the ID of the device to which the stream launching
	 * the host function call is associated, as well as the callable callback which was passed to
	 * @ref enqueue_t::host_function_call, and which the programmer actually wants to be called.
	 */
	template <typename Callable>
	static void callback_launch_adapter(
		stream::handle_t,
		status_t      status,
		void *        stream_wrapper_members_and_callable)
	{
		if (status != cuda::status::success) {
			using tuple_type = ::std::tuple<device::id_t, context::handle_t , stream::handle_t, Callable>;
			delete reinterpret_cast<tuple_type*>(stream_wrapper_members_and_callable);
			return;
		}
		stream_launched_host_function_adapter<Callable>(stream_wrapper_members_and_callable);
	}

public: // mutators

	/**
	 * @brief A gadget through which commands are enqueued on the stream.
	 *
	 * @note this class exists solely as a form of "syntactic sugar", allowing for code such as
	 *
	 *   my_stream.enqueue.copy(foo, bar, my_size)
	 */
	class enqueue_t {
	protected:
		const stream_t& associated_stream;

	public:
		enqueue_t(const stream_t& stream) : associated_stream(stream) {}

		template<typename KernelFunction, typename... KernelParameters>
		void kernel_launch(
			const KernelFunction&       kernel_function,
			launch_configuration_t      launch_configuration,
			KernelParameters &&...      parameters) const
		{
			return cuda::enqueue_launch(
				kernel_function,
				associated_stream,
				launch_configuration,
				::std::forward<KernelParameters>(parameters)...);
		}

		void type_erased_kernel_launch(
			const kernel_t&         kernel,
			launch_configuration_t  launch_configuration,
			span<const void*>       marshalled_arguments) const
		{
			cuda::launch_type_erased(kernel, associated_stream, launch_configuration, marshalled_arguments);
		}

		/**
		 * Have the CUDA device perform an I/O operation between two specified
		 * memory regions (on or off the actual device)
		 *
		 */

		///@{
		/**
		 * @param destination destination region into which to copy. May be
		 * anywhere in which memory can be mapped to the device's memory space (e.g.
		 * the device's global memory, host memory or the global memory of another device)
		 * @param source destination region from which to copy. May be
		 * anywhere in which memory can be mapped to the device's memory space (e.g.
		 * the device's global memory, host memory or the global memory of another device)
		 * @param num_bytes size of the region to copy
		 **/
		void copy(void *destination, const void *source, size_t num_bytes) const
		{
			// CUDA doesn't seem to need us to be in the stream's context to enqueue the copy;
			// however, unfortunately, it does require us to be in _some_ context.
			context::current::detail_::scoped_ensurer_t ensure_we_have_a_current_scope{associated_stream.context_handle_};
			memory::async::detail_::copy(destination, source, num_bytes, associated_stream.handle_);
		}

		void copy(void* destination, memory::const_region_t source, size_t num_bytes) const
		{
#ifndef NDEBUG
			if (source.size() < num_bytes) {
				throw ::std::logic_error("Attempt to copy more than the source region's size");
			}
#endif
			copy(destination, source.start(), num_bytes);
		}

		void copy(memory::region_t destination, memory::const_region_t source, size_t num_bytes) const
		{
			copy(destination.start(), source, num_bytes);
		}

		void copy(memory::region_t destination, memory::const_region_t source) const
		{
			copy(destination, source, source.size());
		}

		void copy(void* destination, memory::const_region_t source) const
		{
			copy(destination, source, source.size());
		}
		///@}

		/**
		 * Set all bytes of a certain region in device memory (or unified memory,
		 * but using the CUDA device to do it) to a single fixed value.
		 *
		 * @param destination Beginning of the region to fill
		 * @param byte_value the value with which to fill the memory region bytes
		 * @param num_bytes size of the region to fill
		 */
		void memset(void *destination, int byte_value, size_t num_bytes) const
		{
			// Is it necessary to set the device? I wonder.
			context::current::detail_::scoped_override_t set_context_for_this_scope(associated_stream.context_handle_);
			memory::device::async::detail_::set(destination, byte_value, num_bytes, associated_stream.handle_);
		}

		/**
		 * Set all bytes of a certain region in device memory (or unified memory,
		 * but using the CUDA device to do it) to zero.
		 *
		 * @note this is a separate method, since the CUDA runtime has a separate
		 * API call for setting to zero; does that mean there are special facilities
		 * for zero'ing memory faster? Who knows.
		 *
		 * @param destination Beginning of the region to fill
		 * @param num_bytes size of the region to fill
		 */
		void memzero(void *destination, size_t num_bytes) const
		{
			context::current::detail_::scoped_override_t set_context_for_this_scope(associated_stream.context_handle_);
			memory::device::async::detail_::zero(destination, num_bytes, associated_stream.handle_);
		}

		/**
		 * Have an event 'fire', i.e. marked as having occurred,
		 * after all hereto-scheduled work on this stream has been completed.
		 * Threads which are @ref stream_t::wait_on() 'ing the event will become available
		 * for continued execution.
		 *
		 * @param existing_event A pre-created CUDA event (for the stream's device); any existing
		 * "registration" of the event to occur elsewhere is overwritten.
		 *
		 * @note It is possible to wait for events across devices, but it is _not_ possible to
		 * trigger events across devices.
		 **/
		event_t& event(event_t& existing_event) const;

		/**
		 * Have an event 'fire', i.e. marked as having occurred,
		 * after all hereto-scheduled work on this stream has been completed.
		 * Threads which are @ref stream_t::wait_on() 'ing the event will become available
		 * for continued execution.
		 *
		 * @note the parameters are the same as for @ref event::create()
		 *
		 * @note It is possible to wait for events across devices, but it is _not_ possible to
		 * trigger events across devices.
		 *
		 **/
		event_t event(
			bool          uses_blocking_sync = event::sync_by_busy_waiting,
			bool          records_timing     = event::do_record_timings,
			bool          interprocess       = event::not_interprocess) const;

		/**
		 * Execute the specified function on the calling host thread once all
		 * hereto-scheduled work on this stream has been completed.
		 *
		 * @param callable_ a function to execute on the host. It must be callable
		 * with two parameters: `cuda::stream::handle_t stream_handle, cuda::event::handle_t event_handle`
		 */
		template <typename Callable>
		void host_function_call(Callable callable_) const
		{
			context::current::detail_::scoped_override_t set_context_for_this_scope(associated_stream.context_handle_);

			// Since callable_ will be going out of scope after the enqueueing,
			// and we don't know anything about the scope of the original argument with
			// which we were called, we must make a copy of `callable_` on the heap
			// and pass that as the user-defined data. We also add information about
			// the enqueueing stream.
			auto raw_callable_extra_argument = new
				::std::tuple<device::id_t, context::handle_t, stream::handle_t, Callable>(
				associated_stream.device_id_,
				associated_stream.context_handle_,
				associated_stream.handle(),
					Callable(::std::move(callable_))
				);

			// While we always register the same static function, `callback_adapter` as the
			// callback - what it will actually _do_ is invoke the callback we were passed.

#if CUDA_VERSION >= 10000
			auto status = cuLaunchHostFunc(
				associated_stream.handle_, &stream_launched_host_function_adapter<Callable>, raw_callable_extra_argument);
				// Could have used the equivalent Driver API call: cuLaunchHostFunc()
#else
			// The nVIDIA runtime API (at least up to v10.2) requires passing 0 as the flags
			// variable, see:
			// http://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__STREAM.html
			static constexpr const unsigned fixed_flags { 0u };
			auto status = cuStreamAddCallback(
				associated_stream.handle_, &callback_launch_adapter<Callable>, raw_callable_extra_argument, fixed_flags);
				// Could have used the equivalent Driver API call: cuAddStreamCallback()
#endif

			throw_if_error_lazy(status, "Failed scheduling a callback to be launched on "
				+ stream::detail_::identify(associated_stream.handle_,
					associated_stream.context_handle_, associated_stream.device_id_));
		}

#if CUDA_VERSION >= 11020
		/**
		 * Allocate a specified amount of memory.
		 *
		 * @param num_bytes amount of memory to allocate
		 * @return a region whose location is set when scheduling, but the memory of which
		 * only become allocated for use once the allocation task is actually reached by
		 * the stream and completed.
		 */
		memory::region_t allocate(size_t num_bytes) const
		{
			return memory::device::async::allocate(associated_stream, num_bytes);
		}

		/**
		 * Allocate a specified amount of memory.
		 *
		 * @param num_bytes amount of memory to allocate
		 * @return a region whose location is set when scheduling, but the memory of which
		 * only become allocated for use once the allocation task is actually reached by
		 * the stream and completed.
		 */
		///@{
		void free(void* region_start) const
		{
			memory::device::async::free(associated_stream, region_start);
		}

		void free(memory::region_t region) {
			memory::device::async::free(associated_stream, region);
		}
#endif
		///@{

		/**
		 * Sets the attachment of a region of managed memory (i.e. in the address space visible
		 * on all CUDA devices and the host) in one of several supported attachment modes.
		 *
		 * The attachmentis actually a commitment vis-a-vis the CUDA driver and the GPU itself
		 * that it doesn't need to worry about accesses to this memory from devices other than
		 * its object of attachment, so that the driver can optimize scheduling accordingly.
		 *
		 * @note by default, the memory region is attached to this specific stream on its
		 * specific device. In this case, the host will be allowed to read from this memory
		 * region whenever no kernels are pending on this stream.
		 *
		 * @note Attachment happens asynchronously, as an operation on this stream, i.e.
		 * the attachment goes into effect (some time after) previous scheduled actions have
		 * concluded.
		 */
		///@{
		/**
		 * @param managed_region_start a pointer to the beginning of the managed memory region.
		 * This cannot be a pointer to anywhere in the middle of an allocated region - you must
		 * pass whatever @ref cuda::memory::managed::allocate() returned.
		 */
		void attach_managed_region(
			const void* managed_region_start,
			memory::managed::attachment_t attachment = memory::managed::attachment_t::single_stream) const
		{
			context::current::detail_::scoped_override_t set_context_for_this_scope(associated_stream.context_handle_);
			// This fixed value is required by the CUDA Runtime API,
			// to indicate that the entire memory region, rather than a part of it, will be
			// attached to this stream
			constexpr const size_t length = 0;
			auto flags = static_cast<unsigned>(attachment);
			auto status =  cuStreamAttachMemAsync(
				associated_stream.handle_,  memory::device::address(managed_region_start), length, flags);
				// Could have used the equivalent Driver API call cuStreamAttachMemAsync
			throw_if_error_lazy(status, "Failed scheduling an attachment of a managed memory region on "
				+ stream::detail_::identify(associated_stream.handle_, associated_stream.context_handle_,
				associated_stream.device_id_));
		}

		/**
		 * @param region the managed memory region to attach; it cannot be a sub-region -
		 * you must pass whatever @ref cuda::memory::managed::allocate() returned.
		 */
		void attach_managed_region(
			memory::managed::region_t region,
			memory::managed::attachment_t attachment = memory::managed::attachment_t::single_stream) const
		{
			attach_managed_region(region.start(), attachment);
		}
		///@}

		/**
		 * Will pause all further activity on the stream until the specified event has
		 * occurred  (i.e. has fired, i.e. has had all preceding scheduled work
		 * on the stream on which it was recorded completed).
		 *
		 * @note this call will not delay any already-enqueued work on the stream,
		 * only work enqueued _after_ the call.
		 *
		 * @param event_ the event for whose occurrence to wait; the event
		 * would typically be recorded on another stream.
		 *
		 */
		void wait(const event_t& event_) const;

		/**
		 * Schedule writing a single value to global device memory after all
		 * previous work has concluded.
		 *
		 * @tparam T the value to schedule a setting of. Can only be a raw
		 * uint32_t or uint64_t !
		 * @param address location in global device memory to set at the appropriate time.
		 * @param value the value to write to @p address.
		 * @param with_memory_barrier if false, allows reordering of this write operation
		 * with writes scheduled before it.
		 */
		template <typename T>
		void set_single_value(T* __restrict__ address, T value, bool with_memory_barrier = true) const
		{
			static_assert(
				::std::is_same<T,int32_t>::value or ::std::is_same<T,int64_t>::value,
				"Unsupported type for stream value wait."
			);
			unsigned flags = with_memory_barrier ?
				CU_STREAM_WRITE_VALUE_DEFAULT :
				CU_STREAM_WRITE_VALUE_NO_MEMORY_BARRIER;
			auto result = static_cast<status_t>(
				stream::detail_::write_value(associated_stream.handle_, address, value, flags));
			throw_if_error_lazy(result, "Failed scheduling a write to global memory on "
				+ stream::detail_::identify(associated_stream.handle_,associated_stream.context_handle_,
				+ associated_stream.device_id_));
		}

		/**
		 * Wait for a value in device global memory to change so as to meet some condition
		 *
		 * @tparam T the value to schedule a setting of. Can only be a raw
		 * uint32_t or uint64_t !
		 * @param address location in global device memory to set at the appropriate time.
		 * @param condition the kind of condition to check against the reference value. Examples:
		 * equal to 5, greater-or-equal to 5, non-zero bitwise-and with 5 etc.
		 * @param value the condition is checked against this reference value. Example: waiting on
		 * the value at address to be greater-or-equal to this value.
		 * @param with_memory_barrier If true, all remote writes guaranteed to have reached the device
		 * before the wait is performed will be visible to all operations on this stream/queue scheduled
		 * after the wait.
		 */
		template <typename T>
		void wait(const T* address, stream::wait_condition_t condition, T value, bool with_memory_barrier = false) const
		{
			static_assert(
				::std::is_same<T,int32_t>::value or ::std::is_same<T,int64_t>::value,
				"Unsupported type for stream value wait."
			);
			unsigned flags = static_cast<unsigned>(condition) |
				(with_memory_barrier ? CU_STREAM_WAIT_VALUE_FLUSH : 0);
			auto result = static_cast<status_t>(
				stream::detail_::wait_on_value(associated_stream.handle_, address, value, flags));
			throw_if_error_lazy(result,
				"Failed scheduling a wait on global memory address on "
				+ stream::detail_::identify(
					associated_stream.handle_,
					associated_stream.context_handle_,
					associated_stream.device_id_) );
		}

		/**
		 * Guarantee all remote writes to the specified address are visible to subsequent operations
		 * scheduled on this stream.
		 *
		 * @param address location the previous remote writes to which need to be visible to
		 * subsequent operations.
		 */
		void flush_remote_writes() const
		{
			CUstreamBatchMemOpParams flush_op;
			flush_op.operation = CU_STREAM_MEM_OP_FLUSH_REMOTE_WRITES;
			unsigned count = 1;
			unsigned flags = 0;
			// Let's cross our fingers and assume nothing else needs to be set here...
			cuStreamBatchMemOp(associated_stream.handle_, count, &flush_op, flags);
		}

		/**
		 * Enqueue multiple single-value write, wait and flush operations to the device
		 * (avoiding the overhead of multiple enqueue calls).
		 *
		 * @note see @ref wait(), @ref set_single_value and @ref flush_remote_writes.
		 *
		 * @{
		 */

		/**
		 * @param ops_begin beginning of a sequence of single-value operation specifications
		 * @param ops_end end of a sequence of single-value operation specifications
		 */
		template <typename Iterator>
		void single_value_operations_batch(Iterator ops_begin, Iterator ops_end) const
		{
			static_assert(
				::std::is_same<typename ::std::iterator_traits<Iterator>::value_type, CUstreamBatchMemOpParams>::value,
				"Only accepting iterator pairs for the CUDA-driver-API memory operation descriptor,"
				" CUstreamBatchMemOpParams, as the value type");
			auto num_ops = ::std::distance(ops_begin, ops_end);
			if (::std::is_same<typename ::std::remove_const<decltype(ops_begin)>::type, CUstreamBatchMemOpParams* >::value,
				"Only accepting containers of the CUDA-driver-API memory operation descriptor, CUstreamBatchMemOpParams")
			{
				auto ops_ptr = reinterpret_cast<const CUstreamBatchMemOpParams*>(ops_begin);
				cuStreamBatchMemOp(associated_stream.handle_, num_ops, ops_ptr);
			}
			else {
				auto ops_uptr = ::std::unique_ptr<CUstreamBatchMemOpParams[]>(new CUstreamBatchMemOpParams[num_ops]);
				::std::copy(ops_begin, ops_end, ops_uptr.get());
				cuStreamBatchMemOp(associated_stream.handle_, num_ops, ops_uptr.get());
			}
		}

		/**
		 * @param single_value_ops A sequence of single-value operation specifiers to enqueue together.
		 */
		template <typename Container>
		void single_value_operations_batch(const Container& single_value_ops) const
		{
			return single_value_operations_batch(single_value_ops.begin(), single_value_ops.end());
		}

	}; // class enqueue_t

	friend class enqueue_t;

	/**
	 * Block or busy-wait until all previously-scheduled work
	 * on this stream has been completed
	 */
	void synchronize() const
	{
		cuda::synchronize(*this);
	}

#if CUDA_VERSION >= 11000
	stream::synchronization_policy_t synchronization_policy()
	{
		context::current::detail_::scoped_override_t set_context_for_this_scope(context_handle_);
		CUstreamAttrValue wrapped_result{};
		auto status = cuStreamGetAttribute(handle_, CU_STREAM_ATTRIBUTE_SYNCHRONIZATION_POLICY, &wrapped_result);
		throw_if_error_lazy(status, ::std::string("Obtaining the synchronization policy of ") + stream::detail_::identify(*this));
		return static_cast<stream::synchronization_policy_t>(wrapped_result.syncPolicy);
	}

	void set_synchronization_policy(stream::synchronization_policy_t policy)
	{
		context::current::detail_::scoped_override_t set_context_for_this_scope(context_handle_);
		CUstreamAttrValue wrapped_value{};
		wrapped_value.syncPolicy = static_cast<CUsynchronizationPolicy>(policy);
		auto status = cuStreamSetAttribute(handle_, CU_STREAM_ATTRIBUTE_SYNCHRONIZATION_POLICY, &wrapped_value);
		throw_if_error_lazy(status, ::std::string("Setting the synchronization policy of ") + stream::detail_::identify(*this));
	}
#endif

protected: // constructor

	stream_t(
		device::id_t       device_id,
		context::handle_t  context_handle,
		stream::handle_t   stream_handle,
		bool               take_ownership = false,
		bool               hold_primary_context_refcount_unit = false) noexcept
	:
		device_id_(device_id),
		context_handle_(context_handle),
		handle_(stream_handle),
		owning(take_ownership),
		holds_pc_refcount_unit(hold_primary_context_refcount_unit)
	{ }

public: // constructors and destructor

	// Streams cannot be copied, despite our allowing non-owning class instances.
	// The reason is that we might inadvertently copy of an owning stream, creating
	// a non-owning stream and letting the original owning stream go out of scope -
	// thus destructing the object, and destroying the underlying CUDA object.
	// Essentially, that is like passing a reference to a local variable - which we
	// may not do.
	stream_t(const stream_t& other) = delete;

	stream_t(stream_t&& other) noexcept :
		stream_t(other.device_id_, other.context_handle_, other.handle_, other.owning, other.holds_pc_refcount_unit)
	{
		other.owning = false;
		other.holds_pc_refcount_unit = false;
	}

	~stream_t() noexcept(false)
	{
		if (owning) {
			context::current::detail_::scoped_override_t set_context_for_this_scope(context_handle_);
			cuStreamDestroy(handle_);
		}
		// TODO: DRY
		if (holds_pc_refcount_unit) {
#ifdef NDEBUG
			device::primary_context::detail_::decrease_refcount_nothrow(device_id_);
				// Note: "Swallowing" any potential error to avoid ::std::terminate(); also,
				// because a failure probably means the primary context is inactive already
#else
			device::primary_context::detail_::decrease_refcount(device_id_);
#endif
		}
	}

public: // operators

	stream_t& operator=(const stream_t& other) = delete;
	stream_t& operator=(stream_t&& other) noexcept
	{
		::std::swap(device_id_, other.device_id_);
		::std::swap(context_handle_, other.context_handle_);
		::std::swap(handle_, other.handle_);
		::std::swap(owning, other.owning);
		::std::swap(holds_pc_refcount_unit, holds_pc_refcount_unit);
		return *this;
	}

public: // friendship

	friend stream_t stream::wrap(
		device::id_t       device_id,
		context::handle_t  context_handle,
		stream::handle_t   stream_handle,
		bool               take_ownership,
		bool               hold_pc_refcount_unit) noexcept;

	/**
	 * @note two stream proxies may be equal even though one is the owning reference
	 * and the other isn't, or if only one holds a primary context reference unit
	 * and the other doesn't.
	 */
	friend inline bool operator==(const stream_t& lhs, const stream_t& rhs) noexcept
	{
		return
			lhs.context_handle_ == rhs.context_handle_
#ifndef NDEBUG
			and lhs.device_id_ == rhs.device_id_
#endif
			and lhs.handle_ == rhs.handle_;
	}

protected: // data members
	device::id_t       device_id_;
	context::handle_t  context_handle_;
	stream::handle_t   handle_;
	bool               owning;
	bool               holds_pc_refcount_unit;
		// When context_handle_ is the handle of a primary context, this event may
		// be "keeping that context alive" through the refcount - in which case
		// it must release its refcount unit on destruction

public: // data members - which only exist in lieu of namespaces
	const enqueue_t     enqueue { *this };
		// The use of *this here is safe, since enqueue_t doesn't do anything with it
		// on its own. Any use of enqueue only happens through, well, *this - and
		// after construction.
};

inline bool operator!=(const stream_t& lhs, const stream_t& rhs) noexcept
{
	return not (lhs == rhs);
}

namespace stream {

inline stream_t wrap(
	device::id_t       device_id,
	context::handle_t  context_handle,
	stream::handle_t   stream_handle,
	bool               take_ownership,
	bool               hold_pc_refcount_unit) noexcept
{
	return { device_id, context_handle, stream_handle, take_ownership, hold_pc_refcount_unit };
}

namespace detail_ {

inline stream_t create(
	device::id_t       device_id,
	context::handle_t  context_handle,
	bool               synchronizes_with_default_stream,
	priority_t         priority = stream::default_priority,
	bool               hold_pc_refcount_unit = false)
{
	context::current::detail_::scoped_override_t set_context_for_this_scope(context_handle);
	auto new_stream_handle = cuda::stream::detail_::create_raw_in_current_context(
		synchronizes_with_default_stream, priority);
	return wrap(device_id, context_handle, new_stream_handle, do_take_ownership, hold_pc_refcount_unit);
}

template<>
inline CUresult wait_on_value<uint32_t>(CUstream stream_handle, CUdeviceptr address, uint32_t value, unsigned int flags)
{
	return cuStreamWaitValue32(stream_handle, address, value, flags);
}

template<>
inline CUresult wait_on_value<uint64_t>(CUstream stream_handle, CUdeviceptr address, uint64_t value, unsigned int flags)
{
	return cuStreamWaitValue64(stream_handle, address, value, flags);
}

template<>
inline CUresult write_value<uint32_t>(CUstream stream_handle, CUdeviceptr address, uint32_t value, unsigned int flags)
{
	return cuStreamWriteValue32(stream_handle, address, value, flags);
}

template<>
inline CUresult write_value<uint64_t>(CUstream stream_handle, CUdeviceptr address, uint64_t value, unsigned int flags)
{
	return cuStreamWriteValue64(stream_handle, address, value, flags);
}

} // namespace detail_

/**
 * @brief Create a new stream (= queue) in the primary execution context
 * of a CUDA device.
 *
 * @param device the device on which a stream is to be created
 * @param synchronizes_with_default_stream if true, no work on this stream
 * will execute concurrently with work from the default stream (stream 0)
 * @param priority priority of tasks on the stream, relative to other streams,
 * for execution scheduling; lower numbers represent higher properties. Each
 * device has a range of priorities, which can be obtained using
 * @ref device_t::stream_priority_range() .
 * @return The newly-created stream
 */
///@{

/**
 * @brief Create a new stream (= queue) in the primary execution context
 * of a CUDA device.
 *
 * @param device the device on which a stream is to be created
 */
stream_t create(
	const device_t&   device,
	bool              synchronizes_with_default_stream,
	priority_t        priority = stream::default_priority);

/**
 * @brief Create a new stream (= queue) in a CUDA execution context.
 *
 * @param context the execution context in which to create the stream
 */
stream_t create(
	const context_t&  context,
	bool              synchronizes_with_default_stream,
	priority_t        priority = stream::default_priority,
	bool              hold_pc_refcount_unit = false);
///@}

} // namespace stream

using queue_t = stream_t;
using queue_id_t = stream::handle_t;

inline void synchronize(const stream_t& stream)
{
	// Note: Unfortunately, even though CUDA should be aware of which context a stream belongs to,
	// and not have trouble acting on a stream in another context - it balks at doing so under
	// certain conditions, so we must place ourselves in the stream's context.
	context::current::detail_::scoped_override_t set_context_for_this_scope(stream.context_handle());
	auto status = cuStreamSynchronize(stream.handle());
	throw_if_error_lazy(status, "Failed synchronizing " + stream::detail_::identify(stream));
}

#if CUDA_VERSION >= 11000
/**
 * Overwrite all "attributes" of one stream with those of another
 *
 * @param dest The stream whose attributes will be overwritten
 * @param src The stream whose attributes are to be copied
 *
 * @note As of CUDA 11.5, the "attributes" are the thread
 * synchronization policy and the various L2 access policy window
 * settings; see https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#L2_access_policy
 * for details.
 */
void copy_attributes(const stream_t& dest, const stream_t& src);
#endif // CUDA_VERSION >= 11000

} // namespace cuda

#endif // CUDA_API_WRAPPERS_STREAM_HPP_


text:
/*
 * Created by SharpDevelop.
 * User: Anthony
 * Date: 5/16/2007
 * Time: 12:55 AM
 *
 */

using System;
using System.Collections.Generic;
using LibHid;

namespace LibUSBLauncher
{
	/// <summary>
	/// Description of LauncherManager.
	/// </summary>
	public class LauncherManager
	{
		#region Private Data
		private List<USBLauncher> _launchers = new List<USBLauncher>();
		private const int _writeEndPoint = 0x81;
		private const int _readEndPoint = 0x01;
		private const int _timeout = 4096;
		#endregion

		#region Dispose
		private bool isDisposed = false;
	 	protected virtual void Dispose(bool disposing)
	  	{
	    	if (!isDisposed) // only dispose once!
	    	{
	    		if(disposing)
	    		{
	    			Disconnect();
	    		}
	    	}
	    	this.isDisposed = true;
	  	}

	 	public void Dispose()
	  	{
	    	Dispose(true);
	    	// tell the GC not to finalize
	    	GC.SuppressFinalize(this);
	  	}
		#endregion

		#region Properties
		public int Count
		{
			get { return _launchers.Count; }
		}

		public List<USBLauncher> Launchers
		{
			get { return _launchers; }
		}
		#endregion

		#region Public Methods
		/// <summary>
		/// Connects to usb launchers, returns true if at least one is found
		/// </summary>
		/// <returns>True if at least one launcher is found</returns>
		public bool Connect(LibHid.UsbHidPort dreamCheeky, LibHid.UsbHidPort rocketBaby)
		{
			DreamCheekyLauncher launcher1 = new DreamCheekyLauncher(dreamCheeky);
            RocketBabyLauncher launcher2 = new RocketBabyLauncher(rocketBaby);

            if (launcher1.Port.SpecifiedDevice != null)
                Launchers.Add(launcher1);

            if (launcher2.Port.SpecifiedDevice != null)
                Launchers.Add(launcher2);

            return Launchers.Count > 0;
		}

		/// <summary>
		/// Closes connection to all devices
		/// </summary>
		public void Disconnect()
		{
			foreach(USBLauncher l in _launchers)
			{
				l.Close();
			}

			_launchers.Clear();
		}
		#endregion

		public void PassMessages(ref System.Windows.Forms.Message m)
		{
			foreach(USBLauncher launcher in Launchers)
			{
				launcher.Port.ParseMessages(ref m);

			}
		}

		public void PassHandle(System.IntPtr Handle)
		{

			foreach(USBLauncher launcher in Launchers)
			{
				launcher.Port.RegisterHandle(Handle);
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
var game = new Phaser.Game(400, 400, Phaser.AUTO, 'test');

var BasicGame = function(game) {};

BasicGame.Boot = function (game) {};

var pie;

BasicGame.Boot.prototype =
{
    preload: function() {
        game.time.advancedTiming = true;
        game.stage.backgroundColor = '#3c3640';
    },
	create: function()
	{
        pie = new PieProgress(game, game.world.centerX, game.world.centerY, 32);
        game.world.add(pie);

        var gui = new dat.GUI();
        gui.add(pie, 'progress', 0, 1);
        gui.add(pie, 'radius', 20, 128);
        gui.add(pie, 'weight', 0, 1);
        gui.addColor(pie, 'color');
    },
    update: function() {

    },
    render: function()
    {
        game.debug.text(game.time.fps || '--', 2, 14, "#00ff00");
    }
};

var PieProgress = function(game, x, y, radius, color, angle, weight) {
    this._radius = radius;
    this._progress = 1;
    this._weight = weight || 0.25;
    this._color = color || "#fff";
    this.bmp = game.add.bitmapData((this._radius * 2) + (this._weight * (this._radius * 0.6)), (this._radius * 2) + (this._weight * (this._radius * 0.6)));
    Phaser.Sprite.call(this, game, x, y, this.bmp);

    this.anchor.set(0.5);
    this.angle = angle || -90;
    this.updateProgress();
}

PieProgress.prototype = Object.create(Phaser.Sprite.prototype);
PieProgress.prototype.constructor = PieProgress;

PieProgress.prototype.updateProgress = function() {
    var progress = this._progress;
    progress = Phaser.Math.clamp(progress, 0.00001, 0.99999);

    this.bmp.clear();
    this.bmp.ctx.strokeStyle = this.color;
    this.bmp.ctx.lineWidth = this._weight * this._radius;
    this.bmp.ctx.beginPath();
    this.bmp.ctx.arc(this.bmp.width * 0.5, this.bmp.height * 0.5, this._radius - 15, 0, (Math.PI * 2) * progress, false);
    this.bmp.ctx.stroke();
    this.bmp.dirty = true;
};

PieProgress.prototype.updateBmdSize = function() {
    this.bmp.resize((this._radius * 2) + (this._weight * (this._radius * 0.75)), (this._radius * 2) + (this._weight * (this._radius * 0.75)));
};

Object.defineProperty(PieProgress.prototype, 'color', {
    get: function() {
        return this._color;
    },
    set: function(val) {
        this._color = val;
        this.updateProgress();
    }
});

Object.defineProperty(PieProgress.prototype, 'radius', {
    get: function() {
        return this._radius;
    },
    set: function(val) {
        this._radius = (val > 0 ? val : 0);
        this.updateBmdSize();
        this.updateProgress();
    }
});

Object.defineProperty(PieProgress.prototype, 'progress', {
    get: function() {
        return this._progress;
    },
    set: function(val) {
        this._progress = Phaser.Math.clamp(val, 0, 1);
        this.updateProgress();
    }
});

Object.defineProperty(PieProgress.prototype, 'weight', {
    get: function() {
        return this._weight;
    },
    set: function(val) {
        this._weight = Phaser.Math.clamp(val, 0.01, 0.99);
        this.updateBmdSize();
        this.updateProgress();
    }
});

game.state.add('Boot', BasicGame.Boot);
game.state.start('Boot');


text:
var chai = require('chai')
chai.Should()
chai.use(require('chai-things'))
chai.use(require('@signalk/signalk-schema').chaiModule)

function generatePGNs (json) {
  return [json, json.replace('Engine Instance', 'Instance')]
}

describe('127488 engine trim Port', function () {
  it('complete engine trim sentence converts', function () {
    generatePGNs(
      '{"timestamp":"2019-01-09T00:11:11.654Z","prio":2,"pgn":127488,"src":8,"dst":255,"fields":{"Instance":"Single Engine or Dual Engine Port","Speed":0,"Tilt/Trim":31},"description":"Engine Parameters, Rapid Update"}'
    ).forEach(pgn => {
      var tree = require('./testMapper').toNested(JSON.parse(pgn))
      tree.should.have.nested.property('propulsion.port.drive.trimState')
      tree.should.have.nested.property(
        'propulsion.port.drive.trimState.value',
        0.31
      )
      tree.should.be.validSignalKVesselIgnoringIdentity
    })
  })
})

describe('127488 engine trim Starboard', function () {
  it('complete engine trim sentence converts', function () {
    generatePGNs(
      '{"timestamp":"2019-01-09T00:11:11.654Z","prio":2,"pgn":127488,"src":8,"dst":255,"fields":{"Instance":"Dual Engine Starboard","Speed":0,"Tilt/Trim":31},"description":"Engine Parameters, Rapid Update"}'
    ).forEach(pgn => {
      var tree = require('./testMapper').toNested(JSON.parse(pgn))
      tree.should.have.nested.property('propulsion.starboard.drive.trimState')
      tree.should.have.nested.property(
        'propulsion.starboard.drive.trimState.value',
        0.31
      )
      tree.should.be.validSignalKVesselIgnoringIdentity
    })
  })
})

describe('127488 engine trim 2', function () {
  it('complete engine trim sentence converts', function () {
    generatePGNs(
      '{"timestamp":"2019-01-09T00:11:11.654Z","prio":2,"pgn":127488,"src":8,"dst":255,"fields":{"Instance":2,"Speed":0,"Tilt/Trim":31},"description":"Engine Parameters, Rapid Update"}'
    ).forEach(pgn => {
      var tree = require('./testMapper').toNested(JSON.parse(pgn))
      tree.should.have.nested.property('propulsion.2.drive.trimState')
      tree.should.have.nested.property(
        'propulsion.2.drive.trimState.value',
        0.31
      )
      tree.should.be.validSignalKVesselIgnoringIdentity
    })
  })
})


text:
ACCEPTED

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

#### Published in
Symb. bot. upsal. 20(no. 1): 281 (1972)

#### Original name
Sphaeria stercoris DC., 1805

### Remarks
null


text:
package com.akavrt.worko.provider;

import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.Calendar;
import java.util.Locale;

/**
 * @author Victor Balabanov <akavrt@gmail.com>
 */
public class IntervalStatHelper {
    private static String sStatSqlBounded = WorkoProvider.STAT_SQL_UNBOUNDED +
            " WHERE " + WorkoContract.Sets.DAY + " >= ? AND " + WorkoContract.Sets.DAY + " < ?";

    private final Context mContext;
    private final SQLiteDatabase mDb;

    public IntervalStatHelper(Context context, SQLiteDatabase db) {
        this.mContext = context;
        this.mDb = db;
    }

    public Cursor weekStat() {
        Locale currentLocale = mContext.getResources().getConfiguration().locale;

        Calendar currentDate = Calendar.getInstance(currentLocale);
        int firstDayOfWeek = currentDate.getFirstDayOfWeek();
        int days = (currentDate.get(Calendar.DAY_OF_WEEK) + 7 - firstDayOfWeek) % 7;

        Calendar currWeekStartDate = Calendar.getInstance(currentLocale);
        currWeekStartDate.setTime(currentDate.getTime());
        currWeekStartDate.add(Calendar.DATE, -days);
        currWeekStartDate.set(Calendar.HOUR_OF_DAY, 0);
        currWeekStartDate.set(Calendar.MINUTE, 0);
        currWeekStartDate.set(Calendar.SECOND, 0);
        currWeekStartDate.set(Calendar.MILLISECOND, 0);

        Calendar prevWeekStartDate = Calendar.getInstance(currentLocale);
        prevWeekStartDate.setTime(currWeekStartDate.getTime());
        prevWeekStartDate.add(Calendar.DATE, -7);

        Calendar nextWeekStartDate = Calendar.getInstance(currentLocale);
        nextWeekStartDate.setTime(currWeekStartDate.getTime());
        nextWeekStartDate.add(Calendar.DATE, 7);

        return adjacentIntervalsStat(
                currentLocale,
                prevWeekStartDate,
                currWeekStartDate,
                nextWeekStartDate);
    }

    public Cursor monthStat() {
        Locale currentLocale = mContext.getResources().getConfiguration().locale;

        Calendar currMonthStartDate = Calendar.getInstance(currentLocale);
        currMonthStartDate.set(Calendar.DAY_OF_MONTH,
                currMonthStartDate.getActualMinimum(Calendar.DAY_OF_MONTH));
        currMonthStartDate.set(Calendar.HOUR_OF_DAY, 0);
        currMonthStartDate.set(Calendar.MINUTE, 0);
        currMonthStartDate.set(Calendar.SECOND, 0);
        currMonthStartDate.set(Calendar.MILLISECOND, 0);

        Calendar prevMonthStartDate = Calendar.getInstance(currentLocale);
        prevMonthStartDate.setTime(currMonthStartDate.getTime());
        prevMonthStartDate.add(Calendar.MONTH, -1);

        Calendar nextMonthStartDate = Calendar.getInstance(currentLocale);
        nextMonthStartDate.setTime(currMonthStartDate.getTime());
        nextMonthStartDate.add(Calendar.MONTH, 1);

        return adjacentIntervalsStat(
                currentLocale,
                prevMonthStartDate,
                currMonthStartDate,
                nextMonthStartDate);
    }

    private Cursor adjacentIntervalsStat(Locale locale,
                                         Calendar prevIntervalStartDate,
                                         Calendar currIntervalStartDate,
                                         Calendar nextIntervalStartDate) {
        String prevIntervalStartDateSt =
                Long.toString(prevIntervalStartDate.getTimeInMillis() / 1000);
        String currIntervalStartDateSt =
                Long.toString(currIntervalStartDate.getTimeInMillis() / 1000);
        String nextIntervalStartDateSt =
                Long.toString(nextIntervalStartDate.getTimeInMillis() / 1000);

        MatrixCursor result = new MatrixCursor(
                new String[]{
                        WorkoContract.WeekStat.DAYS,
                        WorkoContract.WeekStat.SETS,
                        WorkoContract.WeekStat.PULL_UPS,
                        WorkoContract.WeekStat.RECORD,
                        WorkoContract.WeekStat.INTERVAL_START,
                        WorkoContract.WeekStat.INTERVAL_END
                }
        );

        // current interval
        MatrixCursor.RowBuilder builder =
                addIntervalStat(currIntervalStartDateSt, nextIntervalStartDateSt, result);

        Calendar currIntervalEndDate = Calendar.getInstance(locale);
        currIntervalEndDate.setTime(nextIntervalStartDate.getTime());
        currIntervalEndDate.add(Calendar.DATE, -1);

        builder.add(currIntervalStartDate.getTimeInMillis());
        builder.add(currIntervalEndDate.getTimeInMillis());

        // previous interval
        builder = addIntervalStat(prevIntervalStartDateSt, currIntervalStartDateSt, result);

        Calendar prevIntervalEndDate = Calendar.getInstance(locale);
        prevIntervalEndDate.setTime(currIntervalStartDate.getTime());
        prevIntervalEndDate.add(Calendar.DATE, -1);

        builder.add(prevIntervalStartDate.getTimeInMillis());
        builder.add(prevIntervalEndDate.getTimeInMillis());

        return result;
    }

    private MatrixCursor.RowBuilder addIntervalStat(String currIntervalStartDateSt,
                                                    String nextIntervalStartDateSt,
                                                    MatrixCursor result) {
        Cursor interval = mDb.rawQuery(sStatSqlBounded,
                new String[]{currIntervalStartDateSt, nextIntervalStartDateSt});

        int daysIndex = interval.getColumnIndexOrThrow(WorkoContract.StatisticsColumns.DAYS);
        int setsIndex = interval.getColumnIndexOrThrow(WorkoContract.StatisticsColumns.SETS);
        int pullUpsIndex = interval.getColumnIndexOrThrow(WorkoContract.StatisticsColumns.PULL_UPS);
        int recordIndex = interval.getColumnIndexOrThrow(WorkoContract.StatisticsColumns.RECORD);

        int intervalDays = 0;
        int intervalSets = 0;
        int intervalPullUps = 0;
        int intervalRecord = 0;
        if (interval != null) {
            if (interval.getCount() > 0 && interval.moveToNext()) {
                intervalDays = interval.getInt(daysIndex);
                intervalSets = interval.getInt(setsIndex);
                intervalPullUps = interval.getInt(pullUpsIndex);
                intervalRecord = interval.getInt(recordIndex);
            }

            interval.close();
        }

        return result.newRow()
                .add(intervalDays)
                .add(intervalSets)
                .add(intervalPullUps)
                .add(intervalRecord);
    }

}


text:
/**
 * Created by marto on 28-Oct-16.
 */
'use strict'

const path = require('path')

let root = path.normalize(path.join(__dirname, '/../../'))

module.exports = {
    development : {
        rootPath: root,
        db : 'mongodb://localhost:27017/bitcoin-wallet-db',
        port: 3000
    },
    staging: {
        rootPath: root,
        db: process.env.MONGO_DB,
        port: process.env.port
    },
    production: {
        rootPath: root,
        db: process.env.MONGO_DB,
        port: process.env.port
    }
}


text:
Restores last remembered selection

    selectionRestore([noRefresh])

        noRefresh
        boolean, optional indicates if to refresh the grid

Returns time it took to restore selection.

Description

This method restores last saved selection from .last._selection property. It is used internally to remember
and then restore selection after local sort and grid reload methods.

If you have a grid defined in the following way:
<textarea class="javascript">
let grid = new w2grid({
    name    : 'grid',
    columns: [
        { field: 'recid', text: 'ID', size: '50px' },
        { field: 'lname', text: 'Last Name', size: '30%' },
        { field: 'fname', text: 'First Name', size: '30%' },
        { field: 'email', text: 'Email', size: '40%' },
        { field: 'sdate', text: 'Start Date', size: '120px' },
        { field: 'sdate', text: 'End Date', size: '120px' }
    ],
    records: [
        { recid: 1, fname: 'John', lname: 'doe', email: 'vitali@gmail.com', sdate: '1/3/2012' },
        { recid: 2, fname: 'Stuart', lname: 'Motzart', email: 'jdoe@gmail.com', sdate: '2/4/2012' },
        { recid: 3, fname: 'Jin', lname: 'Franson', email: '--', sdate: '4/23/2012' },
        { recid: 4, fname: 'Susan', lname: 'Ottie', email: 'jdoe@gmail.com', sdate: '5/3/2012' },
        { recid: 5, fname: 'Kelly', lname: 'Silver', email: 'jdoe@gmail.com', sdate: '4/3/2012' },
        { recid: 6, fname: 'Francis', lname: 'Gatos', email: 'vitali@gmail.com', sdate: '2/5/2012' }
    ]
});
</textarea>

You can do:
<textarea class="javascript">
grid.selectionSave();
// do some grid changes
grid.selectionRestore();
</textarea>


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

    <string name="app_name">faceinfo</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="action_hide">Hide Panel</string>
    <string name="action_show">Show Panel</string>
    <string name="action_anchor_enable">Enable Anchor Point</string>
    <string name="action_anchor_disable">Disable Anchor Point</string>

</resources>


text:
package a

import "strings"

type Name string

type FullName string

func (n FullName) Name() Name {
	if i := strings.LastIndexByte(string(n), '.'); i >= 0 {
		return Name(n[i+1:])
	}
	return Name(n)
}


text:
import './inputFloat'
import './inputBits'
import './inputBitCount'
import './byteOrder'
import './numberScroll'


text:
[![Build Status](https://travis-ci.org/mushorg/glutton.svg?branch=master)](https://travis-ci.org/mushorg/glutton)
[![GoDoc](https://godoc.org/github.com/mushorg/glutton?status.svg)](https://godoc.org/github.com/mushorg/glutton)

Setup `go 1.7+`. Install required system packages:
```
apt-get install libnetfilter-queue-dev libpcap-dev iptables-dev
```
To change your SSH server default port (i.e. 5001, see `rules.yaml`) and restart sshd:
```
sed -i 's/[# ]*Port .*/Port 5001/g' /etc/ssh/sshd_config
```
Download glutton, and install dependencies using `dep`:
```
go get github.com/mushorg/glutton
go get -u github.com/golang/dep/cmd/dep
cd $GOPATH/src/github.com/mushorg/glutton/
dep ensure
```
Build glutton:
```
make build
```
To run/test glutton:
```
bin/server
```

# Use as Proxy

Glutton provide SSH and TCP proxy. SSH proxy work as MITM between attacker and server to log every thing in plan text. TCP proxy does not provide facility for logging yet. Examples can be found [here](https://github.com/mushorg/glutton/tree/master/examples).


text:
namespace PerfGen {

const char *classname = "PerfGen Pixel Generator";

PerfGenBase::PerfGenBase(BaseSettings const &settings) : Detector(settings) {

  Stats.setPrefix(EFUSettings.GraphitePrefix, EFUSettings.GraphiteRegion);

  XTRACE(INIT, ALW, "Adding stats");
  // clang-format off
  Stats.create("events.udder", mystats.events_udder);
  Stats.create("transmit.bytes", mystats.tx_bytes);

  /// \todo below stats are common to all detectors and could/should be moved
  Stats.create("kafka.produce_calls", mystats.kafka_produce_calls);
  Stats.create("kafka.produce_fails", mystats.kafka_produce_fails);
  Stats.create("kafka.ev_errors", mystats.kafka_ev_errors);
  Stats.create("kafka.ev_others", mystats.kafka_ev_others);
  Stats.create("kafka.dr_errors", mystats.kafka_dr_errors);
  Stats.create("kafka.dr_others", mystats.kafka_dr_noerrors);
  // clang-format on

  std::function<void()> processingFunc = [this]() {
    PerfGenBase::processingThread();
  };
  Detector::AddThreadFunction(processingFunc, "generator");
}

void PerfGenBase::processingThread() {

  if (EFUSettings.KafkaTopic == "") {
    EFUSettings.KafkaTopic = "perfgen_detector";
  }

  KafkaConfig KafkaCfg(EFUSettings.KafkaConfigFile);
  Producer EventProducer(EFUSettings.KafkaBroker, EFUSettings.KafkaTopic,
                         KafkaCfg.CfgParms);

  auto Produce = [&EventProducer](auto DataBuffer, auto Timestamp) {
    EventProducer.produce(DataBuffer, Timestamp);
  };

  EV42Serializer Serializer(kafka_buffer_size, "perfgen", Produce);

  ESSGeometry ESSGeom(64, 64, 1, 1);

  XTRACE(PROCESS, ALW, "GENERATING TEST IMAGE!");
  Udder UdderImage;
  UdderImage.cachePixels(ESSGeom.nx(), ESSGeom.ny(), &ESSGeom);

  int TimeOfFlight{0};
  int EventsPerPulse{500};

  // ns since 1970 - but with a resolution of one second
  uint64_t EfuTimeRef = 1000000000LU * (uint64_t)time(NULL);
  Timer Elapsed; // provide a us timer

  while (runThreads) {
    // ns since 1970 - but with us resolution
    uint64_t EfuTime = EfuTimeRef + 1000 * Elapsed.timeus();
    XTRACE(DATA, DEB, "EFU Time (ns since 1970): %lu", EfuTime);
    Serializer.pulseTime(EfuTime);

    for (int i = 0; i < EventsPerPulse; i++) {
      auto PixelId = UdderImage.getPixel(ESSGeom.nx(), ESSGeom.ny(), &ESSGeom);
      Serializer.addEvent(TimeOfFlight, PixelId);
      mystats.events_udder++;
      TimeOfFlight++;
    }
    // Serializer.checkAndSetPulseTime(EfuTime);

    usleep(EFUSettings.TestImageUSleep);

    /// Kafka stats update - common to all detectors
    /// don't increment as Producer & Serializer keep absolute count
    mystats.kafka_produce_fails = EventProducer.stats.produce_fails;
    mystats.kafka_ev_errors = EventProducer.stats.ev_errors;
    mystats.kafka_ev_others = EventProducer.stats.ev_others;
    mystats.kafka_dr_errors = EventProducer.stats.dr_errors;
    mystats.kafka_dr_noerrors = EventProducer.stats.dr_noerrors;
    mystats.tx_bytes = Serializer.TxBytes;
    TimeOfFlight = 0;
  }
  // \todo flush everything here
  XTRACE(INPUT, ALW, "Stopping generator thread.");
  return;
}

} // namespace PerfGen


text:
<?php

namespace Victoire\Bundle\BusinessEntityBundle\Handler;

use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use Gedmo\Sluggable\Handler\SlugHandlerInterface;
use Gedmo\Sluggable\Mapping\Event\SluggableAdapter;
use Gedmo\Sluggable\SluggableListener;
use Victoire\Bundle\BusinessEntityBundle\Transliterator\Transliterator;
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessTemplate;

/**
 * Sluggable handler which keep twig variable after urlization.
 */
class TwigSlugHandler implements SlugHandlerInterface
{
    /**
     * @var SluggableListener
     */
    protected $sluggable;

    /**
     * {@inheritdoc}
     */
    public function __construct(SluggableListener $sluggable)
    {
        $this->sluggable = $sluggable;
        $this->transliterator = new Transliterator();
    }

    /**
     * {@inheritdoc}
     */
    public function onChangeDecision(SluggableAdapter $ea, array &$config, $object, &$slug, &$needToChangeSlug)
    {
        $this->sluggable->setTransliterator([$this, 'transliterate']);
        $needToChangeSlug = true;
    }

    /**
     * {@inheritdoc}
     */
    public function onSlugCompletion(SluggableAdapter $ea, array &$config, $object, &$slug)
    {
    }

    /**
     * {@inheritdoc}
     */
    public static function validate(array $options, ClassMetadata $meta)
    {
    }

    /**
     * {@inheritdoc}
     */
    public function postSlugBuild(SluggableAdapter $ea, array &$config, $object, &$slug)
    {
        $this->sluggable->setTransliterator([$this, 'transliterate']);
    }

    /**
     * Transliterates the slug and keep twig variable.
     *
     * @param string $text
     * @param string $separator
     * @param object $object
     *
     * @return string
     */
    public function transliterate($text, $separator, $object)
    {
        if ($object instanceof BusinessTemplate) {
            $slug = $this->transliterator->urlize($text, $separator, true);
        } else {
            $slug = $this->transliterator->urlize($text, $separator);
        }

        return $slug;
    }

    /**
     * {@inheritdoc}
     */
    public function handlesUrlization()
    {
        return true;
    }
}


text:
#include "config.h"

#include <cmath>
#include <public/WebFilterOperation.h>
#include <public/WebFilterOperations.h>
#include <wtf/Vector.h>

namespace WebKit {

class WebFilterOperationsPrivate {
public:
    Vector<WebFilterOperation> operations;
};

void WebFilterOperations::initialize()
{
    m_private.reset(new WebFilterOperationsPrivate);
}

void WebFilterOperations::destroy()
{
    m_private.reset(0);
}

void WebFilterOperations::assign(const WebFilterOperations& other)
{
    m_private->operations = other.m_private->operations;
}

bool WebFilterOperations::equals(const WebFilterOperations& other) const
{
    if (other.size() != size())
        return false;
    for (size_t i = 0; i < m_private->operations.size(); ++i) {
        if (other.at(i) != at(i))
            return false;
    }
    return true;
}

void WebFilterOperations::append(const WebFilterOperation& filter)
{
    m_private->operations.append(filter);
}

void WebFilterOperations::clear()
{
    m_private->operations.clear();
}

bool WebFilterOperations::isEmpty() const
{
    return m_private->operations.isEmpty();
}

static int spreadForStdDeviation(float stdDeviation)
{
    // https://dvcs.w3.org/hg/FXTF/raw-file/tip/filters/index.html#feGaussianBlurElement provides this approximation for
    // evaluating a gaussian blur by a triple box filter.
    float d = floorf(stdDeviation * 3 * sqrt(8.f * atan(1.f)) / 4 + 0.5);
    return static_cast<int>(ceilf(d * 3 / 2));
}

void WebFilterOperations::getOutsets(int& top, int& right, int& bottom, int& left) const
{
    top = right = bottom = left = 0;
    for (size_t i = 0; i < m_private->operations.size(); ++i) {
        const WebFilterOperation op = m_private->operations[i];
        if (op.type() == WebFilterOperation::FilterTypeBlur || op.type() == WebFilterOperation::FilterTypeDropShadow) {
            int spread = spreadForStdDeviation(op.amount());
            if (op.type() == WebFilterOperation::FilterTypeBlur) {
                top += spread;
                right += spread;
                bottom += spread;
                left += spread;
            } else {
                top += spread - op.dropShadowOffset().y;
                right += spread + op.dropShadowOffset().x;
                bottom += spread + op.dropShadowOffset().y;
                left += spread - op.dropShadowOffset().x;
            }
        }
    }
}

bool WebFilterOperations::hasFilterThatMovesPixels() const
{
    for (size_t i = 0; i < m_private->operations.size(); ++i) {
        const WebFilterOperation op = m_private->operations[i];
        switch (op.type()) {
        case WebFilterOperation::FilterTypeBlur:
        case WebFilterOperation::FilterTypeDropShadow:
        case WebFilterOperation::FilterTypeZoom:
            return true;
        default:
            break;
        }
    }
    return false;
}

bool WebFilterOperations::hasFilterThatAffectsOpacity() const
{
    for (size_t i = 0; i < m_private->operations.size(); ++i) {
        const WebFilterOperation op = m_private->operations[i];
        switch (op.type()) {
        case WebFilterOperation::FilterTypeOpacity:
        case WebFilterOperation::FilterTypeBlur:
        case WebFilterOperation::FilterTypeDropShadow:
        case WebFilterOperation::FilterTypeZoom:
            return true;
        case WebFilterOperation::FilterTypeColorMatrix: {
            const SkScalar* matrix = op.matrix();
            return matrix[15]
                || matrix[16]
                || matrix[17]
                || matrix[18] != 1
                || matrix[19];
        }
        default:
            break;
        }
    }
    return false;
}

size_t WebFilterOperations::size() const
{
    return m_private->operations.size();
}

WebFilterOperation WebFilterOperations::at(size_t i) const
{
    return m_private->operations.at(i);
}

} // namespace WebKit


text:
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE QuasiQuotes           #-}
{-# LANGUAGE TemplateHaskell       #-}
{-# LANGUAGE TypeFamilies          #-}
import           Yesod
import Data.Maybe (fromJust)
import qualified Data.Text as T
data App = App

mkYesod "App" [parseRoutes|
/         HomeR     GET
/setname  SetNameR  GET POST
/sayhello SayHelloR GET
|]

instance Yesod App

instance RenderMessage App FormMessage where
    renderMessage _ _ = defaultFormMessage

getHomeR :: Handler Html
getHomeR = defaultLayout
    [whamlet|

            Set your name

            Say hello
    |]

checkBoxWidget :: T.Text -> T.Text -> Widget
checkBoxWidget check name = if (T.unpack check) == "True" then toWidget [hamlet| <input type=checkbox name=#{T.unpack name} checked>    |]
                                                          else toWidget [hamlet| <input type=checkbox name=#{T.unpack name} unchecked>  |]

-- Display the set name form
getSetNameR :: Handler Html
getSetNameR = do
    mname <- lookupSession "name"
    mcheck1 <- lookupSession "check1"
    mcheck2 <- lookupSession "check2"
    mcheck3 <- lookupSession "check3"
    mcheck4 <- lookupSession "check4"
    case (mname, mcheck1, mcheck2, mcheck3, mcheck4) of
        (Just name, Just check1, Just check2, Just check3, Just check4) -> defaultLayout [whamlet| <form method=post>
                                                My name is #
                                                <input type=text name=name value=#{fromJust mname}>
                                                 . #
                                                 ^{checkBoxWidget check1 (T.pack "check1")}
                                                 ^{checkBoxWidget check2 (T.pack "check2")}
                                                 ^{checkBoxWidget check3 (T.pack "check3")}
                                                 ^{checkBoxWidget check4 (T.pack "check4")}
                                                <input type=submit value="Set name n' check">
                                    |]
        (_,_,_,_,_)   -> defaultLayout [whamlet| <form method=post>
                                                    My name is #
                                                    <input type=text name=name>
                                                    . #
                                                     ^{checkBoxWidget (T.pack "False") (T.pack "check1")}
                                                     ^{checkBoxWidget (T.pack "False") (T.pack "check2")}
                                                     ^{checkBoxWidget (T.pack "Flase") (T.pack "check3")}
                                                     ^{checkBoxWidget (T.pack "False") (T.pack "check4")}
                                                    <input type=submit value="Set name n' check">
                                    |]

-- Retreive the submitted name from the user
postSetNameR :: Handler ()
postSetNameR = do
    -- Get the submitted name and set it in the session
    name <- runInputPost $ ireq textField "name"
    check1 <- runInputPost $ ireq checkBoxField "check1"
    check2 <- runInputPost $ ireq checkBoxField "check2"
    check3 <- runInputPost $ ireq checkBoxField "check3"
    check4 <- runInputPost $ ireq checkBoxField "check4"
    setSession "name" name
    setSession "check1" $ T.pack $ show check1
    setSession "check2" $ T.pack $ show check2
    setSession "check3" $ T.pack $ show check3
    setSession "check4" $ T.pack $ show check4

    -- After we get a name, redirect to the ultimate destination.
    -- If no destination is set, default to the homepage
    redirectUltDest HomeR

getSayHelloR :: Handler Html
getSayHelloR = do
    -- Lookup the name value set in the session
    mname <- lookupSession "name"
    mcheck1 <- lookupSession "check1"
    mcheck2 <- lookupSession "check2"
    mcheck3 <- lookupSession "check3"
    mcheck4 <- lookupSession "check4"
    case (mname,mcheck1,mcheck2,mcheck3,mcheck4) of

         (Just name, Just check1, Just check2, Just check3, Just check4)-> defaultLayout [whamlet|
Welcome #{name}, the box Nr1. was set on #{show check1}

                                                                                the box Nr2. was set on #{show check2}

                                                                                the box Nr3. was set on #{show check3}

                                                                                the box Nr4. was set on #{show check4}

                                                                                |]
         (_,_,_,_,_) -> do
            -- No name in the session, set the current page as
            -- the ultimate destination and red
    -- After we get a name, redirect to thirect to the
            -- SetName page
            setUltDestCurrent
            setMessage "Please tell me your name"
            redirect SetNameR

main :: IO ()
main = warp 3000 App


text:
Getline.ts
===============

This document describes how the getline.ts interface looks like

**Add New Loan**
------
Method for adding a new loan

**Method Name**

`addNewLoan(owner, description, amount, rate, paybackTimePeriod)`

**Params:**

 * `owner=[string]`
 * `description=[string]`
 * `amount=[number]`
 * `rate=[number]`
 * `paybackTime=[number] // Format: 1468959781804 `

**Get Loan By Id**
------
Should return single loan

**Method**

`getLoanById(id)`

**Params:**

 * `id=[string]`

**Response:**

```javascript
{
  id: '12345',
  amount: '1.23',
  funded: '0.12',
  currenct: 'ETH',
  rate: '0.15',
  laonState: 1
}

```
**Loan State :**

* `0` - INVALID
* `1` - COLLATERAL_COLLECTION
* `2` - FUNDRAISING
* `3` - PAYBACK
* `4` - FINISHED

**Get Loans By Owner**
------
Should return all loans own by the owner

**Method**

`getLoansByOwner(owner)`

**Params:**

 * `owner=[string]`

**Response:**

List of loans described in getLoanById method

 **Get Fundraising Loans**
------
Should return all loans which are in fundraising phase

**Method**

`getFundraisingLoans()`

**Response:**

List of loans described in getLoanById method


text:
<?php

namespace App\Containers\Settings\Tasks;

use App\Containers\Settings\Data\Repositories\SettingRepository;
use App\Ship\Parents\Tasks\Task;

class CreateSettingTask extends Task
{
    /**
     * @var SettingRepository
     */
    private $repository;

    /**
     * CreateSettingTask constructor.
     *
     * @param SettingRepository $repository
     */
    public function __construct(SettingRepository $repository)
    {
        $this->repository = $repository;
    }

    /**
     * @param array $data
     *
     * @return mixed
     */
    public function run(array $data)
    {
        return $this->repository->create($data);
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.wpi.first.wpilibj.templates;

import edu.wpi.first.wpilibj.PIDSource;
import edu.wpi.first.wpilibj.Accelerometer;
import edu.wpi.first.wpilibj.templates.RobotMap;
import edu.wpi.first.wpilibj.Timer;
/**
 *
 * @author Jessie
 */
public class AccelerometerPosition implements PIDSource{

    double a;
    double v;
    double vPrev = 0;
    double x;
    double xPrev = 0;
    double t = 0;
    Accelerometer accelerometer;
    Timer timer;

    public AccelerometerPosition(){
        accelerometer = new Accelerometer(RobotMap.accelerometer);
        timer = new Timer();
        timer.start();
    }

    public double pidGet(){
        a = accelerometer.getAcceleration();
        v = (a * (timer.get() * 1000000 - t)) + vPrev;
        x = (.5 * a * ((timer.get() * 1000000 - t) * (timer.get() * 1000000 - t)) + v * (timer.get() * 1000000 - t) + xPrev);
        t = timer.get() * 1000000;
        vPrev = v;
        double xFinal = x;
        xPrev = x;
        return xFinal;
    }

    public void reset(){
        v = 0;
        x = 0;
    }

}


text:
<?php
/**
 * The contents of this file was generated using the WSDLs as provided by eBay.
 *
 * DO NOT EDIT THIS FILE!
 */

namespace DTS\eBaySDK\Finding\Enums;

/**
 *
 */
class SortOrderType
{
    const C_BEST_MATCH = 'BestMatch';
    const C_BID_COUNT_FEWEST = 'BidCountFewest';
    const C_BID_COUNT_MOST = 'BidCountMost';
    const C_COUNTRY_ASCENDING = 'CountryAscending';
    const C_COUNTRY_DESCENDING = 'CountryDescending';
    const C_CURRENT_PRICE_HIGHEST = 'CurrentPriceHighest';
    const C_DISTANCE_NEAREST = 'DistanceNearest';
    const C_END_TIME_SOONEST = 'EndTimeSoonest';
    const C_PRICE_PLUS_SHIPPING_HIGHEST = 'PricePlusShippingHighest';
    const C_PRICE_PLUS_SHIPPING_LOWEST = 'PricePlusShippingLowest';
    const C_START_TIME_NEWEST = 'StartTimeNewest';
}


text:
<?php
namespace LeBonCoinBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;

class SearchForm extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('searchField', 'search', array(
                "required" => true,
                "attr" => array(
                    "placeholder" => "Rechercher...",
                    "pattern" => "^[A-Za-z0-9_\.\:\-]{3,}$",
                    "title" => "au moins 3 caractères alphanuméric (plus '.' et '_')",
                    "class" => "form-control",
                    "id" => "top-search"
                )
            ))
            ->add('categories', EntityType::class, array(
                'class' => 'LeBonCoinBundle:Categories',
                'choice_label' => 'name',
                'multiple' => true,
                'expanded' => true,
            ))
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => null
        ));
    }
}


text:
<?xml version="1.0"?>
<ruleset name="shapeshift-rules">

    <rule ref="pmd/basic.xml"></rule>
    <!--<rule ref="pmd/braces.xml"/>-->
    <!--<rule ref="pmd/clone.xml"/>-->
    <!--<rule ref="pmd/codesize.xml"/>-->
    <!--<rule ref="pmd/comments.xml"></rule>-->
    <!--<rule ref="pmd/controversial.xml"></rule>-->
    <!--<rule ref="pmd/coupling.xml"></rule>-->
    <!--<rule ref="pmd/design.xml"/>-->
    <!--<rule ref="pmd/empty.xml"/>-->
    <!--<rule ref="pmd/finalizers.xml"/>-->
    <!--<rule ref="pmd/imports.xml"/>-->
    <!--<rule ref="pmd/j2ee.xml"/>-->
    <!--<rule ref="pmd/javabeans.xml"></rule>-->
    <!--<rule ref="pmd/junit.xml"/>-->
    <!--<rule ref="pmd/logging-jakarta-commons.xml"/>-->
    <!--<rule ref="pmd/logging-java.xml"/>-->
    <!--<rule ref="pmd/naming.xml"></rule>-->
    <!--<rule ref="pmd/optimizations.xml"></rule>-->
    <!--<rule ref="pmd/strictexception.xml"></rule>-->
    <!--<rule ref="pmd/strings.xml"/>-->
    <!--<rule ref="pmd/sunsecure.xml"/>-->
    <!--<rule ref="pmd/typeresolution.xml"/>-->
    <!--<rule ref="pmd/unnecessary.xml"/>-->
    <!--<rule ref="pmd/unusedcode.xml"/>-->

    <rule ref="pmd/basic.xml/CollapsibleIfStatements">
        <priority>4</priority>
    </rule>

    <!-- Here's some rules we'll specify one at a time -->
    <!--<rule ref="rulesets/unusedcode.xml/UnusedLocalVariable"/>
    <rule ref="rulesets/unusedcode.xml/UnusedPrivateField"/>
    <rule ref="rulesets/imports.xml/DuplicateImports"/>
    <rule ref="rulesets/basic.xml/UnnecessaryConversionTemporary"/>-->

    <!-- We want to customize this rule a bit, change the message and raise the priority  -->
    <!--<rule ref="rulesets/basic.xml/EmptyCatchBlock" message="Must handle exceptions">
        <priority>2</priority>
    </rule>-->

    <!-- Note we want everything from braces.xml except the WhileLoopsMustUseBracesRule -->
    <!--<rule ref="rulesets/braces.xml">
        <exclude name="WhileLoopsMustUseBracesRule"/>
    </rule>-->
</ruleset>


text:
'use strict';

import _ from 'lodash';
import {ACCOUNT_SERVICE} from 'core/account/account.service';
import {APPLICATION_READ_SERVICE} from 'core/application/service/application.read.service';
import {APPLICATION_WRITE_SERVICE} from 'core/application/service/application.write.service';
import {APPLICATION_NAME_VALIDATION_MESSAGES} from './validation/applicationNameValidationMessages.component';
import {TASK_READ_SERVICE} from 'core/task/task.read.service';
import {VALIDATE_APPLICATION_NAME} from './validation/validateApplicationName.directive';
import {CHAOS_MONKEY_NEW_APPLICATION_CONFIG_COMPONENT} from 'core/chaosMonkey/chaosMonkeyNewApplicationConfig.component';
import {SETTINGS} from 'core/config/settings';

const angular = require('angular');

module.exports = angular
  .module('spinnaker.application.create.modal.controller', [
    require('@uirouter/angularjs').default,
    APPLICATION_WRITE_SERVICE,
    APPLICATION_READ_SERVICE,
    ACCOUNT_SERVICE,
    TASK_READ_SERVICE,
    APPLICATION_NAME_VALIDATION_MESSAGES,
    VALIDATE_APPLICATION_NAME,
    require('./applicationProviderFields.component.js'),
    CHAOS_MONKEY_NEW_APPLICATION_CONFIG_COMPONENT,
  ])
  .controller('CreateApplicationModalCtrl', function($scope, $q, $log, $state, $uibModalInstance, accountService,
                                                     applicationWriter, applicationReader, taskReader, $timeout) {

    let applicationLoader = applicationReader.listApplications();
    applicationLoader.then((applications) => this.data.appNameList = _.map(applications, 'name'));

    let providerLoader = accountService.listProviders();
    providerLoader.then((providers) => this.data.cloudProviders = providers);

    $q.all([applicationLoader, providerLoader]).then(() => this.state.initializing = false);

    this.state = {
      initializing: true,
      submitting: false,
      errorMessages: [],
      permissionsInvalid: false,
    };
    this.data = {

    };
    this.application = {
      cloudProviders: [],
      instancePort: SETTINGS.defaultInstancePort || null,
    };

    let submitting = () => {
      this.state.errorMessages = [];
      this.state.submitting = true;
    };

    let goIdle = () => {
      this.state.submitting = false;
    };

    var navigateTimeout = null;

    let routeToApplication = () => {
      navigateTimeout = $timeout(() => {
        $state.go(
          'home.applications.application.insight.clusters', {
            application: this.application.name,
          }
        );
      }, 1000 );
    };

    $scope.$on('$destroy', () => $timeout.cancel(navigateTimeout));

    let waitUntilApplicationIsCreated = (task) => {
      return taskReader.waitUntilTaskCompletes(task)
        .then(routeToApplication, () => {
          this.state.errorMessages.push('Could not create application: ' + task.failureMessage);
          goIdle();
        });
    };

    let createApplicationFailure = () => {
      this.state.errorMessages.push('Could not create application');
      goIdle();
    };

    this.createApplication = () => {
      return applicationWriter.createApplication(this.application)
        .then(waitUntilApplicationIsCreated, createApplicationFailure);
    };

    this.updateCloudProviderHealthWarning = () => {
      if (!this.application.platformHealthOnlyShowOverride) {
        // Show the warning if platformHealthOnlyShowOverride is being enabled.
        this.data.showOverrideWarning = `Simply enabling the "Consider only cloud provider health when executing tasks"
          option above is usually sufficient for most applications that want the same health provider behavior for
          all stages. Note that pipelines will require manual updating if this setting is disabled in the future.`;
      }
    };

    function permissionsAreValid(permissions) {
      if (permissions.READ.includes(null) || permissions.WRITE.includes(null)) {
        return false;
      }
      if (permissions.READ.length > 0 && permissions.WRITE.length === 0) {
        return false;
      }
      return true;
    }

    this.handlePermissionsChange = (permissions) => {
      this.state.permissionsInvalid = !permissionsAreValid(permissions);
      this.application.permissions = permissions;
      $scope.$digest();
    };

    this.submit = () => {
      submitting();
      this.application.name = this.application.name.toLowerCase();
      if (this.data.cloudProviders.length === 1) {
        this.application.cloudProviders = this.data.cloudProviders;
      }
      this.createApplication();

    };

  });


text:
import React from 'react';

import CoreDivider from '../../Divider';

const Divider = props => <CoreDivider {...props} />;

Divider.displayName = 'Divider';

export default Divider;


text:
'use strict';

const chalk = require('chalk'),
      eyes = require('eyes'),
      request = require('../request');

module.exports = (state, _, cb) => {
  const url = state.conf('api:url');

  if (state.posts.length === 0) {
    state.log.warn('no new posts found to save');
    return cb();
  } else if (!state.feed.id) {
    state.log.error(`feed ${chalk.red(state.feed.uri)} has no database id`);
    return cb();
  }

  state.log.info(`saving ${chalk.blue(state.posts.length)} posts`);

  state.posts.forEach(post => post.feedId = state.feed.id);

  const opts = {
    url: `${url}/bulk/posts`,
    method: 'POST',
    body: state.posts,
    json: true
  };

  request(opts, (err, _, body) => {
    if (err) {
      state.log.error('failed saving posts');
      eyes.inspect(err);
    } else if (!Array.isArray(body)) {
      state.log.error('failed saving posts');
      eyes.inspect(body);
    } else {
      body.forEach((data, index) => {
        const post = state.posts[index];
        if (data.isError) {
          state.log.error(`failed saving post ${chalk.red(post.guid)}`);
          eyes.inspect(data);
        } else {
          state.log.info(`saved post ${chalk.blue(data.id)} ${chalk.green(data.guid)}`);
          post.id = data.id;
        }
      });
    }
    cb(err);
  });
};


text:
package DAO.anotacao;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target (ElementType.METHOD)
@Retention (RetentionPolicy.RUNTIME)
public @interface RecuperaConjunto
{}


text:
package eks

import (
	"github.com/aws/aws-sdk-go/private/protocol"
)

const (

	// ErrCodeAccessDeniedException for service response error code
	// "AccessDeniedException".
	//
	// You don't have permissions to perform the requested operation. The user or
	// role that is making the request must have at least one IAM permissions policy
	// attached that grants the required permissions. For more information, see
	// Access Management (https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html)
	// in the IAM User Guide.
	ErrCodeAccessDeniedException = "AccessDeniedException"

	// ErrCodeBadRequestException for service response error code
	// "BadRequestException".
	//
	// This exception is thrown if the request contains a semantic error. The precise
	// meaning will depend on the API, and will be documented in the error message.
	ErrCodeBadRequestException = "BadRequestException"

	// ErrCodeClientException for service response error code
	// "ClientException".
	//
	// These errors are usually caused by a client action. Actions can include using
	// an action or resource on behalf of a user that doesn't have permissions to
	// use the action or resource or specifying an identifier that is not valid.
	ErrCodeClientException = "ClientException"

	// ErrCodeInvalidParameterException for service response error code
	// "InvalidParameterException".
	//
	// The specified parameter is invalid. Review the available parameters for the
	// API request.
	ErrCodeInvalidParameterException = "InvalidParameterException"

	// ErrCodeInvalidRequestException for service response error code
	// "InvalidRequestException".
	//
	// The request is invalid given the state of the cluster. Check the state of
	// the cluster and the associated operations.
	ErrCodeInvalidRequestException = "InvalidRequestException"

	// ErrCodeNotFoundException for service response error code
	// "NotFoundException".
	//
	// A service resource associated with the request could not be found. Clients
	// should not retry such requests.
	ErrCodeNotFoundException = "NotFoundException"

	// ErrCodeResourceInUseException for service response error code
	// "ResourceInUseException".
	//
	// The specified resource is in use.
	ErrCodeResourceInUseException = "ResourceInUseException"

	// ErrCodeResourceLimitExceededException for service response error code
	// "ResourceLimitExceededException".
	//
	// You have encountered a service limit on the specified resource.
	ErrCodeResourceLimitExceededException = "ResourceLimitExceededException"

	// ErrCodeResourceNotFoundException for service response error code
	// "ResourceNotFoundException".
	//
	// The specified resource could not be found. You can view your available clusters
	// with ListClusters. You can view your available managed node groups with ListNodegroups.
	// Amazon EKS clusters and node groups are Region-specific.
	ErrCodeResourceNotFoundException = "ResourceNotFoundException"

	// ErrCodeResourcePropagationDelayException for service response error code
	// "ResourcePropagationDelayException".
	//
	// Required resources (such as service-linked roles) were created and are still
	// propagating. Retry later.
	ErrCodeResourcePropagationDelayException = "ResourcePropagationDelayException"

	// ErrCodeServerException for service response error code
	// "ServerException".
	//
	// These errors are usually caused by a server-side issue.
	ErrCodeServerException = "ServerException"

	// ErrCodeServiceUnavailableException for service response error code
	// "ServiceUnavailableException".
	//
	// The service is unavailable. Back off and retry the operation.
	ErrCodeServiceUnavailableException = "ServiceUnavailableException"

	// ErrCodeUnsupportedAvailabilityZoneException for service response error code
	// "UnsupportedAvailabilityZoneException".
	//
	// At least one of your specified cluster subnets is in an Availability Zone
	// that does not support Amazon EKS. The exception output specifies the supported
	// Availability Zones for your account, from which you can choose subnets for
	// your cluster.
	ErrCodeUnsupportedAvailabilityZoneException = "UnsupportedAvailabilityZoneException"
)

var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{
	"AccessDeniedException":                newErrorAccessDeniedException,
	"BadRequestException":                  newErrorBadRequestException,
	"ClientException":                      newErrorClientException,
	"InvalidParameterException":            newErrorInvalidParameterException,
	"InvalidRequestException":              newErrorInvalidRequestException,
	"NotFoundException":                    newErrorNotFoundException,
	"ResourceInUseException":               newErrorResourceInUseException,
	"ResourceLimitExceededException":       newErrorResourceLimitExceededException,
	"ResourceNotFoundException":            newErrorResourceNotFoundException,
	"ResourcePropagationDelayException":    newErrorResourcePropagationDelayException,
	"ServerException":                      newErrorServerException,
	"ServiceUnavailableException":          newErrorServiceUnavailableException,
	"UnsupportedAvailabilityZoneException": newErrorUnsupportedAvailabilityZoneException,
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;

namespace StackExchange.Opserver.Data.Dashboard.Providers
{
    public abstract class DashboardDataProvider<TSettings> : DashboardDataProvider where TSettings : class, IProviderSettings
    {
        public TSettings Settings { get; protected set; }

        protected DashboardDataProvider(TSettings settings) : base(settings)
        {
            Settings = settings;
        }
    }

    public abstract class DashboardDataProvider : PollNode
    {
        public abstract bool HasData { get; }
        public string Name { get; protected set; }

        protected DashboardDataProvider(string uniqueKey) : base(uniqueKey) { }

        protected DashboardDataProvider(IProviderSettings settings) : base(settings.Name + "Dashboard")
        {
            Name = settings.Name;
        }

        /// <summary>
        /// Returns the current exceptions for this data provider
        /// </summary>
        public virtual IEnumerable<string> GetExceptions()
        {
            foreach (var p in DataPollers)
            {
                if (p.ErrorMessage.HasValue())
                    yield return p.ParentMemberName + ": " + p.ErrorMessage;
            }
        }

        #region Nodes

        public abstract List<Node> AllNodes { get; }

        public Node GetNodeById(string id)
        {
            return AllNodes.FirstOrDefault(s => s.Id == id);
        }

        public Node GetNodeByHostname(string hostName)
        {
            if (!Current.Settings.Dashboard.Enabled || hostName.IsNullOrEmpty()) return null;
            return AllNodes.FirstOrDefault(s => s.Name.ToLowerInvariant().Contains(hostName.ToLowerInvariant()));
        }

        public virtual IEnumerable<Node> GetNodesByIP(IPAddress ip)
        {
            return AllNodes.Where(n => n.IPs?.Contains(ip) == true);
        }

        public virtual string GetManagementUrl(Node node) { return null; }
        public abstract Task<List<Node.CPUUtilization>> GetCPUUtilization(Node node, DateTime? start, DateTime? end, int? pointCount = null);
        public abstract Task<List<Node.MemoryUtilization>> GetMemoryUtilization(Node node, DateTime? start, DateTime? end, int? pointCount = null);

        public Interface GetInterface(string id) => AllNodes.SelectMany(n => n.Interfaces.Where(i => i.Id == id)).FirstOrDefault();

        public abstract Task<List<Interface.InterfaceUtilization>> GetUtilization(Interface iface, DateTime? start, DateTime? end, int? pointCount = null);

        public Volume GetVolume(string id) => AllNodes.SelectMany(n => n.Volumes.Where(v => v.Id == id)).FirstOrDefault();

        public abstract Task<List<Volume.VolumeUtilization>> GetUtilization(Volume volume, DateTime? start, DateTime? end, int? pointCount = null);

        public Application GetApplication(string id) => AllNodes.SelectMany(n => n.Apps.Where(a => a.Id == id)).FirstOrDefault();

        #endregion

        #region Cache

        protected Cache<T> ProviderCache<T>(
            Func<Task<T>> fetch,
            int cacheSeconds,
            int? cacheFailureSeconds = null,
            bool affectsStatus = true,
            [CallerMemberName] string memberName = "",
            [CallerFilePath] string sourceFilePath = "",
            [CallerLineNumber] int sourceLineNumber = 0)
            where T : class
        {
            return new Cache<T>(memberName, sourceFilePath, sourceLineNumber)
                {
                    AffectsNodeStatus = affectsStatus,
                    CacheForSeconds = cacheSeconds,
                    CacheFailureForSeconds = cacheFailureSeconds,
                    UpdateCache = UpdateFromProvider(typeof (T).Name + "-List", fetch)
                };
        }

        public Action<Cache<T>> UpdateFromProvider<T>(string opName, Func<Task<T>> fetch) where T : class
        {
            return UpdateCacheItem(description: "Data Provieder Fetch: " + NodeType + ":" + opName,
                                   getData: fetch,
                                   addExceptionData: e => e.AddLoggedData("NodeType", NodeType),
                                   logExceptions: true);
        }

        #endregion
    }
}


text:
package org.hisp.dhis.program.hibernate;

import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore;
import org.hisp.dhis.program.ProgramIndicator;
import org.hisp.dhis.program.ProgramIndicatorStore;

/**
 * @author Chau Thu Tran
 */
public class HibernateProgramIndicatorStore
    extends HibernateIdentifiableObjectStore<ProgramIndicator>
    implements ProgramIndicatorStore
{
}