auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Object saveInstance(EntityRecord entityRecord, Long deleteValueFieldId) { EntityDto entity = getEntity(entityRecord.getEntitySchemaId()); validateCredentials(entity); <START> validateNonEditableProperty(entity.getId()); <END> try { MotechDataService service = getServiceForEntity(entity); Class<?> entityClass = getEntityClass(entity); boolean newObject = entityRecord.getId() == null; Object instance; if (newObject) { instance = entityClass.newInstance(); } else { instance = service.retrieve(ID, entityRecord.getId()); if (instance == null) { throw new ObjectNotFoundException(); } } updateFields(instance, entityRecord.getFields(), service, deleteValueFieldId, !newObject); if (newObject) { return service.create(instance); } else { return service.update(instance); } } catch (Exception e) { LOGGER.error("Unable to save object instance", e); throw new ObjectUpdateException(e); } }</code><technical_language>queries database instead of query, overload this method</technical_language>

Target:
public Object saveInstance(EntityRecord entityRecord, Long deleteValueFieldId) { EntityDto entity = getEntity(entityRecord.getEntitySchemaId()); validateCredentials(entity); validateNonEditableProperty(entity); try { MotechDataService service = getServiceForEntity(entity); Class<?> entityClass = getEntityClass(entity); boolean newObject = entityRecord.getId() == null; Object instance; if (newObject) { instance = entityClass.newInstance(); } else { instance = service.retrieve(ID, entityRecord.getId()); if (instance == null) { throw new ObjectNotFoundException(); } } updateFields(instance, entityRecord.getFields(), service, deleteValueFieldId, !newObject); if (newObject) { return service.create(instance); } else { return service.update(instance); } } catch (Exception e) { LOGGER.error("Unable to save object instance", e); throw new ObjectUpdateException(e); } }
Source:
<code>public Object visit(ASTCompilationUnit node, Object data) { methodReportLevel = getProperty(METHOD_LEVEL_DESCRIPTOR); classReportLevel = getProperty(CLASS_LEVEL_DESCRIPTOR); <START> if (cycloOptions == null) { <END> cycloOptions = MetricOptions.ofOptions(getProperty(CYCLO_OPTIONS_DESCRIPTOR)); } super.visit(node, data); return data; }</code><technical_language>Do need this null check here</technical_language>

Target:
public Object visit(ASTCompilationUnit node, Object data) { methodReportLevel = getProperty(METHOD_LEVEL_DESCRIPTOR); classReportLevel = getProperty(CLASS_LEVEL_DESCRIPTOR); cycloOptions = MetricOptions.ofOptions(getProperty(CYCLO_OPTIONS_DESCRIPTOR)); super.visit(node, data); return data; }
Source:
<code>public void testQosError_performsFailover() throws Exception { <START> server1.enqueue(new MockResponse().setResponseCode(UNAVAILABLE_RESPONSE_CODE)); <END> server1.enqueue(new MockResponse().setBody("\"foo\"")); server2.enqueue(new MockResponse().setBody("\"bar\"")); assertThat(proxy.string(), is("bar")); }</code><technical_language>I prefer 503</technical_language>

Target:
public void testQosError_performsFailover() throws Exception { server1.enqueue(new MockResponse().setResponseCode(503)); server1.enqueue(new MockResponse().setBody("\"foo\"")); server2.enqueue(new MockResponse().setBody("\"bar\"")); assertThat(proxy.string(), is("bar")); }
Source:
<code>public void setUp() throws Exception { ca = OpenSSLX509Certificate.fromX509PemInputStream(openTestFile("ca-cert.pem")); cert = OpenSSLX509Certificate.fromX509PemInputStream(openTestFile("cert.pem")); certEmbedded = OpenSSLX509Certificate.fromX509PemInputStream( openTestFile("cert-ct-embedded.pem")); PublicKey key = OpenSSLKey.fromPublicKeyPemInputStream( openTestFile("ct-server-key-public.pem")).getPublicKey(); <START> CTLogStore store = new CTLogStoreImpl(new CTLogInfo[] { <END> new CTLogInfo(key, "Test Log", "foo") }); ctVerifier = new CTVerifier(store); }</code><technical_language>this compile</technical_language>

Target:
public void setUp() throws Exception { ca = OpenSSLX509Certificate.fromX509PemInputStream(openTestFile("ca-cert.pem")); cert = OpenSSLX509Certificate.fromX509PemInputStream(openTestFile("cert.pem")); certEmbedded = OpenSSLX509Certificate.fromX509PemInputStream( openTestFile("cert-ct-embedded.pem")); PublicKey key = OpenSSLKey.fromPublicKeyPemInputStream( openTestFile("ct-server-key-public.pem")).getPublicKey(); final CTLogInfo log = new CTLogInfo(key, "Test Log", "foo"); CTLogStore store = new CTLogStore() { public CTLogInfo getKnownLog(byte[] logId) { if (Arrays.equals(logId, log.getID())) { return log; } else { return null; } } }; ctVerifier = new CTVerifier(store); }
Source:
<code>public void currentUser_throwsIfMultipleUsersLoggedIn() { AuthenticationServer originalAuthServer = SyncManager.getAuthServer(); AuthenticationServer authServer = Mockito.mock(AuthenticationServer.class); <START> SyncManager.setAuthServerImpl(authServer); <END> when(authServer.loginUser(any(SyncCredentials.class), any(URL.class))).thenAnswer(new Answer<AuthenticateResponse>() { @Override public AuthenticateResponse answer(InvocationOnMock invocationOnMock) throws Throwable { return getNewRandomUser(); } }); SyncUser.login(SyncCredentials.facebook("foo"), "http:/test.realm.io/auth"); SyncUser.login(SyncCredentials.facebook("foo"), "http:/test.realm.io/auth"); try { SyncUser.currentUser(); fail(); } catch (IllegalStateException ignore) { } finally { SyncManager.setAuthServerImpl(originalAuthServer); } }</code><technical_language>I this line moved in try block avoid a chance for mock AuthenticationServer left</technical_language>

Target:
public void currentUser_throwsIfMultipleUsersLoggedIn() { AuthenticationServer originalAuthServer = SyncManager.getAuthServer(); AuthenticationServer authServer = Mockito.mock(AuthenticationServer.class); SyncManager.setAuthServerImpl(authServer); try { when(authServer.loginUser(any(SyncCredentials.class), any(URL.class))).thenAnswer(new Answer<AuthenticateResponse>() { @Override public AuthenticateResponse answer(InvocationOnMock invocationOnMock) throws Throwable { return getNewRandomUser(); } }); SyncUser.login(SyncCredentials.facebook("foo"), "http:/test.realm.io/auth"); SyncUser.login(SyncCredentials.facebook("foo"), "http:/test.realm.io/auth"); try { SyncUser.currentUser(); fail(); } catch (IllegalStateException ignore) { } } finally { SyncManager.setAuthServerImpl(originalAuthServer); } }
Source:
<code><START> protected final AlarmManager getAlarmManager() { <END> return getAlarmManager(this.getApplicationContext()); }</code><technical_language>I suggest this, sibling, createPendingIntent final</technical_language>

Target:
protected AlarmManager getAlarmManager() { return getAlarmManager(this.getApplicationContext()); }
Source:
<code>protected static void addDependencies(URL hpiResUrl, String fromPath, Set<URL> dependencySet) throws URISyntaxException, MalformedURLException { if (dependencySet.contains(hpiResUrl)) { return; } Manifest manifest = parsePluginManifest(hpiResUrl); String dependencySpec = manifest.getMainAttributes().getValue("Plugin-Dependencies"); if (dependencySpec != null) { String[] dependencyTokens = dependencySpec.split(","); ServletContext context = Jenkins.getActiveInstance().servletContext; for (String dependencyToken : dependencyTokens) { if (dependencyToken.endsWith(";resolution:=optional")) { continue; } <START> String[] artifactIdVersionPair = dependencyToken.split(":"); <END> String artifactId = artifactIdVersionPair[0]; VersionNumber dependencyVersion = new VersionNumber(artifactIdVersionPair[1]); PluginManager manager = Jenkins.getActiveInstance().getPluginManager(); VersionNumber installedVersion = manager.getPluginVersion(manager.rootDir, artifactId); if (installedVersion != null && installedVersion.isNewerThan(dependencyVersion)) { continue; } URL dependencyURL = context.getResource(fromPath + "/" + artifactId + ".hpi"); if (dependencyURL == null) { dependencyURL = context.getResource(fromPath + "/" + artifactId + ".jpi"); } if (dependencyURL != null) { addDependencies(dependencyURL, fromPath, dependencySet); dependencySet.add(dependencyURL); } } } }</code><technical_language>string ;optional=true, is it</technical_language>

Target:
protected static void addDependencies(URL hpiResUrl, String fromPath, Set<URL> dependencySet) throws URISyntaxException, MalformedURLException { if (dependencySet.contains(hpiResUrl)) { return; } Manifest manifest = parsePluginManifest(hpiResUrl); String dependencySpec = manifest.getMainAttributes().getValue("Plugin-Dependencies"); if (dependencySpec != null) { String[] dependencyTokens = dependencySpec.split(","); ServletContext context = Jenkins.getActiveInstance().servletContext; for (String dependencyToken : dependencyTokens) { if (dependencyToken.endsWith(";resolution:=optional")) { continue; } String[] artifactIdVersionPair = dependencyToken.split(":"); String artifactId = artifactIdVersionPair[0]; VersionNumber dependencyVersion = new VersionNumber(artifactIdVersionPair[1]); PluginManager manager = Jenkins.getActiveInstance().getPluginManager(); VersionNumber installedVersion = manager.getPluginVersion(manager.rootDir, artifactId); if (installedVersion != null && !installedVersion.isOlderThan(dependencyVersion)) { continue; } URL dependencyURL = context.getResource(fromPath + "/" + artifactId + ".hpi"); if (dependencyURL == null) { dependencyURL = context.getResource(fromPath + "/" + artifactId + ".jpi"); } if (dependencyURL != null) { addDependencies(dependencyURL, fromPath, dependencySet); dependencySet.add(dependencyURL); } } } }
Source:
<code>public Mono<Void> run(CancellationToken cancellationToken) { logger.info("Partition {}: renewer task started.", this.lease.getLeaseToken()); return Mono.just(this) .flatMap(value -> { if (cancellationToken.isCancellationRequested()) { return Mono.empty(); } ZonedDateTime stopTimer = ZonedDateTime.now().plus(this.leaseRenewInterval); return Mono.just(value) .delayElement(Duration.ofMillis(100)) .repeat( () -> { ZonedDateTime currentTime = ZonedDateTime.now(); return !cancellationToken.isCancellationRequested() && currentTime.isBefore(stopTimer); }).last(); }) .flatMap(value -> { if (cancellationToken.isCancellationRequested()) { return Mono.empty(); } return this.renew(cancellationToken); }) .repeat(() -> { if (cancellationToken.isCancellationRequested()) { logger.info("Partition {}: renewer task stopped.", this.lease.getLeaseToken()); } return !cancellationToken.isCancellationRequested(); }) .then() .onErrorResume(throwable -> { if (throwable instanceof LeaseLostException) { <START> logger.warn("Partition {}: renew lease loop failed.", this.lease.getLeaseToken(), throwable); <END> } else { logger.error("Partition {}: renew lease loop failed.", this.lease.getLeaseToken(), throwable); } return Mono.error(throwable); }); }</code><technical_language>discussed, lets change this info</technical_language>

Target:
public Mono<Void> run(CancellationToken cancellationToken) { logger.info("Partition {}: renewer task started.", this.lease.getLeaseToken()); return Mono.just(this) .flatMap(value -> { if (cancellationToken.isCancellationRequested()) { return Mono.empty(); } ZonedDateTime stopTimer = ZonedDateTime.now().plus(this.leaseRenewInterval); return Mono.just(value) .delayElement(Duration.ofMillis(100)) .repeat( () -> { ZonedDateTime currentTime = ZonedDateTime.now(); return !cancellationToken.isCancellationRequested() && currentTime.isBefore(stopTimer); }).last(); }) .flatMap(value -> { if (cancellationToken.isCancellationRequested()) { return Mono.empty(); } return this.renew(cancellationToken); }) .repeat(() -> { if (cancellationToken.isCancellationRequested()) { logger.info("Partition {}: renewer task stopped.", this.lease.getLeaseToken()); } return !cancellationToken.isCancellationRequested(); }) .then() .onErrorResume(throwable -> { if (throwable instanceof LeaseLostException) { logger.info("Partition {}: renew lease loop failed.", this.lease.getLeaseToken(), throwable); } else { logger.error("Partition {}: renew lease loop failed.", this.lease.getLeaseToken(), throwable); } return Mono.error(throwable); }); }
Source:
<code>private boolean isSelfRef(Map.Entry<String, String> env) { if (env.getValue().contains("${".concat(env.getKey()).concat("}"))) { return true; } <START> if (env.getValue().contains("$".concat(env.getKey()))) { <END> return true; } return false; }</code><technical_language>work correctly with: FOO=something $FOOBAR</technical_language>

Target:
private static boolean isSelfRef(Map.Entry<String, String> env) { if (env.getValue().contains("${".concat(env.getKey()).concat("}"))) { return true; } if (env.getValue().contains("$".concat(env.getKey()))) { return true; } return false; }
Source:
<code>public void compactFully() throws Exception { FileReftableDatabase refDb = (FileReftableDatabase) db.getRefDatabase(); PersonIdent person = new PersonIdent("jane", "jane@invalid"); ObjectId aId = db.exactRef("refs/heads/a").getObjectId(); ObjectId bId = db.exactRef("refs/heads/b").getObjectId(); SecureRandom random = new SecureRandom(); List<String> strs = new ArrayList<>(); for (int i = 0; i < 1024; i++) { strs.add(String.format("%02x", random.nextInt(256))); } String randomStr = String.join("", strs); String refName = "branch"; for (long i = 0; i < 2; i++) { RefUpdate ru = refDb.newUpdate(refName, false); ru.setNewObjectId(i % 2 == 0 ? aId : bId); ru.setForceUpdate(true); ru.setRefLogMessage(i == 0 ? randomStr : "short", false); ru.setRefLogIdent(person); RefUpdate.Result res = ru.update(); assertTrue(res == Result.NEW || res == FORCED); } <START> assertTrue(randomStr.equals(refDb.getReflogReader(refName).getReverseEntry(1).getComment())); refDb.compactFully(); assertTrue(randomStr.equals(refDb.getReflogReader(refName).getReverseEntry(1).getComment())); } <END></code><technical_language>Do need assertions for refs refLogs</technical_language>

Target:
public void compactFully() throws Exception { FileReftableDatabase refDb = (FileReftableDatabase) db.getRefDatabase(); PersonIdent person = new PersonIdent("jane", "jane@invalid"); ObjectId aId = db.exactRef("refs/heads/a").getObjectId(); ObjectId bId = db.exactRef("refs/heads/b").getObjectId(); SecureRandom random = new SecureRandom(); List<String> strs = new ArrayList<>(); for (int i = 0; i < 1024; i++) { strs.add(String.format("%02x", random.nextInt(256))); } String randomStr = String.join("", strs); String refName = "branch"; for (long i = 0; i < 2; i++) { RefUpdate ru = refDb.newUpdate(refName, false); ru.setNewObjectId(i % 2 == 0 ? aId : bId); ru.setForceUpdate(true); ru.setRefLogMessage(i == 0 ? randomStr : "short", false); ru.setRefLogIdent(person); RefUpdate.Result res = ru.update(); assertTrue(res == Result.NEW || res == FORCED); } assertEquals(refDb.exactRef(refName).getObjectId(), bId); assertTrue(randomStr.equals(refDb.getReflogReader(refName).getReverseEntry(1).getComment())); refDb.compactFully(); assertEquals(refDb.exactRef(refName).getObjectId(), bId); assertTrue(randomStr.equals(refDb.getReflogReader(refName).getReverseEntry(1).getComment())); }
Source:
<code>public void run(HelloWorldConfiguration configuration, Environment environment) { final PersonDAO dao = new PersonDAO(hibernateBundle.getSessionFactory()); final Template template = configuration.buildTemplate(); environment.healthChecks().register("template", new TemplateHealthCheck(template)); environment.jersey().register(DateRequiredFeature.class); environment.jersey().register(new AuthDynamicFeature(new BasicCredentialAuthFilter.Builder<User>() .setAuthenticator(new ExampleAuthenticator()) .setAuthorizer(new ExampleAuthorizer()) .setRealm("SUPER SECRET STUFF") .buildAuthFilter())); <START> environment.jersey(). <END> environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class)); environment.jersey().register(RolesAllowedDynamicFeature.class); environment.jersey().register(new HelloWorldResource(template)); environment.jersey().register(new ViewResource()); environment.jersey().register(new ProtectedResource()); environment.jersey().register(new PeopleResource(dao)); environment.jersey().register(new PersonResource(dao)); environment.jersey().register(new FilteredResource()); }</code><technical_language>line belong here. :wink:</technical_language>

Target:
public void run(HelloWorldConfiguration configuration, Environment environment) { final PersonDAO dao = new PersonDAO(hibernateBundle.getSessionFactory()); final Template template = configuration.buildTemplate(); environment.healthChecks().register("template", new TemplateHealthCheck(template)); environment.jersey().register(DateRequiredFeature.class); environment.jersey().register(new AuthDynamicFeature(new BasicCredentialAuthFilter.Builder<User>() .setAuthenticator(new ExampleAuthenticator()) .setAuthorizer(new ExampleAuthorizer()) .setRealm("SUPER SECRET STUFF") .buildAuthFilter())); environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class)); environment.jersey().register(RolesAllowedDynamicFeature.class); environment.jersey().register(new HelloWorldResource(template)); environment.jersey().register(new ViewResource()); environment.jersey().register(new ProtectedResource()); environment.jersey().register(new PeopleResource(dao)); environment.jersey().register(new PersonResource(dao)); environment.jersey().register(new FilteredResource()); }
Source:
<code><START> private void swap(int fpos, int spos) <END> { double tmpElement = elements[fpos]; double tmpWeight = weights[fpos]; elements[fpos] = elements[spos]; weights[fpos] = weights[spos]; elements[spos] = tmpElement; weights[spos] = tmpWeight; }</code><technical_language>@atavory is way. do need this</technical_language>

Target:
private void swap(int fpos, int spos) { double tmpElement = samples[fpos]; double tmpWeight = weights[fpos]; samples[fpos] = samples[spos]; weights[fpos] = weights[spos]; samples[spos] = tmpElement; weights[spos] = tmpWeight; }
Source:
<code>public void moveToTrash() { Tracking.trackEvent(Tracking.PROJECT_EVENT, <START> Tracking.PROJECT_ACTION_MOVE_TO_TRASH_PROJECT_YA, getProjectName()); <END> Ode.getInstance().getProjectService().moveToTrash(getProjectId(), new OdeAsyncCallback<UserProject>( MESSAGES.moveToTrashProjectError()) { @Override public void onSuccess(UserProject project) { if (project.getProjectId() == projectInfo.getProjectId()) { projectInfo.moveToTrash(); Ode.getInstance().getProjectManager().trashProjecct(getProjectId()); } } }); }</code><technical_language>Code style: Continuation indent 4 spaces. of other code in this file copied Ode.java needs reindented</technical_language>

Target:
public void moveToTrash() { Tracking.trackEvent(Tracking.PROJECT_EVENT, Tracking.PROJECT_ACTION_MOVE_TO_TRASH_PROJECT_YA, getProjectName()); Ode.getInstance().getProjectService().moveToTrash(getProjectId(), new OdeAsyncCallback<UserProject>( MESSAGES.moveToTrashProjectError()) { @Override public void onSuccess(UserProject project) { if (project.getProjectId() == projectInfo.getProjectId()) { projectInfo.moveToTrash(); Ode.getInstance().getProjectManager().trashProject(getProjectId()); } } }); }
Source:
<code>public static TmfStateValue newValueString(@Nullable String strValue) { if (strValue == null) { return nullValue(); } for (char c : strValue.toCharArray()) { if (Character.isISOControl(c)) { Activator.getDefault().logError("Trying to use invalid string: " + strValue); throw new IllegalArgumentException(); } } StringStateValue tmfStateValue = STRING_CACHE.get(strValue); if (tmfStateValue == null) { tmfStateValue = new StringStateValue(strValue); STRING_CACHE.put(strValue, tmfStateValue); if (STRING_CACHE.size() > STRING_CACHE_SIZE) { <START> STRING_CACHE.remove(STRING_CACHE.keySet().iterator().next()); <END> } } return tmfStateValue; }</code><technical_language>Yeah removing element is terrible. Random already. I out easy implement a LRU cache a LinkedHashMap, <LINK_0> . Pretty nifty</technical_language>

Target:
public static TmfStateValue newValueString(@Nullable String strValue) { if (strValue == null) { return nullValue(); } StringStateValue tmfStateValue = STRING_CACHE.get(strValue); if( tmfStateValue != null ) { return tmfStateValue; } for (char c : strValue.toCharArray()) { if (Character.isISOControl(c)) { Activator.getDefault().logError("Trying to use invalid string: " + strValue); throw new IllegalArgumentException(); } } tmfStateValue = new StringStateValue(strValue); STRING_CACHE.put(strValue, tmfStateValue); if (STRING_CACHE.size() > STRING_CACHE_SIZE) { STRING_CACHE.remove(STRING_CACHE.keySet().iterator().next()); } return tmfStateValue; }
Source:
<code>public void download(User user, @RemainedPath String path, HttpServletResponse response) { <START> path = decodePathWithUTF8(path); <END> FileEntry fileEntry = fileEntryService.getOne(user, path); if (fileEntry == null) { LOG.error("{} requested to download not existing file entity {}", user.getUserId(), path); throw new NGrinderRuntimeException("download requested file not exists in file entity " + path); } response.reset(); response.setContentType("application/octet-stream; charset=UTF-8"); ContentDisposition contentDisposition = ContentDisposition.builder("attachment") .filename(fileEntry.getFileName(), StandardCharsets.UTF_8) .build(); response.setHeader("Content-Disposition", contentDisposition.toString()); response.addHeader("Content-Length", "" + fileEntry.getFileSize()); byte[] buffer = new byte[4096]; ByteArrayInputStream fis = null; OutputStream toClient = null; try { fis = new ByteArrayInputStream(fileEntry.getContentBytes()); toClient = new BufferedOutputStream(response.getOutputStream()); int readLength; while (((readLength = fis.read(buffer)) != -1)) { toClient.write(buffer, 0, readLength); } } catch (IOException e) { throw processException("error while download file", e); } finally { IOUtils.closeQuietly(fis); IOUtils.closeQuietly(toClient); } }</code><technical_language>move this RemainedPathArgumentHandler</technical_language>

Target:
public void download(User user, @RemainedPath String path, HttpServletResponse response) { FileEntry fileEntry = fileEntryService.getOne(user, path); if (fileEntry == null) { LOG.error("{} requested to download not existing file entity {}", user.getUserId(), path); throw new NGrinderRuntimeException("download requested file not exists in file entity " + path); } response.reset(); response.setContentType("application/octet-stream; charset=UTF-8"); ContentDisposition contentDisposition = ContentDisposition.builder("attachment") .filename(fileEntry.getFileName(), StandardCharsets.UTF_8) .build(); response.setHeader("Content-Disposition", contentDisposition.toString()); response.addHeader("Content-Length", "" + fileEntry.getFileSize()); try (ByteArrayInputStream fis = new ByteArrayInputStream(fileEntry.getContentBytes()); OutputStream os = new BufferedOutputStream(response.getOutputStream())) { IOUtils.copy(fis, os); } catch (IOException e) { throw processException("error while download file", e); } }
Source:
<code>public Timeline2 getData() { String type = "all"; String midUrl; String url; Thread[] dataThreads = new Thread[3]; this.postList = new Timeline2(this.order); switch(type) { case "all": case "profile": midUrl = "profile/"; url = this.baseUrl + midUrl + this.query; dataThreads[0] = new ConcurrentScrape(url, "profile"); dataThreads[0].start(); if("profile".equals(type)) break; case "question": midUrl = "search/?q="; url = this.baseUrl + midUrl + this.query + "&type=question"; dataThreads[1] = new ConcurrentScrape(url, "question"); dataThreads[1].start(); if("question".equals(type)) break; case "answer": midUrl = "search/?q="; url = this.baseUrl + midUrl + this.query + "&type=answer"; dataThreads[2] = new ConcurrentScrape(url, "answer"); dataThreads[2].start(); if("answer".equals(type)) break; default: break; } try { for (int i=0; i<3; i++) { dataThreads[i].join(); } } catch(InterruptedException e) { <START> DAO.severe("Couldn't complete all threads"); <END> } return this.postList; }</code><technical_language>need mention scraper name type variable is easy debug</technical_language>

Target:
public Timeline2 getData() { String type = "all"; String midUrl; String url; Thread[] dataThreads = new Thread[2]; this.postList = new Timeline2(this.order); switch(type) { case "all": case "user": midUrl = "profile/"; url = this.baseUrl + midUrl + this.query; dataThreads[0] = new ConcurrentScrape(url, "users"); dataThreads[0].start(); if("user".equals(type)) break; case "question": midUrl = "search/?q="; url = this.baseUrl + midUrl + this.query + "&type=question"; dataThreads[1] = new ConcurrentScrape(url, "question"); dataThreads[1].start(); if("question".equals(type)) break; default: break; } int i = 0; try { for (i = 0; i < dataThreads.length; i++) { dataThreads[i].join(); } } catch(InterruptedException e) { String stuck_at = ""; switch(i) { case 0: stuck_at = "users"; break; case 1: stuck_at = "question"; break; case 2: stuck_at = "answer"; break; default: stuck_at = "unknown, check the code"; } DAO.severe("Couldn't complete all threads, stuck at scraper: " + this.scraperName + " dataThread: " + stuck_at); } return this.postList; }
Source:
<code>public List<StoredObject> getObjects(@Nonnull String query, int start, int size) { try (Stream<Path> stream = Files.list(file.toPath())) { return stream.skip(start) .map(Path::toFile) .filter(currentFile -> currentFile.getName().contains(query) && currentFile.isFile() && !currentFile.getName().startsWith("__")) .limit(size) .map(StoredObject::new) .collect(Collectors.toList()); } catch (IOException e) { <START> throw Exceptions.createHandled().error(e).handle(); <END> } }</code><technical_language>s.o</technical_language>

Target:
public List<StoredObject> getObjects(@Nonnull String query, int start, int size) { try (Stream<Path> stream = Files.list(file.toPath())) { return stream.map(Path::toFile) .filter(currentFile -> currentFile.getName().contains(query) && currentFile.isFile() && !currentFile.getName().startsWith("__")) .skip(start) .limit(size) .map(StoredObject::new) .collect(Collectors.toList()); } catch (IOException e) { throw Exceptions.handle(e); } }
Source:
<code>private void popMessageAndSend() { Message<Object> message = null; byte[] value = null; try { if (readFromLeft) { <START> value = this.boundListOperations.leftPop( this.receiveTimeout, TimeUnit.MILLISECONDS); <END> } else { value = this.boundListOperations.rightPop( this.receiveTimeout, TimeUnit.MILLISECONDS); } } catch (Exception e) { this.listening = false; if (this.active) { logger.error("Failed to execute listening task. Will attempt to resubmit in " + this.recoveryInterval + " milliseconds.", e); this.publishException(e); this.sleepBeforeRecoveryAttempt(); } else { logger.debug("Failed to execute listening task. " + e.getClass() + ": " + e.getMessage()); } return; } if (value != null) { if (this.expectMessage) { try { message = (Message<Object>) this.serializer.deserialize(value); } catch (Exception e) { throw new MessagingException("Deserialization of Message failed.", e); } } else { Object payload = value; if (this.serializer != null) { payload = this.serializer.deserialize(value); } message = this.getMessageBuilderFactory().withPayload(payload).build(); } } if (message != null) { if (this.listening) { this.sendMessage(message); } else { if (readFromLeft) { this.boundListOperations.leftPush(value); } else { this.boundListOperations.rightPush(value); } } } }</code><technical_language>unnecessary space of parens (here in else clause)</technical_language>

Target:
private void popMessageAndSend() { Message<Object> message = null; byte[] value = null; try { if (this.rightPop) { value = this.boundListOperations.rightPop(this.receiveTimeout, TimeUnit.MILLISECONDS); } else { value = this.boundListOperations.leftPop(this.receiveTimeout, TimeUnit.MILLISECONDS); } } catch (Exception e) { this.listening = false; if (this.active) { logger.error("Failed to execute listening task. Will attempt to resubmit in " + this.recoveryInterval + " milliseconds.", e); this.publishException(e); this.sleepBeforeRecoveryAttempt(); } else { logger.debug("Failed to execute listening task. " + e.getClass() + ": " + e.getMessage()); } return; } if (value != null) { if (this.expectMessage) { try { message = (Message<Object>) this.serializer.deserialize(value); } catch (Exception e) { throw new MessagingException("Deserialization of Message failed.", e); } } else { Object payload = value; if (this.serializer != null) { payload = this.serializer.deserialize(value); } message = this.getMessageBuilderFactory().withPayload(payload).build(); } } if (message != null) { if (this.listening) { this.sendMessage(message); } else { if (this.rightPop) { this.boundListOperations.rightPush(value); } else { this.boundListOperations.leftPush(value); } } } }
Source:
<code><START> public void unregisterConsumer(EventConsumer consumer, String publisherName) { <END> if (consumer == null) { throw new InvalidParameterException("Consumer must not be null"); } regMgmtLock.lock(); try { log.debug("unregisterConsumer " + consumer.getClass().getCanonicalName() + " for " + publisherName); RegisteredPublisher publisher = this.nameToPublisher.get(publisherName); if (publisher != null) { publisher.removeComsumer(consumer); } else { for (RegisteredConsumer regCon : this.danglingConsumers) { if (regCon.getConsumer().equals(consumer)) { this.danglingConsumers.remove(regCon); break; } } } } finally { regMgmtLock.unlock(); } }</code><technical_language>This (the method) indentation char</technical_language>

Target:
public void unregisterConsumer(EventConsumer consumer, String publisherName) { if (consumer == null) { throw new InvalidParameterException("Consumer must not be null"); } regMgmtLock.lock(); try { log.debug("unregisterConsumer " + consumer.getClass().getCanonicalName() + " for " + publisherName); RegisteredPublisher publisher = this.nameToPublisher.get(publisherName); if (publisher != null) { publisher.removeComsumer(consumer); } else { removeDanglingConsumer(consumer); } } finally { regMgmtLock.unlock(); } }
Source:
<code>public boolean failover(Guid currentCommandSpmId, Set<Guid> mTriedVdssList) { synchronized (syncObj) { mTriedVdssList.add(currentCommandSpmId); <START> if (currentCommandSpmId.equals(mCurrentVdsId)) { <END> if (getHasVdssForSpmSelection(mCurrentVdsId, mTriedVdssList)) { Guid vdsId = mCurrentVdsId; nullifyInternalProxies(); boolean performFailover = false; if (vdsId != null) { try { VDSReturnValue statusResult = ResourceManager.getInstance().runVdsCommand(VDSCommandType.SpmStatus, new SpmStatusVDSCommandParameters(vdsId, _storagePoolId)); if (statusResult != null && statusResult.getSucceeded() && (((SpmStatusResult) statusResult.getReturnValue()).getSpmStatus() == SpmStatus.SPM || ((SpmStatusResult) statusResult .getReturnValue()).getSpmStatus() == SpmStatus.Contend)) { performFailover = ResourceManager .getInstance() .runVdsCommand(VDSCommandType.SpmStop, new SpmStopVDSCommandParameters(vdsId, _storagePoolId)) .getSucceeded(); } else { performFailover = true; } } catch (Exception ex) { log.errorFormat("Could not get spm status on host {0} for spmStop.", vdsId); performFailover = true; } } if (performFailover) { log.infoFormat("Irs placed on server {0} failed. Proceed Failover", vdsId); mTriedVdssList.add(vdsId); return true; } else { log.errorFormat("IRS failover failed - cant allocate vds server"); return false; } } return false; } } return true; }</code><technical_language>line 457 performs getHasVdssForSpmSelection(mCurrentVdsId, mTriedVdssList) in line 461 if mCurrentVdsId == null return false, need query check for vdss if check if null</technical_language>

Target:
public boolean failover(Guid currentCommandSpmId, Set<Guid> mTriedVdssList) { synchronized (syncObj) { mTriedVdssList.add(currentCommandSpmId); if (currentCommandSpmId.equals(mCurrentVdsId)) { if (getHasVdssForSpmSelection(mCurrentVdsId, mTriedVdssList)) { Guid vdsId = mCurrentVdsId; nullifyInternalProxies(); boolean performFailover = false; try { VDSReturnValue statusResult = ResourceManager.getInstance().runVdsCommand(VDSCommandType.SpmStatus, new SpmStatusVDSCommandParameters(vdsId, _storagePoolId)); if (statusResult != null && statusResult.getSucceeded() && (((SpmStatusResult) statusResult.getReturnValue()).getSpmStatus() == SpmStatus.SPM || ((SpmStatusResult) statusResult .getReturnValue()).getSpmStatus() == SpmStatus.Contend)) { performFailover = ResourceManager .getInstance() .runVdsCommand(VDSCommandType.SpmStop, new SpmStopVDSCommandParameters(vdsId, _storagePoolId)) .getSucceeded(); } else { performFailover = true; } } catch (Exception ex) { log.errorFormat("Could not get spm status on host {0} for spmStop.", vdsId); performFailover = true; } if (performFailover) { log.infoFormat("Irs placed on server {0} failed. Proceed Failover", vdsId); return true; } else { log.errorFormat("IRS failover failed - cant allocate vds server"); return false; } } return false; } } return true; }
Source:
<code><START> public static boolean tryLockIrsProxyData(Guid storagePoolId) { <END> try { return _irsProxyData.get(storagePoolId).tryLockIrsProxyLockObject(); } catch (Exception e) { return false; } }</code><technical_language>align null treatment in methods</technical_language>

Target:
public static boolean tryLockIrsProxyData(Guid storagePoolId) { IrsProxyData proxyData = _irsProxyData.get(storagePoolId); if (proxyData != null) { _irsProxyData.get(storagePoolId).tryLockIrsProxyLockObject(); return true; } else { return false; } }
Source:
<code>public Object perform(InvocationContext ctx) throws Throwable { MVCCEntry e = (MVCCEntry) ctx.lookupEntry(key); if (e != null && !e.isRemoved()) { Object value = e.getValue(); if (lifespan == null) { <START> if (valueMatcher.matches(e, value, e.getValue(), valueEquivalence)) { <END> e.setExpired(true); return performRemove(e, ctx); } } else if (e.getMetadata() == null) { if (value == null) { e.setExpired(true); return performRemove(e, ctx); } } else if ( e.getLifespan() == lifespan) { if (valueMatcher.matches(e, value, e.getValue(), valueEquivalence)) { e.setExpired(true); return performRemove(e, ctx); } } else { log.trace("Cannot remove entry as it's lifespan or value do not match"); } } else { log.trace("Nothing to remove since the entry doesn't exist in the context or it is already removed"); } successful = false; return false; }</code><technical_language>this check fail expire a newer value? If not, do need extra lifespan check</technical_language>

Target:
public Object perform(InvocationContext ctx) throws Throwable { MVCCEntry e = (MVCCEntry) ctx.lookupEntry(key); if (e != null && !e.isRemoved()) { Object value = e.getValue(); if (lifespan == null) { if (valueMatcher.matches(e, value, e.getValue(), valueEquivalence)) { e.setExpired(true); return performRemove(e, ctx); } } else if (e.getMetadata() == null) { if (value == null || valueMatcher.matches(e, value, e.getValue(), valueEquivalence)) { e.setExpired(true); return performRemove(e, ctx); } } else if (e.getLifespan() > 0 && e.getLifespan() == lifespan) { if (valueMatcher.matches(e, value, e.getValue(), valueEquivalence)) { e.setExpired(true); return performRemove(e, ctx); } } else { log.trace("Cannot remove entry as its lifespan or value do not match"); } } else { log.trace("Nothing to remove since the entry doesn't exist in the context or it is already removed"); } successful = false; return false; }
Source:
<code>public void close() { if(!isClosed){ <START> isClosed = true; <END> cipherRead = null; cipherWrite = null; cipherParams = null; underlyingThing.close(); } }</code><technical_language>concerned a race condition here. Consider: 1. Another thread checks isClosed, finds false this line hit yet. 2. This thread completes close(). 3. other thread continues cipherWrite / cipherRead; NPE</technical_language>

Target:
public void close() { if(!isClosed){ isClosed = true; underlyingThing.close(); } }
Source:
<code>private void validateData(Run<?, ?> run, TaskListener listener, StorageAccountInfo storageAccount, <START> String expContainerName) throws IOException, InterruptedException { <END> if ( (run.getResult() == Result.FAILURE || run.getResult() == Result.ABORTED) && uploadArtifactsOnlyIfSuccessful) { listener.getLogger().println( Messages.WAStoragePublisher_build_failed_err()); } if (storageAccount == null) { listener.getLogger().println( Messages.WAStoragePublisher_storage_account_err()); run.setResult(Result.UNSTABLE); } if (Utils.isNullOrEmpty(filesPath)) { listener.getLogger().println( Messages.WAStoragePublisher_filepath_err()); run.setResult(Result.UNSTABLE); } if (getArtifactUploadType() == UploadType.INVALID) { listener.getLogger().println( Messages.WAStoragePublisher_uploadtype_invalid()); run.setResult(Result.UNSTABLE); } try { WAStorageClient.validateStorageAccount( storageAccount.getStorageAccName(), storageAccount.getStorageAccountKey(), storageAccount.getBlobEndPointURL()); } catch (Exception e) { listener.getLogger().println(Messages.Client_SA_val_fail()); listener.getLogger().println( "Storage Account name --->" + storageAccount.getStorageAccName() + "<----"); listener.getLogger().println( "Blob end point url --->" + storageAccount.getBlobEndPointURL() + "<----"); run.setResult(Result.UNSTABLE); } }</code><technical_language>of container name</technical_language>

Target:
private boolean validateData(Run<?, ?> run, TaskListener listener, StorageAccountInfo storageAccount, String expContainerName) throws IOException, InterruptedException { if ((run.getResult() == Result.FAILURE || run.getResult() == Result.ABORTED) && uploadArtifactsOnlyIfSuccessful) { listener.getLogger().println( Messages.WAStoragePublisher_build_failed_err()); return false; } if (storageAccount == null) { listener.getLogger().println( Messages.WAStoragePublisher_storage_account_err()); return false; } if (Utils.isNullOrEmpty(filesPath)) { listener.getLogger().println( Messages.WAStoragePublisher_filepath_err()); return false; } if (getArtifactUploadType() == UploadType.INVALID) { listener.getLogger().println( Messages.WAStoragePublisher_uploadtype_invalid()); return false; } if (Utils.isNullOrEmpty(expContainerName)) { listener.getLogger().println("Container name is null or empty"); return false; } if (!Utils.validateContainerName(expContainerName)) { listener.getLogger().println("Container name contains invalid characters"); return false; } try { WAStorageClient.validateStorageAccount(storageAccount); } catch (Exception e) { listener.getLogger().println(Messages.Client_SA_val_fail()); listener.getLogger().println( "Storage Account name --->" + storageAccount.getStorageAccName() + "<----"); listener.getLogger().println( "Blob end point url --->" + storageAccount.getBlobEndPointURL() + "<----"); return false; } return true; }
Source:
<code>public void classTearDown() throws IOException { <START> generateResultAnalysis("StudentProfileLNPTest", 0.2, 10000); <END> deleteTestData(JSON_DATA_PATH); deleteDataFiles(); }</code><technical_language>suggestion generateResultAnalysis(getClass().getSimpleName(), 0.2, 10000);</technical_language>

Target:
public void classTearDown() throws IOException { deleteTestData(); deleteDataFiles(); }
Source:
<code>public static DocumentBuilder createAndGetDocumentBuilder(Source schemaSource) throws SAXException, ParserConfigurationException, IOException { <START> List<Source> schemaSources = new ArrayList<>(); <END> schemaSources.add(new StreamSource(CORE_SCHEMA_URL.openStream())); schemaSources.add(schemaSource); return createAndGetDocumentBuilder(schemaSources); }</code><technical_language>ArrayList of size 2. Arrays.asList</technical_language>

Target:
public static DocumentBuilder createAndGetDocumentBuilder(Source schemaSource) throws SAXException, ParserConfigurationException, IOException { List<Source> schemaSources = new ArrayList<>(2); schemaSources.add(new StreamSource(CORE_SCHEMA_URL.openStream())); schemaSources.add(schemaSource); return createAndGetDocumentBuilder(schemaSources); }
Source:
<code>public void run() throws Exception { TChannel server = new TChannelServerBuilder("ping-server") .register("ping", new PingRequestHandler()) .port(this.port) .build(); <START> server.start().channel().closeFuture().sync(); <END> }</code><technical_language>out of interest this multithreaded</technical_language>

Target:
public void run() throws Exception { TChannel server = new TChannel.Builder("ping-server") .register("ping", new PingRequestHandler()) .register("also-ping", new PingRequestHandler()) .setPort(this.port) .build(); server.start().channel().closeFuture().sync(); }
Source:
<code>public static ExtMap generateQueryMap(Collection<String> ids, ExtUUID queryEntity) { ExtMap result = new ExtMap().mput( Authz.InvokeKeys.QUERY_ENTITY, queryEntity); ExtKey key = queryEntity.equals(Authz.QueryEntity.GROUP) ? Authz.GroupRecord.ID : Authz.PrincipalRecord.ID; List<ExtMap> filter = new ArrayList<>(); <START> for (String id : ids) { <END> filter.add(createMapForKeyAndValue(key, id)); } result.mput( QueryFilterRecord.OPERATOR, QueryFilterOperator.OR ).mput( QueryFilterRecord.FILTER, filter ); return result; }</code><technical_language>simplified stream</technical_language>

Target:
public static ExtMap generateQueryMap(Collection<String> ids, ExtUUID queryEntity) { ExtMap result = new ExtMap().mput( Authz.InvokeKeys.QUERY_ENTITY, queryEntity); ExtKey key = queryEntity.equals(Authz.QueryEntity.GROUP) ? Authz.GroupRecord.ID : Authz.PrincipalRecord.ID; List<ExtMap> filter = ids.stream().map((id) -> createMapForKeyAndValue(key, id)).collect(Collectors.toList()); result.mput( QueryFilterRecord.OPERATOR, QueryFilterOperator.OR ).mput( QueryFilterRecord.FILTER, filter ); return result; }
Source:
<code>public void run() { Iterator<String> it = spawn.getSpawnState().jobIdIterator(); <START> List<String> jobIdsNotInCache = new LinkedList<>(); <END> try { outputStream.write("{\"search\": [".getBytes()); while (it.hasNext()) { String jobId = it.next(); String expandedConfig = spawn.getCachedExpandedJob(jobId); if (expandedConfig == null) { jobIdsNotInCache.add(jobId); continue; } searchExpandedConfig(jobId, expandedConfig); } for (String jobId : jobIdsNotInCache) { try { searchExpandedConfig(jobId, spawn.getExpandedConfig(jobId)); } catch (ExecutionException e) { log.warn("failed to get expanded config", e); } } outputStream.write("]}".getBytes()); outputStream.flush(); } catch (IOException e) { log.warn("i/o exception in search thread", e); } finally { try { outputStream.close(); } catch (IOException e) { log.warn("failed to close jobsearcher", e); } } }</code><technical_language>want ArrayList instead of a LinkedList</technical_language>

Target:
public void run() { Iterator<String> it = spawn.getSpawnState().jobIdIterator(); List<String> jobIdsNotInCache = new ArrayList<>(); try { outputStream.write("{\"search\": [".getBytes()); while (it.hasNext()) { String jobId = it.next(); String expandedConfig = spawn.getCachedExpandedJob(jobId); if (expandedConfig == null) { jobIdsNotInCache.add(jobId); continue; } searchExpandedConfig(jobId, expandedConfig); } for (String jobId : jobIdsNotInCache) { try { searchExpandedConfig(jobId, spawn.getExpandedConfig(jobId)); } catch (ExecutionException e) { log.warn("failed to get expanded config", e); } } outputStream.write("]}".getBytes()); outputStream.flush(); } catch (IOException e) { log.warn("i/o exception in search thread", e); } finally { try { outputStream.close(); } catch (IOException e) { log.warn("failed to close jobsearcher", e); } } }
Source:
<code>private static InternationalFixedDate resolvePreviousValid(final int prolepticYear, final int month, final int day) { <START> if (month == 0 && day == 0) { <END> return createYearDay(prolepticYear); } if (month == -1 && day == -1 && InternationalFixedChronology.INSTANCE.isLeapYear(prolepticYear)) { return createLeapDay(prolepticYear); } int monthR = month == -1 ? 7 : month == 0 ? InternationalFixedChronology.MONTHS_IN_YEAR : Math.min(month, InternationalFixedChronology.MONTHS_IN_YEAR); int dayR = day == -1 ? 1 : day == 0 ? InternationalFixedChronology.DAYS_IN_MONTH : Math.min(day, InternationalFixedChronology.DAYS_IN_MONTH); return of(prolepticYear, monthR, dayR); }</code><technical_language>resolvePreviousValid(...) - guard future failure, check day-of-month for year-day/leap-day, coerce it: if (month == -1 && isLeapYear(prolepticYear) { return createLeapDay(prolepticYear); } (because situations day-of-month set). Month/day-of-month out-of-range, need full checks (ie, instantiate constructor, route static factories). point of this method is speed leniency</technical_language>

Target:
private static InternationalFixedDate resolvePreviousValid(final int prolepticYear, final int month, final int day) { if ((month == 0 && day == 0) || (month == -1 && day == -1 && INSTANCE.isLeapYear(prolepticYear))) { return create(prolepticYear, month, day); } int monthR = month == -1 ? 7 : month == 0 ? MONTHS_IN_YEAR : Math.min(month, MONTHS_IN_YEAR); int dayR = day == -1 ? 1 : day == 0 ? DAYS_IN_MONTH : Math.min(day, DAYS_IN_MONTH); return create(prolepticYear, monthR, dayR); }
Source:
<code>private void pickFileVFS() { String prevName = jobMeta.environmentSubstitute( getPath() ); if ( !Utils.isEmpty( prevName ) ) { try { if ( KettleVFS.fileExists( prevName ) ) { selectJob( ProviderFilterType.LOCAL ); <START> return; <END> } else { if ( !prevName.endsWith( ".kjb" ) ) { prevName = getEntryName( Const.trim( getPath() ) + ".kjb" ); } if ( KettleVFS.fileExists( prevName ) ) { wPath.setText( prevName ); specificationMethod = ObjectLocationSpecificationMethod.FILENAME; return; } else if ( askToCreateNewJob( prevName ) ) { return; } } } catch ( Exception e ) { } } selectJob( ProviderFilterType.LOCAL ); }</code><technical_language>line 311 is 330, this if block eliminated line 313 refactor as: if ( !KettleVFS.fileExists( prevName ) )</technical_language>

Target:
private void pickFileVFS() { String prevName = jobMeta.environmentSubstitute( getPath() ); if ( !Utils.isEmpty( prevName ) ) { try { if ( !KettleVFS.fileExists( prevName ) ) { if ( !prevName.endsWith( ".kjb" ) ) { prevName = getEntryName( Const.trim( getPath() ) + ".kjb" ); } if ( KettleVFS.fileExists( prevName ) ) { wPath.setText( prevName ); specificationMethod = ObjectLocationSpecificationMethod.FILENAME; return; } else if ( askToCreateNewJob( prevName ) ) { return; } } } catch ( Exception e ) { } } selectJob( ProviderFilterType.LOCAL ); }
Source:
<code>public static OptionalInt getConcurrentLifespansPerNode(Session session) { Integer result = session.getSystemProperty(CONCURRENT_LIFESPANS_PER_NODE, Integer.class); <START> checkArgument(result >= 0, "Concurrent lifespans per node must be non-negative"); <END> if (result == 0) { return OptionalInt.empty(); } else { return OptionalInt.of(result); } }</code><technical_language>I prefer original error message zero a special meaning here</technical_language>

Target:
public static OptionalInt getConcurrentLifespansPerNode(Session session) { Integer result = session.getSystemProperty(CONCURRENT_LIFESPANS_PER_NODE, Integer.class); if (result == 0) { return OptionalInt.empty(); } else { checkArgument(result > 0, "Concurrent lifespans per node must be positive if set to non-zero"); return OptionalInt.of(result); } }
Source:
<code>public String toString() { <START> return super.toString() + ", " + "JdbcRuntimeInfo: {" + "driverClassName:" + driverClassName + "}"; <END> }</code><technical_language>create strings ? ", " + "JdbcRuntimeInfo: {" + "driverClassName:"</technical_language>

Target:
public String toString() { return super.toString() + ", JdbcRuntimeInfo: {driverClassName:" + driverClassName + "}"; }