text:
Customizing Grids
=================

We assume that you are familiar what grids are. If not check the documentation of the :doc:`Grid Bundle </bundles/SyliusGridBundle/index>`
and :doc:`Grid Component </components/Grid/index>` first.

Why would you customize grids?
------------------------------

When you would like to change how the index view of an entity looks like in the administration panel,
then you have to override its grid.

* remove a field from grid
* change a field of grid
* reorder fields
* override entire grid

How to customize grids?
-----------------------

.. tip::

    First of all if you are attempting to change anything in any state machine in **Sylius** you will need a special file:
    ``app/config/grids.yml`` which has to be imported in the ``app/config/config.yml``.

.. code-block:: yaml

    # app/config/config.yml
    imports:
        - { resource: "grids.yml" }

How to remove a field from grid?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If you would like to remove a field for an existing Sylius grid, you will need to disable it in the `app/config/grids.yml`.

Let's imagine that we would like to hide the **titles of product reviews** field on the `sylius_admin_product_review` grid.

.. code-block:: yaml

    # app/config/grids.yml
    sylius_grid:
        grids:
            sylius_admin_product_review:
                fields:
                    title:
                        enabled: false

That's all. Now the `title` field will be disabled.

How to modify a field of grid?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If you would like to modify for instance a label of any field from grid, that's what you need to do:

.. code-block:: yaml

    # app/config/grids.yml
    sylius_grid:
        grids:
            sylius_admin_product_review:
                fields:
                    date:
                        label: "When was it added?"

How to remove a filter from grid?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If you would like to remove a filter for an existing Sylius grid, you will need to disable it in the `app/config/grids.yml`.

Let's imagine that we would like to hide the **titles filter of product reviews** on the `sylius_admin_product_review` grid.

.. code-block:: yaml

    # app/config/grids.yml
    sylius_grid:
        grids:
            sylius_admin_product_review:
                filters:
                    title:
                        enabled: false

That's all. Now the `title` filter will be disabled.

How to remove an action from grid?
----------------------------------

If you would like to disable some actions for any grid you just need to set their `enabled` option to `false` like below:

.. code-block:: yaml

    # app/config/grids.yml
    sylius_grid:
        grids:
            sylius_admin_product_review:
                actions:
                    item:
                        delete:
                            type: delete
                            enabled: false

How to modify positions of fields, filters and actions in grid?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

For fields, filters and actions it is possible to easily change the order in which they are displayed in the grid.

See an example of fields order modification on the `sylius_admin_product_review` grid below:

.. code-block:: yaml

    # app/config/grids.yml
    sylius_grid:
        grids:
            sylius_admin_product_review:
                fields:
                    date:
                        position: 5
                    title:
                        position: 6
                    rating:
                        position: 3
                    status:
                        position: 1
                    reviewSubject:
                        position: 2
                    author:
                        position: 4

Learn more
----------

* :doc:`Grid - Component Documentation </components/Grid/index>`
* :doc:`Grid - Bundle Documentation </bundles/SyliusGridBundle/index>`


text:
package net.sf.mmm.code.api.node;

import net.sf.mmm.code.api.copy.CodeCopyMapper;
import net.sf.mmm.code.api.item.CodeItem;
import net.sf.mmm.code.api.item.CodeMutableItem;

/**
 * {@link CodeNode} that is also a {@link CodeItem}.
 *
 * @author Joerg Hohwiller (hohwille at users.sourceforge.net)
 * @since 1.0.0
 */
public abstract interface CodeNodeItem extends CodeNode, CodeMutableItem {

  @Override
  CodeNodeItem copy();

  @Override
  CodeNodeItem copy(CodeCopyMapper mapper);

}

redpajama_set_name: RedPajamaGithub


text:
import traceback

from st2tests import config as test_config
test_config.parse_args()

from st2actions import worker
from st2actions import scheduler
from st2actions.notifier import notifier
from st2common.constants import action as action_constants
from st2common.models.db.liveaction import LiveActionDB

__all__ = [
    'MockLiveActionPublisher'
]

class MockLiveActionPublisher(object):

    @classmethod
    def publish_create(cls, payload):
        try:
            if isinstance(payload, LiveActionDB):
                scheduler.get_scheduler().process(payload)
        except Exception:
            traceback.print_exc()
            print(payload)

    @classmethod
    def publish_state(cls, payload, state):
        try:
            if isinstance(payload, LiveActionDB):
                if state == action_constants.LIVEACTION_STATUS_REQUESTED:
                    scheduler.get_scheduler().process(payload)
                else:
                    worker.get_worker().process(payload)
        except Exception:
            traceback.print_exc()
            print(payload)

    @classmethod
    def publish_update(cls, payload):
        try:
            if isinstance(payload, LiveActionDB):
                notifier.get_notifier().process(payload)
        except Exception:
            traceback.print_exc()
            print(payload)


text:
<?php if(!$pager->pageCount) return ?>
<?php if(isset($pager->previous)): ?>
<a class="previous" href="<?php echo $url.'?page='.$pager->previous ?>">Wstecz
<?php else: ?>
Wstecz
<?php endif ?> |
<?php foreach ($pager->pagesInRange as $page): ?>
<?php if ($page != $pager->current): ?>
    <a href="<?php echo $url.'?page='.$page; ?>"><?php echo $page; ?> |
<?php else: ?>
    <?php echo $page; ?> |
<?php endif; ?>
<?php endforeach; ?>
<?php if(isset($pager->next)): ?>
<a class="next" href="<?php echo $url.'?page='.$pager->next ?>">Dalej
<?php else: ?>
Dalej
<?php endif ?>


text:
/**
 * Empty name space for the Message singleton.
 *
 * @namespace Blockly.Msg
 */
import * as goog from '../closure/goog/goog.js';
goog.declareModuleId('Blockly.Msg');

/** A dictionary of localised messages. */
export const Msg: {[key: string]: string} = Object.create(null);

/**
 * Sets the locale (i.e. the localized messages/block-text/etc) to the given
 * locale.
 *
 * This is not useful/necessary when loading from a script tag, because the
 * messages are automatically cluged into the Blockly.Msg object. But we provide
 * it in both the script-tag and non-script-tag contexts so that the tscompiler
 * can properly create our type definition files.
 *
 * @param locale An object defining the messages for a given language.
 */
export const setLocale = function(locale: {[key: string]: string}) {
  Object.keys(locale).forEach(function(k) {
    Msg[k] = locale[k];
  });
};


text:
from binding import *
from ..namespace import sys
from ..ADT.StringRef import StringRef

DynamicLibrary = sys.Class()

@DynamicLibrary
class DynamicLibrary:
    _include_ = 'llvm/Support/DynamicLibrary.h'
    isValid = Method(cast(Bool, bool))
    getAddressOfSymbol = Method(cast(VoidPtr, int), cast(str, ConstCharPtr))

    LoadPermanentLibrary = CustomStaticMethod(
                          'DynamicLibrary_LoadLibraryPermanently',
                          PyObjectPtr,             # bool --- failed?
                          cast(str, ConstCharPtr), # filename
                          PyObjectPtr,             # std::string * errmsg = 0
                          ).require_only(1)

    SearchForAddressOfSymbol = StaticMethod(cast(VoidPtr, int), # address
                                            cast(str, ConstCharPtr), # symName
                                            )

    AddSymbol = StaticMethod(Void,
                             cast(str, StringRef), # symbolName
                             cast(int, VoidPtr),   # address
                             )

    getPermanentLibrary = CustomStaticMethod(
                          'DynamicLibrary_getPermanentLibrary',
                          PyObjectPtr,
                          cast(str, ConstCharPtr), # filename
                          PyObjectPtr,             # std::string * errmsg = 0
                          ).require_only(1)


text:
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

For example, given the following triangle

```
[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]
```

The minimum path sum from top to bottom is `11` (i.e., 2 + 3 + 5 + 1 = 11).

**Note:**

Bonus point if you are able to do this using only O(*n*) extra space, where *n* is the total number of rows in the triangle.


text:
"""A test runner based on multiprocessing.

This program will run all the tests in separate processes to speed things up.
"""

import curses
import os
import StringIO
import subprocess
import sys
import time
import unittest

import psutil

# These need to register plugins so,
# pylint: disable=unused-import,g-bad-import-order
from grr.lib import server_plugins
from grr.checks import tests
from grr.client import tests

from grr.gui.api_plugins import tests
from grr.gui import http_api_test
from grr.gui import api_aff4_object_renderers_test
from grr.gui import api_value_renderers_test
from grr.lib import flags
from grr.lib import test_lib
from grr.lib import tests
from grr.lib import utils
from grr.parsers import tests
from grr.server.data_server import tests
from grr.tools.export_plugins import tests
from grr.worker import worker_test
# pylint: enable=unused-import,g-bad-import-order

flags.DEFINE_string("output", None,
                    "The name of the file we write on (default stderr).")

flags.DEFINE_list("exclude_tests", [],
                  "A comma-separated list of tests to exclude form running.")

flags.DEFINE_integer("processes", 0,
                     "Total number of simultaneous tests to run.")

class Colorizer(object):
  """A Class which wraps a string with colors."""

  COLORS = "BLACK BLUE GREEN CYAN RED MAGENTA YELLOW WHITE"
  COLOR_MAP = dict([(x, i) for i, x in enumerate(COLORS.split())])

  terminal_capable = False

  def __init__(self, stream=None):
    if stream is None:
      stream = sys.stdout

    try:
      if stream.isatty():
        curses.setupterm()
        self.terminal_capable = True
    except AttributeError:
      pass

  def Render(self, color, string, forground=True):
    """Decorate the string with the ansii escapes for the color."""
    if not self.terminal_capable or color not in self.COLOR_MAP:
      return string

    escape_seq = curses.tigetstr("setf")
    if not forground:
      escape_seq = curses.tigetstr("setb")

    if not escape_seq:
      return string

    return (curses.tparm(escape_seq, self.COLOR_MAP[color]) + string +
            curses.tigetstr("sgr0"))

class GRREverythingTestLoader(test_lib.GRRTestLoader):
  """Load all GRR test cases."""
  base_class = test_lib.GRRBaseTest

def RunTest(test_suite, stream=None):
  """Run an individual test.

  Ignore the argument test_suite passed to this function, then
  magically acquire an individual test name as specified by the --tests
  flag, run it, and then exit the whole Python program completely.

  Args:
    test_suite: Ignored.
    stream: The stream to print results to.

  Returns:
    This function does not return; it causes a program exit.
  """

  out_fd = stream
  if stream:
    out_fd = StringIO.StringIO()

  try:
    # Here we use a GRREverythingTestLoader to load tests from.
    # However, the fact that GRREverythingTestLoader loads all
    # tests is irrelevant, because GrrTestProgram simply reads
    # from the --tests flag passed to the program, so not all
    # tests are ran. Only the test specified via --tests will
    # be ran. Because --tests supports only one test at a time
    # this will cause only an individual test to be ran.
    # GrrTestProgram then terminates the execution of the whole
    # python program using sys.exit() so this function does not
    # return.
    test_lib.GrrTestProgram(argv=[sys.argv[0], test_suite],
                            testLoader=GRREverythingTestLoader(
                                labels=flags.FLAGS.labels),
                            testRunner=unittest.TextTestRunner(
                                stream=out_fd))
  finally:
    # Clean up before the program exits.
    if stream:
      stream.write("Test name: %s\n" % test_suite)
      stream.write(out_fd.getvalue())
      stream.flush()

def WaitForAvailableProcesses(processes, max_processes=5, completion_cb=None):
  while True:
    pending_processes = 0

    # Check up on all the processes in our queue:
    for name, metadata in processes.items():
      # Skip the processes which already exited.
      if metadata.get("exit_code") is not None:
        continue

      exit_code = metadata["pipe"].poll()

      if exit_code is None:
        pending_processes += 1
      else:
        metadata["exit_code"] = exit_code

        # Child has exited, report it.
        if completion_cb:
          completion_cb(name, metadata)

    # Do we need to wait for processes to become available?
    if pending_processes <= max_processes:
      break

    time.sleep(0.1)

def ReportTestResult(name, metadata):
  """Print statistics about the outcome of a test run."""
  now = time.time()
  colorizer = Colorizer()

  if metadata["exit_code"] == 0:
    # Test completed successfully:
    result = colorizer.Render("GREEN", "PASSED")
  else:
    result = colorizer.Render("RED", "FAILED")
    result += open(metadata["output_path"], "rb").read()

  print "\t{0: <40} {1} in {2: >6.2f}s".format(
      name, result, now - metadata["start"])

def DoesTestHaveLabels(cls, labels):
  """Returns true if any tests in cls have any of the labels."""
  labels = set(labels)

  for name in dir(cls):
    if name.startswith("test"):
      item = getattr(cls, name, None)
      if labels.intersection(getattr(item, "labels", set(["small"]))):
        return True

  return False

def main(argv=None):
  if flags.FLAGS.tests:
    stream = sys.stderr

    if flags.FLAGS.output:
      stream = open(flags.FLAGS.output, "ab")
      os.close(sys.stderr.fileno())
      os.close(sys.stdout.fileno())
      sys.stderr = stream
      sys.stdout = stream

    sys.argv = [""]
    if flags.FLAGS.verbose:
      sys.argv.append("--verbose")

    if flags.FLAGS.debug:
      sys.argv.append("--debug")

    suites = flags.FLAGS.tests or test_lib.GRRBaseTest.classes

    if len(suites) != 1:
      raise ValueError("Only a single test is supported in single "
                       "processing mode, but %i were specified" %
                       len(suites))

    test_suite = suites[0]
    print "Running test %s in single process mode" % test_suite
    sys.stdout.flush()
    RunTest(test_suite, stream=stream)

  else:
    processes = {}
    print "Running tests with labels %s" % ",".join(flags.FLAGS.labels)

    with utils.TempDirectory() as temp_dir:
      start = time.time()
      labels = set(flags.FLAGS.labels)

      for name, cls in test_lib.GRRBaseTest.classes.items():
        if name.startswith("_"):
          continue

        if labels and not DoesTestHaveLabels(cls, labels):
          continue

        if name in flags.FLAGS.exclude_tests:
          print "Skipping test %s" % name
          continue

        result_filename = os.path.join(temp_dir, name)

        argv = [sys.executable] + sys.argv[:]
        if "--output" not in argv:
          argv.extend(["--output", result_filename])

        if flags.FLAGS.config:
          argv.extend(["--config", flags.FLAGS.config])

        argv.extend(["--tests", name])
        argv.extend(["--labels", ",".join(flags.FLAGS.labels)])

        # Maintain metadata about each test.
        processes[name] = dict(pipe=subprocess.Popen(argv),
                               start=time.time(), output_path=result_filename,
                               test=name)

        max_processes = flags.FLAGS.processes
        if not max_processes:
          max_processes = max(psutil.cpu_count() - 1, 1)
        WaitForAvailableProcesses(
            processes, max_processes=max_processes,
            completion_cb=ReportTestResult)

      # Wait for all jobs to finish.
      WaitForAvailableProcesses(processes, max_processes=0,
                                completion_cb=ReportTestResult)

      passed_tests = [p for p in processes.values() if p["exit_code"] == 0]
      failed_tests = [p for p in processes.values() if p["exit_code"] != 0]

      print "\nRan %s tests in %0.2f sec, %s tests passed, %s tests failed." % (
          len(processes), time.time() - start, len(passed_tests),
          len(failed_tests))

      if failed_tests:
        colorizer = Colorizer()

        print "Failing tests: "
        for metadata in failed_tests:
          print colorizer.Render("RED", metadata["test"])

        sys.exit(-1)

if __name__ == "__main__":
  flags.StartMain(main)


text:
using System;
using System.Collections.Generic;
using System.Data.Linq;
using LinqToDB.Mapping;

namespace Tests.Model
{
	public class Northwind
	{
		public abstract class EntityBase<T>
			where T: notnull

		{
			protected abstract T Key { get; }

			public override bool Equals(object? obj)
			{
				if (obj == null)
					return false;

				return GetType() == obj.GetType() && Key.Equals(((EntityBase<T>)obj).Key);
			}

			public override int GetHashCode()
			{
				return Key.GetHashCode();
			}
		}

		[Table("Categories")]
		public class Category
		{
			[PrimaryKey, Identity] public int     CategoryID;
			[Column, NotNull]      public string  CategoryName = null!;
			[Column]               public string? Description;
			[Column]               public Binary? Picture;

			[Association(ThisKey="CategoryID", OtherKey="CategoryID")]
			public List<Product> Products = null!;
		}

		[Table("CustomerCustomerDemo")]
		public class CustomerCustomerDemo
		{
			[PrimaryKey, NotNull] public string CustomerID = null!;
			[PrimaryKey, NotNull] public string CustomerTypeID = null!;

			[Association(ThisKey="CustomerTypeID", OtherKey="CustomerTypeID")]
			public CustomerDemographic CustomerDemographics = null!;

			[Association(ThisKey="CustomerID", OtherKey="CustomerID")]
			public Customer Customers = null!;
		}

		[Table("CustomerDemographics")]
		public class CustomerDemographic
		{
			[PrimaryKey, NotNull] public string  CustomerTypeID = null!;
			[Column]              public string? CustomerDesc;

			[Association(ThisKey="CustomerTypeID", OtherKey="CustomerTypeID")]
			public List<CustomerCustomerDemo> CustomerCustomerDemos = null!;
		}

		[Table(Name="Customers")]
		public class Customer : EntityBase<string>
		{
			[PrimaryKey]      public string  CustomerID = null!;
			[Column, NotNull] public string  CompanyName = null!;
			[Column]          public string? ContactName;
			[Column]          public string? ContactTitle;
			[Column]          public string? Address;
			[Column]          public string? City;
			[Column]          public string? Region;
			[Column]          public string? PostalCode;
			[Column]          public string? Country;
			[Column]          public string? Phone;
			[Column]          public string? Fax;

			[Association(ThisKey="CustomerID", OtherKey="CustomerID")]
			public List<CustomerCustomerDemo> CustomerCustomerDemos = null!;

			[Association(ThisKey="CustomerID", OtherKey="CustomerID")]
			public List<Order> Orders = null!;

			protected override string Key
			{
				get { return CustomerID; }
			}
		}

		[Table(Name="Employees")]
		public class Employee : EntityBase<int>
		{
			[PrimaryKey, Identity] public int       EmployeeID;
			[Column, NotNull]      public string    LastName = null!;
			[Column, NotNull]      public string    FirstName = null!;
			[Column]               public string?   Title;
			[Column]               public string?   TitleOfCourtesy;
			[Column]               public DateTime? BirthDate;
			[Column]               public DateTime? HireDate;
			[Column]               public string?   Address;
			[Column]               public string?   City;
			[Column]               public string?   Region;
			[Column]               public string?   PostalCode;
			[Column]               public string?   Country;
			[Column]               public string?   HomePhone;
			[Column]               public string?   Extension;
			[Column]               public Binary?   Photo;
			[Column]               public string?   Notes;
			[Column]               public int?      ReportsTo;
			[Column]               public string?   PhotoPath;

			[Association(ThisKey="EmployeeID", OtherKey="ReportsTo")]  public List<Employee>          Employees = null!;
			[Association(ThisKey="EmployeeID", OtherKey="EmployeeID")] public List<EmployeeTerritory> EmployeeTerritories = null!;
			[Association(ThisKey="EmployeeID", OtherKey="EmployeeID")] public List<Order>             Orders = null!;
			[Association(ThisKey="ReportsTo",  OtherKey="EmployeeID")] public Employee?               ReportsToEmployee;

			public Employee?          Employee2         { get; set; }
			public Order?             Order             { get; set; }
			public EmployeeTerritory? EmployeeTerritory { get; set; }

			protected override int Key
			{
				get { return EmployeeID; }
			}
		}

		[Table("EmployeeTerritories")]
		public class EmployeeTerritory
		{
			[PrimaryKey]          public int    EmployeeID;
			[PrimaryKey, NotNull] public string TerritoryID = null!;

			[Association(ThisKey="EmployeeID",  OtherKey="EmployeeID")]  public Employee  Employee = null!;
			[Association(ThisKey="TerritoryID", OtherKey="TerritoryID")] public Territory Territory = null!;
		}

		[Table(Name="Order Details")]
		public class OrderDetail
		{
			[PrimaryKey] public int     OrderID;
			[PrimaryKey] public int     ProductID;
			[Column]     public decimal UnitPrice;
			[Column]     public short   Quantity;
			[Column]     public double  Discount;

			[Association(ThisKey="OrderID",   OtherKey="OrderID")]   public Order   Order = null!;
			[Association(ThisKey="ProductID", OtherKey="ProductID")] public Product Product = null!;
		}

		[Table(Name="Orders")]
		public class Order : EntityBase<int>
		{
			[PrimaryKey, Identity] public int       OrderID;
			[Column]               public string?   CustomerID;
			[Column]               public int?      EmployeeID;
			[Column]               public DateTime? OrderDate;
			[Column]               public DateTime? RequiredDate;
			[Column]               public DateTime? ShippedDate;
			[Column]               public int?      ShipVia;
			[Column]               public decimal   Freight;
			[Column]               public string?   ShipName;
			[Column]               public string?   ShipAddress;
			[Column]               public string?   ShipCity;
			[Column]               public string?   ShipRegion;
			[Column]               public string?   ShipPostalCode;
			[Column]               public string?   ShipCountry;

			[Association(ThisKey="OrderID",    OtherKey="OrderID")]                     public List<OrderDetail> OrderDetails = null!;
			[Association(ThisKey="CustomerID", OtherKey="CustomerID", CanBeNull=false)] public Customer?         Customer;
			[Association(ThisKey="EmployeeID", OtherKey="EmployeeID")]                  public Employee?         Employee;
			[Association(ThisKey="ShipVia",    OtherKey="ShipperID")]                   public Shipper?          Shipper;

			public OrderDetail? OrderDetail { get; set; }

			protected override int Key
			{
				get { return OrderID; }
			}
		}

		[Table(Name="Products")]
		[InheritanceMapping(Code=true,  Type=typeof(DiscontinuedProduct))]
		[InheritanceMapping(Code=false, Type=typeof(ActiveProduct))]
		public abstract class Product
		{
			[PrimaryKey, Identity]         public int      ProductID;
			[Column, NotNull]              public string   ProductName = null!;
			[Column]                       public int?     SupplierID;
			[Column]                       public int?     CategoryID;
			[Column]                       public string?  QuantityPerUnit;
			[Column]                       public decimal? UnitPrice;
			[Column]                       public short?   UnitsInStock;
			[Column]                       public short?   UnitsOnOrder;
			[Column]                       public short?   ReorderLevel;
			[Column(IsDiscriminator=true)] public bool     Discontinued;

			[Association(ThisKey="ProductID",  OtherKey="ProductID")]  public List<OrderDetail> OrderDetails = null!;
			[Association(ThisKey="CategoryID", OtherKey="CategoryID")] public Category?         Category;
			[Association(ThisKey="SupplierID", OtherKey="SupplierID")] public Supplier?         Supplier;
		}

		public class ActiveProduct       : Product {}
		public class DiscontinuedProduct : Product {}

		[Table(Name="Region")]
		public class Region
		{
			[PrimaryKey]      public int    RegionID;
			[Column, NotNull] public string RegionDescription = null!;

			[Association(ThisKey="RegionID", OtherKey="RegionID")]
			public List<Territory> Territories = null!;
		}

		[Table(Name="Shippers")]
		public class Shipper
		{
			[PrimaryKey, Identity] public int     ShipperID;
			[Column, NotNull]      public string  CompanyName = null!;
			[Column]               public string? Phone;

			[Association(ThisKey="ShipperID", OtherKey="ShipVia")]
			public List<Order> Orders = null!;
		}

		[Table(Name="Suppliers")]
		public class Supplier
		{
			[PrimaryKey, Identity] public int     SupplierID;
			[Column, NotNull]      public string  CompanyName = null!;
			[Column]               public string? ContactName;
			[Column]               public string? ContactTitle;
			[Column]               public string? Address;
			[Column]               public string? City;
			[Column]               public string? Region;
			[Column]               public string? PostalCode;
			[Column]               public string? Country;
			[Column]               public string? Phone;
			[Column]               public string? Fax;
			[Column]               public string? HomePage;

			[Association(ThisKey="SupplierID", OtherKey="SupplierID")]
			public List<Product> Products = null!;
		}

		[Table(Name="Territories")]
		public class Territory
		{
			[PrimaryKey, NotNull] public string TerritoryID = null!;
			[Column, NotNull]     public string TerritoryDescription = null!;
			[Column]              public int    RegionID;

			public EmployeeTerritory? EmployeeTerritory { get; set; }

			[Association(ThisKey="TerritoryID", OtherKey="TerritoryID")]
			public List<EmployeeTerritory> EmployeeTerritories = null!;

			[Association(ThisKey="RegionID", OtherKey="RegionID")]
			public Region Region = null!;
		}
	}
}


text:
require 'erb'
module Flok
  module TransitionCompiler
    #Compile a ruby file containing flok controller definitions (from the transition)
    def self.compile rb_src
      #Execute code in this context, the context will hold all the information
      #that is used to then generate code
      context = TransitionCompilerContext.new
      context.instance_eval(rb_src, __FILE__, __LINE__)

      @src = ""
      ctable_erb = File.read File.join(File.dirname(__FILE__), "./transition_compiler_templates/ttable.js.erb")
      ctable_renderer = ERB.new(ctable_erb)
      @src << ctable_renderer.result(context.get_binding)

      #puts @src

      return @src
    end
  end
end

#Compiler executes all rb code inside this context
module Flok
  class TransitionCompilerContext
    attr_accessor :controllers, :actions, :ons

    def initialize
      @controllers = []
      @actions = []
      @ons = []
    end

    def get_binding
      return binding
    end

    def transition name, &block
    end

    def action controller, name, &block
      @actions << TransitionCompilerAction.new(controller, name, self, &block)
    end

    def on controller_name, action_name, name, &block
    end

    def actions_for_controller controller_name
      return @actions.select{|e| e.controller.name == controller_name}
    end

    def spots_for_controller controller_name
      return @controllers.detect{|e| e.name == controller_name}.spots
    end
  end

  #Event handler inside an action
  class TransitionCompilerOn
    attr_accessor :controller_name, :action_name, :name
  end

  class TransitionCompilerAction
    attr_accessor :controller, :name, :on_entry_src, :ons

    def initialize controller, name, ctx, &block
      @controller = controller
      @name = name
      @ctx = ctx
      @ons = [] #Event handlers

      self.instance_eval(&block)
    end

    def on_entry js_src
      #returns a string
      @on_entry_src = macro(js_src)
    end

    def on name, js_src
      @ons << {:name => name, :src => macro(js_src)}
    end

    def macro js_src
      lines = js_src.split("\n").map do |line|

      end

      return lines.join("\n")
    end

    def macro text
      out = StringIO.new

      text.split("\n").each do |l|
        #EMBED(vc_name, spot_name, context) macro
        if l =~ /Embed/
          l.strip!
          l.gsub!(/Embed\(/, "")
          l.gsub! /\)$/, ""
          l.gsub! /\);$/, ""
          o = l.split(",").map{|e| e.strip}

          vc_name = o.shift.gsub(/"/, "")
          spot_name = o.shift.gsub(/"/, "")
          context = o.shift

          #Get the spot
          spot_index = @controller.spots.index(spot_name)
          raise "controller #{@controller.name.inspect} attempted to embed #{spot_name.inspect} inside #{@name.inspect}, but #{spot_name.inspect} was not defined in 'spots' (#{@controller.spots.inspect})" unless spot_index

          #Calculate spot index as an offset from the base address using the index of the spot in the spots
          #address offset
          res = %{

            var ptr = _embed("#{vc_name}", __base__+#{spot_index}+1, #{context}, __base__);
            __info__.embeds[#{spot_index-1}].push(ptr);
          }
          out.puts res
        #Send(event_name, info)
        elsif l =~ /Send/
          l.strip!
          l.gsub!(/Send\(/, "")
          l.gsub! /\)$/, ""
          l.gsub! /\);$/, ""
          o = l.split(",").map{|e| e.strip}

          event_name = o.shift.gsub(/"/, "")
          info = o.shift

          out << %{
           main_q.push([3, "if_event", __base__, "#{event_name}", #{info}])
          }
        #Raise(event_name, info)
        elsif l =~ /Raise/
          l.strip!
          l.gsub!(/Raise\(/, "")
          l.gsub! /\)$/, ""
          l.gsub! /\);$/, ""
          o = l.split(",").map{|e| e.strip}

          event_name = o.shift
          info = o.shift

          out << %{
            int_event(__info__.event_gw, #{event_name}, #{info});
          }
        #Lower(spot_name, event_name, info)
        elsif l =~ /Lower/
          l.strip!
          l.gsub!(/Lower\(/, "")
          l.gsub! /\)$/, ""
          l.gsub! /\);$/, ""
          o = l.split(",").map{|e| e.strip}

          spot_name = o.shift.gsub(/"/, "")
          event_name = o.shift
          info = o.shift

          #Get the spot
          spot_index = @controller.spots.index(spot_name)
          raise "controller #{@controller.name.inspect} attempted to lower message to #{spot_name.inspect} inside #{@name.inspect}, but #{spot_name.inspect} was not defined in 'spots' (#{@controller.spots.inspect})" unless spot_index

          #Forward an event to the appropriate spot
          out << %{

            var vcs = __info__.embeds[#{spot_index-1}];
            for (var i = 0; i < vcs.length; ++i) {
              int_event(vcs[i], #{event_name}, #{info});
            }
          }

        #GOTO(action_name)
        elsif l =~ /Goto/
          l.strip!
          l.gsub!(/Goto\(/, "")
          l.gsub! /\)$/, ""
          l.gsub! /\);$/, ""
          o = l.split(",").map{|e| e.strip}

          action_name = o.shift.gsub(/"/, "")

          #Switch the actions, reset embeds, and call on_entry
          res = %{
            var old_action = __info__.action;
            __info__.action = "#{action_name}";

            //Remove all views
            var embeds = __info__.embeds;
            for (var i = 0; i < __info__.embeds.length; ++i) {
              for (var j = 0; j < __info__.embeds[i].length; ++j) {
                //Free +1 because that will be the 'main' view
                main_q.push([1, "if_free_view", embeds[i][j]+1]);

                <% if @debug %>
                  var vp = embeds[i][j]+1;
                  //First locate spot this view belongs to in reverse hash
                  var spot = debug_ui_view_to_spot[vp];

                  //Find it's index in the spot
                  var idx = debug_ui_spot_to_views[spot].indexOf(vp);

                  //Remove it from the spot => [view]
                  debug_ui_spot_to_views[spot].splice(idx, 1);

                  //Remove it from the reverse hash
                  delete debug_ui_view_to_spot[vp];
                <% end %>
              }
            }

            //Prep embeds array, embeds[0] refers to the spot bp+2 (bp is vc, bp+1 is main)
            __info__.embeds = [];
            for (var i = 1; i < #{@controller.spots.count}; ++i) {
              __info__.embeds.push([]);
            }

            //Call on_entry for the new action via the singleton on_entry
            //located in ctable
            __info__.cte.actions[__info__.action].on_entry(__base__)

            //Send off event for action change
            main_q.push([3, "if_event", __base__, "action", {
              from: old_action,
              to: "#{action_name}"
            }]);
          }
          out.puts res
        #Request(service_name, payload, event_name_cb)
        elsif l =~ /Request/
          l.strip!
          l.gsub!(/Request\(/, "")
          l.gsub! /\)$/, ""
          l.gsub! /\);$/, ""
          o = l.split(",").map{|e| e.strip}

          name = o.shift.gsub(/"/, "")
          info = o.shift.gsub(/"/, "")
          event_name = o.shift

          out << %{
            service_#{name}_req(#{info}, __base__, #{event_name});
          }
        else
          out.puts l
        end
      end

      return out.string
    end

    #You can def things in controller and use them as macros inside actions
    #But these defs. live in the TransitionCompilerController instance and we need
    #to delegate these calls to the controller that are not available in the action
    def method_missing method, *args, &block
      if macro = @controller.macros[method]
        #Call the macro in our context
        self.instance_eval(&macro)
      else
        raise "No macro found named: #{method}"
      end
    end
  end

  class TransitionCompilerController
    attr_accessor :name, :spots, :macros
    def initialize name, ctx, &block
      @name = name
      @ctx = ctx
      @spots = ['main']
      @macros = {}

      self.instance_eval(&block)
    end

    #Create an action macro
    def macro name, &block
      @macros[name] = block
    end

    #Names of spots
    def spots *spots
      @spots += spots
    end

    #Pass through action
    def action name, &block
      @ctx.action self, name, &block
    end
  end
end


text:
import glob
import inspect
import os
import pathlib
import unittest

import monai

class TestAllImport(unittest.TestCase):
    def test_public_api(self):
        """
        This is to check "monai.__all__" should be consistent with
        the top-level folders except for "__pycache__", "_extensions" and "csrc" (cpp/cuda src)
        """
        base_folder = os.path.dirname(monai.__file__)
        to_search = os.path.join(base_folder, "*", "")
        subfolders = [os.path.basename(x[:-1]) for x in glob.glob(to_search)]
        to_exclude = ("__pycache__", "_extensions", "csrc")
        mod = []
        for code_folder in subfolders:
            if code_folder in to_exclude:
                continue
            mod.append(code_folder)
        self.assertEqual(sorted(monai.__all__), sorted(mod))

    def test_transform_api(self):
        """monai subclasses of MapTransforms must have alias names ending with 'd', 'D', 'Dict'"""
        to_exclude = {"MapTransform"}  # except for these transforms
        to_exclude_docs = {"Decollate", "Ensemble", "Invert", "SaveClassification", "RandTorchVision", "RandCrop"}
        to_exclude_docs.update({"DeleteItems", "SelectItems", "FlattenSubKeys", "CopyItems", "ConcatItems"})
        to_exclude_docs.update({"ToMetaTensor", "FromMetaTensor"})
        xforms = {
            name: obj
            for name, obj in monai.transforms.__dict__.items()
            if inspect.isclass(obj) and issubclass(obj, monai.transforms.MapTransform)
        }
        names = sorted(x for x in xforms if x not in to_exclude)
        remained = set(names)
        doc_file = os.path.join(pathlib.Path(__file__).parent.parent, "docs", "source", "transforms.rst")
        contents = pathlib.Path(doc_file).read_text() if os.path.exists(doc_file) else None
        for n in names:
            if not n.endswith("d"):
                continue
            with self.subTest(n=n):
                basename = n[:-1]  # Transformd basename is Transform
                for docname in (f"{basename}", f"{basename}d"):
                    if docname in to_exclude_docs:
                        continue
                    if (contents is not None) and f"`{docname}`" not in f"{contents}":
                        self.assertTrue(False, f"please add `{docname}` to docs/source/transforms.rst")
                for postfix in ("D", "d", "Dict"):
                    remained.remove(f"{basename}{postfix}")
        self.assertFalse(remained)

if __name__ == "__main__":
    unittest.main()


text:
package user

import "github.com/google/flatbuffers/go"

import (
	myservice "github.com/dictav/go-grpcrgen/example/myservice"
	context "golang.org/x/net/context"
	grpc "google.golang.org/grpc"
)

// Client API for User service
type UserClient interface {
	Get(ctx context.Context, in *flatbuffers.Builder,
		opts ...grpc.CallOption) (*User, error)
}

type userClient struct {
	cc *grpc.ClientConn
}

func NewUserClient(cc *grpc.ClientConn) UserClient {
	return &userClient{cc}
}

func (c *userClient) Get(ctx context.Context, in *flatbuffers.Builder,
	opts ...grpc.CallOption) (*User, error) {
	out := new(User)
	err := grpc.Invoke(ctx, "/user.User/Get", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

// Server API for User service
type UserServer interface {
	Get(context.Context, *myservice.Request) (*flatbuffers.Builder, error)
}

func RegisterUserServer(s *grpc.Server, srv UserServer) {
	s.RegisterService(&_User_serviceDesc, srv)
}

func _User_Get_Handler(srv interface{}, ctx context.Context,
	dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(myservice.Request)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(UserServer).Get(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/user.User/Get",
	}

	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(UserServer).Get(ctx, req.(*myservice.Request))
	}
	return interceptor(ctx, in, info, handler)
}

var _User_serviceDesc = grpc.ServiceDesc{
	ServiceName: "user.User",
	HandlerType: (*UserServer)(nil),
	Methods: []grpc.MethodDesc{
		{
			MethodName: "Get",
			Handler:    _User_Get_Handler,
		},
	},
	Streams: []grpc.StreamDesc{},
}


text:
<?php

namespace Phalcon\Builder;

use Phalcon\Script\Color;
use Phalcon\Config;
use Phalcon\Validation;
use Phalcon\Validation\Validator\Namespaces;

/**
 * Abstract Component
 *
 * Base class for builder components
 *
 * @package Phalcon\Builder
 */
abstract class Component
{
    /**
     * Builder Options
     * @var Options
     */
    protected $options = null;

    /**
     * Path Component
     * @var Path
     */
    protected $path;

    /**
     * Create Builder object
     *
     * @param array $options Builder options
     */
    public function __construct(array $options = array())
    {
        $this->options = new Options($options);
        $this->path = new Path(realpath('.') . DIRECTORY_SEPARATOR);
    }

    protected function checkNamespace($namespace)
    {
        $validation = new Validation();

        $validation->add('namespace', new Namespaces(array(
            'allowEmpty' => true
        )));

        $messages = $validation->validate(array('namespace' => $namespace));

        if (count($messages)) {
            $errors = array();
            foreach ($messages as $message) {
                $errors[] = $message->getMessage();
            }

            throw new BuilderException(sprintf('%s', implode(PHP_EOL, $errors)));
        }

        return true;
    }

    /**
     * Tries to find the current configuration in the application
     *
     * @param string $type Config type: ini | php
     * @return \Phalcon\Config
     * @throws BuilderException
     */
    protected function getConfig($type = null)
    {
        return $this->path->getConfig($type);
    }

    /**
     * Check if a path is absolute
     *
     * @param string $path Path to check
     *
     * @return bool
     */
    public function isAbsolutePath($path)
    {
        return $this->path->isAbsolutePath($path);
    }

    /**
     * Check if the script is running on Console mode
     *
     * @return boolean
     */
    public function isConsole()
    {
        return PHP_SAPI == 'cli';
    }

    /**
     * Check if the current adapter is supported by Phalcon
     *
     * @param  string $adapter
     *
     * @return bool
     * @throws BuilderException
     */
    public function isSupportedAdapter($adapter)
    {
        if (!class_exists('\Phalcon\Db\Adapter\Pdo\\' . $adapter)) {
            throw new BuilderException("Adapter $adapter is not supported");
        }

        return true;
    }

    /**
     * Shows a success notification
     *
     * @param string $message
     */
    protected function _notifySuccess($message)
    {
        print Color::success($message);
    }

    abstract public function build();
}


text:
  * Fixed the possibility to add a host when connecting to a unknown host
  * Fixed the encoding that was raising invalid byte sequence.

## 1.0.2

### bug fix
  * Fixed ssh input password
  * Fixed dry-run mode to not delete files from backup folder

## 1.0.1
  * The Real first release. Just improved the README.

## 1.0

* First release.


text:
import type { TArticleThread, TThread } from '@/spec'

export const CARD_THREAD = {
  JOB: 'job',
  RADAR: 'radar',
  MEETUP: 'meetup',
}

export const ARTICLE_THREAD = {
  REPO: 'repo',
  POST: 'post',
  BLOG: 'blog',
  JOB: 'job',
  RADAR: 'radar',
  WORKS: 'works',
  MEETUP: 'meetup',
} as Record<Uppercase<TArticleThread>, TArticleThread>

export const THREAD = {
  ...ARTICLE_THREAD,
  CPER: 'cper',
  MAP: 'map',
  INTERVIEW: 'interview',
  TEAM: 'team',
  PRODUCT: 'product',
  GUIDE: 'guide',
  ACCOUNT: 'account',
  SETTING: 'setting',
  // for groupher
  KANBAN: 'kanban',
  CHANGELOG: 'changelog',
  HELP: 'help',
  ABOUT: 'about',
} as Record<Uppercase<TThread>, TThread>


text:
// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.

#include <net/inet>
#include <net/dhcp/dh4client.hpp>
#include <net/ip6/slaac.hpp>
#include <smp>
#include <net/socket.hpp>
#include <net/tcp/packet4_view.hpp> // due to ICMP error //temp
#include <net/udp/packet4_view.hpp> // due to ICMP error //temp

using namespace net;

Inet::Inet(hw::Nic& nic)
  : dns_server_(IP4::ADDR_ANY),
    nic_(nic), arp_(*this), ndp_(*this),
    mld_(*this), /*mld2_(*this),*/
    ip4_(*this), ip6_(*this),
    icmp_(*this), icmp6_(*this),
    udp_(*this), tcp_(*this),
    dns_(*this), domain_name_{}, MTU_(nic.MTU())
{
  static_assert(sizeof(ip4::Addr) == 4, "IPv4 addresses must be 32-bits");

  /** SMP related **/
  this->cpu_id = SMP::cpu_id();
  INFO("Inet", "Bringing up %s on CPU %d",
        ifname().c_str(), this->get_cpu_id());

  /** Upstream delegates */
  auto arp_bottom(upstream{arp_, &Arp::receive});
  auto ip4_bottom(upstream_ip{ip4_, &IP4::receive});
  auto ip6_bottom(upstream_ip{ip6_, &IP6::receive});
  auto icmp4_bottom(upstream{icmp_, &ICMPv4::receive});
  auto icmp6_bottom(upstream{icmp6_, &ICMPv6::receive});
  auto udp4_bottom(upstream{udp_, &UDP::receive4});
  auto udp6_bottom(upstream{udp_, &UDP::receive6});
  auto tcp4_bottom(upstream{tcp_, &TCP::receive4});
  auto tcp6_bottom(upstream{tcp_, &TCP::receive6});
  auto ndp_bottom(upstream{ndp_, &Ndp::receive});
  auto mld_bottom(upstream{mld_, &Mld::receive});

  /** Upstream wiring  */
  // Packets available
  nic.on_transmit_queue_available({this, &Inet::process_sendq});

  // Link -> Arp
  nic_.set_arp_upstream(arp_bottom);

  // Link -> IP4
  nic_.set_ip4_upstream(ip4_bottom);

  // Link -> IP6
  nic_.set_ip6_upstream(ip6_bottom);

  // IP4 -> ICMP
  ip4_.set_icmp_handler(icmp4_bottom);

  // IP6 -> ICMP6
  ip6_.set_icmp_handler(icmp6_bottom);

  // IP4 -> UDP
  ip4_.set_udp_handler(udp4_bottom);

  // IP6 -> UDP
  ip6_.set_udp_handler(udp6_bottom);

  // IP4 -> TCP
  ip4_.set_tcp_handler(tcp4_bottom);

  // IP6 -> TCP
  ip6_.set_tcp_handler(tcp6_bottom);

  // ICMPv6 -> NDP
  icmp6_.set_ndp_handler(ndp_bottom);

  // ICMPv6 -> MLD
  icmp6_.set_mld_handler(mld_bottom);

  /** Downstream delegates */
  auto link_top(nic_.create_link_downstream());
  auto arp_top(IP4::downstream_arp{arp_, &Arp::transmit});
  auto ndp_top(IP6::downstream_ndp{ndp_, &Ndp::transmit});
  auto ip4_top(downstream{ip4_, &IP4::transmit});
  auto ip6_top(downstream{ip6_, &IP6::transmit});

  /** Downstream wiring. */

  // ICMP -> IP4
  icmp_.set_network_out(ip4_top);

  // ICMPv6 -> IP6
  icmp6_.set_network_out(ip6_top);

  // UDP4 -> IP4
  udp_.set_network_out4(ip4_top);

  // UDP6 -> IP6
  udp_.set_network_out6(ip6_top);

  // TCP4 -> IP4
  tcp_.set_network_out4(ip4_top);

  // TCP6 -> IP6
  tcp_.set_network_out6(ip6_top);

  // IP4 -> Arp
  ip4_.set_linklayer_out(arp_top);

  // IP6 -> Ndp
  ip6_.set_linklayer_out(ndp_top);

  // NDP -> Link
  ndp_.set_linklayer_out(link_top);

  // MLD -> Link
  mld_.set_linklayer_out(link_top);

  // Arp -> Link
  assert(link_top);
  arp_.set_linklayer_out(link_top);

#ifndef INCLUDEOS_SINGLE_THREADED
  // move this nework stack automatically
  // to the current CPU if its not 0
  if (SMP::cpu_id() != 0) {
    this->move_to_this_cpu();
  }
#endif
}

void Inet::error_report(Error& err, Packet_ptr orig_pckt) {
  // if its a forged packet, it might be too small
  if (orig_pckt->size() < 40) return;

  auto pckt_ip4 = static_unique_ptr_cast<PacketIP4>(std::move(orig_pckt));
  // Get the destination to the original packet
  Socket dest = [](std::unique_ptr<PacketIP4>& pkt)->Socket {
    // if its a forged packet, it might not be IPv4
    if (pkt->is_ipv4() == false) return {};
    switch (pkt->ip_protocol()) {
      case Protocol::UDP: {
        auto udp = udp::Packet4_view_raw(pkt.get());
        return udp.destination();
      }
      case Protocol::TCP: {
        auto tcp = tcp::Packet4_view_raw(pkt.get());
        return tcp.destination();
      }
      default:
        return {};
    }
  }(pckt_ip4);

  bool too_big = false;
  if (err.is_icmp()) {
    auto* icmp_err = dynamic_cast<ICMP_error*>(&err);
    if (icmp_err == nullptr) {
      return; // not an ICMP error
    }

    if (icmp_err->is_too_big()) {
      // If Path MTU Discovery is not enabled, ignore the ICMP Datagram Too Big message
      if (not ip4_.path_mtu_discovery())
        return;

      too_big = true;

      // We have received a response to a packet with an MTU that is too big for a node in the path,
      // and the packet has been dropped (the original packet was too big and the Don't Fragment bit was set)

      // Notify every protocol of the received MTU if any of the protocol's connections use the given
      // path (based on destination address)

      // Also need to notify the instance that sent the packet that the packet has been dropped, so
      // it can retransmit it

      // A Destination Unreachable: Fragmentation Needed ICMP error message has been received
      // And we'll notify the IP layer of the received MTU value
      // IP will create the path if it doesn't exist and only update the value if
      // the value is smaller than the already registered pmtu for this path/destination
      // If the received MTU value is zero, the method will use the original packet's Total Length
      // and Header Length values to estimate a new Path MTU value
      ip4_.update_path(dest, icmp_err->pmtu(), too_big, pckt_ip4->ip_total_length(), pckt_ip4->ip_header_length());

      // The actual MTU for the path is set in the error object
      icmp_err->set_pmtu(ip4_.pmtu(dest));
    }
  }

  if (too_big) {
    // Notify both transport layers in case they use the path
    udp_.error_report(err, dest);
    tcp_.error_report(err, dest);
  } else if (pckt_ip4->ip_protocol() == Protocol::UDP) {
    udp_.error_report(err, dest);
  } else if (pckt_ip4->ip_protocol() == Protocol::TCP) {
    tcp_.error_report(err, dest);
  }
}

void Inet::negotiate_dhcp(double timeout, dhcp_timeout_func handler) {
  INFO("Inet", "Negotiating DHCP (%.1fs timeout)...", timeout);
  if (!dhcp_)
      dhcp_ = std::make_shared<DHClient>(*this);
  // @timeout for DHCP-server negotation
  dhcp_->negotiate(std::chrono::seconds((uint32_t)timeout));
  // add timeout_handler if supplied
  if (handler)
      dhcp_->on_config(handler);
}

void Inet::autoconf_v6(int retries, slaac_timeout_func handler,
        uint64_t token, bool use_token)
{

  INFO("Inet", "Attempting automatic configuration of ipv6 address");
  if (!slaac_)
      slaac_ = std::make_unique<Slaac>(*this);

  // @Retries for Slaac auto-configuration
  slaac_->autoconf_start(retries, token, use_token);

  // add failure_handler if supplied
  if (handler)
      slaac_->on_config(handler);
}

void Inet::network_config(ip4::Addr addr,
                           ip4::Addr nmask,
                           ip4::Addr gw,
                           ip4::Addr dns)
{
  ip_obj().set_addr(addr);
  ip_obj().set_netmask(nmask);
  ip_obj().set_gateway(gw);
  this->dns_server_ = (dns == IP4::ADDR_ANY) ? gw : dns;
  INFO("Inet", "Network configured (%s)", nic_.mac().to_string().c_str());
  INFO2("IP: \t\t%s", ip_addr().str().c_str());
  INFO2("Netmask: \t%s", netmask().str().c_str());
  INFO2("Gateway: \t%s", gateway().str().c_str());
  INFO2("DNS Server: \t%s", dns_server_.str().c_str());

  for(auto& handler : configured_handlers_)
    handler(*this);

  configured_handlers_.clear();
}

void Inet::network_config6(IP6::addr addr6,
                           uint8_t   prefix6,
                           IP6::addr gateway6)
{

  ndp().set_static_addr(std::move(addr6));
  ndp().set_static_prefix(prefix6);
  ndp().set_static_gateway(std::move(gateway6));
  INFO("Inet6", "Network configured (%s)", nic_.mac().to_string().c_str());
  INFO2("IP6: \t\t%s", ndp().static_ip().to_string().c_str());
  INFO2("Prefix: \t%d", ndp().static_prefix());
  INFO2("Gateway: \t%s", ndp().static_gateway().str().c_str());

  for(auto& handler : configured_handlers_)
    handler(*this);

  configured_handlers_.clear();
}

void Inet::add_addr(const ip6::Addr& addr, uint8_t prefix,
              uint32_t pref_lifetime, uint32_t valid_lifetime)
{
  int r = this->ip6_.addr_list().input(
    addr, prefix, pref_lifetime, valid_lifetime);
  if(r == 1) {
    INFO("Inet6", "Address configured %s", addr.to_string().c_str());
  }
}

void Inet::add_addr_autoconf(const ip6::Addr& addr, uint8_t prefix,
                       uint32_t pref_lifetime, uint32_t valid_lifetime)
{
  Expects(prefix == 64);
  int r = this->ip6_.addr_list().input_autoconf(
    addr, prefix, pref_lifetime, valid_lifetime);
  if(r == 1) {
    INFO("Inet6", "Address configured %s (autoconf)", addr.to_string().c_str());
  }
}

void Inet::enable_conntrack(std::shared_ptr<Conntrack> ct)
{
  Expects(conntrack_ == nullptr && "Conntrack is already set");
  conntrack_ = ct;
}

void Inet::process_sendq(size_t packets) {

  ////////////////////////////////////////////
  // divide up fairly
  size_t div = packets / tqa.size();

  // give each protocol a chance to take
  for (size_t i = 0; i < tqa.size(); i++)
    tqa[i](div);

  // hand out remaining
  for (size_t i = 0; i < tqa.size(); i++) {
    div = transmit_queue_available();
    if (!div) break;
    // give as much as possible
    tqa[i](div);
  }
  ////////////////////////////////////////////

  /*
    size_t list[tqa.size()];
    for (size_t i = 0; i < tqa.size(); i++)
    list[i] = tqa[i](0);

    size_t give[tqa.size()] = {0};
    int cp = 0; // current protocol

    // distribute packets one at a time for each protocol
    while (packets--)
    {
    if (list[cp])
    {
    // give one packet
    give[cp]++;  list[cp]--;
    }
    cp = (cp + 1) % tqa.size();
    }
    // hand out several packets per protocol
    for (size_t i = 0; i < tqa.size(); i++)
    if (give[i]) tqa[i](give[i]);
  */
}

void Inet::force_start_send_queues()
{
  size_t packets = transmit_queue_available();
  if (packets) process_sendq(packets);
}

void Inet::move_to_this_cpu()
{
  this->cpu_id = SMP::cpu_id();
  nic_.move_to_this_cpu();
}

void Inet::cache_link_addr(ip4::Addr ip, MAC::Addr mac)
{ arp_.cache(ip, mac); }

void Inet::flush_link_cache()
{ arp_.flush_cache(); }

void Inet::set_link_cache_flush_interval(std::chrono::minutes min)
{ arp_.set_cache_flush_interval(min); }

void Inet::set_route_checker(Route_checker delg)
{ arp_.set_proxy_policy(delg); }

void Inet::reset_pmtu(Socket dest, IP4::PMTU pmtu)
{ tcp_.reset_pmtu(dest, pmtu); /* Maybe later: udp_.reset_pmtu(dest, pmtu);*/ }

void Inet::resolve(const std::string& hostname,
     resolve_func       func,
     bool               force)
{
  if(is_configured_v6() and dns_server6_ != ip6::Addr::addr_any)
    resolve(hostname, this->dns_server6_, func, force);
  else
    resolve(hostname, this->dns_server_, func, force);
}

void Inet::resolve(const std::string& hostname,
      net::Addr         server,
      resolve_func      func,
      bool              force)
{
  Expects(not hostname.empty());
  dns_.resolve(server, hostname, func, force);
}

void Inet::set_route_checker6(Route_checker6 delg)
{ ndp_.set_proxy_policy(delg); }


text:
pymatgen.io.abinit.inputs module
================================

.. automodule:: pymatgen.io.abinit.inputs
   :members:
   :undoc-members:
   :show-inheritance:


text:
form#new_company
{
    padding-top: 40px;
}

div#new_company_left
{
    float: left;
}

div#new_company_left_left
{
    float: left;
    width: 110px;
}

div#new_company_left_right
{
    float: right;
    width: 430px;
}

div#new_company_right_right
{
    float: left;
    width: 350px;
}

div#new_company_right_left
{
    float: left;
    width: 200px;
}

.hero-unit-company
{
    width: 1170px;
    height: 760px;
}

.form-error
{
    color: red;
    font-size: 11px;
}

#mrmcburger_getajobbundle_companytype_name-label
{
    padding-top: 6px;
}

#mrmcburger_getajobbundle_companytype_sector-label
{
    padding-top: 15px;
}

#mrmcburger_getajobbundle_companytype_address_number-label
{
    padding-top: 15px;
}

#mrmcburger_getajobbundle_companytype_address_type-label
{
    padding-top: 15px;
}

#mrmcburger_getajobbundle_companytype_address_name-label
{
    padding-top: 15px;
}

#mrmcburger_getajobbundle_companytype_address_additional-label
{
    padding-top: 15px;
}

#mrmcburger_getajobbundle_companytype_address_zip-label
{
    padding-top: 15px;
}

#mrmcburger_getajobbundle_companytype_address_city-label
{
    padding-top: 15px;
}

#mrmcburger_getajobbundle_companytype_presentation-label
{
    padding-top: 15px;
}

#mrmcburger_getajobbundle_companytype_numbers-label
{
    padding-top: 15px;
}

#mrmcburger_getajobbundle_companytype_phone-label
{
    padding-top: 15px;
}

#mrmcburger_getajobbundle_companytype_mail-label
{
    padding-top: 15px;
}

#mrmcburger_getajobbundle_companytype_add_company
{
    margin-top: 90px;
}

#mrmcburger_getajobbundle_companytype_companycriteria_displacement-label
{
    padding-top: 6px;
}

#mrmcburger_getajobbundle_companytype_companycriteria_celebrity-label
{
    padding-top: 15px;
}

#mrmcburger_getajobbundle_companytype_companycriteria_missionInterest-label
{
    padding-top: 15px;
}

#mrmcburger_getajobbundle_companytype_companycriteria_salaryExpectation-label
{
    padding-top: 15px;
}

#mrmcburger_getajobbundle_companytype_companycriteria_workConditions-label
{
    padding-top: 15px;
}

#mrmcburger_getajobbundle_companytype_companycriteria_evolutionPossibilities-label
{
    padding-top: 15px;
}

#newcompany-address-label
{
    padding-top: 15px;
    padding-bottom: 20px;
}

#newcompany-address-label label
{
    padding-left: 15px;
}

#newcompany-address-widget
{
    padding-top: 45px;
    padding-bottom: 20px;
}

.content
{
    width: 1120px;
    min-height:720px;
    padding-top: 40px;
    margin : auto;
    background-color: #EEEEEE;
}

#show-company
{
    padding-top: 30px;
    font-size: 14px;
    font-weight: normal;
    line-height: 20px;
}

#show-company-header-left
{
    float: left;
    width: 300px;
    padding-left: 200px;
}

#show-company-header
{
    padding-bottom: 40px;
    padding-top: 20px;
}

#address-label
{
    font-size: 14px;
    font-weight: normal;
}

#modify_company #new_company_left  #new_company_left_right #mrmcburger_getajobbundle_companytype_sector
{
    margin-top: 12px;
}

#modify_company  #new_company_left  #new_company_left_right #newcompany-address-widget
{
    padding-top: 33px;
    padding-bottom: 20px;
}

#modify_company  #new_company_right
{
    padding-top: 5px;
}

#delete_company
{
    padding-top: 60px;
}

#list-company
{
    margin-top: 50px;
}

.hero-unit-listcompany
{
    width: 1170px;
    height: 1000px;
    font-size: 14px;
    font-weight: normal;
}

.navigation
{
    margin-top: 10px;
}


text:
#pragma once

#include <windows.h>
#include <string>
#include <strsafe.h>

// NOTE: SERVICE_ACCEPT_PRESHUTDOWN is supported on Windows Vista/W2K8 and later
#define WIN32_SVC_ACCEPTED_CONTROLS  (SERVICE_ACCEPT_STOP               \
                                      | SERVICE_ACCEPT_PAUSE_CONTINUE   \
                                      | SERVICE_ACCEPT_SHUTDOWN         \
                                      | SERVICE_ACCEPT_PRESHUTDOWN      \
                                      | SERVICE_ACCEPT_POWEREVENT)

#define WIN32_SERVICES_KEY_NAME         L"System\\CurrentControlSet\\Services"
#define WIN32_SERVICES_APP_EVENTLOG_KEY L"\\EventLog\\Application"

//
// Win32ServiceT
//
// This class template implements a generic Windows service. It holds a
// reference to the real service and takes care of the common features, such
// as registering the service with the Windows Event Manager and handling
// events from the Service Control Manager. It expects the actual
// Service to provide the following member functions:
//
//  initService             - performs all initialization for starting the service
//  start                   - starts the service
//  stop                    - stops the service
//  svcCtrlPreShutdown      - prepare to shutdown (SERVICE_CONTROL_PRESHUTDOWN)
//  svcCtrlShutdown         - shutdown (SERVICE_CONTROL_SHUTDOWN)
//  svcCtrlUninstallService - uninstall (Service::SVC_CTRL_UNINSTALL_SERVICE)
//  svcCtrlStop             - SERVICE_CONTROL_STOP
//  svcCtrlPause            - SERVICE_CONTROL_PAUSE
//  svcCtrlContinue         - SERVICE_CONTROL_CONTINUE
//  svcCtrlPowerResume      - processes a PBT_APMRESUMEAUTOMATIC type power event
//  svcCtrlPowerSuspend     - processes a PBT_APMSUSPEND type power event
//  svcCtrlPowerDefault     - processes all other power events
//  svcCtrlDefault          - processes all other service control events
template <class Service>
class Win32ServiceT : public Service
{
public:
    typedef typename Service::Config        Config;
    typedef typename Config::Win32Service   Win32Service;
    typedef typename Config::Logger         Logger;

    const DWORD      m_acceptedControls;

    // Initialize with an object that provides the actual service
    Win32ServiceT();

    // Neither the copy constructor nor the copy assignment operator are implemented.
    Win32ServiceT(const Win32ServiceT& other) = delete;
    Win32ServiceT& operator=(const Win32ServiceT& rhs) = delete;

    // Neither the move constructor nor move assignment operator are implemented.
    Win32ServiceT(Win32ServiceT&& other) = delete;
    Win32ServiceT& operator=(Win32ServiceT&& rhs) = delete;

    void WINAPI svcMain(DWORD dwArgc, LPWSTR *lpszArgv);
    DWORD WINAPI svcCtrlHandler(DWORD  dwControl,
                                DWORD  dwEventType,
                                LPVOID lpEventData,
                                LPVOID lpContext);
    static void WINAPI svcMainWrapper(DWORD dwArgc, LPWSTR *lpszArgv);
    static DWORD WINAPI svcCtrlHandlerWrapper(DWORD     dwControl,
                                              DWORD     dwEventType,
                                              LPVOID    lpEventData,
                                              LPVOID    lpContext);
    void setServiceIdentity(const std::wstring& svcName,
                            const std::wstring& svcDisplayName,
                            const std::wstring& svcDescription);
    void  svcReportEvent(WORD eventType, DWORD msgID, DWORD err);
    void  svcReportEvent(WORD eventType, DWORD msgID, const std::wstring &msg);
    DWORD svcReportStatus(DWORD dwCurrentState,
                          DWORD dwWin32ExitCode,
                          DWORD dwWaitHint);
    DWORD WINAPI startWin32Service();
    DWORD WINAPI registerService(SC_HANDLE hSCM, DWORD startType, LPCTSTR path, SC_HANDLE *service);
    SC_HANDLE WINAPI openService(SC_HANDLE hSCM);
    void WINAPI deleteService();

private:
    static Win32Service    *m_win32SvcPtr;
    SERVICE_STATUS_HANDLE   m_svcStatusHandle;
    SERVICE_STATUS          m_svcStatus;
    HANDLE                  m_stopEvent;
    Logger                  m_logger;

    DWORD registerEventLog(const TCHAR *path) const;
};  // class Win32ServiceT

template <class T>
Win32ServiceT<T>::Win32ServiceT()
    : m_stopEvent(0)
    , m_acceptedControls(WIN32_SVC_ACCEPTED_CONTROLS | SVC_ACCEPTED_CONTROLS)
    , m_svcStatus{0}
{
    // Set the static pointer to this service so the static functions
    // Win32ServiceT<T>::svcMainWrapper and
    // Win32ServiceT<T>::svcCtrlHandlerWrapper can find this object.
    m_win32SvcPtr = this;

    // Tell our superclass (the *real* service) about us so it can report
    // status via svcReportStatus()
    setWin32Service(this);
}

template <class T>
DWORD Win32ServiceT<T>::registerEventLog(const TCHAR *path) const
{
    DWORD           result;
    HKEY            appEventLogKey;
    HKEY            svcEventLogKey;
    std::wstring    tmp(WIN32_SERVICES_KEY_NAME);

    tmp += WIN32_SERVICES_APP_EVENTLOG_KEY;

    // Open HKLM\System\CurrentControlSet\Services\EventLog\Application
    result = ::RegOpenKeyEx(HKEY_LOCAL_MACHINE,
                            tmp.c_str(),
                            0,
                            KEY_ALL_ACCESS,
                            &appEventLogKey);
    if (ERROR_SUCCESS == result)
    {
        // Create the service's eventlog key
        result = ::RegCreateKeyEx(appEventLogKey,
                                  m_serviceName.c_str(),
                                  0,
                                  0,
                                  REG_OPTION_NON_VOLATILE,
                                  KEY_ALL_ACCESS,
                                  NULL,
                                  &svcEventLogKey,
                                  0);
        if (ERROR_SUCCESS == result)
        {
            DWORD   supportedTypes = EVENTLOG_ERROR_TYPE
                | EVENTLOG_INFORMATION_TYPE
                | EVENTLOG_WARNING_TYPE;
            // Setup the Windows event log
            ::RegSetValueEx(svcEventLogKey,
                            TEXT("EventMessageFile"),
                            0,
                            REG_EXPAND_SZ,
                            reinterpret_cast<const BYTE *>(path),
                            static_cast<DWORD>(lstrlen(path) * sizeof(TCHAR) + sizeof(TCHAR)));

            ::RegSetValueEx(svcEventLogKey,
                            TEXT("TypesSupported"),
                            0,
                            REG_DWORD,
                            reinterpret_cast<BYTE *>(&supportedTypes),
                            sizeof supportedTypes);

            ::RegCloseKey(svcEventLogKey);
        }

        ::RegCloseKey(appEventLogKey);
    }

    return result;
}

// Function:
//  svcReportEvent
//
// Purpose:
//   Logs messages to the event log
//
// Parameters:
//   eventType -
//   msgID
//   err
//
// Return value:
//   None
//
// Remarks:
//   The service must have an entry in the Application event log.
//
template <class T>
void Win32ServiceT<T>::svcReportEvent(WORD eventType, DWORD msgID, DWORD err)
{
    HANDLE  hEventSource;
    TCHAR   buf[50];
    LPCTSTR args[] = {buf};
    WORD    count = sizeof args / sizeof LPCTSTR;
    HRESULT hResult;

    if ((eventType == EVENTLOG_INFORMATION_TYPE)
        || (eventType == EVENTLOG_WARNING_TYPE)
        || (eventType == EVENTLOG_ERROR_TYPE)
        || (eventType == EVENTLOG_SUCCESS))
    {
        hResult = ::StringCchPrintf((LPTSTR)buf,
                                    sizeof buf / sizeof(TCHAR),
                                    L"0x%08x",
                                    err);
        if (SUCCEEDED(hResult))
        {
            hEventSource = ::RegisterEventSource(NULL, m_serviceName.c_str());

            if (NULL != hEventSource)
            {
                ::ReportEvent(hEventSource,     // event log handle
                              eventType,        // event type
                              SVC_MSG_CATEGORY, // event category
                              msgID,            // event identifier
                              NULL,             // no security identifier
                              count,            // size of lpszStrings array
                              0,                // no binary data
                              args,             // array of strings
                              NULL);            // no binary data
                ::DeregisterEventSource(hEventSource);
            }
        }
        else
        {
            /// @todo: trace_warning("Failed to convert error %d to a string", err);
        }
    }
}   // Win32ServiceT<T>::svcReportEvent

// Function:
//  svcReportEvent
//
// Purpose:
//   Logs messages to the event log
//
// Parameters:
//   szFunction - name of function that failed
//
// Return value:
//   None
//
// Remarks:
//   The service must have an entry in the Application event log.
//
template <class T>
void Win32ServiceT<T>::svcReportEvent(WORD eventType, DWORD msgID, const std::wstring &msg)
{
    HANDLE  hEventSource;
    TCHAR   buf[MAX_PATH];
    LPCTSTR args[] = {buf};
    WORD    count = sizeof args / sizeof LPCTSTR;
    //HRESULT hResult;

    if ((eventType == EVENTLOG_INFORMATION_TYPE)
        || (eventType == EVENTLOG_WARNING_TYPE)
        || (eventType == EVENTLOG_ERROR_TYPE)
        || (eventType == EVENTLOG_SUCCESS))
    {

        ::wcscpy(buf, msg.c_str());
        hEventSource = ::RegisterEventSource(NULL, m_serviceName.c_str());

        if (NULL != hEventSource)
        {
            ::ReportEvent(hEventSource,     // event log handle
                          eventType,        // event type
                          SVC_MSG_CATEGORY, // event category
                          msgID,            // event identifier
                          NULL,             // no security identifier
                          count,            // size of lpszStrings array
                          0,                // no binary data
                          args,             // array of strings
                          NULL);            // no binary data
            ::DeregisterEventSource(hEventSource);
        }
    }
}   // Win32ServiceT<T>::svcReportEvent

//
// Purpose:
//   Sets the current service status and reports it to the SCM.
//
// Parameters:
//   dwCurrentState - The current state (see SERVICE_STATUS)
//   dwWin32ExitCode - The system error code
//   dwWaitHint - Estimated time for pending operation,
//     in milliseconds
//
// Return value:
//   None
//
template <class T>
DWORD Win32ServiceT<T>::svcReportStatus(DWORD    dwCurrentState,
                                        DWORD    dwWin32ExitCode,
                                        DWORD    dwWaitHint)
{
    static DWORD dwCheckPoint = 1;
    DWORD st;

    // Fill in the SERVICE_STATUS structure.
    m_svcStatus.dwCurrentState = dwCurrentState;
    m_svcStatus.dwWin32ExitCode = dwWin32ExitCode;
    m_svcStatus.dwWaitHint = dwWaitHint;

    // Accept controls if we're running or paused
    if (SERVICE_RUNNING == dwCurrentState
        || SERVICE_PAUSED == dwCurrentState)
    {
        m_svcStatus.dwControlsAccepted = m_acceptedControls;
    }
    else
    {
        m_svcStatus.dwControlsAccepted = 0;
    }

    // Increment the checkpoint until we're running or stopped
    if ((dwCurrentState == SERVICE_RUNNING)
        || (dwCurrentState == SERVICE_STOPPED))
    {
        dwCheckPoint = 0;
        m_svcStatus.dwCheckPoint = 0;
    }
    else
    {
        m_svcStatus.dwCheckPoint = dwCheckPoint++;
    }

    // Report the status of the service to the SCM.
    if (SetServiceStatus(m_svcStatusHandle, &m_svcStatus))
    {
        st = NO_ERROR;
    }
    else
    {
        st = GetLastError();
    }

    return st;
}   // Win32ServiceT<T>::svcReportStatus

//
// Purpose:
//   Entry point for the service
//
// Parameters:
//   dwArgc - Number of arguments in the lpszArgv array
//   lpszArgv - Array of strings. The first string is the name of
//     the service and subsequent strings are passed by the process
//     that called the StartService function to start the service.
//
//  Description
//
//
// Return value:
//   None.
//
template <class T>
void WINAPI Win32ServiceT<T>::svcMain(DWORD dwArgc, LPWSTR *lpszArgv)
{
    DWORD   st = ERROR_SUCCESS;

    /// @todo: log_trace(LOG_TRACE_TRACE, "Starting the service");
    m_svcStatus.dwCurrentState = SERVICE_STOPPED;
    m_svcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
    m_svcStatus.dwServiceSpecificExitCode = 0;
    svcReportEvent(EVENTLOG_INFORMATION_TYPE,
                   SVC_MSG_REGISTERING_SCM,
                   st);

    // Register the handler function for the service
    m_svcStatusHandle = ::RegisterServiceCtrlHandlerEx(lpszArgv[0],
                                                       svcCtrlHandlerWrapper,
                                                       this);

    if(m_svcStatusHandle)
    {
        // Report initial status to the SCM
        st = svcReportStatus(SERVICE_START_PENDING, NO_ERROR, SVC_WAIT_HINT);
        /// @todo: log_trace(LOG_TRACE_TRACE, "Registered service control handler");

        if (ERROR_SUCCESS == st)
        {
            // Record start-pending event
            svcReportEvent(EVENTLOG_INFORMATION_TYPE,
                           SVC_MSG_REPORTED_START_PENDING,
                           0);
            /// @todo: log_trace(LOG_TRACE_TRACE, "Reported status service start pending");
            // Create an event. The control handler function, svcCtrlHandlerWrapper,
            // signals this event when it receives the stop control code.
            m_stopEvent = ::CreateEventW(NULL,  // default security attributes
                                         TRUE,  // manual reset event
                                         FALSE, // not signaled
                                         NULL); // no name

            if (NULL != m_stopEvent)
            {
                /// @todo: log_trace(LOG_TRACE_TRACE, "Created stop event");
                svcReportEvent(EVENTLOG_INFORMATION_TYPE,
                               SVC_MSG_INITIALIZING,
                               st);

                // Initialize the real service
                st = initService();
                if (ERROR_SUCCESS == st)
                {
                    /// @todo: log_trace(LOG_TRACE_TERSE, "Service successfully initialized");
                    svcReportEvent(EVENTLOG_INFORMATION_TYPE,
                                   SVC_MSG_INITIALIZED,
                                   st);

                    // Start the real service
                    st = start();
                    if (ERROR_SUCCESS == st)
                    {
                        st = svcReportStatus(SERVICE_RUNNING, NO_ERROR, 0);
                        /// @todo: log_trace(LOG_TRACE_NOTICE, "%ws is running", m_serviceName.c_str());
                        if (ERROR_SUCCESS == st)
                        {
                            // report to the event log and trace log that the service is running
                            svcReportEvent(EVENTLOG_SUCCESS,
                                           SVC_MSG_REPORTED_STARTED,
                                           0);

                            /*
                             * wait here for a stop event.
                             */
                            ::WaitForSingleObject(m_stopEvent, INFINITE);
                            /// @todo: log_trace(LOG_TRACE_NOTICE, "%ws stopped", m_serviceName.c_str());
                            svcReportEvent(EVENTLOG_SUCCESS,
                                           SVC_MSG_STOPPED,
                                           0);
                            svcReportStatus(SERVICE_STOPPED, st, 0);
                        }
                        else
                        {
                            stop();
                            /// @todo: log_trace_error("Failed to report service running: %d", st);

                            svcReportEvent(EVENTLOG_ERROR_TYPE,
                                           SVC_MSG_START_FAILURE,
                                           st);
                            svcReportStatus(SERVICE_STOPPED, st, 0);
                        }
                    }
                    else
                    {
                        /// @todo: log_trace_error("Failed to start service: 0x%08x", st);
                        svcReportEvent(EVENTLOG_ERROR_TYPE,
                                       SVC_MSG_START_FAILURE,
                                       st);
                        svcReportStatus(SERVICE_STOPPED, st, 0);
                    }
                }
                else
                {
                    svcReportEvent(EVENTLOG_ERROR_TYPE,
                                   SVC_MSG_INITIALIZATION_FAILURE,
                                   st);
                    svcReportStatus(SERVICE_STOPPED, st, 0);
                }
            }
            else
            {
                st = ::GetLastError();
                /// @todo: log_trace_error("Reporting status service start pending failed: %d", st);
                svcReportStatus(SERVICE_STOPPED, st, 0);
            }
        }
        else
        {
            /// @todo: log_trace_error("Failed to report service service start-pending: %d", st);
        }
    }
    else
    {
        st = GetLastError();
        /// @todo: log_trace_error("Failed register service: %d", st);
    }
}   // Win32ServiceT<T>::svcMain

/*
** Win32ServiceT<T>::svcCtrlHandler handles the following service controls:
**
**  SERVICE_CONTROL_PRESHUTDOWN
**  SERVICE_CONTROL_SHUTDOWN
**  SVC_CTRL_UNINSTALL_SERVICE
**  SERVICE_CONTROL_STOP
**  SERVICE_CONTROL_PAUSE
**  SERVICE_CONTROL_CONTINUE
*/
template <class T>
DWORD WINAPI Win32ServiceT<T>::svcCtrlHandler(DWORD   dwControl,
                                              DWORD   dwEventType,
                                              LPVOID  lpEventData,
                                              LPVOID  lpContext)
{
    DWORD st = ERROR_SUCCESS;

    // Handle the requested control code. Each case reports status to the
    // Windows SCM and calls the *real* service's method to handle processing
    // of that case.
    switch(dwControl)
    {
        case SERVICE_CONTROL_PRESHUTDOWN:
        case SERVICE_CONTROL_SHUTDOWN:
            // The OS is shutting down.
        {
            if (SERVICE_CONTROL_PRESHUTDOWN == dwControl)
            {
                /// @todo: log_trace(LOG_TRACE_INFO, "Preshutdown event received");
                st = svcCtrlPreShutdown(dwEventType, lpEventData, lpContext);
            }
            else
            {
                /// @todo: log_trace(LOG_TRACE_INFO, "Shutdown event received");
                st = svcCtrlShutdown(dwEventType, lpEventData, lpContext);
            }

            // FIXME: what to do if st != ERROR_SUCCESS?
            svcReportStatus(SERVICE_STOP_PENDING, st, SVC_WAIT_HINT);
            svcReportEvent(EVENTLOG_INFORMATION_TYPE, SVC_MSG_SHUTTING_DOWN, 0);
            svcReportStatus(SERVICE_STOP_PENDING, st, SVC_WAIT_HINT);
            // Signal the service to stop.
            ::SetEvent(m_stopEvent);
        }
        break;

        case SVC_CTRL_UNINSTALL_SERVICE:
        {
            /// @todo: log_trace(LOG_TRACE_INFO, "Uninstall service event received");

            svcReportStatus(SERVICE_STOP_PENDING, st, SVC_WAIT_HINT);
            svcReportEvent(EVENTLOG_SUCCESS, SVC_MSG_UNINSTALL_SERVICE, 0);
            st = svcCtrlUninstallService(dwEventType, lpEventData, lpContext);

            // tell the SCM we're stopping soon
            svcReportStatus(SERVICE_STOP_PENDING, st, SVC_WAIT_HINT);
            // Signal the service to stop.
            ::SetEvent(m_stopEvent);
        }
        break;

        case SERVICE_CONTROL_STOP:
            // The service is being stopped (no OS shutdown)
        {
            /// @todo: log_trace(LOG_TRACE_INFO, "Stop event received");

            svcReportStatus(SERVICE_STOP_PENDING, st, SVC_WAIT_HINT);
            svcReportEvent(EVENTLOG_INFORMATION_TYPE, SVC_MSG_STOPPING, 0);

            st = svcCtrlStop(dwEventType, lpEventData, lpContext);
            svcReportStatus(SERVICE_STOP_PENDING, st, SVC_WAIT_HINT);

            // Signal the service to stop.
            ::SetEvent(m_stopEvent);
        }
        break;  // case SERVICE_CONTROL_STOP

        case SERVICE_CONTROL_PAUSE:
        {
            /// @todo: log_trace(LOG_TRACE_INFO, "Pause service event received");

            svcReportStatus(SERVICE_PAUSE_PENDING, st, SVC_WAIT_HINT);
            svcReportEvent(EVENTLOG_SUCCESS, SVC_MSG_PAUSED, 0);
            st = svcCtrlPause(dwEventType, lpEventData, lpContext);

            svcReportStatus(SERVICE_PAUSED, st, 0);
        }
        break;

        case SERVICE_CONTROL_CONTINUE:
        {
            /// @todo: log_trace(LOG_TRACE_INFO, "Continue service event received");

            svcReportStatus(SERVICE_CONTINUE_PENDING, st, SVC_WAIT_HINT);
            // Ensure the reconnect event is reset
            svcReportEvent(EVENTLOG_SUCCESS, SVC_MSG_CONTINUING, 0);
            st = svcCtrlContinue(dwEventType, lpEventData, lpContext);

            // FIXME: what to do if st != ERROR_SUCCESS?
            svcReportStatus(SERVICE_RUNNING, st, 0);
        }
        break;

        case SERVICE_CONTROL_POWEREVENT:
        {
            /* handle case where the server is put into a low-power mode,
            ** or brought back from one.
            **
            ** Note that for this value of dwControl, the dwEventType can be:
            **
            **  PBT_APMPOWERSTATUSCHANGE (0xA) - ignore, related to batteries
            **  PBT_APMRESUMEAUTOMATIC (0x12) - resuming low-power state (sent every time)
            **  PBT_APMRESUMESUSPEND (0x7) - resuming from a low-power state (sent if triggered by a user)
            **  PBT_APMSUSPEND (0x4) - entering a suspended state.
            **  PBT_POWERSETTINGCHANGE (0x8013) - power setting change; ignore.
            */
            svcReportEvent(EVENTLOG_INFORMATION_TYPE, SVC_MSG_POWER_EVENT, 0);
            switch (dwEventType)
            {
                case PBT_APMRESUMEAUTOMATIC:
                {
                    /// @todo: log_trace(LOG_TRACE_INFO, "Resume power event received");

                    svcReportStatus(SERVICE_CONTINUE_PENDING, st, SVC_WAIT_HINT);
                    st = svcCtrlPowerResume(lpEventData, lpContext);

                    svcReportEvent(EVENTLOG_SUCCESS, SVC_MSG_POWER_EVENT_AUTO_RESUME, 0);
                    svcReportStatus(SERVICE_RUNNING, st, 0);
                }
                break;

                case PBT_APMSUSPEND:
                {
                    /// @todo: log_trace(LOG_TRACE_INFO, "Suspend power event received");

                    svcReportStatus(SERVICE_PAUSE_PENDING, st, SVC_POWER_SUSPEND_HINT);
                    svcReportEvent(EVENTLOG_SUCCESS, SVC_MSG_POWER_EVENT_SUSPEND, 0);
                    st = svcCtrlPowerSuspend(lpEventData, lpContext);

                    svcReportStatus(SERVICE_PAUSED, st, 0);
                }
                break;

                default:
                    /// @todo: log_trace(LOG_TRACE_INFO, "Unimplemented power event (%d) received",
                    // dwEventType);

                    st = svcCtrlPowerDefault(dwEventType, lpEventData, lpContext);
                    svcReportStatus(m_svcStatus.dwCurrentState, st, 0);
                    break;
            }
        }
        break;

        case SERVICE_CONTROL_INTERROGATE:
            /// @todo: log_trace(LOG_TRACE_INFO, "Interrogate event received");

            svcReportStatus(m_svcStatus.dwCurrentState, st, 0);
            break;

        default:
            /// @todo: log_trace(LOG_TRACE_INFO, "Received control event %d. Passing to default handler", dwControl);
            st = svcCtrlDefault(dwControl,
                                dwEventType,
                                lpEventData,
                                lpContext);
            break;
    }

    return st;
}   // Win32ServiceT<T>::svcCtrlHandler

template <class T>
void WINAPI Win32ServiceT<T>::svcMainWrapper(DWORD dwArgc, LPWSTR *lpszArgv)
{
    m_win32SvcPtr->svcMain(dwArgc, lpszArgv);
}

//
// svcCtrlHandlerWrapper
//
// This is a static member function, so we can pass its address to
// RegisterServiceCtrlHandlerEx. This way data is forwarded to the service-
// specific svcCtrlHandler function.
template <class T>
DWORD WINAPI Win32ServiceT<T>::svcCtrlHandlerWrapper(DWORD    dwControl,
                                                     DWORD    dwEventType,
                                                     LPVOID   lpEventData,
                                                     LPVOID   lpContext)
{
    DWORD result;
    result = m_win32SvcPtr->svcCtrlHandler(dwControl,
                                           dwEventType,
                                           lpEventData,
                                           lpContext);
    return result;
}

template <class T>
DWORD WINAPI Win32ServiceT<T>::startWin32Service()
{
    DWORD result;

    SERVICE_TABLE_ENTRY DispatchTable[] =
        {
            {(LPWSTR)m_serviceName.c_str(), svcMainWrapper},
            {NULL, NULL}
        };

    // StartServiceCtrlDispatcher returns when the service has stopped.
    // The process should simply terminate when the call returns.
    /// @todo: log_trace(LOG_TRACE_NOTICE, "Starting %ws", m_serviceName.c_str());
    if (FALSE == ::StartServiceCtrlDispatcher(DispatchTable))
    {
        result = ::GetLastError();
        /// @todo: log_trace_error("Start service control dispatcher failed: %d", result);
    }
    else
    {
        result = NO_ERROR;
    }

    /// @todo: log_trace(LOG_TRACE_NOTICE, "%ws exiting: %d", m_serviceName.c_str(), result);

    return result;
}

template <class T>
DWORD WINAPI Win32ServiceT<T>::registerService(SC_HANDLE hSCM,
                                               DWORD startType,
                                               LPCTSTR path,
                                               SC_HANDLE *service)
{
    DWORD result;

    /// @todo doug: someday pass in the desired values for dwServiceType rather
    // than hard-coding them here.
    SC_HANDLE svc = ::CreateService(hSCM,                       // hSCManager
                                    m_serviceName.c_str(),      // lpServiceName
                                    m_displayName.c_str(),      // dwDisplayName
                                    SERVICE_ALL_ACCESS,         // dwDesiredAccess
                                    SERVICE_WIN32_OWN_PROCESS,  // dwServiceType
                                    startType,                  // dwStartType
                                    SERVICE_ERROR_NORMAL,       // dwErrorControl
                                    path,                       // lpBinaryPathName
                                    0,                          // lpLoadOrderGroup
                                    0,                          // lpdwTagId
                                    0,                          // lpDependencies
                                    0,                          // lpServiceStartName
                                    0);                         // lpPassword
    if (svc)
    {
        SERVICE_DESCRIPTION     svcDesc;
        // restart w/ 60 second delay
        SC_ACTION                       svcActions[3];
        // reset failure count after 1 day of clean running
        SERVICE_FAILURE_ACTIONS         svcFailureActions = {
            86400,  // reset period
            NULL,   // reboot message
            NULL,   // CreateProcess command
            sizeof svcActions / sizeof(SC_ACTION),  // No. items in svcActions
            svcActions  // SC_ACTIONS array
        };
        SERVICE_FAILURE_ACTIONS_FLAG    svcFailureActionsFlag = {TRUE};

        // Restart the service after 2 minutes for the first two failures.
        // After the third failure, take no action.
        svcActions[0].Type = SC_ACTION_RESTART;
        svcActions[0].Delay = 120000;
        svcActions[1].Type = SC_ACTION_RESTART;
        svcActions[1].Delay = 120000;
        svcActions[2].Type = SC_ACTION_NONE;
        svcActions[2].Delay = 120000;

        result = registerEventLog(path);
        svcDesc.lpDescription = (LPWSTR)m_description.c_str();
        // Add a description to the service
        ::ChangeServiceConfig2(svc, SERVICE_CONFIG_DESCRIPTION, &svcDesc);

        // Ensure the SCM can restart the service if it fails
        ::ChangeServiceConfig2(svc, SERVICE_CONFIG_FAILURE_ACTIONS, &svcFailureActions);
        ::ChangeServiceConfig2(svc, SERVICE_CONFIG_FAILURE_ACTIONS_FLAG, &svcFailureActionsFlag);
        // save the service handle for later use
        *service = svc;
    }
    else
    {
        result = ::GetLastError();
        /// @todo: log_trace_error("Failed to create service. Error code: %d", result);
    }

    return result;
}

template <class T>
SC_HANDLE WINAPI Win32ServiceT<T>::openService(SC_HANDLE hSCM)
{
    return ::OpenService(hSCM, m_serviceName.c_str(), SERVICE_ALL_ACCESS);
}

template <class T>
void WINAPI Win32ServiceT<T>::deleteService()
{
	// Delete this service's event log registry key
	std::wstring    tmp(WIN32_SERVICES_KEY_NAME);

    tmp += WIN32_SERVICES_APP_EVENTLOG_KEY;
    tmp += m_serviceName.c_str();
    ::RegDeleteKey(HKEY_LOCAL_MACHINE, tmp.c_str());
}


text:
<?php

namespace Core {

    use Psr\Http\Message\ResponseInterface as Response;
    use Psr\Http\Message\ServerRequestInterface as Request;

    class NotFoundHandler
    {
        public function __invoke(Request $request, Response $response)
        {
            $basePath = $request->getUri()->getBaseUrl();
            return $response
                ->withStatus(404)
                ->withHeader('Content-Type', 'text/html')
                ->write($this->html($basePath));
        }

        public function html($basePath)
        {
            $html = '

                            <title>Page Not Found</title>

                                    404
                                    Page Not Found

The requested page was not found.

BACK TO HOME

                    ';
            return $html;
        }

    }
}


text:
import React = require('react');

interface Prop {
    x: boolean;
}
class Poisoned extends React.Component<Prop, {}> {
    render() {
        return
Hello
;
    }
}

// OK
let p = <Poisoned x/>;


text:
package com.onkarnene.upcomingmovies.adapter;
/*
 * Created by Onkar Nene on 12-01-2017.
 */

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.onkarnene.upcomingmovies.R;
import com.onkarnene.upcomingmovies.model.Movie;
import com.onkarnene.upcomingmovies.utils.APIConfig;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MovieListAdapter extends RecyclerView.Adapter<MovieListAdapter.ViewHolder> {

    private ArrayList<Movie> m_movies;
    private Context m_context;
    private IMovieCallback m_movieCallback;

    /**
     * Constructor function
     * @param context of the activity
     */
    public MovieListAdapter(Context context) {
        this.m_context = context;
    }

    /**
     * Set list of Movie model
     * @param movies contains data
     */
    public void setMovies(@NonNull ArrayList<Movie> movies) {
        this.m_movies = movies;
    }

    /**
     * @param movieCallback function to be register
     */
    public void setMovieCallback(IMovieCallback movieCallback) {
        this.m_movieCallback = movieCallback;
    }

    @Override
    public MovieListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_movie_list, parent, false);
        return new ViewHolder(view);
    }

    @SuppressLint("SimpleDateFormat")
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        try {
            String imageURL = APIConfig.IMAGE_API_URL + APIConfig.POSTER_SIZE_92 + this.m_movies.get(position).getPosterPath();
            Glide.with(this.m_context)
                    .load(imageURL)
                    .centerCrop()
                    .placeholder(R.drawable.place_holder)
                    .crossFade()
                    .into(holder.thumbnail);

            holder.setMovie(this.m_movies.get(position));
            holder.movieTitle.setText(this.m_movies.get(position).getMovieTitle());
            if (this.m_movies.get(position).getAdultStatus()) {
                holder.adultStatus.setText(this.m_context.getResources().getString(R.string.adult));
            } else {
                holder.adultStatus.setText(this.m_context.getResources().getString(R.string.ua));
            }
            String dateData = this.m_movies.get(position).getReleaseDate();
            holder.releaseDate.setText(dateData);
            Date date = new SimpleDateFormat("dd/MM/yyyy").parse(dateData);
            this.m_movies.get(position).setReleaseDate(new SimpleDateFormat("yyyy-MM-dd").format(date));
        } catch (NullPointerException | ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getItemCount() {
        if (this.m_movies == null) {
            return 0;
        } else {
            return this.m_movies.size();
        }
    }

    /**
     * Callback interface
     * Listens item click event
     */
    public interface IMovieCallback {
        public void onItemClick(Movie movie);
    }

    /**
     * Holds the view for respective ListItem
     */
    class ViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.thumbnail)
        ImageView thumbnail;

        @BindView(R.id.releaseDate)
        TextView releaseDate;

        @BindView(R.id.title)
        TextView movieTitle;

        @BindView(R.id.adultStatus)
        TextView adultStatus;

        private Movie m_movie;

        /**
         * Constructor function
         * @param itemView contains respective ListItem
         */
        ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        void setMovie(Movie movie) {
            this.m_movie = movie;
        }

        @OnClick(R.id.card_view)
        public void onListItemClickListener(View view) {
            if (m_movieCallback != null) {
                m_movieCallback.onItemClick(this.m_movie);
            }
        }
    }
}