text:
<?php

/*
 * %LICENSE% - see LICENSE
 *
 * $Id: class.codeinterpreter.php,v 1.3 2013-01-14 21:04:52 dkolev Exp $
 */

/**
 * @package VESHTER
 *
 */

/**
 * Programming language interpreter that runs different scripts and returns their result
 *
 * @version $Revision: 1.3 $
 * @package VESHTER
 *
 */
class CCodeInterpreter extends CGadget
{

    /**
     * @param string Original code wrapper for the interpreter
     */
    function __construct()
    {
        parent::__construct();
        $this->SetVersion('$Revision: 1.3 $');
    }

    function __destruct()
    {
        parent::__destruct();
    }

    /**
     * Executes a script in the current wrapper
     */
    public function EvalScript($snippet, &$context)
    {
        //don't waste any time trying to run an empty script
        if (CString::IsNullOrEmpty($snippet))
        {
            throw new CExceptionInvalidData('No script to interpret');
        }

        try
        {
            $snippet = preg_replace('/<\?(php)?/i', '######### PHP begin token removed', $snippet);
            $snippet = preg_replace('/\?>/i', '######### PHP end token removed', $snippet);
            $snippet = trim($snippet);

            $wrapper = <<<PHP

######### Wrapper begin
%s
######### Wrapper end

//return false is nothing happened
return null;

PHP;

            //print ($script);
            //exit;

            $script = CString::Format($wrapper, $snippet);

            $result = eval($script);
        }
        catch (CExceptionEx $ex)
        {
            $result = false;
            throw $ex;
            //CEnvironment::Dump($ex);
        }

        return $result;
    }

}

/*
 *
 * Changelog:
 * $Log: class.codeinterpreter.php,v $
 * Revision 1.3  2013-01-14 21:04:52  dkolev
 * Merge to prototype
 *
 * Revision 1.2.4.1  2011-11-25 22:17:14  dkolev
 * Cleaned up constructors. Imported new captcha functionality
 *
 * Revision 1.2  2010-07-04 18:32:39  dkolev
 * Sniff improvements
 *
 * Revision 1.1  2009-12-27 19:57:19  dkolev
 * Refactoring and moving to proper folders
 *
 * Revision 1.6  2009-11-15 00:52:08  dkolev
 * Added <?/<?php filter
 *
 * Revision 1.5  2009-03-30 05:11:36  dkolev
 * Improved encapsulated code execution and better bubbling of exceptions
 *
 * Revision 1.4  2009-03-30 01:05:44  dkolev
 * Added context to the EvalScript function
 *
 * Revision 1.3  2008-12-15 03:41:56  dkolev
 * Minor changes
 *
 * Revision 1.2  2008/08/18 08:27:22  dkolev
 * Changed some double quotes to singles
 *
 * Revision 1.1  2008/05/31 04:28:25  dkolev
 * Initial import
 *
 *
 */

?>


text:
import CoolProp
CP = CoolProp.CoolProp
import os
import codecs

web_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
root_dir = os.path.abspath(os.path.join(web_dir, '..'))

fluid_template = u""".. _fluid_{fluid:s}:

{fluid_stars:s}
{fluid:s}
{fluid_stars:s}

{references:s}
{aliases:s}

Fluid Information
=================

.. csv-table::
   :header-rows: 1
   :widths: 40, 60
   :delim: ;
   :file: {fluid:s}-info.csv

REFPROP Validation Data
=======================

.. note::

    This figure compares the results generated from CoolProp and those generated from REFPROP.  They are all results obtained in the form :math:`Y(T,\\rho)`, where :math:`Y` is the parameter of interest and which for all EOS is a direct evaluation of the EOS

    You can download the script that generated the following figure here: :download:`(link to script)<REFPROPplots/{fluid:s}.py>`, right-click the link and then save as... or the equivalent in your browser.  You can also download this figure :download:`as a PDF<REFPROPplots/{fluid:s}.pdf>`.

.. image:: REFPROPplots/{fluid:s}.png

Consistency Plots
=================

The following figure shows all the flash routines that are available for this fluid.  A red + is a failure of the flash routine, a black dot is a success.  Hopefully you will only see black dots.  The red curve is the maximum temperature curve, and the blue curve is the melting line if one is available for the fluid.

In this figure, we start off with a state point given by T,P and then we calculate each of the other possible output pairs in turn, and then try to re-calculate T,P from the new input pair.  If we don't arrive back at the original T,P values, there is a problem in the flash routine in CoolProp.  For more information on how these figures were generated, see :py:mod:`CoolProp.Plots.ConsistencyPlots`

.. note::

    You can download the script that generated the following figure here: :download:`(link to script)<Consistencyplots/{fluid:s}.py>`, right-click the link and then save as... or the equivalent in your browser.  You can also download this figure :download:`as a PDF<Consistencyplots/{fluid:s}.pdf>`.

.. image:: Consistencyplots/{fluid:s}.png

"""

table_template = """ Parameter, Value
**General**;
Molar mass [kg/mol];{mm:s}
CAS number; {CAS:s}
ASHRAE class; {ASHRAE:s}
Formula; {formula:s}
Acentric factor; {acentric:s}
InChI; {inchi:s}
InChIKey; {inchikey:s}
SMILES; {smiles:s}
ChemSpider ID; {ChemSpider_id:s}
2D image; .. image:: {twoDurl:s}
**Limits**;
Maximum temperature [K];{Tmax:s}
Maximum pressure [Pa];{pmax:s}
**Triple point**;
Triple point temperature [K];{Tt:s}
Triple point pressure [Pa]; {pt:s}
**Critical point**;
Critical point temperature [K]; {Tc:s}
Critical point density [kg/m3]; {rhoc_mass:s}
Critical point density [mol/m3]; {rhoc_molar:s}
Critical point pressure [Pa]; {pc:s}
{reducing_string:s}
"""

reducing_template = """**Reducing point**;
Reducing point temperature [K]; {Tr:s}
Reducing point density [mol/m3]; {rhor_molar:s}
"""

bibtex_keys = ['EOS', 'CP0', 'CONDUCTIVITY', 'VISCOSITY', 'MELTING_LINE', 'SURFACE_TENSION']
bibtex_map = {'EOS': 'Equation of State',
              'CP0': 'Ideal gas specific heat',
              'CONDUCTIVITY': 'Thermal Conductivity',
              'VISCOSITY': 'Viscosity',
              'MELTING_LINE': 'Melting Line',
              'SURFACE_TENSION': 'Surface Tension'}

from pybtex.database.input import bibtex
parser = bibtex.Parser()
bibdata = parser.parse_file(os.path.join(root_dir, "CoolPropBibTeXLibrary.bib"))

from CoolProp.BibtexParser import BibTeXerClass
BTC = BibTeXerClass(os.path.join(root_dir, "CoolPropBibTeXLibrary.bib"))

# See http://stackoverflow.com/questions/19751402/does-pybtex-support-accent-special-characters-in-bib-file/19754245#19754245
import pybtex
style = pybtex.plugin.find_plugin('pybtex.style.formatting', 'plain')()
backend = pybtex.plugin.find_plugin('pybtex.backends', 'html')()
parser = pybtex.database.input.bibtex.Parser()

def entry2html(entry):
    for e in entry:
        return e.text.render(backend).replace('{', '').replace('}', '').replace('\n', ' ')

def generate_bibtex_string(fluid):
    string = ''
    for key in bibtex_keys:
        header_string = ''
        sect_strings = []
        try:
            # get the item
            bibtex_key = CoolProp.CoolProp.get_BibTeXKey(fluid, key).strip()
            for thekey in bibtex_key.split(','):
                if thekey.strip() in bibdata.entries.keys():
                    html = BTC.getEntry(key=thekey.strip(), fmt='html')
                    if len(sect_strings) == 0:
                        sect = bibtex_map[key]
                        header_string = sect + '\n' + '-' * len(sect) + '\n\n'
                    sect_strings.append('.. raw:: html\n\n   ' + html + '\n\n')
        except ValueError as E:
            print("error: %s" % E)
        string += header_string + '\n\n.. raw:: html\n\n

 \n\n'.join(sect_strings)
    return string

class FluidInfoTableGenerator(object):

    def __init__(self, name):

        self.name = name

    def write(self, path):
        def tos(n):
            ''' convert number to nicely formatted string '''
            n = str(n)
            if 'e' in n:
                n = n.replace('e', ':math:`\times 10^{')
                n += '}`'
            else:
                return n
            return n
        molar_mass = CoolProp.CoolProp.PropsSI(self.name, 'molemass')
        Tt = CoolProp.CoolProp.PropsSI(self.name, 'Ttriple')
        Tc = CoolProp.CoolProp.PropsSI(self.name, 'Tcrit')
        Tr = CoolProp.CoolProp.PropsSI(self.name, 'T_reducing')
        pc = CoolProp.CoolProp.PropsSI(self.name, 'pcrit')
        pt = CoolProp.CoolProp.PropsSI(self.name, 'ptriple')
        if pt is None:
            pt = "Unknown"
        Tmax = CoolProp.CoolProp.PropsSI(self.name, 'Tmax')
        pmax = CoolProp.CoolProp.PropsSI(self.name, 'pmax')
        acentric = CoolProp.CoolProp.PropsSI(self.name, 'acentric')
        rhoc_mass = CoolProp.CoolProp.PropsSI(self.name, 'rhomass_critical')
        rhoc_molar = CoolProp.CoolProp.PropsSI(self.name, 'rhomolar_critical')
        rhor_molar = CoolProp.CoolProp.PropsSI(self.name, 'rhomolar_reducing')

        CAS = CoolProp.CoolProp.get_fluid_param_string(self.name, "CAS")
        ASHRAE = CoolProp.CoolProp.get_fluid_param_string(self.name, "ASHRAE34")
        formula = CoolProp.CoolProp.get_fluid_param_string(self.name, "formula")
        if formula:
            formula = ':math:`' + formula + '`'
        else:
            formula = 'Not applicable'
        formula = formula.replace('_{1}', '')
        InChI = CoolProp.CoolProp.get_fluid_param_string(self.name, "INCHI")
        InChiKey = CoolProp.CoolProp.get_fluid_param_string(self.name, "INCHIKEY")
        smiles = CoolProp.CoolProp.get_fluid_param_string(self.name, "SMILES")
        ChemSpider_id = CoolProp.CoolProp.get_fluid_param_string(self.name, "CHEMSPIDER_ID")
        twoDurl = CoolProp.CoolProp.get_fluid_param_string(self.name, "2DPNG_URL")

        # Generate (or not) the reducing data
        reducing_data = ''
        if abs(Tr - Tc) > 1e-3:
            reducing_data = reducing_template.format(Tr=tos(Tr),
                                                     rhor_molar=tos(rhor_molar))

        args = dict(mm=tos(molar_mass),
                    Tt=tos(Tt),
                    pt=tos(pt),
                    Tc=tos(Tc),
                    rhoc_mass=tos(rhoc_mass),
                    rhoc_molar=tos(rhoc_molar),
                    pc=tos(pc),
                    acentric=tos(acentric),
                    CAS=tos(CAS),
                    ASHRAE=tos(ASHRAE),
                    Tmax=tos(Tmax),
                    pmax=tos(pmax),
                    reducing_string=reducing_data,
                    formula=formula,
                    inchi=InChI,
                    inchikey=InChiKey,
                    smiles=smiles,
                    ChemSpider_id=ChemSpider_id,
                    twoDurl=twoDurl
                    )
        out = table_template.format(**args)

        with open(os.path.join(path, self.name + '-info.csv'), 'w') as fp:
            print("writing %s" % os.path.join(path, self.name + '-info.csv'))
            fp.write(out)

class FluidGenerator(object):
    def __init__(self, fluid):
        self.fluid = fluid

    def write(self, path):

        # Write CSV table data for fluid information
        ITG = FluidInfoTableGenerator(self.fluid)
        ITG.write(path)

        del_old = CP.get_config_string(CP.LIST_STRING_DELIMITER)

        CP.set_config_string(CP.LIST_STRING_DELIMITER, '|')
        try:
            aliases = ', '.join(['``' + a.strip() + '``' for a in CoolProp.CoolProp.get_fluid_param_string(self.fluid, 'aliases').strip().split('|') if a])
        finally:
            CP.set_config_string(CP.LIST_STRING_DELIMITER, del_old)

        if aliases:
            aliases = 'Aliases\n=======\n\n' + aliases + '\n'

        references = generate_bibtex_string(self.fluid)
        if references:
            references = 'References\n==========\n' + references + '\n'

        # Write RST file for fluid
        out = fluid_template.format(aliases=aliases,
                                    fluid=self.fluid,
                                    fluid_stars='*' * len(self.fluid),
                                    references=references
                                    )

        with codecs.open(os.path.join(path, self.fluid + '.rst'), 'w', encoding='utf-8') as fp:
            print("writing %s" % os.path.join(path, self.fluid + '.rst'))
            fp.write(out)

redpajama_set_name: RedPajamaGithub


text:
package com.company;

        import java.math.BigDecimal;
        import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = Integer.parseInt(scanner.nextLine());

        List<BigDecimal> numbers = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            numbers.add(new BigDecimal(scanner.nextLine()));
        }

        Collections.sort(numbers);
        for (int i = numbers.size() - 1; i >= Math.max(0, numbers.size() - 3) ; i--) {
            System.out.printf("%s%n", numbers.get(i).toPlainString());
        }
    }
}


text:
<!DOCTYPE html>

<title><#:C('sitename')#>--会员中心</title>
<meta name="keywords" content="<#:C('keyword')#>"/>
<meta name="description" content="<#:C('content')#>"/>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<include file="Pub:Css"/>

   <include file="Pub:top"/>
   <include file="Pub:nav"/>

 <a href="<#:U('user/index')#>" title="返回首页" class="tip-bottom">首页

   <include file="Pub:foot"/>


text:
"""Utilities for using Sonnet with TensorFlow Distribution Strategy."""

from sonnet.src.distribute.distributed_batch_norm import CrossReplicaBatchNorm
from sonnet.src.distribute.replicator import create_variables_eagerly
from sonnet.src.distribute.replicator import Replicator
from sonnet.src.distribute.replicator import TpuReplicator

__all__ = (
    "create_variables_eagerly",
    "Replicator",
    "TpuReplicator",
    "CrossReplicaBatchNorm",
)


text:
class Change < ActiveRecord::Base
  def name
    "#{record_type} #{event}"
  end

  def description
    "#{User.find(user_id).login} #{event} #{record_type.constantize.find(record_id).name} on #{created_at}"
  end
end


text:
#ifndef _COMEDIDEV_H
#define _COMEDIDEV_H

#include <linux/dma-mapping.h>
#include <linux/mutex.h>
#include <linux/spinlock_types.h>
#include <linux/rwsem.h>
#include <linux/kref.h>

#include "comedi.h"

#define COMEDI_VERSION(a, b, c) (((a) << 16) + ((b) << 8) + (c))
#define COMEDI_VERSION_CODE COMEDI_VERSION(COMEDI_MAJORVERSION, \
	COMEDI_MINORVERSION, COMEDI_MICROVERSION)
#define COMEDI_RELEASE VERSION

#define COMEDI_NUM_BOARD_MINORS 0x30

struct comedi_subdevice {
	struct comedi_device *device;
	int index;
	int type;
	int n_chan;
	int subdev_flags;
	int len_chanlist;	/* maximum length of channel/gain list */

	void *private;

	struct comedi_async *async;

	void *lock;
	void *busy;
	unsigned runflags;
	spinlock_t spin_lock;

	unsigned int io_bits;

	unsigned int maxdata;	/* if maxdata==0, use list */
	const unsigned int *maxdata_list;	/* list is channel specific */

	const struct comedi_lrange *range_table;
	const struct comedi_lrange *const *range_table_list;

	unsigned int *chanlist;	/* driver-owned chanlist (not used) */

	int (*insn_read)(struct comedi_device *, struct comedi_subdevice *,
			 struct comedi_insn *, unsigned int *);
	int (*insn_write)(struct comedi_device *, struct comedi_subdevice *,
			  struct comedi_insn *, unsigned int *);
	int (*insn_bits)(struct comedi_device *, struct comedi_subdevice *,
			 struct comedi_insn *, unsigned int *);
	int (*insn_config)(struct comedi_device *, struct comedi_subdevice *,
			   struct comedi_insn *, unsigned int *);

	int (*do_cmd)(struct comedi_device *, struct comedi_subdevice *);
	int (*do_cmdtest)(struct comedi_device *, struct comedi_subdevice *,
			  struct comedi_cmd *);
	int (*poll)(struct comedi_device *, struct comedi_subdevice *);
	int (*cancel)(struct comedi_device *, struct comedi_subdevice *);

	/* called when the buffer changes */
	int (*buf_change)(struct comedi_device *, struct comedi_subdevice *);

	void (*munge)(struct comedi_device *dev, struct comedi_subdevice *s,
		      void *data, unsigned int num_bytes,
		      unsigned int start_chan_index);
	enum dma_data_direction async_dma_dir;

	unsigned int state;

	struct device *class_dev;
	int minor;

	unsigned int *readback;
};

struct comedi_buf_page {
	void *virt_addr;
	dma_addr_t dma_addr;
};

struct comedi_buf_map {
	struct device *dma_hw_dev;
	struct comedi_buf_page *page_list;
	unsigned int n_pages;
	enum dma_data_direction dma_dir;
	struct kref refcount;
};

/**
 * struct comedi_async - control data for asynchronous comedi commands
 * @prealloc_buf:	preallocated buffer
 * @prealloc_bufsz:	buffer size (in bytes)
 * @buf_map:		map of buffer pages
 * @max_bufsize:	maximum buffer size (in bytes)
 * @buf_write_count:	"write completed" count (in bytes, modulo 2**32)
 * @buf_write_alloc_count: "allocated for writing" count (in bytes,
 *			modulo 2**32)
 * @buf_read_count:	"read completed" count (in bytes, modulo 2**32)
 * @buf_read_alloc_count: "allocated for reading" count (in bytes,
 *			modulo 2**32)
 * @buf_write_ptr:	buffer position for writer
 * @buf_read_ptr:	buffer position for reader
 * @cur_chan:		current position in chanlist for scan (for those
 *			drivers that use it)
 * @scans_done:		the number of scans completed (COMEDI_CB_EOS)
 * @scan_progress:	amount received or sent for current scan (in bytes)
 * @munge_chan:		current position in chanlist for "munging"
 * @munge_count:	"munge" count (in bytes, modulo 2**32)
 * @munge_ptr:		buffer position for "munging"
 * @events:		bit-vector of events that have occurred
 * @cmd:		details of comedi command in progress
 * @wait_head:		task wait queue for file reader or writer
 * @cb_mask:		bit-vector of events that should wake waiting tasks
 * @inttrig:		software trigger function for command, or NULL
 *
 * Note about the ..._count and ..._ptr members:
 *
 * Think of the _Count values being integers of unlimited size, indexing
 * into a buffer of infinite length (though only an advancing portion
 * of the buffer of fixed length prealloc_bufsz is accessible at any time).
 * Then:
 *
 *   Buf_Read_Count <= Buf_Read_Alloc_Count <= Munge_Count <=
 *   Buf_Write_Count <= Buf_Write_Alloc_Count <=
 *   (Buf_Read_Count + prealloc_bufsz)
 *
 * (Those aren't the actual members, apart from prealloc_bufsz.) When
 * the buffer is reset, those _Count values start at 0 and only increase
 * in value, maintaining the above inequalities until the next time the
 * buffer is reset.  The buffer is divided into the following regions by
 * the inequalities:
 *
 *   [0, Buf_Read_Count):
 *     old region no longer accessible
 *   [Buf_Read_Count, Buf_Read_Alloc_Count):
 *     filled and munged region allocated for reading but not yet read
 *   [Buf_Read_Alloc_Count, Munge_Count):
 *     filled and munged region not yet allocated for reading
 *   [Munge_Count, Buf_Write_Count):
 *     filled region not yet munged
 *   [Buf_Write_Count, Buf_Write_Alloc_Count):
 *     unfilled region allocated for writing but not yet written
 *   [Buf_Write_Alloc_Count, Buf_Read_Count + prealloc_bufsz):
 *     unfilled region not yet allocated for writing
 *   [Buf_Read_Count + prealloc_bufsz, infinity):
 *     unfilled region not yet accessible
 *
 * Data needs to be written into the buffer before it can be read out,
 * and may need to be converted (or "munged") between the two
 * operations.  Extra unfilled buffer space may need to allocated for
 * writing (advancing Buf_Write_Alloc_Count) before new data is written.
 * After writing new data, the newly filled space needs to be released
 * (advancing Buf_Write_Count).  This also results in the new data being
 * "munged" (advancing Munge_Count).  Before data is read out of the
 * buffer, extra space may need to be allocated for reading (advancing
 * Buf_Read_Alloc_Count).  After the data has been read out, the space
 * needs to be released (advancing Buf_Read_Count).
 *
 * The actual members, buf_read_count, buf_read_alloc_count,
 * munge_count, buf_write_count, and buf_write_alloc_count take the
 * value of the corresponding capitalized _Count values modulo 2^32
 * (UINT_MAX+1).  Subtracting a "higher" _count value from a "lower"
 * _count value gives the same answer as subtracting a "higher" _Count
 * value from a lower _Count value because prealloc_bufsz < UINT_MAX+1.
 * The modulo operation is done implicitly.
 *
 * The buf_read_ptr, munge_ptr, and buf_write_ptr members take the value
 * of the corresponding capitalized _Count values modulo prealloc_bufsz.
 * These correspond to byte indices in the physical buffer.  The modulo
 * operation is done by subtracting prealloc_bufsz when the value
 * exceeds prealloc_bufsz (assuming prealloc_bufsz plus the increment is
 * less than or equal to UINT_MAX).
 */
struct comedi_async {
	void *prealloc_buf;
	unsigned int prealloc_bufsz;
	struct comedi_buf_map *buf_map;
	unsigned int max_bufsize;
	unsigned int buf_write_count;
	unsigned int buf_write_alloc_count;
	unsigned int buf_read_count;
	unsigned int buf_read_alloc_count;
	unsigned int buf_write_ptr;
	unsigned int buf_read_ptr;
	unsigned int cur_chan;
	unsigned int scans_done;
	unsigned int scan_progress;
	unsigned int munge_chan;
	unsigned int munge_count;
	unsigned int munge_ptr;
	unsigned int events;
	struct comedi_cmd cmd;
	wait_queue_head_t wait_head;
	unsigned int cb_mask;
	int (*inttrig)(struct comedi_device *dev, struct comedi_subdevice *s,
		       unsigned int x);
};

/**
 * comedi_async callback "events"
 * @COMEDI_CB_EOS:		end-of-scan
 * @COMEDI_CB_EOA:		end-of-acquisition/output
 * @COMEDI_CB_BLOCK:		data has arrived, wakes up read() / write()
 * @COMEDI_CB_EOBUF:		DEPRECATED: end of buffer
 * @COMEDI_CB_ERROR:		card error during acquisition
 * @COMEDI_CB_OVERFLOW:		buffer overflow/underflow
 *
 * @COMEDI_CB_ERROR_MASK:	events that indicate an error has occurred
 * @COMEDI_CB_CANCEL_MASK:	events that will cancel an async command
 */
#define COMEDI_CB_EOS		BIT(0)
#define COMEDI_CB_EOA		BIT(1)
#define COMEDI_CB_BLOCK		BIT(2)
#define COMEDI_CB_EOBUF		BIT(3)
#define COMEDI_CB_ERROR		BIT(4)
#define COMEDI_CB_OVERFLOW	BIT(5)

#define COMEDI_CB_ERROR_MASK	(COMEDI_CB_ERROR | COMEDI_CB_OVERFLOW)
#define COMEDI_CB_CANCEL_MASK	(COMEDI_CB_EOA | COMEDI_CB_ERROR_MASK)

struct comedi_driver {
	struct comedi_driver *next;

	const char *driver_name;
	struct module *module;
	int (*attach)(struct comedi_device *, struct comedi_devconfig *);
	void (*detach)(struct comedi_device *);
	int (*auto_attach)(struct comedi_device *, unsigned long);

	/* number of elements in board_name and board_id arrays */
	unsigned int num_names;
	const char *const *board_name;
	/* offset in bytes from one board name pointer to the next */
	int offset;
};

struct comedi_device {
	int use_count;
	struct comedi_driver *driver;
	struct comedi_8254 *pacer;
	void *private;

	struct device *class_dev;
	int minor;
	unsigned int detach_count;
	/* hw_dev is passed to dma_alloc_coherent when allocating async buffers
	 * for subdevices that have async_dma_dir set to something other than
	 * DMA_NONE */
	struct device *hw_dev;

	const char *board_name;
	const void *board_ptr;
	bool attached:1;
	bool ioenabled:1;
	spinlock_t spinlock;
	struct mutex mutex;
	struct rw_semaphore attach_lock;
	struct kref refcount;

	int n_subdevices;
	struct comedi_subdevice *subdevices;

	/* dumb */
	void __iomem *mmio;
	unsigned long iobase;
	unsigned long iolen;
	unsigned int irq;

	struct comedi_subdevice *read_subdev;
	struct comedi_subdevice *write_subdev;

	struct fasync_struct *async_queue;

	int (*open)(struct comedi_device *dev);
	void (*close)(struct comedi_device *dev);
};

/*
 * function prototypes
 */

void comedi_event(struct comedi_device *dev, struct comedi_subdevice *s);

struct comedi_device *comedi_dev_get_from_minor(unsigned minor);
int comedi_dev_put(struct comedi_device *dev);

bool comedi_is_subdevice_running(struct comedi_subdevice *s);

void *comedi_alloc_spriv(struct comedi_subdevice *s, size_t size);
void comedi_set_spriv_auto_free(struct comedi_subdevice *s);

int comedi_check_chanlist(struct comedi_subdevice *s,
			  int n,
			  unsigned int *chanlist);

/* range stuff */

#define RANGE(a, b)		{(a)*1e6, (b)*1e6, 0}
#define RANGE_ext(a, b)		{(a)*1e6, (b)*1e6, RF_EXTERNAL}
#define RANGE_mA(a, b)		{(a)*1e6, (b)*1e6, UNIT_mA}
#define RANGE_unitless(a, b)	{(a)*1e6, (b)*1e6, 0}
#define BIP_RANGE(a)		{-(a)*1e6, (a)*1e6, 0}
#define UNI_RANGE(a)		{0, (a)*1e6, 0}

extern const struct comedi_lrange range_bipolar10;
extern const struct comedi_lrange range_bipolar5;
extern const struct comedi_lrange range_bipolar2_5;
extern const struct comedi_lrange range_unipolar10;
extern const struct comedi_lrange range_unipolar5;
extern const struct comedi_lrange range_unipolar2_5;
extern const struct comedi_lrange range_0_20mA;
extern const struct comedi_lrange range_4_20mA;
extern const struct comedi_lrange range_0_32mA;
extern const struct comedi_lrange range_unknown;

#define range_digital		range_unipolar5

#if __GNUC__ >= 3
#define GCC_ZERO_LENGTH_ARRAY
#else
#define GCC_ZERO_LENGTH_ARRAY 0
#endif

struct comedi_lrange {
	int length;
	struct comedi_krange range[GCC_ZERO_LENGTH_ARRAY];
};

static inline bool comedi_range_is_bipolar(struct comedi_subdevice *s,
					   unsigned int range)
{
	return s->range_table->range[range].min < 0;
}

static inline bool comedi_range_is_unipolar(struct comedi_subdevice *s,
					    unsigned int range)
{
	return s->range_table->range[range].min >= 0;
}

static inline bool comedi_range_is_external(struct comedi_subdevice *s,
					    unsigned int range)
{
	return !!(s->range_table->range[range].flags & RF_EXTERNAL);
}

static inline bool comedi_chan_range_is_bipolar(struct comedi_subdevice *s,
						unsigned int chan,
						unsigned int range)
{
	return s->range_table_list[chan]->range[range].min < 0;
}

static inline bool comedi_chan_range_is_unipolar(struct comedi_subdevice *s,
						 unsigned int chan,
						 unsigned int range)
{
	return s->range_table_list[chan]->range[range].min >= 0;
}

static inline bool comedi_chan_range_is_external(struct comedi_subdevice *s,
						 unsigned int chan,
						 unsigned int range)
{
	return !!(s->range_table_list[chan]->range[range].flags & RF_EXTERNAL);
}

/* munge between offset binary and two's complement values */
static inline unsigned int comedi_offset_munge(struct comedi_subdevice *s,
					       unsigned int val)
{
	return val ^ s->maxdata ^ (s->maxdata >> 1);
}

/**
 * comedi_bytes_per_sample - determine subdevice sample size
 * @s:		comedi_subdevice struct
 *
 * The sample size will be 4 (sizeof int) or 2 (sizeof short) depending on
 * whether the SDF_LSAMPL subdevice flag is set or not.
 *
 * Returns the subdevice sample size.
 */
static inline unsigned int comedi_bytes_per_sample(struct comedi_subdevice *s)
{
	return s->subdev_flags & SDF_LSAMPL ? sizeof(int) : sizeof(short);
}

/**
 * comedi_sample_shift - determine log2 of subdevice sample size
 * @s:		comedi_subdevice struct
 *
 * The sample size will be 4 (sizeof int) or 2 (sizeof short) depending on
 * whether the SDF_LSAMPL subdevice flag is set or not.  The log2 of the
 * sample size will be 2 or 1 and can be used as the right operand of a
 * bit-shift operator to multiply or divide something by the sample size.
 *
 * Returns log2 of the subdevice sample size.
 */
static inline unsigned int comedi_sample_shift(struct comedi_subdevice *s)
{
	return s->subdev_flags & SDF_LSAMPL ? 2 : 1;
}

/**
 * comedi_bytes_to_samples - converts a number of bytes to a number of samples
 * @s:		comedi_subdevice struct
 * @nbytes:	number of bytes
 *
 * Returns the number of bytes divided by the subdevice sample size.
 */
static inline unsigned int comedi_bytes_to_samples(struct comedi_subdevice *s,
						   unsigned int nbytes)
{
	return nbytes >> comedi_sample_shift(s);
}

/**
 * comedi_samples_to_bytes - converts a number of samples to a number of bytes
 * @s:		comedi_subdevice struct
 * @nsamples:	number of samples
 *
 * Returns the number of samples multiplied by the subdevice sample size.
 * Does not check for arithmetic overflow.
 */
static inline unsigned int comedi_samples_to_bytes(struct comedi_subdevice *s,
						   unsigned int nsamples)
{
	return nsamples << comedi_sample_shift(s);
}

/**
 * comedi_check_trigger_src() - trivially validate a comedi_cmd trigger source
 * @src: pointer to the trigger source to validate
 * @flags: bitmask of valid TRIG_* for the trigger
 *
 * This is used in "step 1" of the do_cmdtest functions of comedi drivers
 * to vaildate the comedi_cmd triggers. The mask of the @src against the
 * @flags allows the userspace comedilib to pass all the comedi_cmd
 * triggers as TRIG_ANY and get back a bitmask of the valid trigger sources.
 */
static inline int comedi_check_trigger_src(unsigned int *src,
					   unsigned int flags)
{
	unsigned int orig_src = *src;

	*src = orig_src & flags;
	if (*src == TRIG_INVALID || *src != orig_src)
		return -EINVAL;
	return 0;
}

/**
 * comedi_check_trigger_is_unique() - make sure a trigger source is unique
 * @src: the trigger source to check
 */
static inline int comedi_check_trigger_is_unique(unsigned int src)
{
	/* this test is true if more than one _src bit is set */
	if ((src & (src - 1)) != 0)
		return -EINVAL;
	return 0;
}

/**
 * comedi_check_trigger_arg_is() - trivially validate a trigger argument
 * @arg: pointer to the trigger arg to validate
 * @val: the value the argument should be
 */
static inline int comedi_check_trigger_arg_is(unsigned int *arg,
					      unsigned int val)
{
	if (*arg != val) {
		*arg = val;
		return -EINVAL;
	}
	return 0;
}

/**
 * comedi_check_trigger_arg_min() - trivially validate a trigger argument
 * @arg: pointer to the trigger arg to validate
 * @val: the minimum value the argument should be
 */
static inline int comedi_check_trigger_arg_min(unsigned int *arg,
					       unsigned int val)
{
	if (*arg < val) {
		*arg = val;
		return -EINVAL;
	}
	return 0;
}

/**
 * comedi_check_trigger_arg_max() - trivially validate a trigger argument
 * @arg: pointer to the trigger arg to validate
 * @val: the maximum value the argument should be
 */
static inline int comedi_check_trigger_arg_max(unsigned int *arg,
					       unsigned int val)
{
	if (*arg > val) {
		*arg = val;
		return -EINVAL;
	}
	return 0;
}

/*
 * Must set dev->hw_dev if you wish to dma directly into comedi's buffer.
 * Also useful for retrieving a previously configured hardware device of
 * known bus type.  Set automatically for auto-configured devices.
 * Automatically set to NULL when detaching hardware device.
 */
int comedi_set_hw_dev(struct comedi_device *dev, struct device *hw_dev);

static inline unsigned int comedi_buf_n_bytes_ready(struct comedi_subdevice *s)
{
	return s->async->buf_write_count - s->async->buf_read_count;
}

unsigned int comedi_buf_write_alloc(struct comedi_subdevice *s, unsigned int n);
unsigned int comedi_buf_write_free(struct comedi_subdevice *s, unsigned int n);

unsigned int comedi_buf_read_n_available(struct comedi_subdevice *s);
unsigned int comedi_buf_read_alloc(struct comedi_subdevice *s, unsigned int n);
unsigned int comedi_buf_read_free(struct comedi_subdevice *s, unsigned int n);

unsigned int comedi_buf_write_samples(struct comedi_subdevice *s,
				      const void *data, unsigned int nsamples);
unsigned int comedi_buf_read_samples(struct comedi_subdevice *s,
				     void *data, unsigned int nsamples);

/* drivers.c - general comedi driver functions */

#define COMEDI_TIMEOUT_MS	1000

int comedi_timeout(struct comedi_device *, struct comedi_subdevice *,
		   struct comedi_insn *,
		   int (*cb)(struct comedi_device *, struct comedi_subdevice *,
			     struct comedi_insn *, unsigned long context),
		   unsigned long context);

unsigned int comedi_handle_events(struct comedi_device *dev,
				  struct comedi_subdevice *s);

int comedi_dio_insn_config(struct comedi_device *, struct comedi_subdevice *,
			   struct comedi_insn *, unsigned int *data,
			   unsigned int mask);
unsigned int comedi_dio_update_state(struct comedi_subdevice *,
				     unsigned int *data);
unsigned int comedi_bytes_per_scan(struct comedi_subdevice *s);
unsigned int comedi_nscans_left(struct comedi_subdevice *s,
				unsigned int nscans);
unsigned int comedi_nsamples_left(struct comedi_subdevice *s,
				  unsigned int nsamples);
void comedi_inc_scan_progress(struct comedi_subdevice *s,
			      unsigned int num_bytes);

void *comedi_alloc_devpriv(struct comedi_device *, size_t);
int comedi_alloc_subdevices(struct comedi_device *, int);
int comedi_alloc_subdev_readback(struct comedi_subdevice *);

int comedi_readback_insn_read(struct comedi_device *, struct comedi_subdevice *,
			      struct comedi_insn *, unsigned int *data);

int comedi_load_firmware(struct comedi_device *, struct device *,
			 const char *name,
			 int (*cb)(struct comedi_device *,
				   const u8 *data, size_t size,
				   unsigned long context),
			 unsigned long context);

int __comedi_request_region(struct comedi_device *,
			    unsigned long start, unsigned long len);
int comedi_request_region(struct comedi_device *,
			  unsigned long start, unsigned long len);
void comedi_legacy_detach(struct comedi_device *);

int comedi_auto_config(struct device *, struct comedi_driver *,
		       unsigned long context);
void comedi_auto_unconfig(struct device *);

int comedi_driver_register(struct comedi_driver *);
void comedi_driver_unregister(struct comedi_driver *);

/**
 * module_comedi_driver() - Helper macro for registering a comedi driver
 * @__comedi_driver: comedi_driver struct
 *
 * Helper macro for comedi drivers which do not do anything special in module
 * init/exit. This eliminates a lot of boilerplate. Each module may only use
 * this macro once, and calling it replaces module_init() and module_exit().
 */
#define module_comedi_driver(__comedi_driver) \
	module_driver(__comedi_driver, comedi_driver_register, \
			comedi_driver_unregister)

#endif /* _COMEDIDEV_H */


text:
"""LogParser package."""

__version__ = "1.3"
__license__ = "Apache"
__copyright__ = "Copyright 2016 Real-Time Innovations, Inc."
# pylint: disable=E0603
__all__ = ("devices", "countset", "logger", "logparser", "logs", "utils")


text:
<!DOCTYPE html>

	<meta charset="utf-8"/>
	<title>KMF - Kevoree Modeling Framework</title>
	<meta name="description" content=""/>
	<meta name="keywords" content="modeling, MDE, MDA, framework, java, kotlin, scala, javascript, kevoree, KMF, EMF, ecore, xmi, json"/>
	<meta name="author" content="Fouquet Francois"/>
	<meta name="viewport" content="width=device-width, initial-scale=1"/>
	<link rel="shortcut icon" type="image/icon" href="favicon.ico"/>

	<link rel="stylesheet" href="css/custom.min.css"/>
	<link rel="stylesheet" href="css/tuktuk.min.css"/>
	<link rel="stylesheet" href="css/tuktuk.theme.min.css"/>
	<link rel="stylesheet" href="css/tuktuk.icons.css"/>

	<link rel="stylesheet" href="highlight/styles/tomorrow.css"/>

Kevoree Modeling Framework

				Home
				About
				Features
				Contribute

Free the code from models !

Models are no longer restricted to modeling environments. The increasing use of Model@Runtime requires rich and efficient modeling frameworks.

                    KMF is developed to provide efficient modeling frameworks to edit, compose and synchronize models on Java and JavaScript Virtual Machines.

				Documentation

				Playground

current version

1.9.2

About Kevoree Modeling Framework

KMF generates modeling frameworks and API for JS and JVM platforms, from a domain metamodel.
                    It also offers comparison, merge and incremental synchronisation mechanisms tuned for Runtime use, making a powerful tool for server-side storage and presentation in a simple browser.
                    In short, KMF generate business specific API and Tools from a metamodel, ready for distributed modeling activities.

Features

Let's take a concrete example

				Concrete things are better to understand abstract modeling tools.

When you think about Cloud  systems...

You think of hosting nodes
					and hosted software .

Everything begins with a metamodel

A cloud is composed by

A collection of nodes identified by an ID.

Each Node contains several software identified by their names.

Use any eclipse graphical or textual editor to produce an ecore metamodel.

				See the XMI

Then KMF generates POJO *like* API

Java

//Creation of a Cloud instance
Cloud cloud = factory.createCloud();
//Creation of a Node
Node myAmazonEC2node = factory.createNode();
myAmazonEC2node.setId("EC2_0");
//Adding the node to the cloud
cloud.addNodes(myAmazonEC2node);
//Creation of a Software
Softwzre myNginx = factory.createSoftware();
myNginx.setName("SRV0");
//Attaching the software to the node
myAmazonEC2node.addSoftwares(myNginx);

JS

//create a cloud
var cloud = factory.createCloud();
//create a node
var myAmazonEC2node = factory.createNode();
myAmazonEC2node.id = "EC2_0";
//add node to your cloud
cloud.addNodes(myAmazonEC2node);
//create a software
var myNginx = factory.createSoftware();
myNginx.name = "SRV0";
//attach the software to your new node
myAmazonEC2node.addSoftwares(myNginx);

Easily access model elements using IDs and Paths

Java

//select your node by ID
Node ec2node = cloud.findNodesByID("EC2_0");
//or with XPath style
ec2node = cloud.findByPath("nodes[EC2_0]");
//then select a software
Software soft = ec2node.findSoftwaresByName("SRV0");
//or by path
soft=cloud.findByPath("nodes[EC2_0]/softwares[SRV0]");
//print the path of any element
System.out.println(soft.path(););
//print on console : nodes[EC2_0]/softwares[SRV0]

JS

//select your node by ID
var ec2node = cloud.findNodesByID("EC2_0");
//or with XPath style
ec2node = cloud.findByPath("nodes[EC2_0]");
//then select a software
var soft = ec2node.findSoftwaresByName("SRV0");
//or by path
soft=cloud.findByPath("nodes[EC2_0]/softwares[SRV0]");
//print the path of any element
console.log(soft.path(););
//print on console : nodes[EC2_0]/softwares[SRV0]

Model elements selection using paths is way faster than iterating on collections.

                Similarly to database IDs or NoSQL indexes, KMF uses hashtables to speed up the lookup of elements.

Load, Save and Clone your models in XMI or JSON

Java

ModelCloner     cloner = new DefaultModelCloner();
ModelSerializer jsonSaver = new JSONModelSerializer();
ModelLoader     jsonLoader = new JSONModelLoader();
ModelSerializer xmiSaver = new XMIModelSerializer();
ModelLoader     xmiLoader = new XMINModelLoader();

//Save in standard XMI Format (work Eclipse)
System.out.println(xmiSaver.serialize(myCloud));
//Save in human readable JSON
System.out.println(jsonSaver.serialize(myCloud));

//Load from JSON and take first package (only one here)
Cloud cloud = jsonLoader
	.loadModelFromString(txtPayLoad).get(0);
//Load from XMI
Cloud cloud = xmiLoader
	.loadModelFromString(txtPayLoad).get(0);

//Clone the entire model
Cloud clonedModel = cloner.clone(cloud);
//Clone to a readonly structure
clonedModel = cloner.clone(cloud,true);
//Only clone a part of model, share the first node
cloud.getNodes().get(0).setRecursiveReadOnly();
Cloud clonedModel = cloner.cloneMutableOnly(cloud);

JS

var cloner = new DefaultModelCloner();
var jsonSaver = new JSONModelSerializer();
var jsonLoader = new JSONModelLoader();
var xmiSaver = new XMIModelSerializer();
var xmiLoader = new XMINModelLoader();

//Save in human readable JSON
console.log(jsonSaver.serialize(myCloud));

//Load from JSON and take first package
var cloud = jsonLoader
	.loadModelFromString(txtPayLoad).get(0);

//Clone the entire model
var clonedModel = cloner.clone(cloud);
//Clone to a readonly structure
var clonedModel = cloner.clone(cloud,true);
//Only clone a part of model, share the first node
cloud.getNodes().get(0).setRecursiveReadOnly();
var clonedModel = cloner.cloneMutableOnly(cloud);

//save into XMI format
var savedModel = xmiSaver.serialize(cloud);
//reload from XMI stream
var reloadCloud = xmiLoader
	.loadModelFromString(savedModel);

We support the standard XMI interchange format for compatibility with other modeling framework tool like EMF.

               In addition KMF offers to serialize your models in JSON format for more portability, especially designed for web usage.

               KMF allows to set part of the model as Read-Only. With this feature, the clone operator is able to efficiently clone mutable elements only.

               This ability drastically speeds up the cloning and enables processes of clones in parallel.

Use Events to stay informed

Java

//Create a listener
class ModelSyncListener implements ModelTreeListener {
    @Override
    public void elementChanged(ModelEvent event){
	   switch(event.getType()){
	     case ActionType.ADD:
	       System.out.println("Add "+event);
	       break;
	     case ActionType.SET:
	       System.out.println("Set "+event);
               break;
	   }
    }
}
//Add it as TreeListener
//Listens this element + all contained
cloud.addModelTreeListener(new ModelSyncListener());
//Std listener only listen local event
//cloud.addModelListener(new ModelSyncListener());
Node node = factory.createNode();
node.setID("EC1");
//Trigger event ADD
cloud.addNodes(node);
//Trigger event SET
node.setId("EC2_1");

JS

//Declare events listener
var listener = { elementChanged : function(event){
 switch(event.getType()){
  case ActionType.$ADD:
    console.log("Add event ! "+event);
	break;
  case ActionType.$SET:
    console.log("Set event ! "+event);
	break;
 }
}};
//Add as Tree (meaning global) listener
cloud.addModelTreeListener(listener);
//Std listener only listen local event
//cloud.addModelListener(listener);
var node = factory.createNode();
node.id = "EC1";
//Trigger event ADD
cloud.addNodes(node);
//Trigger event SET
node.id = "EC2_1";

Events are triggered each time an attribute or a relation of a model element is edited.

               They make it easier to synchronize a presentation layer like a DOM fragment and the modeling layer.

Set operators to merge and compare

Java

ModelCompare compare = new DefaultModelCompare();

//Produces the trace sequence to go from MO to M1
TraceSequence diffSeq = compare.diff(model0,model1);
//Produces the trace sequence of MO inter M1
TraceSequence interSeq = compare.inter(model0,model1);
//Produces the trace sequence of MO merged with M1
TraceSequence mergeSeq = compare.merge(model0,model1);
for(trace : diffSeq.getTraces()){
	//Prints the difference between M0 and M1
	System.out.println(trace);
}
//Merges M1 into M0
mergeSeq.applyOn(model0);
assert(model1.modelEquals(m0));
Cloud model3 = factory.createCloud();
interSeq.applyOn(model3);
//model3 is now the common part of M0 and M1

JS

var compare = new DefaultModelCompare();

//Produce the trace sequence of MO -> M1
var diffSeq = compare.diff(model0,model1);
//Produce the trace sequence of MO inter M1
var interSeq = compare.inter(model0,model1);
//Produces the trace sequence of MO merged with M1
var mergeSeq = compare.merge(model0,model1);
for(i=0;i < diffSeq.getTraces().$size;i++){
	//Print the comparison between M0 and M1
	console.log(diffSeq.getTraces()[i]);
}
//Merge M1 into M0
mergeSeq.applyOn(model0);
assert(model1.modelEquals(m0));
var model3 = factory.createCloud();
interSeq.applyOn(model3);
//model3 is now the common part of M0 and M1

Each set operator manipulates models as trace sequences. A Trace is defined as an atomic operation modifying a model (add, set, remove).

                Trace sequences can be applied on models, making it possible to build any operators using these atomic steps.

Synchronize your models incrementally !

Java

Cloud cloudM0 = factory.createNode();
Cloud cloudM1 = factory.createNode();

ModelCompare compare = new DefaultModelCompare();
Event2Trace conv = new Event2Trace(compare);
cloudM0.addModelTreeListener(new ModelTreeListener(){
 @Override
 public void elementChanged(ModelEvent event) {
  TraceSequence traceSeq = conv.convert(event);
  //send via network for remote synchronisation
  //traceSeq are serialiable
  traceSeq.applyOn(cloudM1);
 }
});
//Add a new node to cloudM0
Node newNode = factory.createNode();
newNode.setId("newNode")
cloudM0.addNodes(newNode);
//Now CloudM1 has also create one node
assert(cloudM1.findNodesById("newNode") != null);

JS

var cloudM0 = factory.createNode();
var cloudM1 = factory.createNode();

var compare = new DefaultModelCompare();
var conv = new Event2Trace(compare);
var listener = { elementChanged : function(event){
    var traces = apply.convert(event);
	//send trace to network or browser events
	//for remote synchronization
    traces.applyOn(cloudM1);
}};

//Add a new node to cloudM0
var newNode = factory.createNode();
newNode.setId("newNode")
cloudM0.addNodes(newNode);

//Now CloudM1 has also create one node
assert(cloudM1.findNodesById("newNode") != null);

To synchronize several model instances simply capture events, convert them to trace, broadcast, and apply on each models.

                Coupled with a conflict resolution mechanism, this makes the foundation for collaborative distributed modeling.

Dive efficiently into models

Java

ModelVisitor visitor = new ModelVisitor(){
    public override fun visit(
      KMFContainer elem,
      String refNameInParent,
	  KMFContainer parent) {
	    System.out.println(elem.path())
    }
}
//recursive navigation into contained elements
cloud.visit(true,true,false);
//recursive navigation into not contained references
cloud.visit(true,false,true);
//Non recursive navigation into cloud references
cloud.visit(false,true,true);

ModelAttributesVisitor visitorAtts
	= new ModelAttributesVisitor(){
    public override fun visit(
      Object attValue,
      String name,
	  KMFContainer parent) {
	    System.out.println("Visit "+name)
    }
}
//Visit all attributes of Cloud
cloud.visit(visitorAtts);

JS

var visitor = new ModelVisitor();
visitor.visit = function(modelElem){
	console.log(modelElem.metaClassName());
}
//recursive navigation into contained elements
cloud.visit(true,true,false);
//recursive navigation into not contained references
cloud.visit(true,false,true);
//Non recursive navigation into cloud references
cloud.visit(false,true,true);

var visitorAtts = new ModelAttributesVisitor();
visitorAtts.visit = function(attValue,name,parent) {
	console.log(name);
}
//Visit all attributes of Cloud
cloud.visit(visitorAtts);

The Visitor API replaces the natural iterative navigation through model elements.
				You can choos to visit recursively or not (first boolean parameters).
				Visit methods are generated to offer best performances.
				In addition users can stop the recursion at anytime by using the stopVisit() methods inside the visitor object to globally stop the process.
				Also, noChildrenVisit() skips children.

Inject behavior and build executable model

Kotlin (JVM) and JS

//declare a new aspect on Node
aspect trait NodeAspect : Node {
	//private method
	//are not include in model
	private fun privateProcess(){};
	//method add to Node metaClass
	fun newService(){}
}
//Add a new concept named ExNode
//The new concept will inherit Node
metaClass("ExNode") ExNodeA : Node {
	//public method
	fun ExRun(){
	}
}
//create an instance of the concept
var newNode = factory.createExNode();

JS

//JS version can use static aspects
//same as the JVM version.
//In addition model elements
//are generated extensible dynamically
//by leveraging prototypes

//add a method to the Node concept
factory.createNode().prototype.prettyPrint =
 function prettyPrint(){
   console.log(this.metaClassName());
}
//create a standard node object
var node = factory.createNode();
//call aspect method
node.prettyPrint();

Aspects replace the derived method of ecore. Allowing to write statically verified code instead of ugly putting code in

And many more things...

Efficiency

KMF takes efficiency seriously.
With a generative approach, you can expect the best performance at runtime for your modeling operations.

Easy of Use and Portable

Unlike other modeling framework, KMF provides cross compilation for Java and JS platforms. Moreover it doesn't need any library @Runtime and is easy-to-use for any OO developper by leveraging simple POJO api.

Distributed

Collaborative and distributed modeling is enabled by KMF thanks to the incremental synchronization mechanism.

                    It is now possible to embed and synchronize your models on tablets, phones and your home computer.

Want to test it LIVE ? Try our playground .

				PlayGround

Contribute

Want to help? We're on GitHub.
 Feel free to give us any feedback.

				Source on GitHub

Free Software

					We're researchers from Interdisciplinary Center for Security, Reliability and Trust (SnT), University of Luxembourg and INRIA Rennes (FR).

Join the team

					Help to build KMF on GitHub.

Need some help?

					Start your own project and ask us on GitHub!

			KMF is a child project of Kevoree


text:
Ansible roles for Pundun management

Usage:

```sh
export ANSIBLE_HOST_KEY_CHECKING=False
ansible-playbook -i production site.yml -K
#Alternatively, depending on hosts defined in production file
ansible-playbook -i production bare_metal.yml -K
```

If hosts are docker containers that are running on local host, you may use docker_play.sh

```sh
./docker_play.sh
```


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

class RMCTRL extends CI_Controller {

	public function index()
	{
		$this->load->view('pages/RM/index');
	}
}


text:
"""
Manage proposal kinds.

Everything is keyed off the ProposalKind slug value.
"""
from django.conf import settings
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType

from symposion.conference.models import current_conference, Section, Conference
from symposion.proposals.models import ProposalKind, ProposalSection
from symposion.reviews.models import Review

class KindTracker(object):
    # Internal data structure
    def __init__(self, kind_slug):
        self.slug = kind_slug
        self.model_class = None
        self.form_class = None
        self.section_name = None

trackers = {}
trackers_by_section_slug = {}

def _get_tracker(slug):
    if slug not in trackers:
        trackers[slug] = KindTracker(slug)
    return trackers[slug]

def register_proposal_model(kind_slug, model_class, section_name):
    tracker = _get_tracker(kind_slug)
    tracker.model_class = model_class
    tracker.section_name = section_name

def register_proposal_form(kind_slug, form_class):
    _get_tracker(kind_slug).form_class = form_class

def get_proposal_model(kind_slug):
    model_class = _get_tracker(kind_slug).model_class
    if not model_class:
        raise ValueError("No model_class has been registered for proposal kind %r" % kind_slug)
    return model_class

def get_section_name(kind_slug):
    name = _get_tracker(kind_slug).section_name
    if not name:
        raise ValueError("No section_name has been registered for proposal kind %r" % kind_slug)
    return name

def get_proposal_form(kind_slug):
    form_class = _get_tracker(kind_slug).form_class
    if not form_class:
        raise ValueError("No form class has been registered for proposal kind %r" % kind_slug)
    return form_class

def get_proposal_model_from_section_slug(section_slug):
    if section_slug not in trackers_by_section_slug:
        kind = ProposalKind.objects.get(section__slug=section_slug)
        trackers_by_section_slug[section_slug] = _get_tracker(kind.slug)
    model_class = trackers_by_section_slug[section_slug].model_class
    if not model_class:
        raise ValueError("No model class has been registered for section slug %r" % section_slug)
    return model_class

def get_kind_slugs():
    return trackers.keys()

def ensure_proposal_records():
    """
    This can be called (after Django is done initializing) to make sure
    all the expected records exist for the defined kinds, including
    Permissions, ProposalKinds, ProposalSections, and Sections.

    It's invoked from symposion.proposals.signals on a post_migrate
    signal, so it gets run on each deploy automatically.

    It can also be invoked manually with the management command
    "ensure_proposal_records".
    """
    Conference.objects.get_or_create(pk=settings.CONFERENCE_ID)
    conference = current_conference()
    review_ct = ContentType.objects.get_for_model(Review)

    for kind_slug in get_kind_slugs():
        section_slug = kind_slug + "s"
        section_name = get_section_name(kind_slug)
        section, created = Section.objects.get_or_create(
            conference=conference,
            slug=section_slug,
            defaults=dict(
                name=section_name
            )
        )
        kind, created = ProposalKind.objects.get_or_create(
            slug=kind_slug,
            section=section,
            defaults=dict(
                name=section_name
            )
        )
        ProposalSection.objects.get_or_create(
            section=section,
            defaults=dict(
                closed=True,
                published=False,
            )
        )

        for verb in ['review', 'manage']:
            Permission.objects.get_or_create(
                codename='can_%s_%s' % (verb, section_slug),
                content_type=review_ct,
                defaults=dict(
                    name='Can %s %ss' % (verb, section.name),
                )
            )


text:
Native Rust access to the x86 and x86_64 CPUID instruction.

[![Build Status](https://travis-ci.org/shepmaster/cupid.svg)](https://travis-ci.org/shepmaster/cupid) [![Current Version](http://meritbadge.herokuapp.com/cupid)](https://crates.io/crates/cupid)

[Documentation](https://shepmaster.github.io/cupid/)

## Overview

```rust
extern crate cupid;

fn main() {
    let information = cupid::master();
    println!("{:#?}", information);
    if let Some(information) = information {
        if information.sse4_2() {
             println!("SSE 4.2 Available");
        }
    }
}
```

## See also

* [libcpuid](http://libcpuid.sourceforge.net/) - A C library providing
  access to the CPUID instruction.
* [cpuid](https://crates.io/crates/cpuid) - Rust bindings to the
  libcpuid library.
* [rust-x86](https://github.com/gz/rust-x86) - Another native crate
  that includes CPUID and more.

## Contributing

1. Fork it ( https://github.com/shepmaster/cupid/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Add a failing test.
4. Add code to pass the test.
5. Commit your changes (`git commit -am 'Add some feature'`)
6. Ensure tests pass.
7. Push to the branch (`git push origin my-new-feature`)
8. Create a new Pull Request


text:
package ytdl

import (
	"fmt"
	"net/url"
	"strconv"
	"strings"
)

// FormatKey is a string type containing a key in a video format map
type FormatKey string

// Available format Keys
const (
	FormatExtensionKey     FormatKey = "ext"
	FormatResolutionKey    FormatKey = "res"
	FormatVideoEncodingKey FormatKey = "videnc"
	FormatAudioEncodingKey FormatKey = "audenc"
	FormatItagKey          FormatKey = "itag"
	FormatAudioBitrateKey  FormatKey = "audbr"
	FormatFPSKey           FormatKey = "fps"
)

type Range struct {
	Start string `json:"start"`
	End   string `json:"end"`
}

type Format struct {
	Itag
	Adaptive bool
	// FromDASH indicates that the stream
	// was extracted from the DASH manifest file
	FromDASH bool
	Index    *Range
	Init     *Range
	url      string
	s        string
	sig      string
	stream   string
	conn     string
	sp       string
}

func parseFormat(queryString string) (*Format, error) {
	query, err := url.ParseQuery(queryString)
	if err != nil {
		return nil, err
	}

	format := Format{}

	for k, v := range query {
		switch k {
		case "itag":
			i, err := strconv.Atoi(v[0])
			if err != nil {
				return nil, fmt.Errorf("unable to parse itag param: %w", err)
			}

			itag := getItag(i)
			if itag == nil {
				return nil, fmt.Errorf("no metadata found for itag: %v", i)
			}

			format.Itag = *itag
		case "url":
			format.url = v[0]
		case "s":
			format.s = v[0]
		case "sig":
			format.sig = v[0]
		case "stream":
			format.stream = v[0]
		case "conn":
			format.conn = v[0]
		case "sp":
			format.sp = v[0]
		case "index":
			format.Index, err = parseRange(v[0])
			if err != nil {
				return nil, fmt.Errorf("unable to parse index range")
			}
		case "init":
			format.Init, err = parseRange(v[0])
			if err != nil {
				return nil, fmt.Errorf("unable to parse init range")
			}
		}
	}
	return &format, nil
}

func parseRange(s string) (*Range, error) {
	sa := strings.Split(s, "-")
	if len(sa) != 2 {
		return nil, fmt.Errorf("Invalid range")
	}
	return &Range{Start: sa[0], End: sa[1]}, nil
}

// ValueForKey gets the format value for a format key, used for filtering
func (f *Format) ValueForKey(key FormatKey) interface{} {
	switch key {
	case FormatItagKey:
		return f.Itag.Number
	case FormatExtensionKey:
		return f.Extension
	case FormatResolutionKey:
		return f.Resolution
	case FormatVideoEncodingKey:
		return f.VideoEncoding
	case FormatAudioEncodingKey:
		return f.AudioEncoding
	case FormatAudioBitrateKey:
		return f.AudioBitrate
	case FormatFPSKey:
		return f.FPS
	default:
		return fmt.Errorf("Unknown format key: %v", key)
	}
}

func (f *Format) CompareKey(other *Format, key FormatKey) int {
	switch key {
	case FormatResolutionKey:
		return f.resolution() - other.resolution()
	case FormatAudioBitrateKey:
		return f.AudioBitrate - other.AudioBitrate
	case FormatFPSKey:
		return f.FPS - other.FPS
	default:
		return 0
	}
}

// width in pixels
func (f *Format) resolution() int {
	res := f.Itag.Resolution
	if len(res) < 2 {
		return 0
	}

	width, _ := strconv.Atoi(res[:len(res)-2])
	return width
}


text:
module.exports = function(ctx, lab) {
	// Test shortcuts
	var expect = require('code').expect;
	var before = lab.before;
	var after = lab.after;
	var describe = lab.experiment;
	var it = lab.test;

	describe('verify pool-entry api', function() {

		it('should start with an empty pool on set endpoint', function(done) {
			ctx.server.inject({method: 'get', url: ctx.baseSetUrl}, function(res) {
				expect(res.statusCode).to.equal(200);
				expect(res.result.pool.length).to.equal(0);
				done();
			});
		});

		var baseSetPoolUrl = ctx.baseSetUrl + '/poolentry';
		var poolEntryId1;
		it('should allow me to create a new poolEntry', function(done) {
			var poolEntry = {
				name: 'test-pool-entry-post',
				volume: 0.75,
				sampleType: 'local',
				sampleId: 'abcd-efgh'
			};
			ctx.server.inject({method: 'post', url: baseSetPoolUrl, payload: JSON.stringify(poolEntry)}, function(res) {
				expect(res.statusCode).to.equal(200);
				expect(res.result.volume).to.equal(0.75);
				poolEntryId1 = res.result.id;
				done();
			});
		});

		it('should have added the new pool entry to the set for me', function(done) {
			ctx.server.inject({method: 'get', url: ctx.baseSetUrl}, function(res) {
				expect(res.statusCode).to.equal(200);
				expect(res.result.pool.length).to.equal(1);
				expect(res.result.pool[0].id).to.equal(poolEntryId1);
				ctx.server.inject({method: 'get', url: ctx.baseSetUrl + '/poolentry/' + poolEntryId1}, function(res) {
					expect(res.statusCode).to.equal(200);
					expect(res.result.volume).to.equal(0.75);
					done();
				});
			});
		});

		var poolEntryId2;
		it('should allow me to create a second poolEntry', function(done) {
			var poolEntry = {
				name: 'test-pool-entry-post',
				volume: 0.5,
				sampleType: 'local',
				sampleId: 'abcd-efgh'
			};
			ctx.server.inject({method: 'post', url: baseSetPoolUrl, payload: JSON.stringify(poolEntry)}, function(res) {
				expect(res.statusCode).to.equal(200);
				expect(res.result.volume).to.equal(0.5);
				poolEntryId2 = res.result.id;
				if(ctx.app.config.logThings['test--list-collections']) {
					console.log('poolEntryId1: ' + poolEntryId1 + ' poolEntryId2: ' + poolEntryId2);
				}
				ctx.server.inject({method: 'get', url: ctx.baseSetUrl}, function(res) {
					expect(res.statusCode).to.equal(200);
					expect(res.result.pool.length).to.equal(2);
					expect(res.result.pool[1].id).to.equal(poolEntryId2);
					ctx.server.inject({method: 'get', url: ctx.baseSetUrl + '/poolentry/' + poolEntryId2}, function(res) {
						expect(res.statusCode).to.equal(200);
						expect(res.result.volume).to.equal(0.5);
						done();
					});
				});
			});
		});

		it('should allow me to delete the first poolEntry now', function(done) {
			ctx.server.inject({method: 'delete', url: baseSetPoolUrl + '/' + poolEntryId1}, function(res) {
				expect(res.statusCode).to.equal(200);
				done();
			});
		});

		it('should fail to delete the thing we just deleted', function(done) {
			ctx.server.inject({method: 'delete', url: baseSetPoolUrl + '/' + poolEntryId1}, function(res) {
				expect(res.statusCode).to.equal(404);
				done();
			});
		});

		it('should have removed the deleted pool entry from the set', function(done) {
			ctx.server.inject({method: 'get', url: ctx.baseSetUrl}, function(res) {
				expect(res.statusCode).to.equal(200);
				expect(res.result.pool.length).to.equal(1);
				expect(res.result.pool[0].id).to.equal(poolEntryId2);
				done();
			});
		});
	});
};


text:
package gov.nih.nci.cabig.caaers.domain;

import static gov.nih.nci.cabig.caaers.CaaersUseCase.CREATE_EXPEDITED_REPORT;
import gov.nih.nci.cabig.caaers.AbstractTestCase;
import gov.nih.nci.cabig.caaers.CaaersUseCases;
import gov.nih.nci.cabig.caaers.utils.DateUtils;

import java.util.Date;

/**
 * @author Rhett Sutphin
 */
@CaaersUseCases({CREATE_EXPEDITED_REPORT})
public class AdverseEventResponseDescriptionTest extends AbstractTestCase {
    private AdverseEventResponseDescription description;

    @Override
    protected void setUp() throws Exception {
        super.setUp();

        description = Fixtures.createAdverseEventResponseDescription();

    }

    public void testCopy() {
        AdverseEventResponseDescription adverseEventResponseDescription = description.copy();

        assertNull("must not coy id", adverseEventResponseDescription.getId());

        assertNull("must not coy grid id", adverseEventResponseDescription.getGridId());
        assertNull("must not coy version number", adverseEventResponseDescription.getVersion());
        assertNull("must not coy expeditedReport", adverseEventResponseDescription.getReport());
        assertEquals(description.getAutopsyPerformed(), adverseEventResponseDescription.getAutopsyPerformed());
        assertEquals(description.getBlindBroken(), adverseEventResponseDescription.getBlindBroken());
        assertEquals(description.getCauseOfDeath(), adverseEventResponseDescription.getCauseOfDeath());

        assertEquals(DateUtils.formatDate(description.getDateRemovedFromProtocol()), DateUtils.formatDate(adverseEventResponseDescription.getDateRemovedFromProtocol()));
        assertEquals(description.getDaysNotGiven(), adverseEventResponseDescription.getDaysNotGiven());
        assertEquals(description.getEventAbate(), adverseEventResponseDescription.getEventAbate());
        assertEquals(description.getEventDescription(), adverseEventResponseDescription.getEventDescription());
        assertEquals(description.getEventReappear(), adverseEventResponseDescription.getEventReappear());
        assertEquals(description.getPresentStatus(), adverseEventResponseDescription.getPresentStatus());
        //Commented below 2 lines date formats might have a mismatch. The asserts are failing. Revist to fix.
        //assertEquals(recoveryDate, adverseEventResponseDescription.getRecoveryDate());
        //assertEquals(reducedDate, adverseEventResponseDescription.getReducedDate());
        assertEquals(description.getRetreated(), adverseEventResponseDescription.getRetreated());
        assertEquals(description.getStudyDrugInterrupted(), adverseEventResponseDescription.getStudyDrugInterrupted());
        //assertEquals(reducedDose, adverseEventResponseDescription.getReducedDose());
        //assertEquals(retreated, adverseEventResponseDescription.getRetreated());
        //assertEquals(studyDrugInterrupted, adverseEventResponseDescription.getStudyDrugInterrupted());

        assertEquals("primaryTreatment must be same", description.getPrimaryTreatment(), adverseEventResponseDescription.getPrimaryTreatment());

    }

    public void testIsRemovedWhenRemoved() throws Exception {
        description.setDateRemovedFromProtocol(new Date());
        assertTrue(description.isRemovedFromProtocol());
    }

    public void testIsNotRemovedWhenRemoved() throws Exception {
        description.setDateRemovedFromProtocol(null);
        assertFalse(description.isRemovedFromProtocol());
    }

    public void testCopyPrimaryTreatmentApproximateTime() {
    	 AdverseEventResponseDescription adverseEventResponseDescription = description.copy();

        assertEquals("primaryTreatmentApproximateTime must  be refer same objects", description.getPrimaryTreatmentApproximateTime(), adverseEventResponseDescription.getPrimaryTreatmentApproximateTime());
//        assertEquals("primaryTreatmentApproximateTime must  be refer same objects",
//        		primaryTreatmentApproximateTime,
//        		adverseEventResponseDescription.getPrimaryTreatmentApproximateTime());
//
//        assertEquals("primaryTreatmentApproximateTime must  refer same object ", primaryTreatmentApproximateTime, adverseEventResponseDescription.getPrimaryTreatmentApproximateTime());

    }
}


text:
<?php

declare(strict_types=1);

namespace BrianFaust\Ark\API\Two;

use BrianFaust\Ark\API\AbstractAPI;
use Illuminate\Support\Collection;

class Peers extends AbstractAPI
{
    /**
     * @return \Illuminate\Support\Collection
     */
    public function all(): Collection
    {
        return $this->get('peers');
    }

    /**
     * @param string $ip
     *
     * @return \Illuminate\Support\Collection
     */
    public function get(string $ip): Collection
    {
        return $this->get("peers/${ip}");
    }
}


text:
<?php

	class NeuralRutasApp {

		public static function __Constructor($Tipo = false) {
			//Tomamos la variable del Mod_Rewrite y validamos el url para determinar el path correspondiente
		 	$Url = SysNeuralNucleo::LeerURLModReWrite();
		 	//Convertimos el Modulo correspondiente
		 	$Modulo = (empty($Url[0])) ? 'Default' : $Url[0];
		 	//Leemos el archivo de configuracion de accesos y lo convertimos en un array
		 	$Array = SysNeuralNucleo::CargarArchivoJsonConfiguracion('ConfigAcceso.json');
		 	//Validamos si existe la aplicacion correspondiente
		 	if(array_key_exists(mb_strtoupper($Modulo), $Array)) {
		 		//Leemos el archivo de configuracion
			 	$Rutas = SysNeuralNucleo::LeerArchivosConfiguracionRutasModulo($Array[mb_strtoupper($Modulo)]['Enrutamiento']['Carpeta'], $Array[mb_strtoupper($Modulo)]['Enrutamiento']['Configuracion']);
		 	}
		 	//Liberamos Memoria
		 	unset($Url, $Modulo, $Array);
		 	//Regresamos el Array Correspondiente
		 	return $Rutas[$Tipo];
		}

		/**
		 * RutaURLBase generada http://localhost/
		 * */
		public static function RutaURLBase($Ruta = false) {
			return __NeuralUrlRoot__.$Ruta;
		}

		/**
		 * RutaURL generada http://localhost/Modulo/Controlador/Metodo
		 * */
		public static function RutaURL($Ruta = false) {
			return __NeuralUrlRoot__.self::__Constructor('Modulo').'/'.$Ruta;
		}

		/**
		 * RutaPublico generada http://localhost/Public/Carpeta_Modulo/
		 * */
		public static function RutaPublico($Ruta = false) {
			return __NeuralUrlRoot__.'Public/'.self::__Constructor('Carpeta_Public').'/'.$Ruta;
		}

		/**
		 * RutaImagenes generada http://localhost/Public/Carpeta_Modulo/Carpeta_Imagenes/
		 * */
		public static function RutaImagenes($Ruta) {
			return __NeuralUrlRoot__.'Public/'.self::__Constructor('Carpeta_Public').'/'.self::__Constructor('Carpeta_Imagenes').'/'.$Ruta;
		}

		/**
		 * RutaCss generada http://localhost/Public/Carpeta_Modulo/Carpeta_Css/
		 * */
		public static function RutaCss($Ruta) {
			return __NeuralUrlRoot__.'Public/'.self::__Constructor('Carpeta_Public').'/'.self::__Constructor('Carpeta_Css').'/'.$Ruta;
		}

		/**
		 * RutaJs generada http://localhost/Public/Carpeta_Modulo/Carpeta_Js/
		 * */
		public static function RutaJs($Ruta) {
			return __NeuralUrlRoot__.'Public/'.self::__Constructor('Carpeta_Public').'/'.self::__Constructor('Carpeta_Js').'/'.$Ruta;
		}
	}


text:
PathGenerationGBM::PathGenerationGBM(shared_ptr<RandomBase> TheGenerator_,
									 double Spot0_,
									 double T_,
									 const Parameters& drift_,
									 const Parameters& vol_,
									 unsigned long steps_)
	: PathGeneration(TheGenerator_, Spot0_, T_, steps_), drift(drift_), vol(vol_)
{
	TheGenerator->ResetDimensionality(steps);
	deltaT = T / steps;
	_drift = drift.Integral(0, deltaT) - .5 * vol.IntegralSquare(0, deltaT);
	_vol_sqrt = sqrt(vol.IntegralSquare(0, deltaT));
}

void PathGenerationGBM::SetSteps(unsigned long steps_){
	steps = steps_;
	TheGenerator->ResetDimensionality(steps);
	deltaT = T / steps;
	_drift = drift.Integral(0, deltaT) - .5 * vol.IntegralSquare(0, deltaT);
	_vol_sqrt = sqrt(vol.IntegralSquare(0, deltaT));
}

void PathGenerationGBM::SetDrift(const Parameters& drift_){ drift = drift_; }
void PathGenerationGBM::SetVol(const Parameters& vol_){ vol = vol_; }

double PathGenerationGBM::GetOnePath(args& args_) const {

	TheGenerator->GetGaussians(args_[0]);

	double log_stock_spot = log(Spot0);

	for (size_t i(0); i < steps; ++i)
		log_stock_spot += _drift + _vol_sqrt * args_[0][i];

	return exp(log_stock_spot);
}

MJArray PathGenerationGBM::GetWholePath(args& args_)  {

	MJArray stock_path(steps+1);

	TheGenerator->GetGaussians(args_[0]);

	stock_path[0] = Spot0;

	for (size_t i(0); i < stock_path.size() - 1; ++i)
		stock_path[i + 1] = stock_path[i] * exp(_drift + _vol_sqrt * args_[0][i]);

	return stock_path;
}

//Stepping methods
//One further thing to implement is an alternative Path bsd on Euler stepping

PathEulerStepping::PathEulerStepping(shared_ptr<RandomBase> TheGenerator_,
									 double Spot0_,
									 double T_,
									 const Parameters& drift_,
									 const Parameters& vol_,
									 unsigned long steps_)
 : PathGeneration(TheGenerator_, Spot0_, T_, steps_), drift(drift_), vol(vol_)
{
	TheGenerator->ResetDimensionality(steps);
	deltaT = T / steps;
	_drift = 1.0 + drift.Integral(0, deltaT);
	_vol_sqrt = sqrt(vol.IntegralSquare(0, deltaT));

}

double PathEulerStepping::GetOnePath(args& args_) const{

	TheGenerator->GetGaussians(args_[0]);

	double stock_spot = Spot0;

	for (size_t i(0); i < steps; ++i)
		stock_spot *= (_drift + _vol_sqrt * args_[0][i]);

	return stock_spot;

}

MJArray PathEulerStepping::GetWholePath(args& args_) {

	MJArray stock_path(steps + 1);

	TheGenerator->GetGaussians(args_[0]);

	stock_path[0] = Spot0;

	for (size_t i(0); i < stock_path.size() - 1; ++i)
		stock_path[i + 1] = stock_path[i] * (_drift + _vol_sqrt * args_[0][i]);

	return stock_path;
}


text:
import {rule, group} from '../typography-fixer';

/**
 * A common ruleset for HTML typographic enhancement.
 *
 * It includes rules for:
 *
 * - Wrapping double quotes in quotation marks in a span with the `dquo` class
 * - Wrapping ampersand in a span with the `amp` class
 * - Wrapping many consecutive capitals in a span with the `caps` class
 *
 * @type {Array<Object>}
 */
const html = group('common', [
  rule('quotes', /(\u00ab|\u00bb|\u201c|\u201d)/, '$1'),
  rule('ampersand', /(&|&)($|\s)/, '$1$2'),
  rule('caps', /(([A-Z]\.?){2,})/, '$1'),
]);

export default html;


text:
{% extends "shop/base.html" %}
{% load i18n %}

{% block navbar %}

{% trans "Home" %}

{% trans "Newsletter Subscription" %}

{% endblock %}

{% block content %}

{% trans "Newsletter Subscription" %}

{% if form.errors %}

{% blocktrans count form.errors|length as count %}Please correct the following error:{% plural %}Please correct the following errors:{% endblocktrans %}

{% endif %}

<form method="post" action="{% url newsletter_update %}">{% csrf_token %}

{% trans 'Your name' %}:	{{ form.full_name }}

	{% if form.full_name.errors %}
 	*** {{ form.full_name.errors|join:", " }}
{% endif %}

{% trans 'Email address' %}:	{{ form.email }}

	{% if form.email.errors %}
 	*** {{ form.email.errors|join:", " }}
{% endif %}

{% trans 'Subscribe' %}:	{{ form.subscribed }}

	{% if form.subscribed.errors %}
 	*** {{ form.subscribed.errors|join:", " }}
{% endif %}

	<input type="submit" value="{% trans "Subscribe" %}"/>

</form>

{% endblock %}


text:
#ifndef AERON_ERROR_H
#define AERON_ERROR_H

#include <string.h>
#include <stdbool.h>

#include "aeron_common.h"
#include "util/aeron_platform.h"

#define AERON_ERROR_MAX_TOTAL_LENGTH (8192)

typedef struct aeron_per_thread_error_stct
{
    int errcode;
    size_t offset;
    char errmsg[AERON_ERROR_MAX_TOTAL_LENGTH];
}
aeron_per_thread_error_t;

int aeron_errcode(void);
const char *aeron_errmsg(void);
void aeron_set_errno(int errcode);
const char *aeron_error_code_str(int errcode);
void aeron_err_set(int errcode, const char *function, const char *filename, int line_number, const char *format, ...);
void aeron_err_append(const char *function, const char *filename, int line_number, const char *format, ...);
void aeron_err_clear(void);

#if defined(AERON_COMPILER_MSVC)
bool aeron_error_dll_process_attach();
void aeron_error_dll_thread_detach();
void aeron_error_dll_process_detach();
void aeron_err_set_windows(
    int errcode, const char *function, const char *filename, int line_number, const char *format, ...);
#define __FILENAME__ (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)
#define AERON_SET_ERR_WIN(errcode, fmt, ...) aeron_err_set_windows(errcode, __func__, __FILENAME__, __LINE__, fmt, __VA_ARGS__)
#else
#define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
#endif

#define AERON_SET_ERR(errcode, fmt, ...) aeron_err_set(errcode, __func__, __FILENAME__, __LINE__, fmt, __VA_ARGS__)
#define AERON_APPEND_ERR(fmt, ...) aeron_err_append(__func__, __FILENAME__, __LINE__, fmt, __VA_ARGS__)
#define AERON_NULL_STR(v) NULL == v ? "NULL" : "OK"

#endif //AERON_ERROR_H


text:
use std::{f64};

fn main() {
	// create a struct variable
	let mut circle1 = Circle {
		x:10.0,radius : 10.0
	};

	println!("x:{},radius : {}", circle1.x, circle1.radius );

	println!("Radius : {}", get_radius(&circle1) );

	println!("x : {}", circle1.get_x());
}

// define your custom user datatype
struct Circle {
	x : f64,
	radius : f64,
}

fn get_radius(c1 : &Circle) -> f64{
	c1.radius
}

// recommended way of creating structs
impl Circle {
	// pub makes this function public which makes it accessible outsite the scope {}
	pub fn get_x(&self) -> f64 {
		self.x
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/main_close_up" android:state_pressed="false"/>
    <!-- 设置按钮未被按下时的图片 -->
    <item android:drawable="@drawable/main_close_down" android:state_pressed="true"/>
    <!-- 设置按钮按下时的图片 -->

</selector>


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author awzurn
 */
public class classexerise extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * GET and
     * POST methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /*
             * TODO output your page here. You may use following sample code.
             */
            out.println("");
            out.println("");
            out.println("<meta content=\"text/html; charset=ISO-8859-1\"http-equiv=\"content-type\"");
            out.println("<title>classexerise.htm</title>");
            out.println("");
            out.println("");
            out.println("
");
            out.println("<form action=\"createTable\" name=\"Information\">");
            out.println("
");
            out.println("
");
            out.println("
");
            out.println("Enter Your Name
	");
            out.println("<input name=\"Name\">

");
            out.println("
Enter Number of Rows
	");
            out.println("<input value=\"1\" name=\"Rows\">

");
            out.println("
Enter Number of Columns
	");
            out.println("<input name=\"Columns\" value=\"1\">
");
            out.println("
<input name=\"Submit\" value=\"Submit\" type=\"submit\">
	");
            out.println("<input name=\"Reset\" value=\"Reset\" type=\"reset\">

");
            out.println("
");
            out.println("
");
            out.println("
");
            out.println("</form>");
            out.println("");
            out.println("");

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * GET method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * POST method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}


text:
passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});


text:
package com.codepath.apps.restclienttemplate;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ProgressBar;

import com.codepath.apps.restclienttemplate.models.Tweet;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.parceler.Parcels;

import java.util.ArrayList;

import cz.msebera.android.httpclient.Header;

public class TimelineActivity extends AppCompatActivity {
    private TwitterClient client;
    private SwipeRefreshLayout swipeContainer;
    TweetAdapter tweetAdapter;
    ArrayList<Tweet> tweets;
    RecyclerView rvTweets;
    private final int REQUEST_CODE = 100;
    MenuItem miActionProgressItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_timeline);

        swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer);
        // Setup refresh listener which triggers new data loading
        swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // Your code to refresh the list here.
                // Make sure you call swipeContainer.setRefreshing(false)
                // once the network request has completed successfully.
                showProgressBar();
                fetchTimelineAsync(0);

            }
        });
        // Configure the refreshing colors
        swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);

        client = TwitterApp.getRestClient();
        // find recyclerview
        rvTweets = (RecyclerView) findViewById(R.id.rvTweet);
        // init arraylist
        tweets = new ArrayList<>();
        // construct adapter
        tweetAdapter = new TweetAdapter(tweets);

        // setup recyclerview (layout manager, use adapter)
        rvTweets.setLayoutManager(new LinearLayoutManager(this));

        // set the adapter
        rvTweets.setAdapter(tweetAdapter);
        populateTimeline();

    }

    public void showProgressBar() {
        // Show progress item
        miActionProgressItem.setVisible(true);
    }

    public void hideProgressBar() {
        // Hide progress item
        miActionProgressItem.setVisible(false);
    }
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // Store instance of the menu item containing progress
        miActionProgressItem = menu.findItem(R.id.miActionProgress);
        // Extract the action-view from the menu item
        ProgressBar v =  (ProgressBar) MenuItemCompat.getActionView(miActionProgressItem);
        // Return to finish
        return super.onPrepareOptionsMenu(menu);
    }

    public void fetchTimelineAsync(int page) {
        // Send the network request to fetch the updated data
        // `client` here is an instance of Android Async HTTP
        // getHomeTimeline is an example endpoint.

        client.getHomeTimeline(0, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                // super.onSuccess(statusCode, headers, response);
                // Remember to CLEAR OUT old items before appending in the new ones
                tweetAdapter.clear();
                // ...the data has come back, add new items to your adapter...
                // for each entry deserialize json object
                for (int i = 0; i < response.length(); i++) {
                    // convert each object to tweet model
                    // add tweet model to data structure
                    // notify adapter model was added
                    try{
                        Tweet tweet = Tweet.fromJSON(response.getJSONObject(i));
                        tweets.add(tweet);
                        tweetAdapter.notifyItemInserted(tweets.size() - 1);

                    } catch(JSONException e) {
                        e.printStackTrace();
                    }

                }
                tweetAdapter.addAll(tweets);
                // Now we call setRefreshing(false) to signal refresh has finished
                swipeContainer.setRefreshing(false);
                hideProgressBar();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                Log.d("DEBUG", "Fetch timeline error: " + errorResponse.toString());
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                Log.d("DEBUG", "Fetch timeline error: " + errorResponse.toString());

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    public void onComposeAction(MenuItem mi) {
        // handle click here
        Intent i = new Intent(TimelineActivity.this, ComposeActivity.class);
        startActivityForResult(i, REQUEST_CODE);
    }

    private void populateTimeline() {
        client.getHomeTimeline(0, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                Log.d("TwitterClient", response.toString());
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                //Log.d("TwitterClient", response.toString());
                // iterate through json array

                // for each entry deserialize json object
                for (int i = 0; i < response.length(); i++) {
                    // convert each object to tweet model
                    // add tweet model to data structure
                    // notify adapter model was added
                    try{
                        Tweet tweet = Tweet.fromJSON(response.getJSONObject(i));
                        tweets.add(tweet);
                        tweetAdapter.notifyItemInserted(tweets.size() - 1);
                    } catch(JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.d("TwitterClient", responseString);
                throwable.printStackTrace();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                Log.d("TwitterClient", errorResponse.toString());
                throwable.printStackTrace();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
                Log.d("TwitterClient", errorResponse.toString());
                throwable.printStackTrace();
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // REQUEST_CODE is defined above
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
            // Extract name value from result extras
            Tweet tweet = Parcels.unwrap(data.getParcelableExtra(Tweet.class.getSimpleName()));
            int code = data.getExtras().getInt("code", 0);
            tweets.add(0, tweet);
            tweetAdapter.notifyItemInserted(0);
            rvTweets.scrollToPosition(0);
            // Toast the name to display temporarily on screen
            // Toast.makeText(this, name, Toast.LENGTH_SHORT).show();

        }
    }
}


text:
(function(data) {
  define(['iwc', 'handlebars', 'jquery'], function(iwc, handlebars, $) {
    iwc.component({

      // The name of this component
      name: 'hello-button',

      // The markup template is compiled as a handlebars template
      template: handlebars.default.compile(data.markup),

      // Stylesheet
      styles: data.styles,

      // This is the model template for the component
      model: {
        value: 0,
        clicks: []
      },

      // This is the view template for the component
      view: {
        target: '.target',
        'data-loaded': null
      },

      // Find all the nodes in the DOM to apply this to
      targets: function() {
        return $('.component--hello-button');
      },

      // Return an array to detect state changes on the component
      state: function(ref) {
        return [ref.model.value]
      },

      // Update the component from the model
      update: function(ref) {
        var view = ref.view;
        var model = ref.model;
        view.target.html(model.value);
      },

      // Invoke this setup on each component instance
      instance: function(ref) {
        var root = ref.root;
        var model = ref.model;
        var view = ref.view;

        // Populate view
        view.target = $(root).find('.target');

        // Update on click events
        $(root).find('button').click(function(e) {
          console.log(model);
          model.value += 1;
          for (var i = 0; i < model.clicks.length; ++i) {
            model.clicks[i](e, root, model, view);
          }
          ref.update();
        });

        // Run custom init script when loaded
        if (view['data-loaded']) {
          eval(view['data-loaded']);
        }
      }
    });
  });
})({
  styles: ".component--hello-button {\n    padding: 10px;\n    border-radius: 5px;\n    background: #efefef;\n    font-family: sans-serif;\n    border: 1px solid #9f9f9f;\n    text-transform: uppercase;\n}\n\n.component--hello-button .clicks {\n    float: right;\n    font-size: 0.8em;\n}\n\n.component--hello-button button {\n    width: 500px;\n    height: 50px;\n    line-height: 50px;\n    font-size: 1.2em;\n    font-weight: bold;\n}",
  markup: "
\n    <button>{{data.data-header}}</button>\n
clicks: {{model.value}}
\n
"
});


text:
#include <aws/signer/model/SignedObject.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace signer
{
namespace Model
{

SignedObject::SignedObject() :
    m_s3HasBeenSet(false)
{
}

SignedObject::SignedObject(JsonView jsonValue) :
    m_s3HasBeenSet(false)
{
  *this = jsonValue;
}

SignedObject& SignedObject::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("s3"))
  {
    m_s3 = jsonValue.GetObject("s3");

    m_s3HasBeenSet = true;
  }

  return *this;
}

JsonValue SignedObject::Jsonize() const
{
  JsonValue payload;

  if(m_s3HasBeenSet)
  {
   payload.WithObject("s3", m_s3.Jsonize());

  }

  return payload;
}

} // namespace Model
} // namespace signer
} // namespace Aws


text:
{-# LANGUAGE
      DeriveFunctor,
      TupleSections
  #-}

{-|
Module      : Data.Monoid.Zero
Copyright   : (c) 2015 Maciej Piróg
License     : MIT
Maintainer  : maciej.adam.pirog@gmail.com
Stability   : experimental

Typeclasses for monoids with (left, right, or \"two-sided\") zero
elements (aka absorbing elements) and their free implementations.
Just like monoids are related to backtracking computations, right
zero monoids are related to backtracking computation with Prolog's
cut operator (see the module "Data.List.Cut").
-}
module Data.Monoid.Zero
  (
    -- * Zero monoids
    MonoidZero(..),
    AdjoinZero(..),
    -- * Left zero monoids
    MonoidLZero(..),
    AdjoinLZero(..),
    -- * Right zero monoids
    MonoidRZero(..),
    AdjoinRZero(..),
  )
  where

import Control.Applicative (pure, (<$>))
import Data.Foldable (Foldable (..))
import Data.Traversable (Traversable (..))
import Data.Monoid (Monoid(..), Product(..), All(..), Any(..))

--
-- MONOID ZERO
--

-- | Class of zero monoids. Instances should satisfy:
--
-- * @'mappend' zero m = zero@
--
-- * @'mappend' m zero = zero@
class (Monoid m) => MonoidZero m where
  zero :: m

-- | A zero monoid freely generated by a monoid.
newtype AdjoinZero m = AdjoinZero { adjoinZero :: Maybe m }
 deriving (Functor, Eq, Ord)

instance (Show m) => Show (AdjoinZero m) where
  show (AdjoinZero (Just m)) = show m
  show (AdjoinZero Nothing)  = "*"

instance Foldable AdjoinZero where
  foldMap f (AdjoinZero (Just m)) = f m
  foldMap f (AdjoinZero Nothing)  = mempty

instance Traversable AdjoinZero where
  traverse f (AdjoinZero (Just a)) = AdjoinZero . Just <$> f a
  traverse f (AdjoinZero Nothing)  = pure $ AdjoinZero Nothing

instance (Monoid m) => Monoid (AdjoinZero m) where
  mempty = AdjoinZero $ Just $ mempty
  AdjoinZero Nothing `mappend` _     = AdjoinZero Nothing
  _ `mappend` AdjoinZero Nothing     = AdjoinZero Nothing
  AdjoinZero (Just m) `mappend` AdjoinZero (Just n) =
    AdjoinZero $ Just (m `mappend` n)

instance (Monoid m) => MonoidZero (AdjoinZero m) where
  zero = AdjoinZero Nothing

instance (Monoid m) => MonoidLZero (AdjoinZero m) where
  lzero = AdjoinZero Nothing

instance (Monoid m) => MonoidRZero (AdjoinZero m) where
  rzero = AdjoinZero Nothing

instance (Num n) => MonoidZero (Product n) where
  zero = Product 0

instance MonoidZero All where
  zero = All False

instance MonoidZero Any where
  zero = Any True

instance MonoidZero () where
  zero = ()

instance (MonoidZero a, MonoidZero b) => MonoidZero (a, b) where
  zero = (zero, zero)

instance (MonoidZero a, MonoidZero b, MonoidZero c) => MonoidZero (a, b, c) where
  zero = (zero, zero, zero)

instance (MonoidZero a, MonoidZero b, MonoidZero c, MonoidZero d) => MonoidZero (a, b, c, d) where
  zero = (zero, zero, zero, zero)

instance (MonoidZero a, MonoidZero b, MonoidZero c, MonoidZero d, MonoidZero e) => MonoidZero (a, b, c, d, e) where
  zero = (zero, zero, zero, zero, zero)

--
-- MONOID LZERO
--

-- | Class of left zero monoids. Instances should satisfy:
--
-- * @'mappend' m lzero = lzero@
class (Monoid m) => MonoidLZero m where
  lzero :: m

-- | A left zero monoid freely generated by a monoid.
newtype AdjoinLZero m = AdjoinLZero { unAdjoinLZero :: (Bool, m) }
 deriving (Functor, Eq, Ord)

instance Foldable AdjoinLZero where
  foldMap f (AdjoinLZero (_, a)) = f a

instance Traversable AdjoinLZero where
  traverse f (AdjoinLZero (b, a)) = AdjoinLZero . (b, ) <$> f a

instance (Show m) => Show (AdjoinLZero m) where
  show (AdjoinLZero (b, m)) = (if b then "*" else "") ++ show m

instance (Monoid m) => Monoid (AdjoinLZero m) where
  mempty = AdjoinLZero (False, mempty)
  _ `mappend` AdjoinLZero (True, n) = AdjoinLZero (True, n)
  AdjoinLZero (b, m) `mappend` AdjoinLZero (False, n) =
      AdjoinLZero (b, m `mappend` n)

instance (Monoid m) => MonoidLZero (AdjoinLZero m) where
  lzero = AdjoinLZero (True, mempty)

instance (Num n) => MonoidLZero (Product n) where
  lzero = Product 0

instance MonoidLZero All where
  lzero = All False

instance MonoidLZero Any where
  lzero = Any True

instance MonoidLZero () where
  lzero = ()

instance (MonoidLZero a, MonoidLZero b) => MonoidLZero (a, b) where
  lzero = (lzero, lzero)

instance (MonoidLZero a, MonoidLZero b, MonoidLZero c) => MonoidLZero (a, b, c) where
  lzero = (lzero, lzero, lzero)

instance (MonoidLZero a, MonoidLZero b, MonoidLZero c, MonoidLZero d) => MonoidLZero (a, b, c, d) where
  lzero = (lzero, lzero, lzero, lzero)

instance (MonoidLZero a, MonoidLZero b, MonoidLZero c, MonoidLZero d, MonoidLZero e) => MonoidLZero (a, b, c, d, e) where
  lzero = (lzero, lzero, lzero, lzero, lzero)

--
-- MONOID RZERO
--

-- | Class of right zero monoids. Instances should satisfy:
--
-- * @'mappend' rzero m = rzero@
class (Monoid m) => MonoidRZero m where
  rzero :: m

-- | A right zero monoid freely generated by a monoid.
newtype AdjoinRZero m = AdjoinRZero { unAdjoinRZero :: (m, Bool) }
 deriving (Functor, Eq, Ord)

instance Foldable AdjoinRZero where
  foldMap f (AdjoinRZero (a, _)) = f a

instance Traversable AdjoinRZero where
  traverse f (AdjoinRZero (a, b)) = AdjoinRZero . (, b) <$> f a

instance (Show m) => Show (AdjoinRZero m) where
  show (AdjoinRZero (m, b)) = show m ++ (if b then "*" else "")

instance (Monoid m) => Monoid (AdjoinRZero m) where
  mempty = AdjoinRZero (mempty, False)
  AdjoinRZero (m, True)  `mappend` _ = AdjoinRZero (m, True)
  AdjoinRZero (m, False) `mappend` AdjoinRZero (n, b) =
    AdjoinRZero (m `mappend` n, b)

instance (Monoid m) => MonoidRZero (AdjoinRZero m) where
  rzero = AdjoinRZero (mempty, True)

instance (Num n) => MonoidRZero (Product n) where
  rzero = Product 0

instance MonoidRZero All where
  rzero = All False

instance MonoidRZero Any where
  rzero = Any True

instance MonoidRZero () where
  rzero = ()

instance (MonoidRZero a, MonoidRZero b) => MonoidRZero (a, b) where
  rzero = (rzero, rzero)

instance (MonoidRZero a, MonoidRZero b, MonoidRZero c) => MonoidRZero (a, b, c) where
  rzero = (rzero, rzero, rzero)

instance (MonoidRZero a, MonoidRZero b, MonoidRZero c, MonoidRZero d) => MonoidRZero (a, b, c, d) where
  rzero = (rzero, rzero, rzero, rzero)

instance (MonoidRZero a, MonoidRZero b, MonoidRZero c, MonoidRZero d, MonoidRZero e) => MonoidRZero (a, b, c, d, e) where
  rzero = (rzero, rzero, rzero, rzero, rzero)