auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public SAMFileSpan removeContentsAfter(final SAMFileSpan fileSpan) { if(fileSpan == null) return clone(); if(!(fileSpan instanceof BAMFileSpan)) throw new SAMException("Unable to compare "); final BAMFileSpan bamFileSpan = (BAMFileSpan)fileSpan; if(bamFileSpan.isEmpty()) return clone(); validateSorted(); final BAMFileSpan trimmedChunkList = new BAMFileSpan(); final long chunkEnd = bamFileSpan.chunks.get(0).getChunkEnd(); for(final Chunk chunkToTrim: chunks) { if(chunkToTrim.getChunkStart() < chunkEnd) { if(chunkToTrim.getChunkEnd() <= chunkEnd) { trimmedChunkList.add(chunkToTrim.clone()); } else { <START> trimmedChunkList.add(new Chunk(chunkToTrim.getChunkStart(),chunkEnd)); <END> } } } return trimmedChunkList; }</code><technical_language>Do a good test confirm chunks in returned filespan sorted trimming? (applies removeContentsBefore() well)</technical_language>

Target:
public SAMFileSpan removeContentsAfter(final SAMFileSpan fileSpan) { if(fileSpan == null) return clone(); if(!(fileSpan instanceof BAMFileSpan)) throw new SAMException("Unable to compare "); final BAMFileSpan bamFileSpan = (BAMFileSpan)fileSpan; if(bamFileSpan.isEmpty()) return clone(); validateSorted(); final BAMFileSpan trimmedChunkList = new BAMFileSpan(); final long chunkEnd = bamFileSpan.chunks.get(bamFileSpan.chunks.size() - 1).getChunkEnd(); for(final Chunk chunkToTrim: chunks) { if(chunkToTrim.getChunkStart() < chunkEnd) { if(chunkToTrim.getChunkEnd() <= chunkEnd) { trimmedChunkList.add(chunkToTrim.clone()); } else { trimmedChunkList.add(new Chunk(chunkToTrim.getChunkStart(),chunkEnd)); } } } return trimmedChunkList; }
Source:
<code>protected BaseReceivePack(final Repository into) { db = into; walk = new RevWalk(db); final ReceiveConfig cfg = db.getConfig().get(ReceiveConfig.KEY); objectChecker = cfg.newObjectChecker(); allowCreates = cfg.allowCreates; allowAnyDeletes = true; allowBranchDeletes = cfg.allowDeletes; allowNonFastForwards = cfg.allowNonFastForwards; allowOfsDelta = cfg.allowOfsDelta; advertiseRefsHook = AdvertiseRefsHook.DEFAULT; refFilter = RefFilter.DEFAULT; advertisedHaves = new HashSet<ObjectId>(); clientShallowCommits = new HashSet<ObjectId>(); <START> String dirPath = db.getDirectory() != null ? db.getDirectory().getPath() : "" ; END> pushCertificateParser = new PushCertificateParser(into, cfg, dirPath); }</code><technical_language>if pass Repository NonceGenerator, pull out directory? DFS implementations supply a NonceGenerator pull out getRepositoryName</technical_language>

Target:
protected BaseReceivePack(final Repository into) { db = into; walk = new RevWalk(db); final ReceiveConfig cfg = db.getConfig().get(ReceiveConfig.KEY); objectChecker = cfg.newObjectChecker(); allowCreates = cfg.allowCreates; allowAnyDeletes = true; allowBranchDeletes = cfg.allowDeletes; allowNonFastForwards = cfg.allowNonFastForwards; allowOfsDelta = cfg.allowOfsDelta; advertiseRefsHook = AdvertiseRefsHook.DEFAULT; refFilter = RefFilter.DEFAULT; advertisedHaves = new HashSet<ObjectId>(); clientShallowCommits = new HashSet<ObjectId>(); pushCertificateParser = new PushCertificateParser(db, cfg); }
Source:
<code>public FSDataInputStream openFile(Path path, HiveFileContext hiveFileContext) throws Exception { <START> return fileSystem.openFile(path, hiveFileContext); <END> }</code><technical_language>This is work. openFile delegates underlying file system. input stream cache</technical_language>

Target:
public FSDataInputStream openFile(Path path, HiveFileContext hiveFileContext) throws Exception { URIStatus uriStatus = mFileSystem.getStatus(getAlluxioPath(path)); AlluxioURIStatus alluxioURIStatus = new AlluxioURIStatus(uriStatus.getFileInfo(), hiveFileContext); FileInStream fileInStream = mFileSystem.openFile(alluxioURIStatus, OpenFilePOptions.getDefaultInstance()); return new FSDataInputStream(new AlluxioCachingHdfsFileInputStream(fileInStream)); }
Source:
<code>private DoubleArray strikesShifted(double forward, double shiftOutput, DoubleArray strikesLike, ValueType strikeType) { int nbStrikes = strikesLike.size(); double[] strikes = new double[nbStrikes]; if (strikeType.equals(ValueType.STRIKE)) { for (int i = 0; i < nbStrikes; i++) { strikes[i] = strikesLike.get(i) + shiftOutput; } return DoubleArray.ofUnsafe(strikes); } if (strikeType.equals(ValueType.SIMPLE_MONEYNESS)) { for (int i = 0; i < nbStrikes; i++) { strikes[i] = forward + strikesLike.get(i) + shiftOutput; } return DoubleArray.ofUnsafe(strikes); } if (strikeType.equals(ValueType.LOG_MONEYNESS)) { for (int i = 0; i < nbStrikes; i++) { <START> strikes[i] = forward * strikesLike.get(i) + shiftOutput; <END> } return DoubleArray.ofUnsafe(strikes); } throw new IllegalArgumentException("Strike type not supported"); }</code><technical_language>wrong formula</technical_language>

Target:
private DoubleArray strikesShifted(double forward, double shiftOutput, DoubleArray strikesLike, ValueType strikeType) { int nbStrikes = strikesLike.size(); double[] strikes = new double[nbStrikes]; if (strikeType.equals(ValueType.STRIKE)) { for (int i = 0; i < nbStrikes; i++) { strikes[i] = strikesLike.get(i) + shiftOutput; } return DoubleArray.ofUnsafe(strikes); } if (strikeType.equals(ValueType.SIMPLE_MONEYNESS)) { for (int i = 0; i < nbStrikes; i++) { strikes[i] = forward + strikesLike.get(i) + shiftOutput; } return DoubleArray.ofUnsafe(strikes); } if (strikeType.equals(ValueType.LOG_MONEYNESS)) { for (int i = 0; i < nbStrikes; i++) { strikes[i] = forward * Math.exp(strikesLike.get(i)) + shiftOutput; } return DoubleArray.ofUnsafe(strikes); } throw new IllegalArgumentException("Strike type not supported"); }
Source:
<code>public String getCategoryId() { <START> return "itemcategory-standaloneprojects"; <END> }</code><technical_language>Is this simply standaloneprojects</technical_language>

Target:
public String getCategoryId() { return "standaloneprojects"; }
Source:
<code>private ParseTree getPermissionExpressionTree(Class<? extends Annotation> annotationClass, Annotation annotation) { try { if (annotationClass == SharePermission.class) { <START> return null; <END> } String expression = (String) annotationClass.getMethod("expression").invoke(annotation); boolean hasExpression = !expression.isEmpty(); if (!hasExpression) { log.warn("Poorly configured permission: {}", annotationClass.getName(), "no checks specified."); throw new IllegalArgumentException("Poorly configured permission '" + annotationClass.getName() + "'"); } return parseExpression(expression); } catch (ReflectiveOperationException e) { log.warn("Unknown permission: {}, {}", annotationClass.getName(), e); throw new IllegalArgumentException("Unknown permission '" + annotationClass.getName() + "'", e); } }</code><technical_language>This happen, it? ReadPermission evaluated instead</technical_language>

Target:
private ParseTree getPermissionExpressionTree(Class<? extends Annotation> annotationClass, Annotation annotation) { try { String expression = (String) annotationClass.getMethod("expression").invoke(annotation); boolean hasExpression = !expression.isEmpty(); if (!hasExpression) { log.warn("Poorly configured permission: {}", annotationClass.getName(), "no checks specified."); throw new IllegalArgumentException("Poorly configured permission '" + annotationClass.getName() + "'"); } return parseExpression(expression); } catch (ReflectiveOperationException e) { log.warn("Unknown permission: {}, {}", annotationClass.getName(), e); throw new IllegalArgumentException("Unknown permission '" + annotationClass.getName() + "'", e); } }
Source:
<code>public void testDeactivation() { assertTrue("Should resolve model one dialog", resourceExists("/apps/test/model1/cq:dialog")); providers.get("com.adobe.acs.commons.mcp.model.SimpleModelOne").doDeactivate(); <START> assertFalse("Should resolve model one dialog", resourceExists("/apps/test/model1/cq:dialog")); <END> }</code><technical_language>suggestion assertFalse("Should resolve model dialog", resourceExists("/apps/test/model1/cq:dialog"));</technical_language>

Target:
public void testDeactivation() { assertTrue("Should resolve model one dialog", resourceExists("/apps/test/model1/cq:dialog")); providers.get("com.adobe.acs.commons.mcp.model.SimpleModelOne").doDeactivate(); assertFalse("Should not resolve model one dialog", resourceExists("/apps/test/model1/cq:dialog")); }
Source:
<code>public int handleCommand(final Namespace ns, final Manager m) { if (!m.isRegistered()) { System.err.println("User is not registered."); return 1; } for (String contact_number : ns.<String>getList("contact")) { m.setContactBlocked(contact_number, false); } <START> if(ns.<String>getList("group") != null) { <END> for (String groupIdString : ns.<String>getList("group")) { try { byte[] groupId = Util.decodeGroupId(groupIdString); m.setGroupBlocked(groupId, false); } catch (GroupIdFormatException | GroupNotFoundException e) { System.err.println(e.getMessage()); } } } return 0; }</code><technical_language>missing space if</technical_language>

Target:
public int handleCommand(final Namespace ns, final Manager m) { if (!m.isRegistered()) { System.err.println("User is not registered."); return 1; } for (String contact_number : ns.<String>getList("contact")) { try { m.setContactBlocked(contact_number, false); } catch (InvalidNumberException e) { System.err.println(e.getMessage()); } } if (ns.<String>getList("group") != null) { for (String groupIdString : ns.<String>getList("group")) { try { byte[] groupId = Util.decodeGroupId(groupIdString); m.setGroupBlocked(groupId, false); } catch (GroupIdFormatException | GroupNotFoundException e) { System.err.println(e.getMessage()); } } } return 0; }
Source:
<code>public boolean delete(Data dataKey) { MultiMapValue value = multiMapValues.remove(dataKey); if (value != null) { decrSize(value.size()); return true; <START> } else { <END> return false; } }</code><technical_language>Redundant else block</technical_language>

Target:
public boolean delete(Data dataKey) { MultiMapValue value = multiMapValues.remove(dataKey); if (value != null) { decrSize(value.size()); return true; } return false; }
Source:
<code>protected String getTypeLabel() { <START> return checkNotNull("type"); END> }</code><technical_language>for checkNonNull, Objects.requireNonNull is preferred. labels externalized</technical_language>

Target:
protected String getTypeLabel() { return Objects.requireNonNull(Messages.CallingContextTreeViewer_LabelType); }
Source:
<code>public Object queries(@QueryParam("queries") String queriesParam) throws InterruptedException, ExecutionException { final int queries = getQueries(queriesParam); final World[] worlds = new World[queries]; Callable<World[]> callable = () -> { Session session = emf.createEntityManager().unwrap(Session.class); session.setDefaultReadOnly(true); try { final AtomicInteger i = new AtomicInteger(0); <START> ThreadLocalRandom.current().ints(1, 10000).distinct().limit(queries).forEach( <END> (randomValue)->worlds[i.getAndAdd(1)] = (World) session.byId(World.class).load(randomValue) ); return worlds; } finally { session.close(); } }; Future<World[]> futureWorlds = Common.EXECUTOR.submit(callable); return futureWorlds.get(); }</code><technical_language>10001 instead of 10000 [the upper bound is exclusive](<LINK_0>,int))</technical_language>

Target:
public Object queries(@QueryParam("queries") String queriesParam) throws InterruptedException, ExecutionException { final int queries = getQueries(queriesParam); final World[] worlds = new World[queries]; Callable<World[]> callable = () -> { Session session = emf.createEntityManager().unwrap(Session.class); session.setDefaultReadOnly(true); try { final AtomicInteger i = new AtomicInteger(0); ThreadLocalRandom.current().ints(1, 10001).distinct().limit(queries).forEach( (randomValue)->worlds[i.getAndAdd(1)] = (World) session.byId(World.class).load(randomValue) ); return worlds; } finally { session.close(); } }; Future<World[]> futureWorlds = Common.EXECUTOR.submit(callable); return futureWorlds.get(); }
Source:
<code>public Observable<T> subscribeChannel(String channelName, Object... args) { final String channelId = getSubscriptionUniqueId(channelName, args); LOG.info("Subscribing to channel {}", channelId); return Observable.<T>create( e -> { if (webSocketChannel == null || !webSocketChannel.isOpen()) { e.onError(new NotConnectedException()); } channels.computeIfAbsent( channelId, cid -> { Subscription newSubscription = new Subscription(e, channelName, args); try { sendMessage(getSubscribeMessage(channelName, args)); } catch ( Exception throwable) { e.onError(throwable); } return newSubscription; }); }) .doOnDispose( () -> { if (channels.remove(channelId) != null) { try { sendMessage(getUnsubscribeMessage(channelId)); } catch (IOException e) { <START> LOG.error("Failed to unsubscribe channel: {}", channelId); <END> } } }) .share(); }</code><technical_language>Do want log more information error occurred was</technical_language>

Target:
public Observable<T> subscribeChannel(String channelName, Object... args) { final String channelId = getSubscriptionUniqueId(channelName, args); LOG.info("Subscribing to channel {}", channelId); return Observable.<T>create( e -> { if (webSocketChannel == null || !webSocketChannel.isOpen()) { e.onError(new NotConnectedException()); } channels.computeIfAbsent( channelId, cid -> { Subscription newSubscription = new Subscription(e, channelName, args); try { sendMessage(getSubscribeMessage(channelName, args)); } catch ( Exception throwable) { e.onError(throwable); } return newSubscription; }); }) .doOnDispose( () -> { if (channels.remove(channelId) != null) { try { sendMessage(getUnsubscribeMessage(channelId)); } catch (IOException e) { LOG.debug("Failed to unsubscribe channel: {}", channelId, e.toString()); } catch (Exception e) { LOG.warn("Failed to unsubscribe channel: {}", channelId, e); } } }) .share(); }
Source:
<code><START> public static void checkPartitionStrategy(Schema schema, PartitionStrategy strategy) { <END> if (strategy == null) { return; } Preconditions.checkState(schema.getType() == Schema.Type.RECORD, "Cannot partition non-records: " + schema); for (org.kitesdk.data.spi.FieldPartitioner fp : strategy.getFieldPartitioners()) { Schema.Field field = schema.getField(fp.getSourceName()); Preconditions.checkState(field != null, "Cannot partition on (missing from schema)", fp.getSourceName()); Preconditions.checkState( SchemaUtil.checkType(field.schema().getType(), fp.getSourceType()), "Field type does not match partitioner {}", field.schema().getType(), fp); } }</code><technical_language>This public</technical_language>

Target:
private static void checkPartitionStrategy(Schema schema, PartitionStrategy strategy) { if (strategy == null) { return; } Preconditions.checkState(schema.getType() == Schema.Type.RECORD, "Cannot partition non-records: " + schema); for (org.kitesdk.data.spi.FieldPartitioner fp : strategy.getFieldPartitioners()) { Schema.Field field = schema.getField(fp.getSourceName()); Preconditions.checkState(field != null, "Cannot partition on (missing from schema)", fp.getSourceName()); Preconditions.checkState( SchemaUtil.checkType(field.schema().getType(), fp.getSourceType()), "Field type does not match partitioner {}", field.schema().getType(), fp); } }
Source:
<code>public List<SnapshotInfo> getSnapshots(long volumeId, DataStoreRole role) { SnapshotDataStoreVO snapshotStore = snapshotStoreDao.findByVolume(volumeId, role); if (snapshotStore == null) { <START> return null; <END> } DataStore store = storeMgr.getDataStore(snapshotStore.getDataStoreId(), role); List<SnapshotVO> volSnapShots = snapshotDao.listByVolumeId(volumeId); List<SnapshotInfo> infos = new ArrayList<>(); for(SnapshotVO snapshot: volSnapShots) { SnapshotObject info = SnapshotObject.getSnapshotObject(snapshot, store); infos.add(info); } return infos; }</code><technical_language>This a NPE. Consider returning empty list</technical_language>

Target:
public List<SnapshotInfo> getSnapshots(long volumeId, DataStoreRole role) { SnapshotDataStoreVO snapshotStore = snapshotStoreDao.findByVolume(volumeId, role); if (snapshotStore == null) { return new ArrayList<>(); } DataStore store = storeMgr.getDataStore(snapshotStore.getDataStoreId(), role); List<SnapshotVO> volSnapShots = snapshotDao.listByVolumeId(volumeId); List<SnapshotInfo> infos = new ArrayList<>(); for(SnapshotVO snapshot: volSnapShots) { SnapshotObject info = SnapshotObject.getSnapshotObject(snapshot, store); infos.add(info); } return infos; }
Source:
<code>public boolean isAuthenticated(Request request) { String authheader = request.getHeader(Constants.AUTHORIZATION_HEADER); if (authheader != null && authheader.startsWith(Constants.BEARER_AUTH_HEADER)) { String accessToken = authheader.substring(Constants.BEARER_AUTH_HEADER.length()).trim(); try { <START> OAuth2ClientApplicationDTO validationApp = this.validateAccessToken(accessToken); <END> OAuth2TokenValidationResponseDTO validationResponse = null; if (validationApp != null) { validationResponse = validationApp.getAccessTokenValidationResponse(); } if (validationResponse != null) { if (validationResponse.isValid()) { String userName = validationResponse.getAuthorizedUser(); return true; } } } catch (Exception e) { log.error("Error when calling the remote service ",e); } } return false; }</code><technical_language>"this" is redundant</technical_language>

Target:
public boolean isAuthenticated(Request request) { String authheader = request.getHeader(Constants.AUTHORIZATION_HEADER); if (authheader != null && authheader.startsWith(Constants.BEARER_AUTH_HEADER)) { String accessToken = authheader.substring(Constants.BEARER_AUTH_HEADER.length()).trim(); try { OAuth2ClientApplicationDTO validationApp = validateAccessToken(accessToken); OAuth2TokenValidationResponseDTO validationResponse = null; if (validationApp != null) { validationResponse = validationApp.getAccessTokenValidationResponse(); } if (validationResponse != null) { if (validationResponse.isValid()) { String userName = validationResponse.getAuthorizedUser(); return true; } } } catch (RemoteException e) { log.error("Error when calling the remote service", e); } } return false; }
Source:
<code>public String[] getCredentials() { String[] credential = new String[2]; log.info("generate new valid token for admin"); try { Response response; WebTarget wr = this.client.target(url); String payload = "{\"auth\": {\"tenantName\": \"" + tenant + "\", \"" + "passwordCredentials\":{\"username\": \"" + user + "\"," + " \"password\": \"" + pass + "\"}}}"; Invocation.Builder builder = wr.request(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON); response = builder.post(Entity.entity(payload, MediaType.APPLICATION_JSON)); <START> if (response.getStatus() == 200) { <END> JSONObject jsonObject = JSONObject.fromObject(response.readEntity(String.class)); jsonObject = (JSONObject) jsonObject.get("access"); if (jsonObject.containsKey("token")) { JSONObject tokenObject = (JSONObject) jsonObject.get("token"); token = (String) tokenObject.get("id"); tenantId = (String) ((JSONObject) tokenObject.get("tenant")).get("id"); credential[0] = token; credential[1] = tenantId; log.info("generated new token for tenantId:" + tenantId); } } else { String exceptionMessage = "Failed : HTTP error code : (" + url + ")" + response.getStatus() + " message: " + response; log.error(exceptionMessage); throw new AuthenticationConnectionException(exceptionMessage); } } catch (Exception ex) { throw new AuthenticationConnectionException("Error in authentication: " + ex); } return credential; }</code><technical_language>Magic number</technical_language>

Target:
public String[] getCredentials() { String[] credential = new String[2]; log.info("generate new valid token for admin"); try { Response response; WebTarget wr = this.client.target(url); String payload = "{\"auth\": {\"tenantName\": \"" + tenant + "\", \"" + "passwordCredentials\":{\"username\": \"" + user + "\"," + " \"password\": \"" + pass + "\"}}}"; Invocation.Builder builder = wr.request(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON); response = builder.post(Entity.entity(payload, MediaType.APPLICATION_JSON)); if ((response.getStatus() == CODE_200) || (response.getStatus() == CODE_203)) { JSONObject jsonObject = JSONObject.fromObject(response.readEntity(String.class)); jsonObject = (JSONObject) jsonObject.get("access"); if (jsonObject.containsKey("token")) { JSONObject tokenObject = (JSONObject) jsonObject.get("token"); token = (String) tokenObject.get("id"); tenantId = (String) ((JSONObject) tokenObject.get("tenant")).get("id"); credential[0] = token; credential[1] = tenantId; log.info("generated new token for tenantId:" + tenantId); } } else { String exceptionMessage = "Failed : HTTP error code : (" + url + ")" + response.getStatus() + " message: " + response; log.error(exceptionMessage); throw new AuthenticationConnectionException(exceptionMessage); } } catch (Exception ex) { throw new AuthenticationConnectionException("Error in authentication: " + ex); } return credential; }
Source:
<code><START> private byte[] fromBytesPayload(Message<byte[]> message) throws UnsupportedEncodingException, Exception { <END> byte[] headers = this.objectMapper.writeValueAsBytes(message.getHeaders()); byte[] payload = message.getPayload(); ByteBuffer buffer = ByteBuffer.wrap(new byte[8 + headers.length + payload.length]); buffer.putInt(headers.length); buffer.put(headers); buffer.putInt(payload.length); buffer.put(payload); return buffer.array(); }</code><technical_language>Redundant UnsupportedEncodingException</technical_language>

Target:
private byte[] fromBytesPayload(Message<byte[]> message) throws Exception { byte[] headers = this.objectMapper.writeValueAsBytes(message.getHeaders()); byte[] payload = message.getPayload(); ByteBuffer buffer = ByteBuffer.wrap(new byte[8 + headers.length + payload.length]); buffer.putInt(headers.length); buffer.put(headers); buffer.putInt(payload.length); buffer.put(payload); return buffer.array(); }
Source:
<code>private KubernetesNamespaceMeta asNamespaceMeta(Namespace namespace) { <START> Map<String, String> attributes = new HashMap<>(); <END> if (namespace.getStatus() != null && namespace.getStatus().getPhase() != null) { attributes.put(PHASE_ATTRIBUTE, namespace.getStatus().getPhase()); } return new KubernetesNamespaceMetaImpl(namespace.getMetadata().getName(), attributes); }</code><technical_language>A bit of a nitpick creating a hashmap preinitialized capacity of (at least) 16 put 1 element there</technical_language>

Target:
private KubernetesNamespaceMeta asNamespaceMeta(Namespace namespace) { Map<String, String> attributes = new HashMap<>(2); if (namespace.getStatus() != null && namespace.getStatus().getPhase() != null) { attributes.put(PHASE_ATTRIBUTE, namespace.getStatus().getPhase()); } return new KubernetesNamespaceMetaImpl(namespace.getMetadata().getName(), attributes); }
Source:
<code>public void testTableName() { final Config config = new Config() { @Override public String getUser() { return "testTableName"; } @Override public Environment getEnvironment() { return Environment.LOCAL; <START> } <END> @Override public String get(String key) { return null; } @Override public int getInt(String key) { return 0; } @Override public List<String> getList(String key) { return null; } }; final String fqTableName = DynamoUtils.getFullyQualifiedTableName(TestHealthDataRecord.class, config); assertEquals("local-testTableName-TestHealthDataRecord", fqTableName); final String simpleTableName = DynamoUtils.getSimpleTableName(fqTableName, config); assertEquals("TestHealthDataRecord", simpleTableName); assertEquals(fqTableName, DynamoUtils.getFullyQualifiedTableName(simpleTableName, config)); }</code><technical_language>a mock for this? least, write code</technical_language>

Target:
public void testTableName() { final Config config = mock(Config.class); when(config.getUser()).thenReturn("testTableName"); when(config.getEnvironment()).thenReturn(Environment.LOCAL); final String fqTableName = DynamoUtils.getFullyQualifiedTableName(TestHealthDataRecord.class, config); assertEquals("local-testTableName-TestHealthDataRecord", fqTableName); final String simpleTableName = DynamoUtils.getSimpleTableName(fqTableName, config); assertEquals("TestHealthDataRecord", simpleTableName); assertEquals(fqTableName, DynamoUtils.getFullyQualifiedTableName(simpleTableName, config)); }
Source:
<code>public String toString() { <START> return "(" + name + " " + lambdaExpr + ", " + argsExpr + ")"; <END> }</code><technical_language>nit: called (if ever) , String.format(..) equivalent. needed in some other places</technical_language>

Target:
public String toString() { return StringUtils.format("(%s %s, %s)", name, lambdaExpr, argsExpr); }
Source:
<code>public boolean hasCurrency(String name) { <START> return true; END> }</code><technical_language>this case? This kind of sketchy - matter currency I try use, Ess currencies this one? Reserve some additional UI top of this hides this detail for single currency economies</technical_language>

Target:
public boolean hasCurrency(String name) { return name.equalsIgnoreCase(ess.getSettings().getCurrencySingular()); }
Source:
<code>public FileSystemContextReinitializer(FileSystemContext context) { mContext = context; mExecutor = new ConfigHashSync(context); REINIT_EXECUTOR.submit( <START> new HeartbeatThread(HeartbeatContext.META_MASTER_CONFIG_HASH_SYNC, mContext.getId(), <END> mExecutor, mContext.getClientContext().getClusterConf().getMs( PropertyKey.USER_CONF_SYNC_INTERVAL), mContext.getClientContext().getClusterConf(), mContext.getClientContext().getUserState())); }</code><technical_language>I suspect submission hold thread rest a chance run</technical_language>

Target:
public FileSystemContextReinitializer(FileSystemContext context) { mContext = context; mExecutor = new ConfigHashSync(context); mFuture = REINIT_EXECUTOR.scheduleAtFixedRate(() -> { try { mExecutor.heartbeat(); } catch (Exception e) { LOG.error("Uncaught exception in config hearbeat executor, shutting down", e); } }, 0, mContext.getClientContext().getClusterConf().getMs(PropertyKey.USER_CONF_SYNC_INTERVAL), TimeUnit.MILLISECONDS); }
Source:
<code>public void setFilter(String filter) { if(filter.equals(null)) { <START> throw new IllegalArgumentException("Invalid filter value"); <END> } String[] allowedFilters = {"Point", "Hermite", "Cubic", "Box", "Gaussian", "Catrom", "Triangle", "Quadratic", "Mitchell"}; for (int i = 0; i < allowedFilters.length; i++) { if(filter.equalsIgnoreCase(allowedFilters[i])) { this.filter = filter; return; } } throw new IllegalArgumentException("Invalid filter value"); }</code><technical_language>This Exception message is misleading. is invalid... is simply null. message state "Filter null" wish print allowedFilters part of exception message</technical_language>

Target:
public void setFilter(String filter) { if(filter.equals(null)) { throw new IllegalArgumentException("Filter value cannot be null. Valid values are point, hermite, " + "cubic, box, gaussian, catrom, triangle, quadratic and mitchell."); } String[] allowedFilters = {"Point", "Hermite", "Cubic", "Box", "Gaussian", "Catrom", "Triangle", "Quadratic", "Mitchell"}; for (int i = 0; i < allowedFilters.length; i++) { if(filter.equalsIgnoreCase(allowedFilters[i])) { this.filter = filter; return; } } throw new IllegalArgumentException("Invalid filter value. Valid values are point, hermite, " + "cubic, box, gaussian, catrom, triangle, quadratic and mitchell."); }
Source:
<code>public static RuleChain setupCompositionWithTimelock( Class<?> eteClass, String composeFile, List<String> availableClientNames, Map<String, String> environment) { <START> waitDuration = Duration.TEN_MINUTES; <END> return setup(eteClass, composeFile, availableClientNames, environment, true); }</code><technical_language>intentional</technical_language>

Target:
public static RuleChain setupCompositionWithTimelock( Class<?> eteClass, String composeFile, List<String> availableClientNames, Map<String, String> environment) { waitDuration = Duration.TWO_MINUTES; return setup(eteClass, composeFile, availableClientNames, environment, true); }
Source:
<code><START> public void testSerdeForConsumerPropertiesWithPasswords() throws Exception <END> { String jsonStr = "{\n" + " \"type\": \"kafka\",\n" + " \"topic\": \"my-topic\",\n" + " \"consumerProperties\": {\"bootstrap.servers\":\"localhost:9092\"," + " \"ssl.truststore.password\":\"mytruststorepassword\"," + " \"ssl.keystore.password\":\"mykeystorepassword\"," + " \"ssl.key.password\":\"mykeypassword\"}\n" + "}"; KafkaSupervisorIOConfig config = mapper.readValue( mapper.writeValueAsString( mapper.readValue( jsonStr, KafkaSupervisorIOConfig.class ) ), KafkaSupervisorIOConfig.class ); Assert.assertEquals("my-topic", config.getTopic()); Map<String, Object> consumerPropertyMap = config.getConsumerProperties(); DefaultPasswordProvider trustStorePasswordProvider = new DefaultPasswordProvider(String.valueOf(consumerPropertyMap.get( "ssl.truststore.password"))); DefaultPasswordProvider keyStorePasswordProvider = new DefaultPasswordProvider(String.valueOf(consumerPropertyMap.get( "ssl.keystore.password"))); DefaultPasswordProvider keyPasswordProvider = new DefaultPasswordProvider(String.valueOf(consumerPropertyMap.get( "ssl.key.password"))); Assert.assertEquals("localhost:9092", consumerPropertyMap.get("bootstrap.servers")); Assert.assertEquals("mytruststorepassword", trustStorePasswordProvider.getPassword()); Assert.assertEquals("mykeystorepassword", keyStorePasswordProvider.getPassword()); Assert.assertEquals("mykeypassword", keyPasswordProvider.getPassword()); }</code><technical_language>Sounds reasonable me. interested in testing functionality of EnvironmentVariablePasswordProvider here, done in EnvironmentVariablePasswordProviderTest (but tested it..)</technical_language>

Target:
public void testSerdeForConsumerPropertiesWithPasswords() throws Exception { String jsonStr = "{\n" + " \"type\": \"kafka\",\n" + " \"topic\": \"my-topic\",\n" + " \"consumerProperties\": {\"bootstrap.servers\":\"localhost:9092\",\n" + " \"ssl.truststore.password\":{\"type\": \"default\", \"password\": \"mytruststorepassword\"},\n" + " \"ssl.keystore.password\":{\"type\": \"default\", \"password\": \"mykeystorepassword\"},\n" + " \"ssl.key.password\":\"mykeypassword\"}\n" + "}"; KafkaSupervisorIOConfig config = mapper.readValue( jsonStr, KafkaSupervisorIOConfig.class ); Properties props = new Properties(); KafkaIndexTask.addConsumerPropertiesFromConfig(props, mapper, config.getConsumerProperties()); Assert.assertEquals("my-topic", config.getTopic()); Assert.assertEquals("localhost:9092", props.getProperty("bootstrap.servers")); Assert.assertEquals("mytruststorepassword", props.getProperty("ssl.truststore.password")); Assert.assertEquals("mykeystorepassword", props.getProperty("ssl.keystore.password")); Assert.assertEquals("mykeypassword", props.getProperty("ssl.key.password")); }
Source:
<code>private ProjectState lookup(final Project.NameKey key) throws OrmException { final ReviewDb db = schema.open(); try { final Project p = db.projects().get(key); if (p == null) { return null; } final List<RefRight> rights = <START> Collections.unmodifiableList(db.refRights().byProject( <END> p.getNameKey()).toList()); return projectStateFactory.create(p, rights, inheritedRights); } finally { db.close(); } }</code><technical_language>RefControl sorts RefRights use, a need for List<RefRight>. API change List Collection these</technical_language>

Target:
private ProjectState lookup(final Project.NameKey key) throws OrmException { final ReviewDb db = schema.open(); try { final Project p = db.projects().get(key); if (p == null) { return null; } final Collection<RefRight> rights = Collections.unmodifiableCollection(db.refRights().byProject( p.getNameKey()).toList()); return projectStateFactory.create(p, rights, inheritedRights); } finally { db.close(); } }
Source:
<code>public boolean cancel(boolean mayInterruptIfRunning) { if (this.timeoutTask != null) { this.timeoutTask.cancel(true); } AsyncRabbitTemplate.this.pending.remove(this.correlationId); if (RabbitFuture.this.channel != null) { <START> AsyncRabbitTemplate.this.directReplyToContainer.releaseConsumerFor(RabbitFuture.this.channel, false, <END> null); } return super.cancel(mayInterruptIfRunning); }</code><technical_language>directReplyToContainer null. I agree this.channel is fully depends of AsyncRabbitTemplate.this.directReplyToContainer, modify avoid a noise: ![potential_npe](<LINK_0> provide some message anyway. is in event downstream: consumer.cancelConsumer("Consumer " + this + " canceled due " + message); ... publishConsumerFailedEvent(eventMessage, true, null); minor: need in RabbitFuture. prefix for this.channel</technical_language>

Target:
public boolean cancel(boolean mayInterruptIfRunning) { if (this.timeoutTask != null) { this.timeoutTask.cancel(true); } AsyncRabbitTemplate.this.pending.remove(this.correlationId); if (this.channel != null && AsyncRabbitTemplate.this.directReplyToContainer != null) { AsyncRabbitTemplate.this.directReplyToContainer.releaseConsumerFor(this.channel, false, null); } return super.cancel(mayInterruptIfRunning); }
Source:
<code>private boolean getEncodecoordinatesMeasures(Configuration configuration) { org.geotools.gml3.v3_2.GMLConfiguration config; if (configuration instanceof org.geotools.gml3.v3_2.GMLConfiguration) { config = (org.geotools.gml3.v3_2.GMLConfiguration) configuration; } else { config = configuration.getDependency(org.geotools.gml3.v3_2.GMLConfiguration.class); } <START> <END> if (config == null) { return true; } else { return config.getEncodeCoordinatesMeasures(); } }</code><technical_language>Unsure this one, encoding measures for invalid problematic GML in output, do if explicitly requested</technical_language>

Target:
private boolean getEncodecoordinatesMeasures(Configuration configuration) { org.geotools.gml3.v3_2.GMLConfiguration config; if (configuration instanceof org.geotools.gml3.v3_2.GMLConfiguration) { config = (org.geotools.gml3.v3_2.GMLConfiguration) configuration; } else { config = configuration.getDependency(org.geotools.gml3.v3_2.GMLConfiguration.class); } if (config == null) { return false; } else { return config.getEncodeMeasures(); } }
Source:
<code>private void loadMainActivity(){ settings = getSharedPreferences("prefs", 0); <START> SharedPreferences.Editor editor = settings.edit(); <END> editor.putBoolean("firstRun", false); editor.commit(); Intent intent = new Intent(this, StartActivity.class); startActivity(intent); finish(); }</code><technical_language>Name this variable sharedPreferencesEditor for readability</technical_language>

Target:
private void loadMainActivity() { sharedPreferences = getSharedPreferences("prefs", 0); SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit(); sharedPreferencesEditor.putBoolean("firstRun", false); sharedPreferencesEditor.commit(); startActivity(new Intent(this, StartActivity.class)); finish(); }
Source:
<code>public void onFlush(FlushEvent event) { getCurrentWorkPlan( state.getContextProvider(), event.getSession() ).prepare(); Session session = event.getSession(); <START> Synchronization synchronization = flushSynch.get( session ); <END> if ( synchronization != null ) { flushSynch.remove( session ); log.debug( "flush event causing index update out of transaction" ); synchronization.beforeCompletion(); synchronization.afterCompletion( Status.STATUS_COMMITTED ); } }</code><technical_language>This looks... unnecessary? call execute work plan? main advantage is get rid of this weird synchronization map</technical_language>

Target:
public void onFlush(FlushEvent event) { HibernateOrmListenerContextProvider contextProvider = state.getContextProvider(); EventSource session = event.getSession(); PojoWorkPlan currentWorkPlan = getCurrentWorkPlan( contextProvider, session ); currentWorkPlan.prepare(); if ( !session.isTransactionInProgress() ) { AutomaticIndexingSynchronizationStrategy synchronizationStrategy = contextProvider.getSynchronizationStrategy(); synchronizationStrategy.handleFuture( currentWorkPlan.execute() ); } }
Source:
<code><START> public List<String> getDeletions() { <END> return deletes; }</code><technical_language>allow overload OpenEngSBModel</technical_language>

Target:
public List<OpenEngSBModel> getDeletions() { return deletes; }
Source:
<code>public BookieSocketAddress replaceBookie(List<BookieSocketAddress> existingBookies, int bookieIdx) throws BKNotEnoughBookiesException { BookieSocketAddress addr = existingBookies.get(bookieIdx); try { <START> List<BookieSocketAddress> existingAndQuarantinedBookies = Lists.newArrayList(); <END> existingAndQuarantinedBookies.addAll(existingBookies); existingAndQuarantinedBookies.addAll(quarantinedBookies.asMap().keySet()); return placementPolicy.replaceBookie(addr, new HashSet<BookieSocketAddress>(existingAndQuarantinedBookies)); } catch (BKNotEnoughBookiesException e) { if (logger.isDebugEnabled()) { logger.debug("Not enough healthy bookies available, using quarantined bookies"); } return placementPolicy.replaceBookie(addr, new HashSet<BookieSocketAddress>(existingBookies)); } }</code><technical_language>create a hash set directly</technical_language>

Target:
public BookieSocketAddress replaceBookie(List<BookieSocketAddress> existingBookies, int bookieIdx) throws BKNotEnoughBookiesException { BookieSocketAddress addr = existingBookies.get(bookieIdx); try { Set<BookieSocketAddress> existingAndQuarantinedBookies = new HashSet<BookieSocketAddress>(existingBookies); existingAndQuarantinedBookies.addAll(quarantinedBookies.asMap().keySet()); return placementPolicy.replaceBookie(addr, existingAndQuarantinedBookies); } catch (BKNotEnoughBookiesException e) { if (logger.isDebugEnabled()) { logger.debug("Not enough healthy bookies available, using quarantined bookies"); } return placementPolicy.replaceBookie(addr, new HashSet<BookieSocketAddress>(existingBookies)); } }
Source:
<code>public Proposal(List<Command> cmds) { <START> this.commands = <END> cmds; }</code><technical_language>unmodifiable copy here</technical_language>

Target:
public Proposal(List<Command> cmds) { commands = Collections.unmodifiableList(new ArrayList<>(cmds)); }
Source:
<code>private MockHttpServletRequest requestToSave() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerPort(443); request.setSecure(true); request.setScheme("https"); request.setServerName("abc.com"); request.setRequestURI("/destination"); <START> request.setServletPath("/destination"); <END> request.setQueryString("param1=a&param2=b&param3=1122"); return request; }</code><technical_language>set servlet path for this test pass</technical_language>

Target:
private MockHttpServletRequest requestToSave() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerPort(443); request.setSecure(true); request.setScheme("https"); request.setServerName("abc.com"); request.setRequestURI("/destination"); request.setQueryString("param1=a&param2=b&param3=1122"); return request; }
Source:
<code>public Void performTask() throws Throwable { SavedPage savedPage = new SavedPage(title); savedPage.writeToFileSystem(page); SavedPagePersister persister = (SavedPagePersister) app.getPersister(SavedPage.class); persister.upsert(savedPage); try { ImageUrlMap imageUrlMap = new ImageUrlMap.Builder(savedPage.getBaseDir()).extractUrls(page).build(); downloadImages(imageUrlMap); savedPage.writeUrlMap(imageUrlMap.toJSON()); } catch (HttpRequest.HttpRequestException e) { <START> Log.e(TAG, "image download failed", e); END> } return null; }</code><technical_language>Add a FIXME here</technical_language>

Target:
public Boolean performTask() throws Throwable { SavedPage savedPage = new SavedPage(title); savedPage.writeToFileSystem(page); SavedPagePersister persister = (SavedPagePersister) app.getPersister(SavedPage.class); persister.upsert(savedPage); try { ImageUrlMap imageUrlMap = new ImageUrlMap.Builder(savedPage.getBaseDir()).extractUrls(page).build(); downloadImages(imageUrlMap); savedPage.writeUrlMap(imageUrlMap.toJSON()); return true; } catch (HttpRequest.HttpRequestException e) { Log.e(TAG, "image download failed", e); return false; } }
Source:
<code>public void shouldGenerateVepInput() throws Exception { mongoRule.restoreDump(getResourceUrl(MONGO_DUMP), jobOptions.getDbName()); File vepOutputFolder = temporaryFolderRule.newFolder(); File vepInputFile = new File(VepUtils.resolveVepInput(vepOutputFolder.getAbsolutePath(), STUDY_ID, FILE_ID)); if (vepInputFile.exists()) vepInputFile.delete(); assertFalse(vepInputFile.exists()); JobParameters jobParameters = new EvaJobParameterBuilder() .collectionVariantsName("variants") <START> .databaseName("VepInputGeneratorStepTest") <END> .inputStudyId(STUDY_ID) .inputVcfId(FILE_ID) .outputDirAnnotation(vepOutputFolder.getAbsolutePath()) .toJobParameters(); JobExecution jobExecution = jobLauncherTestUtils.launchStep(BeanNames.GENERATE_VEP_INPUT_STEP, jobParameters); assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus()); assertTrue(vepInputFile.exists()); assertEquals("20\t60343\t60343\tG/A\t+", readFirstLine(vepInputFile)); }</code><technical_language>This a random database based TemporaryMongoRule</technical_language>

Target:
public void shouldGenerateVepInput() throws Exception { String randomTemporaryDatabaseName = mongoRule.restoreDumpInTemporaryDatabase(getResourceUrl(MONGO_DUMP)); File vepOutputFolder = temporaryFolderRule.newFolder(); File vepInputFile = new File(VepUtils.resolveVepInput(vepOutputFolder.getAbsolutePath(), STUDY_ID, FILE_ID)); if (vepInputFile.exists()) vepInputFile.delete(); assertFalse(vepInputFile.exists()); JobParameters jobParameters = new EvaJobParameterBuilder() .collectionVariantsName("variants") .databaseName(randomTemporaryDatabaseName) .inputStudyId(STUDY_ID) .inputVcfId(FILE_ID) .outputDirAnnotation(vepOutputFolder.getAbsolutePath()) .toJobParameters(); JobExecution jobExecution = jobLauncherTestUtils.launchStep(BeanNames.GENERATE_VEP_INPUT_STEP, jobParameters); assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus()); assertTrue(vepInputFile.exists()); assertEquals("20\t60343\t60343\tG/A\t+", readFirstLine(vepInputFile)); }
Source:
<code><START> public Request authenticate(Route route, Response response) throws IOException { <END> if (requiresAuth(response.request())) { userSessionInfoProvider.reauthenticate(); return addBridgeHeaders(response.request()); } return null; }</code><technical_language>a retry count here, avoiding infinite loops for 401s (e.g. password changed)</technical_language>

Target:
public Request authenticate(Route route, Response response) throws IOException { if (requiresAuth(response.request(), false)) { userSessionInfoProvider.reauthenticate(); return addBridgeHeaders(response.request()); } return null; }
Source:
<code>public void run() { Builder builder = new Builder(); builder.build(); Dataset dataset = new Dataset(); dataset.read(); Learner learner = new Learner(builder.parser, builder.params, dataset); learner.learn(); if (server) { Master master = new Master(builder); Server server = new Server(master); server.run(); } <START> if (interactiveLearning) { <END> Master master = new InteractiveMaster(builder); InteractiveServer server = new InteractiveServer(master); server.run(); master.runInteractivePrompt(); } if (interactive) { Master master = new InteractiveMaster(builder); master.runInteractivePrompt(); } }</code><technical_language>code specializes interactive? Ideally, instantiate InteractiveMaster class reflection takes care of setting else up...this clutter Main.java</technical_language>

Target:
public void run() { Builder builder = new Builder(); builder.build(); Dataset dataset = new Dataset(); dataset.read(); Learner learner = new Learner(builder.parser, builder.params, dataset); learner.learn(); if (server || interactive) { Master master = createMaster(masterType, builder); if (server) master.runServer(); if (interactive) master.runInteractivePrompt(); } }
Source:
<code>public void doAddRoleWithID(String roleName, String[] userIDList, boolean shared) throws UserStoreException { List<String> userList = getUserNamesFromUserIDs(Arrays.asList(userIDList)); <START> String userStoreDomain = getUserStoreOfRoles(roleName).getDomainName(); <END> boolean containsInvalidUsernames = userList.stream() .anyMatch(username -> !UserCoreUtil.extractDomainFromName(username).equalsIgnoreCase(userStoreDomain)); if (containsInvalidUsernames) { throw new UserStoreException("One or more users in the users list: " + userList + " do not belong to the" + " user store: " + userStoreDomain); } userList = userList.stream().map(UserCoreUtil::removeDomainFromName).collect(Collectors.toList()); RoleContext roleContext; roleContext = createRoleContext(roleName); roleContext.setMembers(userList.toArray(new String[0])); addLDAPRole(roleContext); if (shared && isSharedGroupEnabled()) { String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); roleName = roleName + UserCoreConstants.TENANT_DOMAIN_COMBINER + tenantDomain; roleContext = createRoleContext(roleName); addLDAPRole(roleContext); } }</code><technical_language>getMyDomainName()</technical_language>

Target:
public void doAddRoleWithID(String roleName, String[] userIDList, boolean shared) throws UserStoreException { List<String> userList = getUserNamesFromUserIDs(Arrays.asList(userIDList)); String userStoreDomain = getMyDomainName(); boolean containsInvalidUsernames = userList.stream() .anyMatch(username -> !UserCoreUtil.extractDomainFromName(username).equalsIgnoreCase(userStoreDomain)); if (containsInvalidUsernames) { throw new UserStoreException("One or more users in the users list: " + userList + " do not belong to the" + " user store: " + userStoreDomain); } userList = userList.stream().map(UserCoreUtil::removeDomainFromName).collect(Collectors.toList()); RoleContext roleContext; roleContext = createRoleContext(roleName); roleContext.setMembers(userList.toArray(new String[0])); addLDAPRole(roleContext); if (shared && isSharedGroupEnabled()) { String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); roleName = roleName + UserCoreConstants.TENANT_DOMAIN_COMBINER + tenantDomain; roleContext = createRoleContext(roleName); addLDAPRole(roleContext); } }
Source:
<code>private void parseAmazonS3URI(String s3Uri) { <START> AmazonS3URI amazonS3URI = new AmazonS3URI(s3Uri); <END> if ((scheme = amazonS3URI.getURI().getScheme()) == null) { throw new IllegalArgumentException("You have to specify a valid scheme in the provided s3 uri. Empty value is not allowed."); } if ((host = amazonS3URI.getURI().getHost()) == null) { throw new IllegalArgumentException("You have to specify a valid host in the provided s3 uri. Empty value is not allowed."); } if ((bucketName = amazonS3URI.getBucket()) == null) { throw new IllegalArgumentException("You have to specify a valid bucket name in the provided s3 uri. Empty value is not allowed."); } if ((keyName = amazonS3URI.getKey()) == null) { throw new IllegalArgumentException("You have to specify a valid key name in the provided s3 uri. Empty value is not allowed."); } }</code><technical_language>this in model class</technical_language>

Target:
private void parseAmazonS3URI(String s3Uri) { AmazonS3URI amazonS3URI = new AmazonS3URI(s3Uri); if ((scheme = amazonS3URI.getURI().getScheme()) == null) { throw new IllegalArgumentException("You have to specify a valid scheme in the provided s3 uri. Empty value is not allowed."); } if ((host = amazonS3URI.getURI().getHost()) == null) { throw new IllegalArgumentException("You have to specify a valid host in the provided s3 uri. Empty value is not allowed."); } if ((bucketName = amazonS3URI.getBucket()) == null) { throw new IllegalArgumentException("You have to specify a valid bucket name in the provided s3 uri. Empty value is not allowed."); } if ((s3RemoteRelativePath = amazonS3URI.getKey()) == null) { throw new IllegalArgumentException("You have to specify a valid key name in the provided s3 uri. Empty value is not allowed."); } }