idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
11,200
protected static void sort ( double [ ] d , double [ ] e , DenseMatrix V ) { int i = 0 ; int n = d . length ; double [ ] temp = new double [ n ] ; for ( int j = 1 ; j < n ; j ++ ) { double real = d [ j ] ; double img = e [ j ] ; for ( int k = 0 ; k < n ; k ++ ) { temp [ k ] = V . get ( k , j ) ; } for ( i = j - 1 ; i >= 0 ; i -- ) { if ( d [ i ] >= d [ j ] ) { break ; } d [ i + 1 ] = d [ i ] ; e [ i + 1 ] = e [ i ] ; for ( int k = 0 ; k < n ; k ++ ) { V . set ( k , i + 1 , V . get ( k , i ) ) ; } } d [ i + 1 ] = real ; e [ i + 1 ] = img ; for ( int k = 0 ; k < n ; k ++ ) { V . set ( k , i + 1 , temp [ k ] ) ; } } }
Sort eigenvalues and eigenvectors .
11,201
public double rand ( ) { if ( k - Math . floor ( k ) != 0.0 ) { throw new IllegalArgumentException ( "Gamma random number generator support only integer shape parameter." ) ; } double r = 0.0 ; for ( int i = 0 ; i < k ; i ++ ) { r += Math . log ( Math . random ( ) ) ; } r *= - theta ; return r ; }
Only support shape parameter k of integer .
11,202
private void initCanvas ( ) { GraphicsEnvironment ge = GraphicsEnvironment . getLocalGraphicsEnvironment ( ) ; if ( ge . isHeadless ( ) ) { setPreferredSize ( new Dimension ( 1600 , 1200 ) ) ; } setLayout ( new BorderLayout ( ) ) ; canvas = new MathCanvas ( ) ; add ( canvas , BorderLayout . CENTER ) ; initContextMenauAndToolBar ( ) ; }
Initialize the canvas .
11,203
public void save ( File file ) throws IOException { BufferedImage bi = new BufferedImage ( canvas . getWidth ( ) , canvas . getHeight ( ) , BufferedImage . TYPE_INT_ARGB ) ; Graphics2D g2d = bi . createGraphics ( ) ; canvas . print ( g2d ) ; ImageIO . write ( bi , FileChooser . getExtension ( file ) , file ) ; }
Exports the plot to an image file .
11,204
public void reset ( ) { base . reset ( ) ; graphics . projection . reset ( ) ; baseGrid . setBase ( base ) ; if ( graphics . projection instanceof Projection3D ) { ( ( Projection3D ) graphics . projection ) . setDefaultView ( ) ; } canvas . repaint ( ) ; }
Resets the plot .
11,205
private void initBase ( double [ ] lowerBound , double [ ] upperBound , boolean extendBound ) { base = new Base ( lowerBound , upperBound , extendBound ) ; backupBase = base ; baseGrid = new BaseGrid ( base ) ; }
Initialize a coordinate base .
11,206
public void add ( Plot p ) { shapes . add ( p ) ; JComponent [ ] tb = p . getToolBar ( ) ; if ( tb != null ) { toolbar . addSeparator ( ) ; for ( JComponent comp : tb ) { toolbar . add ( comp ) ; } } repaint ( ) ; }
Add a graphical shape to the canvas .
11,207
public void remove ( Plot p ) { shapes . remove ( p ) ; JComponent [ ] tb = p . getToolBar ( ) ; if ( tb != null ) { for ( JComponent comp : tb ) { toolbar . remove ( comp ) ; } } repaint ( ) ; }
Remove a graphical shape from the canvas .
11,208
public void point ( char legend , Color color , double ... coord ) { add ( new Point ( legend , color , coord ) ) ; }
Adds a point to this canvas .
11,209
public LinePlot line ( double [ ] y , Line . Style style ) { return line ( null , y , style ) ; }
Add a poly line plot of given data into the current canvas .
11,210
public StaircasePlot staircase ( String id , double [ ] [ ] data , Color color ) { if ( data [ 0 ] . length != 2 && data [ 0 ] . length != 3 ) { throw new IllegalArgumentException ( "Invalid data dimension: " + data [ 0 ] . length ) ; } StaircasePlot plot = new StaircasePlot ( data ) ; plot . setID ( id ) ; plot . setColor ( color ) ; add ( plot ) ; return plot ; }
Adds a staircase line plot to this canvas .
11,211
public Grid grid ( double [ ] [ ] [ ] data ) { if ( base . dimension != 2 ) { throw new IllegalArgumentException ( "Grid can be only painted in a 2D canvas. Try surface() for 3D grid." ) ; } Grid grid = new Grid ( data ) ; add ( grid ) ; return grid ; }
Adds a 2D grid plot to the canvas .
11,212
public static PlotCanvas screeplot ( PCA pca ) { int n = pca . getVarianceProportion ( ) . length ; double [ ] lowerBound = { 0 , 0.0 } ; double [ ] upperBound = { n + 1 , 1.0 } ; PlotCanvas canvas = new PlotCanvas ( lowerBound , upperBound , false ) ; canvas . setAxisLabels ( "Principal Component" , "Proportion of Variance" ) ; String [ ] labels = new String [ n ] ; double [ ] x = new double [ n ] ; double [ ] [ ] data = new double [ n ] [ 2 ] ; double [ ] [ ] data2 = new double [ n ] [ 2 ] ; for ( int i = 0 ; i < n ; i ++ ) { labels [ i ] = "PC" + ( i + 1 ) ; x [ i ] = i + 1 ; data [ i ] [ 0 ] = x [ i ] ; data [ i ] [ 1 ] = pca . getVarianceProportion ( ) [ i ] ; data2 [ i ] [ 0 ] = x [ i ] ; data2 [ i ] [ 1 ] = pca . getCumulativeVarianceProportion ( ) [ i ] ; } LinePlot plot = new LinePlot ( data ) ; plot . setID ( "Variance" ) ; plot . setColor ( Color . RED ) ; plot . setLegend ( '@' ) ; canvas . add ( plot ) ; canvas . getAxis ( 0 ) . addLabel ( labels , x ) ; LinePlot plot2 = new LinePlot ( data2 ) ; plot2 . setID ( "Cumulative Variance" ) ; plot2 . setColor ( Color . BLUE ) ; plot2 . setLegend ( '@' ) ; canvas . add ( plot2 ) ; return canvas ; }
Create a scree plot for PCA .
11,213
public AttributeVector response ( ) { double [ ] y = new double [ data . size ( ) ] ; for ( int i = 0 ; i < y . length ; i ++ ) { y [ i ] = data . get ( i ) . y ; } return new AttributeVector ( response , y ) ; }
Returns the response attribute vector . null means no response variable in this dataset .
11,214
public void setOmega ( double omega ) { this . omega = omega ; this . constant = 2 * Math . sqrt ( Math . pow ( 2 , ( 1 / omega ) ) - 1 ) / sigma ; }
Set the omega parameter .
11,215
public void setSigma ( double sigma ) { this . sigma = sigma ; this . constant = 2 * Math . sqrt ( Math . pow ( 2 , ( 1 / omega ) ) - 1 ) / sigma ; }
Set the sigma parameter .
11,216
protected PlotCanvas paintOnCanvas ( double [ ] [ ] data , int [ ] label ) { PlotCanvas canvas = ScatterPlot . plot ( data , pointLegend ) ; for ( int i = 0 ; i < data . length ; i ++ ) { canvas . point ( pointLegend , Palette . COLORS [ label [ i ] ] , data [ i ] ) ; } return canvas ; }
paint given data with label on canvas
11,217
double error ( int [ ] x , int [ ] y ) { int e = 0 ; for ( int i = 0 ; i < x . length ; i ++ ) { if ( x [ i ] != y [ i ] ) { e ++ ; } } return ( double ) e / x . length ; }
Returns the error rate .
11,218
public double [ ] feature ( T [ ] x ) { double [ ] bag = new double [ features . size ( ) ] ; if ( binary ) { for ( T word : x ) { Integer f = features . get ( word ) ; if ( f != null ) { bag [ f ] = 1.0 ; } } } else { for ( T word : x ) { Integer f = features . get ( word ) ; if ( f != null ) { bag [ f ] ++ ; } } } return bag ; }
Returns the bag - of - words features of a document . The features are real - valued in convenience of most learning algorithms although they take only integer or binary values .
11,219
public static double d ( int [ ] x1 , int [ ] x2 ) { int n1 = x1 . length ; int n2 = x2 . length ; double [ ] [ ] table = new double [ 2 ] [ n2 + 1 ] ; table [ 0 ] [ 0 ] = 0 ; for ( int i = 1 ; i <= n2 ; i ++ ) { table [ 0 ] [ i ] = Double . POSITIVE_INFINITY ; } for ( int i = 1 ; i <= n1 ; i ++ ) { table [ 1 ] [ 0 ] = Double . POSITIVE_INFINITY ; for ( int j = 1 ; j <= n2 ; j ++ ) { double cost = Math . abs ( x1 [ i - 1 ] - x2 [ j - 1 ] ) ; double min = table [ 0 ] [ j - 1 ] ; if ( min > table [ 0 ] [ j ] ) { min = table [ 0 ] [ j ] ; } if ( min > table [ 1 ] [ j - 1 ] ) { min = table [ 1 ] [ j - 1 ] ; } table [ 1 ] [ j ] = cost + min ; } double [ ] swap = table [ 0 ] ; table [ 0 ] = table [ 1 ] ; table [ 1 ] = swap ; } return table [ 0 ] [ n2 ] ; }
Dynamic time warping without path constraints .
11,220
public double [ ] rand ( ) { double [ ] spt = new double [ mu . length ] ; for ( int i = 0 ; i < mu . length ; i ++ ) { double u , v , q ; do { u = Math . random ( ) ; v = 1.7156 * ( Math . random ( ) - 0.5 ) ; double x = u - 0.449871 ; double y = Math . abs ( v ) + 0.386595 ; q = x * x + y * ( 0.19600 * y - 0.25472 * x ) ; } while ( q > 0.27597 && ( q > 0.27846 || v * v > - 4 * Math . log ( u ) * u * u ) ) ; spt [ i ] = v / u ; } double [ ] pt = new double [ sigmaL . nrows ( ) ] ; for ( int i = 0 ; i < pt . length ; i ++ ) { for ( int j = 0 ; j <= i ; j ++ ) { pt [ i ] += sigmaL . get ( i , j ) * spt [ j ] ; } } Math . plus ( pt , mu ) ; return pt ; }
Generate a random multivariate Gaussian sample .
11,221
public AttributeDataset parse ( String name , InputStream stream ) throws IOException , ParseException { BufferedReader reader = new BufferedReader ( new InputStreamReader ( stream ) ) ; String line = reader . readLine ( ) ; if ( line == null ) { throw new IOException ( "Empty data source." ) ; } String [ ] tokens = line . split ( "\t" , - 1 ) ; int p = ( tokens . length - 2 ) / 2 ; line = reader . readLine ( ) ; if ( line == null ) { throw new IOException ( "Premature end of file." ) ; } String [ ] samples = line . split ( "\t" , - 1 ) ; if ( samples . length != tokens . length - 1 ) { throw new IOException ( "Invalid sample description header." ) ; } Attribute [ ] attributes = new Attribute [ p ] ; for ( int i = 0 ; i < p ; i ++ ) { attributes [ i ] = new NumericAttribute ( tokens [ 2 * i + 2 ] , samples [ 2 * i + 1 ] ) ; } line = reader . readLine ( ) ; if ( line == null ) { throw new IOException ( "Premature end of file." ) ; } int n = Integer . parseInt ( line ) ; if ( n <= 0 ) { throw new IOException ( "Invalid number of rows: " + n ) ; } AttributeDataset data = new AttributeDataset ( name , attributes ) ; for ( int i = 0 ; i < n ; i ++ ) { line = reader . readLine ( ) ; if ( line == null ) { throw new IOException ( "Premature end of file." ) ; } tokens = line . split ( "\t" , - 1 ) ; if ( tokens . length != samples . length + 1 ) { throw new IOException ( String . format ( "Invalid number of elements of line %d: %d" , i + 4 , tokens . length ) ) ; } double [ ] x = new double [ p ] ; for ( int j = 0 ; j < p ; j ++ ) { x [ j ] = Double . valueOf ( tokens [ 2 * j + 2 ] ) ; } AttributeDataset . Row datum = data . add ( x ) ; datum . name = tokens [ 1 ] ; datum . description = tokens [ 0 ] ; } reader . close ( ) ; return data ; }
Parse a RES dataset from an input stream .
11,222
public void setPageSize ( int s ) { if ( s <= 0 ) { throw new IllegalArgumentException ( "non-positive page size: " + s ) ; } if ( s == pageSize ) { return ; } int oldPageSize = pageSize ; pageSize = s ; page = ( oldPageSize * page ) / pageSize ; fireTableDataChanged ( ) ; }
Sets the page size .
11,223
public void add ( E datum ) { if ( root == null ) { root = new Node ( count ++ , datum ) ; } else { root . add ( datum ) ; } }
Add a datum into the BK - tree .
11,224
private void search ( Node node , E q , int k , List < Neighbor < E , E > > neighbors ) { int d = ( int ) distance . d ( node . object , q ) ; if ( d <= k ) { if ( node . object != q || ! identicalExcluded ) { neighbors . add ( new Neighbor < > ( node . object , node . object , node . index , d ) ) ; } } if ( node . children != null ) { int start = Math . max ( 1 , d - k ) ; int end = Math . min ( node . children . size ( ) , d + k + 1 ) ; for ( int i = start ; i < end ; i ++ ) { Node child = node . children . get ( i ) ; if ( child != null ) { search ( child , q , k , neighbors ) ; } } } }
Do a range search in the given subtree .
11,225
private List < String > getConcepts ( Concept c ) { List < String > keywords = new ArrayList < > ( ) ; while ( c != null ) { if ( c . synset != null ) { keywords . addAll ( c . synset ) ; } if ( c . children != null ) { for ( Concept child : c . children ) { keywords . addAll ( getConcepts ( child ) ) ; } } } return keywords ; }
Returns all named concepts from this taxonomy
11,226
public void transform ( double [ ] a ) { int n = a . length ; if ( ! Math . isPower2 ( n ) ) { throw new IllegalArgumentException ( "The data vector size is not a power of 2." ) ; } if ( n < ncof ) { throw new IllegalArgumentException ( "The data vector size is less than wavelet coefficient size." ) ; } for ( int nn = n ; nn >= ncof ; nn >>= 1 ) { forward ( a , nn ) ; } }
Discrete wavelet transform .
11,227
public void inverse ( double [ ] a ) { int n = a . length ; if ( ! Math . isPower2 ( n ) ) { throw new IllegalArgumentException ( "The data vector size is not a power of 2." ) ; } if ( n < ncof ) { throw new IllegalArgumentException ( "The data vector size is less than wavelet coefficient size." ) ; } int start = n >> ( int ) Math . floor ( Math . log2 ( n / ( ncof - 1 ) ) ) ; for ( int nn = start ; nn <= n ; nn <<= 1 ) { backward ( a , nn ) ; } }
Inverse discrete wavelet transform .
11,228
private int firstVowel ( String word , int last ) { int i = 0 ; if ( ( i < last ) && ( ! ( vowel ( word . charAt ( i ) , 'a' ) ) ) ) { i ++ ; } if ( i != 0 ) { while ( ( i < last ) && ( ! ( vowel ( word . charAt ( i ) , word . charAt ( i - 1 ) ) ) ) ) { i ++ ; } } if ( i < last ) { return i ; } return last ; }
Checks lowercase word for position of the first vowel
11,229
private String stripPrefixes ( String word ) { String [ ] prefixes = { "kilo" , "micro" , "milli" , "intra" , "ultra" , "mega" , "nano" , "pico" , "pseudo" } ; int last = prefixes . length ; for ( int i = 0 ; i < last ; i ++ ) { if ( ( word . startsWith ( prefixes [ i ] ) ) && ( word . length ( ) > prefixes [ i ] . length ( ) ) ) { word = word . substring ( prefixes [ i ] . length ( ) ) ; return word ; } } return word ; }
Removes prefixes so that suffix removal can commence .
11,230
private String cleanup ( String word ) { int last = word . length ( ) ; String temp = "" ; for ( int i = 0 ; i < last ; i ++ ) { if ( ( word . charAt ( i ) >= 'a' ) & ( word . charAt ( i ) <= 'z' ) ) { temp += word . charAt ( i ) ; } } return temp ; }
Remove all non letter or digit characters from word
11,231
public static PennTreebankPOS tag ( String word ) { for ( int i = 0 ; i < REGEX . length ; i ++ ) { if ( REGEX [ i ] . matcher ( word ) . matches ( ) ) { return REGEX_POS [ i ] ; } } return null ; }
Returns the POS tag of a given word based on the regular expression over word string . Returns null if no match .
11,232
public AttributeDataset range ( int from , int to ) { AttributeDataset sub = new AttributeDataset ( name + '[' + from + ", " + to + ']' , attributes , response ) ; sub . description = description ; for ( int i = from ; i < to ; i ++ ) { sub . add ( get ( i ) ) ; } return sub ; }
Returns the rows in the given range [ from to ) .
11,233
public AttributeDataset columns ( String ... cols ) { Attribute [ ] attrs = new Attribute [ cols . length ] ; int [ ] index = new int [ cols . length ] ; for ( int k = 0 ; k < cols . length ; k ++ ) { for ( int j = 0 ; j < attributes . length ; j ++ ) { if ( attributes [ j ] . getName ( ) . equals ( cols [ k ] ) ) { index [ k ] = j ; attrs [ k ] = attributes [ j ] ; break ; } } if ( attrs [ k ] == null ) { throw new IllegalArgumentException ( "Unknown column: " + cols [ k ] ) ; } } AttributeDataset sub = new AttributeDataset ( name , attrs , response ) ; for ( Datum < double [ ] > datum : data ) { double [ ] x = new double [ index . length ] ; for ( int i = 0 ; i < x . length ; i ++ ) { x [ i ] = datum . x [ index [ i ] ] ; } Row row = response == null ? sub . add ( x ) : sub . add ( x , datum . y ) ; row . name = datum . name ; row . weight = datum . weight ; row . description = datum . description ; row . timestamp = datum . timestamp ; } return sub ; }
Returns a dataset with selected columns .
11,234
public AttributeDataset remove ( String ... cols ) { HashSet < String > remains = new HashSet < > ( ) ; for ( Attribute attr : attributes ) { remains . add ( attr . getName ( ) ) ; } for ( String col : cols ) { remains . remove ( col ) ; } Attribute [ ] attrs = new Attribute [ remains . size ( ) ] ; int [ ] index = new int [ remains . size ( ) ] ; for ( int j = 0 , i = 0 ; j < attributes . length ; j ++ ) { if ( remains . contains ( attributes [ j ] . getName ( ) ) ) { index [ i ] = j ; attrs [ i ] = attributes [ j ] ; i ++ ; } } AttributeDataset sub = new AttributeDataset ( name , attrs , response ) ; for ( Datum < double [ ] > datum : data ) { double [ ] x = new double [ index . length ] ; for ( int i = 0 ; i < x . length ; i ++ ) { x [ i ] = datum . x [ index [ i ] ] ; } Row row = response == null ? sub . add ( x ) : sub . add ( x , datum . y ) ; row . name = datum . name ; row . weight = datum . weight ; row . description = datum . description ; row . timestamp = datum . timestamp ; } return sub ; }
Returns a new dataset without given columns .
11,235
public double det ( ) { if ( au == null ) { decompose ( ) ; } double dd = d ; for ( int i = 0 ; i < n ; i ++ ) { dd *= au [ i ] [ 0 ] ; } return dd ; }
Returns the matrix determinant .
11,236
public void decompose ( ) { final double TINY = 1.0e-40 ; int mm = m1 + m2 + 1 ; index = new int [ n ] ; au = new double [ n ] [ mm ] ; al = new double [ n ] [ m1 ] ; for ( int i = 0 ; i < A . length ; i ++ ) { System . arraycopy ( A [ i ] , 0 , au [ i ] , 0 , A [ i ] . length ) ; } double dum ; int l = m1 ; for ( int i = 0 ; i < m1 ; i ++ ) { for ( int j = m1 - i ; j < mm ; j ++ ) { au [ i ] [ j - l ] = au [ i ] [ j ] ; } l -- ; for ( int j = mm - l - 1 ; j < mm ; j ++ ) au [ i ] [ j ] = 0.0 ; } d = 1.0 ; l = m1 ; for ( int k = 0 ; k < n ; k ++ ) { dum = au [ k ] [ 0 ] ; int i = k ; if ( l < n ) { l ++ ; } for ( int j = k + 1 ; j < l ; j ++ ) { if ( Math . abs ( au [ j ] [ 0 ] ) > Math . abs ( dum ) ) { dum = au [ j ] [ 0 ] ; i = j ; } } index [ k ] = i + 1 ; if ( dum == 0.0 ) { au [ k ] [ 0 ] = TINY ; } if ( i != k ) { d = - d ; double [ ] swap = au [ k ] ; au [ k ] = au [ i ] ; au [ i ] = swap ; } for ( i = k + 1 ; i < l ; i ++ ) { dum = au [ i ] [ 0 ] / au [ k ] [ 0 ] ; al [ k ] [ i - k - 1 ] = dum ; for ( int j = 1 ; j < mm ; j ++ ) { au [ i ] [ j - 1 ] = au [ i ] [ j ] - dum * au [ k ] [ j ] ; } au [ i ] [ mm - 1 ] = 0.0 ; } } }
LU decomposition .
11,237
public void improve ( double [ ] b , double [ ] x ) { if ( b . length != n || x . length != n ) { throw new IllegalArgumentException ( String . format ( "Row dimensions do not agree: A is %d x %d, but b is %d x 1 and x is %d x 1" , n , n , b . length , x . length ) ) ; } double [ ] r = b . clone ( ) ; axpy ( x , r , - 1.0 ) ; solve ( r , r ) ; for ( int i = 0 ; i < n ; i ++ ) { x [ i ] -= r [ i ] ; } }
Iteratively improve a solution to linear equations .
11,238
public void onScrolled ( ) { final int lastPosition = getLayoutManager ( ) . findLastVisibleItemPosition ( ) ; final int firstPosition = getLayoutManager ( ) . findFirstVisibleItemPosition ( ) ; int lastCardIndex = - 1 ; int firstCardIndex = - 1 ; int position = lastPosition ; for ( int i = lastPosition ; i >= firstPosition ; i -- ) { lastCardIndex = mGroupBasicAdapter . findCardIdxFor ( i ) ; if ( lastCardIndex >= 0 ) { position = i ; break ; } } for ( int i = firstCardIndex ; i <= lastPosition ; i ++ ) { firstCardIndex = mGroupBasicAdapter . findCardIdxFor ( i ) ; if ( firstCardIndex >= 0 ) { break ; } } if ( lastCardIndex < 0 || firstCardIndex < 0 ) return ; final CardLoadSupport loadSupport = getService ( CardLoadSupport . class ) ; if ( loadSupport == null ) return ; List < Card > cards = mGroupBasicAdapter . getGroups ( ) ; Card current = cards . get ( lastCardIndex ) ; Pair < Range < Integer > , Card > pair = mGroupBasicAdapter . getCardRange ( lastCardIndex ) ; if ( pair != null && position >= pair . first . getUpper ( ) - mPreLoadNumber ) { if ( ! TextUtils . isEmpty ( current . load ) && current . loaded ) { if ( current . loadMore ) { loadSupport . loadMore ( current ) ; loadSupport . reactiveDoLoadMore ( current ) ; } return ; } } boolean loadedMore = false ; for ( int i = firstCardIndex ; i < Math . min ( lastCardIndex + mPreLoadNumber , cards . size ( ) ) ; i ++ ) { Card c = cards . get ( i ) ; if ( ! TextUtils . isEmpty ( c . load ) && ! c . loaded ) { if ( c . loadMore && ! loadedMore ) { loadSupport . loadMore ( c ) ; loadSupport . reactiveDoLoadMore ( c ) ; loadedMore = true ; } else { loadSupport . doLoad ( c ) ; loadSupport . reactiveDoLoad ( c ) ; } c . loaded = true ; } } if ( mEnableAutoLoadMore && mGroupBasicAdapter . getItemCount ( ) - position < mPreLoadNumber ) { loadMoreCard ( ) ; } }
Call this method in RecyclerView s scroll listener . Would trigger the preload of card s data .
11,239
protected void removeBatchBy ( int removeIdx ) { if ( mGroupBasicAdapter != null ) { Pair < Range < Integer > , Card > cardPair = mGroupBasicAdapter . getCardRange ( removeIdx ) ; if ( cardPair != null ) { removeBatchBy ( cardPair . second ) ; } } }
Remove all cells in a card with target index
11,240
protected void removeBatchBy ( Card group ) { VirtualLayoutManager layoutManager = getLayoutManager ( ) ; if ( group != null && mGroupBasicAdapter != null && layoutManager != null ) { int cardIdx = mGroupBasicAdapter . findCardIdxForCard ( group ) ; List < LayoutHelper > layoutHelpers = layoutManager . getLayoutHelpers ( ) ; LayoutHelper emptyLayoutHelper = null ; int removeItemCount = 0 ; if ( layoutHelpers != null && cardIdx >= 0 && cardIdx < layoutHelpers . size ( ) ) { for ( int i = 0 , size = layoutHelpers . size ( ) ; i < size ; i ++ ) { LayoutHelper layoutHelper = layoutHelpers . get ( i ) ; int start = layoutHelper . getRange ( ) . getLower ( ) ; int end = layoutHelper . getRange ( ) . getUpper ( ) ; if ( i < cardIdx ) { } else if ( i == cardIdx ) { removeItemCount = layoutHelper . getItemCount ( ) ; emptyLayoutHelper = layoutHelper ; } else { layoutHelper . setRange ( start - removeItemCount , end - removeItemCount ) ; } } if ( emptyLayoutHelper != null ) { final List < LayoutHelper > newLayoutHelpers = new LinkedList < > ( layoutHelpers ) ; newLayoutHelpers . remove ( emptyLayoutHelper ) ; layoutManager . setLayoutHelpers ( newLayoutHelpers ) ; } mGroupBasicAdapter . removeComponents ( group ) ; } } }
Remove all cells in a card .
11,241
public void replace ( BaseCell oldOne , BaseCell newOne ) { VirtualLayoutManager layoutManager = getLayoutManager ( ) ; if ( oldOne != null && newOne != null && mGroupBasicAdapter != null && layoutManager != null ) { int replacePosition = mGroupBasicAdapter . getPositionByItem ( oldOne ) ; if ( replacePosition >= 0 ) { int cardIdx = mGroupBasicAdapter . findCardIdxFor ( replacePosition ) ; Card card = mGroupBasicAdapter . getCardRange ( cardIdx ) . second ; card . replaceCell ( oldOne , newOne ) ; mGroupBasicAdapter . replaceComponent ( Arrays . asList ( oldOne ) , Arrays . asList ( newOne ) ) ; } } }
Replace cell one by one .
11,242
public void replace ( Card parent , List < BaseCell > cells ) { VirtualLayoutManager layoutManager = getLayoutManager ( ) ; if ( parent != null && cells != null && cells . size ( ) > 0 && mGroupBasicAdapter != null && layoutManager != null ) { Card card = parent ; List < BaseCell > oldChildren = new ArrayList < > ( parent . getCells ( ) ) ; if ( oldChildren . size ( ) == cells . size ( ) ) { card . setCells ( cells ) ; mGroupBasicAdapter . replaceComponent ( oldChildren , cells ) ; } else { List < LayoutHelper > layoutHelpers = layoutManager . getLayoutHelpers ( ) ; int cardIdx = mGroupBasicAdapter . findCardIdxForCard ( parent ) ; int diff = 0 ; if ( layoutHelpers != null && cardIdx >= 0 && cardIdx < layoutHelpers . size ( ) ) { for ( int i = 0 , size = layoutHelpers . size ( ) ; i < size ; i ++ ) { LayoutHelper layoutHelper = layoutHelpers . get ( i ) ; int start = layoutHelper . getRange ( ) . getLower ( ) ; int end = layoutHelper . getRange ( ) . getUpper ( ) ; if ( i < cardIdx ) { } else if ( i == cardIdx ) { diff = cells . size ( ) - layoutHelper . getItemCount ( ) ; layoutHelper . setItemCount ( cells . size ( ) ) ; layoutHelper . setRange ( start , end + diff ) ; } else { layoutHelper . setRange ( start + diff , end + diff ) ; } } card . setCells ( cells ) ; mGroupBasicAdapter . replaceComponent ( oldChildren , cells ) ; } } } }
Replace parent card s children . Cells size should be equal with parent s children size .
11,243
public void replace ( Card oldOne , Card newOne ) { VirtualLayoutManager layoutManager = getLayoutManager ( ) ; if ( oldOne != null && newOne != null && mGroupBasicAdapter != null && layoutManager != null ) { List < LayoutHelper > layoutHelpers = layoutManager . getLayoutHelpers ( ) ; int cardIdx = mGroupBasicAdapter . findCardIdxForCard ( oldOne ) ; if ( layoutHelpers != null && cardIdx >= 0 && cardIdx < layoutHelpers . size ( ) ) { final List < LayoutHelper > newLayoutHelpers = new LinkedList < > ( ) ; for ( int i = 0 , size = layoutHelpers . size ( ) ; i < size ; i ++ ) { LayoutHelper layoutHelper = layoutHelpers . get ( i ) ; if ( i == cardIdx ) { layoutHelper = newOne . getLayoutHelper ( ) ; } newLayoutHelpers . add ( layoutHelper ) ; } layoutManager . setLayoutHelpers ( newLayoutHelpers ) ; mGroupBasicAdapter . replaceComponent ( oldOne , newOne ) ; } } }
Replace card one by one . New one s children size should be equal with old one s children size .
11,244
public void unbindView ( ) { if ( mContentView != null ) { this . mContentView . setAdapter ( null ) ; this . mContentView . setLayoutManager ( null ) ; this . mContentView = null ; } }
Unbind the adapter and layoutManger to recyclerView . And also set null to them .
11,245
public Consumer < T > asOriginalDataConsumer ( ) { return new Consumer < T > ( ) { public void accept ( T t ) throws Exception { setData ( t ) ; } } ; }
Make engine as a consumer to accept origin data from user
11,246
public Consumer < List < C > > asParsedDataConsumer ( ) { return new Consumer < List < C > > ( ) { public void accept ( List < C > cs ) throws Exception { setData ( cs ) ; } } ; }
Make engine as a consumer to accept parsed data from user
11,247
public void removeData ( int position ) { Preconditions . checkState ( mGroupBasicAdapter != null , "Must call bindView() first" ) ; this . mGroupBasicAdapter . removeGroup ( position ) ; }
Remove a card at target card position . It cause full screen item s rebinding be careful .
11,248
public void removeData ( C data ) { Preconditions . checkState ( mGroupBasicAdapter != null , "Must call bindView() first" ) ; this . mGroupBasicAdapter . removeGroup ( data ) ; }
Remove the target card from list . It cause full screen item s rebinding be careful .
11,249
public Range < Integer > getCardRange ( String id ) { Preconditions . checkState ( mGroupBasicAdapter != null , "Must call bindView() first" ) ; return this . mGroupBasicAdapter . getCardRange ( id ) ; }
Get card range by id
11,250
public Consumer < UpdateCellOp > asUpdateCellConsumer ( ) { return new Consumer < UpdateCellOp > ( ) { public void accept ( UpdateCellOp op ) throws Exception { update ( op . getArg1 ( ) ) ; } } ; }
Make engine as a consumer to accept cell data change
11,251
public void reset ( ) { methodMap . clear ( ) ; postBindMap . clear ( ) ; postUnBindMap . clear ( ) ; cellInitedMap . clear ( ) ; cellFlareIdMap . clear ( ) ; mvResolver . reset ( ) ; }
FIXME sholud be called after original component s postUnBind method excuted
11,252
private int computeFirstCompletelyVisibleItemPositionForScrolledX ( float [ ] starts ) { if ( lSCell == null || starts == null || starts . length <= 0 ) { return 0 ; } for ( int i = 0 ; i < starts . length ; i ++ ) { if ( starts [ i ] >= lSCell . currentDistance ) { return i ; } } return starts . length - 1 ; }
Find the first completely visible position .
11,253
public void removeComponent ( int position ) { if ( mData != null && position >= 0 && position < mData . size ( ) ) { removeComponent ( mData . get ( position ) ) ; } }
!!! Do not call this method directly . It s not designed for users . remove a component
11,254
public void removeComponent ( BaseCell component ) { int removePosition = getPositionByItem ( component ) ; if ( mData != null && component != null && removePosition >= 0 ) { if ( mCards != null ) { List < Pair < Range < Integer > , Card > > newCards = new ArrayList < > ( ) ; for ( int i = 0 , size = mCards . size ( ) ; i < size ; i ++ ) { Pair < Range < Integer > , Card > pair = mCards . get ( i ) ; int start = pair . first . getLower ( ) ; int end = pair . first . getUpper ( ) ; if ( end < removePosition ) { newCards . add ( pair ) ; } else if ( start <= removePosition && removePosition < end ) { int itemCount = end - start - 1 ; if ( itemCount > 0 ) { Pair < Range < Integer > , Card > newPair = new Pair < > ( Range . create ( start , end - 1 ) , pair . second ) ; newCards . add ( newPair ) ; } } else if ( removePosition <= start ) { Pair < Range < Integer > , Card > newPair = new Pair < > ( Range . create ( start - 1 , end - 1 ) , pair . second ) ; newCards . add ( newPair ) ; } } component . removed ( ) ; mCards . clear ( ) ; mCards . addAll ( newCards ) ; mData . remove ( component ) ; notifyItemRemoved ( removePosition ) ; int last = mLayoutManager . findLastVisibleItemPosition ( ) ; notifyItemRangeChanged ( removePosition , last - removePosition ) ; } } }
!!! Do not call this method directly . It s not designed for users .
11,255
public < V extends View > void registerCell ( String type , final Class < V > viewClz ) { if ( viewHolderMap . get ( type ) == null ) { mDefaultCellBinderResolver . register ( type , new BaseCellBinder < > ( viewClz , mMVHelper ) ) ; } else { mDefaultCellBinderResolver . register ( type , new BaseCellBinder < ViewHolderCreator . ViewHolder , V > ( viewHolderMap . get ( type ) , mMVHelper ) ) ; } mMVHelper . resolver ( ) . register ( type , viewClz ) ; }
register cell with custom view class the model of cell is provided with default type
11,256
public void registerCard ( String type , Class < ? extends Card > cardClz ) { mDefaultCardResolver . register ( type , cardClz ) ; }
register card with type and card class
11,257
public void onClick ( View targetView , BaseCell cell , int eventType ) { if ( cell instanceof Cell ) { onClick ( targetView , ( Cell ) cell , eventType ) ; } else { onClick ( targetView , cell , eventType , null ) ; } }
Handler click event on item
11,258
public void bind ( C data ) { if ( itemView == null || controller == null ) { return ; } this . controller . mountView ( data , itemView ) ; this . data = data ; }
Bind data to inner view
11,259
public void unbind ( ) { if ( itemView == null || controller == null ) { return ; } if ( data != null ) { this . controller . unmountView ( data , itemView ) ; } }
unbind the data make the view re - usable
11,260
public void setTag ( int key , Object value ) { if ( mTag == null ) { mTag = new SparseArray < > ( ) ; } mTag . put ( key , value ) ; }
bind a tag to baseCell
11,261
public static void init ( final Context context , IInnerImageSetter innerImageSetter , Class < ? extends ImageView > imageClazz ) { if ( sInitialized ) { return ; } Preconditions . checkArgument ( context != null , "context should not be null" ) ; Preconditions . checkArgument ( innerImageSetter != null , "innerImageSetter should not be null" ) ; Preconditions . checkArgument ( imageClazz != null , "imageClazz should not be null" ) ; TangramViewMetrics . initWith ( context . getApplicationContext ( ) ) ; ImageUtils . sImageClass = imageClazz ; ImageUtils . setImageSetter ( innerImageSetter ) ; sInitialized = true ; }
init global Tangram environment .
11,262
public static ImageView createImageInstance ( Context context ) { if ( sImageClass != null ) { if ( imageViewConstructor == null ) { try { imageViewConstructor = sImageClass . getConstructor ( Context . class ) ; } catch ( NoSuchMethodException e ) { e . printStackTrace ( ) ; } } if ( imageViewConstructor != null ) { try { return ( ImageView ) imageViewConstructor . newInstance ( context ) ; } catch ( InstantiationException e ) { e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } catch ( InvocationTargetException e ) { e . printStackTrace ( ) ; } } } return null ; }
create a custom ImageView instance
11,263
private void setIndicatorMeasure ( View indicator , int width , int height , int margin ) { if ( indicator != null ) { ViewGroup . LayoutParams layoutParams = indicator . getLayoutParams ( ) ; layoutParams . width = width ; layoutParams . height = height ; if ( margin > 0 ) { if ( layoutParams instanceof FrameLayout . LayoutParams ) { FrameLayout . LayoutParams frameLayoutParams = ( FrameLayout . LayoutParams ) layoutParams ; frameLayoutParams . topMargin = margin ; } else if ( layoutParams instanceof LayoutParams ) { LayoutParams linearLayoutParams = ( LayoutParams ) layoutParams ; linearLayoutParams . topMargin = margin ; } } indicator . setLayoutParams ( layoutParams ) ; } }
Set indicator measure
11,264
public void appendArg ( String key , String value ) { if ( args != null ) { args . put ( key , value ) ; } }
Append arg to map
11,265
public Map < String , Map < String , Object > > getPropertyMetadataAndValuesAsMap ( ) { Map < String , Map < String , Object > > configMap = new HashMap < > ( ) ; for ( ConfigurationProperty property : this ) { Map < String , Object > mapValue = new HashMap < > ( ) ; mapValue . put ( "isSecure" , property . isSecure ( ) ) ; if ( property . isSecure ( ) ) { mapValue . put ( VALUE_KEY , property . getEncryptedValue ( ) ) ; } else { final String value = property . getConfigurationValue ( ) == null ? null : property . getConfigurationValue ( ) . getValue ( ) ; mapValue . put ( VALUE_KEY , value ) ; } mapValue . put ( "displayValue" , property . getDisplayValue ( ) ) ; configMap . put ( property . getConfigKeyName ( ) , mapValue ) ; } return configMap ; }
Used in erb
11,266
public boolean cancel ( int timeout , TimeUnit timeoutUnit ) throws InterruptedException { if ( isCanceled ( ) ) { return true ; } cancelLatch . countDown ( ) ; try { return doneLatch . await ( timeout , timeoutUnit ) ; } finally { new DefaultCurrentProcess ( ) . infanticide ( ) ; } }
Cancel build and wait for build session done
11,267
public Map < String , Object > toMap ( ) { HashMap < String , Object > map = new HashMap < > ( ) ; map . put ( "id" , id ) ; map . put ( "pipelineName" , pipelineName ) ; map . put ( "stageName" , stageName ) ; map . put ( "myCheckin" , myCheckin ) ; map . put ( "event" , event . toString ( ) ) ; return map ; }
Used for JSON serialization in Rails
11,268
public static String quoteArgument ( String argument ) { if ( QUOTED_STRING . matcher ( argument ) . matches ( ) || ! UNESCAPED_SPACE_OR_QUOTES . matcher ( argument ) . find ( ) ) { return argument ; } return String . format ( "\"%s\"" , DOUBLE_QUOTE . matcher ( argument ) . replaceAll ( Matcher . quoteReplacement ( "\\" ) + "$1" ) ) ; }
Surrounds a string with double quotes if it is not already surrounded by single or double quotes or if it contains unescaped spaces single quotes or double quotes . When surrounding with double quotes this method will only escape double quotes in the String .
11,269
public < T > void set ( Option < T > option , T value ) { findOption ( option ) . setValue ( value ) ; }
Finds matching option by option name and sets specified value
11,270
public < T > Option < T > findOption ( Option < T > option ) { for ( Option candidateOption : options ) { if ( candidateOption . hasSameNameAs ( option ) ) { return candidateOption ; } } throw new RuntimeException ( "You tried to set an unexpected option" ) ; }
Finds matching option by option name
11,271
public String getRevisionsBasedOnDependenciesForDebug ( CaseInsensitiveString pipelineName , final Integer targetIterationCount ) { CruiseConfig cruiseConfig = goConfigService . getCurrentConfig ( ) ; FanInGraph fanInGraph = new FanInGraph ( cruiseConfig , pipelineName , materialRepository , pipelineDao , systemEnvironment , materialConfigConverter ) ; final String [ ] iterationData = { null } ; fanInGraph . setFanInEventListener ( ( iterationCount , dependencyFanInNodes ) -> { if ( iterationCount == targetIterationCount ) { iterationData [ 0 ] = new GsonBuilder ( ) . setExclusionStrategies ( getGsonExclusionStrategy ( ) ) . create ( ) . toJson ( dependencyFanInNodes ) ; } } ) ; PipelineConfig pipelineConfig = goConfigService . pipelineConfigNamed ( pipelineName ) ; Materials materials = materialConfigConverter . toMaterials ( pipelineConfig . materialConfigs ( ) ) ; MaterialRevisions actualRevisions = new MaterialRevisions ( ) ; for ( Material material : materials ) { actualRevisions . addAll ( materialRepository . findLatestModification ( material ) ) ; } MaterialRevisions materialRevisions = fanInGraph . computeRevisions ( actualRevisions , pipelineTimeline ) ; if ( iterationData [ 0 ] == null ) { iterationData [ 0 ] = new GsonBuilder ( ) . setExclusionStrategies ( getGsonExclusionStrategy ( ) ) . create ( ) . toJson ( materialRevisions ) ; } return iterationData [ 0 ] ; }
This is for debugging purposes
11,272
public void saveModification ( MaterialInstance materialInstance , Modification modification ) { modification . setMaterialInstance ( materialInstance ) ; try { getHibernateTemplate ( ) . saveOrUpdate ( modification ) ; removeLatestCachedModification ( materialInstance , modification ) ; removeCachedModificationCountFor ( materialInstance ) ; removeCachedModificationsFor ( materialInstance ) ; } catch ( Exception e ) { String message = "Cannot save modification " + modification ; LOGGER . error ( message , e ) ; throw new RuntimeException ( message , e ) ; } }
Used in tests
11,273
public boolean ensurePipelineVisible ( CaseInsensitiveString pipelineToAdd ) { boolean modified = false ; for ( DashboardFilter f : viewFilters . filters ( ) ) { modified = modified || f . allowPipeline ( pipelineToAdd ) ; } return modified ; }
Allows pipeline to be visible to entire filter set ; generally used as an after - hook on pipeline creation .
11,274
void deleteAll ( ) { transactionTemplate . execute ( new TransactionCallbackWithoutResult ( ) { protected void doInTransactionWithoutResult ( TransactionStatus status ) { sessionFactory . getCurrentSession ( ) . createQuery ( "DELETE FROM VersionInfo" ) . executeUpdate ( ) ; } } ) ; }
used only in tests
11,275
public static DefaultGoApiResponse incompleteRequest ( String responseBody ) { DefaultGoApiResponse defaultGoApiResponse = new DefaultGoApiResponse ( 412 ) ; defaultGoApiResponse . setResponseBody ( responseBody ) ; return defaultGoApiResponse ; }
Creates an instance DefaultGoApiResponse which represents incomplete request with response code 412
11,276
public static DefaultGoApiResponse badRequest ( String responseBody ) { DefaultGoApiResponse defaultGoApiResponse = new DefaultGoApiResponse ( 400 ) ; defaultGoApiResponse . setResponseBody ( responseBody ) ; return defaultGoApiResponse ; }
Creates an instance DefaultGoApiResponse which represents bad request with response code 400
11,277
public static DefaultGoApiResponse error ( String responseBody ) { DefaultGoApiResponse defaultGoApiResponse = new DefaultGoApiResponse ( 500 ) ; defaultGoApiResponse . setResponseBody ( responseBody ) ; return defaultGoApiResponse ; }
Creates an instance DefaultGoApiResponse which represents error request with response code 500
11,278
public static DefaultGoApiResponse success ( String responseBody ) { DefaultGoApiResponse defaultGoApiResponse = new DefaultGoApiResponse ( SUCCESS_RESPONSE_CODE ) ; defaultGoApiResponse . setResponseBody ( responseBody ) ; return defaultGoApiResponse ; }
Creates an instance DefaultGoApiResponse which represents success request with response code 200
11,279
String [ ] getCommandLine ( ) { List < String > args = new ArrayList < > ( ) ; if ( executable != null ) { args . add ( executable ) ; } for ( int i = 0 ; i < arguments . size ( ) ; i ++ ) { CommandArgument argument = arguments . get ( i ) ; args . add ( argument . forCommandLine ( ) ) ; } return args . toArray ( new String [ args . size ( ) ] ) ; }
Returns the executable and all defined arguments .
11,280
public void setWorkingDirectory ( String path ) { if ( path != null ) { File dir = new File ( path ) ; checkWorkingDir ( dir ) ; workingDir = dir ; } else { workingDir = null ; } }
Sets execution directory .
11,281
private void checkWorkingDir ( File dir ) { if ( dir != null ) { if ( ! dir . exists ( ) ) { throw new CommandLineException ( "Working directory \"" + dir . getAbsolutePath ( ) + "\" does not exist!" ) ; } else if ( ! dir . isDirectory ( ) ) { throw new CommandLineException ( "Path \"" + dir . getAbsolutePath ( ) + "\" does not specify a " + "directory." ) ; } } }
and not a valid working directory
11,282
boolean verifySigned ( File keystore , Certificate agentCertificate ) { try { KeyStore store = KeyStore . getInstance ( "JKS" ) ; FileInputStream inputStream = new FileInputStream ( keystore ) ; store . load ( inputStream , PASSWORD_AS_CHAR_ARRAY ) ; IOUtils . closeQuietly ( inputStream ) ; KeyStore . PrivateKeyEntry intermediateEntry = ( KeyStore . PrivateKeyEntry ) store . getEntry ( "ca-intermediate" , new KeyStore . PasswordProtection ( PASSWORD_AS_CHAR_ARRAY ) ) ; Certificate intermediateCertificate = intermediateEntry . getCertificate ( ) ; agentCertificate . verify ( intermediateCertificate . getPublicKey ( ) ) ; return true ; } catch ( Exception e ) { return false ; } }
Used for testing
11,283
public void debug ( String message ) { if ( loggingService == null ) { System . out . println ( message ) ; return ; } loggingService . debug ( pluginId , loggerName , message ) ; }
Messages to be logged in debug mode .
11,284
public void info ( String message , Object arg1 , Object arg2 ) { if ( loggingService == null ) { System . out . println ( message ) ; return ; } loggingService . info ( pluginId , loggerName , message , arg1 , arg2 ) ; }
Messages to be logged in info mode according to the specified format and arguments .
11,285
public void error ( String message ) { if ( loggingService == null ) { System . err . println ( message ) ; return ; } loggingService . error ( pluginId , loggerName , message ) ; }
Messages to be logged in error mode .
11,286
public boolean isValid ( ) { if ( PluggableTaskConfigStore . store ( ) . preferenceFor ( pluginConfiguration . getId ( ) ) == null ) { addError ( TYPE , String . format ( "Could not find plugin for given pluggable id:[%s]." , pluginConfiguration . getId ( ) ) ) ; } configuration . validateTree ( ) ; return ( errors . isEmpty ( ) && ! configuration . hasErrors ( ) ) ; }
This method is called from PluggableTaskService to validate Tasks .
11,287
private void internalUpdateJobStateAndResult ( final JobInstance job ) { transactionTemplate . execute ( new TransactionCallbackWithoutResult ( ) { protected void doInTransactionWithoutResult ( TransactionStatus status ) { jobInstanceDao . updateStateAndResult ( job ) ; if ( job . isCompleted ( ) ) { buildPropertiesService . saveCruiseProperties ( job ) ; } } } ) ; }
This method exists only so that we can scope the transaction properly
11,288
public synchronized void onTimer ( ) { CruiseConfig currentConfig = applicationContext . getBean ( CruiseConfigProvider . class ) . getCurrentConfig ( ) ; purgeStaleHealthMessages ( currentConfig ) ; LOG . debug ( "Recomputing material to pipeline mappings." ) ; HashMap < ServerHealthState , Set < String > > erroredPipelines = new HashMap < > ( ) ; for ( Map . Entry < HealthStateType , ServerHealthState > entry : serverHealth . entrySet ( ) ) { erroredPipelines . put ( entry . getValue ( ) , entry . getValue ( ) . getPipelineNames ( currentConfig ) ) ; } pipelinesWithErrors = erroredPipelines ; LOG . debug ( "Done recomputing material to pipeline mappings." ) ; }
called from spring timer
11,289
P4Client _p4 ( File workDir , ConsoleOutputStreamConsumer consumer , boolean failOnError ) throws Exception { String clientName = clientName ( workDir ) ; return P4Client . fromServerAndPort ( getFingerprint ( ) , serverAndPort , userName , getPassword ( ) , clientName , this . useTickets , workDir , p4view ( clientName ) , consumer , failOnError ) ; }
not for use externally created for testing convenience
11,290
public List < String > getMessages ( ) { List < String > errorMessages = new ArrayList < > ( ) ; for ( ValidationError error : errors ) { errorMessages . add ( error . getMessage ( ) ) ; } return errorMessages ; }
Collects error message string as list from all the errors in the container
11,291
public synchronized GoConfigSaveResult writeWithLock ( UpdateConfigCommand updatingCommand , GoConfigHolder configHolder ) { try { GoConfigHolder validatedConfigHolder ; List < PartialConfig > lastKnownPartials = cachedGoPartials . lastKnownPartials ( ) ; List < PartialConfig > lastValidPartials = cachedGoPartials . lastValidPartials ( ) ; try { validatedConfigHolder = trySavingConfig ( updatingCommand , configHolder , lastKnownPartials ) ; updateMergedConfigForEdit ( validatedConfigHolder , lastKnownPartials ) ; } catch ( Exception e ) { if ( lastKnownPartials . isEmpty ( ) || areKnownPartialsSameAsValidPartials ( lastKnownPartials , lastValidPartials ) ) { throw e ; } else { LOGGER . warn ( "Merged config update operation failed on LATEST {} partials. Falling back to using LAST VALID {} partials. Exception message was: {}" , lastKnownPartials . size ( ) , lastValidPartials . size ( ) , e . getMessage ( ) , e ) ; try { validatedConfigHolder = trySavingConfig ( updatingCommand , configHolder , lastValidPartials ) ; updateMergedConfigForEdit ( validatedConfigHolder , lastValidPartials ) ; LOGGER . info ( "Update operation on merged configuration succeeded with old {} LAST VALID partials." , lastValidPartials . size ( ) ) ; } catch ( GoConfigInvalidException fallbackFailed ) { LOGGER . warn ( "Merged config update operation failed using fallback LAST VALID {} partials. Exception message was: {}" , lastValidPartials . size ( ) , fallbackFailed . getMessage ( ) , fallbackFailed ) ; throw new GoConfigInvalidMergeException ( lastValidPartials , fallbackFailed ) ; } } } ConfigSaveState configSaveState = shouldMergeConfig ( updatingCommand , configHolder ) ? ConfigSaveState . MERGED : ConfigSaveState . UPDATED ; return new GoConfigSaveResult ( validatedConfigHolder , configSaveState ) ; } catch ( ConfigFileHasChangedException e ) { LOGGER . warn ( "Configuration file could not be merged successfully after a concurrent edit: {}" , e . getMessage ( ) , e ) ; throw e ; } catch ( GoConfigInvalidException e ) { LOGGER . warn ( "Configuration file is invalid: {}" , e . getMessage ( ) , e ) ; throw bomb ( e . getMessage ( ) , e ) ; } catch ( Exception e ) { LOGGER . error ( "Configuration file is not valid: {}" , e . getMessage ( ) , e ) ; throw bomb ( e . getMessage ( ) , e ) ; } finally { LOGGER . debug ( "[Config Save] Done writing with lock" ) ; } }
This method should be removed once we have API s for all entities which should use writeEntityWithLock and full config save should use writeFullConfigWithLock
11,292
public static BuildCommand export ( String name , String value , boolean isSecure ) { return new BuildCommand ( "export" , map ( "name" , name , "value" , value , "secure" , String . valueOf ( isSecure ) ) ) ; }
set environment variable with displaying it
11,293
public static Vector tokenizePath ( String path , String separator ) { Vector ret = new Vector ( ) ; if ( FileUtil . isAbsolutePath ( path ) ) { String [ ] s = FileUtil . dissect ( path ) ; ret . add ( s [ 0 ] ) ; path = s [ 1 ] ; } StringTokenizer st = new StringTokenizer ( path , separator ) ; while ( st . hasMoreTokens ( ) ) { ret . addElement ( st . nextToken ( ) ) ; } return ret ; }
Breaks a path up into a Vector of path elements tokenizing on
11,294
public static String rtrimWildcardTokens ( String input ) { String [ ] tokens = tokenizePathAsArray ( input ) ; StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < tokens . length ; i ++ ) { if ( hasWildcards ( tokens [ i ] ) ) { break ; } if ( i > 0 && sb . charAt ( sb . length ( ) - 1 ) != File . separatorChar ) { sb . append ( File . separatorChar ) ; } sb . append ( tokens [ i ] ) ; } return sb . toString ( ) ; }
removes from a pattern all tokens to the right containing wildcards
11,295
public static ExecutionResult failure ( String message ) { ExecutionResult executionResult = new ExecutionResult ( ) ; executionResult . withErrorMessages ( message ) ; return executionResult ; }
Mark the result as Failure .
11,296
public static ExecutionResult success ( String message ) { ExecutionResult executionResult = new ExecutionResult ( ) ; executionResult . withSuccessMessages ( message ) ; return executionResult ; }
Mark the result as Success .
11,297
public synchronized void consumeLine ( final String line ) { if ( StringUtils . isNotEmpty ( errorStr ) ) { if ( StringUtils . equalsIgnoreCase ( line . trim ( ) , errorStr ) ) { foundError = true ; } } }
Ugly parsing of Exec output into some Elements . Gets called from StreamPumper .
11,298
public void deleteJobPlanAssociatedEntities ( JobInstance job ) { JobPlan jobPlan = loadPlan ( job . getId ( ) ) ; environmentVariableDao . deleteAll ( jobPlan . getVariables ( ) ) ; artifactPlanRepository . deleteAll ( jobPlan . getArtifactPlansOfType ( ArtifactPlanType . file ) ) ; artifactPropertiesGeneratorRepository . deleteAll ( jobPlan . getPropertyGenerators ( ) ) ; resourceRepository . deleteAll ( jobPlan . getResources ( ) ) ; if ( jobPlan . requiresElasticAgent ( ) ) { jobAgentMetadataDao . delete ( jobAgentMetadataDao . load ( jobPlan . getJobId ( ) ) ) ; } }
this will be called from Job Status Listener when Job is completed .
11,299
static Date convertDate ( String date ) throws ParseException { final int zIndex = date . indexOf ( 'Z' ) ; if ( zIndex - 3 < 0 ) { throw new ParseException ( date + " doesn't match the expected subversion date format" , date . length ( ) ) ; } String withoutMicroSeconds = date . substring ( 0 , zIndex - 3 ) ; return getOutDateFormatter ( ) . parse ( withoutMicroSeconds ) ; }
Converts the specified SVN date string into a Date .