text:
#import "HexGrid.h"
#import "Game.h"

@implementation HexGrid

- (id) initWithRows: (unsigned)nRows columns: (unsigned)nColumns
            spacing: (CGSize)spacing
           position: (CGPoint)pos
{
    // Ignore given spacing.height; set it to make the hexagons regular.
    CGFloat capHeight = spacing.height / 2 * tan(M_PI/6);
    CGFloat side = spacing.height / 2 / cos(M_PI/6);
    spacing.height = side + capHeight;

    self = [super initWithRows: nRows columns: nColumns
                       spacing: spacing
                      position: pos];
    if( self ) {
        _capHeight = capHeight;
        _side = side;
        self.bounds = CGRectMake(-1, -1,
                                 (nColumns+0.5)*spacing.width + 2,
                                 nRows*spacing.height+capHeight + 2);
        _cellClass = [Hex class];
    }
    return self;
}

- (id) initWithRows: (unsigned)nRows columns: (unsigned)nColumns
              frame: (CGRect)frame;
{
    // Compute the horizontal spacing:
    CGFloat s = floor(MIN( (frame.size.width -2.0)/nColumns,
                         (frame.size.height-2.0)/(nRows+0.5*tan(M_PI/6)) / (0.5*(tan(M_PI/6)+1/cos(M_PI/6))) ));
    self = [self initWithRows: nRows columns: nColumns
                      spacing: CGSizeMake(s,s)
                     position: frame.origin];
    if( self ) {
        // Center in frame:
        CGRect curFrame = self.frame;
        curFrame.origin.x = round( curFrame.origin.x + (frame.size.width - curFrame.size.width )/2.0f );
        curFrame.origin.y = round( curFrame.origin.y + (frame.size.height- curFrame.size.height)/2.0f );
        self.frame = curFrame;
    }
    return self;
}

- (void) dealloc
{
    CGPathRelease(_cellPath);
    [super dealloc];
}

- (void) addCellsInHexagon
{
    int size = _nRows - !(_nRows & 1);      // make it odd
    for( int row=0; row<_nRows; row++ ) {
        int n;                              // # of hexes remaining in this row
        if( row < size )
            n = size - abs(row-size/2);
        else
            n = 0;
        int c0 = floor(((int)_nRows+1-n -(row&1))/2.0);       // col of 1st remaining hex

        for( int col=0; col<_nColumns; col++ )
            if( col>=c0 && col<c0+n )
                [self addCellAtRow: row column: col];
    }
}

- (GridCell*) createCellAtRow: (unsigned)row column: (unsigned)col
               suggestedFrame: (CGRect)frame
{
    // Overridden to stagger the odd-numbered rows
    BOOL stagger = (row & 1) != 0;
    if( _reversed && (_nRows & 1) )
        stagger = !stagger;
    if( stagger )
        frame.origin.x += _spacing.width/2;
    frame.size.height += _capHeight;
    return [super createCellAtRow: row column: col suggestedFrame: frame];
}

// Returns a hexagonal CG path defining a cell's outline. Used by cells when drawing & hit-testing.
- (CGPathRef) cellPath
{
    if( ! _cellPath ) {
        CGFloat x1 = _spacing.width/2;
        CGFloat x2 = _spacing.width;
        CGFloat y1 = _capHeight;
        CGFloat y2 = y1 + _side;
        CGFloat y3 = y2 + _capHeight;
        CGPoint p[6] = { {0,y1}, {x1,0}, {x2,y1}, {x2,y2}, {x1,y3}, {0,y2} };

        CGMutablePathRef path = CGPathCreateMutable();
        CGPathAddLines(path, NULL, p, 6);
        CGPathCloseSubpath(path);
        _cellPath = path;
    }
    return _cellPath;
}

@end

#pragma mark -

@implementation Hex

- (void) drawInParentContext: (CGContextRef)ctx fill: (BOOL)fill
{
    CGContextSaveGState(ctx);
    CGPoint pos = self.position;
    CGContextTranslateCTM(ctx, pos.x, pos.y);
    CGContextBeginPath(ctx);
    CGContextAddPath(ctx, [(HexGrid*)_grid cellPath]);
    CGContextDrawPath(ctx, (fill ?kCGPathFill :kCGPathStroke));

    if( !fill && self.highlighted ) {
        // Highlight by drawing my outline in the highlight color:
        CGContextSetStrokeColorWithColor(ctx, self.borderColor);
        CGContextSetLineWidth(ctx,6);
        CGContextBeginPath(ctx);
        CGContextAddPath(ctx, [(HexGrid*)_grid cellPath]);
        CGContextDrawPath(ctx, kCGPathStroke);
    }
    CGContextRestoreGState(ctx);
}

- (BOOL)containsPoint:(CGPoint)p
{
    return [super containsPoint: p]
        && CGPathContainsPoint( [(HexGrid*)_grid cellPath], NULL, p, NO );
}

- (void) setHighlighted: (BOOL)highlighted
{
    if( highlighted != self.highlighted ) {
        [super setHighlighted: highlighted];
        [_grid setNeedsDisplay];        // So I'll be asked to redraw myself
    }
}

#pragma mark -
#pragma mark NEIGHBORS:

- (NSArray*) neighbors
{
    NSMutableArray *neighbors = [NSMutableArray arrayWithCapacity: 6];
    Hex* n[6] = {self.nw, self.ne, self.w, self.e, self.sw, self.se};
    for( int i=0; i<6; i++ )
        if( n[i] )
            [neighbors addObject: n[i]];
    return neighbors;
}

- (Hex*) nw     {return (Hex*)[_grid cellAtRow: _row+1 column: _column - ((_row+1)&1)];}
- (Hex*) ne     {return (Hex*)[_grid cellAtRow: _row+1 column: _column + (_row&1)];}
- (Hex*) e      {return (Hex*)[_grid cellAtRow: _row   column: _column + 1];}
- (Hex*) se     {return (Hex*)[_grid cellAtRow: _row-1 column: _column + (_row&1)];}
- (Hex*) sw     {return (Hex*)[_grid cellAtRow: _row-1 column: _column - ((_row-1)&1)];}
- (Hex*) w      {return (Hex*)[_grid cellAtRow: _row   column: _column - 1];}

// Directions relative to the current player:
- (Hex*) fl     {return self.fwdIsN ?self.nw :self.se;}
- (Hex*) fr     {return self.fwdIsN ?self.ne :self.sw;}
- (Hex*) r      {return self.fwdIsN ?self.e  :self.w;}
- (Hex*) br     {return self.fwdIsN ?self.se :self.nw;}
- (Hex*) bl     {return self.fwdIsN ?self.sw :self.ne;}
- (Hex*) l      {return self.fwdIsN ?self.w  :self.e;}

@end


text:
<?php

// src/Lestroistoques/RecettesBundle/Form/RecetteIngredientEditType.php

namespace Lestroistoques\RecettesBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class RecetteIngredientEditType extends RecetteIngredientType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);

        $builder
            ->add   ('ingredient', new IngredientType(), array('disabled' => 'true'))
        ;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'lestroistoques_recettesbundle_recetteingredientedit';
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.camunda.bpm.engine.impl.batch;

import static org.camunda.bpm.engine.impl.util.EnsureUtil.ensureNotNull;

import org.camunda.bpm.engine.impl.batch.BatchMonitorJobHandler.BatchMonitorJobConfiguration;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.jobexecutor.JobHandler;
import org.camunda.bpm.engine.impl.jobexecutor.JobHandlerConfiguration;
import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity;
import org.camunda.bpm.engine.impl.persistence.entity.JobEntity;

/**
 * Job handler for batch monitor jobs. The batch monitor job
 * polls for the completion of the batch.
 */
public class BatchMonitorJobHandler implements JobHandler<BatchMonitorJobConfiguration> {

  public static final String TYPE = "batch-monitor-job";

  public String getType() {
    return TYPE;
  }

  public void execute(BatchMonitorJobConfiguration configuration, ExecutionEntity execution, CommandContext commandContext, String tenantId) {

    String batchId = configuration.getBatchId();
    BatchEntity batch = commandContext.getBatchManager().findBatchById(configuration.getBatchId());
    ensureNotNull("Batch with id '" + batchId + "' cannot be found", "batch", batch);

    boolean completed = batch.isCompleted();

    if (!completed) {
      batch.createMonitorJob(true);
    }
    else {
      batch.delete(false, false);
    }
  }

  @Override
  public BatchMonitorJobConfiguration newConfiguration(String canonicalString) {
    return new BatchMonitorJobConfiguration(canonicalString);
  }

  public static class BatchMonitorJobConfiguration implements JobHandlerConfiguration {
    protected String batchId;

    public BatchMonitorJobConfiguration(String batchId) {
      this.batchId = batchId;
    }

    public String getBatchId() {
      return batchId;
    }

    @Override
    public String toCanonicalString() {
      return batchId;
    }
  }

  public void onDelete(BatchMonitorJobConfiguration configuration, JobEntity jobEntity) {
    // do nothing
  }

}


text:
package minium.cucumber.rest;

import static minium.cucumber.rest.CucumberRestConstants.GLUES_URI;
import static minium.cucumber.rest.CucumberRestConstants.HOOK_EXEC_URI;
import static minium.cucumber.rest.CucumberRestConstants.HOOK_TAG_MATCH_URI;
import static minium.cucumber.rest.CucumberRestConstants.SNIPPET_URI;
import static minium.cucumber.rest.CucumberRestConstants.STEP_EXEC_URI;
import static minium.cucumber.rest.CucumberRestConstants.STEP_MATCHED_URI;
import static minium.cucumber.rest.CucumberRestConstants.WORLDS_URI;
import static minium.cucumber.rest.CucumberRestConstants.WORLD_URI;
import gherkin.I18n;
import gherkin.formatter.Argument;
import gherkin.formatter.model.Step;
import gherkin.formatter.model.Tag;

import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import minium.cucumber.rest.dto.ArgumentDTO;
import minium.cucumber.rest.dto.ExecutionResult.Status;
import minium.cucumber.rest.dto.GlueDTO;
import minium.cucumber.rest.dto.HookDefinitionDTO;
import minium.cucumber.rest.dto.HookExecutionResult;
import minium.cucumber.rest.dto.ScenarioDTO;
import minium.cucumber.rest.dto.SnippetRequestDTO;
import minium.cucumber.rest.dto.StepDTO;
import minium.cucumber.rest.dto.StepDefinitionDTO;
import minium.cucumber.rest.dto.StepDefinitionInvocation;
import minium.cucumber.rest.dto.StepExecutionResult;
import minium.cucumber.rest.dto.StepMatchDTO;
import minium.cucumber.rest.dto.TagDTO;
import minium.cucumber.rest.dto.WorldDTO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import com.google.common.base.Preconditions;

import cucumber.api.Scenario;
import cucumber.api.SnippetType;
import cucumber.runtime.Backend;
import cucumber.runtime.Glue;
import cucumber.runtime.UnreportedStepExecutor;
import cucumber.runtime.snippets.FunctionNameGenerator;

public class RemoteBackend implements Backend {

    private static final Logger LOGGER = LoggerFactory.getLogger(RemoteBackend.class);

    private static final String FUNCTION_NAME = "function name";
    private static final Map<String, SnippetType> snippetTypes = new HashMap<String, SnippetType>();

    static {
        snippetTypes.put(SnippetType.CAMELCASE.getFunctionNameGenerator().generateFunctionName(FUNCTION_NAME), SnippetType.CAMELCASE);
        snippetTypes.put(SnippetType.UNDERSCORE.getFunctionNameGenerator().generateFunctionName(FUNCTION_NAME), SnippetType.UNDERSCORE);
    }

    private final String backendUrl;
    private final RestTemplate template;
    private WorldDTO world;

    public RemoteBackend(String baseUrl) {
        this(baseUrl, new RestTemplate());
    }

    public RemoteBackend(String baseUrl, RestTemplate template) {
        this.backendUrl = baseUrl;
        this.template = template;
    }

    public RestTemplate getTemplate() {
        return template;
    }

    @Override
    public void loadGlue(Glue glue, List<String> gluePaths) {
        URI uri = uriBuilderFor(GLUES_URI).queryParam("path", gluePaths.toArray()).buildAndExpand().toUri();
        GlueDTO remoteGlue = template.postForObject(uri, null, GlueDTO.class);

        for (HookDefinitionDTO definitionDto : remoteGlue.getBeforeHooks()) {
            glue.addBeforeHook(new RemoteHookDefinition(this, definitionDto));
        }
        for (HookDefinitionDTO definitionDto : remoteGlue.getAfterHooks()) {
            glue.addAfterHook(new RemoteHookDefinition(this, definitionDto));
        }
        for (StepDefinitionDTO definitionDto : remoteGlue.getStepDefinitions()) {
            glue.addStepDefinition(new RemoteStepDefinition(this, definitionDto));
        }
    }

    @Override
    public void setUnreportedStepExecutor(UnreportedStepExecutor executor) {
        // not used here
    }

    @Override
    public void buildWorld() {
        if (world != null) {
            LOGGER.warn("A world with UUID {} already exists", world.getUuid());
        }
        URI uri = uriBuilderFor(WORLDS_URI).buildAndExpand().toUri();
        world = template.postForObject(uri, null, WorldDTO.class);
    }

    @Override
    public void disposeWorld() {
        if (world == null) {
            LOGGER.warn("No world exists");
        } else {
            URI uri = uriBuilderFor(WORLD_URI).buildAndExpand(world.getUuid()).toUri();
            template.delete(uri);
            world = null;
        }
    }

    @Override
    public String getSnippet(Step step, FunctionNameGenerator nameGenerator) {
        SnippetType snippetType = getSnippetType(nameGenerator);
        URI uri = uriBuilderFor(SNIPPET_URI).buildAndExpand().toUri();
        SnippetRequestDTO snippetRequest = new SnippetRequestDTO(new StepDTO(step), snippetType);
        return template.postForObject(uri, snippetRequest, String.class);
    }

    public void execute(HookDefinitionDTO hookDefinition, Scenario scenario) {
        ScenarioDTO remoteScenario = new ScenarioDTO(scenario);
        URI uri = uriBuilderFor(HOOK_EXEC_URI).buildAndExpand(hookDefinition.getGlueId(), hookDefinition.getId()).toUri();
        HookExecutionResult execution = template.postForObject(uri, remoteScenario, HookExecutionResult.class);
        remoteScenario.populate(scenario);

        if (execution.getStatus() == Status.FAILED) {
            throw new RemoteExecutionException(execution.getException());
        }
    }

    public boolean matches(HookDefinitionDTO hookDefinition, Collection<Tag> tags) {
        URI uri = uriBuilderFor(HOOK_TAG_MATCH_URI).buildAndExpand(hookDefinition.getGlueId(), hookDefinition.getId()).toUri();
        return template.postForObject(uri, toTagDTOs(tags), Boolean.class);
    }

    public void execute(StepDefinitionDTO stepDefinition, I18n i18n, Object[] args) {
        StepDefinitionInvocation stepDefinitionInvocation = new StepDefinitionInvocation(i18n, args);
        URI uri = uriBuilderFor(STEP_EXEC_URI).buildAndExpand(stepDefinition.getGlueId(), stepDefinition.getId()).toUri();
        StepExecutionResult execution = template.postForObject(uri, stepDefinitionInvocation, StepExecutionResult.class);

        if (execution.getStatus() == Status.FAILED) {
            throw new RemoteExecutionException(execution.getException());
        }
    }

    public SnippetType getSnippetType(FunctionNameGenerator nameGenerator) {
        String functionName = nameGenerator.generateFunctionName(FUNCTION_NAME);
        SnippetType snippetType = snippetTypes.get(functionName);
        return Preconditions.checkNotNull(snippetType, "FunctionNameGenerator is not camel case or underscore (it generated %s)", functionName);
    }

    public List<Argument> matchedArguments(StepDefinitionDTO stepDefinition, Step step) {
        StepDTO stepProxy = new StepDTO(step);
        URI uri = uriBuilderFor(STEP_MATCHED_URI).buildAndExpand(stepDefinition.getGlueId(), stepDefinition.getId()).toUri();
        StepMatchDTO match = template.postForObject(uri, stepProxy, StepMatchDTO.class);
        return toGerkinArguments(match.getArguments());
    }

    protected UriComponentsBuilder uriBuilderFor(String path) {
        return UriComponentsBuilder.fromHttpUrl(backendUrl + path);
    }

    protected List<Argument> toGerkinArguments(ArgumentDTO[] matchedArguments) {
        if (matchedArguments == null) return null;
        List<Argument> gherkinArgs = new ArrayList<Argument>();
        for (ArgumentDTO arg : matchedArguments) {
            gherkinArgs.add(arg.toArgument());
        }
        return gherkinArgs;
    }

    protected List<TagDTO> toTagDTOs(Collection<Tag> gherkinTags) {
        if (gherkinTags == null) return null;
        List<TagDTO> dtos = new ArrayList<TagDTO>();
        for (Tag gherkinTag : gherkinTags) {
            dtos.add(new TagDTO(gherkinTag));
        }
        return dtos;
    }
}


text:
import sys
from java.lang import *
from java.util import *
from java.io import *
from org.xml.sax import *
from gov.sns.xal.smf import *
from gov.sns.xal.smf.impl import *
from gov.sns.xal.smf.impl.qualify import *
from gov.sns.xal.smf.xdxf import *
from gov.sns.xal.smf.parser import *
from gov.sns.xal.smf.data import *
from gov.sns.xal.model import *
from gov.sns.xal.model.xml import *
from gov.sns.tools.beam import *
###################################################################################
false= (1<0)
true=(1>0)

latin="MEBT"
#latin="lanl_MEBT"

#probin="particle"
probin="envelope"

# lattice input locations
lat_file={
	"MEBT":"xml/MEBT_lanl_lattice.xml",
	"lanl_MEBT":"/home/klotz/workspace/xaldev/work/xml/ModelValidation.lat.mod.xal.xml"}

# probe input locations
prb_file={
	"??":"workspace/xaldev/xal_xmls/sns_probes.xml",
	"particle":"/home/klotz/workspace/xaldev/work/xml/ModelValidation.particle.probe.mod.xal.xml",
	"envelope":"/home/klotz/workspace/xaldev/work/xml/ModelValidation.envelope.probe.mod.xal.xml"}

def showParticleProbe(traj):
	iterState= traj.stateIterator()
	count=0
	print "PARTICLE PROBE RESULTS"
	titles =  "  Position      Energy        x            x'          y           y'"
	titles+=  "\n======================================================================="
	print titles
	while iterState.hasNext():
		count += 1
		if count%10==0:
			print "\n",titles

		state= iterState.next()
		s= state.getPosition()
		W= state.getKineticEnergy()
		phasevect= state.phaseCoordinates()
		x= phasevect.getx()
		xp=phasevect.getxp()
		y =phasevect.gety()
		yp=phasevect.getyp()

		#digits=8
		#buffer = repr(s)[:digits]
		#buffer+= "  "+repr(W)[:digits]
		#buffer+= "  "+repr(x)[:digits]
		#buffer+= "  "+repr(xp)[:digits]
		#buffer+= "  "+repr(y)[:digits]
		#buffer+= "  "+repr(yp)[:digits]

		float="%+010f"
		scien="%+010.3e"
		digits = float % s
		buffer = digits
		digits = scien % W
		buffer += "  "+digits
		digits = float % x
		buffer += "  "+digits
		digits = float % xp
		buffer += "  "+digits
		digits = float % y
		buffer += "  "+digits
		digits = float % yp
		buffer += "  "+digits
		buffer += "  "+state.getElementId()
		print buffer

def showEnvelopeProbe(traj):
	iterState= traj.stateIterator()
	count=0
	print "ENVELOPE PROBE RESULTS"
	titles =  "  Position      eps-x         x            x'        eps-y          y           y'"
	titles+=  "\n===================================================================================="
	print titles
	while iterState.hasNext():
		count += 1
		if count%10==0:
			print "\n",titles

		state= iterState.next()
		s= state.getPosition()
		twiss= state.twissParameters()

		x = twiss[0].getEnvelopeRadius()
		xp= twiss[0].getEnvelopeSlope()
		ex= twiss[0].getEmittance()

		y = twiss[1].getEnvelopeRadius()
		yp= twiss[1].getEnvelopeSlope()
		ey= twiss[1].getEmittance()

		float="%+010f"
		scien="%+010.3e"
		digits = float % s
		buffer = digits
		digits = scien % ex
		buffer += "  "+digits
		digits = float % x
		buffer += "  "+digits
		digits = float % xp
		buffer += "  "+digits
		digits = scien % ey
		buffer += "  "+digits
		digits = float % y
		buffer += "  "+digits
		digits = float % yp
		buffer += "  "+digits
		buffer += "  "+state.getElementId()
		print buffer

if __name__ == '__main__':

	#load the lattice
	try:
		cin=lat_file[latin]
		print "Using '",cin,"' as lattice input"
		print "======================================================"
		lattice = LatticeXmlParser.parse(cin,false)

		#dump current state and content to output
		buffer =    "LATTICE - "+lattice.getType()
		buffer += "\nID        :"+lattice.getId()
		buffer += "\nAuthor    :"+lattice.getAuthor()
		buffer += "\nDate      :"+lattice.getDate()
		buffer += "\nVersion   :"+lattice.getVersion()
		buffer += "\nComments  :"+lattice.getComments()
		buffer += "\nChildren  :"+repr(lattice.getChildCount())
		buffer += "\nLeaves    :"+repr(lattice.getLeafCount())
		buffer += "\nLength    :"+repr(lattice.getLength())
		buffer += "\n================================================"
		print buffer

		cout= PrintWriter(System.out, Boolean("true"))
		#lattice.print(cout)

	except ParsingException:
		print ParsingException.getMessage()
		sys.exit(-1)
	except Exception:
		print Exception.getMessage()
		sys.exit(-1)

	#laod the probe
	try:
		cin=prb_file[probin]
		print "Using '",cin,"' as probe input"
		print "======================================================"
		envProbe=ProbeXmlParser.parse(cin)

		#dump some initial probe parameters
		buffer  = "PROBE - " +repr(envProbe.getComment())
		buffer += "\nBeta               :"+repr(envProbe.getBeta())
		buffer += "\nGamma              :"+repr(envProbe.getGamma())
		buffer += "\nKinetic Energy     :"+repr(envProbe.getKineticEnergy())
		buffer += "\nPosition           :"+repr(envProbe.getPosition())
		buffer += "\nSpecies Charge     :"+repr(envProbe.getSpeciesCharge())
		buffer += "\nSpecies Rest Energy:"+repr(envProbe.getSpeciesRestEnergy())
		buffer += "\n================================================"
		print buffer
	except ParsingException:
		print ParsingException.getMessage()
		sys.exit(-1)
	except Exception:
		print Exception.getMessage()
		sys.exit(-1)

	#propagate the probe
	try:
		lattice.propagate(envProbe)
		envTraj= envProbe.getTrajectory()
		envTraj.setDescription("validation trajectory")
	except ModelException:
		print ModelException.getMessage()
		sys.exit(-1)
	except Exception:
		print Exception.getMessage()
		sys.exit(-1)

	#show results
	if probin == "particle":
		showParticleProbe(envTraj)
	if probin == "envelope":
		showEnvelopeProbe(envTraj)


text:
/*!
nphysics
========
**nphysics** is a 2 and 3-dimensional physics engine for games and animations.
It uses [ncollide](http://ncollide.org) for collision detection, and
[nalgebra](http://nalgebra.org) for vector/matrix math. 2D and 3D
implementations both share the same code!

Examples are available in the `examples2d` and `examples3d` directories. There
is also a short (outdated) [demonstration video](http://youtu.be/CANjXZ5rocI).
An on-line version of this documentation is available
[here](http://nphysics.org). Feel free to ask for help and discuss features on
the official [user forum](http://users.nphysics.org).

## Why another physics engine?
There are a lot of physics engine out there.
However having a physics engine written in Rust is much more fun than
writing bindings and has several advantages:

- it shows that Rust is suitable for soft real-time applications
- it shows how well Rust behaves with highly generic code
- it shows that there is no need to write two separate engine for 2D and 3D:
  genericity wrt the dimension is possible (modulo low level arithmetic
  specializations for each dimension).
- in a not-that-near future, C++ will die of ugliness. Then, people will
  search for a physics engine and **nphysics** will be there, proudly
  exhibiting its _Rusty_ sexyness.

## Features
- Static and dynamic rigid bodies.
- Common convex primitives: cone, box, ball, cylinder.
- Concave geometries build from convex primitives (aka. compound geometries).
- Stable stacking.
- Island based sleeping (objects deactivation).
- Ray casting.
- Swept sphere based continuous collision detection.
- Ball-in-socket joint.
- FixedJoint joint.
- Sensors.
- Deformable bodies (aka. soft-bodies)
- Kinematic bodies

## What is missing?
**nphysics** is a very young library and needs to learn a lot of things to
become a grown up. Many missing features are because of missing features on
**ncollide**. Features missing from **nphysics** itself include:

- more joints, joint limits, joint motors and breakable joints.
- parallel pipeline
- GPU-based pipeline

## Dependencies
All dependencies are automatically cloned with a recursive clone.
The libraries needed to compile the physics engine are:

* [ncollide](http://ncollide.org): the collision detection library.
* [nalgebra](http://nalgebra.org): the linear algebra library.

The libraries needed to compile the examples are:

*/
#![deny(non_camel_case_types)]
#![deny(unused_parens)]
#![deny(non_upper_case_globals)]
#![deny(unused_qualifications)]
#![deny(missing_docs)] // FIXME: deny this
#![deny(unused_results)]
#![deny(bare_trait_objects)]
#![allow(type_alias_bounds)]
#![warn(non_camel_case_types)]
#![allow(missing_copy_implementations)]
#![doc(html_root_url = "http://nphysics.org/rustdoc/")]

#[macro_use]
extern crate approx;
#[macro_use]
extern crate downcast_rs;
#[macro_use]
extern crate bitflags;

extern crate nalgebra as na;
#[cfg(feature = "dim2")]
extern crate ncollide2d as ncollide;
#[cfg(feature = "dim3")]
extern crate ncollide3d as ncollide;
extern crate num_traits as num;

//#[cfg(test)]
//extern crate test;

macro_rules! try_ret {
    ($val: expr) => {
        try_ret!($val, ())
    };
    ($val: expr, $ret: expr) => {
        if let Some(val) = $val {
            val
        } else {
            return $ret;
        }
    };
}

macro_rules! try_continue {
    ($val: expr) => {
        if let Some(val) = $val {
            val
        } else {
            continue;
        }
    };
}

macro_rules! desc_setters(
    ($($with_method: ident, $set_method: ident $(, $arg: ident: $t: ty)*)*) => {
        $(
            #[allow(missing_docs)]
            #[inline]
            pub fn $with_method(mut self $(, $arg: $t)*) -> Self {
                $(
                    self.$arg = $arg;
                )*
                self
            }

            #[allow(missing_docs)]
            #[inline]
            pub fn $set_method(&mut self $(, $arg: $t)*) -> &mut Self {
                $(
                    self.$arg = $arg;
                )*
                self
            }
        )*
    }
);

macro_rules! desc_custom_setters(
    ($($this: ident.$with_method: ident, $set_method: ident $(, $arg: ident: $t: ty)* | $imp: expr)*) => {
        $(
            #[allow(missing_docs)]
            #[inline]
            pub fn $with_method(mut $this $(, $arg: $t)*) -> Self {
                $imp
                $this
            }

            #[allow(missing_docs)]
            #[inline]
            pub fn $set_method(&mut $this $(, $arg: $t)*) -> &mut Self {
                $imp
                $this
            }
        )*
    }
);

macro_rules! desc_custom_getters(
    ($($this: ident.$get_method: ident: $t: ty | $imp: expr)*) => {
        $(
            #[allow(missing_docs)]
            #[inline]
            pub fn $get_method(&$this) -> $t {
                $imp
            }
        )*
    }
);

macro_rules! desc_getters(
    ($([val] $name: ident -> $val: ident: $t: ty)* $([ref] $ref_name: ident -> $ref_val: ident: $ref_t: ty)*) => {
        $(
            #[allow(missing_docs)]
            #[inline]
            pub fn $name(&self) -> $t {
                self.$val
            }
        )*
        $(
            #[allow(missing_docs)]
            #[inline]
            pub fn $ref_name(&self) -> &$ref_t {
                &self.$ref_val
            }
        )*
    }
);

macro_rules! user_data_accessors(
    () => {
        /// Retrieves a reference to the user-defined user-data attached to this object.
        #[inline]
        pub fn user_data(&self) -> Option<&(dyn Any + Send + Sync)> {
            self.user_data.as_deref()
        }

        /// Retrieves a mutable reference to the user-defined user-data attached to this object.
        #[inline]
        pub fn user_data_mut(&mut self) -> Option<&mut (dyn Any + Send + Sync)> {
            self.user_data.as_deref_mut()
        }

        /// Sets the user-defined data attached to this object.
        #[inline]
        pub fn set_user_data(&mut self, data: Option<Box<dyn Any + Send + Sync>>) -> Option<Box<dyn Any + Send + Sync>> {
            std::mem::replace(&mut self.user_data, data)
        }

        /// Replace by `None` the user-defined data attached to this object and returns the old value.
        #[inline]
        pub fn take_user_data(&mut self) -> Option<Box<dyn Any + Send + Sync>> {
            self.user_data.take()
        }
    }
);

macro_rules! user_data_desc_accessors(
    () => {
        /// Sets a user-data to be attached to the object being built.
        pub fn user_data(mut self, data: impl UserData) -> Self {
            self.user_data = Some(UserDataBox(Box::new(data) as Box<dyn UserData>));
            self
        }

        /// Sets the user-data to be attached to the object being built.
        pub fn set_user_data(&mut self, data: Option<impl UserData>) -> &mut Self {
            self.user_data = data.map(|data| UserDataBox(Box::new(data) as Box<dyn UserData>));
            self
        }

        /// Reference to the user-data to be attached to the object being built.
        pub fn get_user_data(&self) -> Option<&(dyn Any + Send + Sync)> {
            self.user_data.as_ref().map(|data| data.0.as_any())
        }
    }
);

const NOT_REGISTERED_ERROR: &'static str =
    "This collider has not been registered into a world (proxy indexes are None).";

pub mod algebra;
pub mod counters;
pub mod detection;
pub mod force_generator;
pub mod joint;
pub mod material;
pub mod object;
pub mod solver;
pub mod utils;
pub mod volumetric;
pub mod world;
// mod tests;

pub use nalgebra;
#[cfg(feature = "dim2")]
pub use ncollide2d;
#[cfg(feature = "dim3")]
pub use ncollide3d;
pub use simba;

/// Compilation flags dependent aliases for mathematical types.
#[cfg(feature = "dim3")]
pub mod math {
    use crate::algebra::{Force3, Inertia3, Velocity3};
    use na::{
        Dynamic, Isometry3, Matrix3, Matrix6, MatrixMN, MatrixSlice6xX, MatrixSliceMut6xX, Point3,
        Rotation3, Translation3, UnitQuaternion, Vector3, Vector6, U3, U6,
    };

    pub use crate::algebra::ForceType;

    /// The maximum number of possible rotations and translations of a rigid body.
    pub const SPATIAL_DIM: usize = 6;
    /// The maximum number of possible rotations of a rigid body.
    pub const ANGULAR_DIM: usize = 3;
    /// The maximum number of possible translations of a rigid body.
    pub const DIM: usize = 3;

    /// The dimension of the ambiant space.
    pub type Dim = U3;

    /// The dimension of a spatial vector.
    pub type SpatialDim = U6;

    /// The dimension of the rotations.
    pub type AngularDim = U3;

    /// The point type.
    pub type Point<N> = Point3<N>;

    /// The angular vector type.
    pub type AngularVector<N> = Vector3<N>;

    /// The vector type.
    pub type Vector<N> = Vector3<N>;

    /// The vector type with dimension `SpatialDim × 1`.
    pub type SpatialVector<N> = Vector6<N>;

    /// The orientation type.
    pub type Orientation<N> = Vector3<N>;

    /// The transformation matrix type.
    pub type Isometry<N> = Isometry3<N>;

    /// The rotation type.
    pub type Rotation<N> = UnitQuaternion<N>;

    /// The rotation matrix type.
    pub type RotationMatrix<N> = Rotation3<N>;

    /// The translation type.
    pub type Translation<N> = Translation3<N>;

    /// The velocity type combining the linear velocity and the angular velocity.
    pub type Velocity<N> = Velocity3<N>;

    /// The force type combining a linear force and a torque.
    pub type Force<N> = Force3<N>;

    /// The inertia tensor type.
    pub type AngularInertia<N> = Matrix3<N>;

    /// The inertia type.
    pub type Inertia<N> = Inertia3<N>;

    /// The inertia matrix type.
    pub type InertiaMatrix<N> = Matrix6<N>;

    /// Square matrix with dimension `Dim × Dim`.
    pub type Matrix<N> = Matrix3<N>;

    /// Square matrix with dimension `SpatialDim × SpatialDim`.
    pub type SpatialMatrix<N> = Matrix6<N>;

    /// The type of a constraint jacobian in twist coordinates.
    pub type Jacobian<N> = MatrixMN<N, U6, Dynamic>;

    /// The type of a slice of the constraint jacobian in twist coordinates.
    pub type JacobianSlice<'a, N> = MatrixSlice6xX<'a, N>;

    /// The type of a mutable slice of the constraint jacobian in twist coordinates.
    pub type JacobianSliceMut<'a, N> = MatrixSliceMut6xX<'a, N>;
}

/// Compilation flags dependent aliases for mathematical types.
#[cfg(feature = "dim2")]
pub mod math {
    use crate::algebra::{Force2, Inertia2, Velocity2};
    use na::{
        Dynamic, Isometry2, Matrix1, Matrix2, Matrix3, MatrixMN, MatrixSlice3xX, MatrixSliceMut3xX,
        Point2, Rotation2, Translation2, UnitComplex, Vector1, Vector2, Vector3, U1, U2, U3,
    };

    pub use crate::algebra::ForceType;

    /// The maximum number of possible rotations and translations of a rigid body.
    pub const SPATIAL_DIM: usize = 3;
    /// The maximum number of possible rotations of a rigid body.
    pub const ANGULAR_DIM: usize = 1;
    /// The maximum number of possible translations of a rigid body.
    pub const DIM: usize = 2;

    /// The dimension of the ambient space.
    pub type Dim = U2;

    /// The dimension of the rotation.
    pub type AngularDim = U1;

    /// The dimension of a spatial vector.
    pub type SpatialDim = U3;

    /// The point type.
    pub type Point<N> = Point2<N>;

    /// The vector type with dimension `SpatialDim × 1`.
    pub type SpatialVector<N> = Vector3<N>;

    /// The angular vector type.
    pub type AngularVector<N> = Vector1<N>;

    /// The vector type.
    pub type Vector<N> = Vector2<N>;

    /// The orientation type.
    pub type Orientation<N> = Vector1<N>;

    /// The transformation matrix type.
    pub type Isometry<N> = Isometry2<N>;

    /// The rotation type.
    pub type Rotation<N> = UnitComplex<N>;

    /// The rotation matrix type.
    pub type RotationMatrix<N> = Rotation2<N>;

    /// The translation type.
    pub type Translation<N> = Translation2<N>;

    /// The velocity type combining the linear velocity and the angular velocity.
    pub type Velocity<N> = Velocity2<N>;

    /// The force type combining a linear force and a torque.
    pub type Force<N> = Force2<N>;

    /// The inertia tensor type.
    pub type AngularInertia<N> = Matrix1<N>;

    /// The inertia type.
    pub type Inertia<N> = Inertia2<N>;

    /// The inertia matrix type.
    pub type InertiaMatrix<N> = Matrix3<N>;

    /// Square matrix with dimension `Dim × Dim`.
    pub type Matrix<N> = Matrix2<N>;

    /// Square matrix with dimension `SpatialDim × SpatialDim`.
    pub type SpatialMatrix<N> = Matrix3<N>;

    /// The type of a constraint jacobian in twist coordinates.
    pub type Jacobian<N> = MatrixMN<N, U3, Dynamic>;

    /// The type of a slice of the constraint jacobian in twist coordinates.
    pub type JacobianSlice<'a, N> = MatrixSlice3xX<'a, N>;

    /// The type of a mutable slice of the constraint jacobian in twist coordinates.
    pub type JacobianSliceMut<'a, N> = MatrixSliceMut3xX<'a, N>;
}


text:
package org.apache.activemq.artemis.utils;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.ByteBuffer;
import java.nio.ReadOnlyBufferException;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.netty.buffer.ByteBuf;
import io.netty.util.internal.PlatformDependent;
import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.logs.ActiveMQUtilBundle;
import org.jboss.logging.Logger;

public class ByteUtil {

   public static final String NON_ASCII_STRING = "@@@@@";

   private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
   private static final String prefix = "^\\s*(\\d+)\\s*";
   private static final String suffix = "(b)?\\s*$";
   private static final Pattern ONE = Pattern.compile(prefix + suffix, Pattern.CASE_INSENSITIVE);
   private static final Pattern KILO = Pattern.compile(prefix + "k" + suffix, Pattern.CASE_INSENSITIVE);
   private static final Pattern MEGA = Pattern.compile(prefix + "m" + suffix, Pattern.CASE_INSENSITIVE);
   private static final Pattern GIGA = Pattern.compile(prefix + "g" + suffix, Pattern.CASE_INSENSITIVE);
   private static final String[] BYTE_SUFFIXES = new String[] {"E", "P", "T", "G", "M", "K", ""};
   private static final double[] BYTE_MAGNITUDES = new double[7];

   static {
      for (int i = 18, j = 0; i >= 0; i -= 3, j++) {
         BYTE_MAGNITUDES[j] = Math.pow(10, i);
      }
   }

   public static void debugFrame(Logger logger, String message, ByteBuf byteIn) {
      if (logger.isTraceEnabled()) {
         outFrame(logger, message, byteIn, false);
      }
   }

   public static void outFrame(Logger logger, String message, ByteBuf byteIn, boolean info) {
      int location = byteIn.readerIndex();
      // debugging
      byte[] frame = new byte[byteIn.writerIndex()];
      byteIn.readBytes(frame);

      try {
         if (info) {
            logger.info(message + "\n" + ByteUtil.formatGroup(ByteUtil.bytesToHex(frame), 8, 16));
         } else {
            logger.trace(message + "\n" + ByteUtil.formatGroup(ByteUtil.bytesToHex(frame), 8, 16));
         }
      } catch (Exception e) {
         logger.warn(e.getMessage(), e);
      }

      byteIn.readerIndex(location);
   }

   public static String formatGroup(String str, int groupSize, int lineBreak) {
      StringBuffer buffer = new StringBuffer();

      int line = 1;
      buffer.append("/*  0 */ \"");
      for (int i = 0; i < str.length(); i += groupSize) {
         buffer.append(str.substring(i, i + Math.min(str.length() - i, groupSize)));

         if ((i + groupSize) % lineBreak == 0) {
            buffer.append("\" +\n/* ");
            line++;
            if (line < 10) {
               buffer.append(" ");
            }
            buffer.append(Integer.toString(i) + " */ \"");
         } else if ((i + groupSize) % groupSize == 0 && str.length() - i > groupSize) {
            buffer.append("\" + \"");
         }
      }

      buffer.append("\";");

      return buffer.toString();

   }

   public static String maxString(String value, int size) {
      if (value.length() < size) {
         return value;
      } else {
         return value.substring(0, size / 2) + " ... " + value.substring(value.length() - size / 2);
      }
   }

   public static String bytesToHex(byte[] bytes) {
      char[] hexChars = new char[bytes.length * 2];
      for (int j = 0; j < bytes.length; j++) {
         int v = bytes[j] & 0xFF;
         hexChars[j * 2] = hexArray[v >>> 4];
         hexChars[j * 2 + 1] = hexArray[v & 0x0F];
      }
      return new String(hexChars);
   }

   /** Simplify reading of a byte array in a programmers understable way */
   public static String debugByteArray(byte[] byteArray) {
      StringWriter builder = new StringWriter();
      PrintWriter writer = new PrintWriter(builder);
      for (int i = 0; i < byteArray.length; i++) {
         writer.print("\t[" + i + "]=" + ByteUtil.byteToChar(byteArray[i]) + " / " + byteArray[i]);
         if (i > 0 && i % 8 == 0) {
            writer.println();
         } else {
            writer.print(" ");
         }
      }
      return builder.toString();
   }

   public static String byteToChar(byte value) {
      char[] hexChars = new char[2];
      int v = value & 0xFF;
      hexChars[0] = hexArray[v >>> 4];
      hexChars[1] = hexArray[v & 0x0F];
      return new String(hexChars);
   }

   public static String bytesToHex(byte[] bytes, int groupSize) {
      if (bytes == null) {
         return "NULL";
      }

      if (bytes.length == 0) {
         return "[]";
      }

      char[] hexChars = new char[bytes.length * 2 + numberOfGroups(bytes, groupSize)];
      int outPos = 0;
      for (int j = 0; j < bytes.length; j++) {
         if (j > 0 && j % groupSize == 0) {
            hexChars[outPos++] = ' ';
         }
         int v = bytes[j] & 0xFF;
         hexChars[outPos++] = hexArray[v >>> 4];
         hexChars[outPos++] = hexArray[v & 0x0F];
      }
      return new String(hexChars);
   }

   public static String toSimpleString(byte[] bytes) {
      SimpleString simpleString = new SimpleString(bytes);
      String value = simpleString.toString();

      for (char c : value.toCharArray()) {
         if (c < ' ' || c > 127) {
            return NON_ASCII_STRING;
         }
      }

      return value;
   }

   private static int numberOfGroups(byte[] bytes, int groupSize) {
      int groups = bytes.length / groupSize;

      if (bytes.length % groupSize == 0) {
         groups--;
      }

      return groups;
   }

   public static final byte[] intToBytes(int value) {
      return new byte[] {
         (byte)(value >>> 24),
         (byte)(value >>> 16),
         (byte)(value >>> 8),
         (byte)value
      };
   }

   public static int bytesToInt(byte[] b) {
      return ((int) b[3] & 0xff)
            | ((int) b[2] & 0xff) << 8
            | ((int) b[1] & 0xff) << 16
            | ((int) b[0] & 0xff) << 24;
   }

   public static long bytesToLong(byte[] b) {
      return ((long) b[7] & 0xff)
         | ((long) b[6] & 0xff) << 8
         | ((long) b[5] & 0xff) << 16
         | ((long) b[4] & 0xff) << 24
         | ((long) b[3] & 0xff) << 32
         | ((long) b[2] & 0xff) << 40
         | ((long) b[1] & 0xff) << 48
         | ((long) b[0] & 0xff) << 56;
   }

   public static byte[] longToBytes(long value) {
      byte[] output = new byte[8];
      longToBytes(value, output, 0);
      return output;
   }

   public static void longToBytes(long x, byte[] output, int offset) {
      output[offset] = (byte)(x >>> 56);
      output[offset + 1] = (byte)(x >>> 48);
      output[offset + 2] = (byte)(x >>> 40);
      output[offset + 3] = (byte)(x >>> 32);
      output[offset + 4] = (byte)(x >>> 24);
      output[offset + 5] = (byte)(x >>> 16);
      output[offset + 6] = (byte)(x >>>  8);
      output[offset + 7] = (byte)(x);
   }

   public static byte[] doubleLongToBytes(long value1, long value2) {
      byte[] output = new byte[16];
      longToBytes(value1, output, 0);
      longToBytes(value2, output, 8);
      return output;
   }

   public static byte[] hexToBytes(String hexStr) {
      byte[] bytes = new byte[hexStr.length() / 2];
      for (int i = 0; i < bytes.length; i++) {
         bytes[i] = (byte) Integer.parseInt(hexStr.substring(2 * i, 2 * i + 2), 16);
      }
      return bytes;
   }

   public static String readLine(ActiveMQBuffer buffer) {
      StringBuilder sb = new StringBuilder("");
      char c = buffer.readChar();
      while (c != '\n') {
         sb.append(c);
         c = buffer.readChar();
      }
      return sb.toString();
   }

   public static long convertTextBytes(final String text) {
      try {
         Matcher m = ONE.matcher(text);
         if (m.matches()) {
            return Long.valueOf(Long.parseLong(m.group(1)));
         }

         m = KILO.matcher(text);
         if (m.matches()) {
            return Long.valueOf(Long.parseLong(m.group(1)) * 1024);
         }

         m = MEGA.matcher(text);
         if (m.matches()) {
            return Long.valueOf(Long.parseLong(m.group(1)) * 1024 * 1024);
         }

         m = GIGA.matcher(text);
         if (m.matches()) {
            return Long.valueOf(Long.parseLong(m.group(1)) * 1024 * 1024 * 1024);
         }

         return Long.parseLong(text);
      } catch (NumberFormatException e) {
         throw ActiveMQUtilBundle.BUNDLE.failedToParseLong(text);
      }
   }

   public static int hashCode(byte[] bytes) {
      if (PlatformDependent.hasUnsafe() && PlatformDependent.isUnaligned()) {
         return unsafeHashCode(bytes);
      }
      return Arrays.hashCode(bytes);
   }

   /**
    * This hash code computation is borrowed by {@link io.netty.buffer.ByteBufUtil#hashCode(ByteBuf)}.
    */
   private static int unsafeHashCode(byte[] bytes) {
      if (bytes == null) {
         return 0;
      }
      final int len = bytes.length;
      int hashCode = 1;
      final int intCount = len >>> 2;
      int arrayIndex = 0;
      // reading in batch both help hash code computation data dependencies and save memory bandwidth
      for (int i = 0; i < intCount; i++) {
         hashCode = 31 * hashCode + PlatformDependent.getInt(bytes, arrayIndex);
         arrayIndex += Integer.BYTES;
      }
      final byte remaining = (byte) (len & 3);
      if (remaining > 0) {
         hashCode = unsafeUnrolledHashCode(bytes, arrayIndex, remaining, hashCode);
      }
      return hashCode == 0 ? 1 : hashCode;
   }

   private static int unsafeUnrolledHashCode(byte[] bytes, int index, int bytesCount, int h) {
      // there is still the hash data dependency but is more friendly
      // then a plain loop, given that we know no loop is needed here
      assert bytesCount > 0 && bytesCount < 4;
      h = 31 * h + PlatformDependent.getByte(bytes, index);
      if (bytesCount == 1) {
         return h;
      }
      h = 31 * h + PlatformDependent.getByte(bytes, index + 1);
      if (bytesCount == 2) {
         return h;
      }
      h = 31 * h + PlatformDependent.getByte(bytes, index + 2);
      return h;
   }

   public static boolean equals(final byte[] left, final byte[] right) {
      return equals(left, right, 0, right.length);
   }

   public static boolean equals(final byte[] left,
                                final byte[] right,
                                final int rightOffset,
                                final int rightLength) {
      if (left == right)
         return true;
      if (left == null || right == null)
         return false;
      if (left.length != rightLength)
         return false;
      if (PlatformDependent.isUnaligned() && PlatformDependent.hasUnsafe()) {
         return equalsUnsafe(left, right, rightOffset, rightLength);
      } else {
         return equalsSafe(left, right, rightOffset, rightLength);
      }
   }

   private static boolean equalsSafe(byte[] left, byte[] right, int rightOffset, int rightLength) {
      for (int i = 0; i < rightLength; i++)
         if (left[i] != right[rightOffset + i])
            return false;
      return true;
   }

   private static boolean equalsUnsafe(final byte[] left,
                                       final byte[] right,
                                       final int rightOffset,
                                       final int rightLength) {
      final int longCount = rightLength >>> 3;
      final int bytesCount = rightLength & 7;
      int bytesIndex = rightOffset;
      int charsIndex = 0;
      for (int i = 0; i < longCount; i++) {
         final long charsLong = PlatformDependent.getLong(left, charsIndex);
         final long bytesLong = PlatformDependent.getLong(right, bytesIndex);
         if (charsLong != bytesLong) {
            return false;
         }
         bytesIndex += 8;
         charsIndex += 8;
      }
      for (int i = 0; i < bytesCount; i++) {
         final byte charsByte = PlatformDependent.getByte(left, charsIndex);
         final byte bytesByte = PlatformDependent.getByte(right, bytesIndex);
         if (charsByte != bytesByte) {
            return false;
         }
         bytesIndex++;
         charsIndex++;
      }
      return true;
   }

   /**
    * Returns {@code true} if  the {@link SimpleString} encoded content into {@code bytes} is equals to {@code s},
    * {@code false} otherwise.
    * <p>
    * It assumes that the {@code bytes} content is read using {@link SimpleString#readSimpleString(ByteBuf, int)} ie starting right after the
    * length field.
    */
   public static boolean equals(final byte[] bytes, final ByteBuf byteBuf, final int offset, final int length) {
      if (bytes.length != length)
         return false;
      if (PlatformDependent.isUnaligned() && PlatformDependent.hasUnsafe()) {
         if ((offset + length) > byteBuf.writerIndex()) {
            throw new IndexOutOfBoundsException();
         }
         if (byteBuf.hasArray()) {
            return equals(bytes, byteBuf.array(), byteBuf.arrayOffset() + offset, length);
         } else if (byteBuf.hasMemoryAddress()) {
            return equalsOffHeap(bytes, byteBuf.memoryAddress(), offset, length);
         }
      }
      return equalsOnHeap(bytes, byteBuf, offset, length);
   }

   private static boolean equalsOnHeap(final byte[] bytes, final ByteBuf byteBuf, final int offset, final int length) {
      if (bytes.length != length)
         return false;
      for (int i = 0; i < length; i++)
         if (bytes[i] != byteBuf.getByte(offset + i))
            return false;
      return true;
   }

   private static boolean equalsOffHeap(final byte[] bytes,
                                        final long address,
                                        final int offset,
                                        final int length) {
      final int longCount = length >>> 3;
      final int bytesCount = length & 7;
      long bytesAddress = address + offset;
      int charsIndex = 0;
      for (int i = 0; i < longCount; i++) {
         final long charsLong = PlatformDependent.getLong(bytes, charsIndex);
         final long bytesLong = PlatformDependent.getLong(bytesAddress);
         if (charsLong != bytesLong) {
            return false;

         }
         bytesAddress += 8;
         charsIndex += 8;
      }
      for (int i = 0; i < bytesCount; i++) {
         final byte charsByte = PlatformDependent.getByte(bytes, charsIndex);
         final byte bytesByte = PlatformDependent.getByte(bytesAddress);
         if (charsByte != bytesByte) {
            return false;

         }
         bytesAddress++;
         charsIndex++;
      }
      return true;
   }

   public static int intFromBytes(byte b1, byte b2, byte b3, byte b4) {
      return b1 << 24 | (b2 & 0xFF) << 16 | (b3 & 0xFF) << 8 | (b4 & 0xFF);
   }

   /**
    * It zeroes the whole {@link ByteBuffer#capacity()} of the given {@code buffer}.
    *
    * @throws ReadOnlyBufferException if {@code buffer} is read-only
    */
   public static void zeros(final ByteBuffer buffer) {
      uncheckedZeros(buffer, 0, buffer.capacity());
   }

   /**
    * It zeroes {@code bytes} of the given {@code buffer}, starting (inclusive) from {@code offset}.
    *
    * @throws IndexOutOfBoundsException if {@code offset + bytes > }{@link ByteBuffer#capacity()} or {@code offset >= }{@link ByteBuffer#capacity()}
    * @throws IllegalArgumentException  if {@code offset} or {@code capacity} are less then 0
    * @throws ReadOnlyBufferException   if {@code buffer} is read-only
    */
   public static void zeros(final ByteBuffer buffer, int offset, int bytes) {
      if (offset < 0 || bytes < 0) {
         throw new IllegalArgumentException();
      }
      final int capacity = buffer.capacity();
      if (offset >= capacity || (offset + bytes) > capacity) {
         throw new IndexOutOfBoundsException();
      }
      uncheckedZeros(buffer, offset, bytes);
   }

   private static void uncheckedZeros(final ByteBuffer buffer, int offset, int bytes) {
      if (buffer.isReadOnly()) {
         throw new ReadOnlyBufferException();
      }
      final byte zero = (byte) 0;
      if (buffer.isDirect() && PlatformDependent.hasUnsafe()) {
         PlatformDependent.setMemory(PlatformDependent.directBufferAddress(buffer) + offset, bytes, zero);
      } else if (buffer.hasArray()) {
         //SIMD OPTIMIZATION
         final int arrayOffset = buffer.arrayOffset();
         final int start = arrayOffset + offset;
         Arrays.fill(buffer.array(), start, start + bytes, zero);
      } else {
         //slow path
         for (int i = 0; i < bytes; i++) {
            buffer.put(i + offset, zero);
         }
      }
   }

   public static String getHumanReadableByteCount(long bytes) {
      if (bytes == 0) {
         return "0B";
      }

      int i = 0;
      while (i < BYTE_MAGNITUDES.length && BYTE_MAGNITUDES[i] > bytes) {
         i++;
      }

      return String.format("%.1f%sB", bytes / BYTE_MAGNITUDES[i], BYTE_SUFFIXES[i]);
   }
}


text:
<%= _.classify(appname) %>.<%= _.classify(name) %>Controller = Ember.ObjectController.extend({
  // Implement your controller here.
});


text:
scriptMain = {
    campoSelect: ".listUsuario",
    init: function () {
        scriptMain.generateSelect()
        scriptMain.generateDatepicker();
        scriptMain.relatorioFunc();
        scriptMain.pizzaFunc();
        scriptMain.grafoFunc();
    },

    generateSelect: function(){
        $(scriptMain.campoSelect).select2({
            placeholder: 'Seleccionar usuarios',
             width: '82%'
        });
    },

    generateDatepicker: function(){
       $("#endDate").datepicker({
            format:'mm-yyyy',
            viewMode: "months",
            minViewMode: "months",
            startDate: '2007/03/03',
            startDate: new Date(2003, 00, 01),
            endDate: new Date(2007, 11, 31),
            autoclose: true
        })

       $("#iniDate").datepicker({
            format:'mm-yyyy',
            viewMode: "months",
            minViewMode: "months",
            startDate: new Date(2003, 00, 01),
            endDate: new Date(2007, 11, 31),
            autoclose: true
        }).on("changeDate", function(e) {
            value = $("#iniDate").datepicker("getDate");
            $("#endDate").datepicker("setStartDate", value)
            $("#endDate").prop('disabled', false);

        });
        $('#iniDate').datepicker('setDate', new Date(2007, 00, 01));
        $('#endDate').datepicker('setDate', new Date(2007, 11, 31));
        $("#endDate").prop('disabled', true);
    },

    relatorioFunc: function(){
        $("#relatorio").click(function(event) {
            valores = scriptMain.getData()
            if (valores.estatus == 200){
                $.ajax({
                    url: baseUrl + 'index.php/ejercicio/resultRelatorio',
                    type: 'post',
                    async: false,
                    data: {valores: valores},
                    dataType: 'json',
                    success: function (data) {
                        if(data.estatus == 200){
                            $('#resultadoConsulta').html(data.html)
                        }else{
                            scriptMain.sweetalert('No se encontraron coincidencias', 'Intentelo con otra busqueda', 'error')
                            $('#resultadoConsulta').html('')
                        }
                    }
                });
            }
        });
    },

    getData: function(){
        nombres = $(scriptMain.campoSelect).val();
        fechaInicio = $('#iniDate').val()
        fechaFin = $('#endDate').val()
        if (nombres == null || fechaInicio == '' || fechaFin == '') {
            scriptMain.sweetalert('Error!', 'Todos los campos son obligatorios', 'error')
            return {estatus: 500}
        } else if (fechaInicio > fechaFin){
            scriptMain.sweetalert('Error!', 'La fecha de inicio es superior a la fecha final', 'error')
            return {estatus: 500}
        }
        return {nombres: nombres, fechaInicio: fechaInicio, fechaFin: fechaFin, estatus: 200}
    },

    pizzaFunc: function(){
        $("#pizza").click(function(event) {
            valores = scriptMain.getData()
            if (valores.estatus == 200){
                $.ajax({
                    url: baseUrl + 'index.php/ejercicio/resultPizza',
                    type: 'post',
                    async: false,
                    data: {valores: valores},
                    dataType: 'json',
                    success: function (data) {
                        if (data.estatus == 200) {
                            $('#resultadoConsulta').html(data.html)
                            scriptMain.generatePizza(data.data);
                        }else{
                            scriptMain.sweetalert('No se encontraron coincidencias', 'Intentelo con otra busqueda', 'error')
                            $("canvas").hide()
                        }
                    }
                });
            }
        });
    },

    getRandomColor: function() {
        var letters = '0123456789ABCDEF'.split('');
        var color = '#';
        for (var i = 0; i < 6; i++ ) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    },

    generatePizza: function(data){
        label = Array();
        datas = Array();
        color = Array();

        Object.keys(data).forEach(function (key) {
            label.push(key);
            datas.push(data[key].toFixed(2))
            color.push(scriptMain.getRandomColor())
        });
        var ctx = document.getElementById("myChart");
        var myChart = new Chart(ctx, {
            type: 'pie',
            data: {
                labels: label,
                datasets: [{
                    data: datas,
                    backgroundColor: color,
                    borderWidth: 1
                }]
            }

        });
    },

    grafoFunc: function(){
        $("#grafico").click(function(event) {
            valores = scriptMain.getData()
            if (valores.estatus == 200){
                $.ajax({
                    url: baseUrl + 'index.php/ejercicio/resultGrafico',
                    type: 'post',
                    async: false,
                    data: {valores: valores},
                    dataType: 'json',
                    success: function (data) {
                        if (data.estatus == 200) {
                            $('#resultadoConsulta').html(data.html)
                            scriptMain.generateGrafica(data);
                        }else{
                            scriptMain.sweetalert('No se encontraron coincidencias', 'Intentelo con otra busqueda', 'error')
                            $("canvas").hide()
                        }
                    }
                });
            }
        });
    },

    generateGrafica: function(data){
        label = Array();
        datas = Array();
        color = Array();
        promedio = Array();
        Object.keys(data.data).forEach(function (key) {
            label.push(key);
            datas.push(data.data[key].toFixed(2));
            color.push(scriptMain.getRandomColor());
            promedio.push(data.promedio);
        });
        var ctx = document.getElementById("myChart");
        var mixedChart = new Chart(ctx, {
            type: 'bar',
            data: {
            datasets: [{
                  label: 'Custo Fixo Médio',
                  data: promedio,
                  borderColor:  '#00ffff',
                  type: 'line',
                  fill: false
                },{
                  label: 'Consultor',
                  data: datas,
                  backgroundColor: color,
                }],
            labels: label
            },
        });
        $("canvas").show()
    },

    sweetalert: function(title, message, type){
        swal(title, message, type)
    }

}


text:
use std::env;
use std::io::Write;
use std::net;
use std::str;
use std::time::Duration;

use clap::{App, Arg};
use log::{error, info, trace};

use uuid::Uuid;

use tokio::io::AsyncWriteExt;
use tokio::net::TcpStream;

use mqtt::control::variable_header::ConnectReturnCode;
use mqtt::packet::*;
use mqtt::TopicFilter;
use mqtt::{Decodable, Encodable, QualityOfService};

fn generate_client_id() -> String {
    format!("/MQTT/rust/{}", Uuid::new_v4())
}

#[tokio::main]
async fn main() {
    // configure logging
    env::set_var("RUST_LOG", env::var_os("RUST_LOG").unwrap_or_else(|| "info".into()));
    env_logger::init();

    let matches = App::new("sub-client")
        .author("Y. T. Chung <zonyitoo@gmail.com>")
        .arg(
            Arg::with_name("SERVER")
                .short("S")
                .long("server")
                .takes_value(true)
                .required(true)
                .help("MQTT server address (host:port)"),
        )
        .arg(
            Arg::with_name("SUBSCRIBE")
                .short("s")
                .long("subscribe")
                .takes_value(true)
                .multiple(true)
                .required(true)
                .help("Channel filter to subscribe"),
        )
        .arg(
            Arg::with_name("USER_NAME")
                .short("u")
                .long("username")
                .takes_value(true)
                .help("Login user name"),
        )
        .arg(
            Arg::with_name("PASSWORD")
                .short("p")
                .long("password")
                .takes_value(true)
                .help("Password"),
        )
        .arg(
            Arg::with_name("CLIENT_ID")
                .short("i")
                .long("client-identifier")
                .takes_value(true)
                .help("Client identifier"),
        )
        .get_matches();

    let server_addr = matches.value_of("SERVER").unwrap();
    let client_id = matches
        .value_of("CLIENT_ID")
        .map(|x| x.to_owned())
        .unwrap_or_else(generate_client_id);
    let channel_filters: Vec<(TopicFilter, QualityOfService)> = matches
        .values_of("SUBSCRIBE")
        .unwrap()
        .map(|c| (TopicFilter::new(c.to_string()).unwrap(), QualityOfService::Level0))
        .collect();

    let keep_alive = 10;

    info!("Connecting to {:?} ... ", server_addr);
    let mut stream = net::TcpStream::connect(server_addr).unwrap();
    info!("Connected!");

    info!("Client identifier {:?}", client_id);
    let mut conn = ConnectPacket::new(client_id);
    conn.set_clean_session(true);
    conn.set_keep_alive(keep_alive);
    let mut buf = Vec::new();
    conn.encode(&mut buf).unwrap();
    stream.write_all(&buf[..]).unwrap();

    let connack = ConnackPacket::decode(&mut stream).unwrap();
    trace!("CONNACK {:?}", connack);

    if connack.connect_return_code() != ConnectReturnCode::ConnectionAccepted {
        panic!(
            "Failed to connect to server, return code {:?}",
            connack.connect_return_code()
        );
    }

    // const CHANNEL_FILTER: &'static str = "typing-speed-test.aoeu.eu";
    info!("Applying channel filters {:?} ...", channel_filters);
    let sub = SubscribePacket::new(10, channel_filters);
    let mut buf = Vec::new();
    sub.encode(&mut buf).unwrap();
    stream.write_all(&buf[..]).unwrap();

    loop {
        let packet = match VariablePacket::decode(&mut stream) {
            Ok(pk) => pk,
            Err(err) => {
                error!("Error in receiving packet {:?}", err);
                continue;
            }
        };
        trace!("PACKET {:?}", packet);

        if let VariablePacket::SubackPacket(ref ack) = packet {
            if ack.packet_identifier() != 10 {
                panic!("SUBACK packet identifier not match");
            }

            info!("Subscribed!");
            break;
        }
    }

    // connection made, start the async work
    stream.set_nonblocking(true).unwrap();
    let mut stream = TcpStream::from_std(stream).unwrap();
    let (mut mqtt_read, mut mqtt_write) = stream.split();

    let ping_sender = async move {
        loop {
            info!("Sending PINGREQ to broker");

            let pingreq_packet = PingreqPacket::new();

            let mut buf = Vec::new();
            pingreq_packet.encode(&mut buf).unwrap();
            mqtt_write.write_all(&buf).await.unwrap();

            tokio::time::sleep(Duration::from_secs(keep_alive as u64 / 2)).await;
        }
    };

    let receiver = async move {
        while let Ok(packet) = VariablePacket::parse(&mut mqtt_read).await {
            trace!("PACKET {:?}", packet);

            match packet {
                VariablePacket::PingrespPacket(..) => {
                    info!("Received PINGRESP from broker ..");
                }
                VariablePacket::PublishPacket(ref publ) => {
                    let msg = match str::from_utf8(publ.payload()) {
                        Ok(msg) => msg,
                        Err(err) => {
                            error!("Failed to decode publish message {:?}", err);
                            continue;
                        }
                    };
                    info!("PUBLISH ({}): {}", publ.topic_name(), msg);
                }
                _ => {}
            }
        }
    };

    tokio::pin!(ping_sender);
    tokio::pin!(receiver);

    tokio::join!(ping_sender, receiver);
}


text:
<?php

/*
|--------------------------------------------------------------------------
| Broadcast Channels
|--------------------------------------------------------------------------
|
| Here you may register all of the event broadcasting channels that your
| application supports. The given channel authorization callbacks are
| used to check if an authenticated user can listen to the channel.
|
*/

use App\Models\Student;
use App\Models\User;

Broadcast::channel('student.{student}', function (User $user, Student $student) {
    return $user->nid == $student->nid;
});

Broadcast::channel('admin.test', function (User $user) {
    return $user->isAbleTo('broadcast.manage');
});


text:
package se.toxbee.sleepfighter.challenge.factory;

import com.google.common.collect.Maps;

import java.util.Map;

import se.toxbee.sleepfighter.challenge.Challenge;
import se.toxbee.sleepfighter.challenge.ChallengePrototypeDefinition;
import se.toxbee.sleepfighter.challenge.fluidsnake.FluidSnakeChallenge;
import se.toxbee.sleepfighter.challenge.math.MathChallenge;
import se.toxbee.sleepfighter.challenge.memory.MemoryChallenge;
import se.toxbee.sleepfighter.challenge.rotosnake.RotoSnakeChallenge;
import se.toxbee.sleepfighter.challenge.shake.ShakeChallenge;
import se.toxbee.sleepfighter.challenge.sort.SortChallenge;
import se.toxbee.sleepfighter.model.challenge.ChallengeType;

/**
 * A simple factory class for construction of challenges.
 */
public class ChallengeFactory {
	private static Map<ChallengeType, ChallengePrototypeDefinition> prototypeDefinitions;

	/**
	 * Construct a new instance of {@link Challenge} from a given
	 * {@link ChallengeType}.
	 *
	 * @param type
	 *            the type of the challenge
	 * @return a new instance of the challenge
	 */
	public static Challenge getChallenge(ChallengeType type) {
		switch (type) {
		case MATH:
			return new MathChallenge();
		case MEMORY:
			return new MemoryChallenge();
		case SORT:
			return new SortChallenge();
		case FLUID_SNAKE:
			return new FluidSnakeChallenge();
		case ROTO_SNAKE:
			return new RotoSnakeChallenge();
		case SHAKE:
			return new ShakeChallenge();
		default:
			throw new IllegalArgumentException("Undefined challenge");
		}
	}

	public static ChallengePrototypeDefinition getPrototypeDefinition( ChallengeType type ) {
		if ( prototypeDefinitions == null ) {
			prototypeDefinitions = Maps.newEnumMap( ChallengeType.class );
		}

		ChallengePrototypeDefinition def = prototypeDefinitions.get( type );

		if ( def == null ) {
			switch ( type ) {

			case MATH:
				def = new MathChallenge.PrototypeDefinition();
				break;

			case MEMORY:
				def = new MemoryChallenge.PrototypeDefinition();
				break;

			case SORT:
				def = new SortChallenge.PrototypeDefinition();
				break;

			case FLUID_SNAKE:
				def = new FluidSnakeChallenge.PrototypeDefinition();
				break;
			case ROTO_SNAKE:
				def = new RotoSnakeChallenge.PrototypeDefinition();
				break;
			case SHAKE:
				def = new ShakeChallenge.PrototypeDefinition();
				break;
			default:
				throw new IllegalArgumentException( "Undefined challenge" );
			}

			prototypeDefinitions.put( type, def );
		}

		return def;
	}
}


text:
package me.ederign.resources;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import me.ederign.domain.Ship;

@Path("ship")
public class ShipResource {

    @GET
    @Path("{id}")
    @Produces({ MediaType.APPLICATION_JSON})
    public Response getTitular( @PathParam("id") String id ) {
        Ship ship = new Ship("1", "Campinas" );
        return Response.ok(ship).build();
    }
}


text:
<?php
declare(strict_types = 1);

namespace Fixtures\Innmind\Url\Authority;

use Innmind\Url\Authority\UserInformation as Model;
use Innmind\BlackBox\Set;

final class UserInformation
{
    /**
     * @return Set<Model>
     */
    public static function any(): Set
    {
        return new Set\Either(
            Set\Composite::immutable(
                static function($user, $password): Model {
                    return Model::of($user, $password);
                },
                UserInformation\User::any(),
                new Set\Either(
                    UserInformation\Password::any(),
                    Set\Elements::of(Model\Password::none()),
                ),
            ),
            Set\Elements::of(Model::none()),
        );
    }
}


text:
//%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements.  Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////

//
// Author:      Adrian Schuur, schuur@de.ibm.com
//
// Modified By:
//
//%/////////////////////////////////////////////////////////////////////////////

package org.pegasus.jmpi;

/**
    Creates and instantiates a CIM scope, a qualifier attribute that
    indicates the CIM objects with which the qualifier can be used.
    For example, the qualifier 'ABSTRACT' has the following scope
    definition: Scope (Class Association Indication), meaning that
    it can only be used with classes, associations, and indications.
 */

public class CIMScope {

    private static final int BAD=0;
    public static final int SCHEMA=1;
    public static final int CLASS=2;
    public static final int ASSOCIATION=3;
    public static final int INDICATION=4;
    public static final int PROPERTY=5;
    public static final int REFERENCE=6;
    public static final int METHOD=7;
    public static final int PARAMETER=8;
    public static final int INSTANCE=9;
    public static final int ANY=10;

    private int scope=0;

    public CIMScope(int sc) {
	    scope=sc;
    }

    public static CIMScope getScope(int sc) {
        if (sc>BAD && sc<=ANY) return new CIMScope(sc);
	return(null);
    }

    public int getScope() {
	return(scope);
    }

}


text:
export class Message {
    public address:string;
    public content:string;
    public timestamp:any;
    public owner:boolean;

    constructor(address:string, content:string, owner:boolean){
        this.address = address;
        this.content = content;
        this.owner = owner;
        this.timestamp = new Date();
    }
}


text: <input id="usage-stats" type="checkbox">


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/diag/mdia/mdiafwd.H $                                 */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2012,2020                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#ifndef __MDIA_MDIAFWD_H
#define __MDIA_MDIAFWD_H

/**
 * @file mdiafwd.H
 * @brief internal mdia declarations
 */

#include <mdia/mdia.H>
#include <mdia/mdiareasoncodes.H>
#include <targeting/common/attributes.H>
#include <targeting/common/targetservice.H>
#include <vector>
#include <map>

/**
 * @brief forwards
 */
class MdiaSmTest;
class MdiaTest;
class MdiaMbaTest;
class MdiaCommandMonitorTest;
class MdiaTraceTest;
class MdiaWorkItemTest;

namespace MDIA
{

/**
 * forwards
 */
class StateMachine;
class WorkItem;
class CommandMonitor;
struct Globals;
struct WorkFlowProperties;

/**
 * @brief per mba diagnostic mode
 */
enum DiagMode
{
    ONE_PATTERN,
    FOUR_PATTERNS,
    NINE_PATTERNS,
};

/**
 * @brief misc constants
 */
enum
{

    // mcc dstlfir unit regs
    DSTLFIR                 = 0x0C010D00,
    DSTLFIR_MASK            = 0x0C010D03,
    DSTLFIR_ACT0            = 0x0C010D06,
    DSTLFIR_ACT1            = 0x0C010D07,
    DSTLCFG2                = 0x0C010D0E,

    // ocmb mcbist unit regs
    OCMB_MCBIST_FIR         = 0x08011800,
    OCMB_MCBIST_FIR_AND     = 0x08011801,
    OCMB_MCBIST_FIR_MASK    = 0x08011803,
    OCMB_MCBIST_FIR_ACT0    = 0x08011806,
    OCMB_MCBIST_FIR_ACT1    = 0x08011807,

    // ocmb omidlfir unit regs
    OMIDLFIR                = 0x08012800,
    OMIDLFIR_MASK           = 0x08012803,
    OMIDLFIR_ACT0           = 0x08012806,
    OMIDLFIR_ACT1           = 0x08012807,

    // proc regs
    IPOLL_MASK              = 0x000F0033,
    IPOLL_STATUS            = 0x000F0034,
    GLOBAL_CS_FIR           = 0x570F001C,
    GLOBAL_RE_FIR           = 0x570F001B,
    GLOBAL_UCS_FIR          = 0x570F002A,
    GLOBAL_HA_FIR           = 0x570F002B,

    // mc chiplet registers
    MC0_CHIPLET_HA_FIR      = 0x0C040004,
    MC0_CHIPLET_HA_FIR_MASK = 0x0C040044,
    MC1_CHIPLET_HA_FIR      = 0x0D040004,
    MC1_CHIPLET_HA_FIR_MASK = 0x0D040044,
    MC2_CHIPLET_HA_FIR      = 0x0E040004,
    MC2_CHIPLET_HA_FIR_MASK = 0x0E040044,
    MC3_CHIPLET_HA_FIR      = 0x0F040004,
    MC3_CHIPLET_HA_FIR_MASK = 0x0F040044,
};

/**
 * @brief workflow status
 */
enum WorkFlowStatus
{
    /**
     * @brief workflow in progress or hasn't started yet
     */
    IN_PROGRESS,

    /**
     * @brief indicates workflow stopped because a maint command timed out
     */
    COMMAND_TIMED_OUT,

    /**
     * @brief indicates workflow stopped because of a failure
     */
    FAILED,

    /**
     * @brief workflow finished
     */
    COMPLETE,
};

/**
* @brief Workflow container of workflow phases
*/
typedef std::vector<uint64_t> WorkFlow;

/**
* @brief WorkflowAssocMap target / workflow association map
*/
typedef std::map<TARGETING::TargetHandle_t, WorkFlow> WorkFlowAssocMap;

/**
* @brief WorkflowAssoc target / workflow association list element
*/
typedef WorkFlowAssocMap::const_iterator WorkFlowAssoc;

/**
* @brief MonitorIDs container of monitorIDs unique to a target
*/
typedef std::vector<uint64_t> MonitorIDs;

/**
 * @brief getDiagnosticMode get the mode (scrub, init, one, four, nine)
 *
 * @param[in] i_globals policy flags needed to determine the mode
 * @param[in] i_target the mba/mcbist target for which the mode is determined
 * @param[out] o_mode the mode for the target mba/mcbist
 *
 * @retval 0 no error
 * @retval !0 unexpected error occurred
 */
errlHndl_t getDiagnosticMode(
        const Globals & i_globals,
        TARGETING::TargetHandle_t i_trgt,
        DiagMode & o_mode);

/**
 * @brief getWorkFlow get the workflow for an mba/mcbist target
 *
 * @param[in] i_mode the diagnostic mode for the target
 * @param[out] o_wf the workflow for the mba/mcbist target
 * @param[in] i_globals policy flags needed to determine MNFG status
 *
 * @retval 0 no error
 * @retval !0 unexpected error occurred
 */
errlHndl_t getWorkFlow(
        DiagMode i_mode,
        WorkFlow & o_wf,
        const Globals & i_globals);

/**
 * @brief doStepCleanup shut down threads and pools on step exit
 *
 * @param[in] i_globals contains objects to be cleaned up
 *
 * @return nullptr on success; non-nullptr on error
 */
errlHndl_t doStepCleanup(const Globals & i_globals);

/**
 * @brief check if hw state has been changed for an mba
 *        or mcbist's associated targets
 *
 * @param[in] i_trgt input mba/mcbist target
 *
 * @retval true if hw state has been changed or else
 */
bool isHWStateChanged(TARGETING::TargetHandle_t i_trgt);

/**
 * @brief clear hw changed state for an mba
 *        or mcbist's associated targets
 *
 * @param[in] i_trgt input mba/mcbist target
 *
 */
void clearHWStateChanged(TARGETING::TargetHandle_t i_trgt);

}
#endif


text:
//
//  GNetworkingManager.h
//  GNetworking
//
//  Created by ge wei on 2017/3/30.
//  Copyright © 2017年 gxw. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface GNetworkingManager : NSObject

/**
 POST请求

 @param url 请求链接
 @param param 参数
 @param success 成功回调
 @param failure 失败回调
 */
+ (void)POST:(NSString *)url
       param:(NSDictionary *)param
     success:(void (^)(NSDictionary *responseObject))success
     failure:(void (^)(NSError *error))failure;

/**
 GET请求

 @param url 请求链接
 @param param 参数
 @param success 成功回调
 @param failure 失败回调
 */
+ (void)GET:(NSString *)url
      param:(NSDictionary *)param
    success:(void (^)(NSDictionary *responseObject))success
    failure:(void (^)(NSError *error))failure;

/**
 上传

 @param url 请求链接
 @param param 参数
 @param items 需要上传的数据
 @param uploadProgressBlock 进度
 @param success 成功回调
 @param failure 失败回调
 */
+ (void)UPLOAD:(NSString *)url
         param:(NSDictionary *)param
         items:(NSArray *)items
      progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
       success:(void (^) (NSDictionary * responseObject))success
       failure:(void (^) (NSError *error))failure;

/**
 同步POST请求

 @param url 请求url
 @param param 请求参数
 @return 返回结果
 */
+ (id)sync_POST:(NSString *)url
                param:(NSDictionary *)param;

/**
 同步GET请求

 @param url 请求url
 @param param 请求参数
 @return 返回结果
 */
+ (id)sync_GET:(NSString *)url
               param:(NSDictionary *)param;

@end


text:
    <md-list>

Lista de Cuidadores

        <md-button class="md-raised md-primary" ng-click="cuidCtrl.cadastrar()">Cadastrar Novo</md-button>
        <md-list-item ng-repeat="cuid in cuidCtrl.cuidadores" ng-click="cuidCtrl.showItem($event, cuid)">
            <md-icon md-svg-icon="assets/svg/avatar-1.svg" class="imagem-contato"></md-icon>

{{ cuid.c_nome }}

        </md-list-item>

    </md-list>


text:
import {PlatformModule} from '@angular/cdk/platform';
import {NgModule} from '@angular/core';
import {CdkPlatformOverviewExample} from './cdk-platform-overview/cdk-platform-overview-example';

const EXAMPLES = [CdkPlatformOverviewExample];

@NgModule({
  imports: [
    PlatformModule,
  ],
  declarations: EXAMPLES,
  exports: EXAMPLES,
})
export class CdkPlatformExamplesModule {
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<servico xsi:schemaLocation="http://servicos.gov.br/v3/schema.../servico.xsd" xmlns="http://servicos.gov.br/v3/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <id>criar-leitos-clinicos-de-retaguarda</id>
    <dbId>1536</dbId>
    <nome>Criar leitos clínicos de retaguarda</nome>
    <sigla></sigla>
    <descricao>São  leitos para a retaguarda às urgências e emergências que deverão ser criados, como novos, ou qualificados em hospitais acima de 50 leitos localizados na região de saúde em que os hospitais estão inseridos, podendo ser implantados em hospitais estratégicos de alta complexidade ou em hospitais de menor adensamento tecnológico que deem suporte às portas de entrada hospitalares, prontos-socorros, unidades de pronto  atendimento e UPA 24h, devendo, como pressuposto, ser exclusivos para a retaguarda às urgências e estar disponíveis nas centrais de regulação hospitalar.</descricao>
    <contato></contato>
    <gratuito>true</gratuito>
    <porcentagem-manual>false</porcentagem-manual>
    <servico-digital>false</servico-digital>
    <link-servico-digital></link-servico-digital>
    <solicitantes>
        <solicitante id="2438">
            <tipo>Estados e municípios</tipo>
            <requisitos></requisitos>
        </solicitante>
    </solicitantes>
    <tempo-total-estimado>
        <nao-estimado-ainda/>
        <descricao></descricao>
    </tempo-total-estimado>
    <validade-documento>
        <descricao></descricao>
    </validade-documento>
    <etapas>
        <etapa id="4881">
            <titulo>Cadastrar leitos</titulo>
            <descricao></descricao>
            <documentos>
                <default/>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="4940" tipo="presencial">
                        <descricao>Ministério da Saúde</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
    </etapas>
    <orgao id="http://estruturaorganizacional.dados.gov.br/id/unidade-organizacional/304" dbId="37534">
        <nomeOrgao>Ministério da Saúde (MS)</nomeOrgao>
    </orgao>
    <segmentos-da-sociedade>
        <item idSegmento="2" idServicoSegmento="4899">Órgãos e entidades públicas</item>
    </segmentos-da-sociedade>
    <areas-de-interesse>
        <item>Saúde</item>
    </areas-de-interesse>
    <palavras-chave>
        <item id="9093">leitos clínicos</item>
        <item id="9094">financiamento</item>
        <item id="9095">sus</item>
    </palavras-chave>
    <servicos-relacionados>
        <item>1530</item>
    </servicos-relacionados>
</servico>


text:
package sbt.mavenint

/** An exception we can throw if we encounter issues. */
class MavenResolutionException(msg: String) extends RuntimeException(msg) {}


text:
package com.danikula.aibolit;

import android.content.Context;
import android.view.View;

public class InvisibleInjectionContext implements InjectionContext {

    private Context context;

    public InvisibleInjectionContext(Context context) {
        this.context = context;
    }

    @Override
    public View getRootView() {
        throw new UnsupportedOperationException(InvisibleInjectionContext.class.getSimpleName() + " do not have visible presentation!");
    }

    @Override
    public Context getAndroidContext() {
        return context;
    }

}


text:
namespace Avalonia.Input
{
    public static class DataFormats
    {
        /// <summary>
        /// Dataformat for plaintext
        /// </summary>
        public static readonly string Text = nameof(Text);

        /// <summary>
        /// Dataformat for one or more filenames
        /// </summary>
        public static readonly string FileNames = nameof(FileNames);
    }
}


text:
<title>Name lookup - Using the GNU Compiler Collection (GCC)</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using the GNU Compiler Collection (GCC)">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="C_002b_002b-Misunderstandings.html#C_002b_002b-Misunderstandings" title="C++ Misunderstandings">
<link rel="prev" href="Static-Definitions.html#Static-Definitions" title="Static Definitions">
<link rel="next" href="Temporaries.html#Temporaries" title="Temporaries">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: Temporaries,
Previous: Static Definitions,
Up: C++ Misunderstandings

11.8.2 Name lookup, templates, and accessing members of base classes

The C++ standard prescribes that all names that are not dependent on
template parameters are bound to their present definitions when parsing
a template function or class.1  Only names that are dependent are looked up at the point
of instantiation.  For example, consider

       void foo(double);

       struct A {
         template <typename T>
         void f () {
           foo (1);        // 1
           int i = N;      // 2
           T t;
           t.bar();        // 3
           foo (t);        // 4
         }

         static const int N;
       };

Here, the names foo and N appear in a context that does
not depend on the type of T.  The compiler will thus require that
they are defined in the context of use in the template, not only before
the point of instantiation, and will here use ::foo(double) and
A::N, respectively.  In particular, it will convert the integer
value to a double when passing it to ::foo(double).

Conversely, bar and the call to foo in the fourth marked
line are used in contexts that do depend on the type of T, so
they are only looked up at the point of instantiation, and you can
provide declarations for them after declaring the template, but before
instantiating it.  In particular, if you instantiate A::f<int>,
the last line will call an overloaded ::foo(int) if one was
provided, even if after the declaration of struct A.

This distinction between lookup of dependent and non-dependent names is
called two-stage (or dependent) name lookup.  G++ implements it
since version 3.4.

Two-stage name lookup sometimes leads to situations with behavior
different from non-template codes.  The most common is probably this:

       template <typename T> struct Base {
         int i;
       };

       template <typename T> struct Derived : public Base<T> {
         int get_i() { return i; }
       };

In get_i(), i is not used in a dependent context, so the
compiler will look for a name declared at the enclosing namespace scope
(which is the global scope here).  It will not look into the base class,
since that is dependent and you may declare specializations of
Base even after declaring Derived, so the compiler can't
really know what i would refer to.  If there is no global
variable i, then you will get an error message.

In order to make it clear that you want the member of the base class,
you need to defer lookup until instantiation time, at which the base
class is known.  For this, you need to access i in a dependent
context, by either using this->i (remember that this is of
type Derived<T>*, so is obviously dependent), or using
Base<T>::i.  Alternatively, Base<T>::i might be brought
into scope by a using-declaration.

Another, similar example involves calling member functions of a base
class:

       template <typename T> struct Base {
           int f();
       };

       template <typename T> struct Derived : Base<T> {
           int g() { return f(); };
       };

Again, the call to f() is not dependent on template arguments
(there are no arguments that depend on the type T, and it is also
not otherwise specified that the call should be in a dependent context).
Thus a global declaration of such a function must be available, since
the one in the base class is not visible until instantiation time.  The
compiler will consequently produce the following error message:

       x.cc: In member function `int Derived<T>::g()':
       x.cc:6: error: there are no arguments to `f' that depend on a template
          parameter, so a declaration of `f' must be available
       x.cc:6: error: (if you use `-fpermissive', G++ will accept your code, but
          allowing the use of an undeclared name is deprecated)

To make the code valid either use this->f(), or
Base<T>::f().  Using the <samp>-fpermissive</samp> flag will also let
the compiler accept the code, by marking all function calls for which no
declaration is visible at the time of definition of the template for
later lookup at instantiation time, as if it were a dependent call.
We do not recommend using <samp>-fpermissive</samp> to work around invalid
code, and it will also only catch cases where functions in base classes
are called, not where variables in base classes are used (as in the
example above).

Note that some compilers (including G++ versions prior to 3.4) get these
examples wrong and accept above code without an error.  Those compilers
do not implement two-stage name lookup correctly.

Footnotes

[1] The C++ standard just uses the
term “dependent” for names that depend on the type or value of
template parameters.  This shorter term will also be used in the rest of
this section.


text:
"""Serializer classes module.

Each of the classes works with a graph object to serialize it to a specific
format.
"""
from sql_graph.serializing.bq_serializer import BQSerializer
from sql_graph.serializing.reactflow_serializer import ReactFlowSerializer


text:
package com.intellij.codeInsight.daemon;

import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.UserDataHolderEx;
import com.intellij.openapi.util.text.StringHash;
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;

import java.util.concurrent.atomic.AtomicInteger;

public class UsedColors {
  private static final Key<Object/*UsedColor or UsedColor[]*/> USED_COLOR = Key.create("USED_COLOR");

  public static final AtomicInteger counter = new AtomicInteger();
  private static class UsedColor {
    @NotNull final String name;
    final int index;

    UsedColor(@NotNull String name, int index) {
      this.name = name;
      this.index = index;
      counter.incrementAndGet();
    }
  }

  public static int getOrAddColorIndex(@NotNull final UserDataHolderEx context,
                                       @NotNull final String name,
                                       int colorsCount) {
    int colorIndex;
    while (true) {
      Object data = context.getUserData(USED_COLOR);
      Object newColors;
      if (data == null) {
        colorIndex = hashColor(name, colorsCount);
        newColors = new UsedColor(name, colorIndex); // put an object instead of array to save space
      }
      else if (data instanceof UsedColor) {
        UsedColor usedColor = (UsedColor)data;
        if (usedColor.name.equals(name)) {
          colorIndex = usedColor.index;
          newColors = null; // found, no need to create new
        }
        else {
          int hashedIndex = hashColor(name, colorsCount);
          if (hashedIndex == usedColor.index) hashedIndex = (hashedIndex + 1) % colorsCount;
          colorIndex = hashedIndex;
          UsedColor newColor = new UsedColor(name, colorIndex);
          newColors = new UsedColor[]{usedColor, newColor};
        }
      }
      else {
        colorIndex = -1;
        int hashedIndex = hashColor(name, colorsCount);
        int[] index2usage = new int[colorsCount];
        UsedColor[] usedColors = (UsedColor[])data;
        for (UsedColor usedColor : usedColors) {
          int index = usedColor.index;
          index2usage[index]++;
          if (usedColor.name.equals(name)) {
            colorIndex = index;
            break;
          }
        }
        if (colorIndex == -1) {
          int minIndex1 = indexOfMin(index2usage, hashedIndex, colorsCount);
          int minIndex2 = indexOfMin(index2usage, 0, hashedIndex);
          colorIndex = index2usage[minIndex1] <= index2usage[minIndex2] ? minIndex1 : minIndex2;
          UsedColor newColor = new UsedColor(name, colorIndex);
          newColors = ArrayUtil.append(usedColors, newColor);
        }
        else {
          newColors = null;
        }
      }
      if (newColors == null || context.replace(USED_COLOR, data, newColors)) {
        break;
      }
    }

    return colorIndex;
  }

  private static int hashColor(@NotNull String name, int colorsCount) {
    return Math.abs(StringHash.murmur(name, 0x55AA) % colorsCount);
  }

  @Contract(pure = true)
  private static int indexOfMin(@NotNull int[] values, int start, int end) {
    int min = Integer.MAX_VALUE;
    int minIndex = start;
    for (int i = start; i < end; i++) {
      int value = values[i];
      if (value < min) {
        min = value;
        minIndex = i;
      }
    }
    return minIndex;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NMEA_Tools.Decoder.Exceptions
{
    public class WordFormatException : Exception
    {
        public WordFormatException(string message, Exception innerException) : base(message, innerException)
        {

        }
    }
}


text:
package com.moumou.locate;

import android.content.Context;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.moumou.locate.reminder.Reminder;

import java.util.List;

/**
 * Created by MouMou on 29-12-16.
 */

public class ReminderListAdapter extends ArrayAdapter<Reminder> {

    //todo make this
    public ReminderListAdapter(Context context, int resource, List<Reminder> objects) {
        super(context, resource, objects);
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, @NonNull ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext())
                    .inflate(R.layout.reminder_list_item, parent, false);
        }
        Reminder r = getItem(position);

        TextView title = (TextView) convertView.findViewById(R.id.reminder_title);
        TextView description = (TextView) convertView.findViewById(R.id.reminder_desc);

        Typeface roboto = Typeface.createFromAsset(getContext().getAssets(),
                                                   "font/Roboto-Regular.ttf");
        title.setTypeface(roboto);
        description.setTypeface(roboto);

        title.setText(r != null ? r.getLabel().replace('_', ' ') : "Null Reminder");

        description.setText(r != null ? r.toDescriptionString() : "Null Reminder");
        return convertView;
    }

    @Override
    public boolean isEmpty() {
        return super.isEmpty();
    }
}