auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void handleTownHallBroadcast(TileTownHall tile, BlockPosition position) { validateTownHallPosition(); BlockPosition pos = getTownHallPosition(); if (pos != null) { double curDist = getDistanceSq(pos.x + 0.5d, pos.y, pos.z + 0.5d); double newDist = getDistanceSq(position.x + 0.5d, position.y, position.z + 0.5d); if (newDist < curDist) { setTownHallPosition(position); if (upkeepAutoBlock == null || upkeepAutoBlock.equals(pos)) { upkeepAutoBlock = position; } } } else { setTownHallPosition(position); if (upkeepAutoBlock == null || upkeepAutoBlock.equals(pos)) { upkeepAutoBlock = position; } } if (getTownHall().alarmActive) isAlarmed = true; else isAlarmed = false; }

Target:
public void handleTownHallBroadcast(TileTownHall tile, BlockPosition position) { validateTownHallPosition(); BlockPosition pos = getTownHallPosition(); if (pos != null) { double curDist = getDistanceSq(pos.x + 0.5d, pos.y, pos.z + 0.5d); double newDist = getDistanceSq(position.x + 0.5d, position.y, position.z + 0.5d); if (newDist < curDist) { setTownHallPosition(position); if (upkeepAutoBlock == null || upkeepAutoBlock.equals(pos)) { upkeepAutoBlock = position; } } } else { setTownHallPosition(position); if (upkeepAutoBlock == null || upkeepAutoBlock.equals(pos)) { upkeepAutoBlock = position; } } isAlarmed = getTownHall().alarmActive; }
Source:
public String getClusterNamespace() { Connection connection = getConnection(); if(connection != null) { return connection.getClusterNamespace(); } return ""; }

Target:
public String getClusterNamespace() { Connection connection = getConnection(); if(connection != null) { return connection.getClusterNamespace(); } return ICommonAttributes.COMMON_NAMESPACE; }
Source:
protected void processSpanImpl(Span span, Map<String, String[]> servletRequestParameters) { long sum = 0; for (String weaselParameterToSum : weaselParametersToSum) { final Long timing = parsedLongOrNull(getParameterValueOrNull(weaselParameterToSum, servletRequestParameters)); if (timing == null) { discardSpan(span); return; } else { sum += timing; } } span.setTag(TIMING_RESOURCE, sum); }

Target:
protected void processSpanImpl(Span span, Map<String, String[]> servletRequestParameters) { long sum = 0; for (String weaselParameterToSum : weaselParametersToSum) { final Long timing = parsedLongOrNull(getParameterValueOrNull(weaselParameterToSum, servletRequestParameters)); if (timing == null) { return; } else { sum += timing; } } span.setTag(TIMING_RESOURCE, sum); }
Source:
public void onMessage(Message message) { log.info(message.toString()); try { String messageBody = getMessageBody(message); Event event = new Event(messageBody); eventManager.handleEvent(event); log.info("Received Event: " + event); } catch (Exception e) { log.error("Failed to decode and store event ", e); } }

Target:
public void onMessage(Message message) { log.info(message.toString()); try { String messageBody = getMessageBody(message); Event event = new Event(messageBody); eventManager.handle(event); log.info("Received Event: " + event); } catch (Exception e) { log.error("Failed to decode and store event ", e); } }
Source:
private void recalculateTotalExperience() { if (!dontRecalculateExperience.get()) { this.experienceTotal = this.xpAtLevel(this.experienceLevel) + Math.round(this.experience * this.xpBarCap()); } }

Target:
private void recalculateTotalExperience() { if (!this.dontRecalculateExperience) { int newExperienceInLevel = (int) (this.experience * this.xpBarCap()); this.experienceTotal = this.xpAtLevel(this.experienceLevel) + newExperienceInLevel; this.experience = (float) newExperienceInLevel / this.xpBarCap(); } }
Source:
<T> Ref<T> getOrLoadRef(DfsStreamKey key, RefLoader<T> loader) throws IOException { int slot = slot(key, 0); HashEntry e1 = table.get(slot); Ref<T> ref = scanRef(e1, key, 0); if (ref != null) { getStat(statHit, key).incrementAndGet(); return ref; } getStat(statMiss, key).incrementAndGet(); ReentrantLock regionLock = lockFor(key, 0); regionLock.lock(); try { HashEntry e2 = table.get(slot); if (e2 != e1) { ref = scanRef(e2, key, 0); if (ref != null) { getStat(statHit, key).incrementAndGet(); return ref; } } ref = loader.load(); reserveSpace(ref.size, key); for (;;) { HashEntry n = new HashEntry(clean(e2), ref); if (table.compareAndSet(slot, e2, n)) break; e2 = table.get(slot); } addToClock(ref, 0); } finally { regionLock.unlock(); } return ref; }

Target:
<T> Ref<T> getOrLoadRef(DfsStreamKey key, RefLoader<T> loader) throws IOException { int slot = slot(key, 0); HashEntry e1 = table.get(slot); Ref<T> ref = scanRef(e1, key, 0); if (ref != null) { getStat(statHit, key).incrementAndGet(); return ref; } ReentrantLock regionLock = lockFor(key, 0); regionLock.lock(); try { HashEntry e2 = table.get(slot); if (e2 != e1) { ref = scanRef(e2, key, 0); if (ref != null) { getStat(statHit, key).incrementAndGet(); return ref; } } getStat(statMiss, key).incrementAndGet(); ref = loader.load(); reserveSpace(ref.size, key); for (;;) { HashEntry n = new HashEntry(clean(e2), ref); if (table.compareAndSet(slot, e2, n)) break; e2 = table.get(slot); } addToClock(ref, 0); } finally { regionLock.unlock(); } return ref; }
Source:
public void testInterrupt() throws Exception { InterruptTestRunner runner = new InterruptTestRunner(); runner.start(); try { runner.join(); } catch (InterruptedException ie) { fail(); } if (runner.failure != null) { throw runner.failure; } }

Target:
public void testInterrupt() throws Exception { final Object lock = new Object(); final CountDownLatch cdl = new CountDownLatch(1); final Waiter waiter = new Waiter(lock, cdl); waiter.start(); try { cdl.await(); } catch (InterruptedException ie) { fail(); } synchronized (lock) { waiter.interrupt(); } try { waiter.join(); } catch (InterruptedException ie) { fail(); } assertTrue(waiter.wasInterrupted()); }
Source:
private static @CheckForNull ResourceBundle getBundle(@Nonnull String baseName, @Nonnull Locale locale, @Nonnull ClassLoader classLoader) { try { return ResourceBundle.getBundle(baseName, locale, classLoader); } catch (MissingResourceException e) { logger.info(e.getMessage()); } return null; }

Target:
private static @CheckForNull ResourceBundle getBundle(@Nonnull String baseName, @Nonnull Locale locale, @Nonnull ClassLoader classLoader) { try { return ResourceBundle.getBundle(baseName, locale, classLoader); } catch (MissingResourceException e) { logger.warning(e.getMessage()); } return null; }
Source:
public ZeroConfig read(JsonReader in) throws IOException, NumberFormatException { ZeroConfig result = new ZeroConfig(); in.beginObject(); while (in.hasNext()) { String field = in.nextName(); String value = in.nextString(); switch (field) { case "message": result.setMessage(value); break; case "background": result.setBackground(Color.parseColor(value)); break; case "foreground": result.setForeground(Color.parseColor(value)); break; case "exitTitle": result.setExitTitle(value); break; case "exitWarning": result.setExitWarning(value); break; case "partnerInfoText": result.setPartnerInfoText(value); break; case "partnerInfoUrl": result.setPartnerInfoUrl(value); break; case "bannerUrl": result.setBannerUrl(value); break; default: throw new IOException("zeroconfig response contained unknown property"); } } return result; }

Target:
public ZeroConfig read(JsonReader in) throws IOException, NumberFormatException { ZeroConfig result = new ZeroConfig(); in.beginObject(); while (in.hasNext()) { String field = in.nextName(); String value = in.nextString(); switch (field) { case "message": result.setMessage(value); break; case "background": result.setBackground(Color.parseColor(value)); break; case "foreground": result.setForeground(Color.parseColor(value)); break; case "exitTitle": result.setExitTitle(value); break; case "exitWarning": result.setExitWarning(value); break; case "partnerInfoText": result.setPartnerInfoText(value); break; case "partnerInfoUrl": result.setPartnerInfoUrl(Uri.parse(value)); break; case "bannerUrl": result.setBannerUrl(Uri.parse(value)); break; default: break; } } return result; }
Source:
public List<StreamsDatum> process(StreamsDatum entry) { List<StreamsDatum> result = Lists.newArrayList(); ObjectNode rootDocument = getRootDocument(entry); Map<String, String> params = prepareParams(entry); URI uri; for( Map.Entry<String,String> param : params.entrySet()) { uriBuilder = uriBuilder.setParameter(param.getKey(), param.getValue()); } try { uri = uriBuilder.build(); } catch (URISyntaxException e) { LOGGER.error("URI error {}", uriBuilder.toString()); return result; } HttpEntity payload = preparePayload(entry); HttpPost httpPost = prepareHttpPost(uri, payload); CloseableHttpResponse response = null; String entityString = null; try { response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); if (response.getStatusLine().getStatusCode() == 200 && entity != null) { entityString = EntityUtils.toString(entity); } } catch (IOException e) { LOGGER.error("IO error:\n{}\n{}\n{}", uri.toString(), response, e.getMessage()); return result; } finally { try { response.close(); } catch (IOException e) } if( entityString == null ) return result; LOGGER.debug(entityString); ObjectNode extensionFragment = prepareExtensionFragment(entityString); ActivityObject extensionEntity = getEntityToExtend(rootDocument); ExtensionUtil.addExtension(extensionEntity, this.configuration.getExtension(), extensionFragment); rootDocument = setEntityToExtend(rootDocument, extensionEntity); entry.setDocument(rootDocument); result.add(entry); return result; }

Target:
public List<StreamsDatum> process(StreamsDatum entry) { List<StreamsDatum> result = Lists.newArrayList(); ObjectNode rootDocument = getRootDocument(entry); Map<String, String> params = prepareParams(entry); URI uri; for( Map.Entry<String,String> param : params.entrySet()) { uriBuilder = uriBuilder.setParameter(param.getKey(), param.getValue()); } try { uri = uriBuilder.build(); } catch (URISyntaxException e) { LOGGER.error("URI error {}", uriBuilder.toString(), e); return result; } HttpEntity payload = preparePayload(entry); HttpPost httpPost = prepareHttpPost(uri, payload); CloseableHttpResponse response = null; String entityString = null; try { response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); if (response.getStatusLine().getStatusCode() == 200 && entity != null) { entityString = EntityUtils.toString(entity); } } catch (IOException e) { LOGGER.error("IO error:\n{}\n{}\n{}", uri.toString(), response, e); return result; } finally { try { response.close(); } catch (IOException e) } if( entityString == null ) return result; LOGGER.debug(entityString); ObjectNode extensionFragment = prepareExtensionFragment(entityString); ActivityObject extensionEntity = getEntityToExtend(rootDocument); ExtensionUtil.addExtension(extensionEntity, this.configuration.getExtension(), extensionFragment); rootDocument = setEntityToExtend(rootDocument, extensionEntity); entry.setDocument(rootDocument); result.add(entry); return result; }
Source:
public Box(String orient) { setOrient(orient); setAttribute("org.zkoss.zul.css.flex", false); }

Target:
public Box(String orient) { setOrient(orient); }
Source:
public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value != null) { setBorder(BORDER); ScriptWrapper item = (ScriptWrapper) value; if (panel.loadedScript == item) setText("<html><b>" + item.getName() + " (loaded)</b></html>"); else setText(item.getName()); } return this; }

Target:
public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value != null) { setBorder(BORDER); ScriptWrapper item = (ScriptWrapper) value; if (panel.loadedScript == item) setText( "<html><b>" + StringEscapeUtils.unescapeHtml(item.getName()) + " (loaded)</b></html>"); else setText(item.getName()); } return this; }
Source:
public InsertSelect addColumns(String[] columnNames) { Collections.addAll( this.columnNames,columnNames ); return this; }

Target:
public InsertSelect addColumns(String[] columnNames) { this.columnNames.ensureCapacity(this.columnNames.size()+columnNames.length); Collections.addAll( this.columnNames,columnNames ); return this; }
Source:
public static int getStrongSignal(IMultipartContainer container, EnumFacing side, EnumFacing face) { if (container == null) { return 0; } IMultipart part = container.getPartInSlot(PartSlot.getFaceSlot(side)); if (part != null) { return part instanceof IRedstonePart ? ((IRedstonePart) part).getStrongSignal(side) : 0; } part = container.getPartInSlot(PartSlot.getEdgeSlot(side, face)); if (part != null) { return part instanceof IRedstonePart ? ((IRedstonePart) part).getStrongSignal(side) : 0; } part = container.getPartInSlot(PartSlot.getFaceSlot(face)); if (part != null) { return part instanceof IRedstonePart ? ((IRedstonePart) part).getStrongSignal(side) : 0; } int max = 0; if (face == null) { part = container.getPartInSlot(PartSlot.CENTER); if (part instanceof IRedstonePart) { max = ((IRedstonePart) part).getStrongSignal(side); } } for (IMultipart p : container.getParts()) { if (!(p instanceof ISlottedRedstonePart) || ((ISlottedRedstonePart) p).getSlotMask().isEmpty()) { if (p instanceof IRedstonePart) { max = Math.max(max, ((IRedstonePart) p).getStrongSignal(side)); } } } return max; }

Target:
public static int getStrongSignal(IMultipartContainer container, EnumFacing side, EnumFacing face) { if (container == null) { return 0; } IMultipart part = container.getPartInSlot(PartSlot.getFaceSlot(side)); if (part != null) { return part instanceof IRedstonePart ? ((IRedstonePart) part).getStrongSignal(side) : 0; } part = container.getPartInSlot(PartSlot.getEdgeSlot(side, face)); if (part != null) { return part instanceof IRedstonePart ? ((IRedstonePart) part).getStrongSignal(side) : 0; } part = container.getPartInSlot(PartSlot.getFaceSlot(face)); if (part != null) { return part instanceof IRedstonePart ? ((IRedstonePart) part).getStrongSignal(side) : 0; } int max = 0; if (face == null) { part = container.getPartInSlot(PartSlot.CENTER); if (part instanceof IRedstonePart) { max = ((IRedstonePart) part).getStrongSignal(side); } } for (IMultipart p : container.getParts()) { if ((!(p instanceof ISlottedRedstonePart) || ((ISlottedRedstonePart) p).getSlotMask().isEmpty()) && p instanceof IRedstonePart) { max = Math.max(max, ((IRedstonePart) p).getStrongSignal(side)); } } return max; }
Source:
public void testFileWithEmptyLineOnlyWithLfCrCrlf() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(NewlineAtEndOfFileCheck.class); checkConfig.addAttribute("lineSeparator", LineSeparatorOption.LF_CR_CRLF.toString()); final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; verify( createChecker(checkConfig), getPath("InputNewlineAtEndOfFileNewlineAtEnd.txt"), expected); }

Target:
public void testFileWithEmptyLineOnlyWithLfCrCrlf() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(NewlineAtEndOfFileCheck.class); checkConfig.addAttribute("lineSeparator", LineSeparatorOption.LF_CR_CRLF.toString()); final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; verify( createChecker(checkConfig), getPath("InputNewlineAtEndOfFileNewlineAtEndLf.txt"), expected); }
Source:
public void testCreateAndGetInSameTransaction(KeycloakSession session) { RealmModel realm = session.realms().getRealmByName("test"); ClientModel client = realm.getClientByClientId("test-app"); UserSessionModel userSession = session.sessions().createUserSession(realm, session.users().getUserByUsername("user1", realm), "user1", "127.0.0.2", "form", true, null, null); createClientSession(session, client, userSession, "http://redirect", "state"); UserSessionModel userSessionLoaded = session.sessions().getUserSession(realm, userSession.getId()); AuthenticatedClientSessionModel clientSessionLoaded = userSessionLoaded.getAuthenticatedClientSessions().get(client.getId()); Assert.assertNotNull(userSessionLoaded); Assert.assertNotNull(clientSessionLoaded); Assert.assertEquals(userSession.getId(), clientSessionLoaded.getUserSession().getId()); Assert.assertEquals(1, userSessionLoaded.getAuthenticatedClientSessions().size()); }

Target:
public void testCreateAndGetInSameTransaction(KeycloakSession session) { RealmModel realm = session.realms().getRealmByName("test"); ClientModel client = realm.getClientByClientId("test-app"); UserSessionModel userSession = session.sessions().createUserSession(realm, session.users().getUserByUsername("user1", realm), "user1", "127.0.0.2", "form", true, null, null); AuthenticatedClientSessionModel clientSession = createClientSession(session, client, userSession, "http://redirect", "state"); UserSessionModel userSessionLoaded = session.sessions().getUserSession(realm, userSession.getId()); AuthenticatedClientSessionModel clientSessionLoaded = userSessionLoaded.getAuthenticatedClientSessions().get(client.getId()); Assert.assertNotNull(userSessionLoaded); Assert.assertNotNull(clientSessionLoaded); Assert.assertEquals(userSession.getId(), clientSessionLoaded.getUserSession().getId()); Assert.assertEquals(1, userSessionLoaded.getAuthenticatedClientSessions().size()); }
Source:
private boolean stopTransferIfNecessary(ImageTransfer entity, long ts) { if (getParameters().getKeepaliveInterval() > 0 && (entity.getPhase() == ImageTransferPhase.INITIALIZING || entity.getPhase() == ImageTransferPhase.TRANSFERRING) && (entity.getLastUpdated().getTime() / 1000) + getParameters().getKeepaliveInterval() < ts) { String action = "paused"; ImageTransferPhase phase = ImageTransferPhase.PAUSED_SYSTEM; if (getParameters().getTransferType() == TransferType.Download) { action = "canceled"; phase = ImageTransferPhase.CANCELLED; } log.warn("Transfer was due to no updates in seconds. {}", action, ts - (entity.getLastUpdated().getTime() / 1000), getTransferDescription()); updateEntityPhase(phase); return true; } return false; }

Target:
private boolean stopTransferIfNecessary(ImageTransfer entity, long ts) { if (transferImageInactivityTimeoutInSeconds > 0 && (entity.getPhase() == ImageTransferPhase.INITIALIZING || entity.getPhase() == ImageTransferPhase.TRANSFERRING) && (entity.getLastUpdated().getTime() / 1000) + transferImageInactivityTimeoutInSeconds < ts) { ImageTransferPhase phase = ImageTransferPhase.PAUSED_SYSTEM; if (getParameters().getTransferType() == TransferType.Download) { phase = ImageTransferPhase.CANCELLED; } log.warn("Transfer phase was changed to due to no updates in seconds. {}", phase.toString(), ts - (entity.getLastUpdated().getTime() / 1000), getTransferDescription()); updateEntityPhase(phase); return true; } return false; }
Source:
private String extract(final StringValueStyle style) { if (style == null || style.getStringValue() == null || style.getStringValue().isEmpty()) { return null; } return style.getStringValue(); }

Target:
private String extract(final StringValueStyle style) { if (null == style || null == style.getStringValue() || style.getStringValue().isEmpty()) { return null; } return style.getStringValue(); }
Source:
private void setupViewModels() { backgroundLocationViewModel = ViewModelProviders.of(this, new FormEntryViewModelFactory()).get(BackgroundLocationViewModel.class); identityPromptViewModel = ViewModelProviders.of(this).get(IdentityPromptViewModel.class); identityPromptViewModel.requiresIdentityToContinue().observe(this, requiresIdentity -> { if (requiresIdentity) { IdentifyUserPromptDialogFragment dialog = IdentifyUserPromptDialogFragment.create(getFormController().getFormTitle()); DialogUtils.showIfNotShowing(dialog, getSupportFragmentManager()); } }); identityPromptViewModel.isFormEntryCancelled().observe(this, isFormEntryCancelled -> { if (isFormEntryCancelled) { finish(); } }); FormSaveViewModel.Factory changesReasonViewModelFactory = new FormSaveViewModel.Factory(); formSaveViewModel = ViewModelProviders .of(this, changesReasonViewModelFactory) .get(FormSaveViewModel.class); formSaveViewModel.setAnalytics(analytics); formSaveViewModel.getSavedResult().observe(this, this::handleSaveResult); }

Target:
private void setupViewModels() { backgroundLocationViewModel = ViewModelProviders.of(this, new FormEntryViewModelFactory()).get(BackgroundLocationViewModel.class); identityPromptViewModel = ViewModelProviders.of(this).get(IdentityPromptViewModel.class); identityPromptViewModel.requiresIdentityToContinue().observe(this, requiresIdentity -> { if (requiresIdentity) { IdentifyUserPromptDialogFragment dialog = IdentifyUserPromptDialogFragment.create(getFormController().getFormTitle()); DialogUtils.showIfNotShowing(dialog, getSupportFragmentManager()); } }); identityPromptViewModel.isFormEntryCancelled().observe(this, isFormEntryCancelled -> { if (isFormEntryCancelled) { finish(); } }); FormSaveViewModel.Factory changesReasonViewModelFactory = new FormSaveViewModel.Factory(analytics); formSaveViewModel = ViewModelProviders .of(this, changesReasonViewModelFactory) .get(FormSaveViewModel.class); formSaveViewModel.getSavedResult().observe(this, this::handleSaveResult); }
Source:
public void delete() throws IOException { super.delete(); for(MatrixRun run : getExactRuns()) { if (run.getWhyKeepLog() != null) continue; run.delete(); } }

Target:
public void delete() throws IOException { super.delete(); for(MatrixRun run : getExactRuns()) { run.delete(); } }
Source:
protected void updateIteration() { refreshIteration = refreshIteration++ % NUMBER_VMS_REFRESHES_BEFORE_SAVE; }

Target:
protected void updateIteration() { refreshIteration = (++refreshIteration) % NUMBER_VMS_REFRESHES_BEFORE_SAVE; }
Source:
public boolean isModelerResource() { if (resource.getURI() != null) { return new FileQuery(resource.getURI().fileExtension()).isVSMFile(); } return false; }

Target:
public boolean isModelerResource() { try { if (resource.getURI() != null) { return new FileQuery(resource.getURI().fileExtension()).isVSMFile(); } } catch (IllegalStateException e) { } return false; }
Source:
public static void main(String args[]) throws Exception { VerifiableProperties verifiableProperties = StoreToolsUtil.getVerifiableProperties(args); String storeId = verifiableProperties.getString("storeId", "dummy"); MetricRegistry registry = new MetricRegistry(); StoreToolsMetrics metrics = new StoreToolsMetrics(registry, storeId); JmxReporter reporter = null; try { reporter = JmxReporter.forRegistry(registry).build(); reporter.start(); DumpDataTool dumpDataTool = new DumpDataTool(verifiableProperties, metrics); dumpDataTool.doOperation(); } finally { if (reporter != null) { reporter.stop(); } } }

Target:
public static void main(String args[]) throws Exception { VerifiableProperties verifiableProperties = StoreToolsUtil.getVerifiableProperties(args); MetricRegistry registry = new MetricRegistry(); StoreToolsMetrics metrics = new StoreToolsMetrics(registry); JmxReporter reporter = null; try { reporter = JmxReporter.forRegistry(registry).build(); reporter.start(); DumpDataTool dumpDataTool = new DumpDataTool(verifiableProperties, metrics); dumpDataTool.doOperation(); } finally { if (reporter != null) { reporter.stop(); } } }
Source:
public static ICleanUpFixCore createCleanUp(CompilationUnit root, boolean addMissingMethod, boolean makeTypeAbstract, IProblemLocationCore[] problems) { Assert.isLegal(!addMissingMethod || !makeTypeAbstract); if (!addMissingMethod && !makeTypeAbstract) return null; if (problems.length == 0) return null; ArrayList<CompilationUnitRewriteOperation> operations= new ArrayList<>(); for (IProblemLocationCore problem : problems) { if (addMissingMethod) { ASTNode typeNode= getSelectedTypeNode(root, problem); if (typeNode != null && !isTypeBindingNull(typeNode)) { operations.add(new AddUnimplementedMethodsOperation(typeNode)); } } else { ASTNode typeNode= getSelectedTypeNode(root, problem); if (typeNode instanceof TypeDeclaration) { operations.add(new MakeTypeAbstractOperation((TypeDeclaration) typeNode)); } } } if (operations.size() == 0) return null; String label; if (addMissingMethod) { label= CorrectionMessages.UnimplementedMethodsCorrectionProposal_description; } else { label= CorrectionMessages.UnimplementedCodeFix_MakeAbstractFix_label; } return new UnimplementedCodeFixCore(label, root, operations.toArray(new CompilationUnitRewriteOperation[operations.size()])); }

Target:
public static ICleanUpFixCore createCleanUp(CompilationUnit root, boolean addMissingMethod, boolean makeTypeAbstract, IProblemLocationCore[] problems) { Assert.isLegal(!addMissingMethod || !makeTypeAbstract); if (!addMissingMethod && !makeTypeAbstract) return null; if (problems.length == 0) return null; ArrayList<CompilationUnitRewriteOperation> operations= new ArrayList<>(); for (IProblemLocationCore problem : problems) { if (addMissingMethod) { ASTNode typeNode= getSelectedTypeNode(root, problem); if (typeNode != null && !isTypeBindingNull(typeNode)) { operations.add(new AddUnimplementedMethodsOperation(typeNode)); } } else { ASTNode typeNode= getSelectedTypeNode(root, problem); if (typeNode instanceof TypeDeclaration) { operations.add(new MakeTypeAbstractOperation((TypeDeclaration) typeNode)); } } } if (operations.isEmpty()) return null; String label; if (addMissingMethod) { label= CorrectionMessages.UnimplementedMethodsCorrectionProposal_description; } else { label= CorrectionMessages.UnimplementedCodeFix_MakeAbstractFix_label; } return new UnimplementedCodeFixCore(label, root, operations.toArray(new CompilationUnitRewriteOperation[operations.size()])); }
Source:
public CsvLoader(Map<String, String> config) { CSVFormat format = CSVFormat.EXCEL; if (config.containsKey("delimiter")) { format = format.withDelimiter(config.get("delimiter").charAt(0)); } if (config.containsKey("quoteChar")) { format = format.withQuote(config.get("quoteChar").charAt(0)); } if (config.containsKey("quoteMode")) { format = format.withQuoteMode(QuoteMode.valueOf(config.get("quoteMode"))); } if (config.containsKey("commentStart")) { format = format.withCommentMarker(config.get("commentStart").charAt(0)); } if (config.containsKey("escape")) { format = format.withCommentMarker(config.get("escape").charAt(0)); } if (config.containsKey("ignoreSurroundingSpaces")) { format = format.withIgnoreSurroundingSpaces(config.get("ignoreSurroundingSpaces").equals("true")); } if (config.containsKey("ignoreEmptyLines")) { format = format.withIgnoreEmptyLines(config.get("ignoreEmptyLines").equals("true")); } if (config.containsKey("recordSeparator")) { format = format.withRecordSeparator(config.get("recordSeparator")); } if (config.containsKey("nullString")) { format = format.withNullString(config.get("nullString")); } if (config.containsKey("trim")) { format = format.withTrim(config.get("trim").equals("true")); } if (config.containsKey("trailingDelimiter")) { format = format.withTrailingDelimiter(config.get("trailingDelimiter").equals("true")); } this.format = format .withAllowMissingColumnNames() .withHeader(); }

Target:
public CsvLoader(Map<String, String> config) { CSVFormat format = CSVFormat.EXCEL; if (config.containsKey("delimiter")) { format = format.withDelimiter(onlyChar(config, "delimiter")); } if (config.containsKey("quoteChar")) { format = format.withQuote(onlyChar(config, "quoteChar")); } if (config.containsKey("quoteMode")) { format = format.withQuoteMode(QuoteMode.valueOf(config.get("quoteMode"))); } if (config.containsKey("commentStart")) { format = format.withCommentMarker(onlyChar(config, "commentStart")); } if (config.containsKey("escape")) { format = format.withCommentMarker(onlyChar(config, "escape")); } if (config.containsKey("ignoreSurroundingSpaces")) { format = format.withIgnoreSurroundingSpaces(config.get("ignoreSurroundingSpaces").equals("true")); } if (config.containsKey("ignoreEmptyLines")) { format = format.withIgnoreEmptyLines(config.get("ignoreEmptyLines").equals("true")); } if (config.containsKey("recordSeparator")) { format = format.withRecordSeparator(config.get("recordSeparator")); } if (config.containsKey("nullString")) { format = format.withNullString(config.get("nullString")); } if (config.containsKey("trim")) { format = format.withTrim(config.get("trim").equals("true")); } if (config.containsKey("trailingDelimiter")) { format = format.withTrailingDelimiter(config.get("trailingDelimiter").equals("true")); } this.format = format .withAllowMissingColumnNames() .withHeader(); }
Source:
public synchronized void stop() { if (driver != null) { driver.stop(); } }

Target:
public synchronized void stop() { if (driver != null) { driver.stop(); } else { LOGGER.warning("Unable to stop Mesos driver: driver is null."); } }
Source:
void addVolume(FsVolumeReference ref) { FsVolumeImpl volume = (FsVolumeImpl) ref.getVolume(); volumes.add(volume); if (enableSameDiskTiering && (volume.getStorageType() == StorageType.DISK || volume.getStorageType() == StorageType.ARCHIVE)) { mountVolumeMap.addVolume(volume); } if (blockScanner != null) { blockScanner.addVolumeScanner(ref); } else { IOUtils.cleanup(null, ref); } removeVolumeFailureInfo(volume.getStorageLocation()); FsDatasetImpl.LOG.info("Added new volume: " + volume.getStorageID()); }

Target:
void addVolume(FsVolumeReference ref) { FsVolumeImpl volume = (FsVolumeImpl) ref.getVolume(); volumes.add(volume); if (isSameDiskTieringApplied(volume)) { mountVolumeMap.addVolume(volume); } if (blockScanner != null) { blockScanner.addVolumeScanner(ref); } else { IOUtils.cleanup(null, ref); } removeVolumeFailureInfo(volume.getStorageLocation()); FsDatasetImpl.LOG.info("Added new volume: " + volume.getStorageID()); }
Source:
public List<ChePlugin> execute() throws InfrastructureException { Span tracingSpan = tracer.buildSpan(SPAN_NAME).start(); TracingUtil.setWorkspaceId(tracingSpan, workspaceId); try { volumesStrategy.prepare( brokerEnvironment, workspaceId, startSynchronizer.getStartTimeoutMillis()); } catch (InfrastructureException e) { TracingUtil.setErrorStatus(tracingSpan, e); tracingSpan.finish(); throw e; } tracingSpan.finish(); return nextPhase.execute(); }

Target:
public List<ChePlugin> execute() throws InfrastructureException { Span tracingSpan = tracer.buildSpan(PREPARE_STORAGE_PHASE).start(); TracingTags.WORKSPACE_ID.set(tracingSpan, workspaceId); try { volumesStrategy.prepare( brokerEnvironment, workspaceId, startSynchronizer.getStartTimeoutMillis()); } catch (InfrastructureException e) { TracingTags.setErrorStatus(tracingSpan, e); throw e; } finally { tracingSpan.finish(); } return nextPhase.execute(); }
Source:
protected void generateComponent() { String normalizationProcessorId = addNormalizationProcessorBuilder(); String boltId = "normalizationBolt" + UUID_FOR_COMPONENTS; String boltClassName = "com.hortonworks.iotas.streams.layout.component.impl.normalization.NormalizationBolt"; List boltConstructorArgs = new ArrayList(); Map ref = getRefYaml(normalizationProcessorId); boltConstructorArgs.add(ref); component = createComponent(boltId, boltClassName, null, boltConstructorArgs, null); addParallelismToComponent(); }

Target:
protected void generateComponent() { String normalizationProcessorId = addNormalizationProcessorBuilder(); String boltId = "normalizationBolt" + UUID_FOR_COMPONENTS; String boltClassName = "com.hortonworks.iotas.streams.runtime.storm.bolt.normalization.NormalizationBolt"; List boltConstructorArgs = new ArrayList(); Map ref = getRefYaml(normalizationProcessorId); boltConstructorArgs.add(ref); component = createComponent(boltId, boltClassName, null, boltConstructorArgs, null); addParallelismToComponent(); }
Source:
private boolean transitionState(ExecutionState currentState, ExecutionState targetState, Throwable error) { if (currentState.isTerminal()) { throw new IllegalStateException("Cannot leave terminal state " + currentState + " to transition to " + targetState + '.'); } if (state == currentState) { state = targetState; markTimestamp(targetState); if (error == null) { LOG.info("{} ({}) switched from to {}.", getVertex().getTaskNameWithSubtaskIndex(), getAttemptId(), currentState, targetState); } else { if (LOG.isInfoEnabled()) { final String locationInformation = getAssignedResource() != null ? getAssignedResource().toString() : "not deployed"; LOG.info( "{} ({}) switched from to on {}.", getVertex().getTaskNameWithSubtaskIndex(), getAttemptId(), currentState, targetState, locationInformation, error); } } getExecutionGraph().getExecutionStateUpdateListener().onStateUpdate(attemptId, state); if (targetState.isTerminal()) { terminalStateFuture.complete(targetState); } try { vertex.notifyStateTransition(this, targetState, error); } catch (Throwable t) { LOG.error("Error while notifying execution graph of execution state transition.", t); } return true; } else { return false; } }

Target:
private boolean transitionState(ExecutionState currentState, ExecutionState targetState, Throwable error) { if (currentState.isTerminal()) { throw new IllegalStateException("Cannot leave terminal state " + currentState + " to transition to " + targetState + '.'); } if (state == currentState) { state = targetState; markTimestamp(targetState); if (error == null) { LOG.info("{} ({}) switched from to {}.", getVertex().getTaskNameWithSubtaskIndex(), getAttemptId(), currentState, targetState); } else { if (LOG.isInfoEnabled()) { final String locationInformation = getAssignedResource() != null ? getAssignedResource().toString() : "not deployed"; LOG.info( "{} ({}) switched from to on {}.", getVertex().getTaskNameWithSubtaskIndex(), getAttemptId(), currentState, targetState, locationInformation, error); } } if (targetState.isTerminal()) { terminalStateFuture.complete(targetState); } try { vertex.notifyStateTransition(this, targetState, error); } catch (Throwable t) { LOG.error("Error while notifying execution graph of execution state transition.", t); } return true; } else { return false; } }
Source:
Mono<KeyPhrasesCollection> extractKeyPhrasesSingleText(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); final TextDocumentInput textDocumentInput = new TextDocumentInput("0", document); textDocumentInput.setLanguage(language); return extractKeyPhrasesWithResponse(Collections.singletonList(textDocumentInput), null) .map(keyPhraseResultCollection -> { for (ExtractKeyPhraseResult keyPhraseResult : keyPhraseResultCollection.getValue()) { if (keyPhraseResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(keyPhraseResult.getError())); } return new KeyPhrasesCollection(keyPhraseResult.getKeyPhrases(), keyPhraseResult.getKeyPhrases().getWarnings()); } throw logger.logExceptionAsError( new TextAnalyticsException("None key Phrases extracted.", TextAnalyticsErrorCode.fromString("NoneKeyPhrasesExtracted").toString(), null)); }); } catch (RuntimeException ex) { return monoError(logger, ex); } }

Target:
Mono<KeyPhrasesCollection> extractKeyPhrasesSingleText(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); final TextDocumentInput textDocumentInput = new TextDocumentInput("0", document); textDocumentInput.setLanguage(language); return extractKeyPhrasesWithResponse(Collections.singletonList(textDocumentInput), null) .map(resultCollectionResponse -> { KeyPhrasesCollection keyPhrasesCollection = null; for (ExtractKeyPhraseResult keyPhraseResult : resultCollectionResponse.getValue()) { if (keyPhraseResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(keyPhraseResult.getError())); } keyPhrasesCollection = new KeyPhrasesCollection(keyPhraseResult.getKeyPhrases(), keyPhraseResult.getKeyPhrases().getWarnings()); } return keyPhrasesCollection; }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
Source:
private void registerGlueCodeScope(ConfigurableApplicationContext context) { do { synchronized (context) { context.getBeanFactory().registerScope(SCOPE_CUCUMBER_GLUE, new GlueCodeScope()); context = (ConfigurableApplicationContext) context.getParent(); } } while (context != null); }

Target:
private void registerGlueCodeScope(ConfigurableApplicationContext context) { do { context.getBeanFactory().registerScope(SCOPE_CUCUMBER_GLUE, new GlueCodeScope()); context = (ConfigurableApplicationContext) context.getParent(); } while (context != null); }
Source:
public CallStatus run() { RequestMetrics.Context context = metrics.startLockRequest(getLockCommandName(), domain); LOGGER.debug("run: domain={}, resource={}, caller={}", domain, resource, caller); Error.reset(); Error.push("rest"); Error.push(getClass().getSimpleName()); Error.push(resource); try { Locking locking = RestConfiguration.getFactory().getLocking(domain); JsonNode result = runLockCommand(locking); ObjectNode o = NODE_FACTORY.objectNode(); o.set("result", result); return new CallStatus(new SimpleJsonObject(o)); } catch (Error e) { context.markRequestException(e); LOGGER.error("failure: {}", e); return new CallStatus(e); } catch (Exception e) { context.markRequestException(e); LOGGER.error("failure: {}", e); return new CallStatus(Error.get(RestCrudConstants.ERR_REST_ERROR, e.toString())); } finally { context.endRequestMonitoring(); } }

Target:
public CallStatus run() { RequestMetrics.Context metricCtx = metrics.startLockRequest(getLockCommandName(), domain); LOGGER.debug("run: domain={}, resource={}, caller={}", domain, resource, caller); Error.reset(); Error.push("rest"); Error.push(getClass().getSimpleName()); Error.push(resource); try { Locking locking = RestConfiguration.getFactory().getLocking(domain); JsonNode result = runLockCommand(locking); ObjectNode o = NODE_FACTORY.objectNode(); o.set("result", result); return new CallStatus(new SimpleJsonObject(o)); } catch (Error e) { metricCtx.markRequestException(e); LOGGER.error("failure: {}", e); return new CallStatus(e); } catch (Exception e) { Error error = Error.get(RestCrudConstants.ERR_REST_ERROR, e.toString()); metricCtx.markRequestException(error); LOGGER.error("failure: {}", e); return new CallStatus(error); } finally { metricCtx.endRequestMonitoring(); } }
Source:
public static <T extends AbstractModelObject> List<ObjectComponentDescriptor<T>> for_(T item) { return Jenkins.get().getExtensionList(ObjectComponent.class).stream() .filter(component -> component.isApplicable(item.getClass())) .map(component -> ((ObjectComponent<T>) component)) .filter(component -> component.isApplicable(item)) .map(ObjectComponent::getDescriptor) .collect(Collectors.toList()); }

Target:
public static <T extends AbstractModelObject> List<ObjectComponentDescriptor<T>> for_(T item) { return allInstances(item).stream() .map(ObjectComponent::getDescriptor) .collect(Collectors.toList()); }
Source:
public void biteEntity(int entityId) { Entity e = player.getEntityWorld().getEntityByID(entityId); if (player.isSpectator()) { VampirismMod.log.w(TAG, "Player can't bite in spectator mode"); return; } if (e != null && e instanceof EntityLivingBase) { if (e.getDistance(player) <= player.getEntityAttribute(EntityPlayer.REACH_DISTANCE).getAttributeValue() + 1) { if (determineBiteType(((EntityLivingBase) e)) == BITE_TYPE.ATTACK) { biteEntity(((EntityLivingBase) e)); } else { victim = e.getEntityId(); PotionEffect effect = new PotionEffect(Potion.getPotionFromResourceLocation("slowness"), 20, 7); ((EntityLivingBase) e).addPotionEffect(effect); PotionEffect feedingEffect = new PotionEffect(PotionFeeding.POTION, 25); player.addPotionEffect(feedingEffect); } } else { VampirismMod.log.w(TAG, "Entity sent by client is not in reach " + entityId); } } }

Target:
public void biteEntity(int entityId) { Entity e = player.getEntityWorld().getEntityByID(entityId); if (player.isSpectator()) { VampirismMod.log.w(TAG, "Player can't bite in spectator mode"); return; } if (e != null && e instanceof EntityLivingBase) { if (e.getDistance(player) <= player.getEntityAttribute(EntityPlayer.REACH_DISTANCE).getAttributeValue() + 1) { feed_victim_bite_type = determineBiteType((EntityLivingBase) e); if (feed_victim_bite_type == BITE_TYPE.ATTACK || feed_victim_bite_type == BITE_TYPE.ATTACK_HUNTER) { biteAttack((EntityLivingBase) e, feed_victim_bite_type == BITE_TYPE.ATTACK_HUNTER); } else if (feed_victim_bite_type == BITE_TYPE.NONE) { return; } else { if (feed_victim == -1) feedBiteTickCounter = 0; feed_victim = e.getEntityId(); PotionEffect effect = new PotionEffect(Potion.getPotionById(2), 20, 7, false, false); ((EntityLivingBase) e).addPotionEffect(effect); PotionEffect feedingEffect = new PotionEffect(Potion.getPotionById(2), 25, 1, false, false); player.addPotionEffect(feedingEffect); NBTTagCompound nbt = new NBTTagCompound(); nbt.setInteger(KEY_VICTIM_ID, feed_victim); sync(nbt, true); } } else { VampirismMod.log.w(TAG, "Entity sent by client is not in reach " + entityId); } } }
Source:
public void shouldSaveEncounterTypeWhenEncounterTypesAreNotLocked() throws Exception { EncounterService es = Context.getEncounterService(); EncounterTypeFormController controller = (EncounterTypeFormController) applicationContext .getBean("encounterTypeForm"); controller.setApplicationContext(applicationContext); controller.setSuccessView("index.htm"); controller.setFormView("EncounterType.form"); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/admin/encounters/encounterType.form?encounterTypeId=1"); request.setSession(new MockHttpSession(null)); HttpServletResponse response = new MockHttpServletResponse(); controller.handleRequest(request, response); request.setMethod("POST"); request.addParameter("action", "Save EncounterType"); ModelAndView mav = controller.handleRequest(request, response); Assert.assertNotSame("The save attempt should have passed!", "index.htm", mav.getViewName()); Assert.assertNotNull(es.getEncounterType(1)); }

Target:
public void shouldSaveEncounterTypeWhenEncounterTypesAreNotLocked() throws Exception { EncounterService es = Context.getEncounterService(); EncounterTypeFormController controller = (EncounterTypeFormController) applicationContext .getBean("encounterTypeForm"); controller.setApplicationContext(applicationContext); controller.setSuccessView("index.htm"); controller.setFormView("EncounterType.form"); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/admin/encounters/encounterType.form?encounterTypeId=1"); request.setSession(new MockHttpSession(null)); HttpServletResponse response = new MockHttpServletResponse(); controller.handleRequest(request, response); request.setMethod("POST"); request.addParameter("action", "Save EncounterType"); ModelAndView mav = controller.handleRequest(request, response); Assert.assertSame(controller.getFormView(), mav.getViewName()); Assert.assertNotEquals("The save attempt should have passed!", "index.htm", mav.getViewName()); Assert.assertNotNull(es.getEncounterType(1)); }
Source:
public FormulaDto update(final FormulaDto formulaDto) { final Formula formula = this.daoFactory.getFormulaDAO().getById(formulaDto.getFormulaId()); formula.setInputs(FormulaUtils.convertFormulaVariableListToCVTermList(formulaDto.getInputs())); formula.setDefinition(formulaDto.getDefinition()); this.daoFactory.getFormulaDAO().update(formula); return FormulaUtils.convertToFormulaDto(formula); }

Target:
public FormulaDto update(final FormulaDto formulaDto) { final Formula formula = FormulaUtils.convertToFormula(formulaDto); this.daoFactory.getFormulaDAO().merge(formula); return formulaDto; }
Source:
public DocumentWriteOperation makeDocumentWriteOperation(UriMaker uriMaker, long count, T handle) { if (handle == null) { throw new IllegalArgumentException("Handle cannot be null"); } String uri = uriMaker.makeUri((int) count, (JSONWriteHandle) handle); return new DocumentWriteOperationImpl( DocumentWriteOperation.OperationType.DOCUMENT_WRITE, uri, null, handle ); }

Target:
public DocumentWriteOperation makeDocumentWriteOperation(UriMaker uriMaker, long count, T handle) { if (handle == null) { throw new IllegalArgumentException("Handle cannot be null"); } String uri = uriMaker.makeUri(count, (JSONWriteHandle) handle); return new DocumentWriteOperationImpl( DocumentWriteOperation.OperationType.DOCUMENT_WRITE, uri, null, handle ); }
Source:
private Object readResolve() { if (isLeapDay() || isYearDay()) { return InternationalFixedDate.of(prolepticYear, isLeapDay(), isYearDay()); } return InternationalFixedDate.of(prolepticYear, getMonth(), getDayOfMonth()); }

Target:
private Object readResolve() { return InternationalFixedDate.of(this.prolepticYear, this.month, this.day); }
Source:
public void checkAttributeValue(PerunSessionImpl sess, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException { List<String> pshell = (List<String>) attribute.getValue(); if (pshell != null){ for(String shell : pshell){ if(shell != null){ if(shell.isEmpty()){ throw new WrongAttributeValueException("shell cannot be empty"); }else{ sess.getPerunBl().getModulesUtilsBl().checkFormatOfShell(shell, attribute); } }else{ throw new WrongAttributeValueException("shell cannot be null"); } } } }

Target:
public void checkAttributeValue(PerunSessionImpl sess, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException { List<String> pshell = (List<String>) attribute.getValue(); if (pshell != null){ for(String shell : pshell){ if(shell != null){ if(shell.isEmpty()){ throw new WrongAttributeValueException("shell cannot be empty"); }else{ sess.getPerunBl().getModulesUtilsBl().checkFormatOfShell(shell, attribute); } }else{ throw new WrongAttributeValueException(attribute, user, "shell cannot be empty"); } } } }
Source:
public static void setVisibility (boolean visible, Context context) { PreferenceUtils.setValue(context, PreferenceUtils.KEY_SETTING_VISIBILITY, String.valueOf(visible ? 0 : 1)); try { MainApplication.visible = visible; ServerAPI.setVisibility(context, visible); if (visible == false) { LocationService.stop(context); } else { LocationService.start(context); } } catch (Exception ex) { ex.printStackTrace(); } }

Target:
public static void setVisibility (boolean visible, Context context) { PreferenceUtils.setValue(context, PreferenceUtils.KEY_SETTING_VISIBILITY, String.valueOf(visible ? 0 : 1)); try { MainApplication.visible = visible; ServerAPI.setVisibility(context, visible); if (visible == false) { LocationService.stop(context); } else { LocationService.start(context); } } catch (Exception ex) { Log.e(TAG, "Could not set visibility:" + ex.getMessage()); } }