auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static void main(String[] args) { Traverson traverson = new Traverson(URI.create("http://localhost:8080"), MediaTypes.HAL_JSON); <START> Map<String, Object> parameters = new HashMap<String, Object>(); <END> parameters.put("location", "40.740337,-73.995146"); parameters.put("distance", "0.5miles"); PagedResources<Resource<Store>> resources = traverson. follow("stores", "search", "by-location"). withTemplateParameters(parameters). toObject(TYPE_REFERENCE); PageMetadata metadata = resources.getMetadata(); System.out.println(String.format("Got %s of %s stores: ", resources.getContent().size(), metadata.getTotalElements())); for (Resource<Store> resource : resources) { Store store = resource.getContent(); System.out.println(String.format("- %s - %s", store.name, store.address)); } }</code><technical_language>Left overs intermediate removal of Java 7 settings</technical_language>

Target:
public static void main(String[] args) { Traverson traverson = new Traverson(URI.create("http://localhost:8080"), MediaTypes.HAL_JSON); Map<String, Object> parameters = new HashMap<>(); parameters.put("location", "40.740337,-73.995146"); parameters.put("distance", "0.5miles"); PagedResources<Resource<Store>> resources = traverson. follow("stores", "search", "by-location"). withTemplateParameters(parameters). toObject(TYPE_REFERENCE); PageMetadata metadata = resources.getMetadata(); System.out.println(String.format("Got %s of %s stores: ", resources.getContent().size(), metadata.getTotalElements())); for (Resource<Store> resource : resources) { Store store = resource.getContent(); System.out.println(String.format("- %s - %s", store.name, store.address)); } }
Source:
<code>public void testOutofElection() { HashMap<Long,Vote> outofelection = new HashMap<Long,Vote>(); outofelection.put(1L, new Vote(0x0, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x17, ServerState.FOLLOWING)); outofelection.put(2L, new Vote(0x0, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x17, ServerState.FOLLOWING)); outofelection.put(4L, new Vote(0x1, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x18, ServerState.FOLLOWING)); Vote vote = new Vote(0x1, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x18, ServerState.LEADING); outofelection.put(5L, vote); Notification n = new Notification(); n.version = vote.getVersion(); n.leader = vote.getId(); n.zxid = vote.getZxid(); n.electionEpoch = vote.getElectionEpoch(); n.state = vote.getState(); n.peerEpoch = vote.getPeerEpoch(); n.sid = 5L; fle.logicalclock.set(0x1); <START> Assert.assertTrue("Termination predicate failed", <END> fle.getVoteTracker(outofelection, new Vote(n.version, n.leader, n.zxid, n.electionEpoch, n.peerEpoch, n.state)).hasAllQuorums()); Assert.assertTrue("Leader check failed", fle.checkLeader(outofelection, n.leader, n.electionEpoch)); }</code><technical_language>I testing predicates - this patch / 3.4 termPredicate active. Suggest rephrase "Termination predicate failed" else</technical_language>

Target:
public void testOutofElection() { HashMap<Long,Vote> outofelection = new HashMap<Long,Vote>(); outofelection.put(1L, new Vote(0x0, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x17, ServerState.FOLLOWING)); outofelection.put(2L, new Vote(0x0, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x17, ServerState.FOLLOWING)); outofelection.put(4L, new Vote(0x1, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x18, ServerState.FOLLOWING)); Vote vote = new Vote(0x1, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x18, ServerState.LEADING); outofelection.put(5L, vote); Notification n = new Notification(); n.version = vote.getVersion(); n.leader = vote.getId(); n.zxid = vote.getZxid(); n.electionEpoch = vote.getElectionEpoch(); n.state = vote.getState(); n.peerEpoch = vote.getPeerEpoch(); n.sid = 5L; fle.logicalclock.set(0x1); Assert.assertTrue("Quorum check failed", fle.getVoteTracker(outofelection, new Vote(n.version, n.leader, n.zxid, n.electionEpoch, n.peerEpoch, n.state)).hasAllQuorums()); Assert.assertTrue("Leader check failed", fle.checkLeader(outofelection, n.leader, n.electionEpoch)); }
Source:
<code>public <T, K extends Exception> T applyWithPermit(FunctionCheckedException<F, T, K> function) throws K { if (localThreadPool.tryAcquire()) { return applyAndRelease(localThreadPool, function); } if (sharedThreadPool.tryAcquire()) { return applyAndRelease(sharedThreadPool, function); } <START> throw new TooManyRequestsException("ThreadPooledLockService was unable to acquire a permit to assign a server " <END> + "thread to the request."); }</code><technical_language>nit: preferably break line instead, avoid splitting string: throw new TooManyRequestsException( "ThreadPooledLockService unable acquire a permit assign a server thread request.");</technical_language>

Target:
public <T, K extends Exception> T applyWithPermit(FunctionCheckedException<F, T, K> function) throws K { if (localThreadPool.tryAcquire()) { return applyAndRelease(localThreadPool, function); } if (sharedThreadPool.tryAcquire()) { return applyAndRelease(sharedThreadPool, function); } throw new TooManyRequestsException( "ThreadPooledLockService was unable to acquire a permit to assign a server thread to the request."); }
Source:
<code>public Object get(WebRequest request) { boolean authenticated = Context.isAuthenticated(); SimpleObject session = new SimpleObject(); session.add("sessionId", request.getSessionId()).add("authenticated", authenticated); if (authenticated) { User user = Context.getAuthenticatedUser(); String rep = request.getParameter(RestConstants.REQUEST_PROPERTY_FOR_REPRESENTATION); <START> if(null == rep || RestConstants.REPRESENTATION_DEFAULT.equals(rep)){ <END> SimpleObject authenticatedUser = new SimpleObject(); authenticatedUser.add("uuid", user.getUuid()).add("display", StringUtils.isNotEmpty(user.getUsername()) ? user.getUsername() : user.getSystemId()); session.add("user", authenticatedUser); } else if(RestConstants.REPRESENTATION_FULL.equals(rep)){ SimpleObject authenticatedUser = (SimpleObject)ConversionUtil.convertToRepresentation(user, Representation.DEFAULT, UserConverter1_8.class); session.add("user", authenticatedUser); } } return session; }</code><technical_language>want manually construct a simple object. want return a proper representation of User. Pseudo code for this: Representation rep = getRepresentation(request); // DEFAULT if is specified. RestService.getRepresentation(String) for this def userRep = ConversionUtil.convertToRepresentation(Context.getAuthenticatedUser(), rep);</technical_language>

Target:
public Object get(WebRequest request) { boolean authenticated = Context.isAuthenticated(); SimpleObject session = new SimpleObject(); session.add("sessionId", request.getSessionId()).add("authenticated", authenticated); if (authenticated) { String repParam = request.getParameter(RestConstants.REQUEST_PROPERTY_FOR_REPRESENTATION); Representation rep = (repParam != null) ? restService.getRepresentation(repParam) : Representation.DEFAULT; session.add("user",ConversionUtil.convertToRepresentation(Context.getAuthenticatedUser(), rep)); } return session; }
Source:
<code>public void testSnapshotSyncStreamImplementation() throws Exception { initLogReplicationFSM(ReaderImplementation.STREAMS); writeToMap(); transitionAvailable.acquire(); <START> fsm.input(new LogReplicationEvent(LogReplicationEventType.SNAPSHOT_SYNC_REQUEST)); <END> System.out.println("**** Wait for snapshot sync to complete"); Queue<LogReplicationEntry> listenerQueue = ((TestDataSender) dataSender).getEntryQueue(); while (listenerQueue.size() < LARGE_NUM_ENTRIES/StreamsSnapshotReader.MAX_NUM_SMR_ENTRY) { sleep(WAIT_TIME); System.out.print("\nqueueSize " + listenerQueue.size() + "\n"); } System.out.print("\nqueueSize " + listenerQueue.size() + "\n"); assertThat(LARGE_NUM_ENTRIES/StreamsSnapshotReader.MAX_NUM_SMR_ENTRY).isLessThanOrEqualTo(listenerQueue.size()); writeTxIncrementalUpdates(); int incrementalUpdates = 0; while(incrementalUpdates < NUM_ENTRIES) { ((TestDataSender)dataSender).getEntryQueue().poll(); incrementalUpdates++; } assertThat(incrementalUpdates).isEqualTo(NUM_ENTRIES); }</code><technical_language>here, this change? this is verifying event transitions expected state</technical_language>

Target:
public void testSnapshotSyncStreamImplementation() throws Exception { initLogReplicationFSM(ReaderImplementation.STREAMS); writeToMap(); transitionAvailable.acquire(); transition(LogReplicationEventType.SNAPSHOT_SYNC_REQUEST, LogReplicationStateType.IN_SNAPSHOT_SYNC, true); log.info("**** Wait for snapshot sync to complete"); Queue<LogReplicationEntry> listenerQueue = ((TestDataSender) dataSender).getEntryQueue(); while (listenerQueue.size() < LARGE_NUM_ENTRIES/StreamsSnapshotReader.MAX_NUM_SMR_ENTRY) { sleep(WAIT_TIME); } log.info("queueSize ", listenerQueue.size()); assertThat(LARGE_NUM_ENTRIES/StreamsSnapshotReader.MAX_NUM_SMR_ENTRY).isLessThanOrEqualTo(listenerQueue.size()); writeTxIncrementalUpdates(); int incrementalUpdates = 0; while(incrementalUpdates < NUM_ENTRIES) { ((TestDataSender)dataSender).getEntryQueue().poll(); incrementalUpdates++; } assertThat(incrementalUpdates).isEqualTo(NUM_ENTRIES); }
Source:
<code>public synchronized RegisteredService save(final RegisteredService registeredService, final boolean publishEvent) { publishEvent(new CasRegisteredServicePreSaveEvent(this, registeredService)); <START> var r = this.serviceRegistry.save(registeredService); <END> this.services.put(r.getId(), r); saveInternal(registeredService); if (publishEvent) { publishEvent(new CasRegisteredServiceSavedEvent(this, r)); } return r; }</code><technical_language>Is this change needed</technical_language>

Target:
public synchronized RegisteredService save(final RegisteredService registeredService, final boolean publishEvent) { publishEvent(new CasRegisteredServicePreSaveEvent(this, registeredService)); val r = this.serviceRegistry.save(registeredService); this.services.put(r.getId(), r); saveInternal(registeredService); if (publishEvent) { publishEvent(new CasRegisteredServiceSavedEvent(this, r)); } return r; }
Source:
<code>public void getConnection(ProxyTarget target, HttpServerExchange exchange, final ProxyCallback<ProxyConnection> callback, long timeout, TimeUnit timeUnit) { String containerId = containerResolver.resolveContainerId(exchange, configuration.getContainerInfosPerContainer()); LoadBalancingProxyClient client = containerClients.get(containerId); try { client.getConnection(target, exchange, new ProxyCallback<ProxyConnection>() { @Override public void completed(HttpServerExchange exchange, ProxyConnection result) { callback.completed(exchange, result); } @Override public void failed(HttpServerExchange httpServerExchange) { try { adminHandler.removeUnavailableServer(((CaptureHostLoadBalancingProxyClient) client).getUri()); } finally { callback.failed(exchange); ((CaptureHostLoadBalancingProxyClient) client).clear(); } } @Override public void couldNotResolveBackend(HttpServerExchange exchange) { callback.couldNotResolveBackend(exchange); } @Override public void queuedRequestFailed(HttpServerExchange exchange) { callback.queuedRequestFailed(exchange); } }, timeout, timeUnit); <START> } catch (Exception e) { <END> if (e instanceof SocketException || e instanceof UnknownHostException || e instanceof UnresolvedAddressException ) { adminHandler.removeUnavailableServer(((CaptureHostLoadBalancingProxyClient) client).getUri()); } throw new RuntimeException(e); } }</code><technical_language>is point of this try catch statement here? I checked exception thrown above</technical_language>

Target:
public void getConnection(ProxyTarget target, HttpServerExchange exchange, final ProxyCallback<ProxyConnection> callback, long timeout, TimeUnit timeUnit) { String containerId = containerResolver.resolveContainerId(exchange, configuration.getContainerInfosPerContainer()); CaptureHostLoadBalancingProxyClient client = containerClients.get(containerId); try { client.getConnection(target, exchange, new ProxyCallback<ProxyConnection>() { @Override public void completed(HttpServerExchange exchange, ProxyConnection result) { callback.completed(exchange, result); } @Override public void failed(HttpServerExchange httpServerExchange) { try { adminHandler.removeUnavailableServer(client.getUri()); } finally { callback.failed(exchange); client.clear(); } } @Override public void couldNotResolveBackend(HttpServerExchange exchange) { callback.couldNotResolveBackend(exchange); } @Override public void queuedRequestFailed(HttpServerExchange exchange) { callback.queuedRequestFailed(exchange); } }, timeout, timeUnit); } catch (Exception e) { if (e instanceof SocketException || e instanceof UnknownHostException || e instanceof UnresolvedAddressException ) { adminHandler.removeUnavailableServer(client.getUri()); } throw new RuntimeException(e); } }
Source:
<code><START> public T getHelper() { <END> if (mHelper == null) { Log.w(LOG_TAG, "Helper not created."); } return mHelper; }</code><technical_language>@Nullable people supposed handle null helpers? crash instead if this is a valid configuration</technical_language>

Target:
public T getHelper() { if (mHelper == null) { throw new TestHelperException("Helper not created"); } return mHelper; }
Source:
<code>static Result compile(Iterable<? extends Processor> processors, Iterable<? extends JavaFileObject> sources) { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); <START> if(compiler == null) <END> throw new CompilerNotFoundException(); DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>(); InMemoryJavaFileManager fileManager = new InMemoryJavaFileManager( compiler.getStandardFileManager(diagnosticCollector, Locale.getDefault(), UTF_8)); CompilationTask task = compiler.getTask( null, fileManager, diagnosticCollector, ImmutableSet.<String>of(), ImmutableSet.<String>of(), sources); task.setProcessors(processors); boolean successful = task.call(); return new Result(successful, sortDiagnosticsByKind(diagnosticCollector.getDiagnostics()), fileManager.getOutputFiles()); }</code><technical_language>nit: space if, prefer curly braces if statements a single line</technical_language>

Target:
static Result compile(Iterable<? extends Processor> processors, Iterable<? extends JavaFileObject> sources) { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if (compiler == null) { throw new IllegalStateException("Java Compiler is not present. " + "May be, you need to include tools.jar on your dependency list."); } DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>(); InMemoryJavaFileManager fileManager = new InMemoryJavaFileManager( compiler.getStandardFileManager(diagnosticCollector, Locale.getDefault(), UTF_8)); CompilationTask task = compiler.getTask( null, fileManager, diagnosticCollector, ImmutableSet.<String>of(), ImmutableSet.<String>of(), sources); task.setProcessors(processors); boolean successful = task.call(); return new Result(successful, sortDiagnosticsByKind(diagnosticCollector.getDiagnostics()), fileManager.getOutputFiles()); }
Source:
<code>public void testIsOpenFalseWhenTransportClosed() throws Exception { <START> when(mockTrans.isOpen()).thenReturn(false); <END> assertFalse(muxTransport.isOpen()); }</code><technical_language>want set registry too</technical_language>

Target:
public void testIsOpenFalseWhenTransportClosed() throws Exception { when(mockTrans.isOpen()).thenReturn(false); registry = new FClientRegistry(); muxTransport.setRegistry(registry); assertFalse(muxTransport.isOpen()); }
Source:
<code>private void testGetWithAtleastOneNonExistentBlob(List<BlobId> blobIds) { try { store.get(blobIds, EnumSet.noneOf(StoreGetOptions.class)); <START> assertTrue("get with any non existent id should fail", false); <END> } catch (StoreException e) { assertTrue("get with any non existent blob id should throw exception with " + StoreErrorCodes.ID_Not_Found + " error code.", e.getErrorCode().equals(StoreErrorCodes.ID_Not_Found)); } }</code><technical_language>change to: fail(message)</technical_language>

Target:
private void testGetWithAtleastOneNonExistentBlob(List<BlobId> blobIds) { try { store.get(blobIds, EnumSet.noneOf(StoreGetOptions.class)); fail("get with any non existent id should fail"); } catch (StoreException e) { assertEquals("get with any non existent blob id should throw exception with " + StoreErrorCodes.ID_Not_Found + " error code.", e.getErrorCode(), StoreErrorCodes.ID_Not_Found); } }
Source:
<code>private static FormDef deserializeFormDef(Context context, File formDefFile) { FileInputStream fis = null; DataInputStream dis = null; FormDef fd; try { fd = new FormDef(DeveloperPreferences.useExpressionCachingInForms()); fis = new FileInputStream(formDefFile); dis = new DataInputStream(new BufferedInputStream(fis)); fd.readExternal(dis, CommCareApplication.instance().getPrototypeFactory(context)); <START> dis.close(); <END> } catch (Throwable e) { e.printStackTrace(); fd = null; } finally { StreamsUtil.closeStream(fis); StreamsUtil.closeStream(dis); } return fd; }</code><technical_language>This get removed, right</technical_language>

Target:
private static FormDef deserializeFormDef(Context context, File formDefFile) { FileInputStream fis = null; DataInputStream dis = null; FormDef fd; try { fd = new FormDef(DeveloperPreferences.useExpressionCachingInForms()); fis = new FileInputStream(formDefFile); dis = new DataInputStream(new BufferedInputStream(fis)); fd.readExternal(dis, CommCareApplication.instance().getPrototypeFactory(context)); } catch (Throwable e) { e.printStackTrace(); fd = null; } finally { StreamsUtil.closeStream(fis); StreamsUtil.closeStream(dis); } return fd; }
Source:
<code>public static boolean fixAppDataPermissions(Context context) { if (!Shell.SU.available()) { Log.e(TAG,"Root is not available. Cannot fix permssions "); return false; } try { ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(),0); Log.d(TAG,"Uid of '" + context.getPackageName() + "' is " + appInfo.uid); Process fixPerm = Runtime.getRuntime().exec("su"); DataOutputStream fixPermOut = new DataOutputStream(fixPerm.getOutputStream()); String dir = context.getFilesDir().getAbsolutePath(); String cmd = "chown -R " + appInfo.uid + ":" + appInfo.uid + " " + dir + "\n"; Log.d(TAG,"Running: '" + cmd); fixPermOut.writeBytes(cmd); cmd = "restorecon -R " + dir + "\n"; Log.d(TAG,"Running: '" + cmd); fixPermOut.writeBytes(cmd); fixPermOut.writeBytes("sleep 2\n"); <START> fixPermOut.writeBytes("exit\n"); <END> fixPermOut.flush(); if (fixPerm.waitFor() == 0) { Log.i(TAG,"Successfully changed the owner, the group and the SELinux context of '" + dir + "'."); return true; } else { return false; } } catch (IOException | InterruptedException e) { Log.w(TAG,"Cannot chown data directory",e); } catch (NameNotFoundException e) { Log.w(TAG,"This should not happen",e); } return false; }</code><technical_language>fact called output stream is a bit strange, smells writing stdout. Also, is sleep exit needed</technical_language>

Target:
public static boolean fixAppDataPermissions(Context context) { if (!Shell.SU.available()) { Log.e(TAG, "Root is not available. Cannot fix permssions."); return false; } try { ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0); Log.d(TAG, "Uid of '" + context.getPackageName() + "' is " + appInfo.uid); Process fixPerm = Runtime.getRuntime().exec("su"); DataOutputStream fixPermOut = new DataOutputStream(fixPerm.getOutputStream()); String dir = context.getFilesDir().getAbsolutePath(); String cmd = "chown -R " + appInfo.uid + ":" + appInfo.uid + " " + dir + "\n"; Log.d(TAG, "Running: '" + cmd); fixPermOut.writeBytes(cmd); cmd = "restorecon -R " + dir + "\n"; Log.d(TAG, "Running: '" + cmd); fixPermOut.writeBytes(cmd); fixPermOut.flush(); fixPermOut.close(); int ret = fixPerm.waitFor(); Log.i(TAG, "Changed the owner, the group and the SELinux context of '" + dir + "'. Result: " + ret); return ret == 0; } catch (IOException | InterruptedException e) { Log.w(TAG, "Cannot chown data directory", e); } catch (NameNotFoundException e) { Log.w(TAG, "This should not happen", e); } return false; }
Source:
<code>public void setAttributes(Map<String, Object> attrs) { this.attrs = U.sealMap(attrs); <START> Object id = this.attrs.get("CLUSTER_REGION_ID"); <END> if (id == null) regionId = null; else if (id instanceof Integer) regionId = ((Integer)id).longValue(); else if (id instanceof Long) regionId = (Long)id; else if (id instanceof String) try { regionId = Long.valueOf((String)id); } catch (NumberFormatException ignored) { regionId = null; } else regionId = null; }</code><technical_language>CLUSTER_REGION_ID set attributes is convenient. User opportunity set it: 1. IgniteConfiguration.setClusterRegionId(long) 2. system property - IgniteSystemProperties.IGNITE_CLUSTER_REGION_ID - is flexible allows pass ID ignite.sh 3. I remove public attribute name</technical_language>

Target:
public void setAttributes(Map<String, Object> attrs) { this.attrs = U.sealMap(attrs); }
Source:
<code>public int getContentHeight() { <START> return getFont().getHeight(); <END> }</code><technical_language>This right, docs this "The returned include height of content in editor, height of visible content. Note method returns 0, if editor parent. "</technical_language>

Target:
public int getContentHeight() { System.out.println("warning: TextEditor::getContentHeight needs a more correct implementation"); return getFont().getHeight(); }
Source:
<code><START> public String getId() <END> { return this.id; }</code><technical_language>Is this change needed</technical_language>

Target:
String getId() { return this.id; }
Source:
<code>public Object instantiate(final Target<?> target, Parameters parameters) { <START> Function<Parameter, Parameter> INDEXED_PARAMETERS = new Function<Parameter, Parameter>() { <END> int i = 0; @Override public Parameter apply(Parameter parameter) { if (target.getName().equals(parameter.getName())) { return new Parameter(parameter.getName() + "[" + i++ + "]", parameter.getValue()); } return parameter; } }; List<Parameter> fixed = FluentIterable.from(parameters.forTarget(target)) .transform(INDEXED_PARAMETERS).toList(); return delegate.instantiate(target, new Parameters(fixed)); }</code><technical_language>if var name is uppercased, a constant. change name indexedParameters</technical_language>

Target:
public Object instantiate(final Target<?> target, Parameters parameters) { List<Parameter> fixed = FluentIterable.from(parameters.forTarget(target)) .transform(indexedParameters(target)).toList(); return delegate.instantiate(target, new Parameters(fixed)); }
Source:
<code>private void setDialogPaneContent(TurboIssue issue) { try { createMainLayout(); setTitleLabel(issue); getDialogPane().setContent(mainLayout); } catch (IOException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>else need done recover error? close dialog instead of showing a partially-loaded interface</technical_language>

Target:
private void setDialogPaneContent(TurboIssue issue) { createMainLayout(); setTitleLabel(issue); getDialogPane().setContent(mainLayout); }
Source:
<code>protected void waitForServerBlocked(TerracottaServer server) { <START> waitUntil(() -> isServerBlocked(server), is(true), ASSERT_TIMEOUT); <END> }</code><technical_language>I waitUntil(() -> isServerBlocked(server), is(true)); is enough: is a method a supplier matcher re-using assertion timeout already. is getAssertTimeout() instead of ASSERT_TIMEOUT getAssertTimeout() is meant overridden in classes set a timeout</technical_language>

Target:
protected void waitForServerBlocked(TerracottaServer server) { waitUntil(() -> isServerBlocked(server), is(true)); }
Source:
<code>public Connection connect(URI uri, Properties properties) throws ConnectionException { <START> URI keyURI = createKey(uri); <END> ServerDescriptor serverDescriptor = servers.get(keyURI); if (serverDescriptor == null) { throw new IllegalArgumentException("No server available for " + uri); } Connection connection = serverDescriptor.server.connectNewClient(); serverDescriptor.add(connection, properties); LOGGER.info("Client opened to PassthroughServer at {}", formatConnectionId(connection), keyURI); return (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class[] { Connection.class }, new ConnectionInvocationHandler(serverDescriptor, connection)); }</code><technical_language>This call suspicious too</technical_language>

Target:
public Connection connect(URI uri, Properties properties) throws ConnectionException { checkURI(uri); ServerDescriptor serverDescriptor = SERVERS.get(uri); if (serverDescriptor == null) { throw new IllegalArgumentException("No server available for " + uri); } Connection connection = serverDescriptor.server.connectNewClient(); serverDescriptor.add(connection, properties); LOGGER.info("Client opened to PassthroughServer at {}", formatConnectionId(connection), uri); return (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class[] { Connection.class }, new ConnectionInvocationHandler(serverDescriptor, connection)); }
Source:
<code>@Test public void customSampler() throws Exception { String path = "/foo"; close(); SamplerFunction<HttpRequest> sampler = (HttpRuleSampler.newBuilder() .putRule(pathStartsWith(path), Sampler.NEVER_SAMPLE) .build()); httpTracing = httpTracing.toBuilder().clientSampler(sampler).build(); <START> client = newClient(server.getPort()); <END> server.enqueue(new MockResponse()); get(client, path); RecordedRequest request = takeRequest(); assertThat(request.getHeaders().toMultimap()) .containsEntry("x-b3-sampled", asList("0")); }</code><technical_language>nit: extra parenthesis in function</technical_language>

Target:
@Test public void customSampler() throws Exception { String path = "/foo"; close(); SamplerFunction<HttpRequest> sampler = HttpRuleSampler.newBuilder() .putRule(pathStartsWith(path), Sampler.NEVER_SAMPLE) .build(); httpTracing = httpTracing.toBuilder().clientSampler(sampler).build(); client = newClient(server.getPort()); server.enqueue(new MockResponse()); get(client, path); RecordedRequest request = takeRequest(); assertThat(request.getHeaders().toMultimap()) .containsEntry("x-b3-sampled", asList("0")); }
Source:
<code>public void whenNoChangesDetectedButSchemaIsDifferent() throws Exception { final EventTypeTestBuilder builder = EventTypeTestBuilder.builder(); final EventType oldEventType = builder.schema("{}").build(); final EventType newEventType = builder.schema("{\"example\":\"something\"}").build(); Mockito.doReturn(Optional.empty()).when(evolutionConstraint).validate(oldEventType, newEventType); Mockito.doReturn(NO_CHANGES).when(compatibleChanges).get(any()); Mockito.doReturn(Lists.newArrayList(new SchemaChange(TITLE_CHANGED, "#/"))).when(schemaDiff) .collectChanges(any(), any()); <START> final EventType eventType = service.evolve(oldEventType, newEventType); <END> }</code><technical_language>I need declare eventType, is</technical_language>

Target:
public void whenNoChangesDetectedButSchemaIsDifferent() throws Exception { final EventTypeTestBuilder builder = EventTypeTestBuilder.builder(); final EventType oldEventType = builder.schema("{}").build(); final EventType newEventType = builder.schema("{\"example\":\"something\"}").build(); Mockito.doReturn(Optional.empty()).when(evolutionConstraint).validate(oldEventType, newEventType); Mockito.doReturn(NO_CHANGES).when(compatibleChanges).get(any()); Mockito.doReturn(Lists.newArrayList(new SchemaChange(TITLE_CHANGED, "#/"))).when(schemaDiff) .collectChanges(any(), any()); service.evolve(oldEventType, newEventType); }
Source:
<code>private void commitFile(String encodedPartition) { if (!startOffsets.containsKey(encodedPartition)) { return; } long startOffset = startOffsets.get(encodedPartition); long endOffset = offsets.get(encodedPartition); String tempFile = tempFiles.get(encodedPartition); String directory = getDirectory(encodedPartition); String committedFile = FileUtils.committedFileName( url, topicsDir, directory, tp, startOffset, endOffset, extension, zeroPadOffsetFormat ); String directoryName = FileUtils.directoryName(url, topicsDir, directory); if (!storage.exists(directoryName)) { storage.create(directoryName); } storage.commit(tempFile, committedFile); startOffsets.remove(encodedPartition); offsets.remove(encodedPartition); offset = offset + recordCounter; <START> committedOffset = offset; <END> recordCounter = 0; log.info("Committed for {}", committedFile, tp); }</code><technical_language>here? committedOffset is offset - 1. EDIT: endOffset find committed offset here? metrics match filenames show HDFS</technical_language>

Target:
private void commitFile(String encodedPartition) { log.debug("Committing file for partition {}", encodedPartition); if (!startOffsets.containsKey(encodedPartition)) { return; } long startOffset = startOffsets.get(encodedPartition); long endOffset = offsets.get(encodedPartition); String tempFile = tempFiles.get(encodedPartition); String directory = getDirectory(encodedPartition); String committedFile = FileUtils.committedFileName( url, topicsDir, directory, tp, startOffset, endOffset, extension, zeroPadOffsetFormat ); String directoryName = FileUtils.directoryName(url, topicsDir, directory); if (!storage.exists(directoryName)) { storage.create(directoryName); } storage.commit(tempFile, committedFile); startOffsets.remove(encodedPartition); offsets.remove(encodedPartition); offset = offset + recordCounter; committedOffset = offset - 1; recordCounter = 0; log.info("Committed for {}", committedFile, tp); }
Source:
<code>File get(String bsn, Version version, Map<String, String> properties, DownloadListener... listeners) throws Exception { Resource resource = getBridge().get(bsn, version); if (resource == null) return null; ContentCapability contentCapability = ResourceUtils.getContentCapability(resource); if (contentCapability == null) return null; URI url = contentCapability.url(); boolean packed = url.getPath() .endsWith(Unpack200.PACKED_SUFFIX); final File link = new File(location, bsn + "-" + version + ".jar"); Promise<File> go = client.build() .useCache(MAX_STALE) .async(url.toURL()); if (listeners.length == 0) { return handleDownloadResult(packed, link, go); } new DownloadListenerPromise(reporter, name + ": get " + bsn + ";" + version + " " + url, go, listeners); <START> return handleDownloadResult(packed, link, go); <END> }</code><technical_language>do this way. need do unpacking a map operation promise. block in this method point of listeners is block here</technical_language>

Target:
File get(String bsn, Version version, Map<String, String> properties, DownloadListener... listeners) throws Exception { Resource resource = getBridge().get(bsn, version); if (resource == null) return null; ContentCapability contentCapability = ResourceUtils.getContentCapability(resource); if (contentCapability == null) return null; URI url = contentCapability.url(); final File source = client.getCacheFileFor(url); final File link = new File(location, bsn + "-" + version + ".jar"); IO.createSymbolicLinkOrCopy(link, source); Promise<File> go = client.build() .useCache(MAX_STALE) .asTag() .async(url.toURL()) .map(tag -> processor.unpackAndLinkIfNeeded(tag, link)); if (listeners.length == 0) return go.getValue(); new DownloadListenerPromise(reporter, name + ": get " + bsn + ";" + version + " " + url, go, listeners); return link; }
Source:
<code>private void validateSecuritySchemeReferences(Model model, AbstractNode node, Set<SwaggerError> errors) { if (node.getPointerString().matches(".*/security/\\d+")) { AbstractNode securitySchemes = model.find(securityPointer); if (node.isObject()) { for (String field : node.asObject().fieldNames()) { AbstractNode securityScheme = securitySchemes.get(field); if (securityScheme == null) { errors.add( error(node.get(field), IMarker.SEVERITY_ERROR, Messages.error_invalid_reference_type)); <START> } else { <END> validateSecuritySchemScopes(node, field, securityScheme, errors); } } } } }</code><technical_language>I (on line 50), enough info expected type, add explanation end of standard "Invalid object reference, referenced object is of expected type": > Invalid object reference, referenced object is of expected type. a valid security scheme</technical_language>

Target:
private void validateSecuritySchemeReferences(Model model, AbstractNode node, Set<SwaggerError> errors) { if (node.getPointerString().matches(".*/security/\\d+")) { AbstractNode securitySchemes = model.find(securityPointer); if (node.isObject()) { for (String field : node.asObject().fieldNames()) { AbstractNode securityScheme = securitySchemes.get(field); if (securityScheme == null) { String message = Messages.error_invalid_reference_type + " It should be a valid security scheme."; errors.add(error(node.get(field), IMarker.SEVERITY_ERROR, message)); } else { validateSecuritySchemeScopes(node, field, securityScheme, errors); } } } } }
Source:
<code>protected Subject createSubjectFromToken(JWT token) { String principal = token.getSubject(); String claimvalue = null; if (expectedPrincipalClaim != null) { claimvalue = token.getClaim(expectedPrincipalClaim); } if (claimvalue != null) { <START> principal = claimvalue.toLowerCase(Locale.ENGLISH); <END> } @SuppressWarnings("rawtypes") HashSet emptySet = new HashSet(); Set<Principal> principals = new HashSet<>(); Principal p = new PrimaryPrincipal(principal); principals.add(p); return new Subject(true, principals, emptySet, emptySet); }</code><technical_language>Is Locale.ENGLISH correct here? Locale.ROOT</technical_language>

Target:
protected Subject createSubjectFromToken(JWT token) { String principal = token.getSubject(); String claimvalue = null; if (expectedPrincipalClaim != null) { claimvalue = token.getClaim(expectedPrincipalClaim); } if (claimvalue != null) { principal = claimvalue.toLowerCase(Locale.ROOT); } @SuppressWarnings("rawtypes") HashSet emptySet = new HashSet(); Set<Principal> principals = new HashSet<>(); Principal p = new PrimaryPrincipal(principal); principals.add(p); return new Subject(true, principals, emptySet, emptySet); }
Source:
<code>static List<TrackableInventoryEntry> getTrackableInventory() { final List<TrackableInventoryEntry> trackableInventoryEntries = new ArrayList<>(); int skip = 0; TrackableInventoryEntry[] entries = null; <START> while (entries == null || entries.length == MAX_TAKE) { <END> entries = getAPI("/trackables?inCollection=false&take=" + MAX_TAKE + "&skip=" + skip, TrackableInventoryEntry[].class).blockingGet(); trackableInventoryEntries.addAll(Arrays.asList(entries)); skip += MAX_TAKE; } return trackableInventoryEntries; }</code><technical_language>get rid of condition (and null-initialization of entries) a do-while loop</technical_language>

Target:
static List<TrackableInventoryEntry> getTrackableInventory() { final List<TrackableInventoryEntry> trackableInventoryEntries = new ArrayList<>(); int skip = 0; TrackableInventoryEntry[] entries; do { entries = getAPI("/trackables?inCollection=false&take=" + MAX_TAKE + "&skip=" + skip, TrackableInventoryEntry[].class).blockingGet(); trackableInventoryEntries.addAll(Arrays.asList(entries)); skip += MAX_TAKE; } while (entries.length == MAX_TAKE); return trackableInventoryEntries; }
Source:
<code>public void testChangingCurrentFrameCLINotification() throws Throwable { ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<MIStoppedEvent>(fMultiRunControl.getSession(), MIStoppedEvent.class); SyncUtil.addBreakpoint(SOURCE_NAME + ":" + getLineForTag("LINE_MAIN_ALL_THREADS_STARTED"), false); SyncUtil.addBreakpoint("36", false); SyncUtil.resumeAll(); eventWaitor.waitForEvent(2000); eventWaitor.waitForEvent(2000); eventWaitor.waitForEvent(2000); eventWaitor.waitForEvent(2000); <START> eventWaitor.waitForEvent(2000); <END> assertEquals("2",switchThreadAndCaptureThreadSwitchedEvent("2")); for (int i = 0; i < 2; i++) { assertEquals("1",switchFrameAndCaptureStackFrameSwitchedEvent("1")); assertEquals("0",switchFrameAndCaptureStackFrameSwitchedEvent("0")); } }</code><technical_language>massageTimeout instead,</technical_language>

Target:
public void testChangingCurrentFrameCLINotification() throws Throwable { ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<MIStoppedEvent>(fMultiRunControl.getSession(), MIStoppedEvent.class); SyncUtil.addBreakpoint(SOURCE_NAME + ":" + getLineForTag("LINE_MAIN_ALL_THREADS_STARTED"), false); SyncUtil.addBreakpoint("36", false); SyncUtil.resumeAll(); eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); assertEquals("2",switchThreadAndCaptureThreadSwitchedEvent("2")); for (int i = 0; i < 2; i++) { assertEquals("1",switchFrameAndCaptureStackFrameSwitchedEvent("1")); assertEquals("0",switchFrameAndCaptureStackFrameSwitchedEvent("0")); } }
Source:
<code>public void define(WebService.NewController context) { WebService.NewAction action = context.createAction(ACTION_LIST) .setSince("6.6") .setDescription("List the branches of a project.<br/>" + <START> "Requires 'Browse on the project' or 'Execute analysis' rights on the specified project.") <END> .setResponseExample(Resources.getResource(getClass(), "list-example.json")) .setHandler(this); addProjectParam(action); }</code><technical_language>term "Browse" "Browse project"</technical_language>

Target:
public void define(WebService.NewController context) { WebService.NewAction action = context.createAction(ACTION_LIST) .setSince("6.6") .setDescription("List the branches of a project.<br/>" + "Requires 'Browse' or 'Execute analysis' rights on the specified project.") .setResponseExample(Resources.getResource(getClass(), "list-example.json")) .setHandler(this); addProjectParam(action); }
Source:
<code><START> public String[] getFinalizedUptoPartitions(List<Message> lastMessages, <END> List<Message> committedMessages) throws Exception { if (lastMessages == null || committedMessages == null) { LOG.error("Either: and is null", lastMessages, committedMessages); return null; } assert lastMessages.size() == committedMessages.size(); long minMillis = Long.MAX_VALUE; for (int i = 0; i < lastMessages.size(); i++) { long millis = getFinalizedTimestampMillis(lastMessages.get(i), committedMessages.get(i)); if (millis < minMillis) { minMillis = millis; } } if (minMillis == Long.MAX_VALUE) { LOG.error("No valid timestamps among messages: and {}", lastMessages, committedMessages); return null; } minMillis -= 3600L * 1000L; LOG.info("adjusted millis {}", minMillis); return generatePartitions(minMillis, mUsingHourly, mUsingMinutely); }</code><technical_language>this line is changed</technical_language>

Target:
public String[] getFinalizedUptoPartitions(List<Message> lastMessages, List<Message> committedMessages) throws Exception { if (lastMessages == null || committedMessages == null) { LOG.error("Either: and is null", lastMessages, committedMessages); return null; } assert lastMessages.size() == committedMessages.size(); long minMillis = Long.MAX_VALUE; for (int i = 0; i < lastMessages.size(); i++) { long millis = getFinalizedTimestampMillis(lastMessages.get(i), committedMessages.get(i)); if (millis < minMillis) { LOG.info("partition {}, time {}", i, millis); minMillis = millis; } } if (minMillis == Long.MAX_VALUE) { LOG.error("No valid timestamps among messages: and {}", lastMessages, committedMessages); return null; } minMillis -= mFinalizerDelaySeconds * 1000L; LOG.info("adjusted millis {}", minMillis); return generatePartitions(minMillis, mUsingHourly); }
Source:
<code><START> public void testTransformNoTimeout() throws Exception { <END> Exchange mockExchange = mock(Exchange.class); when(mockExchange.getIn()).thenReturn(message); when(mockExchange.getOut()).thenReturn(message); when(mockExchange.getOut()).thenReturn(message); when(mockExchange.getIn().getHeader("timeoutMilliseconds")).thenReturn(1000L); inputTransformerProducer.process(mockExchange); }</code><technical_language>This test needs a verification</technical_language>

Target:
public void testTransformNoTimeout() throws Exception { Exchange mockExchange = mock(Exchange.class); when(mockExchange.getIn()).thenReturn(message); when(mockExchange.getOut()).thenReturn(message); when(mockExchange.getOut()).thenReturn(message); when(mockExchange.getIn().getHeader("timeoutMilliseconds")).thenReturn(1000L); inputTransformerProducer.process(mockExchange); verify(message).setBody(any(Metacard.class)); }
Source:
<code>public AttributeDefinition getAttributeDefinition() { AttributeDefinition attr = new AttributeDefinition(); attr.setNamespace(AttributesManager.NS_USER_ATTR_VIRT); attr.setFriendlyName("loa"); attr.setDisplayName("Level of assurance"); <START> attr.setType(Integer.class.getName()); <END> attr.setDescription("The highest value of LoA from all user's userExtSources."); return attr; }</code><technical_language>historically "String" type for LoA, in production DBs. Please fix type String in modules (user|member:virt:loa). Thank you</technical_language>

Target:
public AttributeDefinition getAttributeDefinition() { AttributeDefinition attr = new AttributeDefinition(); attr.setNamespace(AttributesManager.NS_USER_ATTR_VIRT); attr.setFriendlyName("loa"); attr.setDisplayName("Level of assurance"); attr.setType(String.class.getName()); attr.setDescription("The highest value of LoA from all user's userExtSources."); return attr; }
Source:
<code>public static IChatComponent newChatWithLinks(String string) { final Pattern pattern = Pattern.compile("((?:(?:https?)://)?(?:[-\\w_\\.]{2,}\\.[a-z]{2,4}.*?(?=[\\.\\?!,;:]?(?:[\u00A7 \\n]|$))))", Pattern.CASE_INSENSITIVE); IChatComponent ichat = new ChatComponentText(""); String[] array = string.split(" "); for (int i = 0; i < array.length; i++) { IChatComponent link = new ChatComponentText(array[i]); if (pattern.matcher(array[i]).matches()) { String url = array[i].toLowerCase(); if (!url.startsWith("http://") && !url.startsWith("https://")) { url = "http://" + url; } ClickEvent click = new ClickEvent(ClickEvent.Action.OPEN_URL, url); <START> ichat.getChatStyle().setChatClickEvent(click); <END> } ichat.appendSibling(link); } return ichat; }</code><technical_language>this applied link, instead of ichat</technical_language>

Target:
public static IChatComponent newChatWithLinks(String string) { final Pattern pattern = Pattern.compile("((?:(?:https?)://)?(?:[-\\w_\\.]{2,}\\.[a-z]{2,4}.*?(?=[\\.\\?!,;:]?(?:[\u00A7 \\n]|$))))", Pattern.CASE_INSENSITIVE); IChatComponent ichat = new ChatComponentText(""); String[] array = string.split(" "); for (int i = 0; i < array.length; i++) { IChatComponent link = new ChatComponentText(array[i]); if (pattern.matcher(array[i]).matches()) { String url = array[i].toLowerCase(); if (!url.startsWith("http://") && !url.startsWith("https://")) { url = "http://" + url; } ClickEvent click = new ClickEvent(ClickEvent.Action.OPEN_URL, url); link.getChatStyle().setChatClickEvent(click); } ichat.appendSibling(link); } return ichat; }
Source:
<code>public CloseableIterator<InputRow> read() throws IOException { return new CloseableIterator<InputRow>() { final Firehose firehose = firehoseFactory.connect(inputRowParser, temporaryDirectory); @Override public boolean hasNext() { try { return firehose.hasMore(); } catch (IOException e) { <START> throw new RuntimeException(e); <END> } } @Override public InputRow next() { try { return firehose.nextRow(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void close() throws IOException { firehose.close(); } }; }</code><technical_language>UncheckedIOException instead</technical_language>

Target:
public CloseableIterator<InputRow> read() throws IOException { return new CloseableIterator<InputRow>() { final Firehose firehose = firehoseFactory.connect(inputRowParser, temporaryDirectory); @Override public boolean hasNext() { try { return firehose.hasMore(); } catch (IOException e) { throw new UncheckedIOException(e); } } @Override public InputRow next() { try { return firehose.nextRow(); } catch (IOException e) { throw new UncheckedIOException(e); } } @Override public void close() throws IOException { firehose.close(); } }; }
Source:
<code>public CourseComponent(BlockModel blockModel, CourseComponent parent){ <START> this(blockModel, parent, false); <END> }</code><technical_language>Do need a default case? force people explicit</technical_language>

Target:
public CourseComponent(BlockModel blockModel, CourseComponent parent){ this.id = blockModel.id; this.type = blockModel.type; this.name = blockModel.displayName; this.graded = blockModel.graded; this.blockUrl = blockModel.blockUrl; this.webUrl = blockModel.webUrl; this.responsiveUI = blockModel.responsiveUI; this.format = blockModel.format; this.blockCount = blockModel.blockCount == null ? new BlockCount() : blockModel.blockCount; this.parent = parent; if ( parent == null){ this.root = this; } else { parent.getChildren().add(this); this.root = (CourseComponent)parent.getRoot(); } }
Source:
<code>private static boolean loadXmlFile(File file, boolean addFile) { IStatus status = XmlUtils.xmlValidate(file); if (status.isOK()) { deleteSupplementaryFile(file.getName()); <START> if (addFile) { status = XmlUtils.addXmlFile(file); } <END> if (status.isOK()) { File xmlFile = XmlUtils.getXmlFilesPath().addTrailingSeparator().append(file.getName()).toFile(); XmlUtils.preloadXmlAnalysesOutput(xmlFile); XmlAnalysisModuleSource.notifyModuleChange(); refreshProject(); return true; } Activator.logError(Messages.ManageXMLAnalysisDialog_ImportFileFailed); TraceUtils.displayErrorMsg(Messages.ManageXMLAnalysisDialog_ImportFileFailed, status.getMessage()); } else { Activator.logError(Messages.ManageXMLAnalysisDialog_ImportFileFailed); TraceUtils.displayErrorMsg(Messages.ManageXMLAnalysisDialog_ImportFileFailed, status.getMessage()); } return false; }</code><technical_language>add else for XmlUtils.updateXmlFile(file); for file edits. a hunch this useful soon for else, module pre-compilation. need for line get file path</technical_language>

Target:
private static boolean loadXmlFile(File file, boolean addFile) { IStatus status = XmlUtils.xmlValidate(file); if (status.isOK()) { deleteSupplementaryFile(file.getName()); if (addFile) { status = XmlUtils.addXmlFile(file); } else { XmlUtils.updateXmlFile(file); } if (status.isOK()) { XmlAnalysisModuleSource.notifyModuleChange(); refreshProject(); return true; } Activator.logError(Messages.ManageXMLAnalysisDialog_ImportFileFailed); TraceUtils.displayErrorMsg(Messages.ManageXMLAnalysisDialog_ImportFileFailed, status.getMessage()); } else { Activator.logError(Messages.ManageXMLAnalysisDialog_ImportFileFailed); TraceUtils.displayErrorMsg(Messages.ManageXMLAnalysisDialog_ImportFileFailed, status.getMessage()); } return false; }
Source:
<code>public void dispose() { for (String fboName : fboNames) { <START> frameBuffersManager.removeUsage(fboName); END> } }</code><technical_language>A typical name for method is release (opposed acquire)</technical_language>

Target:
public void dispose() { for (Map.Entry<ResourceUrn, BaseFBOsManager> entry : fboUsages.entrySet()) { ResourceUrn fboName = entry.getKey(); BaseFBOsManager baseFBOsManager = entry.getValue(); baseFBOsManager.release(fboName); } fboUsages.clear(); }