text:
.. highlight:: shell

============
Contributing
============

Contributions are welcome, and they are greatly appreciated! Every
little bit helps, and credit will always be given.

You can contribute in many ways:

Types of Contributions
----------------------

Report Bugs
~~~~~~~~~~~

Report bugs at https://github.com/Michael-E-Rose/scholarmetrics/issues.

If you are reporting a bug, please include:

* Your operating system name and version.
* Any details about your local setup that might be helpful in troubleshooting.
* Detailed steps to reproduce the bug.

Fix Bugs
~~~~~~~~

Look through the GitHub issues for bugs. Anything tagged with "bug"
is open to whoever wants to implement it.

Implement Features
~~~~~~~~~~~~~~~~~~

Look through the GitHub issues for features. Anything tagged with "enhancement"
is open to whoever wants to implement it.

Write Documentation
~~~~~~~~~~~~~~~~~~~

scholarmetrics could always use more documentation, whether as part of the
official scholarmetrics docs, in docstrings, or even on the web in blog posts,
articles, and such.

Submit Feedback
~~~~~~~~~~~~~~~

The best way to send feedback is to file an issue at https://github.com/Michael-E-Rose/scholarmetrics/issues.

If you are proposing a feature:

* Explain in detail how it would work.
* Keep the scope as narrow as possible, to make it easier to implement.
* Respect the Respect the `Python Code of Conduct <https://www.python.org/psf/codeofconduct/>`_.

Get Started!
------------

Ready to contribute? Here's how to set up `scholarmetrics` for local development.

1. Fork the `scholarmetrics` repo on GitHub.
2. Clone your fork locally::

    $ git clone git@github.com:your_name_here/scholarmetrics.git

3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development::

    $ mkvirtualenv scholarmetrics
    $ cd scholarmetrics/
    $ python setup.py develop

4. Create a branch for local development::

    $ git checkout -b name-of-your-bugfix-or-feature

   Now you can make your changes locally.
   Feel free to add your name to `AUTHORS.rst <AUTHORS.rst>`_.

5. Commit your changes and push your branch to GitHub::

    $ git add .
    $ git commit -m "Your detailed description of your changes."
    $ git push origin name-of-your-bugfix-or-feature

6. Submit a pull request through the GitHub website.

Pull Request Guidelines
-----------------------

Before you submit a pull request, check that it meets these guidelines:

1. The pull request should include tests.
2. Adhere to `PEP8 <https://www.python.org/dev/peps/pep-0008/>`_.
3. The pull request should work for Python 2.7, 3.3, 3.4 and 3.5, and for PyPy. Check
   https://travis-ci.org/Michael-E-Rose/scholarmetrics/pull_requests
   and make sure that the tests pass for all supported Python versions.

Tips
----

To run a subset of tests::

    $ python -m unittest tests.test_scholarmetrics


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp"
    android:background="?android:attr/selectableItemBackground">

    <!--分类图片-->
    <ImageView
        android:id="@+id/category_icon"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_centerVertical="true"
        android:scaleType="centerCrop"
        android:src="@mipmap/category_list_02" />
    <!--分类的标题-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_toRightOf="@id/category_icon"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tv_category_small_type"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/shape_ring_text"
            android:paddingLeft="4dp"
            android:paddingRight="4dp"
            android:paddingTop="1dp"
            android:paddingBottom="1dp"
            android:text="家教"
            android:textColor="#D85434" />

        <TextView
            android:id="@+id/tv_category_info"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="4dp"
            android:lines="1"
            android:ellipsize="end"
            android:padding="3dp"
            android:text="高中英语教学" />
    </LinearLayout>

    <!--发布的时间和位置-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_marginLeft="20dp"
        android:layout_toRightOf="@id/category_icon"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tv_category_update_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:drawableLeft="@mipmap/time_logo"
            android:drawablePadding="5dp"
            android:padding="3dp"
            android:text="2017.08.12" />

        <TextView
            android:id="@+id/tv_category_distance"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:drawableLeft="@mipmap/address_logo"
            android:drawablePadding="3dp"
            android:lines="1"
            android:ellipsize="end"
            android:text="广州" />
    </LinearLayout>
    <!--价格-->
    <TextView
        android:id="@+id/tv_category_price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/category_icon"
        android:layout_marginLeft="20dp"
        android:layout_toRightOf="@id/category_icon"
        android:text="¥200.00"
        android:textColor="#D85434"
        android:textSize="16sp" />
</RelativeLayout>

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hadoop.mapred.pipes;

import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.Partitioner;
import org.apache.hadoop.util.ReflectionUtils;

/**
 * This partitioner is one that can either be set manually per a record or it
 * can fall back onto a Java partitioner that was set by the user.
 */
class PipesPartitioner<K extends WritableComparable,
                       V extends Writable>
  implements Partitioner<K, V> {

  private static final ThreadLocal<Integer> CACHE = new ThreadLocal<Integer>();
  private Partitioner<K, V> part = null;

  @SuppressWarnings("unchecked")
  public void configure(JobConf conf) {
    part =
      ReflectionUtils.newInstance(Submitter.getJavaPartitioner(conf), conf);
  }

  /**
   * Set the next key to have the given partition.
   * @param newValue the next partition value
   */
  static void setNextPartition(int newValue) {
    CACHE.set(newValue);
  }

  /**
   * If a partition result was set manually, return it. Otherwise, we call
   * the Java partitioner.
   * @param key the key to partition
   * @param value the value to partition
   * @param numPartitions the number of reduces
   */
  public int getPartition(K key, V value,
                          int numPartitions) {
    Integer result = CACHE.get();
    if (result == null) {
      return part.getPartition(key, value, numPartitions);
    } else {
      return result;
    }
  }

}


text:
/**
 * Author : Florian Simon <florian@tentwentyfour.lu>
 * Role   : Abstract main menu view.
 */

package Views.Base;

import Game.Grid;
import Views.View;

trait GameView extends View {
  override type ControllerSubtype = Controllers.GameView;

  /**
   * Callback called whenever the game grid gets updated.
   *
   * @param grid The new grid to display.
   */
  def gridUpdated(grid : Grid);
}


text:
"""Custom neural-net layers for physics simulations."""

import functools
from typing import (
    Any, Callable, Dict, Optional, Sequence, Tuple, TypeVar, Union,
)

import haiku as hk
import jax
from jax import lax
import jax.numpy as jnp
from jax_cfd.base import array_utils
from jax_cfd.base import boundaries
from jax_cfd.base import grids
from jax_cfd.ml import layers_util
from jax_cfd.ml import tiling
import numpy as np
import scipy.linalg

Array = Union[np.ndarray, jnp.DeviceArray]
IntOrSequence = Union[int, Sequence[int]]

class PeriodicConvGeneral(hk.Module):
  """General periodic convolution module."""

  def __init__(
      self,
      base_convolution: Callable[..., Any],
      output_channels: int,
      kernel_shape: Tuple[int, ...],
      rate: int = 1,
      tile_layout: Optional[Tuple[int, ...]] = None,
      name: str = 'periodic_conv_general',
      **conv_kwargs: Any
  ):
    """Constructs PeriodicConvGeneral module.

    We use `VALID` padding on `base_convolution` and explicit padding to achieve
    the effect of periodic boundary conditions. This function computes
    `paddings` and combines `jnp.pad` function calls with `base_convolution`
    module to produce the dersired effect.

    Args:
      base_convolution: standard convolution module e.g. hk.Conv1D.
      output_channels: number of output channels.
      kernel_shape: shape of the kernel, compatible with `base_convolution`.
      rate: dilation rate of the convolution.
      tile_layout: optional layout for tiling spatial dimensions in a batch.
      name: name of the module.
      **conv_kwargs: additional arguments passed to `base_convolution`.
    """
    super().__init__(name=name)
    self._padding = []
    for kernel_size in kernel_shape:
      effective_kernel = kernel_size + (rate - 1) * (kernel_size - 1)
      pad_left = effective_kernel // 2
      self._padding.append((pad_left, effective_kernel - pad_left - 1))
    self._tile_layout = tile_layout
    self._conv_module = base_convolution(
        output_channels=output_channels, kernel_shape=kernel_shape,
        padding='VALID', rate=rate, **conv_kwargs)

  def __call__(self, inputs):
    return tiling.apply_convolution(
        self._conv_module, inputs, self._tile_layout, self._padding)

class PeriodicConv1D(PeriodicConvGeneral):
  """Periodic convolution module in 1D."""

  def __init__(
      self,
      output_channels: int,
      kernel_shape: Tuple[int],
      rate: int = 1,
      tile_layout: Optional[Tuple[int]] = None,
      name='periodic_conv_1d',
      **conv_kwargs
  ):
    """Constructs PeriodicConv1D module."""
    super().__init__(
        base_convolution=hk.Conv1D,
        output_channels=output_channels,
        kernel_shape=kernel_shape,
        rate=rate,
        tile_layout=tile_layout,
        name=name,
        **conv_kwargs
    )

class PeriodicConv2D(PeriodicConvGeneral):
  """Periodic convolution module in 2D."""

  def __init__(
      self,
      output_channels: int,
      kernel_shape: Tuple[int, int],
      rate: int = 1,
      tile_layout: Optional[Tuple[int, int]] = None,
      name='periodic_conv_2d',
      **conv_kwargs
  ):
    """Constructs PeriodicConv2D module."""
    super().__init__(
        base_convolution=hk.Conv2D,
        output_channels=output_channels,
        kernel_shape=kernel_shape,
        rate=rate,
        tile_layout=tile_layout,
        name=name,
        **conv_kwargs
    )

class PeriodicConv3D(PeriodicConvGeneral):
  """Periodic convolution module in 3D."""

  def __init__(
      self,
      output_channels: int,
      kernel_shape: Tuple[int, int, int],
      rate: int = 1,
      tile_layout: Optional[Tuple[int, int, int]] = None,
      name='periodic_conv_3d',
      **conv_kwargs
  ):
    """Constructs PeriodicConv3D module."""
    super().__init__(
        base_convolution=hk.Conv3D,
        output_channels=output_channels,
        kernel_shape=kernel_shape,
        rate=rate,
        tile_layout=tile_layout,
        name=name,
        **conv_kwargs
    )

class MirrorConvGeneral(hk.Module):
  """General periodic convolution module."""

  def __init__(self,
               base_convolution: Callable[..., Any],
               output_channels: int,
               kernel_shape: Tuple[int, ...],
               rate: int = 1,
               tile_layout: Optional[Tuple[int, ...]] = None,
               name: str = 'mirror_conv_general',
               **conv_kwargs: Any):
    """Constructs MirrorConvGeneral module.

    We use `VALID` padding on `base_convolution` and explicit padding beyond
    the boudaries. This function computes paddings` and combines `jnp.pad`
    function calls with `base_convolution` module.

    Args:
      base_convolution: standard convolution module e.g. hk.Conv1D.
      output_channels: number of output channels.
      kernel_shape: shape of the kernel, compatible with `base_convolution`.
      rate: dilation rate of the convolution.
      tile_layout: optional layout for tiling spatial dimensions in a batch.
      name: name of the module.
      **conv_kwargs: additional arguments passed to `base_convolution`.
    """
    super().__init__(name=name)
    self._padding = np.zeros(2).astype('int')
    for kernel_size in kernel_shape:
      effective_kernel = kernel_size + (rate - 1) * (kernel_size - 1)
      pad_left = effective_kernel // 2
      self._padding += np.array([pad_left,
                                 effective_kernel - pad_left - 1]).astype('int')
    self._tile_layout = tile_layout
    self._conv_module = base_convolution(
        output_channels=output_channels, kernel_shape=kernel_shape,
        padding='VALID', rate=rate, **conv_kwargs)

  def _expand_var(self, var):
    var = var.bc.pad_all(
        var, (self._padding,) * var.grid.ndim, mode=boundaries.Padding.MIRROR)
    return jnp.expand_dims(var.data, axis=-1)

  def __call__(self, inputs):
    input_data = tuple(self._expand_var(var) for var in inputs)
    input_data = array_utils.concat_along_axis(
        jax.tree_leaves(input_data), axis=-1)
    outputs = self._conv_module(input_data)
    outputs = array_utils.split_axis(outputs, -1)
    outputs = tuple(
        var_input.bc.impose_bc(
            grids.GridArray(var, var_input.offset, var_input.grid))
        for var, var_input in zip(outputs, inputs))
    return outputs

class MirrorConv2D(MirrorConvGeneral):
  """Mirror convolution module in 2D."""

  def __init__(self,
               output_channels: int,
               kernel_shape: Tuple[int, int],
               rate: int = 1,
               tile_layout: Optional[Tuple[int, int]] = None,
               name='mirror_conv_2d',
               **conv_kwargs):
    """Constructs MirrorConv2D module."""
    super().__init__(
        base_convolution=hk.Conv2D,
        output_channels=output_channels,
        kernel_shape=kernel_shape,
        rate=rate,
        tile_layout=tile_layout,
        name=name,
        **conv_kwargs)

class PeriodicConvTransposeGeneral(hk.Module):
  """General periodic transpose convolution module."""

  def __init__(
      self,
      base_convolution: Callable[..., Any],
      output_channels: int,
      kernel_shape: Tuple[int, ...],
      stride: int = 1,
      tile_layout: Optional[Tuple[int, ...]] = None,
      name: str = 'periodic_conv_transpose_general',
      **conv_kwargs: Any
  ):
    """Constructs PeriodicConvTransposeGeneral module.

    To achieve the effect of periodic convolutions we first pad the inputs at
    the start of each spatial axis with wrap mode to ensure that the output
    generated by the original slice of the inputs receive contributions from
    periodic images when the `base_convolution` is applied. The
    `base_convolution` is applied with `VALID` padding followed by slicing
    to discard the boundary values. Additionally we perform a roll on the output
    to avoid the drift of spatial axes. (in standard implementation of the
    transposed convolutions the kernel applied to index [i] affects outputs at
    indicdes [i: i + kernel_size]. We perceive the center of the affected field
    as the spatial location of the output and hence shift it back by half of
    the kernel size.)

    Args:
      base_convolution: standard transpose convolution module.
      output_channels: number of output channels.
      kernel_shape: shape of the kernel, compatible with `base_convolution`.
      stride: stride to use in `base_convolution`.
      tile_layout: optional layout for tiling spatial dimensions in a batch.
      name: name of the module.
      **conv_kwargs: additional arguments passed to `base_convolution`.
    """
    if tile_layout is not None:
      raise NotImplementedError(
          "tile_layout doesn't work yet for transpose convolutions")
    super().__init__(name=name)
    self._stride = stride
    self._kernel_shape = kernel_shape
    self._padding = []
    self._roll_shifts = []
    for kernel_size in kernel_shape:
      # left pad should be large enough so that contribution from the leftmost
      # element just affect the output of the input's original first index: i.e.
      # stride * left_pad (output of the first index) should be less or equal to
      # kernel_size (last affected value of the input)
      pad_left = kernel_size // stride + 1
      self._padding.append((pad_left, 0))
      # we shift by half a kernel size at the end to recover spatial alignment.
      self._roll_shifts.append(-((kernel_size - 1) // 2))
    self._tile_layout = tile_layout
    self._conv_module = base_convolution(
        output_channels=output_channels, kernel_shape=kernel_shape,
        stride=stride, padding='VALID', **conv_kwargs)

  def __call__(self, inputs):
    """Applies PeriodicTransposeConvolution to `inputs`.

    Args:
      inputs: array with spatial and channel axes to which
        PeriodicTransposeConvolution is applied.

    Returns:
      `inputs` convolved with the kernel of the module with periodic padding.
    """
    ndim = len(self._kernel_shape)
    output_slice = []
    for axis, (left_pad, _) in enumerate(self._padding[:ndim]):
      axis_size = inputs.shape[axis]
      output_start = self._stride * left_pad
      output_end = self._stride * (axis_size + left_pad)
      output_slice.append(slice(output_start, output_end))
    output_slice.append(slice(None, None))
    output = tiling.apply_convolution(
        self._conv_module, inputs, self._tile_layout, self._padding)
    sliced_output = output[tuple(output_slice)]
    return jnp.roll(sliced_output, self._roll_shifts, list(range(ndim)))

class PeriodicConvTranspose1D(PeriodicConvTransposeGeneral):
  """Periodic transpose convolution module in 1D."""

  def __init__(
      self,
      output_channels: int,
      kernel_shape: Tuple[int],
      stride: int = 1,
      tile_layout: Optional[Tuple[int]] = None,
      name='periodic_conv_transpose_1d',
      **conv_kwargs
  ):
    """Constructs PeriodicConv1D module."""
    super().__init__(
        base_convolution=hk.Conv1DTranspose,
        output_channels=output_channels,
        kernel_shape=kernel_shape,
        stride=stride,
        tile_layout=tile_layout,
        name=name,
        **conv_kwargs
    )

class PeriodicConvTranspose2D(PeriodicConvTransposeGeneral):
  """Periodic transpose convolution module in 2D."""

  def __init__(
      self,
      output_channels: int,
      kernel_shape: Tuple[int, int],
      stride: int = 1,
      tile_layout: Optional[Tuple[int, int]] = None,
      name='periodic_conv_transpose_2d',
      **conv_kwargs
  ):
    """Constructs PeriodicConv2D module."""
    super().__init__(
        base_convolution=hk.Conv2DTranspose,
        output_channels=output_channels,
        kernel_shape=kernel_shape,
        stride=stride,
        tile_layout=tile_layout,
        name=name,
        **conv_kwargs
    )

class PeriodicConvTranspose3D(PeriodicConvTransposeGeneral):
  """Periodic transpose convolution module in 3D."""

  def __init__(
      self,
      output_channels: int,
      kernel_shape: Tuple[int, int, int],
      stride: int = 1,
      tile_layout: Optional[Tuple[int, int, int]] = None,
      name='periodic_conv_transpose_3d',
      **conv_kwargs
  ):
    """Constructs PeriodicConv3D module."""
    super().__init__(
        base_convolution=hk.Conv3DTranspose,
        output_channels=output_channels,
        kernel_shape=kernel_shape,
        stride=stride,
        tile_layout=tile_layout,
        name=name,
        **conv_kwargs
    )

def rescale_to_range(
    inputs: Array,
    min_value: float,
    max_value: float,
    axes: Tuple[int, ...]
) -> Array:
  """Rescales inputs to [min_value, max_value] range.

  Note that this function performs input dependent transformation, which might
  not be suitable for models that aim to learn different dynamics for different
  scales.

  Args:
    inputs: array to be rescaled to [min_value, max_value] range.
    min_value: value to which the smallest entry of `inputs` is mapped to.
    max_value: value to which the largest entry of `inputs` is mapped to.
    axes: `inputs` axes across which we search for smallest and largest values.

  Returns:
    `inputs` rescaled to [min_value, max_value] range.
  """
  inputs_max = jnp.max(inputs, axis=axes, keepdims=True)
  inputs_min = jnp.min(inputs, axis=axes, keepdims=True)
  scale = (inputs_max - inputs_min) / (max_value - min_value)
  return (inputs - inputs_min) / scale + min_value

class NonPeriodicConvGeneral(hk.Module):
  """General periodic convolution module."""

  def __init__(self,
               base_convolution: Callable[..., Any],
               output_channels: int,
               kernel_shape: Tuple[int, ...],
               rate: int = 1,
               name: str = 'periodic_conv_general',
               **conv_kwargs: Any):
    """Constructs NonPeriodicConvGeneral module similar to a Periodic one.

    Args:
      base_convolution: standard convolution module e.g. hk.Conv1D.
      output_channels: number of output channels.
      kernel_shape: shape of the kernel, compatible with `base_convolution`.
      rate: dilation rate of the convolution.
      name: name of the module.
      **conv_kwargs: additional arguments passed to `base_convolution`.
    """
    super().__init__(name=name)
    self._conv_module = base_convolution(
        output_channels=output_channels,
        kernel_shape=kernel_shape,
        padding='VALID',
        rate=rate,
        **conv_kwargs)

  def __call__(self, inputs):
    output = self._conv_module(jnp.expand_dims(inputs, axis=0))
    return jnp.squeeze(output, axis=0)

class NonPeriodicConv1D(NonPeriodicConvGeneral):
  """Periodic convolution module in 1D."""

  def __init__(self,
               output_channels: int,
               kernel_shape: Tuple[int, ...],
               rate: int = 1,
               name='periodic_conv_1d',
               **conv_kwargs):
    """Constructs PeriodicConv1D module."""
    super().__init__(
        base_convolution=hk.Conv1D,
        output_channels=output_channels,
        kernel_shape=kernel_shape,
        rate=rate,
        name=name,
        **conv_kwargs)

class PolynomialConstraint():
  """Module that parametrizes coefficients of polynomially accurate derivatives.

  Generates stencil coefficients that are guaranteed to approximate derivative
  of `derivative_orders[i]` along ith dimension with polynomial accuracy of
  `accuracy_order` order. The approximation is enforced by taking a linear
  superposition of the nullspace of linear constraints combined with a bias
  solution, which can be either specified directly using `bias` argument or
  generated automatically using `layers_util.polynomial_accuracy_coefficients`.
  """

  def __init__(
      self,
      stencils: Sequence[np.ndarray],
      derivative_orders: Tuple[int, ...],
      method: layers_util.Method,
      steps: Tuple[float, ...],
      accuracy_order: int = 1,
      bias_accuracy_order: int = 1,
      bias: Optional[Array] = None,
      precision: lax.Precision = lax.Precision.HIGHEST
  ):
    """Constructs the object.

    Args:
      stencils: sequence of 1d stencils, one per grid dimension
      derivative_orders: derivative orders along corresponding directions.
      method: discretization method (finite volumes or finite differences).
      steps: spatial separations between the adjacent cells.
      accuracy_order: order to which polynomial accuracy is enforced.
      bias_accuracy_order: integer order of polynomial accuracy to use for the
        bias term. Only used if bias is not provided.
      bias: np.ndarray of shape (grid_size,) to which zero-vectors will be
        mapped. Must satisfy polynomial accuracy to the requested order. By
        default, we use standard low-order coefficients for the given grid.
      precision: numerical precision for matrix multplication. Only relevant on
        TPUs.
    """
    self.precision = precision
    grid_steps = {*steps}
    if len(grid_steps) != 1:
      raise ValueError('nonuniform steps not supported by PolynomialConstraint')
    grid_step, = grid_steps
    #  stencil coefficients `c` satisfying `constraint_matrix @ c = rhs`
    #  satisfies polynomial accuracy constraint of the given order
    constraint_matrix, rhs = layers_util.polynomial_accuracy_constraints(
        stencils, method, derivative_orders, accuracy_order, grid_step)

    if bias is None:
      bias_grid = layers_util.polynomial_accuracy_coefficients(
          stencils, method, derivative_orders, bias_accuracy_order, grid_step)
      bias = bias_grid.ravel()

    self.bias = bias
    norm = np.linalg.norm(np.dot(constraint_matrix, bias) - rhs)
    if norm > 1e-8:
      raise ValueError('invalid bias, not in nullspace')

    # https://en.wikipedia.org/wiki/Kernel_(linear_algebra)#Nonhomogeneous_systems_of_linear_equations
    _, _, v = np.linalg.svd(constraint_matrix)
    nullspace_size = constraint_matrix.shape[1] - constraint_matrix.shape[0]
    if not nullspace_size:
      raise ValueError(
          'there is only one valid solution accurate to this order')

    # nullspace from the SVD is always normalized such that its singular values
    # are 1 or 0, which means it's actually independent of the grid spacing.
    self._nullspace_size = nullspace_size
    self.nullspace = v[-nullspace_size:]
    self.nullspace /= (grid_step**np.array(derivative_orders)).prod()

  @property
  def subspace_size(self) -> int:
    """Returns the size of the coefficients subspace with desired accuracy."""
    return self._nullspace_size

  def __call__(
      self,
      inputs: Array
  ) -> Array:
    """Returns polynomially accurate coefficients parametrized by `inputs`.

    Args:
      inputs: array whose last dimension represents linear superposition of
        valid polynomially accurate coefficients. Last dimension must be equal
        to `subspace_size`.

    Returns:
      array whose last dimension represents valid coefficients that approximate
      `derivate_orders` with polynomial accuracy on a stencil specified in
      `stencils` at position (0.,) * ndims.
    """
    return self.bias + jnp.tensordot(inputs, self.nullspace, axes=[-1, 0],
                                     precision=self.precision)

class StencilCoefficients():
  """Module that approximates stencil coefficients with polynomial accuracy.

  Generates stencil coefficients that approximate a spatial derivative of
  order `derivative_orders[i]` along i'th dimension by combining a trainable
  model generated by `tower_factory` and `PolynomilConstraint` layer.
  """

  def __init__(
      self,
      stencils: Sequence[np.ndarray],
      derivative_orders: Tuple[int, ...],
      tower_factory: Callable[[int], Callable[..., Any]],
      steps: Tuple[float, ...],
      method: layers_util.Method = layers_util.Method.FINITE_VOLUME,
      **kwargs: Any,
  ):
    """Constructs the object.

    Args:
      stencils: sequence of 1d stencils, one per grid dimension
      derivative_orders: derivative orders along corresponding directions.
      tower_factory: callable that constructs a neural network with specified
        number of output channels and the same spatial resolution as its inputs.
      steps: spatial separations between the adjacent cells.
      method: discretization method passed to PolynomialConstraint.
      **kwargs: additional arguments to be passed to PolynomialConstraint
        constructor.
    """
    self._polynomial_constraint = PolynomialConstraint(
        stencils, derivative_orders, method, steps, **kwargs)
    self._tower = tower_factory(self._polynomial_constraint.subspace_size)

  def __call__(self, inputs: Array, **kwargs) -> Array:
    """Returns coefficients approximating derivative conditioned on `inputs`."""
    parametrization = self._tower(inputs, **kwargs)
    return self._polynomial_constraint(parametrization)

class SpatialDerivativeFromLogits:
  """Module that transforms logits to polynomially accurate derivatives.

  Applies `PolynomialConstraint` layer to input logits and combines the
  resulting coefficients with basis. Compared to `SpatialDerivative`, this
  module does not compute `logits`, but takes them as an argument.
  """

  def __init__(
      self,
      stencil_shape: Tuple[int, ...],
      input_offset: Tuple[float, ...],
      target_offset: Tuple[float, ...],
      derivative_orders: Tuple[int, ...],
      steps: Tuple[float, ...],
      extract_patch_method: str = 'roll',
      tile_layout: Optional[Tuple[int, ...]] = None,
      method: layers_util.Method = layers_util.Method.FINITE_VOLUME,
  ):
    self.stencil_shape = stencil_shape
    self.roll, shift = layers_util.get_roll_and_shift(
        input_offset, target_offset)
    stencils = layers_util.get_stencils(stencil_shape, shift, steps)
    self.constraint = PolynomialConstraint(
        stencils, derivative_orders, method, steps)
    self._extract_patch_method = extract_patch_method
    self.tile_layout = tile_layout

  @property
  def subspace_size(self) -> int:
    return self.constraint.subspace_size

  @property
  def stencil_size(self) -> int:
    return int(np.prod(self.stencil_shape))

  def _validate_logits(self, logits):
    if logits.shape[-1] != self.subspace_size:
      raise ValueError('The last dimension of `logits` did not match subspace '
                       f'size; {logits.shape[-1]} vs. {self.subspace_size}')

  def extract_patches(self, inputs):
    rolled = jnp.roll(inputs, self.roll)
    patches = layers_util.extract_patches(
        rolled, self.stencil_shape,
        self._extract_patch_method, self.tile_layout)
    return patches

  @functools.partial(jax.named_call, name='SpatialDerivativeFromLogits')
  def __call__(self, inputs, logits):
    self._validate_logits(logits)
    coefficients = self.constraint(logits)
    patches = self.extract_patches(inputs)
    return layers_util.apply_coefficients(coefficients, patches)

T = TypeVar('T')

def fuse_spatial_derivative_layers(
    derivatives: Dict[T, SpatialDerivativeFromLogits],
    all_logits: jnp.ndarray,
    *,
    constrain_with_conv: bool = False,
    fuse_patches: bool = False,
) -> Dict[T, Callable[[jnp.ndarray], jnp.ndarray]]:
  """Evaluate spatial derivatives by fusing together constraints.

  Despite the additional calculation, this can be faster on TPUs because the
  full block diagonal constraint matrix is small enough to fit within a 128x128
  matrix.

  Args:
    derivatives: mapping from key to SpatialDerivativeFromLogits.
    all_logits: stacked logits to use as input into spatial derivatives.
    constrain_with_conv: whether to constrain with a 1x1 convolution instead of
      direct matrix multiplication.
    fuse_patches: whether to also fuse the extraction of patches.

  Returns:
    Functions that when applied evaluate derivatives.
  """
  joint_bias = jnp.concatenate(
      [derivative.constraint.bias for derivative in derivatives.values()])
  joint_nullspace = scipy.linalg.block_diag(
      *[deriv.constraint.nullspace for deriv in derivatives.values()]
  )
  precision, = {deriv.constraint.precision for deriv in derivatives.values()}
  tile_layout, = {deriv.tile_layout for deriv in derivatives.values()}

  if constrain_with_conv:
    ndim = len(tile_layout)
    kernel = jnp.expand_dims(
        joint_nullspace.astype(np.float32), axis=tuple(range(ndim)))
    all_coefficients = joint_bias + layers_util.periodic_convolution(
        all_logits, kernel, tile_layout=tile_layout, precision=precision)
  else:
    if tile_layout is not None:
      all_logits = tiling.space_to_batch(all_logits, tile_layout)
    all_coefficients = joint_bias + jnp.tensordot(
        all_logits, joint_nullspace, axes=[-1, 0], precision=precision)
    if tile_layout is not None:
      all_coefficients = tiling.batch_to_space(all_coefficients, tile_layout)

  stencil_sizes = [deriv.stencil_size for deriv in derivatives.values()]
  coefficients_list = jnp.split(
      all_coefficients, np.cumsum(stencil_sizes), axis=-1)
  coefficients_map = dict(zip(derivatives, coefficients_list))

  stencil_shapes = [deriv.stencil_shape for k, deriv in derivatives.items()]
  for k, deriv in derivatives.items():
    if any(r != 0 for r in deriv.roll):
      raise ValueError(f'derivative {k} uses roll: {deriv.roll}')

  @functools.partial(jax.named_call, name='evaluate_derivatives')
  def evaluate(key, inputs):
    if fuse_patches:
      all_patches = layers_util.fused_extract_patches(
          inputs, stencil_shapes, tile_layout)
      all_terms = all_coefficients * all_patches
      split_terms = jnp.split(all_terms, np.cumsum(stencil_sizes), axis=-1)
      index = list(derivatives).index(key)
      return jnp.sum(split_terms[index], axis=-1, keepdims=True)
    else:
      patches = derivatives[key].extract_patches(inputs)
      return layers_util.apply_coefficients(coefficients_map[key], patches)

  return {k: functools.partial(evaluate, k) for k in derivatives}

class SpatialDerivative:
  """Module that learns spatial derivative with polynomial accuracy.

  Combines StencilCoefficients with extract_stencils to construct a trainable
  model that approximates spatial derivative.
  """

  def __init__(
      self,
      stencil_shape: Tuple[int, ...],
      input_offset: Tuple[float, ...],
      target_offset: Tuple[float, ...],
      derivative_orders: Tuple[int, ...],
      tower_factory: Callable[[int], Callable[..., Any]],
      steps: Tuple[float, ...],
      extract_patch_method: str = 'roll',
      tile_layout: Optional[Tuple[int, ...]] = None,
  ):
    self._stencil_shape = stencil_shape
    self._roll, self._shift = layers_util.get_roll_and_shift(
        input_offset, target_offset)
    stencils = layers_util.get_stencils(stencil_shape, self._shift, steps)
    self._coefficients_module = StencilCoefficients(
        stencils, derivative_orders, tower_factory, steps)
    self._extract_patch_method = extract_patch_method
    self._tile_layout = tile_layout

  @functools.partial(jax.named_call, name='SpatialDerivative')
  def __call__(self, inputs, *auxiliary_inputs):
    """Computes spatial derivative of `inputs` evaluated at `offset`."""
    # TODO(jamieas): consider moving this roll inside `extract_patches`. For the
    # `roll` implementation of `extract_patches`, we can simply add it to the
    # `shifts`. For the `conv` implementation, we may be able to effectively
    # roll the input by adjusting how arrays are padded.
    rolled = jnp.roll(inputs, self._roll)
    patches = layers_util.extract_patches(
        rolled, self._stencil_shape,
        self._extract_patch_method, self._tile_layout)
    if auxiliary_inputs is not None:
      auxiliary_inputs = [jnp.roll(aux, self._roll) for aux in auxiliary_inputs]
      rolled = jnp.concatenate([rolled, *auxiliary_inputs], axis=-1)
    coefficients = self._coefficients_module(rolled)
    return layers_util.apply_coefficients(coefficients, patches)


text:
using System;
using System.Diagnostics.Contracts;

namespace It.Uniba.Di.Cdg.SocialTfs.ServiceLibrary.Twitter
{
    /// <summary>
    /// Rapresent a post in Twitter.
    /// </summary>
    /// <remarks>
    /// All public attributes are matched by the JSON web response.
    /// In this way it's possible to serizalize automatically from the web response.
    /// </remarks>
    class TwitterPost : IPost
    {
        #region Attributes

        public long id { get; set; }
        public String text { get; set; }
        public String created_at { get; set; }

        #endregion

        long IPost.Id
        {
            get { return id; }
        }

        String IPost.Text
        {
            get { return text; }
        }

        DateTime IPost.CreatedAt
        {
            get { return ParseDate(created_at); }
        }

        /// <summary>
        /// Convert the date returned by the web in the standard <see cref="DateTime"/> format.
        /// </summary>
        /// <param name="d">Date as String.</param>
        /// <returns>Date in a standard format.</returns>
        private DateTime ParseDate(String d)
        {
            Contract.Requires(!String.IsNullOrEmpty(d));

            char[] delimiterChars = { ' ', ':' };
            String[] words = d.Split(delimiterChars);
            int month = 0;
            switch (words[1])
            {
                case "Jan":
                    month = 1;
                    break;
                case "Feb":
                    month = 2;
                    break;
                case "Mar":
                    month = 3;
                    break;
                case "Apr":
                    month = 4;
                    break;
                case "May":
                    month = 5;
                    break;
                case "Jun":
                    month = 6;
                    break;
                case "Jul":
                    month = 7;
                    break;
                case "Aug":
                    month = 8;
                    break;
                case "Sep":
                    month = 9;
                    break;
                case "Oct":
                    month = 10;
                    break;
                case "Nov":
                    month = 11;
                    break;
                case "Dec":
                    month = 12;
                    break;
            }
            return new DateTime(Int32.Parse(words[7]), month, Int32.Parse(words[2]), Int32.Parse(words[3]), Int32.Parse(words[4]), Int32.Parse(words[5]));
        }
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.ComponentModel;

namespace Python.Runtime
{
    /// <summary>
    /// Performs data conversions between managed types and Python types.
    /// </summary>
    [SuppressUnmanagedCodeSecurity]
    internal class Converter
    {
        private Converter()
        {
        }

        private static NumberFormatInfo nfi;
        private static Type objectType;
        private static Type stringType;
        private static Type singleType;
        private static Type doubleType;
        private static Type decimalType;
        private static Type int16Type;
        private static Type int32Type;
        private static Type int64Type;
        private static Type flagsType;
        private static Type boolType;
        private static Type typeType;

        static Converter()
        {
            nfi = NumberFormatInfo.InvariantInfo;
            objectType = typeof(Object);
            stringType = typeof(String);
            int16Type = typeof(Int16);
            int32Type = typeof(Int32);
            int64Type = typeof(Int64);
            singleType = typeof(Single);
            doubleType = typeof(Double);
            decimalType = typeof(Decimal);
            flagsType = typeof(FlagsAttribute);
            boolType = typeof(Boolean);
            typeType = typeof(Type);
        }

        /// <summary>
        /// Given a builtin Python type, return the corresponding CLR type.
        /// </summary>
        internal static Type GetTypeByAlias(IntPtr op)
        {
            if (op == Runtime.PyStringType)
                return stringType;

            if (op == Runtime.PyUnicodeType)
                return stringType;

            if (op == Runtime.PyIntType)
                return int32Type;

            if (op == Runtime.PyLongType)
                return int64Type;

            if (op == Runtime.PyFloatType)
                return doubleType;

            if (op == Runtime.PyBoolType)
                return boolType;

            return null;
        }

        internal static IntPtr GetPythonTypeByAlias(Type op)
        {
            if (op == stringType)
                return Runtime.PyUnicodeType;

            if (op == int16Type)
                return Runtime.PyIntType;

            if (op == int32Type)
                return Runtime.PyIntType;

            if (op == int64Type && Runtime.IsPython2)
                return Runtime.PyLongType;

            if (op == int64Type)
                return Runtime.PyIntType;

            if (op == doubleType)
                return Runtime.PyFloatType;

            if (op == singleType)
                return Runtime.PyFloatType;

            if (op == boolType)
                return Runtime.PyBoolType;

            return IntPtr.Zero;
        }

        /// <summary>
        /// Return a Python object for the given native object, converting
        /// basic types (string, int, etc.) into equivalent Python objects.
        /// This always returns a new reference. Note that the System.Decimal
        /// type has no Python equivalent and converts to a managed instance.
        /// </summary>
        internal static IntPtr ToPython<T>(T value)
        {
            return ToPython(value, typeof(T));
        }

        internal static IntPtr ToPython(object value, Type type)
        {
            if (value is PyObject)
            {
                IntPtr handle = ((PyObject)value).Handle;
                Runtime.XIncref(handle);
                return handle;
            }
            IntPtr result = IntPtr.Zero;

            // Null always converts to None in Python.

            if (value == null)
            {
                result = Runtime.PyNone;
                Runtime.XIncref(result);
                return result;
            }

			if (value is IList && !(value is INotifyPropertyChanged) && value.GetType().IsGenericType)
			{
                using (var resultlist = new PyList())
                {
                    foreach (object o in (IEnumerable)value)
                    {
                        using (var p = new PyObject(ToPython(o, o?.GetType())))
                        {
                            resultlist.Append(p);
                        }
                    }
                    Runtime.XIncref(resultlist.Handle);
                    return resultlist.Handle;
                }
            }

            // it the type is a python subclass of a managed type then return the
            // underlying python object rather than construct a new wrapper object.
            var pyderived = value as IPythonDerivedType;
            if (null != pyderived)
            {
                #if NETSTANDARD
                return ClassDerivedObject.ToPython(pyderived);
                #else
                // if object is remote don't do this
                if (!System.Runtime.Remoting.RemotingServices.IsTransparentProxy(pyderived))
                {
                    return ClassDerivedObject.ToPython(pyderived);
                }
                #endif
            }

            // hmm - from Python, we almost never care what the declared
            // type is. we'd rather have the object bound to the actual
            // implementing class.

            type = value.GetType();

            TypeCode tc = Type.GetTypeCode(type);

            switch (tc)
            {
                case TypeCode.Object:
                    return CLRObject.GetInstHandle(value, type);

                case TypeCode.String:
                    return Runtime.PyUnicode_FromString((string)value);

                case TypeCode.Int32:
                    return Runtime.PyInt_FromInt32((int)value);

                case TypeCode.Boolean:
                    if ((bool)value)
                    {
                        Runtime.XIncref(Runtime.PyTrue);
                        return Runtime.PyTrue;
                    }
                    Runtime.XIncref(Runtime.PyFalse);
                    return Runtime.PyFalse;

                case TypeCode.Byte:
                    return Runtime.PyInt_FromInt32((int)((byte)value));

                case TypeCode.Char:
                    return Runtime.PyUnicode_FromOrdinal((int)((char)value));

                case TypeCode.Int16:
                    return Runtime.PyInt_FromInt32((int)((short)value));

                case TypeCode.Int64:
                    return Runtime.PyLong_FromLongLong((long)value);

                case TypeCode.Single:
                    // return Runtime.PyFloat_FromDouble((double)((float)value));
                    string ss = ((float)value).ToString(nfi);
                    IntPtr ps = Runtime.PyString_FromString(ss);
                    IntPtr op = Runtime.PyFloat_FromString(ps, IntPtr.Zero);
                    Runtime.XDecref(ps);
                    return op;

                case TypeCode.Double:
                    return Runtime.PyFloat_FromDouble((double)value);

                case TypeCode.SByte:
                    return Runtime.PyInt_FromInt32((int)((sbyte)value));

                case TypeCode.UInt16:
                    return Runtime.PyInt_FromInt32((int)((ushort)value));

                case TypeCode.UInt32:
                    return Runtime.PyLong_FromUnsignedLong((uint)value);

                case TypeCode.UInt64:
                    return Runtime.PyLong_FromUnsignedLongLong((ulong)value);

                default:
                    if (value is IEnumerable)
                    {
                        using (var resultlist = new PyList())
                        {
                            foreach (object o in (IEnumerable)value)
                            {
                                using (var p = new PyObject(ToPython(o, o?.GetType())))
                                {
                                    resultlist.Append(p);
                                }
                            }
                            Runtime.XIncref(resultlist.Handle);
                            return resultlist.Handle;
                        }
                    }
                    result = CLRObject.GetInstHandle(value, type);
                    return result;
            }
        }

        /// <summary>
        /// In a few situations, we don't have any advisory type information
        /// when we want to convert an object to Python.
        /// </summary>
        internal static IntPtr ToPythonImplicit(object value)
        {
            if (value == null)
            {
                IntPtr result = Runtime.PyNone;
                Runtime.XIncref(result);
                return result;
            }

            return ToPython(value, objectType);
        }

        /// <summary>
        /// Return a managed object for the given Python object, taking funny
        /// byref types into account.
        /// </summary>
        internal static bool ToManaged(IntPtr value, Type type,
            out object result, bool setError)
        {
            if (type.IsByRef)
            {
                type = type.GetElementType();
            }
            return Converter.ToManagedValue(value, type, out result, setError);
        }

        internal static bool ToManagedValue(IntPtr value, Type obType,
            out object result, bool setError)
        {
            if (obType == typeof(PyObject))
            {
                Runtime.XIncref(value); // PyObject() assumes ownership
                result = new PyObject(value);
                return true;
            }

            // Common case: if the Python value is a wrapped managed object
            // instance, just return the wrapped object.
            ManagedType mt = ManagedType.GetManagedObject(value);
            result = null;

            if (mt != null)
            {
                if (mt is CLRObject)
                {
                    object tmp = ((CLRObject)mt).inst;
                    if (obType.IsInstanceOfType(tmp))
                    {
                        result = tmp;
                        return true;
                    }
                    Exceptions.SetError(Exceptions.TypeError, $"value cannot be converted to {obType}");
                    return false;
                }
                if (mt is ClassBase)
                {
                    result = ((ClassBase)mt).type;
                    return true;
                }
                // shouldn't happen
                return false;
            }

            if (value == Runtime.PyNone && !obType.IsValueType)
            {
                result = null;
                return true;
            }

            if (obType.IsGenericType && obType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                if( value == Runtime.PyNone )
                {
                    result = null;
                    return true;
                }
                // Set type to underlying type
                obType = obType.GetGenericArguments()[0];
            }

            if (obType.IsArray)
            {
                return ToArray(value, obType, out result, setError);
            }

            if (obType.IsEnum)
            {
                return ToEnum(value, obType, out result, setError);
            }

            // Conversion to 'Object' is done based on some reasonable default
            // conversions (Python string -> managed string, Python int -> Int32 etc.).
            if (obType == objectType)
            {
                if (Runtime.IsStringType(value))
                {
                    return ToPrimitive(value, stringType, out result, setError);
                }

                if (Runtime.PyBool_Check(value))
                {
                    return ToPrimitive(value, boolType, out result, setError);
                }

                if (Runtime.PyInt_Check(value))
                {
                    return ToPrimitive(value, int32Type, out result, setError);
                }

                if (Runtime.PyLong_Check(value))
                {
                    return ToPrimitive(value, int64Type, out result, setError);
                }

                if (Runtime.PyFloat_Check(value))
                {
                    return ToPrimitive(value, doubleType, out result, setError);
                }

                if (Runtime.PySequence_Check(value))
                {
                    return ToArray(value, typeof(object[]), out result, setError);
                }

                if (setError)
                {
                    Exceptions.SetError(Exceptions.TypeError, "value cannot be converted to Object");
                }

                return false;
            }

            // Conversion to 'Type' is done using the same mappings as above for objects.
            if (obType == typeType)
            {
                if (value == Runtime.PyStringType)
                {
                    result = stringType;
                    return true;
                }

                if (value == Runtime.PyBoolType)
                {
                    result = boolType;
                    return true;
                }

                if (value == Runtime.PyIntType)
                {
                    result = int32Type;
                    return true;
                }

                if (value == Runtime.PyLongType)
                {
                    result = int64Type;
                    return true;
                }

                if (value == Runtime.PyFloatType)
                {
                    result = doubleType;
                    return true;
                }

                if (value == Runtime.PyListType || value == Runtime.PyTupleType)
                {
                    result = typeof(object[]);
                    return true;
                }

                if (setError)
                {
                    Exceptions.SetError(Exceptions.TypeError, "value cannot be converted to Type");
                }

                return false;
            }

            return ToPrimitive(value, obType, out result, setError);
        }

        /// <summary>
        /// Convert a Python value to an instance of a primitive managed type.
        /// </summary>
        private static bool ToPrimitive(IntPtr value, Type obType, out object result, bool setError)
        {
            IntPtr overflow = Exceptions.OverflowError;
            TypeCode tc = Type.GetTypeCode(obType);
            result = null;
            IntPtr op;
            int ival;

            switch (tc)
            {
                case TypeCode.String:
                    string st = Runtime.GetManagedString(value);
                    if (st == null)
                    {
                        goto type_error;
                    }
                    result = st;
                    return true;

                case TypeCode.Int32:
                    // Trickery to support 64-bit platforms.
                    if (Runtime.IsPython2 && Runtime.Is32Bit)
                    {
                        op = Runtime.PyNumber_Int(value);

                        // As of Python 2.3, large ints magically convert :(
                        if (Runtime.PyLong_Check(op))
                        {
                            Runtime.XDecref(op);
                            goto overflow;
                        }

                        if (op == IntPtr.Zero)
                        {
                            if (Exceptions.ExceptionMatches(overflow))
                            {
                                goto overflow;
                            }
                            goto type_error;
                        }
                        ival = (int)Runtime.PyInt_AsLong(op);
                        Runtime.XDecref(op);
                        result = ival;
                        return true;
                    }
                    else // Python3 always use PyLong API
                    {
                        op = Runtime.PyNumber_Long(value);
                        if (op == IntPtr.Zero)
                        {
                            Exceptions.Clear();
                            if (Exceptions.ExceptionMatches(overflow))
                            {
                                goto overflow;
                            }
                            goto type_error;
                        }
                        long ll = (long)Runtime.PyLong_AsLongLong(op);
                        Runtime.XDecref(op);
                        if (ll == -1 && Exceptions.ErrorOccurred())
                        {
                            goto overflow;
                        }
                        if (ll > Int32.MaxValue || ll < Int32.MinValue)
                        {
                            goto overflow;
                        }
                        result = (int)ll;
                        return true;
                    }

                case TypeCode.Boolean:
                    result = Runtime.PyObject_IsTrue(value) != 0;
                    return true;

                case TypeCode.Byte:
#if PYTHON3
                    if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
                    {
                        if (Runtime.PyBytes_Size(value) == 1)
                        {
                            op = Runtime.PyBytes_AS_STRING(value);
                            result = (byte)Marshal.ReadByte(op);
                            return true;
                        }
                        goto type_error;
                    }
#elif PYTHON2
                    if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType))
                    {
                        if (Runtime.PyString_Size(value) == 1)
                        {
                            op = Runtime.PyString_AsString(value);
                            result = (byte)Marshal.ReadByte(op);
                            return true;
                        }
                        goto type_error;
                    }
#endif

                    op = Runtime.PyNumber_Int(value);
                    if (op == IntPtr.Zero)
                    {
                        if (Exceptions.ExceptionMatches(overflow))
                        {
                            goto overflow;
                        }
                        goto type_error;
                    }
                    ival = (int)Runtime.PyInt_AsLong(op);
                    Runtime.XDecref(op);

                    if (ival > Byte.MaxValue || ival < Byte.MinValue)
                    {
                        goto overflow;
                    }
                    byte b = (byte)ival;
                    result = b;
                    return true;

                case TypeCode.SByte:
#if PYTHON3
                    if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
                    {
                        if (Runtime.PyBytes_Size(value) == 1)
                        {
                            op = Runtime.PyBytes_AS_STRING(value);
                            result = (byte)Marshal.ReadByte(op);
                            return true;
                        }
                        goto type_error;
                    }
#elif PYTHON2
                    if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType))
                    {
                        if (Runtime.PyString_Size(value) == 1)
                        {
                            op = Runtime.PyString_AsString(value);
                            result = (sbyte)Marshal.ReadByte(op);
                            return true;
                        }
                        goto type_error;
                    }
#endif

                    op = Runtime.PyNumber_Int(value);
                    if (op == IntPtr.Zero)
                    {
                        if (Exceptions.ExceptionMatches(overflow))
                        {
                            goto overflow;
                        }
                        goto type_error;
                    }
                    ival = (int)Runtime.PyInt_AsLong(op);
                    Runtime.XDecref(op);

                    if (ival > SByte.MaxValue || ival < SByte.MinValue)
                    {
                        goto overflow;
                    }
                    sbyte sb = (sbyte)ival;
                    result = sb;
                    return true;

                case TypeCode.Char:
#if PYTHON3
                    if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
                    {
                        if (Runtime.PyBytes_Size(value) == 1)
                        {
                            op = Runtime.PyBytes_AS_STRING(value);
                            result = (byte)Marshal.ReadByte(op);
                            return true;
                        }
                        goto type_error;
                    }
#elif PYTHON2
                    if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType))
                    {
                        if (Runtime.PyString_Size(value) == 1)
                        {
                            op = Runtime.PyString_AsString(value);
                            result = (char)Marshal.ReadByte(op);
                            return true;
                        }
                        goto type_error;
                    }
#endif
                    else if (Runtime.PyObject_TypeCheck(value, Runtime.PyUnicodeType))
                    {
                        if (Runtime.PyUnicode_GetSize(value) == 1)
                        {
                            op = Runtime.PyUnicode_AsUnicode(value);
                            Char[] buff = new Char[1];
                            Marshal.Copy(op, buff, 0, 1);
                            result = buff[0];
                            return true;
                        }
                        goto type_error;
                    }

                    op = Runtime.PyNumber_Int(value);
                    if (op == IntPtr.Zero)
                    {
                        goto type_error;
                    }
                    ival = Runtime.PyInt_AsLong(op);
                    Runtime.XDecref(op);
                    if (ival > Char.MaxValue || ival < Char.MinValue)
                    {
                        goto overflow;
                    }
                    result = (char)ival;
                    return true;

                case TypeCode.Int16:
                    op = Runtime.PyNumber_Int(value);
                    if (op == IntPtr.Zero)
                    {
                        if (Exceptions.ExceptionMatches(overflow))
                        {
                            goto overflow;
                        }
                        goto type_error;
                    }
                    ival = (int)Runtime.PyInt_AsLong(op);
                    Runtime.XDecref(op);
                    if (ival > Int16.MaxValue || ival < Int16.MinValue)
                    {
                        goto overflow;
                    }
                    short s = (short)ival;
                    result = s;
                    return true;

                case TypeCode.Int64:
                    op = Runtime.PyNumber_Long(value);
                    if (op == IntPtr.Zero)
                    {
                        if (Exceptions.ExceptionMatches(overflow))
                        {
                            goto overflow;
                        }
                        goto type_error;
                    }
                    long l = (long)Runtime.PyLong_AsLongLong(op);
                    Runtime.XDecref(op);
                    if ((l == -1) && Exceptions.ErrorOccurred())
                    {
                        goto overflow;
                    }
                    result = l;
                    return true;

                case TypeCode.UInt16:
                    op = Runtime.PyNumber_Int(value);
                    if (op == IntPtr.Zero)
                    {
                        if (Exceptions.ExceptionMatches(overflow))
                        {
                            goto overflow;
                        }
                        goto type_error;
                    }
                    ival = (int)Runtime.PyInt_AsLong(op);
                    Runtime.XDecref(op);
                    if (ival > UInt16.MaxValue || ival < UInt16.MinValue)
                    {
                        goto overflow;
                    }
                    ushort us = (ushort)ival;
                    result = us;
                    return true;

                case TypeCode.UInt32:
                    op = Runtime.PyNumber_Long(value);
                    if (op == IntPtr.Zero)
                    {
                        if (Exceptions.ExceptionMatches(overflow))
                        {
                            goto overflow;
                        }
                        goto type_error;
                    }

                    uint ui;
                    try
                    {
                        ui = Convert.ToUInt32(Runtime.PyLong_AsUnsignedLong(op));
                    } catch (OverflowException)
                    {
                        // Probably wasn't an overflow in python but was in C# (e.g. if cpython
                        // longs are 64 bit then 0xFFFFFFFF + 1 will not overflow in
                        // PyLong_AsUnsignedLong)
                        Runtime.XDecref(op);
                        goto overflow;
                    }

                    if (Exceptions.ErrorOccurred())
                    {
                        Runtime.XDecref(op);
                        goto overflow;
                    }

                    IntPtr check = Runtime.PyLong_FromUnsignedLong(ui);
                    int err = Runtime.PyObject_Compare(check, op);
                    Runtime.XDecref(check);
                    Runtime.XDecref(op);
                    if (0 != err || Exceptions.ErrorOccurred())
                    {
                        goto overflow;
                    }

                    result = ui;
                    return true;

                case TypeCode.UInt64:
                    op = Runtime.PyNumber_Long(value);
                    if (op == IntPtr.Zero)
                    {
                        if (Exceptions.ExceptionMatches(overflow))
                        {
                            goto overflow;
                        }
                        goto type_error;
                    }
                    ulong ul = (ulong)Runtime.PyLong_AsUnsignedLongLong(op);
                    Runtime.XDecref(op);
                    if (Exceptions.ErrorOccurred())
                    {
                        goto overflow;
                    }
                    result = ul;
                    return true;

                case TypeCode.Single:
                    op = Runtime.PyNumber_Float(value);
                    if (op == IntPtr.Zero)
                    {
                        if (Exceptions.ExceptionMatches(overflow))
                        {
                            goto overflow;
                        }
                        goto type_error;
                    }
                    double dd = Runtime.PyFloat_AsDouble(op);
                    Runtime.CheckExceptionOccurred();
                    Runtime.XDecref(op);
                    if (dd > Single.MaxValue || dd < Single.MinValue)
                    {
                        if (!double.IsInfinity(dd))
                        {
                            goto overflow;
                        }
                    }
                    result = (float)dd;
                    return true;

                case TypeCode.Double:
                    op = Runtime.PyNumber_Float(value);
                    if (op == IntPtr.Zero)
                    {
                        goto type_error;
                    }
                    double d = Runtime.PyFloat_AsDouble(op);
                    Runtime.CheckExceptionOccurred();
                    Runtime.XDecref(op);
                    result = d;
                    return true;
            }

            type_error:

            if (setError)
            {
                string tpName = Runtime.PyObject_GetTypeName(value);
                Exceptions.SetError(Exceptions.TypeError, $"'{tpName}' value cannot be converted to {obType}");
            }

            return false;

            overflow:

            if (setError)
            {
                Exceptions.SetError(Exceptions.OverflowError, "value too large to convert");
            }

            return false;
        }

        private static void SetConversionError(IntPtr value, Type target)
        {
            IntPtr ob = Runtime.PyObject_Repr(value);
            string src = Runtime.GetManagedString(ob);
            Runtime.XDecref(ob);
            Exceptions.SetError(Exceptions.TypeError, $"Cannot convert {src} to {target}");
        }

        /// <summary>
        /// Convert a Python value to a correctly typed managed array instance.
        /// The Python value must support the Python iterator protocol or and the
        /// items in the sequence must be convertible to the target array type.
        /// </summary>
        private static bool ToArray(IntPtr value, Type obType, out object result, bool setError)
        {
            Type elementType = obType.GetElementType();
            result = null;

            bool IsSeqObj = Runtime.PySequence_Check(value);
            var len = IsSeqObj ? Runtime.PySequence_Size(value) : -1;

            IntPtr IterObject = Runtime.PyObject_GetIter(value);

            if(IterObject==IntPtr.Zero) {
                if (setError)
                {
                    SetConversionError(value, obType);
                }
                return false;
            }

            Array items;

            var listType = typeof(List<>);
            var constructedListType = listType.MakeGenericType(elementType);
            IList list = IsSeqObj ? (IList) Activator.CreateInstance(constructedListType, new Object[] {(int) len}) :
                                        (IList) Activator.CreateInstance(constructedListType);
            IntPtr item;

            while ((item = Runtime.PyIter_Next(IterObject)) != IntPtr.Zero)
            {
                object obj = null;

                if (!Converter.ToManaged(item, elementType, out obj, true))
                {
                    Runtime.XDecref(item);
                    return false;
                }

                list.Add(obj);
                Runtime.XDecref(item);
            }
            Runtime.XDecref(IterObject);

            items = Array.CreateInstance(elementType, list.Count);
            list.CopyTo(items, 0);

            result = items;
            return true;
        }

        /// <summary>
        /// Convert a Python value to a correctly typed managed enum instance.
        /// </summary>
        private static bool ToEnum(IntPtr value, Type obType, out object result, bool setError)
        {
            Type etype = Enum.GetUnderlyingType(obType);
            result = null;

            if (!ToPrimitive(value, etype, out result, setError))
            {
                return false;
            }

            if (Enum.IsDefined(obType, result))
            {
                result = Enum.ToObject(obType, result);
                return true;
            }

            if (obType.GetCustomAttributes(flagsType, true).Length > 0)
            {
                result = Enum.ToObject(obType, result);
                return true;
            }

            if (setError)
            {
                Exceptions.SetError(Exceptions.ValueError, "invalid enumeration value");
            }

            return false;
        }
    }

    public static class ConverterExtension
    {
        public static PyObject ToPython(this object o)
        {
            return new PyObject(Converter.ToPython(o, o?.GetType()));
        }
    }
}


text:
package org.slf4j.impl;

import org.slf4j.ILoggerFactory;
import org.slf4j.spi.LoggerFactoryBinder;

/**
 * The static binder for slf4j logging, which allows CAS
 * to select its own {@link org.slf4j.ILoggerFactory} instance at runtime.
 * Note that this class MUST reside in the {@code org.slf4j.impl}
 * package so it can be loaded by the runtime dynamic lookup.
 * @author Misagh Moayyed
 * @since 4.1.0
 */
public final class StaticLoggerBinder implements LoggerFactoryBinder {

    /**
     * The unique instance of this class.
     */
    private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();

    /**
     * The {@link ILoggerFactory} instance returned by the
     * {@link #getLoggerFactory} method should always be the same
     * object.
     */
    private final ILoggerFactory loggerFactory;

    /**
     * Instantiates a new Static logger binder.
     */
    private StaticLoggerBinder() {
        this.loggerFactory = new CasLoggerFactory();
    }

    /**
     * Return the singleton of this class.
     *
     * @return the StaticLoggerBinder singleton
     */
    public static StaticLoggerBinder getSingleton() {
        return SINGLETON;
    }

    @Override
    public ILoggerFactory getLoggerFactory() {
        return this.loggerFactory;
    }

    @Override
    public String getLoggerFactoryClassStr() {
        return CasLoggerFactory.class.getName();
    }
}