text:
@implementation GradientScatterPlot

+ (void)load
{
	[super registerPlotItem:self];
}

- (id)init
{
    if (self = [super init]) {
        title = @"Gradient Scatter Plot";
    }

    return self;
}

- (void)killGraph
{
    if ([graphs count]) {
        CPGraph *graph = [graphs objectAtIndex:0];

        if (symbolTextAnnotation) {
            [graph.plotAreaFrame.plotArea removeAnnotation:symbolTextAnnotation];
            [symbolTextAnnotation release];
            symbolTextAnnotation = nil;
        }
    }

    [super killGraph];
}

- (void)generateData
{
    if (plotData == nil) {
        NSMutableArray *contentArray = [NSMutableArray arrayWithCapacity:100];
        for (NSUInteger i = 0; i < 10; i++) {
            id x = [NSDecimalNumber numberWithDouble:1.0 + i * 0.05];
            id y = [NSDecimalNumber numberWithDouble:1.2 * rand()/(double)RAND_MAX + 0.5];
            [contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x, @"x", y, @"y", nil]];
        }
        plotData = [contentArray retain];
    }
}

- (void)renderInLayer:(CPGraphHostingView *)layerHostingView withTheme:(CPTheme *)theme
{
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
    CGRect bounds = layerHostingView.bounds;
#else
    CGRect bounds = NSRectToCGRect(layerHostingView.bounds);
#endif

    CPGraph* graph = [[[CPXYGraph alloc] initWithFrame:[layerHostingView bounds]] autorelease];
    [self addGraph:graph toHostingView:layerHostingView];
    [self applyTheme:theme toGraph:graph withDefault:[CPTheme themeNamed:kCPSlateTheme]];

    [self setTitleDefaultsForGraph:graph withBounds:bounds];
    [self setPaddingDefaultsForGraph:graph withBounds:bounds];

    // Setup scatter plot space
    CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
    plotSpace.allowsUserInteraction = YES;
    plotSpace.delegate = self;

    // Grid line styles
    CPMutableLineStyle *majorGridLineStyle = [CPMutableLineStyle lineStyle];
    majorGridLineStyle.lineWidth = 0.75;
    majorGridLineStyle.lineColor = [[CPColor colorWithGenericGray:0.2] colorWithAlphaComponent:0.75];

    CPMutableLineStyle *minorGridLineStyle = [CPMutableLineStyle lineStyle];
    minorGridLineStyle.lineWidth = 0.25;
    minorGridLineStyle.lineColor = [[CPColor whiteColor] colorWithAlphaComponent:0.1];

    CPMutableLineStyle *redLineStyle = [CPMutableLineStyle lineStyle];
    redLineStyle.lineWidth = 10.0;
    redLineStyle.lineColor = [[CPColor redColor] colorWithAlphaComponent:0.5];

    // Axes
    // Label x axis with a fixed interval policy
    CPXYAxisSet *axisSet = (CPXYAxisSet *)graph.axisSet;
    CPXYAxis *x = axisSet.xAxis;
    x.majorIntervalLength = CPDecimalFromString(@"0.5");
    x.orthogonalCoordinateDecimal = CPDecimalFromString(@"1.0");
    x.minorTicksPerInterval = 2;
    x.majorGridLineStyle = majorGridLineStyle;
    x.minorGridLineStyle = minorGridLineStyle;

    x.title = @"X Axis";
    x.titleOffset = 30.0;
    x.titleLocation = CPDecimalFromString(@"1.25");

	// Label y with an automatic label policy.
    CPXYAxis *y = axisSet.yAxis;
    y.labelingPolicy = CPAxisLabelingPolicyAutomatic;
    y.orthogonalCoordinateDecimal = CPDecimalFromString(@"1.0");
    y.minorTicksPerInterval = 2;
    y.preferredNumberOfMajorTicks = 8;
    y.majorGridLineStyle = majorGridLineStyle;
    y.minorGridLineStyle = minorGridLineStyle;
    y.labelOffset = 10.0;

    y.title = @"Y Axis";
    y.titleOffset = 30.0;
    y.titleLocation = CPDecimalFromString(@"1.0");

    // Rotate the labels by 45 degrees, just to show it can be done.
    labelRotation = M_PI * 0.25;

    // Add an extra y axis (red)
    // We add constraints to this axis below
    CPXYAxis *y2 = [[(CPXYAxis *)[CPXYAxis alloc] initWithFrame:CGRectZero] autorelease];
    y2.labelingPolicy = CPAxisLabelingPolicyAutomatic;
    y2.orthogonalCoordinateDecimal = CPDecimalFromString(@"3");
    y2.minorTicksPerInterval = 0;
    y2.preferredNumberOfMajorTicks = 4;
    y2.majorGridLineStyle = majorGridLineStyle;
    y2.minorGridLineStyle = minorGridLineStyle;
    y2.labelOffset = 10.0;
    y2.coordinate = CPCoordinateY;
    y2.plotSpace = graph.defaultPlotSpace;
    y2.axisLineStyle = redLineStyle;
    y2.majorTickLineStyle = redLineStyle;
    y2.minorTickLineStyle = nil;
    y2.labelTextStyle = nil;
    y2.visibleRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromInteger(2) length:CPDecimalFromInteger(3)];

    // Set axes
    //graph.axisSet.axes = [NSArray arrayWithObjects:x, y, y2, nil];
    graph.axisSet.axes = [NSArray arrayWithObjects:x, y, y2, nil];

    // Put an area gradient under the plot above
    //NSString *pathToFillImage = [[NSBundle mainBundle] pathForResource:@"BlueTexture" ofType:@"png"];
    //CPImage *fillImage = [CPImage imageForPNGFile:pathToFillImage];
    //fillImage.tiled = YES;
    //CPFill *areaGradientFill = [CPFill fillWithImage:fillImage];

    // Create a plot that uses the data source method
    CPScatterPlot *dataSourceLinePlot = [[[CPScatterPlot alloc] init] autorelease];
    dataSourceLinePlot.identifier = @"Data Source Plot";

    CPMutableLineStyle *lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
    lineStyle.lineWidth = 3.0;
    lineStyle.lineColor = [CPColor greenColor];
    dataSourceLinePlot.dataLineStyle = lineStyle;
    dataSourceLinePlot.dataSource = self;
    [graph addPlot:dataSourceLinePlot];

    // Put an area gradient under the plot above
    CPColor *areaColor = [CPColor colorWithComponentRed:0.3 green:1.0 blue:0.3 alpha:0.8];
    CPGradient *areaGradient = [CPGradient gradientWithBeginningColor:areaColor endingColor:[CPColor clearColor]];
    areaGradient.angle = -90.0;
    CPFill* areaGradientFill = [CPFill fillWithGradient:areaGradient];
    dataSourceLinePlot.areaFill = areaGradientFill;
    dataSourceLinePlot.areaBaseValue = CPDecimalFromString(@"0.0");

    [self generateData];

    // Auto scale the plot space to fit the plot data
    // Extend the y range by 10% for neatness
    [plotSpace scaleToFitPlots:[NSArray arrayWithObjects:dataSourceLinePlot, nil]];
    CPPlotRange *xRange = plotSpace.xRange;
    CPPlotRange *yRange = plotSpace.yRange;
    [xRange expandRangeByFactor:CPDecimalFromDouble(1.3)];
    [yRange expandRangeByFactor:CPDecimalFromDouble(1.3)];
    plotSpace.yRange = yRange;

    // Restrict y range to a global range
    CPPlotRange *globalYRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0f)
                                                            length:CPDecimalFromFloat(2.0f)];
    plotSpace.globalYRange = globalYRange;

    // set the x and y shift to match the new ranges
    CGFloat length = xRange.lengthDouble;
    xShift = length - 3.0;
    length = yRange.lengthDouble;
    yShift = length - 2.0;

    // Position y2 axis relative to the plot area, ie, not moving when dragging
    CPConstraints y2Constraints = {CPConstraintNone, CPConstraintFixed};
    y2.isFloatingAxis = YES;
    y2.constraints = y2Constraints;

    // Add plot symbols
    CPMutableLineStyle *symbolLineStyle = [CPMutableLineStyle lineStyle];
    symbolLineStyle.lineColor = [CPColor blackColor];
    CPPlotSymbol *plotSymbol = [CPPlotSymbol ellipsePlotSymbol];
    plotSymbol.fill = [CPFill fillWithColor:[CPColor blueColor]];
    plotSymbol.lineStyle = symbolLineStyle;
    plotSymbol.size = CGSizeMake(10.0, 10.0);
    dataSourceLinePlot.plotSymbol = plotSymbol;

    // Set plot delegate, to know when symbols have been touched
    // We will display an annotation when a symbol is touched
    dataSourceLinePlot.delegate = self;
    dataSourceLinePlot.plotSymbolMarginForHitDetection = 5.0f;
}

- (void)dealloc
{
    [plotData release];
	[super dealloc];
}

#pragma mark -
#pragma mark Plot Data Source Methods

-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
    return [plotData count];
}

-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
    NSNumber* num = [[plotData objectAtIndex:index] valueForKey:(fieldEnum == CPScatterPlotFieldX ? @"x" : @"y")];
    if (fieldEnum == CPScatterPlotFieldY) {
        num = [NSNumber numberWithDouble:[num doubleValue]];
    }

    return num;
}

#pragma mark -
#pragma mark Plot Space Delegate Methods

-(CPPlotRange *)plotSpace:(CPPlotSpace *)space willChangePlotRangeTo:(CPPlotRange *)newRange forCoordinate:(CPCoordinate)coordinate
{
    // Impose a limit on how far user can scroll in x
    if ( coordinate == CPCoordinateX ) {
        CPPlotRange *maxRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(-1.0f) length:CPDecimalFromFloat(6.0f)];
        CPPlotRange *changedRange = [[newRange copy] autorelease];
        [changedRange shiftEndToFitInRange:maxRange];
        [changedRange shiftLocationToFitInRange:maxRange];
        newRange = changedRange;
    }
    return newRange;
}

#pragma mark -
#pragma mark CPScatterPlot delegate method

-(void)scatterPlot:(CPScatterPlot *)plot plotSymbolWasSelectedAtRecordIndex:(NSUInteger)index
{
    CPGraph* graph = [graphs objectAtIndex:0];

    if ( symbolTextAnnotation ) {
        [graph.plotAreaFrame.plotArea removeAnnotation:symbolTextAnnotation];
        symbolTextAnnotation = nil;
    }

    // Setup a style for the annotation
    CPMutableTextStyle *hitAnnotationTextStyle = [CPMutableTextStyle textStyle];
    hitAnnotationTextStyle.color = [CPColor whiteColor];
    hitAnnotationTextStyle.fontSize = 16.0f;
    hitAnnotationTextStyle.fontName = @"Helvetica-Bold";

    // Determine point of symbol in plot coordinates
    NSNumber *x = [[plotData objectAtIndex:index] valueForKey:@"x"];
    NSNumber *y = [[plotData objectAtIndex:index] valueForKey:@"y"];
    NSArray *anchorPoint = [NSArray arrayWithObjects:x, y, nil];

    // Add annotation
    // First make a string for the y value
    NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
    [formatter setMaximumFractionDigits:2];
    NSString *yString = [formatter stringFromNumber:y];

    // Now add the annotation to the plot area
    CPTextLayer *textLayer = [[[CPTextLayer alloc] initWithText:yString style:hitAnnotationTextStyle] autorelease];
    symbolTextAnnotation = [[CPPlotSpaceAnnotation alloc] initWithPlotSpace:graph.defaultPlotSpace anchorPlotPoint:anchorPoint];
    symbolTextAnnotation.contentLayer = textLayer;
    symbolTextAnnotation.displacement = CGPointMake(0.0f, 20.0f);
    [graph.plotAreaFrame.plotArea addAnnotation:symbolTextAnnotation];
}

@end


text:
![image_squidhome@2x.png](http://i.imgur.com/RIvu9.png)

Generate a unit test for your Sails app.

this a fork by [sails-generate-test](https://github.com/sailsjs/sails-generate-test)

## Install
```
npm install --save sails-generate-unittest
```

#### Modules to using for test: Mocha + Chai + Sinon + Supertest

* [chai](https://github.com/chaijs/chai)
* [mocha](https://github.com/mochajs/mocha)
* [sinon](https://github.com/sinonjs/sinon)
* [supertest](https://github.com/visionmedia/supertest)

#### Modules to using for code coverage tool: Istanbul
* [istanbul](https://github.com/gotwarlost/istanbul)

```
npm install -D chai mocha sinon supertest istanbul
```

### The unit tests will be executed out by a task Grunt

#### Install Grunt and module for mocha + istanbul
```
npm install -D grunt grunt-mocha-istanbul
```

##### Or you can copy this piece of code in the file `package.json` and then run `npm install`

```json
{
  "devDependencies": {
    "chai": "^3.5.0",
    "grunt": "^1.0.1",
    "grunt-mocha-istanbul": "^5.0.1",
    "istanbul": "^0.4.3",
    "mocha": "^2.5.3",
    "sinon": "^1.17.4",
    "sinon-chai": "^2.8.0",
    "supertest": "^1.2.0"
  }
}
```

## we must modify the `.sailsrc` file and add the module Test:
```json
{
  "generators": {
    "modules": {
        "test": "sails-generate-unittest"
    }
  }
}
```

## once the modules installed, we can run the tests generator
```
sails generate test <apiname>
```
### `<apiname>` is the endpoint we want to test
for example, we have User module and User controller, the execution would be:
```
sails generate test User
```

## The end result will be the generation of the following structure test

    test                        - Root directory for test
    ├── fixtures
    ├── integration
    │   ├── blueprint           - Test directory for Blueprint
    │   ├── controller          - Test directory for controllers
    │   ├── models              - For Models
    │   ├── polices             - For Polices
    │   └── services            - For Services
    ├── README.md               - README file
    ├── bootstrap.test.js       - Load sails to test
    └── moncha.opts             - Mocha configurations

## Gruntjs tasks to be created

    task
    ├── config
    │   └── mocha_istanbul.js   - Mocha and Istanbul coverage configuration
    └── register
        └── test.js             - Task for to run test

## Creating test environment

    config
    └── env
        └── test.js             - Test environment

### More Resources

- [Stackoverflow](http://stackoverflow.com/questions/tagged/sails.js)
- [#sailsjs on Freenode](http://webchat.freenode.net/) (IRC channel)
- [Twitter](https://twitter.com/sailsjs)
- [Professional/enterprise](https://github.com/balderdashy/sails-docs/blob/master/FAQ.md#are-there-professional-support-options)
- [Tutorials](https://github.com/balderdashy/sails-docs/blob/master/FAQ.md#where-do-i-get-help)
-

### License

**[MIT](./LICENSE)**

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Kenjis\MonkeyPatch\Exception;

use RuntimeException;

class ExitException extends RuntimeException
{
	public $file;
	public $line;
	public $class;
	public $method;
	public $exit_status;
}


text:
/**
 * Forked from https://github.com/deepsweet/istanbul-instrumenter-loader@0.1.3
 */

'use strict';

var istanbul = require('istanbul');
var path = require('path');

var root = path.join(__dirname, '../../../');
var skipInstrumenting = [
  './node_modules',
  './test',
  './src/debug'
].map(function(filePath) {
  return path.join(root, filePath);
});

function ignoreContent(source) {
  return '/* istanbul ignore next */\n(function() {\n' + source + '\n}());';
}

module.exports = function(source) {
  var extensionMatch = this.query.match(/(\?|&)extension=([^&]+)/);
  var extensionVar = (extensionMatch && extensionMatch[2]) || '';
  var instrumenter = new istanbul.Instrumenter({
    coverageVariable: '__coverage__',
    embedSource: true,
    noAutoWrap: true
  });
  var filePath = this.resourcePath;

  if (/\.json$/.test(filePath)) {
    return ignoreContent(source);
  }

  for (var i = 0; i < skipInstrumenting.length; i++) {
    var folderPath = skipInstrumenting[i];
    if (filePath.substr(0, folderPath.length) === folderPath) {
      return ignoreContent(source);
    }
  }

  if (this.cacheable) {
    this.cacheable();
  }

  var claimedPath = filePath.replace(/\.js$/, extensionVar);
  return instrumenter.instrumentSync(source, path.relative(root, claimedPath));
};


text:
package com.ggj.service;

import com.ggj.bean.City;
import com.ggj.dao.CityDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * author:gaoguangjin
 * Description:
 * Email:335424093@qq.com
 * Date 2016/1/23 15:57
 */
@Service
@Transactional(readOnly = true)
public class CityService {
    @Autowired
    private CityDao cityDao;

   public  City getCity(int id){
       return  cityDao.getCity(id);
   }

    @Transactional(readOnly = false)
    public void insert(City city){
        cityDao.insert(city);
    }

    /**
     * 测试事务
     */
    @Transactional(readOnly = false)
    public void transation(){
        City city=new City("shanghai","SH");
        cityDao.insert(city);
        Integer.parseInt("d");
    }

}


text:
	#ifndef _UNICODE
		#define _UNICODE
	#endif
#endif

#define _WARNINGS 3

#ifdef WIN32
#pragma warning(disable : 4996)
#endif

#ifdef WIN32
#pragma warning(disable:4100)
#pragma warning(  disable : 4244 )        // Issue warning 4244
#endif

#ifdef WIN32
#pragma warning(  default : 4244 )        // Issue warning 4244
#endif

#ifdef WIN32
#include "windows.h"
#endif

#include <wx/wx.h>
#if wxUSE_UNICODE
	#ifndef _UNICODE
		#define _UNICODE
	#endif
#endif

#include <algorithm>
#include <list>
#include <vector>
#include <map>
#include <set>
#include <fstream>
#include <iomanip>
#include <cmath>
#include <sstream>
#include <ctime>
#include <iostream>

#include <stdio.h>
#include <stdlib.h>

#include <string.h>
#include <math.h>

//Following is required to be defined on Ubuntu with OCC 6.3.1
#ifndef HAVE_IOSTREAM
#define HAVE_IOSTREAM
#endif

#ifndef CHAR_BIT
#define CHAR_BIT 8
#endif

#ifndef INT_MAX
	#define INT_MAX 2147483647
#endif
#ifndef INT_MIN
	#define INT_MIN  (-2147483647 - 1)
#endif

#include <Standard.hxx>
#include <Standard_TypeDef.hxx>

#include <Bnd_Box.hxx>
#include <BRepAdaptor_Curve.hxx>
#include <BRepAdaptor_Surface.hxx>
#include <BRepAlgoAPI_Common.hxx>
#include <BRepAlgoAPI_Cut.hxx>
#include <BRepAlgoAPI_Fuse.hxx>
#include <BRepAlgo_Fuse.hxx>
#include <BRepBndLib.hxx>
#include <BRepBuilderAPI_GTransform.hxx>
#include <BRepBuilderAPI_MakeEdge.hxx>
#include <BRepBuilderAPI_MakeFace.hxx>
#include <BRepBuilderAPI_MakePolygon.hxx>
#include <BRepBuilderAPI_MakeShape.hxx>
#include <BRepBuilderAPI_MakeSolid.hxx>
#include <BRepBuilderAPI_MakeWire.hxx>
#include <BRepBuilderAPI_Transform.hxx>
#include <BRepExtrema_DistShapeShape.hxx>
#include <BRepFilletAPI_MakeChamfer.hxx>
#include <BRepFilletAPI_MakeFillet.hxx>
#include <BRepFilletAPI_MakeFillet2d.hxx>
#include <BRepGProp.hxx>
#include <BRepMesh_IncrementalMesh.hxx>
#include <BRepOffsetAPI_DraftAngle.hxx>
#include <BRepOffsetAPI_MakeEvolved.hxx>
#include <BRepOffsetAPI_MakeOffset.hxx>
#include <BRepOffsetAPI_MakeOffsetShape.hxx>
#include <BRepOffsetAPI_MakePipe.hxx>
#include <BRepOffsetAPI_Sewing.hxx>
#include <BRepOffsetAPI_ThruSections.hxx>
#include <BRepPrimAPI_MakeBox.hxx>
#include <BRepPrimAPI_MakeCone.hxx>
#include <BRepPrimAPI_MakeCylinder.hxx>
#include <BRepPrimAPI_MakePrism.hxx>
#include <BRepPrimAPI_MakeRevol.hxx>
#include <BRepPrimAPI_MakeSphere.hxx>
#include <BRep_Tool.hxx>
#include <BRepTools.hxx>
#include <BRepTools_WireExplorer.hxx>
#include <GCPnts_AbscissaPoint.hxx>
#include <GC_MakeSegment.hxx>
#include <GC_MakeArcOfCircle.hxx>
#include <Geom_Axis1Placement.hxx>
#include <Geom_BezierCurve.hxx>
#include <Geom_BezierSurface.hxx>
#include <Geom_BSplineCurve.hxx>
#include <Geom_BSplineSurface.hxx>
#include <Geom_Curve.hxx>
#include <Geom_Line.hxx>
#include <Geom_Plane.hxx>
#include <GeomAPI_IntCS.hxx>
#include <GeomAPI_Interpolate.hxx>
#include <GeomAPI_IntSS.hxx>
#include <GeomAPI_PointsToBSpline.hxx>
#include <GeomAPI_ProjectPointOnCurve.hxx>
#include <GeomAPI_ProjectPointOnSurf.hxx>
#include <GeomConvert_CompCurveToBSplineCurve.hxx>
#include <GeomLProp_SLProps.hxx>
#include <GProp_GProps.hxx>
#include <gp.hxx>
#include <gp_Ax1.hxx>
#include <gp_Circ.hxx>
#include <gp_Cone.hxx>
#include <gp_Cylinder.hxx>
#include <gp_Dir.hxx>
#include <gp_Elips.hxx>
#include <gp_GTrsf.hxx>
#include <gp_Lin.hxx>
#include <gp_Pln.hxx>
#include <gp_Pnt.hxx>
#include <gp_Sphere.hxx>
#include <gp_Torus.hxx>
#include <gp_Trsf.hxx>
#include <gp_Vec.hxx>
#include <Handle_Geom_TrimmedCurve.hxx>
#include <IGESControl_Controller.hxx>
#include <IGESControl_Reader.hxx>
#include <IGESControl_Writer.hxx>
#include <IntTools_FaceFace.hxx>
#include "math_BFGS.hxx"
#include "math_MultipleVarFunctionWithGradient.hxx"
#include <Poly_Connect.hxx>
#include <Poly_Polygon3D.hxx>
#include <Poly_PolygonOnTriangulation.hxx>
#include <Poly_Triangulation.hxx>
#include <Precision.hxx>
#include <ShapeFix_Wire.hxx>
#include <Standard_ErrorHandler.hxx>
#include <StdPrs_ToolShadedShape.hxx>
#include <STEPControl_Controller.hxx>
#include <STEPControl_Reader.hxx>
#include <STEPControl_Writer.hxx>
#include <TColgp_Array1OfDir.hxx>
#include <TColgp_Array1OfPnt.hxx>
#include <TColgp_Array2OfPnt.hxx>
#include <TColgp_HArray1OfPnt.hxx>
#include <TColStd_Array1OfInteger.hxx>
#include <TColStd_Array1OfReal.hxx>
#include <TopExp.hxx>
#include <TopExp_Explorer.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Face.hxx>
#include <TopoDS_Shape.hxx>
#include <TopoDS_Solid.hxx>
#include <TopoDS_Vertex.hxx>
#include <TopoDS_Wire.hxx>
#include <TopOpeBRep_FacesIntersector.hxx>
#include <TopOpeBRepBuild_FuseFace.hxx>
#include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
#include <TopTools_ListIteratorOfListOfShape.hxx>
#include <TopTools_MapIteratorOfMapOfShape.hxx>
#include <TopTools_MapOfShape.hxx>
#include <UnitsAPI.hxx>

#ifdef __WXMSW__
#ifdef _DEBUG
    #include <wx/msw/msvcrt.h>      // redefines the new() operator
#endif
#endif

#include <wx/aui/aui.h>
#include "wx/brush.h"
#include "wx/button.h"
#include <wx/clipbrd.h>
#include <wx/checklst.h>
#include "wx/choice.h"
#include <wx/choicdlg.h>
#include <wx/cmdline.h>
#include "wx/combobox.h"
#include <wx/confbase.h>
#include <wx/config.h>
#include "wx/cursor.h"
#include <wx/dc.h>
#include "wx/dcclient.h"
#include <wx/dcmirror.h>
#include "wx/defs.h"
#include "wx/dirdlg.h"
#include "wx/dnd.h"
#include <wx/dynlib.h>
#include "wx/event.h"
#include <wx/fileconf.h>
#include <wx/filedlg.h>
#include <wx/filename.h>
#include <wx/glcanvas.h>
#include "wx/hash.h"
#include <wx/image.h>
#include <wx/imaglist.h>
#include "wx/intl.h"
#include "wx/layout.h"
#include "wx/log.h"
#include <wx/menuitem.h>
#include "wx/msgdlg.h"
#include "wx/object.h"
#include "wx/panel.h"
#include "wx/pen.h"
#include "wx/popupwin.h"
#include <wx/print.h>
#include <wx/printdlg.h>
#include "wx/settings.h"
#include "wx/scrolwin.h"
#include "wx/sizer.h"
#include "wx/stattext.h"
#include <wx/stdpaths.h>
#include "wx/string.h"
#include <wx/sizer.h>
#include "wx/textctrl.h"
#include "wx/textdlg.h"
#include <wx/toolbar.h>
#include <wx/tooltip.h>
#include <wx/treectrl.h>
#include "wx/window.h"
#include <wx/tokenzr.h>

#include "../tinyxml/tinyxml.h"

extern "C" {
#include <GL/gl.h>
#include <GL/glu.h>
}

#include "../interface/strconv.h"
#include "../interface/Geom.h"
#include "../interface/HeeksObj.h"
#include "../interface/HeeksColor.h"
#include "../interface/Material.h"
#include "../interface/InputMode.h"
#include "../interface/Tool.h"
#include "../interface/PropertyString.h"
#include "../interface/HeeksCADInterface.h"
#include "HeeksCAD.h"

#include "ConversionTools.h"
#include "CoordinateSystem.h"
#include "Face.h"
#include "Edge.h"
#include "Loop.h"
#include "Gripper.h"
//#include "Loop.h"
#include "MarkedList.h"
#include "Shape.h"
#include "Sketch.h"
#include "Solid.h"

// Visual Studio 2010 work arround

#if _MSC_VER == 1600
	#include <iterator>
#endif


text:
//=================================================================================================

//=================================================================================================

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/SymmetricMatrix.h>
#include <blaze/math/UpperMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatsmatadd/OperationTest.h>
#include <blazetest/system/MathTest.h>

//=================================================================================================
//
//  MAIN FUNCTION
//
//=================================================================================================

//*************************************************************************************************
int main()
{
   std::cout << "   Running 'SDbUCa'..." << std::endl;

   using blazetest::mathtest::TypeA;
   using blazetest::mathtest::TypeB;

   try
   {
      // Matrix type definitions
      typedef blaze::SymmetricMatrix< blaze::DynamicMatrix<TypeB> >  SDb;
      typedef blaze::UpperMatrix< blaze::CompressedMatrix<TypeA> >   UCa;

      // Creator type definitions
      typedef blazetest::Creator<SDb>  CSDb;
      typedef blazetest::Creator<UCa>  CUCa;

      // Running tests with small matrices
      for( size_t i=0UL; i<=6UL; ++i ) {
         for( size_t j=0UL; j<=UCa::maxNonZeros( i ); ++j ) {
            RUN_DMATSMATADD_OPERATION_TEST( CSDb( i ), CUCa( i, j ) );
         }
      }

      // Running tests with large matrices
      RUN_DMATSMATADD_OPERATION_TEST( CSDb(  67UL ), CUCa(  67UL,  7UL ) );
      RUN_DMATSMATADD_OPERATION_TEST( CSDb( 128UL ), CUCa( 128UL, 16UL ) );
   }
   catch( std::exception& ex ) {
      std::cerr << "\n\n ERROR DETECTED during dense matrix/sparse matrix addition:\n"
                << ex.what() << "\n";
      return EXIT_FAILURE;
   }

   return EXIT_SUCCESS;
}
//*************************************************************************************************


text:
title:  Jongerenles
date:   23/07/2021
---

### Het prijskaartje dat hangt aan rust

#### Opdracht van de vorige week

`Wanneer maakt geld gelukkig?`

#### Lees samen

2 Samuel 12:1-23

#### Ijsbrekervraag

`Wat geeft jou rust?`

#### Inspiratie

'Toen zei David tegen Natan: 'Ik heb iets heel ergs gedaan. Natan zei: 'De Heer vergeeft het u.' (2 Samuel 12:13, BGT.)

#### Behandel de tekst

Ooit was David een herder. God koos hem echter tot koning. David deed veel goede dingen, maar ook een aantal hele foute. Een van de grootste fouten die koning David in zijn leven had begaan, was de vrouw van een trouwe soldaat in zijn leger afpakken. Ze heette Batseba. David ging vreemd met haar en maakte haar zwanger. Zij kon niets tegen de koning inbrengen. Dit was pure lust van David. Hij had dit helemaal niet hoeven doen. Als koning had hij immers alles wat zijn hartje begeerde, hij kwam niets tekort. En toch moest en zou hij deze vrouw in bezit krijgen. Maar toen hij ontdekte dat ze zwanger was, liet hij haar man terugkeren van het front en probeerde hem bij haar te laten slapen zodat het zou lijken alsof hij de vader van het kind zou zijn. Dat plan mislukte echter met als gevolg dat koning David die soldaat, Uria genaamd, liet omkomen tijdens een strijd met de Ammonieten. God vond het echter bijzonder slecht wat David had gedaan en stuurde de profeet Natan naar hem toe.

#### Gespreksvragen naar aanleiding van de tekst

`Wat doet de profeet Natan zodra hij bij koning David aankomt? (2 Samuel 12:1)`

`Wie zijn de hoofdpersonen in dit verhaal en wat bezaten zij? (verzen 1-3)`

`Wat gebeurt er op een dag in het leven van die rijke man? Hoe lost hij dit op? (vers 4) En, wat vind jij hiervan en waarom?`

`Hoe reageerde koning David en wat moet er volgens hem gebeuren? (verzen 5-6)`

`Naar wie verwijzen de hoofdpersonen in het verhaal? (verzen 7-9)`

`Hoe past God het oordeel van David (verzen 5-6) toe? (verzen 10-12)`

`Wat is Davids reactie? (vers 13)`

`Hoe krijg je rust van de onrust die het gevolg is van je zonden?`

#### Opdracht

`Hoe vind jij rust bij God?`


text:
.class public final Landroid/content/pm/PackageParser$ActivityIntentInfo;
.super Landroid/content/pm/PackageParser$IntentInfo;
.source "PackageParser.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/content/pm/PackageParser;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "ActivityIntentInfo"
.end annotation

# instance fields
.field public final activity:Landroid/content/pm/PackageParser$Activity;

# direct methods
.method public constructor <init>(Landroid/content/pm/PackageParser$Activity;)V
    .locals 0
    .parameter "_activity"

    .prologue
    .line 3779
    invoke-direct {p0}, Landroid/content/pm/PackageParser$IntentInfo;-><init>()V

    .line 3780
    iput-object p1, p0, Landroid/content/pm/PackageParser$ActivityIntentInfo;->activity:Landroid/content/pm/PackageParser$Activity;

    .line 3781
    return-void
.end method

# virtual methods
.method public toString()Ljava/lang/String;
    .locals 2

    .prologue
    .line 3784
    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    const-string v1, "ActivityIntentInfo{"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-static {p0}, Ljava/lang/System;->identityHashCode(Ljava/lang/Object;)I

    move-result v1

    invoke-static {v1}, Ljava/lang/Integer;->toHexString(I)Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, " "

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    iget-object v1, p0, Landroid/content/pm/PackageParser$ActivityIntentInfo;->activity:Landroid/content/pm/PackageParser$Activity;

    iget-object v1, v1, Landroid/content/pm/PackageParser$Activity;->info:Landroid/content/pm/ActivityInfo;

    iget-object v1, v1, Landroid/content/pm/ActivityInfo;->name:Ljava/lang/String;

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string/jumbo v1, "}"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method


text:
// TaskStorage.cs
//

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Runtime.Serialization;

namespace TaskList {

    public class TaskDTO {

        public DateTime DueDate {
            get;
            set;
        }

        public bool IsCompleted {
            get;
            set;
        }

        public string Name {
            get;
            set;
        }
    }

    internal static class TaskStorage {

        public static Task[] LoadTasks() {
            Task[] tasks = null;

            try {
                IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
                if (storage.FileExists("Tasks.xml")) {
                    using (Stream tasksStream = storage.OpenFile("TaskList.xml", FileMode.Open)) {
                        DataContractSerializer reader = new DataContractSerializer(typeof(TaskDTO[]));

                        TaskDTO[] taskObjects = (TaskDTO[])reader.ReadObject(tasksStream);

                        tasks = new Task[taskObjects.Length];
                        for (int i = 0; i < taskObjects.Length; i++) {
                            tasks[i] = new Task() {
                                Name = taskObjects[i].Name,
                                DueDate = taskObjects[i].DueDate,
                                IsCompleted = taskObjects[i].IsCompleted
                            };
                        }

                        IPredicate<Task> filter = new AllTasksFilter();
                        foreach (Task task in tasks) {
                            task.Filter(filter);
                        }
                    }
                }
            }
            catch {
            }

            return tasks;
        }

        public static void SaveTasks(Task[] tasks) {
            try {
                IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();

                using (Stream tasksStream = storage.OpenFile("TaskList.xml", FileMode.Create)) {
                    DataContractSerializer writer = new DataContractSerializer(typeof(TaskDTO[]));

                    TaskDTO[] taskObjects = new TaskDTO[tasks.Length];
                    for (int i = 0; i < tasks.Length; i++) {
                        taskObjects[i] = new TaskDTO() {
                            Name = tasks[i].Name,
                            DueDate = tasks[i].DueDate,
                            IsCompleted = tasks[i].IsCompleted
                        };
                    }

                    writer.WriteObject(tasksStream, taskObjects);
                    tasksStream.Flush();
                }
            }
            catch {
            }
        }
    }
}


text:
/**
 *
 */
package gov.va.med.siteservice.interactive.commands;

import gov.va.med.interactive.Command;
import gov.va.med.interactive.CommandParametersDescription;
import gov.va.med.interactive.CommandProcessor;
import gov.va.med.siteservice.ProtocolServerConfiguration;
import gov.va.med.siteservice.SiteResolutionProviderConfiguration;

/**
 * @author vhaiswbeckec
 *
 */
public class AddProtocolCommand
extends Command<SiteResolutionProviderConfiguration>
{
	private static final CommandParametersDescription<?>[] commandParametersDescription =
		new CommandParametersDescription[]
		{
			new CommandParametersDescription<String>("protocol", String.class, true),
			new CommandParametersDescription<String>("application", String.class, true),
			new CommandParametersDescription<String>("metadataPath", String.class, true),
			new CommandParametersDescription<String>("imagePath", String.class, true),
			new CommandParametersDescription<Boolean>("vista", Boolean.class, false),
		};
	public static CommandParametersDescription<?>[] getCommandParametersDescription()
	{
		return commandParametersDescription;
	}

	/**
	 * @param commandParameterValues
	 */
	public AddProtocolCommand(String[] commandParameterValues)
	{
		super(commandParameterValues);
	}

	/**
	 * @see gov.va.med.interactive.Command#processCommand(gov.va.med.interactive.CommandProcessor, java.lang.Object)
	 */
	@Override
	public void processCommand(CommandProcessor<SiteResolutionProviderConfiguration> processor, SiteResolutionProviderConfiguration config)
	throws Exception
	{
		String protocol = this.getParameterValue("protocol", String.class);
		String application = this.getParameterValue("application", String.class);
		String metadataPath = this.getParameterValue("metadataPath", String.class);
		String imagePath = this.getParameterValue("imagePath", String.class);
		Boolean vista = this.getParameterValue("vista", Boolean.class);

		ProtocolServerConfiguration protocolConfiguration = new ProtocolServerConfiguration(
			vista == null ? false : vista.booleanValue(),
			application,
			metadataPath,
			imagePath
		);

		config.addProtocolConfiguration(protocol, protocolConfiguration );
	}
}


text:
============
Installation
============

At the command line::

    $ easy_install django-publica-menus

Or, if you have virtualenvwrapper installed::

    $ mkvirtualenv django-publica-menus
    $ pip install django-publica-menus


text:
device_name=$1

TIME=`date +%Y%m%d_%H%M%S`

cd /etc/ssl/certs

if [ "$2" ]
	then
	echo "******* generating root key ************"
	openssl genrsa -out rootCA.key 2048
	echo "******* self signing root key ************"
	openssl req -x509 -new -nodes -key rootCA.key -days 3650 -out rootCA.pem
fi

echo "******* generating server key ************"
cd /etc/pki/tls/private
if [ -f "localhost.key"];	then
	mv localhost.key localhost-$TIME.key
fi
openssl genrsa -out $device_name.key 2048

echo "******* generating server csr  key ************"
cd /etc/pki/tls/certs
openssl req -new -key ../private/$device_name.key -out $device_name.csr

echo "******* signing server csr ************"
if [ -f "localhost.crt"];	then
	mv localhost.crt localhost-$TIME.crt
fi
openssl x509 -req -in $device_name.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out $device_name.crt -days 3650


text:
concurrent.core.logging package
===============================

Submodules
----------

concurrent.core.logging.log module
----------------------------------

.. automodule:: concurrent.core.logging.log
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: concurrent.core.logging
    :members:
    :undoc-members:
    :show-inheritance:


text:
/**
 * @file
 * Declares ignite::Ignite class.
 */

#ifndef _IGNITE_IGNITE
#define _IGNITE_IGNITE

#include "ignite/cache/cache.h"
#include "ignite/transactions/transactions.h"
#include "ignite/impl/ignite_impl.h"
#include "ignite/ignite_configuration.h"

namespace ignite
{
    /**
     * Main interface to operate with %Ignite.
     *
     * This class implemented as a reference to an implementation so copying
     * of this class instance will only create another reference to the same
     * underlying object. Underlying object released automatically once all
     * the instances are destructed.
     */
    class IGNITE_IMPORT_EXPORT Ignite
    {
        friend class impl::IgniteImpl;
    public:
        /**
         * Default constructor.
         */
        Ignite();

        /**
         * Constructor.
         */
        Ignite(impl::IgniteImpl* impl);

        /**
         * Get Ignite instance name.
         *
         * @return Name.
         */
        const char* GetName() const;

        /**
         * Get node configuration.
         *
         * This method should only be used on the valid instance.
         *
         * @return Node configuration.
         */
        const IgniteConfiguration& GetConfiguration() const;

        /**
         * Get cache.
         *
         * This method should only be used on the valid instance.
         *
         * @param name Cache name.
         * @return Cache.
         */
        template<typename K, typename V>
        cache::Cache<K, V> GetCache(const char* name)
        {
            IgniteError err;

            cache::Cache<K, V> res = GetCache<K, V>(name, err);

            IgniteError::ThrowIfNeeded(err);

            return res;
        }

        /**
         * Get cache.
         *
         * This method should only be used on the valid instance.
         *
         * @param name Cache name.
         * @param err Error;
         * @return Cache.
         */
        template<typename K, typename V>
        cache::Cache<K, V> GetCache(const char* name, IgniteError& err)
        {
            impl::cache::CacheImpl* cacheImpl = impl.Get()->GetCache<K, V>(name, err);

            return cache::Cache<K, V>(cacheImpl);
        }

        /**
         * Get or create cache.
         *
         * This method should only be used on the valid instance.
         *
         * @param name Cache name.
         * @return Cache.
         */
        template<typename K, typename V>
        cache::Cache<K, V> GetOrCreateCache(const char* name)
        {
            IgniteError err;

            cache::Cache<K, V> res = GetOrCreateCache<K, V>(name, err);

            IgniteError::ThrowIfNeeded(err);

            return res;
        }

        /**
         * Get or create cache.
         *
         * This method should only be used on the valid instance.
         *
         * @param name Cache name.
         * @param err Error;
         * @return Cache.
         */
        template<typename K, typename V>
        cache::Cache<K, V> GetOrCreateCache(const char* name, IgniteError& err)
        {
            impl::cache::CacheImpl* cacheImpl = impl.Get()->GetOrCreateCache<K, V>(name, err);

            return cache::Cache<K, V>(cacheImpl);
        }

        /**
         * Create cache.
         *
         * This method should only be used on the valid instance.
         *
         * @param name Cache name.
         * @return Cache.
         */
        template<typename K, typename V>
        cache::Cache<K, V> CreateCache(const char* name)
        {
            IgniteError err;

            cache::Cache<K, V> res = CreateCache<K, V>(name, err);

            IgniteError::ThrowIfNeeded(err);

            return res;
        }

        /**
         * Create cache.
         *
         * This method should only be used on the valid instance.
         *
         * @param name Cache name.
         * @param err Error;
         * @return Cache.
         */
        template<typename K, typename V>
        cache::Cache<K, V> CreateCache(const char* name, IgniteError& err)
        {
            impl::cache::CacheImpl* cacheImpl = impl.Get()->CreateCache<K, V>(name, err);

            return cache::Cache<K, V>(cacheImpl);
        }

        /**
         * Get transactions.
         *
         * This method should only be used on the valid instance.
         *
         * @return Transaction class instance.
         */
        transactions::Transactions GetTransactions();

        /**
         * Get ignite binding.
         *
         * This method should only be used on the valid instance.
         *
         * @return IgniteBinding class instance.
         */
        IgniteBinding GetBinding();

        /**
         * Check if the instance is valid.
         *
         * Invalid instance can be returned if some of the previous
         * operations have resulted in a failure. For example invalid
         * instance can be returned by not-throwing version of method
         * in case of error. Invalid instances also often can be
         * created using default constructor.
         *
         * @return True if the instance is valid and can be used.
         */
        bool IsValid() const
        {
            return impl.IsValid();
        }

    private:
        /** Implementation delegate. */
        ignite::common::concurrent::SharedPointer<impl::IgniteImpl> impl;
    };
}

#endif //_IGNITE_IGNITE


text:
package handlers

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/emicklei/go-restful"
	"github.com/quintilesims/layer0/api/logic"
	"github.com/quintilesims/layer0/common/config"
	"github.com/quintilesims/layer0/common/errors"
	"github.com/quintilesims/layer0/common/models"
)

type AdminHandler struct {
	AdminLogic logic.AdminLogic
}

func NewAdminHandler(adminLogic logic.AdminLogic) *AdminHandler {
	return &AdminHandler{
		AdminLogic: adminLogic,
	}
}

func (this AdminHandler) Routes() *restful.WebService {
	service := new(restful.WebService)
	service.Path("/admin").
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)

	id := service.PathParameter("id", "identifier of the environment").
		DataType("string")

	service.Route(service.GET("/version").
		Filter(basicAuthenticate).
		To(this.GetVersion).
		Doc("Returns Current API version"))

	service.Route(service.PUT("/scale/{id}").
		Filter(basicAuthenticate).
		To(this.RunEnvironmentScaler).
		Reads("").
		Param(id).
		Doc("Run resource manager on an environment"))

	service.Route(service.GET("/config").
		To(this.GetConfig).
		Doc("Returns Configuration of the API Server").
		Writes(models.APIConfig{}))

	service.Route(service.POST("/sql").
		Filter(basicAuthenticate).
		To(this.UpdateSQL).
		Reads(models.SQLVersion{}).
		Doc("Configures sql settings"))

	return service
}

func (this *AdminHandler) GetVersion(request *restful.Request, response *restful.Response) {
	version := config.APIVersion()
	response.WriteAsJson(version)
}

func (this *AdminHandler) GetConfig(request *restful.Request, response *restful.Response) {
	publicSubnets := []string{}
	for _, subnet := range strings.Split(config.AWSPublicSubnets(), ",") {
		publicSubnets = append(publicSubnets, subnet)
	}

	privateSubnets := []string{}
	for _, subnet := range strings.Split(config.AWSPrivateSubnets(), ",") {
		privateSubnets = append(privateSubnets, subnet)
	}

	model := models.APIConfig{
		Prefix:         config.Prefix(),
		VPCID:          config.AWSVPCID(),
		PublicSubnets:  publicSubnets,
		PrivateSubnets: privateSubnets,
	}

	response.WriteAsJson(model)
}

func (this *AdminHandler) RunEnvironmentScaler(request *restful.Request, response *restful.Response) {
	id := request.PathParameter("id")
	if id == "" {
		err := fmt.Errorf("Parameter 'id' is required")
		BadRequest(response, errors.MissingParameter, err)
		return
	}

	info, err := this.AdminLogic.RunEnvironmentScaler(id)
	if err != nil {
		ReturnError(response, err)
		return
	}

	response.WriteAsJson(info)
}

func (this *AdminHandler) UpdateSQL(request *restful.Request, response *restful.Response) {
	if err := this.AdminLogic.UpdateSQL(); err != nil {
		ReturnError(response, err)
		return
	}

	response.WriteHeader(http.StatusNoContent)
}


text:
package uk.ac.ebi.eva.pipeline.parameters.validation.job;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.batch.core.JobParameter;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersInvalidException;

import uk.ac.ebi.eva.pipeline.parameters.JobParametersNames;
import uk.ac.ebi.eva.test.rules.PipelineTemporaryFolderRule;

import java.util.Map;
import java.util.TreeMap;

/**
 * Tests that the arguments necessary to run a {@link uk.ac.ebi.eva.pipeline.jobs.GenotypedVcfJob} are
 * correctly validated
 */
public class GenotypedVcfJobParametersValidatorTest {

    private GenotypedVcfJobParametersValidator validator;

    @Rule
    public PipelineTemporaryFolderRule temporaryFolder = new PipelineTemporaryFolderRule();

    private Map<String, JobParameter> requiredParameters;

    private Map<String, JobParameter> annotationParameters;

    private Map<String, JobParameter> statsParameters;

    private Map<String, JobParameter> optionalParameters;

    @Before
    public void setUp() throws Exception {
        validator = new GenotypedVcfJobParametersValidator();
        final String dir = temporaryFolder.getRoot().getCanonicalPath();

        requiredParameters = new TreeMap<>();

        // variant load step
        requiredParameters.put(JobParametersNames.DB_NAME, new JobParameter("database"));
        requiredParameters.put(JobParametersNames.DB_COLLECTIONS_VARIANTS_NAME, new JobParameter("variants"));
        requiredParameters.put(JobParametersNames.INPUT_STUDY_ID, new JobParameter("inputStudyId"));
        requiredParameters.put(JobParametersNames.INPUT_VCF_ID, new JobParameter("inputVcfId"));
        requiredParameters.put(JobParametersNames.INPUT_VCF_AGGREGATION, new JobParameter("NONE"));
        requiredParameters.put(JobParametersNames.INPUT_VCF,
                new JobParameter(temporaryFolder.newFile().getCanonicalPath()));

        // file load step
        requiredParameters.put(JobParametersNames.DB_COLLECTIONS_FILES_NAME, new JobParameter("collectionsFilesName"));
        requiredParameters.put(JobParametersNames.INPUT_STUDY_NAME, new JobParameter("inputStudyName"));
        requiredParameters.put(JobParametersNames.INPUT_STUDY_TYPE, new JobParameter("COLLECTION"));

        // skips
        requiredParameters.put(JobParametersNames.ANNOTATION_SKIP, new JobParameter("false"));
        requiredParameters.put(JobParametersNames.STATISTICS_SKIP, new JobParameter("false"));

        // annotation
        annotationParameters = new TreeMap<>();
        annotationParameters.put(JobParametersNames.OUTPUT_DIR_ANNOTATION, new JobParameter(dir));
        annotationParameters.put(JobParametersNames.APP_VEP_CACHE_SPECIES, new JobParameter("Human"));
        annotationParameters.put(JobParametersNames.APP_VEP_CACHE_VERSION, new JobParameter("100_A"));
        annotationParameters.put(JobParametersNames.APP_VEP_VERSION, new JobParameter("80"));
        annotationParameters.put(JobParametersNames.APP_VEP_NUMFORKS, new JobParameter("6"));
        annotationParameters.put(JobParametersNames.APP_VEP_TIMEOUT, new JobParameter("600"));
        annotationParameters.put(JobParametersNames.ANNOTATION_OVERWRITE, new JobParameter("false"));
        annotationParameters.put(JobParametersNames.DB_COLLECTIONS_ANNOTATION_METADATA_NAME,
                new JobParameter("annotationMetadata"));
        annotationParameters.put(JobParametersNames.APP_VEP_CACHE_PATH,
                new JobParameter(temporaryFolder.getRoot().getCanonicalPath()));
        annotationParameters.put(JobParametersNames.APP_VEP_PATH,
                new JobParameter(temporaryFolder.newFile().getCanonicalPath()));
        annotationParameters.put(JobParametersNames.INPUT_FASTA,
                new JobParameter(temporaryFolder.newFile().getCanonicalPath()));

        // statistics
        statsParameters = new TreeMap<>();
        statsParameters.put(JobParametersNames.OUTPUT_DIR_STATISTICS, new JobParameter(dir));

        // optionals
        optionalParameters = new TreeMap<>();
        optionalParameters.put(JobParametersNames.CONFIG_CHUNK_SIZE, new JobParameter("100"));
        optionalParameters.put(JobParametersNames.CONFIG_RESTARTABILITY_ALLOW, new JobParameter("true"));
        optionalParameters.put(JobParametersNames.STATISTICS_OVERWRITE, new JobParameter("true"));
    }

    // The next tests show behaviour about the required parameters

    @Test
    public void allJobParametersAreValid() throws JobParametersInvalidException {
        Map<String, JobParameter> parameters = new TreeMap<>();
        parameters.putAll(requiredParameters);
        parameters.putAll(optionalParameters);
        parameters.putAll(annotationParameters);
        parameters.putAll(statsParameters);
        validator.validate(new JobParameters(parameters));
    }

    @Test
    public void allRequiredJobParametersAreValid() throws JobParametersInvalidException {
        Map<String, JobParameter> parameters = new TreeMap<>();
        parameters.putAll(requiredParameters);
        parameters.putAll(annotationParameters);
        parameters.putAll(statsParameters);
        validator.validate(new JobParameters(parameters));
    }

    @Test(expected = JobParametersInvalidException.class)
    public void dbNameIsRequiredSkippingAnnotationAndStats() throws JobParametersInvalidException {
        Map<String, JobParameter> parameters = new TreeMap<>();
        parameters.putAll(requiredParameters);
        parameters.putAll(optionalParameters);
        parameters.remove(JobParametersNames.DB_NAME);
        parameters.put(JobParametersNames.ANNOTATION_SKIP, new JobParameter("true"));
        parameters.put(JobParametersNames.STATISTICS_SKIP, new JobParameter("true"));
        validator.validate(new JobParameters(parameters));
    }

    @Test(expected = JobParametersInvalidException.class)
    public void dbNameIsRequiredWithoutSkippingAnnotation() throws JobParametersInvalidException {
        Map<String, JobParameter> parameters = new TreeMap<>();
        parameters.putAll(requiredParameters);
        parameters.putAll(optionalParameters);
        parameters.putAll(annotationParameters);
        parameters.remove(JobParametersNames.DB_NAME);
        parameters.put(JobParametersNames.STATISTICS_SKIP, new JobParameter("true"));
        validator.validate(new JobParameters(parameters));
    }

    @Test(expected = JobParametersInvalidException.class)
    public void dbNameIsRequiredWithoutSkippingStats() throws JobParametersInvalidException {
        Map<String, JobParameter> parameters = new TreeMap<>();
        parameters.putAll(requiredParameters);
        parameters.putAll(optionalParameters);
        parameters.putAll(statsParameters);
        parameters.put(JobParametersNames.ANNOTATION_SKIP, new JobParameter("true"));
        parameters.remove(JobParametersNames.DB_NAME);
        validator.validate(new JobParameters(parameters));
    }

    @Test(expected = JobParametersInvalidException.class)
    public void dbNameIsRequiredWithoutSkippingAnnotationAndStats() throws JobParametersInvalidException {
        Map<String, JobParameter> parameters = new TreeMap<>();
        parameters.putAll(requiredParameters);
        parameters.putAll(optionalParameters);
        parameters.putAll(annotationParameters);
        parameters.putAll(statsParameters);
        parameters.remove(JobParametersNames.DB_NAME);
        validator.validate(new JobParameters(parameters));
    }

    // The next tests show what happens when not all the annotation parameters are present

    @Test
    public void annotationParametersAreNotRequiredIfAnnotationIsSkipped() throws JobParametersInvalidException {
        Map<String, JobParameter> parameters = new TreeMap<>();
        parameters.putAll(requiredParameters);
        parameters.putAll(optionalParameters);
        parameters.putAll(statsParameters);
        parameters.put(JobParametersNames.ANNOTATION_SKIP, new JobParameter("true"));
        validator.validate(new JobParameters(parameters));
    }

    @Test(expected = JobParametersInvalidException.class)
    public void annotationParametersAreRequiredIfAnnotationIsNotSkipped() throws JobParametersInvalidException {
        Map<String, JobParameter> parameters = new TreeMap<>();
        parameters.putAll(requiredParameters);
        parameters.putAll(optionalParameters);
        parameters.putAll(statsParameters);
        validator.validate(new JobParameters(parameters));
    }

    /**
     * The parameter APP_VEP_CACHE_SPECIES is chosen as one belonging to the annotation parameters. We don't check
     * for every annotation parameter, because in AnnotationLoaderStepParametersValidatorTest and
     * GenerateVepAnnotationStepParametersValidatorTest, it is already
     * checked that every missing required parameter makes the validation fail.
     */
    @Test(expected = JobParametersInvalidException.class)
    public void appVepCacheSpeciesIsRequiredIfAnnotationIsNotSkipped() throws JobParametersInvalidException {
        Map<String, JobParameter> parameters = new TreeMap<>();
        parameters.putAll(requiredParameters);
        parameters.putAll(optionalParameters);
        parameters.putAll(annotationParameters);
        parameters.putAll(statsParameters);
        parameters.remove(JobParametersNames.APP_VEP_CACHE_SPECIES);
        validator.validate(new JobParameters(parameters));
    }

    // The next tests show what happens when not all the stats parameters are present

    @Test
    public void statsParametersAreNotRequiredIfStatsIsSkipped() throws JobParametersInvalidException {
        Map<String, JobParameter> parameters = new TreeMap<>();
        parameters.putAll(requiredParameters);
        parameters.putAll(optionalParameters);
        parameters.putAll(annotationParameters);
        parameters.put(JobParametersNames.STATISTICS_SKIP, new JobParameter("true"));
        validator.validate(new JobParameters(parameters));
    }

    @Test(expected = JobParametersInvalidException.class)
    public void statsParametersAreRequiredIfStatsIsNotSkipped() throws JobParametersInvalidException {
        Map<String, JobParameter> parameters = new TreeMap<>();
        parameters.putAll(requiredParameters);
        parameters.putAll(optionalParameters);
        parameters.putAll(annotationParameters);
        validator.validate(new JobParameters(parameters));
    }

    @Test(expected = JobParametersInvalidException.class)
    public void outputDirStatistitcsIsRequiredIfStatsIsNotSkipped() throws JobParametersInvalidException {
        Map<String, JobParameter> parameters = new TreeMap<>();
        parameters.putAll(requiredParameters);
        parameters.putAll(optionalParameters);
        parameters.putAll(annotationParameters);
        parameters.putAll(statsParameters);
        parameters.remove(JobParametersNames.OUTPUT_DIR_STATISTICS);
        validator.validate(new JobParameters(parameters));
    }
}


text:
from django.conf import settings
from django.contrib.staticfiles import utils
from django.contrib.staticfiles.finders import BaseStorageFinder
from .storage import BuiltFileStorage

class BuiltFileFinder(BaseStorageFinder):
    storage = BuiltFileStorage

class BuildableFileFinder(object):
    """
    Wraps a finder class in order to exclude files.

    """
    def __init__(self, finder, include_patterns=None):
        self.wrapped = finder
        self.include_patterns = include_patterns or settings.STATICBUILDER_INCLUDE_FILES

    def list(self, ignore_patterns):
        """
        Delegate the work of this method to the wrapped finder, but filter its
        results.

        """
        for path, storage in self.wrapped.list(ignore_patterns):
            if utils.matches_patterns(path, self.include_patterns):
                yield path, storage

    def __getattr__(self, name):
        """
        Proxy to the wrapped object.

        """
        return getattr(self.wrapped, name)


text:
/*
 * 10. Create a stored procedures in the
 * Northwind database for finding the total incomes
 * for given supplier name and period (start date, end date).
 * Implement a C# method that calls the stored procedure and
 * returns the returned record set.
 */
namespace _10.Stored_Procedures
{
    using System;
    using System.Linq;
    using Northwind.Model;

    class StoredProceduresDemo
    {
        static void Main()
        {
            var supplierName = "Exotic Liquids";
            var startDate = new DateTime(1996, 1, 1);
            var endDate = new DateTime(1997, 12, 31);

            using (var northwindEntities = new NorthwindEntities())
            {
                var totalIncomes = northwindEntities.
                    usp_TotalIncomesOfSupplier(supplierName, startDate, endDate).Single();

                Console.WriteLine("Total incomes: {0:C}", totalIncomes);
            }
        }
    }
}


text:
package com.ctrip.di.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

/**
 * Yarn jobs Mapper
 * @author xgliao
 *
 */
@Repository
public interface YarnJobsMapper {

	public void insertYarnJob(YarnJobsDo yarnJobsDo);

	public List<YarnJobsDo> getYanJobs();

	public Long getMaxStartTime();

	public List<YarnJobCountDo> getAllCount();

	public List<YarnJobCountDo> getJobCountByDate(int date);

	public List<YarnJobCountDo> getJobCountByPageRange(int start, int end);

	public List<YarnJobUserCountDo> getCountByDateUser();

	public List<YarnJobUserCountDo> getCountByDateUserD(int date);

	public List<YarnJobUserCountDo> getCountByDateUserForPage(int start, int num);

	public List<YarnUserJobDo> getNewestUserJobCount();

	public List<YarnUserJobDo> getUserJobCountByDate(int date);

	public List<YarnJobUserCountDo> getYarnJobUserByDate(String date);

	public List<YarnJobUserCountDo> getYarnJobUserByUserName(String userName);

}


text:
#include "headers.h"
#include <stdlib.h>
#include <math.h>

//-----------------------------------------------------------------------------
//  Constants
//-----------------------------------------------------------------------------
static const double OMEGA   = 0.55;    // under-relaxation parameter
static const int    MAXITER = 10;      // max. iterations for storage updating
static const double STOPTOL = 0.005;   // storage updating stopping tolerance

//-----------------------------------------------------------------------------
//  External functions (declared in funcs.h)
//-----------------------------------------------------------------------------
//  flowrout_init            (called by routing_open)
//  flowrout_close           (called by routing_close)
//  flowrout_getRoutingStep  (called routing_getRoutingStep)
//  flowrout_execute         (called routing_execute)

//-----------------------------------------------------------------------------
//  Local functions
//-----------------------------------------------------------------------------
static void   initLinkDepths(void);
static void   initNodeDepths(void);
static void   initNodes(void);
static void   initLinks(void);
static void   validateTreeLayout(void);
static void   validateGeneralLayout(void);
static void   updateStorageState(int i, int j, int links[], double dt);
static double getStorageOutflow(int node, int j, int links[], double dt);
static double getLinkInflow(int link, double dt);
static void   setNewNodeState(int node, double dt);
static void   setNewLinkState(int link);
static void   updateNodeDepth(int node, double y);
static int    steadyflow_execute(int link, double* qin, double* qout,
              double tStep);

//=============================================================================

void flowrout_init(int routingModel)
//
//  Input:   routingModel = routing model code
//  Output:  none
//  Purpose: initializes flow routing system.
//
{
    // --- initialize for dynamic wave routing
    if ( routingModel == DW )
    {
        // --- check for valid conveyance network layout
        validateGeneralLayout();
        dynwave_init();

        // --- initialize node & link depths if not using a hotstart file
        if ( Fhotstart1.mode == NO_FILE )
        {
            initNodeDepths();
            initLinkDepths();
        }
    }

    // --- validate network layout for kinematic wave routing
    else validateTreeLayout();

    // --- initialize node & link volumes
    initNodes();
    initLinks();
}

//=============================================================================

void  flowrout_close(int routingModel)
//
//  Input:   routingModel = routing method code
//  Output:  none
//  Purpose: closes down routing method used.
//
{
    if ( routingModel == DW ) dynwave_close();
}

//=============================================================================

double flowrout_getRoutingStep(int routingModel, double fixedStep)
//
//  Input:   routingModel = type of routing method used
//           fixedStep = user-assigned max. routing step (sec)
//  Output:  returns adjusted value of routing time step (sec)
//  Purpose: finds variable time step for dynamic wave routing.
//
{
    if ( routingModel == DW )
    {
        return dynwave_getRoutingStep(fixedStep);
    }
    return fixedStep;
}

//=============================================================================

int flowrout_execute(int links[], int routingModel, double tStep)
//
//  Input:   links = array of link indexes in topo-sorted order
//           routingModel = type of routing method used
//           tStep = routing time step (sec)
//  Output:  returns number of computational steps taken
//  Purpose: routes flow through conveyance network over current time step.
//
{
    int   i, j;
    int   n1;                          // upstream node of link
    double qin;                        // link inflow (cfs)
    double qout;                       // link outflow (cfs)
    double steps;                      // computational step count

    // --- set overflows to drain any ponded water
    if ( ErrorCode ) return 0;
    for (j = 0; j < Nobjects[NODE]; j++)
    {
        Node[j].updated = FALSE;
        Node[j].overflow = 0.0;
        if ( Node[j].type != STORAGE
        &&   Node[j].newVolume > Node[j].fullVolume )
        {
            Node[j].overflow = (Node[j].newVolume - Node[j].fullVolume)/tStep;
        }
    }

    // --- execute dynamic wave routing if called for
    if ( routingModel == DW )
    {
        return dynwave_execute(tStep);
    }

    // --- otherwise examine each link, moving from upstream to downstream
    steps = 0.0;
    for (i = 0; i < Nobjects[LINK]; i++)
    {
        // --- see if upstream node is a storage unit whose state needs updating
        j = links[i];
        n1 = Link[j].node1;
        if ( Node[n1].type == STORAGE ) updateStorageState(n1, i, links, tStep);

        // --- retrieve inflow at upstream end of link
        qin  = getLinkInflow(j, tStep);

        // route flow through link
        if ( routingModel == SF )
            steps += steadyflow_execute(j, &qin, &qout, tStep);
        else steps += kinwave_execute(j, &qin, &qout, tStep);
        Link[j].newFlow = qout;

        // adjust outflow at upstream node and inflow at downstream node
        Node[ Link[j].node1 ].outflow += qin;
        Node[ Link[j].node2 ].inflow += qout;
    }
    if ( Nobjects[LINK] > 0 ) steps /= Nobjects[LINK];

    // --- update state of each non-updated node and link
    for ( j=0; j<Nobjects[NODE]; j++) setNewNodeState(j, tStep);
    for ( j=0; j<Nobjects[LINK]; j++) setNewLinkState(j);
    return (int)(steps+0.5);
}

//=============================================================================

void validateTreeLayout()
//
//  Input:   none
//  Output:  none
//  Purpose: validates tree-like conveyance system layout used for Steady
//           and Kinematic Wave flow routing
//
{
    int    j;

    // --- check nodes
    for ( j = 0; j < Nobjects[NODE]; j++ )
    {
        switch ( Node[j].type )
        {
          // --- dividers must have only 2 outlet links
          case DIVIDER:
            if ( Node[j].degree > 2 )
            {
                report_writeErrorMsg(ERR_DIVIDER, Node[j].ID);
            }
            break;

          // --- outfalls cannot have any outlet links
          case OUTFALL:
            if ( Node[j].degree > 0 )
            {
                report_writeErrorMsg(ERR_OUTFALL, Node[j].ID);
            }
            break;

          // --- storage nodes can have multiple outlets
          case STORAGE: break;

          // --- all other nodes allowed only one outlet link
          default:
            if ( Node[j].degree > 1 )
            {
                report_writeErrorMsg(ERR_MULTI_OUTLET, Node[j].ID);
            }
        }
    }

    // ---  check links
    for (j=0; j<Nobjects[LINK]; j++)
    {
        switch ( Link[j].type )
        {
          // --- non-dummy conduits cannot have adverse slope
          case CONDUIT:
              if ( Conduit[Link[j].subIndex].slope < 0.0 &&
                   Link[j].xsect.type != DUMMY )
              {
                  report_writeErrorMsg(ERR_SLOPE, Link[j].ID);
              }
              break;

          // --- regulator links must be outlets of storage nodes
          case ORIFICE:
          case WEIR:
          case OUTLET:
            if ( Node[Link[j].node1].type != STORAGE )
            {
                report_writeErrorMsg(ERR_REGULATOR, Link[j].ID);
            }
        }
    }
}

//=============================================================================

void validateGeneralLayout()
//
//  Input:   none
//  Output:  nonw
//  Purpose: validates general conveyance system layout.
//
{
    int i, j;
    int outletCount = 0;

    // --- use node inflow attribute to count inflow connections
    for ( i=0; i<Nobjects[NODE]; i++ ) Node[i].inflow = 0.0;

    // --- examine each link
    for ( j = 0; j < Nobjects[LINK]; j++ )
    {
        // --- update inflow link count of downstream node
        i = Link[j].node1;
        if ( Node[i].type != OUTFALL ) i = Link[j].node2;
        Node[i].inflow += 1.0;

        // --- if link is dummy link or ideal pump then it must
        //     be the only link exiting the upstream node
        if ( (Link[j].type == CONDUIT && Link[j].xsect.type == DUMMY) ||
             (Link[j].type == PUMP &&
              Pump[Link[j].subIndex].type == IDEAL_PUMP) )
        {
            i = Link[j].node1;
            if ( Link[j].direction < 0 ) i = Link[j].node2;
            if ( Node[i].degree > 1 )
            {
                report_writeErrorMsg(ERR_DUMMY_LINK, Node[i].ID);
            }
        }
    }

    // --- check each node to see if it qualifies as an outlet node
    //     (meaning that degree = 0)
    for ( i = 0; i < Nobjects[NODE]; i++ )
    {
        // --- if node is of type Outfall, check that it has only 1
        //     connecting link (which can either be an outflow or inflow link)
        if ( Node[i].type == OUTFALL )
        {
            if ( Node[i].degree + (int)Node[i].inflow > 1 )
            {
                report_writeErrorMsg(ERR_OUTFALL, Node[i].ID);
            }
            else outletCount++;
        }
    }
    if ( outletCount == 0 ) report_writeErrorMsg(ERR_NO_OUTLETS, "");

    // --- reset node inflows back to zero
    for ( i = 0; i < Nobjects[NODE]; i++ )
    {
        if ( Node[i].inflow == 0.0 ) Node[i].degree = -Node[i].degree;
        Node[i].inflow = 0.0;
    }
}

//=============================================================================

void initNodeDepths(void)
//
//  Input:   none
//  Output:  none
//  Purpose: sets initial depth at nodes for Dynamic Wave flow routing.
//
{
    int   i;                           // link or node index
    int   n;                           // node index
    double y;                          // node water depth (ft)

    // --- use Node[].inflow as a temporary accumulator for depth in
    //     connecting links and Node[].outflow as a temporary counter
    //     for the number of connecting links
    for (i = 0; i < Nobjects[NODE]; i++)
    {
        Node[i].inflow  = 0.0;
        Node[i].outflow = 0.0;
    }

    // --- total up flow depths in all connecting links into nodes
    for (i = 0; i < Nobjects[LINK]; i++)
    {
        if ( Link[i].newDepth > FUDGE ) y = Link[i].newDepth + Link[i].offset1;
        else y = 0.0;
        n = Link[i].node1;
        Node[n].inflow += y;
        Node[n].outflow += 1.0;
        n = Link[i].node2;
        Node[n].inflow += y;
        Node[n].outflow += 1.0;
    }

    // --- if no user-supplied depth then set initial depth at non-storage/
    //     non-outfall nodes to average of depths in connecting links
    for ( i = 0; i < Nobjects[NODE]; i++ )
    {
        if ( Node[i].type == OUTFALL ) continue;
        if ( Node[i].type == STORAGE ) continue;
        if ( Node[i].initDepth > 0.0 ) continue;
        if ( Node[i].outflow > 0.0 )
        {
            Node[i].newDepth = Node[i].inflow / Node[i].outflow;
        }
    }

    // --- compute initial depths at all outfall nodes
    for ( i = 0; i < Nobjects[LINK]; i++ ) link_setOutfallDepth(i);
}

//=============================================================================

void initLinkDepths()
//
//  Input:   none
//  Output:  none
//  Purpose: sets initial flow depths in conduits under Dyn. Wave routing.
//
{
    int    i;                          // link index
    double y, y1, y2;                  // depths (ft)

    // --- examine each link
    for (i = 0; i < Nobjects[LINK]; i++)
    {
        // --- examine each conduit
        if ( Link[i].type == CONDUIT )
        {
            // --- skip conduits with user-assigned initial flows
            //     (their depths have already been set to normal depth)
            if ( Link[i].q0 != 0.0 ) continue;

            // --- set depth to average of depths at end nodes
            y1 = Node[Link[i].node1].newDepth - Link[i].offset1;
            y1 = MAX(y1, 0.0);
            y1 = MIN(y1, Link[i].xsect.yFull);
            y2 = Node[Link[i].node2].newDepth - Link[i].offset2;
            y2 = MAX(y2, 0.0);
            y2 = MIN(y2, Link[i].xsect.yFull);
            y = 0.5 * (y1 + y2);
            y = MAX(y, FUDGE);
            Link[i].newDepth = y;
        }
    }
}

//=============================================================================

void initNodes()
//
//  Input:   none
//  Output:  none
//  Purpose: sets initial inflow/outflow and volume for each node
//
{
    int i;

    for ( i = 0; i < Nobjects[NODE]; i++ )
    {
        // --- set default crown elevations here
        Node[i].crownElev = Node[i].invertElev;

        // --- initialize node inflow and outflow
        Node[i].inflow = Node[i].newLatFlow;
        Node[i].outflow = 0.0;

        // --- initialize node volume
        Node[i].newVolume = 0.0;
        if ( AllowPonding &&
             Node[i].pondedArea > 0.0 &&
             Node[i].newDepth > Node[i].fullDepth )
        {
            Node[i].newVolume = Node[i].fullVolume +
                                (Node[i].newDepth - Node[i].fullDepth) *
                                Node[i].pondedArea;
        }
        else Node[i].newVolume = node_getVolume(i, Node[i].newDepth);
    }

    // --- update nodal inflow/outflow at ends of each link
    //     (needed for Steady Flow & Kin. Wave routing)
    for ( i = 0; i < Nobjects[LINK]; i++ )
    {
        if ( Link[i].newFlow >= 0.0 )
        {
            Node[Link[i].node1].outflow += Link[i].newFlow;
            Node[Link[i].node2].inflow  += Link[i].newFlow;
        }
        else
        {
            Node[Link[i].node1].inflow   -= Link[i].newFlow;
            Node[Link[i].node2].outflow  -= Link[i].newFlow;
        }
    }
}

//=============================================================================

void initLinks()
//
//  Input:   none
//  Output:  none
//  Purpose: sets initial upstream/downstream conditions in links.
//
//  Note: initNodes() must have been called first to properly
//        initialize each node's crown elevation.
//
{
    int    i;                          // link index
    int    j;                          // node index
    int    k;                          // conduit or pump index
    double z;                          // crown elev. (ft)

    // --- examine each link
    for ( i = 0; i < Nobjects[LINK]; i++ )
    {
        // --- examine each conduit
        if ( Link[i].type == CONDUIT )
        {
            // --- assign initial flow to both ends of conduit
            k = Link[i].subIndex;
            Conduit[k].q1 = Link[i].newFlow / Conduit[k].barrels;
            Conduit[k].q2 = Conduit[k].q1;

            Conduit[k].q1Old = Conduit[k].q1;
            Conduit[k].q2Old = Conduit[k].q2;

            // --- find areas based on initial flow depth
            Conduit[k].a1 = xsect_getAofY(&Link[i].xsect, Link[i].newDepth);
            Conduit[k].a2 = Conduit[k].a1;

            // --- compute initial volume from area
            Link[i].newVolume = Conduit[k].a1 * link_getLength(i) *
                                Conduit[k].barrels;
            Link[i].oldVolume = Link[i].newVolume;
        }

        // --- update crown elev. of nodes at either end
        j = Link[i].node1;
        z = Node[j].invertElev + Link[i].offset1 + Link[i].xsect.yFull;
        Node[j].crownElev = MAX(Node[j].crownElev, z);
        j = Link[i].node2;
        z = Node[j].invertElev + Link[i].offset2 + Link[i].xsect.yFull;
        Node[j].crownElev = MAX(Node[j].crownElev, z);
    }
}

//=============================================================================

double getLinkInflow(int j, double dt)
//
//  Input:   j  = link index
//           dt = routing time step (sec)
//  Output:  returns link inflow (cfs)
//  Purpose: finds flow into upstream end of link at current time step under
//           Steady or Kin. Wave routing.
//
{
    int   n1 = Link[j].node1;
    double q;
    if ( Link[j].type == CONDUIT ||
         Link[j].type == PUMP ||
         Node[n1].type == STORAGE ) q = link_getInflow(j);
    else q = 0.0;
    return node_getMaxOutflow(n1, q, dt);
}

//=============================================================================

void updateStorageState(int i, int j, int links[], double dt)
//
//  Input:   i = index of storage node
//           j = current position in links array
//           links = array of topo-sorted link indexes
//           dt = routing time step (sec)
//  Output:  none
//  Purpose: updates depth and volume of a storage node using successive
//           approximation with under-relaxation for Steady or Kin. Wave
//           routing.
//
{
    int    iter;                       // iteration counter
    int    stopped;                    // TRUE when iterations stop
    double vFixed;                     // fixed terms of flow balance eqn.
    double v2;                         // new volume estimate (ft3)
    double d1;                         // initial value of storage depth (ft)
    double d2;                         // updated value of storage depth (ft)

    // --- see if storage node needs updating
    if ( Node[i].type != STORAGE ) return;
    if ( Node[i].updated ) return;

    // --- compute terms of flow balance eqn.
    //       v2 = v1 + (inflow - outflow)*dt
    //     that do not depend on storage depth at end of time step
    vFixed = Node[i].oldVolume +
             0.5 * (Node[i].oldNetInflow + Node[i].inflow -
                    Node[i].outflow) * dt;                                     //(5.1.007)
    d1 = Node[i].newDepth;

    // --- iterate finding outflow (which depends on depth) and subsequent
    //     new volume and depth until negligible depth change occurs
    iter = 1;
    stopped = FALSE;
    while ( iter < MAXITER && !stopped )
    {
        // --- find new volume from flow balance eqn.
        v2 = vFixed - 0.5 * getStorageOutflow(i, j, links, dt) * dt;           //(5.1.007)

        // --- limit volume to full volume if no ponding
        //     and compute overflow rate
        v2 = MAX(0.0, v2);
        Node[i].overflow = 0.0;
        if ( v2 > Node[i].fullVolume )
        {
            Node[i].overflow = (v2 - MAX(Node[i].oldVolume,
                                         Node[i].fullVolume)) / dt;
            if ( !AllowPonding || Node[i].pondedArea == 0.0 )
                v2 = Node[i].fullVolume;
        }

        // --- update node's volume & depth
        Node[i].newVolume = v2;
        d2 = node_getDepth(i, v2);
        Node[i].newDepth = d2;

        // --- use under-relaxation to estimate new depth value
        //     and stop if close enough to previous value
        d2 = (1.0 - OMEGA)*d1 + OMEGA*d2;
        if ( fabs(d2 - d1) <= STOPTOL ) stopped = TRUE;

        // --- update old depth with new value and continue to iterate
        Node[i].newDepth = d2;
        d1 = d2;
        iter++;
    }

    // --- mark node as being updated
    Node[i].updated = TRUE;
}

//=============================================================================

double getStorageOutflow(int i, int j, int links[], double dt)
//
//  Input:   i = index of storage node
//           j = current position in links array
//           links = array of topo-sorted link indexes
//           dt = routing time step (sec)
//  Output:  returns total outflow from storage node (cfs)
//  Purpose: computes total flow released from a storage node.
//
{
    int   k, m;
    double outflow = 0.0;

    for (k = j; k < Nobjects[LINK]; k++)
    {
        m = links[k];
        if ( Link[m].node1 != i ) break;
        outflow += getLinkInflow(m, dt);
    }
    return outflow;
}

//=============================================================================

void setNewNodeState(int j, double dt)
//
//  Input:   j  = node index
//           dt = time step (sec)
//  Output:  none
//  Purpose: updates state of node after current time step
//           for Steady Flow or Kinematic Wave flow routing.
//
{
    int   canPond;                     // TRUE if ponding can occur at node
    double newNetInflow;               // inflow - outflow at node (cfs)

    // --- storage nodes have already been updated
    if ( Node[j].type == STORAGE ) return;

    // --- update stored volume using mid-point integration
    newNetInflow = Node[j].inflow - Node[j].outflow - Node[j].losses;          //(5.1.007)
    Node[j].newVolume = Node[j].oldVolume +
                        0.5 * (Node[j].oldNetInflow + newNetInflow) * dt;
    if ( Node[j].newVolume < FUDGE ) Node[j].newVolume = 0.0;

    // --- determine any overflow lost from system
    Node[j].overflow = 0.0;
    canPond = (AllowPonding && Node[j].pondedArea > 0.0);
    if ( Node[j].newVolume > Node[j].fullVolume )
    {
        Node[j].overflow = (Node[j].newVolume - MAX(Node[j].oldVolume,
                            Node[j].fullVolume)) / dt;
        if ( Node[j].overflow < FUDGE ) Node[j].overflow = 0.0;
        if ( !canPond ) Node[j].newVolume = Node[j].fullVolume;
    }

    // --- compute a depth from volume
    //     (depths at upstream nodes are subsequently adjusted in
    //     setNewLinkState to reflect depths in connected conduit)
    Node[j].newDepth = node_getDepth(j, Node[j].newVolume);
}

//=============================================================================

void setNewLinkState(int j)
//
//  Input:   j = link index
//  Output:  none
//  Purpose: updates state of link after current time step under
//           Steady Flow or Kinematic Wave flow routing
//
{
    int   k;
    double a, y1, y2;

    Link[j].newDepth = 0.0;
    Link[j].newVolume = 0.0;

    if ( Link[j].type == CONDUIT )
    {
        // --- find avg. depth from entry/exit conditions
        k = Link[j].subIndex;
        a = 0.5 * (Conduit[k].a1 + Conduit[k].a2);
        Link[j].newVolume = a * link_getLength(j) * Conduit[k].barrels;
        y1 = xsect_getYofA(&Link[j].xsect, Conduit[k].a1);
        y2 = xsect_getYofA(&Link[j].xsect, Conduit[k].a2);
        Link[j].newDepth = 0.5 * (y1 + y2);

        // --- update depths at end nodes
        updateNodeDepth(Link[j].node1, y1 + Link[j].offset1);
        updateNodeDepth(Link[j].node2, y2 + Link[j].offset2);

        // --- check if capacity limited
        if ( Conduit[k].a1 >= Link[j].xsect.aFull )
             Conduit[k].capacityLimited = TRUE;
        else Conduit[k].capacityLimited = FALSE;
    }
}

//=============================================================================

void updateNodeDepth(int i, double y)
//
//  Input:   i = node index
//           y = flow depth (ft)
//  Output:  none
//  Purpose: updates water depth at a node with a possibly higher value.
//
{
    // --- storage nodes were updated elsewhere
    if ( Node[i].type == STORAGE ) return;

    // --- if non-outfall node is flooded, then use full depth
    if ( Node[i].type != OUTFALL &&
         Node[i].overflow > 0.0 ) y = Node[i].fullDepth;

    // --- if current new depth below y
    if ( Node[i].newDepth < y )
    {
        // --- update new depth
        Node[i].newDepth = y;

        // --- depth cannot exceed full depth (if value exists)
        if ( Node[i].fullDepth > 0.0 && y > Node[i].fullDepth )
        {
            Node[i].newDepth = Node[i].fullDepth;
        }
    }
}

//=============================================================================

int steadyflow_execute(int j, double* qin, double* qout, double tStep)
//
//  Input:   j = link index
//           qin = inflow to link (cfs)
//           tStep = time step (sec)
//  Output:  qin = adjusted inflow to link (limited by flow capacity) (cfs)
//           qout = link's outflow (cfs)
//           returns 1 if successful
//  Purpose: performs steady flow routing through a single link.
//
{
    int   k;
    double s;
    double q;

    // --- use Manning eqn. to compute flow area for conduits
    if ( Link[j].type == CONDUIT )
    {
        k = Link[j].subIndex;
        q = (*qin) / Conduit[k].barrels;
        if ( Link[j].xsect.type == DUMMY ) Conduit[k].a1 = 0.0;
        else
        {
            // --- subtract evap and infil losses from inflow
            q -= link_getLossRate(j, tStep);
            if ( q < 0.0 ) q = 0.0;

            // --- flow can't exceed full flow
            if ( q > Link[j].qFull )
            {
                q = Link[j].qFull;
                Conduit[k].a1 = Link[j].xsect.aFull;
                (*qin) = q * Conduit[k].barrels;
            }

            // --- infer flow area from flow rate
            else
            {
                s = q / Conduit[k].beta;
                Conduit[k].a1 = xsect_getAofS(&Link[j].xsect, s);
            }
        }
        Conduit[k].a2 = Conduit[k].a1;
        Conduit[k].q1 = q;
        Conduit[k].q2 = q;
        (*qout) = q * Conduit[k].barrels;
    }
    else (*qout) = (*qin);
    return 1;
}

//=============================================================================


text:
require 'spec_helper'

describe BillingPeriod do
  it "validates uniqueness of begin date" do
    billing_period = create :billing_period

    invalid_period = build :billing_period,
                           user: billing_period.user,
                           begin_date: billing_period.begin_date

    expect(invalid_period).to_not be_valid
  end

  it "validates uniqueness of end date" do
    billing_period = create :billing_period

    invalid_period = build :billing_period,
                           user: billing_period.user,
                           end_date: billing_period.end_date

    expect(invalid_period).to_not be_valid
  end

  it "validates uniqueness of begin and end dates within scope of user" do
    user_1 = create :user
    user_2 = create :user

    user_1_billing_period = create :billing_period, user: user_1
    user_2_billing_period = build :billing_period,
                                   user: user_2,
                                   begin_date: user_1_billing_period.begin_date,
                                   end_date: user_1_billing_period.end_date

    expect(user_2_billing_period).to be_valid
  end
end


text:
package org.kaazing.gateway.transport.http;

import org.apache.mina.core.filterchain.IoFilterChain;
import org.apache.mina.core.future.CloseFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.kaazing.gateway.resource.address.http.HttpResourceAddress;
import org.kaazing.gateway.transport.TypedAttributeKey;
import org.kaazing.gateway.transport.http.bridge.filter.HttpFilterAdapter;
import org.kaazing.mina.core.session.IoSessionEx;
import org.kaazing.mina.netty.util.threadlocal.VicariousThreadLocal;
import org.slf4j.Logger;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/*
 * A pool for reusable persistent transport connections. HttpConnector
 * may pick one of the transport connections instead of creating a new
 * one while connecting to the origin server.
 */
class PersistentConnectionPool {

    private static final String IDLE_FILTER = HttpProtocol.NAME + "#idle";
    private static final TypedAttributeKey<HttpResourceAddress> SERVER_ADDRESS =
            new TypedAttributeKey<>(PersistentConnectionPool.class, "address");

    // server address -> set of persistent connections (per thread).
    // Using ThreadLocal for the following reasons:
    // - we need to return thread-aligned IoSession
    // - it reduces contention compared to synchronized ServerConnections
    private final ThreadLocal<ServerConnections> connections;

    private final Logger logger;
    private final HttpConnectIdleFilter idleFilter;
    private final CloseListener closeListener;

    PersistentConnectionPool(Logger logger) {
        this.connections = new VicariousThreadLocal<ServerConnections>() {
            @Override
            protected  ServerConnections initialValue() {
                return new ServerConnections();
            }
        };
        this.logger = logger;
        this.idleFilter = new HttpConnectIdleFilter(logger);
        this.closeListener = new CloseListener(this);
    }

    /*
     * Cache existing transport session so that it can be used for future
     * connect requests to server
     *
     * @return true if the idle connection is cached for reuse
     *         false otherwise
     */
    boolean recycle(DefaultHttpSession httpSession) {
        if (!add(httpSession)) {
            return false;
        }

        HttpResourceAddress serverAddress = (HttpResourceAddress)httpSession.getRemoteAddress();
        IoSession transportSession = httpSession.getParent();

        SERVER_ADDRESS.set(transportSession, serverAddress);

        // Connection needs to be removed from pool upon session's close. Adding
        // a close future listener for that
        CloseFuture closeFuture = transportSession.getCloseFuture();
        closeFuture.addListener(closeListener);

        // Track transport session idle so that we don't waste resources.
        // Upstream server can take new fresh connections if gateway closes idle connections
        transportSession.getFilterChain().addLast(IDLE_FILTER, idleFilter);
        int keepAliveTimeout = serverAddress.getOption(HttpResourceAddress.KEEP_ALIVE_TIMEOUT);
        transportSession.getConfig().setBothIdleTime(keepAliveTimeout);

        return true;
    }

    /*
     * Returns an existing transport session for the resource address that can be reused
     *
     * @return a reusable IoSession for the address
     *         otherwise null
     */
    IoSession take(HttpResourceAddress serverAddress) {
        IoSession transportSession = removeThreadAligned(serverAddress);
        if (transportSession != null) {
            // Got a cached persistent connection

            // Remove session idle tracking for this session
            transportSession.getConfig().setBothIdleTime(0);
            IoFilterChain filterChain = transportSession.getFilterChain();
            if (filterChain.contains(IDLE_FILTER)) {
                filterChain.remove(IDLE_FILTER);
            }

            // Remove our CloseFuture listener as it is out of pool
            CloseFuture closeFuture = transportSession.getCloseFuture();
            closeFuture.removeListener(closeListener);

            SERVER_ADDRESS.remove(transportSession);
        }

        return transportSession;
    }

    private boolean add(DefaultHttpSession httpSession) {
        HttpResourceAddress serverAddress = (HttpResourceAddress)httpSession.getRemoteAddress();
        IoSession transportSession = httpSession.getParent();

        ServerConnections serverConnections = connections.get();
        boolean cached = serverConnections.add(serverAddress, transportSession);
        if (cached) {
            if (logger.isDebugEnabled()) {
                int cachedConnections = serverConnections.cachedConnections(serverAddress);
                logger.debug(String.format("Caching persistent connection: server = %s session = %s pool = %d",
                        serverAddress.getResource(), transportSession, cachedConnections));
            }
            return true;
        } else {
            if (logger.isDebugEnabled()) {
                int cachedConnections = serverConnections.cachedConnections(serverAddress);
                logger.debug(String.format("NOT caching persistent connection: server = %s session = %s pool = %d",
                        serverAddress.getResource(), transportSession, cachedConnections));
            }
        }
        return false;
    }

    private void remove(HttpResourceAddress serverAddress, IoSession session) {
        ServerConnections serverConnections = connections.get();
        boolean removed = serverConnections.remove(serverAddress, session);
        if (removed) {
            if (logger.isDebugEnabled()) {
                int cachedConnections = serverConnections.cachedConnections(serverAddress);
                logger.debug(String.format("Removing cached persistent connection: server = %s session = %s pool = %d",
                        serverAddress.getResource(), session, cachedConnections));
            }
        }
    }

    private IoSession removeThreadAligned(HttpResourceAddress serverAddress) {
        ServerConnections serverConnections = connections.get();
        IoSession session = serverConnections.removeAny(serverAddress);
        if (session != null) {
            // Connection was in the pool
            if (logger.isDebugEnabled()) {
                int count = serverConnections.cachedConnections(serverAddress);
                logger.debug(String.format("Reusing cached persistent connection: server = %s  session = %s pool = %d",
                        serverAddress.getResource(), session, count));
            }
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug(String.format("Cache miss - NO cached persistent connection: server = %s",
                        serverAddress.getResource()));
            }
        }
        return session;
    }

    /*
     * If a session is closed, it will be removed from this pool using this
     * CloseFuture listener
     */
    private static class CloseListener implements IoFutureListener<CloseFuture> {

        private final PersistentConnectionPool store;

        CloseListener(PersistentConnectionPool store) {
            this.store = store;
        }

        @Override
        public void operationComplete(CloseFuture future) {
            IoSessionEx session = (IoSessionEx) future.getSession();
            HttpResourceAddress serverAddress = SERVER_ADDRESS.get(session);
            store.remove(serverAddress, session);
        }
    }

    /*
     * Filter to detect if a persistent connection is idle
     */
    private static class HttpConnectIdleFilter extends HttpFilterAdapter<IoSessionEx> {
        private final Logger logger;

        HttpConnectIdleFilter(Logger logger) {
            this.logger = logger;
        }

        @Override
        public void sessionIdle(NextFilter nextFilter, IoSession session, IdleStatus status) throws Exception {
            if (logger.isDebugEnabled()) {
                logger.debug(String.format("Idle cached persistent connection: session=%s", session));
            }

            // Transport connection will be removed from pool in an listener of CloseFuture
            session.close(false);
        }
    }

    /**
     * Keeps track of presistent connections to a server. Implemenation is not thread-safe
     * and the caller will take care of thread safety.
     */
    private static class ServerConnections {
        // IoSession[] limits the number of connections as per config
        // null means empty spot, non null means already cached connection
        private final Map<HttpResourceAddress, IoSession[]> addressToConnections;

        private ServerConnections() {
            this.addressToConnections = new HashMap<>();
        }

        /*
         * Caches the given persistent connection for the given server
         * @return true if it is cached
         *         false otherwise
         */
        private boolean add(HttpResourceAddress serverAddress, IoSession session) {
            int maxConnections = serverAddress.getOption(HttpResourceAddress.KEEP_ALIVE_MAX_CONNECTIONS);
            IoSession[] connections = addressToConnections.get(serverAddress);
            if (connections == null) {
                connections = new IoSession[maxConnections];
                addressToConnections.put(serverAddress, connections);
            }

            assert maxConnections == connections.length;
            for(int i=0; i < connections.length; i++) {
                if (connections[i] == null) {
                    connections[i] = session;
                    return true;
                }
            }
            return false;
        }

        /*
         * Removes given persistent connection for the given server
         * @return true if the session is removed from the pool
         *         false otherwise
         */
        private boolean remove(HttpResourceAddress serverAddress, IoSession session) {
            IoSession[] connections = addressToConnections.get(serverAddress);
            if (connections != null) {
                for(int i=0; i < connections.length; i++) {
                    if (connections[i] == session) {
                        connections[i] = null;
                        return true;
                    }
                }
            }
            return false;
        }

        /*
         * Returns a cached persistent connection for the server
         *
         * @return any IoSession for the server if available
         *         null otherwise
         */
        private IoSession removeAny(HttpResourceAddress serverAddress) {
            IoSession[] connections = addressToConnections.get(serverAddress);
            if (connections != null) {
                for(int i=0; i < connections.length; i++) {
                    if (connections[i] != null) {
                        IoSession session = connections[i];
                        connections[i] = null;
                        return session;
                    }
                }
            }
            return null;
        }

        /*
         * Returns the current number of cached persistent connection for the server
         *
         * @return the current number of connections for the server
         *         0 if there no caching for the server
         */
        private int cachedConnections(HttpResourceAddress serverAddress) {
            IoSession[] connections = addressToConnections.get(serverAddress);
            if (connections != null) {
                return (int) Arrays.stream(connections).filter(Objects::nonNull).count();
            }

            return 0;
        }
    }

}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/search_phone"
        android:title="Search Phone"/>

		<item
				android:id="@+id/home"
				android:title="Home"/>

    <item
				android:id="@+id/profile"
				android:title="my_profile"/>
		<item
				android:id="@+id/social"
				android:title="social"
				/>

</menu>