text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.service.duper;

import com.yahoo.vespa.service.monitor.CriticalRegion;

import java.util.ArrayList;
import java.util.List;

/**
 * To detect and throw an {@link IllegalStateException} if the execution of the current thread has
 * reached code point P, some time after the start of a critical region R and before the end of it:
 *
 *

 *
Declare a static final instance of {@link CriticalRegionChecker}.

 *
Invoke {@link #startCriticalRegion(String)} when entering region R, and close
 *     the returned {@link CriticalRegion} when leaving it.

 *
Invoke {@link #assertOutsideCriticalRegions(String)} at code point P.

 *

 *
 * @author hakonhall
 */
public class CriticalRegionChecker {

    private final ThreadLocalDescriptions threadLocalDescriptions = new ThreadLocalDescriptions();
    private final String name;

    public CriticalRegionChecker(String name) {
        this.name = name;
    }

    /** Start of the critical region, within which {@link #assertOutsideCriticalRegions(String)} will throw. */
    public CriticalRegion startCriticalRegion(String regionDescription) {
        List<String> regionDescriptions = threadLocalDescriptions.get();
        regionDescriptions.add(regionDescription);
        Thread threadAtStart = Thread.currentThread();

        return () -> {
            regionDescriptions.remove(regionDescription);

            Thread treadAtClose = Thread.currentThread();
            if (threadAtStart != treadAtClose) {
                throw new IllegalStateException(name + ": A critical region cannot cross threads: " +
                        regionDescription);
            }
        };
    }

    /** @throws IllegalStateException if within one or more critical regions. */
    public void assertOutsideCriticalRegions(String codePointDescription) throws IllegalStateException {
        List<String> regionDescriptions = threadLocalDescriptions.get();
        if (regionDescriptions.size() > 0) {
            throw new IllegalStateException(name + ": Code point " + codePointDescription +
                    " is within these critical regions: " + regionDescriptions);
        }
    }

    private static class ThreadLocalDescriptions extends ThreadLocal<List<String>> {
        @Override
        protected List<String> initialValue() {
            return new ArrayList<>();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate;
using NHibernate.Linq;
using ThinkingHome.Core.Plugins.Utils;
using ThinkingHome.Plugins.Listener.Api;
using ThinkingHome.Plugins.Listener.Attributes;
using ThinkingHome.Plugins.UniUI.Model;
using ThinkingHome.Plugins.UniUI.Widgets;

namespace ThinkingHome.Plugins.UniUI
{
	public partial class UniUiPlugin
	{
		[HttpCommand("/api/uniui/dashboard/list")]
		public object GetDashboardList(HttpRequestParams request)
		{
			using (var session = Context.OpenSession())
			{
				var allDashboards = session.Query<Dashboard>().ToArray();

				var list = GetDashboardListModel(allDashboards);

				return list;
			}
		}

		[HttpCommand("/api/uniui/dashboard/create")]
		public object CreateDashboard(HttpRequestParams request)
		{
			string title = request.GetRequiredString("title");

			using (var session = Context.OpenSession())
			{
				var dashboard = new Dashboard
				{
					Id = Guid.NewGuid(),
					Title = title,
					SortOrder = int.MaxValue
				};

				session.Save(dashboard);
				session.Flush();

				return dashboard.Id;
			}
		}

		[HttpCommand("/api/uniui/dashboard/delete")]
		public object DeleteDashboard(HttpRequestParams request)
		{
			Guid id = request.GetRequiredGuid("id");

			using (var session = Context.OpenSession())
			{
				var dashboard = session.Get<Dashboard>(id);

				if (dashboard != null)
				{
					session.Delete(dashboard);
					session.Flush();
				}
			}

			return null;
		}

		[HttpCommand("/api/uniui/dashboard/details")]
		public object GetDashboardDetails(HttpRequestParams request)
		{
			Guid? id = request.GetGuid("id");

			using (var session = Context.OpenSession())
			{
				var allDashboards = session.Query<Dashboard>().ToArray();

				if (allDashboards.Any())
				{
					var selected = id.HasValue
						? allDashboards.Single(d => d.Id == id.Value)
						: allDashboards.First();

					var dashboardList = GetDashboardListModel(allDashboards, selected.Id);

					var allPanels = session.Query<Panel>()
						.Where(w => w.Dashboard.Id == selected.Id)
						.ToArray();

					var allWidgets = session.Query<Widget>()
						.Where(w => w.Panel.Dashboard.Id == selected.Id)
						.ToArray();

					var allParameters = session.Query<WidgetParameter>()
						.Where(w => w.Widget.Panel.Dashboard.Id == selected.Id)
						.ToArray();

					var panelList = GetPanelListModel(allPanels, allWidgets, allParameters, session);

					return new
					{
						dashboards = dashboardList,
						panels = panelList
					};
				}

				return null;
			}
		}

		private object[] GetDashboardListModel(Dashboard[] allDashboards, Guid? activeId = null)
		{
			var model = allDashboards
					.Select(x => (object)new
					{
						id = x.Id,
						title = x.Title,
						sortOrder = x.SortOrder,
						active = activeId == x.Id
					})
					.ToArray();

			return model;
		}

		private object[] GetPanelListModel(Panel[] allPanels, Widget[] allWidgets, WidgetParameter[] allParameters, ISession session)
		{
			var list = new List<object>();

			foreach (var panel in allPanels)
			{
				var panelWidgets = allWidgets.Where(w => w.Panel.Id == panel.Id).ToArray();
				var widgetListModel = GetWidgetListModel(panelWidgets, allParameters, session);

				var model = new {
					id = panel.Id,
					title = panel.Title,
					widgets = widgetListModel,
					sortOrder = panel.SortOrder
				};

				list.Add(model);
			}

			return list.ToArray();
		}

		private object[] GetWidgetListModel(Widget[] panelWidgets, WidgetParameter[] allParameters, ISession session)
		{
			var list = new List<object>();

			foreach (var widget in panelWidgets)
			{
				var def = defs.GetValueOrDefault(widget.TypeAlias);

				if (def != null)
				{
					var parameters = allParameters.Where(p => p.Widget.Id == widget.Id).ToArray();

					var model = GetWidgetModel(def, widget, parameters, session);

					if (model != null)
					{
						list.Add(model);
					}
				}
			}
			return list.ToArray();
		}

		/// <summary>
		/// Подготовка модели для отображения виджета в интерфейсе
		/// </summary>
		/// <param name="def">Определение виджета</param>
		/// <param name="widget">Данные об экземпляре виджета</param>
		/// <param name="parameters">Параметры виджета</param>
		/// <param name="session">Сессия БД</param>
		private object GetWidgetModel(IWidgetDefinition def, Widget widget, WidgetParameter[] parameters, ISession session)
		{
			try
			{
				var data = def.GetWidgetData(widget, parameters, session, Logger);

				var model = new
				{
					id = widget.Id,
					type = widget.TypeAlias,
					displayName = widget.DisplayName,
					sortOrder = widget.SortOrder,
					data
				};

				return model;
			}
			catch (Exception ex)
			{
				var message = string.Format(
					"UI widget error (id: {0}, type:{1})", widget.Id, widget.TypeAlias);
				Logger.ErrorException(message, ex);

				return null;
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/monitoring/v3/service_service.proto

package com.google.monitoring.v3;

public interface ListServiceLevelObjectivesResponseOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.monitoring.v3.ListServiceLevelObjectivesResponse)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * The `ServiceLevelObjective`s matching the specified filter.
   *

   *
   * repeated .google.monitoring.v3.ServiceLevelObjective service_level_objectives = 1;
   */
  java.util.List<com.google.monitoring.v3.ServiceLevelObjective> getServiceLevelObjectivesList();
  /**
   *
   *
   *

   * The `ServiceLevelObjective`s matching the specified filter.
   *

   *
   * repeated .google.monitoring.v3.ServiceLevelObjective service_level_objectives = 1;
   */
  com.google.monitoring.v3.ServiceLevelObjective getServiceLevelObjectives(int index);
  /**
   *
   *
   *

   * The `ServiceLevelObjective`s matching the specified filter.
   *

   *
   * repeated .google.monitoring.v3.ServiceLevelObjective service_level_objectives = 1;
   */
  int getServiceLevelObjectivesCount();
  /**
   *
   *
   *

   * The `ServiceLevelObjective`s matching the specified filter.
   *

   *
   * repeated .google.monitoring.v3.ServiceLevelObjective service_level_objectives = 1;
   */
  java.util.List<? extends com.google.monitoring.v3.ServiceLevelObjectiveOrBuilder>
      getServiceLevelObjectivesOrBuilderList();
  /**
   *
   *
   *

   * The `ServiceLevelObjective`s matching the specified filter.
   *

   *
   * repeated .google.monitoring.v3.ServiceLevelObjective service_level_objectives = 1;
   */
  com.google.monitoring.v3.ServiceLevelObjectiveOrBuilder getServiceLevelObjectivesOrBuilder(
      int index);

  /**
   *
   *
   *

   * If there are more results than have been returned, then this field is set
   * to a non-empty value.  To see the additional results,
   * use that value as `page_token` in the next call to this method.
   *

   *
   * string next_page_token = 2;
   *
   * @return The nextPageToken.
   */
  java.lang.String getNextPageToken();
  /**
   *
   *
   *

   * If there are more results than have been returned, then this field is set
   * to a non-empty value.  To see the additional results,
   * use that value as `page_token` in the next call to this method.
   *

   *
   * string next_page_token = 2;
   *
   * @return The bytes for nextPageToken.
   */
  com.google.protobuf.ByteString getNextPageTokenBytes();
}


text:
'use strict';

// TODO(cpojer): Create a jest-types repo.


text:
#if !defined(AFX_CLIENTDLG_H__394E27A3_F161_11D1_BBFE_0000E8DB52FA__INCLUDED_)
#define AFX_CLIENTDLG_H__394E27A3_F161_11D1_BBFE_0000E8DB52FA__INCLUDED_

#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000

class CClientSocket;
/////////////////////////////////////////////////////////////////////////////
// CClientDlg dialog

class CClientDlg : public CDialog
{
// Construction
public:
	CClientDlg(CWnd* pParent = NULL);	// standard constructor

// Dialog Data
	//{{AFX_DATA(CClientDlg)
	enum { IDD = IDD_CLIENT_DIALOG };
	CButton	m_SendButton;
	CButton	m_DisconnectButton;
	CButton	m_ConnectButton;
	CString	m_Reply;
	CString	m_Message;
	CString	m_Address;
	UINT	m_Port;
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CClientDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);	// DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	HICON m_hIcon;

public:
	CClientSocket* m_pClientSocket;
	void DisplayReply(LPCTSTR szText);
	void Enable(CButton& button);
	void Disable(CButton& button);

	// Generated message map functions
	//{{AFX_MSG(CClientDlg)
	virtual BOOL OnInitDialog();
	afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
	afx_msg void OnPaint();
	afx_msg HCURSOR OnQueryDragIcon();
	afx_msg void OnSend();
	afx_msg void OnDestroy();
	afx_msg void OnConnect();
	afx_msg void OnDisconnect();
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_CLIENTDLG_H__394E27A3_F161_11D1_BBFE_0000E8DB52FA__INCLUDED_)


text:
using ustring = std::basic_string<unsigned char>;

class xml_document {
public:
  struct ParseResult {
    bool eof = false;
    bool has_error = false;
    std::string error_message;
    const unsigned char *rest = nullptr;
  };

  template <int flags>
  ParseResult parse(unsigned char *text, xml_document &parent) {
    return with_error_handling(
        [&] { return impl.parse<flags>(text, parent.impl); });
  }

  template <int flags> ParseResult parse(unsigned char *text) {
    return with_error_handling([&] { return impl.parse<flags>(text); });
  }

  const void clear() { impl.clear(); }

  rapidxml::xml_document<unsigned char> impl;

private:
  template <typename F> ParseResult with_error_handling(F &&f) {
    ParseResult result;
    try {
      result.rest = std::forward<F>(f)();
    } catch (const rapidxml::eof_error &e) {
      result.eof = true;
      result.has_error = true;
      result.error_message = e.what();
    } catch (const rapidxml::parse_error &e) {
      result.has_error = true;
      result.error_message = e.what();
    }
    return result;
  }
};

namespace {
  ERL_NIF_TERM atom_ok;
  ERL_NIF_TERM atom_error;
  ERL_NIF_TERM atom_undefined;
  ERL_NIF_TERM atom_xmlel;
  ERL_NIF_TERM atom_xmlcdata;
  ERL_NIF_TERM atom_xmlstreamstart;
  ERL_NIF_TERM atom_xmlstreamend;
  ERL_NIF_TERM atom_pretty;
  ERL_NIF_TERM atom_true;
  constexpr const unsigned char EMPTY[1] = {0};

  xml_document &get_static_doc() {
    static thread_local xml_document doc;
    doc.clear();
    return doc;
  }

} // namespace

struct Parser {
  ustring stream_tag;
  std::uint64_t max_child_size = 0;
  bool infinite_stream = false;

  static thread_local std::vector<unsigned char> buffer;
  static thread_local std::vector<ERL_NIF_TERM> term_buffer;

  bool copy_buffer(ErlNifEnv *env, ERL_NIF_TERM buf) {
    buffer.clear();

    ErlNifBinary bin;
    if (enif_inspect_binary(env, buf, &bin)) {
      buffer.insert(buffer.end(), bin.data, bin.data + bin.size);
    } else if (enif_is_list(env, buf)) {
      for (ERL_NIF_TERM head; enif_get_list_cell(env, buf, &head, &buf);) {
        if (!enif_inspect_binary(env, head, &bin))
          return false;

        buffer.insert(buffer.end(), bin.data, bin.data + bin.size);
      }
    } else {
      return false;
    }

    buffer.push_back('\0');
    return true;
  }

  void reset() {
    stream_tag.clear();
    buffer.clear();
  }
};

thread_local std::vector<unsigned char> Parser::buffer;
thread_local std::vector<ERL_NIF_TERM> Parser::term_buffer;

struct ParseCtx {
  ErlNifEnv *env;
  Parser *parser;
};

namespace {
ErlNifResourceType *parser_type;

constexpr int default_parse_flags() {
  return rapidxml::parse_no_string_terminators | rapidxml::parse_validate_control_chars;
}

constexpr int parse_one() {
  return rapidxml::parse_parse_one | default_parse_flags();
}

constexpr int parse_open_only() {
  return rapidxml::parse_open_only | default_parse_flags();
}

ERL_NIF_TERM to_subbinary(ParseCtx &ctx, const unsigned char *text,
                          std::size_t len) {
  ERL_NIF_TERM binary;
  unsigned char *bin_data = enif_make_new_binary(ctx.env, len, &binary);
  std::copy(text, text + len, bin_data);
  return binary;
}

ERL_NIF_TERM make_attr_tuple(ParseCtx &ctx,
                             rapidxml::xml_attribute<unsigned char> *attr) {
  ERL_NIF_TERM name = to_subbinary(ctx, attr->name(), attr->name_size());
  ERL_NIF_TERM value = to_subbinary(ctx, attr->value(), attr->value_size());
  return enif_make_tuple2(ctx.env, name, value);
}

ERL_NIF_TERM get_xmlcdata(ParseCtx &ctx,
                          rapidxml::xml_node<unsigned char> *node) {
  return enif_make_tuple2(ctx.env, atom_xmlcdata,
                          to_subbinary(ctx, node->value(), node->value_size()));
}

ERL_NIF_TERM merge_data_nodes(ParseCtx &ctx,
                              rapidxml::xml_node<unsigned char> *node,
                              std::size_t total_size) {
  ERL_NIF_TERM bin;
  unsigned char *it = enif_make_new_binary(ctx.env, total_size, &bin);

  while (total_size > 0) {
    it = std::copy(node->value(), node->value() + node->value_size(), it);
    total_size -= node->value_size();
    node = node->next_sibling();
  }

  return enif_make_tuple2(ctx.env, atom_xmlcdata, bin);
}

void append_pending_data_nodes(ParseCtx &ctx,
                               std::vector<ERL_NIF_TERM> &children,
                               rapidxml::xml_node<unsigned char> *node,
                               const std::size_t pending) {
  if (pending == 0)
    return;

  if (pending == node->value_size())
    children.push_back(get_xmlcdata(ctx, node));
  else
    children.push_back(merge_data_nodes(ctx, node, pending));
}

ERL_NIF_TERM make_xmlel(ParseCtx &ctx, rapidxml::xml_node<unsigned char> *node);

ERL_NIF_TERM get_children_tuple(ParseCtx &ctx,
                                rapidxml::xml_node<unsigned char> *node) {
  std::vector<ERL_NIF_TERM> &children = Parser::term_buffer;
  std::size_t begin = children.size();

  rapidxml::xml_node<unsigned char> *first_data_node = nullptr;
  std::size_t pending_data_size = 0;

  for (rapidxml::xml_node<unsigned char> *child = node->first_node(); child;
       child = child->next_sibling()) {
    const bool is_data_node = child->type() == rapidxml::node_data ||
                              child->type() == rapidxml::node_cdata;

    if (is_data_node) {
      if (pending_data_size == 0)
        first_data_node = child;
      pending_data_size += child->value_size();
    } else {
      append_pending_data_nodes(ctx, children, first_data_node,
                                pending_data_size);
      pending_data_size = 0;
      if (child->type() == rapidxml::node_element)
        children.push_back(make_xmlel(ctx, child));
    }
  }

  append_pending_data_nodes(ctx, children, first_data_node, pending_data_size);

  std::size_t size = children.size() - begin;
  if (size == 0)
    return enif_make_list(ctx.env, 0);

  ERL_NIF_TERM arr =
      enif_make_list_from_array(ctx.env, children.data() + begin, size);
  children.erase(children.end() - size, children.end());
  return arr;
}

std::pair<const unsigned char *, std::size_t>
node_name(rapidxml::xml_node<unsigned char> *node) {
  const unsigned char *start = node->name();
  std::size_t len = node->name_size();
  if (node->prefix()) {
    start = node->prefix();
    len += node->prefix_size() + 1;
  }
  return {start, len};
}

ERL_NIF_TERM make_node_name_binary(ParseCtx &ctx,
                                   rapidxml::xml_node<unsigned char> *node) {
  const unsigned char *start;
  std::size_t len;
  std::tie(start, len) = node_name(node);
  return to_subbinary(ctx, start, len);
}

std::tuple<ERL_NIF_TERM, ERL_NIF_TERM>
get_open_tag(ParseCtx &ctx, rapidxml::xml_node<unsigned char> *node) {
  ERL_NIF_TERM name_term = make_node_name_binary(ctx, node);
  std::vector<ERL_NIF_TERM> &attrs = Parser::term_buffer;
  std::size_t begin = attrs.size();

  for (rapidxml::xml_attribute<unsigned char> *attr = node->first_attribute();
       attr; attr = attr->next_attribute())
    attrs.push_back(make_attr_tuple(ctx, attr));

  std::size_t size = attrs.size() - begin;
  ERL_NIF_TERM attrs_term =
      size == 0
          ? enif_make_list(ctx.env, 0)
          : enif_make_list_from_array(ctx.env, attrs.data() + begin, size);

  attrs.erase(attrs.end() - size, attrs.end());
  return std::make_tuple(name_term, attrs_term);
}

ERL_NIF_TERM make_stream_start_tuple(ParseCtx &ctx,
                                     rapidxml::xml_node<unsigned char> *node) {
  auto name_and_attrs = get_open_tag(ctx, node);
  return enif_make_tuple3(ctx.env, atom_xmlstreamstart, std::get<0>(name_and_attrs),
                          std::get<1>(name_and_attrs));
}

ERL_NIF_TERM make_stream_end_tuple(ParseCtx &ctx) {
  ERL_NIF_TERM name;
  unsigned char *data =
      enif_make_new_binary(ctx.env, ctx.parser->stream_tag.size(), &name);

  std::copy(ctx.parser->stream_tag.begin(), ctx.parser->stream_tag.end(), data);

  return enif_make_tuple2(ctx.env, atom_xmlstreamend, name);
}

ERL_NIF_TERM make_xmlel(ParseCtx &ctx,
                        rapidxml::xml_node<unsigned char> *node) {
  auto name_and_attrs = get_open_tag(ctx, node);
  ERL_NIF_TERM children_term = get_children_tuple(ctx, node);
  return enif_make_tuple4(ctx.env, atom_xmlel, std::get<0>(name_and_attrs),
                          std::get<1>(name_and_attrs), children_term);
}

bool build_children(ErlNifEnv *env, xml_document &doc, ERL_NIF_TERM children,
                    rapidxml::xml_node<unsigned char> &node);

bool build_cdata(ErlNifEnv *env, xml_document &doc, const ERL_NIF_TERM elem[],
                 rapidxml::xml_node<unsigned char> &node) {
  ErlNifBinary bin;
  if (!enif_inspect_iolist_as_binary(env, elem[1], &bin))
    return false;

  auto child = doc.impl.allocate_node(rapidxml::node_data);
  child->value(bin.size > 0 ? bin.data : EMPTY, bin.size);
  node.append_node(child);
  return true;
}

bool build_attrs(ErlNifEnv *env, xml_document &doc, ERL_NIF_TERM attrs,
                 rapidxml::xml_node<unsigned char> &node) {

  if (!enif_is_list(env, attrs))
    return false;

  for (ERL_NIF_TERM head; enif_get_list_cell(env, attrs, &head, &attrs);) {
    int arity;
    const ERL_NIF_TERM *tuple;
    if (!enif_get_tuple(env, head, &arity, &tuple) || arity != 2)
      return false;

    ErlNifBinary key, value;
    if (!enif_inspect_iolist_as_binary(env, tuple[0], &key))
      return false;

    if (!enif_inspect_iolist_as_binary(env, tuple[1], &value))
      return false;

    auto attr = doc.impl.allocate_attribute(key.size > 0 ? key.data : EMPTY,
                                            value.size > 0 ? value.data : EMPTY,
                                            key.size, value.size);
    node.append_attribute(attr);
  }

  return true;
}

bool build_el(ErlNifEnv *env, xml_document &doc, const ERL_NIF_TERM elem[],
              rapidxml::xml_node<unsigned char> &node) {
  ErlNifBinary name;
  if (!enif_inspect_iolist_as_binary(env, elem[1], &name))
    return false;

  auto child = doc.impl.allocate_node(rapidxml::node_element);
  child->name(name.size > 0 ? name.data : EMPTY, name.size);
  node.append_node(child);

  if (!build_attrs(env, doc, elem[2], *child))
    return false;
  if (!build_children(env, doc, elem[3], *child))
    return false;

  return true;
}

bool build_child(ErlNifEnv *env, xml_document &doc, ERL_NIF_TERM child,
                 rapidxml::xml_node<unsigned char> &node) {
  int arity;
  const ERL_NIF_TERM *tuple;
  if (!enif_get_tuple(env, child, &arity, &tuple))
    return false;

  if (arity == 2 && enif_compare(atom_xmlcdata, tuple[0]) == 0) {
    if (!build_cdata(env, doc, tuple, node))
      return false;
  } else if (arity == 4 && enif_compare(atom_xmlel, tuple[0]) == 0) {
    if (!build_el(env, doc, tuple, node))
      return false;
  } else {
    return false;
  }

  return true;
}

bool build_children(ErlNifEnv *env, xml_document &doc, ERL_NIF_TERM children,
                    rapidxml::xml_node<unsigned char> &node) {

  if (!enif_is_list(env, children))
    return false;

  for (ERL_NIF_TERM head;
       enif_get_list_cell(env, children, &head, &children);) {
    if (!build_child(env, doc, head, node))
      return false;
  }

  return true;
}

ERL_NIF_TERM node_to_binary(ErlNifEnv *env,
                            rapidxml::xml_node<unsigned char> &node,
                            int flags) {
  static thread_local std::vector<unsigned char> print_buffer;
  print_buffer.clear();

  rapidxml::print(std::back_inserter(print_buffer), node, flags);

  ERL_NIF_TERM ret_binary;
  unsigned char *data =
      enif_make_new_binary(env, print_buffer.size(), &ret_binary);
  std::copy(print_buffer.begin(), print_buffer.end(), data);
  return ret_binary;
}

std::size_t stream_closing_tag_size(Parser *parser) {
  return 3 + parser->stream_tag.size(); // name + </>
}

bool has_stream_closing_tag(Parser *parser, std::size_t offset) {
  if (Parser::buffer.size() < offset + stream_closing_tag_size(parser))
    return false;

  if (Parser::buffer[offset] != '<' || Parser::buffer[offset + 1] != '/')
    return false;

  if (!std::equal(parser->stream_tag.begin(), parser->stream_tag.end(),
                  Parser::buffer.begin() + offset + 2))
    return false;

  // skip whitespace between tag name and closing '>'
  offset = offset + 2 + parser->stream_tag.size();
  while (offset < Parser::buffer.size() - 1 &&
         std::isspace(Parser::buffer[offset]))
    ++offset;

  return Parser::buffer[offset] == '>';
}

} // namespace

extern "C" {
static void delete_parser(ErlNifEnv *env, void *parser) {
  static_cast<Parser *>(parser)->~Parser();
}

static int load(ErlNifEnv *env, void **priv_data, ERL_NIF_TERM load_info) {
  parser_type = enif_open_resource_type(
      env, "exml_nif", "parser", &delete_parser, ERL_NIF_RT_CREATE, nullptr);
  atom_ok = enif_make_atom(env, "ok");
  atom_error = enif_make_atom(env, "error");
  atom_undefined = enif_make_atom(env, "undefined");
  atom_xmlel = enif_make_atom(env, "xmlel");
  atom_xmlcdata = enif_make_atom(env, "xmlcdata");
  atom_xmlstreamstart = enif_make_atom(env, "xmlstreamstart");
  atom_xmlstreamend = enif_make_atom(env, "xmlstreamend");
  atom_pretty = enif_make_atom(env, "pretty");
  atom_true = enif_make_atom(env, "true");

  get_static_doc().impl.set_allocator(enif_alloc, enif_free);

  return 0;
}

static void unload(ErlNifEnv *env, void *priv_data) {
  return;
}

static ERL_NIF_TERM create(ErlNifEnv *env, int argc,
                           const ERL_NIF_TERM argv[]) {
  void *mem = enif_alloc_resource(parser_type, sizeof(Parser));
  Parser *parser = new (mem) Parser;

  ErlNifUInt64 max_child_size;
  if (!enif_get_uint64(env, argv[0], &max_child_size))
    return enif_make_badarg(env);
  parser->max_child_size = static_cast<std::uint64_t>(max_child_size);
  if (enif_compare(atom_true, argv[1]) == 0)
    parser->infinite_stream = true;

  ERL_NIF_TERM term = enif_make_resource(env, parser);
  enif_release_resource(parser);
  return enif_make_tuple2(env, atom_ok, term);
}

static ERL_NIF_TERM parse_next(ErlNifEnv *env, int argc,
                               const ERL_NIF_TERM argv[]) {
  Parser *parser;
  if (!enif_get_resource(env, argv[0], parser_type,
                         reinterpret_cast<void **>(&parser)))
    return enif_make_badarg(env);

  if (!parser->copy_buffer(env, argv[1]))
    return enif_make_badarg(env);

  // Skip initial whitespace even if we don't manage to parse anything.
  // Also needed for has_stream_closing_tag to recognize the tag.
  std::size_t offset = 0;
  while (offset < Parser::buffer.size() - 1 &&
         std::isspace(Parser::buffer[offset]))
    ++offset;

  ParseCtx ctx{env, parser};
  xml_document::ParseResult result;
  ERL_NIF_TERM element;

  xml_document &doc = get_static_doc();
  Parser::term_buffer.clear();

  auto parseStreamOpen = [&] {
    result = doc.parse<parse_open_only()>(Parser::buffer.data() + offset);
    if (!result.has_error) {
      auto name_tag = node_name(doc.impl.first_node());
      parser->stream_tag =
          ustring{std::get<0>(name_tag), std::get<1>(name_tag)};
      element = make_stream_start_tuple(ctx, doc.impl.first_node());
    }
  };

  auto hasStreamReopen = [&] {
    auto parseOpenRes =
        doc.parse<parse_open_only()>(Parser::buffer.data() + offset);
    if (parseOpenRes.has_error)
      return false;
    auto tag_name = node_name(doc.impl.first_node());
    return ustring{std::get<0>(tag_name), std::get<1>(tag_name)} ==
           parser->stream_tag;
  };

  if (parser->infinite_stream) {
    result = doc.parse<parse_one()>(Parser::buffer.data() + offset);
    if (!result.has_error)
      element = make_xmlel(ctx, doc.impl.first_node());
  } else if (parser->stream_tag.empty()) {
    parseStreamOpen();
  } else if (has_stream_closing_tag(parser, offset)) {
    doc.clear();
    // no data after closing tag
    result.rest = &*Parser::buffer.rbegin();
    element = make_stream_end_tuple(ctx);
  } else {
    result = doc.parse<parse_one()>(Parser::buffer.data() + offset);
    if (!result.has_error)
      element = make_xmlel(ctx, doc.impl.first_node());
  }

  if (result.eof && hasStreamReopen()) {
    doc.clear();
    parseStreamOpen();
  }

  if (result.eof) {
    if (parser->max_child_size &&
        Parser::buffer.size() - offset >= parser->max_child_size)
      return enif_make_tuple2(
          env, atom_error,
          enif_make_string(env, "child element too big", ERL_NIF_LATIN1));

    result.rest = Parser::buffer.data() + offset;
    element = atom_undefined;
  } else if (result.has_error) {
    return enif_make_tuple2(
        env, atom_error,
        enif_make_string(env, result.error_message.c_str(), ERL_NIF_LATIN1));
  }

  // Raise an exception when null character is found.
  std::size_t rest_size = &Parser::buffer.back() - result.rest;
  if (std::strlen(reinterpret_cast<const char*>(result.rest)) != rest_size)
    return enif_make_tuple2(
        env, atom_error,
        enif_make_string(env, "null character found in buffer", ERL_NIF_LATIN1));

  return enif_make_tuple3(
      env, atom_ok, element,
      enif_make_uint64(env, result.rest - Parser::buffer.data()));
}

static ERL_NIF_TERM parse(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) {
  Parser parser;
  parser.copy_buffer(env, argv[0]);
  Parser::term_buffer.clear();

  auto &doc = get_static_doc();

  ParseCtx ctx{env, &parser};
  auto result = doc.parse<default_parse_flags()>(Parser::buffer.data());

  if (!result.has_error) {
    ERL_NIF_TERM element = make_xmlel(ctx, doc.impl.first_node());
    return enif_make_tuple2(env, atom_ok, element);
  }

  return enif_make_tuple2(
      env, atom_error,
      enif_make_string(env, result.error_message.c_str(), ERL_NIF_LATIN1));
}

static ERL_NIF_TERM escape_cdata(ErlNifEnv *env, int argc,
                                 const ERL_NIF_TERM argv[]) {
  ErlNifBinary bin;
  if (!enif_inspect_iolist_as_binary(env, argv[0], &bin))
    return enif_make_badarg(env);

  rapidxml::xml_node<unsigned char> node(rapidxml::node_data);
  node.value(bin.data, bin.size);
  return node_to_binary(env, node, rapidxml::print_no_indenting);
}

static ERL_NIF_TERM to_binary(ErlNifEnv *env, int argc,
                              const ERL_NIF_TERM argv[]) {
  int arity;
  const ERL_NIF_TERM *xmlel;
  if (!enif_get_tuple(env, argv[0], &arity, &xmlel))
    return enif_make_badarg(env);

  if (arity != 4 || enif_compare(atom_xmlel, xmlel[0]) != 0)
    return enif_make_badarg(env);

  int flags = rapidxml::print_no_indenting;
  if (enif_compare(atom_pretty, argv[1]) == 0)
    flags = 0;

  xml_document &doc = get_static_doc();
  if (!build_el(env, doc, xmlel, doc.impl))
    return enif_make_badarg(env);

  return node_to_binary(env, doc.impl, flags);
}

static ERL_NIF_TERM reset_parser(ErlNifEnv *env, int argc,
                                 const ERL_NIF_TERM argv[]) {
  Parser *parser;
  if (!enif_get_resource(env, argv[0], parser_type,
                         reinterpret_cast<void **>(&parser)))
    return enif_make_badarg(env);

  parser->reset();
  return atom_ok;
}

static ErlNifFunc nif_funcs[] = {
    {"create", 2, create},         {"parse", 1, parse},
    {"parse_next", 2, parse_next}, {"escape_cdata", 1, escape_cdata},
    {"to_binary", 2, to_binary},   {"reset_parser", 1, reset_parser}};
}

ERL_NIF_INIT(exml_nif, nif_funcs, &load, nullptr, nullptr, &unload)


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2015 Doltech Systems Ltd.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License"); you may not
  ~ use this file except in compliance with the License. You may obtain a copy of
  ~ the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  ~ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  ~ License for the specific language governing permissions and limitations under
  ~ the License.
  -->
<module>
    <public path='resources'>
        <include name='css/*.css'/>
        <include name='js/*.js'/>
    </public>

    <!--Add these style sheets last so that they are the most important!-->
    <stylesheet src='css/demo.css'/>
    <stylesheet src='css/prettify.css'/>
</module>


text:
package hudson.model;

import com.gargoylesoftware.htmlunit.html.HtmlFileInput;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import hudson.matrix.AxisList;
import hudson.matrix.MatrixBuild;
import hudson.matrix.MatrixProject;
import hudson.matrix.TextAxis;
import hudson.model.Cause.*;
import hudson.tasks.Shell;
import hudson.triggers.SCMTrigger.SCMTriggerCause;
import hudson.triggers.TimerTrigger.TimerTriggerCause;
import hudson.util.XStream2;
import hudson.util.OneShotEvent;
import hudson.Launcher;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.jvnet.hudson.test.Bug;
import org.jvnet.hudson.test.HudsonTestCase;
import org.jvnet.hudson.test.TestBuilder;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.servlet.ServletHandler;
import org.mortbay.jetty.servlet.ServletHolder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

/**
 * @author Kohsuke Kawaguchi
 */
public class QueueTest extends HudsonTestCase {
    /**
     * Checks the persistence of queue.
     */
    public void testPersistence() throws Exception {
        Queue q = hudson.getQueue();

        // prevent execution to push stuff into the queue
        hudson.setNumExecutors(0);
        hudson.setNodes(hudson.getNodes());

        FreeStyleProject testProject = createFreeStyleProject("test");
        testProject.scheduleBuild(new UserIdCause());
        q.save();

        System.out.println(FileUtils.readFileToString(new File(hudson.getRootDir(), "queue.xml")));

        assertEquals(1,q.getItems().length);
        q.clear();
        assertEquals(0,q.getItems().length);

        // load the contents back
        q.load();
        assertEquals(1,q.getItems().length);

        // did it bind back to the same object?
        assertSame(q.getItems()[0].task,testProject);
    }

    /**
     * Can {@link Queue} successfully recover removal?
     */
    public void testPersistence2() throws Exception {
        Queue q = hudson.getQueue();

        // prevent execution to push stuff into the queue
        hudson.setNumExecutors(0);
        hudson.setNodes(hudson.getNodes());

        FreeStyleProject testProject = createFreeStyleProject("test");
        testProject.scheduleBuild(new UserIdCause());
        q.save();

        System.out.println(FileUtils.readFileToString(new File(hudson.getRootDir(), "queue.xml")));

        assertEquals(1,q.getItems().length);
        q.clear();
        assertEquals(0,q.getItems().length);

        // delete the project before loading the queue back
        testProject.delete();
        q.load();
        assertEquals(0,q.getItems().length);
    }

    public static final class FileItemPersistenceTestServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
        @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            resp.setContentType("text/html");
            resp.getWriter().println(
                    "<form action='/' method=post name=main enctype='multipart/form-data'>" +
                    "<input type=file name=test><input type=submit>"+
                    "</form>"
            );
        }

        @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            try {
                ServletFileUpload f = new ServletFileUpload(new DiskFileItemFactory());
                List<?> v = f.parseRequest(req);
                assertEquals(1,v.size());
                XStream2 xs = new XStream2();
                System.out.println(xs.toXML(v.get(0)));
            } catch (FileUploadException e) {
                throw new ServletException(e);
            }
        }
    }

    public void testFileItemPersistence() throws Exception {
        // TODO: write a synchronous connector?
        byte[] testData = new byte[1024];
        for( int i=0; i<testData.length; i++ )  testData[i] = (byte)i;

        Server server = new Server();
        SocketConnector connector = new SocketConnector();
        server.addConnector(connector);

        ServletHandler handler = new ServletHandler();
        handler.addServletWithMapping(new ServletHolder(new FileItemPersistenceTestServlet()),"/");
        server.addHandler(handler);

        server.start();

        localPort = connector.getLocalPort();

        try {
            WebClient wc = new WebClient();
            HtmlPage p = (HtmlPage) wc.getPage("http://localhost:" + localPort + '/');
            HtmlForm f = p.getFormByName("main");
            HtmlFileInput input = (HtmlFileInput) f.getInputByName("test");
            input.setData(testData);
            f.submit();
        } finally {
            server.stop();
        }
    }

    public void testFoldableCauseAction() throws Exception {
        final OneShotEvent buildStarted = new OneShotEvent();
        final OneShotEvent buildShouldComplete = new OneShotEvent();

        setQuietPeriod(0);
        FreeStyleProject project = createFreeStyleProject();
        // Make build sleep a while so it blocks new builds
        project.getBuildersList().add(new TestBuilder() {
            public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
                buildStarted.signal();
                buildShouldComplete.block();
                return true;
            }
        });

        // Start one build to block others
        assertTrue(project.scheduleBuild(new UserIdCause()));
        buildStarted.block(); // wait for the build to really start

        // Schedule a new build, and trigger it many ways while it sits in queue
        Future<FreeStyleBuild> fb = project.scheduleBuild2(0, new UserIdCause());
        assertNotNull(fb);
        assertFalse(project.scheduleBuild(new SCMTriggerCause("")));
        assertFalse(project.scheduleBuild(new UserIdCause()));
        assertFalse(project.scheduleBuild(new TimerTriggerCause()));
        assertFalse(project.scheduleBuild(new RemoteCause("1.2.3.4", "test")));
        assertFalse(project.scheduleBuild(new RemoteCause("4.3.2.1", "test")));
        assertFalse(project.scheduleBuild(new SCMTriggerCause("")));
        assertFalse(project.scheduleBuild(new RemoteCause("1.2.3.4", "test")));
        assertFalse(project.scheduleBuild(new RemoteCause("1.2.3.4", "foo")));
        assertFalse(project.scheduleBuild(new SCMTriggerCause("")));
        assertFalse(project.scheduleBuild(new TimerTriggerCause()));

        // Wait for 2nd build to finish
        buildShouldComplete.signal();
        FreeStyleBuild build = fb.get();

        // Make sure proper folding happened.
        CauseAction ca = build.getAction(CauseAction.class);
        assertNotNull(ca);
        StringBuilder causes = new StringBuilder();
        for (Cause c : ca.getCauses()) causes.append(c.getShortDescription() + "\n");
        assertEquals("Build causes should have all items, even duplicates",
                "Started by user SYSTEM\nStarted by an SCM change\n"
                + "Started by user SYSTEM\nStarted by timer\n"
                + "Started by remote host 1.2.3.4 with note: test\n"
                + "Started by remote host 4.3.2.1 with note: test\n"
                + "Started by an SCM change\n"
                + "Started by remote host 1.2.3.4 with note: test\n"
                + "Started by remote host 1.2.3.4 with note: foo\n"
                + "Started by an SCM change\nStarted by timer\n",
                causes.toString());

        // View for build should group duplicates
        WebClient wc = new WebClient();
        String buildPage = wc.getPage(build, "").asText().replace('\n',' ');
        assertTrue("Build page should combine duplicates and show counts: " + buildPage,
                   buildPage.contains("Started by user SYSTEM (2 times) "
                        + "Started by an SCM change (3 times) "
                        + "Started by timer (2 times) "
                        + "Started by remote host 1.2.3.4 with note: test (2 times) "
                        + "Started by remote host 4.3.2.1 with note: test "
                        + "Started by remote host 1.2.3.4 with note: foo"));
    }

    @Bug(8790)
    public void testFlyweightTasks() throws Exception {
        MatrixProject m = createMatrixProject();
        m.addProperty(new ParametersDefinitionProperty(
                new StringParameterDefinition("FOO","value")
        ));
        m.getBuildersList().add(new Shell("sleep 3"));
        m.setAxes(new AxisList(new TextAxis("DoesntMatter", "aaa","bbb")));

        List<Future<MatrixBuild>> r = new ArrayList<Future<MatrixBuild>>();

        for (int i=0; i<3; i++)
            r.add(m.scheduleBuild2(0,new UserIdCause(),new ParametersAction(new StringParameterValue("FOO","value"+i))));

        for (Future<MatrixBuild> f : r)
            assertBuildStatusSuccess(f);
    }
}


text:
package net.spy.memcached.vbucket.config;

import org.codehaus.jettison.json.JSONObject;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;

import java.text.ParseException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import net.spy.memcached.compat.SpyObject;

public class ConfigurationParserJSON extends SpyObject implements ConfigurationParser {
    private static final String NAME_ATTR = "name";
    private static final String URI_ATTR = "uri";
    private static final String STREAMING_URI_ATTR = "streamingUri";
    public Map<String, Pool> parseBase(String base) throws ParseException {
        Map<String, Pool> parsedBase = new HashMap<String, Pool>();
        JSONArray poolsJA = null;
        try {
            JSONObject baseJO = new JSONObject(base);
            poolsJA = baseJO.getJSONArray("pools");
        } catch (JSONException e) {
            throw new ParseException("Can not read base " + base, 0);
        }
        for (int i = 0; i < poolsJA.length(); ++i) {
            try {
                JSONObject poolJO = poolsJA.getJSONObject(i);
                String name = (String) poolJO.get(NAME_ATTR);
                if (name == null || "".equals(name)) {
                    throw new ParseException("Pool's name is missing.", 0);
                }
                String uri = (String) poolJO.get(URI_ATTR);
                if (uri == null || "".equals(uri)) {
                    throw new ParseException("Pool's uri is missing.", 0);
                }
                String streamingUri = (String) poolJO.get(STREAMING_URI_ATTR);
                Pool pool = new Pool(name, new URI(uri), new URI(streamingUri));
                parsedBase.put(name, pool);
            } catch (JSONException e) {
                getLogger().error("One of the pool configuration can not be parsed.", e);
            } catch (URISyntaxException e) {
                getLogger().error("Server provided an incorrect uri.", e);
            }
        }
        return parsedBase;

    }

    public void loadPool(Pool pool, String sPool) throws ParseException {
        try {
            JSONObject poolJO = new JSONObject(sPool);
            JSONObject poolBucketsJO = poolJO.getJSONObject("buckets");
            URI bucketsUri = new URI((String) poolBucketsJO.get("uri"));
            pool.setBucketsUri(bucketsUri);
        } catch (JSONException e) {
            throw new ParseException(e.getMessage(), 0);
        } catch (URISyntaxException e) {
            throw new ParseException(e.getMessage(), 0);
        }
    }

    public Map<String, Bucket> parseBuckets(String buckets) throws ParseException {
        Map<String, Bucket> bucketsMap = new HashMap<String, Bucket>();
        try {
            JSONArray bucketsJA = new JSONArray(buckets);
            for (int i = 0; i < bucketsJA.length(); ++i) {
                JSONObject bucketJO = bucketsJA.getJSONObject(i);
                Bucket bucket = parseBucketFromJSON(bucketJO);
                bucketsMap.put(bucket.getName(), bucket);
            }
        } catch (JSONException e) {
            throw new ParseException(e.getMessage(), 0);
        }
        return bucketsMap;
    }
    public Bucket parseBucket(String sBucket) throws ParseException {
        try {
            return parseBucketFromJSON(new JSONObject(sBucket));
        } catch (JSONException e) {
            throw new ParseException(e.getMessage(), 0);
        }
    }
    private Bucket parseBucketFromJSON(JSONObject bucketJO) throws ParseException {
        try {
            String bucketname = bucketJO.get("name").toString();
            String streamingUri = bucketJO.get("streamingUri").toString();
            ConfigFactory cf = new DefaultConfigFactory();
            Config config = cf.create(bucketJO);
            List<Node> nodes = new ArrayList<Node>();
            JSONArray nodesJA = bucketJO.getJSONArray("nodes");
            for(int i = 0; i < nodesJA.length(); ++i) {
                JSONObject nodeJO = nodesJA.getJSONObject(i);
                String statusValue = nodeJO.get("status").toString();
                Status status = null;
                try {
                    status = Status.valueOf(statusValue);
                } catch (IllegalArgumentException e) {
                    getLogger().error("Unknown status value: " + statusValue);
                }
                String hostname = nodeJO.get("hostname").toString();
                JSONObject portsJO = nodeJO.getJSONObject("ports");
                Map<Port, String> ports = new HashMap<Port, String>();
                for (Port port : Port.values()) {
                    String portValue = portsJO.get(port.toString()).toString();
                    if (portValue == null || portValue.isEmpty()) {
                        continue;
                    }
                    ports.put(port, portValue);
                }
                Node node = new Node(status, hostname, ports);
                nodes.add(node);
            }
            return new Bucket(bucketname, config, new URI(streamingUri), nodes);
        } catch (JSONException e) {
            throw new ParseException(e.getMessage(), 0);
        } catch (URISyntaxException e) {
            throw new ParseException(e.getMessage(), 0);
        }

    }
}


text: export { StyledEngineProvider as default } from '@material-ui/system';


text:
import netCDF4
import numpy as np
import os
import sys

from projections.mp4_utils import to_mp4

def fraction(ds, idx):
  rndwd = ds.variables['rndwd'][idx]
  fulwd = ds.variables['fulwd'][idx]
  combf = ds.variables['combf'][idx]
  return (rndwd + combf) / (rndwd + fulwd + combf)

if len(sys.argv) != 2:
  print("Usage: %s <file.nc>" % os.path.basename(sys.argv[0]))
  sys.exit(1)
fname = sys.argv[1]
title = 'Fraction of commercial wood harvest'
oname = "%s.mp4" % 'wood-harv'
manage = netCDF4.Dataset(fname)
years = manage.variables['time'][:]
if years[0] < 850:
  years = [int(y + 850) for y in years]
else:
  years = map(int, years)

frac = fraction(manage, 0)
for idx, img, text in to_mp4(title, oname, len(years),
                             frac, str(years[0]), 10):
  img.set_array(fraction(manage, idx))
  text.set_text(str(years[idx]))


text:
LinuxKit can run using Oracle VirtualBox. This should work on OSX, Linux
and Windows. The standard install should be sufficient.

NB: Windows support is not currently working but should be fixed soon.

## Boot

The Virtualbox backend currently supports booting from disks or ISOs.
It should work with either BIOS (default) or EFI
(with `linuxkit run vbox --uefi ...`).

## Console

With `linuxkit run vbox` the serial console is redirected to
stdio, providing interactive access to the VM.

## Disks

The Virtualbox backend support configuring a persistent disk using the
standard `linuxkit` `-disk` syntax. Multiple disks are
supported and can be created in `raw` format; other formats that VirtualBox
supports can be attached. Note that additional drives are attached to the
SATA Controller, unlike the VM disk which is on the IDE Controller.

## Networking

You can select the networking mode, which defaults to the standard `nat`, by using the
`-networking` command-line option. Some networking modes (`hostonly`, `bridge`) will require
the additional `adapter` parameter to the `-networking` option:

~~~
-networking hostonly,adapter=vboxnet0
~~~

You can specify more than one `-networking` option to setup multiple adapters. It is
recommended to setup the first adapter as `nat`.


text:
set -e

DESTINATION=$1
FILENAME="$2"

help() {
  echo
  echo "upload.sh [destination IP] [Path to .fw file]"
  echo
  echo "Default destination IP is 'nerves.local'"
  echo "Default firmware bundle is the first .fw file in '_build/\${MIX_TARGET}_\${MIX_ENV}/nerves/images'"
  echo
  echo "MIX_TARGET=$MIX_TARGET"
  echo "MIX_ENV=$MIX_ENV"
  exit 1
}

[ -n "$DESTINATION" ] || DESTINATION=nerves.local
if [ -z "$FILENAME" ]; then
  [ -n "$MIX_TARGET" ] || MIX_TARGET=rpi0
  [ -n "$MIX_ENV" ] || MIX_ENV=dev
  FIRMWARE_PATH="./_build/${MIX_TARGET}_${MIX_ENV}/nerves/images"
  if [ ! -d "$FIRMWARE_PATH" ]; then
      echo "Can't find the build products."
      echo
      echo "Nerves environment"
      echo "MIX_TARGET:    ${MIX_TARGET}"
      echo "MIX_ENV:       ${MIX_ENV}"
      echo
      echo "Make sure your Nerves environment is correct."
      echo
      echo "If the Nerves environment is correct make sure you have built the firmware"
      echo "using 'mix firmware'."
      echo
      echo "If you are uploading a .fw file from a custom path you can specify the"
      echo "path like so:"
      echo
      echo "  $0 <device hostname or IP address> </path/to/my/firmware.fw>"
      echo
      exit 1
  fi

  FILENAME=$(ls "$FIRMWARE_PATH/"*.fw 2> /dev/null | head -n 1)
  [ -n "$FILENAME" ] || (echo "Error: error determining firmware bundle."; help)
fi

[ -f "$FILENAME" ] || (echo "Error: can't find '$FILENAME'"; help)

FIRMWARE_METADATA=$(fwup -m -i "$FILENAME" || echo "meta-product=Error reading metadata!")
FIRMWARE_PRODUCT=$(echo "$FIRMWARE_METADATA" | grep -E "^meta-product=" -m 1 2>/dev/null | cut -d '=' -f 2- | tr -d '"')
FIRMWARE_VERSION=$(echo "$FIRMWARE_METADATA" | grep -E "^meta-version=" -m 1 2>/dev/null | cut -d '=' -f 2- | tr -d '"')
FIRMWARE_PLATFORM=$(echo "$FIRMWARE_METADATA" | grep -E "^meta-platform=" -m 1 2>/dev/null | cut -d '=' -f 2- | tr -d '"')
FIRMWARE_UUID=$(echo "$FIRMWARE_METADATA" | grep -E "^meta-uuid=" -m 1 2>/dev/null | cut -d '=' -f 2- | tr -d '"')

echo "Path: $FILENAME"
echo "Product: $FIRMWARE_PRODUCT $FIRMWARE_VERSION"
echo "UUID: $FIRMWARE_UUID"
echo "Platform: $FIRMWARE_PLATFORM"
echo
echo "Uploading to $DESTINATION..."

cat "$FILENAME" | ssh -s $SSH_OPTIONS $DESTINATION fwup


text:
<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'
 xmlns:g='urn:import:com.google.gwt.user.client.ui'>

 <ui:style gss="true">
.pan_shell_top_container {
}

.panShellMainContainer {
	width:			100%;
	height:			100%;
	position: relative;
    display: flex;
    flex-direction: column;
    flex: 0 1 auto;
    min-height: 0;
    overflow:auto;
}

.layoutColumn {
    -webkit-flex-direction: column;
    flex-direction: column;
}

.layoutRow {
    -webkit-flex-direction: row;
    flex-direction: row;
}

.layout, .layoutColumn, .layoutRow {
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    display: -webkit-box;
    display: -moz-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
}

.flex {
    -webkit-box-flex: 1;
    -webkit-flex: 1;
    flex: 1;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

.flex_none {
    -webkit-box-flex: 0 0 auto;
    -webkit-flex: 0 0 auto;
    flex: 0 0 auto;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

.p6nVulcanLayoutMain {
    height: 100%;
    min-width: 900px;
}

@media screen and (max-width: 960px) {
    .p6nVulcanLayoutMain {
        min-width: 100%;
    }
}
 </ui:style>

<!--
 pan-shell -> mainLayout  -> topContainer   -> barContainer
                          -> mainContainer
-->

 <g:HTMLPanel styleName="{style.p6nVulcanLayoutMain} {style.layoutColumn} {style.flex}">
  <g:SimplePanel styleName="{style.pan_shell_top_container} {style.layoutColumn} {style.flex_none}" ui:field="topContainer"/>
  <g:SimplePanel styleName="{style.panShellMainContainer} {style.layoutRow} {style.flex}" ui:field="mainContainer"/>
 </g:HTMLPanel>

</ui:UiBinder>


text:
require 'tee/version'

# A class like tee(1)
class Tee
  class << self
    # @macro new
    #   @param ios [Array<IO, String>]
    #   @param options [Hash]
    #   @option options [String, Fixnum] :mode ('w')
    #   @option options [Fixnum] :perm (0666)
    #   @option options [IO, nil] :stdout ($stdout)
    #
    # @overload open(*ios, options = {})
    #   A synonym for Tee.new
    #   @macro new
    #   @return [Tee]
    #
    # @overload open(*ios, options = {}, &block)
    #   It will be passed the Tee as an argument,
    #   and the Tee will automatically be closed when the block terminates.
    #   @macro new
    #   @yieldparam tee [Tee]
    #   @return the value of the block
    def open(*args, &block)
      if block_given?
        tee = new(*args)
        begin
          yield tee
        ensure
          tee.send(:close_ios_opened_by_self)
        end
      else
        new(*args)
      end
    end
  end

  # @param value [IO, nil] Sets the attribute stdout
  # @return [IO, nil]      Returns the value of attribute stdout
  attr_accessor :stdout

  # @overload initialize(*ios, options = {})
  #   @macro new
  def initialize(*ios)
    @options = { mode: 'w' }
    @options.update(ios.pop) if ios.last.is_a?(Hash)

    @stdout = @options.key?(:stdout) ? @options.delete(:stdout) : $stdout

    @ios = []
    add(*ios)
  end

  # Add ios
  #
  # @param ios [Array<IO, String>]
  # @return [self]
  def add(*ios)
    open_args = [@options[:mode]]
    open_args << @options[:perm] if @options[:perm]

    _ios = []
    begin
      ios.each do |io|
        _ios << (
          io.respond_to?(:write) ?
            [io, false] :
            [File.open(io, *open_args), true]
        )
      end
    rescue => e
      close_ios_opened_by_self(_ios) rescue nil
      raise e
    end
    @ios.concat(_ios)

    self
  end

  # Delegates #<< to ios
  #
  # @param obj [Object]
  # @return [self]
  def <<(obj)
    each_ios_and_stdout(obj, &:<<)
  end

  # Closes all ios except stdout
  #
  # @return [nil]
  def close
    each_ios(&:close)
    nil
  end

  # Returns true if all ios except stdout is closed, false otherwise.
  #
  # @return [Boolean]
  def closed?
    each_ios.all?(&:closed?)
  end

  # Delegates #flush to ios
  #
  # @return [self]
  def flush
    each_ios_and_stdout(&:flush)
  end

  # Delegates #print to ios
  #
  # @param obj [Object]
  # @return [nil]
  def print(*obj)
    each_ios_and_stdout(*obj, &:print)
    nil
  end

  # Delegates #printf to ios
  #
  # @param format [String]
  # @param obj [Object]
  # @return [nil]
  def printf(format, *obj)
    each_ios_and_stdout(format, *obj, &:printf)
    nil
  end

  # Delegates #putc to ios
  #
  # @param char [Fixnum, String]
  # @return [Fixnum]
  # @return [String]
  def putc(char)
    each_ios_and_stdout(char, &:putc)
    char
  end

  # Delegates #puts to ios
  #
  # @param obj [Object]
  # @return [nil]
  def puts(*obj)
    each_ios_and_stdout(*obj, &:puts)
    nil
  end

  # Delegates #syswrite to ios
  #
  # @param string [String]
  # @return [Array<Integer>]
  def syswrite(string)
    each_ios_and_stdout(string).map(&:syswrite)
  end

  # Returns self
  #
  # @return [self]
  def to_io
    self
  end

  # Delegates #tty? to stdout
  #
  # @return [Boolean]
  def tty?
    @stdout ? @stdout.tty? : false
  end
  alias isatty tty?

  # Delegates #write to ios
  #
  # @param string [String]
  # @return [Array<Integer>]
  def write(string)
    each_ios_and_stdout(string).map(&:write)
  end

  # Delegates #write_nonblock to ios
  #
  # @param string [String]
  # @return [Array<Integer>]
  def write_nonblock(string)
    each_ios_and_stdout(string).map(&:write_nonblock)
  end

  private

  # @return [self]
  def each_ios(*args, &block)
    return to_enum(__method__, *args) unless block_given?
    @ios.each do |io,|
      yield io, *args
    end
    self
  end

  # @return [self]
  def each_ios_and_stdout(*args, &block)
    return to_enum(__method__, *args) unless block_given?
    yield @stdout, *args if @stdout
    each_ios(*args, &block)
  end

  # @return [nil]
  def close_ios_opened_by_self(ios = @ios)
    ios.each do |io, opened|
      io.close if opened && !io.closed?
    end
    nil
  end
end


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Department extends CI_Controller {
	function __construct(){
        parent::__construct();
        $this->load->library(array('template'));
        $this->load->model(array('departmentModel'));
    }

    function listDepartment(){
    	$data['title'] = 'Department';
    	$this->template->adminTemplate('admin/department', $data);
    }

    function formDepartment(){
    	$this->load->view('admin/partialFormDepartment');
    }
    function createDepartment(){
    	$value = array(
    		'depName'=>$_POST['dep']
    		);
    	$insert = $this->departmentModel->createDepartment($value);

    	if ($insert == true) {
    		redirect('department/listDepartment');
    	}
    }

}


text:
<!--
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="@dimen/recycle_item_child_margin_bottom"
    android:layout_marginStart="@dimen/recycle_item_child_margin_right"
    android:layout_marginEnd="@dimen/recycle_item_child_margin_left"
    android:layout_marginTop="@dimen/recycle_item_child_margin_top"
    android:background="@drawable/child_bg"
    android:paddingBottom="@dimen/recycle_item_child_padding_bottom"
    android:paddingTop="@dimen/recycle_item_child_padding_top"
    android:orientation="horizontal"
    android:gravity="center_vertical"
    >

    <TextView
        android:id="@+id/recycler_child_item_title_text_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/recycle_item_child_title_field_margin_left"
        android:ellipsize="end"
        android:layout_weight="1"
        android:hint="@string/placeholder_string"
        android:scrollHorizontally="true"
        android:maxLines="1"
        android:textSize="@dimen/recycle_item_child_title_field_text_size"
        />

    <ImageView
        android:id="@+id/recycle_child_notification_image_view"
        android:layout_width="@dimen/recycle_item_child_notification_icon_image_view_width_height"
        android:layout_height="@dimen/recycle_item_child_notification_icon_image_view_width_height"
        android:layout_marginEnd="@dimen/recycle_item_child_notification_icon_image_view_margin_right"
        android:visibility="gone"
        />

    <TextView
        android:id="@+id/recycler_child_last_updated_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/recycle_item_child_last_updated_text_view_margin_bottom"
        android:layout_marginStart="@dimen/recycle_item_child_last_updated_text_view_margin_left"
        android:layout_marginEnd="@dimen/recycle_item_child_last_updated_text_view_margin_right"
        android:layout_marginTop="@dimen/recycle_item_child_last_updated_text_view_margin_top"
        android:gravity="center_horizontal"
        android:hint="@string/placeholder_string"
        android:textSize="@dimen/recycle_item_child_last_updated_text_size"
        />

    <CheckBox
        android:id="@+id/recycle_child_view_subscribed_check_box"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/recycle_item_child_is_subscribed_check_box_margin_left"
        android:layout_marginEnd="@dimen/recycler_item_subscribed_check_box_margin_right"
        android:clickable="false"
        />

    <Button
        android:id="@+id/recycler_item_download_map_button"
        android:layout_width="@dimen/recycle_item_child_download_button_width"
        android:layout_height="@dimen/recycle_item_child_download_button_height"
        android:layout_marginEnd="@dimen/recycler_item_download_map_button_margin_right"
        android:background="@drawable/ic_file_download_black_36dp"
        />
</LinearLayout>


text:
#pragma once
#include <aws/marketplace-catalog/MarketplaceCatalog_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/marketplace-catalog/model/EntitySummary.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace MarketplaceCatalog
{
namespace Model
{
  class AWS_MARKETPLACECATALOG_API ListEntitiesResult
  {
  public:
    ListEntitiesResult();
    ListEntitiesResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    ListEntitiesResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
 Array of EntitySummary object.

     */
    inline const Aws::Vector<EntitySummary>& GetEntitySummaryList() const{ return m_entitySummaryList; }

    /**
     *
 Array of EntitySummary object.

     */
    inline void SetEntitySummaryList(const Aws::Vector<EntitySummary>& value) { m_entitySummaryList = value; }

    /**
     *
 Array of EntitySummary object.

     */
    inline void SetEntitySummaryList(Aws::Vector<EntitySummary>&& value) { m_entitySummaryList = std::move(value); }

    /**
     *
 Array of EntitySummary object.

     */
    inline ListEntitiesResult& WithEntitySummaryList(const Aws::Vector<EntitySummary>& value) { SetEntitySummaryList(value); return *this;}

    /**
     *
 Array of EntitySummary object.

     */
    inline ListEntitiesResult& WithEntitySummaryList(Aws::Vector<EntitySummary>&& value) { SetEntitySummaryList(std::move(value)); return *this;}

    /**
     *
 Array of EntitySummary object.

     */
    inline ListEntitiesResult& AddEntitySummaryList(const EntitySummary& value) { m_entitySummaryList.push_back(value); return *this; }

    /**
     *
 Array of EntitySummary object.

     */
    inline ListEntitiesResult& AddEntitySummaryList(EntitySummary&& value) { m_entitySummaryList.push_back(std::move(value)); return *this; }

    /**
     *
The value of the next token if it exists. Null if there is no more
     * result.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
The value of the next token if it exists. Null if there is no more
     * result.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextToken = value; }

    /**
     *
The value of the next token if it exists. Null if there is no more
     * result.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); }

    /**
     *
The value of the next token if it exists. Null if there is no more
     * result.

     */
    inline void SetNextToken(const char* value) { m_nextToken.assign(value); }

    /**
     *
The value of the next token if it exists. Null if there is no more
     * result.

     */
    inline ListEntitiesResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
The value of the next token if it exists. Null if there is no more
     * result.

     */
    inline ListEntitiesResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
The value of the next token if it exists. Null if there is no more
     * result.

     */
    inline ListEntitiesResult& WithNextToken(const char* value) { SetNextToken(value); return *this;}

  private:

    Aws::Vector<EntitySummary> m_entitySummaryList;

    Aws::String m_nextToken;
  };

} // namespace Model
} // namespace MarketplaceCatalog
} // namespace Aws


text:
#ifndef __itkB0ImageExtractionImageFilter_h_
#define __itkB0ImageExtractionImageFilter_h_

#include "itkImageToImageFilter.h"

namespace itk{
  /** \class B0ImageExtractionImageFilter
  * \brief This class takes as input a T2-weighted image and computes a brainmask.
  *
  */

  template< class TInputImagePixelType,
  class TOutputImagePixelType >
  class B0ImageExtractionImageFilter :
    public ImageToImageFilter< VectorImage<TInputImagePixelType, 3>,
    Image< TOutputImagePixelType, 3 > >
  {

  public:

    typedef B0ImageExtractionImageFilter Self;
    typedef SmartPointer<Self>                      Pointer;
    typedef SmartPointer<const Self>                ConstPointer;
    typedef ImageToImageFilter< VectorImage< TInputImagePixelType, 3 >,
      Image< TOutputImagePixelType, 3 >  >
      Superclass;

    /** Method for creation through the object factory. */
    itkNewMacro(Self);

    /** Runtime information support. */
    itkTypeMacro(B0ImageExtractionImageFilter,
      ImageToImageFilter);

    typedef TInputImagePixelType                     InputPixelType;

    typedef TOutputImagePixelType                    OutputPixelType;

    typedef typename Superclass::InputImageType      InputImageType;
    typedef typename Superclass::OutputImageType     OutputImageType;

    typedef typename Superclass::OutputImageRegionType
      OutputImageRegionType;

    typedef vnl_vector_fixed< double, 3 >            GradientDirectionType;

    typedef itk::VectorContainer< unsigned int, GradientDirectionType >
      GradientDirectionContainerType;

    GradientDirectionContainerType::Pointer GetDirections()
    { return m_Directions; }
    void SetDirections( GradientDirectionContainerType::Pointer directions )
    { this->m_Directions = directions; }

  protected:

    B0ImageExtractionImageFilter();
    virtual ~B0ImageExtractionImageFilter() {};

    void GenerateData();

    GradientDirectionContainerType::Pointer   m_Directions;

  };

}

#ifndef ITK_MANUAL_INSTANTIATION
#include "itkB0ImageExtractionImageFilter.txx"
#endif

#endif //__itkB0ImageExtractionImageFilter_h_


text:
// Copyright 2012 Mark Cavage, Inc.  All rights reserved.

var assert = require('assert');
var EventEmitter = require('events').EventEmitter;
var http = require('http');
var https = require('https');
var url = require('url');
var util = require('util');

var async = require('async');

var errors = require('./errors');
var Request = require('./request');
var Response = require('./response');
var Route = require('./route');

///--- Globals

var BadMethodError = errors.BadMethodError;
var InvalidVersionError = errors.InvalidVersionError;
var ResourceNotFoundError = errors.ResourceNotFoundError;

///--- Helpers

function argsToChain() {
  assert.ok(arguments.length);

  var args = arguments[0];
  if (args.length < 0)
    throw new TypeError('handler (Function) required');

  var chain = [];

  function process(handlers) {
    handlers.forEach(function (h) {
      if (Array.isArray(h))
        return process(h);
      if (!typeof (h) === 'function')
        throw new TypeError('handlers must be Functions');

      return chain.push(h);
    });
  }
  process(Array.prototype.slice.call(args, 0));

  return chain;
}

function logRequest(req) {
  assert.ok(req);

  req.log.trace('New Request:\n\n%s', req.toString());
}

function default404Handler(req, res, server) {
  res.send(new ResourceNotFoundError(req.url + ' not found'));
  server.emit('after', req, res, null);
}

function default405Handler(req, res, methods, server) {
  res.header('Allow', methods.join(', '));
  if (req.method === 'OPTIONS') {
    res.send(200);
  } else {
    var msg = req.url + ' does not support ' + req.method;
    res.send(new BadMethodError(msg));
  }

  server.emit('after', req, res, null);
}

function defaultBadVersionHandler(req, res, versions, server) {
  var msg = req.method + ' ' + req.url + ' supports versions: ' +
    versions.join(', ');

  res.send(new InvalidVersionError(msg));
  server.emit('after', req, res, null);
}

function toPort(x) {
  x = parseInt(x, 10);
  return (x  >= 0 ? x : false);
}

function isPipeName(s) {
  return (typeof (s) === 'string' && toPort(s) === false);
}

///--- API

/**
 * Constructor. Creates a REST API Server.
 *
 * - options {Object} construction arguments. (bunyan instance required).
 */
function Server(options) {
  if (typeof (options) !== 'object')
    throw new TypeError('options (Object) required');
  if (typeof (options.dtrace) !== 'object')
    throw new TypeError('options.dtrace (Object) required');
  if (typeof (options.log) !== 'object')
    throw new TypeError('options.log (Object) required');

  EventEmitter.call(this);

  this.chain = [];
  this.formatters = options.formatters || {};
  this.log = options.log;
  this.name = options.name || 'restify';
  this.preChain = [];
  this.routes = [];
  this.version = options.version || false;
  this.responseTimeHeader = options.responseTimeHeader || 'X-Response-Time';
  this.responseTimeFormatter = options.responseTimeFormatter;

  var secure = false;
  if (options.certificate && options.key) {
    secure = true;
    this.server = https.createServer({
      cert: options.certificate,
      key: options.key
    });
  } else {
    this.server = http.createServer();
  }

  var self = this;
  this.server.on('error', function (err) {
    self.emit('error', err);
  });

  this.server.on('clientError', function (err) {
    self.emit('clientError', err);
  });

  this.server.on('close', function () {
    self.emit('close');
  });

  this.server.on('connection', function (socket) {
    self.emit('connection', socket);
  });

  this.server.on('upgrade', function (request, socket, headPacket) {
    return self.emit('upgrade', request, socket, headPacket);
  });

  this.server.on('request', function (req, res) {
    return self._request(req, res);
  });

  this.server.on('checkContinue', function (req, res) {
    if (self.listeners('checkContinue').length)
      return self.emit('checkContinue', req, res);

    return self._request(req, res, true);
  });

  this.__defineGetter__('acceptable', function () {
    var accept = Object.keys(self.formatters) || [];
    Response.ACCEPTABLE.forEach(function (a) {
      if (accept.indexOf(a) === -1)
        accept.push(a);
    });

    return accept;
  });

  this.__defineGetter__('name', function () {
    return options.name || 'restify';
  });

  this.__defineGetter__('dtrace', function () {
    return options.dtrace;
  });

  this.__defineGetter__('url', function () {
    if (self.socketPath)
      return 'http://' + self.socketPath;

    var str = secure ? 'https://' : 'http://';
    str += self.address().address;
    str += ':';
    str += self.address().port;
    return str;
  });

  this.__defineGetter__('responseTimeHeader', function () {
    return options.responseTimeHeader || 'X-Response-Time';
  });
}
util.inherits(Server, EventEmitter);
module.exports = Server;

Server.prototype.address = function address() {
  return this.server.address();
};

/**
 * Gets the server up and listening.
 *
 * You can call like:
 *  server.listen(80)
 *  server.listen(80, '127.0.0.1')
 *  server.listen('/tmp/server.sock')
 *
 * And pass in a callback to any of those forms.  Also, by default, invoking
 * this method will trigger DTrace probes to be enabled; to not do that, pass
 * in 'false' as the second to last parameter.
 *
 * @param {Function} callback optionally get notified when listening.
 * @throws {TypeError} on bad input.
 */
Server.prototype.listen = function listen() {
  var callback = false;
  var dtrace = true;
  var self = this;

  function listenCallback() {
    if (dtrace)
      self.dtrace.enable();

    return callback ? callback.call(self) : false;
  }

  if (!arguments.length)
    return this.server.listen(listenCallback);

  callback = arguments[arguments.length - 1];
  if (typeof (callback) !== 'function')
    callback = false;

  if (arguments.length >= 2 && arguments[arguments.length - 2] === false)
    dtrace = false;

  if (!isNaN(arguments[0]))
    arguments[0] = Number(arguments[0]);

  switch (typeof (arguments[0])) {
  case 'function':
    return this.server.listen(listenCallback);

  case 'string':
    if (isPipeName(arguments[0]))
      return this.server.listen(arguments[0], listenCallback);

    throw new TypeError(arguments[0] + ' is not a named pipe');

  case 'number':
    var host = arguments[1];
    return this.server.listen(arguments[0],
                              typeof (host) === 'string' ? host : '0.0.0.0',
                              listenCallback);

  default:
    throw new TypeError('port (Number) required');
  }
};

/**
 * Shuts down this server, and invokes callback (optionally) when done.
 *
 * @param {Function} callback optional callback to invoke when done.
 */
Server.prototype.close = function close(callback) {
  if (callback) {
    if (typeof (callback) !== 'function')
      throw new TypeError('callback must be a function');

    this.server.once('close', function () {
      return callback();
    });
  }

  return this.server.close();
};

// Register all the routing methods
['del', 'get', 'head', 'post', 'put'].forEach(function (method) {

  /**
   * Mounts a chain on the given path against this HTTP verb
   *
   * @param {Object} options the URL to handle, at minimum.
   * @return {Route} the newly created route.
   */
  Server.prototype[method] = function (options) {
    if (arguments.length < 2)
      throw new Error('At least one handler (Function) required');

    if (typeof (options) !== 'object' && typeof (options) !== 'string')
      throw new TypeError('path (String) required');

    var args = Array.prototype.slice.call(arguments, 1);

    if (method === 'del')
      method = 'DELETE';

    return this._addRoute(method.toUpperCase(), options, args);
  };
});

/**
 * Removes a route from the server.
 *
 * You can either pass in the route name or the route object as `name`.
 *
 * @param {String} name the route name.
 * @return {Boolean} true if route was removed, false if not.
 * @throws {TypeError} on bad input.
 */
Server.prototype.rm = function rm(name) {
  if (typeof (name) !== 'string' && !(name instanceof Route))
    throw new TypeError('name (String) required');

  for (var i = 0; i < this.routes.length; i++) {
    if (this.routes[i].name === name || this.routes[i] === name) {
      this.routes.splice(i, 1);
      return true;
    }
  }

  return false;
};

/**
 * Installs a list of handlers to run _before_ the "normal" handlers of all
 * routes.
 *
 * You can pass in any combination of functions or array of functions.
 *
 * @throws {TypeError} on input error.
 */
Server.prototype.use = function use() {
  var chain = argsToChain(arguments);

  if (chain.length) {
    var self = this;
    chain.forEach(function (h) {
      self.chain.push(h);
    });

    this.routes.forEach(function (r) {
      r.use(chain);
    });
  }

  return this;
};

/**
 * Gives you hooks to run _before_ any routes are located.  This gives you
 * a chance to intercept the request and change headers, etc., that routing
 * depends on.  Note that req.params will _not_ be set yet.
 */
Server.prototype.pre = function pre() {
  var self = this;

  return argsToChain(arguments).forEach(function (h) {
    self.preChain.push(h);
  });
};

///--- Private methods

Server.prototype._addRoute = function _addRoute(method, options, handlers) {
  var self = this;

  var chain = this.chain.slice(0);
  argsToChain(handlers).forEach(function (h) {
    chain.push(h);
  });

  if (typeof (options) !== 'object' || options instanceof RegExp)
    options = { url: options };

  var route = new Route({
    log: self.log,
    method: method,
    url: options.path || options.url,
    handlers: chain,
    name: options.name,
    version: options.version || self.version,
    dtrace: self.dtrace
  });
  route.on('error', function (err) {
    self.emit('error', err);
  });
  route.on('done', function (req, res) {
    self.emit('after', req, res, route);
  });
  route.on('uncaughtException', function (req, res, route, err) {
    if (self.listeners('uncaughtException').length) {
      self.emit('uncaughtException', req, res, route, err);
    } else {
      res.send(err);
    }
  });

  this.routes.forEach(function (r) {
    if (r.matchesUrl({ url: options.url })) {
      if (r.methods.indexOf(method) === -1)
        r.methods.push(method);
    }
  });

  this.routes.push(route);
  return route;
};

Server.prototype._request = function _request(request, response, expect100) {
  var self = this;

  var req = new Request({
    log: self.log,
    request: request
  });
  var res = new Response({
    log: self.log,
    request: req,
    response: response,
    formatters: self.formatters,
    serverName: self.name,
    responseTimeHeader: self.responseTimeHeader,
    responseTimeFormatter: self.responseTimeFormatter,
  });

  logRequest(req);

  var before = [];
  this.preChain.forEach(function (h) {
    before.push(function (callback) {
      return h(req, res, callback);
    });
  });
  // Ensure there's always one
  before.push(function (callback) {
    return callback();
  });

  return async.series(before, function (err) {
    if (err)
      return res.send(err);

    var route = self._findRoute(req, res);
    if (!route)
      return false;

    // Secret logger update
    req._setLogger(self.log, route.name);

    res.log = req.log;
    res.defaultHeaders();
    if (expect100)
      res.writeContinue();

    return route.run(req, res);
  });
};

Server.prototype._findRoute = function _findRoute(req, res) {
  assert.ok(req);
  assert.ok(res);

  var params;
  var route;
  var methods = [];
  var versions = [];

  for (var i = 0; i < this.routes.length; i++) {
    var r = this.routes[i];

    if ((params = r.matchesUrl(req))) {
      if (r.matchesMethod(req)) {
        if (r.matchesVersion(req)) {
          route = r;
          break;
        } else {
          if (r.version && versions.indexOf(r.version) === -1)
            versions.push(r.version);
        }
      } else {
        if (methods.indexOf(r.method) === -1)
          methods.push(r.method);
      }
    }
  }

  if (route) {
    req.params = params || {};
    res.methods = route.methods;
    res.version = route.version[route.version.length - 1];
  } else {
    res.methods = methods;
    res.versions = versions;

    if (versions.length) {
      if (!this.listeners('VersionNotAllowed').length)
        this.once('VersionNotAllowed', defaultBadVersionHandler);

      this.emit('VersionNotAllowed', req, res, versions, this);
    } else if (methods.length) {
      if (!this.listeners('MethodNotAllowed').length)
        this.once('MethodNotAllowed', default405Handler);

      this.emit('MethodNotAllowed', req, res, methods, this);
    } else {
      if (!this.listeners('NotFound').length)
        this.once('NotFound', default404Handler);

      this.emit('NotFound', req, res, this);
    }
  }

  return route || false;
};


text:
require 'question'

#Clase de gestion de preguntar True or False.
class TrueOrFalse < Question

#Inicializacion de la isntancia de la clase TrueOrFalse al cual se le pasa un texto para la pregunta y un booleano para la respuesta.
	def initialize (args)
		raise ArgumentError,"Se esperaba una pregunta" unless args.key?(:qt)
		raise ArgumentError,"Se esperaba la pregunta correcta" unless args.key?(:r1)
		args[:r1] = (args[:r1] ? "Cierto" : "Falso")
		args[:wrong] = [(args[:r1] ? "Falso" : "Cierto")]
		super(args)
	end
end


text:
<plugin id="org.dita4publishers.sample.epub_override">

  <require plugin="org.dita4publishers.epub"/>

  <feature extension="package.support.name" value="Eliot Kimber"/>
  <feature extension="package.support.email" value="ekimber@contrext.com"/>

</plugin>


text:
#ifndef _UTILS_H_
#define _UTILS_H_

#include <string>

#include <stdint.h>
#include <sys/stat.h>

namespace Chronos
{
	namespace Utils
	{
		uint64_t getTimestampMS();
		std::string trim(const std::string &in);
		void replace(std::string &str, const std::string &search, const std::string &repl);
		std::string userPathPart(const int userID);
		std::string toString(int num, int places);
		bool directoryExists(const std::string &path);
		bool mkPath(const std::string &path, const mode_t mode = 0755);
		std::string toLower(const std::string &str);
	};
};

#endif


text:
function wrapPromise(func, input) {
    return new Promise(function(resolve, reject) {
        var promiser = function(err, data) {
            if(err !== null) {
                return reject(err);
            }
            resolve(data);
        }
        func(input, promiser);
    });
}

module.exports = wrapPromise;


text:
using GeometryWars.Code.Affectors;
using GeometryWars.Code.Base;
using GeometryWars.Code.Enemies;
using GeometryWars.Code.Main;
using GeometryWars.Code.Projectiles;
using NetEXT.Particles;
using SFML.Graphics;
using SFML.System;
using System.Collections.Generic;

namespace GeometryWars.Code
{
	static class EntityManager
	{
		#region Private Fields
		private static List<Movable> enemies;
		private static List<Movable> enemiesBuffer;
		private static List<EnemyProjectile> enemyProjectiles;
		private static Hero hero;
		private static List<HeroProjectile> heroProjectiles;
		private static List<ScreenText> screenTexts;
		private static ParticleSystem system;
		#endregion Private Fields

		#region Public Constructors

		static EntityManager()
		{
			enemies = new List<Movable>();
			enemiesBuffer = new List<Movable>();
			heroProjectiles = new List<HeroProjectile>();
			enemyProjectiles = new List<EnemyProjectile>();
			hero = Hero.GetInstance();
			system = new ParticleSystem(Game.ParticleTexture);
			screenTexts = new List<ScreenText>();

			system.AddAffector(new BounceOffWall());
		}

		#endregion Public Constructors

		#region Public Properties

		public static int EnemyCount
		{
			get
			{
				int count = 0;
				foreach (Movable movable in enemies)
				{
					if (!(movable is Mini))
						count++;
				}
				return count;
			}
		}

		#endregion Public Properties

		#region Public Methods

		public static void AddEmitter(BaseEmitter emitter)
		{
			system.AddEmitter(emitter, Time.FromSeconds(emitter.EmitterDuration));
		}

		public static void AddEnemy(Movable enemy)
		{
			enemies.Add(enemy);
		}

		public static void AddEnemyProjectile(EnemyProjectile projectile)
		{
			enemyProjectiles.Add(projectile);
		}

		public static void AddProjectile(HeroProjectile projectile)
		{
			heroProjectiles.Add(projectile);
		}

		public static void AddText(ScreenText text)
		{
			screenTexts.Add(text);
		}

		public static void DeleteAllEnemies()
		{
			foreach (Movable enemy in enemies)
			{
				enemy.Delete();
			}
			foreach (EnemyProjectile enemyProjectile in enemyProjectiles)
			{
				enemyProjectile.Delete();
			}
		}

		public static void Draw(RenderTarget window)
		{
			Stars.Draw(window);
			DrawEnemies(window);
			DrawEnemyProjectiles(window);
			DrawHeroProjectiles(window);
			hero.Draw(window);
			system.Draw(window, RenderStates.Default);
			Camera.Update(window, hero.Pos);
			//DrawText(window);
		}

		public static void DrawText(RenderTarget window)
		{
			foreach (ScreenText screenText in screenTexts)
			{
				screenText.Draw(window);
			}
		}

		public static void ForceUpdateText()
		{
			foreach (ScreenText screenText in screenTexts)
			{
				screenText.ForceUpdate();
			}
		}

		public static void Update(float timeDelta)
		{
			Controller.Update();
			hero.Update(timeDelta, enemies);
			UpdateEnemies(timeDelta);
			UpdateEnemyProjectiles(timeDelta);
			UpdateHeroProjectiles(timeDelta);
			Stars.Update(timeDelta);
			Bomb.Update(timeDelta);
			SoundManager.Update();
			//Update particles
			system.Update(Time.FromSeconds(timeDelta));
			StringTable.GetInstance().Update();
			UpdateText();
		}

		#endregion Public Methods

		#region Private Methods

		private static void DrawEnemies(RenderTarget window)
		{
			foreach (Movable enemy in enemies)
			{
				enemy.Draw(window);
			}
		}

		private static void DrawEnemyProjectiles(RenderTarget window)
		{
			foreach (EnemyProjectile projectile in enemyProjectiles)
			{
				projectile.Draw(window);
			}
		}

		private static void DrawHeroProjectiles(RenderTarget window)
		{
			foreach (HeroProjectile projectile in heroProjectiles)
			{
				projectile.Draw(window);
			}
		}

		private static void UpdateEnemies(float timeDelta)
		{
			foreach (Movable enemy in enemies)
			{
				enemy.Update(timeDelta, new[] { hero });
			}

			//Add new enemies
			enemiesBuffer.Clear();

			foreach (Drawable enemy in enemies)
			{
				if (enemy is Movable)
				{
					if (!(enemy is Mini) && enemy.ToDelete)
					{
						//enemiesBuffer.Add();
						enemiesBuffer.Add(new Mini((enemy as Movable).Pos + Common.MovePointByAngle(Mini.Size, 0), 0));
						enemiesBuffer.Add(new Mini((enemy as Movable).Pos + Common.MovePointByAngle(Mini.Size, 118), 118));
						enemiesBuffer.Add(new Mini((enemy as Movable).Pos + Common.MovePointByAngle(Mini.Size, 236), 236));
					}
				}
			}

			foreach (Movable enemy in enemiesBuffer)
			{
				enemies.Add(enemy);
			}

			//Remove all enemies that died
			enemies.RemoveAll(x => x.ToDelete);
		}

		private static void UpdateEnemyProjectiles(float timeDelta)
		{
			IEnumerable<Drawable> heroList = new[] { hero };
			foreach (EnemyProjectile enemyProjectile in enemyProjectiles)
			{
				enemyProjectile.Update(timeDelta, heroList);
			}

			//Remove all enemy projectile that died
			enemyProjectiles.RemoveAll(x => x.ToDelete);
		}

		private static void UpdateHeroProjectiles(float timeDelta)
		{
			foreach (HeroProjectile projectile in heroProjectiles)
			{
				projectile.Update(timeDelta, enemies);
			}

			//Remove all heroProjectiles that died
			heroProjectiles.RemoveAll(x => x.ToDelete);
		}

		private static void UpdateText()
		{
			foreach (ScreenText screenText in screenTexts)
			{
				screenText.Update();
			}
		}

		#endregion Private Methods
	}
}


text:
<?php

namespace backend\modules\usermanage\controllers;

use Yii;
use common\models\User;
use common\models\CreateUser;
use common\models\UpdateUser;
use common\models\UpdatePass;
use common\models\SetPass;
use yii\data\ActiveDataProvider;
use app\models\UserSearch;
//use yii\web\Controller;
use common\component\AccessController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\base\Model;
use yii\web\Response;
use yii\widgets\ActiveForm;
/**
 * UserController implements the CRUD actions for User model.
 */
class UserController extends AccessController
{

    public function behaviors()
    {
        return array_merge(parent::behaviors(), [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ]);
    }

    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionValidate($id =0)
    {
        if($id){
            if (($model = UpdateUser::findOne($id)) !== null) {
            } else {
                throw new NotFoundHttpException('The requested page does not exist.');
            }
        }else{
            $model = new CreateUser;
        }

        if ($model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
    }

    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new UserSearch;
        $dataProvider = $searchModel->search(Yii::$app->request->getQueryParams());

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }

    /**
     * Displays a single User model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new CreateUser;

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->Id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        if (($model = UpdateUser::findOne($id)) !== null) {
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->Id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing User model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->softdelete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the User model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return User the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionSetpassword($id)
    {
        if (($model = SetPass::findOne($id)) !== null) {
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->Id]);
        } else {
            return $this->render('setPass', [
                'model' => $model,
            ]);
        }
    }

    public function actionUpdategroups($id) {
        $models = \common\models\UpdateGroup::findOne($id);

        if ($models->load(Yii::$app->request->post()) && $models->saveAll()) {
            return $this->redirect(['view', 'id' => $models->Id]);
        } else {
            return $this->render('updategroup', [
                'model' => $models,
            ]);
        }
    }
}


text:
package org.arquillian.cube.docker.drone;

import org.jboss.arquillian.config.descriptor.api.ArquillianDescriptor;
import org.jboss.arquillian.core.api.InstanceProducer;
import org.jboss.arquillian.core.api.annotation.ApplicationScoped;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.api.annotation.Observes;

public class CubeDroneConfigurator {

    @Inject
    @ApplicationScoped
    InstanceProducer<CubeDroneConfiguration> cubeDroneConfigurationInstanceProducer;

    public void configure(@Observes ArquillianDescriptor arquillianDescriptor) {
        cubeDroneConfigurationInstanceProducer.set(
                CubeDroneConfiguration.fromMap(
                        arquillianDescriptor.extension("cubedrone").getExtensionProperties()
                )
        );
    }

}