auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private boolean branchExists(String branchName) throws GerritException { BranchInfo[] branches = reviewHarness.getAdminClient().getRemoteProjectBranches("org.eclipse.mylyn.test", new NullProgressMonitor()); for (BranchInfo branch : branches) { <START> if (branch.getRef().endsWith(branchName)) { <END> return true; } } return false; }</code><technical_language>split "/" get segment, avoid degenerate case "refs/for/lalabranch", "refs/for/lalalabranch". matter for this case, for future usage</technical_language>

Target:
private boolean branchExists(String branchName) throws GerritException { BranchInfo[] branches = reviewHarness.getAdminClient().getRemoteProjectBranches("org.eclipse.mylyn.test", new NullProgressMonitor()); for (BranchInfo branch : branches) { String branchRef = StringUtils.trimToEmpty(StringUtils.substringAfterLast(branch.getRef(), "/")); if (branchRef.equals(branchName)) { return true; } } return false; }
Source:
<code>public synchronized void dispose() { if (getIndexer() != null) { getIndexer().dispose(); } <START> @NonNull <END> Iterable<IAnalysisModule> analysisModules = getAnalysisModules(); for (IAnalysisModule module : analysisModules) { module.dispose(); } fAnalysisModules.clear(); super.dispose(); }</code><technical_language>Remove put line</technical_language>

Target:
public synchronized void dispose() { if (getIndexer() != null) { getIndexer().dispose(); } Iterable<IAnalysisModule> analysisModules = getAnalysisModules(); for (IAnalysisModule module : analysisModules) { module.dispose(); } fAnalysisModules.clear(); super.dispose(); }
Source:
<code>protected String generateVmConfiguration(VM vm, List<DiskImage> disks, Map<Guid, VmDevice> vmDevices) { if (vm.getInterfaces() == null || vm.getInterfaces().isEmpty()) { vm.setInterfaces(getVmNetworkInterfaceDao().getAllForVm(vm.getId())); } if (StringUtils.isEmpty(vm.getVmtName())) { VmTemplate t = getVmTemplateDao().get(vm.getVmtGuid()); vm.setVmtName(t.getName()); } if (vmDevices == null) { VmDeviceUtils.setVmDevices(vm.getStaticData()); } else { vm.getStaticData().setManagedDeviceMap(vmDevices); } if (disks == null) { disks = ImagesHandler.filterImageDisks(getDiskDao().getAllForVm(vm.getId()), false, true, true); <START> disks.addAll(ImagesHandler.filterDisksBasedOnCinder(getDiskDao().getAllForVm(vm.getId()))); <END> } for (DiskImage image : disks) { image.setStorageIds(null); } return new OvfManager().ExportVm(vm, new ArrayList<>(disks), ClusterUtils.getCompatibilityVersion(vm)); }</code><technical_language>verify returns active disks</technical_language>

Target:
protected String generateVmConfiguration(VM vm, List<DiskImage> disks, Map<Guid, VmDevice> vmDevices) { if (vm.getInterfaces() == null || vm.getInterfaces().isEmpty()) { vm.setInterfaces(getVmNetworkInterfaceDao().getAllForVm(vm.getId())); } if (StringUtils.isEmpty(vm.getVmtName())) { VmTemplate t = getVmTemplateDao().get(vm.getVmtGuid()); vm.setVmtName(t.getName()); } if (vmDevices == null) { VmDeviceUtils.setVmDevices(vm.getStaticData()); } else { vm.getStaticData().setManagedDeviceMap(vmDevices); } if (disks == null) { disks = ImagesHandler.filterImageDisks(getDiskDao().getAllForVm(vm.getId()), false, true, true); disks.addAll(ImagesHandler.filterDisksBasedOnCinder(getDiskDao().getAllForVm(vm.getId()), true)); } for (DiskImage image : disks) { image.setStorageIds(null); } return new OvfManager().ExportVm(vm, new ArrayList<>(disks), ClusterUtils.getCompatibilityVersion(vm)); }
Source:
<code><START> public TreeHash(HashCode treeHash, HashCode linearHash) { <END> this.treeHash = treeHash; this.linearHash = linearHash; }</code><technical_language>this constructor private access</technical_language>

Target:
private TreeHash(HashCode treeHash, HashCode linearHash) { this.treeHash = checkNotNull(treeHash, "treeHash"); this.linearHash = checkNotNull(linearHash, "linearHash"); }
Source:
<code>default String[] entityTokensGetNames( EntityType type, int[] entityTokenIds ) { IntFunction<String> mapper; if ( type == EntityType.NODE ) { mapper = this::labelGetName; } else if ( type == EntityType.RELATIONSHIP ) { mapper = this::relationshipTypeGetName; } else { <START> return new String[0]; <END> } String[] tokenNames = new String[entityTokenIds.length]; for ( int i = 0; i < entityTokenIds.length; i++ ) { tokenNames[i] = mapper.apply( entityTokenIds[i] ); } return tokenNames; }</code><technical_language>throwing exception? This a weird return value. mapping functions is natural expect result array of size input</technical_language>

Target:
default String[] entityTokensGetNames( EntityType type, int[] entityTokenIds ) { IntFunction<String> mapper; switch ( type ) { case NODE: mapper = this::labelGetName; break; case RELATIONSHIP: mapper = this::relationshipTypeGetName; break; default: throw new IllegalArgumentException( "Cannot lookup names for tokens of type: " + type ); } String[] tokenNames = new String[entityTokenIds.length]; for ( int i = 0; i < entityTokenIds.length; i++ ) { tokenNames[i] = mapper.apply( entityTokenIds[i] ); } return tokenNames; }
Source:
<code>public ClusterEventService getEventService() { <START> return eventingService; <END> }</code><technical_language>variable too</technical_language>

Target:
public ClusterEventService getEventService() { return eventService; }
Source:
<code>public void init() { <START> if (mDbHelper == null || mDbHelper.getAppId() != ProviderUtils.getSeatedOrInstallingAppId()) { <END> String dbName = ProviderUtils.getProviderDbName( ProviderUtils.ProviderType.FORMS, ProviderUtils.getSeatedOrInstallingAppId()); mDbHelper = new DatabaseHelper(CommCareApplication._(), dbName); } }</code><technical_language>worries a bit seated installed notion, concerns end thinking a seated "installing" app time. Is some sort of consistency checking ensure a seated app set installing app, installing app seat</technical_language>

Target:
public void init() { String appId = ProviderUtils.getSandboxedAppId(); if (mDbHelper == null || mDbHelper.getAppId() != appId) { String dbName = ProviderUtils.getProviderDbName(ProviderUtils.ProviderType.FORMS, appId); mDbHelper = new DatabaseHelper(CommCareApplication._(), dbName, appId); } }
Source:
<code>private void toggleNature(final IProject project) { try { PlatformUI.getWorkbench().getProgressService().run(true, false, new <START> WorkspaceModifyOperation(ResourcesPlugin.getWorkspace().getRuleFactory().createRule(ResourcesPlugin.getWorkspace().getRoot())) <END> { @Override protected void execute(IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException { try { if (ModelingProject.hasModelingProjectNature(project)) { ModelingProjectManager.INSTANCE.removeModelingNature(project, monitor); } else { ModelingProjectManager.INSTANCE.convertToModelingProject(project, monitor); } } catch (CoreException e) { UICallBack uiCallback = SiriusEditPlugin.getPlugin().getUiCallback(); if (uiCallback != null) { uiCallback.openError(Messages.ModelingToggleNatureAction_errorDialogTitle, MessageFormat.format(Messages.ModelingToggleNatureAction_errorDialogMessage, e.getMessage())); } } } }); } catch (final InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } throw new RuntimeException(e); } catch (final InterruptedException e) { throw new RuntimeException(e); } }</code><technical_language>IWorkspaceRoot is ISchedulingRule, createRule() resources created</technical_language>

Target:
private void toggleNature(final IProject project) { try { PlatformUI.getWorkbench().getProgressService().run(true, false, new WorkspaceModifyOperation(ResourcesPlugin.getWorkspace().getRoot()) { @Override protected void execute(IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException { try { if (ModelingProject.hasModelingProjectNature(project)) { ModelingProjectManager.INSTANCE.removeModelingNature(project, monitor); } else { ModelingProjectManager.INSTANCE.convertToModelingProject(project, monitor); } } catch (CoreException e) { UICallBack uiCallback = SiriusEditPlugin.getPlugin().getUiCallback(); if (uiCallback != null) { uiCallback.openError(Messages.ModelingToggleNatureAction_errorDialogTitle, MessageFormat.format(Messages.ModelingToggleNatureAction_errorDialogMessage, e.getMessage())); } } } }); } catch (final InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } throw new RuntimeException(e); } catch (final InterruptedException e) { throw new RuntimeException(e); } }
Source:
<code>public void getBiome(BlockPos pos, CallbackInfoReturnable<Biome> ci) { if (!this.isCubicWorld()) return; ICube cube = this.getCubeCache().getLoadedCube(Coords.blockToCube(pos.getX()),Coords.blockToCube(pos.getY()),Coords.blockToCube(pos.getZ())); if (cube == null) <START> return; <END> Biome biome = cube.getBiome(pos, provider.getBiomeProvider()); ci.setReturnValue(biome); ci.cancel(); }</code><technical_language>if cube is null, try column</technical_language>

Target:
public void getBiome(BlockPos pos, CallbackInfoReturnable<Biome> ci) { if (!this.isCubicWorld()) return; ICube cube = this.getCubeCache().getLoadedCube(Coords.blockToCube(pos.getX()),Coords.blockToCube(pos.getY()),Coords.blockToCube(pos.getZ())); if (cube == null) return; Biome biome = cube.getBiome(pos); ci.setReturnValue(biome); ci.cancel(); }
Source:
<code>public <T> T readValue(@Nonnull final IMAPResponse[] content, @Nonnull final Class<T> valueType, @Nonnull final FetchItem[] extensionItems) throws ImapAsyncClientException { if (valueType == StoreResult.class) { <START> return (T) parser.parseToStoreResult(content, extensionItems); <END> } if (valueType == FetchResult.class) { return (T) parser.parseToFetchResult(content, extensionItems); } throw new ImapAsyncClientException(FailureType.UNKNOWN_PARSE_RESULT_TYPE); }</code><technical_language>merge readValue method</technical_language>

Target:
public <T> T readValue(@Nonnull final IMAPResponse[] content, @Nonnull final Class<T> valueType, @Nonnull final FetchItem[] extensionItems) throws ImapAsyncClientException { if (valueType == FetchResult.class) { return (T) parser.parseToFetchResult(content, extensionItems); } throw new ImapAsyncClientException(FailureType.UNKNOWN_PARSE_RESULT_TYPE); }
Source:
<code>public void testCreatingNewVariable() { final String variableName = "testVariable"; final int intToChange = 28; checkIfBrickAtPositionShowsString(0, R.string.brick_when_started); checkIfBrickAtPositionShowsString(setBrickPosition, R.string.brick_ask_label); checkIfBrickAtPositionShowsString(setBrickPosition, R.string.brick_ask_store); <START> onView(withId(R.id.brick_ask_spinner)).perform(click()); <END> onView(withId(R.id.dialog_formula_editor_data_name_edit_text)).perform(typeText(variableName)); onView(withText(R.string.ok)).perform(click()); }</code><technical_language>please utility functions achieve that. (see createNewVariableOnSpinnerInitial createNewVariableOnSpinner)</technical_language>

Target:
public void testCreatingNewVariable() { final String firstVariableName = "firstVariable"; final String secondVariableName = "secondVariable"; checkIfBrickAtPositionShowsString(0, R.string.brick_when_started); checkIfBrickAtPositionShowsString(brickPosition, R.string.brick_ask_label); checkIfBrickAtPositionShowsString(brickPosition, R.string.brick_ask_store); createNewVariableOnSpinnerInitial(R.id.brick_ask_spinner, brickPosition, firstVariableName); createNewVariableOnSpinner(R.id.brick_ask_spinner, brickPosition, secondVariableName); }
Source:
<code>private Guid mockSourceImage() { Guid imageId = Guid.NewGuid(); DiskImage image = new DiskImage(); image.setImageId(imageId); <START> ArrayList<Guid> list = new ArrayList<Guid>(); <END> list.add(STORAGE_DOMAIN_ID); image.setstorage_ids(list); image.setActualSize(4); image.setsize(40); doReturn(Collections.singletonList(image)).when(cmd).getSourceImages(); return imageId; }</code><technical_language>this defined a List<DiskImage></technical_language>

Target:
private Guid mockSourceImage() { Guid imageId = Guid.NewGuid(); DiskImage image = new DiskImage(); image.setImageId(imageId); ArrayList<Guid> list = new ArrayList<Guid>(); list.add(STORAGE_DOMAIN_ID); image.setstorage_ids(list); image.setActualSize(IMAGE_ACTUAL_SIZE_GB); image.setsize(40); doReturn(Collections.singletonList(image)).when(cmd).getSourceImages(); return imageId; }
Source:
<code>private void validateAgentBody(Body body) throws ParamValidationException, PropertyValidationException { <START> if (!(body instanceof EdmAgentBody)) { <END> throw new ParamValidationException(I18nConstants.INVALID_PROPERTY_VALUE, I18nConstants.INVALID_PROPERTY_VALUE, new String[] { "tag.body.type", ResourceTypes.AGENT.getJsonValue() }); } validateAgentEntityBody(body); }</code><technical_language>check based class, body.getType, validation of body type for transcriptions</technical_language>

Target:
private void validateAgentBody(Body body) throws ParamValidationException, PropertyValidationException { if (body.getType() == null || !(body.getType().size() == 1)) { } else if (!ResourceTypes.AGENT.hasJsonValue(body.getType().get(0))) { throw new PropertyValidationException(I18nConstants.INVALID_PROPERTY_VALUE, I18nConstants.INVALID_PROPERTY_VALUE, new String[] { "agent.body.type" }); } validateAgentEntityBody(body); }
Source:
<code>private String compose(String str, Map<String, Pair<String, String>> stringParts, int maxNumericSuffixLength) { if (str != null && <START> stringParts.containsKey(str)) <END> { final Pair<String, String> stringPartsPair = stringParts.get(str); return lpadSuffixWithZeroes(stringPartsPair.getFirst(), stringPartsPair.getSecond(), maxNumericSuffixLength); } else { return str; } }</code><technical_language>this containsKey false</technical_language>

Target:
private String compose(String str, Map<String, Pair<String, String>> stringParts, int maxNumericSuffixLength) { final Pair<String, String> stringPartsPair = str == null ? null : stringParts.get(str); if (stringPartsPair == null) { return str; } else { return lpadSuffixWithZeroes(stringPartsPair.getFirst(), stringPartsPair.getSecond(), maxNumericSuffixLength); } }
Source:
<code>public ISYActiveBindingConfig(Map<Object, Object> config) { this.logger.info( "OpenHab Binding Configuration(refresh='{}',upnp='{}',uuid='{}',ip='{}',port='{}',user='{}',password='{}')", config.get("refresh"), config.get("upnp"), config.get("uuid"), config.get("ip"), config.get("port"), config.get("user"), "xxxxxx"); if (isNotBlank((String) config.get("refresh"))) { refreshInterval = Long.parseLong((String) config.get("refresh")); } if (isNotBlank((String) config.get("user")) && isNotBlank((String) config.get("password"))) { this.user = (String) config.get("user"); this.password = (String) config.get("password"); } else { this.logger.warn("No user/password specified"); } if (isNotBlank((String) config.get("upnp"))) { useUpnp = Boolean.parseBoolean((String) config.get("upnp")); } if (!useUpnp && isNotBlank((String) config.get("uuid")) && isNotBlank((String) config.get("ip")) && isNotBlank((String) config.get("port"))) { this.uuid = (String) config.get("uuid"); this.ipAddress = (String) config.get("ip"); try { this.port = Integer.parseInt((String) config.get("port")); } catch (NumberFormatException ne) { <START> this.logger.error("Not a valid port number"); <END> throw new RuntimeException("Not a valid port number", ne); } if (this.port < 0 || this.port > 65535) { this.logger.error("Port out of range (0-65535)"); throw new NumberFormatException("Invalid port"); } } else { this.logger.info("Using UPNP for ISY connection."); } }</code><technical_language>This a warn instead of error</technical_language>

Target:
public ISYActiveBindingConfig(Map<Object, Object> config) { this.logger.info( "OpenHab Binding Configuration(refresh='{}',upnp='{}',uuid='{}',ip='{}',port='{}',user='{}',password='{}')", config.get("refresh"), config.get("upnp"), config.get("uuid"), config.get("ip"), config.get("port"), config.get("user"), "xxxxxx"); if (isNotBlank((String) config.get("refresh"))) { refreshInterval = Long.parseLong((String) config.get("refresh")); } if (isNotBlank((String) config.get("user")) && isNotBlank((String) config.get("password"))) { this.user = (String) config.get("user"); this.password = (String) config.get("password"); } else { this.logger.warn("No user/password specified"); } if (isNotBlank((String) config.get("upnp"))) { useUpnp = Boolean.parseBoolean((String) config.get("upnp")); } if (!useUpnp && isNotBlank((String) config.get("uuid")) && isNotBlank((String) config.get("ip")) && isNotBlank((String) config.get("port"))) { this.uuid = (String) config.get("uuid"); this.ipAddress = (String) config.get("ip"); try { this.port = Integer.parseInt((String) config.get("port")); } catch (NumberFormatException ne) { this.logger.warn("Not a valid port number"); throw new RuntimeException("Not a valid port number", ne); } if (this.port < 0 || this.port > 65535) { this.logger.warn("Port out of range (0-65535)"); throw new NumberFormatException("Invalid port"); } } else { this.logger.info("Using UPNP for ISY connection."); } }
Source:
<code>private static ClassLoader createCombinedClassLoader(String testPlugin) throws BundleException { ClassLoader testClassLoader = getBundleClassLoader(testPlugin); ClassLoader contextFinder = Thread.currentThread().getContextClassLoader(); ClassLoader surefireClassLoader = ForkedBooter.class.getClassLoader(); <START> return new CombinedClassLoader(testClassLoader, new TychoContextFinder(contextFinder.getParent()), <END> surefireClassLoader); }</code><technical_language>I context finder in list classloading in this order</technical_language>

Target:
private static ClassLoader createCombinedClassLoader(String testPlugin) throws BundleException { ClassLoader testClassLoader = getBundleClassLoader(testPlugin); ClassLoader contextFinder = Thread.currentThread().getContextClassLoader(); ClassLoader surefireClassLoader = ForkedBooter.class.getClassLoader(); return new CombinedClassLoader(testClassLoader, surefireClassLoader, new TychoContextFinder(contextFinder.getParent())); }
Source:
<code>private Patient cursorToPatient(Cursor cursor) { Patient patient = new Patient(); Person person = new Person(); patient.setId(cursor.getLong(cursor.getColumnIndex(PatientTable.Column.ID))); patient.setDisplay(cursor.getString(cursor.getColumnIndex(PatientTable.Column.DISPLAY))); patient.setUuid(cursor.getString(cursor.getColumnIndex(PatientTable.Column.UUID))); patient.setEncounters(cursor.getString(cursor.getColumnIndex(PatientTable.Column.ENCOUNTERS))); PatientIdentifier patientIdentifier = new PatientIdentifier(); patientIdentifier.setIdentifier(cursor.getString(cursor.getColumnIndex(PatientTable.Column.IDENTIFIER))); patient.getIdentifiers().add(patientIdentifier); PersonName personName = new PersonName(); personName.setGivenName(cursor.getString(cursor.getColumnIndex(PatientTable.Column.GIVEN_NAME))); personName.setMiddleName(cursor.getString(cursor.getColumnIndex(PatientTable.Column.MIDDLE_NAME))); personName.setFamilyName(cursor.getString(cursor.getColumnIndex(PatientTable.Column.FAMILY_NAME))); person.getNames().add(personName); person.setGender(cursor.getString(cursor.getColumnIndex(PatientTable.Column.GENDER))); person.setBirthdate(cursor.getString(cursor.getColumnIndex(PatientTable.Column.BIRTH_DATE))); <START> if (null != cursor.getBlob(cursor.getColumnIndex(PatientTable.Column.PHOTO))) { <END> person.setPhoto(byteArrayToBitmap(cursor.getBlob(cursor.getColumnIndex(PatientTable.Column.PHOTO)))); } person.getAddresses().add(cursorToAddress(cursor)); patient.setPerson(person); return patient; }</code><technical_language>increment database index updated (file integers.xml) ? I need this null check</technical_language>

Target:
private Patient cursorToPatient(Cursor cursor) { Patient patient = new Patient(); Person person = new Person(); patient.setId(cursor.getLong(cursor.getColumnIndex(PatientTable.Column.ID))); patient.setDisplay(cursor.getString(cursor.getColumnIndex(PatientTable.Column.DISPLAY))); patient.setUuid(cursor.getString(cursor.getColumnIndex(PatientTable.Column.UUID))); patient.setEncounters(cursor.getString(cursor.getColumnIndex(PatientTable.Column.ENCOUNTERS))); PatientIdentifier patientIdentifier = new PatientIdentifier(); patientIdentifier.setIdentifier(cursor.getString(cursor.getColumnIndex(PatientTable.Column.IDENTIFIER))); patient.getIdentifiers().add(patientIdentifier); PersonName personName = new PersonName(); personName.setGivenName(cursor.getString(cursor.getColumnIndex(PatientTable.Column.GIVEN_NAME))); personName.setMiddleName(cursor.getString(cursor.getColumnIndex(PatientTable.Column.MIDDLE_NAME))); personName.setFamilyName(cursor.getString(cursor.getColumnIndex(PatientTable.Column.FAMILY_NAME))); person.getNames().add(personName); person.setGender(cursor.getString(cursor.getColumnIndex(PatientTable.Column.GENDER))); person.setBirthdate(cursor.getString(cursor.getColumnIndex(PatientTable.Column.BIRTH_DATE))); byte[] photoByteArray = cursor.getBlob(cursor.getColumnIndex(PatientTable.Column.PHOTO)); if (photoByteArray != null) person.setPhoto(byteArrayToBitmap(photoByteArray)); person.getAddresses().add(cursorToAddress(cursor)); patient.setPerson(person); return patient; }
Source:
<code><START> public void postSplit(ObserverContext<RegionCoprocessorEnvironment> ctx, HRegion l, HRegion r) throws IOException { <END> HRegion region = ctx.getEnvironment().getRegion(); if (familyMap != null) { familyMap.clear(); } Scan scan = createScan(); RegionScanner scanner = null; int count = 0; try { scanner = region.getScanner(scan); count = scanRegion(scanner, count); } catch (IOException e) { LOG.error(e); throw e; } finally { if (scanner != null) { try { writeStatsToStatsTable(null, region, scanner); } catch (IOException e) { LOG.error(e); throw e; } } } }</code><technical_language>+1. Nice - automatically invoking analyze a split occurs? clearing stats for previous unsplit region out of date (and do this update atomically)</technical_language>

Target:
public void postSplit(ObserverContext<RegionCoprocessorEnvironment> ctx, HRegion l, HRegion r) throws IOException { HRegion region = ctx.getEnvironment().getRegion(); TableName table = region.getRegionInfo().getTable(); if (!table.getNameAsString().equals(PhoenixDatabaseMetaData.SYSTEM_STATS_NAME)) { if (familyMap != null) { familyMap.clear(); } List<Mutation> mutations = Lists.newArrayListWithExpectedSize(3); long currentTime = TimeKeeper.SYSTEM.getCurrentTime(); Configuration conf = ctx.getEnvironment().getConfiguration(); if(LOG.isDebugEnabled()) { LOG.debug("Collecting stats for the daughter region "+l.getRegionInfo()); } collectStatsForSplitRegions(conf, l, region, true, mutations, currentTime); clear(); if(LOG.isDebugEnabled()) { LOG.debug("Collecting stats for the daughter region "+r.getRegionInfo()); } collectStatsForSplitRegions(conf, r, region, false, mutations, currentTime); if (LOG.isDebugEnabled()) { LOG.debug("Committing stats for the daughter regions as part of split " + r.getRegionInfo()); } commitStats(mutations); } }
Source:
<code>public static void leaveBreadcrumb(@NonNull final byte[] nameBytes, @NonNull final BreadcrumbType type) { String name = new String(nameBytes, Charset.defaultCharset()); <START> getClient().leaveBreadcrumb(name, type, new HashMap<String, String>()); <END> }</code><technical_language>Collections.<String, String>emptyMap() avoid unnecessary allocations this hot path</technical_language>

Target:
public static void leaveBreadcrumb(@NonNull final byte[] nameBytes, @NonNull final BreadcrumbType type) { if (nameBytes == null) { return; } String name = new String(nameBytes, UTF8Charset); getClient().leaveBreadcrumb(name, type, Collections.<String, String>emptyMap()); }
Source:
<code><START> private String getHashCode(String text) { <END> try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); byte[] hash = messageDigest.digest(text.getBytes(StandardCharsets.UTF_8)); StringBuffer hexString = new StringBuffer(); for (byte element : hash) { String hex = Integer.toHexString(0xff & element); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { return String.valueOf(text.hashCode()); } }</code><technical_language>Is this reversible? text.hashCode()? worried collisions</technical_language>

Target:
private String getHashCode(String text) { return Integer.toUnsignedString(text.hashCode()); }
Source:
<code>private List<IContainer> walkDirectory(SubMonitor loopMonitor) throws CoreException { List<IContainer> membersContainer = new ArrayList<>(); <START> IResource[] members = root.members(IContainer.INCLUDE_HIDDEN); loopMonitor.setWorkRemaining(members.length); for (IResource member : members) { int type = member.getType(); if (type != IResource.FILE && !((Resource) member).isFiltered()) { <END> membersContainer.add((IContainer) member); } loopMonitor.split(1); } return membersContainer; }</code><technical_language>This is efficient IFileStore.getChildInfos Resource.filterChildren</technical_language>

Target:
private List<Path> walkDirectory(SubMonitor loopMonitor) throws IOException { List<Path> childrenPath = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(root, IS_DIRECTORY)) { for (Path item : stream) { loopMonitor.setWorkRemaining(100).split(1); childrenPath.add(item); } } return childrenPath; }
Source:
<code>public void getOrderGroupsByPatient_shouldGetOrderGroupsFromMultiplePatients() { <START> OrderGroup orderGroupA = new OrderGroup(); <END> OrderGroup orderGroupB = new OrderGroup(); OrderGroup orderGroupC = new OrderGroup(); Patient existingPatient1 = Context.getPatientService().getPatient(7); Patient existingPatient2 = Context.getPatientService().getPatient(8); orderGroupA.setPatient(existingPatient1); orderGroupB.setPatient(existingPatient1); orderGroupC.setPatient(existingPatient2); assertEquals(0, dao.getOrderGroupsByPatient(existingPatient1).size()); assertEquals(0, dao.getOrderGroupsByPatient(existingPatient2).size()); dao.saveOrderGroup(orderGroupA); dao.saveOrderGroup(orderGroupB); dao.saveOrderGroup(orderGroupC); assertEquals(2, dao.getOrderGroupsByPatient(existingPatient1).size()); assertEquals(1, dao.getOrderGroupsByPatient(existingPatient2).size()); }</code><technical_language>Instead of creating saving this fly fetching them, put in a dataset file fetch there? examples of files: <LINK_0></technical_language>

Target:
public void getOrderGroupsByPatient_shouldGetOrderGroupsFromMultiplePatients() { Patient existingPatient1 = Context.getPatientService().getPatient(7); Patient existingPatient2 = Context.getPatientService().getPatient(8); List<OrderGroup> ordergroups1 = Context.getOrderService().getOrderGroupsByPatient(existingPatient1); List<OrderGroup> ordergroups2 = Context.getOrderService().getOrderGroupsByPatient(existingPatient2); assertEquals(2, ordergroups1.size()); assertEquals(1, ordergroups2.size()); }
Source:
<code>public synchronized Map<String, Object> getLearnerHandlerInfo() { <START> Map<String, Object> info = new LinkedHashMap<>(); <END> info.put("remote_socket_address", getRemoteAddress()); info.put("sid", getSid()); info.put("established", getEstablished()); info.put("queued_packets", queuedPackets.size()); info.put("queued_packets_size", queuedPacketsSize.get()); info.put("packets_received", packetsReceived.longValue()); info.put("packets_sent", packetsSent.longValue()); info.put("requests", requestsReceived.longValue()); info.put("last_zxid", getLastZxid()); return info; }</code><technical_language>a simple pre sized HashMap</technical_language>

Target:
public synchronized Map<String, Object> getLearnerHandlerInfo() { Map<String, Object> info = new LinkedHashMap<>(9); info.put("remote_socket_address", getRemoteAddress()); info.put("sid", getSid()); info.put("established", getEstablished()); info.put("queued_packets", queuedPackets.size()); info.put("queued_packets_size", queuedPacketsSize.get()); info.put("packets_received", packetsReceived.longValue()); info.put("packets_sent", packetsSent.longValue()); info.put("requests", requestsReceived.longValue()); info.put("last_zxid", getLastZxid()); return info; }
Source:
<code>public void testList() throws IOException, StripeException { final Customer customer = Customer.retrieve(CUSTOMER_ID); Map<String, Object> params = new HashMap<String, Object>(); params.put("object", "bank_account"); BankAccount stubbedBankAccount = APIResource.GSON.fromJson( getResourceAsString("/api_fixtures/bank_account.json"), BankAccount.class); ExternalAccountCollection stubbedCollection = new ExternalAccountCollection(); List<ExternalAccount> stubbedData = new LinkedList<ExternalAccount>(); stubbedData.add(stubbedBankAccount); stubbedCollection.setData(stubbedData); stubRequest( APIResource.RequestMethod.GET, String.format("/v1/customers/%s/sources", customer.getId()), params, ExternalAccountCollection.class, stubbedCollection.toJson() <START> ); <END> final ExternalAccountCollection externalAccounts = customer.getSources().list(params); assertNotNull(externalAccounts); assertEquals(1, externalAccounts.getData().size()); verifyRequest( APIResource.RequestMethod.GET, String.format("/v1/customers/%s/sources", customer.getId()) ); BankAccount bankAccount = (BankAccount) externalAccounts.getData().get(0); assertNotNull(bankAccount); }</code><technical_language>I understand this one. a fixture is a list already? I I for other tests</technical_language>

Target:
public void testList() throws IOException, StripeException { final Customer customer = Customer.retrieve(CUSTOMER_ID); Map<String, Object> params = new HashMap<String, Object>(); params.put("object", "bank_account"); params.put("limit", 1); final BankAccount stubbedBankAccount = APIResource.GSON.fromJson( getResourceAsString("/api_fixtures/bank_account.json"), BankAccount.class); final ExternalAccountCollection stubbedCollection = new ExternalAccountCollection(); final List<ExternalAccount> stubbedData = new LinkedList<ExternalAccount>(); stubbedData.add(stubbedBankAccount); stubbedCollection.setData(stubbedData); stubRequest( APIResource.RequestMethod.GET, String.format("/v1/customers/%s/sources", customer.getId()), params, ExternalAccountCollection.class, stubbedCollection.toJson() ); final ExternalAccountCollection externalAccounts = customer.getSources().list(params); assertNotNull(externalAccounts); assertEquals(1, externalAccounts.getData().size()); verifyRequest( APIResource.RequestMethod.GET, String.format("/v1/customers/%s/sources", customer.getId()) ); final BankAccount bankAccount = (BankAccount) externalAccounts.getData().get(0); assertNotNull(bankAccount); }
Source:
<code>public LoginContext loginAs(String username) throws LoginException { boolean isAdministrator = SecurityConstants.ADMINISTRATOR.equalsIgnoreCase(username); Principal principal = new UserPrincipal(username, null, false, isAdministrator); ClientLoginModule.getThreadLocalLogin().push(principal, null, null); return new LoginContext("nuxeo-client-login") { <START> @Override <END> public void logout() throws LoginException { ClientLoginModule.getThreadLocalLogin().pop(); } }; }</code><technical_language>I assume in backport context do Framework.login(username, username) in master</technical_language>

Target:
public LoginContext loginAs(String username) throws LoginException { boolean isAdministrator = SecurityConstants.ADMINISTRATOR.equals(username); Principal principal = new UserPrincipal(username, null, false, isAdministrator); ClientLoginModule.getThreadLocalLogin().push(principal, null, null); return new LoginContext("nuxeo-client-login") { @Override public void logout() throws LoginException { ClientLoginModule.getThreadLocalLogin().pop(); } }; }
Source:
<code>private boolean listWindows(Socket client) { boolean result = true; BufferedSink out = null; try { mWindowsLock.readLock().lock(); out = Okio.buffer(Okio.sink(client.getOutputStream())); for (Entry<View, String> entry : mWindows.entrySet()) { <START> out.writeUtf8(Integer.toHexString(System.identityHashCode(entry.getKey()))); <END> out.writeUtf8CodePoint(' '); out.writeUtf8(entry.getValue()); out.writeUtf8CodePoint('\n'); } out.writeUtf8("DONE.\n"); out.flush(); } catch (Exception e) { result = false; } finally { mWindowsLock.readLock().unlock(); if (out != null) { try { out.close(); } catch (IOException e) { result = false; } } } return result; }</code><technical_language>out.writeHexadecimalUnsignedLong instead of call toHexString</technical_language>

Target:
private boolean listWindows(Socket client) { boolean result = true; BufferedSink out = null; try { mWindowsLock.readLock().lock(); out = Okio.buffer(Okio.sink(client)); for (Entry<View, String> entry : mWindows.entrySet()) { out.writeHexadecimalUnsignedLong(System.identityHashCode(entry.getKey())); out.writeUtf8CodePoint(' '); out.writeUtf8(entry.getValue()); out.writeUtf8CodePoint('\n'); } out.writeUtf8("DONE.\n"); out.flush(); } catch (Exception e) { result = false; } finally { mWindowsLock.readLock().unlock(); if (out != null) { try { out.close(); } catch (IOException e) { result = false; } } } return result; }
Source:
<code>public DepositState getState(String depositUUID) { DepositState result = null; try (Jedis jedis = getJedisPool().getResource()) { String state = jedis.hget(DEPOSIT_STATUS_PREFIX + depositUUID, DepositField.state.name()); result = DepositState.valueOf(state); <START> } catch (IllegalArgumentException | NullPointerException e) { <END> log.debug("Failed to retrieve state for deposit {}", depositUUID, e); } return result; }</code><technical_language>I code changes, do want catching a NPE here? testing for null a path code takes action better</technical_language>

Target:
public DepositState getState(String depositUUID) { try (Jedis jedis = getJedisPool().getResource()) { String state = jedis.hget(DEPOSIT_STATUS_PREFIX + depositUUID, DepositField.state.name()); if (state == null) { log.debug("No state was found for deposit {}", depositUUID); return null; } return DepositState.valueOf(state); } }
Source:
<code>public CatalogInitialization getCatalogInitialization() { <START> if (catalogInitialization!=null) return catalogInitialization; <END> synchronized (this) { if (catalogInitialization!=null) return catalogInitialization; CatalogInitialization ci = new CatalogInitialization(); setCatalogInitialization(ci); return ci; } }</code><technical_language>Double-checked locking is broken in Java, declare variable volatile (<LINK_0> This code is performance sensitive, delete this line code simpler</technical_language>

Target:
public CatalogInitialization getCatalogInitialization() { synchronized (catalogInitMutex) { if (catalogInitialization!=null) return catalogInitialization; CatalogInitialization ci = new CatalogInitialization(); setCatalogInitialization(ci); return ci; } }
Source:
<code>public void flush(String source) { LOG.info("Trying to flush pending sends messages: {}", pendingFutures.size(), pendingFutures.keySet()); <START> while (!pendingFutures.isEmpty()) { <END> try { Thread.sleep(FLUSH_SLEEP_TIME_MILLIS); } catch (InterruptedException e) { String msg = "Flush failed with error"; LOG.error(msg, e); throw new SamzaException(msg, e); } } if (sendExceptionOnCallback != null) { String msg = "Sending one of the message failed during flush"; Throwable throwable = sendExceptionOnCallback; sendExceptionOnCallback = null; LOG.error(msg, throwable); throw new SamzaException(msg, throwable); } LOG.info("Flush succeeded."); }</code><technical_language>This needs a bounded wait</technical_language>

Target:
public synchronized void flush(String source) { LOG.debug("Trying to flush pending sends messages.", pendingFutures.size()); checkCallbackThrowable("Received exception on message send"); CompletableFuture<Void> future = CompletableFuture .allOf(pendingFutures.toArray(new CompletableFuture[pendingFutures.size()])); try { future.get(DEFAULT_FLUSH_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { String msg = "Flush failed with error"; throw new SamzaException(msg, e); } checkCallbackThrowable("Sending one or more of the messages failed during flush"); }
Source:
<code>public void setUp() { <START> ws = new WsActionTester(new ShowAction(db.getDbClient(), parser, duplicationsJsonWriter, userSessionRule, TestComponentFinder.from(db))); <END> db.getDbClient().metricDao().insert(db.getSession(), dataMetric); db.commit(); }</code><technical_language>This inline line 58</technical_language>

Target:
public void setUp() { db.getDbClient().metricDao().insert(db.getSession(), dataMetric); db.commit(); }
Source:
<code>public VdcReturnValueBase RunAction(VdcActionType actionType, VdcActionParametersBase parameters) { VdcReturnValueBase returnValue = isModeAllowToRunAction(actionType); if (returnValue != null) { return returnValue; <START> } <END> return runActionImpl(actionType, parameters, false, null); }</code><technical_language>condition, logic is bool</technical_language>

Target:
public VdcReturnValueBase RunAction(VdcActionType actionType, VdcActionParametersBase parameters) { VdcReturnValueBase returnValue = notAllowToRunAction(actionType); if (returnValue != null) { return returnValue; } return runActionImpl(actionType, parameters, false, null); }
Source:
<code>private void saveIndex() { File storeFolder = folders.getBase(); <START> if (storeFolder.exists()) <END> { File index = new File(storeFolder, INDEX_FILE_NAME); Files.remove(index); try { OutputStream stream = new FileOutputStream(index); ObjectOutputStream oos = new ObjectOutputStream(stream); try { List<DiskData> list = new ArrayList<>(diskDatas.size()); for (DiskData diskData : diskDatas.values()) { if (diskData.sessionIdentifier != null) { list.add(diskData); } } oos.writeObject(list); } finally { stream.close(); oos.close(); } } catch (Exception e) { log.error("Couldn't write DiskPageStore index to file " + index + ".", e); } } }</code><technical_language>try create if exist</technical_language>

Target:
private void saveIndex() { File storeFolder = folders.getBase(); if (storeFolder.exists()) { File index = new File(storeFolder, INDEX_FILE_NAME); Files.remove(index); try (OutputStream stream = new FileOutputStream(index)) { ObjectOutputStream oos = new ObjectOutputStream(stream); List<DiskData> list = new ArrayList<>(diskDatas.size()); for (DiskData diskData : diskDatas.values()) { if (diskData.sessionIdentifier != null) { list.add(diskData); } } oos.writeObject(list); } catch (Exception e) { log.error("Couldn't write DiskPageStore index to file " + index + ".", e); } } }
Source:
<code>private static Block buildSequenceBlock(long start, int count, RowsToKeepResult rowsToKeep) { BlockBuilder builder = BIGINT.createFixedSizeBlockBuilder(count); for (int i = 0; i < count; i++) { BIGINT.writeLong(builder, start + i); } if (rowsToKeep.isKeepAll()) { return builder.build(); } <START> else { <END> return builder.build().getPositions(rowsToKeep.elements(), 0, count); } }</code><technical_language>redundant</technical_language>

Target:
private static Block buildSequenceBlock(long start, int count, RowsToKeepResult rowsToKeep) { BlockBuilder builder = BIGINT.createFixedSizeBlockBuilder(count); for (int i = 0; i < count; i++) { if (rowsToKeep.keepAll() || rowsToKeep.getRowsToKeep().contains(i)) { BIGINT.writeLong(builder, start + i); } } return builder.build(); }
Source:
<code><START> protected void setup(IProgressMonitor monitor) <END> throws SarosCancellationException { if (fileTransferManager == null) throw new LocalCancellationException( "not connected to a XMPP server", CancelOption.DO_NOT_NOTIFY_PEER); transferListener = new TransferListener(TRANSFER_ID + getID()); fileTransferManager.addFileTransferListener(transferListener); }</code><technical_language>is description this method does. setup something, ? if I inherit this class do want some SMACK API I NOP this method</technical_language>

Target:
protected void setup(IProgressMonitor monitor) throws SarosCancellationException { if (fileTransferManager == null) throw new LocalCancellationException( "not connected to a XMPP server", CancelOption.DO_NOT_NOTIFY_PEER); transferListener = new TransferListener(TRANSFER_ID_PREFIX + getID()); fileTransferManager.addFileTransferListener(transferListener); }
Source:
<code>protected RollCycle decodeRollCycle(String retentionDuration) { if (retentionDuration == null || retentionDuration.isEmpty()) { return DAILY; } String rollingPeriod = retentionDuration.substring(retentionDuration.length() - 1); switch (rollingPeriod) { case SECOND_ROLLING_PERIOD: <START> return RollCycles.TEST_SECONDLY; <END> case MINUTE_ROLLING_PERIOD: return MINUTELY; case HOUR_ROLLING_PERIOD: return HOURLY; case DAY_ROLLING_PERIOD: return DAILY; default: throw new IllegalArgumentException("Unknown rolling period: " + rollingPeriod); } }</code><technical_language>static import too. I assume remove RollCycles import</technical_language>

Target:
protected RollCycle decodeRollCycle(String retentionDuration) { if (retentionDuration == null || retentionDuration.isEmpty()) { return DAILY; } String rollingPeriod = retentionDuration.substring(retentionDuration.length() - 1); switch (rollingPeriod) { case SECOND_ROLLING_PERIOD: return TEST_SECONDLY; case MINUTE_ROLLING_PERIOD: return MINUTELY; case HOUR_ROLLING_PERIOD: return HOURLY; case DAY_ROLLING_PERIOD: return DAILY; default: throw new IllegalArgumentException("Unknown rolling period: " + rollingPeriod); } }
Source:
<code>public void testExceptionWhenSubclassSetsInvalidDefaultValue() { try { app.createAndManageChild(EntitySpec.create(EntityProvidingDefaultValueForConfigKeyInRange.class)); fail("Expected exception when managing entity setting invalid default value"); } catch (Exception e) { Throwable t = Exceptions.getFirstThrowableOfType(e, ConstraintViolationException.class); <START> assertNotNull(t); <END> } }</code><technical_language>personal preference for like: if (Exceptions.getFirstThrowableOfType(e, ConstraintViolationException.class) == null) { throw e; } lose underlying exception - is fine, is a real pain a test fails non-deterministically in asfbot</technical_language>

Target:
public void testExceptionWhenSubclassSetsInvalidDefaultValue() { try { app.createAndManageChild(EntitySpec.create(EntityProvidingDefaultValueForConfigKeyInRange.class)); fail("Expected exception when managing entity setting invalid default value"); } catch (Exception e) { Throwable t = Exceptions.getFirstThrowableOfType(e, ConstraintViolationException.class); assertNotNull(t, "Original exception was: " + Exceptions.collapseText(e)); } }
Source:
<code>public static void loadSkins() { final int price = 9999; ironMan = new IronManSkin(price, "Iron Man", "iron_man"); captain = new CaptainSkin(price, "Captain", "captain"); andy = new AndySkin(price, "Andy", "andy"); noob = new NoobSkin(0, "Noob", "noob"); <START> boy = new BoySkin(price, "B-man", "b"); <END> plank = new PlankSkin(price, "Plank", "plank"); }</code><technical_language>I "b" is a bit short for a texture name. I suggest renaming "boy" "b_man". <review,naming</technical_language>

Target:
public static void loadSkins() { ironMan = new IronManSkin(); captain = new CaptainSkin(); andy = new AndySkin(); noob = new NoobSkin(); boy = new BoySkin(); plank = new PlankSkin(); }
Source:
<code>protected Set<Integer> getInternalSelections() { Set<Integer> indexes = super.getSelection(); Set<Integer> <START> internalIndexes <END> = indexes.stream() .mapToInt(index -> fInternalEntryList.indexOf((getResultTable().getEntries().get(index)))) .boxed() .collect(Collectors.toSet()); return internalIndexes; }</code><technical_language>a bit more specific</technical_language>

Target:
protected Set<Integer> getInternalSelections() { Set<Integer> indexes = super.getSelection(); Set<Integer> internalIndexes = indexes.stream() .mapToInt(index -> getResultTable().getEntries().indexOf((getResultTable().getEntries().get(index)))) .boxed() .collect(Collectors.toSet()); return internalIndexes; }
Source:
<code>public void testPackaging_ValidationSkipped() throws Exception { Verifier verifier = getVerifier("/target-platform/packagingKO", false); Map<String, String> args = new HashMap<String, String>(); args.put("tycho.target-platform-plugin.validation.skip", Boolean.TRUE.toString()); <START> verifier.executeGoal("validate"); <END> }</code><technical_language>verifyErrorFreeLog()</technical_language>

Target:
public void testPackaging_ValidationSkipped() throws Exception { Verifier verifier = getVerifier("/target-platform/packagingKO", false); verifier.setSystemProperty("tycho.target-platform-plugin.validation.skip", Boolean.TRUE.toString()); verifier.executeGoal("validate"); }
Source:
<code>public List<SharedWorkflows> sharedWorkflows(@ApiParam(hidden = true) @Auth User user) { final List<String> paths = this.permissionsInterface.workflowsSharedWithUser(user).values() .stream() .flatMap(List::stream) .collect(Collectors.toList()); List<Workflow> workflowList = workflowDAO.findByPaths(paths, false); <START> return this.permissionsInterface.workflowsSharedWithUser(user).entrySet().stream().map(e -> { <END> final List<Workflow> workflows = workflowList.stream() .filter(workflow -> e.getValue().contains(workflow.getWorkflowPath())) .collect(Collectors.toList()); return new SharedWorkflows(e.getKey(), workflows); }).collect(Collectors.toList()); }</code><technical_language>call this method twice. SAM this results in a call time external SAM service. save results calling do processing</technical_language>

Target:
public List<SharedWorkflows> sharedWorkflows(@ApiParam(hidden = true) @Auth User user) { final Map<Role, List<String>> workflowsSharedWithUser = this.permissionsInterface.workflowsSharedWithUser(user); final List<String> paths = workflowsSharedWithUser.values() .stream() .flatMap(List::stream) .collect(Collectors.toList()); List<Workflow> workflowList = workflowDAO.findByPaths(paths, false); return workflowsSharedWithUser.entrySet().stream().map(e -> { final List<Workflow> workflows = workflowList.stream() .filter(workflow -> e.getValue().contains(workflow.getWorkflowPath()) && !workflow.getUsers().contains(user)) .collect(Collectors.toList()); return new SharedWorkflows(e.getKey(), workflows); }).filter(sharedWorkflow -> sharedWorkflow.getWorkflows().size() > 0).collect(Collectors.toList()); }