auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void addServerOfflineWatcher() { Runnable serverOfflineWatcher = new Runnable() { @Override public void run() { long units = 10l; TimeUnit unit = TimeUnit.MINUTES; try { while (true) { HostState state = getStateSafe(); if (state == null || HostState.OFFLINE.equals(state)) { startShutDownCountdown(units, unit); } unit.sleep(units); } }catch (Exception e){ LOG.error("Watcher thread encountered an error - thread will stop for safety", e); } } public HostState getStateSafe() { HostState state; try { state = host.getState(); } catch (IOException e) { LOG.error("Offline watcher failed to get state, counting as OFFLINE. Exception: ", e); state = HostState.OFFLINE; } return state; } private void startShutDownCountdown(long units, TimeUnit unit) { try { unit.sleep(units); HostState state = getStateSafe(); if (state == null || HostState.OFFLINE.equals(state)) { LOG.info("Partition Server was OFFLINE for " + units + " " + unit.toString()); stopSynchronized(); } } catch (InterruptedException e) { LOG.error("Interrupted while performing shutdown countdown", e); } } }; <START> offlineWatcherThread = new Thread(serverOfflineWatcher, "Server Offline Watcher"); <END> offlineWatcherThread.start(); }</code><technical_language>hold this thread in class stop() terminates this thread hang</technical_language>

Target:
private void addServerOfflineWatcher() { Runnable serverOfflineWatcher = new Runnable() { @Override public void run() { long units = 10l; TimeUnit unit = TimeUnit.MINUTES; try { while (true) { HostState state = getStateSafe(); if (state == null || HostState.OFFLINE.equals(state)) { startShutDownCountdown(units, unit); } unit.sleep(units); } }catch (Exception e){ LOG.error("Watcher thread encountered an error - thread will stop for safety", e); } } public HostState getStateSafe() { HostState state; try { state = host.getState(); } catch (IOException e) { LOG.error("Offline watcher failed to get state, counting as OFFLINE. Exception: ", e); state = HostState.OFFLINE; } return state; } private void startShutDownCountdown(long units, TimeUnit unit) { try { unit.sleep(units); HostState state = getStateSafe(); if (state == null || HostState.OFFLINE.equals(state)) { LOG.info("Partition Server was OFFLINE for " + units + " " + unit.toString()); LOG.error("Would have shutdown"); } } catch (InterruptedException e) { LOG.error("Interrupted while performing shutdown countdown", e); } } }; offlineWatcherThread = new Thread(serverOfflineWatcher, "Server Offline Watcher"); offlineWatcherThread.setDaemon(true); offlineWatcherThread.start(); }
Source:
<code>private long doForceInsertNewDocumentWithHistory(BasicDocumentRevision rev, List<String> revHistory) { <START> logger.entering(this.getClass().getCanonicalName(), <END> "doForceInsertNewDocumentWithHistory()", new Object[]{rev, revHistory}); assert !this.containsDocument(rev.getId()); long docNumericID = insertDocumentID(rev.getId()); long parentSequence = 0L; for (int i = 0; i < revHistory.size() - 1; i++) { parentSequence = insertStubRevision(docNumericID, revHistory.get(i), parentSequence); } InsertRevisionOptions options = new InsertRevisionOptions(); options.docNumericId = docNumericID; options.revId = revHistory.get(revHistory.size() - 1); options.parentSequence = parentSequence; options.deleted = rev.isDeleted(); options.current = true; options.data = rev.getBody().asBytes(); options.available = true; options.copyAttachments = false; long sequence = insertRevision(options); return sequence; }</code><technical_language>of this.getClass().getName</technical_language>

Target:
private long doForceInsertNewDocumentWithHistory(BasicDocumentRevision rev, List<String> revHistory) { logger.entering("BasicDocumentRevision", "doForceInsertNewDocumentWithHistory()", new Object[]{rev, revHistory}); assert !this.containsDocument(rev.getId()); long docNumericID = insertDocumentID(rev.getId()); long parentSequence = 0L; for (int i = 0; i < revHistory.size() - 1; i++) { parentSequence = insertStubRevision(docNumericID, revHistory.get(i), parentSequence); } InsertRevisionOptions options = new InsertRevisionOptions(); options.docNumericId = docNumericID; options.revId = revHistory.get(revHistory.size() - 1); options.parentSequence = parentSequence; options.deleted = rev.isDeleted(); options.current = true; options.data = rev.getBody().asBytes(); options.available = true; options.copyAttachments = false; long sequence = insertRevision(options); return sequence; }
Source:
<code>protected Configuration createConfiguration() { <START> Configuration conf = super.createConfiguration(); <END> maybeEnableS3Guard(conf); try { URI bucketURI = new URI(checkNotNull(conf.get("fs.contract.test.fs.s3a"))); S3ATestUtils.removeBucketOverrides(bucketURI.getHost(), conf, READAHEAD_RANGE, INPUT_FADVISE); } catch (URISyntaxException e) { throw new RuntimeException(e); } S3ATestUtils.disableFilesystemCaching(conf); conf.setInt(READAHEAD_RANGE, READAHEAD); conf.set(INPUT_FADVISE, seekPolicy); conf.set(INPUT_FADVISE, seekPolicy); return conf; }</code><technical_language>parameterized test settings ... what? nit: readahead readhead</technical_language>

Target:
protected Configuration createConfiguration() { Configuration conf = super.createConfiguration(); maybeEnableS3Guard(conf); try { URI bucketURI = new URI(checkNotNull(conf.get("fs.contract.test.fs.s3a"))); S3ATestUtils.removeBucketOverrides(bucketURI.getHost(), conf, READAHEAD_RANGE, INPUT_FADVISE); } catch (URISyntaxException e) { throw new RuntimeException(e); } S3ATestUtils.disableFilesystemCaching(conf); conf.setInt(READAHEAD_RANGE, READAHEAD); conf.set(INPUT_FADVISE, seekPolicy); return conf; }
Source:
<code>private static ChunkerModel trainModel(ModelType type, ChunkerFactory factory) throws IOException { TrainingParameters params = TrainingParameters.defaultParams(); <START> params.put("PrintMessages", false); <END> return ChunkerME.train("eng", createSampleStream(), params, factory); }</code><technical_language>is a VERBOSE_PARAM in AbstractTrainer "PrintMessages"</technical_language>

Target:
private static ChunkerModel trainModel(ModelType type, ChunkerFactory factory) throws IOException { TrainingParameters params = TrainingParameters.defaultParams(); params.put(AbstractTrainer.VERBOSE_PARAM, false); return ChunkerME.train("eng", createSampleStream(), params, factory); }
Source:
<code>public static synchronized boolean sendSPAppsQueryFeedsIntent(@Nullable Context context) { <START> assert context != null : "context = null"; <END> final Context appContext = context.getApplicationContext(); if (appContext == null) { Log.wtf(TAG, "Unable to get application context"); return false; } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext); if (!prefs.getBoolean(PREF_HAS_QUERIED_SP_APPS, false)) { appContext.sendBroadcast(new Intent(SPAReceiver.ACTION_SP_APPS_QUERY_FEEDS)); if (BuildConfig.DEBUG) Log.d(TAG, "Sending SP_APPS_QUERY_FEEDS intent"); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean(PREF_HAS_QUERIED_SP_APPS, true); editor.commit(); return true; } else { return false; } }</code><technical_language>this change behavior? assertions checked runtime</technical_language>

Target:
public static synchronized boolean sendSPAppsQueryFeedsIntent(@Nullable Context context) { if (context == null) throw new IllegalArgumentException("context = null"); final Context appContext = context.getApplicationContext(); if (appContext == null) { Log.wtf(TAG, "Unable to get application context"); return false; } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext); if (!prefs.getBoolean(PREF_HAS_QUERIED_SP_APPS, false)) { appContext.sendBroadcast(new Intent(SPAReceiver.ACTION_SP_APPS_QUERY_FEEDS)); if (BuildConfig.DEBUG) Log.d(TAG, "Sending SP_APPS_QUERY_FEEDS intent"); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean(PREF_HAS_QUERIED_SP_APPS, true); editor.commit(); return true; } else { return false; } }
Source:
<code>static void populateConfigFromManifest(@NonNull Configuration config, @NonNull Bundle data) { config.setBuildUUID(data.getString(MF_BUILD_UUID)); config.setAppVersion(data.getString(MF_APP_VERSION)); config.setReleaseStage(data.getString(MF_RELEASE_STAGE)); if (data.containsKey(MF_ENDPOINT)) { String endpoint = data.getString(MF_ENDPOINT); String sessionEndpoint = data.getString(MF_SESSIONS_ENDPOINT); config.setEndpoints(endpoint, sessionEndpoint); } config.setSendThreads(data.getBoolean(MF_SEND_THREADS, true)); config.setPersistUserBetweenSessions( data.getBoolean(MF_PERSIST_USER_BETWEEN_SESSIONS, false)); config.setDetectNdkCrashes(data.getBoolean(MF_DETECT_NDK_CRASHES, false)); <START> config.setDetectAnrs(data.getBoolean(MF_DETECT_ANRS, false)); <END> if (data.containsKey(MF_AUTO_CAPTURE_SESSIONS)) { config.setAutoCaptureSessions(data.getBoolean(MF_AUTO_CAPTURE_SESSIONS)); } config.setEnableExceptionHandler( data.getBoolean(MF_ENABLE_EXCEPTION_HANDLER, true)); }</code><technical_language>set field key is present in manifest, alter code in places default behaviour for detectNdkCrashes changes true</technical_language>

Target:
static void populateConfigFromManifest(@NonNull Configuration config, @NonNull Bundle data) { config.setBuildUUID(data.getString(MF_BUILD_UUID)); config.setAppVersion(data.getString(MF_APP_VERSION)); config.setReleaseStage(data.getString(MF_RELEASE_STAGE)); if (data.containsKey(MF_ENDPOINT)) { String endpoint = data.getString(MF_ENDPOINT); String sessionEndpoint = data.getString(MF_SESSIONS_ENDPOINT); config.setEndpoints(endpoint, sessionEndpoint); } config.setSendThreads(data.getBoolean(MF_SEND_THREADS, true)); config.setPersistUserBetweenSessions( data.getBoolean(MF_PERSIST_USER_BETWEEN_SESSIONS, false)); if (data.containsKey(MF_DETECT_NDK_CRASHES)) { config.setDetectNdkCrashes(data.getBoolean(MF_DETECT_NDK_CRASHES)); } if (data.containsKey(MF_DETECT_ANRS)) { config.setDetectAnrs(data.getBoolean(MF_DETECT_ANRS)); } if (data.containsKey(MF_AUTO_CAPTURE_SESSIONS)) { config.setAutoCaptureSessions(data.getBoolean(MF_AUTO_CAPTURE_SESSIONS)); } config.setEnableExceptionHandler( data.getBoolean(MF_ENABLE_EXCEPTION_HANDLER, true)); }
Source:
<code>private void validateEntrypointSelector(Component component, List<HasMetadata> filteredObjects) throws DevfileException { if (component.getEntrypoints() == null || component.getEntrypoints().isEmpty()) { return; } for (Entrypoint ep : component.getEntrypoints()) { ContainerSearch search = new ContainerSearch(ep.getParentName(), ep.getParentSelector(), ep.getContainerName()); List<Container> cs = search.search(filteredObjects); if (cs.isEmpty()) { throw new DevfileFormatException( format( "Component '%s' of type '%s' contains an entry point that doesn't match any" + " container:\n%s", <START> getIdentifiableComponentName(component), component.getType(), toYAML(ep))); <END> } } }</code><technical_language>convinced putting yaml in exception message is a good idea</technical_language>

Target:
private void validateEntrypointSelector(Component component, List<HasMetadata> filteredObjects) throws DevfileException { if (component.getEntrypoints() == null || component.getEntrypoints().isEmpty()) { return; } for (Entrypoint ep : component.getEntrypoints()) { ContainerSearch search = new ContainerSearch(ep.getParentName(), ep.getParentSelector(), ep.getContainerName()); List<Container> cs = search.search(filteredObjects); if (cs.isEmpty()) { throw new DevfileFormatException( format( "Component '%s' of type '%s' contains an entry point that doesn't match any" + " container.", getIdentifiableComponentName(component), component.getType())); } } }
Source:
<code>public static <T> Constructor<T> findConstructor(@Nonnull final Class<T> klass, @Nonnull final Class<?>... parameterTypes) { Preconditions.checkNotNull(klass, "class"); Preconditions.checkNotNull(parameterTypes, "parameter types"); final Constructor<T> constructor; try { constructor = klass.getDeclaredConstructor(parameterTypes); constructor.setAccessible(true); } catch (final NoSuchMethodException e) { final StringBuilder desc = new StringBuilder(); desc.append(klass.getSimpleName()).append('('); for (int i = 0, length = parameterTypes.length; i < length; i++) { desc.append(parameterTypes[i].getName()); <START> if (i < length - 1) <END> { desc.append(',').append(' '); } } desc.append(')'); throw new UnknownConstructorException("Could not find constructor '" + desc.toString() + "' in " + klass); } return constructor; }</code><technical_language>I avoid indexes, this way: java List<String> parameterNames = Stream.of(parameterTypes).map(Class::getName).collect(Collectors.toList()); desc.append(Joiner.on(", ").join(parameterNames));</technical_language>

Target:
public static <T> Constructor<T> findConstructor(@Nonnull final Class<T> klass, @Nonnull final Class<?>... parameterTypes) { Preconditions.checkNotNull(klass, "class"); Preconditions.checkNotNull(parameterTypes, "parameter types"); try { Constructor<T> constructor = klass.getDeclaredConstructor(parameterTypes); constructor.setAccessible(true); return constructor; } catch (final NoSuchMethodException e) { final StringBuilder desc = new StringBuilder(); desc.append(klass.getSimpleName()); StringJoiner joiner = new StringJoiner(", ", "(", ")"); for (Class<?> type : parameterTypes) { joiner.add(type.getSimpleName()); } desc.append(joiner); throw new UnknownConstructorException("Could not find constructor '" + desc.toString() + "' in " + klass); } }
Source:
<code>public ActivationKeyDTO createActivationKey(@PathParam("owner_key") @Verify(Owner.class) String ownerKey, @ApiParam(name = "activation_key", required = true) ActivationKeyDTO dto) { Owner owner = findOwner(ownerKey); OwnerDTO ownerDTO = translator.translate(owner, OwnerDTO.class); dto.setOwner(ownerDTO); ActivationKey key = new ActivationKey(); this.populateEntity(key, dto); <START> if (StringUtils.isBlank(key.getName())) { <END> throw new BadRequestException(i18n.tr("Must provide a name for activation key.")); } String testName = key.getName().replace("-", "0").replace("_", "0"); if (!testName.matches("[a-zA-Z0-9]*")) { throw new BadRequestException( i18n.tr("The activation key name ''{0}'' must be alphanumeric or " + "include the characters ''-'' or ''_''", key.getName())); } if (activationKeyCurator.lookupForOwner(key.getName(), owner) != null) { throw new BadRequestException( i18n.tr("The activation key name ''{0}'' is already in use for owner {1}", key.getName(), ownerKey)); } if (key.getContentOverrides() != null) { contentOverrideValidator.validate(key.getContentOverrides()); } serviceLevelValidator.validate(owner, key.getServiceLevel()); ActivationKey newKey = activationKeyCurator.create(key); sink.emitActivationKeyCreated(newKey); return translator.translate(newKey, ActivationKeyDTO.class); }</code><technical_language>performing input validation creating model objects, populating data</technical_language>

Target:
public ActivationKeyDTO createActivationKey(@PathParam("owner_key") @Verify(Owner.class) String ownerKey, @ApiParam(name = "activation_key", required = true) ActivationKeyDTO dto) { Owner owner = findOwner(ownerKey); if (StringUtils.isBlank(dto.getName())) { throw new BadRequestException(i18n.tr("Must provide a name for activation key.")); } String testName = dto.getName().replace("-", "0").replace("_", "0"); if (!testName.matches("[a-zA-Z0-9]*")) { throw new BadRequestException( i18n.tr("The activation key name ''{0}'' must be alphanumeric or " + "include the characters ''-'' or ''_''", dto.getName())); } if (activationKeyCurator.lookupForOwner(dto.getName(), owner) != null) { throw new BadRequestException( i18n.tr("The activation key name ''{0}'' is already in use for owner {1}", dto.getName(), ownerKey)); } serviceLevelValidator.validate(owner, dto.getServiceLevel()); OwnerDTO ownerDTO = translator.translate(owner, OwnerDTO.class); dto.setOwner(ownerDTO); ActivationKey key = new ActivationKey(); this.populateEntity(key, dto); if (key.getContentOverrides() != null) { contentOverrideValidator.validate(key.getContentOverrides()); } ActivationKey newKey = activationKeyCurator.create(key); sink.emitActivationKeyCreated(newKey); return translator.translate(newKey, ActivationKeyDTO.class); }
Source:
<code>public void checkDecisionServerContainer() throws Exception { log.info("Running test checkDecisionServerContainer"); prepareClientInvocation(); getKieRestServiceClient(getRouteURL()).listContainers().getResult().getContainers().stream().forEach(container -> { <START> String containerAliasToID = new SumCoder.MD5().encode(container.getResolvedReleaseId().getArtifactId() + "=" + container.getReleaseId()); <END> if (!containerAliasToID.equals(container.getContainerId())){ containerAliasToID = new SumCoder.MD5().encode("AnotherContainer=" + container.getReleaseId()); } Assert.assertTrue(container.getContainerId().equals(containerAliasToID)); Assert.assertEquals(org.kie.server.api.model.KieContainerStatus.STARTED, container.getStatus()); }); }</code><technical_language>I exclusive features Java 8, lambdas. refactor this statement lambdas</technical_language>

Target:
public void checkDecisionServerContainer() throws MalformedURLException { log.info("Running test checkDecisionServerContainer"); prepareClientInvocation(); for (KieContainerResource container : getKieRestServiceClient(getRouteURL()).listContainers().getResult().getContainers()) { String containerAliasToID = new SumCoder.MD5().encode(container.getResolvedReleaseId().getArtifactId() + "=" + container.getReleaseId()); if (!containerAliasToID.equals(container.getContainerId())) { containerAliasToID = new SumCoder.MD5().encode("AnotherContainer=" + container.getReleaseId()); } Assert.assertTrue(container.getContainerId().equals(containerAliasToID)); Assert.assertEquals(org.kie.server.api.model.KieContainerStatus.STARTED, container.getStatus()); } }
Source:
<code>public boolean sendCommand(final Command command) { <START> if (ACTIVE_MQ_SERVER_LOGGER_TRACE_ENABLED) { <END> traceSendCommand(command); } if (isDestroyed()) { return false; } try { physicalSend(command); } catch (Exception e) { return false; } catch (Throwable t) { return false; } return true; }</code><technical_language>this needed? a code consistency POV, this is odd out, follow in code not. (p.s. id prefer was, personal pref, guard statement is understandable, job)</technical_language>

Target:
public boolean sendCommand(final Command command) { if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("sending " + command); } if (isDestroyed()) { return false; } try { physicalSend(command); } catch (Exception e) { return false; } catch (Throwable t) { return false; } return true; }
Source:
<code>default void inputDetail() { or(mandatory(cluster().id()), mandatory(cluster().name())); <START> optional(configuration()); <END> }</code><technical_language>This "registrationConfiguration", name below, fail compile</technical_language>

Target:
default void inputDetail() { or(mandatory(cluster().id()), mandatory(cluster().name())); optional(clone()); optional(exclusive()); optional(vm().name()); or(optional(storageDomain().id()), optional(storageDomain().name())); optional(vm().diskAttachments()[COLLECTION].disk().format()); optional(vm().diskAttachments()[COLLECTION].id()); optional(vm().diskAttachments()[COLLECTION].disk().sparse()); }
Source:
<code>Subject cacheAndReturnSubject(ServerSession session) throws SecurityServiceException { UPAuthenticationToken usernamePasswordToken = new UPAuthenticationToken(session.getUsername(), session.getPassword()); <START> return AccessController.doPrivileged( <END> (ThrowingFunction) () -> securityManager.getSubject(usernamePasswordToken)); }</code><technical_language>I recommend this approach instead: java @VisibleForTesting Subject cacheAndReturnSubject(ServerSession session) throws SecurityServiceException { UPAuthenticationToken usernamePasswordToken = new UPAuthenticationToken(session.getUsername(), session.getPassword()); try { return AccessController.doPrivileged( (PrivilegedExceptionAction<Subject>) () -> securityManager.getSubject(usernamePasswordToken)); } catch (PrivilegedActionException e) { if (e.getCause() instanceof SecurityServiceException) { throw (SecurityServiceException) e.getCause(); } throw new SecurityServiceException(e.getCause()); } }</technical_language>

Target:
Subject cacheAndReturnSubject(ServerSession session) throws SecurityServiceException { UPAuthenticationToken usernamePasswordToken = new UPAuthenticationToken(session.getUsername(), session.getPassword()); try { return AccessController.doPrivileged( (PrivilegedExceptionAction<Subject>) () -> securityManager.getSubject(usernamePasswordToken)); } catch (PrivilegedActionException e) { if (e.getCause() instanceof SecurityServiceException) { throw (SecurityServiceException) e.getCause(); } throw new SecurityServiceException(e.getCause()); } }
Source:
<code>public DruidQueryGenerator.GeneratedDql toQuery() { if (hasLimit() && aggregations > 1 && !groupByColumns.isEmpty()) { throw new PrestoException(DRUID_QUERY_GENERATOR_FAILURE, "Could not pushdown multiple aggregates in the presence of group by and limit"); } String expressions = selections.entrySet().stream() .map(s -> s.getValue().getEscapedDefinition()) .collect(Collectors.joining(", ")); if (expressions.isEmpty()) { throw new PrestoException(DRUID_QUERY_GENERATOR_FAILURE, "Empty Druid query"); } String tableName = from.orElseThrow(() -> new PrestoException(DRUID_QUERY_GENERATOR_FAILURE, "Table name missing in Druid query")); <START> String query = "SELECT " + expressions + " FROM \"" + tableName + "\""; <END> boolean pushdown = false; if (filter.isPresent()) { query += " WHERE " + filter.get(); pushdown = true; } if (!groupByColumns.isEmpty()) { String groupByExpression = groupByColumns.stream() .map(expression -> selections.containsKey(expression) ? selections.get(expression).getEscapedDefinition() : expression.getName()) .collect(Collectors.joining(", ")); query = query + " GROUP BY " + groupByExpression; pushdown = true; } if (hasAggregation()) { pushdown = true; } if (limit.isPresent()) { query += " LIMIT " + limit.getAsLong(); pushdown = true; } return new DruidQueryGenerator.GeneratedDql(tableName, query, pushdown); }</code><technical_language>private function add quotes table column names</technical_language>

Target:
public DruidQueryGenerator.GeneratedDql toQuery() { if (hasLimit() && aggregations > 1 && !groupByColumns.isEmpty()) { throw new PrestoException(DRUID_QUERY_GENERATOR_FAILURE, "Could not pushdown multiple aggregates in the presence of group by and limit"); } String expressions = selections.entrySet().stream() .map(s -> s.getValue().getEscapedDefinition()) .collect(Collectors.joining(", ")); if (expressions.isEmpty()) { throw new PrestoException(DRUID_QUERY_GENERATOR_FAILURE, "Empty Druid query"); } String tableName = from.orElseThrow(() -> new PrestoException(DRUID_QUERY_GENERATOR_FAILURE, "Table name missing in Druid query")); String query = "SELECT " + expressions + " FROM " + escapeSqlIdentifier(tableName); boolean pushdown = false; if (filter.isPresent()) { query += " WHERE " + filter.get(); pushdown = true; } if (!groupByColumns.isEmpty()) { String groupByExpression = groupByColumns.stream() .map(expression -> selections.containsKey(expression) ? selections.get(expression).getEscapedDefinition() : expression.getName()) .collect(Collectors.joining(", ")); query = query + " GROUP BY " + groupByExpression; pushdown = true; } if (hasAggregation()) { pushdown = true; } if (limit.isPresent()) { query += " LIMIT " + limit.getAsLong(); pushdown = true; } return new DruidQueryGenerator.GeneratedDql(tableName, query, pushdown); }
Source:
<code>public BPMNSignal from(ActivitiSignalEvent internalEvent) { BPMNSignalImpl signal = new BPMNSignalImpl(internalEvent.getActivityId(), internalEvent.getActivityName(), internalEvent.getActivityType()); signal.setProcessDefinitionId(internalEvent.getProcessDefinitionId()); signal.setProcessInstanceId(internalEvent.getProcessInstanceId()); <START> signal.setSignalPayload((SignalPayload)internalEvent.getSignalData()); <END> return signal; }</code><technical_language>Thanks @CTI777. Ok, processInstanceId is set picked a process start signal event. For this specific test I intermediate catch signal event a boundary signal event fits better. copy ProcessWithBoundarySignal.bpmn20.xml runtime bundle starter, processInstanceId set. Also, recommend starting instances of process verify in test SIGNAL_RECEIVED catch</technical_language>

Target:
public BPMNSignal from(ActivitiSignalEvent internalEvent) { BPMNSignalImpl signal = new BPMNSignalImpl(internalEvent.getActivityId()); signal.setProcessDefinitionId(internalEvent.getProcessDefinitionId()); signal.setProcessInstanceId(internalEvent.getProcessInstanceId()); SignalPayload signalPayload = ProcessPayloadBuilder.signal() .withName(internalEvent.getSignalName()) .build(); if (internalEvent.getSignalData() != null) { Map<String, Object> sourceVariables = (Map<String, Object>) internalEvent.getSignalData(); signalPayload.setVariables(new HashMap<>(sourceVariables)); } signal.setSignalPayload(signalPayload); return signal; }
Source:
<code>private void recalculateMacsCount() { if (!validate()) { setAvailableMacsCount(-1); return; } if (macRange.getMacPoolId() == null) { String from = getLeftBound().getEntity(); String to = getRightBound().getEntity(); <START> Long count <END> = MacRangeValidation.macToLong(to) - MacRangeValidation.macToLong(from) + 1; setAvailableMacsCount(count.intValue()); } }</code><technical_language>macToLong returns 'long'</technical_language>

Target:
private void recalculateMacsCount() { if (!validate()) { setAvailableMacsCount(-1); return; } if (macRange.getMacPoolId() == null) { String from = getLeftBound().getEntity(); String to = getRightBound().getEntity(); long count = MacRangeValidation.macToLong(to) - MacRangeValidation.macToLong(from) + 1; setAvailableMacsCount((int) count); } }
Source:
<code>protected HttpWebRequest buildEwsHttpWebRequest() throws Exception { <START> HttpWebRequest request = null; <END> try { request = this.getService().prepareHttpWebRequest(); AsyncExecutor ae = new AsyncExecutor(); Callable getStream = new GetStream(request, "getOutputStream"); Future task = ae.submit(getStream, null); ae.shutdown(); this.getService().traceHttpRequestHeaders(TraceFlags.EwsRequestHttpHeaders, request); boolean needSignature = this.getService().getCredentials() != null && this.getService().getCredentials().isNeedSignature(); boolean needTrace = this.getService().isTraceEnabledFor( TraceFlags.EwsRequest); ByteArrayOutputStream memoryStream = new ByteArrayOutputStream(); EwsServiceXmlWriter writer = new EwsServiceXmlWriter(this .getService(), memoryStream); writer.setRequireWSSecurityUtilityNamespace(needSignature); this.writeToXml(writer); if (needSignature || needTrace) { if (needSignature) { this.service.getCredentials().sign(memoryStream); } if (needTrace) { this.getService().traceXml(TraceFlags.EwsRequest, memoryStream); } ByteArrayOutputStream serviceRequestStream = this.getWebRequestStream(task); EwsUtilities.copyStream(memoryStream, serviceRequestStream); } else { ByteArrayOutputStream requestStream = this .getWebRequestStream(task); EwsServiceXmlWriter writer1 = new EwsServiceXmlWriter(this .getService(), requestStream); this.writeToXml(writer1); } return request; } catch (IOException e) { throw new ServiceRequestException(String.format(Strings.ServiceRequestFailed, e.getMessage()), e); } }</code><technical_language>Move this try block combine "request" declaration initialization</technical_language>

Target:
protected HttpWebRequest buildEwsHttpWebRequest() throws Exception { try { HttpWebRequest request = this.getService().prepareHttpWebRequest(); AsyncExecutor ae = new AsyncExecutor(); Callable getStream = new GetStream(request, "getOutputStream"); Future task = ae.submit(getStream, null); ae.shutdown(); this.getService().traceHttpRequestHeaders(TraceFlags.EwsRequestHttpHeaders, request); boolean needSignature = this.getService().getCredentials() != null && this.getService().getCredentials().isNeedSignature(); boolean needTrace = this.getService().isTraceEnabledFor( TraceFlags.EwsRequest); ByteArrayOutputStream memoryStream = new ByteArrayOutputStream(); EwsServiceXmlWriter writer = new EwsServiceXmlWriter(this .getService(), memoryStream); writer.setRequireWSSecurityUtilityNamespace(needSignature); this.writeToXml(writer); if (needSignature || needTrace) { if (needSignature) { this.service.getCredentials().sign(memoryStream); } if (needTrace) { this.getService().traceXml(TraceFlags.EwsRequest, memoryStream); } ByteArrayOutputStream serviceRequestStream = this.getWebRequestStream(task); EwsUtilities.copyStream(memoryStream, serviceRequestStream); } else { ByteArrayOutputStream requestStream = this .getWebRequestStream(task); EwsServiceXmlWriter writer1 = new EwsServiceXmlWriter(this .getService(), requestStream); this.writeToXml(writer1); } return request; } catch (IOException e) { throw new ServiceRequestException(String.format(Strings.ServiceRequestFailed, e.getMessage()), e); } }
Source:
<code>public boolean isImageNetworkDisk(DiskImage diskImage, Version clusterVersion, Guid clusterId) { StorageType storageType = diskImage.getStorageTypes().get(0); if (storageType == StorageType.GLUSTERFS) { <START> if (FeatureSupported.libgfApiSupported(clusterVersion)) { return true; } return isFeatureSupportedAsAdditionalFeature(clusterId, ConfigValues.LibgfApiSupported.name()); <END> } return false; }</code><technical_language>reduced a single boolean expression, is more more clear understand: return FeatureSupported.libgfApiSupported(clusterVersion) || isFeatureSupportedAsAdditionalFeature(clusterId, ConfigValues.LibgfApiSupported.name());</technical_language>

Target:
public boolean isImageNetworkDisk(DiskImage diskImage, Version clusterVersion, Guid clusterId) { StorageType storageType = diskImage.getStorageTypes().get(0); if (storageType == StorageType.GLUSTERFS) { return FeatureSupported.libgfApiSupported(clusterVersion) || isFeatureSupportedAsAdditionalFeature(clusterId, ConfigValues.LibgfApiSupported.name()); } return false; }
Source:
<code>public CompletableFuture<?> purge(String tenantId) { multiTenancyStrategy.checkTenantId( tenantId, eventContext ); <START> JsonObject document = ( tenantId == null ) ? matchAll() : matchAllByTenant( tenantId ); <END> return orchestrator.submit( workFactory.deleteByQuery( indexName, document ) ); }</code><technical_language>I previously discussed, creating work MultiTenancyStrategy's responsibility. reasoning is could, in future, multi-tenancy strategies, discriminator-based strategies potentially index-based (one index tenant) cluster-based (one cluster tenant). assume tenant ID used, multi-tenancy strategy decide that. this account in org.hibernate.search.backend.lucene.work.impl.LuceneStubWorkFactory. update method for example delegates multi-tenancy strategy create works. pass tenant ID work factory, to. work factory, a reference multi-tenancy strategy delegate create work. perfect, change some point, similar move problem IndexWorkExecutor</technical_language>

Target:
public CompletableFuture<?> purge(String tenantId) { multiTenancyStrategy.checkTenantId( tenantId, eventContext ); return orchestrator.submit( workFactory.deleteAll( indexName, tenantId ) ); }
Source:
<code>public void testOneChannel() { final MySignal sig1 = new MySignal(sender, 0); final MySignal sig2 = new MySignal(sender, 0); final MySignal sig3 = new MySignal(sender, 0); synchronized(this) { sender.sendSignal(sig1); sender.sendSignal(sig2); sender.sendSignal(sig3); } <START> sleep(250); <END> assertEquals(1, listener.nbReceived[0]); assertEquals(0, listener.nbReceived[1]); assertEquals(0, listener.nbReceived[2]); }</code><technical_language>250ms is tight time delay is 200ms. I put 1000ms safe</technical_language>

Target:
public void testOneChannel() { final MySignal sig1 = new MySignal(sender, 0); final MySignal sig2 = new MySignal(sender, 0); final MySignal sig3 = new MySignal(sender, 0); synchronized(this) { sender.sendSignal(sig1); sender.sendSignal(sig2); sender.sendSignal(sig3); } sleep(1000); assertEquals(1, listener.nbReceived[0]); assertEquals(0, listener.nbReceived[1]); assertEquals(0, listener.nbReceived[2]); }
Source:
<code>private HBox createNameArea() { HBox nameArea = new HBox(); nameText = new Text(panelName); nameText.setId(model.getDefaultRepo() + "_col" + panel.panelIndex + "_nameText"); nameText.setWrappingWidth(NAME_DISPLAY_WIDTH); nameBox = new HBox(); nameBox.getChildren().add(nameText); nameBox.setMinWidth(NAME_DISPLAY_WIDTH); nameBox.setMaxWidth(NAME_DISPLAY_WIDTH); nameBox.setAlignment(Pos.CENTER_LEFT); nameBox.setOnMouseClicked(mouseEvent -> { if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) { if (mouseEvent.getClickCount() == 2) { mouseEvent.consume(); activateInplaceRename(); } } }); <START> Tooltip.install(nameArea, new Tooltip("Rename")); <END> HBox renameBox = new HBox(); renameButton = new Label(OCTICON_RENAME_PANEL); renameButton.getStyleClass().addAll("octicon", "label-button"); renameButton.setId(model.getDefaultRepo() + "_col" + panel.panelIndex + "_renameButton"); renameButton.setOnMouseClicked(e -> { e.consume(); activateInplaceRename(); }); renameBox.getChildren().add(renameButton); renameBox.setAlignment(Pos.TOP_RIGHT); nameArea.getChildren().addAll(nameBox, renameButton); nameArea.setMinWidth(360); nameArea.setMaxWidth(360); return nameArea; }</code><technical_language>Tool tips slightly more detailed. a word enough</technical_language>

Target:
private HBox createNameArea() { HBox nameArea = new HBox(); nameText = new Text(panelName); nameText.setId(model.getDefaultRepo() + "_col" + panel.panelIndex + "_nameText"); nameText.setWrappingWidth(NAME_DISPLAY_WIDTH); nameBox = new HBox(); nameBox.getChildren().add(nameText); nameBox.setMinWidth(NAME_DISPLAY_WIDTH); nameBox.setMaxWidth(NAME_DISPLAY_WIDTH); nameBox.setAlignment(Pos.CENTER_LEFT); nameBox.setOnMouseClicked(mouseEvent -> { if (mouseEvent.getButton().equals(MouseButton.PRIMARY) && mouseEvent.getClickCount() == 2) { mouseEvent.consume(); activateInplaceRename(); } }); Tooltip.install(nameArea, new Tooltip("Edit the name of this panel")); HBox renameBox = new HBox(); renameButton = new Label(OCTICON_RENAME_PANEL); renameButton.getStyleClass().addAll("octicon", "label-button"); renameButton.setId(model.getDefaultRepo() + "_col" + panel.panelIndex + "_renameButton"); renameButton.setOnMouseClicked(e -> { e.consume(); activateInplaceRename(); }); renameBox.getChildren().add(renameButton); renameBox.setAlignment(Pos.TOP_RIGHT); nameArea.getChildren().addAll(nameBox, renameButton); nameArea.setMinWidth(360); nameArea.setMaxWidth(360); return nameArea; }
Source:
<code>public void sendHttpRequestAndWriteResponseAsJson() throws Exception { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple(HttpURLConnection.HTTP_OK, "{\"msg\": \"hi\"}") ).start(); final GhLabel label = new GhLabel( new ApacheRequest(container.home()), <START> new DefaultGithub() <END> .repos().get(new Coordinates.Simple("mark", "test")), "bug" ); MatcherAssert.assertThat( label.json().getString("msg"), Matchers.equalTo("hi") ); container.stop(); }</code><technical_language>making a real object here? Mockito.mock(Github.class). for other method</technical_language>

Target:
public void sendHttpRequestAndWriteResponseAsJson() throws Exception { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple(HttpURLConnection.HTTP_OK, "{\"msg\": \"hi\"}") ).start(); final GhLabel label = new GhLabel( new ApacheRequest(container.home()), GhLabelTest.repo(), "bug" ); MatcherAssert.assertThat( label.json().getString("msg"), Matchers.equalTo("hi") ); container.stop(); }
Source:
<code>public void run() { synchronized (managedStateImpl.commitLock) { long bytesSum = 0; for (Bucket bucket : managedStateImpl.buckets) { if (bucket != null) { bytesSum += bucket.getSizeInBytes(); } } if (bytesSum > managedStateImpl.getMaxMemorySize()) { Duration duration = managedStateImpl.getDurationPreventingFreeingSpace(); long durationMillis = 0; if (duration != null) { durationMillis = duration.getMillis(); } BucketIdTimeWrapper idTimeWrapper; while (bytesSum > managedStateImpl.getMaxMemorySize() && bucketHeap.size() > 0 && null != (idTimeWrapper = bucketHeap.first())) { if (System.currentTimeMillis() - idTimeWrapper.getLastAccessedTime() < durationMillis) { break; } long bucketId = idTimeWrapper.bucketId; Bucket bucket = managedStateImpl.getBucket(bucketId); if (bucket != null) { synchronized (bucket) { <START> long sizeFreed = 0; <END> try { sizeFreed = bucket.freeMemory(managedStateImpl.getCheckpointManager().getLastTransferredWindow()); LOG.debug("bucket freed {}", bucketId, sizeFreed); } catch (IOException e) { managedStateImpl.throwable.set(e); throw new RuntimeException("freeing " + bucketId, e); } bytesSum -= sizeFreed; } bucketHeap.remove(idTimeWrapper); bucketAccessTimes.remove(bucketId); } } } } }</code><technical_language>this change</technical_language>

Target:
public void run() { synchronized (managedStateImpl.commitLock) { long bytesSum = 0; for (Bucket bucket : managedStateImpl.buckets) { if (bucket != null) { bytesSum += bucket.getSizeInBytes(); } } if (bytesSum > managedStateImpl.getMaxMemorySize()) { Duration duration = managedStateImpl.getDurationPreventingFreeingSpace(); long durationMillis = 0; if (duration != null) { durationMillis = duration.getMillis(); } BucketIdTimeWrapper idTimeWrapper; while (bytesSum > managedStateImpl.getMaxMemorySize() && bucketHeap.size() > 0 && null != (idTimeWrapper = bucketHeap.first())) { if (System.currentTimeMillis() - idTimeWrapper.getLastAccessedTime() < durationMillis) { break; } long bucketId = idTimeWrapper.bucketId; Bucket bucket = managedStateImpl.getBucket(bucketId); if (bucket != null) { synchronized (bucket) { long sizeFreed; try { sizeFreed = bucket.freeMemory(managedStateImpl.getCheckpointManager().getLastTransferredWindow()); LOG.debug("bucket freed {}", bucketId, sizeFreed); } catch (IOException e) { managedStateImpl.throwable.set(e); throw new RuntimeException("freeing " + bucketId, e); } bytesSum -= sizeFreed; } bucketHeap.remove(idTimeWrapper); bucketAccessTimes.remove(bucketId); } } } } }
Source:
<code>protected ProviderMetadata createProviderMetadata() { synchronized (this) { if (providerMeta == null) { providerMeta = new AzureComputeProviderMetadata(); } } return providerMeta; <START> } <END></code><technical_language>Is this necessary? base class method working</technical_language>

Target:
protected ProviderMetadata createProviderMetadata() { if (providerMeta == null) { providerMeta = new AzureComputeProviderMetadata(); } return providerMeta; }
Source:
<code>private void parseConfiguration(String config) throws IllegalArgumentException { String[] mappings = config.split(","); for (String mapping : mappings) { String[] params = mapping.split(":"); if (params.length < 2) { throw new IllegalArgumentException("Configuration " + mapping + " is in-correctly formed. " + "Format should be <fieldname>:<encoder-type>"); } String field = params[0]; String type = params[1].toUpperCase(); <START> EncodeType eType; <END> switch (type) { case "STRING_BASE64": eType = EncodeType.STRING_BASE64; break; case "STRING_BASE32": eType = EncodeType.STRING_BASE32; break; case "BASE64": eType = EncodeType.BASE64; break; case "BASE32": eType = EncodeType.BASE32; break; case "HEX": eType = EncodeType.HEX; break; case "NONE": eType = EncodeType.NONE; break; default: throw new IllegalArgumentException("Unknown encoder type " + type + " found in mapping " + mapping); } if (encodeMap.containsKey(field)) { throw new IllegalArgumentException("Field " + field + " already has encoder set. Check the mapping."); } else { encodeMap.put(field, eType); } } }</code><technical_language>EncodeType eType = EncodeType.valueOf(type) work</technical_language>

Target:
private void parseConfiguration(String config) throws IllegalArgumentException { String[] mappings = config.split(","); for (String mapping : mappings) { String[] params = mapping.split(":"); if (params.length < 2) { throw new IllegalArgumentException("Configuration " + mapping + " is in-correctly formed. " + "Format should be <fieldname>:<encoder-type>"); } String field = params[0]; String type = params[1].toUpperCase(); EncodeType eType = EncodeType.valueOf(type); if (encodeMap.containsKey(field)) { throw new IllegalArgumentException("Field " + field + " already has encoder set. Check the mapping."); } else { encodeMap.put(field, eType); } } }
Source:
<code>protected void readBlob() { closePreviousInputStream(); try { File tmp = File.createTempFile("talend-adls-gen2-tmp", ".parquet"); tmp.deleteOnExit(); BlobClient blobClient = service.getBlobClient(getCurrentBlob().getName()); InputStream input = blobClient.getBlockBlobClient().openInputStream(); Files.copy(input, tmp.toPath(), StandardCopyOption.REPLACE_EXISTING); <START> IOUtils.closeQuietly(input); <END> HadoopInputFile hdpIn = HadoopInputFile.fromPath(new Path(tmp.getPath()), new org.apache.hadoop.conf.Configuration()); reader = AvroParquetReader.<GenericRecord>builder(hdpIn).build(); currentRecord = reader.read(); } catch (IOException e) { throw new ComponentException(e); } }</code><technical_language>Is put "finally" block</technical_language>

Target:
protected void readBlob() { closePreviousInputStream(); InputStream input = null; try { File tmp = File.createTempFile("talend-adls-gen2-tmp", ".parquet"); tmp.deleteOnExit(); BlobClient blobClient = service.getBlobClient(getCurrentBlob().getName()); input = blobClient.getBlockBlobClient().openInputStream(); Files.copy(input, tmp.toPath(), StandardCopyOption.REPLACE_EXISTING); reader = AvroParquetReader.<GenericRecord>builder(new Path(tmp.getPath())).build(); currentRecord = reader.read(); } catch (IOException e) { throw new ComponentException(e); } finally { IOUtils.closeQuietly(input); } }
Source:
<code>public File stripCRLFile(File file) throws IOException { File tempFile = File.createTempFile("candlepin_crl_", ".pem"); BufferedReader r = null; BufferedWriter w = null; String line = null; <START> try { <END> r = new BufferedReader(new FileReader(file)); w = new BufferedWriter(new FileWriter(tempFile)); do { line = r.readLine(); } while (line != null && (WHITESPACE.matcher(line).matches() || CRL_HEADER_PATTERN.matcher(line).matches())); if (line == null) { throw new IOException("No data left in file " + file); } do { w.write(line); line = r.readLine(); } while (line != null && !CRL_FOOTER_PATTERN.matcher(line).matches()); return tempFile; } finally { if (w != null) { w.close(); } if (r != null) { r.close(); } } }</code><technical_language>a multi-try-with-resources try (r = new BufferedReader(new FileReader(file)); w = new BufferedWriter(new FileWriter(tempFile))) { cut boilerplate</technical_language>

Target:
public File stripCRLFile(File file) throws IOException { File tempFile = File.createTempFile("candlepin_crl_", ".pem"); try (BufferedReader r = new BufferedReader(new FileReader(file)); BufferedWriter w = new BufferedWriter(new FileWriter(tempFile))) { String line = null; do { line = r.readLine(); } while (line != null && (WHITESPACE.matcher(line).matches() || CRL_HEADER_PATTERN.matcher(line).matches())); if (line == null) { throw new IOException("No data left in file " + file); } do { w.write(line); line = r.readLine(); } while (line != null && !CRL_FOOTER_PATTERN.matcher(line).matches()); return tempFile; } }
Source:
<code>public FilterInstantSpell(String name) { super(name); <START> this.add(Predicates.or(CardType.INSTANT.getPredicate())); <END> }</code><technical_language>need Predicates.or</technical_language>

Target:
public FilterInstantSpell(String name) { super(name); this.add(CardType.INSTANT.getPredicate()); }
Source:
<code>@Test public void shouldGetBookingFormAsyncThrowError() { String responseError = "{\"error\":\"That userToken is unrecognised.\",\"errorCode\":401,\"usererror\":false}"; ResponseBody responseBody = ResponseBody.create(MediaType.parse("application/json"), responseError); final Response<BookingForm> response = Response.error(401, responseBody); when(bookingApi.getFormAsync("url")) .thenReturn(Observable.just(response)); final TestSubscriber<BookingForm> subscriber = new TestSubscriber<>(); service.getFormAsync("url").subscribe(subscriber); subscriber.awaitTerminalEvent(); subscriber.assertError(BookingError.class); Throwable error = subscriber.getOnErrorEvents().get(0); assertThat(error instanceof BookingError).isTrue(); <START> <END> }</code><technical_language>if test specifics of error as: assertThat(error.getError()).isEqualsTo("That userToken is unrecognised");</technical_language>

Target:
@Test public void shouldGetBookingFormAsyncThrowError() { String responseError = "{\"error\":\"That userToken is unrecognised.\",\"errorCode\":401,\"usererror\":false}"; ResponseBody responseBody = ResponseBody.create(MediaType.parse("application/json"), responseError); final Response<BookingForm> response = Response.error(401, responseBody); when(bookingApi.getFormAsync("url")) .thenReturn(Observable.just(response)); final TestSubscriber<BookingForm> subscriber = new TestSubscriber<>(); service.getFormAsync("url").subscribe(subscriber); subscriber.awaitTerminalEvent(); subscriber.assertError(BookingError.class); Throwable error = subscriber.getOnErrorEvents().get(0); assertThat(error.getMessage()).isEqualTo("That userToken is unrecognised."); }
Source:
<code>private void pushUpstream(final RevCommit commit, final PushMode pushTo) { RemoteConfig config = SimpleConfigurePushDialog .getConfiguredRemote(repository); if (pushTo == PushMode.GERRIT) { final Wizard pushWizard = new PushToGerritWizard(repository); openPushWizard(pushWizard); } else if (config == null) { try { Wizard pushWizard = null; String fullBranch = repository.getFullBranch(); if (fullBranch != null && fullBranch.startsWith(Constants.R_HEADS)) { Ref ref = <START> repository.findRef(fullBranch); <END> pushWizard = new PushBranchWizard(repository, ref); } else { pushWizard = new PushBranchWizard(repository, commit.getId()); } openPushWizard(pushWizard); } catch (IOException e) { Activator.handleError( NLS.bind(UIText.CommitUI_pushFailedMessage, e), e, true); } } else { PushOperationUI op = new PushOperationUI(repository, config.getName(), false); op.start(); } }</code><technical_language>exactRef</technical_language>

Target:
private void pushUpstream(final RevCommit commit, final PushMode pushTo) { RemoteConfig config = SimpleConfigurePushDialog .getConfiguredRemote(repository); if (pushTo == PushMode.GERRIT) { final Wizard pushWizard = new PushToGerritWizard(repository); openPushWizard(pushWizard); } else if (config == null) { try { Wizard pushWizard = null; String fullBranch = repository.getFullBranch(); if (fullBranch != null && fullBranch.startsWith(Constants.R_HEADS)) { Ref ref = repository.exactRef(fullBranch); pushWizard = new PushBranchWizard(repository, ref); } else { pushWizard = new PushBranchWizard(repository, commit.getId()); } openPushWizard(pushWizard); } catch (IOException e) { Activator.handleError( NLS.bind(UIText.CommitUI_pushFailedMessage, e), e, true); } } else { PushOperationUI op = new PushOperationUI(repository, config.getName(), false); op.start(); } }
Source:
<code>public void onError(Exception exception) { AppLog.e(AppLog.T.MEDIA, "Can't optimize the video", exception); if (isStopped) { return; } <START> trackVideoProcessingEvents(true, exception); <END> final EditPostActivity parentActivity = mEditPostActivityWeakReference.get(); if (parentActivity == null || parentActivity.isFinishing()) { return; } ProgressDialog pd = mWeakProgressDialog.get(); dismissProgressDialog(pd); ToastUtils.showToast(parentActivity, R.string.video_optimization_generic_error_message, ToastUtils.Duration.LONG); mVideoOptimizationListener.done(mOriginalPath); }</code><technical_language>of check, tracking exception isStopped is true. Is purpose</technical_language>

Target:
public void onError(Exception exception) { AppLog.e(AppLog.T.MEDIA, "Can't optimize the video", exception); trackVideoProcessingEvents(true, exception); if (isStopped) { return; } final EditPostActivity parentActivity = mEditPostActivityWeakReference.get(); if (parentActivity == null || parentActivity.isFinishing()) { return; } ProgressDialog pd = mWeakProgressDialog.get(); dismissProgressDialog(pd); ToastUtils.showToast(parentActivity, R.string.video_optimization_generic_error_message, ToastUtils.Duration.LONG); mVideoOptimizationListener.done(mOriginalPath); }