auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Status scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { try { Boolean returnFields = false; String[] fieldList = null; if (fields != null) { returnFields = true; fieldList = fields.toArray(new String[fields.size()]); } SolrQuery query = new SolrQuery(); query.setQuery("*:*"); query.setParam("fq", "id:[ " + startkey + " TO * ]"); if (returnFields) { query.setFields(fieldList); } query.setRows(recordcount); final QueryResponse response = client.query(table, query); HashMap<String, ByteIterator> entry; <START> for (SolrDocument hit : response.getResults()) { <END> entry = new HashMap<String, ByteIterator>((int) response.getResults().getNumFound()); for (String field : hit.getFieldNames()) { entry.put(field, new StringByteIterator(String.valueOf(hit.getFirstValue(field)))); } result.add(entry); } return checkStatus(response.getStatus()); } catch (IOException | SolrServerException e) { e.printStackTrace(); } return Status.ERROR; }</code><technical_language>nit: pull response.getResults() a variable? multiple calls getResults</technical_language>

Target:
public Status scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { try { Boolean returnFields = false; String[] fieldList = null; if (fields != null) { returnFields = true; fieldList = fields.toArray(new String[fields.size()]); } SolrQuery query = new SolrQuery(); query.setQuery("*:*"); query.setParam("fq", "id:[ " + startkey + " TO * ]"); if (returnFields) { query.setFields(fieldList); } query.setRows(recordcount); final QueryResponse response = client.query(table, query); SolrDocumentList results = response.getResults(); HashMap<String, ByteIterator> entry; for (SolrDocument hit : results) { entry = new HashMap<String, ByteIterator>((int) results.getNumFound()); for (String field : hit.getFieldNames()) { entry.put(field, new StringByteIterator(String.valueOf(hit.getFirstValue(field)))); } result.add(entry); } return checkStatus(response.getStatus()); } catch (IOException | SolrServerException e) { e.printStackTrace(); } return Status.ERROR; }
Source:
<code><START> private boolean isDirSnapshotable(DistributedFileSystem hdfs, Path path) throws FalconException { <END> try { LOG.debug("HDFS Snapshot extension validating if dir is snapshotable.", path.toString()); SnapshottableDirectoryStatus[] snapshotableDirs = hdfs.getSnapshottableDirListing(); if (snapshotableDirs != null && snapshotableDirs.length > 0) { for (SnapshottableDirectoryStatus dir : snapshotableDirs) { if (dir.getFullPath().toString().equals(path.toString())) { return true; } } } return false; } catch (IOException e) { LOG.error("Unable to verify if dir is snapshot-able. {}", path.toString(), e.getMessage()); throw new FalconException("Unable to verify if dir " + path.toString() + " is snapshot-able", e); } }</code><technical_language>method static</technical_language>

Target:
private static boolean isDirSnapshotable(DistributedFileSystem hdfs, Path path) throws FalconException { try { LOG.debug("HDFS Snapshot extension validating if dir is snapshotable.", path.toString()); SnapshottableDirectoryStatus[] snapshotableDirs = hdfs.getSnapshottableDirListing(); if (snapshotableDirs != null && snapshotableDirs.length > 0) { for (SnapshottableDirectoryStatus dir : snapshotableDirs) { if (dir.getFullPath().toString().equals(path.toString())) { return true; } } } return false; } catch (IOException e) { LOG.error("Unable to verify if dir is snapshot-able. {}", path.toString(), e.getMessage()); throw new FalconException("Unable to verify if dir " + path.toString() + " is snapshot-able", e); } }
Source:
<code>public RawPacket reverseTransform(RawPacket pkt){ long interArrivalTime = getInterArrivalDelayVariation (pkt.getSSRC(), pkt.getTimestamp(), System.currentTimeMillis(), <START> pkt.getLength()); <END> return pkt; }</code><technical_language>This getPayloadLength(), want. I if encoder's target bitrate (as in webrtc.org) want payload length only. bitrate calculations include RTP headers. cc @gpolitis</technical_language>

Target:
public RawPacket reverseTransform(RawPacket pkt){ getBitrateEstimate (pkt.getSSRC(), pkt.getTimestamp(), System.currentTimeMillis(), pkt.getLength()); return pkt; }
Source:
<code>public void initialize() { config = getConfigAs(${bindingIdCamelCase}Configuration.class); scheduler.execute(() -> { <START> boolean initialized = true; END> if (initialized) { } else { } }); updateStatus(ThingStatus.OFFLINE); }</code><technical_language>initialized is misleading - reachable online this is figure out</technical_language>

Target:
public void initialize() { config = getConfigAs(${bindingIdCamelCase}Configuration.class); scheduler.execute(() -> { boolean thingReachable = true; if (thingReachable) { } else { } }); updateStatus(ThingStatus.UNKNOWN); }
Source:
<code>public void setSyntax (String syntax) { <START> boolean isHighlightEnabled = getTxtOutput().getDocument().getLength() < HIGHLIGHT_SCRIPT_MAX_SIZE_THRESHOLD && !isLargeScriptContent; <END> getTxtOutput().setSyntaxEditingStyle(isHighlightEnabled ? syntax : SyntaxConstants.SYNTAX_STYLE_NONE); }</code><technical_language>highlightEnabled</technical_language>

Target:
public void setSyntax (String syntax) { boolean highlightEnabled = getTxtOutput().getDocument().getLength() < HIGHLIGHT_SCRIPT_MAX_SIZE_THRESHOLD && !largeScriptContentSet; getTxtOutput().setSyntaxEditingStyle(highlightEnabled ? syntax : SyntaxConstants.SYNTAX_STYLE_NONE); }
Source:
<code>protected Object transformValue(Object value, Field valueField) { if (null == value) { return null; } Schema nonnull = AvroUtils.unwrapIfNullable(valueField.schema()); LogicalType logicalType = nonnull.getLogicalType(); if (logicalType != null) { if (logicalType == LogicalTypes.date() || logicalType == LogicalTypes.timeMillis() || logicalType == LogicalTypes.timestampMillis()) { <START> return new Date(value instanceof Integer ? (Integer) value : (Long) value); <END> } } String talendType = valueField.getProp(TALEND6_COLUMN_TALEND_TYPE); String javaClass = nonnull.getProp(SchemaConstants.JAVA_CLASS_FLAG); if ("id_Short".equals(talendType)) { return value instanceof Number ? ((Number) value).shortValue() : Short.parseShort(String.valueOf(value)); } else if ("id_Date".equals(talendType) || "java.util.Date".equals(javaClass)) { return value instanceof Date ? value : new Date((Long) value); } else if ("id_Byte".equals(talendType)) { return value instanceof Number ? ((Number) value).byteValue() : Byte.parseByte(String.valueOf(value)); } else if ("id_Character".equals(talendType) || "java.lang.Character".equals(javaClass)) { return value instanceof Character ? value : ((String) value).charAt(0); } else if ("id_BigDecimal".equals(talendType) || "java.math.BigDecimal".equals(javaClass)) { return value instanceof BigDecimal ? value : new BigDecimal(String.valueOf(value)); } return value; }</code><technical_language>side - transformValue() method is critical for performance. is called times, need efficient possible</technical_language>

Target:
protected Object transformValue(Object value, Field valueField) { if (null == value) { return null; } Schema nonnull = AvroUtils.unwrapIfNullable(valueField.schema()); LogicalType logicalType = nonnull.getLogicalType(); if (logicalType != null) { if (logicalType == LogicalTypes.date()) { return dateConversion.fromInt((Integer) value, nonnull, logicalType).toDate(); } else if (logicalType == LogicalTypes.timeMillis()) { return value; } else if (logicalType == LogicalTypes.timestampMillis()) { return timestampConversion.fromLong((Long) value, nonnull, logicalType).toDate(); } } String talendType = valueField.getProp(TALEND6_COLUMN_TALEND_TYPE); String javaClass = nonnull.getProp(SchemaConstants.JAVA_CLASS_FLAG); if ("id_Short".equals(talendType)) { return value instanceof Number ? ((Number) value).shortValue() : Short.parseShort(String.valueOf(value)); } else if ("id_Date".equals(talendType) || "java.util.Date".equals(javaClass)) { return value instanceof Date ? value : new Date((Long) value); } else if ("id_Byte".equals(talendType)) { return value instanceof Number ? ((Number) value).byteValue() : Byte.parseByte(String.valueOf(value)); } else if ("id_Character".equals(talendType) || "java.lang.Character".equals(javaClass)) { return value instanceof Character ? value : ((String) value).charAt(0); } else if ("id_BigDecimal".equals(talendType) || "java.math.BigDecimal".equals(javaClass)) { return value instanceof BigDecimal ? value : new BigDecimal(String.valueOf(value)); } return value; }
Source:
<code>public void testFailRemoveOperation() { try { <START> domainManager.failRemoveOperation(domain, domainAccountsForCleanup, domainNetworkIds, true); <END> } catch (Exception e) { Assert.assertEquals(CloudRuntimeException.class, e.getClass()); } }</code><technical_language>removed of rollBackState, method problematic test. Therefore, @Test(expected=...), instead of this unusual construction here</technical_language>

Target:
public void testFailRemoveOperation() { domainManager.failRemoveOperation(domain, domainAccountsForCleanup, domainNetworkIds, true); }
Source:
<code>public void execute(Context context) throws SQLException { Multimap<Long, PropertyRow> rows = context .prepareSelect("select" + " props.id, props.prop_key, props.resource_id, prj.uuid, props.text_value, props.created_at" + " from properties props" + " left join projects prj on prj.id = props.resource_id and prj.scope = ? and prj.qualifier = ?" + " where" + " props.prop_key like 'sonar.webhooks%'" + <START> " and props.text_value is not null") <END> .setString(1, "PRJ") .setString(2, "TRK") .list(row -> new PropertyRow( row.getLong(1), row.getString(2), row.getNullableLong(3), row.getNullableString(4), row.getString(5), row.getLong(6))) .stream() .collect(MoreCollectors.index(PropertyRow::getResourceId, Function.identity())); for (Map.Entry<Long, Collection<PropertyRow>> entry : rows.asMap().entrySet()) { long projectId = entry.getKey(); if (projectId == NO_RESOURCE_ID) { migrateGlobalWebhooks(context, entry.getValue()); } else { migrateProjectsWebhooks(context, entry.getValue()); } deleteAllWebhookProperties(context); } }</code><technical_language>add prj.enabled=? true</technical_language>

Target:
public void execute(Context context) throws SQLException { Multimap<Long, PropertyRow> rows = context .prepareSelect("select" + " props.id, props.prop_key, props.resource_id, prj.uuid, props.text_value, props.created_at" + " from properties props" + " left join projects prj on prj.id = props.resource_id and prj.scope = ? and prj.qualifier = ? and prj.enabled = ?" + " where" + " props.prop_key like 'sonar.webhooks%'" + " and props.text_value is not null") .setString(1, "PRJ") .setString(2, "TRK") .setBoolean(3, true) .list(row -> new PropertyRow( row.getLong(1), row.getString(2), row.getNullableLong(3), row.getNullableString(4), row.getString(5), row.getLong(6))) .stream() .collect(MoreCollectors.index(PropertyRow::getResourceId, Function.identity())); for (Map.Entry<Long, Collection<PropertyRow>> entry : rows.asMap().entrySet()) { long projectId = entry.getKey(); if (projectId == NO_RESOURCE_ID) { migrateGlobalWebhooks(context, entry.getValue()); } else { migrateProjectsWebhooks(context, entry.getValue()); } deleteAllWebhookProperties(context); } }
Source:
<code>public void setup() { ELEMENTS = getRandomValues(CONTAINER_SIZE, 0); EXPECTED_AGGREGATE = Iterator.of(ELEMENTS).reduce(JmhRunner::aggregate); scalazPersistent = create(v -> { <START> scalaz.Heap<Integer> result = scalaz.Heap.Empty$.MODULE$.apply(); END> for (Integer element : v) { result = result.insert(element, SCALAZ_ORDER); } return result; }, Arrays.asList(ELEMENTS), v -> v.size() == CONTAINER_SIZE); slangPersistent = create(javaslang.collection.PriorityQueue::of, ELEMENTS, ELEMENTS.length, v -> v.size() == CONTAINER_SIZE); }</code><technical_language>// TODO rewrite .insertAll needed rewrite it</technical_language>

Target:
public void setup() { ELEMENTS = getRandomValues(CONTAINER_SIZE, 0); EXPECTED_AGGREGATE = Iterator.of(ELEMENTS).reduce(JmhRunner::aggregate); scalazPersistent = create(v -> scalaz.Heap.Empty$.MODULE$.<Integer> apply().insertAll(asScalaBuffer(v), SCALAZ_ORDER), asList(ELEMENTS), v -> v.size() == CONTAINER_SIZE); slangPersistent = create(javaslang.collection.PriorityQueue::of, ELEMENTS, ELEMENTS.length, v -> v.size() == CONTAINER_SIZE); }
Source:
<code>public void populateCache(UUID uuid) { CompletableFuture.runAsync(() -> { List<String> playerAchievementNamesList = databaseManager.getPlayerAchievementNamesList(uuid); <START> receivedAchievementsCache.put(uuid, new HashSet<>(playerAchievementNamesList)); <END> }); }</code><technical_language>now, receivedAchievementsCache main server thread. If want in asynchronous fashion, care thread-safe</technical_language>

Target:
public void populateCache(UUID uuid) { if (receivedAchievementsCache.containsKey(uuid)) return; CompletableFuture.runAsync(() -> { List<String> playerAchievementNamesList = databaseManager.getPlayerAchievementNamesList(uuid); receivedAchievementsCache.put(uuid, new HashSet<>(playerAchievementNamesList)); }); }
Source:
<code>@AfterClass public static void kiwwTheWabbit() { <START> rabbit.start(); <END> }</code><technical_language>Presume this code is supposed calling kiww, start</technical_language>

Target:
@AfterClass public static void kiwwTheWabbit() { rabbit.stop(); }
Source:
<code>protected static void checkIndexBounds(int[] indexList, int bound) { for (int i = 0; i < indexList.length; i++) { if (indexList[i] >= bound || indexList[i] < 0) { <START> throw new IllegalArgumentException("Index value out of bounds"); <END> } } }</code><technical_language>internal fail method instead of throw new Illeagal..</technical_language>

Target:
protected void checkIndexBounds(int[] indexList, int bound) { for (int i = 0; i < indexList.length; i++) { if (indexList[i] >= bound || indexList[i] < 0) { fail("Index value out of bounds"); } } }
Source:
<code>public InputStream decrypt(String studyId, InputStream source) { if (StringUtils.isBlank(studyId)) { throw new BadRequestException(String.format(Validate.CANNOT_BE_BLANK, "studyId")); } if (source == null) { throw new BadRequestException(String.format(Validate.CANNOT_BE_NULL, "source")); <START> } <END> CmsEncryptor encryptor = getEncryptorForStudy(studyId); try { return encryptor.decrypt(source); } catch (CertificateEncodingException | CMSException | IOException ex) { throw new BridgeServiceException(ex); } }</code><technical_language>this happen a user request? If not, checkNotNull here</technical_language>

Target:
public InputStream decrypt(String studyId, InputStream source) { checkNotNull(studyId); checkArgument(StringUtils.isNotBlank(studyId)); checkNotNull(source); CmsEncryptor encryptor = getEncryptorForStudy(studyId); try { return encryptor.decrypt(source); } catch (CertificateEncodingException | CMSException | IOException ex) { throw new BridgeServiceException(ex); } }
Source:
<code>public int hashCode() { return _apiVersion != null ? _apiVersion.hashCode() : 0; <START> } <END></code><technical_language>Please implement toString() provide debugging state information for debugging purposes</technical_language>

Target:
public int hashCode() { int result = super.hashCode(); result = 31 * result + (_apiVersion != null ? _apiVersion.hashCode() : 0); return result; }
Source:
<code>public Map<String, Object> toMap() { Map<String, Object> rootMap = super.toMap(); Map<String, Object> innerMap = (Map<String, Object>) rootMap.get(GEO_DISTANCE_FIELD); <START> Map<String, Double> location = new HashMap<String, Double>(2); <END> location.put( "lat", center.getLatitude() ); location.put( "lon", center.getLongitude() ); innerMap.put( fieldName, location ); innerMap.put( "unit", "km" ); return rootMap; }</code><technical_language>This initialized a size of 3. reason load factor defaulting .75. intended, put() trigger a resize of internal table</technical_language>

Target:
public Map<String, Object> toMap() { Map<String, Object> rootMap = super.toMap(); Map<String, Object> innerMap = (Map<String, Object>) rootMap.get(GEO_DISTANCE_FIELD); Map<String, Double> location = new HashMap<String, Double>(3); location.put( "lat", center.getLatitude() ); location.put( "lon", center.getLongitude() ); innerMap.put( fieldName, location ); innerMap.put( "unit", "km" ); innerMap.put( "distance_type", "arc" ); return rootMap; }
Source:
<code>public void testSetup() { initMocks(this); accountAdmin = new AccountAdminImpl(); accountAdmin.setLogger(logger); accountAdmin.setAccountStorage(storage); accountAdmin.setAuthenticationAdmin(authenticationAdmin); accountAdmin.start(Collections.<String, Object> emptyMap()); <START> when(newAccount.getGuid()).thenReturn(ID); <END> when(preferences.getId()).thenReturn(ID); when(preferences.getId()).thenReturn(ID); }</code><technical_language>twice</technical_language>

Target:
public void testSetup() { initMocks(this); accountAdmin = new AccountAdminImpl(); accountAdmin.setLogger(logger); accountAdmin.setAccountStorage(storage); accountAdmin.setAuthenticationAdmin(authenticationAdmin); accountAdmin.start(Collections.<String, Object> emptyMap()); when(newAccount.getGuid()).thenReturn(ID); when(preferences.getId()).thenReturn(ID); }
Source:
<code>public BinaryContent transform(Metacard metacard, Map<String, Serializable> arguments) throws CatalogTransformerException { if (metacard == null) { LOGGER.debug("Attempted to transform null metacard"); throw new CatalogTransformerException("Unable to transform null metacard"); } Map<String, String> aliases = (Map<String, String>) arguments.getOrDefault("aliases", new HashMap<>()); String attributeString = (String) arguments.get("columnOrder"); ArrayList<String> attributes = new ArrayList<String>(Arrays.asList((attributeString).split(","))); ArrayList<AttributeDescriptor> allAttributes = new ArrayList<AttributeDescriptor>(metacard.getMetacardType().getAttributeDescriptors()); ArrayList<AttributeDescriptor> descriptors = new ArrayList<AttributeDescriptor>( <START> attributes == null || attributes.isEmpty() <END> ? allAttributes : allAttributes .stream() .filter(attr -> attributes.contains(attr.getName())) .collect(Collectors.toList())); Appendable appendable = writeMetacardsToCsv(Collections.singletonList(metacard), descriptors, aliases); return createResponse(appendable); }</code><technical_language>CollectionUtils.isEmpty(attributes) instead</technical_language>

Target:
public BinaryContent transform(Metacard metacard, Map<String, Serializable> arguments) throws CatalogTransformerException { if (metacard == null) { LOGGER.debug("Attempted to transform null metacard"); throw new CatalogTransformerException("Unable to transform null metacard"); } Map<String, String> aliases = (Map<String, String>) arguments.getOrDefault("aliases", new HashMap<>()); String attributeString = arguments.get(CsvQueryResponseTransformer.COLUMN_ORDER_KEY) != null ? (String) arguments.get(CsvQueryResponseTransformer.COLUMN_ORDER_KEY) : ""; List<String> attributes = Arrays.asList((attributeString).split(",")); List<AttributeDescriptor> allAttributes = new ArrayList<AttributeDescriptor>(metacard.getMetacardType().getAttributeDescriptors()); List<AttributeDescriptor> descriptors = CollectionUtils.isEmpty(attributes) ? allAttributes : allAttributes.stream() .filter(attr -> attributes.contains(attr.getName())) .collect(Collectors.toList()); Appendable appendable = writeMetacardsToCsv(Collections.singletonList(metacard), descriptors, aliases); return createResponse(appendable); }
Source:
<code>public static File getFile(Object source, String filename) throws IOException { Class<?> clazz = (source instanceof Class<?>) ? (Class<?>) source : source.getClass(); if (Platform.isRunning()) { ClassLoader classLoader = clazz.getClassLoader(); if (isOsgiVersion310orNewer(classLoader)) { return getFileFromClassLoader4Luna(filename, classLoader); <START> } else if (isOsgiVersion39orOlder(classLoader)) { <END> return getFileFromClassLoaderBeforeLuna(filename, classLoader); } } else { return getFileFromNotRunningPlatform(filename, clazz); } throw new AssertionFailedError("Could not locate " + filename); }</code><technical_language>this true in case other is false</technical_language>

Target:
public static File getFile(Object source, String filename) throws IOException { Class<?> clazz = (source instanceof Class<?>) ? (Class<?>) source : source.getClass(); if (Platform.isRunning()) { ClassLoader classLoader = clazz.getClassLoader(); try { if (isOsgiVersion310orNewer(classLoader)) { return checkNotNull(getFileFromClassLoader4Luna(filename, classLoader)); } else { return checkNotNull(getFileFromClassLoaderBeforeLuna(filename, classLoader)); } } catch (Exception e) { AssertionFailedError exception = new AssertionFailedError(NLS.bind( "Could not locate {0} using classloader for {1}", filename, clazz)); exception.initCause(e); throw exception; } } else { return getFileFromNotRunningPlatform(filename, clazz); } }
Source:
<code><START> public HashMap<String, ObjectId> getUpdated() { <END> return updated; }</code><technical_language>Style-nit: public API return Map, Set, List a concrete implementation type. I missed this earlier review iterations</technical_language>

Target:
public Map<String, ObjectId> getUpdated() { return updated; }
Source:
<code>protected void init(final VfsNicLabelModel model) { super.init(model); <START> selectedLabelsChanged(VfsNicLabelWidget.this); <END> for (ListModel<String> labelModel : model.getItems()) { labelModel.getSelectedItemChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { selectedLabelsChanged(VfsNicLabelWidget.this); } }); } }</code><technical_language>Please change 'VfsNicLabelWidget.this' 'this', class, prefix is needed</technical_language>

Target:
protected void init(final VfsNicLabelModel model) { super.init(model); selectedLabelsChanged(VfsNicLabelWidget.this); for (ListModel<String> labelModel : model.getItems()) { labelModel.getSelectedItemChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { selectedLabelsChanged(this); } }); } }
Source:
<code>private void onLoadAdvancements(Map<ResourceLocation, Advancement.Builder> advancementsIn, CallbackInfo ci) { if (!SpongeImplHooks.isMainThread() || !ShouldFire.GAME_REGISTRY_EVENT_REGISTER) { return; } final SpongeGameRegistryRegisterEvent<org.spongepowered.api.advancement.Advancement> event = <START> new SpongeGameRegistryRegisterEvent<>(Cause.of(EventContext.empty(), SpongeImpl.getRegistry()), <END> org.spongepowered.api.advancement.Advancement.class, AdvancementRegistryModule.getInstance()); try (ListenerPhaseContext context = PluginPhase.Listener.GENERAL_LISTENER.createPhaseContext() .event(event) .source(Sponge.getGame())) { context.buildAndSwitch(); SpongeImpl.postEvent(event); } }</code><technical_language>creating delegating stack manager</technical_language>

Target:
private void onLoadAdvancements(Map<ResourceLocation, Advancement.Builder> advancementsIn, CallbackInfo ci) { if (!SpongeImplHooks.isMainThread() || !ShouldFire.GAME_REGISTRY_EVENT_REGISTER) { return; } try (ListenerPhaseContext context = PluginPhase.Listener.GENERAL_LISTENER.createPhaseContext() .source(Sponge.getGame())) { context.buildAndSwitch(); SpongeImpl.getCauseStackManager().pushCause(SpongeImpl.getRegistry()); final SpongeGameRegistryRegisterEvent<org.spongepowered.api.advancement.Advancement> event = new SpongeGameRegistryRegisterEvent<>(SpongeImpl.getCauseStackManager().getCurrentCause(), org.spongepowered.api.advancement.Advancement.class, AdvancementRegistryModule.getInstance()); context.event(event); SpongeImpl.postEvent(event); } }
Source:
<code>public Trader(String traderName, double cashInHand) { <START> super(); <END> this.name = name; this.cashInHand = cashInHand; this.position = new ArrayList<Order>(); this.ordersPlaced = new ArrayList<Order>(); }</code><technical_language>Unnecessary call super()</technical_language>

Target:
public Trader(String traderName, double cashInHand) { this.name = name; this.cashInHand = cashInHand; this.position = new ArrayList<Order>(); this.ordersPlaced = new ArrayList<Order>(); }
Source:
<code>private DefaultHttpClient createHttpClientWithProxy() { try { <START> String webProxyEnabled = System.getProperty("web.proxy.enabled"); <END> String proxyHost = System.getProperty("http.proxyHost"); String proxyPortStr = System.getProperty("http.proxyPort"); if (StringUtils.isEmpty(webProxyEnabled) || StringUtils.isEmpty(proxyHost) || StringUtils.isEmpty(proxyHost)) { return new DefaultHttpClient(); } String proxyMode = System.getProperty("http.proxyScheme"); if (StringUtils.isEmpty(proxyMode)) { proxyMode = HttpHost.DEFAULT_SCHEME_NAME; } int proxyPort = Integer.parseInt(proxyPortStr); HttpHost proxy = new HttpHost(proxyHost, proxyPort, proxyMode); final HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, DEFAULT_TIMEOUT); HttpConnectionParams.setSoTimeout(httpParams, DEFAULT_TIMEOUT); DefaultHttpClient baseHttpClient = new DefaultHttpClient(httpParams); baseHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); return baseHttpClient; } catch (Exception e) { String message = "Can't wrap client, exception: " + e.getMessage(); throw new RuntimeException(message); } }</code><technical_language>do need check this property? standard Java classes check if proxyHost set</technical_language>

Target:
private DefaultHttpClient createHttpClientWithProxy() { DefaultHttpClient client = new DefaultHttpClient(); ProxySelector proxySelector = ProxySelector.getDefault(); client.setRoutePlanner(new ProxySelectorRoutePlanner(client.getConnectionManager().getSchemeRegistry(), proxySelector)); return client; }
Source:
<code>public int getPort() { <START> return HTTPS.equals(protocol) && port == 80 ? 443 : port; <END> }</code><technical_language>I port Integer return a default port if null, returning custom port</technical_language>

Target:
public int getPort() { return (port != null) ? port : HTTPS.equals(protocol) ? 443 : 80; }
Source:
<code>protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) { final String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION); if (StringUtils.isBlank(authHeader) || !authHeader.startsWith(Headers.BEARER_TOKEN_PREFIX)) { return null; } final String bearerToken = authHeader.substring(Headers.BEARER_TOKEN_PREFIX.length()); try { final Jws<Claims> claims = Jwts.parser().setSigningKey(signatureKey).parseClaimsJws(bearerToken); logger.debug("Found the following pre-authenticated user: {}", claims.toString()); final UserDetails rslt = new SoffitApiUserDetails(claims.getBody().getSubject()); request.setAttribute(USER_DETAILS_REQUEST_ATTRIBUTE, rslt); return rslt; } catch (Exception e) { logger.error( "Unable to identify pre-authenticated user with Bearer token '{}'", bearerToken, e); } <START> return null; <END> }</code><technical_language>entire context here, <LINK_0></technical_language>

Target:
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) { final String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION); if (StringUtils.isBlank(authHeader) || !authHeader.startsWith(Headers.BEARER_TOKEN_PREFIX)) { return null; } final String bearerToken = authHeader.substring(Headers.BEARER_TOKEN_PREFIX.length()); try { final Jws<Claims> claims = Jwts.parser().setSigningKey(signatureKey).parseClaimsJws(bearerToken); logger.debug("Found the following pre-authenticated user: {}", claims.toString()); final List<String> groupsClaim = claims.getBody().get("groups", List.class); final List<String> groupsList = groupsClaim != null ? groupsClaim : Collections.emptyList(); final UserDetails rslt = new SoffitApiUserDetails(claims.getBody().getSubject(), groupsList); request.setAttribute(USER_DETAILS_REQUEST_ATTRIBUTE, rslt); return rslt; } catch (Exception e) { logger.info("The following Bearer token is unusable: '{}'", bearerToken); logger.debug("Failed to validate and/or parse the specified Bearer token", e); } return null; }
Source:
<code>public int getTerminalHeight() { if( !INTERACT ){ <START> return 40; <END> } if(console == null) { try { this.initBasicConsole(null); } catch (CliInitializationException e) { this.error("Failed to initialize the console: " + e.getLocalizedMessage()); return 24; } } return console.getTerminalHeight(); }</code><technical_language>Strangely, in method error occurs, 24 is returned. This random. is strange 24 returned in case 40 in another. I looked GIT history special. try replace 24 40, I this effect</technical_language>

Target:
public int getTerminalHeight() { if (!INTERACT) { return 24; } if(console == null) { try { this.initBasicConsole(null); } catch (CliInitializationException e) { this.error("Failed to initialize the console: " + e.getLocalizedMessage()); return 24; } } return console.getTerminalHeight(); }
Source:
<code>public static void report(String testId, Throwable cause) { if (cause == null) { log.severe("Can't call report with a null exception"); return; } long exceptionCount = FAILURE_ID.incrementAndGet(); log.severe("Exception #" + exceptionCount + " detected", cause); String targetFileName = exceptionCount + ".exception"; final File tmpFile = new File(targetFileName + ".tmp"); try { <START> if (!tmpFile.createNewFile()) { <END> throw new IOException("Could not create tmp file:" + tmpFile.getAbsolutePath()); } } catch (IOException e) { log.severe("Could not report exception; this means that this exception is not visible to the coordinator", e); return; } writeCauseToFile(testId, cause, tmpFile); final File file = new File(targetFileName); if (!tmpFile.renameTo(file)) { log.severe("Failed to rename tmp file:" + tmpFile + " to " + file); } }</code><technical_language>createNewFile returns false file exists, right? if IOException throwing a more specific message</technical_language>

Target:
public static void report(String testId, Throwable cause) { if (cause == null) { log.severe("Can't call report with a null exception"); return; } long exceptionCount = FAILURE_ID.incrementAndGet(); log.severe("Exception #" + exceptionCount + " detected", cause); String targetFileName = exceptionCount + ".exception"; final File tmpFile = new File(targetFileName + ".tmp"); try { if (!tmpFile.createNewFile()) { throw new IOException("Could not create tmp file:" + tmpFile.getAbsolutePath()+" file already exists."); } } catch (IOException e) { log.severe("Could not report exception; this means that this exception is not visible to the coordinator", e); return; } writeCauseToFile(testId, cause, tmpFile); final File file = new File(targetFileName); if (!tmpFile.renameTo(file)) { log.severe("Failed to rename tmp file:" + tmpFile + " to " + file); } }
Source:
<code>private boolean hasDeploymentInfo() { boolean hasValue = false; for (String s : deploymentDesc) { hasValue |= StringUtils.hasText(s); } if (!hasValue) { return false; } <START> if (StringUtils.isEmpty(deploymentDesc[MODULE_LABEL])) { <END> throw new IllegalStateException("Module label missing"); } if (StringUtils.isEmpty(deploymentDesc[CONTAINER])) { throw new IllegalStateException("Container missing"); } return true; }</code><technical_language>Assert.state() (since IllegalStateException is desired) Assert.hasText(..) (which instead throw IllegalArgumentException). In case though, 6 lines replaced 2, improves test coverage (unless tests of if blocks)</technical_language>

Target:
private boolean hasDeploymentInfo() { boolean hasValue = false; for (String s : deploymentDesc) { hasValue |= StringUtils.hasText(s); } if (!hasValue) { return false; } Assert.state(StringUtils.hasText(deploymentDesc[MODULE_LABEL]), "Module label missing"); Assert.state(StringUtils.hasText(deploymentDesc[CONTAINER]), "Container missing"); return true; }
Source:
<code>private List<SearchHit> sendElasticQuery(ElasticsearchQueryBuilder queryBuilder) { ImmutableList.Builder<SearchHit> result = ImmutableList.builder(); SearchResponse response = queryBuilder.buildScrollSearchRequest().execute().actionGet(timeout.toMillis()); if (response.getHits().getTotalHits() > maxHits) { <START> throw new PrestoException(ELASTICSEARCH_MAX_HITS_EXCEEDED, "The number of hits for the query: " + response.getHits().getTotalHits() + " exceeds the configured max hits: " + maxHits); <END> } while (true) { for (SearchHit hit : response.getHits().getHits()) { result.add(hit); } response = queryBuilder.prepareSearchScroll(response.getScrollId()) .execute() .actionGet(timeout.toMillis()); if (response.getHits().getHits().length == 0) { break; } } return result.build(); }</code><technical_language>throw new PrestoException(ELASTICSEARCH_MAX_HITS_EXCEEDED, format("The number of hits for query (%s) exceeds configured max hits (%s)", response.getHits().getTotalHits(), maxHits));</technical_language>

Target:
private List<SearchHit> sendElasticQuery(ElasticsearchQueryBuilder queryBuilder) { ImmutableList.Builder<SearchHit> result = ImmutableList.builder(); SearchResponse response = queryBuilder.buildScrollSearchRequest() .execute() .actionGet(timeout.toMillis()); if (response.getHits().getTotalHits() > maxHits) { throw new PrestoException(ELASTICSEARCH_MAX_HITS_EXCEEDED, format("The number of hits for the query (%d) exceeds the configured max hits (%d)", response.getHits().getTotalHits(), maxHits)); } while (true) { for (SearchHit hit : response.getHits().getHits()) { result.add(hit); } response = queryBuilder.prepareSearchScroll(response.getScrollId()) .execute() .actionGet(timeout.toMillis()); if (response.getHits().getHits().length == 0) { break; } } return result.build(); }
Source:
<code>public void testInheritanceCycle() throws Exception { String error = tapSystemErr(() -> { int exitStatus = catchSystemExit(() -> DynamicConfigValidator.main(new String[] { "--configDir", "src/test/resources/validator/bad_cyclic_inheritance" })); assertEquals(2, exitStatus); }); <START> assert ("Inheriting from table 'A' creates an illegal cyclic dependency.\n".equals(error) || "Inheriting from table 'B' creates an illegal cyclic dependency.\n".equals(error)); <END> }</code><technical_language>This is resolved in elide-5.x. rebase PR pick fix</technical_language>

Target:
public void testInheritanceCycle() throws Exception { String error = tapSystemErr(() -> { int exitStatus = catchSystemExit(() -> DynamicConfigValidator.main(new String[] { "--configDir", "src/test/resources/validator/bad_cyclic_inheritance" })); assertEquals(2, exitStatus); }); assertTrue(error.contains("Inheriting from table")); assertTrue(error.contains("creates an illegal cyclic dependency.")); }
Source:
<code>public void start(BundleContext context) throws Exception { super.start(context); contextStore = new LocalContextStore(commonContextScaling); File storeFile = getDefaultContextLocation().toFile(); if (!storeFile.exists()) { storeFile.mkdirs(); } contextStore.setContextDirectory(storeFile); contextManager = new InteractionContextManager(contextStore); <START> initContextContributor(); <END> }</code><technical_language>Loading a chain of classes potentially activating other bundles bundle startup problematic. need find a initialize contributors lazily, e.g. context activation</technical_language>

Target:
public void start(BundleContext context) throws Exception { super.start(context); contextStore = new LocalContextStore(commonContextScaling); File storeFile = getDefaultContextLocation().toFile(); if (!storeFile.exists()) { storeFile.mkdirs(); } contextStore.setContextDirectory(storeFile); contextManager = new InteractionContextManager(contextStore); }
Source:
<code>private RSAPrivateKey getSigningKey(final String signingKeystoreName, final String signingKeystoreAlias, final char[] signingKeystorePassphrase) throws KeystoreServiceException, TokenServiceException { if (signingKeystorePassphrase != null) { char[] passphrase; <START> try { passphrase = getSigningKeyPassphrase(signingKeystorePassphrase); } catch (AliasServiceException e) { throw new TokenServiceException(e); } <END> return (RSAPrivateKey) ks.getSigningKey(signingKeystoreName, getSigningKeyAlias(signingKeystoreAlias), passphrase); } return signingKey; }</code><technical_language>getSigningKeyPassphrase longer throws AliasServiceException -> try/catch block is unnecesarry</technical_language>

Target:
private RSAPrivateKey getSigningKey(final String signingKeystoreName, final String signingKeystoreAlias, final char[] signingKeystorePassphrase) throws KeystoreServiceException, TokenServiceException { if (signingKeystorePassphrase != null) { return (RSAPrivateKey) ks.getSigningKey(signingKeystoreName, getSigningKeyAlias(signingKeystoreAlias), getSigningKeyPassphrase(signingKeystorePassphrase)); } return signingKey; }
Source:
<code><START> public UpdateImageOptions copyFrom(String url) { <END> headers.put(COPY_FROM.asGlanceHeader(), url); return this; }</code><technical_language>java public CreateImageOptions copyFrom(URI source) { ... }</technical_language>

Target:
public UpdateImageOptions copyFrom(String url) { headers.put(COPY_FROM, url); return this; }
Source:
<code>public static HandshakeCiphers create(String salt, String secret) { try { byte[] specKey = Jnlp3Util.generate128BitKey(salt + secret); IvParameterSpec spec = new IvParameterSpec(specKey); SecretKey secretKey = generateSecretKey(salt, secret); Cipher encryptCipher = Cipher.getInstance(CIPHER_TRANSFORMATION); encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey, spec); Cipher decryptCipher = Cipher.getInstance(CIPHER_TRANSFORMATION); decryptCipher.init(Cipher.DECRYPT_MODE, secretKey, spec); return new HandshakeCiphers(secretKey, spec, encryptCipher, decryptCipher); } catch (GeneralSecurityException e) { <START> throw (AssertionError) new AssertionError("Failed to create handshake ciphers", e); <END> } }</code><technical_language>suggestion throw new AssertionError("Failed create handshake ciphers", e);</technical_language>

Target:
public static HandshakeCiphers create(String salt, String secret) { try { byte[] specKey = Jnlp3Util.generate128BitKey(salt + secret); IvParameterSpec spec = new IvParameterSpec(specKey); SecretKey secretKey = generateSecretKey(salt, secret); Cipher encryptCipher = Cipher.getInstance(CIPHER_TRANSFORMATION); encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey, spec); Cipher decryptCipher = Cipher.getInstance(CIPHER_TRANSFORMATION); decryptCipher.init(Cipher.DECRYPT_MODE, secretKey, spec); return new HandshakeCiphers(secretKey, spec, encryptCipher, decryptCipher); } catch (GeneralSecurityException e) { throw new AssertionError("Failed to create handshake ciphers", e); } }
Source:
<code>Point getThickness (long widget) { if (OS.GTK3) { int xthickness = 0, ythickness = 0; GtkBorder tmp = new GtkBorder(); long context = OS.gtk_widget_get_style_context (widget); if (OS.GTK_VERSION < OS.VERSION(3, 18, 0)) { OS.gtk_style_context_get_padding (context, OS.GTK_STATE_FLAG_NORMAL, tmp); } else { <START> int styleState = OS.gtk_widget_get_state_flags(widget); <END> OS.gtk_style_context_get_padding (context, styleState, tmp); } OS.gtk_style_context_save (context); OS.gtk_style_context_add_class (context, OS.GTK_STYLE_CLASS_FRAME); xthickness += tmp.left; ythickness += tmp.top; if (OS.GTK_VERSION < OS.VERSION(3, 18, 0)) { OS.gtk_style_context_get_border (context, OS.GTK_STATE_FLAG_NORMAL, tmp); } else { int styleState = OS.gtk_widget_get_state_flags(widget); OS.gtk_style_context_get_border (context, styleState, tmp); } xthickness += tmp.left; ythickness += tmp.top; OS.gtk_style_context_restore (context); return new Point (xthickness, ythickness); } long style = OS.gtk_widget_get_style (widget); return new Point (OS.gtk_style_get_xthickness (style), OS.gtk_style_get_ythickness (style)); }</code><technical_language>need styleState variable all</technical_language>

Target:
Point getThickness (long widget) { if (OS.GTK3) { int xthickness = 0, ythickness = 0; GtkBorder tmp = new GtkBorder(); long context = OS.gtk_widget_get_style_context (widget); int styleState = OS.gtk_widget_get_state_flags(widget); OS.gtk_style_context_save (context); OS.gtk_style_context_add_class (context, OS.GTK_STYLE_CLASS_FRAME); OS.gtk_style_context_get_padding (context, styleState, tmp); xthickness += tmp.left; ythickness += tmp.top; OS.gtk_style_context_get_border (context, styleState, tmp); xthickness += tmp.left; ythickness += tmp.top; OS.gtk_style_context_restore (context); return new Point (xthickness, ythickness); } long style = OS.gtk_widget_get_style (widget); return new Point (OS.gtk_style_get_xthickness (style), OS.gtk_style_get_ythickness (style)); }
Source:
<code>private void recursiveDelete(Path file) throws IOException { Files.walkFileTree(file, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { if (e == null) { Files.delete(dir); return FileVisitResult.CONTINUE; <START> } else { throw e; } <END> } }); }</code><technical_language>This need in else clause. more readable invert logic of this block, i.e.: if (e != null) { throw e; } Files.delete(dir); return FileVisitResult.CONTINUE;</technical_language>

Target:
private void recursiveDelete(Path file) throws IOException { Files.walkFileTree(file, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { if (e != null) { throw e; } Files.delete(dir); return FileVisitResult.CONTINUE; } }); }
Source:
<code>public Future<String> putBlob(BlobProperties blobProperties, byte[] userMetadata, ReadableStreamChannel channel, Callback<String> callback) { currentOperationsCount.incrementAndGet(); routerMetrics.putBlobOperationRate.mark(); routerMetrics.operationQueuingRate.mark(); FutureResult<String> futureResult = new FutureResult<String>(); if (isOpen.get()) { getOperationController().putBlob(blobProperties, userMetadata, channel, futureResult, callback); } else { RouterException routerException = new RouterException("Cannot accept operation because Router is closed", RouterErrorCode.RouterClosed); routerMetrics.operationDequeuingRate.mark(); <START> routerMetrics.operationAbortCount.inc(); <END> routerMetrics.putBlobErrorCount.inc(); routerMetrics.countError(routerException); operationCompleteCallback.completeOperation(futureResult, callback, null, routerException); } return futureResult; }</code><technical_language>incorrect</technical_language>

Target:
public Future<String> putBlob(BlobProperties blobProperties, byte[] userMetadata, ReadableStreamChannel channel, Callback<String> callback) { currentOperationsCount.incrementAndGet(); routerMetrics.putBlobOperationRate.mark(); routerMetrics.operationQueuingRate.mark(); FutureResult<String> futureResult = new FutureResult<String>(); if (isOpen.get()) { getOperationController().putBlob(blobProperties, userMetadata, channel, futureResult, callback); } else { RouterException routerException = new RouterException("Cannot accept operation because Router is closed", RouterErrorCode.RouterClosed); routerMetrics.operationDequeuingRate.mark(); routerMetrics.putBlobErrorCount.inc(); routerMetrics.countError(routerException); operationCompleteCallback.completeOperation(futureResult, callback, null, routerException); } return futureResult; }
Source:
<code>private Collection<LockWatchEvent> getValuesBetweenInclusive(long endVersion, long startVersion) { <START> if (endVersion < startVersion) { <END> return ImmutableList.of(); } return eventMap.subMap(startVersion, INCLUSIVE, endVersion, INCLUSIVE).values(); }</code><technical_language>Feels wrong allow this</technical_language>

Target:
private Collection<LockWatchEvent> getValuesBetweenInclusive(long endVersion, long startVersion) { return eventMap.subMap(startVersion, INCLUSIVE, endVersion, INCLUSIVE).values(); }
Source:
<code>void peekOneMessage() { final int numberOfEvents = 1; when(managementNode.peek()) .thenReturn(Mono.just(mock(ServiceBusReceivedMessage.class))); <START> StepVerifier.create(consumer.peek()) <END> .expectNextCount(numberOfEvents) .verifyComplete(); }</code><technical_language>Do a test peeks next sequence number</technical_language>

Target:
void peekOneMessage() { final int numberOfEvents = 1; when(managementNode.peek()) .thenReturn(just(mock(ServiceBusReceivedMessage.class))); StepVerifier.create(consumer.peek()) .expectNextCount(numberOfEvents) .verifyComplete(); }
Source:
<code>SqlOperator toOp(Map<String, Object> map) { String name = map.get("name").toString(); String kind = map.get("kind").toString(); String syntax = map.get("syntax").toString(); SqlKind sqlKind = SqlKind.valueOf(kind); SqlSyntax sqlSyntax = SqlSyntax.valueOf(syntax); List<SqlOperator> operators = new ArrayList<>(); SqlStdOperatorTable.instance().lookupOperatorOverloads( new SqlIdentifier(name, new SqlParserPos(0, 0)), null, sqlSyntax, operators, SqlNameMatchers.liberal()); for (SqlOperator operator: operators) { if (operator.kind == sqlKind) { return operator; } } String class_ = (String) map.get("class"); if (class_ != null) { return AvaticaUtils.instantiatePlugin(SqlOperator.class, class_); } throw new RuntimeException("No operator for " + name + " with kind: " <START> + kind + ", and syntax: " + syntax); <END> }</code><technical_language>move this exception in CalciteResource.java</technical_language>

Target:
SqlOperator toOp(Map<String, Object> map) { String name = map.get("name").toString(); String kind = map.get("kind").toString(); String syntax = map.get("syntax").toString(); SqlKind sqlKind = SqlKind.valueOf(kind); SqlSyntax sqlSyntax = SqlSyntax.valueOf(syntax); List<SqlOperator> operators = new ArrayList<>(); SqlStdOperatorTable.instance().lookupOperatorOverloads( new SqlIdentifier(name, new SqlParserPos(0, 0)), null, sqlSyntax, operators, SqlNameMatchers.liberal()); for (SqlOperator operator: operators) { if (operator.kind == sqlKind) { return operator; } } String class_ = (String) map.get("class"); if (class_ != null) { return AvaticaUtils.instantiatePlugin(SqlOperator.class, class_); } throw RESOURCE.noOperator(name, kind, syntax).ex(); }
Source:
<code>public void testCloudHubDeploy() throws VerificationException, InterruptedException, TimeoutException { <START> verifier.setEnvironmentVariable("MAVEN_OPTS", "-agentlib:jdwp=transport=dt_socket,server=y,address=8000,suspend=y"); <END> log.info("Executing mule:deploy goal..."); verifier.executeGoal(MULE_DEPLOY); cloudHubDeploymentVerifier.verifyIsDeployed(APPLICATION_NAME); log.info("Application " + APPLICATION_NAME + " successfully deployed to CloudHub."); verifier.verifyErrorFreeLog(); }</code><technical_language>This hang test</technical_language>

Target:
public void testCloudHubDeploy() throws VerificationException, InterruptedException, TimeoutException { log.info("Executing mule:deploy goal..."); verifier.executeGoal(MULE_DEPLOY); cloudHubDeploymentVerifier.verifyIsDeployed(APPLICATION_NAME); log.info("Application " + APPLICATION_NAME + " successfully deployed to CloudHub."); verifier.verifyErrorFreeLog(); }
Source:
<code>Int2IntListLookupTable(int maxSize, IntFunction<IntList> loader) { this.loader = loader; this.lookup = new IntList[maxSize]; <START> Arrays.fill(lookup, null); <END> }</code><technical_language>I thought Java guaranteed object arrays start nulls</technical_language>

Target:
Int2IntListLookupTable(int maxSize, IntFunction<IntList> loader) { this.loader = loader; this.lookup = new IntList[maxSize]; }