auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>SuggestReviewers(AccountVisibility av, AccountInfo.Loader.Factory accountLoaderFactory, AccountControl.Factory accountControlFactory, AccountCache accountCache, GroupMembers.Factory groupMembersFactory, IdentifiedUser.GenericFactory identifiedUserFactory, Provider<CurrentUser> currentUser, Provider<ReviewDb> dbProvider, @GerritServerConfig Config cfg, GroupBackend groupBackend) { this.accountLoaderFactory = accountLoaderFactory; this.accountControlFactory = accountControlFactory; this.accountCache = accountCache; this.groupMembersFactory = groupMembersFactory; this.dbProvider = dbProvider; this.identifiedUserFactory = identifiedUserFactory; this.currentUser = currentUser; this.groupBackend = groupBackend; String suggest = cfg.getString("suggest", null, "accounts"); if ("OFF".equalsIgnoreCase(suggest) || <START> Boolean.FALSE.toString().equalsIgnoreCase(suggest)) <END> { this.suggestAccounts = false; } else { this.suggestAccounts = (av != AccountVisibility.NONE); } this.suggestFrom = cfg.getInt("suggest", null, "from", 0); this.maxAllowed = cfg.getInt("addreviewer", "maxAllowed", PostReviewers.DEFAULT_MAX_REVIEWERS); }</code><technical_language>"false". In tests this I prefer explicitly supply constant string vs. obtaining a constant in a odd way. Especially if other potential values (e.g. "OFF") is enum wraps of alternatives</technical_language>

Target:
SuggestReviewers(AccountVisibility av, AccountInfo.Loader.Factory accountLoaderFactory, AccountControl.Factory accountControlFactory, AccountCache accountCache, GroupMembers.Factory groupMembersFactory, IdentifiedUser.GenericFactory identifiedUserFactory, Provider<CurrentUser> currentUser, Provider<ReviewDb> dbProvider, @GerritServerConfig Config cfg, GroupBackend groupBackend) { this.accountLoaderFactory = accountLoaderFactory; this.accountControlFactory = accountControlFactory; this.accountCache = accountCache; this.groupMembersFactory = groupMembersFactory; this.dbProvider = dbProvider; this.identifiedUserFactory = identifiedUserFactory; this.currentUser = currentUser; this.groupBackend = groupBackend; String suggest = cfg.getString("suggest", null, "accounts"); if ("OFF".equalsIgnoreCase(suggest) || "false".equalsIgnoreCase(suggest)) { this.suggestAccounts = false; } else { this.suggestAccounts = (av != AccountVisibility.NONE); } this.suggestFrom = cfg.getInt("suggest", null, "from", 0); this.maxAllowed = cfg.getInt("addreviewer", "maxAllowed", PostReviewers.DEFAULT_MAX_REVIEWERS); }
Source:
<code>JMXReporter(@Nullable final String portsConfig) { this.mBeanServer = ManagementFactory.getPlatformMBeanServer(); this.registeredMetrics = new HashMap<>(); if (portsConfig != null) { <START> this.jmxServer = JMXServer.getInstance(portsConfig); <END> } else { this.jmxServer = null; } LOG.info("Configured JMXReporter with {port:{}}", portsConfig); }</code><technical_language>find some inform users JVM-wide server, (unexpectedly) running another port. In a similar vein, close jmxServer if re-using singleton</technical_language>

Target:
JMXReporter(@Nullable final String portsConfig) { this.mBeanServer = ManagementFactory.getPlatformMBeanServer(); this.registeredMetrics = new HashMap<>(); if (portsConfig != null) { LOG.warn("JMXReporter port config is deprecated. " + "Please use: instead!", JMXServerOptions.JMX_SERVER_PORT); JMXService.startInstance(portsConfig); } }
Source:
<code>public ToStringHelper string() { <START> ToStringHelper toString = super.string(); <END> if (privateNetworking != null) { toString.add("privateNetworking", privateNetworking); } if (backupsEnabled != null) { toString.add("backupsEnabled", backupsEnabled); } if (!sshKeyIds.isEmpty()) { toString.add("sshKeyIds", sshKeyIds); } return toString; }</code><technical_language>If call omitNullValues(), able add privateNetworking backupsEnabled check for null</technical_language>

Target:
public ToStringHelper string() { ToStringHelper toString = super.string().omitNullValues(); toString.add("privateNetworking", privateNetworking); toString.add("backupsEnabled", backupsEnabled); if (!sshKeyIds.isEmpty()) { toString.add("sshKeyIds", sshKeyIds); } return toString; }
Source:
<code>public CosmosTemplate(CosmosFactory cosmosFactory, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) { <START> Assert.notNull(cosmosFactory, "CosmosDbFactory must not be null!"); <END> Assert.notNull(mappingCosmosConverter, "MappingCosmosConverter must not be null!"); this.cosmosFactory = cosmosFactory; this.cosmosConfig = cosmosConfig; this.mappingCosmosConverter = mappingCosmosConverter; this.cosmosAsyncClient = cosmosFactory.getCosmosClient(); }</code><technical_language>Rename -> CosmosDbFactory CosmosFactory</technical_language>

Target:
public CosmosTemplate(CosmosFactory cosmosFactory, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) { Assert.notNull(cosmosFactory, "CosmosFactory must not be null!"); Assert.notNull(mappingCosmosConverter, "MappingCosmosConverter must not be null!"); this.mappingCosmosConverter = mappingCosmosConverter; this.cosmosAsyncClient = cosmosFactory.getCosmosAsyncClient(); this.databaseName = cosmosFactory.getDatabaseName(); this.responseDiagnosticsProcessor = cosmosConfig.getResponseDiagnosticsProcessor(); this.queryMetricsEnabled = cosmosConfig.isQueryMetricsEnabled(); }
Source:
<code><START> public static <T1, T2, R> Single<R> zip(Single<? extends T1> s1, Single<? extends T2> s2, final Func2<? super T1, ? super T2, ? extends R> zipFunction) { <END> return SingleOperatorZip.zip(new Single<?>[] {s1, s2}, new FuncN<R>() { @Override public R call(Object... args) { return zipFunction.call((T1) args[0], (T2) args[1]); } }); }</code><technical_language>nit: please add final back</technical_language>

Target:
public static final <T1, T2, R> Single<R> zip(Single<? extends T1> s1, Single<? extends T2> s2, final Func2<? super T1, ? super T2, ? extends R> zipFunction) { return SingleOperatorZip.zip(new Single<?>[] {s1, s2}, new FuncN<R>() { @Override public R call(Object... args) { return zipFunction.call((T1) args[0], (T2) args[1]); } }); }
Source:
<code>public boolean shouldExecuteOnProject(Project project) { <START> return fileSystem.hasFiles(fileSystem.predicates().hasLanguage(Python.KEY)); <END> }</code><technical_language>new code is equivalent one: FileQuery.onSource() transformed in a predicate file type</technical_language>

Target:
public boolean shouldExecuteOnProject(Project project) { FilePredicates p = fileSystem.predicates(); return fileSystem.hasFiles(p.and(p.hasType(InputFile.Type.MAIN), p.hasLanguage(Python.KEY))); }
Source:
<code>private void respondHello(String header, Socket s) throws IOException { try { Writer o = new OutputStreamWriter(s.getOutputStream(), "UTF-8"); if (header.startsWith("GET / ")) { o.write("HTTP/1.0 200 OK\n"); o.write("Content-Type: text/plain;charset=UTF-8\n"); o.write("\n"); o.write("Jenkins-Agent-Protocols: "); boolean first = true; for (AgentProtocol p : AgentProtocol.all()) { if (first) first = false; else o.write(","); o.write(p.getName()); } o.write("\n"); o.write("Jenkins-Version: " + Jenkins.VERSION + "\n"); o.write("Jenkins-Session: " + Jenkins.SESSION_HASH + "\n"); <START> o.write("Client: " + s.getInetAddress().getHostAddress() + "\n"); <END> o.flush(); s.shutdownOutput(); } else { o.write("HTTP/1.0 404 Not Found\n"); o.write("Content-Type: text/plain;charset=UTF-8\n"); o.write("\n"); o.write("Not Found\n"); o.flush(); s.shutdownOutput(); } InputStream i = s.getInputStream(); IOUtils.copy(i, new NullOutputStream()); s.shutdownInput(); } finally { s.close(); } }</code><technical_language>printing "Client" giving servers address. want print "Server"</technical_language>

Target:
private void respondHello(String header, Socket s) throws IOException { try { Writer o = new OutputStreamWriter(s.getOutputStream(), "UTF-8"); if (header.startsWith("GET / ")) { o.write("HTTP/1.0 200 OK\r\n"); o.write("Content-Type: text/plain;charset=UTF-8\r\n"); o.write("\r\n"); o.write("Jenkins-Agent-Protocols: "); boolean first = true; for (AgentProtocol p : AgentProtocol.all()) { if (first) first = false; else o.write(","); o.write(p.getName()); } o.write("\r\n"); o.write("Jenkins-Version: " + Jenkins.VERSION + "\r\n"); o.write("Jenkins-Session: " + Jenkins.SESSION_HASH + "\r\n"); o.write("Client: " + s.getInetAddress().getHostAddress() + "\r\n"); o.write("Server: " + s.getLocalAddress().getHostAddress() + "\r\n"); o.flush(); s.shutdownOutput(); } else { o.write("HTTP/1.0 404 Not Found\r\n"); o.write("Content-Type: text/plain;charset=UTF-8\r\n"); o.write("\r\n"); o.write("Not Found\r\n"); o.flush(); s.shutdownOutput(); } InputStream i = s.getInputStream(); IOUtils.copy(i, new NullOutputStream()); s.shutdownInput(); } finally { s.close(); } }
Source:
<code>protected String modifybasename(String suggestedname) { String name=suggestedname; for(String prefix : CUT_PREFIX) { if(suggestedname.toLowerCase().startsWith(prefix)) { if(suggestedname.length()>prefix.length()) { <START> name= suggestedname.substring(prefix.length()); <END> } } } for(String suffix : IRREG_NOUNS.keySet()) { if(name.toLowerCase().endsWith(suffix.toLowerCase())) { String firstpart=name.substring(0,name.length()-suffix.length()); return firstpart+IRREG_NOUNS.get(suffix); } } for(String varname : NO_JAVA_TYPES) { if(name.equalsIgnoreCase(varname)) { return FOR_LOOP_ELEMENT_IDENTIFIER; } } for(String suffix : IRREG_ENDINGS) { if(name.toLowerCase().endsWith(suffix)) { return FOR_LOOP_ELEMENT_IDENTIFIER; } } if(name.length()>2 && name.endsWith("s")) { return name.substring(0,name.length()-1); } return FOR_LOOP_ELEMENT_IDENTIFIER; }</code><technical_language>This is new functionality compared I reviewed before. check for allX X is upper-case character term "allowances" cut owances "all_references" cut _references. need lower-case letter. e.g. "allProblems" "problems" "problem" removing s</technical_language>

Target:
protected String modifybasename(String suggestedname) { String name=suggestedname; for(String prefix : CUT_PREFIX) { if(prefix.length()>=suggestedname.length()) { continue; } char afterprefix= suggestedname.charAt(prefix.length()); if(Character.isUpperCase(afterprefix)||afterprefix=='_') { if(suggestedname.toLowerCase().startsWith(prefix)) { String name_without_prefix= suggestedname.substring(prefix.length()); if(name_without_prefix.startsWith("_")&&name_without_prefix.length()>1) { name= name_without_prefix.substring(1); } else { name= name_without_prefix; } if(name.length()==1) { return name; } break; } } } for(String suffix : IRREG_NOUNS.keySet()) { if(name.toLowerCase().endsWith(suffix.toLowerCase())) { String firstpart=name.substring(0,name.length()-suffix.length()); return firstpart+IRREG_NOUNS.get(suffix); } } for(String varname : NO_JAVA_TYPES) { if(name.equalsIgnoreCase(varname)) { return FOR_LOOP_ELEMENT_IDENTIFIER; } } for(String suffix : IRREG_ENDINGS) { if(name.toLowerCase().endsWith(suffix)) { return FOR_LOOP_ELEMENT_IDENTIFIER; } } if(name.length()>2 && name.endsWith("s")) { return name.substring(0,name.length()-1); } return FOR_LOOP_ELEMENT_IDENTIFIER; }
Source:
<code>private Encounter checkVersionAndSetEncounter(Config config, String responseJson) { Encounter createdEncounter; <START> if ("1.9".equals(config.getOpenMrsVersion())) { <END> createdEncounter = buildGsonWithAdaptersDeserialize().fromJson(responseJson, Encounter.class); } else { createdEncounter = (Encounter) JsonUtils.readJson(responseJson, Encounter.class); } return createdEncounter; }</code><technical_language>constant here, OPENMRS_V1.9</technical_language>

Target:
private Encounter checkVersionAndSetEncounter(Config config, String responseJson) { Encounter createdEncounter; if (OPENMRS_V19.equals(config.getOpenMrsVersion())) { createdEncounter = buildGsonWithAdaptersDeserialize().fromJson(responseJson, Encounter.class); } else { createdEncounter = (Encounter) JsonUtils.readJson(responseJson, Encounter.class); } return createdEncounter; }
Source:
<code>public EEFLabelLifecycleManager(EEFLabelDescription description, IVariableManager variableManager, IInterpreter interpreter, TransactionalEditingDomain editingDomain) { <START> super(description, variableManager, <END> interpreter, editingDomain); this.description = description; }</code><technical_language>done</technical_language>

Target:
public EEFLabelLifecycleManager(EEFLabelDescription description, IVariableManager variableManager, IInterpreter interpreter, TransactionalEditingDomain editingDomain) { super(variableManager, interpreter, editingDomain); this.description = description; }
Source:
<code>public DMNModel compile(Reader source) { try { Definitions dmndefs = null; if(dmnCompilerConfig != null) { <START> if (dmnCompilerConfig.getRegisteredExtensions().isEmpty()) { <END> dmndefs = DMNMarshallerFactory.newMarshallerWithExtensions(getDmnCompilerConfig().getRegisteredExtensions()).unmarshal( source ); } }else { dmndefs = DMNMarshallerFactory.newDefaultMarshaller().unmarshal(source); } DMNModel model = compile( dmndefs ); return model; } catch ( Exception e ) { logger.error( "Error compiling model from source.", e ); } return null; }</code><technical_language>this code wrong. If dmnCompilerConfig is !=null list of extensions is empty, unmarshall source</technical_language>

Target:
public DMNModel compile(Reader source) { try { Definitions dmndefs = null; if(dmnCompilerConfig != null && !dmnCompilerConfig.getRegisteredExtensions().isEmpty()) { dmndefs = DMNMarshallerFactory.newMarshallerWithExtensions(getDmnCompilerConfig().getRegisteredExtensions()).unmarshal( source ); } else { dmndefs = DMNMarshallerFactory.newDefaultMarshaller().unmarshal(source); } DMNModel model = compile( dmndefs ); return model; } catch ( Exception e ) { logger.error( "Error compiling model from source.", e ); } return null; }
Source:
<code><START> public long getIncomingTuplesCount() <END> { return incomingTuplesCount; }</code><technical_language>Please this protected... need for this private</technical_language>

Target:
protected long getIncomingTuplesCount() { return incomingTuplesCount; }
Source:
<code>public void onDeleted(Run run) { Job<?, ?> j = run.getParent(); for (PeepholePermalink pp : Util.filter(j.getPermalinks(), PeepholePermalink.class)) { if (pp.resolve(j)==run) { Run<?,?> r = pp.find(run.getPreviousBuild()); <START> LOGGER.fine("Updating "+pp.getPermalinkFile(j).getName()+" permalink from deleted "+run.getNumber()+" to "+(r == null ? -1 : r.getNumber())); <END> pp.updateCache(j,r); } } }</code><technical_language>Logger.log(FINE, String, Object[]) overload if parameters cheap compute, save overhead of appending strings logging FINE. If parameters expensive compute, wrap in a if (LOGGER.isLoggable(FINE)) block</technical_language>

Target:
public void onDeleted(Run run) { Job<?, ?> j = run.getParent(); for (PeepholePermalink pp : Util.filter(j.getPermalinks(), PeepholePermalink.class)) { if (pp.resolve(j)==run) { Run<?,?> r = pp.find(run.getPreviousBuild()); if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Updating "+pp.getPermalinkFile(j).getName()+" permalink from deleted "+run.getNumber()+" to "+(r == null ? -1 : r.getNumber())); pp.updateCache(j,r); } } }
Source:
<code>@Override public <T> void addPolygon(AirMapPolygon<T> polygon) { try { JSONArray array = new JSONArray(); for (LatLng point : polygon.getPolygonOptions().getPoints()) { JSONObject json = new JSONObject(); json.put("lat", point.latitude); json.put("lng", point.longitude); array.put(json); } <START> webView.loadUrl(String.format("javascript:addPolygon(" + array.toString() + ", %1$d, %2$d, %3$d, %4$d);", polygon.getId(), (int) polygon.getPolygonOptions().getStrokeWidth(), polygon.getPolygonOptions().getStrokeColor(), polygon.getPolygonOptions().getFillColor())); <END> } catch (JSONException e) { Log.e(TAG, "error constructing polyline JSON", e); } }</code><technical_language>wrap this line in multiple, please? long. Locale.US argument String.format</technical_language>

Target:
@Override public <T> void addPolygon(AirMapPolygon<T> polygon) { try { JSONArray array = new JSONArray(); for (LatLng point : polygon.getPolygonOptions().getPoints()) { JSONObject json = new JSONObject(); json.put("lat", point.latitude); json.put("lng", point.longitude); array.put(json); } webView.loadUrl(String.format(Locale.US, "javascript:addPolygon(" + array.toString() + ", %1$d, %2$d, %3$d, %4$d);", polygon.getId(), (int) polygon.getPolygonOptions().getStrokeWidth(), polygon.getPolygonOptions().getStrokeColor(), polygon.getPolygonOptions().getFillColor())); } catch (JSONException e) { Log.e(TAG, "error constructing polyline JSON", e); } }
Source:
<code>public ItemStack tryToFillSlots(ItemStack stack, int... slots) { if (slots.length % 2 != 0) { throw new IllegalArgumentException("Slots must be pairs."); } ItemStack maxStack = stack.clone(); maxStack.setAmount(stack.getMaxStackSize()); <START> Integer firstEmpty = null; <END> for (int s = 0; s < slots.length && stack.getAmount() > 0; s += 2) { int start = slots[s]; int end = slots[s + 1]; int delta = start < end ? 1 : -1; for (int i = start; i != end && stack.getAmount() > 0; i += delta) { if (!itemShiftClickAllowed(i, stack)) { continue; } ItemStack currentStack = getItem(i); if (firstEmpty == null && InventoryUtil.isEmpty(currentStack)) { firstEmpty = i; } else if (currentStack.isSimilar(stack)) { int amount = currentStack.getAmount(); int maxStackSize = Math.min(currentStack.getMaxStackSize(), getMaxStackSize()); int transfer = Math.min(stack.getAmount(), maxStackSize - amount); if (transfer > 0) { currentStack.setAmount(amount + transfer); stack.setAmount(stack.getAmount() - transfer); } setItem(i, currentStack); } } } if (firstEmpty != null) { if (stack.getAmount() > stack.getMaxStackSize()) { setItem(firstEmpty, maxStack); stack.setAmount(stack.getAmount() - stack.getMaxStackSize()); } else { ItemStack finalStack = stack.clone(); setItem(firstEmpty, finalStack); stack.setAmount(0); } } if (stack.getAmount() <= 0) { stack = InventoryUtil.createEmptyStack(); } return stack; }</code><technical_language>this int instead? -1 for uninitialized value</technical_language>

Target:
public ItemStack tryToFillSlots(ItemStack stack, int... slots) { if (slots.length % 2 != 0) { throw new IllegalArgumentException("Slots must be pairs."); } ItemStack maxStack = stack.clone(); maxStack.setAmount(stack.getMaxStackSize()); int firstEmpty = -1; for (int s = 0; s < slots.length && stack.getAmount() > 0; s += 2) { int start = slots[s]; int end = slots[s + 1]; int delta = start < end ? 1 : -1; for (int i = start; i != end && stack.getAmount() > 0; i += delta) { if (!itemShiftClickAllowed(i, stack)) { continue; } ItemStack currentStack = getItem(i); if (firstEmpty == -1 && InventoryUtil.isEmpty(currentStack)) { firstEmpty = i; } else if (currentStack.isSimilar(stack)) { int amount = currentStack.getAmount(); int maxStackSize = Math.min(currentStack.getMaxStackSize(), getMaxStackSize()); int transfer = Math.min(stack.getAmount(), maxStackSize - amount); if (transfer > 0) { currentStack.setAmount(amount + transfer); stack.setAmount(stack.getAmount() - transfer); } setItem(i, currentStack); } } } if (firstEmpty != -1) { if (stack.getAmount() > stack.getMaxStackSize()) { setItem(firstEmpty, maxStack); stack.setAmount(stack.getAmount() - stack.getMaxStackSize()); } else { ItemStack finalStack = stack.clone(); setItem(firstEmpty, finalStack); stack.setAmount(0); } } if (stack.getAmount() <= 0) { stack = InventoryUtil.createEmptyStack(); } return stack; }
Source:
<code>public void testInitializesLocalPersistenceService() throws IOException { <START> final File rootDirectory = folder.newFolder("testInitializesLocalPersistenceService"); <END> try { newCacheManagerBuilder().with(new PersistenceConfiguration(rootDirectory)).build(true); } catch (Exception e) { assertThat(e, instanceOf(StateTransitionException.class)); assertThat(e.getCause(), instanceOf(IllegalArgumentException.class)); assertThat(e.getCause().getMessage().endsWith("CRAP!"), is(true)); } }</code><technical_language>changes, test fail exception is thrown anymore. reason this passes is is fail call catch block. adapt test tests tested before</technical_language>

Target:
public void testInitializesLocalPersistenceService() throws IOException { final File rootDirectory = folder.newFolder("testInitializesLocalPersistenceService"); assertTrue(rootDirectory.delete()); newCacheManagerBuilder().with(new PersistenceConfiguration(rootDirectory)).build(true); assertTrue(rootDirectory.isDirectory()); }
Source:
<code>public void setEnableSmallFileFeatures(final boolean on) { enableSmallFileFeatures = on; <START> Element element = context.getElement().getFirstChildElement(); while (element.getPropertyInt("value") != AccountDiffPreference.WHOLE_FILE_CONTEXT) { element = element.getNextSiblingElement(); } if (element.getPropertyInt("value") == AccountDiffPreference.WHOLE_FILE_CONTEXT) { if (enableSmallFileFeatures) { element.removeAttribute("disabled"); } else { element.setAttribute("disabled", "disabled"); if (AccountDiffPreference.CONTEXT_CHOICES[context.getSelectedIndex()] == AccountDiffPreference.WHOLE_FILE_CONTEXT) { for (int i = 0; i < AccountDiffPreference.CONTEXT_CHOICES.length; i++) { if (AccountDiffPreference.CONTEXT_CHOICES[i] == DiffScreen.LARGE_FILE_CONTEXT) { context.setSelectedIndex(i); break; } } } } } <END> toggleEnabledStatus(save.isEnabled()); }</code><technical_language>Please update this implementation</technical_language>

Target:
public void setEnableSmallFileFeatures(final boolean on) { enableSmallFileFeatures = on; NodeList<OptionElement> options = context.getElement().<SelectElement>cast().getOptions(); int lastIndex = options.getLength() - 1; OptionElement currOption = options.getItem(lastIndex); if (enableSmallFileFeatures) { currOption.setDisabled(false); } else { currOption.setDisabled(true); if (context.getSelectedIndex() == lastIndex) { context.setSelectedIndex(lastIndex - 1); } } toggleEnabledStatus(save.isEnabled()); }
Source:
<code>public Condition voidCondition(Condition condition, String voidReason) { <START> condition.setVoided(true); <END> condition.setVoidedBy(Context.getAuthenticatedUser()); condition.setVoidReason(voidReason); if(condition.getDateVoided() == null){ condition.setDateVoided(new Date()); } Context.getConditionService().saveCondition(condition); return condition; }</code><technical_language>ObsServiceImpl's voidObs()</technical_language>

Target:
public Condition voidCondition(Condition condition, String voidReason) { return conditionDAO.saveCondition(condition); }
Source:
<code>private void update(List<VmNetworkInterface> interfaces) { <START> if (interfaces != null && !interfaces.isEmpty()) { <END> for (VmNetworkInterface ifc : interfaces) { VmNetworkStatistics stats = ifc.getStatistics(); vmManager.update(stats); } } }</code><technical_language>If interfaces.isEmpty() loop body run, this check is redundant</technical_language>

Target:
private void update(List<VmNetworkInterface> interfaces) { if (interfaces == null) { return; } for (VmNetworkInterface ifc : interfaces) { vmManager.update(ifc.getStatistics()); } }
Source:
<code>public void trade() { for (String symbol : this.buyOrders.keySet()){ if (this.sellOrders.containsKey(symbol)){ HashMap<Double, ArrayList<Integer>> orderbook=orderBookCreator(symbol); double matchPrice=matchPrice(orderbook); if(matchPrice>0) try{ market.updateStockPrice(symbol, matchPrice);} catch (StockMarketExpection e){}; for (Order sellOrder : this.sellOrders.get(symbol)){ if (sellOrder.getPrice()<=matchPrice){ try { <START> sellOrder.getTrader().tradePerformed(sellOrder, matchPrice); <END> } catch (StockMarketExpection e) { e.printStackTrace(); } this.sellOrders.remove(sellOrder); } } for (Order buyOrder : this.buyOrders.get(symbol)){ if (buyOrder.getPrice()>=matchPrice){ try { buyOrder.getTrader().tradePerformed(buyOrder, matchPrice); } catch (StockMarketExpection e) { e.printStackTrace(); } this.buyOrders.remove(buyOrder); } } } } }</code><technical_language>properly indent this line, is long</technical_language>

Target:
public void trade() { for (String symbol : this.buyOrders.keySet()){ if (this.sellOrders.containsKey(symbol)){ HashMap<Double, ArrayList<Integer>> orderbook=orderBookCreator(symbol); double matchPrice=matchPrice(orderbook); if(matchPrice>0) try{ market.updateStockPrice(symbol, matchPrice);} catch (StockMarketExpection e){}; for (Order sellOrder : this.sellOrders.get(symbol)){ if (sellOrder.getPrice()<=matchPrice){ try { Trader sellTrader=sellOrder.getTrader(); sellTrader.tradePerformed(sellOrder, matchPrice); } catch (StockMarketExpection e) { e.printStackTrace(); } this.sellOrders.remove(sellOrder); } } for (Order buyOrder : this.buyOrders.get(symbol)){ if (buyOrder.getPrice()>=matchPrice){ try { Trader buyTrader=buyOrder.getTrader(); buyTrader.tradePerformed(buyOrder, matchPrice); } catch (StockMarketExpection e) { e.printStackTrace(); } this.buyOrders.remove(buyOrder); } } } } }
Source:
<code>public void updateRefundTransactionStatus(PaymentGatewayName provider, String refundReference, RefundStatus newRefundStatus) { Optional<RefundTransactionEntity> refundTransaction = refundTransactionDao.findByProviderAndReference(provider, refundReference); <START> String errorMessage = format("Not updating refund transaction status for refundReference [%s] to [%s] charge transaction not found", <END> refundReference, newRefundStatus.getValue() ); updateRefundTransactionStatus(refundTransaction, newRefundStatus, errorMessage); }</code><technical_language>refund transaction found, charge transaction</technical_language>

Target:
public void updateRefundTransactionStatus(PaymentGatewayName provider, String refundReference, RefundStatus newRefundStatus) { Optional<RefundTransactionEntity> refundTransaction = refundTransactionDao.findByProviderAndReference(provider, refundReference); if (refundTransaction.isPresent()) { updateRefundTransactionStatus(newRefundStatus, refundTransaction.get()); } else { logger.warn(format("Not updating refund transaction status for refundReference [%s] to [%s] refund transaction not found", refundReference, newRefundStatus.getValue() )); } }
Source:
<code>public void checkIfCanBeDeleted(@NonNull final I_MKTG_Channel mktgChannel) { if (!isMarketingChannelsUseEnforced()) { return; } boolean canBeDeleted = true; Set<UserId> usersSet = mktgChannelDao.retrieveUsersHavingChannel(mktgChannel.getMKTG_Channel_ID()); <START> for (UserId userId : usersSet) <END> { if (mktgChannelDao.retrieveMarketingChannelsCountForUser(userId) == 1 && !userDAO.isSystemUser(userId)) { canBeDeleted = false; break; } } if (!canBeDeleted) { throw new AdempiereException(MSG_MUST_HAVE_CHANNEL).markAsUserValidationError(); } }</code><technical_language>suggestion for (final UserId userId : usersSet)</technical_language>

Target:
public void checkIfCanBeDeleted(@NonNull final I_MKTG_Channel mktgChannel) { boolean canBeDeleted = true; Set<UserId> usersSet = mktgChannelDao.retrieveUsersHavingChannel(mktgChannel.getMKTG_Channel_ID()); for (final UserId userId : usersSet) { if (mktgChannelDao.retrieveMarketingChannelsCountForUser(userId) > 0) { canBeDeleted = false; break; } } if (!canBeDeleted) { throw new AdempiereException(MSG_MUST_HAVE_CHANNEL).markAsUserValidationError(); } }
Source:
<code>public SlackNotificationPayloadContent(SBuildServer server, SRunningBuild sRunningBuild, SFinishedBuild previousBuild, BuildStateEnum buildState) { payloadCommits = new PayloadContentCommits(); populateCommonContent(server, sRunningBuild, previousBuild, buildState); populateMessageAndText(sRunningBuild, buildState); <START> payloadCommits.populateCommits(sRunningBuild); <END> populateArtifacts(sRunningBuild); populateResults(sRunningBuild); }</code><technical_language>Hey, please fix identation in this file</technical_language>

Target:
public SlackNotificationPayloadContent(SBuildServer server, SRunningBuild sRunningBuild, SFinishedBuild previousBuild, BuildStateEnum buildState) { populateCommonContent(server, sRunningBuild, previousBuild, buildState); populateMessageAndText(sRunningBuild, buildState); payloadCommits.populateCommits(sRunningBuild); populateArtifacts(sRunningBuild); populateResults(sRunningBuild); }
Source:
<code>public DynamicTableSource createDynamicTableSource(Context context) { TableFactoryHelper helper = createTableFactoryHelper(this, context); String hTableName = helper.getOptions().get(TABLE_NAME); <START> Configuration hbaseClientConf = HBaseConfiguration.create(); <END> hbaseClientConf.set(HConstants.ZOOKEEPER_QUORUM, helper.getOptions().get(ZOOKEEPER_QUORUM)); hbaseClientConf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, helper.getOptions().get(ZOOKEEPER_ZNODE_PARENT)); String nullStringLiteral = helper.getOptions().get(NULL_STRING_LITERAL); TableSchema tableSchema = context.getCatalogTable().getSchema(); HBaseTableSchema hbaseSchema = HBaseTableSchema.fromTableSchema(tableSchema); return new HBaseDynamicTableSource( hbaseClientConf, hTableName, hbaseSchema, nullStringLiteral); }</code><technical_language>helper.validate()</technical_language>

Target:
public DynamicTableSource createDynamicTableSource(Context context) { TableFactoryHelper helper = createTableFactoryHelper(this, context); helper.validate(); String hTableName = helper.getOptions().get(TABLE_NAME); Configuration hbaseClientConf = HBaseConfiguration.create(); hbaseClientConf.set(HConstants.ZOOKEEPER_QUORUM, helper.getOptions().get(ZOOKEEPER_QUORUM)); hbaseClientConf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, helper.getOptions().get(ZOOKEEPER_ZNODE_PARENT)); String nullStringLiteral = helper.getOptions().get(NULL_STRING_LITERAL); TableSchema tableSchema = context.getCatalogTable().getSchema(); HBaseTableSchema hbaseSchema = HBaseTableSchema.fromTableSchema(tableSchema); return new HBaseDynamicTableSource( hbaseClientConf, hTableName, hbaseSchema, nullStringLiteral); }
Source:
<code>public ImmutableMap<String, String> query(Serializer serializer) { if (serializer == null) { serializer = Serializer.defaultSerializer(); } ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<>(); if (scope != null) { builder = builder.put("scope", serializer.serializeToQueryParams(scope)); } if (query != null && !query.isEmpty()) { builder = builder.put("query", query); } if (filters != null && !filters.isEmpty()) { for (Map.Entry<String, String> entry : filters.entrySet()) { builder = builder.put("filters[" + entry.getKey() + "]", entry.getValue()); } } if (order != null) { builder = builder.put("order", serializer.serializeToQueryParams(order)); } if (page > 0) { <START> builder = builder.put("page", page + ""); <END> } if (perPage > 0) { builder = builder.put("per_page", perPage + ""); } return builder.build(); }</code><technical_language>String.valueOf(int)</technical_language>

Target:
public Map<String, String> query(Serializer serializer) { if (serializer == null) { serializer = Serializer.defaultSerializer(); } Map<String, String> map = new HashMap<>(); if (scope != null) { map.put("scope", serializer.serializeToQueryParams(scope)); } if (query != null && !query.isEmpty()) { map.put("query", query); } if (filters != null && !filters.isEmpty()) { for (Map.Entry<String, String> entry : filters.entrySet()) { map.put("filters[" + entry.getKey() + "]", entry.getValue()); } } if (order != null) { map.put("order", serializer.serializeToQueryParams(order)); } if (page > 0) { map.put("page", String.valueOf(page)); } if (dataPerPage > 0) { map.put("per_page", String.valueOf(dataPerPage)); } return Collections.unmodifiableMap(map); }
Source:
<code>public int getPostsListLength() { <START> wait.forElementNotVisible(By.className(".spinner")); <END> return postList.size(); }</code><technical_language>wait for spinner here, instead method invocation call new BasePageObject(driver).waitForLoadingOverlayToDisappear(); in test case class</technical_language>

Target:
public int getPostsListLength() { return postList.size(); }
Source:
<code><START> public static List<Diagnostic> validate(String str) throws IOException, RecognitionException { <END> ByteArrayInputStream input = new ByteArrayInputStream(str.getBytes()); ANTLRInputStream antlrStream = new ANTLRInputStream(input); FilterParserLexer lexer = new FilterParserLexer(antlrStream); ArrayList<RecognitionException> lexerExceptions = new ArrayList<>(); lexer.setErrorListener(e -> { lexerExceptions.add((RecognitionException) e); }); CommonTokenStream tokenStream = new CommonTokenStream(lexer); FilterParserParser parser = new FilterParserParser(tokenStream); ArrayList<RecognitionException> parserExceptions = new ArrayList<>(); parser.setErrorListener(e -> { parserExceptions.add((RecognitionException) e); }); parser.parse(); List<Diagnostic> diagnostics = new ArrayList<>(); lexerExceptions.forEach(e -> { String message = lexer.getErrorMessage(e, lexer.getTokenNames()); int idx = e.index; Position start = new Position(e.line, idx); Position end = new Position(e.line, idx); Range range = new Range(start, end); Diagnostic diagnostic = new Diagnostic(range, message); diagnostics.add(diagnostic); }); return diagnostics; }</code><technical_language>presentation, mentioned done a state machine do validation antlr simply fail syntax error other errors. Is case? decided antlr all</technical_language>

Target:
public static List<Diagnostic> validate(String str) throws IOException, RecognitionException { ByteArrayInputStream input = new ByteArrayInputStream(str.getBytes()); ANTLRInputStream antlrStream = new ANTLRInputStream(input); FilterParserLexer lexer = new FilterParserLexer(antlrStream); ArrayList<RecognitionException> lexerExceptions = new ArrayList<>(); lexer.setErrorListener(e -> { lexerExceptions.add((RecognitionException) e); }); CommonTokenStream tokenStream = new CommonTokenStream(lexer); FilterParserParser parser = new FilterParserParser(tokenStream); ArrayList<RecognitionException> parserExceptions = new ArrayList<>(); parser.setErrorListener(e -> { parserExceptions.add((RecognitionException) e); }); parse_return parse = parser.parse(); CommonTree tree = parse.getTree(); List<Diagnostic> diagnostics = new ArrayList<>(); lexerExceptions.forEach(e -> { String message = lexer.getErrorMessage(e, lexer.getTokenNames()); Range range = getRangeFromException(e, str, tree); Diagnostic diagnostic = new Diagnostic(range, message); diagnostics.add(diagnostic); }); parserExceptions.forEach(e -> { String message = parser.getErrorMessage(e, parser.getTokenNames()); Range range = getRangeFromException(e, str, tree); Diagnostic diagnostic = new Diagnostic(range, message); diagnostics.add(diagnostic); }); return preprocessDiagnostics(diagnostics); }
Source:
<code>public static void stringToFile(IContext context, String value, FileDocument destination) throws IOException { <START> stringToFile(context, value, destination, "UTF-8"); <END> }</code><technical_language>Suggest StandardCharsets.UTF-8</technical_language>

Target:
public static void stringToFile(IContext context, String value, FileDocument destination) throws IOException { stringToFile(context, value, destination, StandardCharsets.UTF_8); }
Source:
<code>protected Collection<BackingChecker> getCheckers() throws ConfigurationException { if (checkers == null) { checkers = new HashSet<>(); for (String template : configurationGenerator.getTemplateList()) { try { File templateDir = configurationGenerator.getTemplateConf(template).getParentFile(); String classPath = getClasspathForTemplate(template); String checkClass = configurationGenerator.getUserConfig().getProperty(template + ".check.class"); Optional<URLClassLoader> ucl = getClassLoaderForTemplate(templateDir, classPath); if (ucl.isPresent()) { Class<?> klass = Class.forName(checkClass, true, ucl.get()); checkers.add((BackingChecker) klass.newInstance()); } } catch (IOException e) { log.warn("Unable to read check configuration for template : " + template, e); <START> } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { <END> throw new ConfigurationException("Unable to check configuration for backing service " + template, e); } } checkers.add(new DBCheck()); } return checkers; }</code><technical_language>catch (ReflectiveOperationException e). add ClassCastException (BackingChecker) cast in block above</technical_language>

Target:
protected Collection<BackingChecker> getCheckers() throws ConfigurationException { if (checkers == null) { checkers = new HashSet<>(); for (String template : configurationGenerator.getTemplateList()) { try { File templateDir = configurationGenerator.getTemplateConf(template).getParentFile(); String classPath = getClasspathForTemplate(template); String checkClass = configurationGenerator.getUserConfig().getProperty(template + PARAM_CHECK_SUFFIX); Optional<URLClassLoader> ucl = getClassLoaderForTemplate(templateDir, classPath); if (ucl.isPresent()) { Class<?> klass = Class.forName(checkClass, true, ucl.get()); checkers.add((BackingChecker) klass.newInstance()); } } catch (IOException e) { log.warn("Unable to read check configuration for template : " + template, e); } catch (ReflectiveOperationException | ClassCastException e) { throw new ConfigurationException("Unable to check configuration for backing service " + template, e); } } checkers.add(new DBCheck()); } return checkers; }
Source:
<code>protected Compressor<ByteBuf> buildCompressor() { DriverExecutionProfile defaultProfile = getConfig().getDefaultProfile(); if (!defaultProfile.isDefined(DefaultDriverOption.PROTOCOL_COMPRESSION)) { return Compressor.none(); } <START> <END> String name = defaultProfile.getString(DefaultDriverOption.PROTOCOL_COMPRESSION); switch (name) { case "lz4": return new Lz4Compressor(this); case "snappy": return new SnappyCompressor(this); case "none": return Compressor.none(); default: throw new IllegalArgumentException( String.format( "Unsupported compression algorithm '%s' (from configuration option %s)", name, DefaultDriverOption.PROTOCOL_COMPRESSION.getPath())); } }</code><technical_language>options case-insensitive, preserve behavior. If want switch statement, lower-case name</technical_language>

Target:
protected Compressor<ByteBuf> buildCompressor() { DriverExecutionProfile defaultProfile = getConfig().getDefaultProfile(); String name = defaultProfile.getString(DefaultDriverOption.PROTOCOL_COMPRESSION, "none"); assert name != null : "should use default value"; switch (name.toLowerCase()) { case "lz4": return new Lz4Compressor(this); case "snappy": return new SnappyCompressor(this); case "none": return Compressor.none(); default: throw new IllegalArgumentException( String.format( "Unsupported compression algorithm '%s' (from configuration option %s)", name, DefaultDriverOption.PROTOCOL_COMPRESSION.getPath())); } }
Source:
<code><START> private static Date addDates(Date d, int days) { <END> Calendar c = Calendar.getInstance(); c.setTime(d); c.add(Calendar.DAY_OF_MONTH, days); return c.getTime(); }</code><technical_language>changing method static</technical_language>

Target:
private Date addDates(Date d, int days) { Calendar c = Calendar.getInstance(); c.setTime(d); c.add(Calendar.DAY_OF_MONTH, days); return c.getTime(); }
Source:
<code>private static void reportEntityDetailNavigation(String direction, String navMethod, int detailTabCount) { <START> String detailUiState = <END> detailTabCount > 1 ? CCAnalyticsParamValue.DETAIL_WITH_TABS : CCAnalyticsParamValue.DETAIL_NO_TABS; reportEvent(CCAnalyticsEvent.ENTITY_DETAIL_NAVIGATION, new String[]{ CCAnalyticsParam.DIRECTION, CCAnalyticsParam.METHOD, CCAnalyticsParam.UI_STATE}, new String[]{direction, navMethod, detailUiState}); }</code><technical_language>Nice centralization of this logic</technical_language>

Target:
private static void reportEntityDetailNavigation(String direction, String navMethod, int detailTabCount) { String detailUiState = detailTabCount > 1 ? AnalyticsParamValue.DETAIL_WITH_TABS : AnalyticsParamValue.DETAIL_NO_TABS; reportEvent(CCAnalyticsEvent.ENTITY_DETAIL_NAVIGATION, new String[]{ CCAnalyticsParam.DIRECTION, CCAnalyticsParam.METHOD, CCAnalyticsParam.UI_STATE}, new String[]{direction, navMethod, detailUiState}); }
Source:
<code>private static boolean needsQuote(String s) { <START> char c = s.charAt(0); <END> if (!(c >= 97 && c <= 122)) return true; for (int i = 1; i < s.length(); i++) { c = s.charAt(i); if (!( (c >= 48 && c <= 57) || (c == 95) || (c >= 97 && c <= 122) )) { return true; } } return isReservedCqlKeyword(s); }</code><technical_language>unlikely, escapeId is in a ton of places I for is empty string passed if this throw a StringIndexOutOfBoundsException</technical_language>

Target:
private static boolean needsQuote(String s) { assert s != null && !s.isEmpty(); char c = s.charAt(0); if (!(c >= 97 && c <= 122)) return true; for (int i = 1; i < s.length(); i++) { c = s.charAt(i); if (!( (c >= 48 && c <= 57) || (c == 95) || (c >= 97 && c <= 122) )) { return true; } } return isReservedCqlKeyword(s); }
Source:
<code>public void testAsyncRollback() throws Exception { Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); MessageConsumer messageConsumer = session.createConsumer(queue); messageConsumer.setMessageListener(new MessageListener() { @Override @Transactional public void onMessage(Message message) { try { <START> System.out.println("RECEIVED"); <END> TransactionManager.transactionManager().getTransaction().enlistResource(xaResourceMock); messageConsumer.setMessageListener(null); } catch (Exception e) { System.out.println("PROBLEM " + e.getMessage()); throw new RuntimeException(e); } System.out.println("EXCEPTION"); throw new RuntimeException("Fail - should imply a rollback"); } }); sendMessage(); verify(xaResourceMock, timeout(1_000L).times(1)).rollback(any(Xid.class)); }</code><technical_language>remove printlns if this</technical_language>

Target:
public void testAsyncRollback() throws Exception { Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); MessageConsumer messageConsumer = session.createConsumer(queue); messageConsumer.setMessageListener(new MessageListener() { @Override @Transactional public void onMessage(Message message) { try { TransactionManager.transactionManager().getTransaction().enlistResource(xaResourceMock); messageConsumer.setMessageListener(null); } catch (Exception e) { throw new RuntimeException(e); } throw new RuntimeException("Fail - should imply a rollback"); } }); sendMessage(); verify(xaResourceMock, timeout(1_000L).times(1)).rollback(any(Xid.class)); Message receivedMessage = messageConsumer.receiveNoWait(); assertNotNull(receivedMessage); }
Source:
<code>public void testExtractLoggingOutputs() throws Exception { StringBuilder input = new StringBuilder(); List<String> expectedOutput = new ArrayList<>(); for (int i = 0; i < 5; ++i) { <START> String line = "BashJavaUtils output line " + i; <END> if (i % 2 == 0) { expectedOutput.add(line); } else { line = BashJavaUtils.EXECUTION_PREFIX + line; } input.append(line + "\n"); } String[] commands = {RUN_EXTRACT_LOGGING_OUTPUTS_SCRIPT, input.toString()}; List<String> actualOutput = Arrays.asList(executeScript(commands).split(System.lineSeparator())); assertEquals(expectedOutput, actualOutput); }</code><technical_language>add some special symbols (e.g. " , ' , \ , /) arg expected_lines is correctly extractLoggingOutputs output</technical_language>

Target:
public void testExtractLoggingOutputs() throws Exception { StringBuilder input = new StringBuilder(); List<String> expectedOutput = new ArrayList<>(); for (int i = 0; i < 5; ++i) { String line = "BashJavaUtils output line " + i + " `~!@#$%^&*()-_=+;:,.'\"\\\t/?"; if (i % 2 == 0) { expectedOutput.add(line); } else { line = BashJavaUtils.EXECUTION_PREFIX + line; } input.append(line + "\n"); } String[] commands = {RUN_EXTRACT_LOGGING_OUTPUTS_SCRIPT, input.toString()}; List<String> actualOutput = Arrays.asList(executeScript(commands).split(System.lineSeparator())); assertThat(actualOutput, is(expectedOutput)); }
Source:
<code><START> public static void setMetrics(Configuration config) { <END> LOG.info("Initializing HttpFSServerMetrics"); HttpFSServerWebApp.metrics = HttpFSServerMetrics.create(config, "HttpFSServer"); JvmPauseMonitor pauseMonitor = new JvmPauseMonitor(); pauseMonitor.init(config); pauseMonitor.start(); HttpFSServerWebApp.metrics.getJvmMetrics().setPauseMonitor(pauseMonitor); FSOperations.setBufferSize(config); DefaultMetricsSystem.initialize("HttpFSServer"); }</code><technical_language>this private? is init() in this class</technical_language>

Target:
private static void setMetrics(Configuration config) { LOG.info("Initializing HttpFSServerMetrics"); metrics = HttpFSServerMetrics.create(config, "HttpFSServer"); JvmPauseMonitor pauseMonitor = new JvmPauseMonitor(); pauseMonitor.init(config); pauseMonitor.start(); metrics.getJvmMetrics().setPauseMonitor(pauseMonitor); FSOperations.setBufferSize(config); DefaultMetricsSystem.initialize("HttpFSServer"); }
Source:
<code>public synchronized void unsubscribe(@Nonnull StreamListener streamListener) { SubscriptionThread st = subscriptions.remove(streamListener); if (st == null) { <START> log.warn("StreamManager::unsubscribe has no context for "+streamListener.toString()); <END> return; } st.setShutdown(true); st.interrupt(); log.info("Unsubscribed StreamListener {}", streamListener.toString()); }</code><technical_language>log.warn("StreamManager::unsubscribe context for {}", streamListener);</technical_language>

Target:
public void unsubscribe(@Nonnull StreamListener streamListener) { StreamSubscriber streamSubscriber = unsubscribeInternal(streamListener); if (streamSubscriber != null) { streamSubscriber.getScheduledFuture().cancel(false); } }
Source:
<code>public void testErrorDuringInitialization() throws Exception { dispatcher = createAndStartDispatcher(heartbeatServices, haServices, new ExpectedJobIdJobManagerRunnerFactory(TEST_JOB_ID, createdJobManagerRunnerLatch)); jobMasterLeaderElectionService.isLeader(UUID.randomUUID()); DispatcherGateway dispatcherGateway = dispatcher.getSelfGateway(DispatcherGateway.class); final FailingInitializationJobVertex failingInitializationJobVertex = new FailingInitializationJobVertex( "testVertex"); failingInitializationJobVertex.setInvokableClass(NoOpInvokable.class); JobGraph blockingJobGraph = new JobGraph(TEST_JOB_ID, "failingTestJob", failingInitializationJobVertex); dispatcherGateway.submitJob(blockingJobGraph, TIMEOUT).get(); <START> JobStatus status; do { CompletableFuture<JobStatus> statusFuture = dispatcherGateway.requestJobStatus(blockingJobGraph.getJobID(), TIMEOUT); status = statusFuture.get(); Thread.sleep(50); Assert.assertThat(status, either(is(JobStatus.INITIALIZING)).or(is(JobStatus.FAILED))); } while (status != JobStatus.FAILED); <END> ArchivedExecutionGraph execGraph = dispatcherGateway.requestJob(jobGraph.getJobID(), TIMEOUT).get(); Assert.assertNotNull(execGraph.getFailureInfo()); Assert.assertTrue(execGraph.getFailureInfo().getExceptionAsString().contains("Artificial test failure")); closeDispatcherAfterInitializationError(); }</code><technical_language>replace this dispatcherGateway.requestJobResult waiting returned future</technical_language>

Target:
public void testErrorDuringInitialization() throws Exception { dispatcher = createAndStartDispatcher(heartbeatServices, haServices, new ExpectedJobIdJobManagerRunnerFactory(TEST_JOB_ID, createdJobManagerRunnerLatch)); DispatcherGateway dispatcherGateway = dispatcher.getSelfGateway(DispatcherGateway.class); final FailingInitializationJobVertex failingInitializationJobVertex = new FailingInitializationJobVertex("testVertex"); failingInitializationJobVertex.setInvokableClass(NoOpInvokable.class); JobGraph blockingJobGraph = new JobGraph(TEST_JOB_ID, "failingTestJob", failingInitializationJobVertex); dispatcherGateway.submitJob(blockingJobGraph, TIMEOUT).get(); dispatcherGateway.requestJobResult(TEST_JOB_ID, TIMEOUT).get(); ArchivedExecutionGraph execGraph = dispatcherGateway.requestJob(jobGraph.getJobID(), TIMEOUT).get(); Assert.assertNotNull(execGraph.getFailureInfo()); Throwable throwable = execGraph.getFailureInfo().getException().deserializeError(ClassLoader.getSystemClassLoader()); assertTrue(throwable instanceof JobInitializationException); }