auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void processException(Exception e, String operation) throws RemoteFileChangedException { if (e instanceof AmazonServiceException) { AmazonServiceException serviceException = (AmazonServiceException) e; if (serviceException.getStatusCode() == 412) { versionMismatches.incrementAndGet(); throw new RemoteFileChangedException(uri, operation, String.format( RemoteFileChangedException.PRECONDITIONS_NOT_MET + " on %s." + " Version %s was unavailable", getSource(), getRevisionId()), serviceException); } } }

Target:
public void processException(Exception e, String operation) throws RemoteFileChangedException { if (e instanceof AmazonServiceException) { AmazonServiceException serviceException = (AmazonServiceException) e; if (serviceException.getStatusCode() == SC_PRECONDITION_FAILED) { versionMismatches.incrementAndGet(); throw new RemoteFileChangedException(uri, operation, String.format( RemoteFileChangedException.PRECONDITIONS_FAILED + " on %s." + " Version %s was unavailable", getSource(), getRevisionId()), serviceException); } } }
Source:
public void train() throws IOException { List<String> commands = buildCommands(); ProcessBuilder pb = new ProcessBuilder(commands); pb.directory(new File("./")); LOGGER.info("Start trainning sub process. Commands {}", commands.toString()); Process p = pb.start(); }

Target:
public void train() throws IOException { List<String> commands = buildCommands(); ProcessBuilder pb = new ProcessBuilder(commands); pb.directory(new File("./")); LOGGER.info("Start trainning sub process. Commands {}", commands.toString()); Process p = pb.start(); StreamCollector sc = new StreamCollector(p.getInputStream()); sc.start(); try { p.waitFor(); sc.close(); } catch (InterruptedException e) { throw new RuntimeException(e); } }
Source:
@Override public ExecuteResult prepareAndExecute(StatementHandle h, String sql, long maxRowCount, int maxRowsInFirstFrame, PrepareCallback callback) throws NoSuchStatementException { final CalcitePrepare.CalciteSignature<Object> signature; try { final int updateCount; synchronized (callback.getMonitor()) { callback.clear(); final CalciteConnectionImpl calciteConnection = getConnection(); final CalciteServerStatement statement = calciteConnection.server.getStatement(h); final Context context = statement.createPrepareContext(); final CalcitePrepare.Query<Object> query = toQuery(context, sql); signature = calciteConnection.parseQuery(query, context, maxRowCount); statement.setSignature(signature); switch (signature.statementType) { case CREATE: case DROP: case ALTER: case OTHER_DDL: updateCount = 0; break; default: updateCount = -1; break; } callback.assign(signature, null, updateCount); } callback.execute(); final MetaResultSet metaResultSet = new MetaResultSetImpl(h.connectionId, h.id, false, signature, null, updateCount); return new ExecuteResult(ImmutableList.of(metaResultSet)); } catch (SQLException e) { throw new RuntimeException(e); } }

Target:
@Override public ExecuteResult prepareAndExecute(StatementHandle h, String sql, long maxRowCount, int maxRowsInFirstFrame, PrepareCallback callback) throws NoSuchStatementException { final CalcitePrepare.CalciteSignature<Object> signature; try { final int updateCount; synchronized (callback.getMonitor()) { callback.clear(); final CalciteConnectionImpl calciteConnection = getConnection(); final CalciteServerStatement statement = calciteConnection.server.getStatement(h); final Context context = statement.createPrepareContext(); final CalcitePrepare.Query<Object> query = toQuery(context, sql); signature = calciteConnection.parseQuery(query, context, maxRowCount); statement.setSignature(signature); switch (signature.statementType) { case CREATE: case DROP: case ALTER: case OTHER_DDL: updateCount = 0; break; default: updateCount = -1; break; } callback.assign(signature, null, updateCount); } callback.execute(); final MetaResultSet metaResultSet = MetaResultSet.create(h.connectionId, h.id, false, signature, null, updateCount); return new ExecuteResult(ImmutableList.of(metaResultSet)); } catch (SQLException e) { throw new RuntimeException(e); } }
Source:
private InputStream generateStream() { final Ds3ObjectList objects = new Ds3ObjectList(); objects.setObjects(this.ds3Objects); objects.setPriority(this.priority); objects.setWriteOptimization(this.writeOptimization); objects.setChunkClientProcessingOrderGuarantee(this.chunkOrdering); final StringBuilder xmlOutputBuilder = new StringBuilder(); if (this.getCommand() == BulkCommand.GET) { xmlOutputBuilder.append(XmlOutput.toXml(objects, true)); } else { xmlOutputBuilder.append(XmlOutput.toXml(objects, false)); } final byte[] stringBytes = xmlOutputBuilder.toString().getBytes(); this.size = stringBytes.length; return new ByteArrayInputStream(stringBytes); }

Target:
private InputStream generateStream() { final Ds3ObjectList objects = new Ds3ObjectList(); objects.setObjects(this.ds3Objects); objects.setPriority(this.priority); objects.setWriteOptimization(this.writeOptimization); objects.setChunkClientProcessingOrderGuarantee(this.chunkOrdering); final StringBuilder xmlOutputBuilder = new StringBuilder(); if (this.getCommand() == BulkCommand.PUT) { xmlOutputBuilder.append(XmlOutput.toXml(objects, true)); } else { xmlOutputBuilder.append(XmlOutput.toXml(objects, false)); } final byte[] stringBytes = xmlOutputBuilder.toString().getBytes(); this.size = stringBytes.length; return new ByteArrayInputStream(stringBytes); }
Source:
public static long parseBytes(String input, ConfigOrigin originForException, String pathForException) { String s = ConfigImplUtil.unicodeTrim(input); String unitString = getUnits(s); String numberString = ConfigImplUtil.unicodeTrim(s.substring(0, s.length() - unitString.length())); if (numberString.length() == 0) throw new ConfigException.BadValue(originForException, pathForException, "No number in size-in-bytes value '" + input + "'"); MemoryUnit units = MemoryUnit.parseUnit(unitString); if (units == null) { throw new ConfigException.BadValue(originForException, pathForException, "Could not parse size-in-bytes unit '" + unitString + "' (try k, K, kB, KiB, kilobytes, kibibytes)"); } try { BigInteger result; if (numberString.matches("[0-9]+")) { result = units.bytes.multiply(new BigInteger(numberString)); } else { BigDecimal resultDecimal = (new BigDecimal(units.bytes)).multiply(new BigDecimal(numberString)); result = resultDecimal.toBigInteger(); } if (result.bitLength() < 64) return result.longValue(); else throw new ConfigException.BadValue(originForException, pathForException, "size-in-bytes value is out of range for a 64-bit long: '" + input + "'"); } catch (NumberFormatException e) { throw new ConfigException.BadValue(originForException, pathForException, "Could not parse size-in-bytes number '" + numberString + "'"); } }

Target:
public static BigInteger parseBytes(String input, ConfigOrigin originForException, String pathForException) { String s = ConfigImplUtil.unicodeTrim(input); String unitString = getUnits(s); String numberString = ConfigImplUtil.unicodeTrim(s.substring(0, s.length() - unitString.length())); if (numberString.length() == 0) throw new ConfigException.BadValue(originForException, pathForException, "No number in size-in-bytes value '" + input + "'"); MemoryUnit units = MemoryUnit.parseUnit(unitString); if (units == null) { throw new ConfigException.BadValue(originForException, pathForException, "Could not parse size-in-bytes unit '" + unitString + "' (try k, K, kB, KiB, kilobytes, kibibytes)"); } try { BigInteger result; if (numberString.matches("[0-9]+")) { result = units.bytes.multiply(new BigInteger(numberString)); } else { BigDecimal resultDecimal = (new BigDecimal(units.bytes)).multiply(new BigDecimal(numberString)); result = resultDecimal.toBigInteger(); } return result; } catch (NumberFormatException e) { throw new ConfigException.BadValue(originForException, pathForException, "Could not parse size-in-bytes number '" + numberString + "'"); } }
Source:
public AbstractFFmpegStreamBuilder() { this.parent = null; }

Target:
protected AbstractFFmpegStreamBuilder() { this.parent = null; }
Source:
protected void processStream(String documentId, InputStream contentStream) throws IOException, InterruptedException { currentProgress++; if (currentProgress > 0 && currentProgress % progresLogInterval == 0) { log.info("metadata extaction progress: " + currentProgress + ", time taken to process " + progresLogInterval + " elements: " + ((System.currentTimeMillis() - intervalTime) / 1000) + " secs"); intervalTime = System.currentTimeMillis(); } if (excludedIds.contains(documentId)) { log.info("skipping processing for excluded id " + documentId); return; } log.info("starting processing for id: " + documentId); long startTime = System.currentTimeMillis(); try { ContentExtractor extractor = new ContentExtractor(interruptionTimeoutSecs); extractor.setPDF(contentStream); try { handleContent(extractor, documentId); } catch (Exception e) { log.error((e.getCause() instanceof InvalidPdfException) ? "Invalid PDF file" : "got unexpected exception, just logging", e); handleException(e, documentId); return; } handleProcessingTime(System.currentTimeMillis() - startTime, documentId); } catch (AnalysisException e) { mos.close(); throw new RuntimeException(e); } }

Target:
protected void processStream(String documentId, InputStream contentStream) throws IOException, InterruptedException { currentProgress++; if (currentProgress % progresLogInterval == 0) { log.info("metadata extaction progress: " + currentProgress + ", time taken to process " + progresLogInterval + " elements: " + ((System.currentTimeMillis() - intervalTime) / 1000) + " secs"); intervalTime = System.currentTimeMillis(); } if (excludedIds.contains(documentId)) { log.info("skipping processing for excluded id " + documentId); return; } log.info("starting processing for id: " + documentId); long startTime = System.currentTimeMillis(); try { ContentExtractor extractor = new ContentExtractor(interruptionTimeoutSecs); extractor.setPDF(contentStream); try { handleContent(extractor, documentId); } catch (Exception e) { log.error((e.getCause() instanceof InvalidPdfException) ? "Invalid PDF file" : "got unexpected exception, just logging", e); handleException(e, documentId); return; } handleProcessingTime(System.currentTimeMillis() - startTime, documentId); } catch (AnalysisException e) { mos.close(); throw new RuntimeException(e); } }
Source:
public void testGetStrippedVdsUniqueIdWithoutValidChars() { RegisterVdsParameters paramsMock = getQueryParameters(); when(paramsMock.getVdsUniqueId()).thenReturn("^%^"); String result = getQuery().getStrippedVdsUniqueId(); assertEquals("", result); }

Target:
public void testGetStrippedVdsUniqueIdWithoutValidChars() { RegisterVdsParameters paramsMock = getQueryParameters(); when(paramsMock.getVdsUniqueId()).thenReturn("^%^"); String result = getQuery().getStrippedVdsUniqueId(); assertEquals("Vds id is not empty as expected", result, ""); }
Source:
public JSONObject printBoxBarcodes(HttpSession session, JSONObject json) { return ControllerHelperServiceUtils.printBarcodes(securityManager, printManager, json, new BarcodePrintAssister<Box>() { @Override public Box fetch(long id) throws IOException { return requestManager.getBoxById(id); } @Override public void store(Box item, User user) throws IOException { item.setLastModifier(user); requestManager.saveBox(item); } @Override public String groupName() { return "boxes"; } @Override public String idName() { return "boxId"; } @Override public Iterable<Box> fetchAll(long projectId) throws IOException { return Collections.emptySet(); } }); }

Target:
public JSONObject printBoxBarcodes(HttpSession session, JSONObject json) { return ControllerHelperServiceUtils.printBarcodes(printerService, json, new BarcodePrintAssister<Box>() { @Override public Box fetch(long id) throws IOException { return requestManager.getBoxById(id); } @Override public void store(Box item) throws IOException { requestManager.saveBox(item); } @Override public String getGroupName() { return "boxes"; } @Override public String getIdName() { return "boxId"; } @Override public Iterable<Box> fetchAll(long projectId) throws IOException { throw new UnsupportedOperationException(); } }); }
Source:
private void evict() { int evictionIndex = heads.getEvictionIndex(); if (evictionIndex < 0) { StringBuilder sb = new StringBuilder("Storage Engine and Eviction Failed - Everything Pinned (" + getSize() + " mappings) \n"); sb.append("Storage Engine : ").append(chainStorage); throw new OversizeMappingException(sb.toString()); } else { heads.evict(evictionIndex, false); } }

Target:
private void evict() { int evictionIndex = heads.getEvictionIndex(); if (evictionIndex < 0) { StringBuilder sb = new StringBuilder("Storage Engine and Eviction Failed - Everything Pinned ("); sb.append(getSize()).append(" mappings) \n").append("Storage Engine : ").append(chainStorage); throw new OversizeMappingException(sb.toString()); } else { heads.evict(evictionIndex, false); } }
Source:
public HiveOrcAggregatedMemoryContext() { this.delegate = newSimpleAggregatedMemoryContext(); }

Target:
public HiveOrcAggregatedMemoryContext() { this(newSimpleAggregatedMemoryContext()); }
Source:
public static void withCategories(final BlockingSphereClient client, final List<Supplier<? extends CategoryDraft>> creator, final Consumer<List<Category>> user) { List<Category> categories = creator.stream().map(singleCreator -> { final CategoryDraft categoryDraft = singleCreator.get(); final String slug = englishSlugOf(categoryDraft); final PagedQueryResult<Category> pagedQueryResult = client.executeBlocking(CategoryQuery.of().bySlug(Locale.ENGLISH, slug)); pagedQueryResult.head().ifPresent( category -> client.executeBlocking(CategoryDeleteCommand.of(category)) ); final Category category = client.executeBlocking(CategoryCreateCommand.of(categoryDraft)); LOGGER.debug(() -> "created category " + category.getSlug() + " id: " + category.getId()); return category; }).collect(Collectors.toList()); try { user.accept(categories); } finally { categories.forEach(category -> { final PagedQueryResult<Category> res = client.executeBlocking(CategoryQuery.of().byId(category.getId())); client.executeBlocking(CategoryDeleteCommand.of(res.head().get())); LOGGER.debug(() -> "deleted category " + category.getId()); }); } }

Target:
public static void withCategories(final BlockingSphereClient client, final List<Supplier<? extends CategoryDraft>> creator, final Consumer<List<Category>> user) { List<Category> categories = creator.stream().map(singleCreator -> { final CategoryDraft categoryDraft = singleCreator.get(); final String slug = englishSlugOf(categoryDraft); final PagedQueryResult<Category> pagedQueryResult = client.executeBlocking(CategoryQuery.of().bySlug(Locale.ENGLISH, slug)); pagedQueryResult.head().ifPresent( category -> client.executeBlocking(CategoryDeleteCommand.of(category)) ); final Category category = client.executeBlocking(CategoryCreateCommand.of(categoryDraft)); return category; }).collect(Collectors.toList()); try { user.accept(categories); } finally { categories.forEach(category -> { client.executeBlocking(CategoryDeleteCommand.of(category)); }); } }
Source:
public Object[] getChildren(Object parent) { ArrayList<UMLRTProtocolMessage> protocolMsgs = new ArrayList<>(); EList<UMLRTProtocol> allProtocols = new UniqueEList<>(); for (UMLRTProtocol protocol : protocols) { allProtocols.addAll(ProtocolUtils.getAllProtocols(protocol)); } for (UMLRTProtocol protocol : allProtocols) { if (ProtocolUtils.isCommonProtocol(protocols, protocol)) { addProtocolMsgs(protocolMsgs, protocol); } } return protocolMsgs.stream() .sorted(UMLRTInheritanceKind.facadeComparator()) .map(new Function<UMLRTProtocolMessage, Event>() { @Override public Event apply(UMLRTProtocolMessage msg) { return msg.toReceiveEvent(); } }) .toArray(); }

Target:
public Object[] getChildren(Object parent) { ArrayList<UMLRTProtocolMessage> protocolMsgs = new ArrayList<>(); EList<UMLRTProtocol> allProtocols = new UniqueEList<>(); for (UMLRTProtocol protocol : protocols) { allProtocols.addAll(ProtocolUtils.getAllProtocols(protocol)); } for (UMLRTProtocol protocol : allProtocols) { if (ProtocolUtils.isCommonProtocol(protocols, protocol)) { addProtocolMsgs(protocolMsgs, protocol); } } return protocolMsgs.stream() .sorted(UMLRTInheritanceKind.facadeComparator()) .map(UMLRTProtocolMessage::toReceiveEvent) .toArray(); }
Source:
public String getName() { return "Lambda vars"; }

Target:
public String getName() { return "Lambda"; }
Source:
public CoapEndpoint(Connector connector, NetworkConfig config) { this.config = config; this.connector = connector; if (connector.isTcp()) { this.matcher = new TcpMatcher(config); this.coapstack = new CoapTcpStack(config, new OutboxImpl()); this.serializer = new Serializer(new TcpDataSerializer()); this.parser = new TcpDataParser(); } else { this.matcher = new TcpMatcher(config); this.coapstack = new CoapUdpStack(config, new OutboxImpl()); this.serializer = new Serializer(new UdpDataSerializer()); this.parser = new UdpDataParser(); } this.connector.setRawDataReceiver(new InboxImpl()); }

Target:
public CoapEndpoint(Connector connector, NetworkConfig config) { this.config = config; this.connector = connector; if (connector.isTcp()) { this.matcher = new TcpMatcher(config); this.coapstack = new CoapTcpStack(config, new OutboxImpl()); this.serializer = new Serializer(new TcpDataSerializer()); this.parser = new TcpDataParser(); } else { this.matcher = new UdpMatcher(config); this.coapstack = new CoapUdpStack(config, new OutboxImpl()); this.serializer = new Serializer(new UdpDataSerializer()); this.parser = new UdpDataParser(); } this.connector.setRawDataReceiver(new InboxImpl()); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bot); RecyclerView directions = Views.findById(this, R.id.bot_directions); directions.setHasFixedSize(true); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); directions.setLayoutManager(layoutManager); RecyclerView.Adapter adapter = new DirectionAdapter(LayoutInflater.from(this), Collections.<Direction>emptyList()); directions.setAdapter(adapter); ControllerView controllerView = Views.findById(this, R.id.bot_debug_controls); controllerView.setControllerListener(controllerListener); handler = new Handler(); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bot); RecyclerView directions = Views.findById(this, R.id.bot_directions); directions.setHasFixedSize(true); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); directions.setLayoutManager(layoutManager); RecyclerView.Adapter adapter = new DirectionAdapter(LayoutInflater.from(this), Collections.<Direction>emptyList()); directions.setAdapter(adapter); ControllerView controllerView = Views.findById(this, R.id.bot_debug_controls); controllerView.setControllerListener(controllerListener); Handler handler = new Handler(); commandRepeater = new CommandRepeater(commandRepeatedListener, handler); }
Source:
public String getEditorTitle() { try { return String.format("Table Report - Merge View"); } catch (Exception ex) { } return "Table Report - Merge View"; }

Target:
public String getEditorTitle() { try { Branch branch = BranchManager.getBranch(sourceBranch); return String.format("Table Report - Merge View [%s]", branch.toStringWithId()); } catch (Exception ex) { } return "Table Report - Merge View"; }
Source:
private void initMigrationMode() { ArrayList<EntityModel> migrationModes = new ArrayList<EntityModel>(); Constants constants = ConstantsManager.getInstance().getConstants(); migrationModes.add(new EntityModel(constants.autoAndManMigration(), MigrationSupport.MIGRATABLE)); migrationModes.add(new EntityModel(constants.manualMigrationOnly(), MigrationSupport.IMPLICITLY_NON_MIGRATABLE)); migrationModes.add(new EntityModel(constants.noMigration(), MigrationSupport.PINNED_TO_HOST)); getMigrationMode().setItems(migrationModes); getDisplayProtocol().getSelectedItemChangedEvent().addListener(this); }

Target:
private void initMigrationMode() { ArrayList<EntityModel> migrationModes = new ArrayList<EntityModel>(); Constants constants = ConstantsManager.getInstance().getConstants(); MIGRATABLE_ENTITY.setTitle(constants.autoAndManMigration()); IMPLICITLY_NON_MIGRATABLE_ENTITY.setTitle(constants.manualMigrationOnly()); PINNED_TO_HOST_ENTITY.setTitle(constants.noMigration()); migrationModes.add(MIGRATABLE_ENTITY); migrationModes.add(IMPLICITLY_NON_MIGRATABLE_ENTITY); migrationModes.add(PINNED_TO_HOST_ENTITY); getMigrationMode().setItems(migrationModes); }
Source:
public void setup() throws Exception { System.out.println("Executing setup"); StateStoreProperties.get().setProperty(FalconJPAService.URL, url); Configuration localConf = new Configuration(); fs.initialize(LocalFileSystem.getDefaultUri(localConf), localConf); fs.mkdirs(new Path(DB_BASE_DIR)); createDB(DB_SQL_FILE); falconJPAService.init(); this.dfsCluster = EmbeddedCluster.newCluster("testCluster"); this.conf = dfsCluster.getConf(); }

Target:
public void setup() throws Exception{ StateStoreProperties.get().setProperty(FalconJPAService.URL, url); Configuration localConf = new Configuration(); fs.initialize(LocalFileSystem.getDefaultUri(localConf), localConf); fs.mkdirs(new Path(DB_BASE_DIR)); createDB(DB_SQL_FILE); falconJPAService.init(); this.dfsCluster = EmbeddedCluster.newCluster("testCluster"); this.conf = dfsCluster.getConf(); }
Source:
public void onInitialize() { SkeletalMeshComponent skeletalMesh = actor().skeletalMesh(); if (getNode().play != null) { List<?> animationListToPlay = (List<?>) actor().getComponentField(getNode().play); if (animationListToPlay != null) { skeletalMesh.animation = (MeshAnimation) animationListToPlay.get( random.nextInt(animationListToPlay.size())); } else { skeletalMesh.animation = null; } } if (getNode().loop != null) { skeletalMesh.animationPool.clear(); List<?> animationListToLoop = (List<?>) actor().getComponentField(getNode().loop); if (animationListToLoop != null) { skeletalMesh.animationPool.addAll(animationListToLoop.stream().map(object -> (MeshAnimation) object).collect(Collectors.toList())); } } skeletalMesh.loop = true; actor().save(skeletalMesh); }

Target:
public void onInitialize() { SkeletalMeshComponent skeletalMesh = actor().skeletalMesh(); if (getNode().play != null) { List<?> animationListToPlay = (List<?>) actor().getComponentField(getNode().play); if (animationListToPlay != null) { skeletalMesh.animation = (MeshAnimation) animationListToPlay.get( random.nextInt(animationListToPlay.size())); } else { skeletalMesh.animation = null; } } if (getNode().loop != null) { skeletalMesh.animationPool.clear(); List<?> animationListToLoop = (List<?>) actor().getComponentField(getNode().loop); if (animationListToLoop != null) { for (Object object : animationListToLoop) { skeletalMesh.animationPool.add((MeshAnimation) object); } } } skeletalMesh.loop = true; actor().save(skeletalMesh); }
Source:
protected Control createContents(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(composite); Label infoImage = new Label(composite, SWT.NONE); infoImage.setImage(CommonImages.getImage(CommonImages.INFORMATION)); Link bugLink = new Link(composite, SWT.NONE); bugLink.setText(Messages.BreakpointsPreferencePage_bug_link); bugLink.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { TasksUiUtil.openTask("<LINK_0>"); } }); manageBreakpointsButton = new Button(composite, SWT.CHECK); manageBreakpointsButton.setText(Messages.BreakpointsPreferencePage_Manage_breakpoints); manageBreakpointsButton.setSelection(getPreferenceStore().getBoolean( BreakpointsContextContributor.AUTO_MANAGE_BREAKPOINTS)); GridDataFactory.fillDefaults().span(2, 1).applyTo(manageBreakpointsButton); Group warningGroup = new Group(composite, SWT.SHADOW_ETCHED_IN); warningGroup.setLayout(new GridLayout(1, false)); warningGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); warningGroup.setText(Messages.BreakpointsPreferencePage_Known_Issues); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(warningGroup); GridDataFactory.fillDefaults().span(2, 1).applyTo(warningGroup); createWarning(warningGroup, Messages.Breakpoints_closed_projects_warning); createWarning(warningGroup, Messages.Breakpoints_locations_warning); createWarning(warningGroup, Messages.BreakpointsPreferencePage_unchecking_will_remove); return composite; }

Target:
protected Control createContents(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(composite); Label infoImage = new Label(composite, SWT.NONE); infoImage.setImage(CommonImages.getImage(CommonImages.INFORMATION)); Link bugLink = new Link(composite, SWT.NONE); bugLink.setText(Messages.BreakpointsPreferencePage_bug_link); bugLink.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { BrowserUtil.openUrl("<LINK_0>"); } }); manageBreakpointsButton = new Button(composite, SWT.CHECK); manageBreakpointsButton.setText(Messages.BreakpointsPreferencePage_Manage_breakpoints); manageBreakpointsButton.setSelection(getPreferenceStore().getBoolean( BreakpointsContextContributor.AUTO_MANAGE_BREAKPOINTS)); GridDataFactory.fillDefaults().span(2, 1).applyTo(manageBreakpointsButton); Group warningGroup = new Group(composite, SWT.SHADOW_ETCHED_IN); warningGroup.setLayout(new GridLayout(1, false)); warningGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); warningGroup.setText(Messages.BreakpointsPreferencePage_Known_Issues); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(warningGroup); GridDataFactory.fillDefaults().span(2, 1).applyTo(warningGroup); createWarning(warningGroup, Messages.Breakpoints_closed_projects_warning); createWarning(warningGroup, Messages.Breakpoints_locations_warning); createWarning(warningGroup, Messages.BreakpointsPreferencePage_unchecking_will_remove); return composite; }
Source:
public ResponseHandler write(ResponseCallback callback, boolean startTimeout) throws ConnectionException, BusyConnectionException { ResponseHandler handler = new ResponseHandler(this, callback); dispatcher.add(handler); Message.Request request = callback.request().copy(); request.setStreamId(handler.streamId); if (isDefunct.get()) { dispatcher.removeHandler(handler, true); throw new ConnectionException(address, "Write attempt on defunct connection"); } if (isClosed()) { dispatcher.removeHandler(handler, true); throw new ConnectionException(address, "Connection has been closed"); } logger.trace("{}, stream {}, writing request {}", this, request.getStreamId(), request); writer.incrementAndGet(); if (DISABLE_COALESCING) { channel.writeAndFlush(request).addListener(writeHandler(request, handler)); } else { flush(new FlushItem(channel, request, writeHandler(request, handler))); } if (startTimeout) handler.startTimeout(); return handler; }

Target:
public ResponseHandler write(ResponseCallback callback, boolean startTimeout) throws ConnectionException, BusyConnectionException { ResponseHandler handler = new ResponseHandler(this, callback); dispatcher.add(handler); Message.Request request = callback.request().setStreamId(handler.streamId); if (isDefunct.get()) { dispatcher.removeHandler(handler, true); throw new ConnectionException(address, "Write attempt on defunct connection"); } if (isClosed()) { dispatcher.removeHandler(handler, true); throw new ConnectionException(address, "Connection has been closed"); } logger.trace("{}, stream {}, writing request {}", this, request.getStreamId(), request); writer.incrementAndGet(); if (DISABLE_COALESCING) { channel.writeAndFlush(request).addListener(writeHandler(request, handler)); } else { flush(new FlushItem(channel, request, writeHandler(request, handler))); } if (startTimeout) handler.startTimeout(); return handler; }
Source:
public static TableDataManager getTableDataManager(@Nonnull TableDataManagerConfig tableDataManagerConfig, @Nonnull String instanceId, @Nonnull ZkHelixPropertyStore<ZNRecord> propertyStore, @Nonnull ServerMetrics serverMetrics, @Nonnull HelixManager helixManager) { TableDataManager tableDataManager; switch (TableType.valueOf(tableDataManagerConfig.getTableDataManagerType())) { case OFFLINE: if (tableDataManagerConfig.isDimTable()) { tableDataManager = DimensionTableDataManager.createInstanceByTableName(tableDataManagerConfig.getTableName()); break; } tableDataManager = new OfflineTableDataManager(); break; case REALTIME: tableDataManager = new RealtimeTableDataManager(_segmentBuildSemaphore); break; default: throw new IllegalStateException(); } tableDataManager.init(tableDataManagerConfig, instanceId, propertyStore, serverMetrics, helixManager); return tableDataManager; }

Target:
public static TableDataManager getTableDataManager(@Nonnull TableDataManagerConfig tableDataManagerConfig, @Nonnull String instanceId, @Nonnull ZkHelixPropertyStore<ZNRecord> propertyStore, @Nonnull ServerMetrics serverMetrics, @Nonnull HelixManager helixManager) { TableDataManager tableDataManager; switch (TableType.valueOf(tableDataManagerConfig.getTableDataManagerType())) { case OFFLINE: if (tableDataManagerConfig.isDimTable()) { tableDataManager = DimensionTableDataManager.createInstanceByTableName(tableDataManagerConfig.getTableName()); } else { tableDataManager = new OfflineTableDataManager(); } break; case REALTIME: tableDataManager = new RealtimeTableDataManager(_segmentBuildSemaphore); break; default: throw new IllegalStateException(); } tableDataManager.init(tableDataManagerConfig, instanceId, propertyStore, serverMetrics, helixManager); return tableDataManager; }
Source:
public static Response<AssetReportGetResponse> waitTillReady(PlaidClient client, String assetReportToken) throws Exception { Response<AssetReportGetResponse> response; do { AssetReportGetRequest assetReportGet = new AssetReportGetRequest(assetReportToken); response = client.service().assetReportGet(assetReportGet).execute(); } while ( !response.isSuccessful() && response.errorBody() != null && client.parseError(response).getErrorCode().equals("PRODUCT_NOT_READY") ); return response; }

Target:
public static Response<AssetReportGetResponse> waitTillReady( PlaidClient client, String assetReportToken) throws Exception { int NUM_RETRIES = 20; int INTER_REQUEST_SLEEP = 1000; int attempt = 0; Response<AssetReportGetResponse> response; do { AssetReportGetRequest assetReportGet = new AssetReportGetRequest(assetReportToken); response = client.service().assetReportGet(assetReportGet).execute(); attempt++; Thread.sleep(INTER_REQUEST_SLEEP); } while ( !response.isSuccessful() && response.errorBody() != null && client.parseError(response).getErrorCode().equals(PRODUCT_NOT_READY) && attempt < NUM_RETRIES ); if (!response.isSuccessful()) { throw new Exception( String.format("Could not get asset report. Failed with %s", client.parseError(response).getErrorMessage() )); } return response; }
Source:
public RuleResult validate(final PasswordData passwordData) { final RuleResult result = new RuleResult(true); passwordRules.stream().map((rule) -> rule.validate(passwordData)).filter((rr) -> !rr.isValid()).forEach((rr) -> { result.setValid(false); result.getDetails().addAll(rr.getDetails()); }); return result; }

Target:
public RuleResult validate(final PasswordData passwordData) { final RuleResult result = new RuleResult(true); for (Rule rule : passwordRules) { final RuleResult rr = rule.validate(passwordData); if (!rr.isValid()) { result.setValid(false); result.getDetails().addAll(rr.getDetails()); } } return result; }
Source:
private void processSuccess(LockWatchStateUpdate.Success success) { Preconditions.checkState(latestVersion.isPresent(), "Must have a known version to process successful updates"); Optional<LockWatchVersion> snapshotVersion = snapshot.getSnapshotVersion(); Preconditions.checkState(snapshotVersion.isPresent(), "Must have a snapshot before processing successful updates"); if (success.lastKnownVersion() < snapshotVersion.get().version()) { throw new TransactionLockWatchFailedException( "Cannot process events before the oldest event. The transaction should be retried, although this" + " should only happen very rarely."); } if (success.lastKnownVersion() > latestVersion.get().version()) { assertNoEventsAreMissing(success.events()); latestVersion = Optional.of(LockWatchVersion.of(success.logId(), eventStore.putAll(success.events()))); } }

Target:
private void processSuccess(LockWatchStateUpdate.Success success) { Preconditions.checkState(latestVersion.isPresent(), "Must have a known version to process successful updates"); Optional<LockWatchVersion> snapshotVersion = snapshot.getSnapshotVersion(); Preconditions.checkState(snapshotVersion.isPresent(), "Must have a snapshot before processing successful updates"); if (success.lastKnownVersion() < snapshotVersion.get().version()) { throw new TransactionLockWatchFailedException( "Cannot process events before the oldest event. The transaction should be retried, although this" + " should only happen very rarely."); } if (success.lastKnownVersion() > latestVersion.get().version()) { LockWatchEvents events = new LockWatchEvents.Builder() .addAllEvents(success.events()) .build(); assertNoEventsAreMissing(events); latestVersion = Optional.of(LockWatchVersion.of(success.logId(), eventStore.putAll(events))); } }
Source:
public static Slice stGeometryType(@SqlType(GEOMETRY_TYPE_NAME) Slice input) { GeometryType geometryType = deserializeType(input); String type; switch (geometryType) { case POINT: type = "ST_Point"; break; case MULTI_POINT: type = "ST_MultiPoint"; break; case LINE_STRING: type = "ST_LineString"; break; case MULTI_LINE_STRING: type = "ST_MultiLineString"; break; case POLYGON: type = "ST_Polygon"; break; case MULTI_POLYGON: type = "ST_MultiPolygon"; break; case GEOMETRY_COLLECTION: type = "ST_GeomCollection"; break; default: throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Unexpected geometry type: " + geometryType); } return utf8Slice(type); }

Target:
public static Slice stGeometryType(@SqlType(GEOMETRY_TYPE_NAME) Slice input) { return GeometrySerde.getGeometryType(input).standardName(); }
Source:
public static boolean isDebugSessionAlive(IServer server) { Collection<DebugSessionTracker> trackers = getTrackers(); if (!trackers.isEmpty()) { return trackers.stream().findFirst().get().isDebugSessionAlive(server); } return false; }

Target:
public static boolean isDebugSessionAlive(IServer server) { Collection<DebugSessionTracker> trackers = getTrackers(); if (trackers.isEmpty()) { return false; } for (DebugSessionTracker tracker : trackers) { if (!tracker.isDebugSessionAlive(server)) { return false; } } return true; }
Source:
public static Set<String> getPrefTags(SharedPreferences prefs, Context context) { Set<String> tags = getPrefTags(prefs); if (tags.isEmpty()) { TagsHandler tagsHandler = KissApplication.getApplication(context).getDataHandler().getTagsHandler(); Set<String> list = tagsHandler.getAllTagsAsSet(); for (String tag : list) { tags.add(tag); if (tags.size() >= 5) break; } } return tags; }

Target:
public static Set<String> getPrefTags(SharedPreferences prefs, Context context) { Set<String> prefTags = getPrefTags(prefs); if (prefTags == null || prefTags.isEmpty()) { Set<String> tags = new HashSet<>(5); TagsHandler tagsHandler = KissApplication.getApplication(context).getDataHandler().getTagsHandler(); Set<String> list = tagsHandler.getAllTagsAsSet(); for (String tag : list) { tags.add(tag); if (tags.size() >= 5) break; } return tags; } return prefTags; }
Source:
public static void writeObjectToConfAsBase64(String key, Object obj, Configuration conf) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(obj); oos.close(); conf.set(key, new String(Base64.encodeBase64(baos.toByteArray()), "UTF-8")); }

Target:
public static void writeObjectToConfAsBase64(String key, Object obj, Configuration conf) throws IOException { ByteArrayOutputStream baos = null; GZIPOutputStream gos = null; ObjectOutputStream oos = null; try { baos = new ByteArrayOutputStream(); gos = new GZIPOutputStream(baos); oos = new ObjectOutputStream(gos); oos.writeObject(obj); } finally { Closeables.close(oos); Closeables.close(gos); Closeables.close(baos); } conf.set(key, new String(Base64.encodeBase64(baos.toByteArray()), "UTF-8")); }
Source:
public void shouldProperlyHandleEqualNames() throws Exception { final MockFolder folder = rule.createFolder("FOO"); final FreeStyleProject prj = folder.createProject(FreeStyleProject.class, "FOO"); assertsPath("/FOO/FOO", null, prj); assertsPath("FOO/FOO", null, prj); assertsPath("./FOO", folder, prj); assertsPath(".", folder, folder); assertsPath("../FOO", folder, folder); assertsPath("../FOO/FOO", folder, prj); assertsPath("./FOO", prj, prj); assertsPath(".", prj, folder); assertsPath("../FOO", prj, folder); assertsPath("../FOO/FOO", prj, prj); }

Target:
public void shouldProperlyHandleEqualNames() throws Exception { final MockFolder folder = rule.createFolder("FOO"); final FreeStyleProject prj = folder.createProject(FreeStyleProject.class, "FOO"); assertsPath("/FOO/FOO", null, prj); assertsPath("FOO/FOO", null, prj); assertsPath("FOO", folder, prj); assertsPath("./FOO", folder, prj); assertsPath(".", folder, folder); assertsPath("../FOO", folder, folder); assertsPath("../FOO/FOO", folder, prj); assertsPath("FOO", prj, prj); assertsPath("./FOO", prj, prj); assertsPath(".", prj, folder); assertsPath("../FOO", prj, folder); assertsPath("../FOO/FOO", prj, prj); }
Source:
public int fill(FluidStack resource, boolean doFill) { int k = 0; for (IFluidHandler handler : subHandlers) { k += handler.fill(resource, doFill); } return k; }

Target:
public int fill(FluidStack resource, boolean doFill) { if (resource == null || resource.amount <= 0) return 0; resource = resource.copy(); int totalFillAmount = 0; for (IFluidHandler handler : subHandlers) { int fillAmount = handler.fill(resource, doFill); totalFillAmount += fillAmount; resource.amount -= fillAmount; if (resource.amount <= 0) break; } return totalFillAmount; }
Source:
public String getHelpDoc() { return picard.analysis.CollectInsertSizeMetrics.USAGE_SUMMARY + "Creates output with \"" + String.join("\", \"", OUTPUT_EXTENSIONS) + "\" appended to OUTPUT."; }

Target:
public String getHelpDoc() { return getSummary() + "Creates output with \"" + String.join(", ",getExtensions()) + "\" appended to OUTPUT."; }
Source:
private boolean selectDefaultSubpicLanguage() { String defaultAudioLang = uiMgr.get("default_audio_language", "English"); MediaLangInfo mli = (MediaLangInfo) mediaLangMap.get(defaultAudioLang); SubpictureFormat subs = this.currFile.getFileFormat().getSubpictureFormats(); for(int i = 0; i < subs.length; i++) { if(subs[i].getForced()) { if(subs[i].getLanguage().equalsIgnoreCase(mli.twoChar)) { System.out.println("Setting forced subtitle to index: " + i); playbackControl(DVD_CONTROL_SUBTITLE_CHANGE, i, -1); return true; } for(int j = 0; j < mli.threeChar.length; j++) { if(subs[i].getLanguage().equalsIgnoreCase(mli.threeChar[j])) { System.out.println("Setting forced subtitle to index: " + i); playbackControl(DVD_CONTROL_SUBTITLE_CHANGE, i, -1); return true; } } } } String defaultLang = uiMgr.get("default_subpic_language", ""); if (defaultLang == null || defaultLang.length() == 0) return true; return performLanguageMatch(defaultLang, getDVDAvailableSubpictures(), DVD_CONTROL_SUBTITLE_CHANGE, getDVDSubpicture()); }

Target:
private boolean selectDefaultSubpicLanguage() { String defaultAudioLang = uiMgr.get("default_audio_language", "English"); String defaultLang = uiMgr.get("default_subpic_language", ""); if(defaultLang == null || defaultLang.length() == 0) { String subs = getDVDAvailableSubpictures(); String forcedSubs = new String[subs.length]; boolean hasForcedSub = false; for(int i = 0; i < subs.length; i++) { if(subs[i].toLowerCase().indexOf("[" + Sage.rez("forced") + "]") != -1) { forcedSubs[i] = subs[i]; hasForcedSub = true; } else { forcedSubs[i] = ""; } } if(hasForcedSub) { return performLanguageMatch(defaultAudioLang, forcedSubs, DVD_CONTROL_SUBTITLE_CHANGE, getDVDSubpicture()); } else { return true; } } return performLanguageMatch(defaultLang, getDVDAvailableSubpictures(), DVD_CONTROL_SUBTITLE_CHANGE, getDVDSubpicture()); }
Source:
public Response<Void> stageBlockWithResponse(String base64BlockId, InputStream data, long length, byte[] contentMd5, String leaseId, Duration timeout, Context context) { Objects.requireNonNull(data); data.mark(Integer.MAX_VALUE); Flux<ByteBuffer> fbb = Utility.convertStreamToByteBuffer(data, length, BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE); Mono<Response<Void>> response = client.stageBlockWithResponse(base64BlockId, fbb.subscribeOn(Schedulers.elastic()), length, contentMd5, leaseId, context); return blockWithOptionalTimeout(response, timeout); }

Target:
public Response<Void> stageBlockWithResponse(String base64BlockId, InputStream data, long length, byte[] contentMd5, String leaseId, Duration timeout, Context context) { Objects.requireNonNull(data); Flux<ByteBuffer> fbb = Utility.convertStreamToByteBuffer(data, length, BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE); Mono<Response<Void>> response = client.stageBlockWithResponse(base64BlockId, fbb.subscribeOn(Schedulers.elastic()), length, contentMd5, leaseId, context); return blockWithOptionalTimeout(response, timeout); }
Source:
synchronized void submit(long offset, BigInteger v) { if (!validateOffset((int) offset) || v == null || chceckpoints[(int) offset] != null) { return; } if (s == -1L && offset >= 0) { lag[idx(offset)] = c = s = offset; } if (offset > s) { s = offset; } chceckpoints[(int) offset] = v; }

Target:
synchronized void submit(long offset, BigInteger v) { if (!validateOffset((int) offset) || v == null || chceckpoints[(int) offset] != null) { return; } if (s == -1L && offset >= 0) { lag[idx(offset)] = c = s = offset; } if ((offset - c) >= lag.length) { offer = offset; try { wait(gapTrackerCheckMaxTimeMs); } catch (InterruptedException e) { rateLimitedLog(Level.WARN, e, "Gap tracker wait was interrupted." + m_config.getResourceID().toString()); } } if (offset > s) { s = offset; } chceckpoints[(int) offset] = v; }
Source:
Optional<A> load(I id) { final AggregateReadRequest<I> request = new AggregateReadRequest<>(id, snapshotTrigger); final Optional<AggregateStateRecord> eventsFromStorage = aggregateStorage().read(request); if (eventsFromStorage.isPresent()) { final A result = create(id); final AggregateStateRecord aggregateStateRecord = eventsFromStorage.get(); final AggregateTransaction tx = AggregateTransaction.start(result); result.play(aggregateStateRecord); tx.commit(); return Optional.of(result); } return Optional.absent(); }

Target:
private Optional<A> load(I id) { final Optional<AggregateStateRecord> eventsFromStorage = fetchHistory(id); if (eventsFromStorage.isPresent()) { final A result = play(id, eventsFromStorage.get()); return Optional.of(result); } return Optional.absent(); }
Source:
private Drawable getPlaceholderDrawable() { if (placeholderResId != 0) { if (Build.VERSION.SDK_INT >= 21) { return picasso.context.getDrawable(placeholderResId); } else if (Build.VERSION.SDK_INT >= 16) { return picasso.context.getResources().getDrawable(placeholderResId); } else { final int resolvedId; TypedValue sTempValue = new TypedValue(); picasso.context.getResources().getValue(placeholderResId, sTempValue, true); resolvedId = sTempValue.resourceId; return picasso.context.getResources().getDrawable(resolvedId); } } else { return placeholderDrawable; } }

Target:
private Drawable getPlaceholderDrawable() { if (placeholderResId != 0) { if (Build.VERSION.SDK_INT >= 21) { return picasso.context.getDrawable(placeholderResId); } else if (Build.VERSION.SDK_INT >= 16) { return picasso.context.getResources().getDrawable(placeholderResId); } else { TypedValue value = new TypedValue(); picasso.context.getResources().getValue(placeholderResId, value, true); return picasso.context.getResources().getDrawable(value.resourceId); } } else { return placeholderDrawable; } }
Source:
public CommonPathCapabilities() { }

Target:
private CommonPathCapabilities() { }
Source:
public FakeHttpServletRequest( Map<String, String> parameterMap, Cookie[] cookies, String workspace) { this.parameterMap = parameterMap; this.cookies = cookies; this.workspace = workspace; this.original = Optional.ofNullable( (ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) .map(atts -> atts.getRequest()); }

Target:
public FakeHttpServletRequest( Map<String, String> parameterMap, Cookie[] cookies, String workspace) { this.parameterMap = parameterMap; this.cookies = cookies; this.workspace = workspace; this.original = Optional.ofNullable( (ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) .map(ServletRequestAttributes::getRequest); }
Source:
public static int randomAvailablePort() { int port; try { ServerSocket socket = new ServerSocket(0); port = socket.getLocalPort(); socket.close(); } catch (IOException e) { throw new RuntimeException(e); } return port; }

Target:
public static int randomAvailablePort() { try { ServerSocket socket = new ServerSocket(0); int port = socket.getLocalPort(); socket.close(); return port; } catch (IOException e) { throw new RuntimeException(e); } }
Source:
public <V, K extends Exception> V runWithRetryOnHost( InetSocketAddress specifiedHost, FunctionCheckedException<Cassandra.Client, V, K> fn) throws K { int numTries = 0; boolean shouldRetryOnDifferentHost = false; Set<InetSocketAddress> triedHosts = Sets.newHashSet(); while (true) { if (log.isTraceEnabled()) { log.trace("Running function on host {}.", specifiedHost.getHostString()); } CassandraClientPoolingContainer hostPool = currentPools.get(specifiedHost); if (blacklistedHosts.containsKey(specifiedHost) || hostPool == null || shouldRetryOnDifferentHost) { log.warn("Randomly redirected a query intended for host {}.", specifiedHost); Optional<CassandraClientPoolingContainer> hostPoolCandidate = getRandomGoodHostForPredicate(address -> !triedHosts.contains(address)); hostPool = hostPoolCandidate.orElseGet(this::getRandomGoodHost); } try { return runWithPooledResourceRecordingMetrics(hostPool, fn); } catch (Exception e) { numTries++; triedHosts.add(hostPool.getHost()); this.<K>handleException(numTries, hostPool.getHost(), e); tracingPrefsConfig.run(); if (isRetriableWithBackoffException( tracingPrefsConfig.shouldRetryOnDifferentHostOnThriftTimedOutExceptions(), e)) { log.warn("Retrying with backoff a query intended for host {}.", hostPool.getHost(), e); try { Thread.sleep(numTries * 1000 + (ThreadLocalRandom.current().nextInt(1000) - 500)); } catch (InterruptedException i) { throw new RuntimeException(i); } if (numTries >= MAX_TRIES_SAME_HOST) { shouldRetryOnDifferentHost = true; } } } } }

Target:
public <V, K extends Exception> V runWithRetryOnHost( InetSocketAddress specifiedHost, FunctionCheckedException<Cassandra.Client, V, K> fn) throws K { int numTries = 0; boolean shouldRetryOnDifferentHost = false; Set<InetSocketAddress> triedHosts = Sets.newHashSet(); while (true) { if (log.isTraceEnabled()) { log.trace("Running function on host {}.", specifiedHost.getHostString()); } CassandraClientPoolingContainer hostPool = currentPools.get(specifiedHost); if (blacklistedHosts.containsKey(specifiedHost) || hostPool == null || shouldRetryOnDifferentHost) { log.warn("Randomly redirected a query intended for host {}.", specifiedHost); Optional<CassandraClientPoolingContainer> hostPoolCandidate = getRandomGoodHostForPredicate(address -> !triedHosts.contains(address)); hostPool = hostPoolCandidate.orElseGet(this::getRandomGoodHost); } try { return runWithPooledResourceRecordingMetrics(hostPool, fn); } catch (Exception e) { numTries++; triedHosts.add(hostPool.getHost()); this.<K>handleException(numTries, hostPool.getHost(), e); if (isRetriableWithBackoffException( tracingPrefsConfig.shouldRetryOnDifferentHostOnThriftTimedOutExceptions(), e)) { log.warn("Retrying with backoff a query intended for host {}.", hostPool.getHost(), e); try { Thread.sleep(numTries * 1000 + (ThreadLocalRandom.current().nextInt(1000) - 500)); } catch (InterruptedException i) { throw new RuntimeException(i); } if (numTries >= MAX_TRIES_SAME_HOST) { shouldRetryOnDifferentHost = true; } } } } }