auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static Schema.Type stringToFieldType(String typeString) { if (typeString == null || typeString.isEmpty()) { return null; } String type = typeString.toLowerCase(Locale.ENGLISH); <START> if (type.equals("long")) { <END> return Schema.Type.LONG; } else if (type.equals("double")) { return Schema.Type.DOUBLE; } else if (type.equals("float")) { return Schema.Type.FLOAT; } else if (type.equals("string")) { return Schema.Type.STRING; } return null; }</code><technical_language>This include int, boolean, other types supported in CSV conversions</technical_language>

Target:
private static Schema.Type stringToFieldType(String typeString) { if (typeString == null || typeString.isEmpty()) { return null; } String type = typeString.toLowerCase(Locale.ENGLISH); if (type.equals("long")) { return Schema.Type.LONG; } else if (type.equals("int")) { return Schema.Type.INT; } else if (type.equals("double")) { return Schema.Type.DOUBLE; } else if (type.equals("float")) { return Schema.Type.FLOAT; } else if (type.equals("string")) { return Schema.Type.STRING; } else if (type.equals("boolean")) { return Schema.Type.BOOLEAN; } return null; }
Source:
<code>public void testOpenSSL() throws IOException { assumeTrue(NativeCodeLoader.buildSupportsOpenssl()); OpenSSLSocketFactory.initializeDefaultFactory( OpenSSLSocketFactory.SSLChannelMode.OpenSSL); <START> assertTrue(OpenSSLSocketFactory.getDefaultFactory() <END> .getProviderName().contains("openssl")); }</code><technical_language>AssertJ assert text provided details of failure (i.e. provider name). Goal: a failure a jenkins run provide enough information enable work out failed</technical_language>

Target:
public void testOpenSSL() throws IOException { assumeTrue(NativeCodeLoader.buildSupportsOpenssl()); OpenSSLSocketFactory.initializeDefaultFactory( OpenSSLSocketFactory.SSLChannelMode.OpenSSL); assertThat(OpenSSLSocketFactory.getDefaultFactory() .getProviderName()).contains("openssl"); }
Source:
<code>protected void ensureUserListIsUsed() { <START> users = users == null ? new ArrayList<>() : new ArrayList<>(users); <END> if (user != null && !users.contains(user)) { users.add(user); } else if (email != null && users.isEmpty()) { users.add(NuxeoPrincipal.computeTransientUsername(email)); } }</code><technical_language>do need copy if null</technical_language>

Target:
protected void ensureUserListIsUsed() { users = users == null ? new ArrayList<>() : new ArrayList<>(users); if (user != null && !users.contains(user)) { users.add(user); } else if (email != null && users.isEmpty()) { users.add(computeTransientUsername(email)); } }
Source:
<code>public Response add(Host host) { validateEnums(Host.class, host); validateParameters(host, "name", "address", "rootPassword"); VdsStatic staticHost = getMapper(Host.class, VdsStatic.class).map(host, null); staticHost.setVdsGroupId(getClusterId(host)); AddVdsActionParameters addParams = new AddVdsActionParameters(staticHost, host.getRootPassword()); if (host.isSetOverrideIptables()) { addParams.setOverrideFirewall(host.isOverrideIptables()); } if (host.isSetRebootAfterInstallation()) { addParams.setRebootAfterInstallation(host.isRebootAfterInstallation()); } if (host.isSetSsh()) { if (host.getSsh().isSetUser()) { if (host.getSsh().getUser().isSetPassword()) { addParams.setPassword(host.getSsh().getUser().getPassword()); } } if (host.getSsh().isSetPort()) { addParams.getvds().setSshPort(host.getSsh().getPort().intValue()); } else { if (addParams.getvds().getSshPort() == 0) { addParams.getvds().setSshPort(DEFAULT_SSH_PORT); <START> } <END> } if (host.getSsh().isSetFingerprint()) { addParams.getvds().setSshKeyFingerprint(host.getSsh().getFingerprint()); } } return performCreate(VdcActionType.AddVds, addParams, new QueryIdResolver<Guid>(VdcQueryType.GetVdsByVdsId, IdQueryParameters.class)); }</code><technical_language>set default port in client while done in addparams.port=DEFAULT_PORT i this in BackendHostResource.install()</technical_language>

Target:
public Response add(Host host) { validateEnums(Host.class, host); validateParameters(host, "name", "address", "rootPassword"); VdsStatic staticHost = getMapper(Host.class, VdsStatic.class).map(host, null); staticHost.setVdsGroupId(getClusterId(host)); AddVdsActionParameters addParams = new AddVdsActionParameters(staticHost, host.getRootPassword()); if (host.isSetOverrideIptables()) { addParams.setOverrideFirewall(host.isOverrideIptables()); } if (host.isSetRebootAfterInstallation()) { addParams.setRebootAfterInstallation(host.isRebootAfterInstallation()); } if (host.isSetSsh()) { if (host.getSsh().isSetUser()) { if (host.getSsh().getUser().isSetPassword()) { addParams.setPassword(host.getSsh().getUser().getPassword()); } } if (host.getSsh().isSetPort()) { addParams.getvds().setSshPort(host.getSsh().getPort().intValue()); } if (host.getSsh().isSetFingerprint()) { addParams.getvds().setSshKeyFingerprint(host.getSsh().getFingerprint()); } } return performCreate(VdcActionType.AddVds, addParams, new QueryIdResolver<Guid>(VdcQueryType.GetVdsByVdsId, IdQueryParameters.class)); }
Source:
<code>public static final HTNode readNode(HTConfig config, FileChannel fc) throws IOException { HTNode newNode = null; int res, i; ByteBuffer buffer = ByteBuffer.allocate(config.getBlockSize()); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.clear(); res = fc.read(buffer); assert (res == config.getBlockSize()); buffer.flip(); byte type = buffer.get(); long start = buffer.getLong(); long end = buffer.getLong(); int seqNb = buffer.getInt(); int parentSeqNb = buffer.getInt(); int intervalCount = buffer.getInt(); int stringSectionOffset = buffer.getInt(); buffer.get(); switch (type) { case HTConfig.CORENODE_TYPE: newNode = new CoreNode(config, seqNb, parentSeqNb, start); newNode.readSpecificHeader(buffer); break; case HTConfig.LEAFNODE_TYPE: newNode = new LeafNode(config, seqNb, parentSeqNb, start); newNode.readSpecificHeader(buffer); break; <START> case HTConfig.CLAUDETTENODE_TYPE: <END> newNode = new ClaudetteNode(config, seqNb, parentSeqNb, start); newNode.readSpecificHeader(buffer); break; default: throw new IOException(); } for (i = 0; i < intervalCount; i++) { newNode.intervals.add(HTInterval.readFrom(buffer)); } newNode.nodeEnd = end; newNode.stringSectionOffset = stringSectionOffset; newNode.isOnDisk = true; return newNode; }</code><technical_language>rename</technical_language>

Target:
public static final HTNode readNode(HTConfig config, FileChannel fc) throws IOException { HTNode newNode = null; int res, i; ByteBuffer buffer = ByteBuffer.allocate(config.getBlockSize()); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.clear(); res = fc.read(buffer); assert (res == config.getBlockSize()); buffer.flip(); byte type = buffer.get(); long start = buffer.getLong(); long end = buffer.getLong(); int seqNb = buffer.getInt(); int parentSeqNb = buffer.getInt(); int intervalCount = buffer.getInt(); int stringSectionOffset = buffer.getInt(); buffer.get(); switch (type) { case CORENODE_TYPE: newNode = new CoreNode(config, seqNb, parentSeqNb, start); newNode.readSpecificHeader(buffer); break; case LEAFNODE_TYPE: newNode = new LeafNode(config, seqNb, parentSeqNb, start); newNode.readSpecificHeader(buffer); break; case EXTENSIONNODE_TYPE: newNode = new ExtensionNode(config, seqNb, parentSeqNb, start); newNode.readSpecificHeader(buffer); break; default: throw new IOException(); } for (i = 0; i < intervalCount; i++) { newNode.intervals.add(HTInterval.readFrom(buffer)); } newNode.nodeEnd = end; newNode.stringSectionOffset = stringSectionOffset; newNode.isOnDisk = true; return newNode; }
Source:
<code>AliasModuleSpec(final ModuleIdentifier moduleIdentifier, final ModuleIdentifier aliasTarget) { super(moduleIdentifier); this.aliasTarget = aliasTarget; DependencySpec aliasTargetDependency = DependencySpec.createModuleDependencySpec(PathFilters.acceptAll(), PathFilters.acceptAll(), null, aliasTarget, false); final String mainClass = null; final AssertionSetting assertionSetting = AssertionSetting.INHERIT; <START> final ResourceLoaderSpec[] resourceLoaders = new ResourceLoaderSpec[0]; <END> final DependencySpec[] dependencies = new DependencySpec[] { aliasTargetDependency }; final LocalLoader fallbackLoader = null; final ModuleClassLoaderFactory moduleClassLoaderFactory = null; final ClassFileTransformer classFileTransformer = null; final Map<String, String> properties = Collections.emptyMap(); final PermissionCollection permissionCollection = ModulesPolicy.DEFAULT_PERMISSION_COLLECTION; this.concreteModuleSpec = new ConcreteModuleSpec(moduleIdentifier, mainClass, assertionSetting, resourceLoaders, dependencies, fallbackLoader, moduleClassLoaderFactory, classFileTransformer, properties, permissionCollection); }</code><technical_language>Small nit, ideally this a constant (would save a couple allocations server startup)</technical_language>

Target:
AliasModuleSpec(final ModuleIdentifier moduleIdentifier, final ModuleIdentifier aliasTarget) { super(moduleIdentifier); this.aliasTarget = aliasTarget; DependencySpec aliasTargetDependency = DependencySpec.createModuleDependencySpec(PathFilters.acceptAll(), PathFilters.acceptAll(), null, aliasTarget, false); final String mainClass = null; final AssertionSetting assertionSetting = AssertionSetting.INHERIT; final ResourceLoaderSpec[] resourceLoaders = ResourceLoaderSpec.NO_RESOURCE_LOADERS; final DependencySpec[] dependencies = new DependencySpec[] { aliasTargetDependency }; final LocalLoader fallbackLoader = null; final ModuleClassLoaderFactory moduleClassLoaderFactory = null; final ClassFileTransformer classFileTransformer = null; final Map<String, String> properties = Collections.emptyMap(); final PermissionCollection permissionCollection = ModulesPolicy.DEFAULT_PERMISSION_COLLECTION; this.concreteModuleSpec = new ConcreteModuleSpec(moduleIdentifier, mainClass, assertionSetting, resourceLoaders, dependencies, fallbackLoader, moduleClassLoaderFactory, classFileTransformer, properties, permissionCollection); }
Source:
<code>private ExpectedCondition<Boolean> invisibilityOfAllElements(final List<WebElement> elements) { return new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver webDriver) { for (WebElement element : elements) { try { if (element.isDisplayed()) { return false; } <START> } catch (Exception e) { <END> } } return true; } }; }</code><technical_language>in catch block</technical_language>

Target:
private ExpectedCondition<Boolean> invisibilityOfAllElements(final List<WebElement> elements) { return new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver webDriver) { for (WebElement element : elements) { try { if (element.isDisplayed()) { return false; } } catch (Exception e) { } } return true; } @Override public String toString() { return "invisibility of all elements " + elements; } }; }
Source:
<code>private <V> V as(TypeToken<V> javaType) { <START> if (OBJECT_TYPE.equals(javaType)) { END> @SuppressWarnings("unchecked") V v = (V)asObject(); return v; } else { assert javaType != null; return with(codecFor(javaType)); } }</code><technical_language>a good point, plan move OBJECT_TYPE TypeTokens public, in theory allows users pass get(). null getObject (as initially did)</technical_language>

Target:
private <V> V as(TypeToken<V> javaType) { return with(codecFor(javaType)); }
Source:
<code>public void setUp() throws Exception { <START> MetadataStorageConnectorConfig config = jsonReadWriteRead( <END> "{" + "\"type\" : \"db\",\n" + "\"segmentTable\" : \"segments\"\n" + "}", MetadataStorageConnectorConfig.class ); connector = new TestDerbyConnector( Suppliers.ofInstance(config), Suppliers.ofInstance(tablesConfig) ); }</code><technical_language>do strings here</technical_language>

Target:
public void setUp() throws Exception { connector = new TestDerbyConnector( Suppliers.ofInstance(new MetadataStorageConnectorConfig()), Suppliers.ofInstance(tablesConfig) ); }
Source:
<code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.login_email_screen, container, false); mEmailEditText = (EditText) rootView.findViewById(R.id.login_email); mEmailEditText.addTextChangedListener(this); mEmailEditTextLayout = (TextInputLayout) rootView.findViewById(R.id.login_email_layout); mNextButton = (Button) rootView.findViewById(R.id.login_email_next_button); mNextButton.setOnClickListener(mNextClickListener); mUsernamePasswordButton = rootView.findViewById(R.id.login_email_username_password); mEmailEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { <START> if (!hasFocus) { <END> autocorrectEmail(); } } }); autofillFromBuildConfig(); mEmailEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if ((didPressNextKey(actionId, event) || didPressEnterKey(actionId, event))) { next(getEmail()); return true; } else { return false; } } }); mUsernamePasswordButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mLoginNavInputEmail != null) { mLoginNavInputEmail.loginViaUsernamePassword(); } } }); return rootView; }</code><technical_language>I testing this screen while reviewing code I curious. do focus out of this EditText? Tapping tapping buttons do it</technical_language>

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.login_email_screen, container, false); mEmailEditText = (EditText) rootView.findViewById(R.id.login_email); mEmailEditTextLayout = (TextInputLayout) rootView.findViewById(R.id.login_email_layout); mNextButton = (Button) rootView.findViewById(R.id.login_email_next_button); mNextButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { next(getCleanedEmail()); } }); autoFillFromBuildConfig(); mEmailEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (event != null && event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) { next(getCleanedEmail()); } return true; } }); rootView.findViewById(R.id.login_email_username_password).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mLoginNavInputEmail != null) { mLoginNavInputEmail.loginViaUsernamePassword(); } } }); return rootView; }
Source:
<code>private static boolean thatSupportForNestedPropertiesIsAvailable() { <START> Optional<String> version = Optional.ofNullable(SpringBootVersion.getVersion()); <END> return version.map(v -> v.split("\\.")) .filter(c -> c.length >= 3) .map(v -> new Integer[] { Integer.valueOf(v[0]), Integer.valueOf(v[1]), Integer.valueOf(v[2]) }) .map(c -> c[0] >= 2 && (c[1] >= 1 || c[1] == 0 && c[2] >= 5)) .orElseGet(ActorRepositoryIntegrationTest::boot210Or205SpecificMethodExists); }</code><technical_language>Spring Data a Version class check for valid ranges</technical_language>

Target:
private static boolean thatSupportForNestedPropertiesIsAvailable() { Version minVersion = Version.parse("2.0.5"); Optional<String> currentSpringBootVersion = Optional.ofNullable(SpringBootVersion.getVersion()); return currentSpringBootVersion.map(Version::parse) .map(v -> v.isGreaterThanOrEqualTo(minVersion)) .orElseGet(ActorRepositoryIntegrationTest::fallBackToVersionSpecificClasses); }
Source:
<code>public void waitForJavaScriptTruthy(final String script) { driver.manage().timeouts().implicitlyWait(500, TimeUnit.MILLISECONDS); try { waitFor.until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { try { return (boolean) ((JavascriptExecutor) driver) .executeScript("return !!(" + script + ");"); } catch (WebDriverException e) { PageObjectLogging.logError("waitForJavaScriptTruthy", e); <START> PageObjectLogging.log("Checking script to be truthy", script, false); <END> return false; } } }); } finally { PageObjectLogging.log("Checking script to be truthy", script, true); restoreDeaultImplicitWait(); } }</code><technical_language>oh, please log execption</technical_language>

Target:
public void waitForJavaScriptTruthy(final String script) { driver.manage().timeouts().implicitlyWait(500, TimeUnit.MILLISECONDS); try { waitFor.until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { try { return (boolean) ((JavascriptExecutor) driver) .executeScript("return !!(" + script + ");"); } catch (WebDriverException e) { PageObjectLogging.logError("waitForJavaScriptTruthy", e); return false; } } }); } finally { restoreDeaultImplicitWait(); } }
Source:
<code>public void addRefundTransactionEvent(Long transactionId, RefundStatus refundStatus, ZonedDateTime updated) { jdbi.withHandle(h -> { int update = h.update( "INSERT INTO transaction_events(" + "transaction_id," + "status," + "updated," + "operation" + ")" + "VALUES (" + "?, ?, ?, 'REFUND'" + ")", transactionId, refundStatus.name(), Timestamp.from(updated.toInstant()) ); <START> System.out.println("****************updated: " + update); <END> return update; } ); }</code><technical_language>Left-over debug ouput</technical_language>

Target:
public void addRefundTransactionEvent(Long transactionId, RefundStatus refundStatus, ZonedDateTime updated) { jdbi.withHandle(h -> h.update( "INSERT INTO transaction_events(" + "transaction_id," + "status," + "updated," + "operation" + ")" + "VALUES (" + "?, ?, ?, 'REFUND'" + ")", transactionId, refundStatus.name(), Timestamp.from(updated.toInstant()) ) ); }
Source:
<code>private MetadataInterface findMetadatumIn(DocStructInterface node) { <START> List<? extends MetadataInterface> metadataInterface = node.getAllMetadataByType(selector); <END> for (MetadataInterface metadatum : metadataInterface) { if (selector.getName().equals(metadatum.getMetadataType().getName())) { return metadatum; } } return null; }</code><technical_language>Interface appended variable name</technical_language>

Target:
private MetadataInterface findMetadatumIn(DocStructInterface node) { List<? extends MetadataInterface> metadata = node.getAllMetadataByType(selector); for (MetadataInterface metadatum : metadata) { if (selector.getName().equals(metadatum.getMetadataType().getName())) { return metadatum; } } return null; }
Source:
<code>public void selectionChanged(IWorkbenchPart part, ISelection selection) { final ISelection sel = selection; Job job = new Job(UIText.RepositorySourceProvider_updateRepoSelection) { @Override protected IStatus run(IProgressMonitor monitor) { Repository newRepository; if (sel == null) { newRepository = null; } else { newRepository = SelectionUtils.getRepository( SelectionUtils.getStructuredSelection(sel)); } if (repository != newRepository) { repository = newRepository; fireSourceChanged(ISources.ACTIVE_WORKBENCH_WINDOW, REPOSITORY_PROPERTY, repository); } return Status.OK_STATUS; } }; <START> job.schedule(); <END> }</code><technical_language>scheduling: job system (why users care in background) user, is started user: setSystem(true); setUser(false); job allow run multiple times in parallel itself: ideally a field, cancel() schedule next time. This avoid multiple calls clients avoid unpredictable order of calls (where reported repository is selected last). check for monitor.isCancelled() getRepository()/fireSourceChanged(), this time next selection job waiting run. monitor.isCancelled() return Status.CANCEl_STATUS. dispose()/windowDeactivated() cancel() null job field avoid memory leaks</technical_language>

Target:
public void selectionChanged(IWorkbenchPart part, ISelection selection) { if (updateSelectionJob != null) { updateSelectionJob.cancel(); } final ISelection sel = selection; updateSelectionJob = new Job( UIText.RepositorySourceProvider_updateRepoSelection) { @Override protected IStatus run(IProgressMonitor monitor) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } Repository newRepository; if (sel == null) { newRepository = null; } else { newRepository = SelectionUtils.getRepository( SelectionUtils.getStructuredSelection(sel)); } if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } if (repository != newRepository) { repository = newRepository; fireSourceChanged(ISources.ACTIVE_WORKBENCH_WINDOW, REPOSITORY_PROPERTY, repository); } return Status.OK_STATUS; } }; updateSelectionJob.setSystem(true); updateSelectionJob.setUser(false); updateSelectionJob.schedule(); }
Source:
<code>void attach() { vungleBannerAd.attach(); <START> } <END></code><technical_language>@joshuajplagonera detached destroyed a new Banner refresh, NPE happen: runtime.cc:642] Pending exception java.lang.NullPointerException: Attempt invoke virtual method 'void com.google.ads.mediation.vungle.VungleBannerAd.detach()' a null object reference runtime.cc:642] void com.vungle.mediation.VungleBannerAdapter.detach() (VungleBannerAdapter.java:293) runtime.cc:642] void com.vungle.mediation.VungleBannerAdapter$1.onDetachedFromWindow() (VungleBannerAdapter.java:120)</technical_language>

Target:
void attach() { if (vungleBannerAd != null) { vungleBannerAd.attach(); } }
Source:
<code>public void addCompareInputChangeListener(ICompareInputChangeListener listener) { <START> if (!containsListener(listener)) { <END> listeners.add(listener); } }</code><technical_language>ListenerList implementation takes care of this. Remove "contains" test</technical_language>

Target:
public void addCompareInputChangeListener(ICompareInputChangeListener listener) { listeners.add(listener); }
Source:
<code><START> public ATCommandResponsePacket(int frameID, ATCommandStatus status, String command, byte[] commandData) { <END> super(XBeeAPIType.AT_COMMAND_RESPONSE); this.frameID = frameID; this.status = status; this.command = command; this.commandData = commandData; }</code><technical_language>Throw proper exception if is supported: - NullPointerException if status == null command == null. - IllegalArgumentException if frameID < 0 if frameID > 255</technical_language>

Target:
public ATCommandResponsePacket(int frameID, ATCommandStatus status, String command, byte[] commandData) { super(APIFrameType.AT_COMMAND_RESPONSE); if (command == null) throw new NullPointerException("Command cannot be null."); if (status == null) throw new NullPointerException("Command status cannot be null."); if (frameID < 0 || frameID > 255) throw new IllegalArgumentException("Frame ID must be between 0 and 255."); this.frameID = frameID; this.status = status; this.command = command; this.commandData = commandData; }
Source:
<code>public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case android.R.id.home: toggleNavigationDrawer(!isDrawerOpen()); return true; case R.id.ab_action_refresh: <START> Log.d("YOLO", "Refreshing..."); <END> BusProvider.getInstance().post(new RefreshEvent()); return true; case R.id.ab_action_select_user: startActivityForResult( new Intent(this, LoginActivity.class), LoginActivity.REQUEST_PROFILE ); return true; case R.id.ab_action_about: startActivity(new Intent(this, AppInfoActivity.class)); return true; case R.id.ab_action_logout: showToast("TODO: Logout functionality"); return true; default: return super.onOptionsItemSelected(item); } }</code><technical_language>Rubbish</technical_language>

Target:
public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case android.R.id.home: toggleNavigationDrawer(!isDrawerOpen()); return true; case R.id.ab_action_refresh: BusProvider.getInstance().post(new RefreshEvent()); return true; case R.id.ab_action_select_user: startActivityForResult( new Intent(this, LoginActivity.class), LoginActivity.REQUEST_PROFILE ); return true; case R.id.ab_action_about: startActivity(new Intent(this, AppInfoActivity.class)); return true; case R.id.ab_action_logout: showToast("TODO: Logout functionality"); return true; default: return super.onOptionsItemSelected(item); } }
Source:
<code>AmbryDataNode(String dataCenterName, ClusterMapConfig clusterMapConfig, String hostName, int portNum, String rackId, Integer sslPortNum, long xid, ClusterManagerCallback clusterManagerCallback) throws Exception { this.hostName = hostName; this.plainTextPort = new Port(portNum, PortType.PLAINTEXT); this.sslPort = sslPortNum != null ? new Port(sslPortNum, PortType.SSL) : null; this.dataCenterName = dataCenterName; this.rackId = rackId; this.xid = xid; this.sslEnabledDataCenters = Utils.splitString(clusterMapConfig.clusterMapSslEnabledDatacenters, ","); ResourceStatePolicyFactory resourceStatePolicyFactory = Utils.getObj(clusterMapConfig.clusterMapResourceStatePolicyFactory, this, HardwareState.AVAILABLE, clusterMapConfig); this.resourceStatePolicy = resourceStatePolicyFactory.getResourceStatePolicy(); this.clusterManagerCallback = clusterManagerCallback; <START> validateHostName(clusterMapConfig.clusterMapResolveHostnames, hostName); <END> validatePort(plainTextPort, sslPort, sslEnabledDataCenters.contains(dataCenterName)); }</code><technical_language>Good refactoring</technical_language>

Target:
AmbryDataNode(String dataCenterName, ClusterMapConfig clusterMapConfig, String hostName, int portNum, String rackId, Integer sslPortNum, long xid, ClusterManagerCallback clusterManagerCallback) throws Exception { this.hostName = hostName; this.plainTextPort = new Port(portNum, PortType.PLAINTEXT); this.sslPort = sslPortNum != null ? new Port(sslPortNum, PortType.SSL) : null; this.dataCenterName = dataCenterName; this.rackId = rackId; this.xid = xid; this.sslEnabledDataCenters = Utils.splitString(clusterMapConfig.clusterMapSslEnabledDatacenters, ","); ResourceStatePolicyFactory resourceStatePolicyFactory = Utils.getObj(clusterMapConfig.clusterMapResourceStatePolicyFactory, this, HardwareState.AVAILABLE, clusterMapConfig); this.resourceStatePolicy = resourceStatePolicyFactory.getResourceStatePolicy(); this.clusterManagerCallback = clusterManagerCallback; validateHostName(clusterMapConfig.clusterMapResolveHostnames, hostName); validatePorts(plainTextPort, sslPort, sslEnabledDataCenters.contains(dataCenterName)); }
Source:
<code>private void maybeInitTxns() { if (eosEnabled) { try { producer.initTransactions(); } catch (final TimeoutException exception) { final String errorMessage = "Timeout exception caught when initializing transactions for task " + taskId + ". " + <START> "\nThe broker is either slow or in bad state (like not having enough replicas) in responding the request, " + <END> "or the connection to broker was interrupted sending the request or receiving the response. " + "\n Consider overwriting `max.block.ms` to a larger value to avoid timeout errors"; throw new StreamsException(errorMessage, exception); } catch (final KafkaException exception) { throw new StreamsException("Error encountered while initializing transactions for task " + taskId, exception); } } }</code><technical_language>suggestion "\nThe broker is slow in bad state (like enough replicas) in responding request, " +</technical_language>

Target:
private void maybeInitTxns() { if (eosEnabled) { try { producer.initTransactions(); } catch (final TimeoutException exception) { final String errorMessage = "Timeout exception caught when initializing transactions for task " + taskId + ". " + "\nThe broker is either slow or in bad state (like not having enough replicas) in responding to the request, " + "or the connection to broker was interrupted sending the request or receiving the response. " + "\n Consider overwriting `max.block.ms` to a larger value to avoid timeout errors"; throw new StreamsException(errorMessage, exception); } catch (final KafkaException exception) { throw new StreamsException("Error encountered while initializing transactions for task " + taskId, exception); } } }
Source:
<code>private Command handleFilteredNotification(final Notification notification) { IRefactorService refactorService = getRefactorService(); INotificationMatch match = filter.getMatch(notification); Command command = null; if <START> (null != refactorService && null != match) { <END> IRefactorRequest refactorRequest = new EMFRefactorRequest((EObject) match.getObjectUnderMatch()); refactorRequest.setRefactorResource(match.getResourceUnderMatch()); command = refactorService.getRefactorCommand(refactorRequest); } return command; }</code><technical_language>Test for a match attempting get refactoring service, involves accessing registry throw exceptions. work avoided lots of notifications ..</technical_language>

Target:
private Command handleFilteredNotification(final Notification notification) throws RollbackException { INotificationMatcher match = filter.getMatcher(notification); Command command = null; if (null != match) { IRefactorService refactorService = getRefactorService(); if (!unavailableService) { try { IRefactorRequest refactorRequest = new EMFRefactorRequest((EObject) match.getObjectUnderMatch()); refactorRequest.setRefactorResource(match.getResourceUnderMatch().getURI()); refactorRequest.setType(RefactorType.MOVE); command = refactorService.getRefactorCommand(refactorRequest); } catch (ServiceException e) { throw new RollbackException(new RollbackStatus(Activator.PLUGIN_ID, Status.ERROR, e.getMessage())); } } } return command; }
Source:
<code>public void setUp() throws Exception { <START> TestAccount user = accounts.create("user", "user@example.com", "User"); <END> userSession = new RestSession(server, user); }</code><technical_language>nice a test a user in administrator group, verify ADMINISTRATE_SERVER permission</technical_language>

Target:
public void setUp() throws Exception { TestAccount user = accounts.create("user", "user@example.com", "User"); TestAccount admin = accounts.admin(); userSession = new RestSession(server, user); adminSession = new RestSession(server, admin); }
Source:
<code>Job createJob(final String name, final JobCounter jc) { <START> return new Job("Job 1") { <END> @Override protected IStatus run(IProgressMonitor monitor) { jc.jobDone(getName()); return Status.OK_STATUS; } }; }</code><technical_language>return new Job(name)</technical_language>

Target:
Job createJob(final String name, final JobCounter jc) { return new Job(name) { @Override protected IStatus run(IProgressMonitor monitor) { jc.jobDone(getName()); return Status.OK_STATUS; } }; }
Source:
<code>public void doAccept(String method, Object... params) throws ForbiddenException { String workspaceId; switch (method) { case BROKER_STATUS_CHANGED_METHOD: case BROKER_RESULT_METHOD: <START> workspaceId = ((BrokerStatusChangedEvent) params[0]).getRuntimeId().getWorkspaceId(); <END> break; default: throw new ForbiddenException("Unknown method is configured to be filtered."); } Subject currentSubject = EnvironmentContext.getCurrent().getSubject(); if (!currentSubject.hasPermission( WorkspaceDomain.DOMAIN_ID, workspaceId, WorkspaceDomain.RUN)) { throw new ForbiddenException( "User doesn't have the required permissions to the specified workspace"); } }</code><technical_language>Please, check runtimeId is NULL</technical_language>

Target:
public void doAccept(String method, Object... params) throws ForbiddenException { String workspaceId; switch (method) { case BROKER_STATUS_CHANGED_METHOD: case BROKER_RESULT_METHOD: RuntimeIdentityDto runtimeId = ((BrokerStatusChangedEvent) params[0]).getRuntimeId(); if (runtimeId == null || runtimeId.getWorkspaceId() == null) { throw new ForbiddenException("Workspace id must be specified"); } workspaceId = runtimeId.getWorkspaceId(); break; default: throw new ForbiddenException("Unknown method is configured to be filtered."); } Subject currentSubject = EnvironmentContext.getCurrent().getSubject(); if (!currentSubject.hasPermission( WorkspaceDomain.DOMAIN_ID, workspaceId, WorkspaceDomain.RUN)) { throw new ForbiddenException( "User doesn't have the required permissions to the specified workspace"); } }
Source:
<code>private AbstractArrowSourceFunction<T> createTestArrowSourceFunction( List<T> testData, int batches) throws IOException { RowType rowType = (RowType) dataType.getLogicalType(); VectorSchemaRoot root = VectorSchemaRoot.create( ArrowUtils.toArrowSchema(rowType), allocator); <START> ArrowWriter<T> arrowWriter = createArrowWriter(root, rowType); <END> ByteArrayOutputStream baos = new ByteArrayOutputStream(); ArrowStreamWriter arrowStreamWriter = new ArrowStreamWriter(root, null, baos); arrowStreamWriter.start(); List<List<T>> subLists = Lists.partition(testData, testData.size() / batches + 1); for (List<T> subList : subLists) { for (T value : subList) { arrowWriter.write(value); } arrowWriter.finish(); arrowStreamWriter.writeBatch(); arrowWriter.reset(); } AbstractArrowSourceFunction<T> arrowSourceFunction = createArrowSourceFunction( ArrowUtils.readArrowBatches( Channels.newChannel(new ByteArrayInputStream(baos.toByteArray())))); arrowSourceFunction.setRuntimeContext(Mockito.mock(RuntimeContext.class)); return arrowSourceFunction; }</code><technical_language>verify content of data</technical_language>

Target:
private AbstractArrowSourceFunction<T> createTestArrowSourceFunction( List<T> testData, int batches) throws IOException { ArrowWriter<T> arrowWriter = createArrowWriter(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ArrowStreamWriter arrowStreamWriter = new ArrowStreamWriter(root, null, baos); arrowStreamWriter.start(); List<List<T>> subLists = Lists.partition(testData, testData.size() / batches + 1); for (List<T> subList : subLists) { for (T value : subList) { arrowWriter.write(value); } arrowWriter.finish(); arrowStreamWriter.writeBatch(); arrowWriter.reset(); } AbstractArrowSourceFunction<T> arrowSourceFunction = createArrowSourceFunction( ArrowUtils.readArrowBatches( Channels.newChannel(new ByteArrayInputStream(baos.toByteArray())))); arrowSourceFunction.setRuntimeContext(Mockito.mock(RuntimeContext.class)); return arrowSourceFunction; }
Source:
<code>public ProcessUpdateResult processUpdate( final ProcessUpdateParams params ) { final Site editedSite = (Site) params.getEditedContent(); final SiteConfigs editedSiteConfigs = editedSite.getSiteConfigs(); final Site originalSite = (Site) params.getOriginalContent(); final SiteConfigs originalSiteConfigs = originalSite.getSiteConfigs(); final Context context = ContextAccessor.current(); final AuthenticationInfo authenticationInfo = context.getAuthInfo(); final ProjectName projectName = ProjectName.from( context.getRepositoryId() ); if ( !Objects.equals( originalSiteConfigs, editedSiteConfigs ) ) { if ( !this.projectPermissionsContextManager.hasAdminAccess( authenticationInfo ) ) { if ( ProjectConstants.DEFAULT_PROJECT_NAME.equals( projectName ) ) { throw new ProjectAccessRequiredException( authenticationInfo.getUser().getKey() ); } else if ( !this.projectPermissionsContextManager.hasAnyProjectPermission( projectName, authenticationInfo, Set.of( ProjectRole.OWNER ) ) ) { throw new ProjectAccessRequiredException( authenticationInfo.getUser().getKey(), ProjectRole.OWNER ); } } } <START> return null; <END> }</code><technical_language>@vbradnitski this method returns null</technical_language>

Target:
public ProcessUpdateResult processUpdate( final ProcessUpdateParams params ) { final Site editedSite = (Site) params.getEditedContent(); final SiteConfigs editedSiteConfigs = editedSite.getSiteConfigs(); final Site originalSite = (Site) params.getOriginalContent(); final SiteConfigs originalSiteConfigs = originalSite.getSiteConfigs(); final Context context = ContextAccessor.current(); final AuthenticationInfo authenticationInfo = context.getAuthInfo(); final ProjectName projectName = ProjectName.from( context.getRepositoryId() ); if ( !Objects.equals( originalSiteConfigs, editedSiteConfigs ) ) { if ( !ProjectAccessHelper.hasAdminAccess( authenticationInfo ) ) { if ( ProjectConstants.DEFAULT_PROJECT_NAME.equals( projectName ) ) { throw new ProjectAccessRequiredException( authenticationInfo.getUser().getKey() ); } else if ( !this.projectPermissionsContextManager.hasAnyProjectRole( authenticationInfo, projectName, Set.of( ProjectRole.OWNER ) ) ) { throw new ProjectAccessRequiredException( authenticationInfo.getUser().getKey(), ProjectRole.OWNER ); } } } return null; }
Source:
<code><START> public Class<? extends TestEntity> getJavaClass() { <END> return TestEntity.class; }</code><technical_language>public Class<TestEntity> getJavaClass() is :)</technical_language>

Target:
public Class<TestEntity> getJavaClass() { return TestEntity.class; }
Source:
<code>public void shouldThrowExceptionIfNoTypeMappingWasFoundWithoutAccessingDbWithQueryAsObservable() { final StorIOSQLite storIOSQLite = mock(StorIOSQLite.class); final StorIOSQLite.Internal internal = mock(StorIOSQLite.Internal.class); when(storIOSQLite.get()).thenReturn(new PreparedGet.Builder(storIOSQLite)); when(storIOSQLite.internal()).thenReturn(internal); when(storIOSQLite.observeChangesInTables(any(Set.class))) .thenReturn(Observable.empty()); final TestSubscriber<TestItem> testSubscriber = new TestSubscriber<TestItem>(); storIOSQLite .get() .object(TestItem.class) .withQuery(Query.builder().table("test_table").build()) .prepare() .createObservable() .subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); testSubscriber.assertNoValues(); assertThat(testSubscriber.getOnErrorEvents().get(0)) .isInstanceOf(StorIOException.class) <START> .hasCauseInstanceOf(IllegalStateException.class); <END> verify(storIOSQLite).get(); verify(storIOSQLite).internal(); verify(internal).typeMapping(TestItem.class); verify(internal, never()).query(any(Query.class)); verify(storIOSQLite).observeChangesInTables(anySet()); verifyNoMoreInteractions(storIOSQLite, internal); }</code><technical_language>check exception message</technical_language>

Target:
public void shouldThrowExceptionIfNoTypeMappingWasFoundWithoutAccessingDbWithQueryAsObservable() { final StorIOSQLite storIOSQLite = mock(StorIOSQLite.class); final StorIOSQLite.Internal internal = mock(StorIOSQLite.Internal.class); when(storIOSQLite.get()).thenReturn(new PreparedGet.Builder(storIOSQLite)); when(storIOSQLite.internal()).thenReturn(internal); when(storIOSQLite.observeChangesInTables(any(Set.class))) .thenReturn(Observable.empty()); final TestSubscriber<TestItem> testSubscriber = new TestSubscriber<TestItem>(); storIOSQLite .get() .object(TestItem.class) .withQuery(Query.builder().table("test_table").build()) .prepare() .createObservable() .subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); testSubscriber.assertNoValues(); assertThat(testSubscriber.getOnErrorEvents().get(0)) .isInstanceOf(StorIOException.class) .hasCauseInstanceOf(IllegalStateException.class) .hasMessageEndingWith("This type does not have type mapping: " + "type = " + TestItem.class + "," + "db was not touched by this operation, please add type mapping for this type"); verify(storIOSQLite).get(); verify(storIOSQLite).internal(); verify(internal).typeMapping(TestItem.class); verify(internal, never()).query(any(Query.class)); verify(storIOSQLite).observeChangesInTables(anySet()); verifyNoMoreInteractions(storIOSQLite, internal); }
Source:
<code><START> default void setRetryAnalyzerClass(Class<? extends IRetryAnalyzer> clazz) <END></code><technical_language>call setRetryAnalyzer(....newInstance(clazz))</technical_language>

Target:
default void setRetryAnalyzerClass(Class<? extends IRetryAnalyzer> clazz) { setRetryAnalyzer(ClassHelper.newInstance(clazz)); }
Source:
<code><START> public Parameter[] getParameters() { <END> return new Parameter[]{ ParameterBuilder.create(ON+DESKTOP).label("Turn this test ON for desktop").matching("(YES|NO)") .description("Test will be off by default enter 'YES' in box above to enable"), ParameterBuilder.create(ON+TABLET).label("Turn this test ON for Tablet").matching("(YES|NO)") .description( "Test will be off by default enter 'YES' in box above to enable"), ParameterBuilder.create(ON+MOBILE).label("Turn this test ON for Mobile").matching("(YES|NO)") .description( "Test will be off by default enter 'YES' in box above to enable") }; }</code><technical_language>I strongly agree prefix removal. is more 3 constants good enum candidate. reuse existing one: org.springframework.mobile.device.DeviceType</technical_language>

Target:
public Parameter[] getParameters() { return new Parameter[]{ ParameterBuilder.create(NORMAL.name()) .label("Turn this feature ON for desktop").matching("(?i)(YES|NO)") .description("Feature will be off by default enter 'YES' in box above to enable"), ParameterBuilder.create(TABLET.name()) .label("Turn this feature ON for Tablet").matching("(?i)(YES|NO)") .description("Feature will be off by default enter 'YES' in box above to enable"), ParameterBuilder.create(MOBILE.name()) .label("Turn this feature ON for Mobile").matching("(?i)(YES|NO)") .description("Feature will be off by default enter 'YES' in box above to enable") }; }
Source:
<code>public void setChangesPanelView(ChangesPanelView changesPanelView) { FlowPanel flowPanel = new FlowPanel(); <START> flowPanel.ensureDebugId("git-compare-window-changed_files"); <END> flowPanel.setWidth("600px"); flowPanel.setHeight("345px"); flowPanel.add((Widget) changesPanelView); this.setWidget(flowPanel); }</code><technical_language>git-compare-window-changed-files</technical_language>

Target:
public void setChangesPanelView(ChangesPanelView changesPanelView) { FlowPanel flowPanel = new FlowPanel(); flowPanel.ensureDebugId("git-compare-window-changed-files"); flowPanel.setWidth("600px"); flowPanel.setHeight("345px"); flowPanel.add((Widget) changesPanelView); this.setWidget(flowPanel); }
Source:
<code>public void testBackwardsClock() { int numIterations = 10000; Set<Long> idSet = new HashSet<Long>(numIterations); TimeProvider tp = new TimeProvider() { Random random = new Random(1); @Override public long getTimeInMillis() { <START> if (random.nextInt(1000) == 1) { <END> return System.currentTimeMillis() - 5; } return System.currentTimeMillis(); } }; IdGenerator idgen = new IdGenerator(0L, tp); for (int i = 0; i < numIterations; ++i) { assertTrue(idSet.add(idgen.getNextId())); } assertEquals(numIterations, idSet.size()); }</code><technical_language>random, prefer a deterministic test experiences clock backjumps time run. E.g. jump 1237 iterations, deterministically</technical_language>

Target:
public void testBackwardsClock() { int numIterations = 10000; Set<Long> idSet = new HashSet<Long>(numIterations); TimeProvider tp = new TimeProvider() { private int counter = 0; @Override public long getTimeInMillis() { if ((counter++ % 109) == 0) { return System.currentTimeMillis() - 5; } return System.currentTimeMillis(); } }; IdGenerator idgen = new IdGenerator(0L, tp); for (int i = 0; i < numIterations; ++i) { assertTrue(idSet.add(idgen.getNextId())); } assertEquals(numIterations, idSet.size()); }
Source:
<code>public boolean initialize(AndroidCommCarePlatform platform, boolean isUpgrade) throws IOException, InvalidReferenceException, InvalidStructureException, XmlPullParserException, UnfullfilledRequirementsException { super.initialize(platform, isUpgrade); if (platform.getFormDefId(namespace) == -1) { platform.registerXmlns(namespace, formDefId); } else { FormDefRecord existingForm = FormDefRecord.getFormDef(platform.getFormDefStorage(), platform.getFormDefId(namespace)); FormDefRecord newForm = FormDefRecord.getFormDef(platform.getFormDefStorage(), formDefId); <START> if (newForm.getResourceVersion() > existingForm.getResourceVersion()) { <END> platform.registerXmlns(namespace, formDefId); } } return true; }</code><technical_language>Small point I this >=. a situation resource new resource version resource is out. In case signal this current resource is installed (because is initialized, installed resources) imply this resource is valid, other information installed resource presume be</technical_language>

Target:
public boolean initialize(AndroidCommCarePlatform platform, boolean isUpgrade) throws IOException, InvalidReferenceException, InvalidStructureException, XmlPullParserException, UnfullfilledRequirementsException { super.initialize(platform, isUpgrade); if (platform.getFormDefId(namespace) == -1) { platform.registerXmlns(namespace, formDefId); } else { FormDefRecord existingForm = FormDefRecord.getFormDef(platform.getFormDefStorage(), platform.getFormDefId(namespace)); FormDefRecord newForm = FormDefRecord.getFormDef(platform.getFormDefStorage(), formDefId); if (newForm.getResourceVersion() >= existingForm.getResourceVersion()) { platform.registerXmlns(namespace, formDefId); } } return true; }
Source:
<code>private int evaluateExpressionForNumericResult( final Message<?> requestMessage, Expression expression) { <START> int firstResult = 0; <END> Object evaluationResult = expression.getValue(evaluationContext, requestMessage); if(evaluationResult != null) { if(evaluationResult instanceof Number) { firstResult = ((Number)evaluationResult).intValue(); } else if(evaluationResult instanceof String){ try { firstResult = Integer.parseInt((String)evaluationResult); } catch (NumberFormatException e) { throw new IllegalArgumentException( "Value " + evaluationResult + " passed as cannot be " + "parsed to a number, expected to be numeric"); } } else { throw new IllegalArgumentException("Expected the value to be a Number" + " got " + evaluationResult.getClass().getName()); } } return firstResult; }</code><technical_language>Hi, Amol! Rename, please, this variable. this method covers firstResult case</technical_language>

Target:
private int evaluateExpressionForNumericResult(final Message<?> requestMessage, Expression expression) { int evaluatedResult = 0; if(expression != null) { Object evaluationResult = expression.getValue(evaluationContext, requestMessage); if(evaluationResult != null) { if(evaluationResult instanceof Number) { evaluatedResult = ((Number) evaluationResult).intValue(); } else if(evaluationResult instanceof String){ try { evaluatedResult = Integer.parseInt((String)evaluationResult); } catch (NumberFormatException e) { throw new IllegalArgumentException( "Value " + evaluationResult + " passed as cannot be " + "parsed to a number, expected to be numeric"); } } else { throw new IllegalArgumentException("Expected the value to be a Number" + " got " + evaluationResult.getClass().getName()); } } } return evaluatedResult; }