text:
%% *************************************************************************
%%
%% This is a derivative work of the RIT Space Exploration Standard defining
%% guidelines for content and formatting of project design documents.
%%
%% This document uses IEEEtran.cls, the official IEEE LaTeX class
%% for authors of the Institute of Electrical and Electronics Engineers
%% (IEEE) Transactions journals and conferences.
%%
%% *************************************************************************

%% *************************************************************************
% LaTeX REFERENCES
% ----------------
%   Intro to LaTeX: http://www.rpi.edu/dept/arc/docs/latex/latex-intro.pdf
%   Comprehensive LaTeX symbol list: http://tug.ctan.org/info/symbols/comprehensive/symbols-a4.pdf
%% *************************************************************************

% tell \LaTeX what kind of formatting to use
\documentclass[conference]{IEEEtran} % http://www.ctan.org/pkg/ieeetran
\usepackage{blindtext} % enable placeholder text generator
\usepackage{graphicx} % enable toolbox for embedding figures and pictures
\usepackage{nomencl} % enable package for adding a list of variables and constants at the beginning, aka "nomenclature"
\usepackage{siunitx} % enable package for easily formatting units
\usepackage{hyperref} % enable package for cross-referencing figures, sections, references etc.
% how to use hyperref: http://www2.washjeff.edu/users/rhigginbottom/latex/resources/lecture09.pdf
\usepackage[T1]{fontenc} % change text encoding to make it more crisp
\usepackage{etoolbox} % enable conditionals for help text
\usepackage{booktabs} % make beautiful tables!

% initialize nomenclature package
\makenomenclature{}

% set title. choose something as descriptive and precise as possible. Descriptive > sounding cool. remember this!
\title{Foundation for Development of RIT SPEX Astro Tracking Team}

\author{
  % List the authors of the design document. The Champion should go first.
  % The \$~\$ markers tell \LaTeX{} to treat the text inside to be treated as a math expression. This way you can use operators like \textcaret{} to place characters as superscripts.
  % Some \LaTeX{} templates handle the author block in different ways. For example, the \href{http://www.worldscientific.com/worldscinet/jai}{Journal of Astronomical Instrumentation} requires the authors' addresses and emails to be included as well.
  % The \textbackslash{}thanks command puts the contents inside those brackets in a footnote at the bottom of the first page. Technically speaking, \textbackslash{}thanks is just a specially formatted footnote.
  % IEEE also has a ``long form'' author block for many authors. Check here for more information:
  % \url{https://tex.stackexchange.com/questions/156523/multiple-authors-with-common-affiliations-in-ieeetran-conference-template}
  % Read here for a more advanced options to modifying footnotes in the author block:  \url{http://tex.stackexchange.com/questions/826/symbols-instead-of-numbers-as-footnote-markers}
  %   Here, we use the IEEE long-form author block.
  \IEEEauthorblockN{% This block is for author Names.
    Evan~Putnam\IEEEauthorrefmark{1},  %the number in the bracket is a reference number to identify this footnote. \LaTeX will figure out what symbol to put there.
    Marilyn~Wolbert\IEEEauthorrefmark{2}
  }
  \IEEEauthorblockA{% This block is for the author Affiliations, aka department and university
    RIT Space Exploration, Rochester Institute of Technology \\ %\\ starts a new line
    Rochester, N.Y. \\
    Email:
    \IEEEauthorrefmark{1}emp9173@rit.edu,
    \IEEEauthorrefmark{2}mxw3196@rit.edu
  }
  %%   Below, we use the short-form author block and basically hack it to suit our needs.
  % Philip~Linden$^{*\dagger}$%
  %   \thanks{$^{*}$Project Champion}%
  %   \thanks{$^{\dagger}$BS/MEng '17, Mechanical Engineering},
  % Austin~Bodzas$^{\ddagger}$%
  %   \thanks{$^{\ddagger}$BS '19, Computer Science},
  % Drew~Walters$^{\S}$%
  %   \thanks{$^{\S}$BS '18, Mechanical Engineering Technology},
  % T.J.~Tarazevits$^{**}$%
  %   \thanks{$^{**}$BS '19, Game Design \& Development}%

  %%   If there are many authors, consider using symbolic, numeric (aka arabic),  alphabet footnotes or a combination thereof.
  %% the recommended order for symbolic footnotes is
  %%   (1) asterisk        *   *
  %%   (2) dagger          †   \dagger
  %%   (3) double dagger   ‡   \ddagger
  %%   (4) section symbol  §   \S
  %%   et cetera. For higher counts, use 2x symbols (1)-(4) (i.e. (5) two asterisks **). Keep cycling through (1)-(4) using 3x, 4x, and so on.
  %%   Note that these symbol codes work in math mode and text mode.
  %%   There are ways to make LaTeX do this for you, but it is more advanced and not entirely necessary, especially for short author lists. Not worth the hassle, in my opinion.
}
% page header for pages other than cover page
\markboth{Project Design Document Standard}%
{Linden \MakeLowercase{\textit{et al.}}: RIT Space Exploration}

% Initial setup is over, start building the document itself
\begin{document}
\maketitle%
% correct bad hyphenation here, separated by spaces
\hyphenation{explor-ation}

\begin{abstract}

Astro Tracking is an important sub team of RIT SPEX and has tremendous room for growth.  In order to expand it is crucial to improve current technology and create a foundation for astronomy based research.  Thus a semester long session is proposed to firstly educate new members on the foundational principles of Astronomy and Astronomy research, secondly develop tools to aid in said research, and lastly to improve our showcase of work for Imagine RIT to assist in obtaining corporate sponsors.

      % The abstract is a brief summary of the design document. Typically it includes the purpose of the design document, key goals or objectives, and justifications.
      % Be sure not to confuse the abstract with the introduction.
      % It is easiest to write the abstract after the rest of the paper has been written.
      % That way you can choose key information from the sections that you've already completed and string them together in the abstract.
      % Consider the abstract to be your elevator pitch to anyone reading this design document.
      % What are they reading?
      % What is the goal?
      % Why is it worth my time?
      % The abstract is what will show up in Google results and other search engines, and what people will read when they are deciding what is worth their time and brain power.
\end{abstract}

\label{sec:nomenclature}
\newcommand{\nomunit}[1]{%
\renewcommand{\nomentryend}{\hspace*{\fill}#1}}
\renewcommand{\nompreamble}{
    % If you include mathematical expressions or express variables in the design document, list them with their corresponding definitions here as a list.
    % The two lines below make it look nice when defining units/values to constants.

    % Note that math terms and non-math terms are separated and alphabetized, regardless of the order in which they are defined. (Recall terms \$like this\$ are in the math environment)
    % Read more about advanced nomenclature formatting here:\\
    % \url{https://www.sharelatex.com/learn/Nomenclatures}
  }
\nomenclature{RIT}{Rochester Institute of Technology}
\nomenclature{SPEX}{RIT Space Exploration}
\nomenclature{PDD}{Project Design Document}
% Below are examples of using nomenclature for math symbols and constants or units

% HELPFUL HINT: If you get the warning ``Command terminated with space.'' when using a \command try placing ``%'' or ``{}'' immediately following the command.

% The sections included here are required. Additional sections and subsections may be added as necessary.
\section{Introduction}
\label{sec:introduction}
  % The introduction is a place to give background and context before diving into the subject matter.
  % Establish context for the work you are about to propose and the main ideas of the proposition itself.

\IEEEPARstart{T}{he} RIT Astro Tracking team formed in the Fall of 2016 and was designed for the purpose of Astronomical research and the tracking of artificial satellites.  Considerable growth has been made in regard to general Astronomy skills with a number of quality images and the improvement of general astrophotography skills.  Clear pictures of Jupiter, Saturn, and other objects have been taken by members and showcased at various SPEX related events.  In addition the team has developed software for the automation of its primary telescope, the Meade LX200, where it can be controlled from any location with wireless connectivity.

The team has accomplished much since its inception and the next logical step would be to improve the skills developed as well as begin preliminary tracking of both artificial satellites and other celestial objects.  In order to begin new members will firstly have to be educated on basics, technology to assist in tracking must be developed, and technology must be developed for the maintenance of current equipment.

\section{Primary Objective}
\label{sec:primary-obj}
  % At the end of the day, whether the project ``succeeds'' or ``fails'' is judged against the objectives it sought to meet.
  % Note that results that contradict expectations/hypotheses are not failures if the scientific \& engineering methods are followed along the way.
  % Sometimes our expectations are wrong and that can be just as successful as getting data we thought we'd see.
  % What matters are what questions you intend to answer.
  % This is the main purpose or main goal the project hopes to achieve.

    \subsection{Tracking Mount}
    \label{subsec:trackingmount}
        This project involves the research and development of an active tracking mount for taking pictures with a DSLR of celestial objects.  In order to get pictures of stars the camera needs to take in a lot of light.  However, stars move very fast and will appear as blurred lines if the shutter is not fixed on them for the duration of a long exposure shot.  The mount allows the camera to move along with the stars and capture more light which results in photos otherwise not to be seen with the naked eye.
    \subsection{Orion Mount}
    \label{subsec:orionmount}
        This project involves the research and development of a new mount for the Orion telescope.  It is up to the team to determine a style for the mount and create said mount.  It would also be of preference to have this later able to be automated.
    \subsection{Tracking Software}
    \label{subsec:trackingsoftware}
        This project involves creating software to handle the equations to convert two line elements into a format the telescope understand.  This will involve converting the equations to Cartesian form and plotting the orbits in a 3-Dimensional space.  Will then need to be interfaced with the telescopes
    \subsection{Group Research}
    \label{subsec:groupresearch}
        This project will contain a group of 3-4 students who propose a research proposition that is related to astro tracking.  They will then conduct the research, analyze their results, and present their findings.
    \subsection{General Marketing}
    \label{subsec:generalmarketing}
        In order to garner new interest a marketing campaign for new members will be proposed. New posters will be created that are astro tracking specific to try and garner new membership.
    \subsection{Star Outings}
    \label{subsec:generaloutings}
        In order to continue to improve our general astronomy skills four trips will be planned for general observation throughout the semester.  In addition one trip to the RIT observatory will be planned.

%\begin{figure}
%  \includegraphics[width=\linewidth]{figs/project-life-cycle.png}
%  \caption{A PDD is the first piece of documentation to be archived in the project life cycle. Since the life cycle can be iterative, a new design document may also refer to one or more previous SPPs.}
%\label{fig:lifecycle}
%\end{figure}

% \section{Secondary Objectives}
% \label{sec:secondary-obj}
% Secondary Objectives are lower priority or bonus objectives that are significant but not the main focus of the project. This template does not have secondary objectives.

\section{Benefit to SPEX}
\label{sec:benefit}
% One of the core values of SPEX is to provide opportunities for academic and professional growth for its members,
% and to challenge them with interesting projects.
% In this section, explain how the project would benefit SPEX members as students,
% space enthusiasts, and young professionals.

The benefits to SPEX are two-fold.  Firstly this will give the members new tools and technologies to conduct astro tracking related research.  Secondly it will provide items for the astro tracking team to showcase at events like Imagine RIT.

\subsection{New Technologies and Equipment}
    \subsubsection{Tracking Mount}
    \label{sec:trackingmount}
    Mount to assist in astrophotography without telescope will allow for students to take pictures that were otherwise not able to be taken with current equipment.
    \subsubsection{Orion Mount}
    \label{sec:orionmounts}
    Extra telescope mount to use during star-gazing sessions will allow more students to get hands on experience with the telescopes when they are taken out.
    \subsubsection{Tracking Software}
    \label{sec:trackingmounts}
    Software to help with tracking of artificial satellites will allow members to conduct research in the future.

\subsection{Showcase Pieces for Imagine}
\label{sec:showcasepieces}
Two new mounts will be developed which are physical items that can be used to start conversation with event attendees.  This will appeal to more mechanical individuals who are not directly interested in software.
New pictures will also be taken that will outline the capabilities of both the members and the new technologies developed. These showcase pieces will help improve the credibility of the RIT SPEX Astro Tracking team and increase the chances of future sponsorship for SPEX as a whole.

\section{Implementation}
\label{sec:implementation}
  % What path do you anticipate the project to take?

\subsection{Timeline}
\label{subsec:timeline}
    \subsubsection*{Week 3}
    Project plans.  An outline of the steps each team will take to complete their sub-project
    \subsubsection*{Week 5-7}
    Progress Updates. Update on progress of project
    \subsubsection*{Week 8}
    Mid presentation.  Give an in-depth analysis of the project.  Will outline project status, roadblocks, and what is left to do.
    \subsubsection*{Week 12}
    Projects ideally will be completed, or near-completion, at this point for showcasing at Imagine RIT.

\subsection{Deliverables}
\label{subsec:deliverables}

Deliverable items for this project include a small mid-semester presentation to outline where each of the projects are at and what needs to be done in order to complete them.  Then each team will deliver their final projects.  For each of the mount teams their respected mounts will be the delivery.  The tracking mount should also present pictures taken of celestial objects to indicate it works as desired.  The team working on the software will provide the finished code as well as a presentation outlining how to use it, how it works, as well as the technologies used.  Lastly the research team will present their findings to the group as well as create a small paper that will be reviewed by the team and, ideally, be pushed forth for publication.

\section{Externalities}
  % Things not directly related to the work or outcomes, but related to the project as a whole.
\subsection{Prerequisite Skills}
  % Which skills do team members need to have before work can start (not including skills that will be learned ``on the job'')?
Many of these projects are interdisciplinary but between them will require from ten to twelve members.  Each respected team will get anywhere between two to four members depending on the complexity and skill set of each team.  Ideally for the mounts there should be an upperclassman mechanical engineer.  For the research team there should be at least one physics related major.  Lastly for the software team it will be recommended to have one member familiar with orbital mechanics and another with general software development.

\subsection{Funding Requirements}
  % Estimate costs that would be needed to meet objectives.
Funding requirements for these projects should be kept to a minimum.
The mount teams will not exceed 50 dollars in materials for each respective mount and the software/research teams will require no additional funding.

\subsection{Faculty Support}
  % Identify faculty that will be involved (or would need to be involved) to meet objectives.
  % Note that if a professor is the Principal Investigator (P.I.) for a project, there still needs to be a student as the SPEX Project Champion.
No faculty have explicitly expressed interest in these projects. However they can be consulted if questions do arise in any stage of development.  While it is certainly feasible to do these projects without professor help it would greatly benefit the members to develop relationships with professors to help in development.

\subsection{Long-Term Vision}
\label{sec:vision}
Once new technologies are developed the Astro Tracking team will be better prepared to conduct research in the future.  The mounts allow for obtaining better data during observations, the software will allow for the pursuit of tracking artificial satellites, and the research team will help provide a framework for how to conduct future research.

\section*{Acknowledgements}
The Author would like to thank all sponsors, current members who dedicate their hard work and time, and all faculty advisors for RIT SPEX.

\bibliographystyle{IEEEtran}
\bibliography{sample-with-examples}

%\onecolumn
%\appendices{}
%\section{Project Life Cycle}
%\begin{figure}[h]
%  \centering
%  \includegraphics[]{figs/project-life-cycle.png}
%  \caption{Enlarged version of the diagram in \autoref{fig:lifecycle}.}
%\end{figure}

\end{document}


text:
//--------------------------------------------------------------------------------//
//                               COPYRIGHT NOTICE                                 //
//--------------------------------------------------------------------------------//
// Copyright (c) 2012, Instituto de Microelectronica de Sevilla (IMSE-CNM)        //
//                                                                                //
// All rights reserved.                                                           //
//                                                                                //
// Redistribution and use in source and binary forms, with or without             //
// modification, are permitted provided that the following  conditions are met:   //
//                                                                                //
//     * Redistributions of source code must retain the above copyright notice,   //
//       this list of conditions and the following disclaimer.                    //
//                                                                                //
//     * Redistributions in binary form must reproduce the above copyright        //
//       notice, this list of conditions and the following disclaimer in the      //
//       documentation and/or other materials provided with the distribution.     //
//                                                                                //
//     * Neither the name of the IMSE-CNM nor the names of its contributors may   //
//       be used to endorse or promote products derived from this software        //
//       without specific prior written permission.                               //
//                                                                                //
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"    //
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE      //
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE //
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE  //
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL     //
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR     //
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER     //
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,  //
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE  //
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.           //
//--------------------------------------------------------------------------------//

package xfuzzy.xfdm;

import xfuzzy.lang.*;

/**
 * Implements an identification scheme for fuzzy inference systems
 * based on the "Improved Clustering for Function Approximation"
 * algorithm, as described in [1] which extends [2].
 *
 * [1] Guill\'{e]n, A., Gonz\'{a}lez, J., Rojas, I., Pomares, H., Herrera, L.~J., Valenzuela, O., Prieto, A. (2007)
 *     Using fuzzy logic to improve a clustering technique for function approximation.
 *     Neurocomputing, 70(16-18):2853-2860
 *
 * [2] Gonz\'{a}lez, J., Rojas, I., Pomares, H., Ortega, J., and Prieto, A. (2002).
 *     A new Clustering Technique for Function Aproximation.
 *     IEEE Transactions on Neural Networks, 13(1):132–142.
 *
 * @author fedemp
 **/
public class XfdmICFA extends XfdmAlgorithm {

    // Whether to give verbose output/debug mode
    public static final boolean debug = false;

    // Initialize widths using a fixed radius
    public static final int WIDTH_INIT_FIXED_RADIUS = 1;
    // Inititalize width using the k-nn rule with k=1 (vector distance)
    public static final int WIDTH_INIT_KNN = 2;
    // Inititalize width using the k-nn rule with k=1 (dimension-wise distance)
    public static final int WIDTH_INIT_KNN_PER_DIMENSION = 3;
    // Initialize widths inversely proportional to the distortion
    public static final int WIDTH_INIT_DISTORTION = 4;

    public static final int width_init_scheme = WIDTH_INIT_DISTORTION;

    private int num_clusters;
    private double fuzziness;
    private int num_iterations;
    private boolean migration;

    private double norm_patterns[][];

    // See [1]
    private double clusters[][];
    private double degree_u[][];
    private double weight_w[][];
    private double distances_kjw[][];
    private double estimated_outputs[];

    /* Input dimension + output dimension */
    private int width;

    private double per_center_distortion[];
    private double average_distortion_before;
    private double average_distortion_migrated;

    double[] average_weight_per_center;

    private double[][] clusters_previous;
    private double variation;
    private double epsilon;
    private double radius;

    /**
     * Default constructor.
     **/
    public XfdmICFA() {
	this.migration = true;
	this.num_clusters = 10;
	this.fuzziness = 2.0;
	this.num_iterations = 25;
	this.epsilon = 0.01;
	this.radius = 0.1;
    }

    /**
     * Constructor intended to be used from the GUI system.
     **/
    public XfdmICFA(int num_clusters, int num_iterations, double fuzziness, double espsilon, boolean migration) {
	this.migration = migration;
	this.num_clusters = num_clusters;
	this.fuzziness = fuzziness;
	this.num_iterations = num_iterations;
	this.epsilon = epsilon;
	this.radius = 0.1;
    }

    /**
     * Constructor intended to be used from the configuration file parser.
     **/
    public XfdmICFA(double[] param) {
	this.num_clusters = (int) param[0];
	this.num_iterations = (int) param[1];
	this.fuzziness = param[2];
	this.epsilon = (double) param[3];
	this.migration = (0.0 != param[4]);
	this.radius = 0.1;
    }

    public Object clone() {
	return new XfdmICFA(num_clusters, num_iterations, fuzziness, epsilon, migration);
    }

    private void initializeMatrices() {
	// See [1]
	this.degree_u = new double[norm_patterns.length][clusters.length];
	this.distances_kjw = new double[norm_patterns.length][clusters.length];
	this.weight_w = new double[norm_patterns.length][clusters.length];
	this.estimated_outputs = new double[clusters.length];
	this.per_center_distortion = new double[num_clusters];
	this.average_weight_per_center = new double[num_clusters];
    }

    public int getNumberOfClusters() {
	return this.num_clusters;
    }

    public void setNumberOfClusters(int num) {
	this.num_clusters = num;
    }

    public int getNumberOfIterations() {
	return this.num_iterations;
    }

    public void setNumberOfIterations(int n) {
	this.num_iterations = n;
    }

    public double getFuzziness() {
	return this.fuzziness;
    }

    public void setFuzziness(double fuzz) {
	this.fuzziness = fuzz;
    }

    public double getEpsilon() {
	return this.epsilon;
    }

    public void setEpsilon(double e) {
	this.epsilon = e;
    }

    public boolean getMigration() {
	return this.migration;
    }

    public void setMigration(boolean m) {
	this.migration = m;
    }

    public String toString() {
	return "Improved Clustering for Function Approximation (ICFA)";
    }

    public String toCode() {
	String c = "xfdm_algorithm(ICFA, " + num_clusters + ", " + num_iterations + ", " + fuzziness + ")";
	return c;
    }

    public void compute(Specification spec, XfdmConfig cfg) throws XflException {
	this.spec = spec;
	this.config = cfg;
	this.pattern = config.getPatterns();

	this.opset = createOperatorSet();
	spec.addOperatorset(opset);

	this.inputtype = createInputTypes();
	for (int i = 0; i < inputtype.length; i++)
	    spec.addType(inputtype[i]);
	this.outputtype = createOutputTypes();
	for (int i = 0; i < outputtype.length; i++)
	    spec.addType(outputtype[i]);

	this.rulebase = createEmptyRulebase();
	this.spec.addRulebase(rulebase);

	createSystemStructure();
	this.spec.setModified(true);
	this.pattern.setRanges(spec);
	this.width = config.numinputs + config.numoutputs; // or this.inputtype.length + this.outputtype.length;
	this.norm_patterns = createNormPatterns();
	this.clusters = createInitialClusters();

	initializeMatrices();
	try {
	    do_ICFA_Clustering();
	} catch(Exception e) {
	    System.out.println("Exception in ICFA identification: " + e);
	}
	createContent();
    }

    public boolean do_ICFA_Clustering() throws XflException {

	ICFA_InitWeights();
	if (debug) {
	    System.out.println("Weigths initialized");
	    System.out.println("Starting ICFA Clustering with " + num_iterations + " iterations for " + num_clusters + " clusters.");
	}

	this.variation = Double.POSITIVE_INFINITY;
	for ( int i = 0; (i < num_iterations) && (this.variation > this.epsilon); i++) {
	    if ( debug )
		System.out.println("ICFA Iteration starts " + i + ": ");

	    // save current clusters for later check of variation
	    clusters_previous = clusters.clone();

	    ICFA_UpdateDegrees_U();
	    ICFA_Update_Clusters_EstimatedOutputs_Weights();
	    computeVariation();

	    if (debug) {
		for (int c = 0; c < clusters.length; c++ ) {
		    System.out.print("Cl: " + c + ": ");
		    for ( int j = 0; j < clusters[0].length; j++ )  {
			System.out.print(clusters[c][j] + " ");
		    }
		    System.out.println("");
		}
	    }

	    if ( num_clusters > 1 && migration ) {
		ICFA_Migration();

	    }
	    if (debug)
		System.out.println("* Variation at the end of iteration " + i + ": " + this.variation + " (epsilon: " +
				   this.epsilon + ")");
	}
	return true;
    }

    private void ICFA_Migration()
    {
	// Among the centers that have a distortion above the average, select the one with the smallest distortion
	int index_smallest_above_average = -1;
	double smallest_above_average = Double.POSITIVE_INFINITY;
	int index_largest_above_average = -1;
	double largest_above_average = Double.NEGATIVE_INFINITY;

	average_distortion_before = 0;
	for ( int j = 0; j < num_clusters; j++ ) {
	    per_center_distortion[j] = 0;
	    for ( int k = 0; k < norm_patterns.length; k++ ) {
		per_center_distortion[j] += Math.pow( degree_u[k][j], this.fuzziness ) * distances_kjw[k][j]
		    * weight_w[k][j] * weight_w[k][j];
	    }

	    average_distortion_before += per_center_distortion[j];
	}
	average_distortion_before /= num_clusters;

	for ( int j = 0; j < num_clusters; j++ ) {
	    if (per_center_distortion[j] > average_distortion_before ) {

		if (per_center_distortion[j] > largest_above_average ) {
		    largest_above_average = per_center_distortion[j];
		    index_largest_above_average = j;
		}

		if (per_center_distortion[j] < smallest_above_average ) {
		    smallest_above_average = per_center_distortion[j];
		    index_smallest_above_average = j;
		}
	    }
	}

	if ( index_largest_above_average != index_smallest_above_average &&
	     index_smallest_above_average >= 0 &&
	     index_largest_above_average >= 0 ) {

	    // Migrate the cluster with the smallest distortion among those with distortion above the average.
	    clusters[index_smallest_above_average] = clusters[index_largest_above_average];

	    double distortion_change = Math.abs(average_distortion_migrated-average_distortion_before) /
		average_distortion_before;
	    if (debug) {
		System.out.println("Migration selected, migrating " + index_smallest_above_average + " to " +
				   index_largest_above_average + " -  for " +
				   per_center_distortion[index_smallest_above_average] + ", " +
				   per_center_distortion[index_largest_above_average]);

		System.out.println("Average dist. before: " + average_distortion_before +
				   ", after: " + average_distortion_migrated +
				   ". Distortion change: " + distortion_change );
	    }

	    if ( average_distortion_before > average_distortion_migrated ) {
		if (debug) {
		    System.out.println("Accepting migration");
		    for (int c = 0; c < clusters.length; c++ ) {
			System.out.print("Cl " + c + ": ");
			for ( int j = 0; j < clusters[0].length; j++ )  {
			    System.out.print(clusters[c][j] + " ");
			}
			System.out.println("");
		    }
		}

	    } else {
		// revert migration
		clusters = clusters_previous;
		if (debug)
		    System.out.println("Rejecting migration");
	    }

	} else {
	    if (debug)
		System.out.println("Ignoring absurd migration between " + index_smallest_above_average +
				   " and " + index_largest_above_average);
	    average_distortion_migrated = average_distortion_before;
	}
    }

    private void computeVariation() {
	// compute max. variation to later check whether the clusters have changed significantly:
	double max_var = Double.NEGATIVE_INFINITY;
	for ( int j = 0; j < num_clusters; j++ ) {
	    for ( int k = 0; k < width; k++ ) {
		double diff = Math.abs((clusters[j][k] - clusters_previous[j][k])/clusters_previous[j][k]);
		if ( diff > max_var )
		    max_var = diff;
	    }
	}
	this.variation = max_var;
    }

    private void ICFA_InitWeights()
    {
	// Iterate over input patterns
	for ( int j = 0; j < norm_patterns.length; j++ )
	    // Iterate over clusters
	    for ( int k = 0; k < num_clusters; k++ )
		weight_w[j][k] = 1;
    }

    private void ICFA_UpdateDegrees_U() {
	double pow = 1/(this.fuzziness - 1);
	// First, calculate the point-centers distances
	// Iterate over patterns
	for ( int j = 0; j < norm_patterns.length; j++ ) {
	    // Iterate over clusters
	    for ( int k = 0; k < num_clusters; k++ ) {
		double dist =
		    distances_kjw[j][k] = distance(norm_patterns[j],clusters[k]); // * weight_w[j][k];
	    }
	}

	// Iterate over patterns
	for ( int k = 0; k < norm_patterns.length; k++ ) {
	    // Iterate over clusters
	    for ( int j = 0; j < num_clusters; j++ ) {
		double pow_distances_sum = 0;
		// iterate over clusters again
		for ( int i = 0; i < num_clusters; i++ ) {
		    double squared_weight_w = weight_w[k][j]*weight_w[k][j];
		    double weighted_distances_frac = (distances_kjw[k][j]*squared_weight_w) /
			(distances_kjw[k][i]*squared_weight_w);
		    pow_distances_sum += Math.pow( weighted_distances_frac , pow);

		    degree_u[k][j] = 1/pow_distances_sum;
		}
	    }
	}
    }

    private void ICFA_Update_Clusters_EstimatedOutputs_Weights() {
	// Iterate over clusters
	for ( int j = 0; j < num_clusters; j++ ) {
	    double[] sum_nom_cl = new double[clusters[0].length];
	    double sum_den_cl = 0;
	    double sum_nom_o = 0;
	    double sum_den_o = 0;
	    // Iterate over patterns
	    for ( int k = 0; k < norm_patterns.length; k++ ) {
		double squared_weight_w = weight_w[k][j]*weight_w[k][j];
		double pow_u = Math.pow(degree_u[k][j], fuzziness);
		double coef_cl = pow_u * squared_weight_w;
		sum_nom_cl = sum_vectors( sum_nom_cl, multiply_vector(coef_cl, norm_patterns[k]) );
		sum_den_cl += coef_cl;
		double coef_o = pow_u * distances_kjw[k][j];
		sum_nom_o += coef_o * norm_patterns[k][width - 1];  // width == clusters[0].length
		sum_den_o += coef_o;
	    }

	    // update clusters
	    clusters[j] = divide_vector(sum_nom_cl, sum_den_cl);
	    // update estimated outputs
	    estimated_outputs[j] = sum_nom_o / sum_den_o;

	    // update weights
	    // Iterate over patterns
	    for ( int k = 0; k < norm_patterns.length; k++ ) {
		// get square weights; norm_patterns[k][width -1] is the output value in the training patterns
		weight_w[k][j] = Math.abs( norm_patterns[k][width -1] - estimated_outputs[j] );
	    }
	}

    }

    /**
     * Square euclidean distance.
     **/
    private double distance(double[] x, double[] y) {
	double dist = 0;
	for(int i = 0; i < Math.min(x.length, y.length); i++)
	    dist += (x[i]-y[i]) * (x[i]-y[i]);
	return dist;
    }

    private double[] sum_vectors(double[] x, double[] y)
    {
	double result[] = new double[Math.min(x.length, y.length)];
	for (int i = 0 ; i < Math.min(x.length, y.length); i++ )
	    result[i] = x[i] + y[i];
	return result;
    }

    private double[] sub_vectors(double[] x, double[] y)
    {
	double result[] = new double[Math.min(x.length, y.length)];
	for (int i = 0 ; i < Math.min(x.length, y.length); i++ )
	    result[i] = x[i] - y[i];
	return result;
    }

    private double[] multiply_vector(double x, double[] v)
    {
	double result[] = new double[v.length];
	for(int i = 0; i < v.length; i++)
	    result[i] = x * v[i];
	return result;
    }

    private double[] divide_vector(double[] v, double x)
    {
	double result[] = new double[v.length];
	for(int i = 0; i < v.length; i++)
	    result[i] = v[i] /  x;
	return result;
    }

    /**
     * Patterns are normalized in the [0,1] range.
     **/
    private double[][] createNormPatterns() {
	int len = this.pattern.input.length;
	double normPatterns[][] = new double[len][this.width];
	double[] mins = new double[this.width];
	double[] maxes = new double[this.width];

	// compute mins and maxes
	for(int j = 0; j < width; j++) {
	    if ( j < inputtype.length ) {
		mins[j] = inputtype[j].min();
		maxes[j] = inputtype[j].max();
	    } else {
		mins[j] = outputtype[j-inputtype.length].min();
		maxes[j] = outputtype[j-inputtype.length].max();
	    }
	}

	// normalize in the [0,1] range
	for(int i=0; i < len; i++)
	    for(int j = 0; j < width; j++) {
		if( j < inputtype.length) {
		    normPatterns[i][j] = (pattern.input[i][j]-mins[j])/(maxes[j]-mins[j]);
		} else {
		    normPatterns[i][j] = (pattern.output[i][j-inputtype.length]-mins[j])/(maxes[j]-mins[j]);
		}
	    }
	return normPatterns;
    }

    /**
     * Create and initialize clusters.
     *
     * The initial centers for the inputs are distributed equally through the input domains.
     * The centers for the output are fixed to 1.
     **/
    private double[][] createInitialClusters() {
	double cl[][] = new double[num_clusters][width];
	for ( int j = 0; j < inputtype.length; j++) {
	    for(int i = 0; i < num_clusters; i++) {
		cl[i][j] = 0 + ((double)i+1)/((double)num_clusters+1);
	    }
	}
	for ( int j = 0; j < outputtype.length; j++) {
	    for ( int i = 0; i < num_clusters; i++ ) {
		cl[i][inputtype.length + j] = 1;
	    }
	}

	if (debug) {
	    System.out.println("INITIAL CLUSTERS: ");
	    for (int c = 0; c < num_clusters; c++ ) {
		System.out.print("  Cl " + c + ": ");
		for ( int j = 0; j < cl[0].length; j++ )  {
		    System.out.print( cl[c][j] + " ");
		}
		System.out.println("");
	    }
	}
	return cl;
    }

    /* The following methods are here for historic reasons:
     createRules, createInputTypes, createOutputTypes.  They should be
     moved up in the hierarchy to the XfdmAlgorithm class, as the same
     implementation is shared by all the supported clustering
     schemes. */

    /**
     * Fill in the system specification.
     **/
    private void createContent() {

	if ( WIDTH_INIT_DISTORTION == this.width_init_scheme ) {
	    for ( int j = 0; j < num_clusters; j++ ) {
		average_weight_per_center[j] = 0;
		for ( int k = 0; k < norm_patterns.length; k++ ) {
		    average_weight_per_center[j] += weight_w[k][j];
		}
		average_weight_per_center[j] /= norm_patterns.length;
	    }
	}

	for(int i = 0; i < inputtype.length; i++)
	    createBells(inputtype[i],i);
	for(int i=0; i<outputtype.length; i++) {
	    switch(config.systemstyle.defuz) {
	    case XfdmSystemStyle.FUZZYMEAN:
		createSingletons(outputtype[i],inputtype.length + i);
		break;
	    case XfdmSystemStyle.WEIGHTED:
		// TODO?
		//createBells(outputtype[i],inputtype.length + i);
		break;
	    case XfdmSystemStyle.TAKAGI:
		// TODO?
		//createParametric(outputtype[i],inputtype.length + i);
		break;
	    }
	}
	createRules();
    }

    private void createRules() {
	Variable ivar[] = rulebase.getInputs();
	Variable ovar[] = rulebase.getOutputs();
	int is = Relation.IS;

	for(int i = 0; i < clusters.length; i++) {
	    LinguisticLabel pmf = ivar[0].getType().getAllMembershipFunctions()[i];
	    Relation rel = Relation.create(is,null,null,ivar[0],pmf,rulebase);
	    for(int j = 1; j < ivar.length; j++) {
		pmf = ivar[j].getType().getAllMembershipFunctions()[i];
		Relation nrel = Relation.create(is,null,null,ivar[j],pmf,rulebase);
		rel = Relation.create(Relation.AND,rel,nrel,null,null,rulebase);
	    }
	    Rule rule = new Rule(rel);
	    for(int j = 0; j < ovar.length; j++) {
		pmf = ovar[j].getType().getAllMembershipFunctions()[i];
		rule.add(new Conclusion(ovar[j],pmf,rulebase));
	    }
	    rulebase.addRule(rule);
	}
    }

    protected Type[] createInputTypes() {
	Type itp[] = new Type[config.numinputs];
	for(int i = 0; i < config.numinputs; i++) {
	    String tname = "Tin"+i;
	    Universe universe = null;
	    if(config.commonstyle.isUniverseDefined()) {
		try { universe=new Universe(config.commonstyle.min,config.commonstyle.max);}
		catch(Exception ex) {}
	    }

	    if(config.inputstyle != null && config.inputstyle.length > i &&
	       config.inputstyle[i] != null) {
		tname = "T"+config.inputstyle[i].name;
		if(config.inputstyle[i].isUniverseDefined()) {
		    try {
			universe=new Universe(config.inputstyle[i].min,config.inputstyle[i].max);
		    } catch(Exception ex) {
		    }
		} else {
		    universe = null;
		}
	    }

	    if(universe == null)
		universe = pattern.getUniverse(i,true);
	    itp[i] = new Type(tname,universe);
	}
	return itp;
    }

    private Type[] createOutputTypes() {
	Type otp[] = new Type[config.numoutputs];

	for(int i = 0; i < config.numoutputs; i++) {
	    String tname = "T" + config.systemstyle.outputname;
	    if(config.numoutputs > 1)
		tname += ""+i;
	    otp[i] = new Type(tname,pattern.getUniverse(i,false));
	}
	return otp;
    }

    private void createSingletons(Type type, int index) {
	Universe u = type.getUniverse();
	double min = u.min();
	double max = u.max();
	for(int cl = 0; cl < clusters.length; cl++) {
	    ParamMemFunc pmf = new pkg.xfl.mfunc.singleton();
	    pmf.set("mf" + cl, u);
	    pmf.set( min + clusters[cl][index]*(max-min) );
	    try {
		type.add(pmf);
	    } catch(XflException e) {}
	}
    }

    private void createBells(Type type, int index) {
	Universe u = type.getUniverse();
	double min = u.min();
	double max = u.max();
	double param[] = new double[2];
	for(int i = 0; i < clusters.length; i++) {
	    ParamMemFunc pmf = new pkg.xfl.mfunc.bell();
	    pmf.set("mf"+i, u);
	    param[0] = min + clusters[i][index]*(max-min);

	    if ( WIDTH_INIT_FIXED_RADIUS == width_init_scheme ) {
		// 1st alternative: fix radius, as in subtractive clustering.
		param[1] = radius*(max - min)/2;
	    } else if ( (WIDTH_INIT_KNN == width_init_scheme) || (WIDTH_INIT_KNN_PER_DIMENSION == width_init_scheme) ) {
		// 2nd alternative: k-NN: 1-nearest neighbor (using either overall or per-dimesion distance)
		// Find the nearest neighbor
		int neighbor_index = -1;
		double max_dist = Double.NEGATIVE_INFINITY;
		for (int j = 0; j < norm_patterns.length; j++ ) {
		    if ( distances_kjw[j][i] > max_dist) {
			max_dist = distances_kjw[j][i];
			neighbor_index = j;
		    }
		}
		if ( WIDTH_INIT_KNN == width_init_scheme ) {
		    // 2. k-NN overall distance: this uses overall distance
		    param[1] = distances_kjw[neighbor_index][i] * (max-min)/2;
		} else { // if ( WIDTH_INIT_KNN_PER_DIMENSION == width_init_scheme ) {
		    // 3. * k-NN per-dimension distance:  and this uses per-dimension distance
		    // 3 IS BETTER THAN 2 (and than 1), but WORSE THAN 4
		    double per_dimension_neighbor_distance =
			Math.abs(norm_patterns[neighbor_index][index] - clusters[i][index]);
		    // square it, like in distances_kjw
		    per_dimension_neighbor_distance *= per_dimension_neighbor_distance;
		    param[1] = per_dimension_neighbor_distance * (max-min)/2;
		}
	    } else { //if ( WIDTH_INIT_DISTORTION == width_init_scheme ) {
		// 4th alternative: radius inversely proportional to the distortion.
		// Note the same widths are used for all the inputs of a certain rule
		param[1] = (max-min)/2/average_weight_per_center[i];
	    } // One more possibility, use the distortion: param[1] = (max-min)/2/per_center_distortion[i];

	    try {
		pmf.set(param);
		type.add(pmf);
	    } catch(XflException ex) {}
	}
    }

}

redpajama_set_name: RedPajamaGithub


text:
class CreateGoods < ActiveRecord::Migration
  def change
    create_table :goods do |t|

      t.timestamps
    end
  end
end


text:
<?php
class helper_oauthencode{
    public static function genSign($params, $encode_method = 'md5'){
        ksort($params);
        $string = '';
        foreach($params as $key=>$value){
            $string .= "{$key}={$value}&";
        }
        $string = rtrim($string, '&');
        return call_user_func(array('helper_oauthencode', $encode_method), $string);
    }

    private static function md5($string){
        return md5($string);
    }

    private static function sha1($string){
        return sha1($string);
    }
}


text:
namespace Microsoft.Azure.Management.DataBoxEdge.Models
{

    /// <summary>
    /// Defines values for ClientPermissionType.
    /// </summary>
    public static class ClientPermissionType
    {
        public const string NoAccess = "NoAccess";
        public const string ReadOnly = "ReadOnly";
        public const string ReadWrite = "ReadWrite";
    }
}


text:
import * as React from 'react';
import { CSSModule } from './index';

export interface NavItemProps extends React.HTMLAttributes<HTMLElement> {
  [key: string]: any;
  tag?: React.ElementType;
  active?: boolean;
  cssModule?: CSSModule;
}

declare class NavItem extends React.Component<NavItemProps> {}
export default NavItem;


text:
FROM joynr-base:latest

###################################################
# uninstall java 11
###################################################
RUN dnf remove -y java-11-openjdk-devel \
    java-11-openjdk \
    java-11-openjdk-headless \
    && dnf -y autoremove

###################################################
# configure Java 17 as default
###################################################
RUN update-alternatives --set java /usr/lib/jvm/java-17-openjdk*.x86_64/bin/java \
    && update-alternatives --set javac /usr/lib/jvm/java-17-openjdk*.x86_64/bin/javac \
    && update-alternatives --set jre_openjdk /usr/lib/jvm/java-17-openjdk*.x86_64 \
    && update-alternatives --set java_sdk_openjdk /usr/lib/jvm/java-17-openjdk*.x86_64

###################################################
# Patch Java security configuration so that SHA1
# signed classes are still accepted. This is
# required for old plugins / dependencies required
# by joynr generator which need to stay compatible
# with Java 8 and thus cannot be updated.
###################################################
RUN mkdir -p /tmp/patches/java
COPY patches/java /tmp/patches/java
RUN cd /usr/lib/jvm/java-17/conf/security \
    && patch < /tmp/patches/java/java-17.security.patch \
    && rm -fr /tmp/patches/java


text:
<scientilla-print-header class="d-none d-print-block"></scientilla-print-header>

                Login

                    Istituto Italiano di Tecnologia

                <documentation-sidebar></documentation-sidebar>

<cookie-consent></cookie-consent>

<scientilla-footer class="footer-container"></scientilla-footer>


text:
package b_trees_visualizer.data_structure;

import java.util.ArrayList;
import java.util.Random;
import java.util.Stack;

import b_trees_visualizer.graphic_interface.Applet;

/** MISSION of this class is to provide ADT for BTree**/

public class BTree<E extends Comparable<? super E>> {

	private int grade;
	private Random rand;
	private Stack<Integer> stack;
	private BTreeNode<E> root;
	private final int MAX_NUMBER_KEYS = 1000;

	/**
	** @param grade: Integer
	** @throws Exception : if the grade of the BTree is < 2
	** EFFECT produce a BTree of this.grade = grade.
	** For each node the number of keys is <= 2*this.grade
	** and > t-1
	**/
	public BTree(int grade) {

		try {
			if (grade < 2) {
				throw new Exception();
			}

			this.grade = grade;
			/* used to produce random insertion*/
			this.rand = new Random(System.currentTimeMillis());
			this.stack = new Stack<Integer>();
			root = new BTreeNode<E>();

		} catch (Exception e) {

			System.err.println("The tree's grade must be higher than or equal to 2");

		}
	}

	/**
	** @param data: an ArrayList of integer reprensenting the keys
	** of the root
	**/
	public BTree (ArrayList<E> data) {

		this.root = new BTreeNode<E> (data);

	}

	/**
	** EFFECT produce this with the insertion
	** of a random integer in [0,999]
	**/
	public void next () {

		int key = rand.nextInt(MAX_NUMBER_KEYS);
		stack.push(key);
		((BTree<Integer>)this).insertKey(key,true);

	}

	public boolean isIn (E key) {return stack.contains(key);}

	public E peekRandomOne () {

		int i = this.rand.nextInt(this.stack.size());
		return (E) this.stack.remove(i);
	}

	/**
	** @throws NullPointerException : if the BTree is empty
	** there aren't previous configuration
	** EFFECT produce this without the last element added
	**/
	public void previous () throws NullPointerException {

		if (stack.isEmpty()) {

			throw new NullPointerException();

		}

		int key = stack.pop();
		((BTree<Integer>)this).removeKey(key,true);

	}

	/**
	** @return clonedBTree : a BTree
	** EFFECT produce a copy of this
	**/
	public BTree<E> cloneTree() {
		BTree<E> clonedTree = new BTree<E>(grade);
		clonedTree.setRoot(root.cloneNode());
		return clonedTree;
	}

	/**
	** @return this.grade, Integer
	**/
	public int getGrade() {
		return grade;
	}

	/**
	** @param grade :  integer
	** EFFECT set this.grade = grade
	**/
	public void setGrade(int grade) {
		if (grade > 1) {
			this.grade = grade;
		}
	}

	/**
	** @return root : BTreeNode
	**/
	public BTreeNode<E> getRoot() {
		return root;
	}

	/**
	** @param root  a BTreeNode<E>
	** EFFECT change this.root in root
	**/
	public void setRoot(BTreeNode<E> root) {
		this.root = root;
	}

	/**
	** @param element : an object E
	** @return the BTreeNode containig E
	**/
	public BTreeNode<E> search(E element) {
		return root.search(element);
	}

	/**
	** @param element : an object E,
	** the same of the element in this
	** @param trackSteps : boolean
	** @return 1 if the insertion is competed succesfully
	** 0 otherwise
	** EFFECT insert element in this, if a node is full it's splitted
	**/
	public int insertKey(E element, boolean trackSteps) {
		/* The element is added to the tree only if there isn't already a key with the same value
		 * in the tree. The search method is used in order to not change the tree structure with
		 * the changes that are done while looking for the position to insert the key in.
		 */
		if (root.search(element) == null) {
			//If the root is full, a new root is made by doing a split on the old one.
			if (root.getNumberOfElements() == 2*grade - 1) {
				if (trackSteps) {
					Applet.stepsP.clearStates();
					root.setFocus(true);
					Applet.stepsP.saveTreeState("Initial state");
					root.setFocus(false);
				}
				BTreeNode<E> newRoot = new BTreeNode<E>();
				newRoot.addChild(root);
				newRoot.setLeaf(false);
				BTreeNode<E> oldRoot = root;
				root = newRoot;
				if (trackSteps) { oldRoot.setFocus(true); }
				oldRoot.nodeSplit(newRoot, 0, grade, trackSteps);
				if (trackSteps) { oldRoot.setFocus(false); }
			} else {
				if (trackSteps) {
					Applet.stepsP.clearStates();
					Applet.stepsP.saveTreeState("Initial state");
				}
			}
			root.insertKey(element, grade, trackSteps);
			if (trackSteps) {
				Applet.stepsP.repaint();
			}
			stack.push((Integer) element);
			return 0;
		} else {
			return 1;
		}
	}

	/**
	** @param element : an object E,
	** the same of the element in this
	** @param trackSteps : boolean
	** @return 1 if the elimination of element is completed succesfully
	** 0 otherwise
	** EFFECT remove element from this
	**/
	public int removeKey(E element, boolean trackSteps) {
		/* If there isn't the element in the tree, the removeKey method is not
		 * called to avoid the modifications on the structure that are done
		 * while searching for the key to remove.
		 */
		if (!(root.search(element) == null)) {
			if (trackSteps) {
				Applet.stepsP.clearStates();
				Applet.stepsP.saveTreeState("Initial state");
			}

			root.removeKey(element, grade, trackSteps);
			checkAndRemoveNullRoot();

			if (trackSteps) {
				Applet.stepsP.repaint();
			}
			stack.remove((Integer) element);
			return 0;
		} else {
			return 1;
		}
	}

	/**
	** EFFECT check if the root is null, in this case remove it
	**/
	public void checkAndRemoveNullRoot() {
		if (!root.isLeaf() && root.getNumberOfElements() == 0) {
			root = root.extractChild(0);
		}
	}

	/**
	** @return the String containig the grade and
	** the elements in this.
	**/
	public String toString() {
		return "Grade: " + grade + "\n" + root.toString();
	}

	/**
	** @return the String containig the grade and
	** the elements in this ordered.
	**/
	public String toStringInOrder() {
		return "Grade: " + grade + "\n" + root.toStringInOrder();
	}

	/**
	** @return a boolean. true if the property of BTree are respected in this
	** false otherwise
	**/
	public boolean checkBTree() {
		// The root is checked separately due to the different properties on the
		// data boundaries
		boolean ordered = true;
		ArrayList<E> l = root.toInOrderArrayList();

		boolean temp = !(root.isLeaf() ^ root.getChildren().isEmpty());
		temp &= root.getNumberOfElements() == root.getData().size();
		temp &= root.getNumberOfElements() >= 1 && root.getNumberOfElements() <= 2*grade;

		if (!root.isLeaf()) {
			temp &= root.getNumberOfElements() + 1 == root.getChildren().size();
		}

		for (int i = 0; i < root.getChildren().size(); i++) {
			temp &= root.getChild(i).checkNode(grade);
		}

		// A method that goes through the whole tree in-order is used to check
		// whether the keys in the tree are all following a non-decreasing order.
		for (int i = 0; i < l.size() - 1; i++) {
			ordered &= l.get(i).compareTo(l.get(i + 1)) <= 0;
		}

		return temp && ordered;
	}

	/**
	** @return an integer representing the height of this
	**/
	public int getHeight() {
		return root.getHeightSubtree();
	}

	/**
	** @return true if this is empty
	** false otherwise
	**/
	public boolean isEmpty() {
		return root.getNumberOfElements() == 0;
	}

	/**
	** EFFECT create a new empty BTree
	**/
	public void emptyTree() {
		root = new BTreeNode<E>();
		this.stack = new Stack<Integer> ();
	}
}


text:
// SPDX-License-Identifier: BSD-2-Clause

#include <assert.h>
#include <atomic.h>
#include <kernel/refcount.h>

bool refcount_inc(struct refcount *r)
{
	unsigned int nval;
	unsigned int oval = atomic_load_uint(&r->val);

	while (true) {
		nval = oval + 1;

		/* r->val is 0, we can't do anything more. */
		if (!oval)
			return false;

		if (atomic_cas_uint(&r->val, &oval, nval))
			return true;
		/*
		 * At this point atomic_cas_uint() has updated oval to the
		 * current r->val.
		 */
	}
}

bool refcount_dec(struct refcount *r)
{
	unsigned int nval;
	unsigned int oval = atomic_load_uint(&r->val);

	while (true) {
		assert(oval);
		nval = oval - 1;

		if (atomic_cas_uint(&r->val, &oval, nval)) {
			/*
			 * Value has been updated, if value was set to 0
			 * return true to indicate that.
			 */
			return !nval;
		}
		/*
		 * At this point atomic_cas_uint() has updated oval to the
		 * current r->val.
		 */
	}
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.0"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>EmbASP-Java v7.1.0: it.unical.mat.embasp.specializations.dlv2.android.DLV2AndroidReasoner Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

EmbASP-Java v7.1.0

it

unical

mat

embasp

specializations

dlv2

android

DLV2AndroidReasoner

Public Member Functions |
Protected Member Functions |
List of all members

it.unical.mat.embasp.specializations.dlv2.android.DLV2AndroidReasoner Class Reference

Inheritance diagram for it.unical.mat.embasp.specializations.dlv2.android.DLV2AndroidReasoner:

Public Member Functions

 	DLV2AndroidReasoner ()

String 	handleActionSolve (String program, String options, String filesPath)

void 	onDestroy ()

Protected Member Functions

void 	onHandleIntent (Intent intent)

Constructor & Destructor Documentation

◆ DLV2AndroidReasoner()

          it.unical.mat.embasp.specializations.dlv2.android.DLV2AndroidReasoner.DLV2AndroidReasoner
          (
          	)

inline

Member Function Documentation

◆ handleActionSolve()

          String it.unical.mat.embasp.specializations.dlv2.android.DLV2AndroidReasoner.handleActionSolve
          (
          String
          program,

          String
          options,

          String
          filesPath

          )

inline

◆ onDestroy()

          void it.unical.mat.embasp.specializations.dlv2.android.DLV2AndroidReasoner.onDestroy
          (
          	)

inline

◆ onHandleIntent()

          void it.unical.mat.embasp.specializations.dlv2.android.DLV2AndroidReasoner.onHandleIntent
          (
          Intent
          intent	)

inlineprotected

The documentation for this class was generated from the following file:

embasp-java/app/src/main/java/it/unical/mat/embasp/specializations/dlv2/android/DLV2AndroidReasoner.java

<address class="footer">
Generated by  1.9.0
</address>


text:
"""
The NeuralAgent class wraps a deep Q-network for training and testing
in the Arcade learning environment.

Author: Nathan Sprague

"""

import os
import cPickle
import time
import logging
import json

import numpy as np

from ale_agent_base import AgentBase
import ale_data_set

import sys

sys.setrecursionlimit(10000)

class NeuralAgent(AgentBase):
    def __init__(self, params):
        super(NeuralAgent, self).__init__(params)

        self.params = params
        self.network = None
        self.action_set = None
        self.num_actions = -1

        self.epsilon_start = self.params.epsilon_start
        self.epsilon_min = self.params.epsilon_min
        self.epsilon_decay = self.params.epsilon_decay
        self.replay_memory_size = self.params.replay_memory_size
        self.exp_pref = self.params.experiment_prefix
        self.replay_start_size = self.params.replay_start_size
        self.update_frequency = self.params.update_frequency
        self.phi_length = self.params.phi_length
        self.image_width = self.params.resized_width
        self.image_height = self.params.resized_height

        self.rng = self.params.rng

        self.data_set = ale_data_set.DataSet(width=self.image_width,
                                             height=self.image_height,
                                             rng=self.rng,
                                             max_steps=self.replay_memory_size,
                                             phi_length=self.phi_length)

        # just needs to be big enough to create phi's
        self.test_data_set = ale_data_set.DataSet(width=self.image_width,
                                                  height=self.image_height,
                                                  rng=self.rng,
                                                  max_steps=self.phi_length * 2,
                                                  phi_length=self.phi_length)
        self.epsilon = self.epsilon_start
        if self.epsilon_decay != 0:
            self.epsilon_rate = ((self.epsilon_start - self.epsilon_min) /
                                 self.epsilon_decay)
        else:
            self.epsilon_rate = 0

        self.testing = False

        self.current_epoch = 0
        self.episode_counter = 0
        self.batch_counter = 0
        self.total_reward = 0
        self.holdout_data = None

        # In order to add an element to the data set we need the
        # previous state and action and the current reward.  These
        # will be used to store states and actions.
        self.last_img = None
        self.last_action = None

        self.export_dir = self._create_export_dir()
        self._open_params_file()
        self._open_results_file()
        self._open_learning_file()

    def initialize(self, action_set):
        self.action_set = action_set
        self.num_actions = len(self.action_set)

        if self.params.qlearner_type is None:
            raise Exception("The QLearner/network type has not been specified")

        if self.params.nn_file is None:
            self.network = self.params.qlearner_type(
                num_actions=self.num_actions,
                input_width=self.params.resized_width,
                input_height=self.params.resized_height,
                num_frames=self.params.phi_length,
                params=self.params)
        else:
            handle = open(self.params.nn_file, 'r')
            self.network = cPickle.load(handle)

    # region Dumping/Logging
    def _create_export_dir(self):
        # CREATE A FOLDER TO HOLD RESULTS
        time_str = time.strftime("_%m-%d-%H-%M_", time.gmtime())
        export_dir = self.exp_pref + time_str + \
                     "{}".format(self.params.learning_rate).replace(".", "p") \
                     + "_" + \
                     "{}".format(self.params.discount).replace(".", "p")
        try:
            os.stat(export_dir)
        except OSError:
            os.makedirs(export_dir)

        return export_dir

    def _open_params_file(self):
        self.params_file = open(self.export_dir + '/params.json', 'w')
        param_list = [getattr(self.params, attr) \
            for attr in dir(self.params) \
            if isinstance(getattr(self.params, attr), (int, float, str))]
        json.dump(param_list, self.params_file)
        self.params_file.close()

    def _open_results_file(self):
        logging.info("OPENING " + self.export_dir + '/results.csv')
        self.results_file = open(self.export_dir + '/results.csv', 'w', 0)
        self.results_file.write(
            'epoch,num_episodes,total_reward,reward_per_epoch,mean_q\n')
        self.results_file.flush()

    def _open_learning_file(self):
        self.learning_file = open(self.export_dir + '/learning.csv', 'w', 0)
        self.learning_file.write('mean_loss,epsilon\n')
        self.learning_file.flush()

    def _update_results_file(self, epoch, num_episodes, holdout_sum):
        out = "{},{},{},{},{}\n".format(epoch, num_episodes,
                                        self.total_reward,
                                        self.total_reward / float(num_episodes),
                                        holdout_sum)

        self.results_file.write(out)
        self.results_file.flush()

    def _update_learning_file(self):
        out = "{},{}\n".format(np.mean(self.loss_averages),
                               self.epsilon)
        self.learning_file.write(out)
        self.learning_file.flush()

    def _persist_network(self, network_filename):
        full_filename = os.path.join(self.export_dir, network_filename)
        with open(full_filename, 'w') as net_file:
            cPickle.dump(self.network, net_file, -1)

    # endregion

    def start_epoch(self, epoch):
        self.current_epoch = epoch

    def start_episode(self, observation):
        """
        This method is called once at the beginning of each episode.
        No reward is provided, because reward is only available after
        an action has been taken.

        Arguments:
           observation - height x width numpy array

        Returns:
           An integer action
        """

        self.step_counter = 0
        self.batch_counter = 0
        self.episode_reward = 0

        # We report the mean loss for every epoch.
        self.loss_averages = []

        return_action = self.rng.randint(0, self.num_actions)

        self.last_action = return_action

        self.last_img = observation

        return return_action

    def _show_phis(self, phi1, phi2):
        import matplotlib.pyplot as plt
        for p in range(self.phi_length):
            plt.subplot(2, self.phi_length, p + 1)
            plt.imshow(phi1[p, :, :], interpolation='none', cmap="gray")
            plt.grid(color='r', linestyle='-', linewidth=1)
        for p in range(self.phi_length):
            plt.subplot(2, self.phi_length, p + 5)
            plt.imshow(phi2[p, :, :], interpolation='none', cmap="gray")
            plt.grid(color='r', linestyle='-', linewidth=1)
        plt.show()

    def _step_testing(self, reward, observation):
        action = self._choose_action(data_set=self.test_data_set,
                                     epsilon=.05,
                                     cur_img=observation,
                                     reward=np.clip(reward, -1, 1))
        return action

    def _step_training(self, reward, observation):
        if len(self.data_set) > self.replay_start_size:
            self.epsilon = max(self.epsilon_min,
                               self.epsilon - self.epsilon_rate)

            action = self._choose_action(data_set=self.data_set,
                                         epsilon=self.epsilon,
                                         cur_img=observation,
                                         reward=np.clip(reward, -1, 1))

            if self.step_counter % self.update_frequency == 0:
                loss = self._do_training()
                self.batch_counter += 1
                self.loss_averages.append(loss)

        else:  # Still gathering initial random data...
            action = self._choose_action(data_set=self.data_set,
                                         epsilon=self.epsilon,
                                         cur_img=observation,
                                         reward=np.clip(reward, -1, 1))
        return action

    def step(self, reward, observation):
        """
        This method is called each time step.

        Arguments:
           reward      - Real valued reward.
           observation - A height x width numpy array

        Returns:
           An integer action.

        """
        self.episode_reward += reward
        if self.testing:
            action = self._step_testing(reward, observation)
        else:
            action = self._step_training(reward, observation)

        self.step_counter += 1
        self.last_action = action
        self.last_img = observation

        return action

    def _choose_action(self, data_set, epsilon, cur_img, reward):
        """
        Add the most recent data to the data set and choose
        an action based on the current policy.
        """

        data_set.add_sample(self.last_img, self.last_action, reward, False)
        if self.step_counter >= self.phi_length:
            phi = data_set.phi(cur_img)
            action = self.network.choose_action(phi, epsilon)
        else:
            action = self.rng.randint(0, self.num_actions)

        return action

    def _do_training(self):
        """
        Returns the average loss for the current batch.
        May be overridden if a subclass needs to train the network
        differently.
        """
        states, actions, rewards, next_states, terminals = \
            self.data_set.random_batch(
                self.network.batch_size)
        return self.network.train(states, actions, rewards,
                                  next_states, terminals)

    def end_episode(self, reward, terminal=True):
        """
        This function is called once at the end of an episode.

        Arguments:
           reward      - Real valued reward.
           terminal    - Whether the episode ended intrinsically
                         (ie we didn't run out of steps)
        Returns:
            None
        """

        self.episode_reward += reward
        self.step_counter += 1

        if self.testing:
            # If we run out of time, only count the last episode if
            # it was the only episode.
            if terminal or self.episode_counter == 0:
                self.episode_counter += 1
                self.total_reward += self.episode_reward
        else:

            # Store the latest sample.
            self.data_set.add_sample(self.last_img,
                                     self.last_action,
                                     np.clip(reward, -1, 1),
                                     True)

            if self.batch_counter > 0:
                self._update_learning_file()
                logging.info(
                    "average loss: {:.4f}".format(np.mean(self.loss_averages)))

    def finish_epoch(self, epoch):
        network_filename = 'network_file_' + str(epoch) + '.pkl'
        self._persist_network(network_filename)

    def start_testing(self, epoch):
        self.testing = True
        self.total_reward = 0
        self.episode_counter = 0

    def finish_testing(self, epoch):
        self.testing = False
        holdout_size = 3200

        if self.holdout_data is None and len(self.data_set) > holdout_size:
            self.holdout_data = self.data_set.random_batch(holdout_size)[0]

        holdout_sum = 0
        if self.holdout_data is not None:
            for i in range(holdout_size):
                holdout_sum += np.max(
                    self.network.q_vals(self.holdout_data[i, ...]))

        self._update_results_file(epoch, self.episode_counter,
                                  holdout_sum / holdout_size)

if __name__ == "__main__":
    pass


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MonocleGiraffe.Portable.Helpers
{
    public interface IIncrementalCollection
    {
        Task LoadMoreAsync(uint count);

        bool HasMore { get; }
    }
}


text:
CMAKE_<LANG>_OUTPUT_EXTENSION
-----------------------------

Extension for the output of a compile for a single file.

This is the extension for an object file for the given ``<LANG>``.  For
example ``.obj`` for C on Windows.


text:
FROM drupalci/db-base
MAINTAINER drupalci

# Packages.
RUN apt-get -qq update
RUN apt-get -qq -y install locales debconf wget software-properties-common && \
    add-apt-repository 'deb http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg main'

# Set a default language, so that PostgreSQL can use UTF-8 encoding (required)
RUN localedef -i en_US -c -f UTF-8 en_US.UTF-8
RUN echo 'LANG="en_US.UTF-8"' > /etc/default/locale
RUN echo 'LC_ALL="en_US.UTF-8"' > /etc/default/locale
RUN echo 'LANGUAGE="en_US:en"' >> /etc/default/locale

RUN echo "en_US.UTF-8 UTF-8" > /etc/locale.gen
RUN locale-gen en_US.UTF-8
RUN dpkg-reconfigure locales

ENV LANGUAGE en_US:en
ENV LANG en_US.UTF-8
ENV LC_ALL en_US.UTF-8

# update the apt cache and install our needed packages
RUN wget -O - http://apt.postgresql.org/pub/repos/apt/ACCC4CF8.asc | apt-key add -
RUN apt-get -y update && \
    apt-get -y install postgresql-9.4

RUN apt-get clean && apt-get autoclean && apt-get -y autoremove

# Adjust PostgreSQL configuration so that remote connections to the database are possible.
RUN echo "host all all 0.0.0.0/0 md5" >> /etc/postgresql/9.4/main/pg_hba.conf
RUN echo "listen_addresses='*'" >> /etc/postgresql/9.4/main/postgresql.conf

# Expose the PostgreSQL port
EXPOSE 5432

USER postgres

COPY ./conf/startup.sh /opt/startup.sh

CMD ["/bin/bash", "/opt/startup.sh"]


text:
*A Ruby library for diffing GeoJSON files*

[![Gem Version](https://badge.fury.io/rb/geojson-diff.svg)](http://badge.fury.io/rb/geojson-diff) [![Build Status](https://travis-ci.org/benbalter/geojson-diff.svg?branch=master)](https://travis-ci.org/benbalter/geojson-diff)

## Overview

GeoJSON Diff takes two GeoJSON files representing the same geometry (or geometries) at two points in time, and generates three GeoJSON files representing the `added`, `removed`, and `unchanged` geometries (including changed properties).

These three GeoJSON files can be used to generate a visual representation of the changes (proposed or realized), e.g., by coloring the added elements green and the removed elements red. GeoJSON Diff is what powers [GeoJSON diffing on GitHub](https://github.com/blog/1772-diffable-more-customizable-maps).

### GeoJSON Diff in the wild

See GeoJSON diff in action! Here's [a diff of Illinois's famed 4th congressional district](https://github.com/benbalter/congressional-districts/commit/2233c76ca5bb059582d796f053775d8859198ec5) after undergoing redistricting in 2011:

[![Illinois 4th Congressional district](https://f.cloud.github.com/assets/282759/2090660/63f2e45a-8e97-11e3-9d8b-d4c8078b004e.gif)](https://github.com/benbalter/congressional-districts/commit/2233c76ca5bb059582d796f053775d8859198ec5#diff-85d2c1b78193e963475250414e57940b)

GeoJSON Diff will even diff properties within the geometry when they change:

[![Updating a property](https://f.cloud.github.com/assets/282759/2022569/dfaf96b8-884f-11e3-95ca-8f54c60a2ccf.png)](https://github.com/DU-GIS/Geojson_Data/commit/042e86e417a7fb9e43504640046339e82618e4c2#diff-0cca6b7c0e294c8d3e9d9b8090ab9e24)

## Usage

```ruby
diff = GeojsonDiff.new geojson_before, geojson_after

diff.added
# => {"type":"Feature"... (valid GeoJSON representing the added geometries)

diff.removed
# => {"type":"Feature"... (valid GeoJSON representing the removed geometries)

diff.unchanged
# => {"type":"Feature"... (valid GeoJSON representing the unchanged geometries)
```

For practical examples, take a look at the [test/fixtures directory](test/fixtures).

## Displaying the resulting GeoJSON

Every geometry within the resulting GeoJSON files will be appended with standard GeoJSON properties in the `_geojson_diff` namespace.

* `type` - this field contains either `added`, `removed`, or `unchanged` and describes the state of the geometry as it relates to the initial GeoJSON file.
* `added`, `removed`, `changed` - these fields contain an array of property keys. If a given key is in the `added` array, that property existed in the resulting geometry, but not in the initial geometry. Likewise, if a key is in `removed` array it existed in the initial geometry, but not the resulting geometry, and if the key is in the `changed` array, it existed in both the initial and resulting geometry, but was changed.
* For changed properties, the values of the `after` GeoJSON file will be marked up as a [Diffy `:html` diff](https://github.com/samg/diffy#html-output) and will represent the inline diff of the changed value.

## Installation

### Requirements

GeoJSON Diff is based on [rgeo](https://github.com/dazuma/rgeo), [rgeo-geojson](https://github.com/dazuma/rgeo-geojson), [geos](http://trac.osgeo.org/geos/), [ffi-geos](https://github.com/dark-panda/ffi-geos), and [diffy](https://github.com/samg/diffy).

### Installing GEOS

If you're on OS X and have Homebrew installed, you'll first want to run `brew install geos` to install the GEOS geospatial library. On other systems, consult [the GEOS installation instructions](http://trac.osgeo.org/geos/).

### Installing the Gem

Add the following to your project's Gemfile and run `bundle install`:

`gem 'geojson-diff'`

### Pro-Tip

Because the library depends on [GEOS](http://trac.osgeo.org/geos/), which can be finicky on some systems, the set-it-and-forget-it way to get everything set up is to:

1. Add `gem 'geojson-diff'` to your project's Gemfile
2. Copy the contents of [script/bootstrap](script/bootstrap)
3. `cd` to your project's root directory and paste/run the commands

This will install GEOS and configure the necessary environmental values.

## Development

### Bootstrapping a local development environment

`script/bootstrap`

### Running tests

`script/cibuild`

### Development console

`script/console`

## Troubleshooting GEOS

On some environments, prior to running your application or running `bundle install`, you'll need to run the following commands to properly configure your execution environment for Ruby to find the GEOS library:

```
export GEOS_LIBRARY_PATH=`geos-config --prefix`/lib
bundle config --local build.rgeo --with-geos-dir="$GEOS_LIBRARY_PATH"
````

## License

[MIT](LICENSE.md)

## Contributing

1. Fork the project
2. Create a descriptively named feature branch
3. Make your changes
4. Submit a pull request


text:
//
//  QTRConnectedDevicesViewController.h
//  QuickTransfer
//
//  Created by Harshad on 20/02/14.
//  Copyright (c) 2014 Laughing Buddha Software. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "QTRBonjourTransferDelegate.h"

@interface QTRConnectedDevicesViewController : UIViewController <UINavigationControllerDelegate, UISearchBarDelegate>

/*!
 Initialises the receiver.

 @param transfersController An object confirming to QTRBonjourTransferDelegate protocol. The receiver weakly retains this controller.
 */
- (instancetype)initWithTransfersStore:(id <QTRBonjourTransferDelegate>)transfersStore;

- (void)setImportedFile:(NSURL *)fileURL;

@end


text:
class CPSO2FasterPatcherDlg : public CDialogEx
{
// Construction
public:
	CPSO2FasterPatcherDlg(CWnd* pParent = NULL);	// standard constructor

// Dialog Data
	enum { IDD = IDD_PSO2FASTERPATCHER_DIALOG };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);	// DDX/DDV support

// Implementation
protected:
	HICON m_hIcon;

	// Generated message map functions
	virtual BOOL OnInitDialog();
	afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
	afx_msg void OnPaint();
	afx_msg HCURSOR OnQueryDragIcon();
	DECLARE_MESSAGE_MAP()
public:
	afx_msg void OnBnClickedPatch();
};


text:
<?xml version="1.0" encoding="utf-8"?>
<uax:ListOfNodeState xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:uax="http://opcfoundation.org/UA/2008/02/Types.xsd">
  <uax:NamespaceUris>
    <uax:NamespaceUri>http://cas.eu/UA/CommServer/UnitTests/ReferenceTest</uax:NamespaceUri>
  </uax:NamespaceUris>
  <ReferenceTypeTest xmlns="http://cas.eu/UA/CommServer/UnitTests/ReferenceTest">
    <uax:NodeClass>ReferenceType_32</uax:NodeClass>
    <uax:NodeId>
      <uax:Identifier>ns=1;i=1</uax:Identifier>
    </uax:NodeId>
    <uax:BrowseName>
      <uax:NamespaceIndex>1</uax:NamespaceIndex>
      <uax:Name>ReferenceTypeTest</uax:Name>
    </uax:BrowseName>
    <uax:SuperTypeId>
      <uax:Identifier>i=46</uax:Identifier>
    </uax:SuperTypeId>
    <uax:InverseName>
      <uax:Text>FromSomwhere</uax:Text>
    </uax:InverseName>
  </ReferenceTypeTest>
</uax:ListOfNodeState>


text:
#include <boost/algorithm/string.hpp>
#include <osquery/tables.h>

// see README.api of libdpkg-dev
#define LIBDPKG_VOLATILE_API

extern "C" {
#include <dpkg/dpkg-db.h>

#if LIBDPKG_VERSION < 1017010
// copy pasted from dpkg-db.h
// Prior to libdpkg 1.7.10 these enums are inside struct pkginfo and are not
// visible for other headers
enum pkgwant {
	PKG_WANT_UNKNOWN,
	PKG_WANT_INSTALL,
	PKG_WANT_HOLD,
	PKG_WANT_DEINSTALL,
	PKG_WANT_PURGE,
	/** Not allowed except as special sentinel value in some places. */
	PKG_WANT_SENTINEL,
};

enum pkgeflag {
	PKG_EFLAG_OK		= 0,
	PKG_EFLAG_REINSTREQ	= 1,
};

enum pkgstatus {
	PKG_STAT_NOTINSTALLED,
	PKG_STAT_CONFIGFILES,
	PKG_STAT_HALFINSTALLED,
	PKG_STAT_UNPACKED,
	PKG_STAT_HALFCONFIGURED,
	PKG_STAT_TRIGGERSAWAITED,
	PKG_STAT_TRIGGERSPENDING,
	PKG_STAT_INSTALLED,
};

enum pkgpriority {
	PKG_PRIO_REQUIRED,
	PKG_PRIO_IMPORTANT,
	PKG_PRIO_STANDARD,
	PKG_PRIO_OPTIONAL,
	PKG_PRIO_EXTRA,
	PKG_PRIO_OTHER,
	PKG_PRIO_UNKNOWN,
	PKG_PRIO_UNSET = -1,
};
#endif

#if LIBDPKG_VERSION < 1017023
// libdpkg versions 1.17.23 and newer defines a size_t for fieldinfo which is
// automatically expanded using the FIELD macro found in dpkg/parsedump.h. For
// versions prior we just need the name
#define FIELD(name) name
#endif

#include <dpkg/dpkg.h>
#include <dpkg/pkg-array.h>
#include <dpkg/parsedump.h>
}

namespace osquery {
namespace tables {

/**
* @brief A comparator used to sort the packages array
*/
int pkg_sorter(const void *a, const void *b) {
  const struct pkginfo *pa = *(const struct pkginfo **)a;
  const struct pkginfo *pb = *(const struct pkginfo **)b;
  const char *arch_a = pa->installed.arch->name;
  const char *arch_b = pb->installed.arch->name;
  int res;

  res = strcmp(pa->set->name, pb->set->name);
  if (res) {
    return res;
  }

  if (pa->installed.arch == pb->installed.arch) {
    return 0;
  }

  return strcmp(arch_a, arch_b);
}

/**
* @brief A field extractor to fetch the revision of a package
*
* dpkg tracks the revision as part of version, but we need to
* provde our own fwritefunction for fieldinfos to extract it.
*/
void w_revision(struct varbuf *vb,
                const struct pkginfo *pkg,
                const struct pkgbin *pkgbin,
                enum fwriteflags flags,
                const struct fieldinfo *fip) {
  if (flags & fw_printheader) {
    varbuf_add_str(vb, "Revision: ");
  }
  varbuf_add_str(vb, pkgbin->version.revision);
  if (flags & fw_printheader) {
    varbuf_add_char(vb, '\n');
  }
}

/**
* @brief Initialize dpkg and load packages into memory
*/
void dpkg_setup(struct pkg_array *packages) {
  dpkg_set_progname("osquery");
  push_error_context();

  modstatdb_open(msdbrw_readonly);

  pkg_array_init_from_db(packages);
  pkg_array_sort(packages, pkg_sorter);
}

/**
* @brief Clean up after dpkg operations
*/
void dpkg_teardown(struct pkg_array *packages) {
  pkg_array_destroy(packages);

  pkg_db_reset();
  modstatdb_done();

  pop_error_context(ehflag_normaltidy);
}

const std::map<std::string, std::string> kFieldMappings = {
    {"Package", "name"},
    {"Version", "version"},
    {"Installed-Size", "size"},
    {"Architecture", "arch"},
    {"Source", "source"},
    {"Revision", "revision"}};

/**
* @brief Field names and function references to extract information
*
* These are taken from lib/dpkg/parse.c, with a slight modification to
* add an fwritefunction for Revision. Additional fields can be taken
* as needed.
*/
const struct fieldinfo fieldinfos[] = {
    {FIELD("Package"), f_name, w_name},
    {FIELD("Installed-Size"), f_charfield, w_charfield, PKGIFPOFF(installedsize)},
    {FIELD("Architecture"), f_architecture, w_architecture},
    {FIELD("Source"), f_charfield, w_charfield, PKGIFPOFF(source)},
    {FIELD("Version"), f_version, w_version, PKGIFPOFF(version)},
    {FIELD("Revision"), f_revision, w_revision},
    {NULL}};

void extractDebPackageInfo(const struct pkginfo *pkg, QueryData &results) {
  Row r;
  const struct fieldinfo *fip;
  struct varbuf vb;
  varbuf_init(&vb, 20);

  // Iterate over the desired fieldinfos, calling their fwritefunctions
  // to extract the package's information.
  for (fip = fieldinfos; fip->name; fip++) {
    fip->wcall(&vb, pkg, &pkg->installed, fw_printheader, fip);

    std::string line = vb.string();
    if (!line.empty()) {
      std::size_t separator_position = line.find(':');
      std::string key = line.substr(0, separator_position);
      std::string value = line.substr(separator_position + 1, line.length());
      auto it = kFieldMappings.find(key);
      if (it != kFieldMappings.end()) {
        boost::algorithm::trim(value);
        r[it->second] = value;
      }
    }
    varbuf_reset(&vb);
  }
  varbuf_destroy(&vb);

  results.push_back(r);
}

QueryData genDebs(QueryContext &context) {
  QueryData results;

  struct pkg_array packages;
  dpkg_setup(&packages);
  for (int i = 0; i < packages.n_pkgs; i++) {
    struct pkginfo *pkg = packages.pkgs[i];
	// Casted to int to allow the older enums that were embeded in the packages
	// struct to be compared
	if (static_cast<int>(pkg->status) == static_cast<int>(PKG_STAT_NOTINSTALLED)) {
      continue;
    }

    extractDebPackageInfo(pkg, results);
  }

  dpkg_teardown(&packages);
  return results;
}
}
}


text:
import { stripIndent } from 'common-tags';

export default function(widgetName){
  return stripIndent`
    let { ${widgetName} } = ReactWidgets
    let colors = ['orange', 'red', 'blue', 'purple'];

    class Example extends React.Component {
      render() {
        let { open } = this.state || {};
        let toggleWidget = () => this.setState({ open: !open });

        return (
          <div>
            <button onClick={toggleWidget}>
              {open ? 'close' : 'open'}
            </button>
            <${widgetName}
              open={open}
              data={colors}
              onToggle={()=>{}}
            />
          </div>
        )
      }
    };

    ReactDOM.render(<Example/>, mountNode);
  `
}


text:
---
title: "REST API made easy with Apex, AWS Lambda and AWS API Gateway"
date: "2016-08-24T22:42:44.672Z"
layout: post
path: "/2016/08/25/rest-api-made-easy-with-apex-aws-lambda-and-aws-api-gateway"
categories:
- Development
---
**Update September, 4th:** Adding an example on how to configure CORS for your lambdas.

_Recently, I was asked to rewrite the backend part of the company I'm currently working for with AWS services and Apex, an utility used to facilitate the deployment of [AWS Lambda](https://aws.amazon.com/lambda/) functions. In short terms, AWS Lambda is a FaaS (Functions as a Service): you code simple functions that get input and return output, that's it, nothing else. Similarly, it exists [hook.io](http://hook.io) or [Google Cloud Functions](https://cloud.google.com/functions/). When it comes to [AWS API Gateway](https://aws.amazon.com/api-gateway/), it is a way of mapping your Lambda functions to endpoints, it can do content type matching, security, and stuff you often repeat in your code. So let's dive in!_

An AWS Lambda function can be represented like this:
```js
function(event, context, callback) {}
```

You can use either the context methods `success` and `fail` or the callback method whose first argument is error and second is the response. We can now dive into the Apex world that makes everything Lambda-related easier.

## Apex

Start with downloading and installing APEX CLI from [apex.run](http://apex.run), the website is very useful and well-explained.

1. You get the software
2. You run `apex init` in a new project folder
3. You get a structure like this :
   ```
   project.json
   functions
   ├── bar
   │   ├── function.json
   │   └── index.js
   └── foo
       ├── function.json
       └── index.js
   ```
4. You deploy your functions with `apex deploy`!

And that's it, boom, done, you have functions in the cloud! To use and test them, you just have to call them with `apex invoke <function name>`.

**Bonus for Node.js users**

You can `npm install apex.js`, a [nice package](https://www.npmjs.com/package/apex.js) that let you express your functions using `Promise` and forget about `try { ... } catch { ... }` blocks.

From there :
```js
export default ({ name }, ctx, cb) => {
  try {
    // doing Promise stuff and throwing errors
    cb(null, `Hello ${name}`);
    // or ctx.succeed(`Hello ${name}`)
  } catch(err) {
    cb(err);
    // or ctx.fail(err)
  }
}
```

You get there:
```js
import λ from 'apex.js'

export default λ(({ name }) => {
  // doing Promise stuff and throwing errors
  return `Hello ${name}`
})
```

## API Gateway

### Definitions and deployment

Now let's talk about API Gateway because it's not (yet?) integrated in Apex, so... pretty hard to set up with code you can auto-deploy. But, going deep in Apex issues, you can find some [odd Python script](http://github.com/rotemtom/serverless-ci-example) that let you express swagger definition along with your functions. Let's look at an example:

```js
// function.json
{
  "description": "Say hello to a given name",
  "x-api-gateway": {
    "method": "get",
    "path": "/hello/{name}",
    "parameters":[{
      "name": "name",
      "in": "path",
      "description": "Name of the person we want to say hello",
      "required": true,
      "type": "string"
    }]
  }
}
```

This file is originally used by Apex to configure your lambda function precisely. But you can add more to the definition and that's why we put the swagger definition here, very convenient way of doing things. So you got this **`x-api-gateway` which is a swagger extension AWS is using to add parameters to the API**. Currently the Python script is not really flexible about everything you can do with AWS Swagger extensions. You can check out everything on the AWS docs to extend your Swagger interface.

Now about the main and most complex changes you need to have in your `project.json`:

```js
"x-api-gateway": {
  "base_path": "/api",
  "stage_name":"dev",
  "rest-api-id":"<rest-api-id>",
  "swagger-func-template": {
    "consumes": ["application/json"],
    "produces": ["application/json"],
    "responses": { /* mapping HTTP codes to schemas */ },
    "x-amazon-apigateway-integration": {
      "responses": { /* mapping responses to HTTP codes */ },
      "requestTemplates": { /* See below, this one needs a loooong explanation */ },
      "uri": "arn:aws:apigateway:<region>:lambda:path/2015-03-31/functions/arn:aws:lambda:<region>:<account_id>:function:{{functionName}}/invocations",
      "credentials":"arn:aws:iam::<account_id>:role/APIGatewayLambdaInvokeRole",
      "passthroughBehavior": "when_no_match", /* This thing is important, I spent a lot of time because of it */
      "httpMethod": "{{functionMethod}}",
      "type": "aws"
    },
    "x-amazon-apigateway-auth" : { /* Everything security related */ }
  }
}
```

I've shorten everything but there is a link to a boilerplate at the end of the article that contains a more complete example file. First things first, you need to create a REST API on API Gateway (tip: you can use AWS CLI like this `aws apigateway create-rest-api 'My Awesome API'`), this will gives you an id you need to put on your configuration file.
`swagger-func-template` is kind of global configuration for every function. For more information on how to define responses and stuff, you can check out on [AWS docs](http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions.html#api-gateway-swagger-extensions-integration). Let met explain in a list what's interesting here:

- `uri`: this property needs to be filled with the `arn`(s) Amazon gives you, but no worries, you can fill it by hands. The `{{functionName}}` parameter will be automatically replaced with the function name, leave it like this.
- `credentials`: I didn't search that much for this one, but replace `account_id` and it should work. :)
- `requestTemplates`: This is a mixed format template from [VTL](http://velocity.apache.org/engine/devel/vtl-reference.html) and [JSON Path](http://goessner.net/articles/JsonPath/) used to transform the shape of the input data to transfer it to your lambda. Currently my configuration looks like this:

  ```js
  "application/json": "{\n   \"method\": \"$context.httpMethod\",\n   \"body\" : $input.json('$'),\n   \"headers\": {\n     #foreach($param in $input.params().header.keySet())\n     \"$param\": \"$util.escapeJavaScript($input.params().header.get($param))\" #if($foreach.hasNext),#end\n \n     #end\n   },\n   \"queryParams\": {\n     #foreach($param in $input.params().querystring.keySet())\n     \"$param\": \"$util.escapeJavaScript($input.params().querystring.get($param))\" #if($foreach.hasNext),#end\n \n     #end\n   },\n   \"pathParams\": {\n     #foreach($param in $input.params().path.keySet())\n     \"$param\": \"$util.escapeJavaScript($input.params().path.get($param))\" #if($foreach.hasNext),#end\n \n     #end\n   }\n}"
  ```

  Okay okay, I know this doesn't look good but what if I do this:

  ```vtl
  {
    "method": "$context.httpMethod", // GET, POST, PUT...
    "body" : $input.json('$'), // your payload
    "headers": { // Content-Type and stuff like that
      #foreach($param in $input.params().header.keySet())
        "$param": "$util.escapeJavaScript($input.params().header.get($param))" #if($foreach.hasNext),#end
      #end
    },
    "queryParams": { // for example /sweets?sort=asc will gives you a sort property into queryParams
      #foreach($param in $input.params().querystring.keySet())
        "$param": "$util.escapeJavaScript($input.params().querystring.get($param))" #if($foreach.hasNext),#end
      #end
    },
    "pathParams": { // for example /sweets/{name} will gives you a name property into pathParams
      #foreach($param in $input.params().path.keySet())
        "$param": "$util.escapeJavaScript($input.params().path.get($param))" #if($foreach.hasNext),#end
      #end
    }
  }
  ```

  Better, huh? And we can see that's a kind of enhanced JSON used with $ variables representing input. **What we are doing here is mapping method, body, headers, query parameters and the path parameters into their own property in an object that will be sent to our lambda.** You can even add hardcode properties if you need to. **This structure is really opinionated** : one one hand, it's really convenient because everything is well-separated, but on the other hand, **your lambda needs to know where is the parameters it needs**. _It's your choice to define it like this or putting every properties into the main object._ You could also writing it differently in every `function.json`.
- `passthroughBehavior`: **This one is very important**, it represents the way Amazon will call your lambda using the `requestTemplates`.

  - `when_no_match`: Mapping body with `requestTemplates` and if no content type is matched, content passes through as-is.
  - `when_no_template`: same as `when_no_match` when templates are defined, but if no templates, it passes through as-is.
  - `never`: rejects the method request if the content-type doesn't match anything in mapping template.

  This option made me go crazy during an hour, I had my request mapped only when I was not sending any body (it was set on the `never` option).

Now that everything is settled, you can deploy using the script:
`python api-gateway-deployer/src/__init__.py project.json`

### Apex API Gateway

Python may not be what your co-worker wants to install for a tiny simple script... That's why I **rewrote and enhanced this in Node.js, less code, no Python required** and more flexibility coming if you or other people gets interested.

A simple `npm install -g`[`apex-api-gateway`](https://www.npmjs.com/package/apex-api-gateway) and here you go. _You can also install it locally in your project and call it from an NPM script._

So you might first want to create an API:

`apex-api-gateway create 'My Awesome API'`

This will add a `rest-api-id` field in your `project.json` that can be used later to update your Swagger schema. This way, you don't need to repeat yourself with the AWS CLI. And as we talk about updating, here's how:

`apex-api-gateway update`

Now you can develop and deploy without bothering about AWS user interface, you only need, of course, appropriate security roles.

### Adding CORS

**Warning:** From now on, if you follow this instructions, the configuration won't work with the Python script since `apex-api-gateway` has more advanced features required for this.

I struggled a lot to add CORS to my lambdas, so here's the way to deal with it for anyone annoyed. First, what you need is replying to preflight request, the `OPTIONS` request that many browsers send before the real request to validate the access to a resource. So, let's add what you need in the `project.json`:

```js
{
  /* ... */
  "x-api-gateway": {
    "paths": {
      ".+": {
        "options": {
          "summary": "CORS support",
          "description": "Enable CORS by returning correct headers\n",
          "consumes": ["application/json"],
          "produces": ["application/json"],
          "tags": ["CORS"],
          "x-amazon-apigateway-integration": {
            "type": "mock",
            "requestTemplates": { "application/json": "{\n \"statusCode\" : 200\n}\n" },
            "responses": {
              "default": {
                "statusCode": "200",
                "responseParameters": {
                  "method.response.header.Access-Control-Allow-Headers": "'Content-Type,X-Amz-Date,Authorization,X-Api-Key'",
                  "method.response.header.Access-Control-Allow-Methods": "'GET, PUT, POST, DELETE'",
                  "method.response.header.Access-Control-Allow-Origin": "'*'"
                },
                "responseTemplates": { "application/json": "{}\n" }
              }
            }
          },
          "responses": {
            "200": {
              "description": "Default response for CORS method",
              "headers": {
                "Access-Control-Allow-Headers": { "type": "string" },
                "Access-Control-Allow-Methods": { "type": "string" },
                "Access-Control-Allow-Origin": { "type": "string" }
              }
            }
          }
        }
      }
    },
    /* ... */
  }
  /* ... */
}
```

The `paths` key has been added in the `0.2.0` version of `apex-api-gateway` to set default methods to every resources matched by a regex. You can find more about it on the [`paths` section of the README](https://github.com/yorunohikage/apex-api-gateway#paths). This way, we add an `OPTIONS` request to every resources we want to be available in the browser. The regex is set to match everything, but you could only allow one part of your API, very flexible this way.

Now that we have defined our preflight requests, we have to add the same headers to all the responses we want. And for now, we do it in `swagger-func-template`, the behavior of this key is very similar to `paths` except you don't match paths and methods. In the future, it would likely be merged in `paths` property with a similar behavior for methods.

```js
"swagger-func-template": {
  /* ... */
  "responses": {
    "200": {
      /* ... */
      "headers": {
        "Access-Control-Allow-Headers": { "type": "string" },
        "Access-Control-Allow-Methods": { "type": "string" },
        "Access-Control-Allow-Origin": { "type": "string" }
      }
    },
    /* ... */
  },
  "x-amazon-apigateway-integration": {
    "responses": {
      "default": {
        "statusCode": "200",
        "responseParameters": {
          "method.response.header.Access-Control-Allow-Headers": "'Content-Type,X-Amz-Date,Authorization,X-Api-Key'",
          "method.response.header.Access-Control-Allow-Methods": "'GET, PUT, POST, DELETE'",
          "method.response.header.Access-Control-Allow-Origin": "'*'"
        }
      },
      /* ... */
    },
    /* ... */
  },
  /* ... */
}
```

And that's it, now you still can override per method your configuration if you need to.

## Conclusion

Thanks for reading this, you can check out my **[Apex API Gateway boilerplate on GitHub](https://github.com/YoruNoHikage/apex-api-gateway-boilerplate) (Node.js), it has (almost) everything you need to get you started!** Tell me about the [`apex-api-gateway`](https://www.npmjs.com/package/apex-api-gateway) script and/or don't hesitate to file issues or contribute on the [GitHub repository](https://github.com/YoruNoHikage/apex-api-gateway)

_PS: A friend told me about [ClaudiaJS](https://claudiajs.com/), I never tried it nor saw it before, maybe it is a good alternative for your Lambda functions being written the express.js way._


text:
package org.mh.logcentral.cassandra;

import java.util.logging.Logger;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Host;
import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.Session;

/** Code to connect to the DB, store files, list files and load a file */
public class CassandraDB {

	// TODO: externalize this into the WSO2 AS configuration registry
	String node = "127.0.0.1";

	protected Cluster cluster;
	protected Session session;

	protected static final Logger LOGGER = Logger.getLogger( "CassandraDB" );

	/** open db connection */
	public void connect() {
		cluster = Cluster.builder().addContactPoint( node ).build();
		Metadata metadata = cluster.getMetadata();
		LOGGER.info( "Connected to cluster: "+ metadata.getClusterName() );
		for ( Host host : metadata.getAllHosts() ) {
			LOGGER.info( "Datacenter: "+host.getDatacenter()+"; Host: "+host.getAddress()+"; Rack: "+ host.getRack() );
		}
	}

	/** close db connection */
	public void close() {
		cluster.close();
	}

}


text:
ul.menu li,
ul.menu li a,
ul.links li,
ul.links li a,
.action-links,
#page {
  height: 1%;
}

#block-system-main ul.admin-list li a {
  height: 1px;
  position: relative;
  display: block;
}

#block-system-main ul.admin-list li div.description a {
  display: inline;
}