text:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;

using Duality;
using Duality.IO;

namespace Duality.Editor.AssetManagement
{
	/// <summary>
	/// A static helper class that allows to easily perform operations related to the import and export of Resources.
	/// It takes care of resolving importer conflicts, error handling and notifying the editor of changes.
	///
	/// In case you need a customized, hidden or strictly local asset operation, you can use asset operation classes
	/// directly. Otherwise, prefer using the <see cref="AssetManager"/>.
	/// </summary>
	/// <seealso cref="AssetFirstImportOperation"/>
	/// <seealso cref="AssetReImportOperation"/>
	/// <seealso cref="AssetExportOperation"/>
	public static class AssetManager
	{
		private static List<IAssetImporter> importers = new List<IAssetImporter>();

		/// <summary>
		/// A global event that is fired when an import or re-import operation is finished.
		///
		/// Does not fire on simulated operations and only includes operations that are
		/// performed using the <see cref="AssetManager"/> API.
		/// </summary>
		public static event EventHandler<AssetImportFinishedEventArgs> ImportFinished = null;
		/// <summary>
		/// A global event that is fired when an export operation is finished.
		///
		/// Does not fire on simulated operations and only includes operations that are
		/// performed using the <see cref="AssetManager"/> API.
		/// </summary>
		public static event EventHandler<AssetExportFinishedEventArgs> ExportFinished = null;

		/// <summary>
		/// [GET] Enumerates all known <see cref="IAssetImporter"/>s, each represented by a single instance
		/// and sorted by priority.
		/// </summary>
		public static IEnumerable<IAssetImporter> Importers
		{
			get { return importers; }
		}

		internal static void Init()
		{
			foreach (TypeInfo genType in DualityEditorApp.GetAvailDualityEditorTypes(typeof(IAssetImporter)))
			{
				if (genType.IsAbstract) continue;
				IAssetImporter gen = genType.CreateInstanceOf() as IAssetImporter;
				if (gen != null) importers.Add(gen);
			}
			importers.StableSort((a, b) => b.Priority > a.Priority ? 1 : -1);
		}
		internal static void Terminate()
		{
			importers.Clear();
		}

		/// <summary>
		/// Imports the specified set of input source files and returns a set of output Resources.
		/// </summary>
		/// <param name="inputFiles">An enumerable of input source files that should be imported.</param>
		/// <param name="targetBaseDir">The target directory that serves as a base for creating output Resources.</param>
		/// <param name="inputBaseDir">
		/// The base directory of the previously specified input source files,
		/// which is mapped to the target base directory.
		/// </param>
		/// <returns></returns>
		public static AssetImportOutput[] ImportAssets(IEnumerable<string> inputFiles, string targetBaseDir, string inputBaseDir)
		{
			return ImportAssets(inputFiles, targetBaseDir, inputBaseDir, false);
		}
		/// <summary>
		/// Simulates an import operation in order to determine the expected output. No changes are made.
		/// </summary>
		/// <param name="inputFiles">An enumerable of input source files that should be imported.</param>
		/// <param name="targetBaseDir">The target directory that serves as a base for creating output Resources.</param>
		/// <param name="inputBaseDir">
		/// The base directory of the previously specified input source files,
		/// which is mapped to the target base directory.
		/// </param>
		/// <returns></returns>
		public static AssetImportOutput[] SimulateImportAssets(IEnumerable<string> inputFiles, string targetBaseDir, string inputBaseDir)
		{
			return ImportAssets(inputFiles, targetBaseDir, inputBaseDir, true);
		}
		private static AssetImportOutput[] ImportAssets(IEnumerable<string> inputFiles, string targetBaseDir, string inputBaseDir, bool simulate)
		{
			// Early-out, if no input files are specified
			if (!inputFiles.Any()) return new AssetImportOutput[0];

			bool userAbort = false;
			bool success = false;

			// Set up an import operation and process it
			AssetFirstImportOperation importOperation = new AssetFirstImportOperation(inputFiles, targetBaseDir, inputBaseDir);
			importOperation.ConfirmOverwriteCallback = ConfirmOverwriteData;
			importOperation.ImporterConflictHandler = data =>
			{
				IAssetImporter userSelection = ResolveImporterConflict(data);
				if (userSelection == null) userAbort = true;
				return userSelection;
			};
			success = simulate ?
				importOperation.SimulatePerform() :
				importOperation.Perform();

			// Did we actually do something?
			if (!simulate && !userAbort)
			{
				// If the operation was a failure, display an error message in the editor UI.
				if (!success)
				{
					MessageBox.Show(
						string.Format(Properties.GeneralRes.Msg_CantImport_Text, inputFiles.First()),
						Properties.GeneralRes.Msg_CantImport_Caption,
						MessageBoxButtons.OK,
						MessageBoxIcon.Error);
				}

				// Global event handling
				OnImportFinished(importOperation, success);
			}

			return importOperation.Output.ToArray();
		}

		/// <summary>
		/// Re-Imports the specified set of input source files and returns a set of updated output Resources.
		/// </summary>
		/// <param name="localInputFiles">
		/// An enumerable of input source files that are already part of the local media source folder.
		/// </param>
		/// <returns></returns>
		public static AssetImportOutput[] ReImportAssets(IEnumerable<string> localInputFiles)
		{
			return ReImportAssets(localInputFiles, false);
		}
		/// <summary>
		/// Simulates a re-import operation in order to determine the expected output. No changes are made.
		/// </summary>
		/// <param name="localInputFiles">
		/// An enumerable of input source files that are already part of the local media source folder.
		/// </param>
		/// <returns></returns>
		public static AssetImportOutput[] SimulateReImportAssets(IEnumerable<string> localInputFiles)
		{
			return ReImportAssets(localInputFiles, true);
		}
		private static AssetImportOutput[] ReImportAssets(IEnumerable<string> localInputFiles, bool simulate)
		{
			// Early-out, if no input files are specified
			if (!localInputFiles.Any()) return new AssetImportOutput[0];

			// Set up an import operation and process it
			AssetReImportOperation reimportOperation = new AssetReImportOperation(localInputFiles);
			reimportOperation.ImporterConflictHandler = ResolveImporterConflict;
			bool success = simulate ?
				reimportOperation.SimulatePerform() :
				reimportOperation.Perform();

			// Did we actually do something?
			if (!simulate)
			{
				// Notify the editor that we have modified some Resources
				if (reimportOperation.Output.Any())
				{
					IEnumerable<Resource> touchedResources = reimportOperation.Output.Select(item => item.Resource).Res();
					DualityEditorApp.NotifyObjPropChanged(null, new ObjectSelection(touchedResources));
				}

				// Global event handling
				OnImportFinished(reimportOperation, success);
			}

			return reimportOperation.Output.ToArray();
		}

		/// <summary>
		/// Exports the specified set of input Resources and returns a set of generated or updated output source files.
		/// </summary>
		/// <param name="inputResource">The <see cref="Resource"/> to be exported.</param>
		/// <param name="exportDir">The target directory that serves as a base for creating output source files.</param>
		/// <returns></returns>
		public static string[] ExportAssets(ContentRef<Resource> inputResource, string exportDir = null)
		{
			return ExportAssets(inputResource, exportDir, false);
		}
		/// <summary>
		/// Simulates an export operation in order to determine the expected output. No changes are made.
		/// </summary>
		/// <param name="inputResource">The <see cref="Resource"/> to be exported.</param>
		/// <param name="exportDir">The target directory that serves as a base for creating output source files.</param>
		/// <returns></returns>
		public static string[] SimulateExportAssets(ContentRef<Resource> inputResource, string exportDir = null)
		{
			return ExportAssets(inputResource, exportDir, true);
		}
		private static string[] ExportAssets(ContentRef<Resource> inputResource, string exportDir, bool simulate)
		{
			// Early-out, if the input Resource isn't available
			if (!inputResource.IsAvailable) return new string[0];

			// If there is no export directory set, derive it from the Resource path in the Data folder
			if (exportDir == null)
				exportDir = AssetInternalHelper.GetSourceMediaBaseDir(inputResource);

			bool userAbort = false;
			bool success = false;

			// Set up an export operation and process it
			AssetExportOperation exportOperation = new AssetExportOperation(inputResource.Res, exportDir);
			exportOperation.ImporterConflictHandler = data =>
			{
				IAssetImporter userSelection = ResolveImporterConflict(data);
				if (userSelection == null) userAbort = true;
				return userSelection;
			};
			success = simulate ?
				exportOperation.SimulatePerform() :
				exportOperation.Perform();

			// Did we actually do something?
			if (!simulate && !userAbort)
			{
				// If the exporter modified export parameters of the Resource, notify the editor that we have modified it.
				if (exportOperation.IsAssetInfoChanged)
				{
					DualityEditorApp.NotifyObjPropChanged(null,
						new ObjectSelection(inputResource.Res),
						ReflectionInfo.Property_Resource_AssetInfo);
				}

				// If the operation was a failure, display an error message in the editor UI.
				if (!success)
				{
					MessageBox.Show(
						string.Format(Properties.GeneralRes.Msg_CantExport_Text, inputResource.Path),
						Properties.GeneralRes.Msg_CantExport_Caption,
						MessageBoxButtons.OK,
						MessageBoxIcon.Error);
				}

				// Global event handling
				OnExportFinished(exportOperation, success);
			}

			return exportOperation.OutputPaths.ToArray();
		}

		/// <summary>
		/// Determines the source files of the specified <see cref="Resource"/>, which
		/// were used during the most recent import and can be re-used during export and re-import operations.
		/// </summary>
		/// <param name="resource"></param>
		/// <returns></returns>
		public static string[] GetAssetSourceFiles(ContentRef<Resource> resource)
		{
			// Early-out, if the input Resource isn't available
			if (!resource.IsAvailable) return new string[0];

			// If the Resoure provides an explicit hint which source files were used, rely on that.
			AssetInfo assetInfo = resource.Res.AssetInfo;
			string[] sourceFileHint = (assetInfo != null) ? assetInfo.SourceFileHint : null;
			if (sourceFileHint != null && sourceFileHint.Length > 0)
			{
				string baseDir = AssetInternalHelper.GetSourceMediaBaseDir(resource);
				RawList<string> sourceFilePaths = new RawList<string>(sourceFileHint.Length);
				for (int i = 0; i < sourceFileHint.Length; i++)
				{
					if (string.IsNullOrWhiteSpace(sourceFileHint[i]))
						continue;

					string path = Path.Combine(baseDir, sourceFileHint[i].Replace(AssetInfo.FileHintNameVariable, resource.Name));
					sourceFilePaths.Add(path);
				}
				sourceFilePaths.ShrinkToFit();
				return sourceFilePaths.Data;
			}

			// As a fallback, use a simulated export to determine the imported source.
			// This is assuming a symmetrical import-export, which isn't always true.
			return AssetManager.SimulateExportAssets(resource);
		}

		private static bool ConfirmOverwriteData()
		{
			DialogResult result = MessageBox.Show(
				String.Format(Properties.GeneralRes.Msg_ImportConfirmOverwrite_Text),
				Properties.GeneralRes.Msg_ImportConfirmOverwrite_Caption,
				MessageBoxButtons.YesNo,
				MessageBoxIcon.Warning);
			return result == DialogResult.Yes;
		}
		private static IAssetImporter ResolveImporterConflict(IAssetImporterConflictData data)
		{
			SelectAssetImporterDialog dialog = new SelectAssetImporterDialog(
				data.Importers,
				data.DefaultImporter,
				data.InputFiles);
			DialogResult result = dialog.ShowDialog();
			return dialog.SelectedImporter;
		}

		private static void OnImportFinished(AssetImportOperation operation, bool success)
		{
			if (ImportFinished != null)
			{
				AssetImportFinishedEventArgs args = new AssetImportFinishedEventArgs(
					success,
					operation is AssetReImportOperation,
					operation.Input,
					operation.Output);
				ImportFinished(null, args);
			}
		}
		private static void OnExportFinished(AssetExportOperation operation, bool success)
		{
			if (ExportFinished != null)
			{
				AssetExportFinishedEventArgs args = new AssetExportFinishedEventArgs(
					success,
					operation.Input,
					operation.OutputPaths);
				ExportFinished(null, args);
			}
		}
	}
}


text:
package org.apache.flink.python.tests.util;

import org.apache.flink.table.functions.ScalarFunction;

/**
 * Scala UDF for testing.
 */
public class AddOne extends ScalarFunction {
	public long eval(long input) {
		return input + 1;
	}
}

redpajama_set_name: RedPajamaGithub


text:
\documentclass[11pt]{amsart}

\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage{xcolor}

\usetikzlibrary{
  arrows,
  calc,
  decorations.markings,
  decorations.pathreplacing,
  dsp,
  fit,
  positioning
}
\input{../util/airfoils.tex}
\input{../util/wing.tex}
\input{../util/coordinate_systems.tex}
\input{../util/control.tex}

\newcommand{\aero}{\mathrm{aero}}
\newcommand{\airgrid}{\mathrm{air-grid}}
\newcommand{\app}{a}
\newcommand{\climb}{\mathrm{climb}}
\newcommand{\cmd}{\mathrm{cmd}}
\newcommand{\cutin}{\mathrm{cut-in}}
\newcommand{\cutout}{\mathrm{cut-out}}
\newcommand{\cw}{\mathrm{cw}}
\newcommand{\eff}{\mathrm{eff}}
\newcommand{\extra}{\mathrm{extra}}
\newcommand{\figureeight}{\mathrm{figure-eight}}
\newcommand{\grav}{\mathrm{grav}}
\newcommand{\groundinverter}{\mathrm{ground\;inv.}}
\newcommand{\hover}{\mathrm{hover}}
\newcommand{\kiteinverter}{\mathrm{kite\;inv.}}
\newcommand{\kite}{\mathrm{kite}}
\newcommand{\lp}{\mathrm{loop}}
\newcommand{\mx}{\mathrm{max}}
\newcommand{\mn}{\mathrm{min}}
\newcommand{\motor}{\mathrm{motor}}
\newcommand{\nominal}{\mathrm{nom}}
\newcommand{\path}{\mathrm{path}}
\newcommand{\prop}{\mathrm{prop}}
\newcommand{\shaftgrid}{\mathrm{shaft-grid}}
\newcommand{\swept}{\mathrm{swept}}
\newcommand{\tether}{\mathrm{tether}}
\newcommand{\total}{\mathrm{tot}}
\newcommand{\wind}{\mathrm{wind}}
\newcommand{\mass}{\mathrm{mass}}
\newcommand{\power}{\mathrm{power}}
\newcommand{\powertrain}{\mathrm{powertrain}}
\newcommand{\motorout}{\mathrm{motor-out}}

\definecolor{matlab1}{rgb}{0, 0.4470, 0.7410}
\definecolor{matlab2}{rgb}{0.8500, 0.3250, 0.0980}
\definecolor{matlab3}{rgb}{0.9290, 0.6940, 0.1250}
\definecolor{matlab4}{rgb}{0.4940, 0.1840, 0.5560}
\definecolor{matlab5}{rgb}{0.4660, 0.6740, 0.1880}
\definecolor{matlab6}{rgb}{0.3010, 0.7450, 0.9330}
\definecolor{matlab7}{rgb}{0.6350, 0.0780, 0.1840}

\title{Limits on kite mass}
\author{Makani Technologies LLC}
\date{October 6, 2016}

\begin{document}
\maketitle

% \section*{Nomenclature}

% \begin{tabular}{ll}
%   $m_{\kite}$       & Kite mass \\
%   $m_{\total}$      & Combined kite and tether mass \\
%   $m_{\eff}$        & Effective mass ($m_{\eff} = m_{\kite} + m_{\tether}/3)$ for modeling dynamics \\
%   $\mathit{TWR}$    & Thrust-to-weight ratio \\
%   $\eta_{\airgrid}$ & Efficiency of power conversion from the grid to aerodynamic power \\

% \end{tabular}

\section{Vertical take-off and landing}

The relationship between the required grid power for hover and mass
is:
%
\begin{equation}
  \label{eqn:hover_power}
  P_{\hover} = \frac{1}{\eta_{\shaftgrid} \cdot \mathit{FM}}
               \sqrt{\frac{(\mathit{TWR} \cdot m_{\total} g)^3}
                          {2 \rho_{\mn} f N_{\prop} A_{\prop}}}
\end{equation}
%
where $\mathit{FM}$ is the figure-of-merit of the propellers,
$\mathit{TWR}$ is the thrust-to-weight ratio, $f$ is the fraction of
motors available in a motor-out situation, and $m_{\total}$ is the
combined kite and tether mass.\footnote{The strict limits that
  vertical take-off and landing places on mass and power have
  been covered extensively in other documents
  \cite{tvanalsenoy_power_train}}

Because of the significant cost of the ground-side inverter and other
power components, which scales approximately linearly with power,
vertical take-off and landing (VTOL) systems likely do not make
economic sense unless $P_{\hover} \le P_{\mx}$.  This constraint may
be relaxed somewhat for multi-kite systems, if it is only necessary to
hover a single kite at a time.  In this case, the kite is likely
limited by the available shaft power from the motors.  In a
well-designed system, the available shaft power from the motors should
be approximately, $P_{\mx} / \eta_{\shaftgrid}$, where $P_{\mx}$ is
the per-kite rated power, so that the power system is fully utilized
during generation.  In this case, the constraint imposed by VTOL is:
$\eta_{\shaftgrid}^2 P_{\hover} / f \le P_{\mx}$.  Note that the extra
factor of $\eta_{\shaftgrid} / f$ accounts for the fact that
Eq. \ref{eqn:hover_power} is written in terms of ground power, and
also that it is necessary to acccount for the motor-out fraction again
in a shaft power limited system.

For a single kite M600-like system, assuming $P_{\mx} = 600$ kW,
$\eta_{\shaftgrid} = 0.83$, $\mathit{FM} = 0.68$, $\rho_{\mn} = 0.95$
kg/m$^3$, $A_{\prop} = 3.8$ m$^2$, and $\mathit{TWR} = 1.3$,
$f = 3/4$, this sets a reasonable mass limit of $m_{\total} < 1338$
kg.  For a multi-kite M600-like system, with equivalent parameters,
the mass limit is $m_{\total} < 1416$ kg.  If the motor-out fraction
is increased to $f = 7/8$, then the single- and multi-kite limits are
1409 kg and 1652 kg, respectively.  Above these mass limits, VTOL
becomes expensive quickly, scaling as
$P_{\hover} \propto (m/m_{\nominal})^{3/2}$.

It is of course possible to increase the VTOL lifting ability through
significant design changes to the M600.  The most significant
parameter to change is rotor disk area.  In particular,
Eq. \ref{eqn:hover_power} can be used to solve for the rotor disk area
that meets a given power requirement.  Later in this paper, limits on
the power density of a kite system will be derived, so it is actually
more useful to reexpress Eq. \ref{eqn:hover_power} as a relationship
between maximum power density and disk mass loading:
%
\begin{equation}
  \label{eqn:hover_power2}
  \left(\frac{P_{\mx}}{m_{\total}}\right)^2 >
  k \left(\frac{m_{\total}}{N_{\prop} A_{\prop}}\right)
\end{equation}
%
Assuming the same values as above, the proportionality constant here
is $k \approx 6400$ W$^2$-m$^2$/kg$^3$.  To get a feel for the range
of values this constant could take across kite systems, the value
without motor-out capability is $k \approx 2700$ W$^2$-m$^2$/kg$^3$.

\section{Crosswind flight}

Crosswind flight does not place as strict of a limit on mass as VTOL;
however it still imposes mass limitations stricter than what would be
required for traditional flight vehicles.  The main consequences of
increased mass in crosswind flight are 1) an increase in power
required to maintain a minimum airspeed during climb, 2) an increase
in minimum turning radius, and 3) an increase in power and tension
variations around a loop.  Each of these consequences are analyzed in
detail below.

\subsection{Minimum airspeed climb}

A reasonable requirement for a kite system is to be able to maintain
the minimum allowed airspeed, $v_{\app,\mn}$, while climbing up the loop
with low or zero wind.  Assuming a circular flight path, this results
in the power requirement for climbing of
%
\begin{equation}
  P_{\climb} = \frac{m_{\eff} g_{\parallel} v_{\app,\mn}}{\eta_{\airgrid}}
\end{equation}
%
which may be converted to a limitation on the maximum reasonable
effective mass:
%
\begin{equation}
  \label{eqn:mass_minimum_airspeed_climb}
  m_{\eff} < \frac{\eta_{\airgrid} P_{\mx}}{g_{\parallel} v_{\app,\mn}}
\end{equation}
%
For an M600-like system, assuming $P_{\mx} = 600$ kW,
$\eta_{\airgrid} = 0.67$, a flight path elevation angle of
25$^{\circ}$, and $v_{\app,\mn} = 30$ m/s, the maximum reasonable
effective mass is $m_{\eff} = 1507$ kg.\footnote{TODO: Add drag to
  calculation.}

\begin{figure}[h]
\begin{center}
  \begin{tikzpicture}
    \begin{scope}[scale=2]]
      % Downstrokes.
      \draw[arrows={latex-}] ({sqrt(2) + 1}, 0) arc (0:135:1);
      \draw                  ({sqrt(2) + 1}, 0) arc (0:-135:1);

      \draw[arrows={latex-}] ({-(sqrt(2) + 1)}, 0) arc (180:45:1);
      \draw                  ({-(sqrt(2) + 1)}, 0) arc (180:315:1);

      % Upstrokes.
      \draw[arrows={-latex}] ({-sqrt(2)/2}, {-sqrt(2)/2}) --
      ({ sqrt(2)/2}, { sqrt(2)/2});
      \draw[arrows={-latex}] ({ sqrt(2)/2}, {-sqrt(2)/2}) --
      ({-sqrt(2)/2}, { sqrt(2)/2});

      \draw ({-sqrt(2) - 0.1}, 0) -- ({-sqrt(2) + 0.1}, 0);
      \draw ({-sqrt(2)}, -0.1) -- ({-sqrt(2)}, 0.1);

      \draw ({sqrt(2) - 0.1}, 0) -- ({sqrt(2) + 0.1}, 0);
      \draw ({sqrt(2)}, -0.1) -- ({sqrt(2)}, 0.1);

      \draw[dashed] (0, 0) -- ({sqrt(2)}, 0);
    \end{scope}

    \draw[arrows={latex-latex}] (1, 0) arc (0:45:1);
    \path (1, 0) arc (0:22.5:1) node[above right] {$\psi_{\climb}$};

    \draw [decorate, decoration={brace, amplitude=5pt}]
      ({-sqrt(2)*2}, 0) -- ({-sqrt(2)*2 - 1}, {sqrt(3)})
      node[midway, below left] {$R_{\path}$};

    \draw [decorate, decoration={brace, amplitude=5pt}]
      (0, 0) -- ({-(sqrt(2) * 2)}, 0)
      node[midway, below=0.2] {$\delta$};

  \end{tikzpicture}
  \caption{Figure-eight flight path.}
\end{center}
\end{figure}

One concept that attempts to relax the constraints imposed by a
minimum airspeed climb is to fly figure-eights where the upstrokes are
the long paths between downstrokes.  Now the power to climb is reduced
by the sine of the climb angle:
%
\begin{equation}
  \label{eqn:mass_minimum_airspeed_climb2}
  P_{\climb} = \frac{m_{\eff} g_{\parallel} v_{\app,\mn} \sin \psi_{\climb}}
                    {\eta_{\airgrid}}
\end{equation}
%
Unfortunately, the figure-eight pattern has significant negative
effects on power generation.  One effect is that it pushes part of the
path off-downwind.  Specifically, the center of each of the loops of
the eight will be approximately
$\delta = R_{\path} / \sin \psi_{\climb}$ off-downwind.  Thus, there
will be a power loss roughly proportional to
%
\begin{equation}
  \eta_{\figureeight} \sim \cos^3 (\sin^{-1}(\sin \gamma / \sin \psi_{\climb}))
\end{equation}
%
where $\gamma$ is the half-cone angle of the flight path.  Even for
moderate climb angles, say $\psi_{\climb} = 45^{\circ}$, these losses
are substantial, $\eta_{\figureeight} \sim 0.67$ assuming
$\gamma = 20^{\circ}$ \footnote{For single kite systems, the required
  low elevation angle of the flight path puts a strict limit on the
  maximum half-cone angle.  This can be relaxed somewhat for
  multi-kite systems.}.  And the estimated efficiency drops off
quickly with shallower climb angles, $\eta_{\figureeight} = 0.38$ at
$\psi_{\climb} = 30^{\circ}$.  A second slightly harder to quantify
effect is that the figure-eight will take longer to fly than the
equivalent set of two independent circles, which also reduces power
efficiency.

Nonetheless, flying figure-eights does offer an approach to increasing
the maximum mass calculated with
Eq. \ref{eqn:mass_minimum_airspeed_climb} by a factor of, very
roughly, 1.5, while sacrificing some power efficiency.  For an
M600-like system flying figure-eights, the maximum reasonable
effective mass is, again very roughly, 2300 kg.

Equations \ref{eqn:mass_minimum_airspeed_climb} and
\ref{eqn:mass_minimum_airspeed_climb2} set a fairly strict limit on
the power density of kite systems, which is independent of system
scale.  Using the same parameters used above for the M600 system,
which should apply equally well to a generic kite system, the power
density for a kite system flying a circular path must be greater than
400 W/kg, and the power density for a kite system flying a
figure-eight must be greater than roughly 265 W/kg.

\subsection{Turning radius}

The ability of a kite to turn around a tight circular path is
inversely proportional to its mass.  Higher masses will eventually
force either a larger path radius or an excessively large roll angle.
A larger path radius leads to a longer, draggier, and heavier tether
as well as larger swings in tension and power.  Similarly, an
excessively large roll angle has negative consequences due to the
reduced projected wing area normal to the wind.

To quantify these effects, it is useful to derive the exact
relationship between wing mass and turning radius.  This relationship
can be found by balancing forces in the stability axes' y-z plane.  To
simplify the calculation, the tether is appoximated as a straight line
from the ground-station to the bridle point.  Other effects on the
tether such as the catenary from gravity are ignored.

\begin{figure}[h]
\begin{center}
  \begin{tikzpicture}[scale=0.5]
    \begin{scope}[shift={(-5, 0)}, scale=0.3, rotate=-10]
      \DrawWingFront[]
      \draw[line width=1.5pt, -latex] (4, 1) -- (9, 1) node[midway, above] {$-Y$};
      \draw[line width=1.5pt, -latex] (0, 5) -- (0, 12) node[midway, right] {$L$};
      \draw (-5.86, -0.13) -- (0, -4.92);
      \draw (5.86, -0.13) -- (0, -4.92);
      \draw[dashed] (0, -4.92) -- (0, -15);
    \end{scope}
    \node at (-5, -3) {$\phi_t$};
    \draw[line width=1.5pt, -latex] (-5.25, -1.45) --
    (-3.5, -4.3) node[midway, above right] {$t$};
    \draw[line width=1.5pt, -latex] (-3.5, -1) -- (-2, -2)
    node[below right] {$W$};
    \draw (-5.25, -1.45) -- (0, -10) node[midway, above right] {$l_t$};
    %\draw[dashed] (-5.25, -1.45) -- (-0.975, 1.175);
    \node at (-0.5, -8.5) {$\gamma$};
    \draw[dashed] (0, -10) -- (0, -5);
    %\draw[dashed] (-5, 0) -- (-10, 0) node[near end, above] {$-\phi$};
    %\draw[line width=1.5pt, -latex] (-7, 0) -- (-9, 0) node[midway, below]
    %{$mv^2/R$};
    \DrawCoordinateSystem{shift={(0, -10)}, scale=1}
                         {$x_{\cw}$}{$y_{\cw}$}{$z_{\cw}$}
  \end{tikzpicture}
  \caption{Diagram of force balance in the stability axes' y-z plane.}
\end{center}
\end{figure}

It is easiest to conduct the force balance along axes that are
parallel and perpendicular to the tether.  Because the wing is forced
to fly on the surface of a sphere with radius equal to the tether
length, $l_t$, the acceleration parallel to the tether is
$a_{\parallel} = v_i^2/l_t$.  The lift, pylon side force, and weight
each have components along the direction perpendicular to the tether.
Together, these create an acceleration perpendicular to the tether
given by
%
\begin{equation}
m_{\eff} a_{\bot} = L \sin \phi_t - Y \cos \phi_t -
W_{\cw, x} \cos \gamma - W_{\cw, z} \sin \gamma
\end{equation}
%
Here $m_{\eff}$ is the effective mass of the kite, which is given by
$m_{\eff} = m_{\kite} + m_{\mathrm{tether}} / 3$.  The extra term from
the tether mass comes from calculating the acceleration of a point
mass at the end of a rigid rod due to a force applied at the point
mass.  Also, a few small approximations were made such as ignoring
forces from motor thrust, ignoring the component of drag along the
stability z-axis, and ignoring the cosine term from projecting the
lift vector onto the stability z-axis.

The acceleration projected onto the crosswind flight plane is the
acceleration relevant for following a circular path.  The parallel and
perpendicular accelerations can be combined, projected onto the
crosswind $x$-axis as follows:
%
\begin{align}
  \label{eqn:full_curvature}
  \frac{m_{\eff} v_i^2}{r} =&\;
    \frac{m_{\eff} v_i^2}{l_t} \sin \gamma +
    \frac{1}{2} \rho A v_{\app}^2 \left(C_L \sin \phi_t - C_Y \cos \phi_t \right) \cos \gamma \\ \notag
  & - m (g_{\cw,x} \cos \gamma +
  g_{\cw,z} \sin \gamma) \cos \gamma
\end{align}
%
For the purposes of this discussion, Eq. \ref{eqn:full_curvature} may
be simplified for the turn about the bottom of the loop, directly
downwind, while ignoring some of the smaller terms:
%
\begin{equation}
  r \approx \frac{m_{\eff} v_i^2}
                 {\frac{1}{2} \rho A v_{\app}^2 C_L \sin \phi_t \cos \gamma -
                 m g_{\parallel} \cos^2 \gamma}
\end{equation}

The tether roll angle, $\phi_t$, is the primary control variable for
turning the kite around the path.  It is also possible to use $C_L$ or
$C_Y$ to turn, but these variables significantly affect power
production, so they are likely set by other considerations.  At the
absolute minimum, it is necessary to be able to set $\phi_t$ such that
$r = R_{\path}$ to fly a circle.  However, to be able to {\it control}
the kite it is necessary to have an available-to-desired centripetal
force ratio, $\mathit{CFR}$, greater than one, a similar concept to a
thrust-to-weight ratio.  Thus, the constraint is that there is some
$\phi_t$ such that $1/r > \mathit{CFR} / R_{\path}$.  A realistic
centripetal force ratio may be $\mathit{CFR} \sim 1.5$.  The above
considerations result in the following constraint on path radius:
%
\begin{equation}
  R_{\path} > \mathit{CFR} \cdot
              \frac{m v_{i,\mn}^2}
                   {\frac{1}{2} \rho v_{i,\mn}^2 C_L A \sin \phi_{t,\mx} \cos \gamma_{\mx} -
                    m g_{\parallel} \cos^2 \gamma_{\mx}}
\end{equation}
%
Note that the apparent wind speed was replaced by an inertial speed
because it should still be possible to turn without wind!

The constraint on path radius can be converted to a constraint on
minimum tether length for a given kite mass:
%
\begin{equation}
  l_{t,\mn} > l_{t_0} \frac{m}{m_0 - m}
\end{equation}
%
where the characteristic tether length $l_{t_0}$ is:
%
\begin{equation}
  l_{t_0} = \mathit{CFR} \cdot
  \frac{m_{\eff} v_{i,\mn}^2}{m g_{\parallel} \sin(\gamma_{\mx}) \cos^2(\gamma_{\mx})}
\end{equation}
%
and the characteristic mass $m_0$ is:
%
\begin{equation}
  \label{eqn:characteristic_mass}
  m_0 = \frac{\frac{1}{2} \rho v_{i,\mn}^2 A C_L \sin(\gamma_{\mx} + \phi_{\mx})}
             {g_{\parallel} \cos(\gamma_{\mx})}
\end{equation}

Clearly, this gives an absolute hard limit on mass of $m < m_0$.  This
limit can be tightened somewhat by additionally specifying that the
derivative of the {\it minimum} tether length with respect to
effective mass should not grow faster than the derivative of the
tether length with respect to effective mass:
%
\begin{equation}
  m < m_0 - \sqrt{\frac{l_{t_0} m_0 \lambda_t}{3}}
\end{equation}
%
where $\lambda_t$ is the linear mass density of the tether.

For an M600-like system, assuming $\mathit{CFR} = 1.5$, $\rho = 0.95$
kg/m$^3$, $v_{i,\mn} = 30$ m/s, $\gamma_{\mx} = 20^{\circ}$,
$\phi_{\mx} = 30^{\circ}$, $\lambda_t = 1$ kg/m, and a flight path
elevation angle of $25^{\circ}$, $m_0 \approx 2700$ kg and
$l_{t_0} \approx 540$ m. This implies that $m_{\kite} < 2000$ kg.
And, ideally $m_{\kite}$ should be significantly less to avoid a
runaway in mass.

Equation \ref{eqn:characteristic_mass} sets a fairly strict limit on
wing mass loading, which is independent of system scale.
Specifically, to be able to fly in a circle on a reasonable length
tether, a kite system must have a wing mass loading of less than 60
kg/m$^2$.

\subsection{Tension and power variation}
This section is not finished yet.

% \section{Designing a kite}

% \begin{table}[h]
%   \begin{tabular}{cccc}
%     \hline
%     \hline
%     Parameter               & Symbol               & Value              & Units \\
%     \hline
%     Min. power density      & $\rho_{\power}$      & 400                & W/kg \\
%     Max. wing mass loading  & $\sigma_{\mass}$     & 60                 & kg/m$^2$ \\
%     M600 powertrain density & $\rho_{\powertrain}$ & $1.25 \times 10^3$ & W/kg \\
%     \hline
%     \hline
%   \end{tabular}
% \end{table}

% Choose a rated power: $P_{\mx} = 600$ kW.

% Use the minimum power density to find the maximum effective mass: $P_{\mx} / \rho_{\power} = 1500$ kg.

% Select a lower mass for margin: $m_{\eff, \mx} = 1200$ kg.

% Estimate the amount of kite mass: $m_{\kite, \mx} = 1100$ kg.

% Estimate the total mass: $m_{\total, \mx} = 1400$ kg.

% Use Eq. \ref{} to estimate total rotor area: $N_{\prop} A_{\prop} > 48.8$ m$^2$.

% For current motors, $P_{\mx} = 600$ kW implies $N_{\prop} = 8$.

% Thus, $A_{\prop} = 6.1$ m$^2$ and $R_{\prop} = 1.4$ m.

% Use maximum wing mass loading to determine a minimum wing area:
% $m_{\kite, \mx} / \sigma_{\mass} = 18$ m$^2$.

% Select a higher area for margin: $A_{\kite} = 25$ m$^2$.

\section{Conclusions}

\begin{itemize}

\item For a system with the same aerodynamic and geometric properties
  as the M600, VTOL imposes a {\it total} mass limit of 1200 kg; the
  minimum airspeed climb imposes an {\it effective} mass limit of 1500
  kg (this increases to 2300 kg for a figure-eight flight path); and
  the turning radius imposes a {\it kite} mass limit of 2000 kg.

\item According to the minimum airspeed climb criterion, a kite that
  flies circles must have a power density, referenced to {\it
    effective} mass, of greater than 400 W/kg.  A kite that flies
  figure-eights may relax this to roughly 265 W/kg.  A kite with a
  ground-based power system (i.e. pumping kite) can relax these limits
  even further, potentially to 200 W/kg for figure-eights, due to a
  more efficient power conversion process. These limits are
  essentially independent of scale.

\item Given that the specific power of our powertrains is ~1.25 kW/kg,
  approximately 1/3 to 1/2 of the system weight will be the
  powertrain, independent of scale.  For an M600-like VTOL system,
  this leaves $\sim 500$ kg for structure, servos, etc.

\item After a power density is selected, which meets the limit above,
  Eq. \ref{eqn:hover_power2} may be used to size the total rotor area.

\item According to the turning radius criterion, a kite must have a
  wing mass loading, referenced to {\it kite} mass, of less than 60
  kg/m$^2$.  Again, this limit is independent of scale.

\item At the 600 kW scale, designing a system that supports VTOL will
  require substantially reducing the maximum tension.  Because of the
  square-cube law, larger scales will likely require significant
  topology changes (e.g. more bridling, tailless variants, or
  multi-kites) coupled with a reduction in maximum tension.
\end{itemize}

\begin{thebibliography}{1}
\bibitem{tvanalsenoy_power_train} Alsenoy, Thomas.
  ``Airborne wind powertrain trade-off study.''
  \texttt{Drive > Makani Teams > Engineering > 01\_System\_Engineering > Papers (internal)}. 2016.
\end{thebibliography}

\end{document}


text:
#ifndef JUCER_COMPONENTLAYOUTPANEL_H_INCLUDED
#define JUCER_COMPONENTLAYOUTPANEL_H_INCLUDED

#include "jucer_ComponentLayoutEditor.h"
#include "jucer_EditingPanelBase.h"

//==============================================================================
class ComponentLayoutPanel  : public EditingPanelBase
{
public:
    //==============================================================================
    ComponentLayoutPanel (JucerDocument& doc, ComponentLayout& l)
        : EditingPanelBase (doc,
                            new LayoutPropsPanel (doc, l),
                            new ComponentLayoutEditor (doc, l)),
          layout (l)
    {
    }

    ~ComponentLayoutPanel()
    {
        deleteAllChildren();
    }

    void updatePropertiesList()
    {
        ((LayoutPropsPanel*) propsPanel)->updateList();
    }

    Rectangle<int> getComponentArea() const
    {
        return ((ComponentLayoutEditor*) editor)->getComponentArea();
    }

    Image createComponentSnapshot() const
    {
        return ((ComponentLayoutEditor*) editor)->createComponentLayerSnapshot();
    }

    ComponentLayout& layout;

private:
    class LayoutPropsPanel  : public Component,
                              public ChangeListener
    {
    public:
        LayoutPropsPanel (JucerDocument& doc, ComponentLayout& l)
            : document (doc), layout (l)
        {
            layout.getSelectedSet().addChangeListener (this);
            addAndMakeVisible (propsPanel);
        }

        ~LayoutPropsPanel()
        {
            layout.getSelectedSet().removeChangeListener (this);
            clear();
        }

        void resized()
        {
            propsPanel.setBounds (4, 4, getWidth() - 8, getHeight() - 8);
        }

        void changeListenerCallback (ChangeBroadcaster*)
        {
            updateList();
        }

        void clear()
        {
            propsPanel.clear();
        }

        void updateList()
        {
            clear();

            if (layout.getSelectedSet().getNumSelected() == 1) // xxx need to cope with multiple
            {
                if (Component* comp = layout.getSelectedSet().getSelectedItem (0))
                    if (ComponentTypeHandler* const type = ComponentTypeHandler::getHandlerFor (*comp))
                        type->addPropertiesToPropertyPanel (comp, document, propsPanel);
            }
        }

    private:
        JucerDocument& document;
        ComponentLayout& layout;
        PropertyPanel propsPanel;
    };
};

#endif   // JUCER_COMPONENTLAYOUTPANEL_H_INCLUDED


text:
package com.horntail.music.tmp3.fragments;

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

import com.horntail.music.tmp3.R;
import com.horntail.music.tmp3.adapters.MainFragmentAdapter;
import com.ogaclejapan.smarttablayout.SmartTabLayout;

/**
 * A simple {@link Fragment} subclass.
 */
public class MainFragment extends Fragment {

    public MainFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_main, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle bundle) {
        MainFragmentAdapter adapter = new MainFragmentAdapter(getContext(), getChildFragmentManager());
        ViewPager viewPager = view.findViewById(R.id.view_pager_main);
        //reference to tabLayout
        SmartTabLayout tabLayout = view.findViewById(R.id.sliding_tabs_main);
        //install the adapter
        viewPager.setAdapter(adapter);
        //set tabLayout with viewpager
        tabLayout.setViewPager(viewPager);
    }

}


text:
import Ember from 'ember';

const {Component, computed, inject, observer} = Ember;
const {alias} = computed;

export default Component.extend({
    tagName: 'aside',
    classNames: 'gh-alerts',

    notifications: inject.service(),

    messages: alias('notifications.alerts'),

    messageCountObserver: observer('messages.[]', function () {
        this.sendAction('notify', this.get('messages').length);
    })
});


text:
from flask import Flask, make_response

app = Flask(__name__)

@app.route('/artigos')
def artigos():
    "este endpoint retorna a lista de artigos"

@app.route('/paginas')
def paginas():
    "este endpoint retorna a lista de paginas"

@app.route('/contato')
def contato():
    "este endpoint retorna o form de contato"

######################################
# Esta parte poderia ser uma extensão
######################################
@app.route('/sitemap.xml')
def sitemap():
    items = [
        '<url><loc>{0}</loc></url>'.format(page)
        for page in ['/artigos', '/paginas', '/contato']
    ]
    sitemap_xml = (
        '<?xml version="1.0" encoding="UTF-8"?>'
        '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
        '{0}</urlset>'
    ).format(''.join(items)).strip()
    response = make_response(sitemap_xml)
    response.headers['Content-Type'] = 'application/xml'
    return response
#######################################
# / Esta parte poderia ser uma extensão
#######################################

app.run(debug=True)


text:
"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * @internalapi
 * @module vanilla
 */
/** */
var utils_1 = require("./utils");
var baseLocationService_1 = require("./baseLocationService");
/** A `LocationServices` that uses the browser hash "#" to get/set the current location */
var HashLocationService = (function (_super) {
    __extends(HashLocationService, _super);
    function HashLocationService(router) {
        var _this = _super.call(this, router, false) || this;
        window.addEventListener('hashchange', _this._listener, false);
        return _this;
    }
    HashLocationService.prototype._get = function () {
        return utils_1.trimHashVal(this._location.hash);
    };
    HashLocationService.prototype._set = function (state, title, url, replace) {
        this._location.hash = url;
    };
    HashLocationService.prototype.dispose = function (router) {
        _super.prototype.dispose.call(this, router);
        window.removeEventListener('hashchange', this._listener);
    };
    return HashLocationService;
}(baseLocationService_1.BaseLocationServices));
exports.HashLocationService = HashLocationService;
//# sourceMappingURL=hashLocationService.js.map


text:
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}

print residents['Puffin'] # Prints Puffin's room number

# Your code here!
print residents['Sloth']
print residents['Burmese Python']


text:
package com.cosmos.workflow.runtime.xml.initializer;

import java.util.HashMap;
import java.util.List;

import org.dom4j.Element;

import com.cosmos.utils.text.StringUtils;
import com.cosmos.workflow.activities.sequence.action.network.ssh.SSHExecActivity;
import com.cosmos.workflow.runtime.WorkflowRuntimeException;
import com.cosmos.workflow.runtime.xml.IXmlInitializer;

public class SSHExecActivityInitializer implements IXmlInitializer<SSHExecActivity>{

	@Override
	public void init(SSHExecActivity activity, Element item)
			throws WorkflowRuntimeException {
		String client = item.attributeValue("client");
		String charset = item.attributeValue("charset");
		String out = item.attributeValue("out");
		String arguments = item.attributeValue("arguments");
		String timeout = item.attributeValue("timeout");
		String command = item.getTextTrim();
		if(StringUtils.isEmptyOrNull(client) ||
		    StringUtils.isEmptyOrNull(charset) ||
			StringUtils.isEmptyOrNull(out) ||
			StringUtils.isEmptyOrNull(command)){
			throw new WorkflowRuntimeException("必填项不能为空!");
		}
		activity.setCharset(charset);
		activity.setClient(client);
		activity.setOut(out);
		activity.setCommand(command);
		if(StringUtils.isEmptyOrNull(arguments)){
			activity.setArguments(new String[0]);
		} else {
			activity.setArguments(arguments.split(","));
		}
		if(timeout != null){
			try {
				activity.setTimeout(new Integer(timeout));
			} catch (NumberFormatException e) {
				activity.setTimeout(0);
			}
		}
		Element config = item.element("ssh-environment");
		if(config != null){
			@SuppressWarnings("unchecked")
			List<Element> properties = config.elements("property");
			if(properties.size() !=0){
				HashMap<String, String> pr = new HashMap<String, String>();
				for (Element property : properties) {
					pr.put(property.attributeValue("key"), property.attributeValue("value"));
				}
				activity.setEnv(pr);
			}
		}
	}

}


text: Your thing wasn't found. 404, y'all.


text:
package org.apache.aries.blueprint.jexl.evaluator;

import java.util.*;

import org.apache.aries.blueprint.ext.evaluator.PropertyEvaluatorExt;
import org.apache.commons.jexl2.Expression;
import org.apache.commons.jexl2.JexlEngine;
import org.apache.commons.jexl2.MapContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JexlPropertyEvaluator implements PropertyEvaluatorExt {

    private static final Logger LOGGER = LoggerFactory.getLogger(JexlPropertyEvaluator.class);

    public Object evaluate(String expression, Map<String, Object> properties) {
        try {
            JexlEngine engine = new JexlEngine();
            MapContext context = new MapContext(properties);
            Expression exp = engine.createExpression(expression);
            return exp.evaluate(context);
        } catch (Exception e) {
            LOGGER.info("Could not evaluate expression: {}", expression);
            LOGGER.info("Exception:", e);
            return null;
        }
    }

}


text:
fn peel(food: Option<Food>) -> Option<Peeled> {
    match food {
        Some(food) => Some(Peeled(food)),
        None       => None,
    }
}

// Like above, we need to know if the peeled food exists before chopping.
fn chop(peeled: Option<Peeled>) -> Option<Chopped> {
    match peeled {
        Some(Peeled(food)) => Some(Chopped(food)),
        None               => None,
    }
}

// Similar to previous checks, but using `map()` instead of `match`.
fn cook(chopped: Option<Chopped>) -> Option<Cooked> {
    chopped.map(|Chopped(food)| Cooked(food))
}

// Alternatively, we can chain multiple uses of `map()` to simplify
// the above process.
fn process(food: Option<Food>) -> Option<Cooked> {
    food.map(|f| Peeled(f))
        .map(|Peeled(f)| Chopped(f))
        .map(|Chopped(f)| Cooked(f))
}

// It's important to know whether there's food or not before trying to eat it!
fn eat(food: Option<Cooked>) {
    match food {
        Some(food) => println!("Mmm. I love {:?}", food),
        None       => println!("Oh no! It wasn't edible."),
    }
}

fn main() {
    let apple = Some(Food::Apple);
    let carrot = Some(Food::Carrot);
    let potato = None;

    let cooked_apple = cook(chop(peel(apple)));
    let cooked_carrot = cook(chop(peel(carrot)));
    // Let's try the simpler looking `process()` now.
    let cooked_potato = process(potato);

    eat(cooked_apple);
    eat(cooked_carrot);
    eat(cooked_potato);
}


text:
#define CORE_LOGGING_MODULE_NAME "DebugTest"
//#define CORE_LOGGING_MODULE_LEVEL CL_ALL_FILE

#include "CoreDebugPrint.h"
#include "DebugTest.h"
#include "TCPSocket.h"

// unsigned int g_tcpSocketCount = 0;

DebugTest::DebugTest(Nav2Session& session, const char* name)
   : RegressionTest(name),
     m_session(session)
{

}

void DebugTest::startTest()
{
   // coreprintln("Currently there are %u TCPSocket objecxts.",
   //             g_tcpSocketCount);

   setTestPassed();
}


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel app\models\ProjectUserAssignmentSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Project User Assignments';
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

        <?= Html::a('Create Project User Assignment', ['create'], ['class' => 'btn btn-success']) ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'project_id',
            'user_id',
            'create_time',
            'create_user_id',
            'update_time',
            // 'update_user_id',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>


text:
package cn.xaut.common.security.action;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.xaut.common.security.service.UserSecurityService;
import cn.xaut.shop.pojo.Role;
import cn.xaut.shop.pojo.UserInfo;

import com.opensymphony.xwork2.ActionSupport;

@Controller(value="myLoginAction")
@Scope(value="prototype")
public class MyLoginAction extends ActionSupport implements SessionAware{
	/*@Autowired
	private UserDetailsService userDetailsManager;
	@Autowired
	private AuthenticationManager authenticationManager;
	//private User user;
*/	private String account;
	private String password;

	private String msg;

	@Autowired
	private UserSecurityService userSecurityService;

	protected Map<String,Object> session = null;

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String execute(){
		String showCheckCode = (String) session.get("showCheckCode");
		String SECURITY_LOGIN_EXCEPTION = "";
		account = (String) session.get("login_account");
		if(!(showCheckCode.equals("0"))){
			SECURITY_LOGIN_EXCEPTION = (String) session.get("SECURITY_LOGIN_EXCEPTION");
			msg = SECURITY_LOGIN_EXCEPTION;
		}

		return "failure";
	}

	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	/*public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}*/

	public String goIndexAdmin(){
		UserInfo user = (UserInfo) session.get("user");
		List<Role> roles = userSecurityService.getRolesByUserId(user.getUserinfoId());
		if((roles != null)&&!(roles.isEmpty())){
			Iterator<Role> iter = roles.iterator();
			while(iter.hasNext()){
				Role role = iter.next();
				if("ROLE_SuperAdmin".equals(role.getRoleName())){
					//返回配置管理员主页
					return "goIndexAdmin";
				}
			}
			msg = "该用户没有配置管理员的权限,请勿登录";
			return "failure";
		}else{
			msg = "该用户没有配置管理员的权限,请勿登录";
			return "failure";
		}
	}

}


text:
CKEDITOR.plugins.setLang( 'wbdroplets', 'en',
{
    wbdroplets :
    {
        btn :                'Insert Droplets into page',
        title :              'Droplets',
        name :               'droplet insert',
        errpageselect :      'Please select a Droplet to insert on page!',
        lblpageselection :   'Select a Droplet to insert on page:',
        lbltitle :           'Title:'
    }
})


text:
package net.chibidevteam.apiversioning.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import net.chibidevteam.apiversioning.annotation.ValidApiVersion;

@RestController
@Validated
public class ApiVersionFallbackController {

    @Value("${net.chibidevteam.apiversioning.path.varname}")
    private final String apiPathVarname = "";

    @RequestMapping("${net.chibidevteam.apiversioning.path.api}/**")
    @ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "This endpoint is not implemented for the given version")
    public void pathFallback(@ValidApiVersion @PathVariable(apiPathVarname) String apiVersion) {
        // It only makes difference between not supported versions and non implemented endpoints.
        // It always leads to a HTTP error.
    }
}


text:
title: "Cogito Ergo Expando"
project_id: 3
header:
  teaser: /assets/images/cogito.jpg
---

<img src="../../assets/images/cogito.jpg" width="100%"/>

Group project for the [Artificial Intelligence](http://lia.disi.unibo.it/Courses/AI/fundamentalsAI2018-19/) course in collaboration with [Federico Ruggeri](https://www.linkedin.com/in/federico-ruggeri-a87647145/) e [Sara Bevilaqua](https://www.linkedin.com/in/sara-bevilacqua-00319113a/).

Cogito Ergo Expando is an AI player for Nine Men's Morris boardgame we developed for interal Unibo competition.

### Key Features

#### Internal State
* Internal state representation as an integer array
* Hashing to partially recognize symmetries and rotations.

#### Heuristic Function
* Inspired to [Petcu-Holban](http://www.dasconference.ro/papers/2008/B7.**pdf**) heuristic function

#### Search Algoritm
* Tail recursive search
* Negamax Algorithm
* Alpa-Beta pruning
* Transposition table based on the partiallty symmetric hashcode


text:
jQuery(function ($) {
    "use strict";

/*

    $( "#slider" ).slider({
      range: true,
      min: 0,
      max: 500,
      values: [ 75, 300 ],
      slide: function( event, ui ) {
        $( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
      }
    });
    $( "#amount" ).val( "$" + $( "#slider-range" ).slider( "values", 0 ) +
      " - $" + $( "#slider-range" ).slider( "values", 1 ) );
   */
    function header() {

     var windowHeight = $(window).height();

     var windowWidth = $(window).width();

	    if (windowWidth <  1200 ) {

	/////////////////////////////////////

    //  Disable Mobile Animated

    /////////////////////////////////////

			$("html").removeClass("noIE");

		}

	 /////////////////////////////////////

    //  Sticky Header

    /////////////////////////////////////

	   if (windowHeight > 850) {

	  if ($('#header').length) {

        $(window).on('scroll', function () {

            var winH = $(window).scrollTop();

            var $pageHeader = $('#header');

            if (winH > 60) {

                $pageHeader.addClass('sticky');

            } else {

                $pageHeader.removeClass('sticky');

            }

        });

    }

 };

 	 /////////////////////////////////////

    //  Home slider

    /////////////////////////////////////

        var slider = $(".home-slider .slides");

        var slider2 = $(".home-slider .slides li");

        if (windowHeight > 450) {

            slider.css("max-height", windowHeight - 200);

            slider2.css("max-height", windowHeight - 200);

        };

        $('.scroll_down').click(function (event) {

            event.preventDefault();

            $('html, body').animate({

                scrollTop: windowHeight - 300

            }, 300);

        });

    };

    header();

    $(window).resize(function () {

        header();

    });

    /////////////////////////////////////

    // Qty

    /////////////////////////////////////

    jQuery(".minus_btn").click(function () {

        var inputEl = jQuery(this).parent().children().next();

        var qty = inputEl.val();

        if (jQuery(this).parent().hasClass("minus_btn"))

            qty++;

        else

            qty--;

        if (qty < 0)

            qty = 0;

        inputEl.val(qty);

    })

    jQuery(".plus_btn").click(function () {

        var inputEl = jQuery(this).parent().children().next();

        var qty = inputEl.val();

        if (jQuery(this).hasClass("plus_btn"))

            qty++;

        else

            qty--;

        if (qty < 0)

            qty = 0;

        inputEl.val(qty);

    })

    /////////////////////////////////////

    //  animate elements when they are in viewport

    /////////////////////////////////////

    $('.noIE .animated').waypoint(function () {

        var animation = $(this).data('animation');

        $(this).addClass('animation-done').addClass(animation);

    }, {

        triggerOnce: true,

        offset: '70%'

    });

    /////////////////////////////////////

    //  FLEX SLIDER

    /////////////////////////////////////

    $('.home-slider').flexslider({

        animation: 'fade', //String: Select your animation type, "fade" or "slide"

        //Boolean: Create navigation for previous/next navigation? (true/false)

        slideshowSpeed: 7000, //Integer: Set the speed of the slideshow cycling, in milliseconds

        animationSpeed: 600, //Integer: Set the speed of animations, in milliseconds

        pauseOnHover: false, //Boolean: Pause the slideshow when hovering over slider, then resume when no longer hovering

        prevText: "", //String: Set the text for the "previous" directionNav item

        nextText: "" //String: Set the text for the "next" directionNav item

    });

    $(".flex-control-nav").prepend('');

    $(".flex-control-nav").append('');

    $(".flex-control-nav .prev").click(function () {

        $(".flex-prev").trigger('click');

    });

    $(".flex-control-nav .next").click(function () {

        $(".flex-next").trigger('click');

    });

    $(".flex-control-nav").wrap("

");

    /*PRODUCT FLEXSLIDER*/

        $('#carousel').flexslider({

            animation: "slide",

            controlNav: false,

            animationLoop: false,

            slideshow: false,

            itemWidth: 128,

            itemMargin: 4,

            asNavFor: '#slider-product'

        });

        $('#slider-product').flexslider({

            animation: "slide",

            controlNav: false,

            animationLoop: false,

            slideshow: false,

            sync: "#carousel"

        });

				/*CATEGORY PRODUCT*/

	$('.category-slider').flexslider({

        animation: 'fade', //String: Select your animation type, "fade" or "slide"

        //Boolean: Create navigation for previous/next navigation? (true/false)

        slideshowSpeed: 7000, //Integer: Set the speed of the slideshow cycling, in milliseconds

        animationSpeed: 600, //Integer: Set the speed of animations, in milliseconds

        pauseOnHover: false, //Boolean: Pause the slideshow when hovering over slider, then resume when no longer hovering

        prevText: "", //String: Set the text for the "previous" directionNav item

        nextText: "" //String: Set the text for the "next" directionNav item

    });

		/*CAROUSEL PRODUCT*/

		function carouselBx () {

		 var windowWidth = $(window).width();

if (windowWidth >550) {

  var bxcarousel = $('.bxcarousel li').length;

            if (bxcarousel > 3) {

  $('.bxcarousel').bxSlider({

    slideWidth: 265,

    minSlides: 1,

    maxSlides: 4,

    slideMargin: 25,

	   nextText: '',

        prevText: ''

  });

    $('.bx-next').html(' ')

    $('.bx-prev').html(' ')

			}

}

else{

	  var bxcarousel = $('.bxcarousel li').length;

$('.bxcarousel').bxSlider({

    slideWidth: 265,

    minSlides: 1,

    maxSlides:1,

    slideMargin: 25,

	   nextText: '',

        prevText: ''

  });

    $('.bx-next').html(' ')

    $('.bx-prev').html(' ')

	}

}

	 carouselBx();

    $(window).resize(function() {

        carouselBx();

    });

    /////////////////////////////////////

    //  Menu Mega Bootstrap

    /////////////////////////////////////

    $("#nav .navbar-nav > li .dropdown-toggle").click(function () {

        $(this).parent().toggleClass("open-nav")

    });

    $('input').iCheck({

        checkboxClass: 'icheckbox_minimal',

        radioClass: 'iradio_minimal',

        increaseArea: '20%' // optional

    });

    /////////////////////////////////////

    //  Contact us form validation

    /////////////////////////////////////

    $('#contact-form').on('submit', function (e) {

        e.preventDefault();

        // we clear error messages

        $(this).find('.error').removeClass('error');

        $(this).find('.err_msg').fadeOut(200);

        // validate form

        var validation = validate_contact(e);

        for (var i = 0; i < validation.length; i++) {

            $(validation[i]).addClass('error');

        }

        if (validation.length) {

            $('body, html').animate({

                'scrollTop': $(validation[0]).offset().top - 100

            }, 'easeInCube', function () {

                $(this).select();

            });

            return false;

        } else {

            submit_form(e);

            return true;

        }

    });

    function validate_contact(e) {

        var $form = $(e.target);

        var rule, val, bad_fields = new Array();

        $form.find('input, textarea').each(function () {

            rule = $(this).data('validate');

            if (!rule) return;

            val = $(this).val();

            if (!val.match(rule)) {

                bad_fields.push(this);

            }

        });

        return bad_fields;

    }

    /////////////////////////////////////

    //  Contact us form submit

    /////////////////////////////////////

    function submit_form(e) {

        var $form = $(e.target),

            $btn = $form.find('button'),

            btn_text = $btn.text();

        $.ajax({

            url: 'inc/phpmailer/',

            data: $form.serialize(),

            dataType: 'json',

            type: 'POST',

            beforeSend: function () {

                $('#contact_fail .alert-inner').empty();

                $('#contact_fail').hide();

                $btn.attr('disabled', 'disabled').addClass('btn-disabled').css('cursor', 'not-allowed').text('Sending...');

            },

            success: function (result) {

                if (typeof result.success == 'undefined') {

                    // form is not valid, display errors

                    for (var x in result) {

                        $('#contact_fail .alert-inner').append('
' + result[x] + '
');

                    }

                    $('#contact_fail').fadeIn();

                } else {

                    // form sent successfully and without errors

                    $('#contact_success').fadeIn(700, function () {

                        var $this = $(this);

                        setTimeout(function () {

                            $this.fadeOut();

                        }, 5000);

                    });

                }

            },

            complete: function () {

                $btn.removeAttr('disabled', 'disabled').removeClass('btn-disabled').css('cursor', 'pointer').html(btn_text);

            },

            error: function (jqXHR, textStatus, errorThrown) {

                switch (jqXHR.status) {

                case 404:

                    alert("We're Sorry... The file you are looking for is not found :(");

                    break;

                case 500, 200:

                    $('#contact_fail .alert-inner').append("
Oops, something went wrong and we couldn't send your message :(
");

                    $('#contact_fail').fadeIn();

                    break;

                default:

                    console.log(jqXHR, textStatus, errorThrown);

                }

            }

        });

    }

    function get_max($el) {

        /* Get max height */

        var max = 0;

        $el.each(function () {

            var this_h = $(this).outerHeight();

            if (this_h > max) max = this_h;

        });

        return max;

    }

    $(".sidebar h5").click(function (e) {

        e.preventDefault();

        $(this).parent().find(".tgl_c").slideToggle(300);

        if ($(this).hasClass("active")) {

            $(this).removeClass('active');

        } else {

            $(this).addClass('active');

        }

    });
	 $(".sidebar h5").click(function (e) {

        e.preventDefault();

        $(this).parent().find(".tgl_d").slideToggle(300);

        if ($(this).hasClass("active")) {

            $(this).removeClass('active');

        } else {

            $(this).addClass('active');

        }

    });

/*------------------------------------------------------------------

  Debug top button 13.08  <prestazilla@gmail.com>

-------------------------------------------------------------------*/

$(document).mouseup(function (e) {

    var container = $(".menubtn");

    if (container.has(e.target).length === 0){

       $(".menubtn").removeClass('menu_cshow') ;

    }

});

	 $(".menubtn > a").click(function(){

		 if ( $(this).parent().hasClass("menu_cshow") ) {

	 $(".menu_cshow").removeClass('menu_cshow') ;

     $(this).parent().removeClass('menu_cshow') ;

	}

	else{

     $(".menu_cshow").removeClass('menu_cshow') ;

     $(this).parent().addClass('menu_cshow') ;

		}

		 });

  /*------------------------------------------------------------------

     Select

-------------------------------------------------------------------*/

    if ($('.catelog_c').length > 0) {

  	$(".selbx").selectbox();

	}

/*------------------------------------------------------------------

  Debug top button 13.08  <prestazilla@gmail.com>

-------------------------------------------------------------------*/

    $('input').iCheck({

        checkboxClass: 'icheckbox_minimal',

        radioClass: 'iradio_minimal',

        increaseArea: '20%' // optional

    });

$('.selectItemCount').next('.sbHolder').find('.sbOptions').find('li a').on('click', function(e){
    var count = $(this).html();
    $.ajax({
      type: "POST",
      url: location.protocol+'//'+location.host+'/product/setProductCount/'+count,
      data: {'count': count},
      success: function(data){
        location.reload();
      }
    });
});

});


text:
angular.module('profile_components',[])

.factory('profile_factory', function($http){
	return{
        check_is_bookmarked: function(id) {
           return $http.get(base_url+'profile/is_bookmarked/'+id).then(function(response){
               return response.data;
           });
        },
		add_user_data: function(type, data) {
			var promise = $http.post(base_url+'profile/modify_user_data/'+type+'/add', {'data':data}).then(function(response){
				return response.data;
			});
			return promise;
		},
        modify_user_data: function(type, action, data) {
            var promise = $http.post(base_url+'profile/modify_user_data/'+type+'/'+action, {'data':data}).then(function(response){
                return response.data;
            });
            return promise;
        },
		get_user: function() {
			var promise = $http.get(base_url+'profile/current_user').then(function(response){
				return response.data;
			});
			return promise;
		},
		get_specific_user: function(roleid) {
			var promise = $http.get(base_url+'profile/get_specific_user/?identifier='+roleid).then(function(response){
				return response.data;
			});
			return promise;
		},
		get_user_folders: function(user) {
			folders = {};
			folders['all'] = 0;

			if(user.user_data && user.user_data.saved_record) {
			    folders['all'] = Object.keys(user.user_data.saved_record).length;

			    angular.forEach(user.user_data.saved_record, function(record){
			        if (record.folder){
			            if(folders[record.folder] == undefined) {
			                folders[record.folder] = 1;
			            }
			            else{
			                folders[record.folder] = folders[record.folder] + 1;
			            }
			        }
			    });
			}
			return folders;
		},
		get_user_available_actions: function(){
			var actions = {
                "saved_record_group":['move', 'delete', 'export'],
                "saved_record":['open', 'move', 'delete', 'export'],
                "saved_search_group":['refresh', 'delete'],
                "saved_search":['refresh', 'delete']
            };

			return actions;
		}
	}
})

;


text:
httprpc-python
==============


text:
LIBRARIES=str

include ../../makefiles/Makefile.several
include ../../makefiles/Makefile.common


text:
@import play.api.data.Form
@import play.api.i18n.Messages
@import play.api.mvc.RequestHeader
@import org.webjars.play.WebJarsUtil
@import java.util.UUID

@(form: Form[String], token: UUID)(implicit request: RequestHeader, messages: Messages, webJarsUtil: WebJarsUtil)

@main(messages("reset.password.title")) {
    <fieldset class="col-md-6 col-md-offset-3">
        <legend>@messages("reset.password")</legend>
        @helper.form(action = controllers.routes.ResetPasswordController.submit(token), 'autocomplete -> "off") {

@messages("strong.password.info")

            @helper.CSRF.formField
            @passwordStrength(form("password"), '_hiddenLabel -> messages("password"), 'placeholder -> messages("password"), 'class -> "form-control input-lg")

                    <button id="submit" type="submit" value="submit" class="btn btn-lg btn-primary btn-block">@messages("reset")</button>

        }
    </fieldset>
}


text:
package com.unionpay.uppayplugin.demo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.widget.TextView;
import com.unionpay.UPPayAssistEx;

public class APKActivity extends BaseActivity {

    @Override
    public void doStartUnionPayPlugin(Activity activity, String tn, String mode) {
        // mMode参数解释:
        // 0 - 启动银联正式环境
        // 1 - 连接银联测试环境
        int ret = UPPayAssistEx.startPay(this, null, null, tn, mode);
        if (ret == PLUGIN_NEED_UPGRADE || ret == PLUGIN_NOT_INSTALLED) {
            // 需要重新安装控件
            Log.e(LOG_TAG, " plugin not found or need upgrade!!!");

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示");
            builder.setMessage("完成购买需要安装银联支付控件,是否安装?");

            builder.setNegativeButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            UPPayAssistEx.installUPPayPlugin(APKActivity.this);
                            dialog.dismiss();
                        }
                    });

            builder.setPositiveButton("取消",
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            builder.create().show();

        }
        Log.e(LOG_TAG, "" + ret);
    }

    @Override
    public void updateTextView(TextView tv) {
        String txt = "接入指南:\n1:拷贝sdk目录下的UPPayAssistEx.jar到libs目录下\n2:获取tn后通过UPPayAssistEx.startPay(...)方法调用控件";
        tv.setText(txt);
    }

}


text:
- Can reference widgets by their kv ids
- Can automate checkboxes and toggle buttons


text:
@class XPExpression;

@interface XPTuple : NSObject

+ (instancetype)tupeWithResultItems:(NSArray *)res groupSpecs:(NSArray *)groupSpecs orderSpecs:(NSArray *)orderSpecs;

@property (nonatomic, retain) NSArray *resultItems;
@property (nonatomic, retain) NSArray *groupSpecs;
@property (nonatomic, retain) NSArray *orderSpecs;
@end


text:
#ifndef bredy_base_PROGRAMLOCATION_H_
#define bredy_base_PROGRAMLOCATION_H_

namespace LightSpeed
{

    ///Describes location is source code
    /**
    To construct instance that contains current location, use macro THISLOCATION.
    */
    struct ProgramLocation {

        ///Name of the source file
        const char *file;
        ///line in source file
        int line;
        ///function name
        const char *function;

        ///Constructor
        /**
        To construct current location, use THISLOCATION as constructor
        */
        ProgramLocation(const char *file,
                    int line,
                    const char *function):
                    file(file),line(line),function(function) {}

		ProgramLocation():
		file(""),line(0),function("") {}

					bool operator ==(const ProgramLocation &other) const {
            return file == other.file && line == other.line && function == other.function;
        }
        bool operator !=(const ProgramLocation &other) const {
            return !operator==(other);
        }

		bool isUndefined() const {return file == 0 || file[0] == 0;}

    };

    ///Always contains instance of ProgramLocation class with the current location
    /**
        ProgramLocation thisPlace = THISLOCATION;
    */
#ifdef _DEBUG
    #define THISLOCATION (::LightSpeed::ProgramLocation(__FILE__,__LINE__,__FUNCTION__))
#else
	#define THISLOCATION (::LightSpeed::ProgramLocation(__FUNCTION__,__LINE__,__FUNCTION__))
#endif

}

#endif /*PROGRAMLOCATION_H_*/


text:
package net.imagej.ops.deconvolve;

import java.util.ArrayList;

import net.imagej.ops.Ops;
import net.imagej.ops.filter.AbstractIterativeFFTFilterC;
import net.imagej.ops.filter.convolve.ConvolveFFTC;
import net.imagej.ops.filter.fft.FFTMethodsOpC;
import net.imagej.ops.special.computer.BinaryComputerOp;
import net.imagej.ops.special.computer.Computers;
import net.imagej.ops.special.computer.UnaryComputerOp;
import net.imagej.ops.special.function.Functions;
import net.imagej.ops.special.function.UnaryFunctionOp;
import net.imagej.ops.special.hybrid.Hybrids;
import net.imagej.ops.special.hybrid.UnaryHybridCF;
import net.imagej.ops.special.inplace.UnaryInplaceOp;
import net.imglib2.Dimensions;
import net.imglib2.FinalInterval;
import net.imglib2.Interval;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.img.Img;
import net.imglib2.type.numeric.ComplexType;
import net.imglib2.type.numeric.RealType;
import net.imglib2.util.Util;
import net.imglib2.view.IntervalView;
import net.imglib2.view.Views;

import org.scijava.Priority;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

/**
 * Richardson Lucy algorithm for (@link RandomAccessibleInterval) (Lucy, L. B.
 * (1974). "An iterative technique for the rectification of observed
 * distributions".)
 *
 * @author Brian Northan
 * @param <I>
 * @param <O>
 * @param <K>
 * @param <C>
 */

@Plugin(type = Ops.Deconvolve.RichardsonLucy.class, priority = Priority.HIGH)
public class RichardsonLucyC<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
	extends AbstractIterativeFFTFilterC<I, O, K, C> implements
	Ops.Deconvolve.RichardsonLucy
{

	/**
	 * Op that computes Richardson Lucy update, can be overridden to implement
	 * variations of the algorithm (like RichardsonLucyTV)
	 */
	@Parameter(required = false)
	private UnaryComputerOp<RandomAccessibleInterval<O>, RandomAccessibleInterval<O>> updateOp =
		null;

	/**
	 * The current estimate, by passing in the current estimate the user can
	 * define the starting point (first guess), if no starting estimate is
	 * provided the default starting point will be the input image
	 */
	@Parameter(required = false)
	private RandomAccessibleInterval<O> raiExtendedEstimate;

	/**
	 * A list of optional constraints that are applied at the end of each
	 * iteration (ie can be used to achieve noise removal, non-circulant
	 * normalization, etc.)
	 */
	@Parameter(required = false)
	private ArrayList<UnaryInplaceOp<RandomAccessibleInterval<O>, RandomAccessibleInterval<O>>> iterativePostProcessingOps =
		null;

	private BinaryComputerOp<RandomAccessibleInterval<I>, RandomAccessibleInterval<O>, RandomAccessibleInterval<O>> rlCorrectionOp;

	private UnaryFunctionOp<Interval, Img<O>> createOp;

	private UnaryComputerOp<RandomAccessibleInterval<K>, RandomAccessibleInterval<C>> fftKernelOp;

	private BinaryComputerOp<RandomAccessibleInterval<O>, RandomAccessibleInterval<K>, RandomAccessibleInterval<O>> convolverOp;

	private UnaryComputerOp<RandomAccessibleInterval<I>, RandomAccessibleInterval<O>> copyOp;

	private UnaryComputerOp<RandomAccessibleInterval<O>, RandomAccessibleInterval<O>> copy2Op;

	private RandomAccessibleInterval<O> raiExtendedReblurred;

	@Override
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void initialize() {
		super.initialize();

		if (updateOp == null) {
			updateOp = (UnaryComputerOp) Computers.unary(ops(),
				RichardsonLucyUpdate.class, RandomAccessibleInterval.class,
				RandomAccessibleInterval.class);
		}

		rlCorrectionOp = (BinaryComputerOp) Computers.binary(ops(),
			RichardsonLucyCorrection.class, RandomAccessibleInterval.class,
			RandomAccessibleInterval.class, RandomAccessibleInterval.class,
			getFFTInput(), getFFTKernel());

		fftKernelOp = (UnaryComputerOp) Computers.unary(ops(), FFTMethodsOpC.class,
			getFFTKernel(), RandomAccessibleInterval.class);

		copyOp = (UnaryHybridCF) Hybrids.unaryCF(ops(), Ops.Copy.RAI.class,
			RandomAccessibleInterval.class, IntervalView.class);

		copy2Op = (UnaryHybridCF) Hybrids.unaryCF(ops(), Ops.Copy.RAI.class,
			RandomAccessibleInterval.class, IntervalView.class);

		createOp = (UnaryFunctionOp) Functions.unary(ops(), Ops.Create.Img.class,
			Img.class, Dimensions.class, Util.getTypeFromInterval(out()));

		convolverOp = (BinaryComputerOp) Computers.binary(ops(), ConvolveFFTC.class,
			RandomAccessibleInterval.class, RandomAccessibleInterval.class,
			RandomAccessibleInterval.class, this.getFFTInput(), this.getFFTKernel(),
			true, false);

	}

	@Override
	public void compute(RandomAccessibleInterval<I> in,
		RandomAccessibleInterval<K> kernel, RandomAccessibleInterval<O> out)
	{
		// create FFT input memory if needed
		if (getFFTInput() == null) {
			setFFTInput(getCreateOp().calculate(in));
		}

		// create FFT kernel memory if needed
		if (getFFTKernel() == null) {
			setFFTKernel(getCreateOp().calculate(in));
		}

		// if a starting point for the estimate was not passed in then create
		// estimate Img and use the input as the starting point
		if (raiExtendedEstimate == null) {

			raiExtendedEstimate = createOp.calculate(in);

			copyOp.compute(in, raiExtendedEstimate);
		}

		// create image for the reblurred
		raiExtendedReblurred = createOp.calculate(in);

		// perform fft of psf
		fftKernelOp.compute(kernel, getFFTKernel());

		// -- perform iterations --

		for (int i = 0; i < getMaxIterations(); i++) {

			if (status != null) {
				status.showProgress(i, getMaxIterations());
			}

			// create reblurred by convolving kernel with estimate
			// NOTE: the FFT of the PSF of the kernel has been passed in as a
			// parameter. when the op was set up, and computed above, so we can use
			// compute
			convolverOp.compute(raiExtendedEstimate, this.raiExtendedReblurred);

			// compute correction factor
			rlCorrectionOp.compute(in, raiExtendedReblurred, raiExtendedReblurred);

			// perform update to calculate new estimate
			updateOp.compute(raiExtendedReblurred, raiExtendedEstimate);

			// apply post processing
			if (iterativePostProcessingOps != null) {
				for (UnaryInplaceOp<RandomAccessibleInterval<O>, RandomAccessibleInterval<O>> pp : iterativePostProcessingOps) {
					pp.mutate(raiExtendedEstimate);
				}
			}

			// accelerate the algorithm by taking a larger step
			if (getAccelerator() != null) {
				getAccelerator().mutate(raiExtendedEstimate);
			}
		}

		// -- copy crop padded back to original size

		final long[] start = new long[out.numDimensions()];
		final long[] end = new long[out.numDimensions()];

		for (int d = 0; d < out.numDimensions(); d++) {
			start[d] = 0;
			end[d] = start[d] + out.dimension(d) - 1;
		}

		copy2Op.compute(Views.interval(raiExtendedEstimate, new FinalInterval(start,
			end)), out);
	}

}


text:
/*                                                                  */
/* This is an automatically generated copyright prolog.             */
/* After initializing,  DO NOT MODIFY OR MOVE                       */
/*  --------------------------------------------------------------- */
/*                                                                  */
/* (C) Copyright IBM Corp.  2007, 2007                              */
/* IBM CPL License                                                  */
/*                                                                  */
/*  --------------------------------------------------------------- */
/*                                                                  */
/* end_generated_IBM_copyright_prolog                               */
/**
 * \file common/alignment.h
 */

#ifndef	_ALIGNMENT_H_ // Prevent multiple inclusion
#define	_ALIGNMENT_H_

#include <arch/ppc32/common/namespace.h>

__BEGIN_DECLS

#if defined(__ASSEMBLY__)

#define ALIGN_L1_DIRTYBIT  3
#define ALIGN_QUADWORD     4
#define ALIGN_L1_CACHE     5
#define ALIGN_L1I_CACHE    5
#define ALIGN_L1D_CACHE    5
#define ALIGN_L3_CACHE     7

#elif defined(__GNUC__) || defined(__xlC__)

#define ALIGN_L1_DIRTYBIT __attribute__ ((aligned (  8)))
#define ALIGN_QUADWORD    __attribute__ ((aligned ( 16)))
#define ALIGN_L1_CACHE    __attribute__ ((aligned ( 32)))
#define ALIGN_L1I_CACHE   __attribute__ ((aligned ( 32)))
#define ALIGN_L1D_CACHE   __attribute__ ((aligned ( 32)))
#define ALIGN_L3_CACHE    __attribute__ ((aligned (128)))

#else

#warning "Need alignment directives for your compiler!"

#define ALIGN_QUADWORD
#define ALIGN_L1_CACHE
#define ALIGN_L1I_CACHE
#define ALIGN_L1D_CACHE
#define ALIGN_L3_CACHE

#endif // __ASSEMBLY__

__END_DECLS

#endif // Add nothing below this line


text:
package org.apache.phoenix.util;

import java.io.File;
import java.io.Reader;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.phoenix.jdbc.PhoenixConnection;
import org.apache.phoenix.util.csv.CsvUpsertExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;

/***
 * Upserts CSV data using Phoenix JDBC connection
 */
public class CSVCommonsLoader {

    private static final Logger LOGGER = LoggerFactory.getLogger(CSVCommonsLoader.class);

    public static final String DEFAULT_ARRAY_ELEMENT_SEPARATOR = ":";

    private static final Map<Character,Character> CTRL_CHARACTER_TABLE =
            ImmutableMap.<Character,Character>builder()
                        .put('1', '\u0001')
                        .put('2', '\u0002')
                        .put('3', '\u0003')
                        .put('4', '\u0004')
                        .put('5', '\u0005')
                        .put('6', '\u0006')
                        .put('7', '\u0007')
                        .put('8', '\u0008')
                        .put('9', '\u0009')
                        .build();

    private final PhoenixConnection conn;
    private final String tableName;
    private final List<String> columns;
    private final boolean isStrict;
    private final char fieldDelimiter;
    private final char quoteCharacter;
    private final Character escapeCharacter;
    private PhoenixHeaderSource headerSource = PhoenixHeaderSource.FROM_TABLE;
    private final CSVFormat format;

    private final String arrayElementSeparator;

    public enum PhoenixHeaderSource {
        FROM_TABLE,
        IN_LINE,
        SUPPLIED_BY_USER
    }

    public CSVCommonsLoader(PhoenixConnection conn, String tableName,
            List<String> columns, boolean isStrict) {
        this(conn, tableName, columns, isStrict, ',', '"', null, DEFAULT_ARRAY_ELEMENT_SEPARATOR);
    }

    public CSVCommonsLoader(PhoenixConnection conn, String tableName,
            List<String> columns, boolean isStrict, char fieldDelimiter, char quoteCharacter,
            Character escapeCharacter, String arrayElementSeparator) {
        this.conn = conn;
        this.tableName = tableName;
        this.columns = columns;
        this.isStrict = isStrict;
        this.fieldDelimiter = fieldDelimiter;
        this.quoteCharacter = quoteCharacter;
        this.escapeCharacter = escapeCharacter;

        // implicit in the columns value.
        if (columns !=null && !columns.isEmpty()) {
            headerSource = PhoenixHeaderSource.SUPPLIED_BY_USER;
        }
        else if (columns != null && columns.isEmpty()) {
            headerSource = PhoenixHeaderSource.IN_LINE;
        }

        this.arrayElementSeparator = arrayElementSeparator;
        this.format = buildFormat();
    }

    public CSVFormat getFormat() {
        return format;
    }

    /**
     * default settings
     * delimiter = ','
     * quoteChar = '"',
     * escape = null
     * recordSeparator = CRLF, CR, or LF
     * ignore empty lines allows the last data line to have a recordSeparator
     *
     * @return CSVFormat based on constructor settings.
     */
    private CSVFormat buildFormat() {
        CSVFormat format = CSVFormat.DEFAULT
                .withIgnoreEmptyLines(true)
                .withDelimiter(asControlCharacter(fieldDelimiter))
                .withQuote(asControlCharacter(quoteCharacter));

        if (escapeCharacter != null) {
            format = format.withEscape(asControlCharacter(escapeCharacter));
        }

        switch(headerSource) {
        case FROM_TABLE:
            // obtain headers from table, so format should not expect a header.
            break;
        case IN_LINE:
            // an empty string array triggers csv loader to grab the first line as the header
            format = format.withHeader(new String[0]);
            break;
        case SUPPLIED_BY_USER:
            // a populated string array supplied by the user
            format = format.withHeader(columns.toArray(new String[columns.size()]));
            break;
        default:
            throw new RuntimeException("Header source was unable to be inferred.");

        }
        return format;
    }

    /**
     * Translate a field separator, escape character, or phrase delimiter into a control character
     * if it is a single digit other than 0.
     *
     * @param delimiter
     * @return
     */
    public static char asControlCharacter(char delimiter) {
        return CTRL_CHARACTER_TABLE.getOrDefault(delimiter, delimiter);
    }

    /**
     * Upserts data from CSV file.
     *
     * Data is batched up based on connection batch size.
     * Column PDataType is read from metadata and is used to convert
     * column value to correct type before upsert.
     *
     * The constructor determines the format for the CSV files.
     *
     * @param fileName
     * @throws Exception
     */
    public void upsert(String fileName) throws Exception {
        CSVParser parser = CSVParser.parse(new File(fileName), Charsets.UTF_8, format);
        upsert(parser);
    }

    public void upsert(Reader reader) throws Exception {
        CSVParser parser = new CSVParser(reader,format);
        upsert(parser);
    }

    private static <T> String buildStringFromList(List<T> list) {
        return Joiner.on(", ").useForNull("null").join(list);
    }

    /**
     * Data is batched up based on connection batch size.
     * Column PDataType is read from metadata and is used to convert
     * column value to correct type before upsert.
     *
     * The format is determined by the supplied csvParser.

     * @param csvParser
     *            CSVParser instance
     * @throws Exception
     */
    public void upsert(CSVParser csvParser) throws Exception {
        List<ColumnInfo> columnInfoList = buildColumnInfoList(csvParser);

        boolean wasAutoCommit = conn.getAutoCommit();
        try {
            conn.setAutoCommit(false);
            long start = System.currentTimeMillis();
            CsvUpsertListener upsertListener = new CsvUpsertListener(conn,
                    conn.getMutateBatchSize(), isStrict);
            CsvUpsertExecutor csvUpsertExecutor = new CsvUpsertExecutor(conn, tableName,
                    columnInfoList, upsertListener, arrayElementSeparator);

            csvUpsertExecutor.execute(csvParser);
            csvUpsertExecutor.close();

            conn.commit();
            double elapsedDuration = ((System.currentTimeMillis() - start) / 1000.0);
            System.out.println("CSV Upsert complete. " + upsertListener.getTotalUpsertCount()
                    + " rows upserted");
            System.out.println("Time: " + elapsedDuration + " sec(s)\n");

        } finally {

            // release reader resources.
            if (csvParser != null) {
                csvParser.close();
            }
            if (wasAutoCommit) {
                conn.setAutoCommit(true);
            }
        }
    }

    private List<ColumnInfo> buildColumnInfoList(CSVParser parser) throws SQLException {
        List<String> columns = this.columns;
        switch (headerSource) {
        case FROM_TABLE:
            System.out.println(String.format("csv columns from database."));
            break;
        case IN_LINE:
            columns = new ArrayList<>(parser.getHeaderMap().keySet());
            System.out.println(String.format("csv columns from header line. length=%s, %s",
                    columns.size(), buildStringFromList(columns)));
            break;
        case SUPPLIED_BY_USER:
            System.out.println(String.format("csv columns from user. length=%s, %s",
                    columns.size(), buildStringFromList(columns)));
            break;
        default:
            throw new IllegalStateException("parser has unknown column source.");
        }
        return SchemaUtil.generateColumnInfo(conn, tableName, columns, isStrict);
    }

    static class CsvUpsertListener implements UpsertExecutor.UpsertListener<CSVRecord> {

        private final PhoenixConnection conn;
        private final int upsertBatchSize;
        private long totalUpserts = 0L;
        private final boolean strict;

        CsvUpsertListener(PhoenixConnection conn, int upsertBatchSize, boolean strict) {
            this.conn = conn;
            this.upsertBatchSize = upsertBatchSize;
            this.strict = strict;
        }

        @Override
        public void upsertDone(long upsertCount) {
            totalUpserts = upsertCount;
            if (upsertCount % upsertBatchSize == 0) {
                if (upsertCount % 1000 == 0) {
                    LOGGER.info("Processed upsert #{}", upsertCount);
                }
                try {
                    LOGGER.info("Committing after {} records", upsertCount);
                    conn.commit();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        @Override
        public void errorOnRecord(CSVRecord csvRecord, Throwable throwable) {
            LOGGER.error("Error upserting record " + csvRecord, throwable.getMessage());
            if (strict) {
                Throwables.propagate(throwable);
            }
        }

        /**
         * Get the total number of upserts that this listener has been notified about up until now.
         *
         * @return the total count of upserts
         */
        public long getTotalUpsertCount() {
            return totalUpserts;
        }
    }
}