auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private String createKey( final String key ) { try { final MessageDigest md = MessageDigest.getInstance( "SHA-256" ); md.update( key.getBytes() ); final byte[] digest = md.digest(); return new String( Base64.encode( digest ) ); } catch ( final Exception b ) { return null; <START> } <END> }</code><technical_language>Returning <null> a good idea. Throw error request fail (as meaningful of recovering here). In addition that, a <null> element a segment in key for storage backend is handled NPE. However, I a safe case <null> allowed segment id. General rule: If error sensibly handle locally, try "auto-fix" it, report error caller</technical_language>

Target:
private String createKey( final String key ) { if ( StringUtil.isEmpty( key ) ) { return ANONYMOUS; } try { final MessageDigest md = MessageDigest.getInstance( "SHA-256" ); md.update( key.getBytes() ); final byte[] digest = md.digest(); return new String( Base64.encode( digest ) ); } catch ( final NoSuchAlgorithmException e ) { throw new Error( e ); } }
Source:
<code>static String doTransform(String value, String transform) { switch (transform) { case LOWER_CASE: <START> return value.toLowerCase(); <END> case UPPER_CASE: return value.toUpperCase(); default: throw new UnsupportedOperationException(String.format("transform '%s' is unsupported", transform)); } }</code><technical_language>Locale.ROOT (to avoid problem of #1768)</technical_language>

Target:
static String doTransform(String value, String transform) { switch (transform) { case LOWER_CASE: return value.toLowerCase(Locale.ROOT); case UPPER_CASE: return value.toUpperCase(Locale.ROOT); default: throw new UnsupportedOperationException(String.format("transform '%s' is unsupported", transform)); } }
Source:
<code>public StyledString getStyledText(Object element) { if (fProviders != null) { <START> for (ICHEProvider provider : fProviders) { <END> StyledString styledString = provider.getStyledText(element); if (styledString != null) return styledString; } } if (element instanceof CHNode) { CHNode node= (CHNode) element; ICElement decl= node.getOneRepresentedDeclaration(); if (decl != null) { StyledString label; if (node.isMultiDef()) { long options= fCLabelProvider.getTextFlags(); fCLabelProvider.setTextFlags(LABEL_OPTIONS_SIMPLE); label= fCLabelProvider.getStyledText(decl); fCLabelProvider.setTextFlags(options); } else { label= fCLabelProvider.getStyledText(decl); if (node.isInitializer()) { label= addInitializerDecoration(label); } } int refCount= node.getReferenceCount(); if (refCount > 1) { final int offset= label.length(); label.append(NLS.bind(" ({0} {1})", Integer.valueOf(refCount), CHMessages.CHLabelProvider_matches)); label.setStyle(offset, label.length() - offset, StyledString.COUNTER_STYLER); } String decorated= decorateText(label.getString(), element); if (decorated != null) { return StyledCellLabelProvider.styleDecoratedString(decorated, StyledString.DECORATIONS_STYLER, label); } return label; } } return fCLabelProvider.getStyledText(element); }</code><technical_language>Do providers understand kind of element, ICHENodes? If instanceof check first</technical_language>

Target:
public StyledString getStyledText(Object element) { if (fProviders == null ) { fProviders = fView.getLabelProviders(); } if (fProviders != null) { for (IStyledLabelProvider provider : fProviders) { StyledString styledString = provider.getStyledText(element); if (styledString != null) return styledString; } } if (element instanceof CHNode) { CHNode node= (CHNode) element; ICElement decl= node.getOneRepresentedDeclaration(); if (decl != null) { StyledString label; if (node.isMultiDef()) { long options= fCLabelProvider.getTextFlags(); fCLabelProvider.setTextFlags(LABEL_OPTIONS_SIMPLE); label= fCLabelProvider.getStyledText(decl); fCLabelProvider.setTextFlags(options); } else { label= fCLabelProvider.getStyledText(decl); if (node.isInitializer()) { label= addInitializerDecoration(label); } } int refCount= node.getReferenceCount(); if (refCount > 1) { final int offset= label.length(); label.append(NLS.bind(" ({0} {1})", Integer.valueOf(refCount), CHMessages.CHLabelProvider_matches)); label.setStyle(offset, label.length() - offset, StyledString.COUNTER_STYLER); } String decorated= decorateText(label.getString(), element); if (decorated != null) { return StyledCellLabelProvider.styleDecoratedString(decorated, StyledString.DECORATIONS_STYLER, label); } return label; } } return fCLabelProvider.getStyledText(element); }
Source:
<code>public void showError(@NonNull final Context context, @NonNull final Throwable error) { @StringRes int errorResId = R.string.error_unknown; Icon icon = null; @StringRes int actionTextResId = 0; View.OnClickListener actionListener = null; if (error instanceof IOException) { icon = FontAwesomeIcons.fa_wifi; if (NetworkUtil.isConnected(context)) { errorResId = R.string.network_connected_error; } else { errorResId = R.string.reset_no_network_message; } } else if (error instanceof HttpStatusException) { switch (((HttpStatusException) error).getStatusCode()) { case HttpStatus.SERVICE_UNAVAILABLE: errorResId = R.string.network_service_unavailable; break; case HttpStatus.UPGRADE_REQUIRED: errorResId = R.string.app_version_unsupported; actionTextResId = R.string.label_update; actionListener = AppStoreUtils.OPEN_APP_IN_APP_STORE_CLICK_LISTENER; break; <START> } <END> } if (errorResId == R.string.error_unknown) { logger.error(error, true); } showError(errorResId, icon, actionTextResId, actionListener); }</code><technical_language>icon null in cases other case of IOException. declare icon final final Icon icon; deal cases mark icon @Nullable in method signatures</technical_language>

Target:
public void showError(@NonNull final Context context, @NonNull final Throwable error) { showError(context, error, 0, null); }
Source:
<code>public void readStats(GlowPlayer player) { File statsFile = getPlayerFile(player.getUniqueId()); player.getStatisticMap().getValues().clear(); if (statsFile.exists()) { try { JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser.parse(new FileReader(statsFile)); for (Object o : json.keySet()) { String key = (String) o; <START> int value = (int) (long) json.get(o); <END> player.getStatisticMap().getValues().put(key, value); } } catch (ParseException | IOException e) { e.printStackTrace(); } } }</code><technical_language>casts here</technical_language>

Target:
public void readStats(GlowPlayer player) { File statsFile = getPlayerFile(player.getUniqueId()); player.getStatisticMap().getValues().clear(); if (statsFile.exists()) { try { JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser.parse(new FileReader(statsFile)); for (Object o : json.keySet()) { String key = (String) o; int value = ((Long) json.get(o)).intValue(); player.getStatisticMap().getValues().put(key, value); } } catch (ParseException | IOException e) { e.printStackTrace(); } } }
Source:
<code>public void shouldThrowBadCredentialsExceptionWhenNoUserFound_WithMultipleSearchBase() { final FilterBasedLdapUserSearch filter1 = mock(FilterBasedLdapUserSearch.class); final FilterBasedLdapUserSearch filter2 = mock(FilterBasedLdapUserSearch.class); LdapConfig ldapConfig = setLdapConfig(new BasesConfig(new BaseConfig("base1"), new BaseConfig("base2"))); doReturn(filter1).when(spy).getFilterBasedLdapUserSearch(ldapConfig.getBasesConfig().get(0).getValue(), ldapConfig.searchFilter()); doReturn(filter2).when(spy).getFilterBasedLdapUserSearch(ldapConfig.getBasesConfig().get(1).getValue(), ldapConfig.searchFilter()); when(filter1.searchForUser("username")).thenThrow(new UsernameNotFoundException("User username not found in directory.")); when(filter2.searchForUser("username")).thenThrow(new UsernameNotFoundException("User username not found in directory.")); try { spy.searchForUser("username"); fail("Should have thrown up"); } catch (BadCredentialsException e) { assertThat(e.getMessage(), is("Bad credentials")); <START> } <END> verify(filter1).searchForUser("username"); verify(filter2).searchForUser("username"); }</code><technical_language>start <LINK_0> For asserting exceptions</technical_language>

Target:
public void shouldThrowBadCredentialsExceptionWhenNoUserFound_WithMultipleSearchBase() { final FilterBasedLdapUserSearch filter1 = mock(FilterBasedLdapUserSearch.class); final FilterBasedLdapUserSearch filter2 = mock(FilterBasedLdapUserSearch.class); LdapConfig ldapConfig = setLdapConfig(new BasesConfig(new BaseConfig("base1"), new BaseConfig("base2"))); doReturn(filter1).when(spy).getFilterBasedLdapUserSearch(ldapConfig.getBasesConfig().get(0).getValue(), ldapConfig.searchFilter()); doReturn(filter2).when(spy).getFilterBasedLdapUserSearch(ldapConfig.getBasesConfig().get(1).getValue(), ldapConfig.searchFilter()); when(filter1.searchForUser("username")).thenThrow(new UsernameNotFoundException("User username not found in directory.")); when(filter2.searchForUser("username")).thenThrow(new UsernameNotFoundException("User username not found in directory.")); thrown.expect(BadCredentialsException.class); thrown.expectMessage(is("Bad credentials")); spy.searchForUser("username"); verify(filter1).searchForUser("username"); verify(filter2).searchForUser("username"); }
Source:
<code>protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitLeftHandExprList(@NotNull GoLeftHandExprList o) { super.visitLeftHandExprList(o); for (GoExpression expression : o.getExpressionList()) { <START> ProgressManager.checkCanceled(); <END> if (!(expression instanceof GoSelectorExpr)) continue; GoExpression expr = ContainerUtil.getFirstItem(((GoSelectorExpr)expression).getExpressionList()); if (expr instanceof GoIndexOrSliceExpr) { GoType exprType = expr.getGoType(null); if (exprType != null && exprType.getParent() instanceof GoMapType) { holder.registerProblem(o, "cannot assign to " + expression.getText(), GENERIC_ERROR_OR_WARNING); } } } } }; }</code><technical_language>good</technical_language>

Target:
protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitLeftHandExprList(@NotNull GoLeftHandExprList o) { super.visitLeftHandExprList(o); for (GoExpression expression : o.getExpressionList()) { ProgressManager.checkCanceled(); if (!(expression instanceof GoSelectorExpr)) continue; GoExpression expr = ContainerUtil.getFirstItem(((GoSelectorExpr)expression).getExpressionList()); if (expr instanceof GoIndexOrSliceExpr) { GoType exprType = expr.getGoType(null); if (exprType != null && !(exprType instanceof GoPointerType) && exprType.getParent() instanceof GoMapType) { holder.registerProblem(o, "cannot assign to " + expression.getText(), GENERIC_ERROR_OR_WARNING); } } } } }; }
Source:
<code>public List<DeviceStatus> getPillStatus(@Scope(OAuthScope.ADMINISTRATION_READ) final AccessToken accessToken, @QueryParam("email") final String email, @QueryParam("pill_id_partial") final String pillIdPartial, @QueryParam("end_ts") final Long endTs) { final List<DeviceAccountPair> pills = new ArrayList<>(); <START> if (email != null) { <END> LOGGER.debug("Querying all pills for email = {}", email); final Optional<Long> accountIdOptional = Util.getAccountIdByEmail(accountDAO, email); if (!accountIdOptional.isPresent()) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND) .entity("Account not found!").build()); } pills.addAll(deviceDAO.getPillsForAccountId(accountIdOptional.get())); } else if (pillIdPartial != null) { LOGGER.debug("Querying all pills whose IDs contain = {}", pillIdPartial); pills.addAll(deviceDAO.getPillsByPillIdHint(pillIdPartial)); } else { throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity("Missing query params!").build()); } final List<DeviceStatus> pillStatuses = new ArrayList<>(); for (final DeviceAccountPair pill : pills) { pillStatuses.addAll(deviceDAO.pillStatusBeforeTs(pill.internalDeviceId, new DateTime(endTs, DateTimeZone.UTC))); } return pillStatuses; }</code><technical_language>throw error early if email is null</technical_language>

Target:
public List<DeviceStatus> getPillStatus(@Scope(OAuthScope.ADMINISTRATION_READ) final AccessToken accessToken, @QueryParam("email") final String email, @QueryParam("pill_id_partial") final String pillIdPartial, @QueryParam("end_ts") final Long endTs) { final List<DeviceAccountPair> pills = new ArrayList<>(); if (email == null && pillIdPartial == null){ throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity("Missing query params!").build()); } else if (email != null) { LOGGER.debug("Querying all pills for email = {}", email); final Optional<Long> accountIdOptional = Util.getAccountIdByEmail(accountDAO, email); if (!accountIdOptional.isPresent()) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND) .entity("Account not found!").build()); } pills.addAll(deviceDAO.getPillsForAccountId(accountIdOptional.get())); } else { LOGGER.debug("Querying all pills whose IDs contain = {}", pillIdPartial); pills.addAll(deviceDAOAdmin.getPillsByPillIdHint(pillIdPartial)); } final List<DeviceStatus> pillStatuses = new ArrayList<>(); for (final DeviceAccountPair pill : pills) { pillStatuses.addAll(deviceDAOAdmin.pillStatusBeforeTs(pill.internalDeviceId, new DateTime(endTs, DateTimeZone.UTC))); } return pillStatuses; }
Source:
<code>public Position <START> cursorPosition() <END> { return syncExec(new Result<Position>() { @Override public Position run() { widget.setFocus(); int offset = widget.getSelectionRange().x; int line = widget.getContent().getLineAtOffset(offset); int offsetAtLine = widget.getContent().getOffsetAtLine(line); int column = offset - offsetAtLine; return new Position(line, column); } }); }</code><technical_language>I start of selection wrong. I problem caret position for this part of bug fix. implementation call cursorPosition(false)</technical_language>

Target:
public Position cursorPosition() { return cursorPosition(false); }
Source:
<code>public void findAvailableCapabilitiesByIds() throws Exception { <START> CapabilityList actual = catalog.findByIds(Lists.newArrayList(2, 15, 1)); <END> List<Capability> capabilities = new LinkedList<>(); capabilities.add(new Capability(1, "A")); capabilities.add(new Capability(2, "B")); CapabilityList expected = new CapabilityList(capabilities); assertThat(actual, deepEquals(expected)); }</code><technical_language>Remove of ids (1 2)</technical_language>

Target:
public void findAvailableCapabilitiesByIds() throws Exception { CapabilityList actual = catalog.findByIds(Lists.newArrayList(2, 15)); List<Capability> capabilities = Lists.newArrayList(new Capability(2, "B")); CapabilityList expected = new CapabilityList(capabilities); assertThat(actual, deepEquals(expected)); }
Source:
<code>public void onReceive(Context context, Intent data) { DataHandler dh = KissApplication.getDataHandler(context); ShortcutProvider sp = dh.getShortcutProvider(); <START> if (sp == null) <END> return; String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Log.d("onReceive", "Received shortcut " + name); if (sp.findByName(name) != null) { Log.d("onReceive", "Duplicated shortcut " + name + ", ignoring"); return; } Intent target = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); if (target.getAction() == null) { target.setAction(Intent.ACTION_VIEW); } ShortcutPojo pojo = sp.createPojo(name); pojo.intentUri = target.toUri(0); Bitmap icon = (Bitmap) data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); if (icon != null) { Log.d("onReceive", "Shortcut " + name + " has embedded icon"); pojo.icon = icon; } else { ShortcutIconResource sir = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (sir != null) { Log.d("onReceive", "Received icon package name " + sir.packageName); Log.d("onReceive", "Received icon resource name " + sir.resourceName); pojo.packageName = sir.packageName; pojo.resourceName = sir.resourceName; } else { Log.d("onReceive", "Invalid shortcut " + name + ", ignoring"); return; } } dh.addShortcut(context, pojo); dh.getShortcutProvider().addShortcut(pojo); }</code><technical_language>oh. turns out handling null case. Therefore, initialize shortcuthandler if prefs.getBoolean("enable-shortcuts", true). storing image in DB, i some app add shorcuts fast want givve option user "drop" queries add shortcuts. I remember spoke this earlier in sense, want shortcuts added if displayed. anymore, opinion</technical_language>

Target:
public void onReceive(Context context, Intent data) { DataHandler dh = KissApplication.getDataHandler(context); ShortcutProvider sp = dh.getShortcutProvider(); if (sp == null) return; String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Log.d("onReceive", "Received shortcut " + name); if (sp.findByName(name) != null || dh.getContactProvider().findByName(name) != null || dh.getAppProvider().findByName(name) != null ) { Log.d("onReceive", "Duplicated shortcut " + name + ", ignoring"); return; } Intent target = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); if (target.getAction() == null) { target.setAction(Intent.ACTION_VIEW); } ShortcutPojo pojo = createPojo(name); pojo.intentUri = target.toUri(0); Bitmap icon = (Bitmap) data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); if (icon != null) { Log.d("onReceive", "Shortcut " + name + " has embedded icon"); pojo.icon = icon; } else { ShortcutIconResource sir = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (sir != null) { Log.d("onReceive", "Received icon package name " + sir.packageName); Log.d("onReceive", "Received icon resource name " + sir.resourceName); pojo.packageName = sir.packageName; pojo.resourceName = sir.resourceName; } else { Log.d("onReceive", "Invalid shortcut " + name + ", ignoring"); return; } } dh.getShortcutProvider().addShortcut(pojo); }
Source:
<code>public void updateGroup(byte[] groupId, String name, List<String> members, String avatar) throws IOException, EncapsulatedExceptions, GroupNotFoundException, AttachmentInvalidException { String optName = null; Collection<String> optMembers = null; String optAvatar = null; if(!name.isEmpty()) { optName = name; } if(members.size() > 0) { optMembers = members; } if(!avatar.isEmpty()) { optAvatar = avatar; } <START> System.err.println("sendUpdateGroupMessage(" + Base64.encodeBytes(groupId) + ", " + optName + ", " + optMembers + ", " + optAvatar + ");"); <END> sendUpdateGroupMessage(groupId, optName, optMembers, null); }</code><technical_language>For consistency: "Updating group GROUP_ID, name NAME, ..</technical_language>

Target:
public void updateGroup(byte[] groupId, String name, List<String> members, String avatar) throws IOException, EncapsulatedExceptions, GroupNotFoundException, AttachmentInvalidException { if (name.isEmpty()) { name = null; } if (members.size() == 0) { members = null; } if (avatar.isEmpty()) { avatar = null; } sendUpdateGroupMessage(groupId, name, members, avatar); }
Source:
<code>private List<? extends PsiElement> resolveChain(HaxeReference lefthandExpression, HaxeReference reference) { String identifier = reference instanceof HaxeReferenceExpression ? ((HaxeReferenceExpression)reference).getIdentifier().getText() : reference.getText(); HaxeClassResolveResult leftExpression = lefthandExpression.resolveHaxeClass(); <START> if (leftExpression != HaxeClassResolveResult.EMPTY && leftExpression.getHaxeClass() != null) { <END> HaxeMemberModel member = leftExpression.getHaxeClass().getModel().getMember(identifier); if (member != null) { return Collections.singletonList(member.getBasePsi()); } } if (LOG.isTraceEnabled()) LOG.trace(traceMsg(null)); final HaxeComponentName componentName = tryResolveHelperClass(lefthandExpression, identifier); if (componentName != null) { if (LOG.isTraceEnabled()) LOG.trace("Found component " + componentName.getText()); return Collections.singletonList(componentName); } if (LOG.isTraceEnabled()) LOG.trace(traceMsg("trying keywords (super, new) arrays, literals, etc.")); return resolveByClassAndSymbol(lefthandExpression.resolveHaxeClass(), reference); }</code><technical_language>need test EMPTY</technical_language>

Target:
private List<? extends PsiElement> resolveChain(HaxeReference lefthandExpression, HaxeReference reference) { String identifier = reference instanceof HaxeReferenceExpression ? ((HaxeReferenceExpression)reference).getIdentifier().getText() : reference.getText(); HaxeClassResolveResult leftExpression = lefthandExpression.resolveHaxeClass(); if (leftExpression.getHaxeClass() != null) { HaxeMemberModel member = leftExpression.getHaxeClass().getModel().getMember(identifier); if (member != null) { return Collections.singletonList(member.getBasePsi()); } } if (LOG.isTraceEnabled()) LOG.trace(traceMsg(null)); final HaxeComponentName componentName = tryResolveHelperClass(lefthandExpression, identifier); if (componentName != null) { if (LOG.isTraceEnabled()) LOG.trace("Found component " + componentName.getText()); return Collections.singletonList(componentName); } if (LOG.isTraceEnabled()) LOG.trace(traceMsg("trying keywords (super, new) arrays, literals, etc.")); return resolveByClassAndSymbol(lefthandExpression.resolveHaxeClass(), reference); }
Source:
<code>public Enum<?> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { Enum<?>[] constants = ((Class<Enum<?>>) getValueClass()).getEnumConstants(); String text = CharMatcher .WHITESPACE.removeFrom(jp.getText()) .replace('-', '_') .toUpperCase(Locale.ENGLISH); for (Enum<?> constant : constants) { if (constant.name().equals(text)) { return constant; } } <START> return null; <END> }</code><technical_language>Do want return null throw exception here</technical_language>

Target:
public Enum<?> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { Enum<?>[] constants = ((Class<Enum<?>>) getValueClass()).getEnumConstants(); String text = CharMatcher .WHITESPACE.removeFrom(jp.getText()) .replace('-', '_') .toUpperCase(Locale.ENGLISH); for (Enum<?> constant : constants) { if (constant.name().equals(text)) { return constant; } } throw ctxt.mappingException(getValueClass()); }
Source:
<code><START> public static SpinnakerPluginEndPoint spinnakerPluginEndPoint( <END> SpinnakerPluginManager pluginManager) { return new SpinnakerPluginEndPoint(pluginManager); }</code><technical_language>I EndPoint Endpoint</technical_language>

Target:
public static SpinnakerPluginEndpoint spinnakerPluginEndPoint( SpinnakerPluginManager pluginManager) { return new SpinnakerPluginEndpoint(pluginManager); }
Source:
<code>public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { <START> this.errorChannel = (MessageChannel) applicationContext.getBean(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME); <END> }</code><technical_language>move this resolution afterPropertiesSet() if inject errorChannel @Configuration level</technical_language>

Target:
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; }
Source:
<code><START> public MutableBoundedValue<Integer> getExperienceBetweenLevels() { <END> return new SpongeBoundedValue<Integer>(Keys.EXPERIENCE_FROM_START_OF_LEVEL, 0, intComparator(), 0, Integer.MAX_VALUE, this.expBetweenLevels); }</code><technical_language>Yes, immutable. ImmutableBoundedValue contract is a BoundedValue a MutableBoundedValue</technical_language>

Target:
public ImmutableBoundedValue<Integer> getExperienceBetweenLevels() { return new ImmutableSpongeBoundedValue<>(Keys.EXPERIENCE_FROM_START_OF_LEVEL, this.expBetweenLevels, intComparator(), 0, Integer.MAX_VALUE); }
Source:
<code>public String getBackupIdentifier() { <START> return INSTRUCTOR_BACKUP_LOG_MSG + courseId + email; <END> }</code><technical_language>a delimiter courseId email</technical_language>

Target:
public String getBackupIdentifier() { return INSTRUCTOR_BACKUP_LOG_MSG + courseId + "::" + email; }
Source:
<code>protected void fillContentProvider(AbstractContentProvider contentProvider, ItemsFilter itemsFilter, IProgressMonitor progressMonitor) throws CoreException { if(fTypes != null && fTypes.length > 0) { for (IType <START> fType : <END> fTypes) { if (itemsFilter.isConsistentItem(fType)) { contentProvider.add(fType, itemsFilter); } } } }</code><technical_language>rename type</technical_language>

Target:
protected void fillContentProvider(AbstractContentProvider contentProvider, ItemsFilter itemsFilter, IProgressMonitor progressMonitor) throws CoreException { if(fTypes != null && fTypes.length > 0) { for (IType type : fTypes) { if (itemsFilter.isConsistentItem(type)) { contentProvider.add(type, itemsFilter); } } } }
Source:
<code>private void deleteNetwork(GcpContext context, AuthenticatedContext auth, Network network, String networkId) throws IOException { CloudResource networkResource = createNamedResource(GCP_NETWORK, networkId); try { CloudResource deletedResource = gcpNetworkResourceBuilder.delete(context, auth, networkResource, network); if (deletedResource != null) { PollTask<List<CloudResourceStatus>> task = statusCheckFactory.newPollResourceTask( gcpSubnetResourceBuilder, auth, Collections.singletonList(deletedResource), context, true); syncPollingScheduler.schedule(task); } <START> } catch (Exception e) { <END> LOGGER.debug("Skipping resource creation: {}", e.getMessage()); } }</code><technical_language>creation -> deletion</technical_language>

Target:
private void deleteNetwork(GcpContext context, AuthenticatedContext auth, Network network, String networkId) throws IOException { CloudResource networkResource = createNamedResource(GCP_NETWORK, networkId); try { CloudResource deletedResource = gcpNetworkResourceBuilder.delete(context, auth, networkResource, network); if (deletedResource != null) { PollTask<List<CloudResourceStatus>> task = statusCheckFactory.newPollResourceTask( gcpSubnetResourceBuilder, auth, Collections.singletonList(deletedResource), context, true); syncPollingScheduler.schedule(task); } } catch (Exception e) { LOGGER.debug("Skipping resource deletion: {}", e.getMessage()); } }
Source:
<code>public String[] getSupportedExtensions() { <START> return new String[] { "wtt" }; <END> }</code><technical_language>@Nadahar Right, text/vtt, i fast...my bad</technical_language>

Target:
public String[] getSupportedExtensions() { return new String[] { "vtt" }; }
Source:
<code><START> public Integer getPartSize() { <END> return getPropertyAsInt(FIELD_PART_SIZE); }</code><technical_language>return primitive integer ? a reason create integer objects here</technical_language>

Target:
public int getPartSize() { return getPropertyAsInt(FIELD_PART_SIZE); }
Source:
<code><START> public boolean isInVisibleLines(AbstractInlinedAnnotation annotation) { <END> return visibleLines.isInVisibleLines(annotation); }</code><technical_language>public? package visible only</technical_language>

Target:
boolean isInVisibleLines(AbstractInlinedAnnotation annotation) { return visibleLines.isInVisibleLines(annotation); }
Source:
<code>public ContentAssistant openContentAssistant() { <START> return openContentAssistant(ContentAssistantEnum.DEFAULT); <END> }</code><technical_language>content assist child items. For example in case of editing pom.xml file, is Edit->Content Assist child items. need add logic handle this case too</technical_language>

Target:
public ContentAssistant openContentAssistant() { Menu assistMenu = new ShellMenu("Edit", "Content Assist"); boolean hasAssistMenuChildren = MenuHandler.getInstance().getMenuFromMenuItem(assistMenu.getSWTWidget()) != null; if (hasAssistMenuChildren) return openContentAssistant(ContentAssistantEnum.DEFAULT); else return openContentAssistant("Edit", "Content Assist"); }
Source:
<code>void send(final long destinations[], final VoltMessage message) { if (destinations.length == 0) { return; } final HashMap<Subconnection, ArrayList<Long>> destinationsPerConn = new HashMap<Subconnection, ArrayList<Long>>(); if (m_hasMultiConnections) { for (long remoteHsId : destinations) { Subconnection c = m_connByHSIds.get(remoteHsId); if (c == null) { c = m_connections.get(m_nextConnection.getAndIncrement() % m_connections.size()); bindConnection(remoteHsId, c); } ArrayList<Long> bundle = destinationsPerConn.get(c); if (bundle == null) { bundle = new ArrayList<Long>(); destinationsPerConn.put(c, bundle); } bundle.add(remoteHsId); } for (Entry<Subconnection, ArrayList<Long>> e : destinationsPerConn.entrySet()) { e.getKey().send(Longs.toArray(e.getValue()), message); <START> } <END> } else { m_firstConn.send(destinations, message); } detectDeadHost(); }</code><technical_language>messages special mailboxes, ClientInterface, connection. changes, kinds of messages of connections. connections equal with/without SSL? recollection is encountered issue SSL enabled secondary connections</technical_language>

Target:
void send(final long destinations[], final VoltMessage message) { if (destinations.length == 0) { return; } final HashMap<Subconnection, ArrayList<Long>> destinationsPerConn = new HashMap<Subconnection, ArrayList<Long>>(); if (m_hasMultiConnections) { for (long remoteHsId : destinations) { Subconnection c = null; if (remoteHsId < 0) { c = m_connBySpecialHSIds.get(remoteHsId); } else { c = m_connByHSIds.get(remoteHsId); } if (c == null) { if (remoteHsId < 0) { c = m_connections.get(m_nextConnectionForSpecialHSId.getAndIncrement() % m_connections.size()); } else { c = m_connections.get(m_nextConnection.getAndIncrement() % m_connections.size()); } bindConnection(remoteHsId, c); } ArrayList<Long> bundle = destinationsPerConn.get(c); if (bundle == null) { bundle = new ArrayList<Long>(); destinationsPerConn.put(c, bundle); } bundle.add(remoteHsId); } for (Entry<Subconnection, ArrayList<Long>> e : destinationsPerConn.entrySet()) { e.getKey().send(Longs.toArray(e.getValue()), message); } } else { m_firstConn.send(destinations, message); } detectDeadHost(); }
Source:
<code>public static ArrayOfDoublesSketch deserialize(final Object serializedSketch) { if (serializedSketch instanceof String) { return deserializeFromBase64EncodedString((String) serializedSketch); } else if (serializedSketch instanceof byte[]) { return deserializeFromByteArray((byte[]) serializedSketch); } else if (serializedSketch instanceof ArrayOfDoublesSketch) { return (ArrayOfDoublesSketch) serializedSketch; } <START> throw new IllegalStateException( <END> "Object is not of a type that can deserialize to sketch: " + serializedSketch.getClass() ); }</code><technical_language>ISE</technical_language>

Target:
public static ArrayOfDoublesSketch deserialize(final Object serializedSketch) { if (serializedSketch instanceof String) { return deserializeFromBase64EncodedString((String) serializedSketch); } else if (serializedSketch instanceof byte[]) { return deserializeFromByteArray((byte[]) serializedSketch); } else if (serializedSketch instanceof ArrayOfDoublesSketch) { return (ArrayOfDoublesSketch) serializedSketch; } throw new ISE("Object is not of a type that can deserialize to sketch: %s", serializedSketch.getClass()); }
Source:
<code>protected Note importNoteFromUrl(NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook, Message fromMessage) throws IOException { Note note = null; if (fromMessage != null) { String urlHash = (String) fromMessage.get("hash"); AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal); note = notebook.importNote(urlHash, subject); Message message = new Message(OP.IMPORT_NOTE_STATUS); if (note != null) { note.persist(subject); message.put("importStatus", "success"); } <START> else { <END> message.put("importStatus", "failure"); } conn.send(serializeMessage(message)); broadcastNoteList(subject); } return note; }</code><technical_language>Formatting is here: else 1 line</technical_language>

Target:
protected Note importNoteFromUrl(NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook, Message fromMessage) throws IOException { Note note = null; if (fromMessage != null) { String type = (String) fromMessage.get("type"); if (type.equals("ipfs")) { String name = (String) fromMessage.get("name"); Map<String, Object> options = ((Map<String, Object>) fromMessage.get("options")); String urlHash = (String) options.get("hash"); AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal); note = notebook.importNoteFromBackend(urlHash, name, subject); Message message = new Message(OP.IMPORT_NOTE_STATUS); message.put("type", "ipfs"); message.put("options", options); if (note != null) { note.persist(subject); message.put("importStatus", "success"); } else { message.put("importStatus", "failure"); } conn.send(serializeMessage(message)); broadcastNoteList(subject); } } return note; }
Source:
<code>private void testImmediateSingle(Boolean expected, Boolean lhs, Boolean rhs) { <START> OrExpression and = createOr(lhs, rhs); <END> ImmutableBytesWritable out = new ImmutableBytesWritable(); MultiKeyValueTuple tuple = new MultiKeyValueTuple(); boolean success = and.evaluate(tuple, out); assertTrue(success); assertEquals(expected, PBoolean.INSTANCE.toObject(out)); }</code><technical_language>nit:</technical_language>

Target:
private void testImmediateSingle(Boolean expected, Boolean lhs, Boolean rhs) { OrExpression or = createOr(lhs, rhs); ImmutableBytesWritable out = new ImmutableBytesWritable(); MultiKeyValueTuple tuple = new MultiKeyValueTuple(); boolean success = or.evaluate(tuple, out); assertTrue(success); assertEquals(expected, PBoolean.INSTANCE.toObject(out)); }
Source:
<code>public void delete() { KernelTransaction transaction = safeAcquireTransaction(); try { boolean deleted = transaction.dataWrite().relationshipDelete( id ); if ( !deleted ) { throw new NotFoundException( "Unable to delete Relationship[" + id + "] since it has already been deleted." ); } } catch ( InvalidTransactionTypeKernelException e ) { throw new ConstraintViolationException( e.getMessage(), e ); } catch ( AutoIndexingKernelException e ) { throw new IllegalStateException( "Auto indexing encountered a failure while deleting the relationship: " + e.getMessage(), e ); } catch ( EntityNotFoundException e ) { throw new NotFoundException( "Unable to delete relationship[" + getId() + "] since it is already deleted." ); <START> } <END> }</code><technical_language>I need this catch - this is handled boolean return value</technical_language>

Target:
public void delete() { KernelTransaction transaction = safeAcquireTransaction(); try { boolean deleted = transaction.dataWrite().relationshipDelete( id ); if ( !deleted ) { throw new NotFoundException( "Unable to delete relationship[" + getId() + "] since it is already deleted." ); } } catch ( InvalidTransactionTypeKernelException e ) { throw new ConstraintViolationException( e.getMessage(), e ); } catch ( AutoIndexingKernelException e ) { throw new IllegalStateException( "Auto indexing encountered a failure while deleting the relationship: " + e.getMessage(), e ); } }
Source:
<code>public Iterator<Messages.Envelope> iterator() { return new Iterator<Messages.Envelope>() { @Override public boolean hasNext() { try { String line = input.readLine(); if (line == null) return false; if (line.trim().equals("")) { return hasNext(); } Messages.Envelope.Builder builder = Messages.Envelope.newBuilder(); try { JSON_PARSER.merge(line, builder); } catch(InvalidProtocolBufferException e) { <START> throw new RuntimeException(String.format("Not JSON: %s", line)); <END> } next = builder.build(); return true; } catch (IOException e) { throw new RuntimeException(e); } } @Override public Messages.Envelope next() { if (next == null) { throw new IllegalStateException("next() should only be called after a call to hasNext() that returns true"); } return next; } @Override public void remove() { throw new UnsupportedOperationException(); } }; }</code><technical_language>suggestion throw new RuntimeException(String.format("Not JSON: %s", line), e);</technical_language>

Target:
public Iterator<Messages.Envelope> iterator() { return new Iterator<Messages.Envelope>() { @Override public boolean hasNext() { try { String line = input.readLine(); if (line == null) return false; if (line.trim().equals("")) { return hasNext(); } Messages.Envelope.Builder builder = Messages.Envelope.newBuilder(); try { JSON_PARSER.merge(line, builder); } catch(InvalidProtocolBufferException e) { throw new RuntimeException(String.format("Not JSON: %s", line), e); } next = builder.build(); return true; } catch (IOException e) { throw new RuntimeException(e); } } @Override public Messages.Envelope next() { if (next == null) { throw new IllegalStateException("next() should only be called after a call to hasNext() that returns true"); } return next; } @Override public void remove() { throw new UnsupportedOperationException(); } }; }
Source:
<code>private static void cleanCredentialStore() { File dir = new File(BASE_STORE_DIRECTORY); <START> dir.mkdirs(); <END> File file = new File(BASE_STORE_DIRECTORY + "/mycredstore.cs"); file.delete(); }</code><technical_language>minor need call dir.mkdirs() here. This clean method needs check if file exists if so, delete it</technical_language>

Target:
private static void cleanCredentialStore() { File file = new File(BASE_STORE_DIRECTORY + "/mycredstore.cs"); file.delete(); }
Source:
<code>public List<TransactionDto> getAvailableBalanceTransactions(final Integer lotId) { try { if (lotId != null) { final StringBuilder sql = new StringBuilder(this.SEARCH_TRANSACTIONS_QUERY); sql.append(" and (act.trnstat =").append(TransactionStatus.CONFIRMED.getIntValue()).append(" or (act.trnstat = ") .append(TransactionStatus.PENDING.getIntValue()). append(" and act.trntype = ").append(TransactionType.WITHDRAWAL.getId()).append(")) "); sql.append(" and act.lotid = ").append(lotId).append(" "); final SQLQuery query = this.getSession().createSQLQuery(sql.toString()); <START> query.addScalar("transactionId"); query.addScalar("createdByUsername"); query.addScalar("transactionType"); query.addScalar("amount"); query.addScalar("notes"); query.addScalar("transactionDate", Hibernate.DATE); query.addScalar("lotLotId"); query.addScalar("lotGid"); query.addScalar("lotDesignation"); query.addScalar("lotStockId"); query.addScalar("lotScaleId"); query.addScalar("lotScaleName"); query.addScalar("lotStatus"); query.addScalar("transactionStatus"); query.addScalar("lotLocationId"); query.addScalar("lotComments"); <END> query.setResultTransformer(new AliasToBeanConstructorResultTransformer(this.getTransactionDtoConstructor())); final List<TransactionDto> transactionDtos = query.list(); return transactionDtos; } else { return new ArrayList<>(); } } catch (final HibernateException e) { throw new MiddlewareQueryException("Error at getAvailableBalanceTransactions() query on TransactionDAO: " + e.getMessage(), e); } }</code><technical_language>@clarysabel extracted a method? SEARCH_TRANSACTIONS_QUERY queries need scalars right</technical_language>

Target:
public List<TransactionDto> getAvailableBalanceTransactions(final Integer lotId) { try { if (lotId != null) { final StringBuilder sql = new StringBuilder(SEARCH_TRANSACTIONS_QUERY); sql.append(" and (act.trnstat =").append(TransactionStatus.CONFIRMED.getIntValue()).append(" or (act.trnstat = ") .append(TransactionStatus.PENDING.getIntValue()). append(" and act.trntype = ").append(TransactionType.WITHDRAWAL.getId()).append(")) "); sql.append(" and act.lotid = ").append(lotId).append(" "); final SQLQuery query = this.getSession().createSQLQuery(sql.toString()); this.addSearchTransactionsQueryScalars(query); query.setResultTransformer(new AliasToBeanConstructorResultTransformer(this.getTransactionDtoConstructor())); final List<TransactionDto> transactionDtos = query.list(); return transactionDtos; } else { return new ArrayList<>(); } } catch (final HibernateException e) { throw new MiddlewareQueryException("Error at getAvailableBalanceTransactions() query on TransactionDAO: " + e.getMessage(), e); } }
Source:
<code>public static void handlePartialDownload(InputStream is, HttpHeaders headers, HttpServletResponse response) throws IOException { String contentRange = headers.getFirst(HttpHeaders.RANGE); ByteRangeHeaderParser parser = new ByteRangeHeaderParser(contentRange); List<ByteRange> ranges = parser.getRanges(); if (!CollectionUtils.isEmpty(ranges)) <START> { <END> if (ranges.size() == 1) { logger.debug("Received request for a partial download with a single range."); handlePartialDownloadWithSingleRange(is, ranges.get(0), response); } else { logger.debug("Received request for a partial download with multiple ranges."); handlePartialDownloadWithMultipleRanges(is, ranges, response); } } }</code><technical_language>else throw some Exception notify requestor bad request</technical_language>

Target:
public static void handlePartialDownload(InputStream is, HttpHeaders headers, HttpServletResponse response) throws IOException { String contentRange = headers.getFirst(HttpHeaders.RANGE); ByteRangeHeaderParser parser = new ByteRangeHeaderParser(contentRange); try { List<ByteRange> ranges = parser.getRanges(); if (!CollectionUtils.isEmpty(ranges)) { if (ranges.size() == 1) { logger.debug("Received request for a partial download with a single range."); handlePartialDownloadWithSingleRange(is, ranges.get(0), response); } else { logger.debug("Received request for a partial download with multiple ranges."); handlePartialDownloadWithMultipleRanges(is, ranges, response); } } } catch (ByteRangeValidationException e) { logger.error(e.getMessage(), e); ByteRangeInputStream bris = StreamUtils.findSource(ByteRangeInputStream.class, is); long length = bris != null ? StreamUtils.getLength(bris) : 0; setRangeNotSatisfiable(response, length); } }
Source:
<code><START> public List<GroupModel> getGroups() { <END> List<GroupModel> ldapGroupMappings = getLDAPGroupMappingsConverted(); if (config.getMode() == LDAPGroupMapperMode.LDAP_ONLY) { return ldapGroupMappings; } else { List<GroupModel> modelGroupMappings = super.getGroups(); ldapGroupMappings.addAll(modelGroupMappings); return ldapGroupMappings; } }</code><technical_language>Revert a Set, List negatively impact performance</technical_language>

Target:
public Set<GroupModel> getGroups() { Set<GroupModel> ldapGroupMappings = getLDAPGroupMappingsConverted(); if (config.getMode() == LDAPGroupMapperMode.LDAP_ONLY) { return ldapGroupMappings; } else { Set<GroupModel> modelGroupMappings = super.getGroups(); ldapGroupMappings.addAll(modelGroupMappings); return ldapGroupMappings; } }
Source:
<code>private long getDefaultTimeout() { long timeout = 5 * 60 * 1000; try { <START> timeout = Long.getLong(DEFAULT_TIMEOUT_PROPERTY, timeout); <END> } catch (Exception e) { LOGGER.error(DEFAULT_TIMEOUT_PROPERTY + " is not a number. Using default value " + timeout + "."); } return timeout; }</code><technical_language>I propose log actual timeout if differs default</technical_language>

Target:
private long getDefaultTimeout() { long timeout = DEFAULT_TIMEOUT; try { timeout = Long.getLong(DEFAULT_TIMEOUT_PROPERTY, DEFAULT_TIMEOUT); if (timeout != DEFAULT_TIMEOUT) { LOGGER.debug(DEFAULT_TIMEOUT_PROPERTY + " is set to " + timeout + "."); } } catch (Exception e) { LOGGER.error(DEFAULT_TIMEOUT_PROPERTY + " is not a number. Using default value " + timeout + "."); } return timeout; }
Source:
<code>public void assertAbsenceOfErrors() { if (hasUnhandledErrors()) { if (log.isDebugEnabled()) { try { validator.onErrorUse(nothing()); } catch (ValidationException e) { log.debug("Some validation errors occured: {}", e.getErrors()); } <START> } <END> throw new IllegalStateException( "There are validation errors and you forgot to specify where to go. Please add in your method " + "something like:\n" + "validator.onErrorUse(page()).of(AnyController.class).anyMethod();\n" + "or any view that you like.\n" + "If you didn't add any validation error, it is possible that a conversion error had happened."); } }</code><technical_language>need validator here. errors (getErrors()), it. remove validator dependency. more cyclic dependency ;)</technical_language>

Target:
public void assertAbsenceOfErrors() { if (hasUnhandledErrors()) { log.debug("Some validation errors occured: {}", getErrors()); throw new IllegalStateException( "There are validation errors and you forgot to specify where to go. Please add in your method " + "something like:\n" + "validator.onErrorUse(page()).of(AnyController.class).anyMethod();\n" + "or any view that you like.\n" + "If you didn't add any validation error, it is possible that a conversion error had happened."); } }
Source:
<code>private void init(final Object target, Method method) { final Map<Class<? extends Throwable>, Method> types = new HashMap<Class<? extends Throwable>, Method>(); final Method failingMethod = method; Retryable retryable = method.getAnnotation(Retryable.class); if (retryable != null) { this.recoverMethodName = retryable.recover(); } ReflectionUtils.doWithMethods(target.getClass(), new MethodCallback() { @Override public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { Recover recover = AnnotationUtils.findAnnotation(method, Recover.class); if (recover == null) { recover = findAnnotationOnTarget(target, method); } if (recover != null && failingMethod.getGenericReturnType() instanceof ParameterizedType) { <START> if (method.getGenericReturnType().equals(failingMethod.getGenericReturnType())) { <END> putToMethodsMap(method, types); } } else if (recover != null && method.getReturnType().isAssignableFrom(failingMethod.getReturnType())) { putToMethodsMap(method, types); } } }); this.classifier.setTypeMap(types); optionallyFilterMethodsBy(failingMethod.getReturnType()); }</code><technical_language>While this fixes reported issue, unfortunately, I needs more sophisticated; need examine generic parameter(s) Map<String, Foo> match Map<String, Bar> if Bar is a subclass of Foo</technical_language>

Target:
private void init(final Object target, Method method) { final Map<Class<? extends Throwable>, Method> types = new HashMap<Class<? extends Throwable>, Method>(); final Method failingMethod = method; Retryable retryable = method.getAnnotation(Retryable.class); if (retryable != null) { this.recoverMethodName = retryable.recover(); } ReflectionUtils.doWithMethods(target.getClass(), new MethodCallback() { @Override public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { Recover recover = AnnotationUtils.findAnnotation(method, Recover.class); if (recover == null) { recover = findAnnotationOnTarget(target, method); } if (recover != null && failingMethod.getGenericReturnType() instanceof ParameterizedType && method.getGenericReturnType() instanceof ParameterizedType) { if (isParameterizedTypeAssignable((ParameterizedType) method.getGenericReturnType(), (ParameterizedType) failingMethod.getGenericReturnType())) { putToMethodsMap(method, types); } } else if (recover != null && method.getReturnType().isAssignableFrom(failingMethod.getReturnType())) { putToMethodsMap(method, types); } } }); this.classifier.setTypeMap(types); optionallyFilterMethodsBy(failingMethod.getReturnType()); }
Source:
<code>public void setUp() { super.setUp(); getUtil().deletePage(SPACE_NAME, DOC_NAME); adminPage.gotoPage(); annotationsAdminPage = adminPage.clickAnnotationsSection(); <START> annotationsAdminPage.activateAnnotations(); <END> annotationsAdminPage.displayAnnotationsByDefault(); annotationsAdminPage.displayAnnotationsHighlightByDefault(); annotationsAdminPage.clickSave(); annotableViewPage = new AnnotableViewPage(); adminPage = new AdministrationPage(); getUtil().createPage(SPACE_NAME, DOC_NAME, CONTENT, DOC_TITLE, "xwiki/1.0"); }</code><technical_language>do need do this</technical_language>

Target:
public void setUp() { super.setUp(); getUtil().deletePage(SPACE_NAME, DOC_NAME); adminPage.gotoPage(); annotationsAdminPage = adminPage.clickAnnotationsSection(); annotationsAdminPage.activateAnnotations(); annotationsAdminPage.displayAnnotationsByDefault(); annotationsAdminPage.displayAnnotationsHighlightByDefault(); annotationsAdminPage.clickSave(); annotatableViewPage = new AnnotatableViewPage(); adminPage = new AdministrationPage(); getUtil().createPage(SPACE_NAME, DOC_NAME, CONTENT, DOC_TITLE, "xwiki/1.0"); }