idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
17,500 | public static void figureOutConnect ( PrintStream w , Object ... comps ) { // add all the components via Proxy. List < ComponentAccess > l = new ArrayList < ComponentAccess > ( ) ; for ( Object c : comps ) { l . add ( new ComponentAccess ( c ) ) ; } // find all out slots for ( ComponentAccess cp_out : l ) { w . println ( "// connect " + objName ( cp_out ) ) ; // over all input slots. for ( Access fout : cp_out . outputs ( ) ) { String s = " out2in(" + objName ( cp_out ) + ", \"" + fout . getField ( ) . getName ( ) + "\"" ; for ( ComponentAccess cp_in : l ) { // skip if it is the same component. if ( cp_in == cp_out ) { continue ; } // out points to in for ( Access fin : cp_in . inputs ( ) ) { // name equivalence enought for now. if ( fout . getField ( ) . getName ( ) . equals ( fin . getField ( ) . getName ( ) ) ) { s = s + ", " + objName ( cp_in ) ; } } } w . println ( s + ");" ) ; } w . println ( ) ; } } | Figure out connectivity and generate Java statements . | 288 | 8 |
17,501 | public static List < Class < ? > > getComponentClasses ( URL jar ) throws IOException { JarInputStream jarFile = new JarInputStream ( jar . openStream ( ) ) ; URLClassLoader cl = new URLClassLoader ( new URL [ ] { jar } , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; List < Class < ? > > idx = new ArrayList < Class < ? > > ( ) ; JarEntry jarEntry = jarFile . getNextJarEntry ( ) ; while ( jarEntry != null ) { String classname = jarEntry . getName ( ) ; // System.out.println(classname); if ( classname . endsWith ( ".class" ) ) { classname = classname . substring ( 0 , classname . indexOf ( ".class" ) ) . replace ( ' ' , ' ' ) ; try { Class < ? > c = Class . forName ( classname , false , cl ) ; for ( Method method : c . getMethods ( ) ) { if ( ( method . getAnnotation ( Execute . class ) ) != null ) { idx . add ( c ) ; break ; } } } catch ( ClassNotFoundException ex ) { ex . printStackTrace ( ) ; } } jarEntry = jarFile . getNextJarEntry ( ) ; } jarFile . close ( ) ; return idx ; } | Get all components from a jar file | 298 | 7 |
17,502 | public static URL getDocumentation ( Class < ? > comp , Locale loc ) { Documentation doc = ( Documentation ) comp . getAnnotation ( Documentation . class ) ; if ( doc != null ) { String v = doc . value ( ) ; try { // try full URL first (external reference) URL url = new URL ( v ) ; return url ; } catch ( MalformedURLException E ) { // local resource bundled with the class String name = v . substring ( 0 , v . lastIndexOf ( ' ' ) ) ; String ext = v . substring ( v . lastIndexOf ( ' ' ) ) ; String lang = loc . getLanguage ( ) ; URL f = comp . getResource ( name + "_" + lang + ext ) ; if ( f != null ) { return f ; } f = comp . getResource ( v ) ; if ( f != null ) { return f ; } } } return null ; } | Get the documentation as URL reference ; | 199 | 7 |
17,503 | public static String getDescription ( Class < ? > comp , Locale loc ) { Description descr = ( Description ) comp . getAnnotation ( Description . class ) ; if ( descr != null ) { String lang = loc . getLanguage ( ) ; Method [ ] m = descr . getClass ( ) . getMethods ( ) ; for ( Method method : m ) { // System.out.println(method); if ( method . getName ( ) . equals ( lang ) ) { try { String d = ( String ) method . invoke ( descr , ( Object [ ] ) null ) ; if ( d != null && ! d . isEmpty ( ) ) { return d ; } } catch ( Exception ex ) { ex . printStackTrace ( ) ; } } } return descr . value ( ) ; } return null ; } | Get the Component Description | 177 | 4 |
17,504 | public static Object [ ] stringListToArray ( List < String > list ) { Object [ ] params = null ; if ( list != null ) { params = list . toArray ( new String [ list . size ( ) ] ) ; } return params ; } | Converts list of strings to an array . | 54 | 9 |
17,505 | public static boolean notMatches ( String value , String prefix , String middle , String postfix ) { return ! matches ( value , prefix , middle , postfix ) ; } | Check whether value NOT matches the pattern build with prefix middle part and post - fixer . | 36 | 18 |
17,506 | public static boolean matches ( String value , String prefix , String middle , String postfix ) { String pattern = prefix + middle + postfix ; boolean result = value . matches ( pattern ) ; return result ; } | Check whether value matches the pattern build with prefix middle part and post - fixer . | 43 | 17 |
17,507 | public static boolean matchesWithoutPrefixes ( String value1 , String prefix1 , String value2 , String prefix2 ) { if ( ! value1 . startsWith ( prefix1 ) ) { return false ; } value1 = value1 . substring ( prefix1 . length ( ) ) ; if ( ! value2 . startsWith ( prefix2 ) ) { return false ; } value2 = value2 . substring ( prefix2 . length ( ) ) ; return value1 . equals ( value2 ) ; } | It removes prefixes from values and compare remaining parts . | 107 | 11 |
17,508 | public static ValidationMessage shiftReferenceLocation ( Entry entry , long newSequenceLength ) { Collection < Reference > references = entry . getReferences ( ) ; for ( Reference reference : references ) { for ( Location rlocation : reference . getLocations ( ) . getLocations ( ) ) { { rlocation . setEndPosition ( newSequenceLength ) ; if ( rlocation . getBeginPosition ( ) . equals ( rlocation . getEndPosition ( ) ) ) { return ValidationMessage . message ( Severity . WARNING , UTILS_6 , rlocation . getBeginPosition ( ) , rlocation . getEndPosition ( ) ) ; } } } } return null ; } | Reference Location shifting | 143 | 3 |
17,509 | @ SuppressWarnings ( "nls" ) public void dumpChart ( File chartFile , boolean autoRange , boolean withLegend , int imageWidth , int imageHeight ) throws IOException { JFreeChart chart = ChartFactory . createXYLineChart ( title , xLabel , yLabel , collection , PlotOrientation . VERTICAL , withLegend , false , false ) ; XYPlot plot = ( XYPlot ) chart . getPlot ( ) ; // plot.setDomainPannable(true); // plot.setRangePannable(true); // plot.setForegroundAlpha(0.85f); NumberAxis yAxis = ( NumberAxis ) plot . getRangeAxis ( ) ; yAxis . setStandardTickUnits ( NumberAxis . createStandardTickUnits ( ) ) ; if ( autoRange ) { double delta = ( max - min ) * 0.1 ; yAxis . setRange ( min - delta , max + delta ) ; // TODO reactivate if newer jfree is used // yAxis.setMinorTickCount(4); // yAxis.setMinorTickMarksVisible(true); } // ValueAxis xAxis = plot.getDomainAxis(); // xAxis.setStandardTickUnits(NumberAxis.createStandardTickUnits(Locale.US)); // XYItemRenderer renderer = plot.getRenderer(); // renderer.setDrawBarOutline(false); // // flat bars look best... // renderer.setBarPainter(new StandardXYBarPainter()); // renderer.setShadowVisible(false); if ( ! chartFile . getName ( ) . endsWith ( ".png" ) ) { chartFile = FileUtilities . substituteExtention ( chartFile , "png" ) ; } if ( imageWidth == - 1 ) { imageWidth = IMAGEWIDTH ; } if ( imageHeight == - 1 ) { imageHeight = IMAGEHEIGHT ; } BufferedImage bufferedImage = chart . createBufferedImage ( imageWidth , imageHeight ) ; ImageIO . write ( bufferedImage , "png" , chartFile ) ; } | Creates the chart image and dumps it to file . | 475 | 11 |
17,510 | public RuleWrapper getFirstRule ( ) { if ( featureTypeStylesWrapperList . size ( ) > 0 ) { FeatureTypeStyleWrapper featureTypeStyleWrapper = featureTypeStylesWrapperList . get ( 0 ) ; List < RuleWrapper > rulesWrapperList = featureTypeStyleWrapper . getRulesWrapperList ( ) ; if ( rulesWrapperList . size ( ) > 0 ) { RuleWrapper ruleWrapper = rulesWrapperList . get ( 0 ) ; return ruleWrapper ; } } return null ; } | Facility to get the first rule if available . | 118 | 10 |
17,511 | public boolean isSimpleType ( ) { if ( // fieldType . equals ( Double . class . getCanonicalName ( ) ) || // fieldType . equals ( Float . class . getCanonicalName ( ) ) || // fieldType . equals ( Integer . class . getCanonicalName ( ) ) || // fieldType . equals ( double . class . getCanonicalName ( ) ) || // fieldType . equals ( float . class . getCanonicalName ( ) ) || // fieldType . equals ( int . class . getCanonicalName ( ) ) || // fieldType . equals ( Boolean . class . getCanonicalName ( ) ) || // fieldType . equals ( boolean . class . getCanonicalName ( ) ) || // fieldType . equals ( String . class . getCanonicalName ( ) ) // ) { return true ; } return false ; } | Checks if this field is a simple type . | 191 | 10 |
17,512 | private Long [ ] checkLocation ( Location location ) { Long [ ] positions = new Long [ 2 ] ; if ( location . isComplement ( ) ) { positions [ 0 ] = location . getEndPosition ( ) ; positions [ 1 ] = location . getBeginPosition ( ) ; } else { positions [ 0 ] = location . getBeginPosition ( ) ; positions [ 1 ] = location . getEndPosition ( ) ; } return positions ; } | Checks and swaps positions if in wrong order . | 93 | 10 |
17,513 | @ Deprecated @ Override public String getSequence ( Long beginPosition , Long endPosition ) { if ( beginPosition == null || endPosition == null || ( beginPosition > endPosition ) || beginPosition < 1 || endPosition > getLength ( ) ) { return null ; } int length = ( int ) ( endPosition . longValue ( ) - beginPosition . longValue ( ) ) + 1 ; int offset = beginPosition . intValue ( ) - 1 ; String subSequence = null ; try { subSequence = ByteBufferUtils . string ( getSequenceBuffer ( ) , offset , length ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return subSequence ; } return subSequence ; /*// note begin:1 end:4 has length 4 byte[] subsequence = new byte[length]; synchronized (sequence) { sequence.position(offset); sequence.get(subsequence, 0, length); } String string = new String(subsequence); return string;*/ } | Overridden so we can create appropriate sized buffer before making string . | 216 | 13 |
17,514 | String convertCase ( String str ) { if ( str == null ) { return null ; } return sensitive ? str : str . toLowerCase ( ) ; } | Converts the case of the input String to a standard format . Subsequent operations can then use standard String methods . | 33 | 23 |
17,515 | private void set ( Matrix m ) { this . nRows = 1 ; this . nCols = m . nCols ; this . values = m . values ; } | Set this row vector from a matrix . Only the first row is used . | 37 | 15 |
17,516 | public RowVector getRow ( int r ) throws MatrixException { if ( ( r < 0 ) || ( r >= nRows ) ) { throw new MatrixException ( MatrixException . INVALID_INDEX ) ; } RowVector rv = new RowVector ( nCols ) ; for ( int c = 0 ; c < nCols ; ++ c ) { rv . values [ 0 ] [ c ] = this . values [ r ] [ c ] ; } return rv ; } | Get a row of this matrix . | 105 | 7 |
17,517 | public ColumnVector getColumn ( int c ) throws MatrixException { if ( ( c < 0 ) || ( c >= nCols ) ) { throw new MatrixException ( MatrixException . INVALID_INDEX ) ; } ColumnVector cv = new ColumnVector ( nRows ) ; for ( int r = 0 ; r < nRows ; ++ r ) { cv . values [ r ] [ 0 ] = this . values [ r ] [ c ] ; } return cv ; } | Get a column of this matrix . | 105 | 7 |
17,518 | protected void set ( double values [ ] [ ] ) { this . nRows = values . length ; this . nCols = values [ 0 ] . length ; this . values = values ; for ( int r = 1 ; r < nRows ; ++ r ) { nCols = Math . min ( nCols , values [ r ] . length ) ; } } | Set this matrix from a 2 - d array of values . If the rows do not have the same length then the matrix column count is the length of the shortest row . | 80 | 34 |
17,519 | public void setRow ( RowVector rv , int r ) throws MatrixException { if ( ( r < 0 ) || ( r >= nRows ) ) { throw new MatrixException ( MatrixException . INVALID_INDEX ) ; } if ( nCols != rv . nCols ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } for ( int c = 0 ; c < nCols ; ++ c ) { this . values [ r ] [ c ] = rv . values [ 0 ] [ c ] ; } } | Set a row of this matrix from a row vector . | 124 | 11 |
17,520 | public void setColumn ( ColumnVector cv , int c ) throws MatrixException { if ( ( c < 0 ) || ( c >= nCols ) ) { throw new MatrixException ( MatrixException . INVALID_INDEX ) ; } if ( nRows != cv . nRows ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } for ( int r = 0 ; r < nRows ; ++ r ) { this . values [ r ] [ c ] = cv . values [ r ] [ 0 ] ; } } | Set a column of this matrix from a column vector . | 124 | 11 |
17,521 | public Matrix transpose ( ) { double tv [ ] [ ] = new double [ nCols ] [ nRows ] ; // transposed values // Set the values of the transpose. for ( int r = 0 ; r < nRows ; ++ r ) { for ( int c = 0 ; c < nCols ; ++ c ) { tv [ c ] [ r ] = values [ r ] [ c ] ; } } return new Matrix ( tv ) ; } | Return the transpose of this matrix . | 100 | 8 |
17,522 | public Matrix add ( Matrix m ) throws MatrixException { // Validate m's size. if ( ( nRows != m . nRows ) && ( nCols != m . nCols ) ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } double sv [ ] [ ] = new double [ nRows ] [ nCols ] ; // sum values // Compute values of the sum. for ( int r = 0 ; r < nRows ; ++ r ) { for ( int c = 0 ; c < nCols ; ++ c ) { sv [ r ] [ c ] = values [ r ] [ c ] + m . values [ r ] [ c ] ; } } return new Matrix ( sv ) ; } | Add another matrix to this matrix . | 165 | 7 |
17,523 | public Matrix subtract ( Matrix m ) throws MatrixException { // Validate m's size. if ( ( nRows != m . nRows ) && ( nCols != m . nCols ) ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } double dv [ ] [ ] = new double [ nRows ] [ nCols ] ; // difference values // Compute values of the difference. for ( int r = 0 ; r < nRows ; ++ r ) { for ( int c = 0 ; c < nCols ; ++ c ) { dv [ r ] [ c ] = values [ r ] [ c ] - m . values [ r ] [ c ] ; } } return new Matrix ( dv ) ; } | Subtract another matrix from this matrix . | 168 | 9 |
17,524 | public Matrix multiply ( double k ) { double pv [ ] [ ] = new double [ nRows ] [ nCols ] ; // product values // Compute values of the product. for ( int r = 0 ; r < nRows ; ++ r ) { for ( int c = 0 ; c < nCols ; ++ c ) { pv [ r ] [ c ] = k * values [ r ] [ c ] ; } } return new Matrix ( pv ) ; } | Multiply this matrix by a constant . | 104 | 9 |
17,525 | public Matrix multiply ( Matrix m ) throws MatrixException { // Validate m's dimensions. if ( nCols != m . nRows ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } double pv [ ] [ ] = new double [ nRows ] [ m . nCols ] ; // product values // Compute values of the product. for ( int r = 0 ; r < nRows ; ++ r ) { for ( int c = 0 ; c < m . nCols ; ++ c ) { double dot = 0 ; for ( int k = 0 ; k < nCols ; ++ k ) { dot += values [ r ] [ k ] * m . values [ k ] [ c ] ; } pv [ r ] [ c ] = dot ; } } return new Matrix ( pv ) ; } | Multiply this matrix by another matrix . | 185 | 9 |
17,526 | public static void printInfo ( String filePath ) throws Exception { LasInfo lasInfo = new LasInfo ( ) ; lasInfo . inLas = filePath ; lasInfo . process ( ) ; } | Utility method to run info . | 41 | 7 |
17,527 | private double internalPipeVerify ( int k , double [ ] cDelays , double [ ] [ ] net , double [ ] [ ] timeDischarge , double [ ] [ ] timeFillDegree , int tp ) { int num ; double localdelay , olddelay , qMax , B , known , theta , u ; double [ ] [ ] qPartial ; qPartial = new double [ timeDischarge . length ] [ timeDischarge [ 0 ] . length ] ; calculateDelays ( k , cDelays , net ) ; // First attempt local delay [min] localdelay = 1 ; double accuracy = networkPipes [ 0 ] . getAccuracy ( ) ; int jMax = networkPipes [ 0 ] . getjMax ( ) ; double minG = networkPipes [ 0 ] . getMinG ( ) ; double maxtheta = networkPipes [ 0 ] . getMaxTheta ( ) ; double tolerance = networkPipes [ 0 ] . getTolerance ( ) ; int count = 0 ; do { olddelay = localdelay ; qMax = 0 ; // Updates delays for ( int i = 0 ; i < net . length ; i ++ ) { net [ i ] [ 2 ] += localdelay ; } ; for ( int j = 0 ; j < net . length ; ++ j ) { num = ( int ) net [ j ] [ 0 ] ; getHydrograph ( num , qPartial , olddelay , net [ j ] [ 2 ] , tp ) ; } getHydrograph ( k , qPartial , olddelay , 0 , tp ) ; qMax = ModelsEngine . sumDoublematrixColumns ( k , qPartial , timeDischarge , 0 , qPartial [ 0 ] . length - 1 , pm ) ; if ( qMax <= 1 ) qMax = 1 ; // Resets delays for ( int i = 0 ; i < net . length ; i ++ ) { net [ i ] [ 2 ] -= localdelay ; } calculateFillDegree ( k , timeDischarge , timeFillDegree ) ; B = qMax / ( CUBICMETER2LITER * networkPipes [ k ] . getKs ( ) * sqrt ( networkPipes [ k ] . verifyPipeSlope / METER2CM ) ) ; known = ( B * TWO_THIRTEENOVERTHREE ) / pow ( networkPipes [ k ] . diameterToVerify / METER2CM , EIGHTOVERTHREE ) ; theta = Utility . thisBisection ( maxtheta , known , TWOOVERTHREE , minG , accuracy , jMax , pm , strBuilder ) ; // Average velocity in pipe [ m / s ] u = qMax * 80 / ( pow ( networkPipes [ k ] . diameterToVerify , 2 ) * ( theta - sin ( theta ) ) ) ; localdelay = networkPipes [ k ] . getLenght ( ) / ( celerityfactor1 * u * MINUTE2SEC ) ; count ++ ; // verify if it's an infiniteloop. if ( count > MAX_NUMBER_ITERATION ) { infiniteLoop = true ; throw new ArithmeticException ( ) ; } } while ( abs ( localdelay - olddelay ) / olddelay >= tolerance ) ; cDelays [ k ] = localdelay ; return qMax ; } | verify of the no - head pipes . | 748 | 9 |
17,528 | private void calculateDelays ( int k , double [ ] cDelays , double [ ] [ ] net ) { double t ; int ind , r = 1 ; for ( int j = 0 ; j < net . length ; ++ j ) { t = 0 ; r = 1 ; ind = ( int ) net [ j ] [ 0 ] ; /* * Area k is not included in delays */ while ( networkPipes [ ind ] . getIndexPipeWhereDrain ( ) != k ) { ind = networkPipes [ ind ] . getIndexPipeWhereDrain ( ) ; t += cDelays [ ind ] ; r ++ ; } if ( r > networkPipes . length ) { pm . errorMessage ( msg . message ( "trentoP.error.incorrectmatrix" ) ) ; throw new ArithmeticException ( msg . message ( "trentoP.error.incorrectmatrix" ) ) ; } net [ j ] [ 2 ] = t ; } } | Calcola il ritardo della tubazione k . | 211 | 14 |
17,529 | private double getHydrograph ( int k , double [ ] [ ] Qpartial , double localdelay , double delay , int tp ) { double Qmax = 0 ; double tmin = rainData [ 0 ] [ 0 ] ; /* [min] */ int j = 0 ; double t = tmin ; double Q ; double rain ; int maxRain = 0 ; if ( tMax == tpMaxCalibration ) { maxRain = rainData . length ; } else { maxRain = tp / dt ; } double tMaxApproximate = ModelsEngine . approximate2Multiple ( tMax , dt ) ; for ( t = tmin , j = 0 ; t <= tMaxApproximate ; t += dt , ++ j ) { Q = 0 ; for ( int i = 0 ; i <= maxRain - 1 ; ++ i ) { // [ l / s ] rain = rainData [ i ] [ 1 ] * networkPipes [ k ] . getDrainArea ( ) * networkPipes [ k ] . getRunoffCoefficient ( ) * HAOVERH_TO_METEROVERS ; if ( t <= i * dt ) { Q += 0 ; } else if ( t <= ( i + 1 ) * dt ) { Q += rain * pFunction ( k , t - i * dt , localdelay , delay ) ; } else { Q += rain * ( pFunction ( k , t - i * dt , localdelay , delay ) - pFunction ( k , t - ( i + 1 ) * dt , localdelay , delay ) ) ; } } Qpartial [ j ] [ k ] = Q ; if ( Q >= Qmax ) { Qmax = Q ; } } return Qmax ; } | Restituisce l idrogramma . | 382 | 9 |
17,530 | @ Override public void geoSewer ( ) throws Exception { if ( ! foundMaxrainTime ) { evaluateDischarge ( lastTimeDischarge , lastTimeFillDegree , tpMaxCalibration ) ; } else { /* * start to evaluate the discharge from 15 minutes,evaluate the nearsted value to 15 minutes. */ int minTime = ( int ) ModelsEngine . approximate2Multiple ( INITIAL_TIME , dt ) ; double qMax = 0 ; for ( int i = minTime ; i < tpMaxCalibration ; i = i + dt ) { tpMax = i ; double [ ] [ ] timeDischarge = createMatrix ( ) ; double [ ] [ ] timeFillDegree = createMatrix ( ) ; double q = evaluateDischarge ( timeDischarge , timeFillDegree , i ) ; if ( q > qMax ) { qMax = q ; lastTimeDischarge = timeDischarge ; lastTimeFillDegree = timeFillDegree ; } else if ( q < qMax ) { break ; } if ( isFill ) { break ; } } } getNetData ( ) ; } | Estimate the discharge for each time and for each pipes . | 248 | 12 |
17,531 | private double scanNetwork ( int k , int l , double [ ] one , double [ ] [ ] net ) { int ind ; /* * t Ritardo accumulato dall'onda prima di raggiungere il tratto si sta * dimensionando. */ double t ; /* * Distanza percorsa dall'acqua dall'area dove e' caduta per raggiungere * l'ingresso del tratto che si sta dimensionando. */ double length ; /* * Superfice del sottobacino con chiusura nel tratto che si sta * analizzando. */ double totalarea = 0 ; int r = 0 ; int i = 0 ; /* * In one gli stati sono in ordine di magmitude crescente. Per ogni * stato di magnitude inferiore a quella del tratto l che si sta * progettando. */ for ( int j = 0 ; j < k ; j ++ ) { /* La portata e valutata all'uscita di ciascun tratto */ t = 0 ; /* * ID dello lo stato di magnitude inferiore a quello del tratto che * si sta progettando. */ i = ( int ) one [ j ] ; ind = i ; // la lunghezza del tubo precedentemente progettato length = networkPipes [ ind ] . getLenght ( ) ; // seguo il percorso dell'acqua finch� non si incontra l'uscita. while ( networkPipes [ ind ] . getIdPipeWhereDrain ( ) != OUT_ID_PIPE ) { // lo stato dove drena a sua volta. ind = networkPipes [ ind ] . getIndexPipeWhereDrain ( ) ; /* * se lo stato drena direttamente in quello che si sta * progettando */ if ( ind == l ) { /* * ID dello stato che drena in l, piu o meno direttamente. */ net [ r ] [ 0 ] = i ; /* * lunghezza del percorsa dall'acqua prima di raggiungere lo * stato l che si sta progettando */ net [ r ] [ 1 ] = length + networkPipes [ l ] . getLenght ( ) ; /* * Ritardo accumulato dall'onda di piena formatasi in uno * degli stati a monte, prima di raggiungere il tratto l che * si sta progettando */ net [ r ] [ 2 ] = t ; /* * area di tutti gli stati a monte che direttamente o * indirettamente drenano in l */ totalarea += networkPipes [ i ] . getDrainArea ( ) ; r ++ ; break ; } } /* * viene incrementato solo se l'area drena in l quindi non puo' * superare net->nrh */ if ( r > net . length ) break ; } // area degli stati a monte che drenano in l, l compreso totalarea += networkPipes [ l ] . getDrainArea ( ) ; return totalarea ; } | Compila la mantrice net con tutte i dati del sottobacino con chiusura nel tratto che si sta analizzando e restituisce la sua superfice | 741 | 43 |
17,532 | public void readDwgBlockV15 ( int [ ] data , int offset ) throws Exception { int bitPos = offset ; bitPos = readObjectHeaderV15 ( data , bitPos ) ; Vector v = DwgUtil . getTextString ( data , bitPos ) ; bitPos = ( ( Integer ) v . get ( 0 ) ) . intValue ( ) ; String text = ( String ) v . get ( 1 ) ; name = text ; bitPos = readObjectTailV15 ( data , bitPos ) ; } | Read a Block in the DWG format Version 15 | 114 | 10 |
17,533 | public void setRepeatTimerDelay ( int delay ) { if ( delay <= 0 ) { String message = Logging . getMessage ( "generic.ArgumentOutOfRange" , delay ) ; Logging . logger ( ) . severe ( message ) ; throw new IllegalArgumentException ( message ) ; } this . repeatTimer . setDelay ( delay ) ; } | Set the repeat timer delay in milliseconds . | 77 | 8 |
17,534 | public void setPitchIncrement ( double value ) { if ( value < 0 ) { String message = Logging . getMessage ( "generic.ArgumentOutOfRange" , value ) ; Logging . logger ( ) . severe ( message ) ; throw new IllegalArgumentException ( message ) ; } this . pitchStep = value ; } | Set the pitch increment value in decimal degrees . Doubling this value will double the pitch change speed . Must be positive . Default value is 1 degree . | 72 | 30 |
17,535 | public void setFovIncrement ( double value ) { if ( value < 1 ) { String message = Logging . getMessage ( "generic.ArgumentOutOfRange" , value ) ; Logging . logger ( ) . severe ( message ) ; throw new IllegalArgumentException ( message ) ; } this . fovStep = value ; } | Set the field of view increment factor . At each iteration the current field of view will be multiplied or divided by this value . Must be greater then or equal to one . Default value is 1 . 05 . | 73 | 41 |
17,536 | public void setVeIncrement ( double value ) { if ( value < 0 ) { String message = Logging . getMessage ( "generic.ArgumentOutOfRange" , value ) ; Logging . logger ( ) . severe ( message ) ; throw new IllegalArgumentException ( message ) ; } this . veStep = value ; } | Set the vertical exaggeration increment . At each iteration the current vertical exaggeration will be increased or decreased by this amount . Must be greater than or equal to zero . Default value is 0 . 1 . | 71 | 38 |
17,537 | protected Vec4 computeSurfacePoint ( OrbitView view , Angle heading , Angle pitch ) { Globe globe = wwd . getModel ( ) . getGlobe ( ) ; // Compute transform to be applied to north pointing Y so that it would point in the view direction // Move coordinate system to view center point Matrix transform = globe . computeSurfaceOrientationAtPosition ( view . getCenterPosition ( ) ) ; // Rotate so that the north pointing axes Y will point in the look at direction transform = transform . multiply ( Matrix . fromRotationZ ( heading . multiply ( - 1 ) ) ) ; transform = transform . multiply ( Matrix . fromRotationX ( Angle . NEG90 . add ( pitch ) ) ) ; // Compute forward vector Vec4 forward = Vec4 . UNIT_Y . transformBy4 ( transform ) ; // Return intersection with terrain Intersection [ ] intersections = wwd . getSceneController ( ) . getTerrain ( ) . intersect ( new Line ( view . getEyePoint ( ) , forward ) ) ; return ( intersections != null && intersections . length != 0 ) ? intersections [ 0 ] . getIntersectionPoint ( ) : null ; } | Find out where on the terrain surface the eye would be looking at with the given heading and pitch angles . | 248 | 21 |
17,538 | public static void enableProxy ( String url , String port , String user , String pwd , String nonProxyHosts ) { _url = url ; _port = port ; _user = user ; _pwd = pwd ; System . setProperty ( "http.proxyHost" , url ) ; System . setProperty ( "https.proxyHost" , url ) ; if ( port != null && port . trim ( ) . length ( ) != 0 ) { System . setProperty ( "http.proxyPort" , port ) ; System . setProperty ( "https.proxyPort" , port ) ; } if ( user != null && pwd != null && user . trim ( ) . length ( ) != 0 && pwd . trim ( ) . length ( ) != 0 ) { System . setProperty ( "http.proxyUserName" , user ) ; System . setProperty ( "https.proxyUserName" , user ) ; System . setProperty ( "http.proxyUser" , user ) ; System . setProperty ( "https.proxyUser" , user ) ; System . setProperty ( "http.proxyPassword" , pwd ) ; System . setProperty ( "https.proxyPassword" , pwd ) ; Authenticator . setDefault ( new ProxyAuthenticator ( user , pwd ) ) ; } if ( nonProxyHosts != null ) { System . setProperty ( "http.nonProxyHosts" , nonProxyHosts ) ; } hasProxy = true ; } | Enable the proxy usage based on the url user and pwd . | 315 | 13 |
17,539 | public static void disableProxy ( ) { System . clearProperty ( "http.proxyHost" ) ; System . clearProperty ( "http.proxyPort" ) ; System . clearProperty ( "http.proxyUserName" ) ; System . clearProperty ( "http.proxyUser" ) ; System . clearProperty ( "http.proxyPassword" ) ; System . clearProperty ( "https.proxyHost" ) ; System . clearProperty ( "https.proxyPort" ) ; System . clearProperty ( "https.proxyUserName" ) ; System . clearProperty ( "https.proxyUser" ) ; System . clearProperty ( "https.proxyPassword" ) ; _url = null ; _port = null ; _user = null ; _pwd = null ; hasProxy = false ; } | Disable the proxy usage . | 167 | 5 |
17,540 | public static String loadNativeLibrary ( String nativeLibPath , String libName ) { try { String name = "las_c" ; if ( libName == null ) libName = name ; if ( nativeLibPath != null ) { NativeLibrary . addSearchPath ( libName , nativeLibPath ) ; } WRAPPER = ( LiblasJNALibrary ) Native . loadLibrary ( libName , LiblasJNALibrary . class ) ; } catch ( UnsatisfiedLinkError e ) { return e . getLocalizedMessage ( ) ; } return null ; } | Loads the native libs creating the native wrapper . | 122 | 11 |
17,541 | public static void createTables ( Connection connection ) throws Exception { StringBuilder sB = new StringBuilder ( ) ; sB . append ( "CREATE TABLE " ) ; sB . append ( TABLE_LOG ) ; sB . append ( " (" ) ; sB . append ( COLUMN_ID ) ; sB . append ( " INTEGER PRIMARY KEY AUTOINCREMENT, " ) ; sB . append ( COLUMN_DATAORA ) . append ( " INTEGER NOT NULL, " ) ; sB . append ( COLUMN_LOGMSG ) . append ( " TEXT " ) ; sB . append ( ");" ) ; String CREATE_TABLE = sB . toString ( ) ; sB = new StringBuilder ( ) ; sB . append ( "CREATE INDEX " + TABLE_LOG + "_" + COLUMN_ID + " ON " ) ; sB . append ( TABLE_LOG ) ; sB . append ( " ( " ) ; sB . append ( COLUMN_ID ) ; sB . append ( " );" ) ; String CREATE_INDEX = sB . toString ( ) ; sB = new StringBuilder ( ) ; sB . append ( "CREATE INDEX " + TABLE_LOG + "_" + COLUMN_DATAORA + " ON " ) ; sB . append ( TABLE_LOG ) ; sB . append ( " ( " ) ; sB . append ( COLUMN_DATAORA ) ; sB . append ( " );" ) ; String CREATE_INDEX_DATE = sB . toString ( ) ; try ( Statement statement = connection . createStatement ( ) ) { statement . setQueryTimeout ( 30 ) ; // set timeout to 30 sec. statement . executeUpdate ( CREATE_TABLE ) ; statement . executeUpdate ( CREATE_INDEX ) ; statement . executeUpdate ( CREATE_INDEX_DATE ) ; } catch ( Exception e ) { throw new IOException ( e . getLocalizedMessage ( ) ) ; } } | Create the default log table . | 450 | 6 |
17,542 | public static String convert ( long x , int n , String d ) { if ( x == 0 ) { return "0" ; } String r = "" ; int m = 1 << n ; m -- ; while ( x != 0 ) { r = d . charAt ( ( int ) ( x & m ) ) + r ; x = x >>> n ; } return r ; } | Converts number to string | 80 | 5 |
17,543 | public static String sprintf ( String s , Object [ ] params ) { if ( ( s == null ) || ( params == null ) ) { return s ; } StringBuffer result = new StringBuffer ( "" ) ; String [ ] ss = split ( s ) ; int p = 0 ; for ( int i = 0 ; i < ss . length ; i ++ ) { char c = ss [ i ] . charAt ( 0 ) ; String t = ss [ i ] . substring ( 1 ) ; if ( c == ' ' ) { result . append ( t ) ; } else { Object param = params [ p ] ; if ( param instanceof Integer ) { result . append ( new Format ( t ) . form ( ( Integer ) param ) ) ; } else if ( param instanceof Long ) { result . append ( new Format ( t ) . form ( ( Long ) param ) ) ; } else if ( param instanceof Character ) { result . append ( new Format ( t ) . form ( ( Character ) param ) ) ; } else if ( param instanceof Double ) { result . append ( new Format ( t ) . form ( ( Double ) param ) ) ; } else if ( param instanceof Double ) { result . append ( new Format ( t ) . form ( new Float ( ( Double ) param ) ) ) ; } else { result . append ( new Format ( t ) . form ( param . toString ( ) ) ) ; } p ++ ; } } return result . toString ( ) ; } | Sprintf multiple strings . | 317 | 5 |
17,544 | public void setLowerAndUpperBounds ( double lower , double upper ) { if ( data == null ) { return ; } this . originalLowerBound = lower ; this . originalUpperBound = upper ; if ( originalLowerBound < min ) { offset = Math . abs ( originalLowerBound ) + 10 ; } else { offset = Math . abs ( min ) + 10 ; } if ( calibrationType == MEAN ) { lowerBound = ( originalLowerBound + offset ) * ( mean + offset ) / ( min + offset ) - offset ; upperBound = ( originalUpperBound + offset ) * ( mean + offset ) / ( max + offset ) - offset ; } else { lowerBound = originalLowerBound ; upperBound = originalUpperBound ; } hasBounds = true ; setDeviation ( ) ; } | Set the lower and upper bounds and the actual bounds are determined . | 173 | 13 |
17,545 | private boolean checkLocations ( long length , CompoundLocation < Location > locations ) { for ( Location location : locations . getLocations ( ) ) { if ( location instanceof RemoteLocation ) continue ; if ( location . getIntBeginPosition ( ) == null || location . getIntBeginPosition ( ) < 0 ) { return false ; } if ( location . getIntEndPosition ( ) == null || location . getIntEndPosition ( ) > length ) { return false ; } } return true ; } | Checks that the locations are within the sequence length | 105 | 10 |
17,546 | public static SimpleFeatureSource readFeatureSource ( String path ) throws Exception { File shapeFile = new File ( path ) ; FileDataStore store = FileDataStoreFinder . getDataStore ( shapeFile ) ; SimpleFeatureSource featureSource = store . getFeatureSource ( ) ; return featureSource ; } | Get the feature source from a file . | 63 | 8 |
17,547 | public static GEOMTYPE getGeometryType ( SimpleFeatureCollection featureCollection ) { GeometryDescriptor geometryDescriptor = featureCollection . getSchema ( ) . getGeometryDescriptor ( ) ; if ( EGeometryType . isPolygon ( geometryDescriptor ) ) { return GEOMTYPE . POLYGON ; } else if ( EGeometryType . isLine ( geometryDescriptor ) ) { return GEOMTYPE . LINE ; } else if ( EGeometryType . isPoint ( geometryDescriptor ) ) { return GEOMTYPE . POINT ; } else { return GEOMTYPE . UNKNOWN ; } } | Get the geometry type from a featurecollection . | 139 | 9 |
17,548 | public static void insertBeforeCompass ( WorldWindow wwd , Layer layer ) { // Insert the layer into the layer list just before the compass. int compassPosition = 0 ; LayerList layers = wwd . getModel ( ) . getLayers ( ) ; for ( Layer l : layers ) { if ( l instanceof CompassLayer ) compassPosition = layers . indexOf ( l ) ; } layers . add ( compassPosition , layer ) ; } | Insert a layer before the compass layer . | 93 | 8 |
17,549 | public void readDwgVertex2DV15 ( int [ ] data , int offset ) throws Exception { //System.out.println("readDwgVertex2D executing ..."); int bitPos = offset ; bitPos = readObjectHeaderV15 ( data , bitPos ) ; Vector v = DwgUtil . getRawChar ( data , bitPos ) ; bitPos = ( ( Integer ) v . get ( 0 ) ) . intValue ( ) ; int flags = ( ( Integer ) v . get ( 1 ) ) . intValue ( ) ; this . flags = flags ; v = DwgUtil . getBitDouble ( data , bitPos ) ; bitPos = ( ( Integer ) v . get ( 0 ) ) . intValue ( ) ; double x = ( ( Double ) v . get ( 1 ) ) . doubleValue ( ) ; v = DwgUtil . getBitDouble ( data , bitPos ) ; bitPos = ( ( Integer ) v . get ( 0 ) ) . intValue ( ) ; double y = ( ( Double ) v . get ( 1 ) ) . doubleValue ( ) ; v = DwgUtil . getBitDouble ( data , bitPos ) ; bitPos = ( ( Integer ) v . get ( 0 ) ) . intValue ( ) ; double z = ( ( Double ) v . get ( 1 ) ) . doubleValue ( ) ; double [ ] coord = new double [ ] { x , y , z } ; point = new double [ ] { x , y , z } ; v = DwgUtil . getBitDouble ( data , bitPos ) ; bitPos = ( ( Integer ) v . get ( 0 ) ) . intValue ( ) ; double sw = ( ( Double ) v . get ( 1 ) ) . doubleValue ( ) ; double ew = 0.0 ; if ( sw < 0.0 ) { ew = Math . abs ( sw ) ; sw = ew ; } else { v = DwgUtil . getBitDouble ( data , bitPos ) ; bitPos = ( ( Integer ) v . get ( 0 ) ) . intValue ( ) ; ew = ( ( Double ) v . get ( 1 ) ) . doubleValue ( ) ; } initWidth = sw ; endWidth = ew ; v = DwgUtil . getBitDouble ( data , bitPos ) ; bitPos = ( ( Integer ) v . get ( 0 ) ) . intValue ( ) ; double bulge = ( ( Double ) v . get ( 1 ) ) . doubleValue ( ) ; this . bulge = bulge ; v = DwgUtil . getBitDouble ( data , bitPos ) ; bitPos = ( ( Integer ) v . get ( 0 ) ) . intValue ( ) ; double tandir = ( ( Double ) v . get ( 1 ) ) . doubleValue ( ) ; tangentDir = tandir ; bitPos = readObjectTailV15 ( data , bitPos ) ; } | Read a Vertex2D in the DWG format Version 15 | 640 | 13 |
17,550 | public static double runoffCoefficientError ( double [ ] obs , double [ ] sim , double [ ] precip ) { sameArrayLen ( sim , obs , precip ) ; double mean_pred = Stats . mean ( sim ) ; double mean_val = Stats . mean ( obs ) ; double mean_ppt = Stats . mean ( precip ) ; double error = Math . abs ( ( mean_pred / mean_ppt ) - ( mean_val / mean_ppt ) ) ; return Math . sqrt ( error ) ; } | Runoff coefficient error ROCE | 113 | 7 |
17,551 | public double [ ] update ( double w , double c1 , double rand1 , double c2 , double rand2 , double [ ] globalBest ) { for ( int i = 0 ; i < locations . length ; i ++ ) { particleVelocities [ i ] = w * particleVelocities [ i ] + // c1 * rand1 * ( particleLocalBests [ i ] - locations [ i ] ) + // c2 * rand2 * ( globalBest [ i ] - locations [ i ] ) ; double tmpLocation = locations [ i ] + particleVelocities [ i ] ; /* * if the location falls outside the ranges, it should * not be moved. */ tmpLocations [ i ] = tmpLocation ; } if ( ! PSEngine . parametersInRange ( tmpLocations , ranges ) ) { // System.out.println("PRE-TMPLOCATIONS: " + Arrays.toString(tmpLocations)); // System.out.println("LOCATIONS: " + Arrays.toString(locations)); /* * mirror the value back */ for ( int i = 0 ; i < tmpLocations . length ; i ++ ) { double min = ranges [ i ] [ 0 ] ; double max = ranges [ i ] [ 1 ] ; if ( tmpLocations [ i ] > max ) { double tmp = max - ( tmpLocations [ i ] - max ) ; if ( tmp < min ) { tmp = max ; } locations [ i ] = tmp ; } else if ( tmpLocations [ i ] < min ) { double tmp = min + ( min - tmpLocations [ i ] ) ; if ( tmp > max ) { tmp = min ; } locations [ i ] = tmp ; } else { locations [ i ] = tmpLocations [ i ] ; } } // System.out.println("POST-LOCATIONS: " + Arrays.toString(locations)); // System.out.println("VELOCITIES: " + Arrays.toString(particleVelocities)); return null ; } else { for ( int i = 0 ; i < locations . length ; i ++ ) { locations [ i ] = tmpLocations [ i ] ; } return locations ; } } | Particle swarming formula to update positions . | 472 | 9 |
17,552 | public void setParticleLocalBeststoCurrent ( ) { for ( int i = 0 ; i < locations . length ; i ++ ) { particleLocalBests [ i ] = locations [ i ] ; } } | Setter to set the current positions to be the local best positions . | 45 | 14 |
17,553 | public static File getLastFile ( ) { Preferences preferences = Preferences . userRoot ( ) . node ( GuiBridgeHandler . PREFS_NODE_NAME ) ; String userHome = System . getProperty ( "user.home" ) ; String lastPath = preferences . get ( LAST_PATH , userHome ) ; File file = new File ( lastPath ) ; if ( ! file . exists ( ) ) { return new File ( userHome ) ; } return file ; } | Handle the last set path preference . | 100 | 7 |
17,554 | public static void setLastPath ( String lastPath ) { File file = new File ( lastPath ) ; if ( ! file . isDirectory ( ) ) { lastPath = file . getParentFile ( ) . getAbsolutePath ( ) ; } Preferences preferences = Preferences . userRoot ( ) . node ( GuiBridgeHandler . PREFS_NODE_NAME ) ; preferences . put ( LAST_PATH , lastPath ) ; } | Save the passed path as last path available . | 91 | 9 |
17,555 | public static void setPreference ( String preferenceKey , String value ) { if ( preferencesDb != null ) { preferencesDb . setPreference ( preferenceKey , value ) ; return ; } Preferences preferences = Preferences . userRoot ( ) . node ( GuiBridgeHandler . PREFS_NODE_NAME ) ; if ( value != null ) { preferences . put ( preferenceKey , value ) ; } else { preferences . remove ( preferenceKey ) ; } } | Set a preference . | 95 | 4 |
17,556 | @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public static String [ ] showMultiInputDialog ( Component parentComponent , String title , String [ ] labels , String [ ] defaultValues , HashMap < String , String [ ] > fields2ValuesMap ) { Component [ ] valuesFields = new Component [ labels . length ] ; JPanel panel = new JPanel ( ) ; // panel.setPreferredSize(new Dimension(400, 300)); panel . setBorder ( BorderFactory . createEmptyBorder ( 10 , 10 , 10 , 10 ) ) ; String input [ ] = new String [ labels . length ] ; panel . setLayout ( new GridLayout ( labels . length , 2 , 5 , 5 ) ) ; for ( int i = 0 ; i < labels . length ; i ++ ) { panel . add ( new JLabel ( labels [ i ] ) ) ; boolean doneCombo = false ; if ( fields2ValuesMap != null ) { String [ ] values = fields2ValuesMap . get ( labels [ i ] ) ; if ( values != null ) { JComboBox < String > valuesCombo = new JComboBox <> ( values ) ; valuesFields [ i ] = valuesCombo ; panel . add ( valuesCombo ) ; if ( defaultValues != null ) { valuesCombo . setSelectedItem ( defaultValues [ i ] ) ; } doneCombo = true ; } } if ( ! doneCombo ) { valuesFields [ i ] = new JTextField ( ) ; panel . add ( valuesFields [ i ] ) ; if ( defaultValues != null ) { ( ( JTextField ) valuesFields [ i ] ) . setText ( defaultValues [ i ] ) ; } } } JScrollPane scrollPane = new JScrollPane ( panel ) ; scrollPane . setPreferredSize ( new Dimension ( 550 , 300 ) ) ; int result = JOptionPane . showConfirmDialog ( parentComponent , scrollPane , title , JOptionPane . OK_CANCEL_OPTION ) ; if ( result != JOptionPane . OK_OPTION ) { return null ; } for ( int i = 0 ; i < labels . length ; i ++ ) { if ( valuesFields [ i ] instanceof JTextField ) { JTextField textField = ( JTextField ) valuesFields [ i ] ; input [ i ] = textField . getText ( ) ; } if ( valuesFields [ i ] instanceof JComboBox ) { JComboBox < String > combo = ( JComboBox ) valuesFields [ i ] ; input [ i ] = combo . getSelectedItem ( ) . toString ( ) ; } } return input ; } | Create a simple multi input pane that returns what the use inserts . | 594 | 13 |
17,557 | public static void colorButton ( JButton button , Color color , Integer size ) { if ( size == null ) size = 15 ; BufferedImage bi = new BufferedImage ( size , size , BufferedImage . TYPE_INT_RGB ) ; Graphics2D gr = ( Graphics2D ) bi . getGraphics ( ) ; gr . setColor ( color ) ; gr . fillRect ( 0 , 0 , size , size ) ; gr . dispose ( ) ; button . setIcon ( new ImageIcon ( bi ) ) ; } | Create an image to make a color picker button . | 111 | 11 |
17,558 | public static void setFileBrowsingOnWidgets ( JTextField pathTextField , JButton browseButton , String [ ] allowedExtensions , Runnable postRunnable ) { FileFilter filter = null ; if ( allowedExtensions != null ) { filter = new FileFilter ( ) { @ Override public String getDescription ( ) { return Arrays . toString ( allowedExtensions ) ; } @ Override public boolean accept ( File f ) { if ( f . isDirectory ( ) ) { return true ; } String name = f . getName ( ) ; for ( String ext : allowedExtensions ) { if ( name . toLowerCase ( ) . endsWith ( ext . toLowerCase ( ) ) ) { return true ; } } return false ; } } ; } FileFilter _filter = filter ; browseButton . addActionListener ( e -> { File lastFile = GuiUtilities . getLastFile ( ) ; File [ ] res = showOpenFilesDialog ( browseButton , "Select file" , false , lastFile , _filter ) ; if ( res != null && res . length == 1 ) { String absolutePath = res [ 0 ] . getAbsolutePath ( ) ; pathTextField . setText ( absolutePath ) ; setLastPath ( absolutePath ) ; if ( postRunnable != null ) { postRunnable . run ( ) ; } } } ) ; } | Adds to a textfield and button the necessary to browse for a file . | 299 | 15 |
17,559 | public static void setFolderBrowsingOnWidgets ( JTextField pathTextField , JButton browseButton ) { browseButton . addActionListener ( e -> { File lastFile = GuiUtilities . getLastFile ( ) ; File [ ] res = showOpenFolderDialog ( browseButton , "Select folder" , false , lastFile ) ; if ( res != null && res . length == 1 ) { String absolutePath = res [ 0 ] . getAbsolutePath ( ) ; pathTextField . setText ( absolutePath ) ; setLastPath ( absolutePath ) ; } } ) ; } | Adds to a textfield and button the necessary to browse for a folder . | 128 | 15 |
17,560 | private static double [ ] calculateParameters ( final double [ ] [ ] elevationValues ) { int rows = elevationValues . length ; int cols = elevationValues [ 0 ] . length ; int pointsNum = rows * cols ; final double [ ] [ ] xyMatrix = new double [ pointsNum ] [ 6 ] ; final double [ ] valueArray = new double [ pointsNum ] ; // TODO check on resolution int index = 0 ; for ( int y = 0 ; y < rows ; y ++ ) { for ( int x = 0 ; x < cols ; x ++ ) { xyMatrix [ index ] [ 0 ] = x * x ; // x^2 xyMatrix [ index ] [ 1 ] = y * y ; // y^2 xyMatrix [ index ] [ 2 ] = x * y ; // xy xyMatrix [ index ] [ 3 ] = x ; // x xyMatrix [ index ] [ 4 ] = y ; // y xyMatrix [ index ] [ 5 ] = 1 ; valueArray [ index ] = elevationValues [ y ] [ x ] ; index ++ ; } } RealMatrix A = MatrixUtils . createRealMatrix ( xyMatrix ) ; RealVector z = MatrixUtils . createRealVector ( valueArray ) ; DecompositionSolver solver = new RRQRDecomposition ( A ) . getSolver ( ) ; RealVector solution = solver . solve ( z ) ; // start values for a, b, c, d, e, f, all set to 0.0 final double [ ] parameters = solution . toArray ( ) ; return parameters ; } | Calculates the parameters of a bivariate quadratic equation . | 345 | 14 |
17,561 | public Object column ( int col ) throws jsqlite . Exception { switch ( column_type ( col ) ) { case Constants . SQLITE_INTEGER : return new Long ( column_long ( col ) ) ; case Constants . SQLITE_FLOAT : return new Double ( column_double ( col ) ) ; case Constants . SQLITE_BLOB : return column_bytes ( col ) ; case Constants . SQLITE3_TEXT : return column_string ( col ) ; } return null ; } | Retrieve column data as object from exec ed SQLite3 statement . | 111 | 14 |
17,562 | protected void processGrid ( int cols , int rows , boolean ignoreBorder , Calculator calculator ) throws Exception { ExecutionPlanner planner = createDefaultPlanner ( ) ; planner . setNumberOfTasks ( rows * cols ) ; int startC = 0 ; int startR = 0 ; int endC = cols ; int endR = rows ; if ( ignoreBorder ) { startC = 1 ; startR = 1 ; endC = cols - 1 ; endR = rows - 1 ; } for ( int r = startR ; r < endR ; r ++ ) { for ( int c = startC ; c < endC ; c ++ ) { int _c = c , _r = r ; planner . submit ( ( ) -> { if ( ! pm . isCanceled ( ) ) { calculator . calculate ( _c , _r ) ; } } ) ; } } planner . join ( ) ; } | Loops through all rows and cols of the given grid . | 195 | 13 |
17,563 | @ Override public int compare ( SimpleFeature f1 , SimpleFeature f2 ) { int linkid1 = ( Integer ) f1 . getAttribute ( LINKID ) ; int linkid2 = ( Integer ) f2 . getAttribute ( LINKID ) ; if ( linkid1 < linkid2 ) { return - 1 ; } else if ( linkid1 > linkid2 ) { return 1 ; } else { return 0 ; } } | establish the position of each net point respect to the others | 93 | 11 |
17,564 | public static Color colorFromRbgString ( String rbgString ) { String [ ] split = rbgString . split ( "," ) ; if ( split . length < 3 || split . length > 4 ) { throw new IllegalArgumentException ( "Color string has to be of type r,g,b." ) ; } int r = ( int ) Double . parseDouble ( split [ 0 ] . trim ( ) ) ; int g = ( int ) Double . parseDouble ( split [ 1 ] . trim ( ) ) ; int b = ( int ) Double . parseDouble ( split [ 2 ] . trim ( ) ) ; Color c = null ; if ( split . length == 4 ) { // alpha int a = ( int ) Double . parseDouble ( split [ 3 ] . trim ( ) ) ; c = new Color ( r , g , b , a ) ; } else { c = new Color ( r , g , b ) ; } return c ; } | Converts a color string . | 203 | 6 |
17,565 | public static Color fromHex ( String hex ) { if ( hex . startsWith ( "#" ) ) { hex = hex . substring ( 1 ) ; } int length = hex . length ( ) ; int total = 6 ; if ( length < total ) { // we have a shortened version String token = hex ; int tokenLength = token . length ( ) ; for ( int i = 0 ; i < total ; i = i + tokenLength ) { hex += token ; } } int index = 0 ; String r = hex . substring ( index , index + 2 ) ; String g = hex . substring ( index + 2 , index + 4 ) ; String b = hex . substring ( index + 4 , index + total ) ; return new Color ( Integer . valueOf ( r , 16 ) , Integer . valueOf ( g , 16 ) , Integer . valueOf ( b , 16 ) ) ; } | Convert hex color to Color . | 191 | 7 |
17,566 | public int getFlowAt ( Direction direction ) { switch ( direction ) { case E : return eFlow ; case W : return wFlow ; case N : return nFlow ; case S : return sFlow ; case EN : return enFlow ; case NW : return nwFlow ; case WS : return wsFlow ; case SE : return seFlow ; default : throw new IllegalArgumentException ( ) ; } } | Get the value of the flow in one of the surrounding direction . | 86 | 13 |
17,567 | public FlowNode goDownstream ( ) { if ( isValid ) { Direction direction = Direction . forFlow ( flow ) ; if ( direction != null ) { FlowNode nextNode = new FlowNode ( gridIter , cols , rows , col + direction . col , row + direction . row ) ; if ( nextNode . isValid ) { return nextNode ; } } } return null ; } | Get the next downstream node . | 83 | 6 |
17,568 | @ Override public void started ( ServiceBroker broker ) throws Exception { super . started ( broker ) ; // Set components ServiceBrokerConfig cfg = broker . getConfig ( ) ; serviceInvoker = cfg . getServiceInvoker ( ) ; eventbus = cfg . getEventbus ( ) ; uid = cfg . getUidGenerator ( ) ; } | Initializes Default Context Factory instance . | 80 | 7 |
17,569 | @ Override public void started ( ServiceBroker broker ) throws Exception { super . started ( broker ) ; // Set nodeID this . nodeID = broker . getNodeID ( ) ; // Set components ServiceBrokerConfig cfg = broker . getConfig ( ) ; this . strategy = cfg . getStrategyFactory ( ) ; this . transporter = cfg . getTransporter ( ) ; this . executor = cfg . getExecutor ( ) ; } | Initializes default EventBus instance . | 98 | 7 |
17,570 | protected boolean append ( byte [ ] packet ) { ByteBuffer buffer = ByteBuffer . wrap ( packet ) ; ByteBuffer blocker ; while ( true ) { blocker = blockerBuffer . get ( ) ; if ( blocker == BUFFER_IS_CLOSED ) { return false ; } if ( blockerBuffer . compareAndSet ( blocker , buffer ) ) { queue . add ( buffer ) ; return true ; } } } | Adds a packet to the buffer s queue . | 85 | 9 |
17,571 | protected boolean tryToClose ( ) { ByteBuffer blocker = blockerBuffer . get ( ) ; if ( blocker == BUFFER_IS_CLOSED ) { return true ; } if ( blocker != null ) { return false ; } boolean closed = blockerBuffer . compareAndSet ( null , BUFFER_IS_CLOSED ) ; if ( closed ) { closeResources ( ) ; return true ; } return false ; } | Tries to close this buffer . | 86 | 7 |
17,572 | protected void write ( ) throws Exception { ByteBuffer buffer = queue . peek ( ) ; if ( buffer == null ) { if ( key != null ) { key . interestOps ( 0 ) ; } return ; } if ( channel != null ) { int count ; while ( true ) { count = channel . write ( buffer ) ; // Debug if ( debug ) { logger . info ( count + " bytes submitted to " + channel . getRemoteAddress ( ) + "." ) ; } // EOF? if ( count == - 1 ) { throw new InvalidPacketDataError ( nodeID , "host" , host , "port" , port ) ; } // Remove the submitted buffer from the queue if ( ! buffer . hasRemaining ( ) ) { queue . poll ( ) ; } // Turn off write mode (if the queue is empty) if ( queue . isEmpty ( ) ) { if ( blockerBuffer . compareAndSet ( buffer , null ) && key != null ) { key . interestOps ( 0 ) ; } return ; } else { buffer = queue . peek ( ) ; } } } } | Writes N bytes to the target channel . | 231 | 9 |
17,573 | @ Override public void started ( ServiceBroker broker ) throws Exception { super . started ( broker ) ; // Process config ServiceBrokerConfig cfg = broker . getConfig ( ) ; namespace = cfg . getNamespace ( ) ; if ( namespace != null && ! namespace . isEmpty ( ) ) { prefix = prefix + ' ' + namespace ; } nodeID = broker . getNodeID ( ) ; // Log serializer info serializer . started ( broker ) ; logger . info ( nameOf ( this , true ) + " will use " + nameOf ( serializer , true ) + ' ' ) ; // Get components executor = cfg . getExecutor ( ) ; scheduler = cfg . getScheduler ( ) ; registry = cfg . getServiceRegistry ( ) ; monitor = cfg . getMonitor ( ) ; eventbus = cfg . getEventbus ( ) ; uid = cfg . getUidGenerator ( ) ; // Set channel names eventChannel = channel ( PACKET_EVENT , nodeID ) ; requestChannel = channel ( PACKET_REQUEST , nodeID ) ; responseChannel = channel ( PACKET_RESPONSE , nodeID ) ; discoverBroadcastChannel = channel ( PACKET_DISCOVER , null ) ; discoverChannel = channel ( PACKET_DISCOVER , nodeID ) ; infoBroadcastChannel = channel ( PACKET_INFO , null ) ; infoChannel = channel ( PACKET_INFO , nodeID ) ; disconnectChannel = channel ( PACKET_DISCONNECT , null ) ; heartbeatChannel = channel ( PACKET_HEARTBEAT , null ) ; pingChannel = channel ( PACKET_PING , nodeID ) ; pongChannel = channel ( PACKET_PONG , nodeID ) ; } | Initializes transporter instance . | 381 | 5 |
17,574 | @ Override public void started ( ServiceBroker broker ) throws Exception { super . started ( broker ) ; // Local nodeID this . nodeID = broker . getNodeID ( ) ; // Set components ServiceBrokerConfig cfg = broker . getConfig ( ) ; this . executor = cfg . getExecutor ( ) ; this . scheduler = cfg . getScheduler ( ) ; this . strategyFactory = cfg . getStrategyFactory ( ) ; this . contextFactory = cfg . getContextFactory ( ) ; this . transporter = cfg . getTransporter ( ) ; this . eventbus = cfg . getEventbus ( ) ; this . uid = cfg . getUidGenerator ( ) ; } | Initializes ServiceRegistry instance . | 158 | 7 |
17,575 | protected void reschedule ( long minTimeoutAt ) { if ( minTimeoutAt == Long . MAX_VALUE ) { for ( PendingPromise pending : promises . values ( ) ) { if ( pending . timeoutAt > 0 && pending . timeoutAt < minTimeoutAt ) { minTimeoutAt = pending . timeoutAt ; } } long timeoutAt ; requestStreamReadLock . lock ( ) ; try { for ( IncomingStream stream : requestStreams . values ( ) ) { timeoutAt = stream . getTimeoutAt ( ) ; if ( timeoutAt > 0 && timeoutAt < minTimeoutAt ) { minTimeoutAt = timeoutAt ; } } } finally { requestStreamReadLock . unlock ( ) ; } responseStreamReadLock . lock ( ) ; try { for ( IncomingStream stream : responseStreams . values ( ) ) { timeoutAt = stream . getTimeoutAt ( ) ; if ( timeoutAt > 0 && timeoutAt < minTimeoutAt ) { minTimeoutAt = timeoutAt ; } } } finally { responseStreamReadLock . unlock ( ) ; } } long now = System . currentTimeMillis ( ) ; if ( minTimeoutAt == Long . MAX_VALUE ) { ScheduledFuture < ? > t = callTimeoutTimer . get ( ) ; if ( t != null ) { if ( prevTimeoutAt . get ( ) > now ) { t . cancel ( false ) ; prevTimeoutAt . set ( 0 ) ; } else { callTimeoutTimer . set ( null ) ; prevTimeoutAt . set ( 0 ) ; } } } else { minTimeoutAt = ( minTimeoutAt / 100 * 100 ) + 100 ; long prev = prevTimeoutAt . getAndSet ( minTimeoutAt ) ; if ( prev == minTimeoutAt ) { // Next when not changed return ; } // Stop previous timer ScheduledFuture < ? > t = callTimeoutTimer . get ( ) ; if ( t != null ) { t . cancel ( false ) ; } // Schedule next timeout timer long delay = Math . max ( 10 , minTimeoutAt - now ) ; callTimeoutTimer . set ( scheduler . schedule ( this :: checkTimeouts , delay , TimeUnit . MILLISECONDS ) ) ; } } | Recalculates the next timeout checking time . | 465 | 10 |
17,576 | public byte [ ] generateGossipHello ( ) { if ( cachedHelloMessage != null ) { return cachedHelloMessage ; } try { FastBuildTree root = new FastBuildTree ( 4 ) ; root . putUnsafe ( "ver" , ServiceBroker . PROTOCOL_VERSION ) ; root . putUnsafe ( "sender" , nodeID ) ; if ( useHostname ) { root . putUnsafe ( "host" , getHostName ( ) ) ; } else { root . putUnsafe ( "host" , InetAddress . getLocalHost ( ) . getHostAddress ( ) ) ; } root . putUnsafe ( "port" , reader . getCurrentPort ( ) ) ; cachedHelloMessage = serialize ( PACKET_GOSSIP_HELLO_ID , root ) ; } catch ( Exception error ) { throw new MoleculerError ( "Unable to create HELLO message!" , error , "MoleculerError" , "unknown" , false , 500 , "UNABLE_TO_CREATE_HELLO" ) ; } return cachedHelloMessage ; } | Create Gossip HELLO packet . Hello message is invariable so we can cache it . | 239 | 18 |
17,577 | public ServiceBroker use ( Collection < Middleware > middlewares ) { if ( serviceRegistry == null ) { // Apply middlewares later this . middlewares . addAll ( middlewares ) ; } else { // Apply middlewares now serviceRegistry . use ( middlewares ) ; } return this ; } | Installs a collection of middlewares . | 70 | 9 |
17,578 | public Action getAction ( String actionName , String nodeID ) { return serviceRegistry . getAction ( actionName , nodeID ) ; } | Returns an action by name and nodeID . | 30 | 9 |
17,579 | public final Promise get ( String key ) { byte [ ] binaryKey = key . getBytes ( StandardCharsets . UTF_8 ) ; if ( client != null ) { return new Promise ( client . get ( binaryKey ) ) ; } if ( clusteredClient != null ) { return new Promise ( clusteredClient . get ( binaryKey ) ) ; } return Promise . resolve ( ) ; } | Gets a content by a key . | 82 | 8 |
17,580 | public final Promise set ( String key , byte [ ] value , SetArgs args ) { byte [ ] binaryKey = key . getBytes ( StandardCharsets . UTF_8 ) ; if ( client != null ) { if ( args == null ) { return new Promise ( client . set ( binaryKey , value ) ) ; } return new Promise ( client . set ( binaryKey , value , args ) ) ; } if ( clusteredClient != null ) { if ( args == null ) { return new Promise ( clusteredClient . set ( binaryKey , value ) ) ; } return new Promise ( clusteredClient . set ( binaryKey , value , args ) ) ; } return Promise . resolve ( ) ; } | Sets a content by key . | 146 | 7 |
17,581 | public final Promise clean ( String match ) { ScanArgs args = new ScanArgs ( ) ; args . limit ( 100 ) ; boolean singleStar = match . indexOf ( ' ' ) > - 1 ; boolean doubleStar = match . contains ( "**" ) ; if ( doubleStar ) { args . match ( match . replace ( "**" , "*" ) ) ; } else if ( singleStar ) { if ( match . length ( ) > 1 && match . indexOf ( ' ' ) == - 1 ) { match += ' ' ; } args . match ( match ) ; } else { args . match ( match ) ; } if ( ! singleStar || doubleStar ) { match = null ; } if ( client != null ) { return new Promise ( clean ( client . scan ( args ) , args , match ) ) ; } if ( clusteredClient != null ) { return new Promise ( clean ( clusteredClient . scan ( args ) , args , match ) ) ; } return Promise . resolve ( ) ; } | Deletes a group of items . Removes every key by a match string . | 213 | 16 |
17,582 | public int getTotalCpuPercent ( ) { if ( invalidMonitor . get ( ) ) { return 0 ; } long now = System . currentTimeMillis ( ) ; int cpu ; synchronized ( Monitor . class ) { if ( now - cpuDetectedAt > cacheTimeout ) { try { cachedCPU = detectTotalCpuPercent ( ) ; } catch ( Throwable cause ) { logger . info ( "Unable to detect CPU usage!" , cause ) ; invalidMonitor . set ( true ) ; } cpuDetectedAt = now ; } cpu = cachedCPU ; } return cpu ; } | Returns the cached system CPU usage in percents between 0 and 100 . | 123 | 15 |
17,583 | public long getPID ( ) { long currentPID = cachedPID . get ( ) ; if ( currentPID != 0 ) { return currentPID ; } try { currentPID = detectPID ( ) ; } catch ( Throwable cause ) { logger . info ( "Unable to detect process ID!" , cause ) ; } if ( currentPID == 0 ) { currentPID = System . nanoTime ( ) ; if ( ! cachedPID . compareAndSet ( 0 , currentPID ) ) { currentPID = cachedPID . get ( ) ; } } else { cachedPID . set ( currentPID ) ; } return currentPID ; } | Returns the cached PID of Java VM . | 146 | 8 |
17,584 | public synchronized void reset ( ) { timeoutAt = 0 ; prevSeq = - 1 ; pool . clear ( ) ; stream . closed . set ( false ) ; stream . buffer . clear ( ) ; stream . cause = null ; stream . transferedBytes . set ( 0 ) ; inited . set ( false ) ; } | Used for testing . Resets internal variables . | 68 | 9 |
17,585 | @ Override public void started ( ServiceBroker broker ) throws Exception { super . started ( broker ) ; if ( prefix == null ) { prefix = ( broker . getNodeID ( ) + ' ' ) . toCharArray ( ) ; } } | Initializes UID generator instance . | 52 | 6 |
17,586 | public boolean updateSchema ( String text , ContentType contentType ) { Utils . require ( text != null && text . length ( ) > 0 , "text" ) ; Utils . require ( contentType != null , "contentType" ) ; try { // Send a PUT request to "/_applications/{application}". byte [ ] body = Utils . toBytes ( text ) ; StringBuilder uri = new StringBuilder ( "/_applications/" ) ; uri . append ( Utils . urlEncode ( m_appDef . getAppName ( ) ) ) ; RESTResponse response = m_restClient . sendRequest ( HttpMethod . PUT , uri . toString ( ) , contentType , body ) ; m_logger . debug ( "updateSchema() response: {}" , response . toString ( ) ) ; throwIfErrorResponse ( response ) ; return true ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } | Update the schema for this session s application with the given definition . The text must be formatted in XML or JSON as defined by the given content type . True is returned if the update was successful . An exception is thrown if an error occurred . | 214 | 48 |
17,587 | protected void throwIfErrorResponse ( RESTResponse response ) { if ( response . getCode ( ) . isError ( ) ) { String errMsg = response . getBody ( ) ; if ( Utils . isEmpty ( errMsg ) ) { errMsg = "Unknown error; response code: " + response . getCode ( ) ; } throw new RuntimeException ( errMsg ) ; } } | If the given response shows an error throw a RuntimeException using its text . | 82 | 15 |
17,588 | public String get ( String key ) { if ( requestedKeys == null ) requestedKeys = new HashSet < String > ( ) ; String value = map . get ( key ) ; requestedKeys . add ( key ) ; return value ; } | Gets a value by the key specified . Returns null if the key does not exist . | 49 | 18 |
17,589 | public String getString ( String key ) { String value = get ( key ) ; Utils . require ( value != null , key + " parameter is not set" ) ; return value ; } | Gets a value by the key specified . Unlike get checks that the parameter is not null | 40 | 18 |
17,590 | public int getInt ( String key ) { String value = get ( key ) ; Utils . require ( value != null , key + " parameter is not set" ) ; try { return Integer . parseInt ( value ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( key + " parameter should be a number" ) ; } } | Returns an integer value by the key specified and throws exception if it was not specified | 76 | 16 |
17,591 | public int getInt ( String key , int defaultValue ) { String value = get ( key ) ; if ( value == null ) return defaultValue ; try { return Integer . parseInt ( value ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( key + " parameter should be a number" ) ; } } | Returns an integer value by the key specified or defaultValue if the key was not provided | 71 | 17 |
17,592 | public boolean getBoolean ( String key , boolean defaultValue ) { String value = get ( key ) ; if ( value == null ) return defaultValue ; return XType . getBoolean ( value ) ; } | Returns a boolean value by the key specified or defaultValue if the key was not provided | 44 | 17 |
17,593 | public void checkInvalidParameters ( ) { for ( String key : map . keySet ( ) ) { boolean wasRequested = requestedKeys != null && requestedKeys . contains ( key ) ; if ( ! wasRequested ) throw new IllegalArgumentException ( "Unknown parameter " + key ) ; } } | Checks that there are no more parameters than those that have ever been requested . Call this after you processed all parameters you need if you want an IllegalArgumentException to be thrown if there are more parameters | 63 | 41 |
17,594 | static KeyRange keyRangeStartRow ( byte [ ] startRowKey ) { KeyRange keyRange = new KeyRange ( ) ; keyRange . setStart_key ( startRowKey ) ; keyRange . setEnd_key ( EMPTY_BYTE_BUFFER ) ; keyRange . setCount ( MAX_ROWS_BATCH_SIZE ) ; return keyRange ; } | Create a KeyRange that begins at the given row key . | 80 | 12 |
17,595 | static KeyRange keyRangeSingleRow ( byte [ ] rowKey ) { KeyRange keyRange = new KeyRange ( ) ; keyRange . setStart_key ( rowKey ) ; keyRange . setEnd_key ( rowKey ) ; keyRange . setCount ( 1 ) ; return keyRange ; } | Create a KeyRange that selects a single row with the given key . | 64 | 14 |
17,596 | static SlicePredicate slicePredicateColName ( byte [ ] colName ) { SlicePredicate slicePred = new SlicePredicate ( ) ; slicePred . addToColumn_names ( ByteBuffer . wrap ( colName ) ) ; return slicePred ; } | Create a SlicePredicate that selects a single column . | 57 | 12 |
17,597 | static SlicePredicate slicePredicateColNames ( Collection < byte [ ] > colNames ) { SlicePredicate slicePred = new SlicePredicate ( ) ; for ( byte [ ] colName : colNames ) { slicePred . addToColumn_names ( ByteBuffer . wrap ( colName ) ) ; } return slicePred ; } | Create a SlicePredicate that selects the given column names . | 73 | 13 |
17,598 | public Calendar getTime ( String propName ) { assert propName . endsWith ( "Time" ) ; if ( ! m_properties . containsKey ( propName ) ) { return null ; } Calendar calendar = new GregorianCalendar ( Utils . UTC_TIMEZONE ) ; calendar . setTimeInMillis ( Long . parseLong ( m_properties . get ( propName ) ) ) ; return calendar ; } | Get the value of a time property as a Calendar value . If the given property has not been set or is not a time value null is returned . | 89 | 30 |
17,599 | public UNode toDoc ( ) { UNode rootNode = UNode . createMapNode ( m_taskID , "task" ) ; for ( String name : m_properties . keySet ( ) ) { String value = m_properties . get ( name ) ; if ( name . endsWith ( "Time" ) ) { rootNode . addValueNode ( name , formatTimestamp ( value ) ) ; } else { rootNode . addValueNode ( name , value ) ; } } return rootNode ; } | Serialize this task record into a UNode tree . The root UNode is returned which is a map containing one child value node for each TaskRecord property . The map s name is the task ID with a tag name of task . Timestamp values are formatted into friendly display format . | 109 | 57 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.