auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void shouldGetThePrivateKeyFromUsersPreference() throws Exception { sshKeyStore = spy(new UserProfileSshKeyStore(API_ENDPOINT)); final String privateKey = "private key"; final String publicKey = "public key"; doReturn(ImmutableMap.of("ssh.key.private." + privateKey, "ssh.key.public." + publicKey)).when(sshKeyStore).getSshKeys(); doNothing().when(sshKeyStore).updateSshKeys(any()); Set<String> result = sshKeyStore.getAll(); <START> assertTrue(result.size() == 1 && result.contains(privateKey)); <END> }</code><technical_language>separated asserts</technical_language>

Target:
public void shouldGetThePrivateKeyFromUsersPreference() throws Exception { sshKeyStore = spy(new UserProfileSshKeyStore(API_ENDPOINT)); final String privateKey = "private key"; final String publicKey = "public key"; doReturn(ImmutableMap.of("ssh.key.private." + privateKey, "ssh.key.public." + publicKey)).when(sshKeyStore).getSshKeys(); doNothing().when(sshKeyStore).updateSshKeys(any()); Set<String> result = sshKeyStore.getAll(); assertTrue(result.contains(privateKey)); assertTrue(result.size() == 1); }
Source:
<code>public static QueryNode translateQuery(Map<String, Object> query, Map<String, Object> indexes, Boolean[] indexesCoverQuery) { TranslatorState state = new TranslatorState(); QueryNode node = translateQuery(query, indexes, state); if (state.textIndexMissing) { String msg = "No text index defined, cannot execute query containing a text search."; logger.log(Level.SEVERE, msg); return null; } else if (state.textIndexRequired && state.atLeastOneIndexMissing) { String msg = String.format("Query %s contains a text search but is missing \"json\"" + " index(es). All indexes must exist in order to execute a" + " query containing a text search. Create all necessary" + " indexes for the query and re-execute.", query.toString()); logger.log(Level.SEVERE, msg); return null; } else if (!state.textIndexRequired && (!state.atLeastOneIndexUsed || state.atLeastOneORIndexMissing)) { SqlQueryNode sqlNode = new SqlQueryNode(); Set<String> neededFields = new HashSet<String>(Collections.singletonList("_id")); String allDocsIndex = chooseIndexForFields(neededFields, indexes); if (allDocsIndex != null && !allDocsIndex.isEmpty()) { String tableName = IndexManager.tableNameForIndex(allDocsIndex); <START> String sql = String.format("SELECT _id FROM \"%s\"", tableName); <END> sqlNode.sql = SqlParts.partsForSql(sql, new String[]{}); } AndQueryNode root = new AndQueryNode(); root.children.add(sqlNode); indexesCoverQuery[0] = false; return root; } else { indexesCoverQuery[0] = !state.atLeastOneIndexMissing; return node; } }</code><technical_language>This a specific Locale</technical_language>

Target:
public static QueryNode translateQuery(Map<String, Object> query, Map<String, Object> indexes, Boolean[] indexesCoverQuery) { TranslatorState state = new TranslatorState(); QueryNode node = translateQuery(query, indexes, state); if (state.textIndexMissing) { String msg = "No text index defined, cannot execute query containing a text search."; logger.log(Level.SEVERE, msg); return null; } else if (state.textIndexRequired && state.atLeastOneIndexMissing) { String msg = String.format("Query %s contains a text search but is missing \"json\"" + " index(es). All indexes must exist in order to execute a" + " query containing a text search. Create all necessary" + " indexes for the query and re-execute.", query.toString()); logger.log(Level.SEVERE, msg); return null; } else if (!state.textIndexRequired && (!state.atLeastOneIndexUsed || state.atLeastOneORIndexMissing)) { SqlQueryNode sqlNode = new SqlQueryNode(); Set<String> neededFields = new HashSet<String>(Collections.singletonList("_id")); String allDocsIndex = chooseIndexForFields(neededFields, indexes); if (allDocsIndex != null && !allDocsIndex.isEmpty()) { String tableName = IndexManager.tableNameForIndex(allDocsIndex); String sql = String.format(Locale.ENGLISH, "SELECT _id FROM \"%s\"", tableName); sqlNode.sql = SqlParts.partsForSql(sql, new String[]{}); } AndQueryNode root = new AndQueryNode(); root.children.add(sqlNode); indexesCoverQuery[0] = false; return root; } else { indexesCoverQuery[0] = !state.atLeastOneIndexMissing; return node; } }
Source:
<code>private void initializeCurrentListeners() { UnitedServerListener[] all = null; synchronized(this) { <START> all = getListeners(); <END> isInitialized = true; } for( int i = 0; i < all.length; i++ ) { initializeListener(all[i]); } }</code><technical_language>getListeners() is synchronized, do need synchronized(this) too</technical_language>

Target:
private void initializeCurrentListeners() { Iterator<UnitedServerListener> it = null; synchronized(this) { it = list.iterator(); setInitialized(true); } while( it.hasNext() ) { initializeListener(it.next()); } }
Source:
<code>protected void contentChanged(ITmfTreeViewerEntry rootEntry) { <START> if (fSelectedThread != null) { <END> for (ITmfTreeViewerEntry entry : rootEntry.getChildren()) { if (entry instanceof CpuUsageEntry) { if (fSelectedThread.equals(((CpuUsageEntry) entry).getTid())) { List<ITmfTreeViewerEntry> list = Collections.singletonList(entry); if (list != null) { super.setSelection(list); } return; } } } } }</code><technical_language>fSelectedThread is mutable nullable, this method is synchronized, means change this check throw a NPE. extracted local variable</technical_language>

Target:
protected void contentChanged(ITmfTreeViewerEntry rootEntry) { String selectedThread = fSelectedThread; if (selectedThread != null) { for (ITmfTreeViewerEntry entry : rootEntry.getChildren()) { if (entry instanceof CpuUsageEntry) { if (selectedThread.equals(((CpuUsageEntry) entry).getTid())) { List<ITmfTreeViewerEntry> list = Collections.singletonList(entry); if (list != null) { super.setSelection(list); } return; } } } } }
Source:
<code>protected boolean checkUserAndGroupsAuthorization(Guid userId, HashSet<Guid> groupIds, final ActionGroup actionGroup, final Guid object, final VdcObjectType type, final boolean ignoreEveryone) { if (log.isDebugEnabled()) { <START> log.debugFormat("Checking whether user {0} has permission on {1} groups with {2} action group on {3} object with {4}", <END> userId, StringUtils.join(groupIds, ","), actionGroup, object, type.name()); } final Guid permId = getPermissionDAO().getEntityPermissionsForUserAndGroups(userId, StringUtils.join(groupIds, ","), actionGroup, object, type, ignoreEveryone); if (permId != null) { if (log.isDebugEnabled()) { log.debugFormat("Found permission {0} for user when running {1}, on {2} with id {3}", permId, getActionType(), type.getVdcObjectTranslation(), object); } return true; } if (log.isDebugEnabled()) { log.debugFormat("No permission found for user when running action {0}, on object {1} for action group {2} with id {3}.", getActionType(), type.getVdcObjectTranslation(), actionGroup, object); } return false; }</code><technical_language>This print is relevant, do harm. Change to: Checking user {0} groups {1} action group {3} object type {4}</technical_language>

Target:
protected boolean checkUserAndGroupsAuthorization(Guid userId, HashSet<Guid> groupIds, final ActionGroup actionGroup, final Guid object, final VdcObjectType type, final boolean ignoreEveryone) { if (log.isDebugEnabled()) { log.debugFormat("Checking whether user {0} or groups {1} have action group {3} on object type {4}", userId, StringUtils.join(groupIds, ","), actionGroup, object, type.name()); } final Guid permId = getPermissionDAO().getEntityPermissionsForUserAndGroups(userId, StringUtils.join(groupIds, ","), actionGroup, object, type, ignoreEveryone); if (permId != null) { if (log.isDebugEnabled()) { log.debugFormat("Found permission {0} for user when running {1}, on {2} with id {3}", permId, getActionType(), type.getVdcObjectTranslation(), object); } return true; } if (log.isDebugEnabled()) { log.debugFormat("No permission found for user when running action {0}, on object {1} for action group {2} with id {3}.", getActionType(), type.getVdcObjectTranslation(), actionGroup, object); } return false; }
Source:
<code>public void connect(String controller, String username, char[] password, String clientBindAddress) { checkAlreadyConnected(); try { ctx = CommandContextFactory.getInstance().newCommandContext(new CommandContextConfiguration(controller, username, password, clientBindAddress, false, -1)); ctx.connectController(); } catch (CliInitializationException e) { <START> throw new IllegalStateException("Unable to initialize command context.", e); <END> } catch (CommandLineException e) { throw new IllegalStateException("Unable to connect to controller.", e); } }</code><technical_language>remove this</technical_language>

Target:
public void connect(String controller, String username, char[] password, String clientBindAddress) { checkAlreadyConnected(); try { ctx = CommandContextFactory.getInstance().newCommandContext(new CommandContextConfiguration.Builder() .setController(controller) .setUsername(username) .setPassword(password) .setClientBindAddress(clientBindAddress) .build()); ctx.connectController(); } catch (CliInitializationException e) { throw new IllegalStateException("Unable to initialize command context.", e); } catch (CommandLineException e) { throw new IllegalStateException("Unable to connect to controller.", e); } }
Source:
<code><START> private void processSignals() { <END> this.healtcheckRefreshTime = clock.millis(); signals.drain(this::process); }</code><technical_language>In opinion handle exceptions processing signals here, especially thrown updating topic subscription</technical_language>

Target:
private void processSignals() { refreshHealthcheck(); signals.drain(this::process); refreshHealthcheck(); }
Source:
<code>public void testDisableL1() { GlobalConfigurationBuilder gcb = GlobalConfigurationBuilder.defaultClusteredBuilder(); ConfigurationBuilder cb = new ConfigurationBuilder(); <START> DefaultCacheManager manager = new DefaultCacheManager(gcb.build(), cb.build()); <END> cb = new ConfigurationBuilder(); cb.clustering().cacheMode(CacheMode.DIST_SYNC).l1().disable().disableOnRehash(); manager.defineConfiguration("testConfigCache", cb.build()); manager.getCache("testConfigCache"); }</code><technical_language>Hmmm, this problematic in future. If start a cache manager clustered, needs amended TestCacheManagerFactory mcast settings talking other clusters, create sort of funny situations. In general, cache managers created TestCacheManagerFactory. do right amendments configuration work expected in a multi-threaded testsuite</technical_language>

Target:
public void testDisableL1() { EmbeddedCacheManager manager = TestCacheManagerFactory .createClusteredCacheManager(new ConfigurationBuilder(), new TransportFlags()); try { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.clustering().cacheMode(CacheMode.DIST_SYNC).l1().disable().disableOnRehash(); manager.defineConfiguration("testConfigCache", cb.build()); manager.getCache("testConfigCache"); } finally { TestingUtil.killCacheManagers(manager); } }
Source:
<code>public String getProtoFileName() { <START> return "/library.proto"; <END> }</code><technical_language>is normal a /</technical_language>

Target:
public String getProtoFileName() { return "library.proto"; }
Source:
<code>public static LocalDateTime parseLocalDateTimeForSessionsForm(String date, String hour, String min) { if (date == null || hour == null || min == null) { return null; } <START> LocalDate localDate = parseLocalDate(date, "EEE, dd MMM, yyyy"); <END> if (localDate == null) { return null; } try { return localDate.atTime(Integer.parseInt(hour), Integer.parseInt(min)); } catch (DateTimeException | NumberFormatException e) { return null; } }</code><technical_language>parseLocalDateForSessionsForm</technical_language>

Target:
public static LocalDateTime parseLocalDateTimeForSessionsForm(String date, String hour, String min) { LocalDate localDate = parseLocalDateForSessionsForm(date); if (localDate == null) { return null; } if (hour == null || min == null) { return null; } try { return localDate.atTime(Integer.parseInt(hour), Integer.parseInt(min)); } catch (DateTimeException | NumberFormatException e) { return null; } }
Source:
<code>public static Bitmap inflateDisplayImage(Context context, String jrUri, int boundingWidth, int boundingHeight) { if (jrUri == null || jrUri.equals("")) { return null; } try { <START> String imageFilename = ReferenceManager._().DeriveReference(jrUri).getLocalURI(); <END> final File imageFile = new File(imageFilename); if (!imageFile.exists()) { return null; } Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); if (boundingHeight == -1) { boundingHeight = display.getHeight(); } if (boundingWidth == -1) { boundingWidth = display.getWidth(); } if (DeveloperPreferences.isSmartInflationEnabled()) { return getBitmapScaledForNativeDensity( context.getResources().getDisplayMetrics(), imageFile.getAbsolutePath(), boundingHeight, boundingWidth, DeveloperPreferences.getTargetInflationDensity()); } else { return getBitmapScaledToContainer(imageFile.getAbsolutePath(), boundingHeight, boundingWidth); } } catch (InvalidReferenceException e) { Log.e("ImageInflater", "image invalid reference exception for " + e.getReferenceString()); e.printStackTrace(); } return null; }</code><technical_language>This work jr refs point files, a fallback for do this point a file</technical_language>

Target:
public static Bitmap inflateDisplayImage(Context context, String jrUri, int boundingWidth, int boundingHeight) { if (jrUri == null || jrUri.equals("")) { return null; } try { Reference ref = ReferenceManager._().DeriveReference(jrUri); try { if (!ref.doesBinaryExist()) { return null; } if (!(ref instanceof JavaFileReference)) { return BitmapFactory.decodeStream(ref.getStream()); } } catch (IOException e) { Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, "IO Exception loading reference: " + jrUri); return null; } String imageFilename = ref.getLocalURI(); final File imageFile = new File(imageFilename); if (!imageFile.exists()) { return null; } Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); if (boundingHeight == -1) { boundingHeight = display.getHeight(); } if (boundingWidth == -1) { boundingWidth = display.getWidth(); } if (DeveloperPreferences.isSmartInflationEnabled()) { return getBitmapScaledForNativeDensity( context.getResources().getDisplayMetrics(), imageFile.getAbsolutePath(), boundingHeight, boundingWidth, DeveloperPreferences.getTargetInflationDensity()); } else { return getBitmapScaledToContainer(imageFile.getAbsolutePath(), boundingHeight, boundingWidth); } } catch (InvalidReferenceException e) { Log.e("ImageInflater", "image invalid reference exception for " + e.getReferenceString()); e.printStackTrace(); } return null; }
Source:
<code>public void createFeaturesTest() throws IOException { String[] tokens = new String[] {"he", "went", "with", "you"}; <START> AdaptiveFeatureGenerator generator = new BrownBigramFeatureGenerator(brownCluster); <END> List<String> features = new ArrayList<>(); generator.createFeatures(features, tokens, 3, null); Assert.assertEquals(2, features.size()); Assert.assertTrue(features.contains("pbrowncluster,browncluster=0101,0010")); Assert.assertTrue(features.contains("pbrowncluster,browncluster=01010,00101")); }</code><technical_language>This line moved @Before method too</technical_language>

Target:
public void createFeaturesTest() throws IOException { String[] tokens = new String[] {"he", "went", "with", "you"}; List<String> features = new ArrayList<>(); generator.createFeatures(features, tokens, 3, null); Assert.assertEquals(2, features.size()); Assert.assertTrue(features.contains("pbrowncluster,browncluster=0101,0010")); Assert.assertTrue(features.contains("pbrowncluster,browncluster=01010,00101")); }
Source:
<code>private List<StorageServerConnections> getConnections() { List<StorageServerConnections> connectionsList = new ArrayList<>(); for (int i = 0; i <START> <= NUMBER_OF_EXISTING_CONNECTIONS; <END> i++) { StorageServerConnections conn = new StorageServerConnections(); conn.setId(Guid.newGuid().toString()); connectionsList.add(conn); } return connectionsList; }</code><technical_language>This create 4 connections 3. init index 1 '<'</technical_language>

Target:
private List<StorageServerConnections> getConnections() { List<StorageServerConnections> connectionsList = new ArrayList<>(); for (int i = 0; i < NUMBER_OF_EXISTING_CONNECTIONS; i++) { StorageServerConnections conn = new StorageServerConnections(); conn.setId(Guid.newGuid().toString()); connectionsList.add(conn); } return connectionsList; }
Source:
<code>public static VersionInfo getVersionInfo(VersionResponseMsg msg) { final Gson parser = new GsonBuilder().create(); <START> return parser.fromJson(msg.getJsonPayloadMsg(), VersionInfo.class); <END> }</code><technical_language>this throw a parser exception if json is malformed</technical_language>

Target:
public static VersionInfo getVersionInfo(VersionResponseMsg msg) { final Gson parser = new GsonBuilder().create(); try { return parser.fromJson(msg.getJsonPayloadMsg(), VersionInfo.class); } catch (Exception ex) { throw new SerializerException("Unexpected error while deserializing VersionInfo JSON", ex); } }
Source:
<code>public static KeyPair getKeyPair() { <START> if (keyPairs.isEmpty()) { <END> synchronized (keyPairs) { keyPairs.notify(); } } try { return keyPairs.take(); } catch (InterruptedException e) { logger.error("Thead was interrupted", e); return null; } }</code><technical_language>LinkedBlockingQueues synchronized, I understand need of this notify call</technical_language>

Target:
public static KeyPair getKeyPair() throws NoSuchAlgorithmException { return keyPairProducer.getKeyPair(); }
Source:
<code>void remove(MessageGroup group) { Object correlationKey = group.getGroupId(); <START> if (this.groupIds.contains(correlationKey)) { <END> this.messageStore.removeMessageGroup(correlationKey); this.groupIds.remove(correlationKey); } }</code><technical_language>logic for this method. If here, is group. real problem is in ForceReleaseMessageGroupProcessor implementation. check for presence there. other logic affected. Please, this remove() method protected</technical_language>

Target:
protected void remove(MessageGroup group) { Object correlationKey = group.getGroupId(); this.messageStore.removeMessageGroup(correlationKey); this.groupIds.remove(group.getGroupId()); }
Source:
<code>public AccessControlPolicy[] getPolicies( String absPath ) throws PathNotFoundException, AccessDeniedException, RepositoryException { if (session.isReadOnly()) { throw new AccessDeniedException(JcrI18n.permissionDenied.text(absPath, "read access control content")); } if (!hasPrivileges(absPath, new Privilege[] {privileges.forName(Privilege.JCR_READ_ACCESS_CONTROL)})) { throw new AccessDeniedException(); } AccessControlList acl = findAccessList(absPath, false); <START> return acl == null ? new AccessControlPolicy[0] : new AccessControlPolicy[] {acl}; <END> }</code><technical_language>This is a lot, a static constant empty array</technical_language>

Target:
public AccessControlPolicy[] getPolicies( String absPath ) throws PathNotFoundException, AccessDeniedException, RepositoryException { if (session.isReadOnly()) { throw new AccessDeniedException(JcrI18n.permissionDenied.text(absPath, "read access control content")); } if (!hasPrivileges(absPath, new Privilege[] {privileges.forName(Privilege.JCR_READ_ACCESS_CONTROL)})) { throw new AccessDeniedException(); } AccessControlList acl = findAccessList(absPath, false); return acl == null ? EMPTY_POLICIES : new AccessControlPolicy[] {acl}; }
Source:
<code>public static <TClass, TAnnotation extends Annotation> void scanJar(String path, Class<TClass> superClass, Class<TAnnotation> annotationClass, String requirePackage, Consumer<Class<? extends TClass>> consumer) { log.tracef("Looking for @%s %s, loading classes from %s", annotationClass.getSimpleName(), superClass.getSimpleName(), path); try (ZipInputStream inputStream = new ZipInputStream(new FileInputStream(path))) { for(;;) { ZipEntry entry = inputStream.getNextEntry(); if (entry == null) break; <START> if (!entry.getName().endsWith(".class")) continue; <END> String className = entry.getName().replace('/', '.').substring(0, entry.getName().length() - 6); scanClass(className, superClass, annotationClass, requirePackage, consumer); } } catch (FileNotFoundException e) { log.error("Cannot load executed JAR file '" + path + "'to find stages."); } catch (IOException e) { log.error("Cannot open/read JAR '" + path + "'"); } }</code><technical_language>I introducing .class constant entry.getName().length() - CLASS.length more obvious sight</technical_language>

Target:
public static <TClass, TAnnotation extends Annotation> void scanJar(String path, Class<TClass> superClass, Class<TAnnotation> annotationClass, String requirePackage, Consumer<Class<? extends TClass>> consumer) { log.tracef("Looking for @%s %s, loading classes from %s", annotationClass.getSimpleName(), superClass.getSimpleName(), path); try (ZipInputStream inputStream = new ZipInputStream(new FileInputStream(path))) { for(;;) { ZipEntry entry = inputStream.getNextEntry(); if (entry == null) break; if (!entry.getName().endsWith(CLASS_SUFFIX)) continue; String className = entry.getName().replace('/', '.').substring(0, entry.getName().length() - CLASS_SUFFIX.length()); scanClass(className, superClass, annotationClass, requirePackage, consumer); } } catch (FileNotFoundException e) { log.error("Cannot load executed JAR file '" + path + "'to find stages."); } catch (IOException e) { log.error("Cannot open/read JAR '" + path + "'"); } }
Source:
<code>public void testEquality() { <START> for (boolean ascending : getTestedOrder()) { <END> testEquals(true); testEquals(false); } }</code><technical_language>testing twice, right</technical_language>

Target:
public void testEquality() { for (Order order : getTestedOrder()) { boolean ascending = isAscending(order); testEquals(ascending); } }
Source:
<code>private List<String> toConjuncts(List<HiveColumnHandle> columns, TupleDomain<HiveColumnHandle> tupleDomain) { <START> ImmutableList.Builder<String> builder = ImmutableList.builder(); <END> for (HiveColumnHandle column : columns) { Type type = column.getHiveType().getType(typeManager); if (tupleDomain.getDomains().isPresent() && isAcceptedType(type)) { Domain domain = tupleDomain.getDomains().get().get(column); if (domain != null) { builder.add(toPredicate(domain, type, column.getHiveColumnIndex())); } } } return builder.build(); }</code><technical_language>import ImmutableList.Builder</technical_language>

Target:
private List<String> toConjuncts(List<HiveColumnHandle> columns, TupleDomain<HiveColumnHandle> tupleDomain) { Builder<String> builder = builder(); for (HiveColumnHandle column : columns) { Type type = column.getHiveType().getType(typeManager); if (tupleDomain.getDomains().isPresent() && isSupported(type)) { Domain domain = tupleDomain.getDomains().get().get(column); if (domain != null) { builder.add(toPredicate(domain, type, column.getHiveColumnIndex())); } } } return builder.build(); }
Source:
<code>public void batch_mutate(Map<ByteBuffer, Map<String, List<Mutation>>> mutation_map, ConsistencyLevel consistency_level) throws InvalidRequestException, UnavailableException, TimedOutException, TException { try (CloseableTrace trace = startLocalTrace("client.batch_mutate(number of rows {}, consistency {})", mutation_map.size(), toString(consistency_level))) { <START> registerDuration(() -> { <END> delegate.batch_mutate(mutation_map, consistency_level); return null; }, BATCH_MUTATE_TIMER); } }</code><technical_language>reason tritium for these? I guess need extract interface for Client.. this point pretty surprised decided do :)</technical_language>

Target:
public void batch_mutate(Map<ByteBuffer, Map<String, List<Mutation>>> mutation_map, ConsistencyLevel consistency_level) throws InvalidRequestException, UnavailableException, TimedOutException, TException { int numberOfMutations = mutation_map.size(); try (CloseableTrace trace = startLocalTrace("client.batch_mutate(number of mutations {}, consistency {})", numberOfMutations, consistency_level)) { registerDuration(() -> { delegate.batch_mutate(mutation_map, consistency_level); return null; }, BATCH_MUTATE_TIMER, logger -> logger.warn("client.batch_mutate({}, {})", SafeArg.of("number of mutations", numberOfMutations), SafeArg.of("consistency", consistency_level.toString()))); } }
Source:
<code>public static PersonIdent parsePersonIdent(final byte[] raw, final int nameB) { final Charset cs = parseEncoding(raw); final int emailB = nextLF(raw, nameB, '<'); final int emailE = nextLF(raw, emailB, '>'); if (emailB >= raw.length || raw[emailB] == '\n' || (emailE >= raw.length - 1 && raw[emailE - 1] != '>')) return null; int nameEnd = emailB - 2; while (nameEnd >= 0 && raw[nameEnd] == ' ') nameEnd--; final String name = decode(cs, raw, nameB, nameEnd + 1); <START> final String email = decode(cs, raw, emailB, emailE - 1).trim(); <END> final int tzBegin = lastIndexOfTrim(raw, ' ', raw.length - 1) + 1; if (tzBegin <= emailE) return new PersonIdent(name, email, 0, 0); final int whenBegin = Math.max(emailE, lastIndexOfTrim(raw, ' ', tzBegin - 1) + 1); if (whenBegin >= tzBegin - 1) return new PersonIdent(name, email, 0, 0); final long when = parseLongBase10(raw, whenBegin, null); final int tz = parseTimeZoneOffset(raw, tzBegin); return new PersonIdent(name, email, when * 1000L, tz); }</code><technical_language>do need trim this? is < > as-is email. Do example of a malformed commit email contains leading trailing whitespace <>'s needs discarded? if exists, tempted is proper text of address, preserve text in parsing</technical_language>

Target:
public static PersonIdent parsePersonIdent(final byte[] raw, final int nameB) { final Charset cs = parseEncoding(raw); final int emailB = nextLF(raw, nameB, '<'); final int emailE = nextLF(raw, emailB, '>'); if (emailB >= raw.length || raw[emailB] == '\n' || (emailE >= raw.length - 1 && raw[emailE - 1] != '>')) return null; final int nameEnd = emailB - 2 >= 0 && raw[emailB - 2] == ' ' ? emailB - 2 : emailB - 1; final String name = decode(cs, raw, nameB, nameEnd); final String email = decode(cs, raw, emailB, emailE - 1); final int tzBegin = lastIndexOfTrim(raw, ' ', nextLF(raw, emailE - 1) - 1) + 1; if (tzBegin <= emailE) return new PersonIdent(name, email, 0, 0); final int whenBegin = Math.max(emailE, lastIndexOfTrim(raw, ' ', tzBegin - 1) + 1); if (whenBegin >= tzBegin - 1) return new PersonIdent(name, email, 0, 0); final long when = parseLongBase10(raw, whenBegin, null); final int tz = parseTimeZoneOffset(raw, tzBegin); return new PersonIdent(name, email, when * 1000L, tz); }
Source:
<code><START> public void setIdGenerationStrategy(final IdGenerationStrategy idGenerationStrategy) { <END> this.idGenerationStrategy = idGenerationStrategy; }</code><technical_language>Abstract classes abstract final methods, in (preferably). Mark this method final</technical_language>

Target:
final void setIdGenerationStrategy(final IdGenerationStrategy idGenerationStrategy) { this.idGenerationStrategy = idGenerationStrategy; }
Source:
<code>private Map<String, Object> getConfigMap(String config) { if (config == null) { return null; } String configStr = config; <START> if (configStr.startsWith("{")) { <END> configStr = configStr.substring(1, configStr.length()); } if (configStr.endsWith("}")) { configStr = configStr.substring(0, configStr.length() - 1); } Map<String, Object> map = new HashMap<>(); for (String part : configStr.split("\\s*,\\s*")) { String[] subparts = part.split("=", 2); if (subparts.length == 2 && subparts[0] != null && subparts[1] != null) { map.put(subparts[0].trim(), subparts[1].trim()); } } return map; }</code><technical_language>combine checks "and"? Java if (configStr.startsWith("{") && configStr.endsWith("}")) { configStr = configStr.substring(1, configStr.length() - 1); } I assume valid inputs start end curly bracket any</technical_language>

Target:
private Map<String, Object> getConfigMap(String config) { if (config == null) { return null; } String configStr = config; if (configStr.startsWith("{") && configStr.endsWith("}")) { configStr = configStr.substring(1, configStr.length() - 1); } Map<String, Object> map = new HashMap<>(); for (String part : configStr.split("\\s*,\\s*")) { String[] subparts = part.split("=", 2); if (subparts.length == 2 && subparts[0] != null && subparts[1] != null) { map.put(subparts[0].trim(), subparts[1].trim()); } } return map; }
Source:
<code>private void releaseExportBytes(long releaseOffset) throws IOException { <START> if (!m_committedBuffers.isEmpty() && (m_committedBuffers.peek() != null) <END> && (releaseOffset < m_committedBuffers.peek().uso())) { return; } long lastUso = m_firstUnpolledUso; while (!m_committedBuffers.isEmpty() && m_committedBuffers.peek() != null && releaseOffset >= m_committedBuffers.peek().uso()) { StreamBlock sb = m_committedBuffers.peek(); if (releaseOffset >= sb.uso() + sb.totalUso()) { m_committedBuffers.pop(); try { lastUso = sb.uso() + sb.totalUso(); } finally { sb.discard(); } } else if (releaseOffset >= sb.uso()) { sb.releaseUso(releaseOffset); lastUso = releaseOffset; break; } } m_lastReleaseOffset = releaseOffset; m_firstUnpolledUso = Math.max(m_firstUnpolledUso, lastUso); }</code><technical_language>"m_committedBuffers.peek() == null"</technical_language>

Target:
private void releaseExportBytes(long releaseOffset) throws IOException { if (m_committedBuffers.isEmpty()) return; if (releaseOffset < m_committedBuffers.peek().uso()) { return; } long lastUso = m_firstUnpolledUso; while (!m_committedBuffers.isEmpty() && releaseOffset >= m_committedBuffers.peek().uso()) { StreamBlock sb = m_committedBuffers.peek(); if (releaseOffset >= sb.uso() + sb.totalUso()) { m_committedBuffers.pop(); try { lastUso = sb.uso() + sb.totalUso(); } finally { sb.discard(); } } else if (releaseOffset >= sb.uso()) { sb.releaseUso(releaseOffset); lastUso = releaseOffset; break; } } m_lastReleaseOffset = releaseOffset; m_firstUnpolledUso = Math.max(m_firstUnpolledUso, lastUso); }
Source:
<code>public void deleteCollectionSubmittersGroupForbiddenTest() throws Exception { context.turnOffAuthorisationSystem(); Group submittersGroup = collectionService.createSubmitters(context, collection); context.restoreAuthSystemState(); String token = getAuthToken(eperson.getEmail(), password); getClient(token).perform(delete("/api/core/collections/" + collection.getID() + "/submittersGroup")) <START> .andExpect(status().isForbidden()); <END> }</code><technical_language>double check group is</technical_language>

Target:
public void deleteCollectionSubmittersGroupForbiddenTest() throws Exception { context.turnOffAuthorisationSystem(); Group submittersGroup = collectionService.createSubmitters(context, collection); context.restoreAuthSystemState(); String token = getAuthToken(eperson.getEmail(), password); getClient(token).perform(delete("/api/core/collections/" + collection.getID() + "/submittersGroup")) .andExpect(status().isForbidden()); token = getAuthToken(admin.getEmail(), password); getClient(token).perform(get("/api/core/collections/" + collection.getID() + "/submittersGroup")) .andExpect(status().isOk()) .andExpect( jsonPath("$", GroupMatcher.matchGroupEntry(submittersGroup.getID(), submittersGroup.getName()))); }
Source:
<code>public List<Object> configurations() { <START> return Arrays.asList((Object[])whitelist.split("\\s*,\\s*")); <END> }</code><technical_language>do split trim, regular expressions (first regular expressions error prone, introduce security problems)</technical_language>

Target:
public List<Object> configurations() { return Arrays.asList(whitelist.split(",")).stream().map(String::trim).collect(Collectors.toList()); }
Source:
<code>public void autoCreatePanels_createCustomPanelsFromMenu_panelsCreatedWithAppropriatePanelNameAndFilter() throws NoSuchFieldException, IllegalAccessException { Field panelMenuCreatorField = MenuControl.class.getDeclaredField("panelMenuCreator"); panelMenuCreatorField.setAccessible(true); <START> PanelMenuCreator value = (PanelMenuCreator) panelMenuCreatorField.get(ui.getMenuControl()); <END> for (Map.Entry<String, String> entry : value.generateCustomizedPanelDetails(ui.prefs.getLastLoginUsername()).entrySet()) { customizedPanelMenuItemTest(entry.getKey(), entry.getValue()); } }</code><technical_language>factor out reflection? deal in here</technical_language>

Target:
public void autoCreatePanels_createCustomPanelsFromMenu_panelsCreatedWithAppropriatePanelNameAndFilter() throws NoSuchFieldException, IllegalAccessException { PanelMenuCreator value = (PanelMenuCreator) getPanelMenuCreatorField().get(ui.getMenuControl()); for (Entry<String, String> entry : value.generatePanelDetails(ui.prefs.getLastLoginUsername()).entrySet()) { customizedPanelMenuItemTest(entry.getKey(), entry.getValue()); } }
Source:
<code><START> public Resource<T> getChild(final String name) <END> { throw new RuntimeException("not implemented"); }</code><technical_language>compatible</technical_language>

Target:
public Resource<?> getChild(final String name) { throw new RuntimeException("not implemented"); }
Source:
<code>private void handleError(Map<String, Object> params, Task task, TaskHandlerException e) { LOGGER.debug(String.format("Omitted the task with name: %s and ID: %s because: ", task.getName(), task.getId()), e); activityService.addError(task, e); <START> task.incrementFailuresInRow(); <END> int failureNumber = task.getFailuresInRow(); int possibleErrorsNumber = getPossibleErrorsNumber(); if (failureNumber >= possibleErrorsNumber) { task.setEnabled(false); activityService.addWarning(task); publishTaskDisabledMessage(task.getName()); } taskService.save(task); Map<String, Object> errorParam = new HashMap<>(); errorParam.put(TASK_FAIL_MESSAGE, e.getMessage()); errorParam.put(TASK_FAIL_STACK_TRACE, ExceptionUtils.getStackTrace(e)); errorParam.put(TASK_FAIL_FAILURE_DATE, DateTime.now()); errorParam.put(TASK_FAIL_FAILURE_NUMBER, failureNumber); errorParam.put(TASK_FAIL_TRIGGER_DISABLED, task.isEnabled()); errorParam.put(TASK_FAIL_TASK_ID, task.getId()); errorParam.put(TASK_FAIL_TASK_NAME, task.getName()); params.put(HANDLER_ERROR_PARAM, errorParam); eventRelay.sendEventMessage(new MotechEvent( createHandlerFailureSubject(task.getName(), e.getFailureCause()), params )); }</code><technical_language>log a warn if disabling a task</technical_language>

Target:
private void handleError(Map<String, Object> params, Task task, TaskHandlerException e) { LOGGER.warn("Omitted task: with ID: because: {}", task.getName(), task.getId(), e); activityService.addError(task, e); task.incrementFailuresInRow(); LOGGER.warn("The number of failures for task: is: {}", task.getName(), task.getFailuresInRow()); int failureNumber = task.getFailuresInRow(); int possibleErrorsNumber = getPossibleErrorsNumber(); if (failureNumber >= possibleErrorsNumber) { task.setEnabled(false); activityService.addWarning(task); publishTaskDisabledMessage(task.getName()); } taskService.save(task); Map<String, Object> errorParam = new HashMap<>(); errorParam.put(TASK_FAIL_MESSAGE, e.getMessage()); errorParam.put(TASK_FAIL_STACK_TRACE, ExceptionUtils.getStackTrace(e)); errorParam.put(TASK_FAIL_FAILURE_DATE, DateTime.now()); errorParam.put(TASK_FAIL_FAILURE_NUMBER, failureNumber); errorParam.put(TASK_FAIL_TRIGGER_DISABLED, task.isEnabled()); errorParam.put(TASK_FAIL_TASK_ID, task.getId()); errorParam.put(TASK_FAIL_TASK_NAME, task.getName()); params.put(HANDLER_ERROR_PARAM, errorParam); eventRelay.sendEventMessage(new MotechEvent( createHandlerFailureSubject(task.getName(), e.getFailureCause()), params )); }
Source:
<code>public static void logAndEndMetrics() { if (enabled) { NodeStats stats = nodeStats.get(); if (stats != null && stats.isStarted()) { long elapsedTime = (System.nanoTime() - stats.getStartTime()); <START> if (stats.getEvalCount() > 0 && (elapsedTime / 1000) > threshold) { <END> logger.trace("{}, evalCount:{}, elapsed:{}", stats.getNode(), stats.getEvalCount(), elapsedTime / 1000); } } nodeStats.remove(); } }</code><technical_language>I save this expensive computation elapsedTime / 1000 perform I handle case of stats == null a log similar: this point this is supposed null right</technical_language>

Target:
public static void logAndEndMetrics() { if (enabled) { NodeStats stats = nodeStats.get(); if (stats != null && stats.isStarted()) { long elapsedTimeInMicro = (System.nanoTime() - stats.getStartTime()) / 1000; if (stats.getEvalCount() > 0 && elapsedTimeInMicro > threshold) { logger.trace("{}, evalCount:{}, elapsedMicro:{}", stats.getNode(), stats.getEvalCount(), elapsedTimeInMicro); } } else { logger.warn("nodeStats has to be initialized. Call startMetrics() beforehand : stats = {}", stats); } nodeStats.remove(); } }
Source:
<code>public ContainerRequest filter(ContainerRequest request) { if (getAuthConfig().isEnabled()) { final String resourceName; if (request.getPath().startsWith("druid/worker/v1") || request.getPath().startsWith("druid/indexer/v1")) { resourceName = "WORKER"; } else if (request.getPath().startsWith("druid/coordinator/v1/config")) { resourceName = "COORDINATOR"; <START> } else { <END> throw new WebApplicationException( Response.status(Response.Status.BAD_REQUEST).entity( String.format( "Do not know how to authorize this request path [%s] with ConfigResourceFilter", request.getPath() ) ).build() ); } final AuthorizationInfo authorizationInfo = (AuthorizationInfo) getReq().getAttribute(AuthConfig.DRUID_AUTH_TOKEN); Preconditions.checkNotNull( authorizationInfo, "Security is enabled but no authorization info found in the request" ); final Access authResult = authorizationInfo.isAuthorized( new Resource(resourceName, ResourceType.CONFIG), getAction(request) ); if (!authResult.isAllowed()) { throw new WebApplicationException( Response.status(Response.Status.FORBIDDEN) .entity(String.format("Access-Check-Result: %s", authResult.toString())) .build() ); } } return request; }</code><technical_language>resourceName for states e.g. "config" instead of specific requires conditional hardcoding of URLs? if need give a name</technical_language>

Target:
public ContainerRequest filter(ContainerRequest request) { if (getAuthConfig().isEnabled()) { final String resourceName = "CONFIG"; final AuthorizationInfo authorizationInfo = (AuthorizationInfo) getReq().getAttribute(AuthConfig.DRUID_AUTH_TOKEN); Preconditions.checkNotNull( authorizationInfo, "Security is enabled but no authorization info found in the request" ); final Access authResult = authorizationInfo.isAuthorized( new Resource(resourceName, ResourceType.CONFIG), getAction(request) ); if (!authResult.isAllowed()) { throw new WebApplicationException( Response.status(Response.Status.FORBIDDEN) .entity(String.format("Access-Check-Result: %s", authResult.toString())) .build() ); } } return request; }
Source:
<code>public void init(StateTransferLock stateTransferLock, Configuration configuration, StateTransferManager stateTransferManager, GroupManager groupManager) { this.stateTransferLock = stateTransferLock; this.stateTransferManager = stateTransferManager; this.groupManager = groupManager; <START> transactionDataTimeout = configuration.clustering().sync().replTimeout(); <END> }</code><technical_language>remoteTimeout() is correct one</technical_language>

Target:
public void init(StateTransferLock stateTransferLock, Configuration configuration, StateTransferManager stateTransferManager, GroupManager groupManager) { this.stateTransferLock = stateTransferLock; this.stateTransferManager = stateTransferManager; this.groupManager = groupManager; transactionDataTimeout = configuration.clustering().remoteTimeout(); }
Source:
<code>public void execute(IProgressMonitor m) throws CoreException { if (pullResult != null) throw new CoreException(new Status(IStatus.ERROR, Activator .getPluginId(), CoreText.OperationAlreadyExecuted)); IProgressMonitor monitor; if (m == null) monitor = new NullProgressMonitor(); else monitor = m; IWorkspaceRunnable action = new IWorkspaceRunnable() { public void run(IProgressMonitor mymonitor) throws CoreException { PullCommand pull = new Git(repository).pull(); try { pull.setProgressMonitor(new EclipseGitProgressTransformer( mymonitor)); pull.setTimeout(timeout); pullResult = pull.call(); } catch (GitAPIException e) { IStatus error = new Status(IStatus.ERROR, Activator <START> .getPluginId(), e.getMessage(), e); <END> throw new CoreException(error); } } }; ResourcesPlugin.getWorkspace().run(action, monitor); }</code><technical_language>Activator.error create error status</technical_language>

Target:
public void execute(IProgressMonitor m) throws CoreException { if (pullResult != null) throw new CoreException(new Status(IStatus.ERROR, Activator .getPluginId(), CoreText.OperationAlreadyExecuted)); IProgressMonitor monitor; if (m == null) monitor = new NullProgressMonitor(); else monitor = m; IWorkspaceRunnable action = new IWorkspaceRunnable() { public void run(IProgressMonitor mymonitor) throws CoreException { PullCommand pull = new Git(repository).pull(); try { pull.setProgressMonitor(new EclipseGitProgressTransformer( mymonitor)); pull.setTimeout(timeout); pullResult = pull.call(); } catch (GitAPIException e) { throw new CoreException(Activator.error(e.getMessage(), e)); } } }; ResourcesPlugin.getWorkspace().run(action, monitor); }
Source:
<code>public boolean onMarkerClick(Marker marker) { AnnotationProxy annoProxy = getProxyByMarker(marker); if (annoProxy == null) { Log.e(TAG, "Marker can not be found, click event won't fired.", Log.DEBUG_MODE); return false; } else if (selectedAnnotation != null && selectedAnnotation.equals(annoProxy)) { selectedAnnotation.hideInfo(); selectedAnnotation = null; fireClickEvent(marker, annoProxy, MapModule.PROPERTY_PIN); return true; } fireClickEvent(marker, annoProxy, MapModule.PROPERTY_PIN); selectedAnnotation = annoProxy; <START> if (annoProxy.getShowInfoWindow()) { <END> return false; } else { return true; } }</code><technical_language>If want get a property's value, proxy.getProperty(name). need add another private variable "showInfoWindow" method getShowInfoWindow() in AnnotationProxy.java</technical_language>

Target:
public boolean onMarkerClick(Marker marker) { AnnotationProxy annoProxy = getProxyByMarker(marker); if (annoProxy == null) { Log.e(TAG, "Marker can not be found, click event won't fired.", Log.DEBUG_MODE); return false; } else if (selectedAnnotation != null && selectedAnnotation.equals(annoProxy)) { selectedAnnotation.hideInfo(); selectedAnnotation = null; fireClickEvent(marker, annoProxy, MapModule.PROPERTY_PIN); return true; } fireClickEvent(marker, annoProxy, MapModule.PROPERTY_PIN); selectedAnnotation = annoProxy; boolean showInfoWindow = TiConvert.toBoolean(annoProxy.getProperty(MapModule.PROPERTY_SHOW_INFO_WINDOW), true); if (showInfoWindow) { return false; } else { return true; } }
Source:
<code>public void cancel() throws InterruptedException { super.cancel(); info("Cancel called. Killing the Hive launched MR jobs on the cluster"); String azExecId = jobProps.getString("azkaban.flow.execid"); final String logFilePath = String.format("%s/_job.%s.%s.log", getWorkingDirectory(), azExecId, getId()); <START> info("log file path is: " + logFilePath); <END> HadoopJobUtils.proxyUserKillAllSpawnedHadoopJobs(logFilePath, jobProps, tokenFile, getLog()); }</code><technical_language>log file moved ? get new path</technical_language>

Target:
public void cancel() throws InterruptedException { super.cancel(); info("Cancel called. Killing the Hive launched MR jobs on the cluster"); String azExecId = jobProps.getString(CommonJobProperties.EXEC_ID); final String logFilePath = String.format("%s/_job.%s.%s.log", getWorkingDirectory(), azExecId, getId()); info("log file path is: " + logFilePath); HadoopJobUtils.proxyUserKillAllSpawnedHadoopJobs(logFilePath, jobProps, tokenFile, getLog()); }
Source:
<code>private Request logAndReplaceRequest(Request request) throws IOException { <START> log.log(String.format("---> HTTP %s %s", request.getMethod(), request.getUrl())); <END> for (Header header : request.getHeaders()) { log.log(header.getName() + ": " + header.getValue()); } TypedOutput body = request.getBody(); if (body != null) { if (!request.getHeaders().isEmpty()) { log.log(""); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); body.writeTo(baos); byte[] bodyBytes = baos.toByteArray(); String bodyMime = body.mimeType(); String bodyString = new String(bodyBytes, Utils.parseCharset(bodyMime)); for (int i = 0; i < bodyString.length(); i += LOG_CHUNK_SIZE) { int end = Math.min(bodyString.length(), i + LOG_CHUNK_SIZE); log.log(bodyString.substring(i, end)); } body = new TypedByteArray(bodyMime, bodyBytes); } log.log("---> END HTTP"); return new Request(request.getMethod(), request.getUrl(), request.getHeaders(), body); }</code><technical_language>ugly arrow</technical_language>

Target:
private Request logAndReplaceRequest(Request request) throws IOException { log.log(String.format("---> HTTP %s %s", request.getMethod(), request.getUrl())); for (Header header : request.getHeaders()) { log.log(header.getName() + ": " + header.getValue()); } TypedOutput body = request.getBody(); int bodySize = 0; if (body != null) { if (!request.getHeaders().isEmpty()) { log.log(""); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); body.writeTo(baos); byte[] bodyBytes = baos.toByteArray(); bodySize = bodyBytes.length; String bodyMime = body.mimeType(); String bodyString = new String(bodyBytes, Utils.parseCharset(bodyMime)); for (int i = 0; i < bodyString.length(); i += LOG_CHUNK_SIZE) { int end = Math.min(bodyString.length(), i + LOG_CHUNK_SIZE); log.log(bodyString.substring(i, end)); } body = new TypedByteArray(bodyMime, bodyBytes); } log.log(String.format("---> END HTTP (%s-byte body)", bodySize)); return new Request(request.getMethod(), request.getUrl(), request.getHeaders(), body); }
Source:
<code>public synchronized void sendUpdates(Map<String, Object> state, Set<String> changed) { if (state.get("ScoreBoard.CurrentPeriodNumber") != "0") { if ((inJam && !bool(state.get("ScoreBoard.InJam"))) <START> || (bool(state.get("ScoreBoard.OfficialScore")) <END> && !bool(state.get("ScoreBoard.StatsLocked")) && containsRelevantUpdate(changed))) { writeFile(state); } } inJam = bool(state.get("ScoreBoard.InJam")); }</code><technical_language>A simpler do this this bool(state.get("ScoreBoard.OfficialScore") state. filter out Clock changes if want to</technical_language>

Target:
public synchronized void sendUpdates(Map<String, Object> state, Set<String> changed) { if (state.get("ScoreBoard.CurrentPeriodNumber") != "0") { if ((inJam && !bool(state.get("ScoreBoard.InJam"))) || (bool(state.get("ScoreBoard.OfficialScore")) && containsRelevantUpdate(changed))) { writeFile(state); } } inJam = bool(state.get("ScoreBoard.InJam")); }