auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected String transformResponse(String transformation, String response) { String transformedResponse; try { String[] parts = splitTransformationConfig(transformation); String transformationType = parts[0]; String transformationFunction = parts[1]; <START> if (transformationType == "") { END> transformedResponse = transformationFunction; } else { TransformationService transformationService = TransformationHelper .getTransformationService(TCPActivator.getContext(), transformationType); if (transformationService != null) { transformedResponse = transformationService.transform(transformationFunction, response); } else { transformedResponse = response; logger.warn("couldn't transform response because transformationService of type '{}' is unavailable", transformationType); } } } catch (Exception te) { logger.error("transformation throws exception [transformation=" + transformation + ", response=" + response + "]", te); transformedResponse = response; } logger.debug("transformed response is '{}'", transformedResponse); return transformedResponse; }</code><technical_language>compare strings equals method in Java. Testing == method return true accidentally</technical_language>

Target:
protected String transformResponse(String transformation, String response) { String transformedResponse; Matcher matcher = EXTRACT_FUNCTION_PATTERN.matcher(transformation); String transformationServiceName; String transformationServiceParam; if (StringUtils.isEmpty(transformation) || transformation.equalsIgnoreCase("default")) { transformedResponse = response; } else if (matcher.matches()) { matcher.reset(); matcher.find(); transformationServiceName = matcher.group(1); transformationServiceParam = matcher.group(2); try { TransformationService transformationService = TransformationHelper .getTransformationService(TCPActivator.getContext(), transformationServiceName); if (transformationService != null) { transformedResponse = transformationService.transform(transformationServiceParam, response); } else { transformedResponse = response; logger.warn("couldn't transform response because transformationService of type '{}' is unavailable", transformationServiceName); } } catch (Exception te) { logger.error("transformation throws exception [transformation=" + transformation + ", response=" + response + "]", te); transformedResponse = response; } } else { transformedResponse = transformation; } logger.debug("transformed response is '{}'", transformedResponse); return transformedResponse; }
Source:
<code>public boolean canBePreempted() { <START> assert parent != null; <END> if (parent.policy.checkIfUsageOverFairShare( getResourceUsage(), getFairShare())) { return true; } else { for (FSQueue queue: getChildQueues()) { if (queue.canBePreempted()) { return true; } } } return false; }</code><technical_language>is this necessary</technical_language>

Target:
public boolean canBePreempted() { if (parent == null || parent.policy.checkIfUsageOverFairShare( getResourceUsage(), getFairShare())) { return true; } else { for (FSQueue queue: getChildQueues()) { if (queue.canBePreempted()) { return true; } } } return false; }
Source:
<code>public static Set<InstanceConfig> getBrokerInstanceConfigsForTenant(List<InstanceConfig> instanceConfigs, String tenant) { <START> return new HashSet<>(HelixHelper.getInstancesConfigsWithTag(instanceConfigs, TagNameUtils.getBrokerTagForTenant(tenant))); <END> }</code><technical_language>suggestion return new HashSet<>(getInstancesConfigsWithTag(instanceConfigs, TagNameUtils.getBrokerTagForTenant(tenant)));</technical_language>

Target:
public static Set<InstanceConfig> getBrokerInstanceConfigsForTenant(List<InstanceConfig> instanceConfigs, String tenant) { return new HashSet<>(getInstancesConfigsWithTag(instanceConfigs, TagNameUtils.getBrokerTagForTenant(tenant))); }
Source:
<code>public static ErlangFunctionReferenceImpl<ErlangQAtom> createFunctionReference(@NotNull ErlangQAtom atom) { ErlangFunctionCallExpression call = PsiTreeUtil.getParentOfType(atom, ErlangFunctionCallExpression.class); if (call != null) { int position = getPositionInFunctionCall(call, atom); List<ErlangExpression> expressions = call.getArgumentList().getExpressionList(); <START> if (0 < position && position + 1 < expressions.size()) { <END> ErlangMaxExpression module = ObjectUtils.tryCast(expressions.get(position - 1), ErlangMaxExpression.class); ErlangListExpression list = ObjectUtils.tryCast(expressions.get(position + 1), ErlangListExpression.class); ErlangQAtom moduleAtom = module != null ? module.getQAtom() : null; int arity = list != null ? list.getExpressionList().size() : -1; return new ErlangFunctionReferenceImpl<ErlangQAtom>(atom, moduleAtom, arity); } } return new ErlangFunctionReferenceImpl<ErlangQAtom>(atom, null, -1); }</code><technical_language>Please, do comparisons uniformly. checked right hand side, - left. hard read - choose order stick everywhere</technical_language>

Target:
public static ErlangFunctionReferenceImpl<ErlangQAtom> createFunctionReference(@NotNull ErlangQAtom atom) { ErlangFunctionCallExpression call = PsiTreeUtil.getParentOfType(atom, ErlangFunctionCallExpression.class); if (call != null) { int position = getPositionInFunctionCall(call, atom); List<ErlangExpression> expressions = call.getArgumentList().getExpressionList(); if (position > 0 && position + 1 < expressions.size()) { ErlangMaxExpression module = ObjectUtils.tryCast(expressions.get(position - 1), ErlangMaxExpression.class); ErlangListExpression list = ObjectUtils.tryCast(expressions.get(position + 1), ErlangListExpression.class); ErlangQAtom moduleAtom = module != null ? module.getQAtom() : null; int arity = list != null ? list.getExpressionList().size() : -1; return new ErlangFunctionReferenceImpl<ErlangQAtom>(atom, moduleAtom, arity); } } return new ErlangFunctionReferenceImpl<ErlangQAtom>(atom, null, -1); }
Source:
<code>protected List<String> generateHeaderValues() { List<String> result = new ArrayList<String>(); result.add("Certification Edition"); result.add("CHPL ID"); result.add("Listing Database ID"); result.add("ONC-ACB Certification ID"); result.add("Certification Date"); result.add("Inactive As Of Date"); result.add("Decertified As Of Date"); result.add("Certification Status"); result.add("ACB Name"); result.add("Previous ACB Name"); result.add("Developer Name"); result.add("Developer Database ID"); result.add("Vendor Street Address"); result.add("Vendor City"); result.add("Vendor State"); result.add("Vendor Zip Code"); result.add("Vendor Website"); result.add("Self-developer"); result.add("Vendor Contact Name"); result.add("Vendor Contact Email"); result.add("Vendor Contact Phone"); result.add("Product Name"); result.add("Product Database ID"); <START> result.add("Version"); <END> result.add("Real World Testing Eligibility Year"); result.add("Real World Testing Plan URL"); result.add("Real World Testing Plan Submission Date"); result.add("Real World Testing Results URL"); result.add("Real World Testing Results Submission Date"); result.add("Total Surveillance Activities"); result.add("Total Nonconformities"); result.add("Open Nonconformities"); if (applicableCriteria != null) { for (CertificationCriterionDTO criteria : applicableCriteria) { result.add(criteria.getNumber() + ": " + criteria.getTitle()); } } return result; }</code><technical_language>I this line removed</technical_language>

Target:
protected List<String> generateHeaderValues() { List<String> result = new ArrayList<String>(); result.add("Certification Edition"); result.add("CHPL ID"); result.add("Listing Database ID"); result.add("ONC-ACB Certification ID"); result.add("Certification Date"); result.add("Inactive As Of Date"); result.add("Decertified As Of Date"); result.add("Certification Status"); result.add("ACB Name"); result.add("Previous ACB Name"); result.add("Developer Name"); result.add("Developer Database ID"); result.add("Vendor Street Address"); result.add("Vendor City"); result.add("Vendor State"); result.add("Vendor Zip Code"); result.add("Vendor Website"); result.add("Self-developer"); result.add("Vendor Contact Name"); result.add("Vendor Contact Email"); result.add("Vendor Contact Phone"); result.add("Product Name"); result.add("Product Database ID"); result.add("Version"); result.add("Version Database ID"); result.add("Real World Testing Eligibility Year"); result.add("Real World Testing Plans URL"); result.add("Real World Testing Results URL"); result.add("Total Surveillance Activities"); result.add("Total Nonconformities"); result.add("Open Nonconformities"); if (applicableCriteria != null) { for (CertificationCriterionDTO criteria : applicableCriteria) { result.add(criteria.getNumber() + ": " + criteria.getTitle()); } } return result; }
Source:
<code><START> public List<Timeline> getActiveTimelinesOrdered(final String eventType) <END> throws InternalNakadiException, NoSuchEventTypeException { final List<Timeline> timelines = eventTypeCache.getTimelines(eventType); if (timelines.isEmpty()) { return Collections.singletonList(getFakeTimeline(eventTypeCache.getEventType(eventType))); } else { return timelines.stream().sorted(Comparator.comparing(Timeline::getOrder)).collect(Collectors.toList()); } }</code><technical_language>I a test for this new method</technical_language>

Target:
public List<Timeline> getActiveTimelinesOrdered(final String eventType) throws InternalNakadiException, NoSuchEventTypeException { final List<Timeline> timelines = eventTypeCache.getTimelinesOrdered(eventType); if (timelines.isEmpty()) { return Collections.singletonList(getFakeTimeline(eventTypeCache.getEventType(eventType))); } else { return timelines.stream().filter(t -> t.getSwitchedAt() != null).collect(Collectors.toList()); } }
Source:
<code><START> public void shouldReturnEncounterForLookupGetEncounterByUuid() { <END> String className = OpenMRSEncounter.class.getSimpleName(); Map<String, String> lookupFields = new HashMap<>(); lookupFields.put(UUID, "5"); OpenMRSEncounter openMRSEncounter = new OpenMRSEncounter(); openMRSEncounter.setEncounterType("encounterTypeTest"); when(encounterService.getEncounterByUuid("5")).thenReturn(openMRSEncounter); Object object = taskDataProvider.lookup(className, BY_UUID, lookupFields); assertTrue(object instanceof OpenMRSEncounter); assertEquals("encounterTypeTest", ((OpenMRSEncounter) object).getEncounterType()); verify(encounterService).getEncounterByUuid("5"); }</code><technical_language>Is test testing when().thenReturn() I missing something</technical_language>

Target:
public void shouldReturnEncounterForLookupGetEncounterByUuid() { String className = OpenMRSEncounter.class.getSimpleName(); Map<String, String> lookupFields = new HashMap<>(); lookupFields.put(UUID, "5"); OpenMRSEncounter openMRSEncounter = new OpenMRSEncounter(); openMRSEncounter.setEncounterType("encounterTypeTest"); when(encounterService.getEncounterByUuid("5")).thenReturn(openMRSEncounter); Object object = taskDataProvider.lookup(className, BY_UUID, lookupFields); assertEquals(openMRSEncounter, object); verify(encounterService).getEncounterByUuid("5"); }
Source:
<code>static GeometryHeader fromArrayHeaderBytes( byte[] header ) { int geometryType = Byte.toUnsignedInt( header[1] ); int dimension = Byte.toUnsignedInt( header[2] ); int crsTableId = Byte.toUnsignedInt( header[3] ); <START> int crsCode = Byte.toUnsignedInt( header[5] ) + (Byte.toUnsignedInt( header[4] ) << 8); <END> return new GeometryHeader( geometryType, dimension, crsTableId, crsCode ); }</code><technical_language>please update line "(Byte.toUnsignedInt( header[4] ) << 8) + Byte.toUnsignedInt( header[5] ) "</technical_language>

Target:
static GeometryHeader fromArrayHeaderBytes( byte[] header ) { int geometryType = Byte.toUnsignedInt( header[1] ); int dimension = Byte.toUnsignedInt( header[2] ); int crsTableId = Byte.toUnsignedInt( header[3] ); int crsCode = (Byte.toUnsignedInt( header[4] ) << 8) + Byte.toUnsignedInt( header[5] ); return new GeometryHeader( geometryType, dimension, crsTableId, crsCode ); }
Source:
<code>public void synchronizeStart() throws InterruptedException { Executor e = Executor.currentExecutor(); if (e == null) { throw new IllegalStateException("synchronizeStart shall only be called from an Executor"); } WorkUnit wu = e.getCurrentWorkUnit(); if (wu == null) { throw new IllegalStateException("synchronizeStart shall only be called after a WorkUnit has been assigned"); } boolean mainWork = wu.isMainWork(); try { startLatch.synchronize(); if (mainWork) { future.start.set(e.getCurrentExecutable()); } } catch (Error | RuntimeException | InterruptedException problem) { if (mainWork) { future.start.set(problem); } throw problem; } finally { if (mainWork && !future.start.isDone()) { <START> future.start.set(e.getCurrentExecutable()); <END> } } }</code><technical_language>this override set if exception is raised</technical_language>

Target:
public void synchronizeStart() throws InterruptedException { try { startLatch.synchronize(); } finally { Executor e = Executor.currentExecutor(); WorkUnit wu = e.getCurrentWorkUnit(); if (wu.isMainWork()) { future.start.set(e.getCurrentExecutable()); } } }
Source:
<code><START> static long storageCapacityInBytes(StatFs statFs) { <END> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { return statFs.getTotalBytes(); } else { return (long) statFs.getBlockCount() * (long) statFs.getBlockSize(); } }</code><technical_language>this method is for calculating storage capacity for internal external? Like, if I a device 16GB internal storage a 64GB SD card, numbers this method return right</technical_language>

Target:
long storageCapacityInBytes(StatFs statFs) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { return statFs.getTotalBytes(); } else { return (long) statFs.getBlockCount() * (long) statFs.getBlockSize(); } }
Source:
<code>public PipelinePlacementPolicy(final NodeManager nodeManager, final Configuration conf) { super(nodeManager, conf); <START> this.nodeManager = nodeManager; <END> this.conf = conf; heavy_node_criteria = conf.getInt(ScmConfigKeys.OZONE_SCM_DATANODE_MAX_PIPELINE_ENGAGEMENT, ScmConfigKeys.OZONE_SCM_DATANODE_MAX_PIPELINE_ENGAGEMENT_DEFAULT); }</code><technical_language>This is issue specific this patch. I class hierarchy needs some adjustment. Currently: PipelinePlacementPolicy<-SCMCommonPolicy<-ContainerPlacementPolicy change SCMCommonPolicy base for PipelinePlacementPolicy ContainerPlacementPolicy, if common pieces PipelinePlaceMent ContainerPlacement, move SCMCommonPolicy</technical_language>

Target:
public PipelinePlacementPolicy( final NodeManager nodeManager, final Configuration conf) { super(nodeManager, conf); this.nodeManager = nodeManager; this.conf = conf; heavyNodeCriteria = conf.getInt( ScmConfigKeys.OZONE_DATANODE_MAX_PIPELINE_ENGAGEMENT, ScmConfigKeys.OZONE_DATANODE_MAX_PIPELINE_ENGAGEMENT_DEFAULT); }
Source:
<code>public synchronized void addOrUpdate(final MessageReceiverBreakpoint bId) { FullSourceCoordinate coord = bId.getCoordinate(); BreakpointEnabling<MessageReceiverBreakpoint> existingBP = receiverBreakpoints.get(coord); if (existingBP == null) { existingBP = new BreakpointEnabling<MessageReceiverBreakpoint>(bId); receiverBreakpoints.put(coord, existingBP); } else { <START> existingBP.setEnabled(bId.isEnabled()); <END> } }</code><technical_language>@ctrlpz this is a problem, this line is essential :( need tests for</technical_language>

Target:
public synchronized void addOrUpdate(final MessageReceiverBreakpoint bId) { saveBreakpoint(bId, receiverBreakpoints); }
Source:
<code>protected QosDao<?> getQosDao() { QosType qosType = getParameters().getQosType(); if (qosType == null) { return getDbFacade().getQosBaseDao(); } switch (qosType) { case STORAGE: qosDao = getDbFacade().getStorageQosDao(); break; <START> default: <END> break; } return qosDao; }</code><technical_language>adding a log qosType</technical_language>

Target:
protected QosDao<?> getQosDao() { QosType qosType = getParameters().getQosType(); if (qosType == null) { return getDbFacade().getQosBaseDao(); } switch (qosType) { case STORAGE: qosDao = getDbFacade().getStorageQosDao(); break; default: log.debugFormat("Not handled QoS type: {0}", qosType); break; } return qosDao; }
Source:
<code>private static VertxOptions configureVertx(ClusterManager clusterManager) { VertxOptions options = new VertxOptions() .setClustered(true) <START> .setClusterHost("192.168.1.12") <END> .setClusterPort(17001) .setClusterManager(clusterManager); return options; }</code><technical_language>is clusterHost required</technical_language>

Target:
private static VertxOptions configureVertx(ClusterManager clusterManager) { VertxOptions options = new VertxOptions() .setClustered(true) .setClusterManager(clusterManager); return options; }
Source:
<code>public SuggestLocationsResult suggestLocations(final CharSequence constraint) throws IOException { final String nameCstr = constraint.toString(); final HttpUrl.Builder url = url().addPathSegment("places"); url.addQueryParameter("q", nameCstr); url.addQueryParameter("type[]", "stop_area"); url.addQueryParameter("type[]", "address"); url.addQueryParameter("type[]", "poi"); url.addQueryParameter("type[]", "administrative_region"); url.addQueryParameter("depth", "1"); final CharSequence page = httpClient.get(url.build()); try { final List<SuggestedLocation> locations = new ArrayList<>(); final JSONObject head = new JSONObject(page.toString()); if (head.has("places")) { final JSONArray places = head.getJSONArray("places"); final int priorityBase = places.length(); <START> for (int i = 0; i < places.length(); ++i) { <END> final JSONObject place = places.getJSONObject(i); final int priority = priorityBase - i; final Location location = parseLocation(place); locations.add(new SuggestedLocation(location, priority)); } } final ResultHeader resultHeader = new ResultHeader(network, SERVER_PRODUCT, SERVER_VERSION, null, 0, null); return new SuggestLocationsResult(resultHeader, locations); } catch (final JSONException jsonExc) { throw new ParserException(jsonExc); } }</code><technical_language>a small thing, introduced variable too. numPlaces a more general name</technical_language>

Target:
public SuggestLocationsResult suggestLocations(final CharSequence constraint) throws IOException { final String nameCstr = constraint.toString(); final HttpUrl.Builder url = url().addPathSegment("places"); url.addQueryParameter("q", nameCstr); url.addQueryParameter("type[]", "stop_area"); url.addQueryParameter("type[]", "address"); url.addQueryParameter("type[]", "poi"); url.addQueryParameter("type[]", "administrative_region"); url.addQueryParameter("depth", "1"); final CharSequence page = httpClient.get(url.build()); try { final List<SuggestedLocation> locations = new ArrayList<>(); final JSONObject head = new JSONObject(page.toString()); if (head.has("places")) { final JSONArray places = head.getJSONArray("places"); final int numPlaces = places.length(); for (int i = 0; i < numPlaces; ++i) { final JSONObject place = places.getJSONObject(i); final int priority = numPlaces - i; final Location location = parseLocation(place); locations.add(new SuggestedLocation(location, priority)); } } final ResultHeader resultHeader = new ResultHeader(network, SERVER_PRODUCT, SERVER_VERSION, null, 0, null); return new SuggestLocationsResult(resultHeader, locations); } catch (final JSONException jsonExc) { throw new ParserException(jsonExc); } }
Source:
<code>public TableSpec getTableSpec() { validate(); Map<String, String> tableSpecConfig = new HashMap<>(); generateTableSpecConfig(tableSpecConfig); tableSpecConfig.put(RemoteTableProvider.READ_FN, serializeObject("read function", readFn)); if (writeFn != null) { tableSpecConfig.put(RemoteTableProvider.WRITE_FN, serializeObject("write function", writeFn)); } <START> if (this.rateLimiter == null) { <END> Map<String, Integer> tagCreditsMap = new HashMap<>(); if (readRateLimit > 0) { tagCreditsMap.put(RL_READ_TAG, readRateLimit); } if (writeRateLimit > 0) { tagCreditsMap.put(RL_WRITE_TAG, writeRateLimit); } if (!tagCreditsMap.isEmpty()) { rateLimiter = new EmbeddedTaggedRateLimiter(tagCreditsMap); } } if (rateLimiter != null) { tableSpecConfig.put(RemoteTableProvider.RATE_LIMITER, serializeObject("rate limiter", rateLimiter)); } if (readCreditFn != null) { tableSpecConfig.put(RemoteTableProvider.READ_CREDIT_FN, serializeObject( "read credit function", readCreditFn)); } if (writeCreditFn != null) { tableSpecConfig.put(RemoteTableProvider.WRITE_CREDIT_FN, serializeObject( "write credit function", writeCreditFn)); } return new TableSpec(tableId, serde, RemoteTableProviderFactory.class.getName(), tableSpecConfig); }</code><technical_language>trivial: I usages of this.rateLimiter rateLimiter good stick usage consistently</technical_language>

Target:
public TableSpec getTableSpec() { validate(); Map<String, String> tableSpecConfig = new HashMap<>(); generateTableSpecConfig(tableSpecConfig); tableSpecConfig.put(RemoteTableProvider.READ_FN, serializeObject("read function", readFn)); if (writeFn != null) { tableSpecConfig.put(RemoteTableProvider.WRITE_FN, serializeObject("write function", writeFn)); } if (!tagCreditsMap.isEmpty()) { rateLimiter = new EmbeddedTaggedRateLimiter(tagCreditsMap); } if (rateLimiter != null) { tableSpecConfig.put(RemoteTableProvider.RATE_LIMITER, serializeObject("rate limiter", rateLimiter)); } if (readCreditFn != null) { tableSpecConfig.put(RemoteTableProvider.READ_CREDIT_FN, serializeObject( "read credit function", readCreditFn)); } if (writeCreditFn != null) { tableSpecConfig.put(RemoteTableProvider.WRITE_CREDIT_FN, serializeObject( "write credit function", writeCreditFn)); } return new TableSpec(tableId, serde, RemoteTableProviderFactory.class.getName(), tableSpecConfig); }
Source:
<code><START> public String getRunningFlowIds() { <END> final List<Integer> allIds = new ArrayList<>(); try { getExecutionIdsHelper(allIds, this.executorLoader.fetchUnfinishedFlows().values()); } catch (final ExecutorManagerException e) { this.logger.error("Failed to get running flow ids.", e); } return allIds.toString(); }</code><technical_language>returning a string instead of a list</technical_language>

Target:
public List<Integer> getRunningFlowIds() { final List<Integer> allIds = new ArrayList<>(); try { getExecutionIdsHelper(allIds, this.executorLoader.fetchUnfinishedFlows().values()); } catch (final ExecutorManagerException e) { this.logger.error("Failed to get running flow ids.", e); } return allIds; }
Source:
<code>List<EventID> getGIIEvents() { List<EventID> events = new LinkedList<>(); for (long i = positionBeforeGII; i < positionAfterGII + 1; i++) { <START> Map.Entry entry = region.getEntry(i); <END> if (entry != null && entry.getValue() instanceof HAEventWrapper) { HAEventWrapper wrapper = uncheckedCast(entry.getValue()); events.add(wrapper.getEventId()); } } return events; }</code><technical_language>IDE warning this line removed making this Map.Entry<?, ?> entry</technical_language>

Target:
List<EventID> getGIIEvents() { List<EventID> events = new LinkedList<>(); for (long i = positionBeforeGII; i < positionAfterGII + 1; i++) { Map.Entry<?, ?> entry = region.getEntry(i); if (entry != null && entry.getValue() instanceof HAEventWrapper) { HAEventWrapper wrapper = (HAEventWrapper) entry.getValue(); events.add(wrapper.getEventId()); } } return events; }
Source:
<code>private void fetchGitHubRepository(final int repositoryId) { Log.d(TAG, "fetchGitHubRepository(" + repositoryId + ")"); if (isOngoingRequest(repositoryId)) { Log.d(TAG, "Found an ongoing request for repository " + repositoryId); return; } final String uri = getUniqueId(repositoryId); Disposable disposable = createNetworkObservable(repositoryId) .subscribeOn(Schedulers.computation()) <START> .doOnSubscribe(d -> startRequest(uri)) <END> .doOnError(doOnError(uri)) .doOnDispose(() -> completeRequest(uri)) .subscribe(gitHubRepositoryStore::put, e -> Log.e(TAG, "Error fetching GitHub repository " + repositoryId, e)); addRequest(repositoryId, disposable); }</code><technical_language>in repo is argument used, wildcard __ is instead of name. instead of d is</technical_language>

Target:
private void fetchGitHubRepository(final int repositoryId) { Log.d(TAG, "fetchGitHubRepository(" + repositoryId + ")"); if (isOngoingRequest(repositoryId)) { Log.d(TAG, "Found an ongoing request for repository " + repositoryId); return; } final String uri = getUniqueId(repositoryId); Disposable disposable = createNetworkObservable(repositoryId) .subscribeOn(Schedulers.computation()) .doOnSubscribe(__ -> startRequest(uri)) .doOnError(doOnError(uri)) .doOnDispose(() -> completeRequest(uri)) .subscribe(gitHubRepositoryStore::put, e -> Log.e(TAG, "Error fetching GitHub repository " + repositoryId, e)); addRequest(repositoryId, disposable); }
Source:
<code>private void cleanZombieTasks() { long maxTime = DateTime.getNow() .addMinutes(-1 * Config.<Integer>getValue(ConfigValues.AsyncTaskZombieTaskLifeInMinutes)).getTime(); for (SPMTask task : tasks.values()) { if (task.getParameters().getDbAsyncTask().getStartTime().getTime() < maxTime) { AuditLogable logable = new AuditLogableImpl(); logable.addCustomValue("CommandName", task.getParameters().getDbAsyncTask().getActionType().toString()); logable.addCustomValue("Date", task.getParameters().getDbAsyncTask().getStartTime().toString()); if (task.getLastTaskStatus().getStatus() != AsyncTaskStatusEnum.finished && task.getLastTaskStatus().getStatus() != AsyncTaskStatusEnum.unknown) { task.setZombieTask(true); auditLogDirector.log(logable, AuditLogType.TASK_STOPPING_ASYNC_TASK); log.info( "Cleaning zombie tasks: Stopping async task '{}' that started at '{}' since it reached a timeout of minutes", task.getParameters().getDbAsyncTask().getActionType(), task.getParameters().getDbAsyncTask().getStartTime(), <START> Config.<Integer> getValue(ConfigValues.AsyncTaskZombieTaskLifeInMinutes)); <END> task.stopTask(true); } else { auditLogDirector.log(logable, AuditLogType.TASK_CLEARING_ASYNC_TASK); log.info( "Cleaning zombie tasks: Clearing async task '{}' that started at '{}' since it reached a timeout of minutes", task.getParameters().getDbAsyncTask().getActionType(), task.getParameters().getDbAsyncTask().getStartTime(), Config.<Integer> getValue(ConfigValues.AsyncTaskZombieTaskLifeInMinutes)); task.clearAsyncTask(true); } } } }</code><technical_language>worth cache AsyncTaskZombieTaskLifeInMinutes is in a loop</technical_language>

Target:
private void cleanZombieTasks() { long maxTime = DateTime.getNow() .addMinutes(-1 * Config.<Integer>getValue(ConfigValues.AsyncTaskZombieTaskLifeInMinutes)).getTime(); int asyncZombieTaskLife = Config.<Integer> getValue(ConfigValues.AsyncTaskZombieTaskLifeInMinutes); for (SPMTask task : tasks.values()) { if (task.getParameters().getDbAsyncTask().getStartTime().getTime() < maxTime) { AuditLogable logable = new AuditLogableImpl(); logable.addCustomValue("CommandName", task.getParameters().getDbAsyncTask().getActionType().toString()); logable.addCustomValue("Date", task.getParameters().getDbAsyncTask().getStartTime().toString()); if (task.getLastTaskStatus().getStatus() != AsyncTaskStatusEnum.finished && task.getLastTaskStatus().getStatus() != AsyncTaskStatusEnum.unknown) { task.setZombieTask(true); auditLogDirector.log(logable, AuditLogType.TASK_STOPPING_ASYNC_TASK); log.info( "Cleaning zombie tasks: Stopping async task '{}' that started at '{}' since it reached a timeout of minutes", task.getParameters().getDbAsyncTask().getActionType(), task.getParameters().getDbAsyncTask().getStartTime(), asyncZombieTaskLife); task.stopTask(true); } else { auditLogDirector.log(logable, AuditLogType.TASK_CLEARING_ASYNC_TASK); log.info( "Cleaning zombie tasks: Clearing async task '{}' that started at '{}' since it reached a timeout of minutes", task.getParameters().getDbAsyncTask().getActionType(), task.getParameters().getDbAsyncTask().getStartTime(), asyncZombieTaskLife); task.clearAsyncTask(true); } } } }
Source:
<code>public ImmutableSet<ModelWithPayload<Item>> resolveItems(Iterable<ModelWithPayload<Item>> items) throws NitroException { ImmutableList.Builder<String> itemUris = ImmutableList.builder(); for (ModelWithPayload<Item> itemWithPayload : items) { itemUris.add(itemWithPayload.getModel().getCanonicalUri()); <START> } <END> ResolvedContent resolvedItems = resolve(itemUris.build()); ImmutableSet<Item> itemsOnly = ImmutableSet.copyOf(Iterables.filter( resolvedItems.getAllResolvedResults(), Item.class )); ImmutableSet<ModelWithPayload<Item>> wrappedItems = itemsOnly.stream() .map(input -> wrapResolvedContentWithEmptyPayload(input)) .collect(MoreCollectors.toImmutableSet()); return mergeItemsWithExisting(ImmutableSet.copyOf(items), wrappedItems); }</code><technical_language>ImmutableSet<String> itemUris = StreamSupport.stream(items.spliterator(), false) .map(Item::getCanonicalUri) .collect(MoreCollectors.toImmurableSet());</technical_language>

Target:
public ImmutableSet<ModelWithPayload<Item>> resolveItems(Iterable<ModelWithPayload<Item>> items) throws NitroException { ImmutableSet<String> itemUris = StreamSupport .stream(items.spliterator(), false) .map(ModelWithPayload::getModel) .map(Item::getCanonicalUri) .collect(MoreCollectors.toImmutableSet()); ResolvedContent resolvedItems = resolve(itemUris); ImmutableSet<ModelWithPayload<Item>> wrappedItems = resolvedItems.getAllResolvedResults().stream() .filter(Item.class::isInstance) .map(Item.class::cast) .map(this::wrapResolvedContentWithEmptyPayload) .collect(MoreCollectors.toImmutableSet()); return mergeItemsWithExisting(ImmutableSet.copyOf(items), wrappedItems); }
Source:
<code>public void updateEnrollSuccessLines(List<StudentAttributes>[] students) { for (int i = 1; i < StudentUpdateStatus.STATUS_COUNT - 2; i++) { switch (StudentUpdateStatus.enumRepresentation(i)) { case NEW: for (StudentAttributes newStudent : students[i]) { enrollNewStudentsLines.put(newStudent.email, "Student has been added successfully."); } break; <START> case MODIFIED: <END> for (StudentAttributes modifiedStudent : students[i]) { enrollModifiedStudentsLines.put(modifiedStudent.email, "Student has been modified successfully."); } break; case UNMODIFIED: for (StudentAttributes unmodifiedStudent : students[i]) { enrollUnmodifiedStudentsLines.put(unmodifiedStudent.email, "Existing student has been unmodified."); } break; default: log.severe("Unknown Enrollment status " + i); break; } } }</code><technical_language>I thought "enroll" means new students only? job of "edit" action</technical_language>

Target:
public void updateEnrollSuccessLines(List<StudentAttributes>[] students) { for (int i = 1; i < StudentUpdateStatus.STATUS_COUNT - 2; i++) { switch (StudentUpdateStatus.enumRepresentation(i)) { case NEW: for (StudentAttributes newStudent : students[i]) { enrollNewStudentsLines.put(newStudent.email, "Student has been added successfully."); } break; case MODIFIED: for (StudentAttributes modifiedStudent : students[i]) { enrollModifiedStudentsLines.put(modifiedStudent.email, "Student has been modified successfully."); } break; case UNMODIFIED: for (StudentAttributes unmodifiedStudent : students[i]) { enrollUnmodifiedStudentsLines.put(unmodifiedStudent.email, "Existing student is unmodified."); } break; default: log.severe("Unknown Enrollment status " + i); break; } } }
Source:
<code>public synchronized void onStart(SourceCallback<String, Object> sourceCallback) throws MuleException { checkArgument(heisenberg != null, "config not injected"); HeisenbergExtension.sourceTimesStarted++; configName = refName; location = componentLocation.getLocation(); if (corePoolSize < 0) { throw new RuntimeException(CORE_POOL_SIZE_ERROR_MESSAGE); } receivedDebtProperties = debtProperties; receivedUsableWeapons = usableWeapons; executor = schedulerService.cpuLightScheduler(); connection = connectionProvider.connect(); scheduledFuture = executor.scheduleAtFixedRate(() -> { final Result<String, Object> result = makeResult(sourceCallback); if (result != null) { SourceCallbackContext context = sourceCallback.createContext(); context.addVariable(BATCH_NUMBER, initialBatchNumber); context.fireOnHandle(NEW_BATCH, TypedValue.of(initialBatchNumber)); context.fireOnHandle(NEXT_BATCH, TypedValue.of(frequency)); sourceCallback.handle(result, context); } <START> }, 0, 4000, MILLISECONDS); <END> }</code><technical_language>frequency config. need change frequency for a single test, change in test xml. If need generic, update default</technical_language>

Target:
public synchronized void onStart(SourceCallback<String, Object> sourceCallback) throws MuleException { checkArgument(heisenberg != null, "config not injected"); HeisenbergExtension.sourceTimesStarted++; configName = refName; location = componentLocation.getLocation(); if (corePoolSize < 0) { throw new RuntimeException(CORE_POOL_SIZE_ERROR_MESSAGE); } receivedDebtProperties = debtProperties; receivedUsableWeapons = usableWeapons; executor = schedulerService.cpuLightScheduler(); connection = connectionProvider.connect(); scheduledFuture = executor.scheduleAtFixedRate(() -> { final Result<String, Object> result = makeResult(sourceCallback); if (result != null) { SourceCallbackContext context = sourceCallback.createContext(); context.addVariable(BATCH_NUMBER, initialBatchNumber); context.fireOnHandle(NEW_BATCH, TypedValue.of(initialBatchNumber)); context.fireOnHandle(NEXT_BATCH, TypedValue.of(frequency)); sourceCallback.handle(result, context); } }, 0, frequency, MILLISECONDS); }
Source:
<code>public Option[] uberJar() { return options( <START> gradleBundle("org.ehcache:dist"), jaxbConfiguration(), <END> gradleBundle("org.ehcache:clustered-dist"), jaxbConfiguration(), baseConfiguration("ClusteredOsgiTest", "uberJar") ); }</code><technical_language>Again... need duplicate jaxbConfiguration()</technical_language>

Target:
public Option[] uberJar() { return options( gradleBundle("org.ehcache:dist"), jaxbConfiguration(), gradleBundle("org.ehcache:clustered-dist"), baseConfiguration("ClusteredOsgiTest", "uberJar") ); }
Source:
<code>static BalancerSegmentHolder getRandomBalancerSegmentHolder(final List<ServerHolder> serverHolders) { ServerHolder fromServerHolder = getRandomElementFromList(serverHolders); Collection<DataSegment> segments = fromServerHolder.getServer().getSegments(); Spliterator<DataSegment> chosenSpliterator = segments.spliterator(); DataSegment proposalSegment = null; for (int i = 0; i < Math.log(segments.size()); i++) { if (chosenSpliterator.estimateSize() < SPLITERATOR_SIZE_THRESHOLD) { <START> List<DataSegment> finalList = StreamSupport <END> .stream(chosenSpliterator, false) .collect(Collectors.toList()); proposalSegment = getRandomElementFromList(finalList); break; } Spliterator<DataSegment> newSpliterator = chosenSpliterator.trySplit(); if (ThreadLocalRandom.current().nextBoolean()) { chosenSpliterator = newSpliterator; } } if (fromServerHolder != null) { return new BalancerSegmentHolder(fromServerHolder.getServer(), proposalSegment); } else { return null; } }</code><technical_language>checked if spliterator is SIZED pick a specific element if so</technical_language>

Target:
static BalancerSegmentHolder getRandomBalancerSegmentHolder(final List<ServerHolder> serverHolders) { ServerHolder fromServerHolder = reservoirSampleServer(serverHolders); if (fromServerHolder == null) { return null; } DataSegment proposalSegment; Collection<DataSegment> segments = fromServerHolder.getServer().getSegments(); if (segments.size() == 1) { proposalSegment = segments.iterator().next(); } else { Spliterator<DataSegment> chosenSpliterator = segments.spliterator(); if (chosenSpliterator == null) { return null; } int randomBits = ThreadLocalRandom.current().nextInt(); while (chosenSpliterator.estimateSize() >= SPLITERATOR_SIZE_THRESHOLD) { Spliterator<DataSegment> newSpliterator = chosenSpliterator.trySplit(); boolean chooseNewSpliterator = ((randomBits >>= 1) & 1) == 0; if (chooseNewSpliterator) { chosenSpliterator = newSpliterator; } } List<DataSegment> finalList = StreamSupport .stream(chosenSpliterator, false) .collect(Collectors.toList()); proposalSegment = getRandomElementFromList(finalList); } return new BalancerSegmentHolder(fromServerHolder.getServer(), proposalSegment); }
Source:
<code>public short calculateBreakDamage(GlowBlock target) { <START> return (short) (target.getType().equals(Material.LEAVES) ? 1 : 0); <END> }</code><technical_language>shears loose durability other blocks well</technical_language>

Target:
public short calculateBreakDamage(GlowBlock target) { return (short) (Arrays.asList(new Material[]{Material.LEAVES, Material.LONG_GRASS, Material.WOOL}).contains(target.getType()) ? 1 : 0); }
Source:
<code>public void test_definition() { WebService.Action def = wsTester.getDef(); assertThat(def.key()).isEqualTo("search"); assertThat(def.isInternal()).isFalse(); assertThat(def.isPost()).isFalse(); assertThat(def.since()).isEqualTo("3.6"); assertThat(def.responseExampleAsString()).isNotEmpty(); <START> assertThat(def.params()).extracting("key").containsOnly( <END> "actionPlans", "additionalFields", "asc", "assigned", "assignees", "authors", "componentKeys", "componentRootUuids", "componentRoots", "componentUuids", "components", "createdAfter", "createdAt", "createdBefore", "createdInLast", "directories", "facetMode", "facets", "fileUuids", "issues", "languages", "moduleUuids", "onComponentOnly", "organization", "p", "planned", "projectKeys", "projectUuids", "projects", "ps", "reporters", "resolutions", "resolved", "rules", "s", "severities", "sinceLeakPeriod", "statuses", "tags", "types"); assertThat(def.param("organization")) .matches(p -> p.isInternal()) .matches(p -> p.since().equals("6.4")); }</code><technical_language>I prefer containsExactlyInAnyOrder containsOnly, duplicate items unexpected</technical_language>

Target:
public void test_definition() { WebService.Action def = wsTester.getDef(); assertThat(def.key()).isEqualTo("search"); assertThat(def.isInternal()).isFalse(); assertThat(def.isPost()).isFalse(); assertThat(def.since()).isEqualTo("3.6"); assertThat(def.responseExampleAsString()).isNotEmpty(); assertThat(def.params()).extracting("key").containsExactlyInAnyOrder( "actionPlans", "additionalFields", "asc", "assigned", "assignees", "authors", "componentKeys", "componentRootUuids", "componentRoots", "componentUuids", "components", "createdAfter", "createdAt", "createdBefore", "createdInLast", "directories", "facetMode", "facets", "fileUuids", "issues", "languages", "moduleUuids", "onComponentOnly", "organization", "p", "planned", "projectKeys", "projectUuids", "projects", "ps", "reporters", "resolutions", "resolved", "rules", "s", "severities", "sinceLeakPeriod", "statuses", "tags", "types"); assertThat(def.param("organization")) .matches(p -> p.isInternal()) .matches(p -> p.since().equals("6.4")); }
Source:
<code>private void sendResetRequestAndWait(Map<TopicPartition, Long> outOfRangePartitions, TaskToolbox taskToolbox) throws IOException { Map<Integer, Long> partitionOffsetMap = Maps.newHashMap(); for (Map.Entry<TopicPartition, Long> outOfRangePartition : outOfRangePartitions.entrySet()) { partitionOffsetMap.put(outOfRangePartition.getKey().partition(), outOfRangePartition.getValue()); } boolean result = taskToolbox.getTaskActionClient() .submit(new ResetDataSourceMetadataAction( getDataSource(), new KafkaDataSourceMetadata(new KafkaPartitions( ioConfig.getStartPartitions() .getTopic(), partitionOffsetMap )) )); if (result) { log.makeAlert( <START> "Successfully sent the reset request for partitions [%s], waiting to be killed", <END> partitionOffsetMap.keySet() ).emit(); try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException e) { throw new RuntimeException("Got interrupted while waiting to be killed"); } } else { log.makeAlert("Failed to send reset request for partitions [%s]", partitionOffsetMap.keySet()).emit(); } }</code><technical_language>sites text of alert message group alerts. this is alert message change text "Kafka offsets reset for dataSource[%s]" similar partitions added info addData</technical_language>

Target:
private void sendResetRequestAndWait(Map<TopicPartition, Long> outOfRangePartitions, TaskToolbox taskToolbox) throws IOException { Map<Integer, Long> partitionOffsetMap = Maps.newHashMap(); for (Map.Entry<TopicPartition, Long> outOfRangePartition : outOfRangePartitions.entrySet()) { partitionOffsetMap.put(outOfRangePartition.getKey().partition(), outOfRangePartition.getValue()); } boolean result = taskToolbox.getTaskActionClient() .submit(new ResetDataSourceMetadataAction( getDataSource(), new KafkaDataSourceMetadata(new KafkaPartitions( ioConfig.getStartPartitions() .getTopic(), partitionOffsetMap )) )); if (result) { log.makeAlert("Resetting Kafka offsets for datasource [%s]", getDataSource()) .addData("partitions", partitionOffsetMap.keySet()) .emit(); try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException e) { throw new RuntimeException("Got interrupted while waiting to be killed"); } } else { log.makeAlert("Failed to send reset request for partitions [%s]", partitionOffsetMap.keySet()).emit(); } }
Source:
<code>public Response create( final WhoisResources resources, @Context final HttpServletRequest request, @PathParam("source") final String sourceParam, @QueryParam("password") final List<String> passwords, @CookieParam("crowd.token_key") final String crowdTokenKey) { if (resources == null) { return badRequest("WhoisResources is mandatory"); } try { final Origin origin = updatePerformer.createOrigin(request); final UpdateContext updateContext = updatePerformer.initContext(origin, crowdTokenKey); updateContext.setBatchUpdate(); <START> <END> final Credentials credentials = createCredentials(updateContext.getUserSession(), passwords, null); final List<Update> updates = extractUpdates(resources, credentials); final WhoisResources updatedResources = updatePerformer.performUpdates(updateContext, origin, updates, Keyword.NEW, request); validateUpdates(updateContext, updates, updatedResources); return createResponse(request, updatedResources, Response.Status.OK); } catch (WebApplicationException e) { throw specializeWebApplicationException(e, request, resources); } catch (UpdateFailedException e) { return createResponse(request, e.whoisResources, e.status); } catch (Exception e) { updatePerformer.logError(e); LOGGER.error("Unexpected", e); return createResponse(request, resources, Response.Status.INTERNAL_SERVER_ERROR); } finally { updatePerformer.closeContext(); } }</code><technical_language>auditlogRequest() call - this handy for debugging</technical_language>

Target:
public Response create( final WhoisResources resources, @Context final HttpServletRequest request, @PathParam("source") final String sourceParam, @QueryParam("password") final List<String> passwords, @CookieParam("crowd.token_key") final String crowdTokenKey) { if (resources == null || resources.getWhoisObjects().size() == 0) { return badRequest("WhoisResources is mandatory"); } try { final Origin origin = updatePerformer.createOrigin(request); final UpdateContext updateContext = updatePerformer.initContext(origin, crowdTokenKey); updateContext.setBatchUpdate(); final Credentials credentials = createCredentials(updateContext.getUserSession(), passwords); final List<Update> updates = extractUpdates(resources, credentials); final WhoisResources updatedResources = updatePerformer.performUpdates(updateContext, origin, updates, Keyword.NEW, request); validateUpdates(updateContext, updates, updatedResources); return createResponse(request, updatedResources, Response.Status.OK); } catch (WebApplicationException e) { throw specializeWebApplicationException(e, request, resources); } catch (UpdateFailedException e) { return createResponse(request, e.whoisResources, e.status); } catch (Exception e) { updatePerformer.logError(e); LOGGER.error("Unexpected", e); return createResponse(request, resources, Response.Status.INTERNAL_SERVER_ERROR); } finally { updatePerformer.closeContext(); } }
Source:
<code>private boolean advanceLeft(TSource left, TKey leftKey) { lefts.clear(); lefts.add(left); while (getLeftEnumerator().moveNext()) { left = getLeftEnumerator().current(); TKey leftKey2 = outerKeySelector.apply(left); if (leftKey2 == null) { if (joinType != JoinType.LEFT) { <START> break; <END> } } int c = compare(leftKey, leftKey2); if (c != 0) { if (c > 0) { throw new IllegalStateException( "mergeJoin assumes inputs sorted in ascending order, " + "however '" + leftKey + "' is greater than '" + leftKey2 + "'"); } return true; } lefts.add(left); } return false; }</code><technical_language>merge if conditions</technical_language>

Target:
private boolean advanceLeft(TSource left, TKey leftKey) { lefts.clear(); lefts.add(left); while (getLeftEnumerator().moveNext()) { left = getLeftEnumerator().current(); TKey leftKey2 = outerKeySelector.apply(left); if (leftKey2 == null && joinType != JoinType.LEFT) { break; } int c = compare(leftKey, leftKey2); if (c != 0) { if (c > 0) { throw new IllegalStateException( "mergeJoin assumes inputs sorted in ascending order, " + "however '" + leftKey + "' is greater than '" + leftKey2 + "'"); } return true; } lefts.add(left); } return false; }
Source:
<code>public Metadata getMetadata() { <START> return document.getMetadata(); <END> }</code><technical_language>this</technical_language>

Target:
public Metadata getMetadata() { return this.document.getMetadata(); }
Source:
<code>public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) { Jenkins j = Jenkins.getInstanceOrNull(); <START> if (j != null && j.isDisableRememberMe()) { <END> cancelCookie(request, response, null); return null; } else { try { String rememberMeValue = findRememberMeCookieValue(request, response); if (rememberMeValue == null) { return null; } return retrieveAuthFromCookie(request, response, rememberMeValue); } catch (Exception e) { cancelCookie(request, response, "Failed to handle remember-me cookie: " + Functions.printThrowable(e)); return null; } } }</code><technical_language>doubtful Jenkins singleton, enough working in retrieveAuthFromCookie ultimately successful (User#getById?). return null jenkins == null, return</technical_language>

Target:
public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) { Jenkins j = Jenkins.getInstanceOrNull(); if (j == null) { return null; } if (j.isDisableRememberMe()) { cancelCookie(request, response, null); return null; } else { try { String rememberMeValue = findRememberMeCookieValue(request, response); if (rememberMeValue == null) { return null; } return retrieveAuthFromCookie(request, response, rememberMeValue); } catch (Exception e) { cancelCookie(request, response, "Failed to handle remember-me cookie: " + Functions.printThrowable(e)); return null; } } }
Source:
<code>public long getExternalStorageAvailableSpaceInMb() { if (!isExternalStorageMounted()) { Timber.e("External storage is not mounted"); return 0L; } StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath()); double sdAvailSize = getAvailableSpace(stat); <START> return (long) Math.floor(sdAvailSize / 1048576.0); <END> }</code><technical_language>a number i.e. 1048... a descriptive constant</technical_language>

Target:
public long getExternalStorageAvailableSpaceInMb() { if (!isExternalStorageMounted()) { Timber.e("External storage is not mounted"); return 0L; } StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath()); double sdAvailSize = getAvailableSpace(stat); return (long) Math.floor(sdAvailSize / ONE_MEBIBIT); }
Source:
<code>public Response update(Attribute entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); <START> Context.getPermissionsManager().checkPermission("attribute", getUserId(), entity.getId()); <END> Context.getAttributesManager().updateItem(entity); return Response.ok(entity).build(); }</code><technical_language>I sense some constant for type names</technical_language>

Target:
public Response update(Attribute entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkPermission(Attribute.class, getUserId(), entity.getId()); Context.getAttributesManager().updateItem(entity); return Response.ok(entity).build(); }