text:
namespace DeepEqual.Test
{
	using System;

	using Moq;

	using Xbehave;

	using Shouldly;

	public class ComparisonBuilderTests
	{
		protected ComparisonBuilder SUT { get; set; }

		[Scenario]
		public void Creating_a_builder()
		{
			"When creating a builder".x(() =>
				SUT = new ComparisonBuilder()
			);

			"Then there should be no custom comparisons".x(() =>
				SUT.CustomComparisons.ShouldBeEmpty()
			);

			"And UnmatchedPropertiesIgnored should be false".x(() =>
				SUT.ComplexObjectComparison.IgnoreUnmatchedProperties.ShouldBe(false)
			);
		}

		[Scenario]
		public void Adding_a_custom_Comparison()
		{
			var result = default (ComparisonBuilder);
			var custom = default (IComparison);

			"Given a builder".x(() =>
				SUT = new ComparisonBuilder()
			);

			"And a custom comparison".x(() =>
				custom = new Mock<IComparison>().Object
			);

			"When adding the custom comparison".x(() =>
				result = SUT.WithCustomComparison(custom)
			);

			"Then there should be a custom comparison".x(() =>
				SUT.CustomComparisons.Count.ShouldBe(1)
			);

			"And it should be the correct comparison".x(() =>
				SUT.CustomComparisons[0].ShouldBeSameAs(custom)
			);

			"And it should return the builder".x(() =>
				result.ShouldBeSameAs(SUT)
			);
		}

		[Scenario]
		public void Ignoring_unmatched_properties()
		{
			var result = default (ComparisonBuilder);

			"Given a builder".x(() =>
				SUT = new ComparisonBuilder()
			);

			"When ignoring unmatched properties".x(() =>
				result = SUT.IgnoreUnmatchedProperties()
			);

			"Then UnmatchedPropertiesIgnored should be true".x(() =>
				SUT.ComplexObjectComparison.IgnoreUnmatchedProperties.ShouldBe(true)
			);

			"And it should return the builder".x(() =>
				result.ShouldBeSameAs(SUT)
			);
		}

		[Scenario]
		public void Ignoring_specific_properties()
		{
			var result = default (ComparisonBuilder);

			"Given a builder".x(() =>
				SUT = new ComparisonBuilder()
			);

			"When ignoring the Major property of Version".x(() =>
				result = SUT.IgnoreProperty<Version>(x => x.Major)
			);

			"Then it should add an IgnoredProperty".x(() =>
				SUT.ComplexObjectComparison.IgnoredProperties.Count.ShouldBe(1)
			);

			"And it should return true for the Major property of the Version type".x(() =>
				SUT.ComplexObjectComparison.IgnoredProperties[0](new PropertyReader
					{
						DeclaringType = typeof(Version),
						Name = "Major"
					}).ShouldBe(true)
			);

			"And it should return the builder".x(() =>
				result.ShouldBeSameAs(SUT)
			);
		}

		[Scenario]
		public void Ignoring_specific_properties_2()
		{
			var result = default (ComparisonBuilder);

			"Given a builder".x(() =>
				SUT = new ComparisonBuilder()
			);

			"When ignoring the Major property of Version".x(() =>
				result = SUT.IgnoreProperty(x => x.Name == "Major")
			);

			"Then it should add an IgnoredProperty".x(() =>
				SUT.ComplexObjectComparison.IgnoredProperties.Count.ShouldBe(1)
			);

			"And it should return true for the Major property of the Version type".x(() =>
				SUT.ComplexObjectComparison.IgnoredProperties[0](new PropertyReader
					{
						Name = "Major"
					}).ShouldBe(true)
			);

			"And it should return the builder".x(() =>
				result.ShouldBeSameAs(SUT)
			);
		}

		[Scenario]
		public void Skipping_default_comparison_for_types()
		{
			var result = default (ComparisonBuilder);

			"Given a builder".x(() =>
				SUT = new ComparisonBuilder()
			);

			"When skipping the default comparison fer Version".x(() =>
				result = SUT.SkipDefault<Version>()
			);

			"Then SkippedTypes should contain Version".x(() =>
				SUT.DefaultComparison.SkippedTypes.ShouldContain(typeof (Version))
			);

			"And it should return the builder".x(() =>
				result.ShouldBeSameAs(SUT)
			);
		}

		[Scenario]
		public void Setting_floating_point_tolerance()
		{
			var result = default (ComparisonBuilder);

			"Given a builder".x(() =>
				SUT = new ComparisonBuilder()
			);

			"When setting floating point tolerance".x(() =>
				result = SUT.WithFloatingPointTolerance(0.001d, 0.2f)
			);

			"Then the tolerance should be set".x(() =>
			{
				SUT.DoubleTolerance.ShouldBe(0.001d);
				SUT.SingleTolerance.ShouldBe(0.2f);
			});

			"And it should return the builder".x(() =>
				result.ShouldBeSameAs(SUT)
			);
		}

		[Scenario]
		public void Default_floating_point_tolerance()
		{
			"Given a builder".x(() =>
				SUT = new ComparisonBuilder()
			);

			"Then the tolerance should be set".x(() =>
			{
				SUT.DoubleTolerance.ShouldBe(1e-15d);
				SUT.SingleTolerance.ShouldBe(1e-6f);
			});
		}

		[Scenario]
		public void Expoising_internals_of_a_given_type()
		{
			var result = default (ComparisonBuilder);
			var properties = default (PropertyReader[]);

			"Given a builder".x(() =>
				SUT = new ComparisonBuilder()
			);

			"When exposing the internals of Version".x(() =>
			{
				result = SUT.ExposeInternalsOf<Version>();
				properties = ReflectionCache.GetProperties(new Version(1, 2, 3, 4));
			});

			"Then ReflectionCache should contain the private properties of Version".x(() =>
				properties.ShouldContain(x => x.Name == "_Major")
			);

			"And it should return the builder".x(() =>
				result.ShouldBeSameAs(SUT)
			);
		}

		[Scenario]
		public void Expoising_internals_of_many_types()
		{
			var result = default (ComparisonBuilder);
			var versionProperties = default (PropertyReader[]);
			var uriProperties = default (PropertyReader[]);

			"Given a builder".x(() =>
				SUT = new ComparisonBuilder()
			);

			"When exposing the internals of Version".x(() =>
			{
				result = SUT.ExposeInternalsOf(typeof(Version), typeof(Uri));
				versionProperties = ReflectionCache.GetProperties(new Version(1, 2, 3, 4));
				uriProperties = ReflectionCache.GetProperties(new Uri("http://google.com"));
			});

			"Then ReflectionCache should contain the private properties of Version".x(() =>
				versionProperties.ShouldContain(x => x.Name == "_Major")
			);

			"And ReflectionCache should contain the private properties of Uri".x(() =>
				uriProperties.ShouldContain(x => x.Name == "_syntax")
			);

			"And it should return the builder".x(() =>
				result.ShouldBeSameAs(SUT)
			);
		}

		[Scenario]
		public void Creating_a_default_Comparison()
		{
			var result = default (CompositeComparison);

			"Given a builder".x(() =>
				SUT = new ComparisonBuilder()
			);

			"When calling Create".x(() =>
				result = SUT.Create()
			);

			"Then it not return null".x(() =>
				result.ShouldNotBe(null)
			);

			"And the 1st comparer is the DefaultComparison".x(() =>
				result.Comparisons[0].ShouldBeAssignableTo<FloatComparison>()
			);

			"And the 2nd comparer is the EnumComparison".x(() =>
				result.Comparisons[1].ShouldBeAssignableTo<EnumComparison>()
			);

			"And the 3rd comparer is the DefaultComparison".x(() =>
				result.Comparisons[2].ShouldBeAssignableTo<DefaultComparison>()
			);

			"And the 4th comparer is the DictionaryComparison".x(() =>
				result.Comparisons[3].ShouldBeAssignableTo<DictionaryComparison>()
			);

			"... with a DefaultComparison as the key comparer".x(() =>
				((DictionaryComparison)result.Comparisons[3]).KeyComparer.ShouldBeAssignableTo<DefaultComparison>()
			);

			"... and the value comparer is the result".x(() =>
				((DictionaryComparison)result.Comparisons[3]).ValueComparer.ShouldBeSameAs(result)
			);

			"And the 5th comparer is the DictionaryComparison".x(() =>
				result.Comparisons[4].ShouldBeAssignableTo<SetComparison>()
			);

			"... and the inner comparer is the result".x(() =>
				((SetComparison)result.Comparisons[4]).Inner.ShouldBeSameAs(result)
			);

			"And the 6th comparer is the DictionaryComparison".x(() =>
				result.Comparisons[5].ShouldBeAssignableTo<ListComparison>()
			);

			"... and the inner comparer is the result".x(() =>
				((ListComparison)result.Comparisons[5]).Inner.ShouldBeSameAs(result)
			);

			"And the 7th comparer is the ComplexObjectComparison".x(() =>
				result.Comparisons[6].ShouldBeAssignableTo<ComplexObjectComparison>()
			);

			"... and the inner comparer is the result".x(() =>
				((ComplexObjectComparison)result.Comparisons[6]).Inner.ShouldBeSameAs(result)
			);

			"... and IgnoreUnmatchedProperties should be false".x(() =>
				((ComplexObjectComparison)result.Comparisons[6]).IgnoreUnmatchedProperties.ShouldBe(false)
			);
		}

		[Scenario]
		public void Creating_a_Comparison_with_custom_comparisons()
		{
			var result = default (CompositeComparison);
			var custom = default (IComparison);

			"Given a builder".x(() =>
				SUT = new ComparisonBuilder()
			);

			"And a custom comparison".x(() =>
			{
				custom = new Mock<IComparison>().Object;

				SUT.WithCustomComparison(custom);
			});

			"When calling Create".x(() =>
				result = SUT.Create()
			);

			"Then the 1st comparer is the custom comparison".x(() =>
				result.Comparisons[0].ShouldBeSameAs(custom)
			);
		}

		[Scenario]
		public void Creating_a_Comparison_and_ignoring_unmatched_properties()
		{
			var result = default (CompositeComparison);

			"Given a builder".x(() =>
				SUT = new ComparisonBuilder()
			);

			"And we call IgnoreUnmatchedProperties".x(() =>
				SUT.IgnoreUnmatchedProperties()
			);

			"When calling Create".x(() =>
				result = SUT.Create()
			);

			"Then the 6th comparer is the ComplexObjectComparison".x(() =>
				result.Comparisons[6].ShouldBeAssignableTo<ComplexObjectComparison>()
			);

			"... and IgnoreUnmatchedProperties should be true".x(() =>
				((ComplexObjectComparison)result.Comparisons[6]).IgnoreUnmatchedProperties.ShouldBe(true)
			);
		}
	}
}


text:
\documentclass[11pt,a4paper,landscape]{article}
\usepackage{titling,graphicx,palatino,amsmath,enumerate,booktabs,listings,color}
\usepackage[none]{hyphenat}
\usepackage[parfill]{parskip}
\usepackage{pgfplots}
\usepackage[top=2 cm, bottom= 2 cm, left=1 cm, right=1 cm]{geometry}
\usepackage{enumitem}
\begin{document}

\section*{Sprint reflection Plan 1}
Context : Multimedia services\\
Group : Multimedia services 1\\

\begin{table}[h]
\begin{tabular}{|p{5cm}|p{1.0cm}|p{2.5cm}|p{1.8cm}|p{1.8cm}|p{1.0cm}|p{12cm}}
\textbf{User Story} & \textbf{Task} & \textbf{Task assigned to} & \textbf{Estimated Effort per Task (Hours)} & \textbf{Actual Effort per Task (Hours)} & \textbf{Done} & \textbf{Notes}\\
As a User, I want to be able to log into MoodCat.me & \begin{enumerate}[leftmargin=0.3cm,itemindent=0.1cm]
\item
\item
\item
\item
\end{enumerate}

&
\begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] Gijs
\item[] Gijs
\item[] Jan-Willem
\item[] Jaap
\end{enumerate}

&
\begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] 4
\item[] 6
\item[] 4
\item[] 6
\end{enumerate}
&
\begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] 4
\item[] 6
\item[] 2
\item[] 8
\end{enumerate}
&
\begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] Yes
\item[] Yes
\item[] Yes
\item[] Yes
\end{enumerate}
&
\begin{enumerate}[leftmargin=0.3cm,itemindent=0.1cm]
\item[]
\item[]
\item[]
\item[]
\end{enumerate}
 \\

As a User, I want to be able to play music on MoodCat.me & \begin{enumerate}[leftmargin=0.3cm,itemindent=0.1cm]
\item
\item
\item
\end{enumerate}

&
\begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] Eva
\item[] Gijs
\item[] Jaap
\end{enumerate}

&
\begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] 2
\item[] 13
\item[] 8
\end{enumerate}
 & \begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] 1
\item[] 12
\item[] 6
\end{enumerate}

 & \begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] Yes
\item[] Yes
\item[] Yes
\end{enumerate}

 & \begin{enumerate}[leftmargin=0.5cm,itemindent=0.1cm]
\item Jan-Willem took over this issue.
\item
\item Gijs took over this issue.
\end{enumerate}

\\

As a Developer, I want to be able to run Algorithms on a server-side platform & \begin{enumerate}[leftmargin=0.3cm,itemindent=0.1cm]
\item
\item
\item
\end{enumerate}

&
\begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] Eva
\item[] Tim
\item[] Eva
\end{enumerate}

&
\begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] 3
\item[] 3
\item[] 10
\end{enumerate}

&
\begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] 3
\item[] 4
\item[]
\end{enumerate}

&
\begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] Yes
\item[] Yes
\item[] No
\end{enumerate}

&
\begin{enumerate}[leftmargin=0.5cm,itemindent=0.1cm]
\item Was a team effort with Eva as lead.
\item Originally we chose for Jersey, but then we decided to use RESTeasy.
The interface java.ws.rs is the same, but the implementation is different and easier to configure.
We also decided to use Jackson, Hibernate and Guice, which we also had to install.
\item Has been delayed till sprint 2 due to running out of time.
\end{enumerate}
\\
As a Developer, I want to be able to store and use the data provided by Soundcloud. & \begin{enumerate}[leftmargin=0.3cm,itemindent=0.1cm]
\item
\item
\end{enumerate}

&
\begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] Eva
\item[] Jan-Willem
\end{enumerate}

&
\begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] 3
\item[] 6
\end{enumerate}

& \begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] 10
\item[] 2
\end{enumerate}

& \begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] Yes
\item[] Yes
\end{enumerate}

& \begin{enumerate}[leftmargin=0.5cm,itemindent=0.1cm]
\item Ended up being a lot bigger than expected as features didn't match one-on-one.
\item Eva took over this issue.
\end{enumerate}

 \\

As a Developer, I want to have a well defined interface for any data mining algorithms we will use & \begin{enumerate}[leftmargin=0.3cm,itemindent=0.1cm]
\item
\item
\end{enumerate}

&
\begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] Tim
\item[] Tim
\end{enumerate}

&
\begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] 8
\item[] 6
\end{enumerate}

&
\begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] 8
\item[]
\end{enumerate}

&
\begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] Yes
\item[] No
\end{enumerate}

& \begin{enumerate}[leftmargin=0.5cm,itemindent=0.1cm]
\item Dependency on the core pom.xml was taking a lot of the issue time. Had to come with new solutions.
\item Has been delayed till sprint 2.
\end{enumerate}

\\

As a Developer, I want to decide how we can match users and their moods to rooms and songs. & \begin{enumerate}[leftmargin=0.3cm,itemindent=0.1cm]
\item
\item
\item
\end{enumerate}

&
\begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] Everyone
\item[] Eva
\item[] Jan-Willem
\end{enumerate}

&
\begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] 15
\item[] 5
\item[] 10
\end{enumerate}
& \begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] 15
\item[]
\item[]
\end{enumerate}
& \begin{enumerate}[leftmargin=0.1cm,itemindent=0.1cm]
\item[] Yes
\item[] No
\item[] No
\end{enumerate}
&
\begin{enumerate}[leftmargin=0.5cm,itemindent=0.1cm]
\item Had a 2-hour meeting on friday with everyone and then Eva continued with most of the work.
\item Delayed to sprint 2.
\item Delayed to unknown sprint. Appeared to be not necessary to finish this early.
\end{enumerate}
 \\

\end{tabular}
\end{table}

Other tasked submitted this sprint:\\
We made the product vision document. Tim and Jan-Willem made the document and Eva added the part about the Music Matching algorithm.
In total there has been put around 15 hours on it. \\
We also made a beginning on the requirements document, Eva lead this and in total we spent about 4 hours on this.\\

\end{document}

redpajama_set_name: RedPajamaGithub


text:
package wikipod.vpm.fr.wikipodcasts.search;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import java.util.ArrayList;
import java.util.regex.Pattern;

import fr.vpm.wikipod.location.Localisation;
import fr.vpm.wikipod.location.LocalisationListener;
import fr.vpm.wikipod.wiki.Article;
import fr.vpm.wikipod.wiki.ArticleListener;
import fr.vpm.wikipod.wiki.GeoArticles;
import fr.vpm.wikipod.wiki.http.GeoWiki;
import wikipod.vpm.fr.wikipodcasts.R;
import wikipod.vpm.fr.wikipodcasts.util.ProgressBarListener;

/**
 * Created by vince on 05/12/14.
 */
public class ArticleSearcher implements LocalisationListener, ArticleListener {

  public static final int DEFAULT_RADIUS = 5000; // the radius to search around, in meters

  private final Context context;

  private final ArticleListener articleListener;

  private final ProgressBarListener progressListener;

  public ArticleSearcher(Context context, ArticleListener articleListener, ProgressBarListener progressListener) {
    this.context = context;
    this.articleListener = articleListener;
    this.progressListener = progressListener;
  }

  @Override
  public void onLocalisationChanged(Localisation localisation) {
    searchAroundLocation(localisation);
  }

  public void searchAroundLocation(Localisation location) {
    progressListener.startRefreshProgress();
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
    String source = sharedPrefs.getString("pref_wiki_source", context.getString(R.string.pref_wiki_source_default));
    GeoArticles geoWiki = new GeoWiki(source);
    String radius = sharedPrefs.getString("pref_wiki_search_radius", "5000");
    if (!Pattern.compile("\\d+").matcher(radius).matches()){
      radius = "5000";
    }
    geoWiki.searchArticles(location, Integer.valueOf(radius), this);
  }

  @Override
  public void onArticlesFound(ArrayList<Article> articles) {
    progressListener.stopRefreshProgress();
    if (articles == null){
      articles = new ArrayList<>();
    }
    articleListener.onArticlesFound(articles);
  }
}


text:
package interpreter.expression.display;

import interpreter.expression.DisplayExpression;

/**
 * Sets the color of the pen to that represented by the index
 * Returns given index
 * @author Abhishek B
 *
 */
public class SetPenColor extends DisplayExpression {

}


text:
package eu.timepit.crjdt.circe

import eu.timepit.crjdt.core.Replica
import eu.timepit.crjdt.core.syntax._
import eu.timepit.crjdt.circe.testUtil.{converged, diverged, merge}
import eu.timepit.crjdt.circe.syntax._
import io.circe.Json
import org.scalacheck.Prop._
import org.scalacheck.Properties

object NodeToJsonFigure1Spec extends Properties("NodeToJsonFigure1Spec") {
  val p0 = Replica.empty("p").applyCmd(doc.downField("key") := "A")
  val q0 = merge(Replica.empty("q"), p0)

  property("initial state") = secure {
    converged(p0, q0)
  }

  val p1 = p0.applyCmd(doc.downField("key") := "B")
  val q1 = q0.applyCmd(doc.downField("key") := "C")

  property("divergence") = secure {
    diverged(p1, q1)
  }

  val p2 = merge(p1, q1)
  val q2 = merge(q1, p1)

  property("convergence") = secure {
    converged(p2, q2)
  }

  property("toJson with last-writer-wins conflict resolution") = secure {
    implicit val resolver = RegNodeConflictResolver.LWW
    p2.document.toJson ?= Json.obj(
      "key" -> Json.fromString("C")
    )
  }

  property("toJson with preserve-all-as-array conflict resolution") = secure {
    implicit val resolver = RegNodeConflictResolver.PreserveAllAsArray
    p2.document.toJson ?= Json.obj(
      "key" -> Json.arr(List("B", "C").map(Json.fromString): _*)
    )
  }
}


text:
package com.task.coordinator.base.message.listener;

public interface TcsMessageListenerContainer {

    /*
     * Stars a message listener container will provider concurrent consumers count
     * */
    public void start(int concurrentConsumers);

    public void stop();

    public void destroy();

    public TcsMessageListener getMessageListener();

}


text:
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Photo Commment

        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>


text:
from qtpy.QtWidgets import QVBoxLayout, QLabel, QDialog, QDialogButtonBox, QGridLayout
from qtpy.QtGui import QDoubleValidator, QRegExpValidator
from qtpy.QtCore import QRegExp

from .useful_widgets import LineEditReadOnly, set_tooltip, LineEditExtended

import logging

logger = logging.getLogger(__name__)

class DialogPileupPeakParameters(QDialog):
    def __init__(self, parent=None):

        super().__init__(parent)

        self._data = {"element1": "", "element2": "", "energy": 0}
        # Reference to function that computes pileup energy based on two emission lines
        self._compute_energy = None

        self.setWindowTitle("Pileup Peak Parameters")

        self.le_element1 = LineEditExtended()
        set_tooltip(self.le_element1, "The name of the emission line #1")
        self.le_element2 = LineEditExtended()
        set_tooltip(self.le_element2, "The name of the emission line #2")
        self.peak_energy = LineEditReadOnly()
        set_tooltip(
            self.peak_energy,
            "The energy (location) of the pileup peak center. The energy can not"
            "be edited: it is set based on the selected emission lines",
        )

        self._validator_eline = QRegExpValidator()
        # TODO: the following regex is too broad: [a-z] should be narrowed down
        self._validator_eline.setRegExp(QRegExp(r"^[A-Z][a-z]?_[KLM][a-z]\d$"))

        instructions = QLabel("Specify two emission lines, e.g. Si_Ka1 and Fe_Ka1")

        grid = QGridLayout()
        grid.addWidget(QLabel("Emission line 1:"), 0, 0)
        grid.addWidget(self.le_element1, 0, 1)
        grid.addWidget(QLabel("Emission line 2:"), 1, 0)
        grid.addWidget(self.le_element2, 1, 1)
        grid.addWidget(QLabel("Peak energy, keV:"), 2, 0)
        grid.addWidget(self.peak_energy, 2, 1)

        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.button(QDialogButtonBox.Cancel).setDefault(True)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        self.pb_ok = button_box.button(QDialogButtonBox.Ok)

        vbox = QVBoxLayout()
        vbox.addWidget(instructions)
        vbox.addSpacing(10)
        vbox.addLayout(grid)
        vbox.addWidget(button_box)

        self.setLayout(vbox)

        self.le_element1.editingFinished.connect(self.le_element1_editing_finished)
        self.le_element2.editingFinished.connect(self.le_element2_editing_finished)

        self.le_element1.textChanged.connect(self.le_element1_text_changed)
        self.le_element2.textChanged.connect(self.le_element2_text_changed)

    def set_compute_energy_function(self, func):
        self._compute_energy = func

    def set_parameters(self, data):
        self._data = data.copy()
        self._show_data()

    def get_parameters(self):
        return self._data

    def _format_float(self, v):
        return f"{v:.12g}"

    def _show_data(self):
        self.le_element1.setText(self._data["element1"])
        self.le_element2.setText(self._data["element2"])
        self._show_energy()

    def _show_energy(self, energy=None):
        if energy is None:
            energy = self._data["energy"]
        text = self._format_float(energy)
        self.peak_energy.setText(text)
        self._validate_all()

    def _validate_le_element1(self, text=None):
        return self._validate_eline(self.le_element1, text)

    def _validate_le_element2(self, text=None):
        return self._validate_eline(self.le_element2, text)

    def _validate_peak_energy(self, energy=None):
        # Peak energy is not edited, so it is always has a valid floating point number
        #   The only problem is that it may be out of range.
        if energy is None:
            energy = self._data["energy"]
        valid = self._data["range_low"] < energy < self._data["range_high"]
        self.peak_energy.setValid(valid)
        return valid

    def _validate_all(self):
        valid = self._validate_le_element1() and self._validate_le_element2()
        # Energy doesn't influence the success of validation, but the Ok button
        #   should be disabled if energy if out of range.
        valid_energy = self._validate_peak_energy()
        self.pb_ok.setEnabled(valid and valid_energy)
        return valid

    def _validate_eline(self, le_widget, text):
        if text is None:
            text = le_widget.text()

        valid = True
        if self._validator_eline.validate(text, 0)[0] != QDoubleValidator.Acceptable:
            valid = False
        else:
            # Try to compute energy for the pileup peak
            if self._compute_energy(text, text) == 0:
                valid = False
        le_widget.setValid(valid)
        return valid

    def _refresh_energy(self):
        eline1 = self._data["element1"]
        eline2 = self._data["element2"]
        try:
            energy = self._compute_energy(eline1, eline2)
            self._data["energy"] = energy
            self._show_energy()
        except Exception:
            self._data["energy"] = 0
            self._show_energy()

    def le_element1_editing_finished(self):
        if self._validate_le_element1():
            self._data["element1"] = self.le_element1.text()
            self._refresh_energy()
        else:
            self.le_element1.setText(self._data["element1"])
        self._validate_all()

    def le_element2_editing_finished(self):
        if self._validate_le_element2():
            self._data["element2"] = self.le_element2.text()
            self._refresh_energy()
        else:
            self.le_element2.setText(self._data["element2"])
        self._validate_all()

    def le_element1_text_changed(self, text):
        if self._validate_all():
            self._data["element1"] = self.le_element1.text()
            print(f"element1 - {self._data['element1']}")
            self._refresh_energy()

    def le_element2_text_changed(self, text):
        if self._validate_all():
            self._data["element2"] = self.le_element2.text()
            print(f"element2 - {self._data['element2']}")
            self._refresh_energy()


text:
package com.github.gilbertotorrezan.gwtviews.rebind;

import java.io.PrintWriter;
import java.util.Date;

import com.github.gilbertotorrezan.gwtviews.client.AutoPresenter;
import com.github.gilbertotorrezan.gwtviews.client.CachePolicy;
import com.github.gilbertotorrezan.gwtviews.client.CachedPresenter;
import com.github.gilbertotorrezan.gwtviews.client.Presenter;
import com.github.gilbertotorrezan.gwtviews.client.View;
import com.github.gilbertotorrezan.gwtviews.client.ViewContainer;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.TreeLogger.Type;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.JMethod;
import com.google.gwt.core.ext.typeinfo.JParameterizedType;
import com.google.gwt.core.ext.typeinfo.JType;
import com.google.gwt.core.ext.typeinfo.NotFoundException;
import com.google.gwt.core.ext.typeinfo.TypeOracle;
import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
import com.google.gwt.user.rebind.SourceWriter;

/**
 * Class used by the code generator to create the default {@link Presenter}s of Views and ViewContainers.
 *
 * @author Gilberto Torrezan Filho
 *
 * @since v.1.0.0
 * @see AutoPresenter
 */
public class PresenterGenerator extends Generator {

	@Override
	public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException {

		final TypeOracle typeOracle = context.getTypeOracle();
		JClassType mainType = typeOracle.findType(typeName);

		JParameterizedType parameterized = mainType.getImplementedInterfaces()[0].isParameterized();
		JClassType viewType = parameterized.getTypeArgs()[0];
		final String className = viewType.getQualifiedSourceName();

		String name = mainType.getName().substring(mainType.getName().lastIndexOf('.')+1);
		name = name.substring(0, name.length() - "Presenter".length());
		name = name + "_" + name + "PresenterImpl";

		PrintWriter writer = context.tryCreate(logger, viewType.getPackage().getName(), name);
		if (writer == null){
			return viewType.getPackage().getName() + "." + name;
		}

		ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(viewType.getPackage().getName(), name);
		factory.addImplementedInterface(AutoPresenter.class.getName());

		factory.addImport(Presenter.class.getPackage().getName()+".*");
		factory.addImport("com.google.gwt.user.client.History");
		factory.addImport("com.google.gwt.core.client.GWT");
		factory.addImport("com.google.gwt.user.client.ui.Widget");
		factory.addImport("javax.annotation.Generated");
		factory.addImport("java.util.*");

		factory.addAnnotationDeclaration("@Generated("
				+ "value=\""+PresenterGenerator.class.getName()+"\", "
				+ "date=\""+new Date()+"\", "
				+ "comments=\"Generated by GWT-Views project.\")");

		View view = viewType.getAnnotation(View.class);
		ViewContainer viewContainer = viewType.getAnnotation(ViewContainer.class);

		CachePolicy cache;
		JClassType injectorType = null;
		String injectorMethod = null;
		if (view == null){
			cache = CachePolicy.ALWAYS;
		}
		else {
			cache = view.cache();
		}

		if (cache == CachePolicy.SAME_URL){
			factory.setSuperclass(CachedPresenter.class.getName());
		}

		SourceWriter sourceWriter = factory.createSourceWriter(context, writer);

		sourceWriter.println("//AUTO GENERATED FILE BY GWT-VIEWS AT " + getClass().getName() + ". DO NOT EDIT!\n");

		if (cache == CachePolicy.ALWAYS){
			sourceWriter.println("private Widget view; //the cached view");
		}

		Class<?> injector = view == null ? void.class : view.injector();
		if (injector.equals(void.class)){
			injector = viewContainer == null ? void.class : viewContainer.injector();
		}

		if (!injector.equals(void.class)){
			try {
				injectorType = typeOracle.findType(injector.getName());
				injectorMethod = view != null ? view.injectorMethod() : viewContainer.injectorMethod();
				injectorMethod = getInjectorMethod(logger, injectorType, injectorMethod, className);
			}
			catch (Exception e) {
				logger.log(Type.ERROR, "Error loading the injector class \"" + injector.getName() + "\": " + e, e);
				throw new UnableToCompleteException();
			}
		}

		if (cache == CachePolicy.SAME_URL){
			sourceWriter.println("\n@Override\npublic Widget createNewView(URLToken url) {");
		}
		else {
			sourceWriter.println("\n@Override\npublic Widget getView(URLToken url) {");
		}
		sourceWriter.indent();

		switch (cache) {
		case NEVER: {
			sourceWriter.println("//code for the CachePolicy.NEVER:");
			printInjectorMethod(sourceWriter, className, injectorType, injectorMethod);
		}
		break;
		case ALWAYS: {
			sourceWriter.println("//code for the CachePolicy.ALWAYS:");
			sourceWriter.println("if (this.view == null) {");
			sourceWriter.indent();
			printInjectorMethod(sourceWriter, className, injectorType, injectorMethod);
			sourceWriter.println("this.view = view;");
			sourceWriter.outdent();
			sourceWriter.println("}");
		}
		break;
		case SAME_URL: {
			sourceWriter.println("//code for the CachePolicy.SAME_URL:");
			printInjectorMethod(sourceWriter, className, injectorType, injectorMethod);
		}
		break;
		}

		sourceWriter.println("return view;");
		sourceWriter.outdent();
		sourceWriter.println("}\n");

		sourceWriter.outdent();
		sourceWriter.println("}\n");

		context.commit(logger, writer);

		return factory.getCreatedClassName();
	}

	private String getInjectorMethod(TreeLogger logger, JClassType injector, String injectorMethod, String className) throws UnableToCompleteException {
		if (injectorMethod != null && !injectorMethod.isEmpty()){
			try {
				injector.getMethod(injectorMethod, new JType[0]);
			}
			catch (NotFoundException e) {
				logger.log(Type.WARN, "The injector method \"" + injectorMethod + "\" was not found on class " + injector.getQualifiedSourceName());
				//a compiler error will be trigged if the method really doesn't exist
			}
			return injectorMethod;
		}
		else {
			String methodName = null;
			JMethod[] methods = injector.getInheritableMethods();
			for (JMethod method : methods) {
				JType returnType = method.getReturnType();
				if (returnType.getQualifiedSourceName().equals(className)){
					if (methodName != null){
						logger.log(Type.ERROR, "The injector " + injector.getName() + " has more than one method with " + className
								+ " as return type. Use the \"injectorMethod\" property to specify which one should be used.");
						throw new UnableToCompleteException();
					}
					methodName = method.getName();
				}
			}
			if (methodName == null){
				logger.log(Type.INFO, "The injector " + injector.getName() + " has no methods with " + className
								+ " as return type. The View will not be injected.");
				return null;
			}
			return methodName;
		}
	}

	private void printInjectorMethod(SourceWriter sourceWriter, String className, JClassType injectorType, String injectorMethod){
		if (injectorType != null && injectorMethod != null){
			sourceWriter.println(injectorType.getQualifiedSourceName() + " injector = NavigationManager.getInjectorInstance(" + injectorType.getQualifiedSourceName() + ".class);");
			sourceWriter.println("if (injector == null) injector = GWT.create(" + injectorType.getQualifiedSourceName() + ".class);");
			sourceWriter.println("Widget view = (" + className + ") injector." + injectorMethod + "();");
		}
		else {
			sourceWriter.println("Widget view = GWT.create( " + className + ".class);");
		}
	}

}


text:
<!DOCTYPE HTML>

foo

bar

baz


text:
<?php

return [
    '{attribute} cannot be blank.' => '{attribute} δεν μπορεί να είναι κενό.',
    'The verification code is incorrect.' => 'Ο κωδικός επαλήθευσης είναι λάθος.',
    'Home' => 'Αρχική',
    'You are not allowed to perform this action.' => 'Δεν επιτρέπεται να εκτελέσετε την συγκεκριμένη ενέργεια.',
];


text:
package mj.ocraptor.extraction.tika.parser.chm.accessor;

import mj.ocraptor.extraction.tika.parser.chm.assertion.ChmAssert;
import mj.ocraptor.extraction.tika.parser.chm.core.ChmCommons;

import org.apache.tika.exception.TikaException;

/**
 * The format of a directory listing entry is as follows: BYTE: length of name
 * BYTEs: name (UTF-8 encoded) ENCINT: content section ENCINT: offset ENCINT:
 * length The offset is from the beginning of the content section the file is
 * in, after the section has been decompressed (if appropriate). The length also
 * refers to length of the file in the section after decompression. There are
 * two kinds of file represented in the directory: user data and format related
 * files. The files which are format-related have names which begin with '::',
 * the user data files have names which begin with "/".
 *
 */
public class DirectoryListingEntry {
    /* Length of the entry name */
    private int name_length;
    /* Entry name or directory name */
    private String name;
    /* Entry type */
    private ChmCommons.EntryType entryType;
    /* Entry offset */
    private int offset;
    /* Entry size */
    private int length;

    public DirectoryListingEntry() {

    }

    /**
     * Constructs directoryListingEntry
     *
     * @param name_length
     *            int
     * @param name
     *            String
     * @param isCompressed
     *            ChmCommons.EntryType
     * @param offset
     *            int
     * @param length
     *            int
     * @throws TikaException
     */
    public DirectoryListingEntry(int name_length, String name,
            ChmCommons.EntryType isCompressed, int offset, int length) throws TikaException {
        ChmAssert.assertDirectoryListingEntry(name_length, name, isCompressed, offset, length);
        setNameLength(name_length);
        setName(name);
        setEntryType(isCompressed);
        setOffset(offset);
        setLength(length);
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("name_length:=" + getNameLength() + System.getProperty("line.separator"));
        sb.append("name:=" + getName() + System.getProperty("line.separator"));
        sb.append("entryType:=" + getEntryType() + System.getProperty("line.separator"));
        sb.append("offset:=" + getOffset() + System.getProperty("line.separator"));
        sb.append("length:=" + getLength());
        return sb.toString();
    }

    /**
     * Returns an entry name length
     *
     * @return int
     */
    public int getNameLength() {
        return name_length;
    }

    /**
     * Sets an entry name length
     *
     * @param name_length
     *            int
     */
    protected void setNameLength(int name_length) {
        this.name_length = name_length;
    }

    /**
     * Returns an entry name
     *
     * @return String
     */
    public String getName() {
        return name;
    }

    /**
     * Sets entry name
     *
     * @param name
     *            String
     */
    protected void setName(String name) {
        this.name = name;
    }

    /**
     * Returns ChmCommons.EntryType (COMPRESSED or UNCOMPRESSED)
     *
     * @return ChmCommons.EntryType
     */
    public ChmCommons.EntryType getEntryType() {
        return entryType;
    }

    protected void setEntryType(ChmCommons.EntryType entryType) {
        this.entryType = entryType;
    }

    public int getOffset() {
        return offset;
    }

    protected void setOffset(int offset) {
        this.offset = offset;
    }

    public int getLength() {
        return length;
    }

    protected void setLength(int length) {
        this.length = length;
    }

    public static void main(String[] args) {
    }
}


text:
package com.albedinsky.android.officium.sync;

import android.accounts.Account;
import android.content.ContentProviderClient;
import android.content.SyncResult;
import android.os.Bundle;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.google.gson.Gson;

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

/**
 * Task that can be used to request synchronization via implementation of {@link BaseSyncManager}.
 * Each instance of SyncTask may be identified by its id that can be obtained via {@link #getId()}.
 *

 * Creation of instances of {@link SyncTask SyncTasks} is restricted via {@link SyncTask.Builder} only.
 *

 * If synchronization related to a particular SyncTask depends on some additional data that are needed
 * to perform synchronization logic, these data can be specified via {@link SyncTask.Builder#request(Request)}.
 * The synchronization request object should be a simple POJO object that can be processed by {@link Gson}
 * into its {@link String} representation and also from it. The request object will be processed into
 * Json data whenever instance of SyncTask is requested to put its data into extras {@link Bundle}
 * via {@link #intoExtras(Bundle)} and instantiated from that Json data whenever {@link #getRequest(Class)}
 * is called and the request instance has not been parsed yet.
 *

 * Inheritance instance should override both {@link #SyncTask(Builder)} and {@link #SyncTask(Bundle)}
 * constructors along with {@link #intoExtras(Bundle)} method to perform custom instantiation logic
 * via custom implementation of {@link SyncTask.Builder} or from/into extras {@link Bundle}.
 *
 * @param <R> Type of the request specific for the SyncTask implementation.
 * @author Martin Albedinsky
 */
public class SyncTask<R extends SyncTask.Request> implements Cloneable {

	/**
	 * Interface ===================================================================================
	 */

	/**
	 * Required interface for all synchronization requests.
	 *
	 * @author Martin Albedinsky
	 */
	public interface Request {
	}

	/**
	 * A {@link Request} implementation that can be used for {@link SyncHandler SyncHandlers} that
	 * do not require any synchronization request.
	 *
	 * @author Martin Albedinsky
	 */
	public static final class EmptyRequest implements Request {

		/* We do not allow to create instances of this request. */
		private EmptyRequest() {
		}
	}

	/**
	 * Constants ===================================================================================
	 */

	/**
	 * Log TAG.
	 */
	// private static final String TAG = "SyncTask";

	/**
	 * Defines an annotation for determining set of available states for {@link SyncTask}.
	 *
Available states

	 *

	 *
{@link #IDLE}

	 *
{@link #PENDING}

	 *
{@link #RUNNING}

	 *
{@link #FINISHED}

	 *
{@link #FAILED}

	 *
{@link #CANCELED}

	 *

	 *
	 * @see #getState()
	 */
	@IntDef({
			IDLE,
			PENDING,
			RUNNING,
			FINISHED,
			FAILED,
			CANCELED
	})
	@Retention(RetentionPolicy.SOURCE)
	public @interface State {
	}

	/**
	 * Initial state for each new {@link SyncTask}.
	 */
	public static final int IDLE = 0x00;

	/**
	 * State indicating that {@link SyncTask} is in pending state waiting to be executed.
	 *

	 * Task becomes pending when {@link BaseSyncManager#requestSync(SyncTask)} has been called with
	 * that particular task.
	 */
	public static final int PENDING = 0x01;

	/**
	 * State indicating that {@link SyncTask} is currently being executed.
	 *

	 * Task becomes running when {@link BaseSyncAdapter#onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}
	 * has been called with extras containing that particular task.
	 */
	public static final int RUNNING = 0x02;

	/**
	 * State indicating that {@link SyncTask} has been already executed without any error.
	 *

	 * Task becomes finished when {@link BaseSyncAdapter#onSyncFinished(SyncOperation)} has been
	 * called with sync operation containing that particular task.
	 */
	public static final int FINISHED = 0x03;

	/**
	 * State indicating that {@link SyncTask} has been already executed but an error occurred during
	 * its execution.
	 *

	 * Task becomes finished when {@link BaseSyncAdapter#onSyncFailed(SyncOperation, Exception)} has
	 * been called with sync operation containing that particular task.
	 */
	public static final int FAILED = 0x04;

	/**
	 * State indicating that {@link SyncTask} has been canceled.
	 *

	 * Task becomes canceled when {@link BaseSyncManager#cancelSync()} has been called.
	 */
	public static final int CANCELED = 0x05;

	/**
	 * Default id for synchronization task. This id may be used to identify global synchronization task.
	 */
	public static final int DEFAULT_ID = 0;

	/**
	 * Empty instance of {@link SyncTask} that may be used to pass a sync task to a sync handler that
	 * does not require any data from a caller to perform its synchronization.
	 */
	@SuppressWarnings("unused")
	public static SyncTask<EmptyRequest> EMPTY = new SyncTask<>();

	/**
	 * Static members ==============================================================================
	 */

	/**
	 * Instance of Gson used to parse {@link #mRequestBody} into {@link #mRequest} instance and
	 * vice versa.
	 */
	private static final Gson GSON = new Gson();

	/**
	 * Members =====================================================================================
	 */

	/**
	 * Id specified for this task.
	 */
	private final int mId;

	/**
	 * Request specified for this task. May be {@code null}.
	 */
	private R mRequest;

	/**
	 * Json data of request obtained from {@link Bundle} when this task is created from synchronization
	 * extras via {@link #SyncTask(Bundle)}. This string is used when parsing instance of Request
	 * specific for this
	 *
	 * @see #getRequest(Class)
	 */
	private final String mRequestBody;

	/**
	 * Current state of this synchronization task. May be one of states defined by {@link State @State}
	 * annotation.
	 */
	private int mState = IDLE;

	/**
	 * Constructors ================================================================================
	 */

	/**
	 * Creates an empty instance of SyncTask.
	 */
	private SyncTask() {
		this.mId = -1;
		this.mRequestBody = null;
	}

	/**
	 * Creates a new instance of SyncTask with data of the given one.
	 *
	 * @param other The other sync task of which data to copy to the new one.
	 */
	private SyncTask(SyncTask other) {
		this.mId = other.mId;
		this.mRequestBody = other.mRequestBody;
		this.mState = other.mState;
	}

	/**
	 * Creates a new instance of SyncTask with data specified within the given <var>builder</var>.
	 *
	 * @param builder The builder containing data for the new SyncTask instance.
	 */
	protected SyncTask(@NonNull Builder<R> builder) {
		this.mId = builder.id;
		this.mRequest = builder.request;
		this.mRequestBody = mRequest != null ? GSON.toJson(mRequest) : null;
	}

	/**
	 * Creates a new instance of SyncTask with data specified within the given <var>extras</var>
	 * Bundle.
	 *

	 * Note, that proper instantiation of SyncTask from the given <var>extras</var> Bundle
	 * may be performed only if data for the new SyncTask instance has been previously stored within
	 * the given bundle via {@link #intoExtras(Bundle)} method.
	 *
	 * @param extras The synchronization extras Bundle containing data for the new SyncTask instance.
	 * @see #intoExtras(Bundle)
	 */
	protected SyncTask(@NonNull Bundle extras) {
		this.mId = extras.getInt(SyncExtras.EXTRA_TASK_ID, DEFAULT_ID);
		this.mRequestBody = extras.getString(SyncExtras.EXTRA_TASK_REQUEST_BODY);
		this.mState = extras.getInt(SyncExtras.EXTRA_TASK_STATE, mState);
	}

	/**
	 * Methods =====================================================================================
	 */

	/**
	 * Returns the id of this task.
	 *
	 * @return Id specified for this task.
	 */
	public final int getId() {
		return mId;
	}

	/**
	 * Changes the current state of this task to the specified one.
	 *
	 * @param state The new state for this task. Should be one of states defined by {@link State @State}
	 *              annotation.
	 * @see #getState()
	 */
	final void setState(@State int state) {
		this.mState = state;
	}

	/**
	 * Returns the current state of this task.
	 *
	 * @return This task's state. May be one of states defined by {@link State @State} annotation.
	 */
	@State
	public final int getState() {
		return mState;
	}

	/**
	 * Returns the request specified for this task. If request is {@code null} but there is request
	 * body available after this sync task has been created from the extras {@link Bundle} the desired
	 * request will be parsed from its body using {@link Gson}.
	 *
	 * @param classOfRequest Class used to parse the desired request if it is not parsed yet and there
	 *                       is request body available.
	 * @return This task's request or {@code null} if there is no request specified.
	 */
	@Nullable
	public final R getRequest(@NonNull Class<R> classOfRequest) {
		if (mRequest == null) {
			this.mRequest = !TextUtils.isEmpty(mRequestBody) ? GSON.fromJson(mRequestBody, classOfRequest) : null;
		}
		return mRequest;
	}

	/**
	 * Returns a body of the request specified for this task.
	 *
	 * @return This task's request body in Json format or {@code null} if there is not request specified.
	 */
	@Nullable
	public final String getRequestBody() {
		return mRequestBody;
	}

	/**
	 * Puts all data of this task into the given <var>extras</var> Bundle. Instance of this SyncTask
	 * may be than instantiated from the specified extras via {@link #SyncTask(Bundle)} constructor.
	 *
	 * @param extras The synchronization extras Bundle into which to put data of this task.
	 * @return The given extras Bundle with this task's data.
	 */
	@NonNull
	public Bundle intoExtras(@NonNull Bundle extras) {
		extras.putInt(SyncExtras.EXTRA_TASK_ID, mId);
		extras.putString(SyncExtras.EXTRA_TASK_REQUEST_BODY, mRequestBody);
		extras.putInt(SyncExtras.EXTRA_TASK_STATE, mState);
		return extras;
	}

	/**
	 */
	@Override
	public int hashCode() {
		int hash = mId;
		if (!TextUtils.isEmpty(mRequestBody)) {
			hash = 31 * hash + mRequestBody.hashCode();
		}
		return hash;
	}

	/**
	 */
	@Override
	public boolean equals(Object other) {
		if (other == this) return true;
		if (!(other instanceof SyncTask)) return false;
		final SyncTask task = (SyncTask) other;
		if (task.mId != mId) {
			return false;
		}
		final int requestHash = mRequestBody != null ? mRequestBody.hashCode() : 0;
		final int otherRequestHash = task.mRequestBody != null ? task.mRequestBody.hashCode() : 0;
		return requestHash == otherRequestHash;
	}

	/**
	 */
	@Override
	@SuppressWarnings("StringBufferReplaceableByString")
	public String toString() {
		final StringBuilder builder = new StringBuilder(64);
		builder.append(getClass().getSimpleName());
		builder.append("{id: ");
		builder.append(mId);
		builder.append(", request: ");
		builder.append(mRequest != null ? mRequest : mRequestBody);
		builder.append(", state: ");
		builder.append(stateName(mState));
		return builder.append("}").toString();
	}

	/**
	 * Returns name of the specified <var>state</var>.
	 *
	 * @param state The desired state of which name to return.
	 * @return The state's name.
	 */
	private static String stateName(int state) {
		switch (state) {
			case IDLE:
				return "IDLE";
			case PENDING:
				return "PENDING";
			case RUNNING:
				return "RUNNING";
			case FINISHED:
				return "FINISHED";
			case FAILED:
				return "FAILED";
			default:
				return "UNKNOWN";
		}
	}

	/**
	 * Makes a clone of this task with the same id and request body but with the initial state, which
	 * is {@link #IDLE}.
	 */
	@Override
	@SuppressWarnings({"CloneDoesntDeclareCloneNotSupportedException", "CloneDoesntCallSuperClone"})
	protected SyncTask clone() {
		final SyncTask clone = new SyncTask(this);
		clone.mState = IDLE;
		return clone;
	}

	/**
	 * Inner classes ===============================================================================
	 */

	/**
	 * Builder that can be used to create a new instance of {@link SyncTask}.
	 *
	 * @author Martin Albedinsky
	 */
	public static class Builder<R extends SyncTask.Request> {

		/**
		 * See {@link SyncTask#mId}.
		 */
		private final int id;

		/**
		 * See {@link SyncTask#mRequest}.
		 */
		private R request;

		/**
		 * Creates a new instance of Builder for the specified synchronization <var>taskId</var>.
		 *
		 * @param taskId Id of the synchronization task to build.
		 */
		public Builder(int taskId) {
			this.id = taskId;
		}

		/**
		 * Specifies a request for the synchronization task to build.
		 *
		 * @param request The desired request. This should be a simple POJO object that can be processed
		 *                by {@link Gson}. May be {@code null} if request is not necessary for the
		 *                sync task.
		 * @return This builder to allow methods chaining.
		 */
		public Builder request(@Nullable R request) {
			this.request = request;
			return this;
		}

		/**
		 * Builds a new instance of SyncTask.
		 *
		 * @return New instance of SyncTask with data specified for this builder.
		 */
		@NonNull
		public SyncTask<R> build() {
			return new SyncTask<>(this);
		}
	}
}


text:
(function() {
	'use strict'

	const messages = {}

	// domain messages
	messages.domainAlreadyExist = function(name) {
		return 'Company "{VALUE}" already exists.'.replace(/{VALUE}/, '' + name)
	}

	// category messages
	messages.categoryAlreadyExist = function(name) {
		return 'Category "{VALUE}" already exists.'.replace(/{VALUE}/, '' + name)
	}

	// account messages
	messages.accountAlreadyExist = function(name) {
		return 'Account "{VALUE}" already exists.'.replace(/{VALUE}/, '' + name)
	}

	module.exports = exports = messages
})()


text:
<?php

namespace app\models\glabs\categories;

use app\commands\GlabsController;
use app\models\glabs\objects\ObjectException;
use app\models\glabs\objects\Backpage as Object;
use app\models\glabs\sites\BaseSite;
use PHPHtmlParser\Dom;
use PHPHtmlParser\Exceptions\CurlException;

class Backpage extends BaseCategory
{
    /**
     * @inheritdoc
     */
    public function __construct($url, $title, $categoryId, $type, $count)
    {
        self::$pageParam = '&page=';
        $url = array_map(function ($item) { return $item . '?layout=summary'; }, $url);
        parent::__construct($url, $title, $categoryId, $type, $count);
    }

    /**
     * @inheritdoc
     */
    protected function collectObjects($url)
    {
        if (!array_key_exists($url, $this->collectedCount)) {
            $this->collectedCount[$url] = 0;
        }
        $dom = new Dom();
        try {
            $dom->loadFromUrl($url, [], GlabsController::$curl);
        } catch (CurlException $e) {
            if (false === strpos($e->getMessage(), 'timed out') ) {
                throw new CurlException($e->getMessage());
            }
            if (false === strpos($e->getMessage(), '525') ) {
                throw new CurlException($e->getMessage());
            }
            GlabsController::showMessage(' ...trying again', false);
            return $this->collectObjects($url);
        }

        // end collect. no results
        if (false !== strpos($dom, 'No matches found.')) {
            return true;
        }

        $this->checkTotalObjects($dom);

        /* @var \PHPHtmlParser\Dom\AbstractNode $span */
        foreach ($dom->find('.summaryHeader') as $span) {
            if ($this->isEnoughCollect()) {
                break;
            }

            /* @var \PHPHtmlParser\Dom\AbstractNode $link */
            if ($link = $span->find('a', 0)) {
                $href = $link->getAttribute('href');
                if (in_array($href, $this->collected, true)) {
                    continue;
                }
                $object = new Object($url, $href, $link->text(), $this->categoryId, $this->type);
                try {
                    $object->setPrice();
                } catch (ObjectException $e) {
                    continue;
                }

                $this->collected[] = $href;
                $this->objects[] = $object;
                $this->collectedCount[$url]++;
                BaseSite::$doneObjects++;
                BaseSite::progress();
            }
        }

        if (!$this->isEnoughCollect()) {
            $curl = GlabsController::$curl;
            $curl::$referer = $url;
            $url = str_replace(self::$pageParam . self::$page, '', $url);
            self::$page += self::$page ? 1 : 2;
            return $this->collectObjects($this->getPagedUrl($url));
        }

        return true;
    }

    /**
     * @inheritdoc
     */
    protected function checkTotalObjects($dom)
    {
        if (!$this->count) {
            $this->count = $this->needCount = 2500;
        }

        return true;
    }
}


text:
#ifndef IS_LUAGI_CHERRYPICK
#define IS_LUAGI_CHERRYPICK
#include "lua.h"

int luagi_cherrypick_commit( lua_State *L );
int luagi_cherrypick( lua_State *L );

#endif


text:
package edu.hastings.hastingscollege.tabfragments;

import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.MenuItem;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;

import edu.hastings.hastingscollege.R;
import edu.hastings.hastingscollege.adapter.TabsPagerAdapter;
import edu.hastings.hastingscollege.googleanalytics.MyApplication;

public class SodexoMenu extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.sodexo_menu);
        ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);

        final String KEY_DAY = "dayname";
        Intent in = getIntent();
        String day = in.getStringExtra(KEY_DAY);

        ActionBar actionBar = getActionBar();
        actionBar.setTitle("Sodexo Menu for " + day);
        actionBar.setDisplayHomeAsUpEnabled(true);
        mViewPager.setAdapter(new TabsPagerAdapter(this.getSupportFragmentManager(), day));

        Tracker t = ((MyApplication) getApplication()).getTracker(MyApplication.TrackerName.APP_TRACKER);
        t.setScreenName("Menu");
        t.send(new HitBuilders.AppViewBuilder().build());
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        finish();
        return true;
    }
}


text:
# JSONP Go http middleware

**NOTE: this package has moved to https://github.com/goware/jsonp**

JSONP is a common technique used to communicate with a JSON-serving Web Service with a
Web browser over cross-domains, in place of a XHR request. There is a lot written about
JSONP out there, but the tl;dr on it is a Javascript http client requesting JSONP
will write a `<script>` tag to the head of a page, with the `src` to an API endpoint,
with the addition of a `callback` (or `jsonp`) query parameter that represents a
randomly-named listener function that will parse the request when it comes back from
the server.

This middleware will work with anything that supports standard `http.Handler`. The code
is small, so go read it, but it just buffers the response from the rest of the chain,
and if its a JSON request with a callback, then it will wrap the response in the callback
function before writing it to the actual response writer.

Any feedback is welcome and appreciated!

Written by [@pkieltyka](https://github.com/pkieltyka)

## Example

```go
// JSONP example using Goji framework.. but anything that accepts
// a http.Handler middleware chain will work
package main

import (
  "log"
  "net/http"

  "github.com/pressly/gohttpware/jsonp"
  "github.com/unrolled/render"
  "github.com/zenazn/goji/web"
  "github.com/zenazn/goji/web/middleware"
)

func main() {
  mux := web.New()
  render := render.New(render.Options{})

  mux.Use(middleware.Logger)
  mux.Use(jsonp.Handle)

  mux.Get("/", func(w http.ResponseWriter, r *http.Request) {
    data := &SomeObj{"superman"}
    render.JSON(w, 200, data)
  })

  err := http.ListenAndServe(":4444", mux)
  if err != nil {
    log.Fatal(err)
  }
}

type SomeObj struct {
  Name string `json:"name"`
}

```

*Output:*
```
curl -v "http://localhost:4444/"
> GET / HTTP/1.1
> User-Agent: curl/7.37.1
> Host: localhost:4444
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json; charset=UTF-8
< Date: Sat, 08 Nov 2014 16:05:04 GMT
< Content-Length: 19
<
* Connection #0 to host localhost left intact
{"name":"superman"}
```

```
curl -v "http://localhost:4444/?callback=X"
> GET /?callback=X HTTP/1.1
> User-Agent: curl/7.37.1
> Host: localhost:4444
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Length: 22
< Content-Type: application/javascript
< Date: Sat, 08 Nov 2014 16:05:23 GMT
<
* Connection #0 to host localhost left intact
X({"name":"superman"})
```

## Future ideas

Since JSONP must always respond with a 200, since thats what the browser `<script>`
tag expects, a nice pattern that is also used in the GitHub API is to put the HTTP
response headers in a `"meta"` hash, and the HTTP response body in `"data"`. Like so..

```json
JsonpCallbackFn_abc123etc({
  "meta": {
    "Status": 200,
    "Content-Type": "application/json",
    "Content-Length": "19",
    "etc": "etc"
  },
  "data": { "name": "yummy" }
})
```

.. this can easily be done in some middleware that take the response headers and modifies
the response body by doing some basic concatenation (no point in JSON decoding /
encoding again). I will write this one day.


text:
Upstream
=========
[![Version     ](https://img.shields.io/gem/v/nondestructive_migrations.svg?style=flat)](https://rubygems.org/gems/nondestructive_migrations)
[![Code Climate](https://codeclimate.com/github/jasonfb/nondestructive_migrations/badges/gpa.svg)](https://codeclimate.com/github/jasonfb/nondestructive_migrations)
[![Travis CI](https://travis-ci.org/jasonfb/nondestructive_migrations.svg?branch=master)](https://travis-ci.org/jasonfb/nondestructive_migrations)

Handshake
==========

[![Circle CI](https://circleci.com/gh/strydercorp/nondestructive_migrations.svg?style=svg)](https://circleci.com/gh/strydercorp/nondestructive_migrations)

## About this Fork

This is a fork off of the original repo at https://github.com/jasonfb/nondestructive_migrations

Added to this version are:

1) Add ```disable_ddl_transaction!``` to the template data migration

2) Add a rake task to mark all data migrations as complete, useful for dev environments where the database is dropped from time to time.

3) Logic for announcing to slack when migrations are run, with details.

4) Protections and structure for operating on data carefully.

### print_progress

Call this in your code (loops, likely) to print progress indicator to consle every 500 calls.

## Introduction

Nondestructive migrations, also known as data migrations, are a alternative kind of Rails migration. The data migrations operate exactly like schema migrations, except instead of running migrations to make changes to your schema (adding fields, dropping fields, adding tables, etc), you run data migrations to manipulate data in your app, enqueue or execute Resque jobs that require long-running processes. This happens in a Rails app for different reasons, usually to clean up or supplement data or architectural changes.

Splitting your data migrations from your schema migrations has a particular benefit of achieving the most consistent zero-downtime deploys you can. I recommend you switch your deployment script to allow you to do two types of deploys: a Zero-downtime deploy (no schema migrations) and Schema Migration deploy.

This way, you can deploy any non-destructive (data-only) migration with a Zero-downtime strategy, and opt to make destructive (schema) migrations in a normal deployment (maintenance on, run schema changes, boot up new app,  maintenance off).  Data-only migrations can be run while the app is actually running, augmenting what you can achieve with the migration-style shortcuts provided by Rails.

A word of caution: If you find yourself making a lot of data migrations, you might consider if your product/development/business process is too reliant on one-off data importing. It may be that data management tools will help you in the long run. Nonetheless, separating your schema migrations from your data migrations can be a great strategy for modern Rails development.

Data migrations functional EXACTLY like schema migrations except:

1) They live in db/data_migrate instead of db/migrate

2) They timestamps used to record which ones have been run are in a table called data_migrations instead of the normal schema_migrations table

3) You run them using rake data:migrate instead of rake db:migrate

## Installation
To add to your Rails project, follow these steps.

1) Add this to your gemfile.
```ruby
gem 'nondestructive_migrations'
```

2) Run `bundle install

3) Run the setup script:
```
rails generate data_migrations:install
```
This will create a *schema* migration that will create the data_migrations table itself. (There will be a table in your database called data_migrations which will have two columns: id, version. It works exactly like the schema_migrations table.) Now execute that schema migration (and, in turn, be sure to run this on Production):

```
rake db:migrate
```

You are now set up and ready to start making data migrations. To create your first migration, create it with a generating using a camal-case description of what your data migration does.

```
rails generate data_migration UpdatePhoneNumbers
```

Look for a file called (something like) `db/data_migrate/20140831020834_update_phone_numbers.rb`. It will have been automatically written with an empty up and down method. Add whatever operations you want to do in your **up** method, like large data manipulation jobs, running rake tasks, or enqueuing batch process jobs.

You probably want to put `ActiveRecord::IrreversibleMigration` into the **down** method your data migration:

```
class UpdatePhoneNumbers < ActiveRecord::Migration
  def up
    # do stuff here
  end

  def down
    raise ActiveRecord::IrreversibleMigration
  end
end
```

To actually tell your app to run the data migration, use:

```
rake data:migrate
```

You get three additional rake tasks that operate and have the same syntax as the schema migrations, but operate only on the data migrations.

## rake data:migrate
Migrate all data migrations that haven't been migrated.

## rake data:migrate:down VERSION=xxxxxxxxxxx
Migrate down the specified version

## rake data:migrate:up VERSION=xxxxxxxxxxx
Migrate up the specified versions.

## rake data:rollback
Rollback the last version. Generally data migrations don't have any "down" associated with them so use this only under extreme circumstances.

#

As [![sgringwe](https://github.com/sgringwe)](https://github.com/sgringwe) pointed out to me, by default your data migration will run in a single transaction (just like a schema migration).

To turn this off, add `disable_ddl_transaction!` to the top of your migration, like so:

```
class UpdatePhoneNumbers < ActiveRecord::Migration
  disable_ddl_transaction!
  def up
    # do stuff here
  end

  def down
    raise ActiveRecord::IrreversibleMigration
  end
end
```

# Two Kinds of Deployment
You can read more about doing the preboot feature on Heroku at https://devcenter.heroku.com/articles/preboot (Preboot is no longer an "experimental" feature on Heroku.)

## Schema-Change Deploys

1. Switch OFF preboot feature
2. Deploy to Heroku
3. Enable maintenance-mode
4. Run schema migrations  (app reboots)
5. Disable maintenance mode
6. Run the data migrations
7. Switch preboot feature back ON

## Zero-Downtime deploys (no schema migrations)

(assume preboot is already on)
1. Deploy to heroku with preboot on
2. Heroku switches the incoming requests to use the new app
3. Run data migrations (while new app is up & running)

Basically what you want to do is keep Heroku Preboot ON on your app at all times, except when you want to do a schama-change migration. (see https://devcenter.heroku.com/articles/preboot)

The following example assumes your app is named "yourapp-production" and you have a git origin name for heroku (this is what gets configured in .git/config) of "h-prod" that points to your Heroku Git URL for that app.

~/.bash_profile

alias dd-prod="heroku features:disable preboot -a yourapp-production && git checkout master && git pull && git push h-prod master:master && heroku maintenance:on -a yourapp-production && heroku run rake db:migrate -a yourapp-production && heroku maintenance:off -a yourapp-production && heroku run rake data:migrate -a yourapp-production && heroku features:enable preboot -a yourapp-production"

alias ndd-prod="git checkout master && git pull && git push h-prod master:master && heroku run rake data:migrate -a yourapp-production"

Here you can add these as shell scripts (I use bash). dd-prod is my short hand for "destructive deploy to prod." This is what I use when I want to do a schema change migration. Notice that it first disables preboot, expecting it to be on on your Heroku deploy. ndd-prod means "nondestructive deploy to production". Notice that it assumes preboot is already enabled on your Heroku instance and only runs the data migrations. It does not run the schema migrations.

Alternatively, if you don't like the switching preboot off & on part of that, you can deploy a schema-migration code on Heorku and watch the deploy yourself manually. Immediately upon seeing the "Launching..." step, quickly flip your app into maintenance mode with `heroku maintenance:on`

While maintenance is on, run your schema migrations. Restart your app and wait approximately 1-2 minutes, then turn maintenance off. That should avoid the problem of having two apps running at the same time while you're migrating.

## Example App

You can find the app I use to test against here: https://github.com/jasonfb/example-for-nondestructive-migrations

Note the Gemfile has gem pointed with git parameter (directly to this repo). In yours you can omit git parameters to pull the latest release from rubygems. (This repo's master is working development, so it's probably best to use the last released Gem build).

All that is really interesting in that app you will find in db/migrate (the schema migration to create the data migrations table), and db/data_migrate (where those data migrations live).

## Housekeeping
You can run the specs on this gem against Rails 4.1.6 by running
```
rake test TESTOPTS="-v"
```

Or you can run the specs against Rails 4.0.10, and 4.1.6 by using Appraisal (build-in).

```
appraisal rake test
```

Appraisal runs the specs against different versions of Rails. For more information, see https://github.com/thoughtbot/appraisal

You can check out CodeClimate & Travis reports at the top of this README


text:
package org.apache.camel.builder.component.dsl;

import javax.annotation.Generated;
import org.apache.camel.Component;
import org.apache.camel.builder.component.AbstractComponentBuilder;
import org.apache.camel.builder.component.ComponentBuilder;
import org.apache.camel.component.jmx.JMXComponent;

/**
 * Receive JMX notifications.
 *
 * Generated by camel-package-maven-plugin - do not edit this file!
 */
@Generated("org.apache.camel.maven.packaging.ComponentDslMojo")
public interface JmxComponentBuilderFactory {

    /**
     * JMX (camel-jmx)
     * Receive JMX notifications.
     *
     * Category: monitoring
     * Since: 2.6
     * Maven coordinates: org.apache.camel:camel-jmx
     */
    static JmxComponentBuilder jmx() {
        return new JmxComponentBuilderImpl();
    }

    /**
     * Builder for the JMX component.
     */
    interface JmxComponentBuilder extends ComponentBuilder<JMXComponent> {
        /**
         * Allows for bridging the consumer to the Camel routing Error Handler,
         * which mean any exceptions occurred while the consumer is trying to
         * pickup incoming messages, or the likes, will now be processed as a
         * message and handled by the routing Error Handler. By default the
         * consumer will use the org.apache.camel.spi.ExceptionHandler to deal
         * with exceptions, that will be logged at WARN or ERROR level and
         * ignored.
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: consumer
         */
        default JmxComponentBuilder bridgeErrorHandler(
                boolean bridgeErrorHandler) {
            doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
            return this;
        }
        /**
         * Whether the component should use basic property binding (Camel 2.x)
         * or the newer property binding with additional capabilities.
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: advanced
         */
        @Deprecated
        default JmxComponentBuilder basicPropertyBinding(
                boolean basicPropertyBinding) {
            doSetProperty("basicPropertyBinding", basicPropertyBinding);
            return this;
        }
    }

    class JmxComponentBuilderImpl
            extends
                AbstractComponentBuilder<JMXComponent>
            implements
                JmxComponentBuilder {
        @Override
        protected JMXComponent buildConcreteComponent() {
            return new JMXComponent();
        }
        @Override
        protected boolean setPropertyOnComponent(
                Component component,
                String name,
                Object value) {
            switch (name) {
            case "bridgeErrorHandler": ((JMXComponent) component).setBridgeErrorHandler((boolean) value); return true;
            case "basicPropertyBinding": ((JMXComponent) component).setBasicPropertyBinding((boolean) value); return true;
            default: return false;
            }
        }
    }
}


text:
require 'spec_helper'

describe Acinus::API do

  subject do
    # Class.new(Acinus::API)
    Acinus::API
  end

  def app
    subject
  end

  before :each do
    # ...
  end
  it "speak latin..." do
    get '/'
    last_response.status.should be 200
    last_response.body.should eql "Nondum matura est, nolo acerbam sumere..."
  end
  it 'GET /news' do
    get '/news/'
    last_response.status.should be 200
  end
  it 'GET /entries' do
    get '/entries/'
    last_response.status.should be 200
  end

end # describe Acinus::API


text:
class CreateEvents < ActiveRecord::Migration
  def change
    create_table :events do |t|
      t.string :street_address
      t.string :selected_restaurant_name
      t.string :selected_restaurant_address
      t.string :selected_restaurant_phone_number

      t.integer :planner_id

      t.timestamps null: false
    end
  end
end


text:
@implementation MHTTPServ {
    NSString            *_ipAddr, *_fileName;
    int64_t             _fileSize;
    BOOL                _isNetworkRunning;
    char                _dirPath[MDIR_MAX_PATH];
    FILE                *_fp;
}

+ (instancetype)sharedIns {
    static MHTTPServ *serv;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        serv = [[MHTTPServ alloc] init];
    });
    return serv;
}

- (id)init {
    self = [super init];
    return self;
}

- (NSString*)ipAddr {
    if (_isNetworkRunning) {
        return _ipAddr;
    }
    return nil;
}

- (void)setDelegate:(id<MHTTPServDelegate>)delegate {
    if (delegate && [delegate respondsToSelector:@selector(onMHTTPServEvent:fileName:fileSize:percent:)]) {
        _delegate = delegate;
    }
    else {
        _delegate = nil;
    }
}

// from 'http://zachwaugh.me/posts/programmatically-retrieving-ip-address-of-iphone/'
- (NSString *)getIPAddress
{
    NSString *address = nil;
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;

    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while (temp_addr != NULL) {
            if( temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }

            temp_addr = temp_addr->ifa_next;
        }
    }

    // Free memory
    freeifaddrs(interfaces);

    return address;
}

static void _http_serv_cb(client_http_serv_state_t *st) {
    [[MHTTPServ sharedIns] httpServCB:st];
}

- (void)runningNetwork {
    if (_isNetworkRunning) {
        mnet_check(0);
        [self performSelector:@selector(runningNetwork) withObject:nil afterDelay:0.01];
    }
}

- (BOOL)startServ:(NSString *)dirPath onPort:(NSInteger)port {

    if (dirPath.length<=0 || port<=1024) {
        if (_delegate) {
            [_delegate onMHTTPServEvent:@"param error" fileName:nil fileSize:0 percent:0];
        }
        return NO;
    }

    _ipAddr = [self getIPAddress];
    if (_ipAddr == nil) {
        if (_delegate && [_delegate respondsToSelector:@selector(onMHTTPServEvent:fileName:fileSize:percent:)]) {
            [_delegate onMHTTPServEvent:@"fail to get ip addr" fileName:nil fileSize:0 percent:0];
        }
        return NO;
    }

    // int network
    debug_open("stdout");
    if (mnet_init() <= 0) {
        if (_delegate) {
            [_delegate onMHTTPServEvent:@"fail to init network" fileName:nil fileSize:0 percent:0];
        }
        return NO;
    }

    // set serv config
    client_http_serv_config_t conf;
    memset(&conf, 0, sizeof(conf));

    conf.port = (int)port;
    conf.opaque = NULL;

    if (_pageTitle.length>0 && _pageTitle.length<32) {
        [_pageTitle getCString:conf.title maxLength:32 encoding:NSUTF8StringEncoding];
    } else {
        strcpy(conf.title, "Welcome to MHttpServ");
    }

    if (_pageDevName.length>0 && _pageDevName.length<32) {
        [_pageDevName getCString:conf.dev_name maxLength:32 encoding:NSUTF8StringEncoding];
    }
    else {
        strcpy(conf.dev_name, "Nobody's iOS Device");
    }

    [_ipAddr getCString:conf.ipaddr maxLength:sizeof(conf.ipaddr) encoding:NSUTF8StringEncoding];
    [dirPath getCString:conf.dpath maxLength:MDIR_MAX_PATH encoding:NSUTF8StringEncoding];
    memcpy(_dirPath, conf.dpath, MDIR_MAX_PATH);

    if (client_http_serv_open(&conf, _http_serv_cb)) {
        _isNetworkRunning = YES;
        [self runningNetwork];
        return YES;
    }

    return NO;
}

- (void)stopServ {
    _isNetworkRunning = NO;
    client_http_serv_close();
    mnet_fini();
    debug_close();
}

- (void)httpServCB:(client_http_serv_state_t*)st {
    if (st->method == HTTP_METHOD_GET) {
        return;
    }

    NSString *errMsg = nil;

    if (st->state == HTTP_CB_STATE_BEGIN) {
        char fname[MDIR_MAX_PATH] = {0};
        char path[MDIR_MAX_PATH] = {0};

        strncpy(fname, st->fname, st->fname_len);
        sprintf(path, "%s/%s", _dirPath, fname);

        _fileName = [NSString stringWithUTF8String:fname];
        _fileSize = st->total_length;

        _fp = fopen(path, "wb");
        if (_delegate) {
            if (_fp == NULL) {
                errMsg = @"fail to create file" ;
            }
            [_delegate onMHTTPServEvent:errMsg fileName:_fileName fileSize:_fileSize percent:0];
        }
    }
    else if (st->state == HTTP_CB_STATE_CONTINUE) {
        if (_fp) {
            int ret = (int)fwrite(st->buf, 1, st->buf_len, _fp);
            NSLog(@"HTTP POST: Write data length %d of %d", ret, st->buf_len);

            if (ret < 0) {
                fclose(_fp);
                _fp = NULL;
                errMsg = @"http serv fail to write";
            }

            if (_delegate) {
                float percent = (float)st->bytes_consumed / (float)st->total_length;
                [_delegate onMHTTPServEvent:errMsg fileName:_fileName fileSize:_fileSize percent:percent];
            }
        }
    }
    else if (st->state == HTTP_CB_STATE_END) {
        if (_fp) {
            fclose(_fp);
            _fp = NULL;
            NSLog(@"HTTP POST: Data stream end, clsoe file");

            if(_delegate) {
                [_delegate onMHTTPServEvent:nil fileName:_fileName fileSize:_fileSize percent:1.];
            }
        }
    }
    else if (st->state == HTTP_CB_STATE_ERROR) {
        if (_fp) {
            fclose(_fp);
            _fp = NULL;
            NSLog(@"HTTP POST: Data abort uploading");

            if (_delegate) {
                float percent = (float)st->bytes_consumed / (float)st->total_length;
                [_delegate onMHTTPServEvent:@"http server error" fileName:_fileName fileSize:_fileSize percent:percent];
            }
        }
    }
}

/// return false to stop in block
- (void)enumerateDir:(NSString *)dirPath block:(BOOL (^)(NSString *, BOOL, int64_t))block {
    if (dirPath.length>0 && block) {
        char path[MDIR_MAX_PATH] = {0};
        [dirPath getCString:path maxLength:MDIR_MAX_PATH encoding:NSUTF8StringEncoding];

        mdir_t *m = mdir_open(path);
        if (m) {
            lst_t* lst = mdir_list(m, 1024);
            if (lst) {
                lst_foreach(it, lst) {
                    mdir_entry_t *e = lst_iter_data(it);
                    NSString *fileName = [[NSString alloc] initWithBytes:e->name length:e->namlen encoding:NSUTF8StringEncoding];
                    if (block(fileName, (e->ftype & MDIR_DIRECOTRY), e->fsize) == NO) {
                        break;
                    }
                }
            }
        }
        mdir_close(m);
    }
}

@end