idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
36,600 | protected String getMetricName ( Map < String , String > metadata , String eventName ) { return JOINER . join ( METRIC_KEY_PREFIX , metadata . get ( METADATA_JOB_ID ) , metadata . get ( METADATA_TASK_ID ) , EVENTS_QUALIFIER , eventName ) ; } | Constructs the metric key to be emitted . The actual event name is enriched with the current job and task id to be able to keep track of its origin |
36,601 | public static < T extends Serializable > byte [ ] serializeIntoBytes ( T obj ) throws IOException { try ( ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; ObjectOutputStream oos = new ObjectOutputStream ( bos ) ) { oos . writeObject ( obj ) ; oos . flush ( ) ; return bos . toByteArray ( ) ; } } | Serialize an object into a byte array . |
36,602 | private < T extends URNIdentified > Stream < T > sortStreamLexicographically ( Stream < T > inputStream ) { Spliterator < T > spliterator = inputStream . spliterator ( ) ; if ( spliterator . hasCharacteristics ( Spliterator . SORTED ) && spliterator . getComparator ( ) . equals ( this . lexicographicalComparator ) ) { return StreamSupport . stream ( spliterator , false ) ; } return StreamSupport . stream ( spliterator , false ) . sorted ( this . lexicographicalComparator ) ; } | Sort input stream lexicographically . Noop if the input stream is already sorted . |
36,603 | public void clean ( ) throws IOException { Path versionLocation = ( ( HivePartitionRetentionVersion ) this . datasetVersion ) . getLocation ( ) ; Path datasetLocation = ( ( CleanableHivePartitionDataset ) this . cleanableDataset ) . getLocation ( ) ; String completeName = ( ( HivePartitionRetentionVersion ) this . datasetVersion ) . datasetURN ( ) ; State state = new State ( this . state ) ; this . versionOwnerFs = ProxyUtils . getOwnerFs ( state , this . versionOwner ) ; try ( HiveProxyQueryExecutor queryExecutor = ProxyUtils . getQueryExecutor ( state , this . versionOwner , this . backUpOwner ) ) { if ( ! this . versionOwnerFs . exists ( versionLocation ) ) { log . info ( "Data versionLocation doesn't exist. Metadata will be dropped for the version " + completeName ) ; } else if ( datasetLocation . toString ( ) . equalsIgnoreCase ( versionLocation . toString ( ) ) ) { log . info ( "Dataset location is same as version location. Won't delete the data but metadata will be dropped for the version " + completeName ) ; } else if ( this . simulate ) { log . info ( "Simulate is set to true. Won't move the version " + completeName ) ; return ; } else if ( completeName . contains ( ComplianceConfigurationKeys . STAGING ) ) { log . info ( "Deleting data from version " + completeName ) ; this . versionOwnerFs . delete ( versionLocation , true ) ; } else if ( completeName . contains ( ComplianceConfigurationKeys . BACKUP ) ) { executeAlterQueries ( queryExecutor ) ; Path newVersionLocationParent = getNewVersionLocation ( ) . getParent ( ) ; log . info ( "Creating new dir " + newVersionLocationParent . toString ( ) ) ; this . versionOwnerFs . mkdirs ( newVersionLocationParent ) ; log . info ( "Moving data from " + versionLocation + " to " + getNewVersionLocation ( ) ) ; fsMove ( versionLocation , getNewVersionLocation ( ) ) ; FsPermission permission = new FsPermission ( FsAction . ALL , FsAction . ALL , FsAction . NONE ) ; HadoopUtils . setPermissions ( newVersionLocationParent , this . versionOwner , this . backUpOwner , this . versionOwnerFs , permission ) ; } executeDropVersionQueries ( queryExecutor ) ; } } | If simulate is set to true will simply return . If a version is pointing to a non - existing location then drop the partition and close the jdbc connection . If a version is pointing to the same location as of the dataset then drop the partition and close the jdbc connection . If a version is staging it s data will be deleted and metadata is dropped . IF a versions is backup it s data will be moved to a backup dir current metadata will be dropped and it will be registered in the backup db . |
36,604 | public static List < Properties > loadGenericJobConfigs ( Properties sysProps ) throws ConfigurationException , IOException { Path rootPath = new Path ( sysProps . getProperty ( ConfigurationKeys . JOB_CONFIG_FILE_GENERAL_PATH_KEY ) ) ; PullFileLoader loader = new PullFileLoader ( rootPath , rootPath . getFileSystem ( new Configuration ( ) ) , getJobConfigurationFileExtensions ( sysProps ) , PullFileLoader . DEFAULT_HOCON_PULL_FILE_EXTENSIONS ) ; Config sysConfig = ConfigUtils . propertiesToConfig ( sysProps ) ; Collection < Config > configs = loader . loadPullFilesRecursively ( rootPath , sysConfig , true ) ; List < Properties > jobConfigs = Lists . newArrayList ( ) ; for ( Config config : configs ) { try { jobConfigs . add ( resolveTemplate ( ConfigUtils . configToProperties ( config ) ) ) ; } catch ( IOException ioe ) { LOGGER . error ( "Could not parse job config at " + ConfigUtils . getString ( config , ConfigurationKeys . JOB_CONFIG_FILE_PATH_KEY , "Unknown path" ) , ioe ) ; } } return jobConfigs ; } | Load job configuration from job configuration files stored in general file system located by Path |
36,605 | public static Properties loadGenericJobConfig ( Properties sysProps , Path jobConfigPath , Path jobConfigPathDir ) throws ConfigurationException , IOException { PullFileLoader loader = new PullFileLoader ( jobConfigPathDir , jobConfigPathDir . getFileSystem ( new Configuration ( ) ) , getJobConfigurationFileExtensions ( sysProps ) , PullFileLoader . DEFAULT_HOCON_PULL_FILE_EXTENSIONS ) ; Config sysConfig = ConfigUtils . propertiesToConfig ( sysProps ) ; Config config = loader . loadPullFile ( jobConfigPath , sysConfig , true ) ; return resolveTemplate ( ConfigUtils . configToProperties ( config ) ) ; } | Load a given job configuration file from a general file system . |
36,606 | protected State getRuntimePropsEnrichedTblProps ( ) { State tableProps = new State ( this . props . getTablePartitionProps ( ) ) ; if ( this . props . getRuntimeTableProps ( ) . isPresent ( ) ) { tableProps . setProp ( HiveMetaStoreUtils . RUNTIME_PROPS , this . props . getRuntimeTableProps ( ) . get ( ) ) ; } return tableProps ; } | Enrich the table - level properties with properties carried over from ingestion runtime . Extend this class to add more runtime properties if required . |
36,607 | protected static boolean isNameValid ( String name ) { Preconditions . checkNotNull ( name ) ; name = name . toLowerCase ( ) ; return VALID_DB_TABLE_NAME_PATTERN_1 . matcher ( name ) . matches ( ) && VALID_DB_TABLE_NAME_PATTERN_2 . matcher ( name ) . matches ( ) ; } | Determine whether a database or table name is valid . |
36,608 | private void movePos ( float deltaY ) { if ( ( deltaY < 0 && mPtrIndicator . isInStartPosition ( ) ) ) { if ( DEBUG ) { PtrCLog . e ( LOG_TAG , String . format ( "has reached the top" ) ) ; } return ; } int to = mPtrIndicator . getCurrentPosY ( ) + ( int ) deltaY ; if ( mPtrIndicator . willOverTop ( to ) ) { if ( DEBUG ) { PtrCLog . e ( LOG_TAG , String . format ( "over top" ) ) ; } to = PtrIndicator . POS_START ; } mPtrIndicator . setCurrentPos ( to ) ; int change = to - mPtrIndicator . getLastPosY ( ) ; updatePos ( change ) ; } | if deltaY > 0 move the content down |
36,609 | public void setRefreshCompleteHook ( PtrUIHandlerHook hook ) { mRefreshCompleteHook = hook ; hook . setResumeAction ( new Runnable ( ) { public void run ( ) { if ( DEBUG ) { PtrCLog . d ( LOG_TAG , "mRefreshCompleteHook resume." ) ; } notifyUIRefreshComplete ( true ) ; } } ) ; } | please DO REMEMBER resume the hook |
36,610 | private boolean tryToNotifyReset ( ) { if ( ( mStatus == PTR_STATUS_COMPLETE || mStatus == PTR_STATUS_PREPARE ) && mPtrIndicator . isInStartPosition ( ) ) { if ( mPtrUIHandlerHolder . hasHandler ( ) ) { mPtrUIHandlerHolder . onUIReset ( this ) ; if ( DEBUG ) { PtrCLog . i ( LOG_TAG , "PtrUIHandler: onUIReset" ) ; } } mStatus = PTR_STATUS_INIT ; clearFlag ( ) ; return true ; } return false ; } | If at the top and not in loading reset |
36,611 | private void notifyUIRefreshComplete ( boolean ignoreHook ) { if ( mPtrIndicator . hasLeftStartPosition ( ) && ! ignoreHook && mRefreshCompleteHook != null ) { if ( DEBUG ) { PtrCLog . d ( LOG_TAG , "notifyUIRefreshComplete mRefreshCompleteHook run." ) ; } mRefreshCompleteHook . takeOver ( ) ; return ; } if ( mPtrUIHandlerHolder . hasHandler ( ) ) { if ( DEBUG ) { PtrCLog . i ( LOG_TAG , "PtrUIHandler: onUIRefreshComplete" ) ; } mPtrUIHandlerHolder . onUIRefreshComplete ( this ) ; } mPtrIndicator . onUIRefreshComplete ( ) ; tryScrollBackToTopAfterComplete ( ) ; tryToNotifyReset ( ) ; } | Do real refresh work . If there is a hook execute the hook first . |
36,612 | public static WaitStrategy join ( WaitStrategy ... waitStrategies ) { Preconditions . checkState ( waitStrategies . length > 0 , "Must have at least one wait strategy" ) ; List < WaitStrategy > waitStrategyList = Lists . newArrayList ( waitStrategies ) ; Preconditions . checkState ( ! waitStrategyList . contains ( null ) , "Cannot have a null wait strategy" ) ; return new CompositeWaitStrategy ( waitStrategyList ) ; } | Joins one or more wait strategies to derive a composite wait strategy . The new joined strategy will have a wait time which is total of all wait times computed one after another in order . |
36,613 | public Retryer < V > build ( ) { AttemptTimeLimiter < V > theAttemptTimeLimiter = attemptTimeLimiter == null ? AttemptTimeLimiters . < V > noTimeLimit ( ) : attemptTimeLimiter ; StopStrategy theStopStrategy = stopStrategy == null ? StopStrategies . neverStop ( ) : stopStrategy ; WaitStrategy theWaitStrategy = waitStrategy == null ? WaitStrategies . noWait ( ) : waitStrategy ; BlockStrategy theBlockStrategy = blockStrategy == null ? BlockStrategies . threadSleepStrategy ( ) : blockStrategy ; return new Retryer < V > ( theAttemptTimeLimiter , theStopStrategy , theWaitStrategy , theBlockStrategy , rejectionPredicate , listeners ) ; } | Builds the retryer . |
36,614 | public V call ( Callable < V > callable ) throws ExecutionException , RetryException { long startTime = System . nanoTime ( ) ; for ( int attemptNumber = 1 ; ; attemptNumber ++ ) { Attempt < V > attempt ; try { V result = attemptTimeLimiter . call ( callable ) ; attempt = new ResultAttempt < V > ( result , attemptNumber , TimeUnit . NANOSECONDS . toMillis ( System . nanoTime ( ) - startTime ) ) ; } catch ( Throwable t ) { attempt = new ExceptionAttempt < V > ( t , attemptNumber , TimeUnit . NANOSECONDS . toMillis ( System . nanoTime ( ) - startTime ) ) ; } for ( RetryListener listener : listeners ) { listener . onRetry ( attempt ) ; } if ( ! rejectionPredicate . apply ( attempt ) ) { return attempt . get ( ) ; } if ( stopStrategy . shouldStop ( attempt ) ) { throw new RetryException ( attemptNumber , attempt ) ; } else { long sleepTime = waitStrategy . computeSleepTime ( attempt ) ; try { blockStrategy . block ( sleepTime ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; throw new RetryException ( attemptNumber , attempt ) ; } } } } | Executes the given callable . If the rejection predicate accepts the attempt the stop strategy is used to decide if a new attempt must be made . Then the wait strategy is used to decide how much time to sleep and a new attempt is made . |
36,615 | public static void convertActivityToTranslucentBeforeL ( Activity activity ) { try { Class < ? > [ ] classes = Activity . class . getDeclaredClasses ( ) ; Class < ? > translucentConversionListenerClazz = null ; for ( Class clazz : classes ) { if ( clazz . getSimpleName ( ) . contains ( "TranslucentConversionListener" ) ) { translucentConversionListenerClazz = clazz ; } } Method method = Activity . class . getDeclaredMethod ( "convertToTranslucent" , translucentConversionListenerClazz ) ; method . setAccessible ( true ) ; method . invoke ( activity , new Object [ ] { null } ) ; } catch ( Throwable t ) { } } | Calling the convertToTranslucent method on platforms before Android 5 . 0 |
36,616 | private static void convertActivityToTranslucentAfterL ( Activity activity ) { try { Method getActivityOptions = Activity . class . getDeclaredMethod ( "getActivityOptions" ) ; getActivityOptions . setAccessible ( true ) ; Object options = getActivityOptions . invoke ( activity ) ; Class < ? > [ ] classes = Activity . class . getDeclaredClasses ( ) ; Class < ? > translucentConversionListenerClazz = null ; for ( Class clazz : classes ) { if ( clazz . getSimpleName ( ) . contains ( "TranslucentConversionListener" ) ) { translucentConversionListenerClazz = clazz ; } } Method convertToTranslucent = Activity . class . getDeclaredMethod ( "convertToTranslucent" , translucentConversionListenerClazz , ActivityOptions . class ) ; convertToTranslucent . setAccessible ( true ) ; convertToTranslucent . invoke ( activity , null , options ) ; } catch ( Throwable t ) { } } | Calling the convertToTranslucent method on platforms after Android 5 . 0 |
36,617 | public void addSwipeListener ( SwipeListener listener ) { if ( mListeners == null ) { mListeners = new ArrayList < SwipeListener > ( ) ; } mListeners . add ( listener ) ; } | Add a callback to be invoked when a swipe event is sent to this view . |
36,618 | public void setShadow ( Drawable shadow , int edgeFlag ) { if ( ( edgeFlag & EDGE_LEFT ) != 0 ) { mShadowLeft = shadow ; } else if ( ( edgeFlag & EDGE_RIGHT ) != 0 ) { mShadowRight = shadow ; } else if ( ( edgeFlag & EDGE_BOTTOM ) != 0 ) { mShadowBottom = shadow ; } invalidate ( ) ; } | Set a drawable used for edge shadow . |
36,619 | public void scrollToFinishActivity ( ) { final int childWidth = mContentView . getWidth ( ) ; final int childHeight = mContentView . getHeight ( ) ; int left = 0 , top = 0 ; if ( ( mEdgeFlag & EDGE_LEFT ) != 0 ) { left = childWidth + mShadowLeft . getIntrinsicWidth ( ) + OVERSCROLL_DISTANCE ; mTrackingEdge = EDGE_LEFT ; } else if ( ( mEdgeFlag & EDGE_RIGHT ) != 0 ) { left = - childWidth - mShadowRight . getIntrinsicWidth ( ) - OVERSCROLL_DISTANCE ; mTrackingEdge = EDGE_RIGHT ; } else if ( ( mEdgeFlag & EDGE_BOTTOM ) != 0 ) { top = - childHeight - mShadowBottom . getIntrinsicHeight ( ) - OVERSCROLL_DISTANCE ; mTrackingEdge = EDGE_BOTTOM ; } mDragHelper . smoothSlideViewTo ( mContentView , left , top ) ; invalidate ( ) ; } | Scroll out contentView and finish the activity |
36,620 | public void setSensitivity ( Context context , float sensitivity ) { float s = Math . max ( 0f , Math . min ( 1.0f , sensitivity ) ) ; ViewConfiguration viewConfiguration = ViewConfiguration . get ( context ) ; mTouchSlop = ( int ) ( viewConfiguration . getScaledTouchSlop ( ) * ( 1 / s ) ) ; } | Sets the sensitivity of the dragger . |
36,621 | boolean isPreferredAddress ( InetAddress address ) { if ( this . properties . isUseOnlySiteLocalInterfaces ( ) ) { final boolean siteLocalAddress = address . isSiteLocalAddress ( ) ; if ( ! siteLocalAddress ) { this . log . trace ( "Ignoring address: " + address . getHostAddress ( ) ) ; } return siteLocalAddress ; } final List < String > preferredNetworks = this . properties . getPreferredNetworks ( ) ; if ( preferredNetworks . isEmpty ( ) ) { return true ; } for ( String regex : preferredNetworks ) { final String hostAddress = address . getHostAddress ( ) ; if ( hostAddress . matches ( regex ) || hostAddress . startsWith ( regex ) ) { return true ; } } this . log . trace ( "Ignoring address: " + address . getHostAddress ( ) ) ; return false ; } | For testing . |
36,622 | public Rectangle closeRectFor ( final int tabIndex ) { final Rectangle rect = rects [ tabIndex ] ; final int x = rect . x + rect . width - CLOSE_ICON_WIDTH - CLOSE_ICON_RIGHT_MARGIN ; final int y = rect . y + ( rect . height - CLOSE_ICON_WIDTH ) / 2 ; final int width = CLOSE_ICON_WIDTH ; return new Rectangle ( x , y , width , width ) ; } | Helper - method to get a rectangle definition for the close - icon |
36,623 | protected int calculateTabWidth ( final int tabPlacement , final int tabIndex , final FontMetrics metrics ) { if ( _pane . getSeparators ( ) . contains ( tabIndex ) ) { return SEPARATOR_WIDTH ; } int width = super . calculateTabWidth ( tabPlacement , tabIndex , metrics ) ; if ( ! _pane . getUnclosables ( ) . contains ( tabIndex ) ) { width += CLOSE_ICON_WIDTH ; } return width ; } | Override this to provide extra space on right for close button |
36,624 | protected void paintContentBorder ( final Graphics g , final int tabPlacement , final int tabIndex ) { final int w = tabPane . getWidth ( ) ; final int h = tabPane . getHeight ( ) ; final Insets tabAreaInsets = getTabAreaInsets ( tabPlacement ) ; final int x = 0 ; final int y = calculateTabAreaHeight ( tabPlacement , runCount , maxTabHeight ) + tabAreaInsets . bottom ; g . setColor ( _tabSelectedBackgroundColor ) ; g . fillRect ( x , y , w , h ) ; g . setColor ( _tabBorderColor ) ; final Rectangle selectTabBounds = getTabBounds ( tabPane , tabIndex ) ; g . drawLine ( x , y , selectTabBounds . x , y ) ; g . drawLine ( selectTabBounds . x + selectTabBounds . width , y , x + w , y ) ; } | Paints the border for the tab s content ie . the area below the tabs |
36,625 | protected static Map < String , UnicodeSet > createUnicodeSets ( ) { final Map < String , UnicodeSet > unicodeSets = new TreeMap < > ( ) ; unicodeSets . put ( "Latin, ASCII" , new UnicodeSet ( "[:ASCII:]" ) ) ; unicodeSets . put ( "Latin, non-ASCII" , subUnicodeSet ( "[:Latin:]" , "[:ASCII:]" ) ) ; unicodeSets . put ( "Arabic" , new UnicodeSet ( "[:Script=Arabic:]" ) ) ; unicodeSets . put ( "Armenian" , new UnicodeSet ( "[:Script=Armenian:]" ) ) ; unicodeSets . put ( "Bengali" , new UnicodeSet ( "[:Script=Bengali:]" ) ) ; unicodeSets . put ( "Cyrillic" , new UnicodeSet ( "[:Script=Cyrillic:]" ) ) ; unicodeSets . put ( "Devanagari" , new UnicodeSet ( "[:Script=Devanagari:]" ) ) ; unicodeSets . put ( "Greek" , new UnicodeSet ( "[:Script=Greek:]" ) ) ; unicodeSets . put ( "Han" , new UnicodeSet ( "[:Script=Han:]" ) ) ; unicodeSets . put ( "Gujarati" , new UnicodeSet ( "[:Script=Gujarati:]" ) ) ; unicodeSets . put ( "Georgian" , new UnicodeSet ( "[:Script=Georgian:]" ) ) ; unicodeSets . put ( "Gurmukhi" , new UnicodeSet ( "[:Script=Gurmukhi:]" ) ) ; unicodeSets . put ( "Hangul" , new UnicodeSet ( "[:Script=Hangul:]" ) ) ; unicodeSets . put ( "Hebrew" , new UnicodeSet ( "[:Script=Hebrew:]" ) ) ; unicodeSets . put ( "Hiragana" , new UnicodeSet ( "[:Script=Hiragana:]" ) ) ; unicodeSets . put ( "Kannada" , new UnicodeSet ( "[:Script=Kannada:]" ) ) ; unicodeSets . put ( "Katakana" , new UnicodeSet ( "[:Script=Katakana:]" ) ) ; unicodeSets . put ( "Malayalam" , new UnicodeSet ( "[:Script=Malayalam:]" ) ) ; unicodeSets . put ( "Oriya" , new UnicodeSet ( "[:Script=Oriya:]" ) ) ; unicodeSets . put ( "Syriac" , new UnicodeSet ( "[:Script=Syriac:]" ) ) ; unicodeSets . put ( "Tamil" , new UnicodeSet ( "[:Script=Tamil:]" ) ) ; unicodeSets . put ( "Telugu" , new UnicodeSet ( "[:Script=Telugu:]" ) ) ; unicodeSets . put ( "Thaana" , new UnicodeSet ( "[:Script=Thaana:]" ) ) ; unicodeSets . put ( "Thai" , new UnicodeSet ( "[:Script=Thai:]" ) ) ; return unicodeSets ; } | Creates a map of unicode sets with their names as keys . |
36,626 | public boolean isConfigured ( final boolean throwException ) throws UnconfiguredConfiguredPropertyException , ComponentValidationException , NoResultProducingComponentsException , IllegalStateException { return checkConfiguration ( throwException ) && isConsumedOutDataStreamsJobBuilderConfigured ( throwException ) ; } | Used to verify whether or not the builder s and its immediate children configuration is valid and all properties are satisfied . |
36,627 | private boolean isConsumedOutDataStreamsJobBuilderConfigured ( final boolean throwException ) { final List < AnalysisJobBuilder > consumedOutputDataStreamsJobBuilders = getConsumedOutputDataStreamsJobBuilders ( ) ; for ( final AnalysisJobBuilder analysisJobBuilder : consumedOutputDataStreamsJobBuilders ) { if ( ! analysisJobBuilder . isConfigured ( throwException ) ) { return false ; } } return true ; } | Checks if a job children are configured . |
36,628 | public boolean isDistributable ( ) { final Collection < ComponentBuilder > componentBuilders = getComponentBuilders ( ) ; for ( final ComponentBuilder componentBuilder : componentBuilders ) { if ( ! componentBuilder . isDistributable ( ) ) { return false ; } } final List < AnalysisJobBuilder > childJobBuilders = getConsumedOutputDataStreamsJobBuilders ( ) ; for ( final AnalysisJobBuilder childJobBuilder : childJobBuilders ) { if ( ! childJobBuilder . isDistributable ( ) ) { return false ; } } return true ; } | Determines if the job being built is going to be distributable in a cluster execution environment . |
36,629 | private static File getDirectoryIfExists ( final File existingCandidate , final String path ) { if ( existingCandidate != null ) { return existingCandidate ; } if ( ! Strings . isNullOrEmpty ( path ) ) { final File directory = new File ( path ) ; if ( directory . exists ( ) && directory . isDirectory ( ) ) { return directory ; } } return null ; } | Gets a candidate directory based on a file path if it exists and if it another candidate hasn t already been resolved . |
36,630 | public static void main ( final String [ ] args ) { LookAndFeelManager . get ( ) . init ( ) ; final Injector injector = Guice . createInjector ( new DCModuleImpl ( ) ) ; final AnalysisJobBuilder ajb = injector . getInstance ( AnalysisJobBuilder . class ) ; final Datastore ds = injector . getInstance ( DatastoreCatalog . class ) . getDatastore ( "orderdb" ) ; final DatastoreConnection con = ds . openConnection ( ) ; final Table table = con . getSchemaNavigator ( ) . convertToTable ( "PUBLIC.CUSTOMERS" ) ; ajb . setDatastore ( ds ) ; ajb . addSourceColumns ( table . getLiteralColumns ( ) ) ; ajb . addAnalyzer ( PatternFinderAnalyzer . class ) . addInputColumns ( ajb . getSourceColumns ( ) ) . setName ( "Ungrouped pattern finders" ) ; final AnalyzerComponentBuilder < PatternFinderAnalyzer > groupedPatternFinder = ajb . addAnalyzer ( PatternFinderAnalyzer . class ) ; ajb . addSourceColumns ( "PUBLIC.OFFICES.CITY" , "PUBLIC.OFFICES.TERRITORY" ) ; groupedPatternFinder . setName ( "Grouped PF" ) ; groupedPatternFinder . addInputColumn ( ajb . getSourceColumnByName ( "PUBLIC.OFFICES.CITY" ) ) ; groupedPatternFinder . addInputColumn ( ajb . getSourceColumnByName ( "PUBLIC.OFFICES.TERRITORY" ) , groupedPatternFinder . getDescriptor ( ) . getConfiguredProperty ( "Group column" ) ) ; final ResultWindow resultWindow = injector . getInstance ( ResultWindow . class ) ; resultWindow . setVisible ( true ) ; resultWindow . startAnalysis ( ) ; } | A main method that will display the results of a few example pattern finder analyzers . Useful for tweaking the charts and UI . |
36,631 | public static void main ( final String [ ] args ) throws Exception { LookAndFeelManager . get ( ) . init ( ) ; final Injector injector = Guice . createInjector ( new DCModuleImpl ( VFSUtils . getFileSystemManager ( ) . resolveFile ( "." ) , null ) ) ; final AnalysisJobBuilder ajb = injector . getInstance ( AnalysisJobBuilder . class ) ; final Datastore ds = injector . getInstance ( DatastoreCatalog . class ) . getDatastore ( "orderdb" ) ; final DatastoreConnection con = ds . openConnection ( ) ; final Table table = con . getSchemaNavigator ( ) . convertToTable ( "PUBLIC.CUSTOMERS" ) ; ajb . setDatastore ( ds ) ; ajb . addSourceColumns ( table . getNumberColumns ( ) ) ; ajb . addAnalyzer ( NumberAnalyzer . class ) . addInputColumns ( ajb . getSourceColumns ( ) ) ; final ResultWindow resultWindow = injector . getInstance ( ResultWindow . class ) ; resultWindow . setVisible ( true ) ; resultWindow . startAnalysis ( ) ; } | A main method that will display the results of a few example number analyzers . Useful for tweaking the charts and UI . |
36,632 | private void configureComponentsBeforeBuilding ( final AnalysisJobBuilder jobBuilder , final int partitionNumber ) { for ( final ComponentBuilder cb : jobBuilder . getComponentBuilders ( ) ) { final Set < ConfiguredPropertyDescriptor > targetDatastoreProperties = cb . getDescriptor ( ) . getConfiguredPropertiesByType ( UpdateableDatastore . class , false ) ; for ( final ConfiguredPropertyDescriptor targetDatastoreProperty : targetDatastoreProperties ) { final Object datastoreObject = cb . getConfiguredProperty ( targetDatastoreProperty ) ; if ( datastoreObject instanceof ResourceDatastore ) { final ResourceDatastore resourceDatastore = ( ResourceDatastore ) datastoreObject ; final Resource resource = resourceDatastore . getResource ( ) ; final Resource replacementResource = createReplacementResource ( resource , partitionNumber ) ; if ( replacementResource != null ) { final ResourceDatastore replacementDatastore = createReplacementDatastore ( cb , resourceDatastore , replacementResource ) ; if ( replacementDatastore != null ) { cb . setConfiguredProperty ( targetDatastoreProperty , replacementDatastore ) ; } } } } final Set < ConfiguredPropertyDescriptor > resourceProperties = cb . getDescriptor ( ) . getConfiguredPropertiesByType ( Resource . class , false ) ; for ( final ConfiguredPropertyDescriptor resourceProperty : resourceProperties ) { final Resource resource = ( Resource ) cb . getConfiguredProperty ( resourceProperty ) ; final Resource replacementResource = createReplacementResource ( resource , partitionNumber ) ; if ( replacementResource != null ) { cb . setConfiguredProperty ( resourceProperty , replacementResource ) ; } } if ( cb . getComponentInstance ( ) instanceof CreateCsvFileAnalyzer ) { if ( partitionNumber > 0 ) { cb . setConfiguredProperty ( CreateCsvFileAnalyzer . PROPERTY_INCLUDE_HEADER , false ) ; } } } final List < AnalysisJobBuilder > children = jobBuilder . getConsumedOutputDataStreamsJobBuilders ( ) ; for ( final AnalysisJobBuilder childJobBuilder : children ) { configureComponentsBeforeBuilding ( childJobBuilder , partitionNumber ) ; } } | Applies any partition - specific configuration to the job builder before building it . |
36,633 | public static void createDimensionsColumnCrosstab ( final List < CrosstabDimension > crosstabDimensions , final Crosstab < Number > partialCrosstab ) { if ( partialCrosstab != null ) { final List < CrosstabDimension > dimensions = partialCrosstab . getDimensions ( ) ; for ( final CrosstabDimension dimension : dimensions ) { if ( ! dimensionExits ( crosstabDimensions , dimension ) ) { crosstabDimensions . add ( dimension ) ; } } } } | Add the croosstab dimensions to the list of dimensions |
36,634 | public static void addData ( final Crosstab < Number > mainCrosstab , final Crosstab < Number > partialCrosstab , final CrosstabDimension columnDimension , final CrosstabDimension measureDimension ) { if ( partialCrosstab != null ) { final CrosstabNavigator < Number > mainNavigator = new CrosstabNavigator < > ( mainCrosstab ) ; final CrosstabNavigator < Number > nav = new CrosstabNavigator < > ( partialCrosstab ) ; for ( final String columnCategory : columnDimension . getCategories ( ) ) { nav . where ( columnDimension , columnCategory ) ; mainNavigator . where ( columnDimension , columnCategory ) ; final List < String > categories = measureDimension . getCategories ( ) ; for ( final String measureCategory : categories ) { sumUpData ( mainNavigator , nav , measureDimension , measureCategory ) ; } } } } | Add the values of partial crosstab to the main crosstab |
36,635 | private ChartPanel createChartPanel ( final ValueCountingAnalyzerResult result ) { if ( _valueCounts . size ( ) > ChartUtils . CATEGORY_COUNT_DISPLAY_THRESHOLD ) { logger . info ( "Display threshold of {} in chart surpassed (got {}). Skipping chart." , ChartUtils . CATEGORY_COUNT_DISPLAY_THRESHOLD , _valueCounts . size ( ) ) ; return null ; } final Integer distinctCount = result . getDistinctCount ( ) ; final Integer unexpectedValueCount = result . getUnexpectedValueCount ( ) ; final int totalCount = result . getTotalCount ( ) ; final String title = "Value distribution of " + _groupOrColumnName ; final JFreeChart chart = ChartFactory . createBarChart ( title , "Value" , "Count" , _dataset , PlotOrientation . HORIZONTAL , true , true , false ) ; final List < Title > titles = new ArrayList < > ( ) ; titles . add ( new ShortTextTitle ( "Total count: " + totalCount ) ) ; if ( distinctCount != null ) { titles . add ( new ShortTextTitle ( "Distinct count: " + distinctCount ) ) ; } if ( unexpectedValueCount != null ) { titles . add ( new ShortTextTitle ( "Unexpected value count: " + unexpectedValueCount ) ) ; } chart . setSubtitles ( titles ) ; ChartUtils . applyStyles ( chart ) ; { final CategoryPlot plot = ( CategoryPlot ) chart . getPlot ( ) ; plot . getDomainAxis ( ) . setVisible ( false ) ; int colorIndex = 0 ; for ( int i = 0 ; i < getDataSetItemCount ( ) ; i ++ ) { final String key = getDataSetKey ( i ) ; final Color color ; final String upperCaseKey = key . toUpperCase ( ) ; if ( _valueColorMap . containsKey ( upperCaseKey ) ) { color = _valueColorMap . get ( upperCaseKey ) ; } else { if ( i == getDataSetItemCount ( ) - 1 ) { if ( colorIndex == 0 ) { colorIndex ++ ; } } Color colorCandidate = SLICE_COLORS [ colorIndex ] ; final int darkAmount = i / SLICE_COLORS . length ; for ( int j = 0 ; j < darkAmount ; j ++ ) { colorCandidate = WidgetUtils . slightlyDarker ( colorCandidate ) ; } color = colorCandidate ; colorIndex ++ ; if ( colorIndex >= SLICE_COLORS . length ) { colorIndex = 0 ; } } plot . getRenderer ( ) . setSeriesPaint ( i , color ) ; } } return ChartUtils . createPanel ( chart , false ) ; } | Creates a chart panel or null if chart display is not applicable . |
36,636 | public URI getResultPath ( ) { final String str = _customProperties . get ( PROPERTY_RESULT_PATH ) ; if ( Strings . isNullOrEmpty ( str ) ) { return null ; } return URI . create ( str ) ; } | Gets the path defined in the job properties file |
36,637 | public void setDatastore ( final Datastore datastore , final boolean expandTree ) { final DatastoreConnection con ; if ( datastore == null ) { con = null ; } else { con = datastore . openConnection ( ) ; } _datastore = datastore ; if ( _datastoreConnection != null ) { _datastoreConnection . close ( ) ; } _analysisJobBuilder . setDatastore ( datastore ) ; _datastoreConnection = con ; if ( datastore == null ) { _analysisJobBuilder . reset ( ) ; changePanel ( AnalysisWindowPanelType . WELCOME ) ; } else { changePanel ( AnalysisWindowPanelType . EDITING_CONTEXT ) ; addTableToSource ( con ) ; } setSchemaTree ( datastore , expandTree , con ) ; updateStatusLabel ( ) ; _graph . refresh ( ) ; } | Initializes the window to use a particular datastore in the schema tree . |
36,638 | public boolean upgrade ( final FileObject newFolder ) { try { if ( newFolder . getChildren ( ) . length != 0 ) { return false ; } final FileObject upgradeFromFolderCandidate = findUpgradeCandidate ( newFolder ) ; if ( upgradeFromFolderCandidate == null ) { logger . info ( "Did not find a suitable upgrade candidate" ) ; return false ; } logger . info ( "Upgrading DATACLEANER_HOME from : {}" , upgradeFromFolderCandidate ) ; newFolder . copyFrom ( upgradeFromFolderCandidate , new AllFileSelector ( ) ) ; final UserPreferencesUpgrader userPreferencesUpgrader = new UserPreferencesUpgrader ( newFolder ) ; userPreferencesUpgrader . upgrade ( ) ; final List < String > allFilePaths = DataCleanerHome . getAllInitialFiles ( ) ; for ( final String filePath : allFilePaths ) { overwriteFileWithDefaults ( newFolder , filePath ) ; } return true ; } catch ( final FileSystemException e ) { logger . warn ( "Exception occured during upgrading: {}" , e ) ; return false ; } } | Finds a folder to upgrade from based on the newFolder parameter - upgrades are performed only within the same major version . |
36,639 | protected EnumerationValue [ ] getEnumConstants ( final InputColumn < ? > inputColumn , final ConfiguredPropertyDescriptor mappedEnumsProperty ) { if ( mappedEnumsProperty instanceof EnumerationProvider ) { return ( ( EnumerationProvider ) mappedEnumsProperty ) . values ( ) ; } else { return EnumerationValue . fromArray ( mappedEnumsProperty . getBaseType ( ) . getEnumConstants ( ) ) ; } } | Produces a list of available enum values for a particular input column . |
36,640 | protected DCComboBox < EnumerationValue > createComboBox ( final InputColumn < ? > inputColumn , EnumerationValue mappedEnum ) { if ( mappedEnum == null && inputColumn != null ) { mappedEnum = getSuggestedValue ( inputColumn ) ; } final EnumerationValue [ ] enumConstants = getEnumConstants ( inputColumn , _mappedEnumsProperty ) ; final DCComboBox < EnumerationValue > comboBox = new DCComboBox < > ( enumConstants ) ; comboBox . setRenderer ( getComboBoxRenderer ( inputColumn , _mappedEnumComboBoxes , enumConstants ) ) ; _mappedEnumComboBoxes . put ( inputColumn , comboBox ) ; if ( mappedEnum != null ) { comboBox . setEditable ( true ) ; comboBox . setSelectedItem ( mappedEnum ) ; comboBox . setEditable ( false ) ; } comboBox . addListener ( item -> _mappedEnumsPropertyWidget . fireValueChanged ( ) ) ; return comboBox ; } | Creates a combobox for a particular input column . |
36,641 | protected ListCellRenderer < ? super EnumerationValue > getComboBoxRenderer ( final InputColumn < ? > inputColumn , final Map < InputColumn < ? > , DCComboBox < EnumerationValue > > mappedEnumComboBoxes , final EnumerationValue [ ] enumConstants ) { return new EnumComboBoxListRenderer ( ) ; } | Gets the renderer of items in the comboboxes presenting the enum values . |
36,642 | public static String getValueLabel ( final Object value ) { if ( value == null ) { return NULL_LABEL ; } if ( value instanceof HasLabelAdvice ) { final String suggestedLabel = ( ( HasLabelAdvice ) value ) . getSuggestedLabel ( ) ; if ( ! Strings . isNullOrEmpty ( suggestedLabel ) ) { return suggestedLabel ; } } if ( value instanceof Double || value instanceof Float || value instanceof BigDecimal ) { final NumberFormat format = NumberFormat . getNumberInstance ( ) ; final String result = format . format ( ( Number ) value ) ; logger . debug ( "Formatted decimal {} to: {}" , value , result ) ; return result ; } if ( value instanceof Date ) { final SimpleDateFormat format = new SimpleDateFormat ( "yyyy-MM-dd hh:mm:ss" ) ; final String result = format . format ( ( Date ) value ) ; logger . debug ( "Formatted date {} to: {}" , value , result ) ; return result ; } return getLabel ( value . toString ( ) ) ; } | Gets the label of a value eg . a value in a crosstab . |
36,643 | public DCPanel createPanel ( ) { final DCPanel parentPanel = new DCPanel ( ) ; parentPanel . setLayout ( new BorderLayout ( ) ) ; parentPanel . add ( _sourceComboBoxPanel , BorderLayout . CENTER ) ; parentPanel . add ( _buttonPanel , BorderLayout . EAST ) ; return parentPanel ; } | Creates a panel containing ButtonPanel and SourceComboboxPanel |
36,644 | public void updateSourceComboBoxes ( final Datastore datastore , final Table table ) { _datastore = datastore ; _table = table ; for ( final SourceColumnComboBox sourceColComboBox : _sourceColumnComboBoxes ) { sourceColComboBox . setModel ( datastore , table ) ; } } | updates the SourceColumnComboBoxes with the provided datastore and table |
36,645 | public Date getFrom ( ) { final TimeInterval first = intervals . first ( ) ; if ( first != null ) { return new Date ( first . getFrom ( ) ) ; } return null ; } | Gets the first date in this timeline |
36,646 | public Date getTo ( ) { Long to = null ; for ( final TimeInterval interval : intervals ) { if ( to == null ) { to = interval . getTo ( ) ; } else { to = Math . max ( interval . getTo ( ) , to ) ; } } if ( to != null ) { return new Date ( to ) ; } return null ; } | Gets the last date in this timeline |
36,647 | public static double [ ] [ ] toFeatureVector ( Iterable < ? extends MLRecord > data , List < MLFeatureModifier > featureModifiers ) { final List < double [ ] > trainingInstances = new ArrayList < > ( ) ; for ( MLRecord record : data ) { final double [ ] features = generateFeatureValues ( record , featureModifiers ) ; trainingInstances . add ( features ) ; } final double [ ] [ ] x = trainingInstances . toArray ( new double [ trainingInstances . size ( ) ] [ ] ) ; return x ; } | Generates a matrix of feature values for each record . |
36,648 | public static int [ ] toClassificationVector ( Iterable < MLClassificationRecord > data ) { final List < Integer > responseVariables = new ArrayList < > ( ) ; final List < Object > classifications = new ArrayList < > ( ) ; for ( MLClassificationRecord record : data ) { final Object classification = record . getClassification ( ) ; int classificationIndex = classifications . indexOf ( classification ) ; if ( classificationIndex == - 1 ) { classifications . add ( classification ) ; classificationIndex = classifications . size ( ) - 1 ; } responseVariables . add ( classificationIndex ) ; } final int [ ] y = responseVariables . stream ( ) . mapToInt ( i -> i ) . toArray ( ) ; return y ; } | Generates a vector of classifications for each record . |
36,649 | public static double [ ] toRegressionOutputVector ( Iterable < MLRegressionRecord > data ) { final Stream < MLRegressionRecord > stream = StreamSupport . stream ( data . spliterator ( ) , false ) ; return stream . mapToDouble ( MLRegressionRecord :: getRegressionOutput ) . toArray ( ) ; } | Generates a vector of regression outputs for every record |
36,650 | public final void batchUpdateWidget ( final Runnable action ) { _batchUpdateCounter ++ ; try { action . run ( ) ; } catch ( final RuntimeException e ) { logger . error ( "Exception occurred in widget batch update, fireValueChanged() will not be invoked" , e ) ; throw e ; } finally { _batchUpdateCounter -- ; } if ( _batchUpdateCounter == 0 ) { onBatchFinished ( ) ; } } | Executes a widget batch update . Listeners and other effects of updating individual parts of a widget may be turned off during batch updates . |
36,651 | public static ClassLoader getExtensionClassLoader ( ) { final Collection < ClassLoader > childClassLoaders = new ArrayList < > ( ) ; childClassLoaders . addAll ( _allExtensionClassLoaders ) ; childClassLoaders . add ( ClassLoaderUtils . getParentClassLoader ( ) ) ; return new CompoundClassLoader ( childClassLoaders ) ; } | Gets the classloader that represents the currently loaded extensions classes . |
36,652 | public boolean setProgress ( final int currentRow ) { final boolean result = _progressBar . setValueIfGreater ( currentRow ) ; if ( result ) { _progressCountLabel . setText ( formatNumber ( currentRow ) ) ; } return result ; } | Sets the progress of the processing of the table . |
36,653 | private Column [ ] getQueryOutputColumns ( final boolean checkNames ) { if ( queryOutputColumns == null ) { try ( DatastoreConnection con = datastore . openConnection ( ) ) { queryOutputColumns = con . getSchemaNavigator ( ) . convertToColumns ( schemaName , tableName , outputColumns ) ; } } else if ( checkNames ) { if ( ! isQueryOutputColumnsUpdated ( ) ) { queryOutputColumns = null ; return getQueryOutputColumns ( false ) ; } } return queryOutputColumns ; } | Gets the output columns of the lookup query |
36,654 | public NamedPatternMatch < E > match ( final String string ) { final Matcher matcher = pattern . matcher ( string ) ; while ( matcher . find ( ) ) { final int start = matcher . start ( ) ; final int end = matcher . end ( ) ; if ( start == 0 && end == string . length ( ) ) { final Map < E , String > resultMap = new EnumMap < > ( groupEnum ) ; final Set < Entry < E , Integer > > entries = groupIndexes . entrySet ( ) ; for ( final Entry < E , Integer > entry : entries ) { final E group = entry . getKey ( ) ; final Integer groupIndex = entry . getValue ( ) ; final String result = matcher . group ( groupIndex ) ; resultMap . put ( group , result ) ; } return new NamedPatternMatch < > ( resultMap ) ; } } return null ; } | Matches a string against this named pattern . |
36,655 | public static < E > int compare ( final Comparable < E > obj1 , final E obj2 ) { if ( obj1 == obj2 ) { return 0 ; } if ( obj1 == null ) { return - 1 ; } if ( obj2 == null ) { return 1 ; } return obj1 . compareTo ( obj2 ) ; } | Compares two objects of which one of them is a comparable of the other . |
36,656 | private URI findFile ( final String filePath , final boolean upload ) { try { URI fileURI ; try { fileURI = _hadoopDefaultFS . getUri ( ) . resolve ( filePath ) ; } catch ( final Exception e ) { fileURI = null ; } if ( ( fileURI == null || ! _hadoopDefaultFS . exists ( new Path ( fileURI ) ) ) && upload ) { final File file = new File ( filePath ) ; if ( ! file . isFile ( ) ) { throw new IllegalArgumentException ( "'" + filePath + " does not exist, or is not a file" ) ; } final String fileName = file . toPath ( ) . getFileName ( ) . toString ( ) ; return _applicationDriver . copyFileToHdfs ( file , DATACLEANER_TEMP_DIR + "/" + UUID . randomUUID ( ) + fileName ) ; } return fileURI ; } catch ( final IOException e ) { throw new IllegalArgumentException ( "Path '" + filePath + "' is not a proper file path" ) ; } } | Tries to find a file on HDFS and optionally uploads it if not found . |
36,657 | public static void setFlotHome ( String flotHome ) { if ( flotHome == null || flotHome . trim ( ) . isEmpty ( ) ) { System . clearProperty ( SYSTEM_PROPERTY_FLOT_HOME ) ; } else { final String propValue = flotHome . endsWith ( "/" ) ? flotHome . substring ( 0 , flotHome . length ( ) - 1 ) : flotHome ; System . setProperty ( SYSTEM_PROPERTY_FLOT_HOME , propValue ) ; } } | Sets the home folder of all flot javascript files |
36,658 | public void attach ( final AnalyzerResult explorationResult ) { final ResultProducer resultProducer ; if ( explorationResult == null ) { resultProducer = null ; } else { resultProducer = new DefaultResultProducer ( explorationResult ) ; } attach ( resultProducer ) ; } | Attaches an AnalyzerResult as result - exploration data for the navigated position of the crosstab . |
36,659 | public String getHref ( ) { final String displayName = _componentDescriptor . getDisplayName ( ) ; final String filename = StringUtils . replaceWhitespaces ( displayName . toLowerCase ( ) . trim ( ) , "_" ) . replaceAll ( "\\/" , "_" ) . replaceAll ( "\\\\" , "_" ) ; return filename + ".html" ; } | Gets the href attribute content if a link to this component should be made from elsewhere in the component docs . |
36,660 | public void reorderValue ( final InputColumn < ? > [ ] sortedValue ) { final int offset = 2 ; for ( int i = 0 ; i < sortedValue . length ; i ++ ) { final InputColumn < ? > inputColumn = sortedValue [ i ] ; final JComponent decoration = getOrCreateCheckBoxDecoration ( inputColumn , true ) ; final int position = offset + i ; add ( decoration , position ) ; } updateUI ( ) ; final TreeMap < InputColumn < ? > , DCCheckBox < InputColumn < ? > > > checkBoxesCopy = new TreeMap < > ( _checkBoxes ) ; _checkBoxes . clear ( ) ; for ( final InputColumn < ? > inputColumn : sortedValue ) { final DCCheckBox < InputColumn < ? > > checkBox = checkBoxesCopy . get ( inputColumn ) ; _checkBoxes . put ( inputColumn , checkBox ) ; } _checkBoxes . putAll ( checkBoxesCopy ) ; setValue ( sortedValue ) ; } | Reorders the values |
36,661 | public AverageBuilder addValue ( final Number number ) { final double total = _average * _numValues + number . doubleValue ( ) ; _numValues ++ ; _average = total / _numValues ; return this ; } | Adds a value to the average that is being built . |
36,662 | public boolean setValueIfGreater ( final int newValue ) { final boolean greater = _value . setIfSignificantToUser ( newValue ) ; if ( greater ) { WidgetUtils . invokeSwingAction ( ( ) -> DCProgressBar . super . setValue ( newValue ) ) ; } return greater ; } | Sets the value of the progress bar if the new value is greater than the previous value . |
36,663 | private void createAnalyzers ( final AnalysisJobBuilder ajb , final Class < ? extends Analyzer < ? > > analyzerClass , final List < InputColumn < ? > > columns ) { final int columnsPerAnalyzer = getColumnsPerAnalyzer ( ) ; AnalyzerComponentBuilder < ? > analyzerJobBuilder = ajb . addAnalyzer ( analyzerClass ) ; int columnCount = 0 ; for ( final InputColumn < ? > inputColumn : columns ) { if ( columnCount == columnsPerAnalyzer ) { analyzerJobBuilder = ajb . addAnalyzer ( analyzerClass ) ; columnCount = 0 ; } analyzerJobBuilder . addInputColumn ( inputColumn ) ; if ( isIncludeValueDistribution ( ) ) { ajb . addAnalyzer ( ValueDistributionAnalyzer . class ) . addInputColumn ( inputColumn ) ; } if ( inputColumn . getDataType ( ) == String . class && isIncludePatternFinder ( ) ) { ajb . addAnalyzer ( PatternFinderAnalyzer . class ) . addInputColumn ( inputColumn ) ; } columnCount ++ ; } } | Registers analyzers and up to 4 columns per analyzer . This restriction is to ensure that results will be nicely readable . A table might contain hundreds of columns . |
36,664 | public static Field [ ] getAllFields ( final Class < ? > clazz ) { final List < Field > allFields = new ArrayList < > ( ) ; addFields ( allFields , clazz ) ; return allFields . toArray ( new Field [ allFields . size ( ) ] ) ; } | Gets all fields of a class including private fields in super - classes . |
36,665 | public static Field [ ] getNonSyntheticFields ( final Class < ? > clazz ) { final List < Field > fieldList = new ArrayList < > ( ) ; addFields ( fieldList , clazz , true ) ; return fieldList . toArray ( new Field [ fieldList . size ( ) ] ) ; } | Gets non - synthetic fields of a class including private fields in super - classes . |
36,666 | private void awaitTasks ( ) { if ( _tasksPending . get ( ) == 0 ) { return ; } synchronized ( this ) { while ( _tasksPending . get ( ) != 0 ) { try { logger . info ( "Scan tasks still pending, waiting" ) ; wait ( ) ; } catch ( final InterruptedException e ) { logger . debug ( "Interrupted while awaiting task completion" , e ) ; } } } } | Waits for all pending tasks to finish |
36,667 | public final boolean satisfiedForConsume ( final FilterOutcomes outcomes , final InputRow row ) { final boolean satisfiedOutcomesForConsume = satisfiedOutcomesForConsume ( _hasComponentRequirement , row , outcomes ) ; if ( ! satisfiedOutcomesForConsume ) { return false ; } return satisfiedInputsForConsume ( row , outcomes ) ; } | Ensures that just a single outcome is satisfied |
36,668 | public Object getVertex ( final Point2D point2D ) { final GraphElementAccessor < ? , ? > pickSupport = _visualizationViewer . getPickSupport ( ) ; @ SuppressWarnings ( "rawtypes" ) final Layout graphLayout = _visualizationViewer . getModel ( ) . getGraphLayout ( ) ; @ SuppressWarnings ( "unchecked" ) final Object vertex = pickSupport . getVertex ( graphLayout , point2D . getX ( ) , point2D . getY ( ) ) ; return vertex ; } | Gets the vertex at a particular point or null if it does not exist . |
36,669 | public void cancelDownload ( final boolean hideWindowImmediately ) { logger . info ( "Cancel of download requested" ) ; _cancelled = true ; if ( hideWindowImmediately && _downloadProgressWindow != null ) { WidgetUtils . invokeSwingAction ( _downloadProgressWindow :: close ) ; } } | Cancels the file download . |
36,670 | public void updateProgress ( final Table table , final int currentRow ) { final TableProgressInformationPanel tableProgressInformationPanel = getTableProgressInformationPanel ( table , - 1 ) ; final boolean greater = tableProgressInformationPanel . setProgress ( currentRow ) ; if ( ! greater ) { return ; } ProgressCounter counter = _progressTimingCounters . get ( table ) ; if ( counter == null ) { counter = new ProgressCounter ( ) ; final ProgressCounter previous = _progressTimingCounters . put ( table , counter ) ; if ( previous != null ) { counter = previous ; } } final boolean log ; final int previousCount = counter . get ( ) ; if ( currentRow - previousCount > 1000 ) { log = counter . setIfSignificantToUser ( currentRow ) ; } else { log = false ; } if ( log ) { addUserLog ( "Progress of " + table . getName ( ) + ": " + formatNumber ( currentRow ) + " rows processed" ) ; } } | Informs the panel that the progress for a table is updated |
36,671 | private boolean scanHadoopConfigFiles ( final ServerInformationCatalog serverInformationCatalog , final String selectedServer ) { final HadoopClusterInformation clusterInformation ; if ( selectedServer != null ) { clusterInformation = ( HadoopClusterInformation ) serverInformationCatalog . getServer ( selectedServer ) ; } else { clusterInformation = ( HadoopClusterInformation ) serverInformationCatalog . getServer ( HadoopResource . DEFAULT_CLUSTERREFERENCE ) ; } if ( clusterInformation == null ) { return false ; } final Configuration configuration = HdfsUtils . getHadoopConfigurationWithTimeout ( clusterInformation ) ; _currentDirectory = new Path ( "/" ) ; try { _fileSystem = FileSystem . newInstance ( configuration ) ; } catch ( final IOException e ) { throw new IllegalArgumentException ( "Illegal URI when showing HDFS chooser" , e ) ; } final HdfsDirectoryModel model = ( HdfsDirectoryModel ) _fileList . getModel ( ) ; model . updateFileList ( ) ; return model . _files . length > 0 ; } | This scans Hadoop environment variables for a directory with configuration files |
36,672 | public Map < ComponentJob , AnalyzerResult > getUnsafeResultElements ( ) { if ( _unsafeResultElements == null ) { _unsafeResultElements = new LinkedHashMap < > ( ) ; final Map < ComponentJob , AnalyzerResult > resultMap = _analysisResult . getResultMap ( ) ; for ( final Entry < ComponentJob , AnalyzerResult > entry : resultMap . entrySet ( ) ) { final AnalyzerResult analyzerResult = entry . getValue ( ) ; try { SerializationUtils . serialize ( analyzerResult , new NullOutputStream ( ) ) ; } catch ( final SerializationException e ) { _unsafeResultElements . put ( entry . getKey ( ) , analyzerResult ) ; } } } return _unsafeResultElements ; } | Gets a map of unsafe result elements ie . elements that cannot be saved because serialization fails . |
36,673 | private void escapeValueTo ( final String field , final StringBuilder target ) { if ( field == null ) { target . append ( DETAILS_QUOTE_CHAR ) ; target . append ( DETAILS_QUOTE_CHAR ) ; return ; } target . append ( DETAILS_QUOTE_CHAR ) ; if ( field . indexOf ( DETAILS_ESCAPE_CHAR ) == - 1 && field . indexOf ( DETAILS_QUOTE_CHAR ) == - 1 ) { target . append ( field ) ; } else { final int len = field . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { final char charAt = field . charAt ( i ) ; if ( charAt == DETAILS_ESCAPE_CHAR || charAt == DETAILS_QUOTE_CHAR ) { target . append ( DETAILS_ESCAPE_CHAR ) ; } target . append ( charAt ) ; } } target . append ( DETAILS_QUOTE_CHAR ) ; } | Escapes value for a CSV line and appends it to the target . |
36,674 | public void createMeasureDimensionValueCombinationCrosstab ( final Map < ValueCombination < Number > , Number > valueCombinations , final Crosstab < Number > valueCombinationCrosstab ) { if ( CrosstabReducerHelper . findDimension ( valueCombinationCrosstab , BooleanAnalyzer . DIMENSION_MEASURE ) ) { final SortedSet < Entry < ValueCombination < Number > , Number > > entries = new TreeSet < > ( frequentValueCombinationComparator ) ; entries . addAll ( valueCombinations . entrySet ( ) ) ; final CrosstabNavigator < Number > nav = new CrosstabNavigator < > ( valueCombinationCrosstab ) ; final CrosstabDimension measureDimension = valueCombinationCrosstab . getDimension ( BooleanAnalyzer . DIMENSION_MEASURE ) ; final CrosstabDimension columnDimension = valueCombinationCrosstab . getDimension ( BooleanAnalyzer . DIMENSION_COLUMN ) ; final List < String > columnDimCategories = columnDimension . getCategories ( ) ; int row = 0 ; for ( final Entry < ValueCombination < Number > , Number > entry : entries ) { final String measureName ; if ( row == 0 ) { measureName = BooleanAnalyzer . MEASURE_MOST_FREQUENT ; } else if ( row == entries . size ( ) - 1 ) { measureName = BooleanAnalyzer . MEASURE_LEAST_FREQUENT ; } else { measureName = BooleanAnalyzer . DIMENSION_COMBINATION_PREFIX + row ; } measureDimension . addCategory ( measureName ) ; final Number [ ] values = new Number [ columnDimCategories . size ( ) ] ; final ValueCombination < Number > key = entry . getKey ( ) ; for ( int i = 0 ; i < key . getValueCount ( ) ; i ++ ) { values [ i ] = key . getValueAt ( i ) ; } values [ columnDimCategories . size ( ) - 1 ] = entry . getValue ( ) ; for ( int i = 0 ; i < columnDimCategories . size ( ) ; i ++ ) { nav . where ( columnDimension , columnDimCategories . get ( i ) ) ; nav . where ( measureDimension , measureName ) ; nav . put ( values [ i ] ) ; } row ++ ; } } } | Creates the measure dimension based on the sorted value combinations |
36,675 | public void addValueCombinationsCrosstabDimension ( final Map < ValueCombination < Number > , Number > valueCombMapList , final Crosstab < Number > partialCrosstab ) { final CrosstabNavigator < Number > nav = new CrosstabNavigator < > ( partialCrosstab ) ; final CrosstabDimension columnDimension = partialCrosstab . getDimension ( BooleanAnalyzer . DIMENSION_COLUMN ) ; final CrosstabDimension measureDimension = partialCrosstab . getDimension ( BooleanAnalyzer . DIMENSION_MEASURE ) ; final List < String > columnDimCategories = columnDimension . getCategories ( ) ; final List < String > measureCategories = measureDimension . getCategories ( ) ; for ( final String measureCategory : measureCategories ) { final Number [ ] values = new Number [ columnDimCategories . size ( ) - 1 ] ; for ( int i = 0 ; i < columnDimCategories . size ( ) - 1 ; i ++ ) { nav . where ( columnDimension , columnDimCategories . get ( i ) ) ; final CrosstabNavigator < Number > where = nav . where ( measureDimension , measureCategory ) ; final Number value = where . safeGet ( null ) ; if ( ! columnDimCategories . get ( 0 ) . equals ( BooleanAnalyzer . VALUE_COMBINATION_COLUMN_FREQUENCY ) ) { values [ i ] = value ; } } final CrosstabNavigator < Number > where = nav . where ( columnDimension , BooleanAnalyzer . VALUE_COMBINATION_COLUMN_FREQUENCY ) ; final Number frequency = where . safeGet ( null ) ; final Number frequencyVal = frequency != null ? frequency : 0 ; final ValueCombination < Number > valComb = new ValueCombination < > ( values ) ; final Number combination = valueCombMapList . get ( valComb ) ; if ( combination == null ) { valueCombMapList . put ( valComb , frequencyVal ) ; } else { final Number newValue = CrosstabReducerHelper . sum ( combination , frequencyVal ) ; valueCombMapList . put ( valComb , newValue ) ; } } } | Gather the sum of all possible value combinations of the partial crosstabs |
36,676 | public void onConfigurationChanged ( ) { final Collection < PropertyWidget < ? > > widgets = getWidgets ( ) ; if ( logger . isDebugEnabled ( ) ) { final StringBuilder sb = new StringBuilder ( ) ; sb . append ( "id=" ) ; sb . append ( System . identityHashCode ( this ) ) ; sb . append ( " - onConfigurationChanged() - notifying widgets:" ) ; sb . append ( widgets . size ( ) ) ; for ( final PropertyWidget < ? > widget : widgets ) { final String propertyName = widget . getPropertyDescriptor ( ) . getName ( ) ; final String propertyWidgetClassName = widget . getClass ( ) . getSimpleName ( ) ; sb . append ( "\n - " ) ; sb . append ( propertyName ) ; sb . append ( ": " ) ; sb . append ( propertyWidgetClassName ) ; } logger . debug ( sb . toString ( ) ) ; } for ( final PropertyWidget < ? > widget : widgets ) { @ SuppressWarnings ( "unchecked" ) final PropertyWidget < Object > objectWidget = ( PropertyWidget < Object > ) widget ; final ConfiguredPropertyDescriptor propertyDescriptor = objectWidget . getPropertyDescriptor ( ) ; final Object value = _componentBuilder . getConfiguredProperty ( propertyDescriptor ) ; objectWidget . onValueTouched ( value ) ; } } | Invoked whenever a configured property within this widget factory is changed . |
36,677 | protected Collection < String > normalize ( String string , final boolean tokenize ) { if ( string == null ) { return Collections . emptyList ( ) ; } if ( tokenize ) { final Collection < String > result = new LinkedHashSet < > ( ) ; result . addAll ( normalize ( string , false ) ) ; final Splitter splitter = Splitter . on ( ' ' ) . omitEmptyStrings ( ) ; final List < String > tokens = splitter . splitToList ( string ) ; for ( final String token : tokens ) { final Collection < String > normalizedTokens = normalize ( token , false ) ; result . addAll ( normalizedTokens ) ; } return result ; } else { string = StringUtils . replaceWhitespaces ( string , "" ) ; string = StringUtils . replaceAll ( string , "-" , "" ) ; string = StringUtils . replaceAll ( string , "_" , "" ) ; string = StringUtils . replaceAll ( string , "|" , "" ) ; string = StringUtils . replaceAll ( string , "*" , "" ) ; string = string . toUpperCase ( ) ; if ( string . isEmpty ( ) ) { return Collections . emptyList ( ) ; } final String withoutNumbers = string . replaceAll ( "[0-9]" , "" ) ; if ( withoutNumbers . equals ( string ) || withoutNumbers . isEmpty ( ) ) { return Arrays . asList ( string ) ; } return Arrays . asList ( string , withoutNumbers ) ; } } | Normalizes the incoming string before doing matching |
36,678 | private ValueFrequency getDistinctValueCount ( final ValueCountingAnalyzerResult res ) { int distinctValueCounter = 0 ; ValueFrequency valueCount = null ; if ( res . getNullCount ( ) > 0 ) { distinctValueCounter ++ ; valueCount = new SingleValueFrequency ( LabelUtils . NULL_LABEL , res . getNullCount ( ) ) ; } final int uniqueCount = res . getUniqueCount ( ) ; if ( uniqueCount > 0 ) { if ( uniqueCount > 1 ) { return null ; } distinctValueCounter ++ ; final Collection < String > uniqueValues = res . getUniqueValues ( ) ; String label = LabelUtils . UNIQUE_LABEL ; if ( ! uniqueValues . isEmpty ( ) ) { label = uniqueValues . iterator ( ) . next ( ) ; } valueCount = new CompositeValueFrequency ( label , 1 ) ; } if ( distinctValueCounter > 1 ) { return null ; } final Collection < ValueFrequency > valueCounts = res . getValueCounts ( ) ; if ( valueCounts . size ( ) > 0 ) { distinctValueCounter += valueCounts . size ( ) ; valueCount = valueCounts . iterator ( ) . next ( ) ; } if ( distinctValueCounter > 1 ) { return null ; } return valueCount ; } | Determines if a group result has just a single distinct value count . If so this value count is returned or else null is returned . |
36,679 | public JToggleButton getSelectedToggleButton ( ) { for ( final AbstractButton button : _buttons ) { if ( button instanceof JToggleButton ) { if ( button . isSelected ( ) ) { return ( JToggleButton ) button ; } } } return null ; } | Gets the currently selected toggle button if any . |
36,680 | public static void main ( final String [ ] args ) { LookAndFeelManager . get ( ) . init ( ) ; final ComboButton comboButton1 = new ComboButton ( ) ; comboButton1 . addButton ( "Foo!" , IconUtils . ACTION_ADD_DARK , true ) ; comboButton1 . addButton ( "Boo!" , IconUtils . ACTION_REMOVE_DARK , true ) ; final ComboButton comboButton2 = new ComboButton ( ) ; comboButton2 . addButton ( "Foo!" , IconUtils . ACTION_ADD_DARK , false ) ; comboButton2 . addButton ( "Boo!" , IconUtils . ACTION_REMOVE_DARK , false ) ; comboButton2 . addButton ( "Mrr!" , IconUtils . ACTION_REFRESH , true ) ; comboButton2 . addButton ( "Rrrh!" , IconUtils . ACTION_DRILL_TO_DETAIL , true ) ; final DCPanel panel = new DCPanel ( WidgetUtils . COLOR_DEFAULT_BACKGROUND ) ; panel . add ( comboButton1 ) ; panel . add ( comboButton2 ) ; final JButton regularButton = WidgetFactory . createDefaultButton ( "Regular button" , IconUtils . ACTION_ADD_DARK ) ; panel . add ( regularButton ) ; final JFrame frame = new JFrame ( "test" ) ; frame . setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE ) ; frame . setSize ( 500 , 400 ) ; frame . add ( panel ) ; frame . pack ( ) ; frame . setVisible ( true ) ; } | a simple test app |
36,681 | public final void setMetadataProperty ( final String key , final String value ) { _metadataProperties . put ( key , value ) ; } | Sets a metadata property |
36,682 | public int launch ( final String configurationHdfsPath , final String jobHdfsPath ) throws Exception { final File hadoopConfDir = createTemporaryHadoopConfDir ( ) ; final SparkLauncher sparkLauncher = createSparkLauncher ( hadoopConfDir , configurationHdfsPath , jobHdfsPath , null ) ; return launch ( sparkLauncher ) ; } | Launches and waits for the execution of a DataCleaner job on Spark . |
36,683 | public boolean removeHadoopClusterServerInformation ( final String serverName ) { final Element serverInformationCatalogElement = getServerInformationCatalogElement ( ) ; final Element hadoopClustersElement = getOrCreateChildElementByTagName ( serverInformationCatalogElement , "hadoop-clusters" ) ; return removeChildElementByNameAttribute ( serverName , hadoopClustersElement ) ; } | Removes a Hadoop cluster by its name if it exists and is recognizeable by the externalizer . |
36,684 | public Element getDictionariesElement ( ) { final Element referenceDataCatalogElement = getReferenceDataCatalogElement ( ) ; final Element dictionariesElement = getOrCreateChildElementByTagName ( referenceDataCatalogElement , "dictionaries" ) ; if ( dictionariesElement == null ) { throw new IllegalStateException ( "Could not find <dictionaries> element in configuration file" ) ; } return dictionariesElement ; } | Gets the XML element that represents the dictionaries |
36,685 | public Element getSynonymCatalogsElement ( ) { final Element referenceDataCatalogElement = getReferenceDataCatalogElement ( ) ; final Element synonymCatalogsElement = getOrCreateChildElementByTagName ( referenceDataCatalogElement , "synonym-catalogs" ) ; if ( synonymCatalogsElement == null ) { throw new IllegalStateException ( "Could not find <synonym-catalogs> element in configuration file" ) ; } return synonymCatalogsElement ; } | Gets the XML element that represents the synonym catalogs |
36,686 | public Element getStringPatternsElement ( ) { final Element referenceDataCatalogElement = getReferenceDataCatalogElement ( ) ; final Element stringPatternsElement = getOrCreateChildElementByTagName ( referenceDataCatalogElement , "string-patterns" ) ; if ( stringPatternsElement == null ) { throw new IllegalStateException ( "Could not find <string-patterns> element in configuration file" ) ; } return stringPatternsElement ; } | Gets the XML element that represents the string patterns |
36,687 | public void setAvailableInputColumns ( final Collection < InputColumn < ? > > inputColumns ) { final InputColumn < ? > [ ] items = new InputColumn < ? > [ inputColumns . size ( ) + 1 ] ; int index = 1 ; for ( final InputColumn < ? > inputColumn : inputColumns ) { items [ index ] = inputColumn ; index ++ ; } final DefaultComboBoxModel < InputColumn < ? > > model = new DefaultComboBoxModel < > ( items ) ; _comboBox . setModel ( model ) ; } | Called by the parent widget to update the list of available columns |
36,688 | public static OutputWriter getWriter ( final String filename , final List < InputColumn < ? > > columns ) { final InputColumn < ? > [ ] columnArray = columns . toArray ( new InputColumn < ? > [ columns . size ( ) ] ) ; final String [ ] headers = new String [ columnArray . length ] ; for ( int i = 0 ; i < headers . length ; i ++ ) { headers [ i ] = columnArray [ i ] . getName ( ) ; } return getWriter ( filename , headers , ',' , '"' , '\\' , true , columnArray ) ; } | Creates a CSV output writer with default configuration |
36,689 | public static OutputWriter getWriter ( final String filename , final String [ ] headers , final char separatorChar , final char quoteChar , final char escapeChar , final boolean includeHeader , final InputColumn < ? > ... columns ) { return getWriter ( new FileResource ( filename ) , headers , FileHelper . DEFAULT_ENCODING , separatorChar , quoteChar , escapeChar , includeHeader , columns ) ; } | Creates a CSV output writer |
36,690 | public void onComponentRightClicked ( final ComponentBuilder componentBuilder , final MouseEvent me ) { final boolean isMultiStream = componentBuilder . getDescriptor ( ) . isMultiStreamComponent ( ) ; final JPopupMenu popup = new JPopupMenu ( ) ; final JMenuItem configureComponentMenuItem = new JMenuItem ( "Configure ..." , ImageManager . get ( ) . getImageIcon ( IconUtils . MENU_OPTIONS , IconUtils . ICON_SIZE_SMALL ) ) ; configureComponentMenuItem . addActionListener ( e -> _actions . showConfigurationDialog ( componentBuilder ) ) ; popup . add ( configureComponentMenuItem ) ; if ( ! isMultiStream && componentBuilder instanceof InputColumnSourceJob || componentBuilder instanceof HasFilterOutcomes ) { popup . add ( createLinkMenuItem ( componentBuilder ) ) ; } for ( final OutputDataStream dataStream : componentBuilder . getOutputDataStreams ( ) ) { final JobGraphLinkPainter . VertexContext vertexContext = new JobGraphLinkPainter . VertexContext ( componentBuilder , componentBuilder . getOutputDataStreamJobBuilder ( dataStream ) , dataStream ) ; popup . add ( createLinkMenuItem ( vertexContext ) ) ; } final Icon renameIcon = ImageManager . get ( ) . getImageIcon ( IconUtils . ACTION_RENAME , IconUtils . ICON_SIZE_SMALL ) ; final JMenuItem renameMenuItem = WidgetFactory . createMenuItem ( "Rename component" , renameIcon ) ; renameMenuItem . addActionListener ( new DefaultRenameComponentActionListener ( componentBuilder , _graphContext ) ) ; popup . add ( renameMenuItem ) ; if ( ! isMultiStream && componentBuilder instanceof TransformerComponentBuilder ) { final TransformerComponentBuilder < ? > tjb = ( TransformerComponentBuilder < ? > ) componentBuilder ; final JMenuItem previewMenuItem = new JMenuItem ( "Preview data" , ImageManager . get ( ) . getImageIcon ( IconUtils . ACTION_PREVIEW , IconUtils . ICON_SIZE_SMALL ) ) ; previewMenuItem . addActionListener ( new PreviewTransformedDataActionListener ( _windowContext , tjb ) ) ; previewMenuItem . setEnabled ( componentBuilder . isConfigured ( ) ) ; popup . add ( previewMenuItem ) ; } if ( ChangeRequirementMenu . isRelevant ( componentBuilder ) ) { popup . add ( new ChangeRequirementMenu ( componentBuilder ) ) ; } popup . addSeparator ( ) ; popup . add ( new RemoveComponentMenuItem ( componentBuilder ) ) ; popup . show ( _graphContext . getVisualizationViewer ( ) , me . getX ( ) , me . getY ( ) ) ; } | Invoked when a component is right - clicked |
36,691 | public void onCanvasRightClicked ( final MouseEvent me ) { _linkPainter . cancelLink ( ) ; final JPopupMenu popup = new JPopupMenu ( ) ; final Point point = me . getPoint ( ) ; final AnalysisJobBuilder analysisJobBuilder = _graphContext . getMainAnalysisJobBuilder ( ) ; final DataCleanerConfiguration configuration = analysisJobBuilder . getConfiguration ( ) ; final Set < ComponentSuperCategory > superCategories = configuration . getEnvironment ( ) . getDescriptorProvider ( ) . getComponentSuperCategories ( ) ; for ( final ComponentSuperCategory superCategory : superCategories ) { final DescriptorMenuBuilder menuBuilder = new DescriptorMenuBuilder ( analysisJobBuilder , superCategory , point ) ; final JMenu menu = new JMenu ( superCategory . getName ( ) ) ; menu . setIcon ( IconUtils . getComponentSuperCategoryIcon ( superCategory , IconUtils . ICON_SIZE_MENU_ITEM ) ) ; menuBuilder . addItemsToMenu ( menu ) ; popup . add ( menu ) ; } { final JMenuItem menuItem = WidgetFactory . createMenuItem ( "Job metadata" , IconUtils . MODEL_METADATA ) ; menuItem . addActionListener ( e -> { final MetadataDialog dialog = new MetadataDialog ( _windowContext , analysisJobBuilder ) ; dialog . open ( ) ; } ) ; popup . add ( menuItem ) ; } popup . show ( _graphContext . getVisualizationViewer ( ) , me . getX ( ) , me . getY ( ) ) ; } | Invoked when the canvas is right - clicked |
36,692 | public void copyToClipboard ( final int rowIndex , final int colIndex , final int width , final int height ) { final StringBuilder sb = new StringBuilder ( ) ; if ( rowIndex == 0 && colIndex == 0 && width == getColumnCount ( ) && height == getRowCount ( ) ) { for ( int i = 0 ; i < width ; i ++ ) { sb . append ( getColumnName ( i ) ) ; if ( i < height - 1 ) { sb . append ( "\t" ) ; } } sb . append ( "\n" ) ; } for ( int row = rowIndex ; row < rowIndex + height ; row ++ ) { for ( int col = colIndex ; col < colIndex + width ; col ++ ) { Object value = getValueAt ( row , col ) ; if ( value == null ) { value = "" ; } else if ( value instanceof JComponent ) { value = WidgetUtils . extractText ( ( JComponent ) value ) ; } sb . append ( value ) ; sb . append ( "\t" ) ; } sb . deleteCharAt ( sb . length ( ) - 1 ) ; sb . append ( "\n" ) ; } final Clipboard clipboard = Toolkit . getDefaultToolkit ( ) . getSystemClipboard ( ) ; final StringSelection stsel = new StringSelection ( sb . toString ( ) ) ; clipboard . setContents ( stsel , stsel ) ; } | Copies content from the table to the clipboard . Algorithm is a slight rewrite of the article below . |
36,693 | public void run ( final R row , final String value , final int distinctCount ) { final List < Token > tokens ; try { tokens = _tokenizer . tokenize ( value ) ; } catch ( final RuntimeException e ) { throw new IllegalStateException ( "Error occurred while tokenizing value: " + value , e ) ; } final String patternCode = getPatternCode ( tokens ) ; final Collection < TokenPattern > patterns = getOrCreatePatterns ( patternCode ) ; synchronized ( patterns ) { boolean match = false ; for ( final TokenPattern pattern : patterns ) { if ( pattern . match ( tokens ) ) { storeMatch ( pattern , row , value , distinctCount ) ; match = true ; break ; } } if ( ! match ) { final TokenPattern pattern ; try { pattern = new TokenPatternImpl ( value , tokens , _configuration ) ; } catch ( final RuntimeException e ) { throw new IllegalStateException ( "Error occurred while creating pattern for: " + tokens , e ) ; } storeNewPattern ( pattern , row , value , distinctCount ) ; patterns . add ( pattern ) ; } } } | This method should be invoked by the user of the PatternFinder . Invoke it for each value in your dataset . Repeated values are handled correctly but if available it is more efficient to handle only the distinct values and their corresponding distinct counts . |
36,694 | private String getPatternCode ( final List < Token > tokens ) { final StringBuilder sb = new StringBuilder ( ) ; sb . append ( tokens . size ( ) ) ; for ( final Token token : tokens ) { sb . append ( token . getType ( ) . ordinal ( ) ) ; } return sb . toString ( ) ; } | Creates an almost unique String code for a list of tokens . This code is used to improve search time when looking for potential matching patterns . |
36,695 | public List < DatastoreDescriptor > getAvailableDatastoreDescriptors ( ) { final List < DatastoreDescriptor > availableDatabaseDescriptors = new ArrayList < > ( ) ; final List < DatastoreDescriptor > manualDatastoreDescriptors = getManualDatastoreDescriptors ( ) ; availableDatabaseDescriptors . addAll ( manualDatastoreDescriptors ) ; final List < DatastoreDescriptor > driverBasedDatastoreDescriptors = getDriverBasedDatastoreDescriptors ( ) ; availableDatabaseDescriptors . addAll ( driverBasedDatastoreDescriptors ) ; final Set < String > alreadyAddedDatabaseNames = new HashSet < > ( ) ; for ( final DatastoreDescriptor datastoreDescriptor : driverBasedDatastoreDescriptors ) { alreadyAddedDatabaseNames . add ( datastoreDescriptor . getName ( ) ) ; } final List < DatastoreDescriptor > otherDatastoreDescriptors = getOtherDatastoreDescriptors ( alreadyAddedDatabaseNames ) ; availableDatabaseDescriptors . addAll ( otherDatastoreDescriptors ) ; return availableDatabaseDescriptors ; } | Returns the descriptors of datastore types available in DataCleaner . |
36,696 | public List < DatastoreDescriptor > getAvailableCloudBasedDatastoreDescriptors ( ) { final List < DatastoreDescriptor > availableCloudBasedDatabaseDescriptors = new ArrayList < > ( ) ; availableCloudBasedDatabaseDescriptors . add ( SALESFORCE_DATASTORE_DESCRIPTOR ) ; availableCloudBasedDatabaseDescriptors . add ( SUGARCRM_DATASTORE_DESCRIPTOR ) ; return availableCloudBasedDatabaseDescriptors ; } | Returns the descriptors of cloud - based datastore types available in DataCleaner . |
36,697 | public List < DatastoreDescriptor > getAvailableDatabaseBasedDatastoreDescriptors ( ) { final List < DatastoreDescriptor > availableCloudBasedDatabaseDescriptors = new ArrayList < > ( ) ; availableCloudBasedDatabaseDescriptors . add ( POSTGRESQL_DATASTORE_DESCRIPTOR ) ; availableCloudBasedDatabaseDescriptors . add ( SQLSERVER_DATASTORE_DESCRIPTOR ) ; availableCloudBasedDatabaseDescriptors . add ( ELASTICSEARCH_DATASTORE_DESCRIPTOR ) ; availableCloudBasedDatabaseDescriptors . add ( HBASE_DATASTORE_DESCRIPTOR ) ; availableCloudBasedDatabaseDescriptors . add ( HIVE_DATASTORE_DESCRIPTOR ) ; availableCloudBasedDatabaseDescriptors . add ( CASSANDRA_DATASTORE_DESCRIPTOR ) ; availableCloudBasedDatabaseDescriptors . add ( MONGODB_DATASTORE_DESCRIPTOR ) ; availableCloudBasedDatabaseDescriptors . add ( COUCHDB_DATASTORE_DESCRIPTOR ) ; availableCloudBasedDatabaseDescriptors . add ( DYNAMODB_DATASTORE_DESCRIPTOR ) ; availableCloudBasedDatabaseDescriptors . add ( KAFKA_DATASTORE_DESCRIPTOR ) ; availableCloudBasedDatabaseDescriptors . add ( NEO4J_DATASTORE_DESCRIPTOR ) ; return availableCloudBasedDatabaseDescriptors ; } | Returns the descriptors of database - based datastore types available in DataCleaner . |
36,698 | public void setTable ( final Table table ) { if ( table != _tableRef . get ( ) ) { _tableRef . set ( table ) ; if ( table == null ) { _comboBox . setEmptyModel ( ) ; } else { _comboBox . setModel ( table ) ; } } } | Sets the table to use as a source for the available columns in the combobox . |
36,699 | protected JScrollPane wrapContent ( final JComponent panel ) { panel . setMaximumSize ( new Dimension ( WIDTH_CONTENT , Integer . MAX_VALUE ) ) ; panel . setAlignmentX ( Component . LEFT_ALIGNMENT ) ; final DCPanel wrappingPanel = new DCPanel ( ) ; final BoxLayout layout = new BoxLayout ( wrappingPanel , BoxLayout . PAGE_AXIS ) ; wrappingPanel . setLayout ( layout ) ; wrappingPanel . add ( panel ) ; wrappingPanel . setBorder ( new EmptyBorder ( 0 , MARGIN_LEFT , 0 , 0 ) ) ; return WidgetUtils . scrolleable ( wrappingPanel ) ; } | Wraps a content panel in a scroll pane and applies a maximum width to the content to keep it nicely in place on the screen . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.