auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public CustomUIPane(HaskellCatalog catalog) { this.connectionCreationManager = new ConnectionCreationManager(this); this.selectedBlock = new SimpleObjectProperty<>(Optional.empty()); this.errorOccurred = new SimpleBooleanProperty(false); this.dragStart = Point2D.ZERO; this.offset = Point2D.ZERO; this.catalog = catalog; this.envInstance = catalog.asEnvironment(); <START> exprToFunction = new HashMap<Expr, FunctionBlock>(); <END> try { this.ghci = Optional.of(new GhciSession()); } catch (GhciException e) { this.ghci = Optional.empty(); } this.addEventHandler(MouseEvent.MOUSE_PRESSED, this::handlePress); this.addEventHandler(MouseEvent.MOUSE_DRAGGED, this::handleDrag); this.addEventHandler(ScrollEvent.SCROLL, this::handleScroll); this.addEventHandler(KeyEvent.KEY_PRESSED, this::handleKey); Platform.runLater(() -> { inspector = new InspectorWindow(this); inspector.blockProperty().bind(this.selectedBlock); }); }</code><technical_language>this. prefix elsewhere. here</technical_language>

Target:
public CustomUIPane(HaskellCatalog catalog) { this.connectionCreationManager = new ConnectionCreationManager(this); this.selectedBlock = new SimpleObjectProperty<>(Optional.empty()); this.errorOccurred = new SimpleBooleanProperty(false); this.dragStart = Point2D.ZERO; this.offset = Point2D.ZERO; this.catalog = catalog; this.envInstance = catalog.asEnvironment(); this.exprToFunction = new HashMap<Expr, FunctionBlock>(); try { this.ghci = Optional.of(new GhciSession()); } catch (GhciException e) { this.ghci = Optional.empty(); } this.addEventHandler(MouseEvent.MOUSE_PRESSED, this::handlePress); this.addEventHandler(MouseEvent.MOUSE_DRAGGED, this::handleDrag); this.addEventHandler(ScrollEvent.SCROLL, this::handleScroll); this.addEventHandler(KeyEvent.KEY_PRESSED, this::handleKey); Platform.runLater(() -> { inspector = new InspectorWindow(this); inspector.blockProperty().bind(this.selectedBlock); }); }
Source:
<code>public DozerBeanMapperFactoryBean dozerMapper() throws IOException { DozerBeanMapperFactoryBean factoryBean = new DozerBeanMapperFactoryBean(); factoryBean.setMappingFiles(configurationProperties.getMappingFiles()); factoryBean.setApplicationContext(applicationContext); <START> return factoryBean; <END> }</code><technical_language>wondering if Mapper instance returned, instead of spring factory. spring wire Mapper "magic" :)</technical_language>

Target:
public DozerBeanMapperFactoryBean dozerMapper() throws IOException { DozerBeanMapperFactoryBean factoryBean = new DozerBeanMapperFactoryBean(); factoryBean.setMappingFiles(configurationProperties.getMappingFiles()); return factoryBean; }
Source:
<code>public static OmMultipartUpload from(String key) { String[] split = key.split(OM_KEY_PREFIX); if (split.length < 5) { throw new IllegalArgumentException("Key " + key <START> + " doesn't have enough segments to be a valid multpart upload key"); <END> } String uploadId = split[split.length - 1]; String volume = split[1]; String bucket = split[2]; return new OmMultipartUpload(volume, bucket, key.substring(volume.length() + bucket.length() + 3, key.length() - uploadId.length() - 1), uploadId); }</code><technical_language>multpart -> multipart</technical_language>

Target:
public static OmMultipartUpload from(String key) { String[] split = key.split(OM_KEY_PREFIX); if (split.length < 5) { throw new IllegalArgumentException("Key " + key + " doesn't have enough segments to be a valid multipart upload key"); } String uploadId = split[split.length - 1]; String volume = split[1]; String bucket = split[2]; return new OmMultipartUpload(volume, bucket, key.substring(volume.length() + bucket.length() + 3, key.length() - uploadId.length() - 1), uploadId); }
Source:
<code>public final String buildFreeTextConditionSql(String tableName, String relations, String value, boolean caseSensitive) { StringBuilder sb = new StringBuilder(" ( "); boolean firstTime = true; if (!StringHelper.isNullOrEmpty(value) && !"''".equals(value)) { value = StringFormat.format(getI18NPrefix() + "'%%%1$s%%'", StringHelper.trim(value, '\'')); } if ("=".equals(relations)) { relations = getLikeSyntax(caseSensitive); } else if ("!=".equals(relations)) { relations = "NOT " + getLikeSyntax(caseSensitive); } SortedSet<Map.Entry<String, String>> sortedEntrySet = new TreeSet<>(new ColNameMapEntryComparator()); <START> sortedEntrySet.addAll(columnNameDict.entrySet()); <END> for (Map.Entry<String, String> columnNameEntry : sortedEntrySet) { if (typeDict.get(columnNameEntry.getKey()) == String.class && !notFreeTextSearchableFieldsList.contains(columnNameEntry.getKey())) { if (firstTime) { firstTime = false; } else { sb.append(" OR "); } sb.append(StringFormat.format(" %1$s.%2$s %3$s %4$s", tableName, columnNameEntry.getValue(), relations, value)); } } sb.append(" ) "); return sb.toString(); }</code><technical_language>jenkins failing job: BaseConditionFieldAutoCompleter.java:172, DMI_ENTRY_SETS_MAY_REUSE_ENTRY_OBJECTS, Priority: Adding elements of entry set fail due reuse of Map.Entry object in org.ovirt.engine.core.searchbackend.BaseConditionFieldAutoCompleter.buildFreeTextConditionSql(String, String, String, boolean) entrySet() method is allowed return a view of underlying Map in a single Entry object is reused returned iteration. of Java 1.6, IdentityHashMap EnumMap so. iterating a Map, Entry is valid advance next iteration. If, for example, try pass entrySet addAll method, badly wrong</technical_language>

Target:
public final String buildFreeTextConditionSql(String tableName, String relations, String value, boolean caseSensitive) { StringBuilder sb = new StringBuilder(" ( "); boolean firstTime = true; if (!StringHelper.isNullOrEmpty(value) && !"''".equals(value)) { value = StringFormat.format(getI18NPrefix() + "'%%%1$s%%'", StringHelper.trim(value, '\'')); } if ("=".equals(relations)) { relations = getLikeSyntax(caseSensitive); } else if ("!=".equals(relations)) { relations = "NOT " + getLikeSyntax(caseSensitive); } SortedSet<Map.Entry<String, String>> sortedEntrySet = new TreeSet<>(new ColNameMapEntryComparator()); for (Map.Entry<String, String> entry : columnNameDict.entrySet()) { sortedEntrySet.add(entry); } for (Map.Entry<String, String> columnNameEntry : sortedEntrySet) { if (typeDict.get(columnNameEntry.getKey()) == String.class && !notFreeTextSearchableFieldsList.contains(columnNameEntry.getKey())) { if (firstTime) { firstTime = false; } else { sb.append(" OR "); } sb.append(StringFormat.format(" %1$s.%2$s %3$s %4$s", tableName, columnNameEntry.getValue(), relations, value)); } } sb.append(" ) "); return sb.toString(); }
Source:
<code>public void testGroupCreation() throws AuthenticationException, NoSuchAlgorithmException { identityManager.createNewGroup(TEACHER_USER_ID, VALID_ITEM_ID); final DBCursor cursor = db.getCollection(DatabaseStringConstants.USER_GROUP_COLLECTION).find(); final DBObject dbObject = cursor.next(); System.out.println(dbObject); Assert.assertEquals(VALID_ITEM_ID, dbObject.get(DatabaseStringConstants.COURSE_ID).toString()); String salt = HashManager.generateUnSecureSalt(dbObject.get(DatabaseStringConstants.COURSE_ID).toString()); String hash = null; try { hash = HashManager.toHex(HashManager.createHash(TEACHER_USER_ID, salt).getBytes()); <START> } catch (NoSuchAlgorithmException e) { <END> e.printStackTrace(); } catch (AuthenticationException e) { e.printStackTrace(); } DBObject nonUsers = new BasicDBObject(); nonUsers.put(TEACHER_USER_ID, hash); DBObject adminGroup = (DBObject) dbObject.get(DatabaseStringConstants.NON_USER_LIST); Assert.assertEquals(nonUsers, adminGroup); DBObject students = new BasicDBObject(); DBObject studentGroup = (DBObject) dbObject.get(DatabaseStringConstants.USER_LIST); Assert.assertEquals(students, studentGroup); }</code><technical_language>please combine 2 catches 1 do for both</technical_language>

Target:
public void testGroupCreation() throws AuthenticationException, NoSuchAlgorithmException { identityManager.createNewGroup(TEACHER_USER_ID, VALID_ITEM_ID); final DBCursor cursor = db.getCollection(DatabaseStringConstants.USER_GROUP_COLLECTION).find(); final DBObject dbObject = cursor.next(); System.out.println(dbObject); Assert.assertEquals(VALID_ITEM_ID, dbObject.get(DatabaseStringConstants.COURSE_ID).toString()); String salt = HashManager.generateUnSecureSalt(dbObject.get(DatabaseStringConstants.COURSE_ID).toString()); String hash = null; try { hash = HashManager.toHex(HashManager.createHash(TEACHER_USER_ID, salt).getBytes()); } catch (NoSuchAlgorithmException | AuthenticationException e) { e.printStackTrace(); } DBObject nonUsers = new BasicDBObject(); nonUsers.put(TEACHER_USER_ID, hash); DBObject adminGroup = (DBObject) dbObject.get(DatabaseStringConstants.NON_USER_LIST); Assert.assertEquals(nonUsers, adminGroup); DBObject students = new BasicDBObject(); DBObject studentGroup = (DBObject) dbObject.get(DatabaseStringConstants.USER_LIST); Assert.assertEquals(students, studentGroup); }
Source:
<code>public void testStdOut() { final VariantContextWriter writer = new VariantContextWriterBuilder().setOutputFile("/dev/stdout").clearOptions().build(); <START> Assert.assertNotEquals(((VCFWriter) writer).getOutputStream(), null); <END> Assert.assertNotEquals(((VCFWriter) writer).getStreamName(), IndexingVariantContextWriter.DEFAULT_READER_NAME); }</code><technical_language>Assert.notNull</technical_language>

Target:
public void testStdOut() { final VariantContextWriter writer = new VariantContextWriterBuilder().setOutputFile("/dev/stdout").clearOptions().build(); OutputStream s = ((VCFWriter) writer).getOutputStream(); Assert.assertNotNull(((VCFWriter) writer).getOutputStream()); Assert.assertNotEquals(((VCFWriter) writer).getStreamName(), IndexingVariantContextWriter.DEFAULT_READER_NAME); }
Source:
<code>public Response handle() throws Exception { ServerSideSession session = getDriver().getSession(getRequest().getSession()); <START> List<String> types = new ArrayList<String>(session.getLogManager().getTypes()); <END> Collections.sort(types); return createResponse(types); }</code><technical_language>remove sorting. If possible, convert a List either, if JSON serialization prints a Set a JSON array</technical_language>

Target:
public Response handle() throws Exception { ServerSideSession session = getDriver().getSession(getRequest().getSession()); Set<String> types = session.getLogManager().getTypes(); return createResponse(types); }
Source:
<code>public List<String> getTokens() { ArrayList<String> ret = new ArrayList<>(this.tokenCount); <START> <END> for (int i = 0; i < this.tokenCount; i++) { ret.add(getToken(i)); } return ret; }</code><technical_language>Coding practices: Interface i = new Implementation();</technical_language>

Target:
public List<String> getTokens() { List<String> ret = new ArrayList<String>(tokenCount); for (int i = 0; i < tokenCount; i++) { ret.add(getToken(i)); } return ret; }
Source:
<code>private static void launchMaster(final URL directory) { LaunchTask masterTask = new LaunchTask() { @Override public void run() { log.info("Starting Master"); boolean isStandByMode = Boolean.parseBoolean(environmentProperties.getProperty("realtime.enable.standby.mode")); if (isStandByMode) { while (isStandByMode) { environmentProperties.setProperty(TEST_CONFIG_NAME_PROP, getTestConfigName()); XmlWebApplicationContext context = (XmlWebApplicationContext) loadContext(directory, MASTER_CONFIGURATION, environmentProperties); final Coordinator coordinator = (Coordinator) context.getBean("coordinator"); coordinator.waitForReady(); coordinator.initialize(); Master master = (Master) context.getBean("master"); master.run(); <START> context.destroy(); <END> } } else { WebApplicationContext context = loadContext(directory, MASTER_CONFIGURATION, environmentProperties); Server server = new Server(getPortFrom("master.rest.http.port", 9090)); try { server.setHandler(getServletContextHandler(context)); server.start(); final Coordinator coordinator = (Coordinator) context.getBean("coordinator"); coordinator.waitForReady(); coordinator.initialize(); Master master = (Master) context.getBean("master"); master.run(); } catch (Exception e) { log.error("Error during embedded Jetty handling.", e); throw new RuntimeException(e); } finally { try { server.stop(); } catch (Exception e) { throw new RuntimeException(e); } } } } }; builder.addMainTask(masterTask); }</code><technical_language>MASTER_CONFIGURATION executed time time? do need it</technical_language>

Target:
private static void launchMaster(final URL directory) { LaunchTask masterTask = new LaunchTask() { @Override public void run() { boolean isStandByMode = Boolean.parseBoolean(environmentProperties.getProperty("realtime.enable.standby.mode")); if (isStandByMode) { log.info("Starting Master in stand by mode..."); while (isStandByMode) { environmentProperties.setProperty(TEST_CONFIG_NAME_PROP, getTestConfigName()); XmlWebApplicationContext context = (XmlWebApplicationContext) loadContext(directory, MASTER_CONFIGURATION, environmentProperties); initCoordinator(context); Master master = (Master) context.getBean("master"); master.run(); context.destroy(); } } else { log.info("Starting Master in right away mode..."); WebApplicationContext context = loadContext(directory, MASTER_CONFIGURATION, environmentProperties); Server server = new Server(getPortFrom("master.rest.http.port", 9090)); try { server.setHandler(getServletContextHandler(context)); server.start(); initCoordinator(context); Master master = (Master) context.getBean("master"); master.run(); } catch (Exception e) { log.error("Error during embedded Jetty handling.", e); throw new RuntimeException(e); } finally { try { server.stop(); } catch (Exception e) { throw new RuntimeException(e); } } } } }; builder.addMainTask(masterTask); }
Source:
<code>private DownloadSection writeCSV(DataGrid grid, ContentWriter contentWriter, String csvPath) throws IOException, BadRequestException { try ( OutputStream outputStream = contentWriter.getOutputStream(csvPath); CSVWriter writer = new CSVWriter(new OutputStreamWriter(outputStream, Charset.forName("UTF8")), ',') <START> ) { <END> for (DataGridRow dataGridRow : grid.metadata) { String[] row = new String[dataGridRow.cells.size() + 1]; row[0] = dataGridRow.label; for (int i = 1; i <= dataGridRow.cells.size(); i++) row[i] = dataGridRow.cells.get(i - 1); writer.writeNext(row); } for (DataGridRow dataGridRow : grid.rows) { String[] row = new String[dataGridRow.cells.size() + 1]; row[0] = dataGridRow.label; for (int i = 1; i <= dataGridRow.cells.size(); i++) row[i] = dataGridRow.cells.get(i - 1); writer.writeNext(row); } } return newDownloadSection("csv download", csvPath); }</code><technical_language>Consider declaring instance of OutputStreamWriter variable in try resources. If CSVWriter constructor throws exception OutputStreamWriter is closed</technical_language>

Target:
private DownloadSection writeCSV(DataGrid grid, ContentWriter contentWriter, String csvPath) throws IOException, BadRequestException { try ( OutputStream outputStream = contentWriter.getOutputStream(csvPath); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, Charset.forName("UTF8")); CSVWriter writer = new CSVWriter(outputStreamWriter) ) { for (DataGridRow dataGridRow : grid.metadata) { String[] row = new String[dataGridRow.cells.size() + 1]; row[0] = dataGridRow.label; for (int i = 1; i <= dataGridRow.cells.size(); i++) row[i] = dataGridRow.cells.get(i - 1); writer.writeNext(row); } for (DataGridRow dataGridRow : grid.rows) { String[] row = new String[dataGridRow.cells.size() + 1]; row[0] = dataGridRow.label; for (int i = 1; i <= dataGridRow.cells.size(); i++) row[i] = dataGridRow.cells.get(i - 1); writer.writeNext(row); } } return newDownloadSection("csv download", csvPath); }
Source:
<code>public static JSONObject msgIntegrityToJson(MsgIntegrityViolationWrapper msgIntegrityViolationWrapper) throws JSONException { JSONObject scenarioObj = new JSONObject(); ArrayList<JSONObject> violationsList = new ArrayList<JSONObject>(); scenarioObj.put("superstepId", msgIntegrityViolationWrapper.getSuperstepNo()); for(Object msgWrapper : msgIntegrityViolationWrapper.getExtendedOutgoingMessageWrappers()) { <START> ExtendedOutgoingMessageWrapper extendedOutgoingMessgeWrapper = <END> (ExtendedOutgoingMessageWrapper) msgWrapper; JSONObject violationObj = new JSONObject(); violationObj.put("srcId", extendedOutgoingMessgeWrapper.srcId); violationObj.put("destinationId", extendedOutgoingMessgeWrapper.destinationId); violationObj.put("message", extendedOutgoingMessgeWrapper.message); violationsList.add(violationObj); } scenarioObj.put("violations", violationsList); return scenarioObj; }</code><technical_language>type: extendedOutgoingMessgeWrapper => extendedOutgoingMessageWrapper (a is missing in MessgeWrapper)</technical_language>

Target:
public static JSONObject msgIntegrityToJson( MsgIntegrityViolationWrapper msgIntegrityViolationWrapper) throws JSONException { JSONObject scenarioObj = new JSONObject(); ArrayList<JSONObject> violationsList = new ArrayList<JSONObject>(); scenarioObj.put("superstepId", msgIntegrityViolationWrapper.getSuperstepNo()); for (Object msgWrapper : msgIntegrityViolationWrapper.getExtendedOutgoingMessageWrappers()) { ExtendedOutgoingMessageWrapper extendedOutgoingMessageWrapper = (ExtendedOutgoingMessageWrapper) msgWrapper; JSONObject violationObj = new JSONObject(); violationObj.put("srcId", extendedOutgoingMessageWrapper .srcId); violationObj.put("destinationId", extendedOutgoingMessageWrapper .destinationId); violationObj.put("message", extendedOutgoingMessageWrapper .message); violationsList.add(violationObj); } scenarioObj.put("violations", violationsList); return scenarioObj; }
Source:
<code>protected void wait( Callable<Boolean> conditionIsMet, long maxWait, long pollInterval, String onFailureMessage) <START> throws InterruptedException { <END> final long startTime = System.currentTimeMillis(); LOGGER.trace("Waiting for condition to be met. Max wait time: ms", maxWait); while (true) { try { if (conditionIsMet.call()) { return; } long remainingTime = getRemainingTime(startTime, maxWait); if (remainingTime <= 0) { LOGGER.trace("Condition not met within [{}]", maxWait); throw new SynchronizedInstallerTimeoutException(onFailureMessage); } Thread.sleep(Math.min(remainingTime, pollInterval)); } catch (InterruptedException e) { throw e; } catch (Exception e) { throw new SynchronizedInstallerException( "Exception thrown while waiting for condition to be met.", e); } } }</code><technical_language>package-private for methods left visible for testing</technical_language>

Target:
void wait( Callable<Boolean> conditionIsMet, long maxWait, long pollInterval, String onFailureMessage) throws InterruptedException { final long startTime = System.currentTimeMillis(); LOGGER.trace("Waiting for condition to be met. Max wait time: ms", maxWait); while (true) { try { if (conditionIsMet.call()) { return; } long remainingTime = getRemainingTime(startTime, maxWait); if (remainingTime <= 0) { LOGGER.trace("Condition not met within [{}]", maxWait); throw new SynchronizedInstallerTimeoutException(onFailureMessage); } Thread.sleep(Math.min(remainingTime, pollInterval)); } catch (InterruptedException e) { throw e; } catch (Exception e) { throw new SynchronizedInstallerException( "Exception thrown while waiting for condition to be met.", e); } } }
Source:
<code>public String render(final GetSystemFailureResult obj) { final SystemFailureList result = obj.getResult(); if( (result == null) <START> || (null == result.getSystemFailures()) <END> || (result.getSystemFailures().size() == 0) ) { return "No system failures on remote appliance"; } this.failures = result.getSystemFailures(); initTable(ImmutableList.of("Type", "Failure Message", "Id", "Failure Date")); return "" + result.getSystemFailures().size() + " System Failures:\n" + ASCIITable.getInstance().getTable(getHeaders(), formatTableContents()); }</code><technical_language>getSystemFailures returns a list, a nullGuard</technical_language>

Target:
public String render(final GetSystemFailureResult obj) { final SystemFailureList result = obj.getResult(); if( (result == null) || (Guard.isNullOrEmpty(result.getSystemFailures())) ) { return "No system failures on remote appliance"; } this.failures = result.getSystemFailures(); initTable(ImmutableList.of("Type", "Failure Message", "Id", "Failure Date")); return "" + result.getSystemFailures().size() + " System Failures:\n" + ASCIITable.getInstance().getTable(getHeaders(), formatTableContents()); }
Source:
<code>private Bundle getLoginBundledIntent(AccountAuthenticatorResponse response, String accountType, String authTokenType, boolean isNew) { <START> final Intent intent = new Intent(mContext, LoginActivity.class); <END> intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response); intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType); intent.putExtra(LoginActivity.NEW_ACCOUNT, isNew); intent.putExtra(LoginActivity.AUTH_TOKEN_TYPE, authTokenType); final Bundle bundle = new Bundle(); bundle.putParcelable(AccountManager.KEY_INTENT, intent); return bundle; }</code><technical_language>This intent returned a createIntentX() method</technical_language>

Target:
private Bundle getLoginBundledIntent(AccountAuthenticatorResponse response, String accountType, String authTokenType, boolean isNew) { Intent intent = createIntentLogin(response, accountType, authTokenType, isNew); Bundle bundle = new Bundle(); bundle.putParcelable(AccountManager.KEY_INTENT, intent); return bundle; }
Source:
<code>public void validate(final SCM scmConfig) { final String pluginId = scmConfig.getPluginConfiguration().getId(); final SCMPropertyConfiguration configuration = getScmPropertyConfiguration(scmConfig); ValidationResult validationResult = scmExtension.isSCMConfigurationValid(pluginId, configuration); if (SCMMetadataStore.getInstance().hasPreferenceFor(pluginId)) { SCMConfigurations configurationMetadata = SCMMetadataStore.getInstance().getConfigurationMetadata(pluginId); for (SCMConfiguration scmConfiguration : configurationMetadata.list()) { String key = scmConfiguration.getKey(); boolean isRequired = SCMMetadataStore.getInstance().hasOption(pluginId, key, Property.REQUIRED); ConfigurationProperty property = scmConfig.getConfiguration().getProperty(key); String configValue = property == null ? null : property.getValue(); if (isRequired && StringUtil.isBlank(configValue)) { validationResult.addError(new ValidationError(key, localizer.localize("MANDATORY_CONFIGURATION_FIELD"))); } } } for (ValidationError validationError : validationResult.getErrors()) { <START> scmConfig.getConfiguration().getProperty(validationError.getKey()).addError(validationError.getKey(), validationError.getMessage()); <END> } }</code><technical_language>If a plugin author returns a validation result a wrong key, this line throw a null pointer exception. I this deserves a check</technical_language>

Target:
public void validate(final SCM scmConfig) { final String pluginId = scmConfig.getPluginConfiguration().getId(); final SCMPropertyConfiguration configuration = getScmPropertyConfiguration(scmConfig); ValidationResult validationResult = scmExtension.isSCMConfigurationValid(pluginId, configuration); if (SCMMetadataStore.getInstance().hasPreferenceFor(pluginId)) { SCMConfigurations configurationMetadata = SCMMetadataStore.getInstance().getConfigurationMetadata(pluginId); for (SCMConfiguration scmConfiguration : configurationMetadata.list()) { String key = scmConfiguration.getKey(); boolean isRequired = SCMMetadataStore.getInstance().hasOption(pluginId, key, Property.REQUIRED); ConfigurationProperty property = scmConfig.getConfiguration().getProperty(key); String configValue = property == null ? null : property.getValue(); if (isRequired && StringUtil.isBlank(configValue)) { validationResult.addError(new ValidationError(key, localizer.localize("MANDATORY_CONFIGURATION_FIELD"))); } } } for (ValidationError validationError : validationResult.getErrors()) { ConfigurationProperty property = scmConfig.getConfiguration().getProperty(validationError.getKey()); if (property != null) { property.addError(validationError.getKey(), validationError.getMessage()); } } }
Source:
<code>TrackerEvent(Event event) { <START> super(); <END> eventId = UUID.fromString(event.getEventId()); contexts = event.getContexts(); timestamp = event.getDeviceCreatedTimestamp(); trueTimestamp = event.getTrueTimestamp(); payload = event.getDataPayload(); isService = event instanceof TrackerError; if (event instanceof AbstractPrimitive) { eventName = ((AbstractPrimitive) event).getName(); isPrimitive = true; } else { schema = ((AbstractSelfDescribing) event).getSchema(); isPrimitive = false; } }</code><technical_language>This class superclass, need call super() here</technical_language>

Target:
TrackerEvent(Event event) { eventId = UUID.fromString(event.getEventId()); contexts = event.getContexts(); timestamp = event.getDeviceCreatedTimestamp(); trueTimestamp = event.getTrueTimestamp(); payload = event.getDataPayload(); isService = event instanceof TrackerError; if (event instanceof AbstractPrimitive) { eventName = ((AbstractPrimitive) event).getName(); isPrimitive = true; } else { schema = ((AbstractSelfDescribing) event).getSchema(); isPrimitive = false; } }
Source:
<code>public void handlesTwoRequestInOneConnection() throws Exception { final String text = "Hello Twice!"; final Socket socket = Mockito.mock(Socket.class); final String requests = Joiner.on(BkBasicTest.CRLF).join( BkBasicTest.POST, BkBasicTest.HOST, "Content-Length: 11", "", "Hello First", BkBasicTest.POST, BkBasicTest.HOST, "Content-Length: 12", "", "Hello Second" ); <START> final InputStream input = new ByteArrayInputStream(requests.getBytes()); <END> final OutputStream output = new ByteArrayOutputStream(); Mockito.when(socket.getLocalAddress()).thenReturn( InetAddress.getLocalHost() ); Mockito.when(socket.getInetAddress()).thenReturn( InetAddress.getLocalHost() ); Mockito.when(socket.getLocalPort()).thenReturn(0); Mockito.when(socket.getPort()).thenReturn(0); Mockito.when(socket.getInputStream()).thenReturn(input); Mockito.when(socket.getOutputStream()).thenReturn(output); new BkBasic(new TkText(text)).accept(socket); MatcherAssert.assertThat( socket.getOutputStream().toString(), RegexMatchers.containsPattern(text + ".*?" + text) ); }</code><technical_language>@danff get rid variable <LINK_0></technical_language>

Target:
public void handlesTwoRequestInOneConnection() throws Exception { final String text = "Hello Twice!"; final ByteArrayOutputStream output = new ByteArrayOutputStream(); final ServerSocket server = new ServerSocket(0); try { new Thread( new Runnable() { @Override public void run() { try { new BkBasic(new TkText(text)).accept( server.accept() ); } catch (final IOException exception) { throw new IllegalStateException(exception); } } } ).start(); final Socket socket = new Socket( server.getInetAddress(), server.getLocalPort() ); try { socket.getOutputStream().write( Joiner.on(BkBasicTest.CRLF).join( BkBasicTest.POST, BkBasicTest.HOST, "Content-Length: 11", "", "Hello First", BkBasicTest.POST, BkBasicTest.HOST, "Content-Length: 12", "", "Hello Second" ).getBytes() ); final InputStream input = socket.getInputStream(); final byte[] buffer = new byte[4096]; for (int count = input.read(buffer); count != -1; count = input.read(buffer)) { output.write(buffer, 0, count); } } finally { socket.close(); } } finally { server.close(); } MatcherAssert.assertThat( output.toString(), RegexMatchers.containsPattern(text + ".*?" + text) ); }
Source:
<code>public void store(Collection<E> entities) { <START> final Map<I, EntityRecordWithColumns> records = new HashMap<>(entities.size()); <END> for (E entity : entities) { final EntityRecordWithColumns recordWithColumns = toRecord(entity); records.put(entity.getId(), recordWithColumns); } recordStorage().write(records); }</code><technical_language>Guava method instead</technical_language>

Target:
public void store(Collection<E> entities) { final Map<I, EntityRecordWithColumns> records = newHashMapWithExpectedSize(entities.size()); for (E entity : entities) { final EntityRecordWithColumns recordWithColumns = toRecord(entity); records.put(entity.getId(), recordWithColumns); } recordStorage().write(records); }
Source:
<code>private static OffsetAndLength getReadStartAndLength( long splitStart, long splitLength, long lastStripeEnd, List<Long> stripeOffsets) { <START> if (stripeOffsets == null || stripeOffsets.isEmpty()) { <END> return new OffsetAndLength(0, 0); } long readStart = 0; long readEnd = 0; for (int i = 0; i < stripeOffsets.size(); ++i) { if (splitContainsStripe(splitStart, splitLength, stripeOffsets.get(i))) { readStart = Math.min(readStart, stripeOffsets.get(i)); readEnd = Math.max( readEnd, i == stripeOffsets.size() - 1 ? lastStripeEnd : stripeOffsets.get(i + 1)); } else if (readEnd > 0) { break; } } return new OffsetAndLength(readStart, readEnd - readStart); }</code><technical_language>case is this? Is a unit test for (null, empty?)</technical_language>

Target:
private static OffsetAndLength getReadStartAndLength( long splitStart, long splitLength, long lastStripeEnd, List<Long> stripeOffsets) { checkArgument(stripeOffsets != null, "stripeOffsets is null, failed to read page file footer."); if (stripeOffsets.isEmpty()) { return new OffsetAndLength(0, 0); } long readStart = 0; long readEnd = 0; boolean stripeFound = false; for (int i = 0; i < stripeOffsets.size(); ++i) { if (splitContainsStripe(splitStart, splitLength, stripeOffsets.get(i))) { if (!stripeFound) { readStart = stripeOffsets.get(i); stripeFound = true; } readEnd = i == stripeOffsets.size() - 1 ? lastStripeEnd : stripeOffsets.get(i + 1); } else if (stripeFound) { break; } } return new OffsetAndLength(readStart, readEnd - readStart); }
Source:
<code>public void updateFromItem(final InfoItem infoItem, final HistoryRecordManager historyRecordManager) { if (!(infoItem instanceof CommentsInfoItem)) { return; } final CommentsInfoItem item = (CommentsInfoItem) infoItem; itemBuilder.getImageLoader() .displayImage(item.getUploaderAvatarUrl(), itemThumbnailView, ImageDisplayConstants.DISPLAY_THUMBNAIL_OPTIONS); itemThumbnailView.setOnClickListener(view -> openCommentAuthor(item)); streamUrl = item.getUrl(); itemContentView.setLines(COMMENT_DEFAULT_LINES); commentText = item.getCommentText(); itemContentView.setText(commentText); itemContentView.setOnTouchListener(CommentTextOnTouchListener.INSTANCE); if (itemContentView.getLineCount() == 0) { itemContentView.post(this::ellipsize); } else { ellipsize(); } if (item.getLikeCount() >= 0) { itemLikesCountView.setText(String.valueOf(item.getLikeCount())); } else { itemLikesCountView.setText("-"); } if (item.getUploadDate() != null) { itemPublishedTime.setText(Localization.relativeTime(item.getUploadDate().date())); } else { itemPublishedTime.setText(item.getTextualUploadDate()); } itemView.setOnClickListener(view -> { toggleEllipsize(); if (itemBuilder.getOnCommentsSelectedListener() != null) { itemBuilder.getOnCommentsSelectedListener().selected(item); } }); itemView.setOnLongClickListener(view -> { <START> if (!AndroidTvUtils.isTv(itemBuilder.getContext())) { ShareUtils.copyToClipboard(itemBuilder.getContext(), commentText); } else { openCommentAuthor(item); } <END> return true; }); }</code><technical_language>I code, logic non-TV is more common</technical_language>

Target:
public void updateFromItem(final InfoItem infoItem, final HistoryRecordManager historyRecordManager) { if (!(infoItem instanceof CommentsInfoItem)) { return; } final CommentsInfoItem item = (CommentsInfoItem) infoItem; itemBuilder.getImageLoader() .displayImage(item.getUploaderAvatarUrl(), itemThumbnailView, ImageDisplayConstants.DISPLAY_THUMBNAIL_OPTIONS); itemThumbnailView.setOnClickListener(view -> openCommentAuthor(item)); streamUrl = item.getUrl(); itemContentView.setLines(COMMENT_DEFAULT_LINES); commentText = item.getCommentText(); itemContentView.setText(commentText); itemContentView.setOnTouchListener(CommentTextOnTouchListener.INSTANCE); if (itemContentView.getLineCount() == 0) { itemContentView.post(this::ellipsize); } else { ellipsize(); } if (item.getLikeCount() >= 0) { itemLikesCountView.setText(String.valueOf(item.getLikeCount())); } else { itemLikesCountView.setText("-"); } if (item.getUploadDate() != null) { itemPublishedTime.setText(Localization.relativeTime(item.getUploadDate().date())); } else { itemPublishedTime.setText(item.getTextualUploadDate()); } itemView.setOnClickListener(view -> { toggleEllipsize(); if (itemBuilder.getOnCommentsSelectedListener() != null) { itemBuilder.getOnCommentsSelectedListener().selected(item); } }); itemView.setOnLongClickListener(view -> { if (AndroidTvUtils.isTv(itemBuilder.getContext())) { openCommentAuthor(item); } else { ShareUtils.copyToClipboard(itemBuilder.getContext(), commentText); } return true; }); }
Source:
<code>public void onStartProfiler() { dependencyManager_.withProfvis(profilerDependecyUserAction_, new Command() { @Override public void execute() { enableStartedCommands(); ProfileOperationRequest request = ProfileOperationRequest .create(""); server_.startProfiling(request, new ServerRequestCallback<ProfileOperationResponse>() { @Override public void onResponseReceived(ProfileOperationResponse response) { if (response.getErrorMessage() != null) { globalDisplay_.showErrorMessage("Profiler Error", response.getErrorMessage()); return; } response_ = response; } @Override public void onError(ServerError error) { <START> globalDisplay_.showErrorMessage("Failed to Stop Profiler", <END> error.getMessage()); } }); } }); }</code><technical_language>enableStartedCommands() if start profiling</technical_language>

Target:
public void onStartProfiler() { dependencyManager_.withProfvis(profilerDependecyUserAction_, new Command() { @Override public void execute() { ProfileOperationRequest request = ProfileOperationRequest .create(""); server_.startProfiling(request, new ServerRequestCallback<ProfileOperationResponse>() { @Override public void onResponseReceived(ProfileOperationResponse response) { if (response.getErrorMessage() != null) { globalDisplay_.showErrorMessage("Profiler Error", response.getErrorMessage()); return; } response_ = response; } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage("Failed to Stop Profiler", error.getMessage()); } }); } }); }
Source:
<code>public FacebookPhoto publishToFacebook(byte[] inputBytes, String fileName, String message) { FacebookPhoto response; try { response = client.publish("me/photos", FacebookPhoto.class, <START> BinaryAttachment.with(fileName, inputBytes), Parameter.with("message", message)); <END> } catch (Exception e) { return null; } return response; }</code><technical_language>a question, fileName is name file FB, right</technical_language>

Target:
public FacebookPhoto publishToFacebook(byte[] inputBytes, String fileName, String message) { FacebookPhoto response; try { response = client.publish("me/photos", FacebookPhoto.class, BinaryAttachment.with(fileName, inputBytes), Parameter.with("message", message)); } catch (FacebookException e) { return null; } return response; }
Source:
<code>public Map<String, String> getUAMap(String uaString) { result.clear(); UserAgent browser = null; Device device = null; OS os = null; if (uaString == null) uaString = ""; try { Client c = cachingParser.parse(uaString); if (c != null) { browser = c.userAgent; device = c.device; os = c.os; } } catch (Exception e) { LOG.error(e.getMessage(), e); } if (browser != null) { result.put("browser_family", replaceNA(browser.family)); result.put("browser_major", replaceNA(browser.major)); } else { result.put("browser_family", NA); result.put("browser_major", NA); } if (device != null) { result.put("device_family", replaceNA(device.family)); } else { result.put("device_family", NA); } if (os != null) { result.put("os_family", replaceNA(os.family)); result.put("os_major", replaceNA(os.major)); result.put("os_minor", replaceNA(os.minor)); } else { result.put("os_family", NA); result.put("os_major", NA); result.put("os_minor", NA); } String appVersion = Utilities.getMatched(appVersionPattern, uaString, 1); if (appVersion == null) appVersion = NA; <START> result.put("app_version", appVersion); <END> return result; }</code><technical_language>name this key 'wiki_app_version', for wikimedia App</technical_language>

Target:
public Map<String, String> getUAMap(String uaString) { result.clear(); UserAgent browser = null; Device device = null; OS os = null; if (uaString == null) uaString = ""; try { Client c = cachingParser.parse(uaString); if (c != null) { browser = c.userAgent; device = c.device; os = c.os; } } catch (Exception e) { LOG.error(e.getMessage(), e); } if (browser != null) { result.put("browser_family", replaceNA(browser.family)); result.put("browser_major", replaceNA(browser.major)); } else { result.put("browser_family", NA); result.put("browser_major", NA); } if (device != null) { result.put("device_family", replaceNA(device.family)); } else { result.put("device_family", NA); } if (os != null) { result.put("os_family", replaceNA(os.family)); result.put("os_major", replaceNA(os.major)); result.put("os_minor", replaceNA(os.minor)); } else { result.put("os_family", NA); result.put("os_major", NA); result.put("os_minor", NA); } if (uaString.startsWith("WikipediaApp")) { String delimiterIndex = uaString.indexOf(' ', 13); result.put("wmf_app_version", uaString.substring(13, delimiterIndex)); } else { result.put("wmf_app_version", NA); } return result; }
Source:
<code>public static void dropReplicationSlot(Connection connection, String slotName) throws SQLException, InterruptedException { if (isReplicationSlotActive(connection, slotName)) { if (haveMinimumServerVersion(connection, ServerVersion.v9_5)) { PreparedStatement terminateStatement = connection.prepareStatement( "select pg_terminate_backend(active_pid) from pg_replication_slots " + "where active = true and slot_name= ?"); terminateStatement.setString(1, slotName); terminateStatement.execute(); terminateStatement.close(); } else { boolean stillActive = true; while (stillActive) { <START> TimeUnit.MILLISECONDS.sleep(100L); <END> stillActive = isReplicationSlotActive(connection, slotName); } } } try { PreparedStatement dropStatement = connection.prepareStatement( "select pg_drop_replication_slot(slot_name) " + "from pg_replication_slots where slot_name = ?" ); dropStatement.setString(1, slotName); dropStatement.execute(); dropStatement.close(); } catch (PSQLException e) { if (PSQLState.OBJECT_IN_USE.equals(new PSQLState(e.getSQLState()))) { dropReplicationSlot(connection, slotName); } else { throw e; } } }</code><technical_language>@Gordiychuk , please add some explicit timeout here. For instance 30 seconds so. Travis builds get stuck. Generic rule: cycle explicit timeout</technical_language>

Target:
public static void dropReplicationSlot(Connection connection, String slotName) throws SQLException, InterruptedException, TimeoutException { if (haveMinimumServerVersion(connection, ServerVersion.v9_5)) { PreparedStatement stm = null; try { stm = connection.prepareStatement( "select pg_terminate_backend(active_pid) from pg_replication_slots " + "where active = true and slot_name = ?"); stm.setString(1, slotName); stm.execute(); } finally { closeQuietly(stm); } } waitStopReplicationSlot(connection, slotName); PreparedStatement stm = null; try { stm = connection.prepareStatement( "select pg_drop_replication_slot(slot_name) " + "from pg_replication_slots where slot_name = ?"); stm.setString(1, slotName); stm.execute(); } finally { closeQuietly(stm); } }
Source:
<code>private OfflineUserRestore initDemoUserRestore() throws ResourceInitializationException { try { return new OfflineUserRestore(localLocation); } catch (UnfullfilledRequirementsException e) { <START> throw new ResourceInitializationException(e.getMessage()); <END> } catch (IOException | InvalidStructureException | XmlPullParserException e) { throw new ResourceInitializationException("Demo user restore file was malformed, " + "the following error occurred during parsing: " + e.getMessage()); } catch (InvalidReferenceException e) { throw new ResourceInitializationException( "Reference to demo user restore file was invalid: " + e.getMessage()); } }</code><technical_language>more very, minor point: wrapping exceptions properly (IE: initializing throwable source in new exception) adding string message, lose relevant part of stack trace. This is a general habit get error handling</technical_language>

Target:
private OfflineUserRestore initDemoUserRestore() throws ResourceInitializationException { try { return new OfflineUserRestore(localLocation); } catch (UnfullfilledRequirementsException e) { throw new ResourceInitializationException(e.getMessage(), e); } catch (IOException | InvalidStructureException | XmlPullParserException e) { throw new ResourceInitializationException("Demo user restore file was malformed, " + "the following error occurred during parsing: " + e.getMessage(), e); } catch (InvalidReferenceException e) { throw new ResourceInitializationException( "Reference to demo user restore file was invalid: " + e.getMessage(), e); } }
Source:
<code>public CustomParentViewHolder(View itemView, ParentItemClickListener parentItemClickListener) { super(itemView, parentItemClickListener); numberText = (TextView) itemView.findViewById(R.id.recycler_item_number_parent); dataText = (TextView) itemView.findViewById(R.id.recycler_item_text_parent); arrowExpand = (ImageButton) itemView.findViewById(R.id.recycler_item_arrow_parent); setCustomClickableView(arrowExpand); <START> setRoataion(200); <END> }</code><technical_language>Typo</technical_language>

Target:
public CustomParentViewHolder(View itemView, ParentItemClickListener parentItemClickListener) { super(itemView, parentItemClickListener); numberText = (TextView) itemView.findViewById(R.id.recycler_item_number_parent); dataText = (TextView) itemView.findViewById(R.id.recycler_item_text_parent); arrowExpand = (ImageButton) itemView.findViewById(R.id.recycler_item_arrow_parent); setCustomClickableView(arrowExpand); setRotation(200); }
Source:
<code>public List<String> getRecipients() { List<String> recipients = Lists.newArrayList(); Boolean consentNotificationEmailVerified = getStudy().isConsentNotificationEmailVerified(); if (consentNotificationEmailVerified == null || consentNotificationEmailVerified) { Set<String> studyRecipients = BridgeUtils.commaListToOrderedSet(getStudy().getConsentNotificationEmail()); recipients.addAll( studyRecipients ); <START> } <END> return recipients; }</code><technical_language>Unit tests for verified flag? Unit tests for null withdraw email</technical_language>

Target:
public List<String> getRecipients() { return recipients; }
Source:
<code>BackupSupportingClasses createSupportingClassesForBackupStrategies( Config config ) { PageCache pageCache = createPageCache( fileSystemAbstraction, config ); return new BackupSupportingClasses( <START> backupDelegatorFormConfig( pageCache, config ), <END> haFromConfig( pageCache ), pageCache ); }</code><technical_language>Form</technical_language>

Target:
BackupSupportingClasses createSupportingClassesForBackupStrategies( Config config ) { PageCache pageCache = createPageCache( fileSystemAbstraction, config ); return new BackupSupportingClasses( backupDelegatorFromConfig( pageCache, config ), haFromConfig( pageCache ), pageCache ); }
Source:
<code>public void optionalActivePublisherTest(long elements, PublisherTestRun<T> body) throws Throwable { if (elements > maxElementsFromPublisher()) throw new SkipException(String.format("Unable to run this test, as required elements nr: %d is higher than supported by given producer: %d", elements, maxElementsFromPublisher())); <START> Publisher<T> pub = createPublisher(elements); <END> try { potentiallyPendingTest(pub, body); } catch (Exception ex) { notVerified("Skipped because tested publisher does NOT implement this OPTIONAL requirement."); } }</code><technical_language>this a hook optional return null while active returns a Publisher</technical_language>

Target:
public void optionalActivePublisherTest(long elements, PublisherTestRun<T> body) throws Throwable { if (elements > maxElementsFromPublisher()) { throw new SkipException(String.format("Unable to run this test, as required elements nr: %d is higher than supported by given producer: %d", elements, maxElementsFromPublisher())); } final Publisher<T> pub = createPublisher(elements); final String skipMessage = "Skipped because tested publisher does NOT implement this OPTIONAL requirement."; try { potentiallyPendingTest(pub, body); } catch (Exception ex) { notVerified(skipMessage); } catch (AssertionError ex) { notVerified(skipMessage); } }
Source:
<code>public boolean delete(K key) throws GoraException { String deleteQuery = null; <START> Object[] keyl = null; <END> if (igniteMapping.getPrimaryKey().size() == 1) { deleteQuery = IgniteSQLBuilder.delete(igniteMapping); keyl = new Object[]{key}; } else { } try (PreparedStatement stmt = connection.prepareStatement(deleteQuery)) { IgniteSQLBuilder.fillDeleteStatement(stmt, igniteMapping, keyl); stmt.executeUpdate(); return true; } catch (SQLException ex) { throw new GoraException(ex); } }</code><technical_language>Please intuitive names for variables. Eg:- keyArray, keyValues</technical_language>

Target:
public boolean delete(K key) throws GoraException { String deleteQuery = null; Object[] keyArray = null; if (igniteMapping.getPrimaryKey().size() == 1) { deleteQuery = IgniteSQLBuilder.createDeleteQuery(igniteMapping); keyArray = new Object[]{key}; } else { } try (PreparedStatement stmt = connection.prepareStatement(deleteQuery)) { IgniteSQLBuilder.fillDeleteQuery(stmt, igniteMapping, keyArray); stmt.executeUpdate(); return true; } catch (SQLException ex) { throw new GoraException(ex); } }
Source:
<code>public String generate(TreeLogger treeLogger, GeneratorContext generatorContext, String typeName) throws UnableToCompleteException { setTypeOracle(generatorContext.getTypeOracle()); setTreeLogger(treeLogger); setPropertyOracle(generatorContext.getPropertyOracle()); <START> checkLatestVersion(); <END> PrintWriter printWriter = tryCreatePrintWriter(generatorContext); if (printWriter == null) { return typeName; } PresenterDefinitions presenterDefinitions = new PresenterDefinitions(); findAllPresenters(presenterDefinitions); ClassSourceFileComposerFactory composer = initComposer(); writeMandatoryGetterImports(composer); writePresenterImports(composer, presenterDefinitions); SourceWriter sourceWriter = composer.createSourceWriter(generatorContext, printWriter); writeMandatoryGetter(sourceWriter); writePresentersGetter(sourceWriter, presenterDefinitions); writeBundleGetters(sourceWriter, presenterDefinitions.getCodeSplitBundlePresenters(), generatorContext); Injector injector = Guice.createInjector(new RebindModule(new Logger(treeLogger), generatorContext)); writeFormFactors(injector); closeDefinition(sourceWriter); return DEFAULT_FQ_NAME; }</code><technical_language>This overkill, need check this ONCE</technical_language>

Target:
public String generate(TreeLogger treeLogger, GeneratorContext generatorContext, String typeName) throws UnableToCompleteException { setTypeOracle(generatorContext.getTypeOracle()); setTreeLogger(treeLogger); setPropertyOracle(generatorContext.getPropertyOracle()); PrintWriter printWriter = tryCreatePrintWriter(generatorContext); if (printWriter == null) { return typeName; } PresenterDefinitions presenterDefinitions = new PresenterDefinitions(); findAllPresenters(presenterDefinitions); ClassSourceFileComposerFactory composer = initComposer(); writeMandatoryGetterImports(composer); writePresenterImports(composer, presenterDefinitions); SourceWriter sourceWriter = composer.createSourceWriter(generatorContext, printWriter); writeMandatoryGetter(sourceWriter); writePresentersGetter(sourceWriter, presenterDefinitions); writeBundleGetters(sourceWriter, presenterDefinitions.getCodeSplitBundlePresenters(), generatorContext); Injector injector = Guice.createInjector(new RebindModule(new Logger(treeLogger), generatorContext)); writeFormFactors(injector); closeDefinition(sourceWriter); return DEFAULT_FQ_NAME; }