auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static Object getPythonProxy(String commandPart, Gateway gateway) { String proxyString = commandPart.substring(1, commandPart.length()); String[] parts = proxyString.split(";"); int length = parts.length; Class<?>[] interfaces = new Class<?>[length - 1]; if (length < 2) { throw new Py4JException("Invalid Python Proxy."); } ClassLoadingStrategy classLoadingStrategy = gateway.getClassLoadingStrategy(); if (classLoadingStrategy == null) classLoadingStrategy = ReflectionUtil.getClassLoadingStrategy(); <START> if (classLoadingStrategy == null) <END> classLoadingStrategy = new CurrentThreadClassLoadingStrategy(); for (int i = 1; i < length; i++) { try { interfaces[i - 1] = classLoadingStrategy.classForName(parts[i]); if (!interfaces[i - 1].isInterface()) { throw new Py4JException( "This class " + parts[i] + " is not an interface and cannot be used as a Python Proxy."); } } catch (ClassNotFoundException e) { throw new Py4JException("Invalid interface name: " + parts[i]); } } return gateway.createProxy(ReflectionUtil.getClassLoader(), interfaces, parts[0]); }</code><technical_language>I remove this: default is a class loading strategy. If want prevent a user error (setting class loading strategy Null, validate parameter in ReflectionUtil.setClassLoadingStrategy instead</technical_language>

Target:
public static Object getPythonProxy(String commandPart, Gateway gateway) { String proxyString = commandPart.substring(1, commandPart.length()); String[] parts = proxyString.split(";"); int length = parts.length; Class<?>[] interfaces = new Class<?>[length - 1]; if (length < 2) { throw new Py4JException("Invalid Python Proxy."); } for (int i = 1; i < length; i++) { try { interfaces[i - 1] = ReflectionUtil.classForName(parts[i]); if (!interfaces[i - 1].isInterface()) { throw new Py4JException( "This class " + parts[i] + " is not an interface and cannot be used as a Python Proxy."); } } catch (ClassNotFoundException e) { throw new Py4JException("Invalid interface name: " + parts[i]); } } return gateway.createProxy(ReflectionUtil.getClassLoader(), interfaces, parts[0]); }
Source:
<code>public void testToStringOfTagClass() { final SuppressionCommentFilter filter1 = new SuppressionCommentFilter(); final Object tag1 = getTagsAfterExecution(filter1, "filename", " <START> assertEquals("Invalid toString result", <END> "Tag[text='CHECKSTYLE:OFF', line=1, column=0, type=OFF," + " tagCheckRegexp=.*, tagMessageRegexp=null]", tag1.toString()); final SuppressionCommentFilter filter2 = new SuppressionCommentFilter(); filter2.setMessageFormat(".*"); final Object tag2 = getTagsAfterExecution(filter2, "filename", " assertEquals("Invalid toString result", "Tag[text='CHECKSTYLE:ON', line=1, column=0, type=ON," + " tagCheckRegexp=.*, tagMessageRegexp=.*]", tag2.toString()); }</code><technical_language>this test case split two</technical_language>

Target:
public void testToStringOfTagClass() { final Object tag = getTagsAfterExecutionOnDefaultFilter(" assertEquals("Invalid toString result", "Tag[text='CHECKSTYLE:OFF', line=1, column=0, type=OFF," + " tagCheckRegexp=.*, tagMessageRegexp=null]", tag.toString()); }
Source:
<code>public CopyImageToScreenNode(Context context) { super(context); WorldRenderer worldRenderer = context.get(WorldRenderer.class); requiresCondition(() -> worldRenderer.getCurrentRenderStage() == MONO || worldRenderer.getCurrentRenderStage() == LEFT_EYE); DisplayResolutionDependentFBOs displayResolutionDependentFBOs = context.get(DisplayResolutionDependentFBOs.class); <START> sceneFinalFbo = displayResolutionDependentFBOs.get(FINAL_BUFFER); <END> update(); displayResolutionDependentFBOs.subscribe(this); addDesiredStateChange(new EnableMaterial(DEFAULT_TEXTURED_MATERIAL)); addDesiredStateChange(new SetInputTextureFromFbo(0, sceneFinalFbo, ColorTexture, displayResolutionDependentFBOs, DEFAULT_TEXTURED_MATERIAL, "texture")); }</code><technical_language>Depending "scene" this correct. I personally do term "scene" in other parts of renderer 3d scene. If case inappropriate final buffer is end point of a series of 2d post-processing steps: 3d is involved time get fill pixels send HMD elsewhere. So, in other classes, call finalFbo finalImageFbo. change sceneOpaque opaqueFbo for example</technical_language>

Target:
public CopyImageToScreenNode(Context context) { super(context); WorldRenderer worldRenderer = context.get(WorldRenderer.class); requiresCondition(() -> worldRenderer.getCurrentRenderStage() == MONO || worldRenderer.getCurrentRenderStage() == LEFT_EYE); addDesiredStateChange(new EnableMaterial(DEFAULT_TEXTURED_MATERIAL_URN)); addDesiredStateChange(new SetInputTextureFromFbo(0, FINAL_BUFFER, ColorTexture, context.get(DisplayResolutionDependentFBOs.class), DEFAULT_TEXTURED_MATERIAL_URN, "texture")); }
Source:
<code>public Object[] getChildren(Object parentElement) { if (parentElement instanceof IFeatureModel) { IFeatureModel featureModel = (IFeatureModel) parentElement; String featureId = featureModel.getFeature().getId(); Object[] features = fInput.getFeaturesViewInput().getIncludingFeatures(featureId).toArray(); if (!fInput.getFeaturesViewInput().isIncludeProducts()) { return features; } <START> Object[] products = fInput.getFeaturesViewInput().getIncludingProducts(featureId).toArray(); <END> List<Object> all = new ArrayList<>(features.length + products.length); all.addAll(Arrays.asList(features)); all.addAll(Arrays.asList(products)); return all.toArray(); } return new Object[0]; }</code><technical_language>toArray is unnecessary</technical_language>

Target:
public Object[] getChildren(Object parentElement) { if (parentElement instanceof IFeatureModel) { IFeatureModel featureModel = (IFeatureModel) parentElement; String featureId = featureModel.getFeature().getId(); Collection<IFeatureModel> features = fInput.getFeaturesViewInput().getIncludingFeatures(featureId); if (!fInput.getFeaturesViewInput().isIncludeProducts()) { return features.toArray(); } Collection<IProductModel> products = fInput.getFeaturesViewInput().getIncludingProducts(featureId); List<Object> all = new ArrayList<>(features.size() + products.size()); all.addAll(features); all.addAll(products); return all.toArray(); } return new Object[0]; }
Source:
<code>protected ApplicationOptions getApplicationOptions(PortFinder portFinder) { return new DdfComponentOptions(portFinder) { @Override protected BundleOption getBundleOptions() { return super.getBundleOptions() .add("org.bouncycastle", "bcprov-jdk15on") .add("ddf.catalog.transformer", "catalog-transformer-attribute") <START> .add("org.codice.thirdparty", "jts") <END> .add("org.codice.thirdparty", "picocontainer") .add("ddf.catalog.core", "catalog-core-attachment"); } @Override protected FeatureOption getFeatureOptions() { final String[] springFeatures = { "spring-instrument", "spring-jms", "spring-test", "spring-web" }; final String[] cxfFeatures = {"cxf", "cxf-commands"}; final String[] utilitiesFeatures = {"action-core-impl"}; final String[] kernelFeatures = {"apache-commons"}; return super.getFeatureOptions() .addFeatures("org.apache.karaf.features", "spring", springFeatures) .addFeatures("org.apache.cxf.karaf", "apache-cxf", cxfFeatures) .addFeatures("ddf.features", "utilities", utilitiesFeatures) .addFeatures("ddf.features", "kernel", kernelFeatures) .addFeatureFrom("ddf.thirdparty", "rest-assured", "feature", "rest-assured") .addFeatureFrom( "ddf.platform.util", "util-uuidgenerator-api", "feature", "uuidgenerator-api") .addFeatureFrom("ddf.mime.core", "mime-core-api", "feature", "mime-core-api-only") .addFeatureFrom( "ddf.catalog.core", "catalog-core-api", "feature", "catalog-core-api-only"); } }; }</code><technical_language>Do needed? worries a tests need include bundles (especially picocontainer) able run</technical_language>

Target:
protected ApplicationOptions getApplicationOptions(PortFinder portFinder) { return new DdfComponentOptions(portFinder) { @Override protected BundleOption getBundleOptions() { return super.getBundleOptions() .add("org.bouncycastle", "bcprov-jdk15on") .add("ddf.catalog.transformer", "catalog-transformer-attribute") .add("ddf.catalog.core", "catalog-core-attachment"); } @Override protected FeatureOption getFeatureOptions() { final String[] springFeatures = { "spring-instrument", "spring-jms", "spring-test", "spring-web" }; final String[] cxfFeatures = {"cxf", "cxf-commands"}; final String[] utilitiesFeatures = {"action-core-impl"}; final String[] kernelFeatures = {"apache-commons"}; return super.getFeatureOptions() .addFeatures("org.apache.karaf.features", "spring", springFeatures) .addFeatures("org.apache.cxf.karaf", "apache-cxf", cxfFeatures) .addFeatures("ddf.features", "utilities", utilitiesFeatures) .addFeatures("ddf.features", "kernel", kernelFeatures) .addFeatureFrom("ddf.thirdparty", "rest-assured", "feature", "rest-assured") .addFeatureFrom( "ddf.platform.util", "util-uuidgenerator-api", "feature", "uuidgenerator-api") .addFeatureFrom("ddf.mime.core", "mime-core-api", "feature", "mime-core-api-only") .addFeatureFrom( "ddf.catalog.core", "catalog-core-api", "feature", "catalog-core-api-only"); } }; }
Source:
<code>public void put(final Violation violation) { <START> log.info("PUT VIOLATION INTO EVENTBUS"); <END> eventBus.notify(DEFAULT_VIOLATIONS_TOPIC, Event.wrap(violation)); log.info("VIOLATION IN EVENTBUS"); }</code><technical_language>leg level debug here, avoid spamming logs</technical_language>

Target:
public void put(final Violation violation) { log.debug("PUT VIOLATION INTO EVENTBUS"); eventBus.notify(DEFAULT_VIOLATIONS_TOPIC, Event.wrap(violation)); log.debug("VIOLATION IN EVENTBUS"); }
Source:
<code><START> public static AbstractBAMFileIndex openIndex(SeekableStream stream, SAMSequenceDictionary dictionary) { <END> return new CachingBAMFileIndexOptimized(stream, dictionary); }</code><technical_language>this is unused, deleted</technical_language>

Target:
public static AbstractBAMFileIndex openIndex(SeekableStream stream, SAMSequenceDictionary dictionary) { return new CachingBamFileIndexOptimizedForMerging(stream, dictionary); }
Source:
<code>private DefaultBHttpClientConnection getConnection() { if (conn != null) { return conn; <START> } <END> File socketFile = new File(socketPath); AFUNIXSocket socket; try { socket = AFUNIXSocket.newInstance(); socket.connect(new AFUNIXSocketAddress(socketFile)); conn = new DefaultBHttpClientConnection(CLIENT_BUFFER_SIZE); conn.bind(socket); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } return conn; }</code><technical_language>if connection exist is is open? For example, if a client instance, daemon closed connection. future requests fail. Handing persistent connection is easy. close if a request response partly received. connecting local unix socket is fast, typically send request client, easier create a connection request instead of keeping open connection in client</technical_language>

Target:
private DefaultBHttpClientConnection getConnection() { DefaultBHttpClientConnection conn; File socketFile = new File(socketPath); AFUNIXSocket socket; try { socket = AFUNIXSocket.newInstance(); socket.connect(new AFUNIXSocketAddress(socketFile)); conn = new DefaultBHttpClientConnection(CLIENT_BUFFER_SIZE); conn.bind(socket); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } return conn; }
Source:
<code>public void start() { exec.submit( () -> { while (!Thread.interrupted()) { try { LOG.debug(callerName + ":Waiting for cache update notification"); Pair<String, byte[]> update = updateQueue.take(); String authorizer = update.lhs; byte[] serializedMap = update.rhs; <START> BasicAuthDBConfig dbConfig = itemConfigMap == null ? itemConfig : itemConfigMap.get(update.lhs); <END> if (!dbConfig.isEnableCacheNotifications()) { continue; } LOG.debug(callerName + ":Sending cache update notifications"); List<ListenableFuture<StatusResponseHolder>> futures; if (authorizer != null) { futures = sendUpdate(authorizer, serializedMap); } else { futures = sendUpdate(serializedMap); } try { List<StatusResponseHolder> responses = Futures.allAsList(futures) .get( dbConfig.getCacheNotificationTimeout(), TimeUnit.MILLISECONDS ); for (StatusResponseHolder response : responses) { LOG.debug(callerName + ":Got status: " + response.getStatus()); } } catch (Exception e) { LOG.makeAlert(e, callerName + ":Failed to get response for cache notification.").emit(); } LOG.debug(callerName + ":Received responses for cache update notifications."); } catch (Throwable t) { LOG.makeAlert(t, callerName + ":Error occured while handling updates for cachedUserMaps.").emit(); } } } ); }</code><technical_language>This line reverted BasicAuthDBConfig authorizerConfig = itemConfigMap.get(update.lhs); constructor sets itemConfig is anymore</technical_language>

Target:
public void start() { exec.submit( () -> { while (!Thread.interrupted()) { try { LOG.debug(callerName + ":Waiting for cache update notification"); Pair<String, byte[]> update = updateQueue.take(); String authorizer = update.lhs; byte[] serializedMap = update.rhs; BasicAuthDBConfig authorizerConfig = itemConfigMap.get(update.lhs); if (!authorizerConfig.isEnableCacheNotifications()) { continue; } LOG.debug(callerName + ":Sending cache update notifications"); List<ListenableFuture<StatusResponseHolder>> futures = sendUpdate( authorizer, serializedMap ); try { List<StatusResponseHolder> responses = Futures.allAsList(futures) .get( authorizerConfig.getCacheNotificationTimeout(), TimeUnit.MILLISECONDS ); for (StatusResponseHolder response : responses) { LOG.debug(callerName + ":Got status: " + response.getStatus()); } } catch (Exception e) { LOG.makeAlert(e, callerName + ":Failed to get response for cache notification.").emit(); } LOG.debug(callerName + ":Received responses for cache update notifications."); } catch (Throwable t) { LOG.makeAlert(t, callerName + ":Error occured while handling updates for cachedUserMaps.").emit(); } } } ); }
Source:
<code>public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("Service names: \"").append(Arrays.asList(serviceNames)).append("\" "); builder.append("(class ").append(serviceClassName).append(')'); builder.append(" mode ").append(modeName); builder.append(" state ").append(stateName); if (! stateName.equals(substateName)) { builder.append(" (").append(substateName).append(')'); } if (parentNames != null) { <START> builder.append(" (parent names: ").append(Arrays.asList(parentNames)).append(')'); <END> } final String[] dependencies = this.dependencies; final int dependenciesLength = dependencies.length; if (dependenciesLength > 0) { builder.append(" (dependencies: "); for (int i = 0; i < dependenciesLength; i++) { builder.append(dependencies[i]); if (i < dependenciesLength - 1) { builder.append(", "); } } builder.append(")"); } String exception = this.exception; if (exception != null && ! exception.isEmpty()) { builder.append(" (failure cause: ").append(exception).append(')'); } if (dependencyFailed) { builder.append(" (has failed dependency)"); } if (dependencyUnavailable) { builder.append(" (has unavailable dependency)"); } return builder.toString(); }</code><technical_language>This is another example a name for controller useful</technical_language>

Target:
public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("Service \"").append(serviceName).append("\" "); final String[] aliases = this.aliases; if (aliases.length > 0) { builder.append("(aliases: "); for (int i = 0; i < aliases.length; i++) { builder.append(aliases[i]); if (i < aliases.length - 1) { builder.append(", "); } } builder.append(") "); } builder.append("(class ").append(serviceClassName).append(')'); builder.append(" mode ").append(modeName); builder.append(" state ").append(stateName); if (! stateName.equals(substateName)) { builder.append(" (").append(substateName).append(')'); } String parentName = this.parentName; if (parentName != null) { builder.append(" (parent: ").append(parentName).append(')'); } final String[] dependencies = this.dependencies; final int dependenciesLength = dependencies.length; if (dependenciesLength > 0) { builder.append(" (dependencies: "); for (int i = 0; i < dependenciesLength; i++) { builder.append(dependencies[i]); if (i < dependenciesLength - 1) { builder.append(", "); } } builder.append(")"); } String exception = this.exception; if (exception != null && ! exception.isEmpty()) { builder.append(" (failure cause: ").append(exception).append(')'); } if (dependencyFailed) { builder.append(" (has failed dependency)"); } if (dependencyUnavailable) { builder.append(" (has unavailable dependency)"); } return builder.toString(); }
Source:
<code>public void onOpen(final OpenEvent<DisclosurePanel> event) { if (infoTable == null) { AccountDiffPreference diffPrefs; if (diffBaseId == null) { diffPrefs = null; } else { <START> diffPrefs = (new ListenableAccountDiffPreference()).get(); <END> } Util.DETAIL_SVC.patchSetDetail(patchSet.getId(), diffBaseId, diffPrefs, new GerritCallback<PatchSetDetail>() { public void onSuccess(final PatchSetDetail result) { ensureLoaded(result); patchTable.setRegisterKeys(true); } }); } }</code><technical_language>Style-nit: Parens necessary new operator</technical_language>

Target:
public void onOpen(final OpenEvent<DisclosurePanel> event) { if (infoTable == null) { AccountDiffPreference diffPrefs; if (diffBaseId == null) { diffPrefs = null; } else { diffPrefs = new ListenableAccountDiffPreference().get(); } Util.DETAIL_SVC.patchSetDetail(patchSet.getId(), diffBaseId, diffPrefs, new GerritCallback<PatchSetDetail>() { public void onSuccess(final PatchSetDetail result) { ensureLoaded(result); patchTable.setRegisterKeys(true); } }); } }
Source:
<code>public String getIndent() { StringBuilder indentString = new StringBuilder(); for(int i=0; i<indent; i++){ <START> indentString.append(" "); <END> } return indentString.toString(); }</code><technical_language>' ' enough, need for a String object</technical_language>

Target:
public String getIndent() { StringBuilder indentString = new StringBuilder(); for (int i = 0; i < indentSize; i++) { indentString.append(' '); } return indentString.toString(); }
Source:
<code>private JLabel getAddedCountNameLabel() { if (addedCountNameLabel == null) { <START> addedCountNameLabel = new javax.swing.JLabel(); <END> addedCountNameLabel.setText(Constant.messages.getString("spider.toolbar.added.label")); } return addedCountNameLabel; }</code><technical_language>constructor need fully qualified</technical_language>

Target:
private JLabel getAddedCountNameLabel() { if (addedCountNameLabel == null) { addedCountNameLabel = new JLabel(); addedCountNameLabel.setText(Constant.messages.getString("spider.toolbar.added.label")); } return addedCountNameLabel; }
Source:
<code><START> public static Arg<Integer> columnCount(ColumnSelection columnSelection) { <END> return getArg("columnCount", Iterables.size(columnSelection.getSelectedColumns()), true); }</code><technical_language>this method do logic for "all" a count? a function called allColumns returns a count</technical_language>

Target:
public static Arg<?> columnCount(ColumnSelection columnSelection) { return getArg("columnCount", columnSelection.allColumnsSelected() ? "all" : Iterables.size(columnSelection.getSelectedColumns()), true); }
Source:
<code>public RetryableFeignLoadBalancer(ILoadBalancer lb, IClientConfig clientConfig, ServerIntrospector serverIntrospector, LoadBalancedRetryPolicyFactory loadBalancedRetryPolicyFactory, LoadBalancedBackOffPolicyFactory loadBalancedBackOffPolicyFactory, <START> LoadBalancedRetryListenerFactory loadBalancedRetryListenerFactory) { <END> super(lb, clientConfig, serverIntrospector); this.loadBalancedRetryPolicyFactory = loadBalancedRetryPolicyFactory; this.setRetryHandler(new DefaultLoadBalancerRetryHandler(clientConfig)); this.loadBalancedBackOffPolicyFactory = loadBalancedBackOffPolicyFactory == null ? new LoadBalancedBackOffPolicyFactory.NoBackOffPolicyFactory() : loadBalancedBackOffPolicyFactory; this.loadBalancedRetryListenerFactory = loadBalancedRetryListenerFactory == null ? new LoadBalancedRetryListenerFactory.NoRetryListenerFactory() : loadBalancedRetryListenerFactory; }</code><technical_language>Add a new constructor</technical_language>

Target:
public RetryableFeignLoadBalancer(ILoadBalancer lb, IClientConfig clientConfig, ServerIntrospector serverIntrospector, LoadBalancedRetryPolicyFactory loadBalancedRetryPolicyFactory, LoadBalancedBackOffPolicyFactory loadBalancedBackOffPolicyFactory, LoadBalancedRetryListenerFactory loadBalancedRetryListenerFactory) { super(lb, clientConfig, serverIntrospector); this.loadBalancedRetryPolicyFactory = loadBalancedRetryPolicyFactory; this.setRetryHandler(new DefaultLoadBalancerRetryHandler(clientConfig)); this.loadBalancedBackOffPolicyFactory = loadBalancedBackOffPolicyFactory == null ? new LoadBalancedBackOffPolicyFactory.NoBackOffPolicyFactory() : loadBalancedBackOffPolicyFactory; this.loadBalancedRetryListenerFactory = loadBalancedRetryListenerFactory == null ? new LoadBalancedRetryListenerFactory.DefaultRetryListenerFactory() : loadBalancedRetryListenerFactory; }
Source:
<code>public void shutdownRequested(IRecordProcessorCheckpointer checkpointer) { LOG.info("Shutdown is requested."); if (!initialized) { LOG.info("Record processor was not initialized so no need to initiate a final checkpoint."); return; } try { LOG.info("Requesting a checkpoint on shutdown notification."); <START> checkpointer.checkpoint(); <END> } catch (InvalidStateException e) { LOG.error("Checkpoint triggered during shutdown encountered InvalidStateException: " + e.toString()); } catch (ShutdownException e) { LOG.error("Checkpoint triggered during shutdown encountered ShutdownException: " + e.toString()); } }</code><technical_language>checkpoint is determined application, checkpointing safe. This a similar dispatch mechanism processRecords uses. shortcut dispatch this time, checkpoint a configuration flag. [dispatch code for processRecords](<LINK_0> for reference</technical_language>

Target:
public void shutdownRequested(IRecordProcessorCheckpointer checkpointer) { LOG.info("Shutdown is requested."); if (!initialized) { LOG.info("Record processor was not initialized so no need to initiate a final checkpoint."); return; } LOG.info("Requesting a checkpoint on shutdown notification."); if (!protocol.shutdownRequested(checkpointer)) { LOG.error("Child process failed to complete shutdown notification."); } }
Source:
<code>public boolean receive(InputStream input) throws MessageNotCompleteException, IOException { if (this.fileBytesLeft <= 0 && input.available() >= SIZEOF_INTEGER) { this.fileBytesLeft = readInteger(input); openRandomInFile(); } int read; while ((read = input.read(byteBuffer)) > 0) { fileBuffer.write(byteBuffer, 0, read); this.fileBytesLeft -= read; } boolean readComplete = isInFileComplete(); <START> if (isBufferFilled() || readComplete) { <END> flushBuffer(); } if (readComplete) { closeInFile(); } return readComplete; }</code><technical_language>do get in a situation buffer is filled read is complete</technical_language>

Target:
public boolean receive(InputStream input) throws MessageNotCompleteException, IOException { if (this.fileBytesLeft <= 0 && input.available() >= SIZEOF_INTEGER) { this.fileBytesLeft = readInteger(input); openRandomInFile(); } int read; while ((read = input.read(byteBuffer)) > 0) { fileBuffer.write(byteBuffer, 0, read); this.fileBytesLeft -= read; } boolean readComplete = isFileComplete(); if (isBufferFilled() || readComplete) { flushBuffer(); } if (readComplete) { closeInFile(); } return readComplete; }
Source:
<code>public void testSSLConnect() throws IOException { String connectionId = selector.connect(new InetSocketAddress("localhost", server.port), BUFFER_SIZE, BUFFER_SIZE, PortType.SSL); <START> Assert.assertFalse("Channel should not be ready by now (until handshake completes)", <END> selector.isChannelReady(connectionId)); while (!selector.connected().contains(connectionId)) { selector.poll(10000L); } Assert.assertTrue("Channel should have been ready by now ", selector.isChannelReady(connectionId)); }</code><technical_language>Is a handshake completes fast ready connectionId is added connected</technical_language>

Target:
public void testSSLConnect() throws IOException { String connectionId = selector.connect(new InetSocketAddress("localhost", server.port), BUFFER_SIZE, BUFFER_SIZE, PortType.SSL); while (!selector.connected().contains(connectionId)) { selector.poll(10000L); } Assert.assertTrue("Channel should have been ready by now ", selector.isChannelReady(connectionId)); }
Source:
<code>static byte[] encodeKey(String key, Charset charset) { <START> checkNotNull(key, "key"); <END> byte[] keyBytes = key.getBytes(charset); int length = keyBytes.length; if (length > 250) { throw new IllegalArgumentException("Key is too long: " + key); } if (length <= 0) { throw new IllegalArgumentException("Key is empty"); } for (int i = 0; i < length; i++) { final byte c = keyBytes[i]; if (c >= 0 && c <= 32) { throw new IllegalArgumentException("Invalid key: " + key); } } return keyBytes; }</code><technical_language>Check charset</technical_language>

Target:
static byte[] encodeKey(String key, Charset charset) { checkNotNull(key, "key"); checkNotNull(charset, "charset"); byte[] keyBytes = key.getBytes(charset); int length = keyBytes.length; if (length > 250) { throw new IllegalArgumentException("Key is too long: " + key); } if (length <= 0) { throw new IllegalArgumentException("Key is empty"); } for (int i = 0; i < length; i++) { final byte c = keyBytes[i]; if (c >= 0 && c <= 32) { throw new IllegalArgumentException("Invalid key: " + key); } } return keyBytes; }
Source:
<code>public Request authenticate(Route route, Response response) throws IOException { if(unauthorizedForCluster(response)){ String requestUrl = response.request().url().toString(); Request authRequest = new Request.Builder() <START> .addHeader("X-CSRF-Token", "1") <END> .url(route.address().url().toString() + "oauth/authorize?response_type=token&client_id=openshift-challenging-client") .build(); try ( Response authResponse = tryAuth(authRequest)){ if(authResponse.isSuccessful()) { String token = captureToken(authResponse); return response.request().newBuilder() .header(IHttpConstants.PROPERTY_AUTHORIZATION, String.format("%s %s", IHttpConstants.AUTHORIZATION_BEARER, token)) .build(); } } throw new UnauthorizedException(captureAuthDetails(requestUrl), ResponseCodeInterceptor.getStatus(response.body().string())); } return null; }</code><technical_language>want extract header keys values a constants class for improved readability reusability</technical_language>

Target:
public Request authenticate(Route route, Response response) throws IOException { if(unauthorizedForCluster(response)){ String requestUrl = response.request().url().toString(); Request authRequest = new Request.Builder() .addHeader(CSRF_TOKEN, "1") .url(route.address().url().toString() + "oauth/authorize?response_type=token&client_id=openshift-challenging-client") .build(); try ( Response authResponse = tryAuth(authRequest)){ if(authResponse.isSuccessful()) { String token = extractAndSetAuthContextToken(authResponse); return response.request().newBuilder() .header(IHttpConstants.PROPERTY_AUTHORIZATION, String.format("%s %s", IHttpConstants.AUTHORIZATION_BEARER, token)) .build(); } } throw new UnauthorizedException(captureAuthDetails(requestUrl), ResponseCodeInterceptor.getStatus(response.body().string())); } return null; }
Source:
<code>protected void removeProxies(CoreSession session, List<String> ids) { Set<DocumentRef> proxies = new HashSet<>(); String query = String.format(PROXY_QUERY_TEMPLATE, String.join("', '", ids)); try (IterableQueryResult res = session.queryAndFetch(query, NXQL.NXQL)) { for (Map<String, Serializable> map : res) { proxies.add(new IdRef((String) map.get(NXQL.ECM_UUID))); } } session.removeDocuments(proxies.toArray(new DocumentRef[0])); try { session.save(); } catch (PropertyException e) { <START> getLog().warn("Cannot save session", e); <END> } }</code><technical_language>supposed remove getLog() method</technical_language>

Target:
protected void removeProxies(CoreSession session, List<String> ids) { Set<DocumentRef> proxies = new HashSet<>(); String query = String.format(PROXY_QUERY_TEMPLATE, String.join("', '", ids)); try (IterableQueryResult res = session.queryAndFetch(query, NXQL.NXQL)) { for (Map<String, Serializable> map : res) { proxies.add(new IdRef((String) map.get(NXQL.ECM_UUID))); } } session.removeDocuments(proxies.toArray(new DocumentRef[0])); try { session.save(); } catch (PropertyException e) { log.warn("Cannot save session", e); } }
Source:
<code>private String[] breakUpField(String input) { if(input == null ) {return new String[0];} else { <START> return input.split(" "); <END> } }</code><technical_language>\s+</technical_language>

Target:
private String[] breakUpField(String input) { if(input == null ) {return new String[0];} else { return input.split("\\s+"); } }
Source:
<code>protected void checkArgType(ObjectInspector oi, int i, PrimitiveCategory type) throws UDFArgumentTypeException { <START> PrimitiveCategory primitiveCategory = ((PrimitiveObjectInspector) oi).getPrimitiveCategory(); <END> if (primitiveCategory != type) { throw new UDFArgumentTypeException(0, "A " + type.getClass().getSimpleName() + " argument was expected for " + getFuncName() + " but an argument of type " + oi.getTypeName() + " was given."); } }</code><technical_language>I safer call checkArgPrimitive(io, i) casting. result in weird ClassCastException if called primitive types</technical_language>

Target:
protected void checkArgType(ObjectInspector oi, int i, PrimitiveCategory type) throws UDFArgumentTypeException { checkArgPrimitive(oi, i); PrimitiveCategory primitiveCategory = ((PrimitiveObjectInspector) oi).getPrimitiveCategory(); if (primitiveCategory != type) { throw new UDFArgumentTypeException(0, "A " + type.getClass().getSimpleName() + " argument was expected for " + getFuncName() + " but an argument of type " + oi.getTypeName() + " was given."); } }
Source:
<code>public RunResult runTests(Path path) { buildAntProject(path); List<String> runnerArgs = buildTestRunnerArgs(path); startProcess(runnerArgs); try { <START> FileUtils.deleteDirectory(new File(path.toString() + File.separatorChar + "build")); <END> } catch (IOException e) { throw Throwables.propagate(e); } File resultFile = new File(path.toString() + resultsFile); RunResult result = resultParser.parseTestResult(resultFile); resultFile.delete(); return result; }</code><technical_language>Why</technical_language>

Target:
public RunResult runTests(Path path) { if (!buildAntProject(path)) { return buildRunResult; } List<String> runnerArgs = buildTestRunnerArgs(path); startProcess(runnerArgs); File resultFile = new File(path.toString() + resultsFile); RunResult result = resultParser.parseTestResult(resultFile); resultFile.delete(); return result; }
Source:
<code>protected DocumentModel getClientModel(String clientId) { DirectoryService service = Framework.getService(DirectoryService.class); return Framework.doPrivileged(() -> { try (Session session = service.open(OAUTH2CLIENT_DIRECTORY_NAME)) { Map<String, Serializable> filter = new HashMap<>(); <START> filter.put("clientId", clientId); <END> DocumentModelList docs = session.query(filter); if (docs.size() > 0) { return docs.get(0); } } return null; }); }</code><technical_language>Collections.singletongMap(..., ...)</technical_language>

Target:
protected DocumentModel getClientModel(String clientId) { DirectoryService service = Framework.getService(DirectoryService.class); return Framework.doPrivileged(() -> { try (Session session = service.open(OAUTH2CLIENT_DIRECTORY_NAME)) { Map<String, Serializable> filter = Collections.singletonMap("clientId", clientId); DocumentModelList docs = session.query(filter); if (docs.size() > 0) { return docs.get(0); } } return null; }); }
Source:
<code>private void deleteTestFiles(@Nonnegative IDevice device, @Nonnull String uuid) throws RuntimeRunnerException { if (isVerbose) { System.out.println( "adb shell -s " + device.getSerialNumber() + " find data -name '*jack-tests-" + uuid + "*' -exec rm -rf +"); } try { device.executeShellCommand( <START> "find data -name '*jack-tests-" + uuid + "*' -exec rm -rf +", hostOutput); <END> } catch (TimeoutException | AdbCommandRejectedException | ShellCommandUnresponsiveException | IOException e) { throw new RuntimeRunnerException(e); } }</code><technical_language>nit: string, print is execute</technical_language>

Target:
private void deleteTestFiles(@Nonnegative IDevice device, @Nonnull String uuid) throws RuntimeRunnerException { String deleteCommand = "find data -name '*jack-tests-" + uuid + "*' -exec rm -rf +"; if (isVerbose) { System.out.println("adb -s " + device.getSerialNumber() + " shell " + deleteCommand); } try { device.executeShellCommand(deleteCommand, hostOutput); } catch (TimeoutException | AdbCommandRejectedException | ShellCommandUnresponsiveException | IOException e) { throw new RuntimeRunnerException(e); } }
Source:
<code>public static TypeName getParcelableType(Types types, TypeElement type) { TypeMirror typeMirror = type.asType(); while (typeMirror.getKind() != TypeKind.NONE) { TypeName typeName = TypeName.get(typeMirror); if (typeName instanceof ParameterizedTypeName) { typeName = ((ParameterizedTypeName) typeName).rawType; } if (typeName.isPrimitive() || VALID_TYPES.contains(typeName)) { return typeName; } List<? extends TypeMirror> interfaces = type.getInterfaces(); <START> if (!interfaces.isEmpty()) { <END> for (TypeMirror iface : interfaces) { TypeName ifaceName = TypeName.get(iface); if (VALID_TYPES.contains(ifaceName)) { return ifaceName; } } } type = (TypeElement) types.asElement(typeMirror); typeMirror = type.getSuperclass(); } return null; }</code><technical_language>need this check lets inline getInterfaces() call for</technical_language>

Target:
public static TypeName getParcelableType(Types types, TypeElement type) { TypeMirror typeMirror = type.asType(); while (typeMirror.getKind() != TypeKind.NONE) { TypeName typeName = TypeName.get(typeMirror); if (typeName instanceof ParameterizedTypeName) { typeName = ((ParameterizedTypeName) typeName).rawType; } if (typeName.isPrimitive() || VALID_TYPES.contains(typeName)) { return typeName; } for (TypeMirror iface : type.getInterfaces()) { TypeName ifaceName = TypeName.get(iface); if (VALID_TYPES.contains(ifaceName)) { return ifaceName; } } type = (TypeElement) types.asElement(typeMirror); typeMirror = type.getSuperclass(); } return null; }
Source:
<code>public MemberInfo(Address address, UUID uuid, Map<String, String> attributes, boolean liteMember, MemberVersion version, <START> boolean isAddressMapExists, Map<EndpointQualifier, Address> addressMap) { <END> this(address, uuid, attributes, liteMember, version, NA_MEMBER_LIST_JOIN_VERSION, addressMap); }</code><technical_language>isAddressMapExists is in this constructor. is this intentional? A false older server version. If need of this var, remove this constructor</technical_language>

Target:
public MemberInfo(Address address, UUID uuid, Map<String, String> attributes, boolean liteMember, MemberVersion version, boolean isAddressMapExists, Map<EndpointQualifier, Address> addressMap) { this(address, uuid, attributes, liteMember, version, NA_MEMBER_LIST_JOIN_VERSION, isAddressMapExists ? addressMap : emptyMap()); }
Source:
<code>public void fail(WebElementsCollection collection, List<WebElement> elements, Exception lastError, long timeoutMs) { if (elements == null || elements.isEmpty()) { ElementNotFound elementNotFound = new ElementNotFound(collection, expectedTexts, lastError); elementNotFound.timeoutMs = timeoutMs; throw elementNotFound; } <START> if (elements.size() != expectedTexts.size()) { <END> throw new TextsSizeMismatch(collection, ElementsCollection.texts(elements), expectedTexts, explanation, timeoutMs); } else { throw new TextsMismatch(collection, ElementsCollection.texts(elements), expectedTexts, explanation, timeoutMs); } }</code><technical_language>if { } else if { } else { } construction in this case. please leave condition verification in line</technical_language>

Target:
public void fail(WebElementsCollection collection, List<WebElement> elements, Exception lastError, long timeoutMs) { if (elements == null || elements.isEmpty()) { ElementNotFound elementNotFound = new ElementNotFound(collection, expectedTexts, lastError); elementNotFound.timeoutMs = timeoutMs; throw elementNotFound; } else if (elements.size() != expectedTexts.size()) { throw new TextsSizeMismatch(collection, ElementsCollection.texts(elements), expectedTexts, explanation, timeoutMs); } else { throw new TextsMismatch(collection, ElementsCollection.texts(elements), expectedTexts, explanation, timeoutMs); } }
Source:
<code>public abstract void importPemCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) throws IOException; void importPemCertificateRunner(Consumer<ImportCertificateOptions> testRunner) throws IOException { <START> byte[] certificateContent = readCertificate("certificate.pem"); <END> String certificateName = generateResourceId("importCertPem"); HashMap<String, String> tags = new HashMap<>(); tags.put("key", "val"); ImportCertificateOptions importCertificateOptions = new ImportCertificateOptions(certificateName, certificateContent) .setPolicy(new CertificatePolicy("Self", "CN=AzureSDK") .setContentType(CertificateContentType.PEM)) .setEnabled(true) .setTags(tags); testRunner.accept(importCertificateOptions); }</code><technical_language>file name changed. this intended</technical_language>

Target:
public abstract void importPemCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) throws IOException; void importPemCertificateRunner(Consumer<ImportCertificateOptions> testRunner) throws IOException { byte[] certificateContent = readCertificate("pemCert.pem"); String certificateName = generateResourceId("importCertPem"); HashMap<String, String> tags = new HashMap<>(); tags.put("key", "val"); ImportCertificateOptions importCertificateOptions = new ImportCertificateOptions(certificateName, certificateContent) .setPolicy(new CertificatePolicy("Self", "CN=AzureSDK") .setContentType(CertificateContentType.PEM)) .setEnabled(true) .setTags(tags); testRunner.accept(importCertificateOptions); }
Source:
<code>public CloudProvider createCloudProvider(String cloudProviderId, Configured configuration) { if (!GoogleCloudProvider.ID.equals(cloudProviderId)) { throw new NoSuchElementException("Cloud provider not found: " + cloudProviderId); } CredentialsProvider<GoogleCredentials> provider = new GoogleCredentialsProvider(); GoogleCredentials credentials = provider.createCredentials(configuration); if (credentials.getCompute() == null) { throw new IllegalArgumentException("Invalid cloud provider credentials"); } else { try { credentials.getCompute().regions().list(credentials.getProjectId()).execute(); } catch (IOException e) { <START> e.printStackTrace(); <END> throw new IllegalArgumentException("Invalid cloud provider credentials"); } } return new GoogleCloudProvider(credentials); }</code><technical_language>remove - external layer do proper logging</technical_language>

Target:
public CloudProvider createCloudProvider(String cloudProviderId, Configured configuration) { if (!GoogleCloudProvider.ID.equals(cloudProviderId)) { throw new IllegalArgumentException("Cloud provider not found: " + cloudProviderId); } CredentialsProvider<GoogleCredentials> provider = new GoogleCredentialsProvider(); GoogleCredentials credentials = provider.createCredentials(configuration); Compute compute = credentials.getCompute(); if (compute == null) { throw new IllegalArgumentException("Invalid cloud provider credentials."); } else { String projectId = credentials.getProjectId(); try { compute.regions().list(projectId).execute(); } catch (IOException e) { throw new IllegalArgumentException( "Invalid cloud provider credentials for project '" + projectId + "'.", e); } } return new GoogleCloudProvider(credentials); }
Source:
<code>public String toString() { <START> if (serialPortName!=null) <END> return "Device [id=" + deviceId + ", serialPort=" + serialPortName + "]"; else return "Device [id=" + deviceId + ", host=" + host + ", port=" + port + "]"; }</code><technical_language>curly braces, for one-line statements</technical_language>

Target:
public String toString() { if (serialPortName != null) { return "Device [id=" + deviceId + ", serialPort=" + serialPortName + "]"; } else { return "Device [id=" + deviceId + ", host=" + host + ", port=" + port + "]"; } }
Source:
<code>public static Set<MetaClass> getConfiguredNonBindableTypes() { <START> if (configuredNonBindableTypes == null) { <END> initEnvironmentConfig(); } return configuredNonBindableTypes; }</code><technical_language>In getConfiguredBindableTypes is a "refresh" case configuredBindableTypes loaded. This is important for making work properly refreshes of Super Dev Mode. In this case *might* avoiding this step explicitly non-bindable types generate anything, this tested</technical_language>

Target:
public static Set<MetaClass> getConfiguredNonBindableTypes() { if (configuredNonBindableTypes != null) { configuredNonBindableTypes = refreshConfiguredTypes(configuredNonBindableTypes); } else { initEnvironmentConfig(); } return configuredNonBindableTypes; }
Source:
<code>public void updateScores(HashMap<Integer, Double> scoreMap) { <START> for (GameObject go : gameObjects.values()) <END> { for (Integer iD : scoreMap.keySet()) { if (go.getId() == iD && go instanceof BoDCharacter) { BoDCharacter bodCharacter = (BoDCharacter)go; double score = scoreMap.get(iD); bodCharacter.addScore(score); } } } }</code><technical_language>remove this</technical_language>

Target:
public void updateScores(HashMap<Integer, Double> scoreMap) { for (Integer id : scoreMap.keySet()) { GameObject go = gameObjects.get(id); if (go != null) { BoDCharacter bodCharacter = (BoDCharacter)go; double score = scoreMap.get(id); bodCharacter.addScore(score); } } }
Source:
<code>private static File getDefaultFile() { <START> File netrc; <END> File home = new File(System.getProperty("user.home")); netrc = new File(home, ".netrc"); if (netrc.exists()) return netrc; netrc = new File(home, "_netrc"); if (netrc.exists()) return netrc; return null; }</code><technical_language>need declare this here, instead declare type in line 141</technical_language>

Target:
private static File getDefaultFile() { File home = new File(System.getProperty("user.home")); File netrc = new File(home, ".netrc"); if (netrc.exists()) return netrc; netrc = new File(home, "_netrc"); if (netrc.exists()) return netrc; return null; }
Source:
<code>public static void main(final String[] args) throws Exception { if (args.length == 6) { initializeAcl(args[0], args[1], args[2], args[3], args[4], args[5]); } else { System.out.println("usage: <ZK connect string> <ZK cluster ID> " + <START> "<master user> <master password> <agent user> <agent password>"); <END> } }</code><technical_language>a good citizen call System.exit :wink:</technical_language>

Target:
public static void main(final String[] args) throws Exception { if (args.length == 6) { initializeAcl(args[0], args[1], args[2], args[3], args[4], args[5]); } else { System.out.println("usage: <ZK connect string> <ZK cluster ID> " + "<master user> <master password> <agent user> <agent password>"); System.exit(-1); } }
Source:
<code>private void refreshInternal() { if (isIncludeSubPackages()) { <START> this.querySpecifications.addAll(QuerySpecificationRegistry.getInstance().getPackageSubTreeQueryGroup(this.packageName)); <END> } else { this.querySpecifications.addAll(QuerySpecificationRegistry.getInstance().getQueryGroup(this.packageName)); } }</code><technical_language>if this class internal reference for registry instead of referring central repository refresh method, loosen coupling query group registry (even if for single central registry instance is stored there)</technical_language>

Target:
private void refreshInternal() { if (isIncludeSubPackages()) { this.querySpecifications.addAll(registry.getPackageSubTreeQueryGroup(this.packageName)); } else { this.querySpecifications.addAll(registry.getQueryGroup(this.packageName)); } }
Source:
<code>private void readHeaderData() throws IOException { setFileVersion(parseInt()); skipString(); skipString(); skipString(); skipString(); skipString(); skipBoolean(); <START> if (getFileVersion() == 2) { <END> throw new IOException("Version 2 unsupported"); } manifestName = parseString(); }</code><technical_language>good version in a static variable</technical_language>

Target:
private void readHeaderData() throws IOException { setFileVersion(parseInt()); skipString(); skipString(); skipString(); skipString(); skipString(); skipBoolean(); if (getFileVersion() == INVALID_FILE_VERSION) { throw new IOException("Version '" + INVALID_FILE_VERSION + "' unsupported"); } manifestName = parseString(); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.entity_map_view); MapFragment mapFragment = (MapFragment) getFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); session = CommCareApplication._().getCurrentSession(); SessionDatum selectDatum = session.getNeededDatum(); Detail detail = session.getDetail(selectDatum.getShortDetail()); NodeEntityFactory factory = new NodeEntityFactory(detail, this.getEvaluationContext()); Vector<TreeReference> references = getEvaluationContext().expandReference( selectDatum.getNodeset()); entities = new Vector<>(); for(TreeReference ref : references) { entities.add(factory.getEntity(ref)); } int bogusAddresses = 0; entityLocations = new Vector<>(); for(Entity<TreeReference> entity : entities) { for(int i = 0 ; i < detail.getHeaderForms().length; ++i ){ if("address".equals(detail.getTemplateForms()[i])) { String address = entity.getFieldString(i).trim(); <START> if(address != null && !"".equals(address)) { <END> LatLng location = getLatLngFromAddress(address); if (location == null) { bogusAddresses++; } else { entityLocations.add(new Pair<>(entity, location)); } } } } } Log.d(TAG, "Loaded. " + entityLocations.size() +" addresses discovered, " + bogusAddresses + " could not be located"); }</code><technical_language>need check for null calling trim(), raise a null pointer exception null check reached. implementation of getFieldString, return a String instance, need check in general</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.entity_map_view); SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); Detail detail = session.getDetail(selectDatum.getShortDetail()); addEntityLocations(detail); Log.d(TAG, "Loaded. " + entityLocations.size() + " addresses discovered, " + ( detail.getHeaderForms().length - entityLocations.size()) + " could not be located"); }
Source:
<code>protected boolean eventTriggersAjax(WebElement element, String attribute) { String eventHandler = element.getAttribute(attribute); <START> return eventHandler != null && eventHandler.contains("RichFaces.ajax("); <END> }</code><technical_language>I do this if attribute start call Ajax call executed (the if causing Ajax call sent). in case waiting for completion of a call is end break test. Is happen, unfounded fear</technical_language>

Target:
protected boolean eventTriggersAjax(WebElement element, String attribute) { String eventHandler = element.getAttribute(attribute); return eventHandler != null && (ajaxStartWithOnly? eventHandler.startsWith(RICH_FACES_AJAX_CALL) : eventHandler.contains(RICH_FACES_AJAX_CALL)); }