auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void setTableProperties(final CommandLine cl, final Shell shellState, final int priority, final Map<String,String> options, final String classname, final String name) throws AccumuloException, AccumuloSecurityException, ShellCommandException, TableNotFoundException { final String tableName = OptUtil.getTableOpt(cl, shellState); ScanCommand.ensureTserversCanLoadIterator(shellState, tableName, classname); options.entrySet().removeIf(entry -> entry.getValue() == null || entry.getValue().isEmpty()); final EnumSet<IteratorScope> scopes = EnumSet.noneOf(IteratorScope.class); if (cl.hasOption(allScopeOpt.getOpt()) || cl.hasOption(mincScopeOpt.getOpt())) { scopes.add(IteratorScope.minc); } if (cl.hasOption(allScopeOpt.getOpt()) || cl.hasOption(majcScopeOpt.getOpt())) { scopes.add(IteratorScope.majc); } if (cl.hasOption(allScopeOpt.getOpt()) || cl.hasOption(scanScopeOpt.getOpt())) { scopes.add(IteratorScope.scan); } if (scopes.isEmpty()) { throw new IllegalArgumentException("You must select at least one scope to configure"); } final IteratorSetting setting = new IteratorSetting(priority, name, classname, options); shellState.getAccumuloClient().tableOperations().attachIterator(tableName, setting, scopes); }

Target:
protected void setTableProperties(final CommandLine cl, final Shell shellState, final int priority, final Map<String,String> options, final String classname, final String name) throws AccumuloException, AccumuloSecurityException, ShellCommandException, TableNotFoundException { final String tableName = OptUtil.getTableOpt(cl, shellState); ScanCommand.ensureTserversCanLoadIterator(shellState, tableName, classname); options.values().removeIf(v -> v == null || v.isEmpty()); final EnumSet<IteratorScope> scopes = EnumSet.noneOf(IteratorScope.class); if (cl.hasOption(allScopeOpt.getOpt()) || cl.hasOption(mincScopeOpt.getOpt())) { scopes.add(IteratorScope.minc); } if (cl.hasOption(allScopeOpt.getOpt()) || cl.hasOption(majcScopeOpt.getOpt())) { scopes.add(IteratorScope.majc); } if (cl.hasOption(allScopeOpt.getOpt()) || cl.hasOption(scanScopeOpt.getOpt())) { scopes.add(IteratorScope.scan); } if (scopes.isEmpty()) { throw new IllegalArgumentException("You must select at least one scope to configure"); } final IteratorSetting setting = new IteratorSetting(priority, name, classname, options); shellState.getAccumuloClient().tableOperations().attachIterator(tableName, setting, scopes); }
Source:
public boolean isInflateInsideIf() { if (this.viewAssignmentStatement != null) { if (getFirstAncestorOrNull(this.viewAssignmentStatement, IfStatement.class) != null) { return true; } else if (getFirstAncestorOrNull(this.viewAssignmentStatement, SwitchStatement.class) != null) { return true; } else { Expression inflateExpression = this.getInflateExpression(); if (inflateExpression != null && inflateExpression.getNodeType() == ASTNode.CONDITIONAL_EXPRESSION) { return true; } } } return false; }

Target:
public boolean isInflateInsideIf() { if (this.viewAssignmentStmt != null) { Expression inflateExpr = getInflateExpr(); return getFirstAncestorOrNull(this.viewAssignmentStmt, IfStatement.class, SwitchStatement.class) != null || (inflateExpr != null && inflateExpr.getNodeType() == ASTNode.CONDITIONAL_EXPRESSION); } return false; }
Source:
void shouldNotUpdateCharge_IfEpdqStatusIs6AndChargeStatusIsNotPresent() { final String payload = notificationPayloadForTransaction(payId, EPDQ_AUTHORISED_CANCELLED); charge = getCharge(false); setUpGatewayAccountToReturnGatewayAccountEntity(Optional.of(gatewayAccountEntity)); setUpChargeServiceToReturnCharge(Optional.of(charge)); final boolean result = notificationService.handleNotificationFor(payload, FORWARDED_IP_ADDRESSES); assertTrue(result); verifyNoInteractions(mockChargeNotificationProcessor); }

Target:
void shouldNotUpdateCharge_IfEpdqStatusIs6AndChargeStatusIsNotPresent() { final String payload = notificationPayloadForTransaction(payId, EPDQ_AUTHORISED_CANCELLED); charge = getCharge(false); setUpGatewayAccountToReturnGatewayAccountEntity(Optional.of(gatewayAccountEntity)); setUpChargeServiceToReturnCharge(Optional.of(charge)); assertTrue(notificationService.handleNotificationFor(payload, FORWARDED_IP_ADDRESSES)); verifyNoInteractions(mockChargeNotificationProcessor); }
Source:
private static <D, T, S> double[] calculateLogForwardProbabilities( final HiddenMarkovModel<D, T, S> model, final List<D> data, final List<T> positions) { final List<S> states = model.hiddenStates(); final int width = states.size(); final int length = data.size(); final double[] result = new double[width * length]; if (length == 0) { return result; } final T position0 = positions.get(0); final D datum0 = data.get(0); for (int s = 0; s < states.size(); s++) { final S state = states.get(s); result[s] = model.logPriorProbability(state, position0) + model.logEmissionProbability(datum0, state, position0); } final double[] logSumBuffer = new double[states.size()]; for (int u = 1; u < data.size(); u++) { final int t = u - 1; final int tOffset = width * t; final int uOffset = tOffset + width; final T positionT = positions.get(t); final T positionU = positions.get(u); for (int sU = 0; sU < width; sU++) { final S stateU = states.get(sU); for (int sT = 0; sT < width; sT++) { logSumBuffer[sT] = result[sT + tOffset] + model.logTransitionProbability(states.get(sT), positionT, stateU, positionU); } result[sU + uOffset] = MathUtils.approximateLogSumLog(logSumBuffer) + model.logEmissionProbability(data.get(u), stateU, positionU); } } return result; }

Target:
private static <D, T, S> double[][] calculateLogForwardProbabilities( final HiddenMarkovModel<D, T, S> model, final List<D> data, final List<T> positions) { final List<S> states = model.hiddenStates(); final int numStates = states.size(); final int length = data.size(); final double[][] result = new double[length][numStates]; if (length == 0) { return result; } final T position0 = positions.get(0); final D datum0 = data.get(0); for (int stateIndex = 0; stateIndex < states.size(); stateIndex++) { final S state = states.get(stateIndex); result[0][stateIndex] = model.logPriorProbability(state, position0) + model.logEmissionProbability(datum0, state, position0); } final double[] logSumBuffer = new double[states.size()]; for (int thisPositionIndex = 1; thisPositionIndex < data.size(); thisPositionIndex++) { final int previousPositionIndex = thisPositionIndex - 1; final T previousPosition = positions.get(previousPositionIndex); final T thisPosition = positions.get(thisPositionIndex); for (int thisStateIndex = 0; thisStateIndex < numStates; thisStateIndex++) { final S thisState = states.get(thisStateIndex); for (int previousStateIndex = 0; previousStateIndex < numStates; previousStateIndex++) { logSumBuffer[previousStateIndex] = result[previousPositionIndex][previousStateIndex] + model.logTransitionProbability(states.get(previousStateIndex), previousPosition, thisState, thisPosition); } result[thisPositionIndex][thisStateIndex] = MathUtils.approximateLogSumLog(logSumBuffer) + model.logEmissionProbability(data.get(thisPositionIndex), thisState, thisPosition); } } return result; }
Source:
public Schema(Class<?> cls, EntityDictionary entityDictionary) { this.entityClass = Objects.requireNonNull(cls, "cls"); this.entityDictionary = Objects.requireNonNull(entityDictionary, "entityDictionary"); this.metrics = entityDictionary.getAllFields(getEntityClass()).stream() .filter(this::isMetricField) .filter(field -> getEntityDictionary() .attributeOrRelationAnnotationExists(entityClass, field, MetricAggregation.class) ) .map(field -> constructMetric(field, getEntityClass(), entityDictionary)) .collect( Collectors.collectingAndThen( Collectors.toSet(), Collections::unmodifiableSet ) ); this.dimensions = getEntityDictionary().getAllFields(getEntityClass()).stream() .filter(field -> !isMetricField(field)) .map(field -> constructDimension(field, getEntityClass(), getEntityDictionary())) .collect( Collectors.collectingAndThen( Collectors.toSet(), Collections::unmodifiableSet ) ); this.columns = Stream.concat( getDimensions().stream().map(dimension -> (Column) dimension), getMetrics().stream().map(metric -> (Column) metric) ).collect(Collectors.toSet()); }

Target:
public Schema(Class<?> cls, EntityDictionary entityDictionary) { this.entityClass = Objects.requireNonNull(cls, "cls"); this.entityDictionary = Objects.requireNonNull(entityDictionary, "entityDictionary"); this.metrics = getAllMetrics(); this.dimensions = getAllDimensions(); }
Source:
public void handleNewSession(final String sessionId) throws Exception { if (sessionId != null && !getSessionId().equals(sessionId)) { LOG.info("Session: is not handled because it is expired.", sessionId); return; } LOG.info("Handle new session, instance: {}, type: {}, session id: {}.", _instanceName, _instanceType, sessionId); waitUntilConnected(); stopTimerTasks(); if (_leaderElectionHandler != null) { _leaderElectionHandler.reset(false); } resetHandlers(false); _baseDataAccessor.reset(); if (!ZKUtil.isClusterSetup(_clusterName, _zkclient)) { throw new HelixException("Cluster structure is not set up for cluster: " + _clusterName); } _sessionStartTime = System.currentTimeMillis(); switch (_instanceType) { case PARTICIPANT: handleNewSessionAsParticipant(); break; case CONTROLLER: handleNewSessionAsController(); break; case CONTROLLER_PARTICIPANT: handleNewSessionAsParticipant(); handleNewSessionAsController(); break; case ADMINISTRATOR: case SPECTATOR: default: break; } startTimerTasks(); initHandlers(_handlers); if (_stateListener != null) { try { _stateListener.onConnected(this); } catch (Exception e) { LOG.warn("stateListener.onConnected callback fails", e); } } }

Target:
public void handleNewSession(final String sessionId) throws Exception { waitUntilConnected(); LOG.info("Handle new session, instance: {}, type: {}, session id: {}.", _instanceName, _instanceType, sessionId == null ? "None" : sessionId); stopTimerTasks(); if (_leaderElectionHandler != null) { _leaderElectionHandler.reset(false); } resetHandlers(false); _baseDataAccessor.reset(); if (!ZKUtil.isClusterSetup(_clusterName, _zkclient)) { throw new HelixException("Cluster structure is not set up for cluster: " + _clusterName); } _sessionStartTime = System.currentTimeMillis(); switch (_instanceType) { case PARTICIPANT: handleNewSessionAsParticipant(); break; case CONTROLLER: handleNewSessionAsController(); break; case CONTROLLER_PARTICIPANT: handleNewSessionAsParticipant(); handleNewSessionAsController(); break; case ADMINISTRATOR: case SPECTATOR: default: break; } startTimerTasks(); initHandlers(_handlers); if (_stateListener != null) { try { _stateListener.onConnected(this); } catch (Exception e) { LOG.warn("stateListener.onConnected callback fails", e); } } }
Source:
public void addStateModelDef(String clusterName, String stateModelDef, StateModelDefinition stateModel, boolean recreateIfExists) { if (!ZKUtil.isClusterSetup(clusterName, _zkClient)) { throw new HelixException("cluster " + clusterName + " is not setup yet"); } String stateModelDefPath = HelixUtil.getStateModelDefinitionPath(clusterName); String stateModelPath = stateModelDefPath + "/" + stateModelDef; if (_zkClient.exists(stateModelPath)) { if (recreateIfExists) { logger.warn("Operation.State Model directory exists:" + stateModelPath + ", remove and recreate."); _zkClient.deleteRecursive(stateModelPath); } else { logger.warn("Skip the operation.State Model directory exists:" + stateModelPath); return; } } HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); Builder keyBuilder = accessor.keyBuilder(); accessor.setProperty(keyBuilder.stateModelDef(stateModel.getId()), stateModel); }

Target:
public void addStateModelDef(String clusterName, String stateModelDef, StateModelDefinition stateModel, boolean recreateIfExists) { if (!ZKUtil.isClusterSetup(clusterName, _zkClient)) { throw new HelixException("cluster " + clusterName + " is not setup yet"); } String stateModelDefPath = HelixUtil.getStateModelDefinitionPath(clusterName); String stateModelPath = stateModelDefPath + "/" + stateModelDef; if (_zkClient.exists(stateModelPath)) { if (recreateIfExists) { logger.info("Operation.State Model directory exists:" + stateModelPath + ", remove and recreate."); _zkClient.deleteRecursive(stateModelPath); } else { logger.info("Skip the operation. State Model directory exists:" + stateModelPath); return; } } HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); Builder keyBuilder = accessor.keyBuilder(); accessor.setProperty(keyBuilder.stateModelDef(stateModel.getId()), stateModel); }
Source:
public static OvernightRateSensitivity of( OvernightIndex index, Currency currency, LocalDate fixingDate, double sensitivity) { LocalDate endDate = index.calculateMaturityFromEffective(index.calculateEffectiveFromFixing(fixingDate)); return new OvernightRateSensitivity(index, currency, fixingDate, endDate, sensitivity); }

Target:
public static OvernightRateSensitivity of( OvernightIndex index, Currency currency, LocalDate fixingDate, double sensitivity) { LocalDate endDate = index.calculateMaturityFromEffective(index.calculateEffectiveFromFixing(fixingDate)); return OvernightRateSensitivity.of(index, currency, fixingDate, endDate, sensitivity); }
Source:
private void matched(Matcher matcher, HttpMessage msg, int id) { String tag = getConf(); if (tagHistoryType(msg.getHistoryRef().getHistoryType())) { if (matcher.groupCount() > 0) { StringBuffer result = new StringBuffer(); matcher.appendReplacement(result, tag); tag = result.substring(matcher.start()); parent.addTag(id, tag); } else { parent.addTag(id, tag); } } try { Stats.incCounter(SessionStructure.getHostName(msg), TAG_STATS_PREFIX + this.getConf()); } catch (URIException e) { } }

Target:
private void matched(Matcher matcher, HttpMessage msg, int id) { String tag = getConf(); if (tagHistoryType(msg.getHistoryRef().getHistoryType())) { if (matcher.groupCount() > 0) { tag = matcher.pattern().matcher(matcher.group()).replaceFirst(tag); } parent.addTag(id, tag); } try { Stats.incCounter(SessionStructure.getHostName(msg), TAG_STATS_PREFIX + this.getConf()); } catch (URIException e) { } }
Source:
XmlManifest(RepoCommand command, InputStream inputStream, String filename, String baseUrl, String groups) { this.command = command; this.inputStream = inputStream; this.filename = filename; this.baseUrl = baseUrl.replaceAll("/+$", ""); remotes = new HashMap<String, String>(); projects = new ArrayList<Project>(); plusGroups = new HashSet<String>(); minusGroups = new HashSet<String>(); if (groups == null || groups.length() == 0 || groups.equals("default")) { minusGroups.add("notdefault"); } else { for (String group : groups.split(",")) { if (group.startsWith("-")) minusGroups.add(group.substring(1)); else plusGroups.add(group); } } }

Target:
XmlManifest(RepoCommand command, InputStream inputStream, String filename, String baseUrl, String groups) { this.command = command; this.inputStream = inputStream; this.filename = filename; int lastIndex = baseUrl.length() - 1; while (baseUrl.charAt(lastIndex) == '/') lastIndex--; this.baseUrl = baseUrl.substring(0, lastIndex + 1); remotes = new HashMap<String, String>(); projects = new ArrayList<Project>(); plusGroups = new HashSet<String>(); minusGroups = new HashSet<String>(); if (groups == null || groups.length() == 0 || groups.equals("default")) { minusGroups.add("notdefault"); } else { for (String group : groups.split(",")) { if (group.startsWith("-")) minusGroups.add(group.substring(1)); else plusGroups.add(group); } } }
Source:
public ClusterFeature mapRow(ResultSet rs, int rowNum) throws SQLException { ClusterFeature feature = new ClusterFeature(); feature.setVdsGroupId(getGuidDefaultEmpty(rs, "vds_group_id")); feature.setEnabled(rs.getBoolean("is_enabled")); feature.setFeature(rs.getString("feature")); return feature; }

Target:
public ClusterFeature mapRow(ResultSet rs, int rowNum) throws SQLException { ClusterFeature feature = new ClusterFeature(); feature.setFeatureId(getGuidDefaultEmpty(rs, "feature_id")); feature.setFeature(rs.getString("feature")); feature.setDescription(rs.getString("description")); feature.setApplicationMode(ApplicationMode.from(rs.getInt("app_mode"))); feature.setVersion(rs.getString("version")); return feature; }
Source:
public void zoom(boolean zoomIn) { Point cursorDisplayLocation = getDisplay().getCursorLocation(); Point cursorControlLocation = getParent().toControl(cursorDisplayLocation); Rectangle controlBounds = getBounds(); if (!controlBounds.contains(cursorControlLocation.x, controlBounds.y)) { return; } int nameSpace = fTimeProvider.getNameSpace(); int timeSpace = fTimeProvider.getTimeSpace(); int xPos = Math.max(nameSpace, Math.min(nameSpace + timeSpace, cursorControlLocation.x)); long time0 = fTimeProvider.getTime0(); long time1 = fTimeProvider.getTime1(); long interval = time1 - time0; if (interval == 0) { interval = 1; } long newInterval; if (zoomIn) { newInterval = Math.max(Math.round(interval * ZOOM_IN_FACTOR), fTimeProvider.getMinTimeInterval()); } else { newInterval = (long) Math.ceil(interval * ZOOM_OUT_FACTOR); } long center = time0 + Math.round(((double) (xPos - nameSpace) / timeSpace * interval)); long newTime0 = center - Math.round((double) newInterval * (center - time0) / interval); newTime0 = Math.max(fTimeProvider.getMinTime(), Math.min(newTime0, fTimeProvider.getMaxTime() - newInterval)); long newTime1 = newTime0 + newInterval; fTimeProvider.setStartFinishTimeNotify(newTime0, newTime1); }

Target:
public void zoom(boolean zoomIn) { Point cursorDisplayLocation = getDisplay().getCursorLocation(); Point cursorControlLocation = toControl(cursorDisplayLocation); Point cursorParentLocation = getParent().toControl(cursorDisplayLocation); Rectangle controlBounds = getBounds(); if (!controlBounds.contains(cursorParentLocation.x, controlBounds.y)) { return; } int nameSpace = fTimeProvider.getNameSpace(); int timeSpace = fTimeProvider.getTimeSpace(); int xPos = Math.max(nameSpace, Math.min(nameSpace + timeSpace, cursorControlLocation.x)); long time0 = fTimeProvider.getTime0(); long time1 = fTimeProvider.getTime1(); long interval = time1 - time0; if (interval == 0) { interval = 1; } long newInterval; if (zoomIn) { newInterval = Math.max(Math.round(interval * ZOOM_IN_FACTOR), fTimeProvider.getMinTimeInterval()); } else { newInterval = (long) Math.ceil(interval * ZOOM_OUT_FACTOR); } long center = time0 + Math.round(((double) (xPos - nameSpace) / timeSpace * interval)); long newTime0 = center - Math.round((double) newInterval * (center - time0) / interval); newTime0 = Math.max(fTimeProvider.getMinTime(), Math.min(newTime0, fTimeProvider.getMaxTime() - newInterval)); long newTime1 = newTime0 + newInterval; fTimeProvider.setStartFinishTimeNotify(newTime0, newTime1); }
Source:
private Node tryFoldKnownMethods(Node subtree) { checkArgument(subtree.isCall(), subtree); subtree = tryFoldArrayJoin(subtree); if (subtree.isCall()) { subtree = tryToFoldArrayConcat(subtree); checkState(subtree.isCall(), subtree); Node callTarget = checkNotNull(subtree.getFirstChild()); if (NodeUtil.isGet(callTarget)) { if (callTarget.getFirstChild().isQualifiedName()) { switch (callTarget.getFirstChild().getQualifiedName()) { case "Array": return tryFoldKnownArrayMethods(subtree, callTarget); case "Math": if (isASTNormalized()) { return tryFoldKnownMathMethods(subtree, callTarget); } break; default: } } subtree = tryFoldKnownStringMethods(subtree, callTarget); } else if (callTarget.isName()) { subtree = tryFoldKnownNumericMethods(subtree, callTarget); } } return subtree; }

Target:
private Node tryFoldKnownMethods(Node subtree) { checkArgument(subtree.isCall(), subtree); subtree = tryFoldArrayJoin(subtree); if (subtree.isCall()) { subtree = tryToFoldArrayConcat(subtree); checkState(subtree.isCall(), subtree); Node callTarget = checkNotNull(subtree.getFirstChild()); if (NodeUtil.isGet(callTarget)) { if (isASTNormalized() && callTarget.getFirstChild().isQualifiedName()) { switch (callTarget.getFirstChild().getQualifiedName()) { case "Array": return tryFoldKnownArrayMethods(subtree, callTarget); case "Math": return tryFoldKnownMathMethods(subtree, callTarget); default: } } subtree = tryFoldKnownStringMethods(subtree, callTarget); } else if (callTarget.isName()) { subtree = tryFoldKnownNumericMethods(subtree, callTarget); } } return subtree; }
Source:
public Review(List<ReviewFile> files, boolean revievTestFiles) { if (revievTestFiles) { this.files = files; } else { this.files = FluentIterable.from(files) .filter(new Predicate<ReviewFile>() { @Override public boolean apply(ReviewFile file) { return !file.isTestFile(); } }).toList(); } }

Target:
public Review(List<ReviewFile> files, boolean revievTestFiles) { if (revievTestFiles) { this.files = files; } else { this.files = filterOutTestFiles(files); } }
Source:
public PageWriter(DataSink dataSink, DataSize pageFileStripeMaxSize) { this.dataSink = requireNonNull(dataSink, "pageDataSink is null"); this.maxBufferedBytes = requireNonNull(pageFileStripeMaxSize, "pageFileStripeMaxSize is null").toBytes(); bufferedPages = new ArrayList<>(); stripeOffsets = new ArrayList<>(ImmutableList.of(0L)); }

Target:
public PageWriter(DataSink dataSink, DataSize pageFileStripeMaxSize) { this.dataSink = requireNonNull(dataSink, "pageDataSink is null"); this.maxBufferedBytes = requireNonNull(pageFileStripeMaxSize, "pageFileStripeMaxSize is null").toBytes(); bufferedPages = new ArrayList<>(); stripeOffsets = new ArrayList<>(); }
Source:
public void unvoidPatientProgram_shouldTestUnvoidPatientProgram() { PatientProgram patientProgram = pws.getPatientProgram(1); PatientProgram patientProgram1 = pws.voidPatientProgram(patientProgram, "expired"); Date voidDate = patientProgram.getDateVoided(); patientProgram1 = pws.unvoidPatientProgram(patientProgram); assertEquals(patientProgram1.getVoided(), false); for (PatientState state : patientProgram.getStates()) { if (voidDate != null && voidDate.equals(state.getDateVoided())) { assertEquals(state.getVoided(), false); assertNull(state.getVoidedBy()); assertNull(state.getDateVoided()); assertNull(state.getVoidReason()); } } }

Target:
public void unvoidPatientProgram_shouldTestUnvoidPatientProgram() { PatientProgram existingPatientProgram = pws.getPatientProgram(1); PatientProgram existingPatientProgramVoided = pws.voidPatientProgram(existingPatientProgram, "expired"); Date patientProgramDateVoided = existingPatientProgramVoided.getDateVoided(); existingPatientProgramVoided = pws.unvoidPatientProgram(existingPatientProgram); assertEquals(existingPatientProgramVoided.getVoided(), false); for (PatientState state : existingPatientProgram.getStates()) { assertEquals(state.getVoided(), false); if (patientProgramDateVoided != null && patientProgramDateVoided.equals(state.getDateVoided())) { assertNull(state.getVoidedBy()); assertNull(state.getDateVoided()); assertNull(state.getVoidReason()); } } }
Source:
public void toggleStarred(String key, String value) { TaskAttribute taskAttribute = fTaskData.getRoot(); taskAttribute.getAttribute(key).setValue(value); setAttribute(key, value); }

Target:
public void toggleStarred(String key, String value) { if (key != null && value != null) { TaskAttribute taskAttribute = fTaskData.getRoot(); taskAttribute.getAttribute(key).setValue(value); setAttribute(key, value); } }
Source:
public CliShellEnvironmentVariableHandler() { specs.put(SHELL_DEBUG, new String[] {"true", "false"}, "false"); }

Target:
public CliShellEnvironmentVariableHandler() { }
Source:
private Map<Guid, GlusterAsyncTask> updateTasksInCluster(final VDSGroup cluster) { if (!supportsGlusterAsyncTasksFeature(cluster)) { return null; } Map<Guid, GlusterAsyncTask> runningTasks = getProvider().getTaskListForCluster(cluster.getId()); if (runningTasks == null) { return null; } for (Entry<Guid, GlusterAsyncTask> entry : runningTasks.entrySet()) { Guid taskId = entry.getKey(); final GlusterAsyncTask task = entry.getValue(); List<Step> steps = getStepDao().getStepsByExternalId(taskId); if (steps.isEmpty()) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { try { createJobToMonitor(cluster,task); } catch (VdcBLLException e) { log.error("Error creating job for task from CLI", e); } return null; } }); } for (Step step: steps) { if (step.getEndTime() != null) { continue; } String message = getTaskMessage(cluster,step.getStepType(),task); if(message.contains("Total size moved")) { int start = message.lastIndexOf(' ') + 1; int end = message.length() - 1; String sSize = message.substring(start, end); Long size = Long.parseLong(sSize); sSize = SizeConverter.toString(size); StringBuilder tmp = new StringBuilder(message); tmp = tmp.replace(start, end, sSize); message = new String(tmp.toString()); } step.setDescription(message); if (hasTaskCompleted(task)) { step.markStepEnded(task.getStatus()); endStepJob(step); releaseVolumeLock(task.getTaskId()); } else { getJobRepository().updateStep(step); } } } return runningTasks; }

Target:
private Map<Guid, GlusterAsyncTask> updateTasksInCluster(final VDSGroup cluster) { if (!supportsGlusterAsyncTasksFeature(cluster)) { return null; } Map<Guid, GlusterAsyncTask> runningTasks = getProvider().getTaskListForCluster(cluster.getId()); if (runningTasks == null) { return null; } for (Entry<Guid, GlusterAsyncTask> entry : runningTasks.entrySet()) { Guid taskId = entry.getKey(); final GlusterAsyncTask task = entry.getValue(); List<Step> steps = getStepDao().getStepsByExternalId(taskId); if (steps.isEmpty()) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { try { createJobToMonitor(cluster,task); } catch (VdcBLLException e) { log.error("Error creating job for task from CLI", e); } return null; } }); } for (Step step: steps) { if (step.getEndTime() != null) { continue; } step.setDescription(getTaskMessage(cluster,step.getStepType(),task)); if (hasTaskCompleted(task)) { step.markStepEnded(task.getStatus()); endStepJob(step); releaseVolumeLock(task.getTaskId()); } else { getJobRepository().updateStep(step); } } } return runningTasks; }
Source:
private Map<Class<? extends Annotation>, List<ClientListenerInvocation>> findMethods(Object listener) { Map<Class<? extends Annotation>, List<ClientListenerInvocation>> listenerMethodMap = new HashMap<Class<? extends Annotation>, List<ClientListenerInvocation>>(4, 0.99f); for (Method m : listener.getClass().getMethods()) { for (Map.Entry<Class<? extends Annotation>, Class<?>[]> entry : allowedListeners.entrySet()) { Class<? extends Annotation> annotationType = entry.getKey(); Class<?>[] eventTypes = entry.getValue(); if (m.isAnnotationPresent(annotationType)) { testListenerMethodValidity(m, eventTypes, annotationType.getName()); m.setAccessible(true); ClientListenerInvocation invocation = new ClientListenerInvocation(listener, m); List<ClientListenerInvocation> invocables = listenerMethodMap.get(annotationType); if (invocables == null) { invocables = new ArrayList<ClientListenerInvocation>(); listenerMethodMap.put(annotationType, invocables); } invocables.add(invocation); } } } return listenerMethodMap; }

Target:
private Map<Class<? extends Annotation>, List<ClientListenerInvocation>> findMethods(Object listener) { Map<Class<? extends Annotation>, List<ClientListenerInvocation>> listenerMethodMap = new HashMap<Class<? extends Annotation>, List<ClientListenerInvocation>>(4, 0.99f); for (Method m : listener.getClass().getMethods()) { for (Map.Entry<Class<? extends Annotation>, Class<?>[]> entry : allowedListeners.entrySet()) { Class<? extends Annotation> annotationType = entry.getKey(); Class<?>[] eventTypes = entry.getValue(); if (m.isAnnotationPresent(annotationType)) { testListenerMethodValidity(m, eventTypes, annotationType.getName()); SecurityActions.setAccessible(m); ClientListenerInvocation invocation = new ClientListenerInvocation(listener, m); List<ClientListenerInvocation> invocables = listenerMethodMap.get(annotationType); if (invocables == null) { invocables = new ArrayList<ClientListenerInvocation>(); listenerMethodMap.put(annotationType, invocables); } invocables.add(invocation); } } } return listenerMethodMap; }
Source:
public void createControl(Composite parent) { super.createControl(parent); Composite optionPane = (Composite) this.getControl(); optionPane.setLayout(new GridLayout()); optionPane.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, true)); final SelectionListener linkedListener = new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { getBatchWizard().setLinked(((Button) e.widget).getSelection()); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }; fLink = new Button(optionPane, SWT.RADIO); fLink.setText("Link traces (Recommended)"); fLink.setSelection(true); fLink.setLayoutData(new GridData()); fLink.addSelectionListener(linkedListener); fCopy = new Button(optionPane, SWT.RADIO); fCopy.setText("Copy traces"); fCopy.setLayoutData(new GridData()); fCopy.addSelectionListener(linkedListener); fOverwrite = new Button(optionPane, SWT.CHECK); fOverwrite.setText("Overwrite existing traces (recommended)"); fOverwrite.setLayoutData(new GridData()); fOverwrite.setSelection(true); fOverwrite.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { getBatchWizard().setOverwrite(((Button) e.widget).getSelection()); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); createDestinationGroup(optionPane); getBatchWizard().setResourcePath(getContainerFullPath()); }

Target:
public void createControl(Composite parent) { super.createControl(parent); init(); }
Source:
public static FStringsGrammar createGrammar(String s) { while (s.contains("\\N{")) { int pos = s.indexOf("\\N{") + 3; int posLength = s.substring(0, pos).length(); s = s.replace(s.charAt(pos), '_'); String s_ = s.substring(pos); pos = s_.indexOf("}"); s = s.replace(s.charAt(pos + posLength), '_'); } FastCharStream in = new FastCharStream(s.toCharArray()); FStringsGrammar fStringsGrammar = new FStringsGrammar(in); return fStringsGrammar; }

Target:
public static FStringsGrammar createGrammar(String s) { char[] c = s.toCharArray(); for (int i = 0, z = 0; i < c.length; i++) { if (c[i] == '\\' && i + 2 < c.length && c[i + 1] == 'N' && c[i + 2] == '{') { c[i + 2] = '_'; i += 2; z = i + 1; for (; z < c.length; z++) { if (c[z] == '}') { c[z] = '_'; break; } } } } FastCharStream in = new FastCharStream(c); FStringsGrammar fStringsGrammar = new FStringsGrammar(in); return fStringsGrammar; }
Source:
public Object call() throws Exception { if (request == null) { return null; } try { LOG.info("starting plan change "); LogicalPlan lp = plan.cloneLogicalPlan(); PlanModifier pm = new PlanModifier(lp); pm.applyDagChangeSet(request); lp.validate(); LOG.info("validated logical plan, now making actual change"); pm = new PlanModifier(plan); pm.applyDagChangeSet(request); LOG.info("plan change done"); return null; } finally { plan.clearPendingChangeRequest(); } }

Target:
public Object call() throws Exception { if (request == null) { return null; } try { LOG.info("Starting logical plan change "); LogicalPlan lp = (LogicalPlan)SerializationUtils.clone(plan.getLogicalPlan()); PlanModifier pm = new PlanModifier(lp); pm.applyDagChangeSet(request); lp.validate(); LOG.info("Validated logical plan, now making actual change"); pm = new PlanModifier(plan); pm.applyDagChangeSet(request); LOG.info("plan change done"); return null; } finally { plan.setPendingDagChangeRequest(null); } }
Source:
private static <T extends SpecificRecord>JavaRDD<T> parseResultToAvro(JavaRDD<? extends Result> source, OafEntityToAvroConverter<Result, T> entityConverter) { return source.map(x -> entityConverter.convert(x)).filter(x -> x != null); }

Target:
private static <T extends SpecificRecord>JavaRDD<T> parseResultToAvro(JavaRDD<? extends Result> source, OafEntityToAvroConverter<Result, T> entityConverter) { return source.map(entityConverter::convert).filter(Objects::nonNull); }
Source:
void setResourceInformationUnSafe(Object resource, String resourceName, long amount) { if (!isYarnResourceTypesAvailable) { LOG.info("Will not request extended resource because the underlying YARN does not support it.", resourceName); return; } try { resourceSetResourceInformationMethod.invoke( resource, resourceName, resourceInformationNewInstanceMethod.invoke(null, resourceName, amount)); } catch (Exception e) { LOG.error("Error in setting the external resource {}, will not request it to YARN. {}", resourceName, e); } }

Target:
void setResourceInformationUnSafe(Object resource, String resourceName, long amount) { if (!isYarnResourceTypesAvailable) { LOG.info("Will not request extended resource because the used YARN version does not support it.", resourceName); return; } try { resourceSetResourceInformationMethod.invoke( resource, resourceName, resourceInformationNewInstanceMethod.invoke(null, resourceName, amount)); } catch (Exception e) { LOG.warn("Error in setting the external resource {}. Will not request this resource from YARN.", resourceName, e); } }
Source:
public String getLabel(VDomainModelReference reference) { final String path = getEcorePath(); if (path == null) { } final String firstPath = path.split("/")[1]; final String editPath = firstPath + ".edit/plugin.properties"; final IResource member = ResourcesPlugin.getWorkspace().getRoot().findMember(editPath); if (member.exists()) { final File file = member.getLocation().toFile(); final Properties p = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream(file); p.load(fis); } catch (final FileNotFoundException ex) { ex.printStackTrace(); } catch (final IOException ex) { ex.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch (final IOException ex) { ex.printStackTrace(); } } } final EStructuralFeature feature = getEStructuralFeature(reference); if (feature == null) { return null; } final EClass eClass = feature.getEContainingClass(); final String key = String.format(DISPLAY_NAME, eClass.getName(), feature.getName()); final String result = p.getProperty(key); if (result == null) { return feature.getName(); } return result; } final EStructuralFeature feature = getEStructuralFeature(reference); return feature.getName(); }

Target:
public String getLabel(VDomainModelReference reference) { final String path = getEcorePath(); if (path == null) { try { final BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext(); final ServiceReference<EMFFormsLabelProvider> serviceReference = bundleContext .getServiceReference(EMFFormsLabelProvider.class); final EMFFormsLabelProvider labelProvider = bundleContext.getService(serviceReference); final IObservableValue observableValue = labelProvider.getDisplayName(reference); final String result = (String) observableValue.getValue(); observableValue.dispose(); bundleContext.ungetService(serviceReference); return result; } catch (final NoLabelFoundException ex) { ex.printStackTrace(); } } final String firstPath = path.split("/")[1]; final String editPath = firstPath + ".edit/plugin.properties"; final IResource member = ResourcesPlugin.getWorkspace().getRoot().findMember(editPath); if (member.exists()) { final File file = member.getLocation().toFile(); final Properties p = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream(file); p.load(fis); } catch (final FileNotFoundException ex) { ex.printStackTrace(); } catch (final IOException ex) { ex.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch (final IOException ex) { ex.printStackTrace(); } } } final EStructuralFeature feature = getEStructuralFeature(reference); if (feature == null) { return null; } final EClass eClass = feature.getEContainingClass(); final String key = String.format(DISPLAY_NAME, eClass.getName(), feature.getName()); final String result = p.getProperty(key); if (result == null) { return feature.getName(); } return result; } final EStructuralFeature feature = getEStructuralFeature(reference); return feature.getName(); }
Source:
private static String resolveKafkaService() { final StringBuilder sb = new StringBuilder() .append(resolve(KAFKA_SERVICE_HOST)) .append(":") .append(resolve(KAFKA_SERVICE_PORT)); return sb.toString(); }

Target:
private static String resolveKafkaService() { return new StringBuilder() .append(resolve(KAFKA_SERVICE_HOST)) .append(":") .append(resolve(KAFKA_SERVICE_PORT)).toString(); }
Source:
private void restoreOrInit(PageStoreOptions options) { Preconditions.checkState(mState.get() == READ_ONLY); if (!restore(options)) { try { mPageStore.close(); try (LockResource r = new LockResource(mMetaLock.writeLock())) { mMetaStore.reset(); } PageStore.initialize(options); mPageStore = PageStore.create(options); } catch (Exception e) { LOG.error("Failed to clean up PageStore", e); return; } } mState.set(READ_WRITE); Metrics.STATE.inc(); }

Target:
private void restoreOrInit(PageStoreOptions options) { synchronized (LocalCacheManager.class) { Preconditions.checkState(mState.get() == READ_ONLY); if (!restore(options)) { try (LockResource r = new LockResource(mMetaLock.writeLock())) { mMetaStore.reset(); } try { mPageStore.close(); mPageStore = PageStore.create(options); } catch (Exception e) { LOG.error("Failed to create a new PageStore. Cache is NOT_IN_USE: ", e); mState.set(NOT_IN_USE); Metrics.STATE.dec(); return; } } LOG.info("Cache is in READ_WRITE."); mState.set(READ_WRITE); Metrics.STATE.inc(); } }
Source:
void shutdown() { executor.shutdown(); shutdown = true; }

Target:
void shutdown() { shutdown = true; executor.shutdown(); }
Source:
public void testReadWriteJimfs(String extension, boolean gzipped) throws IOException { final Path jmfsRoot = inMemoryFileSystem.getRootDirectories().iterator().next(); final Path tmp = Files.createTempFile(jmfsRoot, "test", extension); final String expected = "lorem ipswitch, nantucket, bucket"; try( final Writer out = IOUtil.openFileForBufferedWriting(tmp)){ out.write(expected); } try( final InputStream in = new BufferedInputStream(Files.newInputStream(tmp))){ Assert.assertEquals(IOUtil.isGZIPInputStream(in), gzipped); } try( final BufferedReader in = IOUtil.openFileForBufferedReading(tmp)){ final String actual = in.readLine(); Assert.assertEquals(actual, expected); } }

Target:
public void testReadWriteJimfs(String extension, boolean gzipped) throws IOException { final Path jmfsRoot = inMemoryFileSystem.getRootDirectories().iterator().next(); final Path tmp = Files.createTempFile(jmfsRoot, "test", extension); final String expected = "lorem ipswitch, nantucket, bucket"; try (Writer out = IOUtil.openFileForBufferedWriting(tmp)){ out.write(expected); } try (InputStream in = new BufferedInputStream(Files.newInputStream(tmp))){ Assert.assertEquals(IOUtil.isGZIPInputStream(in), gzipped); } try (BufferedReader in = IOUtil.openFileForBufferedReading(tmp)){ final String actual = in.readLine(); Assert.assertEquals(actual, expected); } }
Source:
private boolean maybeCompleted(long time){ if (time >= actionTime && type == TransactionTypeNormal) { return true; } else { return false; } }

Target:
private boolean maybeCompleted(long time){ return shouldAction(time) && type == TransactionTypeNormal; }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { NamedElement element = refactoring.getContextObject(); if (element != null) { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); List<Issue> issues = validator.validate(element.eResource(), CheckMode.NORMAL_AND_FAST, CancelIndicator.NullImpl); Stream<Issue> errors = issues.stream().filter(issue -> issue.getSeverity() == Severity.ERROR); String message = ""; if (errors.count() > 0) { message = "File contains errors!!\n\n"; } message += "Please enter new name: "; InputDialog dialog = new InputDialog(window.getShell(), "Rename.." , message, element.getName(), new NameUniquenessValidator(element)); if (dialog.open() == Window.OK) { String newName = dialog.getValue(); if (newName != null) { ((RenameRefactoring)refactoring).setNewName(newName); refactoring.execute(); } } } return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { NamedElement element = refactoring.getContextObject(); if (element != null) { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); List<Issue> issues = validator.validate(element.eResource(), CheckMode.NORMAL_AND_FAST, CancelIndicator.NullImpl); Stream<Issue> errors = issues.stream().filter(issue -> issue.getSeverity() == Severity.ERROR); RenameDialog dialog = new RenameDialog(window.getShell(), "Rename..", "Please enter new name: ", element.getName(), new NameUniquenessValidator(element), errors.count() > 0); if (dialog.open() == Window.OK) { String newName = dialog.getNewName(); if (newName != null) { ((RenameRefactoring) refactoring).setNewName(newName); refactoring.execute(); } } } return null; }
Source:
public void constructorForJsonModelRunBindsParametersCorrectly() throws Exception { JsonModelDisease expectedDisease = new JsonModelDisease(); GeoJsonDiseaseOccurrenceFeatureCollection expectedOccurrences = new GeoJsonDiseaseOccurrenceFeatureCollection(); Map<Integer, Integer> expectedExtents = new HashMap<>(); JsonModelRun result = new JsonModelRun( expectedDisease, expectedOccurrences, expectedExtents); assertThat(result.getDisease()).isEqualTo(expectedDisease); assertThat(result.getOccurrences()).isEqualTo(expectedOccurrences); assertThat(result.getExtents()).isEqualTo(expectedExtents); }

Target:
public void constructorForJsonModelRunBindsParametersCorrectly() throws Exception { JsonModelDisease expectedDisease = new JsonModelDisease(); GeoJsonDiseaseOccurrenceFeatureCollection expectedOccurrences = new GeoJsonDiseaseOccurrenceFeatureCollection(); Map<Integer, Integer> expectedExtentWeightings = new HashMap<>(); JsonModelRun result = new JsonModelRun( expectedDisease, expectedOccurrences, expectedExtentWeightings); assertThat(result.getDisease()).isEqualTo(expectedDisease); assertThat(result.getOccurrences()).isEqualTo(expectedOccurrences); assertThat(result.getExtentWeightings()).isEqualTo(expectedExtentWeightings); }
Source:
public <T extends OmiseList, S extends Model, R extends Request<S>> T sendRequest(R request, TypeReference<T> typeReference) throws IOException, OmiseException { if (requester == null) return null; return requester.sendRequest(request, typeReference); }

Target:
public <T extends OmiseList, R extends Request<T>> T sendRequest(R request, TypeReference<T> typeReference) throws IOException, OmiseException { if (requester == null) return null; return requester.sendRequest(request, typeReference); }
Source:
public static boolean filterSameDescriptor(IDataChartDescriptor<?, ?> desc, @Nullable IDataChartDescriptor<?, ?> filter) { if (filter != null) { if (desc.getClass() != filter.getClass()) { return false; } } return true; }

Target:
static boolean filterSameDescriptor(IDataChartDescriptor<?, ?> desc, @Nullable IDataChartDescriptor<?, ?> filter) { if (filter != null) { if (desc.getClass() != filter.getClass()) { return false; } } return true; }
Source:
public void dropPartitionFromStorageByFilter(LensSessionHandle sessionid, String cubeTableName, String storageName, String filter) throws LensException { try { acquire(sessionid); String tableName = MetastoreUtil.getStorageTableName(cubeTableName, Storage.getPrefix(storageName)); List<Partition> partitions = getClient(sessionid).getPartitionsByFilter( tableName, filter); for (Partition part : partitions) { Map<String, Date> timeSpec = new HashMap<String, Date>(); Map<String, String> nonTimeSpec = new HashMap<String, String>(); UpdatePeriod updatePeriod = populatePartSpec(part, timeSpec, nonTimeSpec); getClient(sessionid).dropPartition(cubeTableName, storageName, timeSpec, nonTimeSpec, updatePeriod); } LOG.info("Dropped partition for cube table: " + cubeTableName + " storage: " + storageName + " by filter:" + filter); } catch (HiveException exc) { if (exc.getCause() instanceof NoSuchObjectException) { return; } throw new LensException(exc); } finally { release(sessionid); } }

Target:
public void dropPartitionFromStorageByFilter(LensSessionHandle sessionid, String cubeTableName, String storageName, String filter) throws LensException { try { acquire(sessionid); String tableName = MetastoreUtil.getStorageTableName(cubeTableName, Storage.getPrefix(storageName)); List<Partition> partitions = getClient(sessionid).getPartitionsByFilter( tableName, filter); for (Partition part : partitions) { try { Map<String, Date> timeSpec = new HashMap<String, Date>(); Map<String, String> nonTimeSpec = new HashMap<String, String>(); UpdatePeriod updatePeriod = populatePartSpec(part, timeSpec, nonTimeSpec); getClient(sessionid).dropPartition(cubeTableName, storageName, timeSpec, nonTimeSpec, updatePeriod); } catch (HiveException e) { if (e.getCause() instanceof NoSuchObjectException) { continue; } else { throw new LensException(e); } } } LOG.info("Dropped partition for cube table: " + cubeTableName + " storage: " + storageName + " by filter:" + filter); } catch (HiveException exc) { throw new LensException(exc); } finally { release(sessionid); } }
Source:
private void updatePassword(String password) { EditPostRepository editPostRepository = getEditPostRepository(); if (editPostRepository == null) return; String trimmedPassword = password.trim(); Boolean isNewPasswordBlank = trimmedPassword.isEmpty(); String previousPassword = editPostRepository.getPassword(); Boolean isPreviousPasswordBlank = previousPassword.isEmpty() || previousPassword.trim().isEmpty(); if (isNewPasswordBlank && isPreviousPasswordBlank) return; String newPassword = isNewPasswordBlank ? trimmedPassword : password; editPostRepository.updateAsync(postModel -> { postModel.setPassword(newPassword); return true; }, (postModel, result) -> { if (result == UpdatePostResult.Updated.INSTANCE) { mPasswordTextView.setText(newPassword); } return null; }); }

Target:
private void updatePassword(String password) { EditPostRepository editPostRepository = getEditPostRepository(); if (editPostRepository == null) return; String trimmedPassword = password.trim(); Boolean isNewPasswordBlank = trimmedPassword.isEmpty(); String previousPassword = editPostRepository.getPassword(); Boolean isPreviousPasswordBlank = previousPassword.trim().isEmpty(); if (isNewPasswordBlank && isPreviousPasswordBlank) return; String newPassword = isNewPasswordBlank ? trimmedPassword : password; editPostRepository.updateAsync(postModel -> { postModel.setPassword(newPassword); return true; }, (postModel, result) -> { if (result == UpdatePostResult.Updated.INSTANCE) { mPasswordTextView.setText(newPassword); } return null; }); }
Source:
public void transition(TaskImpl task, TaskEvent event) { LOG.info("Scheduling a redundant attempt for task " + task.taskId); task.counters.findCounter(TaskCounter.NUM_SPECULATIONS).increment(1); TaskAttempt earliestUnfinishedAttempt = null; for (TaskAttempt ta : task.attempts.values()) { if (!ta.isFinished() && task.commitAttempt == null) { earliestUnfinishedAttempt = ta; task.nodesWithRunningAttempts.add(ta.getNodeId()); } else { if (TaskAttemptState.SUCCEEDED.equals(ta.getState())) { LOG.info("Ignore speculation scheduling for task since it has succeeded with attempt {}.", task.getTaskId(), ta.getID()); return; } } } if (earliestUnfinishedAttempt == null) { LOG.info("Ignore speculation scheduling since there is no running attempt on task {}.", task.getTaskId()); return; } task.addAndScheduleAttempt(earliestUnfinishedAttempt.getID()); }

Target:
public void transition(TaskImpl task, TaskEvent event) { LOG.info("Scheduling a redundant attempt for task " + task.taskId); task.counters.findCounter(TaskCounter.NUM_SPECULATIONS).increment(1); TaskAttempt earliestUnfinishedAttempt = null; for (TaskAttempt ta : task.attempts.values()) { if (!ta.isFinished()) { earliestUnfinishedAttempt = ta; task.nodesWithRunningAttempts.add(ta.getNodeId()); } else { if (TaskAttemptState.SUCCEEDED.equals(ta.getState())) { LOG.info("Ignore speculation scheduling for task since it has succeeded with attempt {}.", task.getTaskId(), ta.getID()); return; } } } if (earliestUnfinishedAttempt == null) { LOG.info("Ignore speculation scheduling since there is no running attempt on task {}.", task.getTaskId()); return; } if (task.commitAttempt != null) { LOG.info("Ignore speculation scheduling for task since commit has started with commitAttempt {}.", task.getTaskId(), task.commitAttempt); return; } task.addAndScheduleAttempt(earliestUnfinishedAttempt.getID()); }