auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void setBitreserveRequestInterceptorWithEmptyTokenShouldSetTheBitreserveCustomHeadersWithoutAuthenticationHeader() throws Exception { MockRestAdapter<Card> adapter = new MockRestAdapter<>("", null, null); adapter.request(new RepromiseFunction<BitreserveRestAdapter, Card>() { @Override public Promise<Card> call(BitreserveRestAdapter adapter) { User user = Fixtures.loadUser(); user.setBitreserveRestAdapter(adapter); return user.getCardById("foobar"); } }); Request request = adapter.getRequest(); Assert.assertEquals(request.getHeaders().size(), 3); Assert.assertTrue(request.getHeaders().contains(new Header("Accept", "application/json"))); <START> Assert.assertFalse(request.getHeaders().contains(new Header("Authorization", "Basic Zm9vYmFyOlgtT0F1dGgtQmFzaWM="))); <END> Assert.assertTrue(request.getHeaders().contains(new Header("Content-Type", "application/json"))); Assert.assertTrue(request.getHeaders().contains(new Header("User-Agent", "bitreserve-android-sdk 0.1 (<LINK_0>"))); }</code><technical_language>This is unnecessary asserting 3 headers</technical_language>

Target:
public void setBitreserveRequestInterceptorWithEmptyTokenShouldSetTheBitreserveCustomHeadersWithoutAuthenticationHeader() throws Exception { MockRestAdapter<Card> adapter = new MockRestAdapter<>("", null, null); adapter.request(new RepromiseFunction<BitreserveRestAdapter, Card>() { @Override public Promise<Card> call(BitreserveRestAdapter adapter) { User user = Fixtures.loadUser(); user.setBitreserveRestAdapter(adapter); return user.getCardById("foobar"); } }); Request request = adapter.getRequest(); Assert.assertEquals(request.getHeaders().size(), 3); Assert.assertTrue(request.getHeaders().contains(new Header("Accept", "application/json"))); Assert.assertTrue(request.getHeaders().contains(new Header("Content-Type", "application/json"))); Assert.assertTrue(request.getHeaders().contains(new Header("User-Agent", "bitreserve-android-sdk 0.1 (<LINK_0>"))); }
Source:
<code>public void testSubmitAndScheduleExtensionJob() throws Exception { clearDB(); submitCluster(); createExtensionPackage(); String packageBuildLib = new Path(EXTENSION_PATH, "libs/build/").toString(); String result = registerExtension("testExtension", EXTENSION_PATH, "testExtension"); Assert.assertEquals(result, "Extension :testExtension registered successfully."); createDir(PROCESS_APP_PATH); copyExtensionJar(packageBuildLib); APIResult submitResult = submitAndScheduleExtensionJob("testExtension", "testJob", null, null); <START> assertStatus(submitResult); <END> }</code><technical_language>Also, check if Entity is submitted is "RUNNING"</technical_language>

Target:
public void testSubmitAndScheduleExtensionJob() throws Exception { clearDB(); submitCluster(); createExtensionPackage(); String packageBuildLib = new Path(EXTENSION_PATH, "libs/build/").toString(); String result = registerExtension("testExtension", EXTENSION_PATH, "testExtension"); Assert.assertEquals(result, "Extension :testExtension registered successfully."); createDir(PROCESS_APP_PATH); copyExtensionJar(packageBuildLib); APIResult apiResult = submitAndScheduleExtensionJob("testExtension", "testJob", null, null); assertStatus(apiResult); apiResult = getClient().getStatus(EntityType.PROCESS, "sample", CLUSTER_NAME, null, false); assertStatus(apiResult); Assert.assertEquals(apiResult.getMessage(), "RUNNING"); }
Source:
<code>private static void testDiscardCorrectlyUpdatesLastAccessed(boolean discardSome) { CompositeByteBuf cbuf = compositeBuffer(); List<ByteBuf> buffers = new ArrayList<ByteBuf>(4); for (int i = 0; i < 4; i++) { ByteBuf buf = buffer().writeInt(i); <START> cbuf.capacity(cbuf.writerIndex()).addComponent(true, buf); <END> buffers.add(buf); } cbuf.skipBytes(2); if (discardSome) { cbuf.discardSomeReadBytes(); } else { cbuf.discardReadBytes(); } assertEquals(4, cbuf.numComponents()); cbuf.skipBytes(3); if (discardSome) { cbuf.discardSomeReadBytes(); } else { cbuf.discardReadBytes(); } assertEquals(3, cbuf.numComponents()); cbuf.skipBytes(3); assertEquals(2, cbuf.readInt()); if (discardSome) { cbuf.discardSomeReadBytes(); } else { cbuf.discardReadBytes(); } assertEquals(1, cbuf.numComponents()); assertEquals(3, cbuf.readInt()); if (discardSome) { cbuf.discardSomeReadBytes(); } else { cbuf.discardReadBytes(); } assertEquals(0, cbuf.numComponents()); for (ByteBuf buffer: buffers) { assertEquals(0, buffer.refCnt()); } assertTrue(cbuf.release()); }</code><technical_language>Curious .capacity(cbuf.writerIndex()) is needed here</technical_language>

Target:
private static void testDiscardCorrectlyUpdatesLastAccessed(boolean discardSome) { CompositeByteBuf cbuf = compositeBuffer(); List<ByteBuf> buffers = new ArrayList<ByteBuf>(4); for (int i = 0; i < 4; i++) { ByteBuf buf = buffer().writeInt(i); cbuf.addComponent(true, buf); buffers.add(buf); } cbuf.skipBytes(2); if (discardSome) { cbuf.discardSomeReadBytes(); } else { cbuf.discardReadBytes(); } assertEquals(4, cbuf.numComponents()); cbuf.skipBytes(3); if (discardSome) { cbuf.discardSomeReadBytes(); } else { cbuf.discardReadBytes(); } assertEquals(3, cbuf.numComponents()); cbuf.skipBytes(3); assertEquals(2, cbuf.readInt()); if (discardSome) { cbuf.discardSomeReadBytes(); } else { cbuf.discardReadBytes(); } assertEquals(1, cbuf.numComponents()); assertEquals(3, cbuf.readInt()); if (discardSome) { cbuf.discardSomeReadBytes(); } else { cbuf.discardReadBytes(); } assertEquals(0, cbuf.numComponents()); for (ByteBuf buffer: buffers) { assertEquals(0, buffer.refCnt()); } assertTrue(cbuf.release()); }
Source:
<code>public Method getOnCloseMethod(Object webSocketEndpoint) { Method[] methods = webSocketEndpoint.getClass().getMethods(); <START> for (Method method : methods) { <END> if (method.isAnnotationPresent(OnClose.class)) { return method; } } return null; }</code><technical_language>If methods variable null, for loop throw a NPE</technical_language>

Target:
public Method getOnCloseMethod(Object webSocketEndpoint) { Method[] methods = webSocketEndpoint.getClass().getMethods(); if (methods == null) { return null; } for (Method method : methods) { if (method.isAnnotationPresent(OnClose.class)) { return method; } } return null; }
Source:
<code>QueryResult executeQuery(String sql, QueryParam... params) throws QueryExecutionException; QueryResult executeQuery(String sql, QueryType queryType, QueryParam... params) throws QueryExecutionException; Connection getConnection(); <START> Optional<String> getConnector(); <END> void close(); static QueryResult query(String sql, QueryParam... params) throws QueryExecutionException { return defaultQueryExecutor().executeQuery(sql, params); }</code><technical_language>connector in this context? unclear</technical_language>

Target:
QueryResult executeQuery(String sql, QueryParam... params) throws QueryExecutionException; QueryResult executeQuery(String sql, QueryType queryType, QueryParam... params) throws QueryExecutionException; Connection getConnection(); void close(); static QueryResult query(String sql, QueryParam... params) throws QueryExecutionException { return defaultQueryExecutor().executeQuery(sql, params); }
Source:
<code>public EnketoAccountResponse savePformRegistration() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Basic " + userPasswdCombo); headers.add("Accept-Charset", "UTF-8"); EnketoAccountRequest body = new EnketoAccountRequest(ocURL, token); HttpEntity<EnketoAccountRequest> request = new HttpEntity<EnketoAccountRequest>(body, headers); RestTemplate rest = new RestTemplate(); ResponseEntity<EnketoAccountResponse> response = null; if (!checkExistingEnketoAccount()) { response = rest.postForEntity(enketoURL + "/accounts/api/v1/account", request, EnketoAccountResponse.class); } else { try { response = rest.exchange(enketoURL + "/accounts/api/v1/account", HttpMethod.PUT, request, EnketoAccountResponse.class, new HashMap<String, String>()); } catch (Exception e) { <START> logger.error(e.getMessage()); <END> } } return response.getBody(); }</code><technical_language>print entire stacktrace instead of message doing: logger.error(e);</technical_language>

Target:
public EnketoAccountResponse savePformRegistration() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Basic " + userPasswdCombo); headers.add("Accept-Charset", "UTF-8"); EnketoAccountRequest body = new EnketoAccountRequest(ocURL, token); HttpEntity<EnketoAccountRequest> request = new HttpEntity<EnketoAccountRequest>(body, headers); RestTemplate rest = new RestTemplate(); ResponseEntity<EnketoAccountResponse> response = null; if (!checkExistingEnketoAccount()) { response = rest.postForEntity(enketoURL + "/accounts/api/v1/account", request, EnketoAccountResponse.class); } else { try { response = rest.exchange(enketoURL + "/accounts/api/v1/account", HttpMethod.PUT, request, EnketoAccountResponse.class, new HashMap<String, String>()); } catch (Exception e) { logger.error("Error while changing the EnketoURL: ", e); } } return response.getBody(); }
Source:
<code>public static String getGzBaseName(String fname) { if (isGz(fname)) { <START> return fname.substring(0, fname.length() - GZ_SUFFIX.length()); <END> } throw new IAE("[%s] is not a valid gz file name", fname); }</code><technical_language>Files.getNameWithoutExtension here</technical_language>

Target:
public static String getGzBaseName(String fname) { final String reducedFname = Files.getNameWithoutExtension(fname); if (isGz(fname) && !reducedFname.isEmpty()) { return reducedFname; } throw new IAE("[%s] is not a valid gz file name", fname); }
Source:
<code>public void insertTest() { String insertKey = "user0"; Map<String, ByteIterator> insertMap = insertRow(insertKey); OPartitionedDatabasePool pool = orientDBClient.getDatabasePool(); <START> ODatabaseDocumentTx db = pool.acquire(); <END> try { ODictionary<ORecord> dictionary = db.getDictionary(); ODocument result = dictionary.get(insertKey); assertTrue("Assert a row was inserted.", result != null); for (int i = 0; i < NUM_FIELDS; i++) { assertEquals("Assert all inserted columns have correct values.", result.field(FIELD_PREFIX + i), insertMap.get(FIELD_PREFIX + i).toString()); } } finally { db.close(); } }</code><technical_language>This a try w/ resources. other pool.acquire() calls</technical_language>

Target:
public void insertTest() { String insertKey = "user0"; Map<String, ByteIterator> insertMap = insertRow(insertKey); OPartitionedDatabasePool pool = orientDBClient.getDatabasePool(); try(ODatabaseDocumentTx db = pool.acquire()) { ODictionary<ORecord> dictionary = db.getDictionary(); ODocument result = dictionary.get(insertKey); assertTrue("Assert a row was inserted.", result != null); for (int i = 0; i < NUM_FIELDS; i++) { assertEquals("Assert all inserted columns have correct values.", result.field(FIELD_PREFIX + i), insertMap.get(FIELD_PREFIX + i).toString()); } } }
Source:
<code>private void askToOpenProject(StagingEntry stagingEntry) { IResource resource = CommonUtils.getAdapterForObject(stagingEntry, IResource.class); if (resource != null) { IProject project = resource.getProject(); <START> if (!project.isOpen()) { <END> if (MessageDialog.openQuestion(getSite().getShell(), UIText.StagingView_ProjectIsClosed, MessageFormat.format(UIText.StagingView_OpenProject, project.getName()))) { try { project.open(null); } catch (CoreException e) { Activator.handleError( UIText.StagingView_openingProjectFailed, e, true); } } } } }</code><technical_language>Needs check project exists all. Otherwise, if project is closed removed workspace altogether, get exception ugly error dialog</technical_language>

Target:
private void askToOpenProject(StagingEntry stagingEntry) { IResource resource = CommonUtils.getAdapterForObject(stagingEntry, IResource.class); if (resource != null) { IProject project = resource.getProject(); if (!project.isOpen() && project.exists()) { if (MessageDialog.openQuestion(getSite().getShell(), UIText.StagingView_ProjectIsClosed, MessageFormat.format(UIText.StagingView_OpenProject, project.getName()))) { try { project.open(null); } catch (CoreException e) { Activator.handleError( UIText.StagingView_openingProjectFailed, e, true); } } } } }
Source:
<code>private void updateChecksum(SPath docPath, Set<SPath> localEditors, Set<SPath> remoteEditors) { DocumentChecksum checksum = documentChecksums.get(docPath); if (checksum == null) { checksum = new DocumentChecksum(docPath); documentChecksums.put(docPath, checksum); } if (!docPath.getFile().exists()) { <START> LOG.debug("Marking checksum for " + docPath <END> + " as dirty as the file no longer exists locally: " + checksum); checksum.markDirty(); checksum.update(null); return; } else if (!checksum.isDirty()) { return; } String content = editorManager.getContent(checksum.getPath()); if (content == null) { if (localEditors.contains(checksum.getPath())) { LOG.error("EditorManager is in an inconsistent state. " + "It is reporting a locally open editor but no" + " document could be found in the underlying file system: " + checksum); } if (!remoteEditors.contains(checksum.getPath())) { documentChecksums.remove(checksum.getPath()); return; } } checksum.update(content); }</code><technical_language>I find this log message confusing read affected user started recovery. marking checksum dirty actual benefit do this risk update(null) call applied checksum</technical_language>

Target:
private void updateChecksum(SPath docPath, Set<SPath> localEditors, Set<SPath> remoteEditors) { DocumentChecksum checksum = documentChecksums.get(docPath); if (checksum == null) { checksum = new DocumentChecksum(docPath); documentChecksums.put(docPath, checksum); } if (checksum.getHash() != DocumentChecksum.NOT_AVAILABLE && !docPath .getFile().exists()) { LOG.debug("Updating checksum for " + docPath + " to correctly " + "represent that the file no longer exists locally: " + checksum); checksum.markDirty(); checksum.update(null); return; } else if (!checksum.isDirty()) { return; } String content = editorManager.getContent(checksum.getPath()); if (content == null) { if (localEditors.contains(checksum.getPath())) { LOG.error("EditorManager is in an inconsistent state. " + "It is reporting a locally open editor but no" + " document could be found in the underlying file system: " + checksum); } if (!remoteEditors.contains(checksum.getPath())) { documentChecksums.remove(checksum.getPath()); return; } } checksum.update(content); }
Source:
<code>public StoreChangelogReader(final Time time, final StreamsConfig config, final LogContext logContext, final Consumer<byte[], byte[]> restoreConsumer, final StateRestoreListener stateRestoreListener) { this.time = time; this.log = logContext.logger(StoreChangelogReader.class); this.state = ChangelogReaderState.ACTIVE_RESTORING; this.restoreConsumer = restoreConsumer; this.stateRestoreListener = stateRestoreListener; <START> this.pollTimeMs = Duration.ofMillis(config.getLong(StreamsConfig.POLL_MS_CONFIG)); <END> this.updateOffsetIntervalMs = config.getLong(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG) == Long.MAX_VALUE ? DEFAULT_OFFSET_UPDATE_MS : config.getLong(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG); this.lastUpdateOffsetTime = 0L; this.changelogs = new HashMap<>(); }</code><technical_language>type of pollTimeMs is *Duration*. "ms" is a bit redundant</technical_language>

Target:
public StoreChangelogReader(final Time time, final StreamsConfig config, final LogContext logContext, final Consumer<byte[], byte[]> restoreConsumer, final StateRestoreListener stateRestoreListener) { this.time = time; this.log = logContext.logger(StoreChangelogReader.class); this.state = ChangelogReaderState.ACTIVE_RESTORING; this.restoreConsumer = restoreConsumer; this.stateRestoreListener = stateRestoreListener; this.pollTime = Duration.ofMillis(config.getLong(StreamsConfig.POLL_MS_CONFIG)); this.updateOffsetIntervalMs = config.getLong(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG) == Long.MAX_VALUE ? DEFAULT_OFFSET_UPDATE_MS : config.getLong(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG); this.lastUpdateOffsetTime = 0L; this.changelogs = new HashMap<>(); }
Source:
<code>public void started() { <START> try { <END> startDicomOrderFiller(); } catch (Exception e) { } typeAndRoles(); }</code><technical_language>try-catch block is redundant here, exceptions caught logged in startDicomOrderFiller method</technical_language>

Target:
public void started() { startDicomOrderFiller(); typeAndRoles(); }
Source:
<code>public void setMinZoom(final int level) <START> { <END> if (this.minZoom != level) { this.minZoom = level; AjaxRequestTarget target = getRequestCycle().find(AjaxRequestTarget.class); if (target != null && findPage() != null) { target.appendJavaScript(getJSsetMinZoom(minZoom)); } } }</code><technical_language>Do want check parameter non-negative</technical_language>

Target:
public void setMinZoom(final int level) { if (this.minZoom != level) { this.minZoom = level >= 0 ? level : 0; AjaxRequestTarget target = getRequestCycle().find(AjaxRequestTarget.class); if (target != null && findPage() != null) { target.appendJavaScript(getJSsetMinZoom(minZoom)); } } }
Source:
<code>public String toString() { <START> return TimeTZType.formatTime(this); <END> }</code><technical_language>TimeTZParser.formatTime, of class TimeTZType extends DataType<TimeTZ></technical_language>

Target:
public String toString() { return TimeTZParser.formatTime(this); }
Source:
<code>public static ObjectInserter createDryRunInserter() { return new ObjectInserter() { @Override public ObjectId insert(int objectType, long length, InputStream in) throws IOException { <START> return createRandomObjectId(); <END> } @Override public PackParser newPackParser(InputStream in) throws IOException { throw new UnsupportedOperationException(); } @Override public void flush() throws IOException { } @Override public void release() { } }; }</code><technical_language>random? really? I idFor(). public ObjectId insert(int objectType, byte[] data) { return idFor(type, data); } public ObjectId insert(int type, long len, InputStream in) { return idFor(type, len, in); } that. I forget of insert methods is "bottom" of call stack punting InputStream version is required, I implement in terms of idFor return actual SHA-1</technical_language>

Target:
public static ObjectInserter createDryRunInserter() { return new ObjectInserter() { private final MutableObjectId buf = new MutableObjectId(); private final static int LAST_BYTE = Constants.OBJECT_ID_LENGTH - 1; @Override public ObjectId insert(int objectType, long length, InputStream in) throws IOException { buf.setByte(LAST_BYTE, buf.getByte(LAST_BYTE) + 1); return buf.copy(); } @Override public PackParser newPackParser(InputStream in) throws IOException { throw new UnsupportedOperationException(); } @Override public void flush() throws IOException { } @Override public void release() { } }; }
Source:
<code>public void testPointAsText() throws Exception { Client client = getClient(); populateTables(client); VoltTable vt = client.callProcedure("@AdHoc", "select loc, asText(loc) from places order by pk").getResults()[0]; while (vt.advanceRow()) { GeographyPointValue gpv = vt.getPoint(0); if (gpv == null) { assertEquals(null, vt.getString(1)); } else { String wkt = vt.getString(1); <START> assertEquals(gpv.toString().toLowerCase(), wkt.toLowerCase()); <END> } } }</code><technical_language>Please test casing WKT produced Java C++ is same</technical_language>

Target:
public void testPointAsText() throws Exception { Client client = getClient(); populateTables(client); client.callProcedure("places.Insert", 50, "Someplace1", GeographyPointValue.geographyPointFromText("POINT(13.4999999999995 17)")); client.callProcedure("places.Insert", 51, "Someplace2", GeographyPointValue.geographyPointFromText("POINT(-13.499999999999999995 -17)")); VoltTable vt = client.callProcedure("@AdHoc", "select loc, asText(loc) from places order by pk").getResults()[0]; while (vt.advanceRow()) { GeographyPointValue gpv = vt.getPoint(0); if (gpv == null) { assertEquals(null, vt.getString(1)); } else { assertEquals(gpv.toString(), vt.getString(1)); } } }
Source:
<code>private void retryTransferTask(InboundTransferTask task, Set<Address> excludedSources) { if (trace) log.tracef("Retrying failed task: %s", task); <START> synchronized (StateConsumerImpl.this) { <END> Set<Integer> failedSegments = new HashSet<Integer>(); if (removeTransfer(task)) { excludedSources.add(task.getSource()); failedSegments.addAll(task.getSegments()); } failedSegments.retainAll(getOwnedSegments(cacheTopology.getWriteConsistentHash())); failedSegments.removeAll(getOwnedSegments(cacheTopology.getReadConsistentHash())); Map<Address, Set<Integer>> sources = new HashMap<Address, Set<Integer>>(); findSources(failedSegments, sources, excludedSources); for (Map.Entry<Address, Set<Integer>> e : sources.entrySet()) { addTransfer(e.getKey(), e.getValue()); } } }</code><technical_language>This synchronized (this) now. I this I expected in a class, longer</technical_language>

Target:
private void retryTransferTask(InboundTransferTask task, Set<Address> excludedSources) { if (trace) log.tracef("Retrying failed task: %s", task); synchronized (transferMapsLock) { Set<Integer> failedSegments = new HashSet<Integer>(); if (removeTransfer(task)) { excludedSources.add(task.getSource()); failedSegments.addAll(task.getSegments()); } failedSegments.retainAll(getOwnedSegments(cacheTopology.getWriteConsistentHash())); failedSegments.removeAll(getOwnedSegments(cacheTopology.getReadConsistentHash())); Map<Address, Set<Integer>> sources = new HashMap<Address, Set<Integer>>(); findSources(failedSegments, sources, excludedSources); for (Map.Entry<Address, Set<Integer>> e : sources.entrySet()) { addTransfer(e.getKey(), e.getValue()); } } }
Source:
<code>@Override protected boolean isNumericVector(VectorStorage storage) { try { <START> Field f = storage.getClass().getDeclaredField("data"); <END> f.setAccessible(true); double[] arr = (double[]) f.get(storage); return storage.isNumeric() && (arr != null || !isRaw(storage)); } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>sense protected getter getData? case field is renamed</technical_language>

Target:
@Override protected boolean isNumericVector(VectorStorage storage) { try { double[] arr = ((DenseVectorStorage)storage).getData(); return storage.isNumeric() && (arr != null || !isRaw(storage)); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>public AnnotationVisitor visitAnnotation(String desc, boolean visible) { Type type = getType(desc); for (Type annotationType : annotationTypes) { if (annotationType.equals(type)) { Type[] args = methodDesc == null ? new Type[0] : getArgumentTypes(methodDesc); Class[] argClasses = new Class[args.length]; for (int i = 0; i < args.length; i++) { try { switch(args[i].getSort()) { case OBJECT: case ARRAY: argClasses[i] = classFromInternalName(args[i].getInternalName()); break; case BOOLEAN: argClasses[i] = boolean.class; break; case BYTE: argClasses[i] = byte.class; break; case CHAR: argClasses[i] = char.class; break; case DOUBLE: argClasses[i] = double.class; break; case FLOAT: argClasses[i] = float.class; break; case INT: argClasses[i] = int.class; break; case LONG: argClasses[i] = long.class; break; case SHORT: argClasses[i] = short.class; break; } } catch(NullPointerException e) { <START> System.out.println("here"); <END> } } try { if("<init>".equals(name)) annotatedConstructors.add(selfClass().getDeclaredConstructor(argClasses)); else annotatedMethods.add(selfClass().getDeclaredMethod(name, argClasses)); } catch (NoSuchMethodException e) { throw new IllegalStateException(e); } break; } } return super.visitAnnotation(desc, visible); }</code><technical_language>Log error slf4j if safe ignore throw exception</technical_language>

Target:
public AnnotationVisitor visitAnnotation(String desc, boolean visible) { Type type = getType(desc); for (Type annotationType : annotationTypes) { if (annotationType.equals(type)) { Type[] args = methodDesc == null ? new Type[0] : getArgumentTypes(methodDesc); Class[] argClasses = new Class[args.length]; for (int i = 0; i < args.length; i++) { switch(args[i].getSort()) { case OBJECT: case ARRAY: argClasses[i] = classFromInternalName(args[i].getInternalName()); break; case BOOLEAN: argClasses[i] = boolean.class; break; case BYTE: argClasses[i] = byte.class; break; case CHAR: argClasses[i] = char.class; break; case DOUBLE: argClasses[i] = double.class; break; case FLOAT: argClasses[i] = float.class; break; case INT: argClasses[i] = int.class; break; case LONG: argClasses[i] = long.class; break; case SHORT: argClasses[i] = short.class; break; } } try { if("<init>".equals(name)) annotatedConstructors.add(selfClass().getDeclaredConstructor(argClasses)); else annotatedMethods.add(selfClass().getDeclaredMethod(name, argClasses)); } catch (NoSuchMethodException e) { throw new IllegalStateException(e); } break; } } return super.visitAnnotation(desc, visible); }
Source:
<code>private void writeOutUsersDotAttributesFile(File userAttributesFile) { Map<String, Object> json = null; try (InputStream stream = Files.newInputStream(Paths.get(userAttributesFile.toURI()))) { <START> if ((json = MAPPER.parser().parseMap(stream)) == null) { <END> LOGGER.debug("Json not found"); return; } addGuestClaimsProfileAttributes(json); if (json.containsKey(oldHostName)) { json.put(System.getProperty(SystemBaseUrl.HOST), json.remove(oldHostName)); } for (Map.Entry<String, Object> entry : json.entrySet()) { json.put(entry.getKey(), replaceLocalhost(entry.getValue())); } } catch (IOException e) { LOGGER.warn("Unable to read system user attribute file for hostname update.", e); } if (json != null) { try { FileUtils.writeStringToFile(userAttributesFile, Boon.toPrettyJson(json)); } catch (IOException e) { LOGGER.warn("Unable to write user attribute file for system update.", e); } } }</code><technical_language>reason this is 1 line instead of set conditional</technical_language>

Target:
private void writeOutUsersDotAttributesFile(File userAttributesFile) { Map<String, Object> json = null; try (InputStream stream = Files.newInputStream(Paths.get(userAttributesFile.toURI()))) { json = MAPPER.parser().parseMap(stream); } catch (IOException e) { LOGGER.warn("Unable to read system user attribute file for hostname update.", e); return; } addGuestClaimsProfileAttributes(json); if (json.containsKey(oldHostName)) { json.put(System.getProperty(SystemBaseUrl.HOST), json.remove(oldHostName)); } for (Map.Entry<String, Object> entry : json.entrySet()) { json.put(entry.getKey(), replaceLocalhost(entry.getValue())); } try { FileUtils.writeStringToFile( userAttributesFile, Boon.toPrettyJson(json), Charset.defaultCharset()); } catch (IOException e) { LOGGER.warn("Unable to write user attribute file for system update.", e); } }
Source:
<code>public static void login(HttpClient client, String username, String password) throws IOException, InterruptedException, SAXException, ParserConfigurationException { ContentExchange exchange = new ContentExchange(); exchange.setMethod("POST"); <START> exchange.setURL(getSoapURL()); <END> exchange.setRequestContentSource(new ByteArrayInputStream(soapXmlForLogin( username, password))); exchange.setRequestHeader("Content-Type", "text/xml"); exchange.setRequestHeader("SOAPAction", "''"); exchange.setRequestHeader("PrettyPrint", "Yes"); client.send(exchange); exchange.waitForDone(); String response = exchange.getResponseContent(); String tagSession = "<sessionId>"; String tagserverUrl = "<serverUrl>"; String serverUrl = response.substring(response.indexOf(tagserverUrl) + tagserverUrl.length(), response.indexOf("</serverUrl>")); sessionId = response.substring(response.indexOf(tagSession) + tagSession.length(), response.indexOf("</sessionId>")); LoginUrl = serverUrl.substring(0, serverUrl.indexOf("/services")); }</code><technical_language>MalformedURLException caught print error log</technical_language>

Target:
public static void login(HttpClient client, String username, String password) throws IOException, InterruptedException, SAXException, ParserConfigurationException { try { ContentExchange exchange = new ContentExchange(); exchange.setMethod("POST"); exchange.setURL(getSoapURL()); exchange.setRequestContentSource(new ByteArrayInputStream(soapXmlForLogin( username, password))); exchange.setRequestHeader("Content-Type", "text/xml"); exchange.setRequestHeader("SOAPAction", "''"); exchange.setRequestHeader("PrettyPrint", "Yes"); client.send(exchange); exchange.waitForDone(); try { String response = exchange.getResponseContent(); String tagSession = "<sessionId>"; String tagServerUrl = "<serverUrl>"; String serverUrl = response.substring(response.indexOf(tagServerUrl) + tagServerUrl.length(), response.indexOf("</serverUrl>")); sessionId = response.substring(response.indexOf(tagSession) + tagSession.length(), response.indexOf("</sessionId>")); LoginUrl = serverUrl.substring(0, serverUrl.indexOf("/services")); } catch (IndexOutOfBoundsException e) { log.error("Login credentials of Salesforce is wrong...."); throw new SynapseException("Login credentials of Salesforce is wrong....", e); } } catch (MalformedURLException e) { log.error("Error while building URL", e); } catch (InterruptedException e) { log.error("Error in exchange the asynchronous message", e); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { log.error("Error while login to Salesforce" + e.getMessage(), e); } }
Source:
<code>public <V> V run(String callableName, Callable<V> callable) throws Exception { requireNonNull(callableName, "callableName is null"); requireNonNull(callable, "callable is null"); long startTime = System.nanoTime(); int attempt = 0; while (true) { attempt++; try { return callable.call(); } catch (Exception e) { if (attempt >= maxAttempts || Duration.nanosSince(startTime).compareTo(maxRetryTime) >= 0) { <START> throw e; <END> } log.debug("Failed on executing %s with attempt %d, will retry. Exception: %s", callableName, attempt, e.getMessage()); int delayInMs = (int) Math.min(DEFAULT_SLEEP_TIME.toMillis() * Math.pow(scaleFactor, attempt - 1), DEFAULT_SLEEP_TIME.toMillis()); int jitter = ThreadLocalRandom.current().nextInt(Math.max(1, (int) (delayInMs * 0.1))); try { TimeUnit.MILLISECONDS.sleep(delayInMs + jitter); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RuntimeException(ie); } } } }</code><technical_language>nice is exceptions causing retry do in com.facebook.presto.hive.RetryDriver (see addSuppressed in class). helpful debugging issues</technical_language>

Target:
public <V> V run(String callableName, Callable<V> callable) throws Exception { requireNonNull(callableName, "callableName is null"); requireNonNull(callable, "callable is null"); List<Throwable> suppressedExceptions = new ArrayList<>(); long startTime = System.nanoTime(); int attempt = 0; while (true) { attempt++; try { return callable.call(); } catch (Exception e) { if (attempt >= maxAttempts || Duration.nanosSince(startTime).compareTo(maxRetryTime) >= 0) { addSuppressed(e, suppressedExceptions); throw e; } log.debug("Failed on executing %s with attempt %d, will retry. Exception: %s", callableName, attempt, e.getMessage()); suppressedExceptions.add(e); int delayInMs = (int) Math.min(DEFAULT_SLEEP_TIME.toMillis() * Math.pow(DEFAULT_SCALE_FACTOR, attempt - 1), DEFAULT_SLEEP_TIME.toMillis()); int jitter = ThreadLocalRandom.current().nextInt(Math.max(1, (int) (delayInMs * 0.1))); try { MILLISECONDS.sleep(delayInMs + jitter); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RuntimeException(ie); } } } }
Source:
<code>public ASTNode transform(KApp node) throws TransformerException { ASTNode rez = node.getChild().accept(this); if (rez == null) node.setChild(KList.EMPTY); else if (rez instanceof KList) node.setChild((KList) rez); <START> else { <END> KList contents = new KList(); contents.getContents().add((Term) rez); node.setChild(contents); } return node; }</code><technical_language>This weird me. for a transformation of a KList return a KList return element turned a KList caller</technical_language>

Target:
public ASTNode transform(KApp node) throws TransformerException { ASTNode rez = node.getChild().accept(this); assert rez != null; if (rez instanceof KList) node.setChild((KList) rez); else { KList contents = new KList(); contents.getContents().add((Term) rez); node.setChild(contents); } return node; }
Source:
<code><START> protected boolean isValid() { <END> return binder.isValid(); }</code><technical_language>I guess this public well? handy in places, need get binder separatly</technical_language>

Target:
public boolean isValid() { return binder.isValid(); }
Source:
<code>public AbstractSpeechSynthesisMeta() { addPeer("audioFile", "AudioFile", "audioFile"); addCategory("speech"); addDependency("org.myrobotlab.audio", "voice-effects", "1.0", "zip"); <START> addDependency("javazoom", "jlayer", "1.0.1"); <END> addDependency("com.googlecode.soundlibs", "mp3spi", "1.9.5.4"); }</code><technical_language>This class is useless. of subclasses call super() i tell. . if did.. speech synt force jlayer mp3spi a dependency. this class useful remove it</technical_language>

Target:
public AbstractSpeechSynthesisMeta() { addPeer("audioFile", "AudioFile", "audioFile"); addCategory("speech"); addDependency("org.myrobotlab.audio", "voice-effects", "1.0", "zip"); }
Source:
<code>public void testInsertDynamicNullArrayInBulk() throws Exception { execute("create table foo (value integer) with (number_of_replicas=0, column_policy = 'dynamic')"); var listWithNull = new ArrayList<>(1); listWithNull.add(null); long[] rowCounts = execute("insert into foo (bar) values (?)", new Object[][]{ new Object[]{listWithNull}, new Object[]{List.of(1, 2)}, }); <START> refresh(); <END> assertThat(rowCounts[0], is(1L)); assertThat(rowCounts[1], is(1L)); waitForMappingUpdateOnAll("foo", "bar"); execute("select data_type from information_schema.columns where table_name = 'foo' and column_name = 'bar'"); assertThat(response.rows()[0][0], is("bigint_array")); }</code><technical_language>suggestion refresh necessary</technical_language>

Target:
public void testInsertDynamicNullArrayInBulk() throws Exception { execute("create table foo (value integer) with (number_of_replicas=0, column_policy = 'dynamic')"); var listWithNull = new ArrayList<>(1); listWithNull.add(null); long[] rowCounts = execute("insert into foo (bar) values (?)", new Object[][]{ new Object[]{listWithNull}, new Object[]{List.of(1, 2)}, }); assertThat(rowCounts[0], is(1L)); assertThat(rowCounts[1], is(1L)); waitForMappingUpdateOnAll("foo", "bar"); execute("select data_type from information_schema.columns where table_name = 'foo' and column_name = 'bar'"); assertThat(response.rows()[0][0], is("bigint_array")); }
Source:
<code>private String getTeamStr(ArtifactReadable action) { String results = action.getSoleAttributeAsString(AtsAttributeTypes.TeamDefinition, ""); if (Strings.isValid(results)) { results = atsServer.getArtifactByGuid(results).getName(); } else { ArtifactReadable teamWf = getParentTeamWf(action); if (teamWf != null) { <START> return getTeamStr(teamWf); <END> } } return results; }</code><technical_language>For consistency, suggest replace return results =</technical_language>

Target:
private String getTeamStr(ArtifactReadable action) { String results = action.getSoleAttributeAsString(AtsAttributeTypes.TeamDefinition, ""); if (Strings.isValid(results)) { results = atsServer.getArtifactByGuid(results).getName(); } else { ArtifactReadable teamWf = getParentTeamWf(action); if (teamWf != null) { results = getTeamStr(teamWf); } } return results; }
Source:
<code>public SqlArrayTypes register(Class<?> elementType, String sqlTypeName) { <START> final Optional<SqlArrayType<?>> arrayType = Optional.of(SqlArrayType.of(sqlTypeName, Function.identity())); <END> return register((type, c) -> elementType == type ? arrayType : Optional.empty()); }</code><technical_language>SqlArrayTypeFactory.of() instead of duplicating type check</technical_language>

Target:
public SqlArrayTypes register(Class<?> elementType, String sqlTypeName) { return register(SqlArrayTypeFactory.of(elementType, sqlTypeName, Function.identity())); }
Source:
<code><START> public void objectValue(DistinctQueryType queryType) { <END> String resource = String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}", 117546, "xxyyzz-abc"); DistinctMap distinctMap = DistinctMap.create(queryType, null); Utils.ValueHolder<String> outHash = new Utils.ValueHolder<>(); boolean add = distinctMap.add(resource, outHash); assertThat(add).as("Value should be added first time").isTrue(); boolean add2 = distinctMap.add(resource, outHash); assertThat(add2).as("same value should not be added again").isFalse(); resource = String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}", 117546, "xxy%zz-abc"); boolean add3 = distinctMap.add(resource, outHash); assertThat(add3).as("different value should be added again").isTrue(); }</code><technical_language>need a test for objects property values shuffeled: { "name" : "John", "age": 24 } { "age": 24, "name" : "John" } hash same, ordered of JSON properties matter</technical_language>

Target:
public void objectValue(DistinctQueryType queryType) { String resourceString = String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}", 117546, "xxyyzz-abc"); Document resource = new Document(resourceString); DistinctMap distinctMap = DistinctMap.create(queryType, null); Utils.ValueHolder<String> outHash = new Utils.ValueHolder<>(); boolean add = distinctMap.add(resource, outHash); assertThat(add).as("Value should be added first time").isTrue(); boolean add2 = distinctMap.add(resource, outHash); assertThat(add2).as("same value should not be added again").isFalse(); resourceString = String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}", 117546, "xxy%zz-abc"); resource = new Document(resourceString); boolean add3 = distinctMap.add(resource, outHash); assertThat(add3).as("different value should be added again").isTrue(); }
Source:
<code>private void handleAnyChildSPMTaskCompletion(boolean succeeded) { List<Guid> childCommandIds = CommandCoordinatorUtil.getChildCommandIds(getCommandId()); if (childCommandIds.isEmpty()) { return; } Guid currentChildId = childCommandIds.get(0); log.info("Handling child command completion", currentChildId); if (!Guid.isNullOrEmpty(currentChildId)) { CommandBase<?> command = CommandCoordinatorUtil.retrieveCommand(currentChildId); CommandEntity cmdEntity = CommandCoordinatorUtil.getCommandEntity(currentChildId); if (command != null && cmdEntity != null && !cmdEntity.isCallbackNotified()) { if (!succeeded) { command.getParameters().setTaskGroupSuccess(false); } Backend.getInstance().endAction(VdcActionType.ExtendImageSize, command.getParameters(), cloneContextAndDetachFromParent()); <START> if (succeeded && CommandCoordinatorUtil.getCommandEntity(currentChildId) != null) { <END> CommandCoordinatorUtil.getCommandEntity(currentChildId).setCallbackNotified(true); } } } }</code><technical_language>CommandCoordinatorUtil.getCommandEntity(currentChildId) is withing next lines. Please extract a local variable</technical_language>

Target:
private void handleAnyChildSPMTaskCompletion(boolean succeeded) { List<Guid> childCommandIds = CommandCoordinatorUtil.getChildCommandIds(getCommandId()); if (childCommandIds.isEmpty()) { return; } Guid currentChildId = childCommandIds.get(0); log.info("Handling child command completion", currentChildId); if (!Guid.isNullOrEmpty(currentChildId)) { CommandBase<?> command = CommandCoordinatorUtil.retrieveCommand(currentChildId); CommandEntity cmdEntity = CommandCoordinatorUtil.getCommandEntity(currentChildId); if (command != null && cmdEntity != null && !cmdEntity.isCallbackNotified()) { if (!succeeded) { command.getParameters().setTaskGroupSuccess(false); } Backend.getInstance().endAction(VdcActionType.ExtendImageSize, command.getParameters(), cloneContextAndDetachFromParent()); if (succeeded && cmdEntity != null) { cmdEntity.setCallbackNotified(true); } } } }
Source:
<code>public static ProtocolType valueOf(int ordinal) { <START> return ProtocolType.values()[ordinal]; <END> }</code><technical_language>If endpoints frequently deserialized, a good idea cache ProtocolType.values() avoid creating a new array invocation</technical_language>

Target:
public static ProtocolType valueOf(int ordinal) { return PROTOCOL_TYPES[ordinal]; }
Source:
<code>public void setDensity(int density) { if(density < 150 || density > 1200) { <START> throw new IllegalArgumentException("Invalid density value"); <END> } this.density = density; }</code><technical_language>Please values in Exception message</technical_language>

Target:
public void setDensity(int density) { if(density < 150 || density > 1200) { throw new IllegalArgumentException("Invalid density value. Valid range of values is 150-1200."); } this.density = density; }
Source:
<code>private static <T> Predicate<T> isEmpty(String field, RequestScope requestScope) { return (T entity) -> { Object val = getFieldValue(entity, field, requestScope); if (val == null) { return true; } <START> if (val instanceof String) { <END> return ((String) val).isEmpty(); } if (val instanceof Collection<?>) { return ((Collection<?>) val).isEmpty(); } if (val instanceof Map<?, ?>) { return ((Map<?, ?>) val).isEmpty(); } return false; }; }</code><technical_language>i feel collection map handled</technical_language>

Target:
private static <T> Predicate<T> isEmpty(String field, RequestScope requestScope) { return (T entity) -> { Object val = getFieldValue(entity, field, requestScope); if (val == null) { return false; } if (val instanceof Collection<?>) { return ((Collection<?>) val).isEmpty(); } if (val instanceof Map<?, ?>) { return ((Map<?, ?>) val).isEmpty(); } return false; }; }
Source:
<code>private void send(LanguageServer server, String path, FileChangeType changeType) { <START> RegisteredProject project = projectManager.getClosestOrNull(path); <END> if (project == null) { return; } DidChangeWatchedFilesParams params = new DidChangeWatchedFilesParams( Collections.singletonList(new FileEvent(prefixURI(path), changeType))); server.getWorkspaceService().didChangeWatchedFiles(params); }</code><technical_language>is this check necessary</technical_language>

Target:
private void send(LanguageServer server, String path, FileChangeType changeType) { DidChangeWatchedFilesParams params = new DidChangeWatchedFilesParams( Collections.singletonList(new FileEvent(prefixURI(path), changeType))); server.getWorkspaceService().didChangeWatchedFiles(params); }
Source:
<code>private void runWithLock(Command command) { <START> String className = this.getClass().getName(); <END> String lockName = className + ".lock"; String markerName = className + ".done"; TimeUnit lastAccessTimeUnit = TimeUnit.SECONDS; int lastAccessThreshold = 1; File dir = ((JGitPathImpl) navigationFS.getPath("/")) .getFileSystem() .getGit() .getRepository() .getDirectory() .getParentFile(); File marker = new File(dir, markerName); FileSystemLock lock = FileSystemLockManager .getInstance() .getFileSystemLock( dir, lockName, lastAccessTimeUnit, lastAccessThreshold); try { lock.lock(); if (!marker.exists()) { marker.createNewFile(); command.execute(); } } catch (java.io.IOException e) { LOGGER.error(e.getMessage(), e); } finally { lock.unlock(); } }</code><technical_language>this point instead of class name I a simpler name, dashbuilder.lock dashbuilder.done align other "locks done" files. a great job</technical_language>

Target:
private void runWithLock(Command command) { String lockName = "data-migration.lock"; String markerName = "data-migration.done"; TimeUnit lastAccessTimeUnit = TimeUnit.SECONDS; int lastAccessThreshold = 1; File dir = ((JGitPathImpl) navigationFS.getPath("/")) .getFileSystem() .getGit() .getRepository() .getDirectory() .getParentFile(); File marker = new File(dir, markerName); FileSystemLock lock = FileSystemLockManager .getInstance() .getFileSystemLock( dir, lockName, lastAccessTimeUnit, lastAccessThreshold); try { lock.lock(); if (!marker.exists()) { marker.createNewFile(); command.execute(); } } catch (java.io.IOException e) { LOGGER.error(e.getMessage(), e); } finally { lock.unlock(); } }
Source:
<code>public void deleteFeedbackSessionsForCourse(String courseId) { frcLogic.deleteFeedbackResponseCommentsForCourse(courseId); frLogic.deleteFeedbackResponsesForCourse(courseId); fqLogic.deleteFeedbackQuestionsForCourse(courseId); List<FeedbackSessionAttributes> fsList = getFeedbackSessionsForCourse(courseId); <START> fsDb.deleteEntities(fsList); <END> }</code><technical_language>renaming/wrapping deleteEntities clearer called fsDb</technical_language>

Target:
public void deleteFeedbackSessionsForCourse(String courseId) { fsDb.deleteFeedbackSessionsForCourse(courseId); }
Source:
<code>public void testSearchByVariable() { Map<String, Object> data = new HashMap<>(); data.put("name", "my first case"); CaseFileInstance caseFile = caseService.newCaseFileInstance(deploymentUnit.getIdentifier(), EMPTY_CASE_P_ID, data); String caseId = caseService.startCase(deploymentUnit.getIdentifier(), EMPTY_CASE_P_ID, caseFile); Map<String, Object> vars = new HashMap<>(); vars.put("name", "my first case"); List<ProcessInstanceWithVarsDesc> process = advanceCaseRuntimeDataService.queryCaseByVariables(emptyMap(), vars, new QueryContext()); assertEquals(process.size(), 1); assertEquals(process.get(0).getVariables().get("name"), "my first case"); assertNotNull(caseId); assertEquals(FIRST_CASE_ID, caseId); <START> if (caseId != null) { <END> caseService.cancelCase(caseId); } }</code><technical_language>If statement is needed. assertNotNull this happens</technical_language>

Target:
public void testSearchByVariable() { Map<String, Object> data = new HashMap<>(); data.put("name", "my first case"); CaseFileInstance caseFile = caseService.newCaseFileInstance(deploymentUnit.getIdentifier(), EMPTY_CASE_P_ID, data); String caseId = caseService.startCase(deploymentUnit.getIdentifier(), EMPTY_CASE_P_ID, caseFile); List<QueryParam> vars = list(equalsTo("name", "my first case")); List<ProcessInstanceWithVarsDesc> process = advanceCaseRuntimeDataService.queryCaseByVariables(emptyList(), vars, new QueryContext()); assertEquals(1, process.size()); assertEquals("my first case", process.get(0).getExtraData().get("name")); assertNotNull(caseId); assertEquals(FIRST_CASE_ID, caseId); caseService.cancelCase(caseId); }
Source:
<code>public int getVersion() { return <START> 2; <END> }</code><technical_language>Version 3 I</technical_language>

Target:
public int getVersion() { return 3; }
Source:
<code>public Iterable<User> iterate() { <START> return null; <END> }</code><technical_language>a bug, throw UnsupportedOperationException a method is implemented, please fix</technical_language>

Target:
public Iterable<User> iterate() { throw new UnsupportedOperationException(); }