auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void writeIntBE(int val, byte[] buffer, int offset) { buffer[offset++] = (byte) (val >>> 24); buffer[offset++] = (byte) (val >>> 16); buffer[offset++] = (byte) (val >>> 8); buffer[offset] = (byte) val; }

Target:
public static void writeIntBE(int val, byte[] buffer, int offset) { buffer[offset] = (byte) (val >>> 24); buffer[offset + 1] = (byte) (val >>> 16); buffer[offset + 2] = (byte) (val >>> 8); buffer[offset + 3] = (byte) val; }
Source:
public Map<String, Object> parse(String input) { Map<String, Object> map = new LinkedHashMap<>(); Map<String, Object> document = (Map<String, Object>) Configuration.defaultConfiguration().jsonProvider().parse(input); for (Map.Entry<String, Pair<FieldType, JsonPath>> entry : fieldPathMap.entrySet()) { String fieldName = entry.getKey(); Pair<FieldType, JsonPath> pair = entry.getValue(); JsonPath path = pair.rhs; Object parsedVal; if (pair.lhs == FieldType.ROOT) { parsedVal = document.get(fieldName); } else { parsedVal = path.read(document); } map.put(fieldName, parsedVal); } if(useFieldDiscovery) { discoverFields(map, document); } return map; }

Target:
public Map<String, Object> parse(String input) { try { Map<String, Object> map = new LinkedHashMap<>(); Map<String, Object> document = mapper.readValue(input, new TypeReference<Map<String, Object>>() {}); for (Map.Entry<String, Pair<FieldType, JsonPath>> entry : fieldPathMap.entrySet()) { String fieldName = entry.getKey(); Pair<FieldType, JsonPath> pair = entry.getValue(); JsonPath path = pair.rhs; Object parsedVal; if (pair.lhs == FieldType.ROOT) { parsedVal = document.get(fieldName); } else { parsedVal = path.read(document, jsonPathConfig); } if (parsedVal == null) { continue; } parsedVal = valueConversionFunction(parsedVal); map.put(fieldName, parsedVal); } if (useFieldDiscovery) { discoverFields(map, document); } return map; } catch (Exception e) { throw new ParseException(e, "Unable to parse row [%s]", input); } }
Source:
void generateKeyCorrectKeyLengthWithTruncateModifierAndUnicode() { BibEntry bibEntry = new BibEntry(); bibEntry.setField(StandardField.AUTHOR, "Gödel, Kurt"); assertEquals(2, generateKey(bibEntry, "[auth:truncate2").length()); }

Target:
void generateKeyCorrectKeyLengthWithTruncateModifierAndUnicode() { BibEntry bibEntry = new BibEntry().withField(StandardField.AUTHOR, "Gödel, Kurt"); assertEquals(2, generateKey(bibEntry, "[auth:truncate2]").length()); }
Source:
public TableRendererV2(String packageName, Namespace namespace) { Preconditions.checkNotNull(packageName); Preconditions.checkNotNull(namespace); this.packageName = packageName; this.namespace = namespace; }

Target:
public TableRendererV2(String packageName, Namespace namespace) { this.packageName = checkNotNull(packageName); this.namespace = checkNotNull(namespace); }
Source:
public int runCmd(CommandLine cmdLine) throws Exception { ZooKeeper zk = null; LedgerUnderreplicationManager underreplicationManager = null; try { zk = ZooKeeperClient.newBuilder() .connectString(bkConf.getZkServers()) .sessionTimeoutMs(bkConf.getZkTimeout()) .build(); LedgerManagerFactory ledgerManagerFactory = LedgerManagerFactory.newLedgerManagerFactory(bkConf, zk); underreplicationManager = ledgerManagerFactory.newLedgerUnderreplicationManager(); if (!underreplicationManager.isLedgerReplicationEnabled()) { LOG.error("Autorecovery is disabled. So giving up!"); return -1; } BookieSocketAddress auditorId = AuditorElector.getCurrentAuditor(bkConf, zk); if (auditorId == null) { LOG.error("No auditor elected, though Autorecovery is enabled. So giving up."); return -1; } int previousLostBookieRecoveryDelayValue = underreplicationManager.getLostBookieRecoveryDelay(); LOG.info("Resetting LostBookieRecoveryDelay value: {}, to kickstart audit task", previousLostBookieRecoveryDelayValue); underreplicationManager.setLostBookieRecoveryDelay(previousLostBookieRecoveryDelayValue); } finally { if (zk != null) { zk.close(); } } return 0; }

Target:
public int runCmd(CommandLine cmdLine) throws Exception { ClientConfiguration adminConf = new ClientConfiguration(bkConf); BookKeeperAdmin admin = new BookKeeperAdmin(adminConf); try { admin.triggerAudit(); } finally { if (admin != null) { admin.close(); } } return 0; }
Source:
private Image getStatusIcon(IRepositoryElement element) { if (element instanceof IRepositoryQuery) { RepositoryQuery query = (RepositoryQuery) element; boolean showError = false; Throwable exception = query.getStatus().getException(); showError = (query.getLastSynchronizedTimeStamp().equals("<never>") && ((RepositoryStatus.ERROR_IO == query.getStatus().getCode() && exception != null && exception instanceof SocketTimeoutException) || (RepositoryStatus.ERROR_NETWORK) == query.getStatus().getCode() && query.getStatus().getMessage().equals("Http error: Internal Server Error"))); if (showError) { return CommonImages.getImage(CommonImages.ERROR); } } return CommonImages.getImage(CommonImages.WARNING); }

Target:
private Image getStatusIcon(IRepositoryElement element) { if (element instanceof RepositoryQuery) { return CommonImages.getImage(TasksUiInternal.getIconFromStatusOfQuery((RepositoryQuery) element)); } return CommonImages.getImage(CommonImages.WARNING); }
Source:
public void shouldFindUpdatedNodeInInLabelScan() throws Exception { Node node = createNode( "label" ); try ( org.neo4j.internal.kernel.api.Transaction tx = session.beginTransaction(); NodeLabelIndexCursor cursor = cursors.allocateNodeLabelIndexCursor() ) { tx.dataWrite().nodeAddLabel( node.node, node.labels[0] ); tx.dataRead().nodeLabelScan( node.labels[0], cursor ); assertTrue( cursor.next() ); assertEquals( node.node, cursor.nodeReference() ); } }

Target:
public void shouldFindUpdatedNodeInInLabelScan() throws Exception { Node node = createNode( ); try ( org.neo4j.internal.kernel.api.Transaction tx = session.beginTransaction(); NodeLabelIndexCursor cursor = cursors.allocateNodeLabelIndexCursor() ) { int label = tx.tokenWrite().labelGetOrCreateForName( "label" ); tx.dataWrite().nodeAddLabel( node.node, label ); tx.dataRead().nodeLabelScan( label, cursor ); assertTrue( cursor.next() ); assertEquals( node.node, cursor.nodeReference() ); } }
Source:
public Map<String, Fingerprint> loadFingerprints(final File fingerprintFile, final String specificSample) { final VCFFileReader reader = new VCFFileReader(fingerprintFile, false); SequenceUtil.assertSequenceDictionariesEqual(this.haplotypes.getHeader().getSequenceDictionary(), VCFFileReader.getSequenceDictionary(fingerprintFile)); if (isQueryable(fingerprintFile)) { reader.close(); return loadFingerprintsFromIndexedVcf(fingerprintFile, specificSample); } else { reader.close(); log.warn("Couldn't find index for file " + fingerprintFile + " going to read through it all."); return loadFingerprintsFromNonIndexedVcf(fingerprintFile, specificSample); } }

Target:
public Map<String, Fingerprint> loadFingerprints(final File fingerprintFile, final String specificSample) { SequenceUtil.assertSequenceDictionariesEqual(this.haplotypes.getHeader().getSequenceDictionary(), VCFFileReader.getSequenceDictionary(fingerprintFile)); if (isQueryable(fingerprintFile)) { return loadFingerprintsFromIndexedVcf(fingerprintFile, specificSample); } else { log.warn("Couldn't find index for file " + fingerprintFile + " going to read through it all."); return loadFingerprintsFromNonIndexedVcf(fingerprintFile, specificSample); } }
Source:
private void initOriginalFromBuffer(ByteBuffer buf) throws IOException { assert(false); setProcName(SerializationHelper.getVarbinary(buf)); clientHandle = buf.getLong(); serializedParams = buf.slice(); final ByteBuffer duplicate = serializedParams.duplicate(); params = new FutureTask<ParameterSet>(new Callable<ParameterSet>() { @Override public ParameterSet call() throws Exception { return ParameterSet.fromByteBuffer(duplicate); } }); }

Target:
private void initOriginalFromBuffer(ByteBuffer buf) throws IOException { byte[] procNameBytes = SerializationHelper.getVarbinary(buf); if (procNameBytes == null) { throw new IOException("Procedure name cannot be null in invocation deserialization."); } if (procNameBytes.length == 0) { throw new IOException("Procedure name cannot be length zero in invocation deserialization."); } setProcName(procNameBytes); clientHandle = buf.getLong(); serializedParams = buf.slice(); final ByteBuffer duplicate = serializedParams.duplicate(); params = new FutureTask<ParameterSet>(new Callable<ParameterSet>() { @Override public ParameterSet call() throws Exception { return ParameterSet.fromByteBuffer(duplicate); } }); }
Source:
public void testBackoffTimeCapped() { VerificationContext verificationContext = new VerificationContext(); RetryDriver retryDriver = new RetryDriver<>( new RetryConfig() .setMaxAttempts(5) .setMinBackoffDelay(new Duration(10, MILLISECONDS)) .setMaxBackoffDelay(new Duration(100, MILLISECONDS)) .setScaleFactor(1000), QueryException::isRetryable, QueryException.class, verificationContext::addException); retryDriver.run("test", new MockOperation(5, RETRYABLE_EXCEPTION)); }

Target:
public void testBackoffTimeCapped() { RetryDriver retryDriver = new RetryDriver<>( new RetryConfig() .setMaxAttempts(5) .setMinBackoffDelay(new Duration(10, MILLISECONDS)) .setMaxBackoffDelay(new Duration(100, MILLISECONDS)) .setScaleFactor(1000), QueryException::isRetryable, QueryException.class, verificationContext::addException); retryDriver.run("test", new MockOperation(5, RETRYABLE_EXCEPTION)); }
Source:
protected abstract void internalUpdate(TransactionRecord transactionId) throws OseeCoreException; protected abstract void internalClearDirtyState(); protected abstract void internalOnRollBack() throws OseeCoreException; protected abstract int createGammaId() throws OseeCoreException; protected abstract ApplicabilityId getApplicabilityId() throws OseeCoreException; protected abstract void internalAddToEvents(ArtifactEvent artifactEvent) throws OseeCoreException; protected int getNextGammaIdFromSequence() { return (int) ConnectionHandler.getNextSequence(GAMMA_ID_SEQ, true); }

Target:
protected abstract void internalUpdate(TransactionRecord transactionId) throws OseeCoreException; protected abstract void internalClearDirtyState(); protected abstract void internalOnRollBack() throws OseeCoreException; protected abstract int createGammaId() throws OseeCoreException; protected abstract ApplicabilityId getApplicabilityId(); protected abstract void internalAddToEvents(ArtifactEvent artifactEvent) throws OseeCoreException; protected int getNextGammaIdFromSequence() { return (int) ConnectionHandler.getNextSequence(GAMMA_ID_SEQ, true); }
Source:
public AlertQuery createQuery(final Organization organization) { assertIsOpen(); LOGGER.debug().setMessage("Preparing query").log(); return new DefaultAlertQuery(this, organization); }

Target:
public AlertQuery createQuery(final Organization organization) { assertIsOpen(); LOGGER.debug() .setMessage("Preparing query") .addData("organization", organization) .log(); return new DefaultAlertQuery(this, organization); }
Source:
private static String loadVersion() { InputStream in = Version.class.getResourceAsStream("/gerrit-common/Version"); if (in == null) { return null; } try { BufferedReader r = new BufferedReader(new InputStreamReader(in, "UTF-8")); try { String vs = r.readLine(); if (vs != null && vs.startsWith("v")) { vs = vs.substring(1); } if (vs != null && vs.isEmpty()) { vs = null; } return vs; } finally { r.close(); } } catch (IOException e) { return null; } }

Target:
private static String loadVersion() { InputStream in = Version.class.getResourceAsStream("Version"); if (in == null) { return null; } try { BufferedReader r = new BufferedReader(new InputStreamReader(in, "UTF-8")); try { String vs = r.readLine(); if (vs != null && vs.startsWith("v")) { vs = vs.substring(1); } if (vs != null && vs.isEmpty()) { vs = null; } return vs; } finally { r.close(); } } catch (IOException e) { return null; } }
Source:
public void testApplicationBinding_withPrevious_noImportAdded() throws IllegalAccessException, InterruptedException { AgentMessageProcessor processor = (AgentMessageProcessor) this.agent.getMessagingClient().getMessageProcessor(); TestApplicationTemplate app = new TestApplicationTemplate(); processor.scopedInstance = app.getTomcatVm(); MsgCmdChangeBinding msg = new MsgCmdChangeBinding( "ext", new HashSet<>( Arrays.asList( "demo1" ))); processor.processMessage( msg ); Assert.assertEquals( 1, processor.applicationBindings.size()); Assert.assertEquals( 0, processor.applicationNameToExternalExports.size()); msg = new MsgCmdChangeBinding( "ext", new HashSet<>( Arrays.asList( "demo2" ))); processor.processMessage( msg ); Assert.assertEquals( 1, processor.applicationBindings.size()); Assert.assertEquals( 1, processor.applicationBindings.get( "ext" ).size()); Assert.assertTrue( processor.applicationBindings.get( "ext" ).contains( "demo2" )); Assert.assertEquals( 0, processor.applicationNameToExternalExports.size()); }

Target:
public void testApplicationBinding_withPrevious_noImportAdded() throws IllegalAccessException { AgentMessageProcessor processor = (AgentMessageProcessor) this.agent.getMessagingClient().getMessageProcessor(); TestApplicationTemplate app = new TestApplicationTemplate(); processor.scopedInstance = app.getTomcatVm(); MsgCmdChangeBinding msg = new MsgCmdChangeBinding( "ext", new HashSet<>( Arrays.asList( "demo1" ))); processor.processMessage( msg ); Assert.assertEquals( 1, processor.applicationBindings.size()); Assert.assertEquals( 0, processor.applicationNameToExternalExports.size()); msg = new MsgCmdChangeBinding( "ext", new HashSet<>( Arrays.asList( "demo2" ))); processor.processMessage( msg ); Assert.assertEquals( 1, processor.applicationBindings.size()); Assert.assertEquals( 1, processor.applicationBindings.get( "ext" ).size()); Assert.assertTrue( processor.applicationBindings.get( "ext" ).contains( "demo2" )); Assert.assertEquals( 0, processor.applicationNameToExternalExports.size()); }
Source:
private void testAreas(TreeNode rootNode) { Rectangle2D rootBounds = rootNode.getBounds(); if (rootNode instanceof InnerNode) { InnerNode innerNode = (InnerNode) rootNode; double[] rootDimensions = new double[] { rootBounds.getX(), rootBounds.getY(), rootBounds.getWidth(), rootBounds.getHeight() }; Rectangle2D union = Node.union(innerNode.getChildren()); double[] unionDimensions = new double[] {union.getX(), union.getY(), union.getWidth(), union.getHeight()}; assertWithMessage( "The compared bounds are not close enough: rootBounds: %s, unionBounds: %s", rootBounds, union) .that(rootDimensions) .usingTolerance(1.0E-4) .equals(unionDimensions); } for (TreeNode rt : rootNode.getChildren()) { testAreas(rt); } }

Target:
private void testAreas(TreeNode rootNode) { Rectangle2D rootBounds = rootNode.getBounds(); if (rootNode instanceof InnerNode) { InnerNode innerNode = (InnerNode) rootNode; Rectangle2D unionBounds = Node.union(innerNode.getChildren()); assertThat(rootBounds.getMinX()).isWithin(1.0E-3).of(unionBounds.getMinX()); assertThat(rootBounds.getMinY()).isWithin(1.0E-3).of(unionBounds.getMinY()); assertThat(rootBounds.getMaxX()).isWithin(1.0E-3).of(unionBounds.getMaxX()); assertThat(rootBounds.getMaxY()).isWithin(1.0E-3).of(unionBounds.getMaxY()); } for (TreeNode rt : rootNode.getChildren()) { testAreas(rt); } }
Source:
private boolean isNotAllowed(String parameterString) { return (allowedValues.contains(parameterString)); }

Target:
private boolean isNotAllowed(String parameterString) { return !(ALLOWED_VALUES.contains(parameterString.toUpperCase())); }
Source:
public float getBlockLiquidHeight(World world, BlockPos pos, IBlockState state, Material material) { return getFilledPercentage(world, pos); }

Target:
public float getBlockLiquidHeight(World world, BlockPos pos, IBlockState state, Material material) { float filled = getFilledPercentage(world, pos); return Math.max(filled, 0); }
Source:
public boolean hasEditedBySection() { try { return post.findElement(By.cssSelector(".post-edited-by-row")) .getAttribute(CLASS_ATTRIBUTE) .contains(POST_EDITED_BY_CLASS_NAME); } catch (NoSuchElementException e) { return false; } }

Target:
public boolean hasEditedBySection() { try { return post.findElement(By.cssSelector(".post-edited-by-row")) .getAttribute(CLASS_ATTRIBUTE) .contains(POST_EDITED_BY_CLASS_NAME); } catch (NoSuchElementException e) { PageObjectLogging.log("Element not found", "Edited by section not found", true); return false; } }
Source:
public static void waitUntil(IWaitCondition condition, long maxWait) { long waitStart = System.currentTimeMillis(); Display display = Display.getCurrent(); try { while (!condition.test()) { if (System.currentTimeMillis() - waitStart > maxWait) { throw new WaitTimeoutException(condition.getFailureMessage()); } if (display != null) { if (!display.readAndDispatch()) { try { Thread.sleep(UI_THREAD_SLEEP_INTERVAL_MS); } catch (final InterruptedException e) { } } display.update(); } else { try { Thread.sleep(SLEEP_INTERVAL_MS); } catch (final InterruptedException e) { } } } } catch (Exception e) { throw new WaitTimeoutException(condition.getFailureMessage() + "\n" + e.getClass().getName() + ": " + e.getMessage()); } }

Target:
public static void waitUntil(IWaitCondition condition, long maxWait) { long waitStart = System.currentTimeMillis(); Display display = Display.getCurrent(); try { while (!condition.test()) { if (System.currentTimeMillis() - waitStart > maxWait) { throw new WaitTimeoutException(condition.getFailureMessage()); } if (display != null) { if (!display.readAndDispatch()) { try { Thread.sleep(UI_THREAD_SLEEP_INTERVAL_MS); } catch (final InterruptedException e) { } } display.update(); } else { try { Thread.sleep(SLEEP_INTERVAL_MS); } catch (final InterruptedException e) { } } } } catch (Exception e) { throw new WaitTimeoutException(condition.getFailureMessage() + "\n" + e); } }
Source:
public boolean hasSecretParams() { return this.getRepository().hasSecretParams() || this.getConfiguration() .stream() .anyMatch(ConfigurationProperty::hasSecretParams); }

Target:
public boolean hasSecretParams() { return this.getRepository().hasSecretParams() || this.getConfiguration().hasSecretParams(); }
Source:
private void generateActionHttpPost(Method method) { Name name = method.getName(); buffer.addLine("def %1$s(", pythonNames.getMemberStyleName(name)); buffer.startBlock(); buffer.addLine("self,"); method.parameters() .filter(Parameter::isIn) .sorted() .forEach(this::generateFormalParameter); buffer.endBlock(); buffer.addLine("):"); buffer.startBlock(); buffer.addLine("buf = io.BytesIO()"); buffer.addLine("writer = xml.XmlWriter(buf, indent=True)"); buffer.addLine("writer.write_start('action')"); method.parameters() .filter(Parameter::isIn) .sorted() .forEach(this::generateWriteActionParameter); buffer.addLine("writer.write_end()"); buffer.addLine("writer.flush()"); buffer.addLine("body = buf.getvalue()"); buffer.addLine("writer.close()"); buffer.addLine("buf.close()"); buffer.addLine("request = http.Request("); buffer.startBlock(); buffer.addLine("method='POST',"); buffer.addLine("path='%%s/%%s' %% (self._path, '%1$s'),", getPath(name)); buffer.addLine("body=body,"); buffer.endBlock(); buffer.addLine(")"); buffer.addLine("response = self._connection.send(request)"); buffer.addLine("if response.code in [200]:"); buffer.startBlock(); buffer.addLine("return self._check_action(response)"); buffer.endBlock(); buffer.addLine("else:"); buffer.startBlock(); buffer.addLine("self._check_fault(response)"); buffer.endBlock(); buffer.endBlock(); buffer.addLine(); }

Target:
private void generateActionHttpPost(Method method) { Name name = method.getName(); buffer.addLine("def %1$s(", pythonNames.getMemberStyleName(name)); buffer.startBlock(); buffer.addLine("self,"); method.parameters() .filter(Parameter::isIn) .sorted() .forEach(this::generateFormalParameter); buffer.endBlock(); buffer.addLine("):"); buffer.startBlock(); buffer.addLine("buf = io.BytesIO()"); buffer.addLine("writer = xml.XmlWriter(buf, indent=True)"); buffer.addLine("writer.write_start('action')"); method.parameters() .filter(Parameter::isIn) .sorted() .forEach(this::generateWriteActionParameter); buffer.addLine("writer.write_end()"); buffer.addLine("writer.flush()"); buffer.addLine("body = buf.getvalue()"); buffer.addLine("writer.close()"); buffer.addLine("buf.close()"); buffer.addLine("request = http.Request("); buffer.startBlock(); buffer.addLine("method='POST',"); buffer.addLine("path='%%s/%%s' %% (self._path, '%1$s'),", getPath(name)); buffer.addLine("body=body,"); buffer.endBlock(); buffer.addLine(")"); buffer.addLine("response = self._connection.send(request)"); buffer.addLine("if response.code in [200]:"); buffer.startBlock(); buffer.addLine("action = self._check_action(response)"); method.parameters() .filter(x -> x.isOut()) .findFirst() .ifPresent(this::generateActionResponse); buffer.endBlock(); buffer.addLine("else:"); buffer.startBlock(); buffer.addLine("self._check_fault(response)"); buffer.endBlock(); buffer.endBlock(); buffer.addLine(); }
Source:
private void assumeNotWindows() { Assume.assumeFalse(System.getProperty("os.name").startsWith("Windows")); }

Target:
private void assumeNotWindows() { Assume.assumeFalse(Functions.isWindows()); }
Source:
public void checkVariableTypeAndInitializer(VariableTree variableTree) { TypeTree interfaceType = variableTree.type(); ExpressionTree initializer = variableTree.initializer(); if (initializer != null && (initializer.is(Tree.Kind.LAMBDA_EXPRESSION) || isAnonymousClass(initializer))) { matchFunctionalInterface(interfaceType) .ifPresent(treeAndStringInterface -> reportIssue(treeAndStringInterface.classInterface, REPORT_STRING + " '" + treeAndStringInterface.reportString + "'")); } }

Target:
public void checkVariableTypeAndInitializer(VariableTree variableTree) { ExpressionTree initializer = variableTree.initializer(); if (initializer != null && (initializer.is(Tree.Kind.LAMBDA_EXPRESSION) || isAnonymousClass(initializer))) { matchFunctionalInterface((variableTree.symbol().type())).ifPresent(reportString -> { TypeTree variableType = variableTree.type(); reportIssue(variableType, reportMessage(new InterfaceTreeAndStringPairReport(reportString, variableType))); }); } }
Source:
public static String fromContext(Context context) { final PackageManager pm = context.getApplicationContext().getPackageManager(); ApplicationInfo ai; try { ai = pm.getApplicationInfo(context.getPackageName(), 0); } catch (final PackageManager.NameNotFoundException e) { ai = null; } return ai != null ? (String) pm.getApplicationLabel(ai) : null; }

Target:
public static String fromContext(Context context) { final PackageManager pm = context.getApplicationContext().getPackageManager(); try { ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0); return (String) pm.getApplicationLabel(ai); } catch (PackageManager.NameNotFoundException ignored) { return null; } }
Source:
private void setQcowCompat() { if (getDiskImage().getDiskStorageType() == DiskStorageType.IMAGE && getDiskImage().getVolumeFormat().equals(VolumeFormat.COW)) { DiskImage newDiskImage = getDiskImage(); try { setQcowCompat(newDiskImage.getImage(), newDiskImage.getStoragePoolId(), newDiskImage.getId(), newDiskImage.getImageId(), getParameters().getStorageDomainId(), null); imageDao.update(newDiskImage.getImage()); } catch (EngineException e) { log.error("Unable to update the image info for image '{}' (image group: '{}') on domain '{}'", newDiskImage.getImageId(), newDiskImage.getId(), getParameters().getStorageDomainId()); } } }

Target:
private void setQcowCompat() { if (getDiskImage().getDiskStorageType() == DiskStorageType.IMAGE && getDiskImage().getVolumeFormat().equals(VolumeFormat.COW)) { DiskImage newDiskImage = getDiskImage(); try { setQcowCompat(newDiskImage.getImage(), newDiskImage.getStoragePoolId(), newDiskImage.getId(), newDiskImage.getImageId(), getParameters().getStorageDomainId(), null); } catch (EngineException e) { log.error("Unable to update the image info for image '{}' (image group: '{}') on domain '{}'", newDiskImage.getImageId(), newDiskImage.getId(), getParameters().getStorageDomainId()); } } }
Source:
public String getCourseStudentListAsCsv(String courseId, String googleId) throws EntityDoesNotExistException { HashMap<String, CourseDetailsBundle> courses = getCourseSummariesForInstructor(googleId); CourseDetailsBundle course = courses.get(courseId); boolean hasSection = hasIndicatedSections(courseId); String export = ""; export += "Course ID" + "," + Sanitizer.sanitizeForCsv(courseId) + Const.EOL + "Course Name" + "," + Sanitizer.sanitizeForCsv(course.course.name) + Const.EOL + Const.EOL + Const.EOL; if(hasSection){ export += "Section" + ","; } export += "Team" + "," + "First Name" + "," + "Last Name" + "," + "Status" + "," + "Email" + Const.EOL; for (SectionDetailsBundle section : course.sections) { for (TeamDetailsBundle team : section.teams) { for(StudentAttributes student : team.students){ String studentStatus = null; if(student.googleId == null || student.googleId.equals("")){ studentStatus = Const.STUDENT_COURSE_STATUS_YET_TO_JOIN; } else { studentStatus = Const.STUDENT_COURSE_STATUS_JOINED; } if(hasSection){ export += Sanitizer.sanitizeForCsv(section.name) + ","; } String[] splitName = student.name.split(" "); String firstName = ""; String lastName = ""; int lastNameIndex = splitName.length - 1; for (int i = 0; i < lastNameIndex; i++) { firstName += splitName[i] + " "; } lastName = splitName[lastNameIndex]; export += Sanitizer.sanitizeForCsv(team.name) + "," + Sanitizer.sanitizeForCsv(firstName) + "," + Sanitizer.sanitizeForCsv(lastName) + "," + Sanitizer.sanitizeForCsv(studentStatus) + "," + Sanitizer.sanitizeForCsv(student.email) + Const.EOL; } } } return export; }

Target:
public String getCourseStudentListAsCsv(String courseId, String googleId) throws EntityDoesNotExistException { HashMap<String, CourseDetailsBundle> courses = getCourseSummariesForInstructor(googleId); CourseDetailsBundle course = courses.get(courseId); boolean hasSection = hasIndicatedSections(courseId); String export = ""; export += "Course ID" + "," + Sanitizer.sanitizeForCsv(courseId) + Const.EOL + "Course Name" + "," + Sanitizer.sanitizeForCsv(course.course.name) + Const.EOL + Const.EOL + Const.EOL; if(hasSection){ export += "Section" + ","; } export += "Team,First Name,Last Name,Status,Email" + Const.EOL; for (SectionDetailsBundle section : course.sections) { for (TeamDetailsBundle team : section.teams) { for(StudentAttributes student : team.students){ String studentStatus = null; if(student.googleId == null || student.googleId.equals("")){ studentStatus = Const.STUDENT_COURSE_STATUS_YET_TO_JOIN; } else { studentStatus = Const.STUDENT_COURSE_STATUS_JOINED; } if(hasSection){ export += Sanitizer.sanitizeForCsv(section.name) + ","; } String[] splitName = StringHelper.splitName(StringHelper.removeExtraSpace(student.name)); export += Sanitizer.sanitizeForCsv(team.name) + "," + Sanitizer.sanitizeForCsv(splitName[0]) + "," + Sanitizer.sanitizeForCsv(splitName[1]) + "," + Sanitizer.sanitizeForCsv(studentStatus) + "," + Sanitizer.sanitizeForCsv(student.email) + Const.EOL; } } } return export; }
Source:
protected synchronized HttpResponse post(String url, Map<String, String> payloads) throws IOException { HttpPost postRequest = new HttpPost(url); postRequest.setHeader("Accept", ACCEPT_CONTENT_TYPE); StringEntity entity = new StringEntity(OBJECT_MAPPER.writeValueAsString(payloads), ContentType.APPLICATION_JSON); postRequest.setEntity(entity); HttpResponse httpResponse; int hashCode = url.hashCode() + payloads.hashCode(); try { if (_cachedResults.containsKey(hashCode)) { return _cachedResults.get(hashCode); } LOG.info("Executing request: {}, headers: {}, entity: {}", postRequest.getRequestLine(), postRequest.getAllHeaders(), postRequest.getEntity()); httpResponse = _httpClient.execute(postRequest); _cachedResults.put(hashCode, httpResponse); return httpResponse; } catch (IOException e) { LOG.error("Failed to perform customized health check. Is participant endpoint available?", url, e); throw e; } }

Target:
protected HttpResponse post(String url, Map<String, String> payloads) throws IOException { HttpPost postRequest = new HttpPost(url); postRequest.setHeader("Accept", ACCEPT_CONTENT_TYPE); StringEntity entity = new StringEntity(OBJECT_MAPPER.writeValueAsString(payloads), ContentType.APPLICATION_JSON); postRequest.setEntity(entity); try { LOG.info("Executing request: {}, headers: {}, entity: {}", postRequest.getRequestLine(), postRequest.getAllHeaders(), postRequest.getEntity()); return _httpClient.execute(postRequest); } catch (IOException e) { LOG.error("Failed to perform customized health check. Is participant endpoint available?", url, e); throw e; } }
Source:
public void run() { LOG.info("ExchangeScheduled inside run"); while (m_bRunnable) { ExchangeScheduledTask exTask = new ExchangeScheduledTask(); exTask.task(); try { Thread.sleep(refreshInterval); } catch (InterruptedException ex) { LOG.error("Failed to put to sleep: {}", getInstance().getName(), ex.getLocalizedMessage(), ex); } } }

Target:
public void run() { LOG.info("ExchangeScheduled inside run"); while (m_bRunnable) { ExchangeScheduledTask exTask = new ExchangeScheduledTask(); exTask.task(); try { LOG.info("Putting for sleep for milliseconds", getInstance().getName(), refreshInterval); Thread.sleep(refreshInterval); } catch (InterruptedException ex) { LOG.error("Failed to put to sleep: {}", getInstance().getName(), ex.getLocalizedMessage(), ex); } } }
Source:
public Collection<CaseInstance> getSubCaseInstancesByParentCaseId(String parentCaseId, List<CaseStatus> statuses, QueryContext queryContext) { Map<String, Object> params = new HashMap<String, Object>(); params.put("parentCaseId", Arrays.asList(parentCaseId)); params.put("statuses", resolveCaseStatuses(statuses)); applyQueryContext(params, queryContext); applyDeploymentFilter(params); List<CaseInstance> processInstances = commandService.execute(new QueryNameCommand<List<CaseInstance>>("getSubCaseInstancesByParentCaseIds", params)); return processInstances; }

Target:
public Collection<CaseInstance> getSubCaseInstancesByParentCaseId(String parentCaseId, List<CaseStatus> statuses, QueryContext queryContext) { return getSubCases(Arrays.asList(parentCaseId), statuses, queryContext); }
Source:
protected void activate(ComponentContext componentContext) { try { if (log.isDebugEnabled()) { log.debug("Initializing FCM based push notification provider implementation bundle"); } if (log.isDebugEnabled()) { log.debug("FCM based push notification provider implementation bundle has been successfully " + "initialized"); } } catch (Throwable e) { log.error("Error occurred while initializing FCM based push notification provider " + "implementation bundle", e); } }

Target:
protected void activate(ComponentContext componentContext) { try { if (log.isDebugEnabled()) { log.debug("FCM based push notification provider implementation bundle has been successfully " + "initialized"); } } catch (Throwable e) { log.error("Error occurred while initializing FCM based push notification provider " + "implementation bundle", e); } }
Source:
public void typeProcess(TypeElement e, TreePath p) { if (e == null || p == null) { throw new BugInCF("SourceChecker.typeProcess: e=%s, p=%s", e, p); } Context context = ((JavacProcessingEnvironment) processingEnv).getContext(); Source source = Source.instance(context); if (!warnedAboutSourceLevel && source.compareTo(Source.lookup("8")) < 0) { messager.printMessage( javax.tools.Diagnostic.Kind.WARNING, "-source " + source.name + " does not support type annotations"); warnedAboutSourceLevel = true; } Log log = Log.instance(context); if (log.nerrors > this.errsOnLastExit) { this.errsOnLastExit = log.nerrors; previousErrorCompilationUnit = p.getCompilationUnit(); return; } if (p.getCompilationUnit() == previousErrorCompilationUnit) { return; } else { previousErrorCompilationUnit = null; } if (visitor == null) { return; } if (p.getCompilationUnit() != currentRoot) { setRoot(p.getCompilationUnit()); if (hasOption("filenames")) { message(Kind.NOTE, new java.util.Date().toString()); message( Kind.NOTE, "%s is type-checking %s", (Object) this.getClass().getSimpleName(), currentRoot.getSourceFile().getName()); } } try { visitor.visit(p); warnUnneededSuppressions(); } catch (UserError ce) { logUserError(ce); } catch (BugInCF ce) { logBugInCF(ce); } catch (Throwable t) { logBugInCF(wrapThrowableAsBugInCF("SourceChecker.typeProcess", t, p)); } finally { this.errsOnLastExit = log.nerrors; } }

Target:
public void typeProcess(TypeElement e, TreePath p) { if (e == null) { messager.printMessage( javax.tools.Diagnostic.Kind.ERROR, "Refusing to process empty TypeElement"); return; } if (p == null) { messager.printMessage( javax.tools.Diagnostic.Kind.ERROR, "Refusing to process empty TreePath in TypeElement: " + e); return; } Context context = ((JavacProcessingEnvironment) processingEnv).getContext(); Source source = Source.instance(context); if (!warnedAboutSourceLevel && source.compareTo(Source.lookup("8")) < 0) { messager.printMessage( javax.tools.Diagnostic.Kind.WARNING, "-source " + source.name + " does not support type annotations"); warnedAboutSourceLevel = true; } Log log = Log.instance(context); if (log.nerrors > this.errsOnLastExit) { this.errsOnLastExit = log.nerrors; previousErrorCompilationUnit = p.getCompilationUnit(); return; } if (p.getCompilationUnit() == previousErrorCompilationUnit) { return; } else { previousErrorCompilationUnit = null; } if (visitor == null) { return; } if (p.getCompilationUnit() != currentRoot) { setRoot(p.getCompilationUnit()); if (hasOption("filenames")) { message(Kind.NOTE, new java.util.Date().toString()); message( Kind.NOTE, "%s is type-checking %s", (Object) this.getClass().getSimpleName(), currentRoot.getSourceFile().getName()); } } try { visitor.visit(p); warnUnneededSuppressions(); } catch (UserError ce) { logUserError(ce); } catch (BugInCF ce) { logBugInCF(ce); } catch (Throwable t) { logBugInCF(wrapThrowableAsBugInCF("SourceChecker.typeProcess", t, p)); } finally { this.errsOnLastExit = log.nerrors; } }
Source:
public void writeBootstrapPage_scriptSrcHasNoDoubleQuotes_attributeIsTransferred() throws IOException { WebComponentBootstrapHandler handler = new WebComponentBootstrapHandler(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); Element head = new Document("").normalise().head(); Element script = head.ownerDocument().createElement("script"); head.appendChild(script); script.attr("src", "foo'bar%20%27?baz%22"); VaadinResponse response = getMockResponse(stream); handler.writeBootstrapPage("", response, head, ""); String resultingScript = stream.toString(StandardCharsets.UTF_8.name()); MatcherAssert.assertThat(resultingScript, CoreMatchers .not(CoreMatchers.containsString("foo'bar %27?baz%22"))); }

Target:
public void writeBootstrapPage_scriptSrcHasNoDoubleQuotes_attributeIsTransferred() throws IOException { WebComponentBootstrapHandler handler = new WebComponentBootstrapHandler(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); Element head = new Document("").normalise().head(); Element script = head.ownerDocument().createElement("script"); head.appendChild(script); script.attr("src", "foo'bar%20%27?baz%22"); VaadinResponse response = getMockResponse(stream); handler.writeBootstrapPage("", response, head, ""); String resultingScript = stream.toString(StandardCharsets.UTF_8.name()); MatcherAssert.assertThat(resultingScript, CoreMatchers.containsString("foo'bar%20%27?baz%22")); }
Source:
void addRoute(Class<? extends M> messageType, Route<M, C, R> via) throws IllegalStateException { checkNotNull(messageType); checkNotNull(via); Match match = routeFor(messageType); if (match.found()) { String requestedClass = messageType.getName(); String entryClass = match.entryClass() .getName(); if (match.direct()) { throw newIllegalStateException( "The route for the message class `%s` already set. " + "Please remove the route (`%s`) before setting new route.", requestedClass, entryClass); } else { throw newIllegalStateException( "The route for the message class `%s` already defined via " + "the interface `%s`. If you want to have specific routing for " + "the class `%s` please put it before the routing for " + "the super-interface.", requestedClass, entryClass, requestedClass); } } routes.put(messageType, via); }

Target:
void addRoute(Class<? extends M> messageType, Route<M, C, R> via) throws IllegalStateException { checkNotNull(messageType); checkNotNull(via); Match match = routeFor(messageType); if (match.found()) { String requestedClass = messageType.getName(); String entryClass = match.entryClass() .getName(); if (match.direct()) { throw newIllegalStateException( "The route for the message class `%s` already set. " + "Please remove the route (`%s`) before setting new route.", requestedClass, entryClass); } else { throw newIllegalStateException( "The route for the message class `%s` already defined via " + "the interface `%s`. If you want to have specific routing for " + "the class `%s`, please put it before the routing for " + "the super-interface.", requestedClass, entryClass, requestedClass); } } routes.put(messageType, via); }
Source:
private void setDataBindingField() { dataBindingField = holder.generatedClass.field(JMod.PRIVATE, getClasses().VIEW_DATA_BINDING, "viewDataBinding" + ModelConstants.generationSuffix()); }

Target:
private void setDataBindingField() { dataBindingField = holder.generatedClass.field(JMod.PRIVATE, getClasses().VIEW_DATA_BINDING, "viewDataBinding" + generationSuffix()); }
Source:
private void assignEventProducerToTask(EventProducer eventProducer, DatastreamTask task) { eventProducer.assignTask(task); DatastreamEventProducerImpl datastreamEventProducer = (DatastreamEventProducerImpl) task.getEventProducer(); if(task.getEventProducer() == null) { ((DatastreamTaskImpl) task).setEventProducer(new DatastreamEventProducerImpl(task, _schemaRegistryProvider, eventProducer)); } else { datastreamEventProducer.resetEventProducer(eventProducer); } _taskEventProducerMap.put(task, eventProducer); }

Target:
private void assignEventProducerToTask(EventProducer eventProducer, DatastreamTask task) { eventProducer.assignTask(task); DatastreamEventProducerImpl datastreamEventProducer = (DatastreamEventProducerImpl) task.getEventProducer(); if (datastreamEventProducer == null) { ((DatastreamTaskImpl) task).setEventProducer( new DatastreamEventProducerImpl(task, _schemaRegistryProvider, eventProducer)); } else { datastreamEventProducer.resetEventProducer(eventProducer); } _taskEventProducerMap.put(task, eventProducer); }
Source:
private boolean hasVirtCluster() { for (VDSGroup cluster: getAllVdsGroupInPool()) { if (cluster.supportsVirtService()) { return true; } } return false; }

Target:
private boolean hasVirtCluster() { return getAllVdsGroupInPool().stream().anyMatch(VDSGroup::supportsVirtService); }
Source:
public PluggableAlertRepository( final ObjectMapper objectMapper, final PeriodicMetrics periodicMetrics, final Injector injector, final Environment environment, @Named("AlertJobCoordinator") final ActorRef alertJobCoordinator, @Assisted final Config config ) { this( objectMapper, periodicMetrics, ConfigurationHelper.toInstanceMapped(injector, environment, config.getConfig("configProvider")), UUID.fromString(config.getString("organization")), Optional.of(alertJobCoordinator) ); }

Target:
public PluggableAlertRepository( final ObjectMapper objectMapper, final PeriodicMetrics periodicMetrics, final Injector injector, final Environment environment, @Named("AlertJobCoordinator") final ActorRef alertJobCoordinator, @Assisted final Config config ) { this( objectMapper, periodicMetrics, ConfigurationHelper.toInstanceMapped(injector, environment, config.getConfig("configProvider")), UUID.fromString(config.getString("organization")), config.getDuration("openTimeout"), alertJobCoordinator ); }
Source:
public void qcValues(List<SensorValue> values) throws RoutineException { SensorValue prevValue = null; SensorValue currValue = null; SensorValue nextValue = null; List<SensorValue> filteredValues = filterMissingValues(values); int i = 1; while (i < filteredValues.size() - 1) { currValue = filteredValues.get(i); prevValue = filteredValues.get(i - 1); nextValue = filteredValues.get(i + 1); double tDiff = ChronoUnit.SECONDS.between(prevValue.getTime(), currValue.getTime()) / 60.0; double delta = Math .abs(currValue.getDoubleValue() - prevValue.getDoubleValue()) / tDiff; if (delta > maxDelta) { double deltaNext = Math .abs(nextValue.getDoubleValue() - prevValue.getDoubleValue()) / tDiff; if (deltaNext < maxDelta) { addFlag(currValue, Flag.BAD, maxDelta, delta); i++; } else { addFlag(prevValue, Flag.BAD, maxDelta, delta); while ((delta > maxDelta) & (i < filteredValues.size() - 1)) { addFlag(currValue, Flag.BAD, maxDelta, delta); i++; currValue = filteredValues.get(i); prevValue = filteredValues.get(i - 1); tDiff = ChronoUnit.SECONDS.between(prevValue.getTime(), currValue.getTime()) / 60.0; delta = Math.abs( currValue.getDoubleValue() - prevValue.getDoubleValue()) / tDiff; } } } i++; } }

Target:
public void qcValues(List<SensorValue> values) throws RoutineException { SensorValue prevValue = null; SensorValue currValue = null; SensorValue nextValue = null; List<SensorValue> filteredValues = filterMissingValues(values); int i = 1; while (i < filteredValues.size() - 1) { currValue = filteredValues.get(i); prevValue = filteredValues.get(i - 1); nextValue = filteredValues.get(i + 1); double tDiff = ChronoUnit.SECONDS.between(prevValue.getTime(), currValue.getTime()) / 60.0; double delta = Math .abs(currValue.getDoubleValue() - prevValue.getDoubleValue()) / tDiff; if (delta > maxDelta) { double deltaNext = Math .abs(nextValue.getDoubleValue() - prevValue.getDoubleValue()) / tDiff; if (deltaNext < maxDelta) { addFlag(currValue, Flag.BAD, maxDelta, delta); i++; } else { addFlag(prevValue, Flag.BAD, maxDelta, delta); while ((delta > maxDelta) && (i < filteredValues.size() - 1)) { addFlag(currValue, Flag.BAD, maxDelta, delta); i++; currValue = filteredValues.get(i); prevValue = filteredValues.get(i - 1); tDiff = ChronoUnit.SECONDS.between(prevValue.getTime(), currValue.getTime()) / 60.0; delta = Math.abs( currValue.getDoubleValue() - prevValue.getDoubleValue()) / tDiff; } } } i++; } }
Source:
protected AsyncTaskType getTaskType() { return AsyncTaskType.copyImage; }

Target:
protected AsyncTaskType getTaskType() { return isDataOperationsByHSM() ? AsyncTaskType.notSupported : AsyncTaskType.copyImage; }
Source:
public <T> T makeBlockingRequest( AdvertisedSocketAddress upstream, CatchUpRequest request, CatchUpResponseCallback<T> responseHandler ) throws CatchUpClientException { CompletableFuture<T> future = new CompletableFuture<>(); CatchUpChannel channel = pool.acquire( upstream ); future.whenComplete( ( result, e ) -> { if ( e == null ) { pool.release( channel ); } else { pool.dispose( channel ); } } ); channel.setResponseHandler( responseHandler, future ); try { channel.send( request ); String operation = format( "Timed out executing operation %s on %s ", request, upstream ); return waitForCompletion( future, operation, channel::millisSinceLastResponse, inactivityTimeoutMillis, log ); } catch ( CatchUpClientException e ) { pool.dispose( channel ); throw e; } }

Target:
public <T> T makeBlockingRequest( AdvertisedSocketAddress upstream, CatchUpRequest request, CatchUpResponseCallback<T> responseHandler ) throws CatchUpClientException { CompletableFuture<T> future = new CompletableFuture<>(); CatchUpChannel channel = null; try { channel = pool.acquire( upstream ); channel.setResponseHandler( responseHandler, future ); future.whenComplete( new ReleaseOnComplete( channel ) ); channel.send( request ); } catch ( Exception e ) { if ( channel != null ) { pool.dispose( channel ); } throw new CatchUpClientException( "Failed to send request", e ); } String operation = format( "Completed exceptionally when executing operation %s on %s ", request, upstream ); return waitForCompletion( future, operation, channel::millisSinceLastResponse, inactivityTimeoutMillis, log ); }
Source:
public List<Contentlet> dbRelatedContent(final Relationship relationship, final Contentlet contentlet, final boolean hasParent, final boolean live, final String orderBy) throws DotDataException { List<Contentlet> matches = new ArrayList<Contentlet>(); if(contentlet == null || !InodeUtils.isSet(contentlet.getIdentifier())) return matches; String iden = ""; try{ iden = APILocator.getIdentifierAPI().find(contentlet).getInode(); }catch(DotHibernateException dhe){ Logger.error(this.getClass(), "Unable to retrieve Identifier", dhe); } if(!InodeUtils.isSet(iden)) return matches; if (hasParent) { if (live) matches = dbRelatedContentByParent(iden, relationship.getRelationTypeValue(),true, orderBy); else matches = dbRelatedContentByParent(iden, relationship.getRelationTypeValue(),false, orderBy); } else { if (live) matches = dbRelatedContentByChild(iden, relationship.getRelationTypeValue(),true, orderBy); else matches = dbRelatedContentByChild(iden, relationship.getRelationTypeValue(),false, orderBy); } return matches; }

Target:
public List<Contentlet> dbRelatedContent(final Relationship relationship, final Contentlet contentlet, final boolean hasParent, final boolean live, final String orderBy) throws DotDataException { List<Contentlet> matches = new ArrayList<Contentlet>(); if(contentlet == null || !InodeUtils.isSet(contentlet.getIdentifier())) { return matches; } String iden = ""; try{ iden = APILocator.getIdentifierAPI().find(contentlet).getInode(); }catch(DotHibernateException dhe){ Logger.error(this.getClass(), "Unable to retrieve Identifier", dhe); } if(!InodeUtils.isSet(iden)) { return matches; } if (hasParent) { matches = live ? dbRelatedContentByParent(iden, relationship.getRelationTypeValue(),true, orderBy): dbRelatedContentByParent(iden, relationship.getRelationTypeValue(),false, orderBy); } else { matches = live ? dbRelatedContentByChild(iden, relationship.getRelationTypeValue(),true, orderBy): dbRelatedContentByChild(iden, relationship.getRelationTypeValue(),false, orderBy); } return matches; }
Source:
public ConnectivityMonitorFactory getConnectivityMonitorFactory() { return connectivityMonitorFactory; }

Target:
ConnectivityMonitorFactory getConnectivityMonitorFactory() { return connectivityMonitorFactory; }