text:
var commonManager = new function () {
    var _this = this;

    this.setUpDataTable = function (selector, url, columns, defaultOrder, fillExtraData, pageLength, onDraw) {

        if (!pageLength)
            pageLength = 100;
        var main_table_data = $(selector).DataTable({
            "dom": '<"top"lfip<"clear">>t<"bottom"ip<"clear">>',
            //"sDom":'lipft',
            "order": defaultOrder,
            "scrollY": 500,
            "scrollX": true,
            "processing": true, // for show progress bar
            "serverSide": true, // for process server side
            "filter": true, // this is for disable filter (search box)
            "bFilter": true,
            // "searchDelay": 1000,
            "orderMulti": false, // for disable multiple column at once
            // "lengthMenu": [[10, 25, 50, 100, 200, 300, 500, -1], [10, 25, 50, 100, 200, 300, 500, "All"]],
            "lengthMenu": [[10, 25, 50, 100, 200, 300, 400, 500, 800, 1000], [10, 25, 50, 100, 200, 300, 400, 500, 800, 1000]],
            "pageLength": pageLength,
            "ajax": {

                "url": url,
                "type": "POST",
                "datatype": "json",

                "data": function (d) {
                    if (fillExtraData) {
                        fillExtraData(d);
                    }

                }

            },
            "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                fnRowCallback(nRow, aData, iDisplayIndex, iDisplayIndexFull);

            },
            "initComplete": function (settings, json) {

                //   $(main_table_data).find(".dropdown-menu").last().addClass("last-table-action");

                //  $(selector + " tr:last .dropdown-menu").addClass("last-table-action");

            },
            "drawCallback": function (settings) {

                $(selector + " tr:last .dropdown-menu").addClass("last-table-action");

                if (onDraw) {
                    onDraw();

                }
            },
            "columns": columns
        });

        //.fnFilterOnReturn();
        //main_table_data.on('order.dt search.dt', function () {
        //
        //              var d = fillExtraData
        //              main_table_data.column(0, { search: 'applied', order: 'applied', Page: 'applied' }).nodes().each(function (cell, i) {
        //                  cell.innerHTML = i + 1;
        //              });
        //          }).draw();
        $(selector + '_filter input').unbind();
        $(selector + '_filter input').bind('keyup', function (e) {

            var enterVal = this.value;

            if (e.keyCode == 13) {
                main_table_data.search(enterVal).draw();
            }
            else if (e.keyCode == 8 || e.keyCode == 46) {
                if (!enterVal || enterVal.length == 0) {
                    main_table_data.search("").draw();
                }
            }

        });

        return main_table_data;
    };

    this.setUpDataTableNoPaging = function (selector, url, columns, defaultOrder, fillExtraData) {

        var table = $(selector).DataTable({
            "dom": '<"top"i<"clear">>t<"bottom"i<"clear">>',
            "order": defaultOrder,
            "scrollY": 500,
            "scrollX": true,
            "pageLength": -1,
            "bPaginate": false,
            "bLengthChange": false,
            "processing": true, // for show progress bar
            "serverSide": true, // for process server side
            "filter": false, // this is for disable filter (search box)
            // "searchDelay": 1000,
            "orderMulti": false, // for disable multiple column at once
            "ajax": {
                "url": url,
                "type": "POST",
                "datatype": "json",
                "data": function (d) {
                    if (fillExtraData) {
                        fillExtraData(d);
                    }

                }

            },
            "columns": columns
        });

        return table;
    };

    this.showSuccessMessage = function (message) {

        if (!message) {
            message = "Saved Successfully.";
        }

        _this.showMessage(message, 'alert-success');

    };

    this.showErrorMessage = function (message) {

        if (!message) {
            message = "Error.";
        }

        _this.showMessage(message, 'alert-danger');

    };

    this.showMessage = function (message, bootstrapCss) {
        if (!message) {
            message = "No Message.";
        }

        var alertHtml = '
×' + message + '
';
        $(alertHtml).appendTo('body').delay(3000).fadeOut("slow", function () { $(alertHtml).remove() });
    };

    this.getSelectedCheckBoxesBySelector = function (className) {
        var names = [];
        $('.' + className + ':checked').each(function () {
            names.push($(this).val());
        });

        return names;
    };

    this.bindMultiSelectLanguage = function (selector, onLoad) {

        var LanguageURL = TOLK_DANMARK_BASE_URL + "/admin/home/GetAllLanguages";
        $.ajax({
            url: LanguageURL,
            success: function (result) {

                var list = result;
                $.each(list, function (index, language) {
                    $(selector).append($('<option>', {
                        value: language.Id,
                        text: language.Name
                    }));
                });

                $(selector).multiselect({
                    buttonWidth: '100%',
                    inheritClass: true,
                    maxHeight: 200,
                    enableFiltering: true,
                    enableCaseInsensitiveFiltering: true
                });

                if (onLoad)
                    onLoad();

            },
            error: function () {
                //alert("fail");
                commonManager.showErrorMessage("Unknown Error Occurred.");
            }
        });

    };

};


text:
namespace gfx {

namespace {

// Options to parameterized unittests.
struct FallbackFontTestOption {
  bool ignore_get_fallback_failure = false;
  bool skip_code_point_validation = false;
  bool skip_fallback_fonts_validation = false;
};

const FallbackFontTestOption default_fallback_option = {false, false, false};
// Options for tests that does not validate the GetFallbackFont(...) parameters.
const FallbackFontTestOption untested_fallback_option = {true, true, true};

struct BaseFontTestOption {
  const char* family_name = nullptr;
  int delta = 0;
  int style = 0;
  Font::Weight weight = Font::Weight::NORMAL;
};

constexpr BaseFontTestOption default_base_font;
constexpr BaseFontTestOption styled_font = {nullptr, 1, Font::FontStyle::ITALIC,
                                            Font::Weight::BOLD};
constexpr BaseFontTestOption sans_font = {"sans", 2};

using FallbackFontTestParamInfo = std::
    tuple<FallbackFontTestCase, FallbackFontTestOption, BaseFontTestOption>;

class GetFallbackFontTest
    : public ::testing::TestWithParam<FallbackFontTestParamInfo> {
 public:
  GetFallbackFontTest() = default;

  GetFallbackFontTest(const GetFallbackFontTest&) = delete;
  GetFallbackFontTest& operator=(const GetFallbackFontTest&) = delete;

  static std::string ParamInfoToString(
      ::testing::TestParamInfo<FallbackFontTestParamInfo> param_info) {
    const FallbackFontTestCase& test_case = std::get<0>(param_info.param);
    const BaseFontTestOption& base_font_option = std::get<2>(param_info.param);

    std::string font_option;
    if (base_font_option.family_name)
      font_option += std::string("F") + base_font_option.family_name;
    if (base_font_option.delta || base_font_option.style ||
        base_font_option.style) {
      font_option +=
          base::StringPrintf("_d%ds%dw%d", base_font_option.delta,
                             base_font_option.style, base_font_option.weight);
    }

    std::string language_tag = test_case.language_tag;
    base::RemoveChars(language_tag, "-", &language_tag);
    return std::string("S") + uscript_getName(test_case.script) + "L" +
           language_tag + font_option;
  }

  void SetUp() override {
    std::tie(test_case_, test_option_, base_font_option_) = GetParam();
  }

 protected:
  bool GetFallbackFont(const Font& font,
                       const std::string& language_tag,
                       Font* result) {
    return gfx::GetFallbackFont(font, language_tag, test_case_.text, result);
  }

  bool EnsuresScriptSupportCodePoints(const std::u16string& text,
                                      UScriptCode script,
                                      const std::string& script_name) {
    size_t i = 0;
    while (i < text.length()) {
      UChar32 code_point;
      U16_NEXT(text.c_str(), i, text.size(), code_point);
      if (!uscript_hasScript(code_point, script)) {
        // Retrieve the appropriate script
        UErrorCode script_error;
        UScriptCode codepoint_script =
            uscript_getScript(code_point, &script_error);

        ADD_FAILURE() << "CodePoint U+" << std::hex << code_point
                      << " is not part of the script '" << script_name
                      << "'. Script '" << uscript_getName(codepoint_script)
                      << "' detected.";
        return false;
      }
    }
    return true;
  }

  bool DoesFontSupportCodePoints(Font font, const std::u16string& text) {
    sk_sp<SkTypeface> skia_face = font.platform_font()->GetNativeSkTypeface();
    if (!skia_face) {
      ADD_FAILURE() << "Cannot create typeface for '" << font.GetFontName()
                    << "'.";
      return false;
    }

    size_t i = 0;
    const SkGlyphID kUnsupportedGlyph = 0;
    while (i < text.length()) {
      UChar32 code_point;
      U16_NEXT(text.c_str(), i, text.size(), code_point);
      SkGlyphID glyph_id = skia_face->unicharToGlyph(code_point);
      if (glyph_id == kUnsupportedGlyph)
        return false;
    }
    return true;
  }

  FallbackFontTestCase test_case_;
  FallbackFontTestOption test_option_;
  BaseFontTestOption base_font_option_;
  std::string script_name_;

 private:
  // Needed to bypass DCHECK in GetFallbackFont.
  base::test::TaskEnvironment task_environment_{
      base::test::TaskEnvironment::MainThreadType::UI};
};

}  // namespace

// This test ensures the font fallback work correctly. It will ensures that
//   1) The script supports the text
//   2) The input font does not already support the text
//   3) The call to GetFallbackFont() succeed
//   4) The fallback font has a glyph for every character of the text
//
// The previous checks can be activated or deactivated through the class
// FallbackFontTestOption (e.g. test_option_).
TEST_P(GetFallbackFontTest, GetFallbackFont) {
  // Default system font.
  Font base_font;
  // Apply font options to the base font.
  if (base_font_option_.family_name)
    base_font = Font(base_font_option_.family_name, base_font.GetFontSize());
  if (base_font_option_.delta != 0 || base_font_option_.style != 0 ||
      base_font_option_.weight != gfx::Font::Weight::NORMAL) {
    base_font =
        base_font.Derive(base_font_option_.delta, base_font_option_.style,
                         base_font_option_.weight);
  }

#if BUILDFLAG(IS_WIN)
  // Skip testing this call to GetFallbackFont on older windows versions. Some
  // fonts only got introduced on windows 10 and the test will fail on previous
  // versions.
  const bool is_win10 = base::win::GetVersion() >= base::win::Version::WIN10;
  if (test_case_.is_win10 && !is_win10)
    return;
#endif

  // Retrieve the name of the current script.
  script_name_ = uscript_getName(test_case_.script);

  // Validate that tested characters are part of the script.
  if (!test_option_.skip_code_point_validation &&
      !EnsuresScriptSupportCodePoints(test_case_.text, test_case_.script,
                                      script_name_)) {
    return;
  }

  // The default font already support it, do not try to find a fallback font.
  if (DoesFontSupportCodePoints(base_font, test_case_.text))
    return;

  // Retrieve the fallback font.
  Font fallback_font;
  bool result =
      GetFallbackFont(base_font, test_case_.language_tag, &fallback_font);
  if (!result) {
    if (!test_option_.ignore_get_fallback_failure)
      ADD_FAILURE() << "GetFallbackFont failed for '" << script_name_ << "'";
    return;
  }

  // Ensure the fallback font is a part of the validation fallback fonts list.
  if (!test_option_.skip_fallback_fonts_validation) {
    bool valid = std::find(test_case_.fallback_fonts.begin(),
                           test_case_.fallback_fonts.end(),
                           fallback_font.GetFontName()) !=
                 test_case_.fallback_fonts.end();
    if (!valid) {
      ADD_FAILURE() << "GetFallbackFont failed for '" << script_name_
                    << "' invalid fallback font: "
                    << fallback_font.GetFontName()
                    << " not among valid options: "
                    << base::JoinString(test_case_.fallback_fonts, ", ");
      return;
    }
  }

  // Ensure that glyphs exists in the fallback font.
  if (!DoesFontSupportCodePoints(fallback_font, test_case_.text)) {
    ADD_FAILURE() << "Font '" << fallback_font.GetFontName()
                  << "' does not matched every CodePoints.";
    return;
  }
}

// Produces a font test case for every script.
std::vector<FallbackFontTestCase> GetSampleFontTestCases() {
  std::vector<FallbackFontTestCase> result;

  const unsigned int script_max = u_getIntPropertyMaxValue(UCHAR_SCRIPT) + 1;
  for (unsigned int i = 0; i < script_max; i++) {
    const UScriptCode script = static_cast<UScriptCode>(i);

    // Make a sample text to test the script.
    char16_t text[8];
    UErrorCode errorCode = U_ZERO_ERROR;
    int text_length =
        uscript_getSampleString(script, text, std::size(text), &errorCode);
    if (text_length <= 0 || errorCode != U_ZERO_ERROR)
      continue;

    FallbackFontTestCase test_case(script, "", text, {});
    result.push_back(test_case);
  }
  return result;
}

// Ensures that the default fallback font gives known results. The test
// is validating that a known fallback font is given for a given text and font.
INSTANTIATE_TEST_SUITE_P(
    KnownExpectedFonts,
    GetFallbackFontTest,
    testing::Combine(
        testing::ValuesIn(kGetFontFallbackTests),
        testing::Values(default_fallback_option),
        testing::Values(default_base_font, styled_font, sans_font)),
    GetFallbackFontTest::ParamInfoToString);

// Ensures that font fallback functions are working properly for any string
// (strings from any script). The test doesn't enforce the functions to
// give a fallback font. The accepted behaviors are:
//    1) The fallback function failed and doesn't provide a fallback.
//    2) The fallback function succeeded and the font supports every glyphs.
INSTANTIATE_TEST_SUITE_P(
    Glyphs,
    GetFallbackFontTest,
    testing::Combine(testing::ValuesIn(GetSampleFontTestCases()),
                     testing::Values(untested_fallback_option),
                     testing::Values(default_base_font)),
    GetFallbackFontTest::ParamInfoToString);

}  // namespace gfx

redpajama_set_name: RedPajamaGithub


text:
<?php if (!defined('IDIR')) { die; }

/**
* fusionbb_010 Import Moderator module
*
* @package			ImpEx.fusionbb
*
*/
class fusionbb_010 extends fusionbb_000
{
	var $_version 		= '0.0.1';
	var $_dependent 	= '005';
	var $_modulestring 	= 'Import Moderator';

	function fusionbb_010()
	{
		// Constructor
	}

	function init(&$sessionobject, &$displayobject, &$Db_target, &$Db_source)
	{
		if ($this->check_order($sessionobject,$this->_dependent))
		{
			if ($this->_restart)
			{
				if ($this->restart($sessionobject, $displayobject, $Db_target, $Db_source,'clear_imported_moderators'))
				{
					$displayobject->display_now('
Imported moderators have been cleared
');
					$this->_restart = true;
				}
				else
				{
					$sessionobject->add_error('fatal',
											 $this->_modulestring,
											 get_class($this) . '::restart failed , clear_imported_moderators','Check database permissions');
				}
			}

			// Start up the table
			$displayobject->update_basic('title','Import Moderator');
			$displayobject->update_html($displayobject->do_form_header('index',substr(get_class($this) , -3)));
			$displayobject->update_html($displayobject->make_hidden_code(substr(get_class($this) , -3),'WORKING'));
			$displayobject->update_html($displayobject->make_hidden_code('import_moderator','working'));
			$displayobject->update_html($displayobject->make_table_header($this->_modulestring));

			// Ask some questions
			$displayobject->update_html($displayobject->make_input_code('Moderators to import per cycle ','perpage', 500));

			// End the table
			$displayobject->update_html($displayobject->do_form_footer('Continue','Reset'));

			// Reset/Setup counters for this
			$sessionobject->add_session_var(substr(get_class($this) , -3) . '_objects_done', '0');
			$sessionobject->add_session_var(substr(get_class($this) , -3) . '_objects_failed', '0');
			$sessionobject->add_session_var('startat','0');
			$sessionobject->add_session_var('moderatordone','0');
		}
		else
		{
			// Dependant has not been run
			$displayobject->update_html($displayobject->do_form_header('index',''));
			$displayobject->update_html($displayobject->make_description('
This module is dependent on ' . $sessionobject->get_module_title($this->_dependent) . ' cannot run until that is complete.'));
			$displayobject->update_html($displayobject->do_form_footer('Continue',''));
			$sessionobject->set_session_var(substr(get_class($this) , -3),'FALSE');
			$sessionobject->set_session_var('module','000');
		}
	}

	function resume(&$sessionobject, &$displayobject, &$Db_target, &$Db_source)
	{
		// Set up working variables.
		$displayobject->update_basic('displaymodules','FALSE');
		$t_db_type		= $sessionobject->get_session_var('targetdatabasetype');
		$t_tb_prefix	= $sessionobject->get_session_var('targettableprefix');
		$s_db_type		= $sessionobject->get_session_var('sourcedatabasetype');
		$s_tb_prefix	= $sessionobject->get_session_var('sourcetableprefix');

		// Per page vars
		$start_at	= $sessionobject->get_session_var('startat');
		$per_page	= $sessionobject->get_session_var('perpage');
		$class_num	= substr(get_class($this) , -3);
		$idcache	= new ImpExCache($Db_target, $t_db_type, $t_tb_prefix);

		// Start the timing
		if(!$sessionobject->get_session_var($class_num . '_start'))
		{
			$sessionobject->timing($class_num ,'start' ,$sessionobject->get_session_var('autosubmit'));
		}

		// Get an array of moderator details
		$moderator_array = $this->get_fusionbb_moderator_details($Db_source, $s_db_type, $s_tb_prefix, $start_at, $per_page);
		$forum_ids_array = $this->get_forum_ids($Db_target, $t_db_type, $t_tb_prefix);

		// Display count and pass time
		$displayobject->display_now('
Importing ' . count($moderator_array) . ' moderators

From : ' . $start_at . ' ::  To : ' . ($start_at + count($moderator_array)) . '
');

		$moderator_object = new ImpExData($Db_target, $sessionobject, 'moderator');

		foreach ($moderator_array as $moderator_id => $moderator_details)
		{
			$try = (phpversion() < '5' ? $moderator_object : clone($moderator_object));
			// Mandatory
			$try->set_value('mandatory', 'userid',					$idcache->get_id('user', $moderator_details['user_id']));
			$try->set_value('mandatory', 'forumid',					$forum_ids_array["$moderator_details[forum_id]"]);
			$try->set_value('mandatory', 'importmoderatorid',		$moderator_id);

			// Non Mandatory
			$try->set_value('nonmandatory', 'permissions',			$this->_default_mod_permissions);

			// Check if moderator object is valid
			if($try->is_valid())
			{
				if($try->import_moderator($Db_target, $t_db_type, $t_tb_prefix))
				{
					$displayobject->display_now('
' . $try->how_complete() . '% :: moderator -> ' . $idcache->get_id('user', $moderator_details['user_id']));
					$sessionobject->add_session_var($class_num . '_objects_done',intval($sessionobject->get_session_var($class_num . '_objects_done')) + 1 );
				}
				else
				{
					$sessionobject->set_session_var($class_num . '_objects_failed',$sessionobject->get_session_var($class_num. '_objects_failed') + 1 );
					$sessionobject->add_error('warning', $this->_modulestring, get_class($this) . '::import_custom_profile_pic failed.', 'Check database permissions and database table');
					$displayobject->display_now("
Found avatar moderator and DID NOT imported to the  {$t_db_type} database");
				}
			}
			else
			{
				$displayobject->display_now("
Invalid moderator object, skipping." . $try->_failedon);die;
			}
			unset($try);
		}// End foreach

		// Check for page end
		if (count($moderator_array) == 0 OR count($moderator_array) < $per_page)
		{
			$sessionobject->timing($class_num,'stop', $sessionobject->get_session_var('autosubmit'));
			$sessionobject->remove_session_var($class_num . '_start');

			$displayobject->update_html($displayobject->module_finished($this->_modulestring,
										$sessionobject->return_stats($class_num, '_time_taken'),
										$sessionobject->return_stats($class_num, '_objects_done'),
										$sessionobject->return_stats($class_num, '_objects_failed')
										));

			$sessionobject->set_session_var($class_num ,'FINISHED');
			$sessionobject->set_session_var('import_moderator','done');
			$sessionobject->set_session_var('module','000');
			$sessionobject->set_session_var('autosubmit','0');
		}

		$sessionobject->set_session_var('startat',$start_at+$per_page);
		$displayobject->update_html($displayobject->print_redirect('index.php',$sessionobject->get_session_var('pagespeed')));
	}// End resume
}//End Class
# Autogenerated on : November 22, 2004, 6:52 pm
# By ImpEx-generator 1.4.
/*======================================================================*/
?>


text:
package main

import (
	"encoding/json"
	"fmt"
	"github.com/jmoiron/sqlx"
	_ "github.com/mattn/go-sqlite3"
	"github.com/skratchdot/open-golang/open"
	"net"
	"net/http"
	"log"
	"os"
)

type Termine struct {
	Termine     string `db:"termine" json:"termine"`
	Definizione string `db:"definizione" json:"definizione"`
}

var db *sqlx.DB

func searchHandler(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query().Get("q")
	fmt.Println(q)

	w.Header().Set("Content-Type", "application/json")
	rows, err := db.Queryx("SELECT * FROM definizioni WHERE definizioni MATCH ? ORDER BY rank;", q)
	defer rows.Close()

	if (err != nil) {
		log.Fatal(err)
	}

	termini := make([]Termine, 0)
	if err == nil {
		for rows.Next() {
			var t Termine
			err = rows.StructScan(&t)
			termini = append(termini, t)
		}

	} else {
		log.Panic(err.Error())
	}
	json.NewEncoder(w).Encode(termini)
}

func main() {
	//crea il file db3 con questo comando (io uso SQLiteSpy):
	//CREATE VIRTUAL TABLE definizioni USING fts5(termine, definizione);
	//https://sqlite.org/fts5.html

	os.Remove("dizionario.db3")

	db = sqlx.MustConnect("sqlite3", "file:dizionario.db3?loc=auto")
	defer db.Close()

	db.MustExec("CREATE VIRTUAL TABLE definizioni USING fts5(termine, definizione);")
	db.MustExec("INSERT INTO definizioni VALUES ('cavallo','animale equino molto bello')")
	db.MustExec("INSERT INTO definizioni VALUES ('sviluppatore','animale umano un po meno bello del cavallo')")
	db.MustExec("INSERT INTO definizioni VALUES ('cliente','essere mitologico metà umano e metà cavallo')")
	db.MustExec("INSERT INTO definizioni VALUES ('delfino','animale curioso e sapiente. prima di andarsene ringrazia per tutto il pesce')")

	http.HandleFunc("/search", searchHandler)
	http.Handle("/", http.FileServer(http.Dir("static")))

	listener, err := net.Listen("tcp", ":8080")
	go http.Serve(listener, nil)

	err = open.Run("http://localhost:8080/")
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("Chiudi questa finestra (o premi CTRL+c) per uscire...")

	select {}
}


text:
package org.arbeitspferde.groningen.hypothesizer;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.arbeitspferde.groningen.utility.Clock;
import org.arbeitspferde.groningen.utility.SystemClock;
import org.uncommons.watchmaker.framework.CandidateFactory;
import org.uncommons.watchmaker.framework.EvaluatedCandidate;
import org.uncommons.watchmaker.framework.EvolutionUtils;
import org.uncommons.watchmaker.framework.EvolutionaryOperator;
import org.uncommons.watchmaker.framework.FitnessEvaluator;
import org.uncommons.watchmaker.framework.GenerationalEvolutionEngine;
import org.uncommons.watchmaker.framework.PopulationData;
import org.uncommons.watchmaker.framework.SelectionStrategy;
import org.uncommons.watchmaker.framework.TerminationCondition;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * This class provides incremental version of GA, where the calling code has control over the
 * generations. We cannot use the default {@link GenerationalEvolutionEngine} for Groningen since
 * the fitness is computed after the experiment is run on the servers. {@link
 * GenerationalEvolutionEngine} will run the generations until the stopping conditions are met.
 * Instead, this class evolves one generation at a time and returns the population back.
 *
 * This class is not thread safe.
 *
 * @param <T> the type of elements this evolution engine handles.
 */
public class IncrementalEvolutionEngine<T> extends GenerationalEvolutionEngine<T> {

  private final Set<EvolutionObserver<T>> observers =
      new CopyOnWriteArraySet<EvolutionObserver<T>>();

  private final CandidateFactory<T> candidateFactory;
  private final EvolutionaryOperator<T> evolutionScheme;
  private final FitnessEvaluator<? super T> fitnessEvaluator;
  private final SelectionStrategy<? super T> selectionStrategy;
  private final Random rng;
  private final int populationSize;
  private final int eliteCount;
  private final TerminationCondition[] conditions;
  private final Clock clock;

  private int currentGenerationIndex;
  private long startTime;
  private boolean initialized;
  private boolean terminated;

  public IncrementalEvolutionEngine(
      CandidateFactory<T> candidateFactory,
      EvolutionaryOperator<T> evolutionScheme,
      FitnessEvaluator<? super T> fitnessEvaluator,
      SelectionStrategy<? super T> selectionStrategy,
      Random rng,
      int populationSize,
      int eliteCount,
      TerminationCondition... conditions) {
    this(
        candidateFactory,
        evolutionScheme,
        fitnessEvaluator,
        selectionStrategy,
        rng,
        populationSize,
        eliteCount,
        new SystemClock(),
        conditions);
  }

  @VisibleForTesting IncrementalEvolutionEngine(
      CandidateFactory<T> candidateFactory,
      EvolutionaryOperator<T> evolutionScheme,
      FitnessEvaluator<? super T> fitnessEvaluator,
      SelectionStrategy<? super T> selectionStrategy,
      Random rng,
      int populationSize,
      int eliteCount,
      Clock clock,
      TerminationCondition... conditions) {
    super(candidateFactory, evolutionScheme, fitnessEvaluator, selectionStrategy, rng);
    Preconditions.checkArgument(
        eliteCount < populationSize, "Elite count has to be smaller that the population size.");

    this.candidateFactory = candidateFactory;
    this.evolutionScheme = evolutionScheme;
    this.fitnessEvaluator = fitnessEvaluator;
    this.selectionStrategy = selectionStrategy;
    this.rng = rng;
    this.populationSize = populationSize;
    this.eliteCount = eliteCount;
    this.conditions = conditions;
    this.clock = clock;
    super.setSingleThreaded(true);
  }

  /**
   * Performs the first step in the GA, which is to create the initial population by using {@link
   * CandidateFactory}. The population is returned to the caller. This method can be called only
   * once, and before calling {#performNextStep()} method.
   *
   * @return Initial population.
   */
  public List<T> performFirstStep() {
    if (initialized) {
      throw new IllegalStateException("Evolutionary process has already started.");
    }
    if (terminated) {
      throw new IllegalStateException("Evolutionary process has been terminated already.");
    }

    startTime = clock.now().getMillis();

    List<T> population =
        candidateFactory.generateInitialPopulation(populationSize, Collections.<T>emptySet(), rng);
    initialized = true;

    return population;
  }

  /**
   * Performs the subsequent steps in the GA, which is to evolve the population one generation at a
   * time. Unlike other evolution engines, here the population is passed in by the calling code.
   * This method computes the fitness of each individual in the population, applies the evolutionary
   * operators on the population, and returns the population. Call {#performFirstStep()} method
   * before calling this method.
   *
   * @param population Current population.
   * @return Evolved population.
   */
  public List<T> performNextStep(List<T> population) {
    if (!initialized) {
      throw new IllegalStateException("Evolutionary process has not been started yet.");
    }
    if (terminated) {
      throw new IllegalStateException("Evolutionary process has been terminated already.");
    }
    Preconditions.checkArgument(
        population != null && population.size() == populationSize, "Invalid population.");

    // Calculate the fitness scores for each member of the population.
    List<EvaluatedCandidate<T>> evaluatedPopulation = evaluatePopulation(population);

    // Sort the individuals according to their fitness. Individual with highest fitness value will
    // be at the top of the population.
    EvolutionUtils.sortEvaluatedPopulation(evaluatedPopulation, fitnessEvaluator.isNatural());

    // Generate population data
    PopulationData<T> data = EvolutionUtils.getPopulationData(
        evaluatedPopulation, fitnessEvaluator.isNatural(), 0, currentGenerationIndex, startTime);

    notifyPopulationChange(data, evaluatedPopulation);

    // Check if we have met the termination conditions. Only check when there are conditions.
    List<TerminationCondition> satisfiedConditions = null;
    if (conditions[0] != null) {
      satisfiedConditions = EvolutionUtils.shouldContinue(data, conditions);
    }

    // If not met, evolve the population by one generation, and return the evolved population.
    if (satisfiedConditions == null) {
      ++currentGenerationIndex;
      population = performEvolution(evaluatedPopulation, eliteCount, rng);
    } else {
      terminated = true;
    }

    // Otherwise, just return the current population
    return population;
  }

  /**
   * Returns whether the GA has met the termination conditions. If terminated, calling code should
   * not call {#performFirstStep()} or {#performNextStep()} method any more.
   *
   * @return Whether the GA has met the termination conditions or not.
   */
  public boolean isTerminated() {
    return terminated;
  }

  /**
   * Performs single evolution.
   */
  private List<T> performEvolution(
      List<EvaluatedCandidate<T>> evaluatedPopulation, int eliteCount, Random rng) {
    List<T> population = Lists.newArrayListWithCapacity(evaluatedPopulation.size());

    // First perform any elitist selection.
    List<T> elite = Lists.newArrayListWithCapacity(eliteCount);
    Iterator<EvaluatedCandidate<T>> iterator = evaluatedPopulation.iterator();
    while (elite.size() < eliteCount) {
      elite.add(iterator.next().getCandidate());
    }

    // Then select candidates that will be operated on to create the evolved
    // portion of the next generation.
    population.addAll(
        selectionStrategy.select(evaluatedPopulation, fitnessEvaluator.isNatural(),
            evaluatedPopulation.size() - eliteCount, rng));

    // Then evolve the population.
    population = evolutionScheme.apply(population, rng);

    // When the evolution is finished, add the elite individuals to the population.
    population.addAll(elite);

    return population;
  }

  /**
   * Adds a listener to receive status updates on the evolution progress. Updates are dispatched
   * synchronously on the request thread. Observers should complete their processing and return in a
   * timely manner to avoid holding up the evolution.
   *
   * @param observer An evolution observer call-back.
   * @see #removeEvolutionObserver(EvolutionObserver)
   */
  public void addEvolutionObserver(EvolutionObserver<T> observer) {
    observers.add(observer);
  }

  /**
   * Removes an evolution progress listener.
   *
   * @param observer An evolution observer call-back.
   * @see #addEvolutionObserver(EvolutionObserver)
   */
  public void removeEvolutionObserver(EvolutionObserver<T> observer) {
    observers.remove(observer);
  }

  /**
   * Send the population data to all registered observers.
   *
   * @param data Information about the current state of the population.
   */
  private void notifyPopulationChange(
      PopulationData<T> data, List<EvaluatedCandidate<T>> population) {
    for (EvolutionObserver<T> observer : observers) {
      observer.populationUpdate(data, population);
    }
  }
}


text:
app.factory('Wikipedia', ['$rootScope', '$http', '$q', function($rootScope, $http, $q) {
  var cache = {};

  var extractParagraphs = function(data) {
    // sort through the json.
    data = data.query.pages;
    // pages is an object with 1 key
    for (var key in data) {
      data = data[key].revisions[0]['*'];
      break;
    }

    // Create a div to store data so we can manipulate it
    var content = document.createElement('div');
    content.innerHTML = data;

    // Remove all tables
    var tables = content.querySelectorAll('table');
    for (var i = 0; i < tables.length; i++) {
      var table = tables[i];
      table.parentNode.removeChild(table);
    }

    // Fix links so that they point to wikipedia properly
    var links = content.querySelectorAll('a');
    for (var i = 0; i < links.length; i++) {
      var link = links[i];
      var href = link.getAttribute('href');
      if (href.charAt(1) !== '/') {
        link.setAttribute('href', 'http://wikipedia.org' + href);
      }
    }

    // Grab <p> tags and get their HTML
    var htmlPs = content.querySelectorAll('p');
    var paragraphs = [];
    for (var i = 0; i < htmlPs.length; i++) {
      paragraphs.push(htmlPs[i].innerHTML);
    }

    return paragraphs;
  };

  return {
    getSummary: function(country) {
      if (cache.hasOwnProperty(country)) {
        return cache[country];
      } else {
        var summary = $q.defer();
        var url = 'http://en.wikipedia.org/w/api.php?action=query' +
                  '&prop=revisions&rvprop=content&rvsection=0&rvparse=1&titles=' +
                  country + "&format=json&redirects=1&callback=JSON_CALLBACK";

        $http.jsonp(url).success(function(data) {
          var paragraphs = extractParagraphs(data);

          cache[country] = paragraphs;
          $rootScope.loading.wikipediaComplete = true;
          summary.resolve(paragraphs);
        });

        return summary.promise
      }
    }
  };
}]);


text:
import inspect_compute_results
import sys

try:
    sys.exit(inspect_compute_results.main_helper(sys.argv[1:]))
except ValueError as value_error:
    sys.stderr.write(str(value_error))
    sys.exit(1)


text:
swoole_coroutine_system: getaddrinfo
--SKIPIF--
<?php require __DIR__ . '/../include/skipif.inc';
skip_if_offline();
?>
--FILE--
<?php
require __DIR__ . '/../include/bootstrap.php';
go(function () {
    $ip_list = Swoole\Coroutine\System::getaddrinfo('www.baidu.com', AF_INET);
    Assert::assert(!empty($ip_list) and is_array($ip_list));
    foreach ($ip_list as $ip) {
        Assert::assert(preg_match(IP_REGEX, $ip));
    }
    echo "DONE\n";
});
?>
--EXPECT--
DONE


text:
var _ = require('./lodash');

QUnit.module('lodash.first combined');

/** @sample first */
(function() {
    var array = [1, 2, 3];

    var objects = [
    { 'a': 2, 'b': 2 },
    { 'a': 1, 'b': 1 },
    { 'a': 0, 'b': 0 }
    ];

    // should return the first element
    strictEqual(_.first(array), 1);

    // should return the first two elements
    deepEqual(_.first(array, 2), [1, 2]);

    // should work with a `callback`
      var actual = _.first(array, function(num) {
        return num < 3;
    });

      deepEqual(actual, [1, 2]);
}());

/** @example first */
(function() {
    var array = [1, 2, 3];

    var objects = [
    { 'a': 2, 'b': 2 },
    { 'a': 1, 'b': 1 },
    { 'a': 0, 'b': 0 }
    ];

    test('should return the first element', function() {
      strictEqual(_.first(array), 1);
  });

    test('should return the first two elements', function() {
      deepEqual(_.first(array, 2), [1, 2]);
  });

    test('should work with a `callback`', function() {
      var actual = _.first(array, function(num) {
        return num < 3;
    });

      deepEqual(actual, [1, 2]);
  });

    test('should pass the correct `callback` arguments', function() {
      var args;

      _.first(array, function() {
        args || (args = slice.call(arguments));
    });

      deepEqual(args, [1, 0, array]);
  });

    test('supports the `thisArg` argument', function() {
      var actual = _.first(array, function(value, index) {
        return this[index] < 3;
    }, array);

      deepEqual(actual, [1, 2]);
  });

    test('should chain when passing `n`, `callback`, or `thisArg`', function() {
      var actual = _(array).first(2);

      ok(actual instanceof _);

      actual = _(array).first(function(num) {
        return num < 3;
    });

      ok(actual instanceof _);

      actual = _(array).first(function(value, index) {
        return this[index] < 3;
    }, array);

      ok(actual instanceof _);
  });

    test('should not chain when no arguments are passed', function() {
      var actual = _(array).first();
      strictEqual(actual, 1);
  });

    test('should work with an object for `callback`', function() {
      deepEqual(_.first(objects, { 'b': 2 }), objects.slice(0, 1));
  });

    test('should work with a string for `callback`', function() {
      deepEqual(_.first(objects, 'b'), objects.slice(0, 2));
  });
}());


text:
using Android.Graphics;
using Android.Graphics.Drawables;

namespace QuickAction
{
    /// <summary>
    ///   Action item, displayed as menu with icon and text.
    /// </summary>
    public class ActionItem
    {
        public ActionItem() : this(-1, null, null)
        {
        }

        public ActionItem(int actionId, string title) : this(actionId, title, null)
        {
        }

        public ActionItem(Drawable icon) : this(-1, null, icon)
        {
        }

        public ActionItem(int actionId, string title, Drawable icon)
        {
            Title = title;
            Icon = icon;
            ActionId = actionId;
        }

        public int ActionId { get; set; }

        public Bitmap Thumb { get; set; }

        public string Title { get; set; }

        public Drawable Icon { get; set; }

        public bool IsSticky { get; set; }

        public bool Selected { get; set; }
    }
}


text:
package org.ovirt.engine.ui.common.widget.action;

import org.ovirt.engine.ui.common.idhandler.WithElementId;

import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;

public abstract class AbstractActionStackPanelItem<M, T, W extends Widget> extends Composite {

    @UiField(provided = true)
    @WithElementId
    public AbstractActionPanel<T> actionPanel;

    @UiField(provided = true)
    public W dataDisplayWidget;

    public AbstractActionStackPanelItem(M modelProvider) {
        this.dataDisplayWidget = createDataDisplayWidget(modelProvider);
        this.actionPanel = createActionPanel(modelProvider);
    }

    @Override
    protected void initWidget(Widget widget) {
        super.initWidget(widget);

        // Add context menu handler for data display widget
        actionPanel.addContextMenuHandler(dataDisplayWidget);
    }

    public W getDataDisplayWidget() {
        return dataDisplayWidget;
    }

    protected abstract W createDataDisplayWidget(M modelProvider);

    protected abstract AbstractActionPanel<T> createActionPanel(M modelProvider);

}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

require('terra-base/lib/baseStyles');

var _GridRow = require('./GridRow');

var _GridRow2 = _interopRequireDefault(_GridRow);

var _GridColumn = require('./GridColumn');

var _GridColumn2 = _interopRequireDefault(_GridColumn);

require('./Grid.scss');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var propTypes = {
  /**
   * The component that will be displayed at row level.
   */
  children: _propTypes2.default.node.isRequired
};

var Grid = function Grid(props) {
  return _react2.default.createElement('div', props);
};

Grid.propTypes = propTypes;
Grid.Row = _GridRow2.default;
Grid.Column = _GridColumn2.default;

exports.default = Grid;


text:
This project serves as a collection of example configurations focused on Cloud Deploy

Each folder contains its own independent sample application along with a README file that will document any prerequisites required to use the example

Please open a github issue if you find any problems with the examples


text:
const Backbone = require('backbone');
const IconModel = require('./organization-icon-model');
const checkAndBuildOpts = require('builder/helpers/required-opts');

const REQUIRED_OPTS = [
  'orgId',
  'configModel'
];

module.exports = Backbone.Collection.extend({
  initialize: function (models, options) {
    checkAndBuildOpts(options, REQUIRED_OPTS, this);
  },

  model: function (attrs, opts) {
    const options = { ...opts, configModel: opts.collection._configModel };

    return new IconModel(attrs, options);
  },

  url: function (method) {
    const version = this._configModel.urlVersion('organization-assets', method);

    return `/api/${version}/organization/${this._orgId}/assets`;
  }
});


text:
<?php

namespace DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRPlanDefinition;

use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRActionRelationshipType;
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement;
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRId;
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRQuantity\FHIRDuration;
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRRange;
use DCarbone\PHPFHIRGenerated\R4\PHPFHIRConstants;
use DCarbone\PHPFHIRGenerated\R4\PHPFHIRTypeInterface;

/**
 * This resource allows for the definition of various types of plans as a sharable,
 * consumable, and executable artifact. The resource is general enough to support
 * the description of a broad range of clinical artifacts such as clinical decision
 * support rules, order sets and protocols.
 *
 * Class FHIRPlanDefinitionRelatedAction
 * @package \DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRPlanDefinition
 */
class FHIRPlanDefinitionRelatedAction extends FHIRBackboneElement
{
    // name of FHIR type this class describes
    const FHIR_TYPE_NAME = PHPFHIRConstants::TYPE_NAME_PLAN_DEFINITION_DOT_RELATED_ACTION;
    const FIELD_ACTION_ID = 'actionId';
    const FIELD_ACTION_ID_EXT = '_actionId';
    const FIELD_OFFSET_DURATION = 'offsetDuration';
    const FIELD_OFFSET_RANGE = 'offsetRange';
    const FIELD_RELATIONSHIP = 'relationship';
    const FIELD_RELATIONSHIP_EXT = '_relationship';

    /** @var string */
    private $_xmlns = 'http://hl7.org/fhir';

    /**
     * Any combination of letters, numerals, "-" and ".", with a length limit of 64
     * characters. (This might be an integer, an unprefixed OID, UUID or any other
     * identifier pattern that meets these constraints.) Ids are case-insensitive.
     * RFC 4122
     * If the element is present, it must have either a \@value, an \@id referenced from
     * the Narrative, or extensions
     *
     * The element id of the related action.
     *
     * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRId
     */
    protected $actionId = null;

    /**
     * A length of time.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * A duration or range of durations to apply to the relationship. For example,
     * 30-60 minutes before. (choose any one of offset*, but only one)
     *
     * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRQuantity\FHIRDuration
     */
    protected $offsetDuration = null;

    /**
     * A set of ordered Quantities defined by a low and high limit.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * A duration or range of durations to apply to the relationship. For example,
     * 30-60 minutes before. (choose any one of offset*, but only one)
     *
     * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRRange
     */
    protected $offsetRange = null;

    /**
     * Defines the types of relationships between actions.
     * If the element is present, it must have either a \@value, an \@id, or extensions
     *
     * The relationship of this action to the related action.
     *
     * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRActionRelationshipType
     */
    protected $relationship = null;

    /**
     * Validation map for fields in type PlanDefinition.RelatedAction
     * @var array
     */
    private static $_validationRules = [    ];

    /**
     * FHIRPlanDefinitionRelatedAction Constructor
     * @param null|array $data
     */
    public function __construct($data = null)
    {
        if (null === $data || [] === $data) {
            return;
        }
        if (!is_array($data)) {
            throw new \InvalidArgumentException(sprintf(
                'FHIRPlanDefinitionRelatedAction::_construct - $data expected to be null or array, %s seen',
                gettype($data)
            ));
        }
        parent::__construct($data);
        if (isset($data[self::FIELD_ACTION_ID]) || isset($data[self::FIELD_ACTION_ID_EXT])) {
            if (isset($data[self::FIELD_ACTION_ID])) {
                $value = $data[self::FIELD_ACTION_ID];
            } else {
                $value = null;
            }
            if (isset($data[self::FIELD_ACTION_ID_EXT]) && is_array($data[self::FIELD_ACTION_ID_EXT])) {
                $ext = $data[self::FIELD_ACTION_ID_EXT];
            } else {
                $ext = [];
            }
            if (null !== $value) {
                if ($value instanceof FHIRId) {
                    $this->setActionId($value);
                } else if (is_array($value)) {
                    $this->setActionId(new FHIRId(array_merge($ext, $value)));
                } else {
                    $this->setActionId(new FHIRId([FHIRId::FIELD_VALUE => $value] + $ext));
                }
            } else if ([] !== $ext) {
                $this->setActionId(new FHIRId($ext));
            }
        }
        if (isset($data[self::FIELD_OFFSET_DURATION])) {
            if ($data[self::FIELD_OFFSET_DURATION] instanceof FHIRDuration) {
                $this->setOffsetDuration($data[self::FIELD_OFFSET_DURATION]);
            } else {
                $this->setOffsetDuration(new FHIRDuration($data[self::FIELD_OFFSET_DURATION]));
            }
        }
        if (isset($data[self::FIELD_OFFSET_RANGE])) {
            if ($data[self::FIELD_OFFSET_RANGE] instanceof FHIRRange) {
                $this->setOffsetRange($data[self::FIELD_OFFSET_RANGE]);
            } else {
                $this->setOffsetRange(new FHIRRange($data[self::FIELD_OFFSET_RANGE]));
            }
        }
        if (isset($data[self::FIELD_RELATIONSHIP]) || isset($data[self::FIELD_RELATIONSHIP_EXT])) {
            if (isset($data[self::FIELD_RELATIONSHIP])) {
                $value = $data[self::FIELD_RELATIONSHIP];
            } else {
                $value = null;
            }
            if (isset($data[self::FIELD_RELATIONSHIP_EXT]) && is_array($data[self::FIELD_RELATIONSHIP_EXT])) {
                $ext = $data[self::FIELD_RELATIONSHIP_EXT];
            } else {
                $ext = [];
            }
            if (null !== $value) {
                if ($value instanceof FHIRActionRelationshipType) {
                    $this->setRelationship($value);
                } else if (is_array($value)) {
                    $this->setRelationship(new FHIRActionRelationshipType(array_merge($ext, $value)));
                } else {
                    $this->setRelationship(new FHIRActionRelationshipType([FHIRActionRelationshipType::FIELD_VALUE => $value] + $ext));
                }
            } else if ([] !== $ext) {
                $this->setRelationship(new FHIRActionRelationshipType($ext));
            }
        }
    }

    /**
     * @return string
     */
    public function _getFHIRTypeName()
    {
        return self::FHIR_TYPE_NAME;
    }

    /**
     * @return string
     */
    public function _getFHIRXMLElementDefinition()
    {
        $xmlns = $this->_getFHIRXMLNamespace();
        if (null !== $xmlns) {
            $xmlns = " xmlns=\"{$xmlns}\"";
        }
        return "<PlanDefinitionRelatedAction{$xmlns}></PlanDefinitionRelatedAction>";
    }

    /**
     * Any combination of letters, numerals, "-" and ".", with a length limit of 64
     * characters. (This might be an integer, an unprefixed OID, UUID or any other
     * identifier pattern that meets these constraints.) Ids are case-insensitive.
     * RFC 4122
     * If the element is present, it must have either a \@value, an \@id referenced from
     * the Narrative, or extensions
     *
     * The element id of the related action.
     *
     * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRId
     */
    public function getActionId()
    {
        return $this->actionId;
    }

    /**
     * Any combination of letters, numerals, "-" and ".", with a length limit of 64
     * characters. (This might be an integer, an unprefixed OID, UUID or any other
     * identifier pattern that meets these constraints.) Ids are case-insensitive.
     * RFC 4122
     * If the element is present, it must have either a \@value, an \@id referenced from
     * the Narrative, or extensions
     *
     * The element id of the related action.
     *
     * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRId $actionId
     * @return static
     */
    public function setActionId($actionId = null)
    {
        if (null === $actionId) {
            $this->actionId = null;
            return $this;
        }
        if ($actionId instanceof FHIRId) {
            $this->actionId = $actionId;
            return $this;
        }
        $this->actionId = new FHIRId($actionId);
        return $this;
    }

    /**
     * A length of time.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * A duration or range of durations to apply to the relationship. For example,
     * 30-60 minutes before. (choose any one of offset*, but only one)
     *
     * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRQuantity\FHIRDuration
     */
    public function getOffsetDuration()
    {
        return $this->offsetDuration;
    }

    /**
     * A length of time.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * A duration or range of durations to apply to the relationship. For example,
     * 30-60 minutes before. (choose any one of offset*, but only one)
     *
     * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRQuantity\FHIRDuration $offsetDuration
     * @return static
     */
    public function setOffsetDuration(FHIRDuration $offsetDuration = null)
    {
        $this->offsetDuration = $offsetDuration;
        return $this;
    }

    /**
     * A set of ordered Quantities defined by a low and high limit.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * A duration or range of durations to apply to the relationship. For example,
     * 30-60 minutes before. (choose any one of offset*, but only one)
     *
     * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRRange
     */
    public function getOffsetRange()
    {
        return $this->offsetRange;
    }

    /**
     * A set of ordered Quantities defined by a low and high limit.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * A duration or range of durations to apply to the relationship. For example,
     * 30-60 minutes before. (choose any one of offset*, but only one)
     *
     * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRRange $offsetRange
     * @return static
     */
    public function setOffsetRange(FHIRRange $offsetRange = null)
    {
        $this->offsetRange = $offsetRange;
        return $this;
    }

    /**
     * Defines the types of relationships between actions.
     * If the element is present, it must have either a \@value, an \@id, or extensions
     *
     * The relationship of this action to the related action.
     *
     * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRActionRelationshipType
     */
    public function getRelationship()
    {
        return $this->relationship;
    }

    /**
     * Defines the types of relationships between actions.
     * If the element is present, it must have either a \@value, an \@id, or extensions
     *
     * The relationship of this action to the related action.
     *
     * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRActionRelationshipType $relationship
     * @return static
     */
    public function setRelationship(FHIRActionRelationshipType $relationship = null)
    {
        $this->relationship = $relationship;
        return $this;
    }

    /**
     * Returns the validation rules that this type's fields must comply with to be considered "valid"
     * The returned array is in ["fieldname[.offset]" => ["rule" => {constraint}]]
     *
     * @return array
     */
    public function _getValidationRules()
    {
        return self::$_validationRules;
    }

    /**
     * Validates that this type conforms to the specifications set forth for it by FHIR.  An empty array must be seen as
     * passing.
     *
     * @return array
     */
    public function _getValidationErrors()
    {
        $errs = parent::_getValidationErrors();
        $validationRules = $this->_getValidationRules();
        if (null !== ($v = $this->getActionId())) {
            if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
                $errs[self::FIELD_ACTION_ID] = $fieldErrs;
            }
        }
        if (null !== ($v = $this->getOffsetDuration())) {
            if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
                $errs[self::FIELD_OFFSET_DURATION] = $fieldErrs;
            }
        }
        if (null !== ($v = $this->getOffsetRange())) {
            if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
                $errs[self::FIELD_OFFSET_RANGE] = $fieldErrs;
            }
        }
        if (null !== ($v = $this->getRelationship())) {
            if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
                $errs[self::FIELD_RELATIONSHIP] = $fieldErrs;
            }
        }
        if (isset($validationRules[self::FIELD_ACTION_ID])) {
            $v = $this->getActionId();
            foreach($validationRules[self::FIELD_ACTION_ID] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_PLAN_DEFINITION_DOT_RELATED_ACTION, self::FIELD_ACTION_ID, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_ACTION_ID])) {
                        $errs[self::FIELD_ACTION_ID] = [];
                    }
                    $errs[self::FIELD_ACTION_ID][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_OFFSET_DURATION])) {
            $v = $this->getOffsetDuration();
            foreach($validationRules[self::FIELD_OFFSET_DURATION] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_PLAN_DEFINITION_DOT_RELATED_ACTION, self::FIELD_OFFSET_DURATION, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_OFFSET_DURATION])) {
                        $errs[self::FIELD_OFFSET_DURATION] = [];
                    }
                    $errs[self::FIELD_OFFSET_DURATION][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_OFFSET_RANGE])) {
            $v = $this->getOffsetRange();
            foreach($validationRules[self::FIELD_OFFSET_RANGE] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_PLAN_DEFINITION_DOT_RELATED_ACTION, self::FIELD_OFFSET_RANGE, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_OFFSET_RANGE])) {
                        $errs[self::FIELD_OFFSET_RANGE] = [];
                    }
                    $errs[self::FIELD_OFFSET_RANGE][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_RELATIONSHIP])) {
            $v = $this->getRelationship();
            foreach($validationRules[self::FIELD_RELATIONSHIP] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_PLAN_DEFINITION_DOT_RELATED_ACTION, self::FIELD_RELATIONSHIP, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_RELATIONSHIP])) {
                        $errs[self::FIELD_RELATIONSHIP] = [];
                    }
                    $errs[self::FIELD_RELATIONSHIP][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_MODIFIER_EXTENSION])) {
            $v = $this->getModifierExtension();
            foreach($validationRules[self::FIELD_MODIFIER_EXTENSION] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_BACKBONE_ELEMENT, self::FIELD_MODIFIER_EXTENSION, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_MODIFIER_EXTENSION])) {
                        $errs[self::FIELD_MODIFIER_EXTENSION] = [];
                    }
                    $errs[self::FIELD_MODIFIER_EXTENSION][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_EXTENSION])) {
            $v = $this->getExtension();
            foreach($validationRules[self::FIELD_EXTENSION] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ELEMENT, self::FIELD_EXTENSION, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_EXTENSION])) {
                        $errs[self::FIELD_EXTENSION] = [];
                    }
                    $errs[self::FIELD_EXTENSION][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_ID])) {
            $v = $this->getId();
            foreach($validationRules[self::FIELD_ID] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ELEMENT, self::FIELD_ID, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_ID])) {
                        $errs[self::FIELD_ID] = [];
                    }
                    $errs[self::FIELD_ID][$rule] = $err;
                }
            }
        }
        return $errs;
    }

    /**
     * @param \SimpleXMLElement|string|null $sxe
     * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRPlanDefinition\FHIRPlanDefinitionRelatedAction $type
     * @param null|int $libxmlOpts
     * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRPlanDefinition\FHIRPlanDefinitionRelatedAction
     */
    public static function xmlUnserialize($sxe = null, PHPFHIRTypeInterface $type = null, $libxmlOpts = 591872)
    {
        if (null === $sxe) {
            return null;
        }
        if (is_string($sxe)) {
            libxml_use_internal_errors(true);
            $sxe = new \SimpleXMLElement($sxe, $libxmlOpts, false);
            if ($sxe === false) {
                throw new \DomainException(sprintf('FHIRPlanDefinitionRelatedAction::xmlUnserialize - String provided is not parseable as XML: %s', implode(', ', array_map(function(\libXMLError $err) { return $err->message; }, libxml_get_errors()))));
            }
            libxml_use_internal_errors(false);
        }
        if (!($sxe instanceof \SimpleXMLElement)) {
            throw new \InvalidArgumentException(sprintf('FHIRPlanDefinitionRelatedAction::xmlUnserialize - $sxe value must be null, \\SimpleXMLElement, or valid XML string, %s seen', gettype($sxe)));
        }
        if (null === $type) {
            $type = new FHIRPlanDefinitionRelatedAction;
        } elseif (!is_object($type) || !($type instanceof FHIRPlanDefinitionRelatedAction)) {
            throw new \RuntimeException(sprintf(
                'FHIRPlanDefinitionRelatedAction::xmlUnserialize - $type must be instance of \DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRPlanDefinition\FHIRPlanDefinitionRelatedAction or null, %s seen.',
                is_object($type) ? get_class($type) : gettype($type)
            ));
        }
        FHIRBackboneElement::xmlUnserialize($sxe, $type);
        $xmlNamespaces = $sxe->getDocNamespaces(false, false);
        if ([] !== $xmlNamespaces) {
            $ns = reset($xmlNamespaces);
            if (false !== $ns && '' !== $ns) {
                $type->_xmlns = $ns;
            }
        }
        $attributes = $sxe->attributes();
        $children = $sxe->children();
        if (isset($children->actionId)) {
            $type->setActionId(FHIRId::xmlUnserialize($children->actionId));
        }
        if (isset($attributes->actionId)) {
            $pt = $type->getActionId();
            if (null !== $pt) {
                $pt->setValue((string)$attributes->actionId);
            } else {
                $type->setActionId((string)$attributes->actionId);
            }
        }
        if (isset($children->offsetDuration)) {
            $type->setOffsetDuration(FHIRDuration::xmlUnserialize($children->offsetDuration));
        }
        if (isset($children->offsetRange)) {
            $type->setOffsetRange(FHIRRange::xmlUnserialize($children->offsetRange));
        }
        if (isset($children->relationship)) {
            $type->setRelationship(FHIRActionRelationshipType::xmlUnserialize($children->relationship));
        }
        return $type;
    }

    /**
     * @param null|\SimpleXMLElement $sxe
     * @param null|int $libxmlOpts
     * @return \SimpleXMLElement
     */
    public function xmlSerialize(\SimpleXMLElement $sxe = null, $libxmlOpts = 591872)
    {
        if (null === $sxe) {
            $sxe = new \SimpleXMLElement($this->_getFHIRXMLElementDefinition(), $libxmlOpts, false);
        }
        parent::xmlSerialize($sxe);
        if (null !== ($v = $this->getActionId())) {
            $v->xmlSerialize($sxe->addChild(self::FIELD_ACTION_ID, null, $v->_getFHIRXMLNamespace()));
        }
        if (null !== ($v = $this->getOffsetDuration())) {
            $v->xmlSerialize($sxe->addChild(self::FIELD_OFFSET_DURATION, null, $v->_getFHIRXMLNamespace()));
        }
        if (null !== ($v = $this->getOffsetRange())) {
            $v->xmlSerialize($sxe->addChild(self::FIELD_OFFSET_RANGE, null, $v->_getFHIRXMLNamespace()));
        }
        if (null !== ($v = $this->getRelationship())) {
            $v->xmlSerialize($sxe->addChild(self::FIELD_RELATIONSHIP, null, $v->_getFHIRXMLNamespace()));
        }
        return $sxe;
    }

    /**
     * @return array
     */
    public function jsonSerialize()
    {
        $a = parent::jsonSerialize();
        if (null !== ($v = $this->getActionId())) {
            $a[self::FIELD_ACTION_ID] = $v->getValue();
            $enc = $v->jsonSerialize();
            $cnt = count($enc);
            if (0 < $cnt && (1 !== $cnt || (1 === $cnt && !array_key_exists(FHIRId::FIELD_VALUE, $enc)))) {
                unset($enc[FHIRId::FIELD_VALUE]);
                $a[self::FIELD_ACTION_ID_EXT] = $enc;
            }
        }
        if (null !== ($v = $this->getOffsetDuration())) {
            $a[self::FIELD_OFFSET_DURATION] = $v;
        }
        if (null !== ($v = $this->getOffsetRange())) {
            $a[self::FIELD_OFFSET_RANGE] = $v;
        }
        if (null !== ($v = $this->getRelationship())) {
            $a[self::FIELD_RELATIONSHIP] = $v->getValue();
            $enc = $v->jsonSerialize();
            $cnt = count($enc);
            if (0 < $cnt && (1 !== $cnt || (1 === $cnt && !array_key_exists(FHIRActionRelationshipType::FIELD_VALUE, $enc)))) {
                unset($enc[FHIRActionRelationshipType::FIELD_VALUE]);
                $a[self::FIELD_RELATIONSHIP_EXT] = $enc;
            }
        }
        if ([] !== ($vs = $this->_getFHIRComments())) {
            $a[PHPFHIRConstants::JSON_FIELD_FHIR_COMMENTS] = $vs;
        }
        return $a;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return self::FHIR_TYPE_NAME;
    }
}


text:
#include <string>
#include <netinet/in.h>

#include "ts/ts.h"
#include "lulu.h"

// Helper function to cleanly get the IP as a string.
char *
getIP(sockaddr const *s_sockaddr, char res[INET6_ADDRSTRLEN])
{
  res[0] = '\0';

  if (s_sockaddr == nullptr) {
    return nullptr;
  }

  // This is a little kludgy, but the TS APIs that returns sockadd's don't return
  // nullptr's in general (it seems). Maybe that should be fixed, or maybe we should
  // export lib/ts/ink_inet.h as C APIs... (according to amc). But without this check,
  // we get ::1 even when the sockaddr isn't populated (e.g. server addr on a cache hit).
  if (AF_UNSPEC == s_sockaddr->sa_family) {
    return nullptr;
  }

  switch (s_sockaddr->sa_family) {
  case AF_INET: {
    const struct sockaddr_in *s_sockaddr_in = reinterpret_cast<const struct sockaddr_in *>(s_sockaddr);
    inet_ntop(AF_INET, &s_sockaddr_in->sin_addr, res, INET_ADDRSTRLEN);
  } break;
  case AF_INET6: {
    const struct sockaddr_in6 *s_sockaddr_in6 = reinterpret_cast<const struct sockaddr_in6 *>(s_sockaddr);
    inet_ntop(AF_INET6, &s_sockaddr_in6->sin6_addr, res, INET6_ADDRSTRLEN);
  } break;
  }

  return res[0] ? res : nullptr;
}

// Return it as a std::string instead (more expensive, but sometimes convenient)
std::string
getIP(sockaddr const *s_sockaddr)
{
  char res[INET6_ADDRSTRLEN] = {'\0'};

  if (getIP(s_sockaddr, res)) {
    return res;
  }

  return "";
}

// Returns the port of a sockaddr
uint16_t
getPort(sockaddr const *s_sockaddr)
{
  if (!s_sockaddr) {
    return 0;
  }

  switch (s_sockaddr->sa_family) {
  case AF_INET: {
    const struct sockaddr_in *s_sockaddr_in = reinterpret_cast<const struct sockaddr_in *>(s_sockaddr);
    return ntohs(s_sockaddr_in->sin_port);
  } break;
  case AF_INET6: {
    const struct sockaddr_in6 *s_sockaddr_in6 = reinterpret_cast<const struct sockaddr_in6 *>(s_sockaddr);
    return ntohs(s_sockaddr_in6->sin6_port);
  } break;
  default:
    return 0;
    break;
  }
}


text:
package org.dictionary.repository;

import org.dictionary.domain.Language;

public interface LanguageRepositoryCustom {

    Language findByLanguage(String language);

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace DoIt.Controls
{
    //Hilfsklasse die folgendes Problem verhindert:
    //Zu schnelles auf App Bar Hämmern, Mehr als eine MessageBox offen.
    //http://porcupineprogrammer.blogspot.de/2012/02/messagebox-crash-on-windows-phone-7.html
    internal static class SafeMessageBox
    {
        private static bool isMessageBoxOpen = false;
        internal static MessageBoxResult Show(string message, string title)
        {
            if (!isMessageBoxOpen)
            {
                isMessageBoxOpen = true;
                var result = MessageBox.Show(message, title, MessageBoxButton.OK);
                isMessageBoxOpen = false;
                return result;
            }
            else
                return MessageBoxResult.Cancel;
        }
    }
}


text:
package com.hxxc.huaxing.app.ui.search;

public class SortModel {

    private String name;   //显示的数据
    private String sortLetters;  //显示数据拼音的首字母

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSortLetters() {
        return sortLetters;
    }
    public void setSortLetters(String sortLetters) {
        this.sortLetters = sortLetters;
    }

    @Override
    public String toString() {
        return "SortModel{" +
                "name='" + name + '\'' +
                ", sortLetters='" + sortLetters + '\'' +
                '}';
    }
}


text:
package com.huawei.esdk.uc.professional.local.bean;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

import com.huawei.esdk.uc.professional.local.impl.autogen.Adapter3;

/**
 *
Java class for JoinGroupInfo complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="JoinGroupInfo">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="ucAccount" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="status" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *         <element name="groupInfoBase" type="{esdk_uc_professional_server}GroupInfoBase"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "JoinGroupInfo", propOrder = {
    "ucAccount",
    "status",
    "groupInfoBase"
})
public class JoinGroupInfo {

    @XmlElement(required = true)
    protected String ucAccount = "";
    @XmlElement(required = true, type = String.class)
    @XmlJavaTypeAdapter(Adapter3 .class)
    @XmlSchemaType(name = "int")
    protected Integer status;
    @XmlElement(required = true)
    protected GroupInfoBase groupInfoBase;

    /**
     * Gets the value of the ucAccount property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getUcAccount() {
        return ucAccount;
    }

    /**
     * Sets the value of the ucAccount property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setUcAccount(String value) {
        this.ucAccount = value;
    }

    /**
     * Gets the value of the status property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public Integer getStatus() {
        return status;
    }

    /**
     * Sets the value of the status property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setStatus(Integer value) {
        this.status = value;
    }

    /**
     * Gets the value of the groupInfoBase property.
     *
     * @return
     *     possible object is
     *     {@link GroupInfoBase }
     *
     */
    public GroupInfoBase getGroupInfoBase() {
        return groupInfoBase;
    }

    /**
     * Sets the value of the groupInfoBase property.
     *
     * @param value
     *     allowed object is
     *     {@link GroupInfoBase }
     *
     */
    public void setGroupInfoBase(GroupInfoBase value) {
        this.groupInfoBase = value;
    }

}


text:
Biochem Explorer

Found {{totalFound}} compound {{totalFounnd.length > 1 ? 'matches' : 'match'}} for {{cpd.name}}

{{cpd.name}} | {{cpd.id}} | {{cpd.formula}} | {{cpd.abbreviation}}

{{cpd.name}} is present in

    {{reactionCount}} reactions | {{substrateCount}} substrates | {{productCount}} products

        <md-input-container md-no-float flex="45"
            search="opts.query" search-opts="opts" search-placeholder="Search reactions that have {{cpd.name}}">
        </md-input-container>

        <md-progress-circular ng-if="loading"
                              md-mode="indeterminate"
                              class="table-loading"
                              md-diameter="20">
        </md-progress-circular>

        <md-input-container pagination
            pagination-offset="opts.offset"
            pagination-limit="opts.limit"
            pagination-total="filtered.length"
            layout="row"
            layout-align="end center" flex>
        </md-input-container>

            Name
            ID
            EQ

            {{::rxn.name}}
            {{::rxn.id}}


text:
namespace glassfactory.Areas.HelpPage.ModelDescriptions
{
    public class CollectionModelDescription : ModelDescription
    {
        public ModelDescription ElementDescription { get; set; }
    }
}


text:
require 'base64'
require 'net/http'

module Onyx
  class Client
    class << self
      def index(key, string_file)
        settings = Onyx::Configuration.settings
        response = Net::HTTP.start(settings[:host], settings[:port]) do |http|
          request = Net::HTTP::Put.new(settings[:path])
          params = { key: key, image: string_file }
          request.body = params.to_json
          http.request(request)
        end
        JSON.parse(response.body, :symbolize_names => true)
      end

      def search(string_file)
        settings = Onyx::Configuration.settings
        response = Net::HTTP.start(settings[:host], settings[:port]) do |http|
          request = Net::HTTP::Post.new(settings[:path])
          params = { image: string_file }
          request.body = params.to_json
          http.request(request)
        end
        JSON.parse(response.body, :symbolize_names => true)
      end

      def delete(key)
        settings = Onyx::Configuration.settings
        response = Net::HTTP.start(settings[:host], settings[:port]) do |http|
          request = Net::HTTP::Delete.new(settings[:path])
          params = { key: key }
          request.body = params.to_json
          http.request(request)
        end
        JSON.parse(response.body, :symbolize_names => true)
      end
    end
  end
end


text:
"""Fetch GitHub pull requests from SQS, process with jekyll, publish to Amazon S3."""

import json, os, random, string, subprocess

import yaml, boto.sqs, requests

# Convenience

chars = string.lowercase + string.digits
def generate_name(n):
    """Generate random name of length n."""
    return str.join("", [random.sample(chars, 1)[0] for _ in range(n)])

# Load config

config = yaml.load(open("config.yaml", "r"))

# GitHub

github_headers = {
    "accept" : "application/vnd.github.v3+json",
    "authorization" : "token %s" % config["github"]["token"],
}

def comment(url, text, sha = None):
    """Post a GitHub comment."""
    content = { "body" : text }
    if sha:
        content["sha"] = sha
    requests.post(url, headers=github_headers, data=json.dumps(content))

# SQS

sqs = boto.sqs.connect_to_region(config["sqs"]["region"],
                                 aws_access_key_id=config["sqs"]["access"],
                                 aws_secret_access_key=config["sqs"]["secret"])

queue = sqs.get_queue(config["sqs"]["queue"])

# S3

s3 = boto.connect_s3(aws_access_key_id=config["s3"]["access"],
                     aws_secret_access_key=config["s3"]["secret"])
s3_bucket = s3.get_bucket(config["s3"]["bucket"])

def publish(bucket, prefix, site):
    """Publish jekyll output to S3."""
    chop = len(site) + 1
    for entry in os.walk(site):
        for filename in entry[2]:
            src_name = (entry[0] + "/" + filename)
            dst_name = src_name[chop:]
            key = bucket.new_key(prefix + dst_name)
            key.set_contents_from_filename(src_name, policy="public-read", reduced_redundancy=True)

# Environment

os.environ["PATH"] += ":."

base = os.getcwd()
os.environ["GIT_SSH"] = base + "/git-ssh.sh"

if config["github"]["deploy"].startswith("/"):
    os.environ["SSH_KEY"] = config["github"]["deploy"]
else:
    os.environ["SSH_KEY"] = base + "/" + config["github"]["deploy"]

# Check build directory

if not os.path.isdir(config["build_dir"]):
    print "Error: not a directory:", config["build_dir"]
    exit(1)

# Poll forever

while True:
    msgs = queue.get_messages()
    if msgs is not None:
        for msg in msgs:
            body = json.loads(msg.get_body())
            msg.delete() # regardless of success or failure

            is_pull = False
            commit_id = None

            if "pull_request" in body:
                is_pull = True
                pull = body["pull_request"]
                comments = pull["comments_url"]

                if pull["merged"]:
                    comment(comments, ":clap:")
                    continue
                elif pull["state"] == "closed":
                    continue
            elif "head_commit" in body:
                commit = body["head_commit"]
                commit_id = commit["id"]
                comments = body["repository"]["commits_url"].replace("{/sha}", "/%s/comments" % commit["id"])
            else:
                continue

            git_url = body["repository"]["ssh_url"]
            random_name = generate_name(10)
            build_dir = config["build_dir"] + "/" + random_name

            if is_pull:
                checkout = "pull/%i/head" % pull["number"]
            else:
                checkout = commit_id

            cmd = ["process.sh", git_url, checkout, build_dir]

            successful = subprocess.call(cmd) == 0
            if not successful:
                comment(comments, "Failed to generate site! :scream:", commit_id)
                os.rename(build_dir, build_dir + ".failed-preview")
            else:
                try:
                    publish(s3_bucket, random_name + "/", build_dir + "/_site")
                    comment(comments, "http://%s/%s" % (config["s3"]["bucket"], random_name), commit_id)
                    os.rename(build_dir, build_dir + ".published")
                except Exception as exception:
                    comment(comments, "Failed to publish jekyll output! :scream:", commit_id)
                    os.rename(build_dir, build_dir + ".failed-publish")


text:
package lila.slack

import akka.actor._
import com.typesafe.config.Config

import lila.common.PimpedConfig._
import lila.hub.actorApi.{ DonationEvent, Deploy, RemindDeployPre, RemindDeployPost }

final class Env(
    config: Config,
    getLightUser: String => Option[lila.common.LightUser],
    system: ActorSystem) {

  private val IncomingUrl = config getString "incoming.url"
  private val IncomingDefaultChannel = config getString "incoming.default_channel"

  lazy val api = new SlackApi(client, getLightUser)

  private lazy val client = new SlackClient(
    url = IncomingUrl,
    defaultChannel = IncomingDefaultChannel)

  system.actorOf(Props(new Actor {
    override def preStart() {
      system.lilaBus.subscribe(self, 'donation, 'deploy)
    }
    def receive = {
      case d: DonationEvent            => api donation d
      case Deploy(RemindDeployPre, _)  => api.deployPre
      case Deploy(RemindDeployPost, _) => api.deployPost
    }
  }))
}

object Env {

  lazy val current: Env = "slack" boot new Env(
    system = lila.common.PlayApp.system,
    getLightUser = lila.user.Env.current.lightUser,
    config = lila.common.PlayApp loadConfig "slack")
}


text:
package hudson.plugins.scm.koji;

import hudson.util.FormValidation;

import org.fakekoji.xmlrpc.server.JavaServerConstants;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static hudson.plugins.scm.koji.KojiBuildProvider.KojiBuildProviderDescriptor;

public class KojiBuildProviderDescriptorTest {

    @Test
    public void simpelValidValue() {
        final KojiBuildProviderDescriptor descriptor = new KojiBuildProviderDescriptor();
        FormValidation r1 = descriptor.doCheckDownloadUrl("http://aaa.cz");
        FormValidation r2 = descriptor.doCheckTopUrl("http:///bbb.com");
        assertEquals(FormValidation.Kind.OK, r1.kind);
        assertEquals(FormValidation.Kind.OK, r2.kind);
    }

    @Test
    public void simpelInValidValue1() {
        final KojiBuildProviderDescriptor descriptor = new KojiBuildProviderDescriptor();
        FormValidation r = descriptor.doCheckDownloadUrl("blah");
        assertEquals(FormValidation.Kind.ERROR, r.kind);
    }

    @Test
    public void simpelInValidValue2() {
        final KojiBuildProviderDescriptor descriptor = new KojiBuildProviderDescriptor();
        FormValidation r = descriptor.doCheckTopUrl("blah");
        assertEquals(FormValidation.Kind.ERROR, r.kind);
    }

    @Test
    public void advacnedValidValue() {
        final KojiBuildProviderDescriptor descriptor = new KojiBuildProviderDescriptor();
        FormValidation r1 = descriptor.doCheckDownloadUrl("http://aaa.cz:"+ JavaServerConstants.DFAULT_DWNLD_PORT +"/bbb");
        FormValidation r2 = descriptor.doCheckTopUrl("http:///bbb.com:XPORT");
        assertEquals(FormValidation.Kind.OK, r1.kind);
        assertEquals(FormValidation.Kind.OK, r2.kind);
    }

    @Test
    public void advacnedValidValues() {
        final KojiBuildProviderDescriptor descriptor = new KojiBuildProviderDescriptor();
        FormValidation r1 = descriptor.doCheckDownloadUrl("http://aaa.cz http://aaa.cz:"+JavaServerConstants.DFAULT_DWNLD_PORT);
        FormValidation r2 = descriptor.doCheckTopUrl("http://aaa.cz http:///bbb.com:"+JavaServerConstants.DFAULT_RP2C_PORT+"/aaa");
        assertEquals(FormValidation.Kind.OK, r1.kind);
        assertEquals(FormValidation.Kind.OK, r2.kind);
    }

    public void advacnedInvalidValues1() {
        final KojiBuildProviderDescriptor descriptor = new KojiBuildProviderDescriptor();
        FormValidation r1 = descriptor.doCheckDownloadUrl("http://aaa.cz aaa");
        assertEquals(FormValidation.Kind.OK, r1.kind);
    }

    public void advacnedInvalidValues2() {
        final KojiBuildProviderDescriptor descriptor = new KojiBuildProviderDescriptor();
        FormValidation r2 = descriptor.doCheckTopUrl("http://aaa.cz aaa");
        assertEquals(FormValidation.Kind.OK, r2.kind);
    }

    public void advacnedInvalidValues3() {
        final KojiBuildProviderDescriptor descriptor = new KojiBuildProviderDescriptor();
        FormValidation r1 = descriptor.doCheckDownloadUrl("bbb http://aaa.cz");
        assertEquals(FormValidation.Kind.OK, r1.kind);
    }

    public void advacnedInvalidValues4() {
        final KojiBuildProviderDescriptor descriptor = new KojiBuildProviderDescriptor();
        FormValidation r2 = descriptor.doCheckTopUrl("ccc http://aaa.cz");
        assertEquals(FormValidation.Kind.OK, r2.kind);
    }

    public void advacnedHidenInvalidValues() {
        final KojiBuildProviderDescriptor descriptor = new KojiBuildProviderDescriptor();
        FormValidation r2 = descriptor.doCheckTopUrl("http://aaa.cz:DPORTbad");
        assertEquals(FormValidation.Kind.ERROR, r2.kind);
    }

}