idx
int64
0
34.9k
question
stringlengths
12
26.4k
target
stringlengths
15
2.3k
100
public static int hashObject ( Object o ) { return o == null ? 0 : o . hashCode ( ) ; }
Null-safe hash code method for objects. Returns the object hash code if it is not null, and 0 otherwise.
101
boolean needToCheckExclude ( ) { return false ; }
Return whether we need to check namespace prefixes against and exclude result prefixes list.
102
public synchronized void checkAccess ( LicenseCheckerCallback callback ) { if ( mPolicy . allowAccess ( ) ) { Log . i ( TAG , "Using cached license response" ) ; callback . allow ( Policy . LICENSED ) ; } else { LicenseValidator validator = new LicenseValidator ( mPolicy , new NullDeviceLimiter ( ) , callback , generateNonce ( ) , mPackageName , mVersionCode ) ; if ( mService == null ) { Log . i ( TAG , "Binding to licensing service." ) ; try { boolean bindResult = mContext . bindService ( new Intent ( "com.android.vending.licensing.ILicensingService" ) , this , Context . BIND_AUTO_CREATE ) ; if ( bindResult ) { mPendingChecks . offer ( validator ) ; } else { Log . e ( TAG , "Could not bind to service." ) ; handleServiceConnectionError ( validator ) ; } } catch ( Exception e ) { callback . applicationError ( LicenseCheckerCallback . ERROR_MISSING_PERMISSION ) ; } } else { mPendingChecks . offer ( validator ) ; runChecks ( ) ; } } }
Checks if the user should have access to the app. Binds the service if necessary. <p> NOTE: We can let DexGuard obfuscate the string that is passed into bindService. <p> source string: "com.android.vending.licensing.ILicensingService" <p>
103
public Area ( final StendhalRPZone zone , int x , int y , int width , int height ) { this . zone = zone ; final Rectangle2D myshape = new Rectangle2D . Double ( ) ; myshape . setRect ( x , y , width , height ) ; this . shape = myshape ; }
Creates a new Area.
104
private byte nextTC ( ) throws IOException { if ( hasPushbackTC ) { hasPushbackTC = false ; } else { pushbackTC = input . readByte ( ) ; } return pushbackTC ; }
Return the next token code (TC) from the receiver, which indicates what kind of object follows
105
private void newline ( ) { print ( "\n" ) ; }
Put the line separator String onto the print stream.
106
public int size ( ) { return seq . size ( ) ; }
return the number of objects in this sequence.
107
public static String digestString ( String pass , String algorithm ) throws NoSuchAlgorithmException { MessageDigest md ; ByteArrayOutputStream bos ; try { md = MessageDigest . getInstance ( algorithm ) ; byte [ ] digest = md . digest ( pass . getBytes ( "iso-8859-1" ) ) ; bos = new ByteArrayOutputStream ( ) ; OutputStream encodedStream = MimeUtility . encode ( bos , "base64" ) ; encodedStream . write ( digest ) ; return bos . toString ( "iso-8859-1" ) ; } catch ( IOException ioe ) { throw new RuntimeException ( "Fatal error: " + ioe ) ; } catch ( MessagingException me ) { throw new RuntimeException ( "Fatal error: " + me ) ; } }
Calculate digest of given String using given algorithm. Encode digest in MIME-like base64.
108
void storeBlock ( long lobId , int seq , long pos , byte [ ] b , String compressAlgorithm ) throws SQLException { long block ; boolean blockExists = false ; if ( compressAlgorithm != null ) { b = compress . compress ( b , compressAlgorithm ) ; } int hash = Arrays . hashCode ( b ) ; assertHoldsLock ( conn . getSession ( ) ) ; assertHoldsLock ( database ) ; block = getHashCacheBlock ( hash ) ; if ( block != - 1 ) { String sql = "SELECT COMPRESSED, DATA FROM " + LOB_DATA + " WHERE BLOCK = ?" ; PreparedStatement prep = prepare ( sql ) ; prep . setLong ( 1 , block ) ; ResultSet rs = prep . executeQuery ( ) ; if ( rs . next ( ) ) { boolean compressed = rs . getInt ( 1 ) != 0 ; byte [ ] compare = rs . getBytes ( 2 ) ; if ( compressed == ( compressAlgorithm != null ) && Arrays . equals ( b , compare ) ) { blockExists = true ; } } reuse ( sql , prep ) ; } if ( ! blockExists ) { block = nextBlock ++ ; setHashCacheBlock ( hash , block ) ; String sql = "INSERT INTO " + LOB_DATA + "(BLOCK, COMPRESSED, DATA) VALUES(?, ?, ?)" ; PreparedStatement prep = prepare ( sql ) ; prep . setLong ( 1 , block ) ; prep . setInt ( 2 , compressAlgorithm == null ? 0 : 1 ) ; prep . setBytes ( 3 , b ) ; prep . execute ( ) ; reuse ( sql , prep ) ; } String sql = "INSERT INTO " + LOB_MAP + "(LOB, SEQ, POS, HASH, BLOCK) VALUES(?, ?, ?, ?, ?)" ; PreparedStatement prep = prepare ( sql ) ; prep . setLong ( 1 , lobId ) ; prep . setInt ( 2 , seq ) ; prep . setLong ( 3 , pos ) ; prep . setLong ( 4 , hash ) ; prep . setLong ( 5 , block ) ; prep . execute ( ) ; reuse ( sql , prep ) ; }
Store a block in the LOB storage.
109
public static boolean isDirectory ( String path ) { File f = new File ( path ) ; return f . isDirectory ( ) ; }
Checks if the given path is a directory
110
private void putWithValidation ( String key , Object value ) throws BitcoinURIParseException { if ( parameterMap . containsKey ( key ) ) { throw new BitcoinURIParseException ( String . format ( Locale . US , "'%s' is duplicated, URI is invalid" , key ) ) ; } else { parameterMap . put ( key , value ) ; } }
Put the value against the key in the map checking for duplication. This avoids address field overwrite etc.
111
static void transformKillSlot ( final RPObject object ) { final RPObject kills = KeyedSlotUtil . getKeyedSlotObject ( object , "!kills" ) ; if ( kills != null ) { final RPObject newKills = new RPObject ( ) ; for ( final String attr : kills ) { if ( ! attr . equals ( "id" ) ) { String newAttr = attr ; String value = kills . get ( attr ) ; if ( attr . indexOf ( '.' ) < 0 ) { newAttr = updateItemName ( newAttr ) ; newAttr = value + "." + newAttr ; value = "1" ; } newKills . put ( newAttr , value ) ; } } final RPSlot slot = object . getSlot ( "!kills" ) ; slot . remove ( kills . getID ( ) ) ; slot . add ( newKills ) ; } }
Transform kill slot content to the new kill recording system.
112
public static CharSequence trimTrailingWhitespace ( CharSequence source ) { if ( source == null ) return "" ; int i = source . length ( ) ; while ( -- i >= 0 && Character . isWhitespace ( source . charAt ( i ) ) ) { } return source . subSequence ( 0 , i + 1 ) ; }
Trims trailing whitespace. Removes any of these characters: 0009, HORIZONTAL TABULATION 000A, LINE FEED 000B, VERTICAL TABULATION 000C, FORM FEED 000D, CARRIAGE RETURN 001C, FILE SEPARATOR 001D, GROUP SEPARATOR 001E, RECORD SEPARATOR 001F, UNIT SEPARATOR
113
private static void WriteStringVectorToFile ( Vector inputVec , String fileName ) throws StringVectorToFileException { try { BufferedWriter fileW = new BufferedWriter ( new FileWriter ( fileName ) ) ; int lineNum = 0 ; while ( lineNum < inputVec . size ( ) ) { fileW . write ( ( String ) inputVec . elementAt ( lineNum ) ) ; fileW . newLine ( ) ; lineNum = lineNum + 1 ; } ; fileW . close ( ) ; } catch ( Exception e ) { throw new StringVectorToFileException ( "Could not write file " + fileName ) ; } ; }
METHODS FOR READING AND WRITING FILES
114
public boolean before ( String userDefinedValue ) throws IllegalArgumentException { try { return value . before ( getDate ( userDefinedValue ) ) ; } catch ( DataTypeValidationException e ) { throw new IllegalArgumentException ( e . getMessage ( ) ) ; } }
Indicates whether or not provided value is before.
115
public void close ( ) { if ( null != inputStreamReader ) { CarbonUtil . closeStreams ( inputStreamReader ) ; } }
Below method will be used to clear all the stream
116
public static double exponent ( Object left , Object right ) throws PageException { return StrictMath . pow ( Caster . toDoubleValue ( left ) , Caster . toDoubleValue ( right ) ) ; }
calculate the exponent of the left value
117
public synchronized void addActionListener ( ActionListener actionListener ) { if ( actionListeners == null ) actionListeners = new ArrayList < ActionListener > ( ) ; actionListeners . add ( actionListener ) ; if ( fired ) { actionListener . actionPerformed ( new ActionEvent ( this , ActionEvent . ACTION_PERFORMED , "" ) ) ; } }
Adds a listener that will be notified upon completion of all of the running threads. Its actionPerformed method will be called immediately if the threads already finished.
118
public String writeDataFile ( ) throws DataFileException { ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; writeDataFile ( bos ) ; String outString = bos . toString ( ) ; try { if ( bos != null ) bos . close ( ) ; } catch ( IOException e ) { Debug . logWarning ( e , module ) ; } return outString ; }
Returns the records in this DataFile object as a plain text data file content
119
public static Color determineBackgroundColor ( final INaviInstruction startInstruction , final String trackedRegister , final CInstructionResult result ) { Preconditions . checkNotNull ( startInstruction , "IE01671: Start instruction argument can not be null" ) ; Preconditions . checkNotNull ( trackedRegister , "IE01672: Tracked register argument can not be null" ) ; Preconditions . checkNotNull ( result , "IE01673: Result argument can not be null" ) ; if ( result . getInstruction ( ) == startInstruction ) { return Color . decode ( "0x00BF00" ) ; } else if ( result . undefinesAll ( ) ) { return Color . decode ( "0xB30000" ) ; } else if ( result . clearsTrackedRegister ( trackedRegister ) ) { return Color . decode ( "0xA12967" ) ; } else if ( result . undefinesSome ( ) ) { return Color . decode ( "0xED693F" ) ; } else if ( result . defines ( ) ) { return Color . decode ( "0xFFCD55" ) ; } else if ( result . updates ( ) ) { return Color . decode ( "0x5AAB47" ) ; } else if ( result . uses ( ) ) { return Color . decode ( "0x414142" ) ; } else { return Color . WHITE ; } }
Determines the background color to be used in the table and in the graph to highlight a given instruction result.
120
public void removeOnCentralPositionChangedListener ( OnCentralPositionChangedListener listener ) { mOnCentralPositionChangedListeners . remove ( listener ) ; }
Removes a listener that would be called when the central item of the list changes.
121
public void addPickupRS ( ) { int old = _pickupRS ; _pickupRS ++ ; setDirtyAndFirePropertyChange ( "locationAddPickupRS" , Integer . toString ( old ) , Integer . toString ( _pickupRS ) ) ; }
Increments the number of cars and or engines that will be picked up by a train at this location.
122
public void addHeaderView ( View v ) { addHeaderView ( v , null , true ) ; }
Add a fixed view to appear at the top of the grid. If addHeaderView is called more than once, the views will appear in the order they were added. Views added using this call can take focus if they want. <p> NOTE: Call this before calling setAdapter. This is so HeaderGridView can wrap the supplied cursor with one that will also account for header views.
123
public double convert ( ) { return Double . longBitsToDouble ( ints2long ( high , low ) ) ; }
Converts the internal representation (two ints) to a double.
124
public void warn ( XPathContext xctxt , String msg , Object args [ ] ) throws javax . xml . transform . TransformerException { String formattedMsg = XSLMessages . createWarning ( msg , args ) ; ErrorListener errHandler = xctxt . getErrorListener ( ) ; errHandler . warning ( new TransformerException ( formattedMsg , ( SAXSourceLocator ) xctxt . getSAXLocator ( ) ) ) ; }
Warn the user of a problem.
125
public void clearArchiveDirectory ( ) { File directory = new File ( getArchiveDirectory ( ) ) ; if ( directory . exists ( ) && directory . isDirectory ( ) ) { String [ ] listing = directory . list ( ) ; for ( String aListing : listing ) { File file = new File ( getArchiveDirectory ( ) , aListing ) ; file . delete ( ) ; } } if ( ! directory . exists ( ) ) { directory . mkdirs ( ) ; } }
Clears the archive directory.
126
public void testDivideRemainderIsZero ( ) { String a = "8311389578904553209874735431110" ; int aScale = - 15 ; String b = "237468273682987234567849583746" ; int bScale = 20 ; String c = "3.5000000000000000000000000000000E+36" ; int resScale = - 5 ; BigDecimal aNumber = new BigDecimal ( new BigInteger ( a ) , aScale ) ; BigDecimal bNumber = new BigDecimal ( new BigInteger ( b ) , bScale ) ; BigDecimal result = aNumber . divide ( bNumber , resScale , BigDecimal . ROUND_CEILING ) ; assertEquals ( "incorrect value" , c , result . toString ( ) ) ; assertEquals ( "incorrect scale" , resScale , result . scale ( ) ) ; }
Divide: remainder is zero
127
public static boolean nonemptyQueryResult ( ResultSet R ) { logger . trace ( "nonemptyQueryResult(R)" ) ; boolean nonEmpty = false ; if ( R == null ) { return false ; } try { if ( R . getRow ( ) != 0 ) { nonEmpty = true ; } else { logger . trace ( "nonemptyQueryResult(R) - check R.first()..." ) ; nonEmpty = R . first ( ) ; R . beforeFirst ( ) ; } } catch ( Throwable t ) { surfaceThrowable ( "nonemptyQueryResult()" , t ) ; } return nonEmpty ; }
Since the ResultSet class mysteriously lacks a "size()" method, and since simply iterating thru what might be a large ResultSet could be a costly exercise, we play the following games. We take care to try and leave R as we found it, cursor-wise.
128
private String createFullMessageText ( String senderName , String receiverName , String text ) { if ( senderName . equals ( receiverName ) ) { return "You mutter to yourself: " + text ; } else { return senderName + " tells you: " + text ; } }
creates the full message based on the text provided by the player
129
public void validate ( ) throws IgniteCheckedException { for ( CachePluginProvider provider : providersList ) provider . validate ( ) ; }
Validates cache plugin configurations. Throw exception if validation failed.
130
public void testCompareLessScale1 ( ) { String a = "12380964839238475457356735674573563567890295784902768787678287" ; int aScale = 18 ; String b = "4573563567890295784902768787678287" ; int bScale = 28 ; BigDecimal aNumber = new BigDecimal ( new BigInteger ( a ) , aScale ) ; BigDecimal bNumber = new BigDecimal ( new BigInteger ( b ) , bScale ) ; int result = 1 ; assertEquals ( "incorrect result" , result , aNumber . compareTo ( bNumber ) ) ; }
Compare to a number of an less scale
131
protected boolean oneSameNetwork ( MacAddress m1 , MacAddress m2 ) { String net1 = macToGuid . get ( m1 ) ; String net2 = macToGuid . get ( m2 ) ; if ( net1 == null ) return false ; if ( net2 == null ) return false ; return net1 . equals ( net2 ) ; }
Checks to see if two MAC Addresses are on the same network.
132
public static Object [ ] polar2CartesianArray ( Double r , Double alpha ) { double x = r . doubleValue ( ) * Math . cos ( alpha . doubleValue ( ) ) ; double y = r . doubleValue ( ) * Math . sin ( alpha . doubleValue ( ) ) ; return new Object [ ] { new Double ( x ) , new Double ( y ) } ; }
Convert polar coordinates to cartesian coordinates. The function may be called twice, once to retrieve the result columns (with null parameters), and the second time to return the data.
133
protected void singleEnsemble ( final double [ ] ensemble , final NumberVector vec ) { double [ ] buf = new double [ 1 ] ; for ( int i = 0 ; i < ensemble . length ; i ++ ) { buf [ 0 ] = vec . doubleValue ( i ) ; ensemble [ i ] = voting . combine ( buf , 1 ) ; if ( Double . isNaN ( ensemble [ i ] ) ) { LOG . warning ( "NaN after combining: " + FormatUtil . format ( buf ) + " " + voting . toString ( ) ) ; } } applyScaling ( ensemble , scaling ) ; }
Build a single-element "ensemble".
134
@ Override public boolean is_IntBox ( ) { for ( int index = 0 ; index < lines_size ( ) ; ++ index ) { PlaLineInt curr_line = tline_get ( index ) ; if ( ! curr_line . is_orthogonal ( ) ) return false ; if ( ! corner_is_bounded ( index ) ) return false ; } return true ; }
checks if this simplex can be converted into an IntBox
135
public void addItemAtIndex ( T item , int index ) { if ( index <= items . size ( ) ) { items . add ( index , item ) ; fireDataChangedEvent ( DataChangedListener . ADDED , index ) ; } }
Adding an item to list at given index
136
private boolean crossCheckDiagonal ( int startI , int centerJ , int maxCount , int originalStateCountTotal ) { int [ ] stateCount = getCrossCheckStateCount ( ) ; int i = 0 ; while ( startI >= i && centerJ >= i && image . get ( centerJ - i , startI - i ) ) { stateCount [ 2 ] ++ ; i ++ ; } if ( startI < i || centerJ < i ) { return false ; } while ( startI >= i && centerJ >= i && ! image . get ( centerJ - i , startI - i ) && stateCount [ 1 ] <= maxCount ) { stateCount [ 1 ] ++ ; i ++ ; } if ( startI < i || centerJ < i || stateCount [ 1 ] > maxCount ) { return false ; } while ( startI >= i && centerJ >= i && image . get ( centerJ - i , startI - i ) && stateCount [ 0 ] <= maxCount ) { stateCount [ 0 ] ++ ; i ++ ; } if ( stateCount [ 0 ] > maxCount ) { return false ; } int maxI = image . getHeight ( ) ; int maxJ = image . getWidth ( ) ; i = 1 ; while ( startI + i < maxI && centerJ + i < maxJ && image . get ( centerJ + i , startI + i ) ) { stateCount [ 2 ] ++ ; i ++ ; } if ( startI + i >= maxI || centerJ + i >= maxJ ) { return false ; } while ( startI + i < maxI && centerJ + i < maxJ && ! image . get ( centerJ + i , startI + i ) && stateCount [ 3 ] < maxCount ) { stateCount [ 3 ] ++ ; i ++ ; } if ( startI + i >= maxI || centerJ + i >= maxJ || stateCount [ 3 ] >= maxCount ) { return false ; } while ( startI + i < maxI && centerJ + i < maxJ && image . get ( centerJ + i , startI + i ) && stateCount [ 4 ] < maxCount ) { stateCount [ 4 ] ++ ; i ++ ; } if ( stateCount [ 4 ] >= maxCount ) { return false ; } int stateCountTotal = stateCount [ 0 ] + stateCount [ 1 ] + stateCount [ 2 ] + stateCount [ 3 ] + stateCount [ 4 ] ; return Math . abs ( stateCountTotal - originalStateCountTotal ) < 2 * originalStateCountTotal && foundPatternCross ( stateCount ) ; }
After a vertical and horizontal scan finds a potential finder pattern, this method "cross-cross-cross-checks" by scanning down diagonally through the center of the possible finder pattern to see if the same proportion is detected.
137
public static MatchedValuesRequestControl newControl ( final boolean isCritical , final String ... filters ) { Reject . ifFalse ( filters . length > 0 , "filters is empty" ) ; final List < Filter > parsedFilters = new ArrayList < > ( filters . length ) ; for ( final String filter : filters ) { parsedFilters . add ( validateFilter ( Filter . valueOf ( filter ) ) ) ; } return new MatchedValuesRequestControl ( isCritical , Collections . unmodifiableList ( parsedFilters ) ) ; }
Creates a new matched values request control with the provided criticality and list of filters.
138
private void updateIPEndPointDetails ( Map < String , Object > keyMap , StoragePort port , CIMInstance ipPointInstance , String portInstanceID ) throws IOException { if ( null != port ) { updateIPAddress ( getCIMPropertyValue ( ipPointInstance , IPv4Address ) , port ) ; _dbClient . persistObject ( port ) ; } }
update End Point Details
139
public void replace ( String param , String value ) { int [ ] range ; while ( ( range = findTemplate ( param ) ) != null ) buff . replace ( range [ 0 ] , range [ 1 ] , value ) ; }
Substitute the specified text for the parameter
140
public void calcMajorTick ( ) { fraction = UNIT ; double u = majorTick ; double r = maxTick - minTick ; majorTickCount = ( int ) ( r / u ) ; while ( majorTickCount < prefMajorTickCount ) { u = majorTick / 2 ; if ( ! isDiscrete || u == Math . floor ( u ) ) { majorTickCount = ( int ) ( r / u ) ; fraction = HALFS ; if ( majorTickCount >= prefMajorTickCount ) break ; } u = majorTick / 4 ; if ( ! isDiscrete || u == Math . floor ( u ) ) { majorTickCount = ( int ) ( r / u ) ; fraction = QUARTERS ; if ( majorTickCount >= prefMajorTickCount ) break ; } u = majorTick / 5 ; if ( ! isDiscrete || u == Math . floor ( u ) ) { majorTickCount = ( int ) ( r / u ) ; fraction = FIFTHS ; if ( majorTickCount >= prefMajorTickCount ) break ; } if ( isDiscrete && ( majorTick / 10 ) != Math . floor ( majorTick / 10 ) ) { u = majorTick ; majorTickCount = ( int ) ( r / u ) ; break ; } majorTick /= 10 ; u = majorTick ; majorTickCount = ( int ) ( r / u ) ; fraction = UNIT ; } majorTick = u ; if ( isDiscrete && majorTick < 1.0 ) { majorTick = 1.0 ; majorTickCount = ( int ) ( r / majorTick ) ; fraction = UNIT ; } majorTickCount ++ ; while ( ( minTick + majorTick - epsilon ) < minData ) { minTick += majorTick ; majorTickCount -- ; } while ( ( maxTick - majorTick + epsilon ) > maxData ) { maxTick -= majorTick ; majorTickCount -- ; } }
Calculate the optimum major tick distance. Override to change default behaviour
141
private void updateProgress ( String progressLabel , int progress ) { if ( myHost != null && ( ( progress != previousProgress ) || ( ! progressLabel . equals ( previousProgressLabel ) ) ) ) { myHost . updateProgress ( progressLabel , progress ) ; } previousProgress = progress ; previousProgressLabel = progressLabel ; }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
142
private static void decodeBase256Segment ( BitSource bits , StringBuilder result , Collection < byte [ ] > byteSegments ) throws FormatException { int codewordPosition = 1 + bits . getByteOffset ( ) ; int d1 = unrandomize255State ( bits . readBits ( 8 ) , codewordPosition ++ ) ; int count ; if ( d1 == 0 ) { count = bits . available ( ) / 8 ; } else if ( d1 < 250 ) { count = d1 ; } else { count = 250 * ( d1 - 249 ) + unrandomize255State ( bits . readBits ( 8 ) , codewordPosition ++ ) ; } if ( count < 0 ) { throw FormatException . getFormatInstance ( ) ; } byte [ ] bytes = new byte [ count ] ; for ( int i = 0 ; i < count ; i ++ ) { if ( bits . available ( ) < 8 ) { throw FormatException . getFormatInstance ( ) ; } bytes [ i ] = ( byte ) unrandomize255State ( bits . readBits ( 8 ) , codewordPosition ++ ) ; } byteSegments . add ( bytes ) ; try { result . append ( new String ( bytes , "ISO8859_1" ) ) ; } catch ( UnsupportedEncodingException uee ) { throw new IllegalStateException ( "Platform does not support required encoding: " + uee ) ; } }
See ISO 16022:2006, 5.2.9 and Annex B, B.2
143
public static < V > int addDistinctList ( List < V > sourceList , List < V > entryList ) { if ( sourceList == null || isEmpty ( entryList ) ) { return 0 ; } int sourceCount = sourceList . size ( ) ; for ( V entry : entryList ) { if ( ! sourceList . contains ( entry ) ) { sourceList . add ( entry ) ; } } return sourceList . size ( ) - sourceCount ; }
add all distinct entry to list1 from list2
144
private JsonWriter open ( JsonScope empty , String openBracket ) throws IOException { beforeValue ( true ) ; stack . add ( empty ) ; out . write ( openBracket ) ; return this ; }
Enters a new scope by appending any necessary whitespace and the given bracket.
145
public static boolean isCompositionPlaylist ( ResourceByteRangeProvider resourceByteRangeProvider ) throws IOException { try ( InputStream inputStream = resourceByteRangeProvider . getByteRangeAsStream ( 0 , resourceByteRangeProvider . getResourceSize ( ) - 1 ) ) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory . newInstance ( ) ; documentBuilderFactory . setNamespaceAware ( true ) ; DocumentBuilder documentBuilder = documentBuilderFactory . newDocumentBuilder ( ) ; Document document = documentBuilder . parse ( inputStream ) ; NodeList nodeList = null ; for ( String cplNamespaceURI : supportedCPLSchemaURIs ) { nodeList = document . getElementsByTagNameNS ( cplNamespaceURI , "CompositionPlaylist" ) ; if ( nodeList != null && nodeList . getLength ( ) == 1 ) { return true ; } } } catch ( ParserConfigurationException | SAXException e ) { return false ; } return false ; }
A method that confirms if the inputStream corresponds to a Composition document instance.
146
public XMLParser ( final String namespace , final String schema ) throws XMLException { try { JAXBContext jc = JAXBContext . newInstance ( namespace ) ; marshaller = jc . createMarshaller ( ) ; marshaller . setSchema ( XMLSchemaUtils . createSchema ( schema ) ) ; unmarshaller = jc . createUnmarshaller ( ) ; unmarshaller . setSchema ( XMLSchemaUtils . createSchema ( schema ) ) ; } catch ( JAXBException e ) { throw new XMLException ( "Cannot instantiate marshaller/unmarshaller for " + namespace , e ) ; } }
Creates the XMLParser with the namespace and schema file for validation.
147
public void warn ( String msg , Object args [ ] ) throws org . xml . sax . SAXException { String formattedMsg = XSLMessages . createWarning ( msg , args ) ; SAXSourceLocator locator = getLocator ( ) ; ErrorListener handler = m_stylesheetProcessor . getErrorListener ( ) ; try { if ( null != handler ) handler . warning ( new TransformerException ( formattedMsg , locator ) ) ; } catch ( TransformerException te ) { throw new org . xml . sax . SAXException ( te ) ; } }
Warn the user of an problem.
148
public Shape triangle_up ( float x , float y , float height ) { m_path . reset ( ) ; m_path . moveTo ( x , y + height ) ; m_path . lineTo ( x + height / 2 , y ) ; m_path . lineTo ( x + height , ( y + height ) ) ; m_path . closePath ( ) ; return m_path ; }
Returns a up-pointing triangle of the given dimenisions.
149
public double minDataDLIfExists ( int index , double expFPRate , boolean checkErr ) { double [ ] rulesetStat = new double [ 6 ] ; for ( int j = 0 ; j < m_SimpleStats . size ( ) ; j ++ ) { rulesetStat [ 0 ] += m_SimpleStats . get ( j ) [ 0 ] ; rulesetStat [ 2 ] += m_SimpleStats . get ( j ) [ 2 ] ; rulesetStat [ 4 ] += m_SimpleStats . get ( j ) [ 4 ] ; if ( j == m_SimpleStats . size ( ) - 1 ) { rulesetStat [ 1 ] = m_SimpleStats . get ( j ) [ 1 ] ; rulesetStat [ 3 ] = m_SimpleStats . get ( j ) [ 3 ] ; rulesetStat [ 5 ] = m_SimpleStats . get ( j ) [ 5 ] ; } } double potential = 0 ; for ( int k = index + 1 ; k < m_SimpleStats . size ( ) ; k ++ ) { double [ ] ruleStat = getSimpleStats ( k ) ; double ifDeleted = potential ( k , expFPRate , rulesetStat , ruleStat , checkErr ) ; if ( ! Double . isNaN ( ifDeleted ) ) { potential += ifDeleted ; } } double dataDLWith = dataDL ( expFPRate , rulesetStat [ 0 ] , rulesetStat [ 1 ] , rulesetStat [ 4 ] , rulesetStat [ 5 ] ) ; return ( dataDLWith - potential ) ; }
Compute the minimal data description length of the ruleset if the rule in the given position is NOT deleted.<br> The min_data_DL_if_n_deleted = data_DL_if_n_deleted - potential
150
public static void writeIntegerCollection ( @ Nonnull NBTTagCompound data , @ Nonnull Collection < Integer > coll ) { data . setInteger ( "size" , coll . size ( ) ) ; final int [ ] ary = new int [ coll . size ( ) ] ; int i = 0 ; for ( Integer num : coll ) { ary [ i ] = num ; i ++ ; } data . setTag ( "data" , new NBTTagIntArray ( ary ) ) ; }
Writes the given collection to the NBTTagCompound as an IntArray
151
@ SuppressWarnings ( "unchecked" ) public void queryForDump ( String cfName , String fileName , String [ ] ids ) throws Exception { final Class clazz = getClassFromCFName ( cfName ) ; if ( clazz == null ) { return ; } initDumpXmlFile ( cfName ) ; for ( String id : ids ) { queryAndPrintRecord ( URI . create ( id ) , clazz , DbCliOperation . DUMP ) ; } writeToXmlFile ( fileName ) ; }
Query and dump into xml for a particular id in a ColumnFamily
152
private AsciiFuncs ( ) { }
utility class not to be instantiated.
153
public DialogueImporter importDialogue ( String dialogueFile ) { List < DialogueState > turns = XMLDialogueReader . extractDialogue ( dialogueFile ) ; DialogueImporter importer = new DialogueImporter ( this , turns ) ; importer . start ( ) ; return importer ; }
Imports the dialogue specified in the provided file.
154
public static int darker ( int color , float factor ) { int a = Color . alpha ( color ) ; int r = Color . red ( color ) ; int g = Color . green ( color ) ; int b = Color . blue ( color ) ; return Color . argb ( a , Math . max ( ( int ) ( r * factor ) , 0 ) , Math . max ( ( int ) ( g * factor ) , 0 ) , Math . max ( ( int ) ( b * factor ) , 0 ) ) ; }
Retuns a darker color from a specified color by the factor.
155
public static String transformFilename ( String fileName ) { if ( ! fileName . endsWith ( ".fb" ) ) { fileName = fileName + ".fb" ; } return fileName ; }
Transform a user-entered filename into a proper filename, by adding the ".fb" file extension if it isn't already present.
156
public String readLine ( ) throws IOException { return keepCarriageReturns ? readUntilNewline ( ) : reader . readLine ( ) ; }
Reads the next line from the Reader.
157
public void hideValidationMessages ( ) { for ( ValidationErrorMessage invalidField : validationMessages ) { View view = parentView . findViewWithTag ( invalidField . getPaymentProductFieldId ( ) ) ; validationMessageRenderer . removeValidationMessage ( ( ViewGroup ) view . getParent ( ) , invalidField . getPaymentProductFieldId ( ) ) ; } validationMessages . clear ( ) ; fieldIdsOfErrorMessagesShowing . clear ( ) ; }
Hides all visible validationmessages
158
private synchronized void removeLoader ( ClassLoader loader ) { int i ; for ( i = _loaders . size ( ) - 1 ; i >= 0 ; i -- ) { WeakReference < ClassLoader > ref = _loaders . get ( i ) ; ClassLoader refLoader = ref . get ( ) ; if ( refLoader == null ) _loaders . remove ( i ) ; else if ( refLoader == loader ) _loaders . remove ( i ) ; } }
Removes the specified loader.
159
public static double parseString ( String value ) { return Double . parseDouble ( value ) ; }
Parse string value returning a double.
160
private void writePostContent ( HttpURLConnection connection , String postContent ) throws Exception { connection . setRequestMethod ( "POST" ) ; connection . addRequestProperty ( "Content-Type" , "application/xml; charset=utf-8" ) ; connection . setDoOutput ( true ) ; connection . setDoInput ( true ) ; connection . setAllowUserInteraction ( false ) ; DataOutputStream dstream = null ; try { connection . connect ( ) ; dstream = new DataOutputStream ( connection . getOutputStream ( ) ) ; dstream . writeBytes ( postContent ) ; dstream . flush ( ) ; } finally { if ( dstream != null ) { try { dstream . close ( ) ; } catch ( Exception ex ) { _log . error ( "Exception while closing the stream." + " Exception: " + ex , "WebClient._writePostContent()" ) ; } } } }
Send a post request with content to the specified connection
161
public void add ( WFNode node ) { m_nodes . add ( node ) ; }
Add Component and add Mouse Listener
162
@ Override public int clampViewPositionVertical ( View child , int top , int dy ) { int topBound = 0 ; int bottomBound = 0 ; switch ( draggerView . getDragPosition ( ) ) { case TOP : if ( top > 0 ) { topBound = draggerView . getPaddingTop ( ) ; bottomBound = ( int ) draggerListener . dragVerticalDragRange ( ) ; } break ; case BOTTOM : if ( top < 0 ) { topBound = ( int ) - draggerListener . dragVerticalDragRange ( ) ; bottomBound = draggerView . getPaddingTop ( ) ; } break ; default : break ; } return Math . min ( Math . max ( top , topBound ) , bottomBound ) ; }
Return the value of slide based on top and height of the element
163
public String forceGetValueAsString ( ) { if ( mValue == null ) { return "" ; } else if ( mValue instanceof byte [ ] ) { if ( mDataType == TYPE_ASCII ) { return new String ( ( byte [ ] ) mValue , US_ASCII ) ; } else { return Arrays . toString ( ( byte [ ] ) mValue ) ; } } else if ( mValue instanceof long [ ] ) { if ( ( ( long [ ] ) mValue ) . length == 1 ) { return String . valueOf ( ( ( long [ ] ) mValue ) [ 0 ] ) ; } else { return Arrays . toString ( ( long [ ] ) mValue ) ; } } else if ( mValue instanceof Object [ ] ) { if ( ( ( Object [ ] ) mValue ) . length == 1 ) { Object val = ( ( Object [ ] ) mValue ) [ 0 ] ; if ( val == null ) { return "" ; } else { return val . toString ( ) ; } } else { return Arrays . toString ( ( Object [ ] ) mValue ) ; } } else { return mValue . toString ( ) ; } }
Gets a string representation of the value.
164
@ GET @ Produces ( { MediaType . APPLICATION_XML , MediaType . APPLICATION_JSON } ) @ Path ( "/{id}/hosts" ) @ Deprecated public HostList listHosts ( @ PathParam ( "id" ) URI id ) throws DatabaseException { getTenantById ( id , false ) ; verifyAuthorizedInTenantOrg ( id , getUserFromContext ( ) ) ; HostList list = new HostList ( ) ; list . setHosts ( map ( ResourceTypeEnum . HOST , listChildren ( id , Host . class , "label" , "tenant" ) ) ) ; return list ; }
Lists the id and name for all the hosts that belong to the given tenant organization. <p> This method is deprecated. Use /compute/hosts instead
165
private void processDirectorStats ( Map < String , MetricHeaderInfo > metricHeaderInfoMap , Map < String , Double > maxValues , Map < String , String > lastSample ) { MetricHeaderInfo headerInfo = metricHeaderInfoMap . get ( HEADER_KEY_DIRECTOR_BUSY ) ; if ( headerInfo != null ) { String directorBusyString = lastSample . get ( HEADER_KEY_DIRECTOR_BUSY ) ; if ( directorBusyString != null ) { Double percentBusy = Double . valueOf ( directorBusyString ) ; Double iops = ( maxValues . containsKey ( HEADER_KEY_DIRECTOR_FE_OPS ) ) ? maxValues . get ( HEADER_KEY_DIRECTOR_FE_OPS ) : Double . valueOf ( lastSample . get ( HEADER_KEY_DIRECTOR_FE_OPS ) ) ; String lastSampleTime = lastSample . get ( HEADER_KEY_TIME_UTC ) ; portMetricsProcessor . processFEAdaptMetrics ( percentBusy , iops . longValue ( ) , headerInfo . director , lastSampleTime , false ) ; } } }
Process the director metrics found in metricHeaderInfoMap
166
public Point2D transform ( Point2D p ) { if ( p == null ) return null ; return transform . transform ( p , null ) ; }
Applies the transform to the supplied point.
167
static public void assertEquals ( String message , String expected , String actual ) { if ( expected == null && actual == null ) return ; if ( expected != null && expected . equals ( actual ) ) return ; throw new ComparisonFailure ( message , expected , actual ) ; }
Asserts that two Strings are equal.
168
private void correctChanged ( ) { clock . setCorrectHardware ( correctCheckBox . isSelected ( ) , true ) ; changed = true ; }
Method to handle correct check box change
169
private void writeOFMessagesToSwitch ( DatapathId dpid , List < OFMessage > messages ) { IOFSwitch ofswitch = switchService . getSwitch ( dpid ) ; if ( ofswitch != null ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Sending {} new entries to {}" , messages . size ( ) , dpid ) ; } ofswitch . write ( messages ) ; } }
Writes a list of OFMessages to a switch
170
private Set < HiCSSubspace > calculateSubspaces ( Relation < ? extends NumberVector > relation , ArrayList < ArrayDBIDs > subspaceIndex , Random random ) { final int dbdim = RelationUtil . dimensionality ( relation ) ; FiniteProgress dprog = LOG . isVerbose ( ) ? new FiniteProgress ( "Subspace dimensionality" , dbdim , LOG ) : null ; if ( dprog != null ) { dprog . setProcessed ( 2 , LOG ) ; } TreeSet < HiCSSubspace > subspaceList = new TreeSet < > ( HiCSSubspace . SORT_BY_SUBSPACE ) ; TopBoundedHeap < HiCSSubspace > dDimensionalList = new TopBoundedHeap < > ( cutoff , HiCSSubspace . SORT_BY_CONTRAST_ASC ) ; FiniteProgress prog = LOG . isVerbose ( ) ? new FiniteProgress ( "Generating two-element subsets" , ( dbdim * ( dbdim - 1 ) ) > > 1 , LOG ) : null ; for ( int i = 0 ; i < dbdim ; i ++ ) { for ( int j = i + 1 ; j < dbdim ; j ++ ) { HiCSSubspace ts = new HiCSSubspace ( ) ; ts . set ( i ) ; ts . set ( j ) ; calculateContrast ( relation , ts , subspaceIndex , random ) ; dDimensionalList . add ( ts ) ; LOG . incrementProcessed ( prog ) ; } } LOG . ensureCompleted ( prog ) ; IndefiniteProgress qprog = LOG . isVerbose ( ) ? new IndefiniteProgress ( "Testing subspace candidates" , LOG ) : null ; for ( int d = 3 ; ! dDimensionalList . isEmpty ( ) ; d ++ ) { if ( dprog != null ) { dprog . setProcessed ( d , LOG ) ; } ArrayList < HiCSSubspace > candidateList = new ArrayList < > ( dDimensionalList . size ( ) ) ; for ( Heap < HiCSSubspace > . UnorderedIter it = dDimensionalList . unorderedIter ( ) ; it . valid ( ) ; it . advance ( ) ) { subspaceList . add ( it . get ( ) ) ; candidateList . add ( it . get ( ) ) ; } dDimensionalList . clear ( ) ; Collections . sort ( candidateList , HiCSSubspace . SORT_BY_SUBSPACE ) ; for ( int i = 0 ; i < candidateList . size ( ) - 1 ; i ++ ) { for ( int j = i + 1 ; j < candidateList . size ( ) ; j ++ ) { HiCSSubspace set1 = candidateList . get ( i ) ; HiCSSubspace set2 = candidateList . get ( j ) ; HiCSSubspace joinedSet = new HiCSSubspace ( ) ; joinedSet . or ( set1 ) ; joinedSet . or ( set2 ) ; if ( joinedSet . cardinality ( ) != d ) { continue ; } calculateContrast ( relation , joinedSet , subspaceIndex , random ) ; dDimensionalList . add ( joinedSet ) ; LOG . incrementProcessed ( qprog ) ; } } for ( HiCSSubspace cand : candidateList ) { for ( Heap < HiCSSubspace > . UnorderedIter it = dDimensionalList . unorderedIter ( ) ; it . valid ( ) ; it . advance ( ) ) { if ( it . get ( ) . contrast > cand . contrast ) { subspaceList . remove ( cand ) ; break ; } } } } LOG . setCompleted ( qprog ) ; if ( dprog != null ) { dprog . setProcessed ( dbdim , LOG ) ; dprog . ensureCompleted ( LOG ) ; } return subspaceList ; }
Identifies high contrast subspaces in a given full-dimensional database.
171
public void testFailoverAutoReconnect ( ) throws Exception { Set < String > downedHosts = new HashSet < String > ( ) ; downedHosts . add ( HOST_1 ) ; downedHosts . add ( HOST_2 ) ; Properties props = new Properties ( ) ; props . setProperty ( "retriesAllDown" , "2" ) ; props . setProperty ( "maxReconnects" , "2" ) ; props . setProperty ( "initialTimeout" , "1" ) ; for ( boolean foAutoReconnect : new boolean [ ] { true , false } ) { props . setProperty ( "autoReconnect" , Boolean . toString ( foAutoReconnect ) ) ; Connection testConn = getUnreliableFailoverConnection ( new String [ ] { HOST_1 , HOST_2 , HOST_3 } , props , downedHosts ) ; Statement testStmt1 = null , testStmt2 = null ; try { assertEquals ( HOST_3_OK , UnreliableSocketFactory . getHostFromLastConnection ( ) ) ; testStmt1 = testConn . createStatement ( ) ; testStmt2 = testConn . createStatement ( ) ; assertSingleValueQuery ( testStmt1 , "SELECT 1" , 1L ) ; assertSingleValueQuery ( testStmt2 , "SELECT 2" , 2L ) ; UnreliableSocketFactory . dontDownHost ( HOST_2 ) ; UnreliableSocketFactory . downHost ( HOST_3 ) ; assertEquals ( HOST_3_OK , UnreliableSocketFactory . getHostFromLastConnection ( ) ) ; assertSQLException ( testStmt1 , "SELECT 1" , COMM_LINK_ERR_PATTERN ) ; assertEquals ( HOST_2_OK , UnreliableSocketFactory . getHostFromLastConnection ( ) ) ; UnreliableSocketFactory . dontDownHost ( HOST_1 ) ; if ( ! foAutoReconnect ) { assertSQLException ( testStmt1 , "SELECT 1" , STMT_CLOSED_ERR_PATTERN ) ; assertSQLException ( testStmt2 , "SELECT 2" , STMT_CLOSED_ERR_PATTERN ) ; testStmt1 = testConn . createStatement ( ) ; testStmt2 = testConn . createStatement ( ) ; } assertSingleValueQuery ( testStmt1 , "SELECT 1" , 1L ) ; assertSingleValueQuery ( testStmt2 , "SELECT 2" , 2L ) ; UnreliableSocketFactory . downHost ( HOST_2 ) ; assertEquals ( HOST_2_OK , UnreliableSocketFactory . getHostFromLastConnection ( ) ) ; assertSQLException ( testStmt2 , "SELECT 2" , COMM_LINK_ERR_PATTERN ) ; assertEquals ( HOST_1_OK , UnreliableSocketFactory . getHostFromLastConnection ( ) ) ; UnreliableSocketFactory . dontDownHost ( HOST_3 ) ; if ( ! foAutoReconnect ) { assertSQLException ( testStmt1 , "SELECT 1" , STMT_CLOSED_ERR_PATTERN ) ; assertSQLException ( testStmt2 , "SELECT 2" , STMT_CLOSED_ERR_PATTERN ) ; testStmt1 = testConn . createStatement ( ) ; testStmt2 = testConn . createStatement ( ) ; } assertSingleValueQuery ( testStmt1 , "SELECT 1" , 1L ) ; assertSingleValueQuery ( testStmt2 , "SELECT 2" , 2L ) ; UnreliableSocketFactory . downHost ( HOST_1 ) ; assertEquals ( HOST_1_OK , UnreliableSocketFactory . getHostFromLastConnection ( ) ) ; assertSQLException ( testStmt1 , "SELECT 1" , COMM_LINK_ERR_PATTERN ) ; assertEquals ( HOST_3_OK , UnreliableSocketFactory . getHostFromLastConnection ( ) ) ; if ( ! foAutoReconnect ) { assertSQLException ( testStmt1 , "SELECT 1" , STMT_CLOSED_ERR_PATTERN ) ; assertSQLException ( testStmt2 , "SELECT 2" , STMT_CLOSED_ERR_PATTERN ) ; testStmt1 = testConn . createStatement ( ) ; testStmt2 = testConn . createStatement ( ) ; } assertSingleValueQuery ( testStmt1 , "SELECT 1" , 1L ) ; assertSingleValueQuery ( testStmt2 , "SELECT 2" , 2L ) ; if ( foAutoReconnect ) { assertConnectionsHistory ( HOST_1_FAIL , HOST_1_FAIL , HOST_2_FAIL , HOST_2_FAIL , HOST_3_OK , HOST_2_OK , HOST_3_FAIL , HOST_3_FAIL , HOST_2_FAIL , HOST_2_FAIL , HOST_3_FAIL , HOST_3_FAIL , HOST_1_OK , HOST_2_FAIL , HOST_2_FAIL , HOST_3_OK ) ; } else { assertConnectionsHistory ( HOST_1_FAIL , HOST_2_FAIL , HOST_3_OK , HOST_2_OK , HOST_3_FAIL , HOST_2_FAIL , HOST_3_FAIL , HOST_1_OK , HOST_2_FAIL , HOST_3_OK ) ; } } finally { if ( testStmt1 != null ) { testStmt1 . close ( ) ; } if ( testStmt2 != null ) { testStmt2 . close ( ) ; } if ( testConn != null ) { testConn . close ( ) ; } } } }
Tests the property 'autoReconnect' in a failover connection using three hosts and the following sequence of events: - [\HOST_1 : \HOST_2 : /HOST_3] --> HOST_3 - [\HOST_1 : /HOST_2 : \HOST_3] --> HOST_2 - [/HOST_1 : /HOST_2 : \HOST_3] - [/HOST_1 : \HOST_2 : \HOST_3] --> HOST_1 - [/HOST_1 : \HOST_2 : /HOST_3] - [\HOST_1 : \HOST_2 : /HOST_3] --> HOST_3 [Legend: "/HOST_n" --> HOST_n up; "\HOST_n" --> HOST_n down]
172
public void addContainerRequest ( Map < StreamingContainerAgent . ContainerStartRequest , MutablePair < Integer , ContainerRequest > > requestedResources , int loopCounter , List < ContainerRequest > containerRequests , StreamingContainerAgent . ContainerStartRequest csr , ContainerRequest cr ) { MutablePair < Integer , ContainerRequest > pair = new MutablePair < Integer , ContainerRequest > ( loopCounter , cr ) ; requestedResources . put ( csr , pair ) ; containerRequests . add ( cr ) ; }
Add container request to list of issued requests to Yarn along with current loop counter
173
public void waitForChannelState ( DistributedMember member , Map channelState ) throws InterruptedException { if ( Thread . interrupted ( ) ) throw new InterruptedException ( ) ; TCPConduit tc = this . conduit ; if ( tc != null ) { tc . waitForThreadOwnedOrderedConnectionState ( member , channelState ) ; } }
wait for the given connections to process the number of messages associated with the connection in the given map
174
private boolean isSameCircleOfTrust ( BaseConfigType config , String realm , String entityID ) { boolean isTrusted = false ; if ( config != null ) { Map attr = IDFFMetaUtils . getAttributes ( config ) ; List cotList = ( List ) attr . get ( IDFFCOTUtils . COT_LIST ) ; if ( ( cotList != null ) && ! cotList . isEmpty ( ) ) { for ( Iterator iter = cotList . iterator ( ) ; iter . hasNext ( ) ; ) { String cotName = ( String ) iter . next ( ) ; if ( cotManager . isInCircleOfTrust ( realm , cotName , COTConstants . IDFF , entityID ) ) { isTrusted = true ; } } } } return isTrusted ; }
Checks if the remote entity identifier is in the Entity Config's circle of trust.
175
public RuleGrounding ( ) { groundings = new HashSet < Assignment > ( ) ; groundings . add ( new Assignment ( ) ) ; }
Constructs an empty set of groundings
176
public void removeIndexKeyspace ( final String index ) throws IOException { try { QueryProcessor . process ( String . format ( "DROP KEYSPACE \"%s\";" , index ) , ConsistencyLevel . LOCAL_ONE ) ; } catch ( Throwable e ) { throw new IOException ( e . getMessage ( ) , e ) ; } }
Don't use QueryProcessor.executeInternal, we need to propagate this on all nodes.
177
public void writeVecor ( File ftrain , File ftest , File all , File trainLabel ) throws Exception { int labels [ ] = readLabels ( ) ; FileWriter fw = new FileWriter ( ftrain ) ; FileWriter fwt = new FileWriter ( ftest ) ; FileWriter flabel = new FileWriter ( trainLabel ) ; for ( int i = 0 ; i < dataNum ; i ++ ) { if ( TestTrain [ i ] == 1 ) { flabel . write ( String . valueOf ( labels [ i ] ) + '\n' ) ; for ( int j = 0 ; j < dimension ; j ++ ) { if ( j != dimension - 1 ) { fw . write ( String . valueOf ( W [ i ] [ j ] ) + " " ) ; } else { fw . write ( String . valueOf ( W [ i ] [ j ] ) + '\n' ) ; } } } else { for ( int j = 0 ; j < dimension ; j ++ ) { if ( j != dimension - 1 ) { fwt . write ( String . valueOf ( W [ i ] [ j ] ) + " " ) ; } else { fwt . write ( String . valueOf ( W [ i ] [ j ] ) + '\n' ) ; } } } } fw . close ( ) ; fwt . close ( ) ; flabel . close ( ) ; FileWriter fwall = new FileWriter ( all ) ; for ( int i = 0 ; i < dataNum ; i ++ ) { for ( int j = 0 ; j < dimension ; j ++ ) { if ( j != dimension - 1 ) { fwall . write ( String . valueOf ( W [ i ] [ j ] ) + " " ) ; } else { fwall . write ( String . valueOf ( W [ i ] [ j ] ) + '\n' ) ; } } } fwall . close ( ) ; }
Write the trained embedding to certain files.
178
private static Mode decodeAsciiSegment ( BitSource bits , StringBuilder result , StringBuilder resultTrailer ) throws FormatException { boolean upperShift = false ; do { int oneByte = bits . readBits ( 8 ) ; if ( oneByte == 0 ) { throw FormatException . getFormatInstance ( ) ; } else if ( oneByte <= 128 ) { if ( upperShift ) { oneByte += 128 ; } result . append ( ( char ) ( oneByte - 1 ) ) ; return Mode . ASCII_ENCODE ; } else if ( oneByte == 129 ) { return Mode . PAD_ENCODE ; } else if ( oneByte <= 229 ) { int value = oneByte - 130 ; if ( value < 10 ) { result . append ( '0' ) ; } result . append ( value ) ; } else if ( oneByte == 230 ) { return Mode . C40_ENCODE ; } else if ( oneByte == 231 ) { return Mode . BASE256_ENCODE ; } else if ( oneByte == 232 ) { result . append ( ( char ) 29 ) ; } else if ( oneByte == 233 || oneByte == 234 ) { } else if ( oneByte == 235 ) { upperShift = true ; } else if ( oneByte == 236 ) { result . append ( "[)>05" ) ; resultTrailer . insert ( 0 , "" ) ; } else if ( oneByte == 237 ) { result . append ( "[)>06" ) ; resultTrailer . insert ( 0 , "" ) ; } else if ( oneByte == 238 ) { return Mode . ANSIX12_ENCODE ; } else if ( oneByte == 239 ) { return Mode . TEXT_ENCODE ; } else if ( oneByte == 240 ) { return Mode . EDIFACT_ENCODE ; } else if ( oneByte == 241 ) { } else if ( oneByte >= 242 ) { if ( oneByte != 254 || bits . available ( ) != 0 ) { throw FormatException . getFormatInstance ( ) ; } } } while ( bits . available ( ) > 0 ) ; return Mode . ASCII_ENCODE ; }
See ISO 16022:2006, 5.2.3 and Annex C, Table C.2
179
public static String unhtmlAngleBrackets ( String str ) { str = str . replaceAll ( "&lt;" , "<" ) ; str = str . replaceAll ( "&gt;" , ">" ) ; return str ; }
Replace &amp;lt; &amp;gt; entities with &lt; &gt; characters.
180
public long next ( long fromTime ) { if ( getCurrentCount ( ) == 0 || fromTime == 0 || fromTime == startDate . getTime ( ) ) { return first ( ) ; } if ( Debug . verboseOn ( ) ) { Debug . logVerbose ( "Date List Size: " + ( rDateList == null ? 0 : rDateList . size ( ) ) , module ) ; Debug . logVerbose ( "Rule List Size: " + ( rRulesList == null ? 0 : rRulesList . size ( ) ) , module ) ; } if ( rDateList == null && rRulesList == null ) { return 0 ; } long nextRuleTime = fromTime ; boolean hasNext = true ; Iterator < RecurrenceRule > rulesIterator = getRecurrenceRuleIterator ( ) ; while ( rulesIterator . hasNext ( ) ) { RecurrenceRule rule = rulesIterator . next ( ) ; while ( hasNext ) { nextRuleTime = getNextTime ( rule , nextRuleTime ) ; if ( nextRuleTime == 0 || isValid ( nextRuleTime ) ) { hasNext = false ; } } } return nextRuleTime ; }
Returns the next recurrence from the specified time.
181
public static boolean isFileExist ( String filePath , FileType fileType , boolean performFileCheck ) throws IOException { filePath = filePath . replace ( "\\" , "/" ) ; switch ( fileType ) { case HDFS : case VIEWFS : Path path = new Path ( filePath ) ; FileSystem fs = path . getFileSystem ( configuration ) ; if ( performFileCheck ) { return fs . exists ( path ) && fs . isFile ( path ) ; } else { return fs . exists ( path ) ; } case LOCAL : default : File defaultFile = new File ( filePath ) ; if ( performFileCheck ) { return defaultFile . exists ( ) && defaultFile . isFile ( ) ; } else { return defaultFile . exists ( ) ; } } }
This method checks the given path exists or not and also is it file or not if the performFileCheck is true
182
public ResultT extractLatestAttempted ( ) { ArrayList < UpdateT > updates = new ArrayList < > ( inflightAttempted . size ( ) + 1 ) ; synchronized ( attemptedLock ) { updates . add ( finishedAttempted ) ; updates . addAll ( inflightAttempted . values ( ) ) ; } return aggregation . extract ( aggregation . combine ( updates ) ) ; }
Extract the latest values from all attempted and in-progress bundles.
183
public Set < JsonUser > loadKnownUsers ( ) throws InterruptedException , ExecutionException , RemoteException , OperationApplicationException { Set < JsonUser > users = getUsersFromDb ( ) ; if ( users . isEmpty ( ) ) { LOG . i ( "Database contains no user; fetching from server" ) ; users = syncKnownUsers ( ) ; } LOG . i ( String . format ( "Found %d users in db" , users . size ( ) ) ) ; return users ; }
Loads the known users from local store. If there is no user in db or the application can't retrieve from there, then it fetches the users from server
184
public void start ( ) { eventLogThread . start ( ) ; LOGGER . info ( "Started " + eventLogThread . getName ( ) + " with ID " + eventLogThread . getId ( ) + "." ) ; }
Starts the event log thread.
185
private static String htmlencode ( String str ) { if ( str == null ) { return "" ; } else { StringBuilder buf = new StringBuilder ( ) ; for ( char ch : str . toCharArray ( ) ) { switch ( ch ) { case '<' : buf . append ( "&lt;" ) ; break ; case '>' : buf . append ( "&gt;" ) ; break ; case '&' : buf . append ( "&amp;" ) ; break ; default : buf . append ( ch ) ; break ; } } return buf . toString ( ) ; } }
Escapes all '<', '>' and '&' characters in a string.
186
public void testCase3 ( ) { byte aBytes [ ] = { 3 , 4 , 5 , 6 , 7 , 8 , 9 } ; byte bBytes [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 } ; byte rBytes [ ] = { 2 , 2 , 2 , 2 , 2 , 2 , 2 } ; int aSign = 1 ; int bSign = - 1 ; BigInteger aNumber = new BigInteger ( aSign , aBytes ) ; BigInteger bNumber = new BigInteger ( bSign , bBytes ) ; BigInteger result = aNumber . add ( bNumber ) ; byte resBytes [ ] = new byte [ rBytes . length ] ; resBytes = result . toByteArray ( ) ; for ( int i = 0 ; i < resBytes . length ; i ++ ) { assertTrue ( resBytes [ i ] == rBytes [ i ] ) ; } assertEquals ( "incorrect sign" , 1 , result . signum ( ) ) ; }
Add two numbers of the same length. The first one is positive and the second is negative. The first one is greater in absolute value.
187
public static void begin ( ServletRequest request , ServletResponse response , String serviceName , String objectId ) throws ServletException { ServiceContext context = ( ServiceContext ) _localContext . get ( ) ; if ( context == null ) { context = new ServiceContext ( ) ; _localContext . set ( context ) ; } context . _request = request ; context . _response = response ; context . _serviceName = serviceName ; context . _objectId = objectId ; context . _count ++ ; }
Sets the request object prior to calling the service's method.
188
public final BufferedImage loadStoredImage ( String current_image ) { if ( current_image == null ) { return null ; } current_image = removeIllegalFileNameCharacters ( current_image ) ; final String flag = image_type . get ( current_image ) ; BufferedImage image = null ; if ( flag == null ) { return null ; } else if ( flag . equals ( "tif" ) ) { image = loadStoredImage ( current_image , ".tif" ) ; } else if ( flag . equals ( "jpg" ) ) { image = loadStoredJPEGImage ( current_image ) ; } else if ( flag . equals ( "png" ) ) { image = loadStoredImage ( current_image , ".png" ) ; } else if ( flag . equals ( "jpl" ) ) { image = loadStoredImage ( current_image , ".jpl" ) ; } return image ; }
load a image when required and remove from store
189
public boolean canUseCachedProjectData ( ) { if ( ! myGradlePluginVersion . equals ( GRADLE_PLUGIN_RECOMMENDED_VERSION ) ) { return false ; } for ( Map . Entry < String , byte [ ] > entry : myFileChecksums . entrySet ( ) ) { File file = new File ( entry . getKey ( ) ) ; if ( ! file . isAbsolute ( ) ) { file = new File ( myRootDirPath , file . getPath ( ) ) ; } try { if ( ! Arrays . equals ( entry . getValue ( ) , createChecksum ( file ) ) ) { return false ; } } catch ( IOException e ) { return false ; } } return true ; }
Verifies that whether the persisted external project data can be used to create the project or not. <p/> This validates that all the files that the external project data depends on, still have the same content checksum and that the gradle model version is still the same.
190
protected void waitForImage ( Image image ) { int id = ++ nextTrackerID ; tracker . addImage ( image , id ) ; try { tracker . waitForID ( id , 0 ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } tracker . removeImage ( image , id ) ; }
Wait for an image to load.
191
public static String stripFileProtocol ( String uriString ) { if ( uriString . startsWith ( "file://" ) ) { uriString = uriString . substring ( 7 ) ; } return uriString ; }
Removes the "file://" prefix from the given URI string, if applicable. If the given URI string doesn't have a "file://" prefix, it is returned unchanged.
192
@ Override public Object [ ] toArray ( ) { return newArray ( new Object [ size ( ) ] ) ; }
Returns all the elements in an array. The result is a copy of all the elements.
193
private static boolean isNonLeft ( int i0 , int i1 , int i2 , int i3 , double [ ] pts ) { double l1 , l2 , l4 , l5 , l6 , angle1 , angle2 , angle ; l1 = Math . sqrt ( Math . pow ( pts [ i2 + 1 ] - pts [ i1 + 1 ] , 2 ) + Math . pow ( pts [ i2 ] - pts [ i1 ] , 2 ) ) ; l2 = Math . sqrt ( Math . pow ( pts [ i3 + 1 ] - pts [ i2 + 1 ] , 2 ) + Math . pow ( pts [ i3 ] - pts [ i2 ] , 2 ) ) ; l4 = Math . sqrt ( Math . pow ( pts [ i3 + 1 ] - pts [ i0 + 1 ] , 2 ) + Math . pow ( pts [ i3 ] - pts [ i0 ] , 2 ) ) ; l5 = Math . sqrt ( Math . pow ( pts [ i1 + 1 ] - pts [ i0 + 1 ] , 2 ) + Math . pow ( pts [ i1 ] - pts [ i0 ] , 2 ) ) ; l6 = Math . sqrt ( Math . pow ( pts [ i2 + 1 ] - pts [ i0 + 1 ] , 2 ) + Math . pow ( pts [ i2 ] - pts [ i0 ] , 2 ) ) ; angle1 = Math . acos ( ( ( l2 * l2 ) + ( l6 * l6 ) - ( l4 * l4 ) ) / ( 2 * l2 * l6 ) ) ; angle2 = Math . acos ( ( ( l6 * l6 ) + ( l1 * l1 ) - ( l5 * l5 ) ) / ( 2 * l6 * l1 ) ) ; angle = ( Math . PI - angle1 ) - angle2 ; if ( angle <= 0.0 ) { return ( true ) ; } else { return ( false ) ; } }
Convex hull helper method for detecting a non left turn about 3 points
194
@ RequestMapping ( value = "/SAML2/SLO/{tenant:.*}" ) public void sloError ( Locale locale , @ PathVariable ( value = "tenant" ) String tenant , HttpServletResponse response ) throws IOException { logger . info ( "SLO binding error! The client locale is " + locale . toString ( ) + ", tenant is " + tenant ) ; sloDefaultTenantBindingError ( locale , response ) ; }
Handle request sent with a wrong binding
195
public static double cdf ( double x , double lambda ) { return 1.0 - Math . exp ( - lambda * x ) ; }
cumulative density function of the exponential distribution
196
public void testAddMathContextDiffScalePosNeg ( ) { String a = "1231212478987482988429808779810457634781384756794987" ; int aScale = 15 ; String b = "747233429293018787918347987234564568" ; int bScale = - 10 ; String c = "7.47233429416141E+45" ; int cScale = - 31 ; BigDecimal aNumber = new BigDecimal ( new BigInteger ( a ) , aScale ) ; BigDecimal bNumber = new BigDecimal ( new BigInteger ( b ) , bScale ) ; MathContext mc = new MathContext ( 15 , RoundingMode . CEILING ) ; BigDecimal result = aNumber . add ( bNumber , mc ) ; assertEquals ( "incorrect value" , c , c . toString ( ) ) ; assertEquals ( "incorrect scale" , cScale , result . scale ( ) ) ; }
Add two numbers of different scales using MathContext; the first is positive
197
private boolean isDerivedByRestriction ( String ancestorNS , String ancestorName , XSTypeDefinition type ) { XSTypeDefinition oldType = null ; while ( type != null && type != oldType ) { if ( ( ancestorName . equals ( type . getName ( ) ) ) && ( ( ancestorNS != null && ancestorNS . equals ( type . getNamespace ( ) ) ) || ( type . getNamespace ( ) == null && ancestorNS == null ) ) ) { return true ; } oldType = type ; type = type . getBaseType ( ) ; } return false ; }
DOM Level 3 Checks if a type is derived from another by restriction. See: http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#TypeInfo-isDerivedFrom
198
protected Document createConfigurationDocument ( AVList params ) { Document doc = super . createConfigurationDocument ( params ) ; if ( doc == null || doc . getDocumentElement ( ) == null ) return doc ; DataConfigurationUtils . createWMSLayerConfigElements ( params , doc . getDocumentElement ( ) ) ; return doc ; }
Appends WMS tiled image layer configuration elements to the superclass configuration document.
199
public static void onOperatorError ( BiFunction < ? super Throwable , Object , ? extends Throwable > f ) { log . info ( "Hooking new default : onOperatorError" ) ; onOperatorErrorHook = Objects . requireNonNull ( f , "onOperatorErrorHook" ) ; }
Override global operator error mapping which by default add as suppressed exception either data driven exception or error driven exception.