auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testExecuteQueryCommand() { GetDiskImageByDiskAndImageIdsParameters params = getQueryParameters(); when(params.getDiskId()).thenReturn(diskId); when(params.getImageId()).thenReturn(imageId); <START> when(diskImageDao.getDiskImageByDiskAndImageIds(diskId, imageId)).thenReturn(diskImage); <END> GetDiskImageByDiskAndImageIdsQuery<GetDiskImageByDiskAndImageIdsParameters> query = getQuery(); query.executeQueryCommand(); DiskImage returnDiskImage = query.getQueryReturnValue().getReturnValue(); assertEquals(returnDiskImage, diskImage); }</code><technical_language>mock four-arg variant query</technical_language>

Target:
public void testExecuteQueryCommand() { GetDiskImageByDiskAndImageIdsParameters params = getQueryParameters(); when(params.getDiskId()).thenReturn(diskId); when(params.getImageId()).thenReturn(imageId); when(diskImageDao.getDiskImageByDiskAndImageIds( diskId, imageId, getUser().getId(), getQueryParameters().isFiltered())).thenReturn(diskImage); GetDiskImageByDiskAndImageIdsQuery<GetDiskImageByDiskAndImageIdsParameters> query = getQuery(); query.executeQueryCommand(); DiskImage returnDiskImage = query.getQueryReturnValue().getReturnValue(); assertEquals(returnDiskImage, diskImage); }
Source:
<code>public Block intersect( @TypeParameter("E") Type type, @SqlType("array(E)") Block leftArray, @SqlType("array(E)") Block rightArray) { if (leftArray.getPositionCount() < rightArray.getPositionCount()) { Block tempArray = leftArray; leftArray = rightArray; rightArray = tempArray; } int leftPositionCount = leftArray.getPositionCount(); int rightPositionCount = rightArray.getPositionCount(); if (rightPositionCount == 0) { return rightArray; } if (pageBuilder.isFull()) { pageBuilder.reset(); } BlockBuilder blockBuilder = pageBuilder.getBlockBuilder(0); TypedSet rightTypedSet = new TypedSet(type, rightPositionCount, "array_intersect"); for (int i = 0; i < rightPositionCount; i++) { rightTypedSet.add(rightArray, i); } TypedSet intersectTypedSet = new TypedSet(type, rightPositionCount, "array_intersect"); int intersectCount = 0; for (int i = 0; i < leftPositionCount; i++) { if (rightTypedSet.contains(leftArray, i) && !intersectTypedSet.contains(leftArray, i)) { intersectTypedSet.add(leftArray, i); type.appendTo(leftArray, i, blockBuilder); intersectCount++; } } <START> return blockBuilder.getRegion(blockBuilder.getPositionCount() - intersectCount, intersectCount); <END> }</code><technical_language>I intersectTypedSet contains output data, modify TypedSet return elementBlock.build</technical_language>

Target:
public Block intersect( @TypeParameter("E") Type type, @SqlType("array(E)") Block leftArray, @SqlType("array(E)") Block rightArray) { if (leftArray.getPositionCount() < rightArray.getPositionCount()) { Block tempArray = leftArray; leftArray = rightArray; rightArray = tempArray; } int leftPositionCount = leftArray.getPositionCount(); int rightPositionCount = rightArray.getPositionCount(); if (rightPositionCount == 0) { return rightArray; } if (pageBuilder.isFull()) { pageBuilder.reset(); } TypedSet rightTypedSet = new TypedSet(type, rightPositionCount, "array_intersect"); for (int i = 0; i < rightPositionCount; i++) { rightTypedSet.add(rightArray, i); } BlockBuilder blockBuilder = pageBuilder.getBlockBuilder(0); TypedSet intersectTypedSet = new TypedSet(type, blockBuilder, rightPositionCount, "array_intersect"); for (int i = 0; i < leftPositionCount; i++) { if (rightTypedSet.contains(leftArray, i)) { intersectTypedSet.add(leftArray, i); } } pageBuilder.declarePositions(intersectTypedSet.size()); return blockBuilder.getRegion(blockBuilder.getPositionCount() - intersectTypedSet.size(), intersectTypedSet.size()); }
Source:
<code>private ModelNode convertToExpectedType(final ModelNode node) { if (node.getType() == type || node.getType() == ModelType.EXPRESSION || Util.isExpression(node.asString()) || !node.isDefined()) { return node; } <START> ModelNode result = node.clone(); <END> switch (type) { case BIG_DECIMAL: result.set(node.asBigDecimal()); break; case BIG_INTEGER: result.set(node.asBigInteger()); break; case BOOLEAN: result.set(node.asBoolean()); break; case BYTES: result.set(node.asBytes()); break; case DOUBLE: result.set(node.asDouble()); break; case INT: result.set(node.asInt()); break; case LIST: result.set(node.asList()); break; case LONG: result.set(node.asLong()); break; case PROPERTY: result.set(node.asProperty()); break; case TYPE: result.set(node.asType()); break; case STRING: result.set(node.asString()); break; case OBJECT: default: result.set(node); break; } return result; }</code><technical_language>new ModelNode(). In cases in switch ModelValue node is replaced, cost of cloning is unnecessary</technical_language>

Target:
private ModelNode convertToExpectedType(final ModelNode node) { if (node.getType() == type || node.getType() == ModelType.EXPRESSION || Util.isExpression(node.asString()) || !node.isDefined()) { return node; } switch (type) { case BIG_DECIMAL: return new ModelNode(node.asBigDecimal()); case BIG_INTEGER: return new ModelNode(node.asBigInteger()); case BOOLEAN: return new ModelNode(node.asBoolean()); case BYTES: return new ModelNode(node.asBytes()); case DOUBLE: return new ModelNode(node.asDouble()); case INT: return new ModelNode(node.asInt()); case LIST: return new ModelNode().set(node.asList()); case LONG: return new ModelNode(node.asLong()); case PROPERTY: return new ModelNode().set(node.asProperty()); case TYPE: return new ModelNode(node.asType()); case STRING: return new ModelNode(node.asString()); case OBJECT: default: return node; } }
Source:
<code>public void deleteTrace(List<Connection> toDelete, EObject traceModel) { <START> GenericTraceModel TModel = (GenericTraceModel) traceModel; <END> EList<RelatedTo> links = TModel.getTraces(); ResourceSet resourceSet = new ResourceSetImpl(); for (Connection c : toDelete) { links.remove(c.getTlink()); } GenericTraceModel newTraceModel = GenericTraceMetaModelFactory.eINSTANCE.createGenericTraceModel(); newTraceModel.getTraces().addAll(links); URI traceModelURI = EcoreUtil.getURI(traceModel); Resource resourceForTraces = resourceSet.createResource(traceModelURI); resourceForTraces.getContents().add(newTraceModel); try { resourceForTraces.save(null); } catch (IOException e) { e.printStackTrace(); } }</code><technical_language>check traceModel is instance of GenericTraceModel first</technical_language>

Target:
public void deleteTrace(List<Connection> toDelete, EObject traceModel) { if(traceModel instanceof GenericTraceModel) { GenericTraceModel TModel = (GenericTraceModel) traceModel; EList<RelatedTo> links = TModel.getTraces(); ResourceSet resourceSet = new ResourceSetImpl(); for (Connection c : toDelete) { links.remove(c.getTlink()); } GenericTraceModel newTraceModel = GenericTraceMetaModelFactory.eINSTANCE.createGenericTraceModel(); newTraceModel.getTraces().addAll(links); URI traceModelURI = EcoreUtil.getURI(traceModel); Resource resourceForTraces = resourceSet.createResource(traceModelURI); resourceForTraces.getContents().add(newTraceModel); try { resourceForTraces.save(null); } catch (IOException e) { e.printStackTrace(); } } }
Source:
<code>private Map<Guid, GlusterAsyncTask> updateTasksInCluster(final VDSGroup cluster) { if (!supportsGlusterAsyncTasksFeature(cluster)) { return null; } Map<Guid, GlusterAsyncTask> runningTasks = getProvider().getTaskListForCluster(cluster.getId()); if (runningTasks == null) { return null; } for (Entry<Guid, GlusterAsyncTask> entry : runningTasks.entrySet()) { Guid taskId = entry.getKey(); final GlusterAsyncTask task = entry.getValue(); <START> List<Step> steps = getStepDao().getStepsByExternalId(taskId); <END> if (steps == null || steps.isEmpty()) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { try { createJobToMonitor(cluster,task); } catch (VdcBLLException e) { log.error("Error creating job for task from CLI", e); } return null; } }); } else { for (Step step: steps) { if (step.getEndTime() != null) { continue; } step.setDescription(getTaskMessage(cluster,step.getStepType(),task)); if (hasTaskCompleted(task)) { step.markStepEnded(task.getStatus()); endStepJob(step); releaseVolumeLock(task.getTaskId()); } else { getJobRepository().updateStep(step); } } } } return runningTasks; }</code><technical_language>steps null - remove steps == null check</technical_language>

Target:
private Map<Guid, GlusterAsyncTask> updateTasksInCluster(final VDSGroup cluster) { if (!supportsGlusterAsyncTasksFeature(cluster)) { return null; } Map<Guid, GlusterAsyncTask> runningTasks = getProvider().getTaskListForCluster(cluster.getId()); if (runningTasks == null) { return null; } for (Entry<Guid, GlusterAsyncTask> entry : runningTasks.entrySet()) { Guid taskId = entry.getKey(); final GlusterAsyncTask task = entry.getValue(); List<Step> steps = getStepDao().getStepsByExternalId(taskId); if (steps.isEmpty()) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { try { createJobToMonitor(cluster,task); } catch (VdcBLLException e) { log.error("Error creating job for task from CLI", e); } return null; } }); } for (Step step: steps) { if (step.getEndTime() != null) { continue; } step.setDescription(getTaskMessage(cluster,step.getStepType(),task)); if (hasTaskCompleted(task)) { step.markStepEnded(task.getStatus()); endStepJob(step); releaseVolumeLock(task.getTaskId()); } else { getJobRepository().updateStep(step); } } } return runningTasks; }
Source:
<code>public void testUpdateFeedbackSession() throws Exception { restoreTypicalDataInDatastore(); FeedbackSessionAttributes fsa = null; ______TS("failure 1: null object"); try { fsLogic.updateFeedbackSession(fsa); signalFailureToDetectException(); } catch (AssertionError ae) { AssertHelper.assertContains(Const.StatusCodes.NULL_PARAMETER, ae.getMessage()); } catch (Exception e) { signalDetectionOfWrongException("Expected AssertionError"); } ______TS("failure 2: non-existent session name"); fsa = new FeedbackSessionAttributes(); fsa.feedbackSessionName = "asdf_randomName1423"; fsa.courseId = "idOfTypicalCourse1"; try { fsLogic.updateFeedbackSession(fsa); signalFailureToDetectException(); } catch (EntityDoesNotExistException edne) { assertEquals("Trying to update a feedback session that does not exist.", edne.getMessage()); } catch (Exception e) { signalDetectionOfWrongException("Expected EntityDoesNotExistException"); } ______TS("success 1: all changeable values sent are null"); fsa = dataBundle.feedbackSessions.get("session1InCourse1"); fsa.instructions = null; fsa.startTime = null; fsa.endTime = null; fsa.feedbackSessionType = null; fsa.sessionVisibleFromTime = null; fsa.resultsVisibleFromTime = null; try { fsLogic.updateFeedbackSession(fsa); } catch (Exception e) { <START> signalDetectionOfWrongException("No Exceptions Expected"); <END> } assertEquals(fsa.toString(), fsLogic.getFeedbackSession(fsa.feedbackSessionName, fsa.courseId).toString()); }</code><technical_language>this redundant? unexpected exception fail case automatically. need for catch fail explicitly</technical_language>

Target:
public void testUpdateFeedbackSession() throws Exception { restoreTypicalDataInDatastore(); FeedbackSessionAttributes fsa = null; ______TS("failure 1: null object"); try { fsLogic.updateFeedbackSession(fsa); signalFailureToDetectException(); } catch (AssertionError ae) { AssertHelper.assertContains(Const.StatusCodes.NULL_PARAMETER, ae.getMessage()); } ______TS("failure 2: non-existent session name"); fsa = new FeedbackSessionAttributes(); fsa.feedbackSessionName = "asdf_randomName1423"; fsa.courseId = "idOfTypicalCourse1"; try { fsLogic.updateFeedbackSession(fsa); signalFailureToDetectException(); } catch (EntityDoesNotExistException edne) { assertEquals("Trying to update a feedback session that does not exist.", edne.getMessage()); } ______TS("success 1: all changeable values sent are null"); fsa = dataBundle.feedbackSessions.get("session1InCourse1"); fsa.instructions = null; fsa.startTime = null; fsa.endTime = null; fsa.feedbackSessionType = null; fsa.sessionVisibleFromTime = null; fsa.resultsVisibleFromTime = null; fsLogic.updateFeedbackSession(fsa); assertEquals(fsa.toString(), fsLogic.getFeedbackSession(fsa.feedbackSessionName, fsa.courseId).toString()); }
Source:
<code>public static DateTimeZone getTimeZone(String timezoneParam) { try { return DateTimeZone.forID(timezoneParam); } catch (final IllegalArgumentException e) { TimeZone zone = ZoneInfo.getTimeZone(timezoneParam); <START> if(null == zone) return null; <END> try { return DateTimeZone.forTimeZone(zone); } catch (final IllegalArgumentException e1) { return null; } } }</code><technical_language>write this in curly braces block instead of 1 line</technical_language>

Target:
public static DateTimeZone getTimeZone(String timezoneParam) { try { return DateTimeZone.forID(timezoneParam); } catch (final IllegalArgumentException e) { TimeZone zone = ZoneInfo.getTimeZone(timezoneParam); if(null == zone) { return null; } try { return DateTimeZone.forTimeZone(zone); } catch (final IllegalArgumentException e1) { return null; } } }
Source:
<code><START> private void writeMapToDisk(String prefix, byte[] userMapBytes) throws Exception <END> { File cacheDir = new File(commonCacheConfig.getCacheDirectory()); cacheDir.mkdirs(); File userMapFile = new File(commonCacheConfig.getCacheDirectory(), getUserRoleMapFilename(prefix)); Files.write(userMapBytes, userMapFile); }</code><technical_language>reduced IOException</technical_language>

Target:
private void writeMapToDisk(String prefix, byte[] userMapBytes) throws IOException { File cacheDir = new File(commonCacheConfig.getCacheDirectory()); cacheDir.mkdirs(); File userMapFile = new File(commonCacheConfig.getCacheDirectory(), getUserRoleMapFilename(prefix)); Files.write(userMapBytes, userMapFile); }
Source:
<code>public String toString(){ <START> StringBuffer sb = new StringBuffer(); <END> for (int i = 0; i < size.width + 3; i++){ sb.append("-"); } sb.append("\n"); for (int i = 0; i < squares.length; i++){ sb.append("|"); for (int j = 0; j < squares[i].length; j++){ sb.append(squares[i][j].toString()); } sb.append("|\n"); } for (int i = 0; i < size.width + 3; i++){ sb.append("-"); } return sb.toString(); }</code><technical_language>+1 for StringBuffer</technical_language>

Target:
public String toString(){ StringBuffer sb = new StringBuffer(); final int EXTRA_WIDTH = 2; for (int i = 0; i < size.width + EXTRA_WIDTH; i++){ sb.append("-"); } sb.append("\n"); for (int j = 0; j < size.height; j++){ sb.append("|"); for (int i = 0; i < size.width; i++){ sb.append(squares[j][i].toString()); } sb.append("|\n"); } for (int i = 0; i < size.width + EXTRA_WIDTH; i++){ sb.append("-"); } return sb.toString(); }
Source:
<code>public static void createDwrModulesXml(String realPath) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("dwr"); doc.appendChild(rootElement); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); <START> StreamResult result = new StreamResult(new File(realPath, "/WEB-INF/dwr-modules.xml")); <END> transformer.transform(source, result); } catch (ParserConfigurationException pce) { log.error("Failed to parse document", pce); } catch (TransformerException tfe) { log.error("Failed to transorm xml source", tfe); } }</code><technical_language>need get rid of slashes</technical_language>

Target:
public static void createDwrModulesXml(String realPath) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("dwr"); doc.appendChild(rootElement); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(Paths.get(realPath, "WEB-INF", "dwr-modules.xml").toString())); transformer.transform(source, result); } catch (ParserConfigurationException pce) { log.error("Failed to parse document", pce); } catch (TransformerException tfe) { log.error("Failed to transorm xml source", tfe); } }
Source:
<code>public MessageQueueingContentWriter(MessageSender<EntityUpdatedMessage> sender, ContentWriter delegate, Timestamper clock) { <START> this.sender = sender; <END> this.delegate = delegate; this.clock = clock; }</code><technical_language>sense check for null sender? (also other fields...)</technical_language>

Target:
public MessageQueueingContentWriter(MessageSender<EntityUpdatedMessage> sender, ContentWriter delegate, Timestamper clock) { this.sender = checkNotNull(sender); this.delegate = checkNotNull(delegate); this.clock = checkNotNull(clock); }
Source:
<code>public ChartData(IDataChartProvider<?> provider, List<ChartSeries> series) { fProvider = provider; <START> fSeries = series; <END> }</code><technical_language>good store lists passed in parameter directly, below</technical_language>

Target:
public ChartData(IDataChartProvider<?> provider, List<ChartSeries> series) { fProvider = provider; fSeries = checkNotNull(ImmutableList.copyOf(series)); }
Source:
<code>void method2() { <START> return b.method((a, b) -> true); END> }</code><technical_language>implementation catch a case lambda is assigned a variable. check for lambda argument for lambda of proper type (hostnameVerifier) check if is compliant not</technical_language>

Target:
void method2() { BiFunction<String, SSLSession, Boolean> lambda = (a, b) -> true; b.method((a, b) -> true); b.method((a, b) -> (((true)))); b.method((a, b) -> a.equalsIgnoreCase(b.getPeerHost())); b.method(lambda); }
Source:
<code>public static final String md5(final String s) { try { MessageDigest digest = java.security.MessageDigest .getInstance("MD5"); <START> digest.update(s.getBytes()); <END> byte messageDigest[] = digest.digest(); return Base64.encodeToString(messageDigest, Base64.URL_SAFE | Base64.NO_WRAP); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }</code><technical_language>"Encodes this String a sequence of bytes platform's default charset, storing result a new byte array. " ehhhhhhhhhh sounds dangerous. Recommend UTF-8 explicitly for this conversion</technical_language>

Target:
public static final String md5(final String s) { try { MessageDigest digest = java.security.MessageDigest .getInstance("MD5"); digest.update(s.getBytes("utf-8")); byte messageDigest[] = digest.digest(); return Base64.encodeToString(messageDigest, Base64.URL_SAFE | Base64.NO_WRAP); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
Source:
<code>public Integer add(T value) { Integer bit = getBit(value); if (bit != null) { return bit; } rwLock.writeLock().lock(); try { bit = value2Bit.get(value); if (bit != null) { return bit; } bit = freedBitSet.nextSetBit(0); if (bit > -1) { freedBitSet.clear(bit); } else { <START> bit = nextBit; <END> } value2Bit.put(value, bit); bit2Value.put(bit, value); return bit; } finally { rwLock.writeLock().unlock(); } }</code><technical_language>increase nextBit then. this is good? WatchManagerOptimized.addWatch() it, unique id for watch, good... this nextBit++ in place... findbugs some issue this</technical_language>

Target:
public Integer add(T value) { Integer bit = getBit(value); if (bit != null) { return bit; } rwLock.writeLock().lock(); try { bit = value2Bit.get(value); if (bit != null) { return bit; } bit = freedBitSet.nextSetBit(0); if (bit > -1) { freedBitSet.clear(bit); } else { bit = nextBit++; } value2Bit.put(value, bit); bit2Value.put(bit, value); return bit; } finally { rwLock.writeLock().unlock(); } }
Source:
<code>private Result analyzeIsStandard() { if (!wallet.getNetworkParameters().getId().equals(NetworkParameters.ID_MAINNET)) return Result.OK; <START> Map<Sha256Hash, Transaction> depMap = new HashMap<Sha256Hash, Transaction>(); <END> for (Transaction transaction : dependencies) depMap.put(transaction.getHash(), transaction); nonStandard = isStandard(tx, depMap); if (nonStandard != null) return Result.NON_STANDARD; for (Transaction dep : dependencies) { nonStandard = isStandard(dep, depMap); if (nonStandard != null) return Result.NON_STANDARD; } return Result.OK; }</code><technical_language>able drop depMap here? (Don't bother rebasing next commit top of this if complicated, redoing some of anyway)</technical_language>

Target:
private Result analyzeIsStandard() { if (!wallet.getNetworkParameters().getId().equals(NetworkParameters.ID_MAINNET)) return Result.OK; nonStandard = isStandard(tx); if (nonStandard != null) return Result.NON_STANDARD; for (Transaction dep : dependencies) { nonStandard = isStandard(dep); if (nonStandard != null) return Result.NON_STANDARD; } return Result.OK; }
Source:
<code>private void updateToolItem() { ToolItem item = (ToolItem) widget; String text = model.getLocalizedLabel(); final boolean forceText = model.getTags().contains(FORCE_TEXT); if ((item.getImage() == null || forceText) && text != null) { item.setText(text); } else { <START> final MCommand command = model.getCommand(); <END> if (command == null) { item.setText("UnLabled"); } else { item.setText(command.getCommandName()); } } final String tooltip = getToolTipText(); item.setToolTipText(tooltip); item.setSelection(model.isSelected()); item.setEnabled(model.isEnabled()); }</code><technical_language>this force text tool item, if image</technical_language>

Target:
private void updateToolItem() { ToolItem item = (ToolItem) widget; String text = model.getLocalizedLabel(); if (item.getImage() == null || model.getTags().contains(FORCE_TEXT)) { if (text == null || text.length() == 0) { final MCommand command = model.getCommand(); if (command == null) { item.setText("UnLabled"); } else { item.setText(command.getCommandName()); } } else { item.setText(text); } } else { item.setText(""); } final String tooltip = getToolTipText(); item.setToolTipText(tooltip); item.setSelection(model.isSelected()); item.setEnabled(model.isEnabled()); }
Source:
<code>public void open() { <START> <END> }</code><technical_language>Pretty log track state for debugging purposes</technical_language>

Target:
public void open() { assertIsOpen(false); LOGGER.debug().setMessage("Opening NoAlertExecutionRepository").log(); _isOpen.set(true); }
Source:
<code>protected <P> APIResponse doRequest(final String method, final String url, final P payload) throws GeneralException { HttpURLConnection connection = null; InputStream inputStream = null; <START> if (METHOD_PATCH.equals(method)) { <END> allowPatchRequestsIfNeeded(); } try { connection = getConnection(url, payload, method); int status = connection.getResponseCode(); if (APIResponse.isSuccessStatus(status)) { inputStream = connection.getInputStream(); } else { inputStream = connection.getErrorStream(); } return new APIResponse(readToEnd(inputStream), status); } catch (IOException ioe) { throw new GeneralException(ioe); } finally { saveClose(inputStream); if (connection != null) { connection.disconnect(); } } }</code><technical_language>want do case insensitive check</technical_language>

Target:
protected <P> APIResponse doRequest(final String method, final String url, final P payload) throws GeneralException { HttpURLConnection connection = null; InputStream inputStream = null; if (METHOD_PATCH.equalsIgnoreCase(method)) { allowPatchRequestsIfNeeded(); } try { connection = getConnection(url, payload, method); int status = connection.getResponseCode(); if (APIResponse.isSuccessStatus(status)) { inputStream = connection.getInputStream(); } else { inputStream = connection.getErrorStream(); } return new APIResponse(readToEnd(inputStream), status); } catch (IOException ioe) { throw new GeneralException(ioe); } finally { saveClose(inputStream); if (connection != null) { connection.disconnect(); } } }
Source:
<code>protected boolean setAndValidateDiskProfiles() { setDiskProfileParameters(); final Map<Guid, DiskProfileValidator> diskProfileValidationMap = new HashMap<>(); for (final DiskImage diskImage : diskInfoDestinationMap.values()) { if (!diskProfileValidationMap.containsKey(diskImage.getDiskProfileId())) { diskProfileValidationMap.put(diskImage.getDiskProfileId(), new DiskProfileValidator(diskImage.getDiskProfileId())); <START> } <END> if (!validate(diskProfileValidationMap.get(diskImage.getDiskProfileId()) .isStorageDomainValid(diskImage.getStorageIds() .get(0)))) { return false; } } return true; }</code><technical_language>if exists in map, means validated need validate again</technical_language>

Target:
protected boolean setAndValidateDiskProfiles() { setDiskProfileParameters(); final Set<Guid> diskProfilesSet = new HashSet<>(); for (final DiskImage diskImage : diskInfoDestinationMap.values()) { if (!diskProfilesSet.contains(diskImage.getDiskProfileId())) { diskProfilesSet.add(diskImage.getDiskProfileId()); if (!validate(new DiskProfileValidator(diskImage.getDiskProfileId()) .isStorageDomainValid(diskImage.getStorageIds() .get(0)))) { return false; } } } return true; }
Source:
<code>public void interface_extension_with_overwritten_property() { Binder<InterfaceWithOverwrittenMethod> binder = <START> new Binder<>(InterfaceWithOverwrittenMethod.class); <END> }</code><technical_language>please create a simple test binding works? know, bind "property" property in binder IntegerField similar, call readBean some implementor of InterfaceWithOverwrittenMethod, asserting IntegerField desired value</technical_language>

Target:
public void interface_extension_with_overwritten_property() { Binder<TestInterfaceWithOverwrittenMethod> binder = new Binder<>( TestInterfaceWithOverwrittenMethod.class); IntegerTextField field = new IntegerTextField(); binder.bind(field, "property"); TestInterfaceWithOverwrittenMethod bean = new TestInterfaceWithOverwrittenMethod() { @Override public int getProperty() { return 5; } }; binder.setBean(bean); assertEquals(Integer.valueOf(5), field.getValue()); }
Source:
<code>public GetInformationAboutUsersCurrentPlaybackRequest.Builder getInformationAboutUsersCurrentPlayback() { return new GetInformationAboutUsersCurrentPlaybackRequest.Builder(accessToken) .setDefaults(httpManager, scheme, host, port) <START> .additionalTypes("episode"); <END> }</code><technical_language>this default</technical_language>

Target:
public GetInformationAboutUsersCurrentPlaybackRequest.Builder getInformationAboutUsersCurrentPlayback() { return new GetInformationAboutUsersCurrentPlaybackRequest.Builder(accessToken) .setDefaults(httpManager, scheme, host, port); }
Source:
<code>public Refund refund(APIContext apiContext, Refund refund) throws PayPalRESTException { if (this.getId() == null) { throw new IllegalArgumentException("Id cannot be null"); } if (refund == null) { throw new IllegalArgumentException("refund cannot be null"); } apiContext.setRequestId(null); Object[] parameters = new Object[] {this.getId()}; String pattern = "v1/payments/sale/{0}/refund"; String resourcePath = RESTUtil.formatURIPath(pattern, parameters); String payLoad = refund.toJSON(); <START> Refund refund1 = configureAndExecute(apiContext, HttpMethod.POST, resourcePath, payLoad, Refund.class); <END> apiContext.setRequestId(null); return refund1; }</code><technical_language>rename refund1 more sensible. refundResponse response</technical_language>

Target:
public Refund refund(APIContext apiContext, Refund refund) throws PayPalRESTException { if (this.getId() == null) { throw new IllegalArgumentException("Id cannot be null"); } if (refund == null) { throw new IllegalArgumentException("refund cannot be null"); } apiContext.setRequestId(null); Object[] parameters = new Object[] {this.getId()}; String pattern = "v1/payments/sale/{0}/refund"; String resourcePath = RESTUtil.formatURIPath(pattern, parameters); String payLoad = refund.toJSON(); Refund refundResponse = configureAndExecute(apiContext, HttpMethod.POST, resourcePath, payLoad, Refund.class); apiContext.setRequestId(null); return refundResponse; }
Source:
<code>public FireDepartmentMetrics getMetrics(String datasource) { List<FireChief> chiefsOfDatasource = chiefs.get(datasource); if (chiefsOfDatasource == null || chiefsOfDatasource.size() == 0) { return null; } <START> return chiefsOfDatasource.get(0).getMetrics(); <END> }</code><technical_language>I merge metrics of datasource here</technical_language>

Target:
public FireDepartmentMetrics getMetrics(String datasource) { List<FireChief> chiefs = this.chiefs.get(datasource); if (chiefs == null) { return null; } FireDepartmentMetrics snapshot = null; for (FireChief chief : chiefs) { if (snapshot == null) { snapshot = chief.getMetrics().snapshot(); } else { snapshot.merge(chief.getMetrics()); } } return snapshot; }
Source:
<code>private void writeToFileStorage(Multimap<String, Serializable> map, boolean unlockFlush){ long startTime = System.currentTimeMillis(); log.debug("Flush queue. flushId {}. Current queue size is {}", startTime, map.size()); try { for (String logFilePath : map.keySet()) { Collection<Serializable> fileQueue = map.get(logFilePath); if (fileQueue.isEmpty()) { continue; } OutputStream os = null; LogWriterOutput objectOutput = null; try { if (fileStorage.exists(logFilePath)) { os = fileStorage.append(logFilePath); } else { os = fileStorage.create(logFilePath); } os = new BufferedOutputStream(os); objectOutput = getOutput(os); for(Serializable serializable: fileQueue){ objectOutput.writeObject(serializable); } } finally { try { Closeables.closeQuietly(objectOutput); Closeables.close(os, true); } catch (IOException e) { log.error(e.getMessage(), e); } } } }catch (Exception e){ log.error("Error during saving data to fileStorage", e); <START> <END> } finally { log.debug("Flush queue finished. flushId {}.Flush took: {}", startTime, (System.currentTimeMillis() - startTime)); if (unlockFlush) synchronized (lock){ lock.notifyAll(); } } }</code><technical_language>is good Exceptions appears store data file storage. i here. I propose add more catch clause (what deleted), catch Exception, log exception continue. idea is, if write 1 file, try write others</technical_language>

Target:
private void writeToFileStorage(Multimap<String, Serializable> map, boolean unlockFlush){ long startTime = System.currentTimeMillis(); log.debug("Flush queue. flushId {}. Current queue size is {}", startTime, map.size()); try { for (String logFilePath : map.keySet()) { Collection<Serializable> fileQueue = map.get(logFilePath); if (fileQueue.isEmpty()) { continue; } OutputStream os = null; LogWriterOutput objectOutput = null; try { if (fileStorage.exists(logFilePath)) { os = fileStorage.append(logFilePath); } else { os = fileStorage.create(logFilePath); } os = new BufferedOutputStream(os); objectOutput = getOutput(os); for(Serializable serializable: fileQueue){ objectOutput.writeObject(serializable); } }catch (Exception e){ log.error("Error during saving data with path to fileStorage", logFilePath, e); } finally { try { Closeables.closeQuietly(objectOutput); Closeables.close(os, true); } catch (IOException e) { log.error(e.getMessage(), e); } } } } finally { log.debug("Flush queue finished. flushId {}.Flush took: {}", startTime, (System.currentTimeMillis() - startTime)); if (unlockFlush) synchronized (lock){ lock.notifyAll(); } } }
Source:
<code>public boolean addUser(Login user) throws UserLoginException { <START> System.out.println("Inside loginserviceimpl of adduser()"); <END> boolean isCreateUser = false; String passwordHash = null; String saltValue = null; System.out.println("before the dao call"+isCreateUser); try{ saltValue = passwordService.generateRandomSalt(); System.out.println("salt value from the loginserviceimpl" + saltValue); passwordHash = new String(passwordService.calculateHash(saltValue.getBytes(), user.getPassword().getBytes())); System.out.println("After generating password hash from impl class-------"); }catch(PasswordServiceException e){ throw new UserLoginException("Error while calculating hash.", e); } catch (IOException ex) { java.util.logging.Logger.getLogger(LoginServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("generated passwordhash from loginserviceimpl...." + passwordHash); UserLogin userLoginEntity = new UserLogin(); System.out.println("user name for userlogin entity---"+user.getUserName()); userLoginEntity.setUserName(user.getUserName()); System.out.println("saltvalue for userlogin entity---"+saltValue); userLoginEntity.setSha1(passwordHash); userLoginEntity.setSalt(saltValue); isCreateUser = userLoginDAO.createUser(userLoginEntity); System.out.println("after the dao call"+isCreateUser); return isCreateUser; }</code><technical_language>Remove System.outs, replace log4j logging</technical_language>

Target:
public boolean addUser(Login user) throws UserLoginException { boolean isCreateUser = false; String passwordHash = null; String saltValue = null; try { saltValue = passwordService.generateRandomSalt(); passwordHash = new String(passwordService.calculateHash(saltValue.getBytes(), user.getPassword().getBytes())); } catch (PasswordServiceException e) { throw new UserLoginException("Error while calculating hash.", e); } UserLogin userLoginEntity = new UserLogin(); userLoginEntity.setUserName(user.getUserName()); userLoginEntity.setSha1(passwordHash); userLoginEntity.setSalt(saltValue); isCreateUser = userLoginDAO.createUser(userLoginEntity); return isCreateUser; }
Source:
<code>public DeployVirtualMachineOptions apply(CloudStackTemplateOptions templateOptions, Map<String, Network> networks, String zoneId, DeployVirtualMachineOptions options) { checkArgument(templateOptions.getSecurityGroupIds().isEmpty(), "security groups cannot be specified for locations (zones) that use advanced networking"); <START> if (templateOptions.getNetworks().size() > 0) { <END> options.networkIds(templateOptions.getNetworks()); } else if (templateOptions.getIpsToNetworks().isEmpty()) { checkArgument(!networks.isEmpty(), "please setup a network for zone: " + zoneId); Network defaultNetworkInZone = Iterables.getFirst(filter(networks.values(), and(defaultNetworkInZone(zoneId), supportsStaticNAT())), null); if (defaultNetworkInZone == null) { defaultNetworkInZone = Iterables.getFirst(filter(networks.values(), isIsolatedNetwork()), null); } if (defaultNetworkInZone == null) { throw new IllegalArgumentException("please choose a specific network in zone " + zoneId + ": " + networks); } else { options.networkId(defaultNetworkInZone.getId()); } } return options; }</code><technical_language>if (!templateOptions.getNetworks().isEmpty())</technical_language>

Target:
public DeployVirtualMachineOptions apply(CloudStackTemplateOptions templateOptions, Map<String, Network> networks, String zoneId, DeployVirtualMachineOptions options) { checkArgument(templateOptions.getSecurityGroupIds().isEmpty(), "security groups cannot be specified for locations (zones) that use advanced networking"); if (!templateOptions.getNetworks().isEmpty()) { options.networkIds(templateOptions.getNetworks()); } else if (templateOptions.getIpsToNetworks().isEmpty()) { checkArgument(!networks.isEmpty(), "please setup a network for zone: " + zoneId); Network defaultNetworkInZone = Iterables.getFirst(filter(networks.values(), and(defaultNetworkInZone(zoneId), supportsStaticNAT())), null); if (defaultNetworkInZone == null) { defaultNetworkInZone = Iterables.getFirst(filter(networks.values(), isIsolatedNetwork()), null); } if (defaultNetworkInZone == null) { throw new IllegalArgumentException("please choose a specific network in zone " + zoneId + ": " + networks); } else { options.networkId(defaultNetworkInZone.getId()); } } return options; }
Source:
<code><START> public static String getHumanishName(String aPath) { <END> if ("".equals(aPath)) { throw new IllegalArgumentException(); } String path = aPath; int s = path.lastIndexOf('/'); if (s != -1) path = path.substring(s + 1); if (path.endsWith(DOT_GIT)) { if (path.equals(DOT_GIT)) throw new IllegalArgumentException(); path = path.substring(0, path.length() - DOT_GIT.length()); } return path; }</code><technical_language>this instance method of URIish, calling getPath() internally? Also, I if "getBaseName()" "getName()" more suitable a name for this method. mirrors UNIX basename utility, while mirrors more java.io.File IResource API</technical_language>

Target:
public static String getHumanishName(String aPath) throws IllegalArgumentException { if ("".equals(aPath)) throw new IllegalArgumentException(); if (aPath.equals(DOT_GIT)) throw new IllegalArgumentException(); String[] elements = aPath.split("/"); String lastSegment = elements[elements.length - 1]; String result = lastSegment; if (lastSegment.endsWith(DOT_GIT)) result = lastSegment.substring(0, lastSegment.length() - DOT_GIT.length()); if (result.equals("")) result = elements[elements.length - 2]; if ("".equals(result)) throw new IllegalArgumentException(); return result; }
Source:
<code>private void configureSSLServerSocket(SSLServerSocket sslServerSocket) { SSLParameters sslParameters = sslServerSocket.getSSLParameters(); sslParameters.setNeedClientAuth(true); <START> if (cipherSuites != null) { <END> LOG.debug("Setup cipher suites for server socket: {}", Arrays.toString(cipherSuites)); sslParameters.setCipherSuites(cipherSuites); } sslServerSocket.setSSLParameters(sslParameters); }</code><technical_language>do need this check here? cipherSuites null reach here</technical_language>

Target:
private void configureSSLServerSocket(SSLServerSocket sslServerSocket) { SSLParameters sslParameters = sslServerSocket.getSSLParameters(); sslParameters.setNeedClientAuth(true); LOG.debug("Setup cipher suites for server socket: {}", Arrays.toString(cipherSuites)); sslParameters.setCipherSuites(cipherSuites); sslServerSocket.setSSLParameters(sslParameters); }
Source:
<code>public void loggedInUserPropertyFalseTest() throws Exception { <START> context.turnOffAuthorisationSystem(); <END> configurationService.setProperty("webui.user.assumelogin", false); context.restoreAuthSystemState(); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(get("/api/authn/status") .header("X-On-Behalf-Of", eperson.getID())) .andExpect(status().isBadRequest()); context.turnOffAuthorisationSystem(); configurationService.setProperty("webui.user.assumelogin", true); context.restoreAuthSystemState(); }</code><technical_language>turnOff is needed</technical_language>

Target:
public void loggedInUserPropertyFalseTest() throws Exception { configurationService.setProperty("webui.user.assumelogin", false); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(get("/api/authn/status") .header("X-On-Behalf-Of", eperson.getID())) .andExpect(status().isBadRequest()); }
Source:
<code>private void startUpdateTask(final String taskName, final String fileName) { try { this.getContainer().run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { synchronized (BatchImportTraceWizard.this) { SubMonitor sm; sm = SubMonitor.convert(monitor); sm.setTaskName(taskName); sm.setWorkRemaining(TOTALWORK); if (updateFiles(sm, fileName).getSeverity() == IStatus.CANCEL) { <START> ; <END> } sm.done(); } } }); } catch (InvocationTargetException e) { } catch (InterruptedException e) { } finally { } }</code><technical_language>remove empty if statement</technical_language>

Target:
private void startUpdateTask(final String taskName, final String fileName) { try { this.getContainer().run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { synchronized (BatchImportTraceWizard.this) { SubMonitor sm; sm = SubMonitor.convert(monitor); sm.setTaskName(taskName); sm.setWorkRemaining(TOTALWORK); if (updateFiles(sm, fileName).getSeverity() == IStatus.CANCEL) { } sm.done(); } } }); } catch (InvocationTargetException e) { } catch (InterruptedException e) { } finally { } }
Source:
<code>public Map<String, Object> modelAttributes(String identifier, Species species, List<BioentityPropertyName> orderedPropertyNames, String entityName, Map<BioentityPropertyName, Set<String>> propertyValuesByType) { addDesignElements(identifier, propertyValuesByType); Map<String, Object> result = new HashMap<>(); result.put("entityBriefName", StringUtils.isEmpty(entityName) ? identifier : entityName); result.put("entityFullName", StringUtils.isEmpty(entityName) ? identifier : MessageFormat.format("{0} ({1})", identifier, entityName)); result.put("bioEntityDescription", getBioEntityDescription(propertyValuesByType)); result.put("propertyNames", propertiesWeWillDisplay(orderedPropertyNames, propertyValuesByType)); result.put("bioentityProperties", GSON.toJson(bioentityProperties(identifier, species, orderedPropertyNames, propertyValuesByType))); <START> result.put("gene_id",identifier); <END> return result; }</code><technical_language>is this needed? retrieving bioentityProperties in JsonBioentityInformationController</technical_language>

Target:
public Map<String, Object> modelAttributes(String identifier, Species species, List<BioentityPropertyName> orderedPropertyNames, String entityName, Map<BioentityPropertyName, Set<String>> propertyValuesByType) { addDesignElements(identifier, propertyValuesByType); Map<String, Object> result = new HashMap<>(); result.put("entityBriefName", StringUtils.isEmpty(entityName) ? identifier : entityName); result.put("entityFullName", StringUtils.isEmpty(entityName) ? identifier : MessageFormat.format("{0} ({1})", identifier, entityName)); result.put("bioEntityDescription", getBioEntityDescription(propertyValuesByType)); result.put("propertyNames", propertiesWeWillDisplay(orderedPropertyNames, propertyValuesByType)); result.put("bioentityProperties", GSON.toJson(bioentityProperties(identifier, species, orderedPropertyNames, propertyValuesByType))); return result; }
Source:
<code>public int errorType() { <START> final String errorType = headers.get(ERROR_TYPE); if (errorType == null) { throw new IllegalStateException("Message is not an error"); } <END> try { return Integer.parseInt(errorType); } catch (NumberFormatException e) { throw new IllegalStateException("Error type must be a number"); } }</code><technical_language>start returning -1. change contract. I regret this throw new IllegalSt...</technical_language>

Target:
public int errorType() { String errorType = headers.get(ERROR_TYPE); if (errorType == null) { return -1; } try { return Integer.parseInt(errorType); } catch (NumberFormatException e) { throw new IllegalStateException("Error type must be a number"); } }
Source:
<code>@BeforeClass public static void beforeClass() throws UnknownHostException, MalformedURLException { String ipAddress = startAppiumServer(); if (service == null || !service.isRunning()) { throw new AppiumServerHasNotBeenStartedLocallyException("An appium server node is not started!"); } DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "Safari"); capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.IOS_XCUI_TEST); capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "11.3"); capabilities.setCapability(IOSMobileCapabilityType.LAUNCH_TIMEOUT, 500000); capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone 8"); <START> driver = new IOSDriver<>(new URL("http://" + ipAddress + ":4723/wd/hub"), capabilities); <END> }</code><technical_language>hardcoded port number</technical_language>

Target:
@BeforeClass public static void beforeClass() throws UnknownHostException, MalformedURLException { String ipAddress = startAppiumServer(); if (service == null || !service.isRunning()) { throw new AppiumServerHasNotBeenStartedLocallyException("An appium server node is not started!"); } DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "Safari"); capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.IOS_XCUI_TEST); capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "11.3"); capabilities.setCapability(IOSMobileCapabilityType.LAUNCH_TIMEOUT, 500000); capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone 8"); driver = new IOSDriver<>(new URL("http://" + ipAddress + ":" + PORT + "/wd/hub"), capabilities); }
Source:
<code>public void setUp() { <START> cp = new ClassPath(getPath("ant_project")); <END> }</code><technical_language>Requiring path in constructor unnecessary possibly interface troublesome in some cases (which yet). Is a reason for this? a variadic number (ClassPath(Path... paths)) handy</technical_language>

Target:
public void setUp() { cp = new ClassPath(TestUtils.getPath(getClass(), "ant_project")); }
Source:
<code>public RestParameter( String name, Object object) { this.name = name; if (object instanceof Collection) { StringBuilder stringBuilder = new StringBuilder(); String separator = ""; <START> for (Object element : (Collection) object) { <END> stringBuilder.append(separator).append(element); separator = ","; } stringValue = stringBuilder.toString(); } else if (object != null) { this.stringValue = object.toString(); } else { stringValue = ""; } }</code><technical_language>Collection<?> get raw type warning</technical_language>

Target:
public RestParameter( String name, Object object) { this.name = name; if (object instanceof Collection) { StringBuilder stringBuilder = new StringBuilder(); String separator = ""; for (Object element : (Collection<?>) object) { stringBuilder.append(separator).append(element); separator = ","; } stringValue = stringBuilder.toString(); } else if (object != null) { this.stringValue = object.toString(); } else { stringValue = ""; } }