text:
"""
Created on Mon Mar 23 21:14:59 2015.

@author: Morten
"""
import types
import logging
from pprint import pprint, pformat  # noqa
from copy import deepcopy
from collections.abc import MutableSequence

import numpy as np
from scipy.stats import distributions

from anypytools.tools import define2str, path2str, array2anyscript

logger = logging.getLogger("abt.anypytools")

__all__ = [
    "MacroCommand",
    "Load",
    "SetValue",
    "SetValue_random",
    "Dump",
    "SaveDesign",
    "LoadDesign",
    "SaveValues",
    "LoadValues",
    "UpdateValues",
    "OperationRun",
    "SaveData",
]

def _isgenerator(x):
    return isinstance(x, types.GeneratorType)

def _batch(iterable, n=1):
    length = len(iterable)
    for ndx in range(0, length, n):
        yield iterable[ndx : min(ndx + n, length)]

class MacroCommand(object):
    """Class for custom macro commands.

    This class also serves as base class for other macro commands.

    Examples
    --------
    >>> mc = MacroCommand('operation "Main.MyStudy.InverseDynamics"') )
    >>> print(mc)
    operation "Main.MyStudy.InverseDynamics"

    """

    def __init__(self, command):
        if not isinstance(command, list):
            self.cmd = [command]
        else:
            self.cmd = command

    def __repr__(self):
        return self.get_macro(0)

    def get_macro(self, index, **kwarg):
        """Create a string representation of the macro.

        Parameters
        ----------
        index : int
            The index for the macro beeing generated. Some child classes
            use the index to generate different macros depending on the
            index.

        Returns
        -------
        string
            A string with the AnyScript macro

        """
        return "\n".join(self.cmd)

class Load(MacroCommand):
    """Create a load macro command.

    Parameters
    ----------
    filename : str
        Path of the file to load
    defs : dict
        Dictionary of defines statements to set during load
    paths : dict
        Dictionary of path staements to set during load

    Examples
    --------
    >>> Load('model.main.any')
    load "model.main.any"

    >>> paths = {'DATA':'c:/MyModel/Data'}
    >>> defines = {'EXCLUDE_ARMS':None, 'N_STEP':20}
    >>> Load('c:/MyModel/model.main.any', defines, paths)
    load "c:/MyModel/model.main.any" -def EXCLUDE_ARMS="" -def N_STEP="20" -p DATA=---"c:/MyModel/Data"

    >>> mcr = AnyMacro( Load('model_{id}.main.any'), counter_token = '{id}')
    >>> mcr.create_macros(3)
    [[u'load "model_0.main.any"'],
     [u'load "model_1.main.any"'],
     [u'load "model_2.main.any"']]

    """

    def __init__(self, filename, defs={}, paths={}):
        self.filename = filename
        self.defs = defs.copy()
        self.paths = paths.copy()

    def get_macro(self, index, **kwarg):
        cmd = ['load "{}"'.format(self.filename)]

        for key in sorted(self.defs):
            value = self.defs[key]
            cmd.append(define2str(key, value))
        for key in sorted(self.paths):
            value = self.paths[key]
            cmd.append(path2str(key, value))

        return " ".join(cmd)

class SetValue(MacroCommand):
    """Create 'Set Value' classoperation macro command.

    Parameters
    ----------
    var : string
        An AnyScript variable.
    value : number or list of number
        A value or list of values to assign to the AnyScript variable.

    Examples
    ---------
    Set a single values:

    >>> SetValue('Main.Study.myvar1', 23.1)
    classoperation Main.Study.myvar1 "Set Value" --value="23.1"

    >>> SetValue('Main.Study.myvar2', np.array([2,3,4]))
    classoperation Main.Study.myvar2 "Set Value" --value="{2,3,4}"

    Set variable across different macros

    >>> SetValue('Main.Study.myvar1',[1,2,3])
    classoperation Main.Study.myvar1 "Set Value" --value="1"
    classoperation Main.Study.myvar1 "Set Value" --value="2"
    classoperation Main.Study.myvar1 "Set Value" --value="3"

    Here is a elaborate example:

    >>> mg = AnyMacro( Load('MyModel.main.any'),
                     SetValue('Main.Study.myvar1',[1,2]),
                     OperationRun('Main.Study.InverseDynamics') )
    >>> mg.number_of_macros = 2
    [['load "MyModel.main.any"',
      'classoperation Main.Study.myvar1 "Set Value" --value="1"',
      'operation Main.Study.InverseDynamics',
      'run'],
     ['load "MyModel.main.any"',
      'classoperation Main.Study.myvar1 "Set Value" --value="2"',
      'operation Main.Study.InverseDynamics',
      'run']]

    If we generate more macros that there are values then the values are just
    repeated

    >>> mg.number_of_macros = 4
    >>> mg
    [['load "MyModel.main.any"',
      'classoperation Main.Study.myvar1 "Set Value" --value="1"',
      'operation Main.Study.InverseDynamics',
      'run'],
     ['load "MyModel.main.any"',
      'classoperation Main.Study.myvar1 "Set Value" --value="2"',
      'operation Main.Study.InverseDynamics',
      'run'],
     ['load "MyModel.main.any"',
      'classoperation Main.Study.myvar1 "Set Value" --value="1"',
      'operation Main.Study.InverseDynamics',
      'run'],
     ['load "MyModel.main.any"',
      'classoperation Main.Study.myvar1 "Set Value" --value="2"',
      'operation Main.Study.InverseDynamics',
      'run']]

    """

    def __init__(self, var, value):
        self.var = var
        self.value = value

    def __repr__(self):
        if isinstance(self.value, list):
            n_elem = len(self.value)
        else:
            n_elem = 1

        return "\n".join([self.get_macro(i) for i in range(n_elem)])

    def get_macro(self, index, **kwarg):
        if isinstance(self.value, list):
            val = self.value[index % len(self.value)]
        else:
            val = self.value
        return self._format_macro(val)

    def _format_macro(self, val):
        if isinstance(val, np.ndarray):
            val = array2anyscript(val)
        elif isinstance(val, float):
            val = "{:.12g}".format(val)
        elif isinstance(val, int):
            val = "{:d}".format(val)
        return 'classoperation {0} "Set Value" --value="{1}"'.format(self.var, val)

class SetValue_random(SetValue):
    """Create a 'Set Value' macro command from a distribution.

    The value is connected to a distibution in scipy.stats.distributions.

    Parameters
    ----------
    var : str
        An AnyScript variable.
    frozen_distribution : <scipy.stats.distributions.rv_frozen>
        A frozen distribution from scipy.stats.distributions
    default_lower_tail_probability : float
        The lower tail probability of the default value. Defaults to 0.5 which
        is the mean value.

    Examples
    --------
    Creating normal macros will use the default values. Usually the 50 percentile
    (mean values).

    >>> np.random.seed(1)
    >>> from scipy.stats.distributions import logistic, norm
    >>> log_dist = logistic( loc= [1,3,4],scale = [0.1,0.5,1] )
    >>> norm_dist = norm( loc= [0,0,0],scale = [0.1,0.5,1] )
    >>> cmd = [SetValue_random('Main.MyVar1', log_dist), SetValue_random('Main.MyVar2', norm_dist) ]
    >>> mg = AnyMacro(cmd, number_of_macros = 3)
    >>> mg
    [['classoperation Main.MyVar1 "Set Value" --value="{0,0,0}"',
      'classoperation Main.MyVar2 "Set Value" --value="{1,3,4}"'],
     ['classoperation Main.MyVar1 "Set Value" --value="{0,0,0}"',
      'classoperation Main.MyVar2 "Set Value" --value="{1,3,4}"'],
     ['classoperation Main.MyVar1 "Set Value" --value="{0,0,0}"',
      'classoperation Main.MyVar2 "Set Value" --value="{1,3,4}"']]

    Values can be sampled randomly in a 'Monte Carlo' fashion. Note that the
    first value is still the defaut mean values

    >>> mg.create_macros_MonteCarlo()
    [['classoperation Main.MyVar1 "Set Value" --value="{0,0,0}"',
      'classoperation Main.MyVar2 "Set Value" --value="{1,3,4}"'],
     ['classoperation Main.MyVar1 "Set Value" --value="{-0.0209517840916,0.291902872134,-3.68494766954}"',
      'classoperation Main.MyVar2 "Set Value" --value="{0.916378512121,2.11986245798,1.71459079162}"'],
     ['classoperation Main.MyVar1 "Set Value" --value="{-0.0891762169545,-0.198666812922,-0.261723075945}"',
      'classoperation Main.MyVar2 "Set Value" --value="{1.01555799978,2.83695956934,4.7778636562}"']]

    Values can also be sampled with a Latin Hyper Cube sampler.

    >>> mg.create_macros_LHS()
    [['classoperation Main.MyVar1 "Set Value" --value="{0.0928967116493,-0.591418725401,-0.484696993931}"',
      'classoperation Main.MyVar2 "Set Value" --value="{1.01049414425,2.46211329129,5.73806916203}"'],
     ['classoperation Main.MyVar1 "Set Value" --value="{-0.0166741228961,0.707722119582,-0.294180629253}"',
      'classoperation Main.MyVar2 "Set Value" --value="{1.11326829265,2.66016732923,4.28054911097}"'],
     ['classoperation Main.MyVar1 "Set Value" --value="{-0.20265197275,0.114947152258,0.924796936287}"',
      'classoperation Main.MyVar2 "Set Value" --value="{0.806864877696,4.4114188826,2.93941843565}"']]

    """

    def __init__(self, var, frozen_distribution, default_lower_tail_probability=0.5):
        self.var = var
        if not isinstance(frozen_distribution, distributions.rv_frozen):
            raise TypeError(
                "frozen_distribution must be frozen distribtuion from \
                            scipy.stats.distributions"
            )

        self.rv = frozen_distribution

        self.meanvalue = frozen_distribution.mean()
        if isinstance(self.meanvalue, np.ndarray):
            self.shape = self.meanvalue.shape
            self.n_factors = np.prod(self.shape)
            self.default_lower_tail_probability = (
                default_lower_tail_probability * np.ones(self.shape)
            )
        else:
            self.shape = None
            self.n_factors = 1
            self.default_lower_tail_probability = default_lower_tail_probability

    def __repr__(self):
        return self.get_macro(0)

    def get_macro(self, index, lower_tail_probability=None, **kwarg):
        if lower_tail_probability is None:
            lower_tail_probability = self.default_lower_tail_probability

        if self.shape is None and isinstance(lower_tail_probability, np.ndarray):
            lower_tail_probability = lower_tail_probability[0]

        val = self.rv.ppf(lower_tail_probability).reshape(self.shape)
        # Replace any nan from ppf function with actual sampled values.
        if np.any(np.isnan(val)):
            val[np.isnan(val)] = self.rv.rvs()[np.isnan(val)]

        return self._format_macro(val)

class Dump(MacroCommand):
    """Create a Dump classoperation macro command.

    Parameters
    ----------
    var : str or list of str
        The anyscript values to create a 'Dump' macro command for
    include_in_macro: int or list of int
        Specifices in which macros [0,1,2....NumberOfMacros] to include the
        dump command.
        If None, the command is included in all macros.

    Examples
    ---------
    >>> Dump('Main.Study.myvar1')
    classoperation Main.Study.myvar1 "Dump"

    Only include the dump command in the two first macro

    >>> mg = AnyMacro(number_of_macros = 5)
    >>> mg.append(Load('mymodel.main.any'))
    >>> mg.append(Dump('Main.Study.myvar1', include_in_macro = [0,1]))
    >>> mg
    [['load "mymodel.main.any"', 'classoperation Main.Study.myvar1 "Dump"'],
     ['load "mymodel.main.any"', 'classoperation Main.Study.myvar1 "Dump"'],
     ['load "mymodel.main.any"'],
     ['load "mymodel.main.any"'],
     ['load "mymodel.main.any"']]

    """

    def __init__(self, var, include_in_macro=None):
        if not isinstance(var, list):
            self.var_list = [var]
        else:
            self.var_list = var
        self._include_in_macro = include_in_macro

    def get_macro(self, index, **kwarg):
        cmd = []
        if self._include_in_macro is None or index in self._include_in_macro:
            for var in self.var_list:
                cmd.append('classoperation {0} "Dump"'.format(var))
        return "\n".join(cmd)

class SaveDesign(MacroCommand):
    """Create a Save Design classoperation macro command.

    Parameters
    ----------
    operation : str
        The AnyScript operation
    filename : str
        The filename in which to save the design

    Examples
    --------
    >>> SaveDesign('Main.MyStudy.Kinematics', 'c:/design.txt')
    classoperation Main.MyStudy.Kinematics "Save design" --file="c:/design.txt"

    """

    def __init__(self, operation, filename):
        self.filename = filename
        self.operation = operation

    def get_macro(self, index, **kwarg):
        return 'classoperation {} "Save design" --file="{}"'.format(
            self.operation, self.filename
        )

class LoadDesign(MacroCommand):
    """Create a Load Design classoperation macro command.

    Parameters
    ----------
    operation : str
        The AnyScript operation
    filename : str
        The file in which to load the design from

    Examples
    --------
    >>> LoadDesign('Main.MyStudy.Kinematics', 'c:/design.txt')
    classoperation Main.MyStudy.Kinematics "Load design" --file="c:/design.txt"

    """

    def __init__(self, operation, filename):
        self.filename = filename
        self.operation = operation

    def get_macro(self, index, **kwarg):
        return 'classoperation {} "Load design" --file="{}"'.format(
            self.operation, self.filename
        )

class SaveValues(MacroCommand):
    """Create a Save Values classoperation macro command.

    Parameters
    ----------
    filename : str
        The anyset file to save the values to

    Examples
    --------
    >>> SaveValues('c:/values.anyset')
    classoperation Main "Save Values" --file="c:/values.anyset"

    """

    def __init__(self, filename):
        self.filename = filename

    def get_macro(self, index, **kwarg):
        return 'classoperation Main "Save Values" --file="{}"'.format(self.filename)

class SaveData(MacroCommand):
    """Create a Save Data classoperation macro command.

    This macro operation will save all data from a study to a
    HDF5 file.

    Parameters
    ----------
    operation : str
        Operation to save the h5 from
    filename : str
        The anyset file to save the values to

    Examples
    --------
    >>> SaveData('Main.Study', 'output.anydata.h5')
    classoperation Main.Study.Output "Save data" --type="Deep" --file="output.anydata.h5"

    """

    def __init__(self, operation, filename):
        self.filename = filename
        self.opeation = operation

    def get_macro(self, index, **kwarg):
        macro_str = 'classoperation {}.Output "Save data" --type="Deep" --file="{}"'
        return macro_str.format(self.opeation, self.filename)

class LoadValues(MacroCommand):
    """Create a Load Values classoperation macro command.

    Parameters
    ----------
    filename : str
        The anyset file to load the values from.

    Examples
    --------
    >>> LoadValues('c:/values.anyset')
    classoperation Main "Load Values" --file="c:/values.anyset"

    """

    def __init__(self, filename):
        self.filename = filename

    def get_macro(self, index, **kwarg):
        return 'classoperation Main "Load Values" --file="{}"'.format(self.filename)

class UpdateValues(MacroCommand):
    """Create an 'Update Values' classoperation macro command.

    Examples
    --------
    >>> UpdateValues()
    classoperation Main "Update Values"

    """

    def __init__(self):
        pass

    def get_macro(self, index, **kwarg):
        return 'classoperation Main "Update Values"'

class OperationRun(MacroCommand):
    """Create a macro command to select and run an operation.

    Examples
    --------
    >>> OperationRun('Main.MyStudy.Kinematics')
    >>> pprint( mg.generate_macros())
    operation Main.MyStudy.Kinematics
    run

    >>> mg = AnyMacro(Load('my_model.main.any'),
                   OperationRun('Main.MyStudy.Kinematics'))
    >>> mg.create_macros()
    [[u'load "my_model.main.any"', u'operation Main.MyStudy.Kinematics', u'run']]

    """

    def __init__(self, operation):
        self.operation = operation

    def get_macro(self, index, **kwarg):
        return "operation {}".format(self.operation) + "\n" + "run"

class AnyMacro(MutableSequence):
    """
    Class to generate multiple macros.

    Use the class to contruct multiple anyscript macros from a single macro.
    E.g. for parameter studies, Monte Carlo, Latin Hyper Cube studies.

    Parameters
    ----------
    maco_commands : list or positional arguments
        A list of macro command classes. These may also be given a arbitrary number
        of positional arguments.
    counter_token : str
        A string in the macro commands which will be replace with a counter
        for every macro generated
    number_of_macros : int
        The default number of macros which are created. This can be overruled when
        calling the AnyMacro.create_macros() function. Defults to 1.
    seed : int or array_like
        A constant seed value used which will be used every time macros are created.
        Must be convertable to 32 bit unsigned integers.

    Returns
    -------
    An AnyMacro instance
        A Macro object for constructing the macro.

    Examples
    --------
    >>> mg = AnyMacro(number_of_macros = 22)
    >>> mg.append( Load('c:/MyModel/model.main.any', defs = {}, paths = {} ) )
    >>> mg.append( SetValue('Main.myvar', 12.3)  )
    >>> mg.extend( [RunOperation('Main.Study.Kinematics'),
                     Dump('Main.Study.Output.MyVar') ] )
    >>> mg
    [['load "c:/MyModel/model.main.any"',
      'classoperation Main.myvar "Set Value" --value="12.3"',
      'operation Main.Study.Kinematics',
      'run',
      'classoperation Main.Study.Output.MyVar "Dump"'],
     ['load "c:/MyModel/model.main.any"',
      'classoperation Main.myvar "Set Value" --value="12.3"',
      'operation Main.Study.Kinematics',
      'run',
      'classoperation Main.Study.Output.MyVar "Dump"']]

    >>> mg = AnyMacro( number_of_macros = 3, counter_token='{COUNTER}' )
    >>> mg.append(Load('c:/MyModel/model_{COUNTER}_.main.any') )
    >>> pprint(mg.create_macros())
    [['load "c:/MyModel/model_0_.main.any"'],
     ['load "c:/MyModel/model_1_.main.any"'],
     ['load "c:/MyModel/model_2_.main.any"']]

    """

    def __init__(self, *args, **kwargs):  # number_of_macros=1, counter_token = None ):
        super(AnyMacro, self).__init__()
        if len(args) == 0:
            self._list = list()
        else:
            if len(args) == 1 and isinstance(args[0], list):
                args = args[0]
            for arg in args:
                if not isinstance(arg, MacroCommand):
                    raise ValueError("Argument must be valid macro command classes")
            self._list = list(args)

        self.seed = kwargs.pop("seed", None)

        self.number_of_macros = kwargs.pop("number_of_macros", 1)
        self.counter_token = kwargs.pop("counter_token", None)

    def __mul__(self, other):
        if not isinstance(other, (int, float)):
            raise NotImplementedError("operator must be integer")
        mg = deepcopy(self)
        mg.number_of_macros = mg.number_of_macros * round(other)
        return mg

    __rmul__ = __mul__

    def __len__(self):
        return len(self._list)

    def __getitem__(self, ii):
        return self._list[ii]

    def __delitem__(self, ii):
        del self._list[ii]

    def __setitem__(self, ii, val):
        self._list[ii] = val
        return self._list[ii]

    def __str__(self):
        return self.__repr__()

    def __repr__(self):
        return pformat(self.create_macros())

    def insert(self, ii, val):
        self._list.insert(ii, val)

    def append(self, val):
        list_idx = len(self._list)
        self.insert(list_idx, val)

    def create_macros(self, number_of_macros=None, batch_size=None):
        """Generate a given number of macros.

        The function return its output either as list (batch_size = None) or in batches
        as generator object (memory efficient when generating many macros)

        Parameters
        ----------
        number_of_macros : int (Optional)
            The number of macro to create.
        batch_size : int (Optional)
            If specified the function will return a generator which creates macros in
            batches.

        Returns
        -------
        list or generator
            A list macros or a generator which creates macros in batches

        Examples
        --------
        >>> from anypytools import AnyMacro
        >>> from anypytools.macro_commands import *
        >>> macro = [
        ...     Load('c:/Model.main.any'),
        ...     OperationRun('Main.study.Kinematics'),
        ... ]
        >>> mg = AnyMacro(macro, number_of_macros=4)
        >>> macrolist = mg.create_macros()
        >>> pprint(macrolist)
        [['load "c:/Model.main.any"', 'operation Main.study.Kinematics', 'run'],
         ['load "c:/Model.main.any"', 'operation Main.study.Kinematics', 'run'],
         ['load "c:/Model.main.any"', 'operation Main.study.Kinematics', 'run'],
         ['load "c:/Model.main.any"', 'operation Main.study.Kinematics', 'run']]

        Generate macros in batches

        >>> mg = AnyMacro([Load('c:/Model.main.any')], number_of_macros = 6)
        >>> macro_gen =  mg.create_macros(batch_size=2)
        >>> for i, macros in enumerate( macro_gen ):
        ...     print('Batch ', i)
        ...     pprint(macros)
        Batch 0
        [['load "c:/Model.main.any"'], ['load "c:/Model.main.any"']]
        Batch 1
        [['load "c:/Model.main.any"'], ['load "c:/Model.main.any"']]
        Batch 2
        [['load "c:/Model.main.any"'], ['load "c:/Model.main.any"']]

        """
        if batch_size is not None:
            return _batch(self.create_macros(number_of_macros), n=batch_size)

        if number_of_macros is None:
            number_of_macros = self.number_of_macros
        if self.seed is not None:
            np.random.seed(self.seed)
        macro_list = []
        for macro_idx in range(number_of_macros):
            macro = []
            for elem in self:
                mcr = elem.get_macro(macro_idx)
                if self.counter_token:
                    mcr = mcr.replace(self.counter_token, str(macro_idx))
                if mcr != "":
                    macro.extend(mcr.split("\n"))
            macro_list.append(macro)
        return macro_list

    def create_macros_MonteCarlo(self, number_of_macros=None, batch_size=None):  # noqa
        """Generate AnyScript macros for monte carlos studies.

        The function returns macros for Monte Carlo parameter studies. This methods
        extends the `create_macros` methods with functionality to randomly vary
        parameters across macros.

        Values added with `SetValue_random` class are sampled randomly in a
        'Monte Carlo' fashion. Note that the values of the first macro
        is the defaut mean value.

        Parameters
        ----------
        number_of_macros : int (Optional)
            The number of macro to create.
        batch_size : int (Optional)
            If specified the function will return a generator which creates macros in
            batches.

        Returns
        -------
        list or generator
            A list macros or a generator which creates macros in batches

        Examples
        --------
        >>> np.random.seed(1)
        >>> from scipy.stats.distributions import logistic, norm
        >>> log_dist = logistic( loc= [1,3,4],scale = [0.1,0.5,1] )
        >>> norm_dist = norm( loc= [0,0,0],scale = [0.1,0.5,1] )
        >>> cmd = [SetValue_random('Main.MyVar1', log_dist), SetValue_random('Main.MyVar2', norm_dist) ]
        >>> mg = AnyMacro(cmd, number_of_macros = 3)
        >>> mg.create_macros_MonteCarlo()
        [['classoperation Main.MyVar1 "Set Value" --value="{0,0,0}"',
        'classoperation Main.MyVar2 "Set Value" --value="{1,3,4}"'],
        ['classoperation Main.MyVar1 "Set Value" --value="{-0.0209517840916,0.291902872134,-3.68494766954}"',
        'classoperation Main.MyVar2 "Set Value" --value="{0.916378512121,2.11986245798,1.71459079162}"'],
        ['classoperation Main.MyVar1 "Set Value" --value="{-0.0891762169545,-0.198666812922,-0.261723075945}"',
        'classoperation Main.MyVar2 "Set Value" --value="{1.01555799978,2.83695956934,4.7778636562}"']]

        """
        if batch_size is not None:
            return _batch(self.create_macros_MonteCarlo(number_of_macros), batch_size)

        if number_of_macros is None:
            number_of_macros = self.number_of_macros

        if self.seed is not None:
            np.random.seed(self.seed)

        macro_list = []
        for macro_idx in range(number_of_macros):
            macro = []
            lhs_idx = 0
            for elem in self:
                if isinstance(elem, SetValue_random):
                    if macro_idx == 0:
                        lower_tail_probability = (
                            None  # First macro get the default values
                        )
                    else:
                        lower_tail_probability = np.random.random(elem.n_factors)
                    mcr = elem.get_macro(macro_idx, lower_tail_probability)
                    lhs_idx += elem.n_factors
                else:
                    mcr = elem.get_macro(macro_idx)

                if self.counter_token:
                    mcr = mcr.replace(self.counter_token, str(macro_idx))
                if mcr != "":
                    macro.extend(mcr.split("\n"))
            macro_list.append(macro)
        return macro_list

    def create_macros_LHS(
        self,
        number_of_macros=None,
        criterion=None,  # noqa
        iterations=None,
        batch_size=None,
        append_default=False,
    ):
        """Generate AnyScript macros for Latin Hyper Cube Studies studies.

        Generates AnyScript macros for parameter studies using Latin hyper cube
        sampling. The macros added with the `SetValue_random` are created with
        with Latin Hypercube Sampling (LHS) of the parameter space. The number
        of generated macros determines the number of LHS samples.

        The method uses the pyDOE package to generate the LHS data.

        Parameters
        ----------
        number_of_macros : int (Optional)
            The number of macro to create.
        batch_size : int (Optional)
            If specified the function will return a generator which creates macros in
            batches.
        criterion : {None, 'c', 'm', 'cm', 'corr'}
            A a string that specifies how points are sampled
            (see: http://pythonhosted.org/pyDOE/randomized.html)
            `None` (Default) points are randomizes within the intervals.
            "center" or "c" center the points within the sampling intervals
            "maximin" or "m": maximize the minimum distance between points, but place
            the point in a randomized location within its interval
            "centermaximin" or "cm": same as "maximin", but centered within the intervals
            "corr" minimize the maximum correlation coefficient
        iterations : int
            Specifies how many iterations are used to accomplished the selected criterion
        append_default : bool
            If True a macro with default (mean) values is appended to the returned list
            of returned macros

        Returns
        -------
        list or generator
            A list macros or a generator which creates macros in batches

        Examples
        --------
        >>> np.random.seed(1)
        >>> from scipy.stats.distributions import logistic, norm
        >>> log_dist = logistic( loc= [1,3,4],scale = [0.1,0.5,1] )
        >>> norm_dist = norm( loc= [0,0,0],scale = [0.1,0.5,1] )
        >>> cmd = [SetValue_random('Main.MyVar1', log_dist), SetValue_random('Main.MyVar2', norm_dist) ]
        >>> mg = AnyMacro(cmd, number_of_macros = 3)
        >>> mg.create_macros_LHS()
        [['classoperation Main.MyVar1 "Set Value" --value="{0.0928967116493,-0.591418725401,-0.484696993931}"',
        'classoperation Main.MyVar2 "Set Value" --value="{1.01049414425,2.46211329129,5.73806916203}"'],
        ['classoperation Main.MyVar1 "Set Value" --value="{-0.0166741228961,0.707722119582,-0.294180629253}"',
        'classoperation Main.MyVar2 "Set Value" --value="{1.11326829265,2.66016732923,4.28054911097}"'],
        ['classoperation Main.MyVar1 "Set Value" --value="{-0.20265197275,0.114947152258,0.924796936287}"',
        'classoperation Main.MyVar2 "Set Value" --value="{0.806864877696,4.4114188826,2.93941843565}"']]

        """  # noqa
        try:
            import pyDOE
        except ImportError:
            raise ImportError("The pyDOE package must be install to use this class")

        if batch_size is not None:
            return _batch(
                self.create_macros_LHS(number_of_macros, criterion, iterations),
                n=batch_size,
            )

        if number_of_macros is None:
            number_of_macros = self.number_of_macros

        if self.seed is not None:
            np.random.seed(self.seed)

        factors = sum([e.n_factors for e in self if isinstance(e, SetValue_random)])
        lhs_matrix = pyDOE.lhs(
            factors, number_of_macros, criterion=criterion, iterations=iterations
        )

        macro_list = []

        for macro_idx in range(number_of_macros):
            macro = []
            lhs_idx = 0
            for elem in self:
                if isinstance(elem, SetValue_random):
                    lhs_val = lhs_matrix[macro_idx, lhs_idx : lhs_idx + elem.n_factors]
                    mcr = elem.get_macro(macro_idx, lower_tail_probability=lhs_val)
                    lhs_idx += elem.n_factors
                else:
                    mcr = elem.get_macro(macro_idx)

                if self.counter_token:
                    mcr = mcr.replace(self.counter_token, str(macro_idx))
                if len(mcr) > 0:
                    macro.extend(mcr.split("\n"))
            macro_list.append(macro)
        if append_default:
            macro = []
            for elem in self:
                mcr = elem.get_macro(number_of_macros)
                if self.counter_token:
                    mcr = mcr.replace(self.counter_token, str(number_of_macros))
                if len(mcr) > 0:
                    macro.extend(mcr.split("\n"))
            macro_list.append(macro)
        return macro_list

if __name__ == "__main__":

    #    mg = PertubationMacroGenerator()
    #    mg.add_set_value_designvar('test',1)
    #    mg.add_set_value_designvar('test',2)
    #
    #    pprint(mg.generate_macros())
    #
    import pytest

    pytest.main(str("generate_macros.py --doctest-modules"))


text:
'use strict';

var assert = require('assert');
var isint = require('isint');
var portUtils = require('./port-utils');

var EPHEMERAL_PORT_FIRST = 49152;
var EPHEMERAL_PORT_COUNT = 16000;
assert(isint.uint16(EPHEMERAL_PORT_FIRST + EPHEMERAL_PORT_COUNT));

class PortAllocator {
  constructor() {
    this._searchStart = 0;
    this._allocated = 0;
    this._sockets = [];
    this._map = null;
  }

  get allocatedCount() {
    return this._allocated;
  }

  isEphemeralRange(port) {
    return port >= EPHEMERAL_PORT_FIRST && port < EPHEMERAL_PORT_FIRST + EPHEMERAL_PORT_COUNT;
  }

  allocEphemeral(socket) {
    if (this._searchStart < this._sockets.length) {
      for (let i = this._searchStart, l = this._sockets.length; i < l; ++i) {
        if ((null === this._sockets[i]) && ((null !== this._map) ? !this._map.has(EPHEMERAL_PORT_FIRST + i) : true)) {
          this._sockets[i] = socket;
          ++this._allocated;
          this._searchStart = i + 1;
          return EPHEMERAL_PORT_FIRST + i;
        }
      }
    }

    while (this._sockets.length < EPHEMERAL_PORT_COUNT) {
      if (null !== this._map && this._map.has(EPHEMERAL_PORT_FIRST + this._sockets.length)) {
        this._sockets.push(null);
        continue;
      }

      this._sockets.push(socket);
      ++this._allocated;
      this._searchStart = this._sockets.length;
      return EPHEMERAL_PORT_FIRST + this._sockets.length - 1;
    }

    return 0;
  }

  allocPort(port, socket) {
    assert(portUtils.isPort(port));
    if (this.lookup(port)) {
      return false;
    }

    if (null === this._map) {
      this._map = new Map();
    }

    this._map.set(port, socket);
    ++this._allocated;
    return true;
  }

  free(port) {
    assert(portUtils.isPort(port));

    if ((null !== this._map) && this._map.has(port)) {
      this._map.delete(port);
      --this._allocated;
      if (this.isEphemeralRange(port)) {
        if (port - EPHEMERAL_PORT_FIRST < this._searchStart) {
          this._searchStart = port - EPHEMERAL_PORT_FIRST;
        }
      }
      return;
    }

    if (this.isEphemeralRange(port)) {
      var index = port - EPHEMERAL_PORT_FIRST;
      if (index >= this._sockets.length) {
        return;
      }

      if (null === this._sockets[index]) {
        return;
      }

      this._sockets[index] = null;
      if (index < this._searchStart) {
        this._searchStart = index;
      }
      --this._allocated;
      if (0 === this._allocated) {
        this._sockets = [];
        this._searchStart = 0;
      }
    }
  }

  lookup(port) {
    if ((null !== this._map) && this._map.has(port)) {
      return this._map.get(port);
    }

    if (this.isEphemeralRange(port)) {
      var index = port - EPHEMERAL_PORT_FIRST;
      if (index >= this._sockets.length) {
        return null;
      }

      return this._sockets[index];
    }

    return null;
  }
}

module.exports = PortAllocator;

redpajama_set_name: RedPajamaGithub


text:
module PublicSuffix
  # The current library version.
  VERSION = "3.0.3".freeze
end


text:
package model.canvas

/**
 * Created by Stanislaw Robak on 2014-12-26.
 */
class CanvasProperties (val xMin: Double = -100.0, val xMax: Double = 100.0,
                         val yMin: Double = -100.0, val yMax: Double = 100.0,
                          val GUICanvas: GUICanvas,
                           val drawingMode: DrawingMode = new DrawByX)


text:
using System;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using Moq;
using Avalonia.Controls;
using Avalonia.Data;
using Avalonia.Markup.Xaml.Data;
using Avalonia.Styling;
using Xunit;
using System.Reactive.Disposables;
using Avalonia.UnitTests;
using Avalonia.VisualTree;
using System.Linq;

namespace Avalonia.Markup.Xaml.UnitTests.Data
{
    public class BindingTests_TemplatedParent
    {
        [Fact]
        public void OneWay_Binding_Should_Be_Set_Up()
        {
            var target = CreateTarget();
            var binding = new Binding
            {
                Mode = BindingMode.OneWay,
                RelativeSource = new RelativeSource(RelativeSourceMode.TemplatedParent),
                Priority = BindingPriority.TemplatedParent,
                Path = "Foo",
            };

            target.Object.Bind(TextBox.TextProperty, binding);

            target.Verify(x => x.Bind(
                TextBox.TextProperty,
                It.IsAny<IObservable<object>>(),
                BindingPriority.TemplatedParent));
        }

        [Fact]
        public void TwoWay_Binding_Should_Be_Set_Up()
        {
            var target = CreateTarget();
            var binding = new Binding
            {
                Mode = BindingMode.TwoWay,
                RelativeSource = new RelativeSource(RelativeSourceMode.TemplatedParent),
                Priority = BindingPriority.TemplatedParent,
                Path = "Foo",
            };

            target.Object.Bind(TextBox.TextProperty, binding);

            target.Verify(x => x.Bind(
                TextBox.TextProperty,
                It.IsAny<ISubject<object>>(),
                BindingPriority.TemplatedParent));
        }

        [Fact]
        public void TemplateBinding_With_Null_Path_Works()
        {
            using (UnitTestApplication.Start(TestServices.StyledWindow))
            {
                var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
        xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
        xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'>
    <Button Name='button'>
       <Button.Template>
         <ControlTemplate>
           <TextBlock Text='{TemplateBinding}'/>
         </ControlTemplate>
       </Button.Template>
    </Button>
</Window>";
                var loader = new AvaloniaXamlLoader();
                var window = (Window)loader.Load(xaml);
                var button = window.FindControl<Button>("button");

                window.ApplyTemplate();
                button.ApplyTemplate();

                var textBlock = (TextBlock)button.GetVisualChildren().Single();
                Assert.Equal("Avalonia.Controls.Button", textBlock.Text);
            }
        }

        private Mock<IControl> CreateTarget(
            ITemplatedControl templatedParent = null,
            string text = null)
        {
            var result = new Mock<IControl>();

            result.Setup(x => x.GetValue(Control.TemplatedParentProperty)).Returns(templatedParent);
            result.Setup(x => x.GetValue((AvaloniaProperty)Control.TemplatedParentProperty)).Returns(templatedParent);
            result.Setup(x => x.GetValue((AvaloniaProperty)TextBox.TextProperty)).Returns(text);
            result.Setup(x => x.Bind(It.IsAny<AvaloniaProperty>(), It.IsAny<IObservable<object>>(), It.IsAny<BindingPriority>()))
                .Returns(Disposable.Empty);
            return result;
        }
    }
}


text:
package org.scalajs.testsuite.javalib.util

import java.util.Locale

import org.junit.Test
import org.junit.Assert._

/** Sanity tests for the dummy implementation of `java.util.Locale`.
 *
 *  These tests ensure that our dummy implementation of `java.util.Locale`
 *  behaves in an appropriate way. We only test specific behaviors that can
 *  cause tests to "fail to fail" if they are not respected.
 */
class LocaleTest {
  @Test def testDefaultLocaleIsRoot(): Unit = {
    assertEquals(Locale.ROOT, Locale.getDefault())
    assertEquals("", Locale.ROOT.getLanguage())
    assertEquals("", Locale.ROOT.getCountry())
  }

  @Test def testLanguageIsNormalizedLowerCase(): Unit = {
    /* Our implementations of `String.toLowerCase(locale: Locale)` and
     * `String.toUpperCase(locale: Locale)` assume that the result of
     * `locale.getLanguage()` is always all-lowercase.
     * This test makes sure that this is indeed the case.
     */

    assertEquals("lt", new Locale("lt").getLanguage())
    assertEquals("lt", new Locale("LT").getLanguage())
    assertEquals("lt", new Locale("lT").getLanguage())
    assertEquals("lt", new Locale("Lt").getLanguage())

    assertEquals("tr", new Locale("tr").getLanguage())
    assertEquals("tr", new Locale("TR").getLanguage())
    assertEquals("tr", new Locale("tR").getLanguage())
    assertEquals("tr", new Locale("Tr").getLanguage())

    assertEquals("az", new Locale("az").getLanguage())
    assertEquals("az", new Locale("AZ").getLanguage())
    assertEquals("az", new Locale("aZ").getLanguage())
    assertEquals("az", new Locale("Az").getLanguage())

    // The normalization itself is locale-insensitive
    // This was locally tested with a JVM configured in Turkish
    assertEquals("it", new Locale("it").getLanguage())
    assertEquals("it", new Locale("IT").getLanguage())
    assertEquals("it", new Locale("iT").getLanguage())
    assertEquals("it", new Locale("It").getLanguage())
  }
}


text:
release_script="./release_app.sh"
#############################

# Arguments #################
app_list_file=$1
log_dir=$2
version=$3
#############################

# Colors! ###################
BLACK=`tput setaf 0`
RED=`tput setaf 1`
GREEN=`tput setaf 2`
YELLOW=`tput setaf 3`
BLUE=`tput setaf 4`
MAGENTA=`tput setaf 5`
CYAN=`tput setaf 6`
GRAY=`tput setaf 7`
BOLD=`tput bold`
DIM=`tput dim`
UNDER=`tput smul`
RESET=`tput sgr0`
#############################

# Remember the original working directory
# Change working directory to script dir
ORIG_WD="`pwd`"

#############################
# Validate args and conf ####

# App List
if [ -e "`pwd`/$app_list_file" ] ; then
  app_list_file="`pwd`/$app_list_file"
elif ! [ -e $app_list_file ] ; then
  echo "applist not found: $app_list_file"
  exit
fi

# Log Dir
if [ -d "`pwd`/$log_dir" ] ; then
  log_dir="`pwd`/$log_dir"
elif ! [ -d $log_dir ] ; then
  echo "Logging dir not found: $log_dir"
  exit
fi

# Release script
# Change working directory to script dir to look for the script
cd "$(dirname "$0")"
if [ -e "`pwd`/$release_script" ] ; then
  release_script="`pwd`/$release_script"
else
  cd $ORIG_WD
  if [ -e "`pwd`/$release_script" ] ; then
    release_script="`pwd`/$release_script"
  elif ! [ -e $release_script ] ; then
    echo "Release script not found: $release_script"
    exit
  fi
fi

cd $ORIG_WD
echo "$GREEN$BOLD"
echo "Running Release"
echo "==============================================="
echo "$RESET"
echo "${GRAY}Git Version   : $YELLOW$BOLD $version $RESET"
echo "${GRAY}Log directory : $YELLOW$BOLD $log_dir $RESET"
echo "${GRAY}Release script: $YELLOW$BOLD $release_script $RESET"
echo "${GRAY}App List File : $YELLOW$BOLD $app_list_file $RESET"

i=1
skip_count=0
pids=() # Array of process ids to watch
while read p || [[ -n $p ]]; do
  if [[ $p == *"#"* ]]
  then
    i=$[$i+1]
    skip_count=$[$i+1]
    continue
  fi

  sh $release_script $p $version > $log_dir/$p.log 2>&1 &
  PID=$!
  pids+=($PID)

  i=$[$i+1]
done < $app_list_file

# Bash can't do floating point arithmetic so
# we have to be creative with ints
num_pids=${#pids[@]}
marker_percent=5
pid_div=$((100/marker_percent))
marker=$((num_pids/pid_div))

if [ $marker -eq 0 ] ; then
  marker=num_pids
fi

total_markers=$((num_pids/marker))

echo "${GRAY}Skipping      : $YELLOW$BOLD $skip_count $RESET"
echo "${GRAY}Releasing to  : $YELLOW$BOLD $num_pids $RESET"
echo

prog_count=0
#prints the progress bar
print_progress_bar(){
  echo -ne "["
  counter=0
  echo -ne $GREEN
  while (( $counter < $num_markers )) ; do
    echo -ne "#"
    let counter=counter+1
  done
  while (( $counter < total_markers )) ; do
    echo -ne " "
    let counter=counter+1
  done
  echo -ne "$RESET] - $YELLOW$num_done/$num_pids"

  spinner="\\"
  modulo=$(( prog_count % 4 ))

  case $modulo in
  0)
    spinner="\\" ;;
  1)
    spinner="|" ;;
  2)
    spinner="/" ;;
  3)
    spinner="-" ;;
  esac

  echo -ne "$GRAY$BOLD $spinner $RESET \r"
}

# Checks on the progress of the PIDs that are still alive and
# prints out the progress bar
progress(){
  count=0
  for pid in "${pids[@]}"
  do
    if kill -s 0 $pid > /dev/null 2>&1
    then
      count=$[$count+1]
    fi
  done

  # 5 percent = num_pids / 20

  num_done=$((num_pids-count))
  num_markers=$((num_done/marker))

  print_progress_bar

  if (( $count < 1 )) ; then
    echo
    echo
    exit
  fi

  prog_count=$[$prog_count+1]
}

while true; do
  sleep 0.5
  progress
done


text:
package com.blossomproject.core.common.event;

import com.blossomproject.core.common.dto.AbstractAssociationDTO;

/**
 * Application Event which notify the application when an association is soon going to be deleted.
 *
 * @param <DTO> the {@code AbstractAssociationDTO} just before it is deleted
 * @author Maël Gargadennnec
 */
public class BeforeDissociatedEvent<DTO extends AbstractAssociationDTO> extends Event<DTO> {

  public BeforeDissociatedEvent(Object source, DTO entity) {
    super(source, entity);
  }

}


text:
layout: default
title: "Popular Capitalism"

---

{% include interests/popular-capitalism.md %}

### Who is interested in Popular Capitalism?

* [Mr John Redwood]({{ site.baseurl }}/members/mr-john-redwood.html)


text:
require_relative './entity'

module Pudl

  # Base class for all actions
  #
  class BaseAction < Entity

    class Dsl < Entity::Dsl
    end

    class Runner < Entity::Runner

      def run *args
        logger.warn "#{self.class.name} has no run behaviour"
      end

      def dry_run *args
        logger.info entity.inspect
      end

    end

    dsl_class Dsl
    runner_class Runner

  end

end


text:
package io.jenkins.blueocean.rest.model;

/**
 * Describes requested state of a favorited item
 *
 * @author Ivan Meredith
 * @author Vivek Pandey
 *
 * @see io.jenkins.blueocean.rest.model.BluePipeline#favorite(BlueFavoriteAction)
 */
public class BlueFavoriteAction {
    private Boolean favorite;

    public void setFavorite(boolean favorite) {
        this.favorite = favorite;
    }

    /**
     * @return true favorite, false un-favorite, null toggle
     */
    public Boolean isFavorite() {
        return favorite;
    }
}


text:
"""Tests for emojis support."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from timesketch.lib import emojis
from timesketch.lib.testlib import BaseTest

class TestEmojisLib(BaseTest):
    """Tests for the emojis support library."""

    def test_get_emoji(self):
        """Test getting emoji code."""
        skull_emoji = emojis.get_emoji("skull_crossbone")
        skull_code = "&#x2620"

        self.assertEqual(skull_emoji, skull_code)

        locomotive_emoji = emojis.get_emoji("LOCOMOTIVE")
        locomotive_code = "&#x1F682"
        self.assertEqual(locomotive_emoji, locomotive_code)

        does_not_exist = emojis.get_emoji("er_ekki_til")
        self.assertEqual(does_not_exist, "")

    def test_get_helper_from_unicode(self):
        """Test getting helper text from an emoji code."""
        skull_emoji = emojis.get_emoji("skull_crossbone")
        skull_helper = emojis.get_helper_from_unicode(skull_emoji)
        helper_text = "Suspicious entry"

        self.assertEqual(skull_helper, helper_text)

        does_not_exist = emojis.get_helper_from_unicode("er_ekki_til")
        self.assertEqual(does_not_exist, "")

    def test_get_emojis_as_dict(self):
        """Test getting emojis as a dictionary."""
        skull_code = "&#x2620"
        helper_text = "Suspicious entry"
        emojis_dict = emojis.get_emojis_as_dict()
        skull_helper = emojis_dict.get(skull_code)
        self.assertEqual(skull_helper, helper_text)

        does_not_exist = emojis_dict.get("finns_inte")
        self.assertIsNone(does_not_exist)


text:
package params

import (
	"sync/atomic"
)

// A pool of Params
type Pool struct {
	misses int64
	size   int
	list   chan *Params
}

// Create a new pool of count params.
// Each ArrayParam has a maximum size of size.
// If the size exceeds this value, the ArrayParam is converted to a MapParams
func NewPool(size, count int) *Pool {
	pool := &Pool{
		size: size,
		list: make(chan *Params, count),
	}
	for i := 0; i < count; i++ {
		pool.list <- pooled(pool, size)
	}
	return pool
}

// The number of times we tried to checkout but had no available
// params in our pool
func (p *Pool) Misses() int64 {
	return atomic.SwapInt64(&p.misses, 0)
}

// Get a param from the pool or create a new one if the pool is empty
func (p *Pool) Checkout() *Params {
	select {
	case item := <-p.list:
		return item
	default:
		atomic.AddInt64(&p.misses, 1)
		return New(p.size)
	}
}


text:
<resources>
    <string name="app_name">PictureTransformTest</string>
</resources>


text:
CURLRequest Class
#################

The ``CURLRequest`` class is a lightweight HTTP client based on CURL that allows you to talk to other
web sites and servers. It can be used to get the contents of a Google search, retrieve a web page or image,
or communicate with an API, among many other things.

.. contents::
    :local:
    :depth: 2

This class is modeled after the `Guzzle HTTP Client <http://docs.guzzlephp.org/en/latest/>`_ library since
it is one of the more widely used libraries. Where possible, the syntax has been kept the same so that if
your application needs something a little more powerful than what this library provides, you will have
to change very little to move over to use Guzzle.

.. note:: This class requires the `cURL Library <https://www.php.net/manual/en/book.curl.php>`_ to be installed
    in your version of PHP. This is a very common library that is typically available but not all hosts
    will provide it, so please check with your host to verify if you run into problems.

**********************
Config for CURLRequest
**********************

Sharing Options
===============

Due to historical reasons, by default, the CURLRequest shares all the options between requests.
If you send more than one request with an instance of the class,
this behavior may cause an error request with unnecessary headers and body.

You can change the behavior by editing the following config parameter value in **app/Config/CURLRequest.php** to ``false``:

.. literalinclude:: curlrequest/001.php

.. note:: Before v4.2.0, the request body is not reset even if ``$shareOptions`` is false due to a bug.

*******************
Loading the Library
*******************

The library can be loaded either manually or through the :doc:`Services class </concepts/services>`.

To load with the Services class call the ``curlrequest()`` method:

.. literalinclude:: curlrequest/002.php

You can pass in an array of default options as the first parameter to modify how cURL will handle the request.
The options are described later in this document:

.. literalinclude:: curlrequest/003.php

.. note:: When ``$shareOptions`` is false, the default options passed to the class constructor will be used for all requests. Other options will be reset after sending a request.

When creating the class manually, you need to pass a few dependencies in. The first parameter is an
instance of the ``Config\App`` class. The second parameter is a URI instance. The third
parameter is a Response object. The fourth parameter is the optional default ``$options`` array:

.. literalinclude:: curlrequest/004.php

************************
Working with the Library
************************

Working with CURL requests is simply a matter of creating the Request and getting a
:doc:`Response object </outgoing/response>` back. It is meant to handle the communications. After that
you have complete control over how the information is handled.

Making Requests
===============

Most communication is done through the ``request()`` method, which fires off the request, and then returns
a Response instance to you. This takes the HTTP method, the url and an array of options as the parameters.

.. literalinclude:: curlrequest/005.php

.. note:: When ``$shareOptions`` is false, the options passed to the method will be used for the request. After sending the request, they will be cleared. If you want to use the options to all requests, pass the options in the constructor.

Since the response is an instance of ``CodeIgniter\HTTP\Response`` you have all of the normal information
available to you:

.. literalinclude:: curlrequest/006.php

While the ``request()`` method is the most flexible, you can also use the following shortcut methods. They
each take the URL as the first parameter and an array of options as the second:

.. literalinclude:: curlrequest/007.php

Base URI
--------

A ``baseURI`` can be set as one of the options during the instantiation of the class. This allows you to
set a base URI, and then make all requests with that client using relative URLs. This is especially handy
when working with APIs:

.. literalinclude:: curlrequest/008.php

When a relative URI is provided to the ``request()`` method or any of the shortcut methods, it will be combined
with the baseURI according to the rules described by
`RFC 2986, section 2 <https://tools.ietf.org/html/rfc3986#section-5.2>`_. To save you some time, here are some
examples of how the combinations are resolved.

    =====================   ================   ========================
    baseURI                 URI                Result
    =====================   ================   ========================
    `http://foo.com`        /bar               `http://foo.com/bar`
    `http://foo.com/foo`    /bar               `http://foo.com/bar`
    `http://foo.com/foo`    bar                `http://foo.com/bar`
    `http://foo.com/foo/`   bar                `http://foo.com/foo/bar`
    `http://foo.com`        `http://baz.com`   `http://baz.com`
    `http://foo.com/?bar`   bar                `http://foo.com/bar`
    =====================   ================   ========================

Using Responses
===============

Each ``request()`` call returns a Response object that contains a lot of useful information and some helpful
methods. The most commonly used methods let you determine the response itself.

You can get the status code and reason phrase of the response:

.. literalinclude:: curlrequest/009.php

You can retrieve headers from the response:

.. literalinclude:: curlrequest/010.php

The body can be retrieved using the ``getBody()`` method:

.. literalinclude:: curlrequest/011.php

The body is the raw body provided by the remote server. If the content type requires formatting, you will need
to ensure that your script handles that:

.. literalinclude:: curlrequest/012.php

***************
Request Options
***************

This section describes all of the available options you may pass into the constructor, the ``request()`` method,
or any of the shortcut methods.

allow_redirects
===============

By default, cURL will follow all "Location:" headers the remote servers send back. The ``allow_redirects`` option
allows you to modify how that works.

If you set the value to ``false``, then it will not follow any redirects at all:

.. literalinclude:: curlrequest/013.php

Setting it to ``true`` will apply the default settings to the request:

.. literalinclude:: curlrequest/014.php

You can pass in array as the value of the ``allow_redirects`` option to specify new settings in place of the defaults:

.. literalinclude:: curlrequest/015.php

.. note:: Following redirects does not work when PHP is in safe_mode or open_basedir is enabled.

auth
====

Allows you to provide Authentication details for `HTTP Basic <https://www.ietf.org/rfc/rfc2069.txt>`_ and
`Digest <https://www.ietf.org/rfc/rfc2069.txt>`_ and authentication. Your script may have to do extra to support
Digest authentication - this simply passes the username and password along for you. The value must be an
array where the first element is the username, and the second is the password. The third parameter should be
the type of authentication to use, either ``basic`` or ``digest``:

.. literalinclude:: curlrequest/016.php

body
====

There are two ways to set the body of the request for request types that support them, like PUT, OR POST.
The first way is to use the ``setBody()`` method:

.. literalinclude:: curlrequest/017.php

The second method is by passing a ``body`` option in. This is provided to maintain Guzzle API compatibility,
and functions the exact same way as the previous example. The value must be a string:

.. literalinclude:: curlrequest/018.php

cert
====

To specify the location of a PEM formatted client-side certificate, pass a string with the full path to the
file as the ``cert`` option. If a password is required, set the value to an array with the first element
as the path to the certificate, and the second as the password:

.. literalinclude:: curlrequest/019.php

connect_timeout
===============

By default, CodeIgniter does not impose a limit for cURL to attempt to connect to a website. If you need to
modify this value, you can do so by passing the amount of time in seconds with the ``connect_timeout`` option.
You can pass 0 to wait indefinitely:

.. literalinclude:: curlrequest/020.php

cookie
======

This specifies the filename that CURL should use to read cookie values from, and
to save cookie values to. This is done using the CURL_COOKIEJAR and CURL_COOKIEFILE options.
An example:

.. literalinclude:: curlrequest/021.php

debug
=====

When ``debug`` is passed and set to ``true``, this will enable additional debugging to echo to STDERR during the
script execution. This is done by passing CURLOPT_VERBOSE and echoing the output. So, when you're running a built-in
server via ``spark serve`` you will see the output in the console. Otherwise, the output will be written to
the server's error log.

.. literalinclude:: curlrequest/034.php

You can pass a filename as the value for debug to have the output written to a file:

.. literalinclude:: curlrequest/022.php

delay
=====

Allows you to pause a number of milliseconds before sending the request:

.. literalinclude:: curlrequest/023.php

form_params
===========

You can send form data in an application/x-www-form-urlencoded POST request by passing an associative array in
the ``form_params`` option. This will set the ``Content-Type`` header to ``application/x-www-form-urlencoded``
if it's not already set:

.. literalinclude:: curlrequest/024.php

.. note:: ``form_params`` cannot be used with the ``multipart`` option. You will need to use one or the other.
        Use ``form_params`` for ``application/x-www-form-urlencoded`` request, and ``multipart`` for ``multipart/form-data``
        requests.

.. _curlrequest-request-options-headers:

headers
=======

While you can set any headers this request needs by using the ``setHeader()`` method, you can also pass an associative
array of headers in as an option. Each key is the name of a header, and each value is a string or array of strings
representing the header field values:

.. literalinclude:: curlrequest/025.php

If headers are passed into the constructor they are treated as default values that will be overridden later by any
further headers arrays or calls to ``setHeader()``.

http_errors
===========

By default, CURLRequest will fail if the HTTP code returned is greater than or equal to 400. You can set
``http_errors`` to ``false`` to return the content instead:

.. literalinclude:: curlrequest/026.php

json
====

The ``json`` option is used to easily upload JSON encoded data as the body of a request. A Content-Type header
of ``application/json`` is added, overwriting any Content-Type that might be already set. The data provided to
this option can be any value that ``json_encode()`` accepts:

.. literalinclude:: curlrequest/027.php

.. note:: This option does not allow for any customization of the ``json_encode()`` function, or the Content-Type
        header. If you need that ability, you will need to encode the data manually, passing it through the ``setBody()``
        method of CURLRequest, and set the Content-Type header with the ``setHeader()`` method.

multipart
=========

When you need to send files and other data via a POST request, you can use the ``multipart`` option, along with
the `CURLFile Class <https://www.php.net/manual/en/class.curlfile.php>`_. The values should be an associative array
of POST data to send. For safer usage, the legacy method of uploading files by prefixing their name with an `@`
has been disabled. Any files that you want to send must be passed as instances of CURLFile:

.. literalinclude:: curlrequest/028.php

.. note:: ``multipart`` cannot be used with the ``form_params`` option. You can only use one or the other. Use
        ``form_params`` for ``application/x-www-form-urlencoded`` requests, and ``multipart`` for ``multipart/form-data``
        requests.

query
=====

You can pass along data to send as query string variables by passing an associative array as the ``query`` option:

.. literalinclude:: curlrequest/029.php

timeout
=======

By default, cURL functions are allowed to run as long as they take, with no time limit. You can modify this with the ``timeout``
option. The value should be the number of seconds you want the functions to execute for. Use 0 to wait indefinitely:

.. literalinclude:: curlrequest/030.php

user_agent
==========

Allows specifying the User Agent for requests:

.. literalinclude:: curlrequest/031.php

verify
======

This option describes the SSL certificate verification behavior. If the ``verify`` option is ``true``, it enables the
SSL certificate verification and uses the default CA bundle provided by the operating system. If set to ``false`` it
will disable the certificate verification (this is insecure, and allows man-in-the-middle attacks!). You can set it
to a string that contains the path to a CA bundle to enable verification with a custom certificate. The default value
is true:

.. literalinclude:: curlrequest/032.php

version
=======

To set the HTTP protocol to use, you can pass a string or float with the version number (typically either 1.0
or 1.1, 2.0 is currently unsupported.):

.. literalinclude:: curlrequest/033.php


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.f1x.api.message.fields;

// Generated by org.f1x.tools.DictionaryGenerator from QuickFIX dictionary
public enum DiscretionMoveType implements org.f1x.api.message.types.ByteEnum {
	FLOATING((byte)'0'),
	FIXED((byte)'1');

	private final byte code;

	DiscretionMoveType (byte code) {
		this.code  = code;
	}

	public byte getCode() { return code; }

	public static DiscretionMoveType parse(String s) {
		switch(s) {
			case "0" : return FLOATING;
			case "1" : return FIXED;
		}
		return null;
	}

}


text:
namespace _05.NoteStatistics
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class Program
    {
        public static void Main()
        {
            List<double> inputFrequencies = Console.ReadLine()
                .Split(' ').Select(double.Parse).ToList();

            List<double> frequencies = new List<double>
            {261.63, 277.18, 293.66, 311.13, 329.63, 349.23, 369.99, 392.00, 415.30, 440.00, 466.16, 493.88};

            List<string> notes = new List<string>
            {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"};

            List<string> representNotes = new List<string>();

            foreach (var frequency in inputFrequencies)
            {
                int noteIndex = frequencies.IndexOf(frequency);
                string note = notes[noteIndex];
                representNotes.Add(note);
            }

            Console.WriteLine("Notes: {0}", string.Join(" ", representNotes));

            List<string> naturalNotes = new List<string>();
            List<string> sharpNotes = new List<string>();

            foreach (var note in representNotes)
            {
                if (note.Contains("#"))
                {
                    sharpNotes.Add(note);
                }
                else
                {
                    naturalNotes.Add(note);
                }
            }

            Console.WriteLine("Naturals: {0}", string.Join(", ", naturalNotes));
            Console.WriteLine("Sharps: {0}", string.Join(", ", sharpNotes));

            double sumNaturalNotes = 0;

            foreach (var note in naturalNotes)
            {
                int frequencyIndex = notes.IndexOf(note);
                double frequency = frequencies[frequencyIndex];
                sumNaturalNotes += frequency;
            }

            double sumSharpNotes = 0;

            foreach (var note in sharpNotes)
            {
                int frequencyIndex = notes.IndexOf(note);
                double frequency = frequencies[frequencyIndex];
                sumSharpNotes += frequency;
            }

            Console.WriteLine($"Naturals sum: {sumNaturalNotes}");
            Console.WriteLine($"Sharps sum: {sumSharpNotes}");

        }
    }
}


text:
class CreateSemesters < ActiveRecord::Migration[5.1]
  def self.up
    create_table :portal_semesters do |t|

      t.string    :uuid, :limit => 36
      t.string    :name
      t.text      :description

      t.integer   :school_id

      t.datetime  :start_time
      t.datetime  :end_time

      t.timestamps
    end
  end

  def self.down
    drop_table :portal_semesters
  end
end


text:
require 'active_record/connection_adapters/abstract_adapter'
require 'active_record/connection_adapters/statement_pool'
require 'arel/visitors/bind_visitor'

require 'runivedo'

module ActiveRecord
  module Type
    class UUID < Type::Value
      def type_cast_for_database(value)
        value.to_s
      end
    end
  end

  module ConnectionHandling # :nodoc:
    def runivedo_connection(config)
      raise ArgumentError, "No univedo url specified. Missing argument: server" unless config[:server]
      raise ArgumentError, "No univedo app specified. Missing argument: app" unless config[:app]

      url = config[:server]
      bucket = config[:bucket]
      app = config[:app]
      username = config[:username]
      uts = config[:uts] ? IO.read(config[:uts]) : nil
      ConnectionAdapters::RunivedoAdapter.new(url, bucket, app, uts, username, logger, config)
    end
  end

  module ConnectionAdapters #:nodoc:
    class RunivedoAdapter < AbstractAdapter
      attr_reader :session, :perspective, :url, :bucket

      class BindSubstitution < Arel::Visitors::SQLite # :nodoc:
        include Arel::Visitors::BindVisitor
      end

      def initialize(url, bucket, app, uts, username, logger, config)
        super(nil, logger)

        @url = url
        @bucket = bucket
        @app = app
        @uts = uts
        @username = username
        @result = nil

        type_map.register_type 'uuid', Type::UUID.new

        @visitor = Arel::Visitors::SQLite.new self

        @prepared_statements = true

        connect
      end

      def adapter_name #:nodoc:
        'Runivedo'
      end

      def active?
        !@session.closed?
      end

      def connect
        @connection = Runivedo::Connection.new(@url)
        @session = @connection.get_session(@bucket, {username: @username})
        @session.apply_uts(@uts) if @uts
        @perspective = session.get_perspective(@app)
        @connection = @perspective.query
      end

      # Disconnects from the database if already connected. Otherwise, this
      # method does nothing.
      def disconnect!
        super
        @session.close rescue nil
      end

      def reconnect!
        super
        disconnect! rescue nil
        connect
      end

      def native_database_types #:nodoc:
        {
          :primary_key => default_primary_key_type,
          :string      => { :name => "varchar" },
          :text        => { :name => "text" },
          :integer     => { :name => "integer" },
          :float       => { :name => "float" },
          :decimal     => { :name => "decimal" },
          :datetime    => { :name => "datetime" },
          :timestamp   => { :name => "datetime" },
          :time        => { :name => "time" },
          :date        => { :name => "date" },
          :binary      => { :name => "blob" },
          :boolean     => { :name => "boolean" },
          :uuid        => { :name => "uuid" },
        }
      end

      # QUOTING ==================================================

      def quote_table_name_for_assignment(table, attr)
        quote_column_name(attr)
      end

      def quote_column_name(name) #:nodoc:
        %Q("#{name.to_s.gsub('"', '""')}")
      end

      # DATABASE STATEMENTS ======================================

      def exec_query(sql, name = nil, binds = [])
        log(sql, name, binds) do
          if without_prepared_statement?(binds)
            binds = []
          end
          stmt    = @connection.prepare(sql)
          cols    = stmt.column_names
          i = -1
          binds_hash = Hash[binds.map { |col, val|
            [i += 1, val]
          }]
          @result.close if @result
          @result = stmt.execute(binds_hash)
          records = @result.to_a
          stmt.close
          ActiveRecord::Result.new(cols, records)
        end
      end

      def exec_delete(sql, name = 'SQL', binds = [])
        exec_query(sql, name, binds)
        @result.num_affected_rows
      end
      alias :exec_update :exec_delete

      def last_inserted_id(result)
        raise "didn't insert anything" unless @result
        @result.last_inserted_id
      end

      def execute(sql, name = nil) #:nodoc:
        log(sql, name) do
          @connection.prepare(sql).execute.to_a
        end
      end

      def update_sql(sql, name = nil) #:nodoc:
        super
        @result.num_affected_rows
      end

      def delete_sql(sql, name = nil) #:nodoc:
        sql += " WHERE 1=1" unless sql =~ /WHERE/i
        super sql, name
      end

      def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) #:nodoc:
        super
        id_value || @connection.last_insert_row_id
      end
      alias :create :insert_sql

      def select_rows(sql, name = nil, binds = [])
        exec_query(sql, name, binds).rows
      end

      # SCHEMA STATEMENTS ========================================

      def tables(name = nil, table_name = nil) #:nodoc:
        @perspective.get_tables
      end

      def primary_key(table_name)
        "id"
      end

      def columns(table_name)
        @perspective.get_fields_for_table(table_name).map do |name, sql_type|
          sql_type = "integer" if sql_type == "pk"
          cast_type = lookup_cast_type(sql_type)
          Column.new(name, nil, cast_type, sql_type)
        end
      end

      protected

      def _quote(value)
        case value
        when Type::Binary::Data
          "x'#{value.hex}'"
        when UUIDTools::UUID
          "'#{value.to_s}'"
        else
          super
        end
      end
    end
  end
end


text:
from django.shortcuts import render
from django.views.generic import ListView, TemplateView, DetailView
from models import Legislature, Medium

class LegislatureList(ListView):
    model = Legislature
    template_name = 'legislature/legislature-list.html'
    context_object_name = 'legislatures'

class LegislatureDetail(DetailView):
    model = Legislature
    template_name = 'legislature/legislature-detail.html'
    context_object_name = 'legislature'

class MediumDetail(DetailView):
    model = Medium
    template_name = 'legislature/medium-detail.html'
    context_object_name = 'medium'


text:
set -e
export DEBIAN_FRONTEND=noninteractive

#Install ruby from package sources
apt-get install -y ruby ruby-dev

#Install rvm
gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3
curl -sSL https://get.rvm.io | sudo bash -s stable --ruby

#Set rvm permissions
chmod -R 777 /usr/local/rvm

#Install mailcatcher
gem install mailcatcher

#Install capistrano
gem install capistrano

#Install capifony
gem install capifony


text:
package org.wso2.andes.transport;

/**
 * Sender
 *
 */

public interface Sender<T>
{
    void setIdleTimeout(int i);

    void send(T msg);

    void flush();

    void close();

}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Travessa</tipo><logradouro>Aurora</logradouro><bairro>Peró</bairro><cidade>Cabo Frio</cidade><uf>RJ</uf><cep>28924194</cep></feed>


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.Windows.Media.Animation
{
  abstract public partial class StringKeyFrame : System.Windows.Freezable, IKeyFrame
  {
    #region Methods and constructors
    public string InterpolateValue(string baseValue, double keyFrameProgress)
    {
      return default(string);
    }

    protected abstract string InterpolateValueCore(string baseValue, double keyFrameProgress);

    protected StringKeyFrame()
    {
    }

    protected StringKeyFrame(string value)
    {
    }

    protected StringKeyFrame(string value, KeyTime keyTime)
    {
    }
    #endregion

    #region Properties and indexers
    public KeyTime KeyTime
    {
      get
      {
        return default(KeyTime);
      }
      set
      {
      }
    }

    Object System.Windows.Media.Animation.IKeyFrame.Value
    {
      get
      {
        return default(Object);
      }
      set
      {
      }
    }

    public string Value
    {
      get
      {
        return default(string);
      }
      set
      {
      }
    }
    #endregion

    #region Fields
    public readonly static System.Windows.DependencyProperty KeyTimeProperty;
    public readonly static System.Windows.DependencyProperty ValueProperty;
    #endregion
  }
}


text:
extern zend_class_entry *test_exceptions_ce;

ZEPHIR_INIT_CLASS(Test_Exceptions);

PHP_METHOD(Test_Exceptions, testException1);
PHP_METHOD(Test_Exceptions, testExceptionStringEscape);
PHP_METHOD(Test_Exceptions, testException2);
PHP_METHOD(Test_Exceptions, testException3);
PHP_METHOD(Test_Exceptions, getException);
PHP_METHOD(Test_Exceptions, testException4);
PHP_METHOD(Test_Exceptions, testException5);
PHP_METHOD(Test_Exceptions, testExceptionLiteral);
PHP_METHOD(Test_Exceptions, testExceptionSprintf);
PHP_METHOD(Test_Exceptions, testExceptionConcat);
PHP_METHOD(Test_Exceptions, testExceptionRethrow);
PHP_METHOD(Test_Exceptions, testMultiException);
PHP_METHOD(Test_Exceptions, issue1325);
PHP_METHOD(Test_Exceptions, doNoopException);

ZEND_BEGIN_ARG_INFO_EX(arginfo_test_exceptions_testexceptionliteral, 0, 0, 1)
#if PHP_VERSION_ID >= 70200
	ZEND_ARG_TYPE_INFO(0, type, IS_STRING, 0)
#else
	ZEND_ARG_INFO(0, type)
#endif
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_test_exceptions_testexceptionsprintf, 0, 0, 1)
#if PHP_VERSION_ID >= 70200
	ZEND_ARG_TYPE_INFO(0, name, IS_STRING, 0)
#else
	ZEND_ARG_INFO(0, name)
#endif
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_test_exceptions_testexceptionconcat, 0, 0, 2)
#if PHP_VERSION_ID >= 70200
	ZEND_ARG_TYPE_INFO(0, framework, IS_STRING, 0)
#else
	ZEND_ARG_INFO(0, framework)
#endif
#if PHP_VERSION_ID >= 70200
	ZEND_ARG_TYPE_INFO(0, language, IS_STRING, 0)
#else
	ZEND_ARG_INFO(0, language)
#endif
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_test_exceptions_testmultiexception, 0, 0, 2)
	ZEND_ARG_INFO(0, returnValue)
	ZEND_ARG_INFO(0, exception)
ZEND_END_ARG_INFO()

ZEPHIR_INIT_FUNCS(test_exceptions_method_entry) {
	PHP_ME(Test_Exceptions, testException1, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(Test_Exceptions, testExceptionStringEscape, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(Test_Exceptions, testException2, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(Test_Exceptions, testException3, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(Test_Exceptions, getException, NULL, ZEND_ACC_PROTECTED)
	PHP_ME(Test_Exceptions, testException4, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(Test_Exceptions, testException5, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(Test_Exceptions, testExceptionLiteral, arginfo_test_exceptions_testexceptionliteral, ZEND_ACC_PUBLIC)
	PHP_ME(Test_Exceptions, testExceptionSprintf, arginfo_test_exceptions_testexceptionsprintf, ZEND_ACC_PUBLIC)
	PHP_ME(Test_Exceptions, testExceptionConcat, arginfo_test_exceptions_testexceptionconcat, ZEND_ACC_PUBLIC)
	PHP_ME(Test_Exceptions, testExceptionRethrow, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(Test_Exceptions, testMultiException, arginfo_test_exceptions_testmultiexception, ZEND_ACC_PUBLIC)
	PHP_ME(Test_Exceptions, issue1325, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(Test_Exceptions, doNoopException, NULL, ZEND_ACC_PRIVATE)
	PHP_FE_END
};


text:
shared_context 'a GitHub-ish import controller' do
  let(:user) { create(:user) }
  let(:token) { "asdasd12345" }
  let(:access_params) { { github_access_token: token } }

  before do
    sign_in(user)
    allow(controller).to receive(:"#{provider}_import_enabled?").and_return(true)
  end
end


text:
#import <Foundation/NSObject.h>

@class RCBlock;

typedef void (^MyHandler)(RCBlock* name);

@interface RCBlockAA : NSObject

@property(nonatomic, strong) RCBlock* b;

@property(nonatomic, strong) RCBlockAA* child;

@end

typedef void (^MyAHandler)(RCBlockAA* name);

@interface RCBlock : NSObject {
  RCBlock* child;
}

@property(nonatomic, strong) RCBlockAA* a;

@property(nonatomic, strong) MyHandler handler;

@property(nonatomic, strong) MyAHandler a_handler;

@property(nonatomic, strong) RCBlock* child;

@end

@implementation RCBlockAA
@end

@implementation RCBlock

// This code can be executed and one can check that there's a cycle because
// "Dealloc" is not being printed.
- (void)dealloc {
  NSLog(@"Dealloc");
}

- (void)retain_self_in_block_retain_cycle {
  self.handler = ^(RCBlock* b) {
    self->_child = b;
  };
}

- (void)retain_weak_self_in_block_no_retain_cycle {
  __weak typeof(self) weak_self = self;
  self.handler = ^(RCBlock* b) {
    __strong typeof(self) strong_self = weak_self;
    if (strong_self)
      strong_self->_child = b;
  };
}

@end

int test_retain_self_in_block_cycle_bad() {
  RCBlock* c = [[RCBlock alloc] init];
  [c retain_self_in_block_retain_cycle];
  return 0;
}

int test_weak_self_in_block_no_retain_cycle_good() {
  RCBlock* c = [[RCBlock alloc] init];
  [c retain_weak_self_in_block_no_retain_cycle];
  return 0;
}

int retain_a_in_block_cycle_bad() {
  RCBlockAA* a = [RCBlockAA new];
  RCBlock* b = [RCBlock new];
  a.b = b;
  b.a_handler = ^(RCBlockAA* b) {
    a.child = nil;
  };
  return 0;
}


text:
from jinja2 import Template
from pathlib import Path

try:
    import mistune
except ModuleNotFoundError:
    raise ImportError('You need to install mistune to generate reports')

# import mistune
from sklearn_evaluation.report.util import jinja_env

class Report:
    def __init__(self, evaluator, template=None):
        self.evaluator = evaluator

        if template is None:
            template = jinja_env().get_template(self.evaluator.TEMPLATE_NAME)
        elif isinstance(template, Path):
            template = Template(template.read_text())
        elif isinstance(template, str):
            template = Template(template)

        rendered = template.render(e=evaluator)
        md = mistune.Markdown()
        self.rendered = md(rendered)

    def _repr_html_(self):
        return self.rendered

    def save(self, path):
        Path(path).write_text(self.rendered)


text:
import unittest
import test_elements
import test_accelerator
import test_tracking
import test_lattice
import test_optics

suite_list = []
suite_list.append(test_elements.get_suite())
suite_list.append(test_accelerator.get_suite())
suite_list.append(test_lattice.get_suite())
suite_list.append(test_tracking.get_suite())
suite_list.append(test_optics.get_suite())

tests = unittest.TestSuite(suite_list)
unittest.TextTestRunner(verbosity=2).run(tests)


text:
<html>
<script>
var tests = [];

scanFolder("inspector/console");
// scanFolder("inspector/debugger");
scanFolder("inspector/editor");
scanFolder("inspector/elements");
scanFolder("inspector/profiler");
scanFolder("inspector/styles");
scanFolder("inspector/timeline");
scanFolder("inspector");

function scanFolder(folder)
{
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "/LayoutTests/" + folder + "/", false);
    xhr.send(null);
    var text = xhr.responseText;
    var element = document.createElement("div");
    element.innerHTML = text;
    var links = element.querySelectorAll("a");
    for (var i = 0; i < links.length; ++i) {
        var link = links[i].href;
        var match = link.match(/[^\/]*\/([^\/]+\.html)$/);
        if (!match)
            continue;
        var path = "/LayoutTests/" + folder + "/" + match[1];
        var expected = fetchExpectations(path);
        tests.push([path, expected]);
    }
}

function fetchExpectations(path)
{
    var ext = path.lastIndexOf(".");
    path = path.substring(0, ext) + "-expected.txt";

    var expectations = fetch(path) || "";

    var expectationLines = expectations.split("\n");
    var filtered = [];
    for (var i = 0; i < expectationLines.length; ++i) {
        if (!expectationLines[i].indexOf("ALERT: ") ||
            !expectationLines[i].indexOf("CONSOLE MESSAGE: ")) {
            filtered = [];
            continue;
        }
        filtered.push(expectationLines[i]);
    }
    return filtered.join("\n");
}

function fetch(path)
{
    var xhr = new XMLHttpRequest();
    xhr.open("GET", path, false);
    xhr.send(null);
    return xhr.status !== 404 ? xhr.responseText : "";
}

window.parent.postMessage(["tests", tests], "*");

</script>
<body>
</body>
</html>


text:
import inspect
import sys

from tower import ugettext_lazy as _lazy

from mpconstants import countries

from mkt.constants import ratingsbodies
from mkt.constants.ratingsbodies import slugify_iarc_name

class REGION(object):
    """
    A region is like a country but more confusing.

    id::
        The primary key used to identify a region in the DB.

    name::
        The text that appears in the header and region selector menu.

    slug::
        The text that gets stored in the cookie or in ?region=<slug>.
        Use the ISO-3166 code please.

    mcc::
        Don't know what an ITU MCC is? They're useful for carrier billing.
        Read http://en.wikipedia.org/wiki/List_of_mobile_country_codes

    adolescent::
        With a mature region (meaning, it has a volume of useful data) we
        are able to calculate ratings and rankings independently. If a
        store is immature it will continue using the global popularity
        measure. If a store is mature it will use the smaller, more
        relevant set of data.

    weight::
        Determines sort order (after slug).

    special::
        Does this region need to be reviewed separately? That region is
        special.

    low_memory::
        Does this region have low-memory (Tarako) devices?

    """
    id = None
    name = slug = ''
    default_currency = 'USD'
    default_language = 'en-US'
    adolescent = True
    mcc = None
    weight = 0
    ratingsbody = None
    special = False
    low_memory = False

class RESTOFWORLD(REGION):
    id = 1
    name = _lazy(u'Rest of World')
    slug = 'restofworld'
    weight = -1

lookup = {
    'ARG': _lazy(u'Argentina'),
    'BGD': _lazy(u'Bangladesh'),
    'BRA': _lazy(u'Brazil'),
    'CHL': _lazy(u'Chile'),
    'CHN': _lazy(u'China'),
    'COL': _lazy(u'Colombia'),
    'CRI': _lazy(u'Costa Rica'),
    'DEU': _lazy(u'Germany'),
    'ECU': _lazy(u'Ecuador'),
    'ESP': _lazy(u'Spain'),
    'FRA': _lazy(u'France'),
    'GBR': _lazy(u'United Kingdom'),
    'GRC': _lazy(u'Greece'),
    'GTM': _lazy(u'Guatemala'),
    'HUN': _lazy(u'Hungary'),
    'IND': _lazy(u'India'),
    'ITA': _lazy(u'Italy'),
    'MNE': _lazy(u'Montenegro'),
    'NIC': _lazy(u'Nicaragua'),
    'PAN': _lazy(u'Panama'),
    'PER': _lazy(u'Peru'),
    'POL': _lazy(u'Poland'),
    'MEX': _lazy(u'Mexico'),
    'SLV': _lazy(u'El Salvador'),
    'SRB': _lazy(u'Serbia'),
    'USD': _lazy(u'United States'),
    'URY': _lazy(u'Uruguay'),
    'VEN': _lazy(u'Venezuela'),
}

for k, translation in lookup.items():
    country = countries.COUNTRY_DETAILS[k].copy()
    country['name'] = translation
    if country.get('ratingsbody'):
        country['ratingsbody'] = getattr(ratingsbodies, country['ratingsbody'])

    name = country['legacy']
    globals()[name] = type(name, (REGION,), country)

# Please adhere to the new region checklist when adding a new region:
# https://mana.mozilla.org/wiki/display/MARKET/How+to+add+a+new+region

# Create a list of tuples like so (in alphabetical order):
#
#     [('restofworld', <class 'mkt.constants.regions.RESTOFWORLD'>),
#      ('brazil', <class 'mkt.constants.regions.BR'>),
#      ('usa', <class 'mkt.constants.regions.US'>)]
#

DEFINED = sorted(inspect.getmembers(sys.modules[__name__], inspect.isclass),
                 key=lambda x: getattr(x, 'slug', None))
REGIONS_CHOICES = (
    [('restofworld', RESTOFWORLD)] +
    sorted([(v.slug, v) for k, v in DEFINED if v.id and v.weight > -1],
           key=lambda x: x[1].weight, reverse=True)
)

BY_SLUG = sorted([v for k, v in DEFINED if v.id and v.weight > -1],
                 key=lambda v: v.slug)

REGIONS_CHOICES_SLUG = ([('restofworld', RESTOFWORLD)] +
                        [(v.slug, v) for v in BY_SLUG])
REGIONS_CHOICES_ID = ([(RESTOFWORLD.id, RESTOFWORLD)] +
                      [(v.id, v) for v in BY_SLUG])
# Rest of World last here so we can display it after all the other regions.
REGIONS_CHOICES_NAME = ([(v.id, v.name) for v in BY_SLUG] +
                        [(RESTOFWORLD.id, RESTOFWORLD.name)])

REGIONS_DICT = dict(REGIONS_CHOICES)
REGIONS_CHOICES_ID_DICT = dict(REGIONS_CHOICES_ID)
# Provide a dict for looking up the region by slug that includes aliases:
# - "worldwide" is an alias for RESTOFWORLD (bug 940561).
# - "gb" is an alias for UK (bug 973883).
REGION_LOOKUP = dict(REGIONS_DICT.items() +
                     [('worldwide', RESTOFWORLD), ('gb', UK)])
ALL_REGIONS = frozenset(REGIONS_DICT.values())
ALL_REGION_IDS = sorted(REGIONS_CHOICES_ID_DICT.keys())

SPECIAL_REGIONS = [x for x in BY_SLUG if x.special]
SPECIAL_REGION_IDS = sorted(x.id for x in SPECIAL_REGIONS)

# Regions not including restofworld.
REGION_IDS = sorted(REGIONS_CHOICES_ID_DICT.keys())[1:]

GENERIC_RATING_REGION_SLUG = 'generic'

def ALL_REGIONS_WITH_CONTENT_RATINGS():
    """Regions that have ratings bodies."""
    return [x for x in ALL_REGIONS if x.ratingsbody]

def ALL_REGIONS_WITHOUT_CONTENT_RATINGS():
    """
    Regions without ratings bodies and fallback to the GENERIC rating body.
    """
    return set(ALL_REGIONS) - set(ALL_REGIONS_WITH_CONTENT_RATINGS())

def REGION_TO_RATINGS_BODY():
    """
    Return a map of region slugs to ratings body labels for use in
    serializers and to send to Fireplace.

    e.g. {'us': 'esrb', 'mx': 'esrb', 'es': 'pegi', 'br': 'classind'}.
    """
    # Create the mapping.
    region_to_bodies = {}
    for region in ALL_REGIONS_WITH_CONTENT_RATINGS():
        ratings_body_label = GENERIC_RATING_REGION_SLUG
        if region.ratingsbody:
            ratings_body_label = slugify_iarc_name(region.ratingsbody)
        region_to_bodies[region.slug] = ratings_body_label

    return region_to_bodies

def REGIONS_CHOICES_SORTED_BY_NAME():
    """Get the region choices and sort by name.

    Requires a function due to localisation.

    """

    # Avoid circular import.
    from mkt.regions.utils import remove_accents

    by_name = sorted([v for k, v in DEFINED if v.id and v.weight > -1],
                     key=lambda v: remove_accents(unicode(v.name)))
    return ([(v.id, v.name) for v in by_name] +
            [(RESTOFWORLD.id, RESTOFWORLD.name)])


text:
package org.apache.hadoop.hdfs.server.namenode.metrics;

import javax.management.ObjectName;

import org.apache.hadoop.metrics.util.MBeanUtil;
import org.apache.hadoop.metrics.util.MetricsDynamicMBeanBase;
import org.apache.hadoop.metrics.util.MetricsRegistry;

/**
 *
 * This is the JMX MBean for reporting the NameNode Activity.
 * The MBean is register using the name
 *        "hadoop:service=NameNode,name=NameNodeActivity"
 *
 * Many of the activity metrics are sampled and averaged on an interval
 * which can be specified in the metrics config file.
 *

 * For the metrics that are sampled and averaged, one must specify
 * a metrics context that does periodic update calls. Most metrics contexts do.
 * The default Null metrics context however does NOT. So if you aren't
 * using any other metrics context then you can turn on the viewing and averaging
 * of sampled metrics by  specifying the following two lines
 *  in the hadoop-meterics.properties file:
*

 *        dfs.class=org.apache.hadoop.metrics.spi.NullContextWithUpdateThread
 *        dfs.period=10
 *

 *

 * Note that the metrics are collected regardless of the context used.
 * The context with the update thread is used to average the data periodically
 *
 *
 *
 * Impl details: We use a dynamic mbean that gets the list of the metrics
 * from the metrics registry passed as an argument to the constructor
 */

public class NameNodeActivtyMBean extends MetricsDynamicMBeanBase {
  final private ObjectName mbeanName;

  protected NameNodeActivtyMBean(final MetricsRegistry mr) {
    super(mr, "Activity statistics at the NameNode");
    mbeanName = MBeanUtil.registerMBean("NameNode", "NameNodeActivity", this);
  }

  public void shutdown() {
    if (mbeanName != null)
      MBeanUtil.unregisterMBean(mbeanName);
  }
}


text:
package common

import "flag"

const (
	// Port is the predefined fix port on which our servers will listen.
	// Since we run each service in its own container they have their own IP
	// address and a hostname that is the same as the service name.
	Port = 8000
)

var alreadyInitialised = false

// Init contains initialisation code that is shared by client and server config.
func Init() {
	if alreadyInitialised {
		return
	}
	alreadyInitialised = true

	flag.Parse()
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="shortcut icon" type="image/x-icon" href="ico/favicon.ico" />

    <title>About - PuzzleScript Documentation</title>

    <link href="css/bootstrap.css" rel="stylesheet">

    <link href="css/bootstrap-theme.css" rel="stylesheet">

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

          </button>
           PuzzleScript

Make A Game

Documentation

Donate

About

About

PuzzleScript was developed by me (with the assistance/feedback of many other people + tools), Stephen Lavelle (@increpare). Programming puzzle games isn't all that hard in the grand scheme of things, but the barrier to entry is way higher than it needs to be.

It's not a general purpose game making tool, it's not even a general purpose puzzle game making tool.  Or even a avatar-based turn-based puzzle game making tool - games like DROD don't work, or games with very nuanced behaviours, like Puzzles proved impossible.  But it is a tool, and I think it might prove handy/enabling for a number of people, if one is accepting of its limitations.

I've worked on a lot of puzzle games, and decided on a particular group of those that could be handily modelled with a scripting language.  I've seen someone do a similar pattern-matching system before (I can't remember who, though), but it was a lot less flexible - the movement system in this engine is what gives it its real power.

Getting the engine out the door, so to speek, took several weeks of full-time, unreumerated work, and no doubt there's plenty more to come. I am not a wealthy man, I'm an impoverished, self-employed independent game developer whose involvement with such projects amounts to happy indiscretions.  If you appreciate this piece of software, please consider chipping some money my way, okay? :)

I've you've made something cool with the engine, please let me know ( analytic@gmail.com or @increpare ) - I'd love to highlight (and maybe even host as examples) wonderful things that people've made with this.

Credits


text:
package legends;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.nio.file.Files;
import java.nio.file.Path;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import legends.model.LegendsXml;
import legends.xml.handlers.AnnotationContentHandler;

public class LegendsReader {
	private static final Log LOG = LogFactory.getLog(LegendsReader.class);

	public static void read(Path path, Charset cs) throws SAXException, IOException, InstantiationException,
			IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		LOG.info("load legends: " + path);
		XMLReader xmlReader = XMLReaderFactory.createXMLReader();
		AnnotationContentHandler contentHandler = new AnnotationContentHandler(LegendsXml.class);
		contentHandler.setXmlReader(xmlReader);
		xmlReader.setContentHandler(contentHandler);

		CharsetDecoder decoder = cs.newDecoder();
		decoder.onMalformedInput(CodingErrorAction.IGNORE);

		BufferedReader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(path), decoder));
		//		PipedWriter writer = new PipedWriter();
		//		PipedReader fixedReader = new PipedReader(writer);
		//
		//		new Thread() {
		//			public void run() {
		//				try {
		//					String line = null;
		//					LinkedList<String> buffer = new LinkedList<>();
		//					while ((line = reader.readLine()) != null) {
		//						buffer.add(line);
		//						if(buffer.size() < 4)
		//							continue;
		//
		//						line = buffer.pop();
		//							if (line.contains("conspirator_hfid")) {
		//							line = line.replaceAll("<conspirator_hfid>(\\d+)<\\/conspirator>",
		//									"<conspirator_hfid>$1</conspirator_hfid>");
		//						}
		//						if (line.contains("interrogator_hfid")) {
		//							line = line.replaceAll("<interrogator_hfid>(\\d+)<\\/convicted_hfid>",
		//									"<interrogator_hfid>$1</interrogator_hfid>");
		//						}
		//						if(buffer.get(2).contains("acquirer_hfid")) {
		//							line = line+"\r\n<type>hf acquired building</type>";
		//						} else if(buffer.get(2).contains("modifier_hfid")) {
		//							line = line+"\r\n<type>hf modified structure</type>";
		//						} else if(buffer.get(0).contains("speaker_hfid")) {
		//							line = line+"\r\n<type>hf preached</type>";
		//						} else if(buffer.get(1).contains("seller_hfid")) {
		//							line = line+"\r\n<type>hf sold slave</type>";
		//						} else if(buffer.get(0).contains("ransomed_hfid")) {
		//							line = line+"\r\n<type>hf ransomed</type>";
		//						}
		//						writer.write(line);
		//						writer.write("\r\n");
		//					}
		//					for(String l : buffer) {
		//						writer.write(l);
		//						writer.write("\r\n");
		//					}
		//					writer.close();
		//					reader.close();
		//				} catch (IOException e) {
		//					e.printStackTrace();
		//				}
		//			};
		//		}.start();

		InputSource inputSource = new InputSource(reader);
		xmlReader.parse(inputSource);

		contentHandler.printMappedValues();
	}
}


text:
layout: post.jade
title: Streamline your build system with vagrant + sbuild
date: 2013-07-18T21:21Z
tags:
- ubuntu
- linux
- sbuild
- vagrant
---
Remembering what to do in order to get your sbuild environment setup
with deb caching and configuring Barry Warsaws repotools for those
packages not in the archive can be a little tedious at times.

For me I hated upgrading my systems knowing I had to re-setup my
sbuild environments.

In order to streamline this I created a project to help package
builders take some of these boilerplate stuff out of the way and just
create the schroot and start your build.

This vagrant project was modeled after
[SbuildSimple](https://wiki.ubuntu.com/SimpleSbuild). Please check
there for additional information on local packages.

You can find the project at
[github](https://github.com/battlemidget/vagrant-sbuild)

## Features

*   supports lxc and virtualbox
*   apt package caching for quicker builds
*   automatically set maxcpus available to sbuild
*   supports building packages against newer/custom local packages

Using it is fairly simple:

## Setup

Install virtualbox

`$ sudo apt-get install virtualbox`

Install [vagrant](http://downloads.vagrantup.com/)

Install vagrant-sbuild

```bash
$ git clone git://github.com:battlemidget/vagrant-sbuild.git
$ cd vagrant-sbuild
$ git submodule init
$ git submodule update
```

Install [vagrant-lxc](https://github.com/fgrehm/vagrant-lxc)

`$ vagrant plugin install vagrant-lxc`

Set some environment variables

`export DEBEMAIL=Your Name < hi2u@mail.com > export DEBSIGN_KEY=123134`

### Optional

Install [vagrant-cachier](https://github.com/fgrehm/vagrant-cachier) for improved performance

`$ vagrant plugin install vagrant-cachier`

**Note**: I havent personally tested this as apt-cacher-ng is running
  for builds, however, for the provisioning itself it may be
  beneficial if you are doing a lot of provisioning. Make sure you
  read the **Vagrantfile** and uncomment the section that enables the
  auto caching feature.

## Vagrant boxes

A list of lxc supported vagrant boxes can be found at the
[Vagrant LXC wiki](https://github.com/fgrehm/vagrant-lxc/wiki/Base-boxes)
page.

## Usage

`$ vagrant up`

## Create sbuild environments

`$ vagrant mk-sbuild --series saucy`

## Perform builds

`$ vagrant sbuild --project saucy-amd64 --dsc scratch/PACKAGE\*.dsc`

If packages are required that are not in the archive you may place
them in the **repo/** directory and they will be included in any
future builds.

Once complete the build packages should be in your **scratch/**
directory and not once did you have to ssh into your vagrant box :D

## Todo's

*   setup vagrant multi-machine for each series
*   include a config.yaml file for setting your debian maintainer info and other necessities.