text:
package nodes.learning

import java.io.File

import breeze.linalg._
import breeze.numerics._
import breeze.stats._
import org.apache.spark.rdd.RDD
import pipelines._
import utils.MatrixUtils
import utils.external.EncEval

/**
 * A Mixture of Gaussians, usually computed via some clustering process.
 *
 * @param means Cluster centers.
 * @param variances Cluster variances (diagonal)
 * @param weights Cluster weights.
 */
case class GaussianMixtureModel(
    means: DenseMatrix[Double],
    variances: DenseMatrix[Double],
    weights: DenseVector[Double],
    weightThreshold: Double = 1e-4)
  extends Transformer[DenseVector[Double],DenseVector[Double]] {

  private val gmmMeans = means.t
  private val gmmVars = variances.t
  private val gmmWeights = weights.toDenseMatrix

  val k = means.cols
  val dim = means.rows

  require(means.rows == variances.rows && means.cols == variances.cols, "GMM means and variances must be the same size.")
  require(weights.length == k, "Every GMM center must have a weight.")

  /**
   * Returns (thresholded) assignments to each cluster.
   * @param in A Vector
   * @return The thresholded assignments of the vector according to the mixture model.
   */
  def apply(in: DenseVector[Double]): DenseVector[Double] = {
    // TODO: Could maybe do more efficient single-item implementation
    apply(in.asDenseMatrix).toDenseVector
  }

  def apply(X: DenseMatrix[Double]): DenseMatrix[Double] = {
    // gather data statistics
    val numSamples = X.rows
    val numFeatures = X.cols
    val XSq = X :* X

    /*
    compute the squared malhanobis distance for each gaussian.
    sq_mal_dist(i,j) || x_i - mu_j||_Lambda^2.  I am the master of
    computing Euclidean distances without for loops.
    */
    val sqMahlist = (XSq * gmmVars.map(0.5 / _).t) - (X * (gmmMeans :/ gmmVars).t) + (DenseMatrix.ones[Double](numSamples, 1) * (sum(gmmMeans :* gmmMeans :/ gmmVars, Axis._1).t :* 0.5))

    // compute the log likelihood of the approximate posterior
    val llh = DenseMatrix.ones[Double](numSamples, 1) * (-0.5 * numFeatures * math.log(2 * math.Pi) - 0.5 * sum(log(gmmVars), Axis._1).t + log(gmmWeights)) - sqMahlist

    /*
    if we make progress, update our pseudo-likelihood for the E-step.
    by shifting the llh to be peaked at 0, we avoid nasty numerical
    overflows.
    */
    llh(::, *) -= max(llh(*, ::))
    exp.inPlace(llh)
    llh(::, *) :/= sum(llh, Axis._1)
    var q = llh

    /*
    aggressive posterior thresholding: suggested by Xerox.  Thresholds
    the really small weights to sparsify the assignments.
    */
    q = q.map(x => if (x > weightThreshold) x else 0.0)
    q(::, *) :/= sum(q, Axis._1)

    q
  }

  override def apply(in: RDD[DenseVector[Double]]): RDD[DenseVector[Double]] = {
    in.mapPartitions { partition =>
      val assignments = apply(MatrixUtils.rowsToMatrix(partition))
      MatrixUtils.matrixToRowArray(assignments).iterator
    }
  }
}

/**
 * Fit a Gaussian Mixture model to Data.
 *
 * @param k Number of centers to estimate.
 */
class GaussianMixtureModelEstimator(k: Int) extends Estimator[DenseVector[Double], DenseVector[Double]] {

  /**
   * Currently this model works on items that fit in local memory.
   * @param samples
   * @return A PipelineNode (Transformer) which can be called on new data.
   */
  def fit(samples: RDD[DenseVector[Double]]): GaussianMixtureModel = {
    fit(samples.collect)
  }

  /**
   * Fit a Gaussian mixture model with `k` centers to a sample array.
   *
   * @param samples Sample Array - all elements must be the same size.
   * @return A Gaussian Mixture Model.
   */
  def fit(samples: Array[DenseVector[Double]]): GaussianMixtureModel = {
    val extLib = new EncEval
    val nDim = samples(0).length

    // Flatten this thing out.
    val sampleFloats = samples.map(_.toArray.map(_.toFloat))
    val res = extLib.computeGMM(k, nDim, sampleFloats.flatten)

    val meanSize = k*nDim
    val varSize = k*nDim
    val coefSize = k*nDim

    // Each array region is expected to be centroid-major.
    val means = convert(new DenseMatrix(nDim, k, res.slice(0, meanSize)), Double)
    val vars = convert(new DenseMatrix(nDim, k, res.slice(meanSize, meanSize+varSize)), Double)
    val coefs = convert(new DenseVector(res.slice(meanSize+varSize, meanSize+varSize+coefSize)), Double)

    new GaussianMixtureModel(means, vars, coefs)
  }
}

object GaussianMixtureModel {
  def load(meanFile: String, varsFile: String, weightsFile: String): GaussianMixtureModel = {

    val means = csvread(new File(meanFile))
    val variances = csvread(new File(varsFile))
    val weights = csvread(new File(weightsFile)).toDenseVector

    new GaussianMixtureModel(means, variances, weights)
  }
}


text:
from django.db import models
from django.core.urlresolvers import reverse
from django.core.validators import RegexValidator

# Create your models here.

class Scavo(models.Model):
    '''Scavo archeologico.

    Corrisponde al campo DSC e alla relativa scheda di authority
    file.'''

    AREA_CHOICES = (
        ('TEATR', 'Teatro'),
        ('TERME', 'Terme'),
        ('GAS', 'Gas'),
        ('CAVAL', 'Cavalcavia'),
        ('NECRO', 'Necropoli'),
        ('VALTA', 'Ventimiglia alta'),
        ('EXTRA', 'Scavi extraurbani'),
        )

    area = models.CharField(max_length=5, choices=AREA_CHOICES)
    settore = models.CharField(max_length=50)
    scan = models.CharField('SCAN',
                            help_text='''
Denominazione dello scavo. Es."Albintimilium, teatro, parodos est".
Seguire sempre l'ordine dal generale al particolare.''',
                            max_length=45,
                            unique=True)
    scad = models.TextField('SCAD',
                            help_text='Descrizione')
    luogo = models.CharField('Località', max_length=100)
    dsch = models.CharField('DSCH',
                            help_text='Sigla identificativa. Es. "VGF", "XXSP"',
                            max_length=8,
                            blank=True)

    def __unicode__(self):
        return self.scan

    class Meta:
        verbose_name_plural = "scavi"

class ContestoScavo(models.Model):
    '''Unità stratigrafica, strato, livello o altro.

    Un qualunque tipo di indicazione sulla provenienza del materiale
    di scavo, in forma sintetica.'''

    scavo = models.ForeignKey(Scavo)
    numero_nome = models.CharField('Numero o nome',
                                   help_text='Es. "US 551", "Strato II, parodos est, 3° taglio".',
                                   max_length=50)

    def __unicode__(self):
        return "%s - %s" % (self.scavo, self.numero_nome)

    class Meta:
        verbose_name_plural = "contesti di scavo"

class Vano(models.Model):
    '''Un vano all'interno di un magazzino.'''

    ENEL = 'ENEL'
    GAS = 'GAS'
    ANTIQUARIUM = 'ANTIQ'

    MAGAZZINO_CHOICES = (
        (ENEL, 'Magazzino ENEL'),
        (GAS, 'Magazzino Gas'),
        (ANTIQUARIUM, 'Magazzino Antiquarium'),
        )

    numero = models.IntegerField('Numero del vano')
    magazzino = models.CharField(max_length=5, choices=MAGAZZINO_CHOICES)
    desc = models.TextField('Descrizione')

    def __unicode__(self):
        return u'%s - Vano %d' % (self.get_magazzino_display(), self.numero)

    class Meta:
        verbose_name_plural = 'vani'

class CassaManager(models.Manager):
    def get_by_natural_key(self, magazzino, numero):
        return self.get(ldcn__magazzino=magazzino, number=numero)

class Cassa(models.Model):
    '''Basata sul modello "Scheda di cassa".

    Fa riferimento alla scheda ICCD TMA (Tabella materiali).'''

    # informazioni di base
    number = models.CharField('Numero di cassa', max_length=50)
    numscavo = models.IntegerField(
        'Numero di cassa dello scavo',
        blank=True,
        null=True,
        help_text='Il numero di cassa nella numerazione dello scavo, se presente')

    # CD - Codici
    tsk = models.CharField('TSK',
                           help_text='Tipo scheda',
                           max_length=4,
                           default='TMA',
                           editable=False)
    LIR_CHOICES = (
        ('I', 'Inventario'),
        ('P', 'Precatalogo'),
        ('C', 'Catalogo'),
        )
    lir = models.CharField('LIR',
                           help_text='Livello ricerca',
                           max_length=5,
                           choices=LIR_CHOICES,
                           default='I')
    ## NCT - Codice univoco
    NCTR_CODICI = (
        # codici ICCD
        ('01', 'Piemonte'),
        ('02', "Valle d'Aosta"),
        ('03', 'Lombardia'),
        ('04', 'Trentino-Alto Adige'),
        ('05', 'Veneto'),
        ('06', 'Friuli-Venezia Giulia'),
        ('07', 'Liguria'),
        ('08', 'Emilia-Romagna'),
        ('09', 'Toscana'),
        ('10', 'Umbria'),
        ('11', 'Marche'),
        ('12', 'Lazio'),
        ('13', 'Abruzzo'),
        ('14', 'Molise'),
        ('15', 'Campania'),
        ('16', 'Puglia'),
        ('17', 'Basilicata'),
        ('18', 'Calabria'),
        ('19', 'Sicilia'),
        ('20', 'Sardegna'),
        )
    nctr = models.CharField('NCTR',
                            help_text='Codice regione',
                            max_length=2,
                            choices=NCTR_CODICI,
                            default='07')
    nctn = models.CharField('NCTN',
                            help_text='Numero catalogo generale',
                            max_length=8,
                            unique=True,
                            validators=[RegexValidator('[0-9]'*8)],
                            default='00000000')
    esc = models.CharField('ESC',
                           help_text='Ente schedatore',
                           max_length=25,
                           default='S19')
    ecp = models.CharField('ECP',
                           help_text='Ente competente',
                           max_length=25,
                           default='S19')

    # OG - Oggetto
    ## OGT - Oggetto
    ### OGTD = materiale proveniente da Unità Stratigrafica
    ### OGTM - Definizione materiale componente = ceramica/vetro...

    # RE - Modalità di reperimento
    ## DSC - Dati di scavo
    dscd = models.CharField('DSCD',
                            help_text='''
Data in cui è stato effettuato l'intervento di scavo archeologico,
nel formato AAAA/MM/GG. Esempi: 2002/03/25, 2004/00/00, 2005/07/21-2005/10/12.''',
                            max_length=50,
                            validators=[RegexValidator('[0-9][0-9][0-9][0-9]/[0-1][0-9]/[0-3][0-9]')])

    # LC - Localizzazione geografico-amministrativa
    ## PVC LOCALIZZAZIONE GEOGRAFICO-AMMINISTRATIVA ATTUALE
    pvcs = models.CharField('PVCS', help_text='Stato', max_length=50, default='Italia')
    pvcr = models.CharField('PVCR', help_text='Regione', max_length=25, default='Liguria')
    pvcp = models.CharField('PVCP', help_text='Provincia', max_length=3, default='IM')
    pvcc = models.CharField('PVCC', help_text='Comune', max_length=50, default='Ventimiglia')

    # LDC - Collocazione specifica
    ldct = models.CharField('LDCT',
                            help_text='Tipologia del contenitore',
                            max_length=25,
                            default='magazzino')
    ldcn = models.ForeignKey(Vano,
                             verbose_name='LDCN',
                             help_text='Magazzino e vano')
    ldcs = models.CharField('LDCS',
                            help_text='Specifiche: corridoio, colonna',
                            max_length=50)

    # DT CRONOLOGIA
    ## DTZ CRONOLOGIA GENERICA
    dtzg = models.CharField('DTZG',
                            help_text='Fascia cronologica di riferimento',
                            max_length=50)

    DTM_CHOICES = ((c, c) for c in
        (
            'analisi dei materiali',
            'analisi chimico-fisica',
            'analisi stilistica',
            'bibliografia',
            'bollo',
            'contesto',
            'data',
            'dati epigrafici',
            'documentazione',
            'tradizione orale',
            'NR (recupero pregresso)'
            ))

    dtm = models.CharField('DTM',
                           help_text='Motivazione cronologia',
                           max_length=250,
                           choices=DTM_CHOICES)

    # MA MATERIALE
    ## MAC MATERIALE COMPONENTE
    macc = models.CharField('MACC',
                            help_text='Categoria: es. ceramica oppure ceramica/vetro/metallo',
                            max_length=100)
    macq = models.CharField('MACQ', help_text='Quantità', max_length=100)

    # TU CONDIZIONE GIURIDICA E VINCOLI
    ## CDG CONDIZIONE GIURIDICA
    cdgg = models.CharField('CDGG',
                            help_text='Condizione giuridica - Indicazione generica',
                            max_length=50,
                            default='proprietà Stato')

    # AD ACCESSO AI DATI
    ## ADS SPECIFICHE DI ACCESSO AI DATI
    ADSP_CHOICES = (
        ('1', 'intera scheda visibile'),
        ('2', 'limitazione per privacy e tutela')
        )
    adsp = models.CharField('ADSP',
                            help_text='Profilo di accesso',
                            max_length=1,
                            choices=ADSP_CHOICES,
                            default='1')
    adsm = models.CharField('ADSM',
                            help_text='Motivazione',
                            max_length=70,
                            default='dati liberamente accessibili')

    # FTA DOCUMENTAZIONE FOTOGRAFICA
    ftax = models.CharField('FTAX', help_text='genere', max_length=50)
    ftad = models.CharField('FTAD', help_text='data', max_length=25)
    ftat = models.TextField('FTAT', help_text='note', max_length=250)

    # DRA DOCUMENTAZIONE GRAFICA
    drax = models.CharField('DRAX', help_text='genere', max_length=25)
    drat = models.CharField('DRAT', help_text='tipo', max_length=50)
    drao = models.TextField('DRAO', help_text='note', max_length=250)
    dras = models.CharField('DRAS', help_text='scala', max_length=25)
    drac = models.CharField('DRAC', help_text='collocazione', max_length=50)
    draa = models.CharField('DRAA', help_text='autore', max_length=50)
    drad = models.CharField('DRAD', help_text='data', max_length=25)

    # CM COMPILAZIONE
    ## CMP COMPILAZIONE
    cmpd = models.DateField('CMPD', help_text='Data')
    cmpn = models.CharField('CMPN', help_text='Nome', max_length=70)
    fur = models.CharField('FUR', help_text='Funzionario responsabile', max_length=70)

    objects = CassaManager()

    def natural_key(self):
        return (self.number)

    def __unicode__(self):
        return u'Cassa {}'.format(self.number)

    class Meta:
        verbose_name_plural = "casse"
        unique_together = (('ldcn', 'number'),)

class FormaManager(models.Manager):
    def get_by_natural_key(self, famiglia, forma):
        return self.get(famiglia=famiglia, forma=forma)

class FormaDiMateriale(models.Model):
    '''Una forma di oggetto.

    Corrisponde al campo OGTD della scheda TMA.'''

    famiglia = models.CharField(max_length=100)
    forma = models.CharField('OGTD',
                             help_text='Forma',
                             max_length=100)

    objects = FormaManager()

    def natural_key(self):
        return (self.famiglia, self.forma)

    def __unicode__(self):
        return self.forma

    @staticmethod
    def autocomplete_search_fields():
        return ("id__iexact", "forma__icontains", 'famiglia__icontains')

    class Meta:
        verbose_name_plural = 'forme di materiale'
        ordering = ['pk']
        unique_together = (('famiglia', 'forma'),)

class ClasseManager(models.Manager):
    def get_by_natural_key(self, sigla):
        return self.get(sigla=sigla)

class ClasseDiMateriale(models.Model):
    '''Classi di materiale.

    Corrisponde al campo MACL della scheda TMA.'''

    classe = models.CharField(help_text='Classe - MACL',
                              max_length=100)
    sigla = models.CharField(max_length=12,
                             help_text='Sigla della classe',
                             unique=True)
    famiglia = models.CharField(max_length=50, blank=True)
    forme = models.ManyToManyField(FormaDiMateriale, blank=True)

    objects = ClasseManager()

    def natural_key(self):
        return self.sigla

    def __unicode__(self):
        return ' - '.join([self.sigla, self.famiglia, self.classe])

    @staticmethod
    def autocomplete_search_fields():
        return ('id__iexact',
                'sigla__icontains',
                'classe__icontains',
                'famiglia__icontains')

    class Meta:
        verbose_name_plural = "classi di materiale"
        ordering = ['pk']
        unique_together = (('classe', 'famiglia'),)

class MaterialeInCassa(models.Model):
    '''Singoli materiali in una cassa.'''

    cassa = models.ForeignKey(Cassa)
    contesto = models.ForeignKey(ContestoScavo)
    macl = models.ForeignKey(ClasseDiMateriale, verbose_name='MACL - Classe')
    macd = models.ForeignKey(FormaDiMateriale,  verbose_name='MACD - Forma')
    macp = models.CharField('MACP- Tipologia',
                            max_length=200,
                            help_text='Tipologia, es "Lamboglia 9" o "Dressel 23"',
                            blank=True)

    macn_isr = models.CharField('ISR - Iscrizioni', max_length=100, blank=True)
    macn = models.CharField('MACN - Annotazioni', max_length=100, blank=True)

    # conteggi

    help_text_inv = '''Numeri singoli separati da barre es. 123/124/125
oppure intervalli di numeri separati da trattino es. 123-126'''

    orli = models.IntegerField(default=0)
    numeri_inventario_orli = models.CharField(max_length=500,
                                              help_text=help_text_inv,
                                              blank=True)

    anse = models.IntegerField(default=0)
    numeri_inventario_anse = models.CharField(max_length=500,
                                              help_text=help_text_inv,
                                              blank=True)

    fondi = models.IntegerField(default=0)
    numeri_inventario_fondi = models.CharField(max_length=500,
                                               help_text=help_text_inv,
                                               blank=True)

    piedi = models.IntegerField(default=0)
    numeri_inventario_piedi = models.CharField(max_length=500,
                                               help_text=help_text_inv,
                                               blank=True)

    pareti = models.IntegerField(default=0)
    numeri_inventario_pareti = models.CharField(max_length=500,
                                                help_text=help_text_inv,
                                                blank=True)

    nme = models.IntegerField('NME',
                              help_text='Numero minimo di esemplari',
                              default=1)

    def __unicode__(self):
        return u'%s in %s da %s in %s' % (self.macd, self.macl, self.contesto, self.cassa)

    def get_absolute_url(self):
            return reverse('materialeincassa-detail', kwargs={'pk': self.pk})

    class Meta:
        verbose_name_plural = "materiali in cassa"

redpajama_set_name: RedPajamaGithub


text:
package org.jbpm.persistence.processinstance;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.SequenceGenerator;
import javax.persistence.Transient;
import javax.persistence.Version;

import org.drools.core.common.InternalKnowledgeRuntime;
import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.core.impl.StatefulKnowledgeSessionImpl;
import org.drools.core.marshalling.impl.MarshallerReaderContext;
import org.drools.core.marshalling.impl.MarshallerWriteContext;
import org.drools.core.marshalling.impl.PersisterHelper;
import org.drools.core.marshalling.impl.ProcessMarshallerWriteContext;
import org.drools.core.marshalling.impl.ProtobufMarshaller;
import org.drools.persistence.Transformable;
import org.jbpm.marshalling.impl.JBPMMessages;
import org.jbpm.marshalling.impl.ProcessInstanceMarshaller;
import org.jbpm.marshalling.impl.ProcessMarshallerRegistry;
import org.jbpm.marshalling.impl.ProtobufRuleFlowProcessInstanceMarshaller;
import org.jbpm.process.instance.impl.ProcessInstanceImpl;
import org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl;
import org.kie.api.runtime.Environment;
import org.kie.api.runtime.process.ProcessInstance;

@Entity
@SequenceGenerator(name="processInstanceInfoIdSeq", sequenceName="PROCESS_INSTANCE_INFO_ID_SEQ")
public class ProcessInstanceInfo implements Transformable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator="processInstanceInfoIdSeq")
    @Column(name = "InstanceId")
    private Long                              processInstanceId;

    @Version
    @Column(name = "OPTLOCK")
    private int                               version;

    private String                            processId;
    private Date                              startDate;
    private Date                              lastReadDate;
    private Date                              lastModificationDate;
    private int                               state;

    @Lob
    @Column(length=2147483647)
    byte[]                                    processInstanceByteArray;

    @ElementCollection
    @CollectionTable(name="EventTypes", joinColumns=@JoinColumn(name="InstanceId"))
    @Column(name="element")
    private Set<String>                       eventTypes         = new HashSet<String>();

    @Transient
    ProcessInstance                           processInstance;

    @Transient
    Environment                               env;

    protected ProcessInstanceInfo() {
    }

    public ProcessInstanceInfo(ProcessInstance processInstance) {
        this.processInstance = processInstance;
        this.processId = processInstance.getProcessId();
        startDate = new Date();
    }

    public ProcessInstanceInfo(ProcessInstance processInstance,
                               Environment env) {
        this(processInstance);
        this.env = env;
    }

    /**
     * Added in order to satisfy Hibernate AND the JBPMorm.xml:

     *
 Hibernate needs getter/setters for a the field that's mapped.
     *

(field access is inefficient/dangerous, and not necessary)

     *
The JBPMorm.xml queries reference .processInstanceId as well.

     *

     * If we mapped the field using 'name="id"', the queries would thus fail.
     *

     * So instead of that, we just add the getters and use 'name="processInstanceId"'.
     * @return The processInstanceId field value.
     */
    public Long getProcessInstanceId() {
        return processInstanceId;
    }

    public void setProcessInstanceId(Long processInstanceId) {
        this.processInstanceId = processInstanceId;
    }

    public Long getId() {
        return processInstanceId;
    }

    public void setId(Long processInstanceId) {
        this.processInstanceId = processInstanceId;
    }

    public String getProcessId() {
        return processId;
    }

    public Date getStartDate() {
        return startDate;
    }

    public Date getLastModificationDate() {
        return lastModificationDate;
    }

    public Date getLastReadDate() {
        return lastReadDate;
    }

    public void updateLastReadDate() {
    	Date updateTo = new Date();
    	if (lastReadDate == null || lastReadDate.compareTo(updateTo) < 0) {
    		lastReadDate = updateTo;
    	} else {
    		lastReadDate = new Date(lastReadDate.getTime() + 1);
    	}
    }

    public int getState() {
        return state;
    }

    public ProcessInstance getProcessInstance(InternalKnowledgeRuntime kruntime,
                                              Environment env) {
    	return getProcessInstance(kruntime, env, false);
    }

    public ProcessInstance getProcessInstance(InternalKnowledgeRuntime kruntime,
                                              Environment env,
                                              boolean readOnly) {
        this.env = env;
        if ( processInstance == null ) {
            try {
                ByteArrayInputStream bais = new ByteArrayInputStream( processInstanceByteArray );
                MarshallerReaderContext context = new MarshallerReaderContext( bais,
                                                                               (InternalKnowledgeBase) kruntime.getKieBase(),
                                                                               null,
                                                                               null,
                                                                               ProtobufMarshaller.TIMER_READERS,
                                                                               this.env
                                                                              );
                ProcessInstanceMarshaller marshaller = getMarshallerFromContext( context );
            	context.wm = ((StatefulKnowledgeSessionImpl) kruntime).getInternalWorkingMemory();
                processInstance = marshaller.readProcessInstance(context);
                ((WorkflowProcessInstanceImpl) processInstance).setPersisted(false);
                if (readOnly) {
                    ((WorkflowProcessInstanceImpl) processInstance).disconnect();
                }
                context.close();
            } catch ( IOException e ) {
                e.printStackTrace();
                throw new IllegalArgumentException( "IOException while loading process instance: " + e.getMessage(),
                                                    e );
            }
        }
        return processInstance;
    }

    private ProcessInstanceMarshaller getMarshallerFromContext(MarshallerReaderContext context) throws IOException {
        ObjectInputStream stream = context.stream;
        String processInstanceType = stream.readUTF();
        return ProcessMarshallerRegistry.INSTANCE.getMarshaller( processInstanceType );
    }

    private void saveProcessInstanceType(MarshallerWriteContext context,
                                         ProcessInstance processInstance,
                                         String processInstanceType) throws IOException {
        ObjectOutputStream stream = context.stream;
        // saves the processInstance type first
        stream.writeUTF( processInstanceType );
    }

    public void transform() {
//    	if (processInstance == null) {
//    		return;
//    	}
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        boolean variablesChanged = false;
        try {
            ProcessMarshallerWriteContext context = new ProcessMarshallerWriteContext( baos,
                                                                         null,
                                                                         null,
                                                                         null,
                                                                         null,
                                                                         this.env );
            context.setProcessInstanceId(processInstance.getId());
            context.setState(processInstance.getState() == ProcessInstance.STATE_ACTIVE ?
                    ProcessMarshallerWriteContext.STATE_ACTIVE:ProcessMarshallerWriteContext.STATE_COMPLETED);

            String processType = ((ProcessInstanceImpl) processInstance).getProcess().getType();
            saveProcessInstanceType( context,
                                     processInstance,
                                     processType );
            ProcessInstanceMarshaller marshaller = ProcessMarshallerRegistry.INSTANCE.getMarshaller( processType );

            Object result = marshaller.writeProcessInstance( context,
                                                             processInstance);
            if( marshaller instanceof ProtobufRuleFlowProcessInstanceMarshaller && result != null ) {
                JBPMMessages.ProcessInstance _instance = (JBPMMessages.ProcessInstance)result;
                PersisterHelper.writeToStreamWithHeader( context,
                                                         _instance );
            }
            context.close();
        } catch ( IOException e ) {
            throw new IllegalArgumentException( "IOException while storing process instance "
        		+ processInstance.getId() + ": " + e.getMessage(), e );
        }
        byte[] newByteArray = baos.toByteArray();
        if ( variablesChanged || !Arrays.equals( newByteArray,
                                                 processInstanceByteArray ) ) {
            this.state = processInstance.getState();
            this.lastModificationDate = new Date();
            this.processInstanceByteArray = newByteArray;
            this.eventTypes.clear();
            for ( String type : processInstance.getEventTypes() ) {
                eventTypes.add( type );
            }
        }
        if (!processInstance.getProcessId().equals(this.processId)) {
    		this.processId = processInstance.getProcessId();
    	}
        ((WorkflowProcessInstanceImpl) processInstance).setPersisted(true);
    }

    @Override
    public boolean equals(Object obj) {
        if ( obj == null ) {
            return false;
        }
        if ( getClass() != obj.getClass() ) {
            return false;
        }
        final ProcessInstanceInfo other = (ProcessInstanceInfo) obj;
        if ( this.processInstanceId != other.processInstanceId && (this.processInstanceId == null || !this.processInstanceId.equals( other.processInstanceId )) ) {
            return false;
        }
        if ( this.version != other.version ) {
            return false;
        }
        if ( (this.processId == null) ? (other.processId != null) : !this.processId.equals( other.processId ) ) {
            return false;
        }
        if ( this.startDate != other.startDate && (this.startDate == null || !this.startDate.equals( other.startDate )) ) {
            return false;
        }
        if ( this.lastReadDate != other.lastReadDate && (this.lastReadDate == null || !this.lastReadDate.equals( other.lastReadDate )) ) {
            return false;
        }
        if ( this.lastModificationDate != other.lastModificationDate && (this.lastModificationDate == null || !this.lastModificationDate.equals( other.lastModificationDate )) ) {
            return false;
        }
        if ( this.state != other.state ) {
            return false;
        }
        if ( !Arrays.equals( this.processInstanceByteArray,
                             other.processInstanceByteArray ) ) {
            return false;
        }
        if ( this.eventTypes != other.eventTypes && (this.eventTypes == null || !this.eventTypes.equals( other.eventTypes )) ) {
            return false;
        }
        if ( this.processInstance != other.processInstance && (this.processInstance == null || !this.processInstance.equals( other.processInstance )) ) {
            return false;
        }
        if ( this.env != other.env && (this.env == null || !this.env.equals( other.env )) ) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 61 * hash + (this.processInstanceId != null ? this.processInstanceId.hashCode() : 0);
        hash = 61 * hash + this.version;
        hash = 61 * hash + (this.processId != null ? this.processId.hashCode() : 0);
        hash = 61 * hash + (this.startDate != null ? this.startDate.hashCode() : 0);
        hash = 61 * hash + (this.lastReadDate != null ? this.lastReadDate.hashCode() : 0);
        hash = 61 * hash + (this.lastModificationDate != null ? this.lastModificationDate.hashCode() : 0);
        hash = 61 * hash + this.state;
        hash = 61 * hash + Arrays.hashCode( this.processInstanceByteArray );
        hash = 61 * hash + (this.eventTypes != null ? this.eventTypes.hashCode() : 0);
        hash = 61 * hash + (this.processInstance != null ? this.processInstance.hashCode() : 0);
        hash = 61 * hash + (this.env != null ? this.env.hashCode() : 0);
        return hash;
    }

    public int getVersion() {
        return version;
    }

    public Set<String> getEventTypes() {
        return eventTypes;
    }

    public byte [] getProcessInstanceByteArray() {
        return processInstanceByteArray;
    }

    public void clearProcessInstance(){
        processInstance = null;
    }

    public Environment getEnv() {
        return env;
    }

    public void setEnv(Environment env) {
        this.env = env;
    }
}


text:
/*
 * Programmer:  Robb Matzke <matzke@llnl.gov>
 *              Thursday, July 30, 1998
 *
 * Purpose:	Determines if the modification time message is working
 *		properly.  Specifically, the code in H5O_mtime_decode() is
 *		very OS-dependent and this test tries to figure out if it's
 *		working properly.
 */
#include "h5test.h"
#include "H5srcdir.h"

const char *FILENAME[] = {
    "mtime",
    NULL
};

#define TESTFILE1       "tmtimeo.h5"
#define MTIME1          1055531866
#define TESTFILE2       "tmtimen.h5"
#define MTIME2          1041606478

/*-------------------------------------------------------------------------
 * Function:	main
 *
 * Purpose:	H5O_mtime_decode() test.
 *
 * Return:	Success:
 *
 *		Failure:
 *
 * Programmer:	Robb Matzke
 *              Thursday, July 30, 1998
 *
 * Modifications:
 *              Added checks for old and new modification time messages
 *              in pre-created datafiles (generated with gen_old_mtime.c and
 *              gen_new_mtime.c).
 *              Quincey Koziol
 *              Friday, January  3, 2003
 *
 *-------------------------------------------------------------------------
 */
int
main(void)
{
    hid_t	fapl, file, space, dset;
    hsize_t	size[1] = {2};
    time_t	now;
    struct tm	*tm;
    H5O_info_t	oi1, oi2;
    signed char	buf1[32], buf2[32];
    char	filename[1024];

    h5_reset();
    fapl = h5_fileaccess();

    TESTING("modification time messages");

    /* Create the file, create a dataset, then close the file */
    h5_fixname(FILENAME[0], fapl, filename, sizeof filename);
    if((file = H5Fcreate(filename, H5F_ACC_TRUNC, H5P_DEFAULT, fapl)) < 0)
        TEST_ERROR;
    if((space = H5Screate_simple(1, size, NULL)) < 0) TEST_ERROR;
    if((dset = H5Dcreate2(file, "dset", H5T_NATIVE_SCHAR, space, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT)) < 0)
        TEST_ERROR;
    now = HDtime(NULL);
    if(H5Dclose(dset) < 0) TEST_ERROR;
    if(H5Sclose(space) < 0) TEST_ERROR;
    if(H5Fclose(file) < 0) TEST_ERROR;

    /*
     * Open the file and get the modification time. We'll test the
     * H5Oget_info() arguments too: being able to stat something without
     * knowing its name.
     */
    h5_fixname(FILENAME[0], fapl, filename, sizeof filename);
    if((file = H5Fopen(filename, H5F_ACC_RDONLY, fapl)) < 0) TEST_ERROR;
    if(H5Oget_info_by_name(file, "dset", &oi1, H5P_DEFAULT) < 0) TEST_ERROR;
    if((dset = H5Dopen2(file, "dset", H5P_DEFAULT)) < 0) TEST_ERROR;
    if(H5Oget_info(dset, &oi2) < 0) TEST_ERROR;
    if(H5Dclose(dset) < 0) TEST_ERROR;
    if(H5Fclose(file) < 0) TEST_ERROR;

    /* Compare addresses & times from the two ways of calling H5Oget_info() */
    if(oi1.addr != oi2.addr || oi1.ctime != oi2.ctime) {
        H5_FAILED();
        puts("    Calling H5Oget_info() with the dataset ID returned");
        puts("    different values than calling it with a file and dataset");
        puts("    name.");
        goto error;
    }

    /* Compare times -- they must be within 60 seconds of one another */
    if(0 == oi1.ctime) {
        SKIPPED();
        puts("    The modification time could not be decoded on this OS.");
        puts("    Modification times will be mantained in the file but");
        puts("    cannot be queried on this system.  See H5O_mtime_decode().");
        return 0;
    } else if(HDfabs(HDdifftime(now, oi1.ctime)) > 60.0) {
        H5_FAILED();
        tm = HDlocaltime(&(oi1.ctime));
        HDstrftime((char*)buf1, sizeof buf1, "%Y-%m-%d %H:%M:%S", tm);
        tm = HDlocaltime(&now);
        HDstrftime((char*)buf2, sizeof buf2, "%Y-%m-%d %H:%M:%S", tm);
        printf("    got: %s\n    ans: %s\n", buf1, buf2);
        goto error;
    }
    PASSED();

    /* Check opening existing file with old-style modification time information
     * and make certain that the time is correct
     */
    TESTING("accessing old modification time messages");

    {
        char testfile[512]="";
        char *srcdir = HDgetenv("srcdir");

        if(srcdir && ((HDstrlen(srcdir) + strlen(TESTFILE1) + 1) < sizeof(testfile))){
            HDstrcpy(testfile, srcdir);
            HDstrcat(testfile, "/");
        }
        HDstrcat(testfile, TESTFILE1);
        file = H5Fopen(testfile, H5F_ACC_RDONLY, H5P_DEFAULT);
        if(file >= 0){
            if(H5Oget_info_by_name(file, "/Dataset1", &oi1, H5P_DEFAULT) < 0)
                TEST_ERROR;
            if(oi1.ctime != MTIME1) {
                H5_FAILED();
                   /* If this fails, examine H5Omtime.c.  Modification time is very
                    * system dependant (e.g., on Windows DST must be hardcoded). */
                puts("    Old modification time incorrect");
                goto error;
            }
            if(H5Fclose(file) < 0) TEST_ERROR;
        }
        else {
            H5_FAILED();
            printf("***cannot open the pre-created old modification test file (%s)\n",
                testfile);
            goto error;
        } /* end else */
    }
    PASSED();

    /* Check opening existing file with new-style modification time information
     * and make certain that the time is correct
     */
    TESTING("accessing new modification time messages");

    {
        char testfile[512]="";
        char *srcdir = HDgetenv("srcdir");

        if(srcdir && ((HDstrlen(srcdir) + strlen(TESTFILE2) + 1) < sizeof(testfile))){
            HDstrcpy(testfile, srcdir);
            HDstrcat(testfile, "/");
        }
        HDstrcat(testfile, TESTFILE2);
        file = H5Fopen(testfile, H5F_ACC_RDONLY, H5P_DEFAULT);
        if(file >= 0){
            if(H5Oget_info_by_name(file, "/Dataset1", &oi2, H5P_DEFAULT) < 0)
                TEST_ERROR;
            if(oi2.ctime != MTIME2) {
               H5_FAILED();
               puts("    Modification time incorrect.");
               goto error;
            }
            if(H5Fclose(file) < 0) TEST_ERROR;
        }
        else {
            H5_FAILED();
            printf("***cannot open the pre-created old modification test file (%s)\n",
                testfile);
            goto error;
        } /* end else */
    }
    PASSED();

    /* Verify symbol table messages are cached */
    if(h5_verify_cached_stabs(FILENAME, fapl) < 0) TEST_ERROR

    /* All looks good */
    puts("All modification time tests passed.");
    h5_cleanup(FILENAME, fapl);
    return 0;

    /* Something broke */
error:
    return 1;
}


text:
<?php

namespace CottaCush\Yii2\Widgets\Bootstrap;

use CottaCush\Yii2\Assets\BootstrapPluginAsset;
use yii\helpers\Json;
use yii\web\View;

/**
 * BootstrapWidgetTrait is the trait, which provides basic for all bootstrap widgets features.
 *
 * Note: class, which uses this trait must declare public field named `options` with the array default value:
 *
 * ```php
 * class MyWidget extends \yii\base\Widget
 * {
 *     use BootstrapWidgetTrait;
 *
 *     public $options = [];
 * }
 * ```
 *
 * This field is not present in the trait in order to avoid possible PHP Fatal error on definition conflict.
 *
 * @author Antonio Ramirez <amigo.cobos@gmail.com>
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Paul Klimov <klimov.paul@gmail.com>
 * @since 2.0.6
 */
trait BootstrapWidgetTrait
{
    /**
     * @var array the options for the underlying Bootstrap JS plugin.
     * Please refer to the corresponding Bootstrap plugin Web page for possible options.
     * For example, [this page](http://getbootstrap.com/javascript/#modals) shows
     * how to use the "Modal" plugin and the supported options (e.g. "remote").
     */
    public array $clientOptions = [];
    /**
     * @var array the event handlers for the underlying Bootstrap JS plugin.
     * Please refer to the corresponding Bootstrap plugin Web page for possible events.
     * For example, [this page](http://getbootstrap.com/javascript/#modals) shows
     * how to use the "Modal" plugin and the supported events (e.g. "shown").
     */
    public array $clientEvents = [];

    /**
     * Initializes the widget.
     * This method will register the bootstrap asset bundle. If you override this method,
     * make sure you call the parent implementation first.
     */
    public function init()
    {
        parent::init();
        if (!isset($this->options['id'])) {
            $this->options['id'] = $this->getId();
        }
    }

    /**
     * Registers a specific Bootstrap plugin and the related events
     * @param string $name the name of the Bootstrap plugin
     */
    protected function registerPlugin(string $name)
    {
        $view = $this->getView();

        BootstrapPluginAsset::register($view);

        $id = $this->options['id'];

        if ($this->clientOptions !== false) {
            $options = empty($this->clientOptions) ? '' : Json::htmlEncode($this->clientOptions);
            $js = "jQuery('#$id').$name($options);";
            $view->registerJs($js);
        }

        $this->registerClientEvents();
    }

    /**
     * Registers JS event handlers that are listed in [[clientEvents]].
     * @since 2.0.2
     */
    protected function registerClientEvents()
    {
        if (!empty($this->clientEvents)) {
            $id = $this->options['id'];
            $js = [];
            foreach ($this->clientEvents as $event => $handler) {
                $js[] = "jQuery('#$id').on('$event', $handler);";
            }
            $this->getView()->registerJs(implode("\n", $js));
        }
    }

    /**
     * @return View the view object that can be used to render views or view files.
     * @see yii\base\Widget::getView()
     */
    abstract function getView(): View;
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>IFlySpeechUnderstander Class Reference</title>

	<link rel="stylesheet" href="../css/style.css">
	<meta name="viewport" content="initial-scale=1, maximum-scale=1.4">
	<meta name="generator" content="appledoc 2.2.1 (build 1334)">

				IFlyMSC

				iflytek

Index

Hierarchy

							On This Page

							<select id="jump-to">
	<option value="top">Jump To…</option>

	<option value="overview">Overview</option>

	<option value="tasks">Tasks</option>

	<optgroup label="Properties">

		<option value="//api/name/delegate">delegate</option>

		<option value="//api/name/isUnderstanding">isUnderstanding</option>

	</optgroup>

	<optgroup label="Class Methods">

		<option value="//api/name/sharedInstance">+ sharedInstance</option>

	</optgroup>

	<optgroup label="Instance Methods">

		<option value="//api/name/cancel">- cancel</option>

		<option value="//api/name/destroy">- destroy</option>

		<option value="//api/name/setParameter:forKey:">- setParameter:forKey:</option>

		<option value="//api/name/startListening">- startListening</option>

		<option value="//api/name/stopListening">- stopListening</option>

		<option value="//api/name/writeAudio:">- writeAudio:</option>

	</optgroup>

</select>

IFlySpeechUnderstander Class Reference

	Inherits from
	NSObject

	Declared in
	IFlySpeechUnderstander.h

Overview

语义理解接口

  isUnderstanding

是否正在语义理解

@property (readonly) BOOL isUnderstanding

Declared In

IFlySpeechUnderstander.h

  delegate

设置委托对象

@property (nonatomic, retain) id<IFlySpeechRecognizerDelegate> delegate

Declared In

IFlySpeechUnderstander.h

+ sharedInstance

创建语义理解对象的单例

+ (instancetype)sharedInstance

Return Value

语义理解对象

Declared In

IFlySpeechUnderstander.h

– startListening

开始义理解
同时只能进行一路会话,这次会话没有结束不能进行下一路会话,否则会报错。若有需要多次回话,请在onError回调返回后请求下一路回话。

- (BOOL)startListening

Return Value

成功返回YES,失败返回NO

Declared In

IFlySpeechUnderstander.h

– stopListening

停止录音
调用此函数会停止录音,并开始进行语义理解

- (void)stopListening

Declared In

IFlySpeechUnderstander.h

– cancel

取消本次会话

- (void)cancel

Declared In

IFlySpeechUnderstander.h

– setParameter:forKey:

设置语义理解引擎的参数
语义理解的引擎参数(key)取值如下:

*参数	描述

domain	应用的领域: 取值为:iat、search、video、poi、music、asr;
iat:普通文本听写;
search:热词搜索;
video:视频音乐搜索;
video:视频音乐搜索;
asr:关键词识别;

vad_bos	前端点检测: 静音超时时间,即用户多长时间不说话则当做超时处理; 单位:ms;
engine指定iat识别默认值为5000;
其他情况默认值为 4000,范围 0-10000。

vad_eos	后断点检测: 后端点静音检测时间,即用户停止说话多长时间内即认为不再输入,
自动停止录音;单位:ms;
sms 识别默认值为 1800;
其他默认值为 700,范围 0-10000。

sample_rate	采样率:目前支持的采样率设置有 16000 和 8000。

asr_ptt	标点符号设置: 默认为 1,当设置为 0 时,将返回无标点符号文本。

result_type	返回结果的数据格式: 可设置为json,xml,plain,默认为json。

grammarID	识别的语法id: 只针对 domain 设置为"asr"的应用。

asr_audio_path	音频文件名: 设置此参数后,将会自动保存识别的录音文件。
 路径为Documents/(指定值)。
不设置或者设置为nil,则不保存音频。

params	扩展参数: 对于一些特殊的参数可在此设置,一般用于设置语义。

- (BOOL)setParameter:(NSString *)value forKey:(NSString *)key

Parameters

						value

参数对应的取值

						key

语义理解引擎参数

Return Value

成功返回YES;失败返回NO

Declared In

IFlySpeechUnderstander.h

– writeAudio:

写入音频流

- (BOOL)writeAudio:(NSData *)audioData

Parameters

						audioData

音频数据

Return Value

写入成功返回YES,写入失败返回NO

Declared In

IFlySpeechUnderstander.h

– destroy

销毁语义理解对象。

- (BOOL)destroy

Return Value

成功返回YES;失败返回NO

Declared In

IFlySpeechUnderstander.h

Copyright © 2016 iflytek. All rights reserved. Updated: 2016-06-15

Generated by appledoc 2.2.1 (build 1334).


text:
package org.samples.wildfly.deltaspike;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.servlet.ServletRequest;
import org.apache.deltaspike.core.api.common.DeltaSpike;

/**
 * @author arungupta
 */
@RequestScoped
public class MyBean {
    @Inject @DeltaSpike
    private ServletRequest request;

    public String giveMeHostAndPort() {
        return request.getServerName() + ":" + request.getServerPort();
    }
}


text:
package org.jpmml.evaluator;

import java.io.*;
import java.util.*;

import org.dmg.pmml.*;

import com.google.common.collect.*;

public class CsvUtil {

	private CsvUtil(){
	}

	static
	public List<Map<FieldName, String>> load(InputStream is) throws IOException {
		List<Map<FieldName, String>> table = Lists.newArrayList();

		BufferedReader reader = new BufferedReader(new InputStreamReader(is, "US-ASCII"));

		table:
		try {
			String headerLine = reader.readLine();
			if(headerLine == null){
				break table;
			}

			List<FieldName> keys = Lists.newArrayList();

			List<String> headerCells = parseLine(headerLine);
			for(int i = 0; i < headerCells.size(); i++){
				keys.add(FieldName.create(headerCells.get(i)));
			}

			while(true){
				String bodyLine = reader.readLine();
				if(bodyLine == null){
					break;
				}

				Map<FieldName, String> row = Maps.newLinkedHashMap();

				List<String> bodyCells = parseLine(bodyLine);

				// Must be of equal length
				if(bodyCells.size() != headerCells.size()){
					throw new RuntimeException();
				}

				for(int i = 0; i < bodyCells.size(); i++){
					row.put(keys.get(i), bodyCells.get(i));
				}

				table.add(row);
			}
		} finally {
			reader.close();
		}

		return table;
	}

	static
	private List<String> parseLine(String line){
		return Arrays.asList(line.split(","));
	}
}


text:
<?php

class RestrictionRegionCountryDropdownField extends DropdownField{

	public static $defaultname = "-- International --";

	public function __construct($name, $title = null, $source = null, $value = "", $form = null) {
		$source = SiteConfig::current_site_config()->getCountriesList(true);
		parent::__construct($name, $title, $source, $value, $form);
		$this->setHasEmptyDefault(true);
		$this->setEmptyString(self::$defaultname);
	}

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class org.springframework.remoting.support.RemoteExporter (Spring Framework 5.1.18.RELEASE API)</title>
<meta name="date" content="2020-09-15">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.springframework.remoting.support.RemoteExporter

Packages that use RemoteExporter

Package
Description

org.springframework.jms.remoting

Remoting classes for transparent Java-to-Java remoting via a JMS provider.

org.springframework.remoting.caucho

This package provides remoting classes for Caucho's Hessian protocol:
 a proxy factory for accessing Hessian services, and an exporter for
 making beans available to Hessian clients.

org.springframework.remoting.httpinvoker

Remoting classes for transparent Java-to-Java remoting via HTTP invokers.

org.springframework.remoting.rmi

Remoting classes for conventional RMI and transparent remoting via
 RMI invokers.

org.springframework.remoting.support

Generic support classes for remoting implementations.

Uses of RemoteExporter in org.springframework.jms.remoting

Subclasses of RemoteExporter in org.springframework.jms.remoting

Modifier and Type
Class and Description

class
JmsInvokerServiceExporter

JMS message listener that exports the specified service bean as a
 JMS service endpoint, accessible via a JMS invoker proxy.

Uses of RemoteExporter in org.springframework.remoting.caucho

Subclasses of RemoteExporter in org.springframework.remoting.caucho

Modifier and Type
Class and Description

class
HessianExporter

General stream-based protocol exporter for a Hessian endpoint.

class
HessianServiceExporter

Servlet-API-based HTTP request handler that exports the specified service bean
 as Hessian service endpoint, accessible via a Hessian proxy.

class
SimpleHessianServiceExporter

Deprecated.

as of Spring Framework 5.1, in favor of HessianServiceExporter

Uses of RemoteExporter in org.springframework.remoting.httpinvoker

Subclasses of RemoteExporter in org.springframework.remoting.httpinvoker

Modifier and Type
Class and Description

class
HttpInvokerServiceExporter

Servlet-API-based HTTP request handler that exports the specified service bean
 as HTTP invoker service endpoint, accessible via an HTTP invoker proxy.

class
SimpleHttpInvokerServiceExporter

Deprecated.

as of Spring Framework 5.1, in favor of HttpInvokerServiceExporter

Uses of RemoteExporter in org.springframework.remoting.rmi

Subclasses of RemoteExporter in org.springframework.remoting.rmi

Modifier and Type
Class and Description

class
JndiRmiServiceExporter

Service exporter which binds RMI services to JNDI.

class
RemoteInvocationSerializingExporter

Abstract base class for remote service exporters that explicitly deserialize
 RemoteInvocation objects and serialize
 RemoteInvocationResult objects,
 for example Spring's HTTP invoker.

class
RmiBasedExporter

Convenient superclass for RMI-based remote exporters.

class
RmiServiceExporter

RMI exporter that exposes the specified service as RMI object with the specified name.

Uses of RemoteExporter in org.springframework.remoting.support

Subclasses of RemoteExporter in org.springframework.remoting.support

Modifier and Type
Class and Description

class
RemoteInvocationBasedExporter

Abstract base class for remote service exporters that are based
 on deserialization of RemoteInvocation objects.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev

Next

Frames

No Frames

All Classes


text:
/*
 *
 */
#ifndef MCU_ENCODE_HPP
#define MCU_ENCODE_HPP

#include <cstdint>

#include "const/constant.h"

#include "mcu-msg.hpp"

namespace led_d
{
  namespace mcu
  {

    class encode
    {
    public:

      static void wrap (mcu_msg_t &msg);

      template <typename ...payload_t>
      static mcu_msg_t join (uint8_t serial,
                             uint8_t msg_id, payload_t ...payload);

    private:

      static void do_join (mcu_msg_t &msg) {};

      template <typename ...payload_t>
      static void do_join (mcu_msg_t &msg, uint8_t load_1, payload_t ...payload);

      template <typename ...payload_t>
      static void do_join (mcu_msg_t &msg, mcu_msg_t &arr, payload_t ...payload);

    };

    //
    // --------------------------------------------------
    //
    inline void encode::wrap (mcu_msg_t &msg)
    {
      msg.push_front (msg.size ());
      msg.push_front (EYE_CATCH);
    }

    template <typename ...payload_t>
    mcu_msg_t encode::join (uint8_t serial, uint8_t msg_id, payload_t ...payload)
    {
      mcu_msg_t msg;
      msg.push_back (serial);
      msg.push_back (msg_id);

      do_join (msg, payload...);

      return msg;
    }

    template <typename ...payload_t>
    void encode::do_join (mcu_msg_t &msg, uint8_t load_1, payload_t ...payload)
    {
      msg.push_back (load_1);

      do_join (msg, payload...);
    }

    template <typename ...payload_t>
    void encode::do_join (mcu_msg_t &msg, mcu_msg_t &arr, payload_t ...payload)
    {
      msg.splice (msg.end (), arr);

      do_join (msg, payload...);
    }

  } // namespace mcu
} // namespace led_d

#endif


text:
package OptimizationTests.ValuePropagationThroughHeap.EnhLoopAtomicInstance_02;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 *
 * Atomic test cases when optimization should be applied: 'enhanced for' loop plus in-lining
 *
 **/

public class Main {
    final int iterations = 1100;
    int[] arr1 = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};

    int i1;
    int i2;
    int[] i_arr = new int[iterations];

    double d1;
    double d2;
    double[] d_arr = new double[iterations];

    short sh1;
    short sh2;
    short[] sh_arr = new short[iterations];

    char ch1;
    char ch2;
    char[] ch_arr = new char[iterations];

    byte b1;
    byte b2;
    byte[] b_arr = new byte[iterations];

    boolean bl1;
    boolean bl2;
    boolean[] bl_arr = new boolean[iterations];

/* Positive: atomic tests for various iput / iget instructions */

/* iput / iget
*/
   public int test1() {
        this.i_arr[iterations-1] = 1; this.i1 = 2; this.i2 = 3;
        for (int i : arr1)
        {
            a1(this.i1, this.i2,this.i_arr);
        }
        return i_arr[0];
    }

    private void a1(int paramInt1, int paramInt2, int[] paramArrayOfInt)
    {
        int ii = 123456 * (paramInt1 + paramInt2);
        paramArrayOfInt[0] = ii;
    }

/* iput-wide / iget-wide
*/
    public double test2() {
        this.d_arr[0] = 1.0D; this.d1 = 2.0D; this.d2 = 3.0D;
        for (int i : arr1)
        {
            a2(this.d1, this.d2, this.d_arr);
        }
        return d_arr[0];
    }

    private void a2(double paramDouble1, double paramDouble2, double[] paramArrayOfDouble)
    {
        double dd = 0.123456D * (paramDouble1 + paramDouble2);
        paramArrayOfDouble[0] = dd;
    }

/* iput-short / iget-short
*/
    public short test3() {
        this.sh_arr[0] = 11; this.sh1 = 22; this.sh2 = 33;
        for (int i : arr1)
        {
            a3(this.sh1, this.sh2, this.sh_arr);
        }
        return sh_arr[0];
    }

    private void a3(short paramShort1, short paramShort2, short[] paramArrayOfShort)
    {
        short shsh = (short)(12345 * (paramShort2 - paramShort1));
        paramArrayOfShort[0] += shsh;
    }

/* iput-char / iget-char
*/
    public char test4() {
        this.ch_arr[0] = 'a'; this.ch1 = 'b'; this.ch2 = 'c';
        for (int i : arr1)
        {
            a4(this.ch1, this.ch2, this.ch_arr);
        }
        return ch_arr[0];
    }

    private void a4(char paramChar1, char paramChar2, char[] paramArrayOfChar)
    {
        char chch = (char)('f' + (paramChar2 - paramChar1));
        paramArrayOfChar[0] += chch;
    }

/* iput-byte / iget-byte
*/
    public byte test5() {
        this.b_arr[0] = 1; this.b1 = 2; this.b2 = 3;
        for (int i : arr1)
        {
            a5(this.b1, this.b2, this.b_arr);
        }
        return b_arr[0];
    }

    private void a5(byte paramByte1, byte paramByte2, byte[] paramArrayOfByte)
    {
        byte bb = (byte)(12 * (paramByte2 - paramByte1));
        paramArrayOfByte[0] += bb;
    }

/* iput-boolean / iget-boolean
*/
    public boolean test6() {
        this.bl_arr[0] = false; this.bl1 = true; this.bl2 = true;
        for (int i : arr1)
        {
            a6(this.bl1, this.bl2, this.bl_arr);
        }
        return bl_arr[0];
    }

    private void a6(boolean paramBoolean1, boolean paramBoolean2, boolean[] paramArrayOfBoolean)
    {
        boolean blbl = ( true | (paramBoolean2 & paramBoolean1));
        paramArrayOfBoolean[0] = !paramArrayOfBoolean[0] ^ blbl;
    }

    public void runTests() {
        Class c = new Main().getClass();
        Method[] methods = c.getDeclaredMethods();
        Method tempMethod;
        for (int i = 1; i < methods.length; i++) {
            int j = i;
            while (j > 0 &&  methods[j-1].getName().compareTo(methods[j].getName()) > 0) {
                tempMethod = methods[j];
                methods[j] = methods[j-1];
                methods[j-1] = tempMethod;
                j = j - 1;
            }
        }

        Object[] arr = {null};
        for (Method m: methods){
            if (m.getName().startsWith("test")){
                try {
                    String names[] = c.getPackage().getName().split("\\.");
                    String testName = names[names.length-1];
                    System.out.println("getGenericReturnType() = " + m.getGenericReturnType());
                    if (m.getGenericReturnType().toString().equals("char")){
                       System.out.println("Test "+testName+"; Subtest "+m.getName()+"; Result: "+ String.format ("\\u%04x", (int)(m.invoke(this).toString().charAt(0))));
                    }
                    else {
                       System.out.println("Test "+testName+"; Subtest "+m.getName()+"; Result: "+ m.invoke(this));
                    }
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args)
    {
        new Main().runTests();
    }

}


text:
// MESSAGE DISTANCE_SENSOR PACKING

#define MAVLINK_MSG_ID_DISTANCE_SENSOR 132

MAVPACKED(
typedef struct __mavlink_distance_sensor_t {
 uint32_t time_boot_ms; /*< Time since system boot*/
 uint16_t min_distance; /*< Minimum distance the sensor can measure in centimeters*/
 uint16_t max_distance; /*< Maximum distance the sensor can measure in centimeters*/
 uint16_t current_distance; /*< Current distance reading*/
 uint8_t type; /*< Type from MAV_DISTANCE_SENSOR enum.*/
 uint8_t id; /*< Onboard ID of the sensor*/
 uint8_t orientation; /*< Direction the sensor faces from MAV_SENSOR_ORIENTATION enum.*/
 uint8_t covariance; /*< Measurement covariance in centimeters, 0 for unknown / invalid readings*/
}) mavlink_distance_sensor_t;

#define MAVLINK_MSG_ID_DISTANCE_SENSOR_LEN 14
#define MAVLINK_MSG_ID_DISTANCE_SENSOR_MIN_LEN 14
#define MAVLINK_MSG_ID_132_LEN 14
#define MAVLINK_MSG_ID_132_MIN_LEN 14

#define MAVLINK_MSG_ID_DISTANCE_SENSOR_CRC 85
#define MAVLINK_MSG_ID_132_CRC 85

#if MAVLINK_COMMAND_24BIT
#define MAVLINK_MESSAGE_INFO_DISTANCE_SENSOR { \
	132, \
	"DISTANCE_SENSOR", \
	8, \
	{  { "time_boot_ms", NULL, MAVLINK_TYPE_UINT32_T, 0, 0, offsetof(mavlink_distance_sensor_t, time_boot_ms) }, \
         { "min_distance", NULL, MAVLINK_TYPE_UINT16_T, 0, 4, offsetof(mavlink_distance_sensor_t, min_distance) }, \
         { "max_distance", NULL, MAVLINK_TYPE_UINT16_T, 0, 6, offsetof(mavlink_distance_sensor_t, max_distance) }, \
         { "current_distance", NULL, MAVLINK_TYPE_UINT16_T, 0, 8, offsetof(mavlink_distance_sensor_t, current_distance) }, \
         { "type", NULL, MAVLINK_TYPE_UINT8_T, 0, 10, offsetof(mavlink_distance_sensor_t, type) }, \
         { "id", NULL, MAVLINK_TYPE_UINT8_T, 0, 11, offsetof(mavlink_distance_sensor_t, id) }, \
         { "orientation", NULL, MAVLINK_TYPE_UINT8_T, 0, 12, offsetof(mavlink_distance_sensor_t, orientation) }, \
         { "covariance", NULL, MAVLINK_TYPE_UINT8_T, 0, 13, offsetof(mavlink_distance_sensor_t, covariance) }, \
         } \
}
#else
#define MAVLINK_MESSAGE_INFO_DISTANCE_SENSOR { \
	"DISTANCE_SENSOR", \
	8, \
	{  { "time_boot_ms", NULL, MAVLINK_TYPE_UINT32_T, 0, 0, offsetof(mavlink_distance_sensor_t, time_boot_ms) }, \
         { "min_distance", NULL, MAVLINK_TYPE_UINT16_T, 0, 4, offsetof(mavlink_distance_sensor_t, min_distance) }, \
         { "max_distance", NULL, MAVLINK_TYPE_UINT16_T, 0, 6, offsetof(mavlink_distance_sensor_t, max_distance) }, \
         { "current_distance", NULL, MAVLINK_TYPE_UINT16_T, 0, 8, offsetof(mavlink_distance_sensor_t, current_distance) }, \
         { "type", NULL, MAVLINK_TYPE_UINT8_T, 0, 10, offsetof(mavlink_distance_sensor_t, type) }, \
         { "id", NULL, MAVLINK_TYPE_UINT8_T, 0, 11, offsetof(mavlink_distance_sensor_t, id) }, \
         { "orientation", NULL, MAVLINK_TYPE_UINT8_T, 0, 12, offsetof(mavlink_distance_sensor_t, orientation) }, \
         { "covariance", NULL, MAVLINK_TYPE_UINT8_T, 0, 13, offsetof(mavlink_distance_sensor_t, covariance) }, \
         } \
}
#endif

/**
 * @brief Pack a distance_sensor message
 * @param system_id ID of this system
 * @param component_id ID of this component (e.g. 200 for IMU)
 * @param msg The MAVLink message to compress the data into
 *
 * @param time_boot_ms Time since system boot
 * @param min_distance Minimum distance the sensor can measure in centimeters
 * @param max_distance Maximum distance the sensor can measure in centimeters
 * @param current_distance Current distance reading
 * @param type Type from MAV_DISTANCE_SENSOR enum.
 * @param id Onboard ID of the sensor
 * @param orientation Direction the sensor faces from MAV_SENSOR_ORIENTATION enum.
 * @param covariance Measurement covariance in centimeters, 0 for unknown / invalid readings
 * @return length of the message in bytes (excluding serial stream start sign)
 */
static inline uint16_t mavlink_msg_distance_sensor_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg,
						       uint32_t time_boot_ms, uint16_t min_distance, uint16_t max_distance, uint16_t current_distance, uint8_t type, uint8_t id, uint8_t orientation, uint8_t covariance)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
	char buf[MAVLINK_MSG_ID_DISTANCE_SENSOR_LEN];
	_mav_put_uint32_t(buf, 0, time_boot_ms);
	_mav_put_uint16_t(buf, 4, min_distance);
	_mav_put_uint16_t(buf, 6, max_distance);
	_mav_put_uint16_t(buf, 8, current_distance);
	_mav_put_uint8_t(buf, 10, type);
	_mav_put_uint8_t(buf, 11, id);
	_mav_put_uint8_t(buf, 12, orientation);
	_mav_put_uint8_t(buf, 13, covariance);

        memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_DISTANCE_SENSOR_LEN);
#else
	mavlink_distance_sensor_t packet;
	packet.time_boot_ms = time_boot_ms;
	packet.min_distance = min_distance;
	packet.max_distance = max_distance;
	packet.current_distance = current_distance;
	packet.type = type;
	packet.id = id;
	packet.orientation = orientation;
	packet.covariance = covariance;

        memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_DISTANCE_SENSOR_LEN);
#endif

	msg->msgid = MAVLINK_MSG_ID_DISTANCE_SENSOR;
    return mavlink_finalize_message(msg, system_id, component_id, MAVLINK_MSG_ID_DISTANCE_SENSOR_MIN_LEN, MAVLINK_MSG_ID_DISTANCE_SENSOR_LEN, MAVLINK_MSG_ID_DISTANCE_SENSOR_CRC);
}

/**
 * @brief Pack a distance_sensor message on a channel
 * @param system_id ID of this system
 * @param component_id ID of this component (e.g. 200 for IMU)
 * @param chan The MAVLink channel this message will be sent over
 * @param msg The MAVLink message to compress the data into
 * @param time_boot_ms Time since system boot
 * @param min_distance Minimum distance the sensor can measure in centimeters
 * @param max_distance Maximum distance the sensor can measure in centimeters
 * @param current_distance Current distance reading
 * @param type Type from MAV_DISTANCE_SENSOR enum.
 * @param id Onboard ID of the sensor
 * @param orientation Direction the sensor faces from MAV_SENSOR_ORIENTATION enum.
 * @param covariance Measurement covariance in centimeters, 0 for unknown / invalid readings
 * @return length of the message in bytes (excluding serial stream start sign)
 */
static inline uint16_t mavlink_msg_distance_sensor_pack_chan(uint8_t system_id, uint8_t component_id, uint8_t chan,
							   mavlink_message_t* msg,
						           uint32_t time_boot_ms,uint16_t min_distance,uint16_t max_distance,uint16_t current_distance,uint8_t type,uint8_t id,uint8_t orientation,uint8_t covariance)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
	char buf[MAVLINK_MSG_ID_DISTANCE_SENSOR_LEN];
	_mav_put_uint32_t(buf, 0, time_boot_ms);
	_mav_put_uint16_t(buf, 4, min_distance);
	_mav_put_uint16_t(buf, 6, max_distance);
	_mav_put_uint16_t(buf, 8, current_distance);
	_mav_put_uint8_t(buf, 10, type);
	_mav_put_uint8_t(buf, 11, id);
	_mav_put_uint8_t(buf, 12, orientation);
	_mav_put_uint8_t(buf, 13, covariance);

        memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_DISTANCE_SENSOR_LEN);
#else
	mavlink_distance_sensor_t packet;
	packet.time_boot_ms = time_boot_ms;
	packet.min_distance = min_distance;
	packet.max_distance = max_distance;
	packet.current_distance = current_distance;
	packet.type = type;
	packet.id = id;
	packet.orientation = orientation;
	packet.covariance = covariance;

        memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_DISTANCE_SENSOR_LEN);
#endif

	msg->msgid = MAVLINK_MSG_ID_DISTANCE_SENSOR;
    return mavlink_finalize_message_chan(msg, system_id, component_id, chan, MAVLINK_MSG_ID_DISTANCE_SENSOR_MIN_LEN, MAVLINK_MSG_ID_DISTANCE_SENSOR_LEN, MAVLINK_MSG_ID_DISTANCE_SENSOR_CRC);
}

/**
 * @brief Encode a distance_sensor struct
 *
 * @param system_id ID of this system
 * @param component_id ID of this component (e.g. 200 for IMU)
 * @param msg The MAVLink message to compress the data into
 * @param distance_sensor C-struct to read the message contents from
 */
static inline uint16_t mavlink_msg_distance_sensor_encode(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg, const mavlink_distance_sensor_t* distance_sensor)
{
	return mavlink_msg_distance_sensor_pack(system_id, component_id, msg, distance_sensor->time_boot_ms, distance_sensor->min_distance, distance_sensor->max_distance, distance_sensor->current_distance, distance_sensor->type, distance_sensor->id, distance_sensor->orientation, distance_sensor->covariance);
}

/**
 * @brief Encode a distance_sensor struct on a channel
 *
 * @param system_id ID of this system
 * @param component_id ID of this component (e.g. 200 for IMU)
 * @param chan The MAVLink channel this message will be sent over
 * @param msg The MAVLink message to compress the data into
 * @param distance_sensor C-struct to read the message contents from
 */
static inline uint16_t mavlink_msg_distance_sensor_encode_chan(uint8_t system_id, uint8_t component_id, uint8_t chan, mavlink_message_t* msg, const mavlink_distance_sensor_t* distance_sensor)
{
	return mavlink_msg_distance_sensor_pack_chan(system_id, component_id, chan, msg, distance_sensor->time_boot_ms, distance_sensor->min_distance, distance_sensor->max_distance, distance_sensor->current_distance, distance_sensor->type, distance_sensor->id, distance_sensor->orientation, distance_sensor->covariance);
}

/**
 * @brief Send a distance_sensor message
 * @param chan MAVLink channel to send the message
 *
 * @param time_boot_ms Time since system boot
 * @param min_distance Minimum distance the sensor can measure in centimeters
 * @param max_distance Maximum distance the sensor can measure in centimeters
 * @param current_distance Current distance reading
 * @param type Type from MAV_DISTANCE_SENSOR enum.
 * @param id Onboard ID of the sensor
 * @param orientation Direction the sensor faces from MAV_SENSOR_ORIENTATION enum.
 * @param covariance Measurement covariance in centimeters, 0 for unknown / invalid readings
 */
#ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS

static inline void mavlink_msg_distance_sensor_send(mavlink_channel_t chan, uint32_t time_boot_ms, uint16_t min_distance, uint16_t max_distance, uint16_t current_distance, uint8_t type, uint8_t id, uint8_t orientation, uint8_t covariance)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
	char buf[MAVLINK_MSG_ID_DISTANCE_SENSOR_LEN];
	_mav_put_uint32_t(buf, 0, time_boot_ms);
	_mav_put_uint16_t(buf, 4, min_distance);
	_mav_put_uint16_t(buf, 6, max_distance);
	_mav_put_uint16_t(buf, 8, current_distance);
	_mav_put_uint8_t(buf, 10, type);
	_mav_put_uint8_t(buf, 11, id);
	_mav_put_uint8_t(buf, 12, orientation);
	_mav_put_uint8_t(buf, 13, covariance);

    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_DISTANCE_SENSOR, buf, MAVLINK_MSG_ID_DISTANCE_SENSOR_MIN_LEN, MAVLINK_MSG_ID_DISTANCE_SENSOR_LEN, MAVLINK_MSG_ID_DISTANCE_SENSOR_CRC);
#else
	mavlink_distance_sensor_t packet;
	packet.time_boot_ms = time_boot_ms;
	packet.min_distance = min_distance;
	packet.max_distance = max_distance;
	packet.current_distance = current_distance;
	packet.type = type;
	packet.id = id;
	packet.orientation = orientation;
	packet.covariance = covariance;

    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_DISTANCE_SENSOR, (const char *)&packet, MAVLINK_MSG_ID_DISTANCE_SENSOR_MIN_LEN, MAVLINK_MSG_ID_DISTANCE_SENSOR_LEN, MAVLINK_MSG_ID_DISTANCE_SENSOR_CRC);
#endif
}

/**
 * @brief Send a distance_sensor message
 * @param chan MAVLink channel to send the message
 * @param struct The MAVLink struct to serialize
 */
static inline void mavlink_msg_distance_sensor_send_struct(mavlink_channel_t chan, const mavlink_distance_sensor_t* distance_sensor)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
    mavlink_msg_distance_sensor_send(chan, distance_sensor->time_boot_ms, distance_sensor->min_distance, distance_sensor->max_distance, distance_sensor->current_distance, distance_sensor->type, distance_sensor->id, distance_sensor->orientation, distance_sensor->covariance);
#else
    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_DISTANCE_SENSOR, (const char *)distance_sensor, MAVLINK_MSG_ID_DISTANCE_SENSOR_MIN_LEN, MAVLINK_MSG_ID_DISTANCE_SENSOR_LEN, MAVLINK_MSG_ID_DISTANCE_SENSOR_CRC);
#endif
}

#if MAVLINK_MSG_ID_DISTANCE_SENSOR_LEN <= MAVLINK_MAX_PAYLOAD_LEN
/*
  This varient of _send() can be used to save stack space by re-using
  memory from the receive buffer.  The caller provides a
  mavlink_message_t which is the size of a full mavlink message. This
  is usually the receive buffer for the channel, and allows a reply to an
  incoming message with minimum stack space usage.
 */
static inline void mavlink_msg_distance_sensor_send_buf(mavlink_message_t *msgbuf, mavlink_channel_t chan,  uint32_t time_boot_ms, uint16_t min_distance, uint16_t max_distance, uint16_t current_distance, uint8_t type, uint8_t id, uint8_t orientation, uint8_t covariance)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
	char *buf = (char *)msgbuf;
	_mav_put_uint32_t(buf, 0, time_boot_ms);
	_mav_put_uint16_t(buf, 4, min_distance);
	_mav_put_uint16_t(buf, 6, max_distance);
	_mav_put_uint16_t(buf, 8, current_distance);
	_mav_put_uint8_t(buf, 10, type);
	_mav_put_uint8_t(buf, 11, id);
	_mav_put_uint8_t(buf, 12, orientation);
	_mav_put_uint8_t(buf, 13, covariance);

    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_DISTANCE_SENSOR, buf, MAVLINK_MSG_ID_DISTANCE_SENSOR_MIN_LEN, MAVLINK_MSG_ID_DISTANCE_SENSOR_LEN, MAVLINK_MSG_ID_DISTANCE_SENSOR_CRC);
#else
	mavlink_distance_sensor_t *packet = (mavlink_distance_sensor_t *)msgbuf;
	packet->time_boot_ms = time_boot_ms;
	packet->min_distance = min_distance;
	packet->max_distance = max_distance;
	packet->current_distance = current_distance;
	packet->type = type;
	packet->id = id;
	packet->orientation = orientation;
	packet->covariance = covariance;

    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_DISTANCE_SENSOR, (const char *)packet, MAVLINK_MSG_ID_DISTANCE_SENSOR_MIN_LEN, MAVLINK_MSG_ID_DISTANCE_SENSOR_LEN, MAVLINK_MSG_ID_DISTANCE_SENSOR_CRC);
#endif
}
#endif

#endif

// MESSAGE DISTANCE_SENSOR UNPACKING

/**
 * @brief Get field time_boot_ms from distance_sensor message
 *
 * @return Time since system boot
 */
static inline uint32_t mavlink_msg_distance_sensor_get_time_boot_ms(const mavlink_message_t* msg)
{
	return _MAV_RETURN_uint32_t(msg,  0);
}

/**
 * @brief Get field min_distance from distance_sensor message
 *
 * @return Minimum distance the sensor can measure in centimeters
 */
static inline uint16_t mavlink_msg_distance_sensor_get_min_distance(const mavlink_message_t* msg)
{
	return _MAV_RETURN_uint16_t(msg,  4);
}

/**
 * @brief Get field max_distance from distance_sensor message
 *
 * @return Maximum distance the sensor can measure in centimeters
 */
static inline uint16_t mavlink_msg_distance_sensor_get_max_distance(const mavlink_message_t* msg)
{
	return _MAV_RETURN_uint16_t(msg,  6);
}

/**
 * @brief Get field current_distance from distance_sensor message
 *
 * @return Current distance reading
 */
static inline uint16_t mavlink_msg_distance_sensor_get_current_distance(const mavlink_message_t* msg)
{
	return _MAV_RETURN_uint16_t(msg,  8);
}

/**
 * @brief Get field type from distance_sensor message
 *
 * @return Type from MAV_DISTANCE_SENSOR enum.
 */
static inline uint8_t mavlink_msg_distance_sensor_get_type(const mavlink_message_t* msg)
{
	return _MAV_RETURN_uint8_t(msg,  10);
}

/**
 * @brief Get field id from distance_sensor message
 *
 * @return Onboard ID of the sensor
 */
static inline uint8_t mavlink_msg_distance_sensor_get_id(const mavlink_message_t* msg)
{
	return _MAV_RETURN_uint8_t(msg,  11);
}

/**
 * @brief Get field orientation from distance_sensor message
 *
 * @return Direction the sensor faces from MAV_SENSOR_ORIENTATION enum.
 */
static inline uint8_t mavlink_msg_distance_sensor_get_orientation(const mavlink_message_t* msg)
{
	return _MAV_RETURN_uint8_t(msg,  12);
}

/**
 * @brief Get field covariance from distance_sensor message
 *
 * @return Measurement covariance in centimeters, 0 for unknown / invalid readings
 */
static inline uint8_t mavlink_msg_distance_sensor_get_covariance(const mavlink_message_t* msg)
{
	return _MAV_RETURN_uint8_t(msg,  13);
}

/**
 * @brief Decode a distance_sensor message into a struct
 *
 * @param msg The message to decode
 * @param distance_sensor C-struct to decode the message contents into
 */
static inline void mavlink_msg_distance_sensor_decode(const mavlink_message_t* msg, mavlink_distance_sensor_t* distance_sensor)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
	distance_sensor->time_boot_ms = mavlink_msg_distance_sensor_get_time_boot_ms(msg);
	distance_sensor->min_distance = mavlink_msg_distance_sensor_get_min_distance(msg);
	distance_sensor->max_distance = mavlink_msg_distance_sensor_get_max_distance(msg);
	distance_sensor->current_distance = mavlink_msg_distance_sensor_get_current_distance(msg);
	distance_sensor->type = mavlink_msg_distance_sensor_get_type(msg);
	distance_sensor->id = mavlink_msg_distance_sensor_get_id(msg);
	distance_sensor->orientation = mavlink_msg_distance_sensor_get_orientation(msg);
	distance_sensor->covariance = mavlink_msg_distance_sensor_get_covariance(msg);
#else
        uint8_t len = msg->len < MAVLINK_MSG_ID_DISTANCE_SENSOR_LEN? msg->len : MAVLINK_MSG_ID_DISTANCE_SENSOR_LEN;
        memset(distance_sensor, 0, MAVLINK_MSG_ID_DISTANCE_SENSOR_LEN);
	memcpy(distance_sensor, _MAV_PAYLOAD(msg), len);
#endif
}


text:
SELECT
  "DatabaseName",
  "TableName",
  "ColumnName",
  "RowCount",
  "UniqueValueCount",
  "CreateTimeStamp" AT TIME ZONE INTERVAL '0:00' HOUR TO MINUTE AS "CreateTimeStamp"
FROM %s."StatsV"


text:
{% load staticfiles %}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <link rel="apple-touch-icon" sizes="57x57" href="/static/img/favicon/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="/static/img/favicon/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/static/img/favicon/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="/static/img/favicon/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/static/img/favicon/img/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="/static/img/favicon/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/static/img/favicon/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/static/img/favicon/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/static/img/favicon/apple-icon-180x180.png">
    <link rel="icon" type="image/png" sizes="192x192"  href="/static/img/favicon/android-icon-192x192.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/static/img/favicon/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="96x96" href="/static/img/favicon/favicon-96x96.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/static/img/favicon/favicon-16x16.png">
    <link rel="manifest" href="/static/img/favicon/manifest.json">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
    <meta name="theme-color" content="#ffffff">

	<title>{% block head_title %}Post Details{% endblock %}</title>

    <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
    <link href="{% static 'css/prism.css' %}" rel="stylesheet">

    <link href="{% static 'css/custom.css' %}" rel="stylesheet">

            <button type="button" class="navbar-toggle" data-toggle="collapse"
                    data-target="#bs-example-navbar-collapse-1">
                Toggle navigation

            </button>
            Tom Gijselinck

                    Blog

Blog

Post List

                    About

                    Contact

{% block page_content %}

{% endblock %}

Created with Django | hosted by Linode


text:
<?php

declare(strict_types=1);

namespace PhpMyAdmin\Controllers\Database;

use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Response;
use PhpMyAdmin\Template;
use function json_encode;

/**
 * Table/Column autocomplete in SQL editors.
 */
class SqlAutoCompleteController extends AbstractController
{
    /** @var DatabaseInterface */
    private $dbi;

    /**
     * @param Response          $response
     * @param string            $db       Database name.
     * @param DatabaseInterface $dbi
     */
    public function __construct($response, Template $template, $db, $dbi)
    {
        parent::__construct($response, $template, $db);
        $this->dbi = $dbi;
    }

    public function index(): void
    {
        global $cfg, $db, $sql_autocomplete;

        $sql_autocomplete = true;
        if ($cfg['EnableAutocompleteForTablesAndColumns']) {
            $db = $_POST['db'] ?? $db;
            $sql_autocomplete = [];
            if ($db) {
                $tableNames = $this->dbi->getTables($db);
                foreach ($tableNames as $tableName) {
                    $sql_autocomplete[$tableName] = $this->dbi->getColumns(
                        $db,
                        $tableName
                    );
                }
            }
        }
        $this->response->addJSON(['tables' => json_encode($sql_autocomplete)]);
    }
}


text:
#include "ui/UIPageView.h"

NS_CC_BEGIN

namespace ui {

IMPLEMENT_CLASS_GUI_INFO(PageView)

PageView::PageView():
_isAutoScrolling(false),
_autoScrollDistance(0.0f),
_autoScrollSpeed(0.0f),
_autoScrollDirection(AutoScrollDirection::LEFT),
_curPageIdx(0),
_touchMoveDirection(TouchDirection::LEFT),
_leftBoundaryChild(nullptr),
_rightBoundaryChild(nullptr),
_leftBoundary(0.0f),
_rightBoundary(0.0f),
_customScrollThreshold(0.0),
_usingCustomScrollThreshold(false),
_childFocusCancelOffset(5.0f),
_pageViewEventListener(nullptr),
_pageViewEventSelector(nullptr),
_eventCallback(nullptr)
{
    this->setTouchEnabled(true);
}

PageView::~PageView()
{
    _pageViewEventListener = nullptr;
    _pageViewEventSelector = nullptr;
}

PageView* PageView::create()
{
    PageView* widget = new (std::nothrow) PageView();
    if (widget && widget->init())
    {
        widget->autorelease();
        return widget;
    }
    CC_SAFE_DELETE(widget);
    return nullptr;
}

void PageView::onEnter()
{
#if CC_ENABLE_SCRIPT_BINDING
    if (_scriptType == kScriptTypeJavascript)
    {
        if (ScriptEngineManager::sendNodeEventToJSExtended(this, kNodeOnEnter))
            return;
    }
#endif

    Layout::onEnter();
    scheduleUpdate();
}

bool PageView::init()
{
    if (Layout::init())
    {
        setClippingEnabled(true);
        return true;
    }
    return false;
}

void PageView::addWidgetToPage(Widget *widget, ssize_t pageIdx, bool forceCreate)
{
    if (!widget || pageIdx < 0)
    {
        return;
    }

    ssize_t pageCount = this->getPageCount();
    if (pageIdx < 0 || pageIdx >= pageCount)
    {
        if (forceCreate)
        {
            if (pageIdx > pageCount)
            {
                CCLOG("pageIdx is %d, it will be added as page id [%d]",static_cast<int>(pageIdx),static_cast<int>(pageCount));
            }
            Layout* newPage = createPage();
            newPage->addChild(widget);
            addPage(newPage);
        }
    }
    else
    {
        Node * page = _pages.at(pageIdx);
        page->addChild(widget);
    }
}

Layout* PageView::createPage()
{
    Layout* newPage = Layout::create();
    newPage->setContentSize(getContentSize());
    return newPage;
}

void PageView::addPage(Layout* page)
{
    if (!page || _pages.contains(page))
    {
        return;
    }

    addChild(page);
    _pages.pushBack(page);

    _doLayoutDirty = true;
}

void PageView::insertPage(Layout* page, int idx)
{
    if (idx < 0 || !page || _pages.contains(page))
    {
        return;
    }

    ssize_t pageCount = this->getPageCount();
    if (idx >= pageCount)
    {
        addPage(page);
    }
    else
    {
        _pages.insert(idx, page);
        addChild(page);

    }

    _doLayoutDirty = true;
}

void PageView::removePage(Layout* page)
{
    if (!page)
    {
        return;
    }
    removeChild(page);
    _pages.eraseObject(page);

    _doLayoutDirty = true;
}

void PageView::removePageAtIndex(ssize_t index)
{
    if (index < 0 || index >= this->getPages().size())
    {
        return;
    }
    Layout* page = _pages.at(index);
    removePage(page);
}

void PageView::removeAllPages()
{
    for(const auto& node : _pages)
    {
        removeChild(node);
    }
    _pages.clear();
}

void PageView::updateBoundaryPages()
{
    if (_pages.size() <= 0)
    {
        _leftBoundaryChild = nullptr;
        _rightBoundaryChild = nullptr;
        return;
    }
    _leftBoundaryChild = _pages.at(0);
    _rightBoundaryChild = _pages.at(this->getPageCount()-1);
}

ssize_t PageView::getPageCount()const
{
    return _pages.size();
}

float PageView::getPositionXByIndex(ssize_t idx)const
{
    return (getContentSize().width * (idx-_curPageIdx));
}

void PageView::onSizeChanged()
{
    Layout::onSizeChanged();
    _rightBoundary = getContentSize().width;

    _doLayoutDirty = true;
}

void PageView::updateAllPagesSize()
{
    Size selfSize = getContentSize();
    for (auto& page : _pages)
    {
        page->setContentSize(selfSize);
    }
}

void PageView::updateAllPagesPosition()
{
    ssize_t pageCount = this->getPageCount();

    if (pageCount <= 0)
    {
        _curPageIdx = 0;
        return;
    }

    if (_curPageIdx >= pageCount)
    {
        _curPageIdx = pageCount-1;
    }

    float pageWidth = getContentSize().width;
    for (int i=0; i<pageCount; i++)
    {
        Layout* page = _pages.at(i);
        page->setPosition(Vec2((i-_curPageIdx) * pageWidth, 0));

    }
}

void PageView::scrollToPage(ssize_t idx)
{
    if (idx < 0 || idx >= this->getPageCount())
    {
        return;
    }
    _curPageIdx = idx;
    Layout* curPage = _pages.at(idx);
    _autoScrollDistance = -(curPage->getPosition().x);
    _autoScrollSpeed = fabs(_autoScrollDistance)/0.2f;
    _autoScrollDirection = _autoScrollDistance > 0 ? AutoScrollDirection::RIGHT : AutoScrollDirection::LEFT;
    _isAutoScrolling = true;
}

void PageView::update(float dt)
{
    if (_isAutoScrolling)
    {
        this->autoScroll(dt);
    }
}

void PageView::autoScroll(float dt)
    {
        switch (_autoScrollDirection)
        {
            case AutoScrollDirection::LEFT:
            {
                float step = _autoScrollSpeed*dt;
                if (_autoScrollDistance + step >= 0.0f)
                {
                    step = -_autoScrollDistance;
                    _autoScrollDistance = 0.0f;
                    _isAutoScrolling = false;
                }
                else
                {
                    _autoScrollDistance += step;
                }
                scrollPages(-step);
                if (!_isAutoScrolling)
                {
                    pageTurningEvent();
                }
                break;
            }
                break;
            case AutoScrollDirection::RIGHT:
            {
                float step = _autoScrollSpeed*dt;
                if (_autoScrollDistance - step <= 0.0f)
                {
                    step = _autoScrollDistance;
                    _autoScrollDistance = 0.0f;
                    _isAutoScrolling = false;
                }
                else
                {
                    _autoScrollDistance -= step;
                }
                scrollPages(step);

                if (!_isAutoScrolling)
                {
                    pageTurningEvent();
                }

                break;
            }
            default:
                break;
        }

    }

bool PageView::onTouchBegan(Touch *touch, Event *unusedEvent)
{
    bool pass = Layout::onTouchBegan(touch, unusedEvent);
    return pass;
}

void PageView::onTouchMoved(Touch *touch, Event *unusedEvent)
{
    Layout::onTouchMoved(touch, unusedEvent);
    if (!_isInterceptTouch)
    {
        handleMoveLogic(touch);
    }
}

void PageView::onTouchEnded(Touch *touch, Event *unusedEvent)
{
    Layout::onTouchEnded(touch, unusedEvent);
    if (!_isInterceptTouch)
    {
        handleReleaseLogic(touch);
    }
    _isInterceptTouch = false;
}

void PageView::onTouchCancelled(Touch *touch, Event *unusedEvent)
{
    Layout::onTouchCancelled(touch, unusedEvent);
    if (!_isInterceptTouch)
    {
        handleReleaseLogic(touch);
    }
    _isInterceptTouch = false;
}

void PageView::doLayout()
{
    if (!_doLayoutDirty)
    {
        return;
    }

    updateAllPagesPosition();
    updateAllPagesSize();
    updateBoundaryPages();

    _doLayoutDirty = false;
}

void PageView::movePages(float offset)
{
    for (auto& page : this->getPages())
    {
        page->setPosition(Vec2(page->getPosition().x + offset,
                               page->getPosition().y));
    }
}

bool PageView::scrollPages(float touchOffset)
{
    if (this->getPageCount() <= 0)
    {
        return false;
    }

    if (!_leftBoundaryChild || !_rightBoundaryChild)
    {
        return false;
    }

    float realOffset = touchOffset;

    switch (_touchMoveDirection)
    {
        case TouchDirection::LEFT: // left

            if (_rightBoundaryChild->getRightBoundary() + touchOffset <= _rightBoundary)
            {
                realOffset = _rightBoundary - _rightBoundaryChild->getRightBoundary();
                movePages(realOffset);
                return false;
            }
            break;

        case TouchDirection::RIGHT: // right

            if (_leftBoundaryChild->getLeftBoundary() + touchOffset >= _leftBoundary)
            {
                realOffset = _leftBoundary - _leftBoundaryChild->getLeftBoundary();
                movePages(realOffset);
                return false;
            }
            break;
        default:
            break;
    }

    movePages(realOffset);
    return true;
}

void PageView::handleMoveLogic(Touch *touch)
{
    Vec2 touchPoint = touch->getLocation();

    float offset = 0.0;
    offset = touchPoint.x - touch->getPreviousLocation().x;

    if (offset < 0)
    {
        _touchMoveDirection = TouchDirection::LEFT;
    }
    else if (offset > 0)
    {
        _touchMoveDirection = TouchDirection::RIGHT;
    }
    scrollPages(offset);
}

void PageView::setCustomScrollThreshold(float threshold)
{
    CCASSERT(threshold > 0, "Invalid threshold!");
    _customScrollThreshold = threshold;
    this->setUsingCustomScrollThreshold(true);
}

float PageView::getCustomScrollThreshold()const
{
    return _customScrollThreshold;
}

void PageView::setUsingCustomScrollThreshold(bool flag)
{
    _usingCustomScrollThreshold = flag;
}

bool PageView::isUsingCustomScrollThreshold()const
{
    return _usingCustomScrollThreshold;
}

void PageView::handleReleaseLogic(Touch *touch)
{
    if (this->getPageCount() <= 0)
    {
        return;
    }
    Widget* curPage = dynamic_cast<Widget*>(this->getPages().at(_curPageIdx));
    if (curPage)
    {
        Vec2 curPagePos = curPage->getPosition();
        ssize_t pageCount = this->getPageCount();
        float curPageLocation = curPagePos.x;
        float pageWidth = getContentSize().width;
        if (!_usingCustomScrollThreshold) {
            _customScrollThreshold = pageWidth / 2.0;
        }
        float boundary = _customScrollThreshold;
        if (curPageLocation <= -boundary)
        {
            if (_curPageIdx >= pageCount-1)
            {
                scrollPages(-curPageLocation);
            }
            else
            {
                scrollToPage(_curPageIdx+1);
            }
        }
        else if (curPageLocation >= boundary)
        {
            if (_curPageIdx <= 0)
            {
                scrollPages(-curPageLocation);
            }
            else
            {
                scrollToPage(_curPageIdx-1);
            }
        }
        else
        {
            scrollToPage(_curPageIdx);
        }
    }
}

void PageView::interceptTouchEvent(TouchEventType event, Widget *sender, Touch *touch)
{
    Vec2 touchPoint = touch->getLocation();

    switch (event)
    {
        case TouchEventType::BEGAN:
        {
            _touchBeganPosition = touch->getLocation();
            _isInterceptTouch = true;
        }
            break;
        case TouchEventType::MOVED:
        {
            float offset = 0;
            offset = fabs(sender->getTouchBeganPosition().x - touchPoint.x);
            _touchMovePosition = touch->getLocation();
            if (offset > _childFocusCancelOffset)
            {
                sender->setHighlighted(false);
                handleMoveLogic(touch);
            }
        }
            break;
        case TouchEventType::CANCELED:
        case TouchEventType::ENDED:
        {
            _touchEndPosition = touch->getLocation();
            handleReleaseLogic(touch);
            if (sender->isSwallowTouches())
            {
                _isInterceptTouch = false;
            }
        }
            break;
    }
}

void PageView::pageTurningEvent()
{
    this->retain();
    if (_pageViewEventListener && _pageViewEventSelector)
    {
        (_pageViewEventListener->*_pageViewEventSelector)(this, PAGEVIEW_EVENT_TURNING);
    }
    if (_eventCallback) {
        _eventCallback(this,EventType::TURNING);
    }
    if (_ccEventCallback)
    {
        _ccEventCallback(this, static_cast<int>(EventType::TURNING));
    }
    this->release();
}

void PageView::addEventListenerPageView(Ref *target, SEL_PageViewEvent selector)
{
    _pageViewEventListener = target;
    _pageViewEventSelector = selector;
}

void PageView::addEventListener(const ccPageViewCallback& callback)
{
    _eventCallback = callback;
}

ssize_t PageView::getCurPageIndex() const
{
    return _curPageIdx;
}

Vector<Layout*>& PageView::getPages()
{
    return _pages;
}

Layout* PageView::getPage(ssize_t index)
{
    if (index < 0 || index >= this->getPages().size())
    {
        return nullptr;
    }
    return _pages.at(index);
}

std::string PageView::getDescription() const
{
    return "PageView";
}

Widget* PageView::createCloneInstance()
{
    return PageView::create();
}

void PageView::copyClonedWidgetChildren(Widget* model)
{
    auto modelPages = static_cast<PageView*>(model)->getPages();
    for (auto& page : modelPages)
    {
        addPage(static_cast<Layout*>(page->clone()));
    }
}

void PageView::copySpecialProperties(Widget *widget)
{
    PageView* pageView = dynamic_cast<PageView*>(widget);
    if (pageView)
    {
        Layout::copySpecialProperties(widget);
        _eventCallback = pageView->_eventCallback;
        _ccEventCallback = pageView->_ccEventCallback;
        _pageViewEventListener = pageView->_pageViewEventListener;
        _pageViewEventSelector = pageView->_pageViewEventSelector;
        _usingCustomScrollThreshold = pageView->_usingCustomScrollThreshold;
        _customScrollThreshold = pageView->_customScrollThreshold;
    }
}

}

NS_CC_END


text:
using System;
using System.Collections;
using System.Data;
using System.Globalization;
using System.Transactions;
using PCSComMaterials.Inventory.DS;
using PCSComMaterials.Plan.DS;
using PCSComProduct.Items.DS;
using PCSComUtils.Common;
using PCSComUtils.Common.BO;
using PCSComUtils.Common.DS;

using PCSComUtils.MasterSetup.DS;
using PCSComUtils.PCSExc;

namespace PCSComMaterials.Plan.BO
{
    public class MPSRegenerationForKMPCompanyBO
    {
        public DataSet GetList(int iMPSCycleOptionMasterIDID)
        {
            MPSRegenerationForKMPCompanyDS objDs = new MPSRegenerationForKMPCompanyDS();
            return objDs.GetList(iMPSCycleOptionMasterIDID);
        }
    }
}


text:
import fn from '../../addQuarters/index'
import convertToFP from '../_lib/convertToFP/index'

export default convertToFP(fn, 2)


text:
import pyck

domain = [100.0, 100.0, 500.0]
h = domain[0] / 100
smoothingKernelFunc = 2
speedsound = 1
density = 1
shearmodulus = 1
bulkmodulus = 1
# Create a packer, see packers directory for options
Hcp = pyck.HcpPacker(domain, h)
pack = pyck.StructuredPack(Hcp)

tibia_min = [154.2328, 204.0634, -853.9525]  # Read from the tibia STL file
tibia_max = [226.9384, 268.8318, -468.3400]
tibia_len = [tibia_max[0] - tibia_min[0], tibia_max[1] -
             tibia_min[1], tibia_max[2] - tibia_min[2]]
tibia_center = [tibia_min[0] + tibia_len[0] / 2, tibia_min[1] +
                tibia_len[1] / 2, tibia_min[2] + tibia_len[2] / 2]
tibia_scale = 1
tibia_len[0] = tibia_len[0] * tibia_scale
tibia_len[1] = tibia_len[1] * tibia_scale
tibia_len[2] = tibia_len[2] * tibia_scale

tibia_dcenter = [domain[0] / 2, domain[1] / 2, domain[2] / 2]
tibia_translation = [tibia_dcenter[0] - tibia_center[0],
                     tibia_dcenter[1] - tibia_center[1], tibia_dcenter[2] - tibia_center[2]]

stlShape = pyck.StlShape(1, 'tibia_low.stl', tibia_translation)

#cube = pyck.Cuboid(2,[0.2,0.2,0.2],[0.6,0.6,0.6]);

# Map the shapes and generate the pack
pack.AddShape(stlShape)
# pack.AddShape(cube);
pack.Process()

# Create a new model from the pack
model = pyck.Model(pack)

# Create a new field of n-dimensional integers
# Arguments are CreateIntField(label,dimensions)
# label - label for this field in the vtp file
# dimensions - dimensionality of this field, doesnt have to correspond to model dimensions
# Create field of doubles in the same way with CreateDoubleField
stateField = model.CreateIntField("State", 1)

# Arguments are SetIntField(field,tag,value(s))
# field - returned from CreateIntField
# tag - tag applied to particles during shape Mapping
# value(s) - singular value or array of values [v1, v2,...vn] to set of
# particles with a matching tag
model.SetIntField(stateField, 1, 10)
model.SetIntField(stateField, 2, 20)

# Overwrite some parameters
# Arguments are SetParameter(Label,Value)
model.SetParameter("MaxSteps", "100")
model.SetParameter("Mass", "0.5")

# Or use a python dictionary to overwrite parameters
parameters = pyck.Parameters({'ViscAlpha': '0.1', 'ViscBeta': '0.2'})
model.SetParameters(parameters)

# Create a file writer, in this case VTP according to spark format
writer = pyck.SparkWriter()

# Write the VTP file
model.Serialize("tibia.vtp", writer)