signature
stringlengths
43
39.1k
implementation
stringlengths
0
450k
public class TileDaoUtils { /** * Adjust the tile matrix lengths if needed . Check if the tile matrix width * and height need to expand to account for pixel * number of pixels fitting * into the tile matrix lengths * @ param tileMatrixSet * tile matrix set * @ param tileMatrices * tile matrices */ public static void adjustTileMatrixLengths ( TileMatrixSet tileMatrixSet , List < TileMatrix > tileMatrices ) { } }
double tileMatrixWidth = tileMatrixSet . getMaxX ( ) - tileMatrixSet . getMinX ( ) ; double tileMatrixHeight = tileMatrixSet . getMaxY ( ) - tileMatrixSet . getMinY ( ) ; for ( TileMatrix tileMatrix : tileMatrices ) { int tempMatrixWidth = ( int ) ( tileMatrixWidth / ( tileMatrix . getPixelXSize ( ) * tileMatrix . getTileWidth ( ) ) ) ; int tempMatrixHeight = ( int ) ( tileMatrixHeight / ( tileMatrix . getPixelYSize ( ) * tileMatrix . getTileHeight ( ) ) ) ; if ( tempMatrixWidth > tileMatrix . getMatrixWidth ( ) ) { tileMatrix . setMatrixWidth ( tempMatrixWidth ) ; } if ( tempMatrixHeight > tileMatrix . getMatrixHeight ( ) ) { tileMatrix . setMatrixHeight ( tempMatrixHeight ) ; } }
public class BigDecimal { /** * Compute val * 10 ^ n ; return this product if it is * representable as a long , INFLATED otherwise . */ private static long longMultiplyPowerTen ( long val , int n ) { } }
if ( val == 0 || n <= 0 ) return val ; long [ ] tab = LONG_TEN_POWERS_TABLE ; long [ ] bounds = THRESHOLDS_TABLE ; if ( n < tab . length && n < bounds . length ) { long tenpower = tab [ n ] ; if ( val == 1 ) return tenpower ; if ( Math . abs ( val ) <= bounds [ n ] ) return val * tenpower ; } return INFLATED ;
public class MethodWriterImpl { /** * { @ inheritDoc } */ @ Override public void addTags ( ExecutableElement method , Content methodDocTree ) { } }
writer . addTagsInfo ( method , methodDocTree ) ;
public class GraphHuffman { /** * Build the Huffman tree given an array of vertex degrees * @ param vertexDegree vertexDegree [ i ] = degree of ith vertex */ public void buildTree ( int [ ] vertexDegree ) { } }
PriorityQueue < Node > pq = new PriorityQueue < > ( ) ; for ( int i = 0 ; i < vertexDegree . length ; i ++ ) pq . add ( new Node ( i , vertexDegree [ i ] , null , null ) ) ; while ( pq . size ( ) > 1 ) { Node left = pq . remove ( ) ; Node right = pq . remove ( ) ; Node newNode = new Node ( - 1 , left . count + right . count , left , right ) ; pq . add ( newNode ) ; } // Eventually : only one node left - > full tree Node tree = pq . remove ( ) ; // Now : convert tree into binary codes . Traverse tree ( preorder traversal ) - > record path ( left / right ) - > code int [ ] innerNodePath = new int [ MAX_CODE_LENGTH ] ; traverse ( tree , 0L , ( byte ) 0 , - 1 , innerNodePath , 0 ) ;
public class ReportDownloadOptions { /** * Sets the exportFormat value for this ReportDownloadOptions . * @ param exportFormat * The { @ link ExportFormat } used to generate the report . * Default value is { @ link ExportFormat # CSV _ DUMP } . */ public void setExportFormat ( com . google . api . ads . admanager . axis . v201902 . ExportFormat exportFormat ) { } }
this . exportFormat = exportFormat ;
public class AzureBatchDriverConfigurationProviderImpl { /** * Assembles the Driver configuration . * @ param jobFolder the job folder . * @ param clientRemoteId the client remote id . * @ param jobId the job id . * @ param applicationConfiguration the application configuration . * @ return the Driver configuration . */ @ Override public Configuration getDriverConfiguration ( final URI jobFolder , final String clientRemoteId , final String jobId , final Configuration applicationConfiguration ) { } }
ConfigurationModuleBuilder driverConfigurationBuilder = AzureBatchDriverConfiguration . CONF . getBuilder ( ) . bindImplementation ( CommandBuilder . class , this . commandBuilder . getClass ( ) ) ; // If using docker containers , then use a different set of bindings if ( this . containerRegistryProvider . isValid ( ) ) { driverConfigurationBuilder = driverConfigurationBuilder . bindImplementation ( LocalAddressProvider . class , ContainerBasedLocalAddressProvider . class ) . bindImplementation ( TcpPortProvider . class , SetTcpPortProvider . class ) ; } final Configuration driverConfiguration = driverConfigurationBuilder . build ( ) . set ( AzureBatchDriverConfiguration . JOB_IDENTIFIER , jobId ) . set ( AzureBatchDriverConfiguration . CLIENT_REMOTE_IDENTIFIER , clientRemoteId ) . set ( AzureBatchDriverConfiguration . JVM_HEAP_SLACK , this . jvmSlack ) . set ( AzureBatchDriverConfiguration . RUNTIME_NAME , RuntimeIdentifier . RUNTIME_NAME ) . set ( AzureBatchDriverConfiguration . AZURE_BATCH_ACCOUNT_URI , this . azureBatchAccountUri ) . set ( AzureBatchDriverConfiguration . AZURE_BATCH_ACCOUNT_NAME , this . azureBatchAccountName ) . set ( AzureBatchDriverConfiguration . AZURE_BATCH_POOL_ID , this . azureBatchPoolId ) . set ( AzureBatchDriverConfiguration . AZURE_STORAGE_ACCOUNT_NAME , this . azureStorageAccountName ) . set ( AzureBatchDriverConfiguration . AZURE_STORAGE_CONTAINER_NAME , this . azureStorageContainerName ) . set ( AzureBatchDriverConfiguration . CONTAINER_REGISTRY_SERVER , this . containerRegistryProvider . getContainerRegistryServer ( ) ) . set ( AzureBatchDriverConfiguration . CONTAINER_REGISTRY_USERNAME , this . containerRegistryProvider . getContainerRegistryUsername ( ) ) . set ( AzureBatchDriverConfiguration . CONTAINER_REGISTRY_PASSWORD , this . containerRegistryProvider . getContainerRegistryPassword ( ) ) . set ( AzureBatchDriverConfiguration . CONTAINER_IMAGE_NAME , this . containerRegistryProvider . getContainerImageName ( ) ) . setMultiple ( AzureBatchDriverConfiguration . TCP_PORT_SET , this . tcpPortSet ) . build ( ) ; return Configurations . merge ( driverConfiguration , applicationConfiguration ) ;
public class CeylonSdkDownload { /** * Does the actual retrieval . * @ param outputFile The file to write to * @ param repoUrl * @ throws Exception When SDK cannot be retrieved * TODO add proxy and listener and externalize timeout */ private void doGet ( final File outputFile , final String repoUrl ) throws Exception { } }
int readTimeOut = 5 * 60 * 1000 ; Repository repository = new Repository ( repoUrl , repoUrl ) ; wagon . setReadTimeout ( readTimeOut ) ; getLog ( ) . info ( "Read Timeout is set to " + readTimeOut + " milliseconds" ) ; wagon . connect ( repository ) ; wagon . get ( outputFile . getName ( ) , outputFile ) ; wagon . disconnect ( ) ;
public class LogHandle { /** * This method forms part of the keypoint processing logic . It must only be called * from the RecoveryLog . keypoint ( ) method . * RecoveryLog . keypoint will have re - written all currently active data to the * recovery logs keypoint file ( the inactive file when the keypoint was triggered ) * This method will now compelte the keypoint operation by forcing this data to * disk and then marking the old log file INACTIVE . * @ exception InternalLogException An unexpected error has occured . */ public void keypoint ( ) throws InternalLogException { } }
if ( tc . isEntryEnabled ( ) ) Tr . entry ( tc , "keypoint" , this ) ; try { if ( tc . isDebugEnabled ( ) ) Tr . debug ( tc , "Keypointing with isSnapshotSafe set to " + Configuration . _isSnapshotSafe ) ; // Attempt to get exclusive lock on the lock object provided by RecoveryLogService // to protect access to the isSuspended flag , which is toggled during calls // to RecoveryLogService suspend / resume synchronized ( RLSControllerImpl . SUSPEND_LOCK ) { while ( RLSControllerImpl . isSuspended ( ) ) { try { if ( tc . isDebugEnabled ( ) ) Tr . debug ( tc , "Waiting for RecoveryLogService to resume" ) ; RLSControllerImpl . SUSPEND_LOCK . wait ( ) ; } catch ( InterruptedException exc ) { // This exception is received if another thread interrupts this thread by calling this threads // Thread . interrupt method . The RecoveryLogService class does not use this mechanism for // breaking out of the wait call - it uses notifyAll to wake up all waiting threads . This // exception should never be generated . If for some reason it is called then ignore it and // start to wait again . FFDCFilter . processException ( exc , "com.ibm.ws.recoverylog.spi.LogHandle.keypoint" , "923" , this ) ; } } if ( Configuration . _isSnapshotSafe ) { if ( tc . isDebugEnabled ( ) ) Tr . debug ( tc , "Keypointing with isSnapshotSafe set to " + Configuration . _isSnapshotSafe ) ; // Check if we ' ve been configured to run in snapshot safe mode // With this in place we synchronize all keypointInternal method calls and // take the synchronization performance hit . The benefit is that we // can be sure that the log files will be in a consistent state // for snapshotting keypointInternal ( ) ; } } // If we ' re not configured to be snapshot safe then we // run a slight risk here that a force operation could be called // just after the RecoveryLogService has been called to suspend , // as we ' re outwith the sync block . // The benefit is that we don ' t have the synchronization performance // hit when calling the force method if ( ! Configuration . _isSnapshotSafe ) { if ( tc . isDebugEnabled ( ) ) Tr . debug ( tc , "Keypointing with isSnapshotSafe set to " + Configuration . _isSnapshotSafe ) ; keypointInternal ( ) ; } } catch ( InternalLogException exc ) { FFDCFilter . processException ( exc , "com.ibm.ws.recoverylog.spi.LogHandle.keypoint" , "932" , this ) ; if ( tc . isEntryEnabled ( ) ) Tr . exit ( tc , "keypoint" , exc ) ; throw exc ; } if ( tc . isEntryEnabled ( ) ) Tr . exit ( tc , "keypoint" ) ;
public class MapUtil { /** * 对一个Map按Value进行排序 , 返回排序LinkedHashMap , 最多只返回n条 , 多用于Value是Counter的情况 . */ public static < K , V > Map < K , V > topNByValue ( Map < K , V > map , final Comparator < ? super V > comparator , int n ) { } }
return topNByValueInternal ( map , n , new EntryValueComparator < K , V > ( comparator ) ) ;
public class AbstractIoSession { /** * TODO Add method documentation */ public final void increaseScheduledWriteBytes ( int increment ) { } }
scheduledWriteBytes . addAndGet ( increment ) ; if ( getService ( ) instanceof AbstractIoService ) { getService ( ) . getStatistics ( ) . increaseScheduledWriteBytes ( increment ) ; }
public class CPRuleUserSegmentRelPersistenceImpl { /** * Returns all the cp rule user segment rels . * @ return the cp rule user segment rels */ @ Override public List < CPRuleUserSegmentRel > findAll ( ) { } }
return findAll ( QueryUtil . ALL_POS , QueryUtil . ALL_POS , null ) ;
public class Threads { /** * This method recursively visits all thread groups under ' group ' , * searching for the active thread with name ' threadName ' . * @ param group * @ param threadName * @ return */ private static Thread findActiveThreadByName ( ThreadGroup group , String threadName ) { } }
Thread result = null ; // Get threads in ' group ' int numThreads = group . activeCount ( ) ; Thread [ ] threads = new Thread [ numThreads * 2 ] ; numThreads = group . enumerate ( threads , false ) ; // Enumerate each thread in ' group ' for ( int i = 0 ; i < numThreads ; i ++ ) { if ( threads [ i ] . getName ( ) . equals ( threadName ) ) { return threads [ i ] ; } } // Get thread subgroups of ' group ' int numGroups = group . activeGroupCount ( ) ; ThreadGroup [ ] groups = new ThreadGroup [ numGroups * 2 ] ; numGroups = group . enumerate ( groups , false ) ; // Recursively visit each subgroup for ( int i = 0 ; i < numGroups ; i ++ ) { result = findActiveThreadByName ( groups [ i ] , threadName ) ; if ( result != null ) { break ; } } return result ;
public class SentencesUtil { /** * 文本分句 * @ param content 文本 * @ param shortest 是否切割为最细的单位 ( 将逗号也视作分隔符 ) * @ return */ public static List < String > toSentenceList ( String content , boolean shortest ) { } }
return toSentenceList ( content . toCharArray ( ) , shortest ) ;
public class RssServlet { /** * Finds the news , returns { @ code null } when not able to find the news . * Limits the number of news entries per book " maxItems " settings . */ private static List < News > findNews ( ServletContext servletContext , HttpServletRequest req , HttpServletResponse resp , SemanticCMS semanticCMS , Page page ) throws ServletException , IOException { } }
Book book = semanticCMS . getBook ( page . getPageRef ( ) . getBookRef ( ) ) ; Map < String , String > bookParams = book . getParam ( ) ; // Find the news int maxItems ; { String maxItemsVal = getBookParam ( bookParams , CHANNEL_PARAM_PREFIX + "maxItems" ) ; if ( maxItemsVal != null ) { maxItems = Integer . parseInt ( maxItemsVal ) ; if ( maxItems < 1 ) throw new ServletException ( "RSS maxItems may not be less than one: " + maxItems ) ; } else { maxItems = DEFAULT_MAX_ITEMS ; } } List < News > allNews = NewsUtils . findAllNews ( servletContext , req , resp , page ) ; if ( allNews . size ( ) > maxItems ) allNews = allNews . subList ( 0 , maxItems ) ; return allNews ;
public class GeneratePythonlibDoc { /** * Generates the documentation of scripts located in a pythonlib directory . */ public static synchronized void generate ( ) { } }
LOGGER . debug ( "Generating documentation of test documentation included in pythonlib directories." ) ; try { IS_RUNNING = true ; List < File > pythonLibDirectories = findPythonLibDirectories ( ROOT_SCRIPT_DIRECTORY ) ; List < File > pythonScriptFiles = findPythonScripts ( pythonLibDirectories ) ; for ( File script : pythonScriptFiles ) { if ( hasToGenerateDocumentation ( script ) ) { GenerateTestStepsModulesDoc . generate ( script . getAbsolutePath ( ) ) ; } } ALREADY_RUN = true ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; } finally { IS_RUNNING = false ; }
public class EntityTypeUtils { /** * Returns whether the attribute type references single entities ( e . g . is ' XREF ' ) . * @ param attr attribute * @ return true if an attribute references a single entity */ public static boolean isSingleReferenceType ( Attribute attr ) { } }
AttributeType attrType = attr . getDataType ( ) ; switch ( attrType ) { case CATEGORICAL : case FILE : case XREF : return true ; case BOOL : case CATEGORICAL_MREF : case COMPOUND : case DATE : case DATE_TIME : case DECIMAL : case EMAIL : case ENUM : case HTML : case HYPERLINK : case INT : case LONG : case MREF : case ONE_TO_MANY : case SCRIPT : case STRING : case TEXT : return false ; default : throw new UnexpectedEnumException ( attrType ) ; }
public class PackageManagerUtils { /** * Checks if the device has a compass sensor . * @ param manager the package manager . * @ return { @ code true } if the device has a compass sensor . */ @ TargetApi ( Build . VERSION_CODES . FROYO ) public static boolean hasCompassSensorFeature ( PackageManager manager ) { } }
return manager . hasSystemFeature ( PackageManager . FEATURE_SENSOR_COMPASS ) ;
public class UpdatableResultSet { /** * { inheritDoc } . */ public void updateBinaryStream ( int columnIndex , InputStream inputStream , int length ) throws SQLException { } }
updateBinaryStream ( columnIndex , inputStream , ( long ) length ) ;
public class AbstractRemoteClient { /** * Method adds an handler to the internal rsb listener . * @ param handler * @ param wait * @ throws InterruptedException * @ throws CouldNotPerformException */ public void addHandler ( final Handler handler , final boolean wait ) throws InterruptedException , CouldNotPerformException { } }
try { listener . addHandler ( handler , wait ) ; } catch ( CouldNotPerformException ex ) { throw new CouldNotPerformException ( "Could not register Handler!" , ex ) ; }
public class ClassDocImpl { /** * Return the class name as a string . If " full " is true the name is * qualified , otherwise it is qualified by its enclosing class ( es ) only . */ static String getClassName ( ClassSymbol c , boolean full ) { } }
if ( full ) { return c . getQualifiedName ( ) . toString ( ) ; } else { String n = "" ; for ( ; c != null ; c = c . owner . enclClass ( ) ) { n = c . name + ( n . equals ( "" ) ? "" : "." ) + n ; } return n ; }
public class AgentServlet { /** * Fallback used if URL creation didnt work */ private String plainReplacement ( String pUrl , String pServletPath ) { } }
int idx = pUrl . lastIndexOf ( pServletPath ) ; String url ; if ( idx != - 1 ) { url = pUrl . substring ( 0 , idx ) + pServletPath ; } else { url = pUrl ; } return url ;
public class JpaEntityRepositoryBase { /** * if single relationship is requested , perform eager loading . For example , helps to * optimize loading uni - directional associations during inclusions ( used the default * relationship repositories ) */ private boolean optimizeForInclusion ( QuerySpec querySpec ) { } }
ResourceField idField = getIdField ( ) ; return querySpec . getIncludedRelations ( ) . size ( ) == 1 && querySpec . getIncludedFields ( ) . size ( ) == 1 && idField . getUnderlyingName ( ) . equals ( querySpec . getIncludedFields ( ) . get ( 0 ) . getPath ( ) . toString ( ) ) ;
public class WrappedByteBuffer { /** * Fills the buffer with a specific number of repeated bytes . * @ param b * the byte to repeat * @ param size * the number of times to repeat * @ return the buffer */ public WrappedByteBuffer fillWith ( byte b , int size ) { } }
_autoExpand ( size ) ; while ( size -- > 0 ) { _buf . put ( b ) ; } return this ;
public class DataColumnPairGroupServiceImpl { /** * 用于Model对象转化为DO对象 * @ param dataColumnPair * @ return DataMediaPairDO */ private DataColumnPairGroupDO modelToDo ( ColumnGroup columnGroup ) { } }
DataColumnPairGroupDO dataColumnPairGroupDo = new DataColumnPairGroupDO ( ) ; dataColumnPairGroupDo . setId ( columnGroup . getId ( ) ) ; dataColumnPairGroupDo . setColumnPairContent ( JsonUtils . marshalToString ( columnGroup . getColumnPairs ( ) ) ) ; dataColumnPairGroupDo . setDataMediaPairId ( columnGroup . getDataMediaPairId ( ) ) ; dataColumnPairGroupDo . setGmtCreate ( columnGroup . getGmtCreate ( ) ) ; dataColumnPairGroupDo . setGmtModified ( columnGroup . getGmtModified ( ) ) ; return dataColumnPairGroupDo ;
public class GroupByQueryQueryToolChest { /** * This function checks the query for dimensions which can be optimized by applying the dimension extraction * as the final step of the query instead of on every event . * @ param query The query to check for optimizations * @ return A collection of DimensionsSpec which can be extracted at the last second upon query completion . */ public static Collection < DimensionSpec > extractionsToRewrite ( GroupByQuery query ) { } }
return Collections2 . filter ( query . getDimensions ( ) , new Predicate < DimensionSpec > ( ) { @ Override public boolean apply ( DimensionSpec input ) { return input . getExtractionFn ( ) != null && ExtractionFn . ExtractionType . ONE_TO_ONE . equals ( input . getExtractionFn ( ) . getExtractionType ( ) ) ; } } ) ;
public class LambdaToMethod { /** * Translate identifiers within a lambda to the mapped identifier * @ param tree */ @ Override public void visitIdent ( JCIdent tree ) { } }
if ( context == null || ! analyzer . lambdaIdentSymbolFilter ( tree . sym ) ) { super . visitIdent ( tree ) ; } else { int prevPos = make . pos ; try { make . at ( tree ) ; LambdaTranslationContext lambdaContext = ( LambdaTranslationContext ) context ; JCTree ltree = lambdaContext . translate ( tree ) ; if ( ltree != null ) { result = ltree ; } else { // access to untranslated symbols ( i . e . compile - time constants , // members defined inside the lambda body , etc . ) ) super . visitIdent ( tree ) ; } } finally { make . at ( prevPos ) ; } }
public class KeyVaultClientBaseImpl { /** * List secrets in a specified key vault . * The Get Secrets operation is applicable to the entire vault . However , only the base secret identifier and its attributes are provided in the response . Individual secret versions are not listed in the response . This operation requires the secrets / list permission . * @ param nextPageLink The NextLink from the previous successful call to List operation . * @ throws IllegalArgumentException thrown if parameters fail the validation * @ return the observable to the PagedList & lt ; SecretItem & gt ; object */ public Observable < Page < SecretItem > > getSecretsNextAsync ( final String nextPageLink ) { } }
return getSecretsNextWithServiceResponseAsync ( nextPageLink ) . map ( new Func1 < ServiceResponse < Page < SecretItem > > , Page < SecretItem > > ( ) { @ Override public Page < SecretItem > call ( ServiceResponse < Page < SecretItem > > response ) { return response . body ( ) ; } } ) ;
public class HttpResponse { /** * Get http response */ public static HttpResponse getResponse ( String urls , HttpRequest request , HttpMethod method , int connectTimeoutMillis , int readTimeoutMillis ) throws IOException { } }
OutputStream out = null ; InputStream content = null ; HttpResponse response = null ; HttpURLConnection httpConn = request . getHttpConnection ( urls , method . name ( ) ) ; httpConn . setConnectTimeout ( connectTimeoutMillis ) ; httpConn . setReadTimeout ( readTimeoutMillis ) ; try { httpConn . connect ( ) ; if ( null != request . getPayload ( ) && request . getPayload ( ) . length > 0 ) { out = httpConn . getOutputStream ( ) ; out . write ( request . getPayload ( ) ) ; } content = httpConn . getInputStream ( ) ; response = new HttpResponse ( ) ; parseHttpConn ( response , httpConn , content ) ; return response ; } catch ( SocketTimeoutException e ) { throw e ; } catch ( IOException e ) { content = httpConn . getErrorStream ( ) ; response = new HttpResponse ( ) ; parseHttpConn ( response , httpConn , content ) ; return response ; } finally { if ( content != null ) { content . close ( ) ; } httpConn . disconnect ( ) ; }
public class S3Location { /** * Sets the canned ACL to apply to the restore results . * @ param cannedACL The new cannedACL value . * @ return This object for method chaining . */ public S3Location withCannedACL ( CannedAccessControlList cannedACL ) { } }
setCannedACL ( cannedACL == null ? null : cannedACL . toString ( ) ) ; return this ;
public class JavaAudio { /** * Creates a sound instance from the audio data available via { @ code in } . * @ param rsrc an resource instance via which the audio data can be read . * @ param music if true , a custom { @ link Clip } implementation will be used which can handle long * audio clips ; if false , the default Java clip implementation is used which cannot handle long * audio clips . */ public JavaSound createSound ( final JavaAssets . Resource rsrc , final boolean music ) { } }
final JavaSound sound = new JavaSound ( exec ) ; exec . invokeAsync ( new Runnable ( ) { public void run ( ) { try { AudioInputStream ais = rsrc . openAudioStream ( ) ; AudioFormat format = ais . getFormat ( ) ; Clip clip ; if ( music ) { // BigClip needs sounds in PCM _ SIGNED format ; it attempts to do this conversion // internally , but the way it does it fails in some circumstances , so we do it out here if ( format . getEncoding ( ) != AudioFormat . Encoding . PCM_SIGNED ) { ais = AudioSystem . getAudioInputStream ( new AudioFormat ( AudioFormat . Encoding . PCM_SIGNED , format . getSampleRate ( ) , 16 , // we have to force sample size to 16 format . getChannels ( ) , format . getChannels ( ) * 2 , format . getSampleRate ( ) , false // big endian ) , ais ) ; } clip = new BigClip ( ) ; } else { DataLine . Info info = new DataLine . Info ( Clip . class , format ) ; clip = ( Clip ) AudioSystem . getLine ( info ) ; } clip . open ( ais ) ; sound . succeed ( clip ) ; } catch ( Exception e ) { sound . fail ( e ) ; } } } ) ; return sound ;
public class StringUtils { /** * URL - Encodes a given string using UTF - 8 ( some web pages have problems with UTF - 8 and umlauts , consider * { @ link # encodeUrlIso ( String ) } also ) . No UnsupportedEncodingException to handle as it is dealt with in this * method . */ public static String encodeUrl ( String stringToEncode ) { } }
try { return URLEncoder . encode ( stringToEncode , "UTF-8" ) ; } catch ( UnsupportedEncodingException e1 ) { throw new RuntimeException ( e1 ) ; }
public class AbstractPluginRegistry { /** * Creates a plugin classloader for the given plugin file . */ protected PluginClassLoader createPluginClassLoader ( final File pluginFile ) throws IOException { } }
return new PluginClassLoader ( pluginFile , Thread . currentThread ( ) . getContextClassLoader ( ) ) { @ Override protected File createWorkDir ( File pluginArtifactFile ) throws IOException { File workDir = new File ( pluginFile . getParentFile ( ) , ".work" ) ; // $ NON - NLS - 1 $ workDir . mkdirs ( ) ; return workDir ; } } ;
public class ManyDummyContent { /** * Uploads XML from nominatim . openstreetmap . org , parses it , and create DummyItems from it */ private List < DummyItem > loadXmlFromNetwork ( String urlString ) throws IOException { } }
String jString ; // Instantiate the parser List < Entry > entries = null ; List < DummyItem > rtnArray = new ArrayList < DummyItem > ( ) ; BufferedReader streamReader = null ; try { streamReader = new BufferedReader ( downloadUrl ( urlString ) ) ; StringBuilder responseStrBuilder = new StringBuilder ( ) ; String inputStr ; while ( ( inputStr = streamReader . readLine ( ) ) != null ) responseStrBuilder . append ( inputStr ) ; jString = responseStrBuilder . toString ( ) ; if ( jString == null ) { Log . e ( SamplesApplication . TAG , "Nominatim Webpage: request failed for " + urlString ) ; return new ArrayList < DummyItem > ( 0 ) ; } JSONArray jPlaceIds = new JSONArray ( jString ) ; int n = jPlaceIds . length ( ) ; entries = new ArrayList < Entry > ( n ) ; for ( int i = 0 ; i < n ; i ++ ) { JSONObject jPlace = jPlaceIds . getJSONObject ( i ) ; Entry poi = new Entry ( jPlace . optLong ( "place_id" ) , jPlace . getString ( "osm_type" ) , jPlace . getString ( "osm_id" ) , // jPlace . getString ( " place _ rank " ) , jPlace . getString ( "boundingbox" ) , jPlace . getString ( "lat" ) , jPlace . getString ( "lon" ) , jPlace . getString ( "display_name" ) , jPlace . getString ( "class" ) , jPlace . getString ( "type" ) , jPlace . getString ( "importance" ) ) ; entries . add ( poi ) ; } } catch ( JSONException e ) { e . printStackTrace ( ) ; return null ; } finally { if ( streamReader != null ) { streamReader . close ( ) ; } } // StackOverflowXmlParser returns a List ( called " entries " ) of Entry objects . // Each Entry object represents a single place in the XML searchresult . // This section processes the entries list to create a ' DummyItem ' from each entry . for ( Entry entry : entries ) { rtnArray . add ( new DummyItem ( entry . mOsm_id , entry . mDisplay_name . split ( "," ) [ 0 ] , new LatLong ( Double . parseDouble ( entry . mLat ) , Double . parseDouble ( entry . mLon ) ) , entry . mDisplay_name ) ) ; } return rtnArray ;
public class PrimitiveCastExtensions { /** * Decodes a { @ code CharSequence } into a { @ code BigInteger } . * < p > In opposite to the functions of { @ link Integer } , this function is * null - safe and does not generate a { @ link NumberFormatException } . * If the given string cannot by parsed , { @ code 0 } is replied . * < p > See { @ link BigInteger # BigInteger ( String ) } for details on the accepted formats * for the input string of characters . * @ param value a value of { @ code CharSequence } type . * @ return the equivalent value to { @ code value } of { @ code BigInteger } type . * @ since 0.9 * @ see # intValue ( CharSequence ) */ @ Pure @ SuppressWarnings ( "checkstyle:magicnumber" ) public static BigInteger toBigInteger ( CharSequence value ) { } }
try { boolean negative = false ; int index = 0 ; final char firstChar = value . charAt ( 0 ) ; // Handle sign , if present if ( firstChar == '-' ) { negative = true ; ++ index ; } else if ( firstChar == '+' ) { ++ index ; } // Handle radix specifier , if present int radix = 10 ; if ( startsWith ( value , "0x" , index ) || startsWith ( value , "0X" , index ) ) { // $ NON - NLS - 1 $ / / $ NON - NLS - 2 $ index += 2 ; radix = 16 ; } else if ( startsWith ( value , "#" , index ) ) { // $ NON - NLS - 1 $ ++ index ; radix = 16 ; } else if ( startsWith ( value , "0" , index ) && value . length ( ) > 1 + index ) { // $ NON - NLS - 1 $ ++ index ; radix = 8 ; } final CharSequence endValue ; if ( index > 0 ) { endValue = value . subSequence ( index , value . length ( ) ) ; } else { endValue = value ; } final BigInteger number = new BigInteger ( endValue . toString ( ) , radix ) ; if ( negative ) { return number . negate ( ) ; } return number ; } catch ( Throwable exception ) { // Silent error } return BigInteger . valueOf ( 0 ) ;
public class CommonOps_DDF5 { /** * This computes the trace of the matrix : < br > * < br > * trace = & sum ; < sub > i = 1 : n < / sub > { a < sub > ii < / sub > } * The trace is only defined for square matrices . * @ param a A square matrix . Not modified . */ public static double trace ( DMatrix5x5 a ) { } }
return a . a11 + a . a22 + a . a33 + a . a44 + a . a55 ;
public class AbstractCommonService { /** * 添加一条空记录 * @ return */ @ Override public String addEmpty ( ) { } }
CommonModel entity = createModel ( ) ; entity . initNew ( ) ; mDao . insert ( entity ) ; return entity . getId ( ) ;
public class ChannelInitializers { /** * Returns a client - side channel initializer capable of securely sending * and receiving HTTP requests and responses . * < p > Communications will be encrypted as per the configured SSL context < / p > * @ param handler the handler in charge of implementing the business logic * @ param sslContext the SSL context which drives the security of the * link to the server . */ public static final ChannelInitializer < Channel > secureHttpClient ( final SimpleChannelInboundHandler < HttpResponse > handler , final SSLContext sslContext ) { } }
return new ChannelInitializer < Channel > ( ) { @ Override protected void initChannel ( Channel channel ) throws Exception { ChannelPipeline pipeline = channel . pipeline ( ) ; SSLEngine sslEngine = sslContext . createSSLEngine ( ) ; sslEngine . setUseClientMode ( true ) ; pipeline . addLast ( "ssl" , new SslHandler ( sslEngine ) ) ; pipeline . addLast ( "httpCodec" , new HttpClientCodec ( ) ) ; pipeline . addLast ( "aggregator" , new HttpObjectAggregator ( 10 * 1024 * 1024 ) ) ; pipeline . addLast ( "httpClientHandler" , handler ) ; } } ;
public class ComponentDisplayable { /** * HandlerListener */ @ Override public void notifyHandlableAdded ( Featurable featurable ) { } }
if ( featurable . hasFeature ( Displayable . class ) ) { final Displayable displayable = featurable . getFeature ( Displayable . class ) ; final Integer layer = getLayer ( featurable ) ; final Collection < Displayable > displayables = getLayer ( layer ) ; displayables . add ( displayable ) ; indexs . add ( layer ) ; }
public class HttpHealthCheckClient { /** * Returns the specified HttpHealthCheck resource . Gets a list of available HTTP health checks by * making a list ( ) request . * < p > Sample code : * < pre > < code > * try ( HttpHealthCheckClient httpHealthCheckClient = HttpHealthCheckClient . create ( ) ) { * ProjectGlobalHttpHealthCheckName httpHealthCheck = ProjectGlobalHttpHealthCheckName . of ( " [ PROJECT ] " , " [ HTTP _ HEALTH _ CHECK ] " ) ; * HttpHealthCheck2 response = httpHealthCheckClient . getHttpHealthCheck ( httpHealthCheck ) ; * < / code > < / pre > * @ param httpHealthCheck Name of the HttpHealthCheck resource to return . * @ throws com . google . api . gax . rpc . ApiException if the remote call fails */ @ BetaApi public final HttpHealthCheck2 getHttpHealthCheck ( ProjectGlobalHttpHealthCheckName httpHealthCheck ) { } }
GetHttpHealthCheckHttpRequest request = GetHttpHealthCheckHttpRequest . newBuilder ( ) . setHttpHealthCheck ( httpHealthCheck == null ? null : httpHealthCheck . toString ( ) ) . build ( ) ; return getHttpHealthCheck ( request ) ;
public class CommonOps_DDRM { /** * Performs an in - place element by element scalar division with the scalar on bottom . < br > * < br > * a < sub > ij < / sub > = a < sub > ij < / sub > / & alpha ; * @ param a The matrix whose elements are to be divided . Modified . * @ param alpha the amount each element is divided by . */ public static void divide ( DMatrixD1 a , double alpha ) { } }
final int size = a . getNumElements ( ) ; for ( int i = 0 ; i < size ; i ++ ) { a . data [ i ] /= alpha ; }
public class AdminUserAction { @ Override protected void setupHtmlData ( final ActionRuntime runtime ) { } }
super . setupHtmlData ( runtime ) ; runtime . registerData ( "helpLink" , systemHelper . getHelpLink ( fessConfig . getOnlineHelpNameUser ( ) ) ) ; runtime . registerData ( "ldapAdminEnabled" , fessConfig . isLdapAdminEnabled ( ) ) ;
public class Graph { /** * create an empty graph * @ param dbAccess the database on which to perform updates of the graph * @ return the empty graph model */ public static Graph create ( IDBAccess dbAccess ) { } }
ResultHandler rh = new ResultHandler ( dbAccess ) ; Graph ret = rh . getGraph ( ) ; ret . setSyncState ( SyncState . NEW ) ; return ret ;
public class OptionsApi { /** * Modify options . * Replace the existing application options with the specified new values . * @ param options attributes to be updated . * @ throws ProvisioningApiException if the call is unsuccessful . */ public void modifyOptions ( Map < String , Object > options ) throws ProvisioningApiException { } }
try { OptionsPostResponseStatusSuccess resp = optionsApi . optionsPost ( new OptionsPost ( ) . data ( new OptionsPostData ( ) . options ( options ) ) ) ; if ( ! resp . getStatus ( ) . getCode ( ) . equals ( 0 ) ) { throw new ProvisioningApiException ( "Error modifying options. Code: " + resp . getStatus ( ) . getCode ( ) ) ; } } catch ( ApiException e ) { throw new ProvisioningApiException ( "Error modifying options" , e ) ; }
public class AfplibPackageImpl { /** * < ! - - begin - user - doc - - > * < ! - - end - user - doc - - > * @ generated */ public EClass getFNMRG ( ) { } }
if ( fnmrgEClass == null ) { fnmrgEClass = ( EClass ) EPackage . Registry . INSTANCE . getEPackage ( AfplibPackage . eNS_URI ) . getEClassifiers ( ) . get ( 408 ) ; } return fnmrgEClass ;
public class UpgradeStepItem { /** * A list of strings containing detailed information about the errors encountered in a particular step . * @ param issues * A list of strings containing detailed information about the errors encountered in a particular step . */ public void setIssues ( java . util . Collection < String > issues ) { } }
if ( issues == null ) { this . issues = null ; return ; } this . issues = new java . util . ArrayList < String > ( issues ) ;
public class VoiceApi { /** * Send DTMF digits to the specified call . You can send DTMF digits individually with multiple requests or together with multiple digits in one request . * @ param connId The connection ID of the call . * @ param digits The DTMF digits to send to the call . */ public void sendDTMF ( String connId , String digits ) throws WorkspaceApiException { } }
this . sendDTMF ( connId , digits , null , null ) ;
public class ArgTokenizer { /** * Set the allowed options . Must be called before any options would be read * and before calling any of the option functionality below . */ void allowedOptions ( String ... opts ) { } }
for ( String opt : opts ) { options . putIfAbsent ( opt , false ) ; }
public class AtomTetrahedralLigandPlacer3D { /** * Rotates a vector around an axis . * @ param vector vector to be rotated around axis * @ param axis axis of rotation * @ param angle angle to vector rotate around * @ return rotated vector * author : egonw */ public static Vector3d rotate ( Vector3d vector , Vector3d axis , double angle ) { } }
Matrix3d rotate = new Matrix3d ( ) ; rotate . set ( new AxisAngle4d ( axis . x , axis . y , axis . z , angle ) ) ; Vector3d result = new Vector3d ( ) ; rotate . transform ( vector , result ) ; return result ;
public class VoltXMLElementHelper { /** * If one of the elements is null , return the other one diectly . */ public static VoltXMLElement mergeTwoElementsUsingOperator ( String opName , String opElementId , VoltXMLElement first , VoltXMLElement second ) { } }
if ( first == null || second == null ) { return first == null ? second : first ; } if ( opName == null || opElementId == null ) { return null ; } VoltXMLElement retval = new VoltXMLElement ( "operation" ) ; retval . attributes . put ( "id" , opElementId ) ; retval . attributes . put ( "optype" , opName ) ; retval . children . add ( first ) ; retval . children . add ( second ) ; return retval ;
public class DefaultExceptionMapper { /** * < p > parseErrors . < / p > * @ param exception a { @ link java . lang . Throwable } object . * @ param status a int . * @ return a { @ link java . util . List } object . */ protected List < Result . Error > parseErrors ( Throwable exception , int status ) { } }
List < Result . Error > errors = Lists . newArrayList ( ) ; boolean isDev = mode . isDev ( ) ; if ( resourceInfo != null && ( status == 500 || status == 400 ) ) { Class clazz = resourceInfo . getResourceClass ( ) ; if ( clazz != null ) { errors . add ( new Result . Error ( Hashing . murmur3_32 ( ) . hashUnencodedChars ( exception . getClass ( ) . getName ( ) ) . toString ( ) , exception . getMessage ( ) , null , isDev ? ClassUtils . toString ( clazz , resourceInfo . getResourceMethod ( ) ) : null ) ) ; } } if ( isDev ) { errors . addAll ( ErrorMessage . parseErrors ( exception , status ) ) ; } return errors ;
public class CmdLine { /** * the loptions */ private static Options getOptions ( ) { } }
final Options retval = new Options ( ) ; retval . addOption ( "h" , "help" , false , "Display this help page" ) ; retval . addOption ( "p" , "package" , true , "Package to be scanned" ) ; retval . addOption ( "d" , "directory" , true , "Directory to be scanned for classes" ) ; retval . addOption ( "u" , "untested" , true , "Filter for classes to include in the untested class report. If not set no untested class report is generated. Suggest: true()" ) ; retval . addOption ( "i" , "implementation" , false , "Filter for classes to include in the missing implementation class report. If not set no missing implementation class report is generated. Suggest: true()" ) ; retval . addOption ( "e" , "errors" , false , "Produce contract test configuration error report" ) ; retval . addOption ( "c" , "classFilter" , true , "A class filter function. Classes that pass the filter will be included. Default to true() " ) ; return retval ;
public class AppMsg { /** * Make a { @ link AppMsg } that just contains a text view with the text from a * resource . * @ param context The context to use . Usually your * { @ link android . app . Activity } object . * @ param resId The resource id of the string resource to use . Can be * formatted text . * @ param style The style with a background and a duration . * @ throws Resources . NotFoundException if the resource can ' t be found . */ public static AppMsg makeText ( Activity context , int resId , Style style ) throws Resources . NotFoundException { } }
return makeText ( context , context . getResources ( ) . getText ( resId ) , style ) ;
public class HeaderAndFooterGridView { /** * Returns the number of the grid view ' s columns by either using the * < code > getNumColumns < / code > - method on devices with API level 11 or greater , or via reflection * on older devices . * @ return The number of the grid view ' s columns as an { @ link Integer } value or { @ link * # AUTO _ FIT } , if the layout is pending */ protected final int getNumColumnsCompatible ( ) { } }
try { Field numColumns = GridView . class . getDeclaredField ( "mNumColumns" ) ; numColumns . setAccessible ( true ) ; return numColumns . getInt ( this ) ; } catch ( Exception e ) { throw new RuntimeException ( "Unable to retrieve number of columns" , e ) ; }
public class BucketIamSnippets { /** * Example of listing the Bucket - Level IAM Roles and Members */ public Policy listBucketIamMembers ( String bucketName ) { } }
// [ START view _ bucket _ iam _ members ] // Initialize a Cloud Storage client Storage storage = StorageOptions . getDefaultInstance ( ) . getService ( ) ; // Get IAM Policy for a bucket Policy policy = storage . getIamPolicy ( bucketName ) ; // Print Roles and its identities Map < Role , Set < Identity > > policyBindings = policy . getBindings ( ) ; for ( Map . Entry < Role , Set < Identity > > entry : policyBindings . entrySet ( ) ) { System . out . printf ( "Role: %s Identities: %s\n" , entry . getKey ( ) , entry . getValue ( ) ) ; } // [ END view _ bucket _ iam _ members ] return policy ;
public class AutoDisposeEndConsumerHelper { /** * Atomically updates the target upstream AtomicReference from null to the non - null * next Subscription , otherwise cancels next and reports a ProtocolViolationException * if the AtomicReference doesn ' t contain the shared cancelled indicator . * @ param upstream the target AtomicReference to update * @ param next the Subscription to set on it atomically * @ param subscriber the class of the consumer to have a personalized * error message if the upstream already contains a non - cancelled Subscription . * @ return true if successful , false if the content of the AtomicReference was non null */ public static boolean setOnce ( AtomicReference < Subscription > upstream , Subscription next , Class < ? > subscriber ) { } }
AutoDisposeUtil . checkNotNull ( next , "next is null" ) ; if ( ! upstream . compareAndSet ( null , next ) ) { next . cancel ( ) ; if ( upstream . get ( ) != AutoSubscriptionHelper . CANCELLED ) { reportDoubleSubscription ( subscriber ) ; } return false ; } return true ;
public class ConfigLoader { /** * Note that if file starts with ' classpath : ' the resource is looked * up on the classpath instead . */ public static Configuration load ( String file ) throws IOException , SAXException { } }
ConfigurationImpl cfg = new ConfigurationImpl ( ) ; XMLReader parser = XMLReaderFactory . createXMLReader ( ) ; parser . setContentHandler ( new ConfigHandler ( cfg , file ) ) ; if ( file . startsWith ( "classpath:" ) ) { String resource = file . substring ( "classpath:" . length ( ) ) ; ClassLoader cloader = Thread . currentThread ( ) . getContextClassLoader ( ) ; InputStream istream = cloader . getResourceAsStream ( resource ) ; parser . parse ( new InputSource ( istream ) ) ; } else parser . parse ( file ) ; return cfg ;
public class Bundler { /** * Inserts an ArrayList < Integer > value into the mapping of this Bundle , replacing * any existing value for the given key . Either key or value may be null . * @ param key a String , or null * @ param value an ArrayList < Integer > object , or null * @ return this */ public Bundler putIntegerArrayList ( String key , ArrayList < Integer > value ) { } }
bundle . putIntegerArrayList ( key , value ) ; return this ;
public class WorkSheet { /** * Randomly shuffle the columns and rows . Should be constrained to the same * data type if not probably doesn ' t make any sense . * @ param columns * @ param rows * @ throws Exception */ public void shuffleColumnsAndThenRows ( ArrayList < String > columns , ArrayList < String > rows ) throws Exception { } }
doubleValues . clear ( ) ; for ( String column : columns ) { // shuffle all values in the column ArrayList < Integer > rowIndex = new ArrayList < Integer > ( ) ; for ( int i = 0 ; i < rows . size ( ) ; i ++ ) { rowIndex . add ( i ) ; } Collections . shuffle ( rowIndex ) ; for ( int i = 0 ; i < rows . size ( ) ; i ++ ) { String row = rows . get ( i ) ; int randomIndex = rowIndex . get ( i ) ; String destinationRow = rows . get ( randomIndex ) ; String temp = this . getCell ( destinationRow , column ) ; String value = this . getCell ( row , column ) ; this . addCell ( destinationRow , column , value ) ; this . addCell ( row , column , temp ) ; } } for ( String row : rows ) { ArrayList < Integer > columnIndex = new ArrayList < Integer > ( ) ; for ( int i = 0 ; i < columns . size ( ) ; i ++ ) { columnIndex . add ( i ) ; } Collections . shuffle ( columnIndex ) ; for ( int i = 0 ; i < columns . size ( ) ; i ++ ) { String column = columns . get ( i ) ; int randomIndex = columnIndex . get ( i ) ; String destinationCol = columns . get ( randomIndex ) ; String temp = this . getCell ( row , destinationCol ) ; String value = this . getCell ( row , column ) ; this . addCell ( row , destinationCol , value ) ; this . addCell ( row , column , temp ) ; } }