auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void visit(final ElkGraphElement element) { <START> if (element instanceof ElkNode) { <END> if (applyToFullGraphFirst) { ElkUtil.applyVisitors((ElkNode) element, graphVisitors.toArray(new IGraphElementVisitor[graphVisitors.size()])); } else { for (IGraphElementVisitor graphVisitor : graphVisitors) { graphVisitor.visit(element); } } } }</code><technical_language>is this done for nodes? IGraphElementVisitors visit graph elements, nodes</technical_language>

Target:
public void visit(final ElkGraphElement element) { if (applyToFullGraphFirst) { if (element.eContainer() == null && element instanceof ElkNode) { ElkUtil.applyVisitors((ElkNode) element, graphVisitors.toArray(new IGraphElementVisitor[graphVisitors.size()])); } } else { for (IGraphElementVisitor graphVisitor : graphVisitors) { graphVisitor.visit(element); } } }
Source:
<code>public void reportCompleted() { vmPoolMonitor.startingVmCompleted(getVmId(), "reportCompleted"); super.reportCompleted(); <START> } <END></code><technical_language>improvements: 1. checking if vm is part of a pool calling VmPoolMonitor#startingVmCompleted 2. moving new calls executed statement (rather statement) of methods</technical_language>

Target:
public void reportCompleted() { super.reportCompleted(); if (getVm().getVmPoolId() != null) { vmPoolMonitor.startingVmCompleted(getVmId(), "reportCompleted"); } }
Source:
<code>public Ticker getTicker(CurrencyPair currencyPair, Object... args) throws IOException { String deribitInstrumentName = DeribitAdapters.adaptInstrumentName(currencyPair, args); DeribitTicker deribitTicker; try { deribitTicker = super.getDeribitTicker(deribitInstrumentName); } catch (DeribitException ex) { <START> throw new ExchangeException(ex); <END> } return DeribitAdapters.adaptTicker(deribitTicker); }</code><technical_language>this is a step practices: <LINK_0> DeribitErrorAdapter in cased enhance error mapping in future try catch in a obscure main flow, for eg.: try { String deribitInstrumentName = DeribitAdapters.adaptInstrumentName(currencyPair, args); DeribitTicker deribitTicker = super.getDeribitTicker(deribitInstrumentName); return DeribitAdapters.adaptTicker(deribitTicker); } catch (DeribitException ex) { throw new DeribitAdapters.adapt(ex); }</technical_language>

Target:
public Ticker getTicker(CurrencyPair currencyPair, Object... args) throws IOException { String deribitInstrumentName = DeribitAdapters.adaptInstrumentName(currencyPair, args); DeribitTicker deribitTicker; try { deribitTicker = super.getDeribitTicker(deribitInstrumentName); } catch (DeribitException ex) { throw DeribitAdapters.adapt(ex); } return DeribitAdapters.adaptTicker(deribitTicker); }
Source:
<code>public List<Double> sample(final RandomGenerator rng, final Function<Double, Double> logPDF, final int numSamples, final int numBurnIn) { Utils.nonNull(rng); Utils.nonNull(logPDF); ParamUtils.isPositive(numSamples, "Number of samples must be positive."); ParamUtils.isPositive(numBurnIn, "Number of burn-in samples must be positive."); <START> if (numSamples < numBurnIn) { <END> throw new IllegalArgumentException("Number of examples must be greater than number of burn-in samples."); } final List<Double> samples = new ArrayList<>(numSamples); for (int i = 0; i < numSamples; i++) { xCurrent = sample(rng, logPDF); if (i > numBurnIn) { samples.add(xCurrent); } } return samples; }</code><technical_language>Utils.validateArg(numBurnIn <= numSamples. . .)</technical_language>

Target:
public List<Double> sample(final RandomGenerator rng, final Function<Double, Double> logPDF, final int numSamples, final int numBurnIn) { Utils.nonNull(rng); Utils.nonNull(logPDF); ParamUtils.isPositive(numSamples, "Number of samples must be positive."); ParamUtils.isPositiveOrZero(numBurnIn, "Number of burn-in samples must be non-negative."); Utils.validateArg(numBurnIn < numSamples, "Number of samples must be greater than number of burn-in samples."); final List<Double> samples = new ArrayList<>(numSamples); for (int i = 0; i < numSamples; i++) { xCurrent = sample(rng, logPDF); if (i > numBurnIn) { samples.add(xCurrent); } } return samples; }
Source:
<code>private List<String> deserializeMixins(JsonObject configJson) { List<String> mixins = new ArrayList<>(); <START> JsonArray mixinsFromJson = configJson.get("mixinTypes") == null ? null : configJson.get("mixinTypes").getAsJsonArray(); <END> if (mixinsFromJson != null) { for (JsonElement jsonElement : mixinsFromJson) { mixins.add(jsonElement.getAsString()); } } return mixins; }</code><technical_language>mixinTypes :( Change please mixins</technical_language>

Target:
private List<String> deserializeMixins(JsonObject configJson) { JsonArray mixinsFromJson = configJson.get("mixins") == null ? null : configJson.get("mixins").getAsJsonArray(); if (mixinsFromJson == null) { return Collections.emptyList(); } List<String> mixins = new ArrayList<>(mixinsFromJson.size()); for (JsonElement jsonElement : mixinsFromJson) { mixins.add(jsonElement.getAsString()); } return mixins; }
Source:
<code>public ArrayList<String> getMpTermIds() { <START> return mpTermIds; <END> }</code><technical_language>this type List for consistency</technical_language>

Target:
public List<String> getMpTermIds() { return mpTermIds; }
Source:
<code>private List<ParserResult> parseFiles(final AbstractBuild<?, ?> build, final PluginLogger logger) throws IOException, InterruptedException { List<ParserResult> results = Lists.newArrayList(); for (ParserConfiguration configuration : getParserConfigurations()) { String filePattern = configuration.getPattern(); String parserName = configuration.getParserName(); <START> final int resolveDepth = 10; <END> final Map<String,String> buildParameterMap = build.getBuildVariables(); for(int i = 0; i < resolveDepth ; i++) { String old = filePattern; filePattern = Util.replaceMacro(filePattern, buildParameterMap); if (old == filePattern) { break; } } logger.log("Parsing warnings in files '" + filePattern + "' with parser " + parserName); FilesParser parser = new FilesParser(PLUGIN_NAME, filePattern, new FileWarningsParser(ParserRegistry.getParsers(parserName), getDefaultEncoding(), getIncludePattern(), getExcludePattern()), shouldDetectModules(), isMavenBuild(build), canResolveRelativePaths()); ParserResult project = build.getWorkspace().act(parser); logger.logLines(project.getLogMessages()); returnIfCanceled(); results.add(annotate(build, project, configuration.getParserName())); } return results; }</code><technical_language>is this needed 10 times</technical_language>

Target:
private List<ParserResult> parseFiles(final AbstractBuild<?, ?> build, final PluginLogger logger) throws IOException, InterruptedException { List<ParserResult> results = Lists.newArrayList(); for (ParserConfiguration configuration : getParserConfigurations()) { String filePattern = configuration.getPattern(); String parserName = configuration.getParserName(); final int resolveDepth = 10; final Map<String,String> buildParameterMap = build.getBuildVariables(); for(int i = 0; i < resolveDepth ; i++) { String old = filePattern; filePattern = Util.replaceMacro(filePattern, buildParameterMap); if (old.equals(filePattern)) { break; } } logger.log("Parsing warnings in files '" + filePattern + "' with parser " + parserName); FilesParser parser = new FilesParser(PLUGIN_NAME, filePattern, new FileWarningsParser(ParserRegistry.getParsers(parserName), getDefaultEncoding(), getIncludePattern(), getExcludePattern()), shouldDetectModules(), isMavenBuild(build), canResolveRelativePaths()); ParserResult project = build.getWorkspace().act(parser); logger.logLines(project.getLogMessages()); returnIfCanceled(); results.add(annotate(build, project, configuration.getParserName())); } return results; }
Source:
<code>protected void allowAccess(long secretId, long groupId) { dslContext .insertInto(ACCESSGRANTS) <START> .set(ACCESSGRANTS.SECRETID, (int) secretId) <END> .set(ACCESSGRANTS.GROUPID, (int) groupId) .execute(); }</code><technical_language>Math.toIntExact(secretId)</technical_language>

Target:
protected void allowAccess(long secretId, long groupId) { dslContext .insertInto(ACCESSGRANTS) .set(ACCESSGRANTS.SECRETID, Math.toIntExact(secretId)) .set(ACCESSGRANTS.GROUPID, Math.toIntExact(groupId)) .execute(); }
Source:
<code>default Seq<Tuple2<T, T>> innerSelfJoin(BiPredicate<? super T, ? super T> predicate) { List<? extends T> list = toList(); return seq(list).flatMap(t -> seq(list) .filter(u -> predicate.test(t, u)) .map(u -> tuple(t, u))); <START> } <END></code><technical_language>Hmm, I if if this method delegates existing innerJoin() method, start optimising joins in a task..</technical_language>

Target:
default Seq<Tuple2<T, T>> innerSelfJoin(BiPredicate<? super T, ? super T> predicate) { List<? extends T> list = toList(); return seq(list).innerJoin(seq(list), predicate); }
Source:
<code>protected String[][] formatTableContents() { final String [][] formatArray = new String[this.tapeList.size()][]; int i = 0; for (final Tape tape : this.tapeList) { final String bucketArray = new String[this.columnCount]; bucketArray[0] = nullGuard(tape.getBarCode()); bucketArray[1] = nullGuardToString(tape.getId()); bucketArray[2] = nullGuardToString(tape.getState()); <START> final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); <END> DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); bucketArray[3] = nullGuardToDate(tape.getLastModified(),DATE_FORMAT); bucketArray[4] = nullGuardToString(tape.getAvailableRawCapacity()); bucketArray[5] = nullGuardToString(tape.getBucketId()); bucketArray[6] = nullGuardToString(tape.getAssignedToStorageDomain()); formatArray[i++] = (bucketArray); } return formatArray; }</code><technical_language>Move date format a private static final need instance of formatter</technical_language>

Target:
protected String[][] formatTableContents() { final String [][] formatArray = new String[this.tapeList.size()][]; int i = 0; for (final Tape tape : this.tapeList) { final String bucketArray = new String[this.columnCount]; bucketArray[0] = nullGuard(tape.getBarCode()); bucketArray[1] = nullGuardToString(tape.getId()); bucketArray[2] = nullGuardToString(tape.getState()); bucketArray[3] = nullGuardToDate(tape.getLastModified(),DATE_FORMAT); bucketArray[4] = nullGuardToString(tape.getAvailableRawCapacity()); bucketArray[5] = nullGuardToString(tape.getBucketId()); bucketArray[6] = nullGuardToString(tape.getAssignedToStorageDomain()); formatArray[i++] = (bucketArray); } return formatArray; }
Source:
<code><START> public RegionNormalizerWorkQueue() { <END> delegate = new LinkedHashSet<>(); takeLock = new ReentrantLock(); notEmpty = takeLock.newCondition(); putLock = new ReentrantLock(); }</code><technical_language>Local this package? If so, remove public</technical_language>

Target:
RegionNormalizerWorkQueue() { delegate = new LinkedHashSet<>(); takeLock = new ReentrantLock(); notEmpty = takeLock.newCondition(); putLock = new ReentrantLock(); }
Source:
<code>protected void setQcowCompatForSnapshot(DiskImage snapshot, DiskImage volInfo) { if (snapshot.getVolumeFormat().equals(VolumeFormat.COW)) { try { <START> if (volInfo == null) { <END> volInfo = getVolumeInfo(snapshot.getStoragePoolId(), getParameters().getStorageDomainId(), snapshot.getId(), snapshot.getImageId()); } if (volInfo != null) { setQcowCompatByQemuImageInfo(snapshot.getStoragePoolId(), snapshot.getId(), snapshot.getImageId(), getParameters().getStorageDomainId(), snapshot); } imageDao.update(snapshot.getImage()); } catch (EngineException e) { log.error("Unable to update the image info for image '{}' (image group: '{}') on domain '{}'", snapshot.getImageId(), snapshot.getId(), getParameters().getStorageDomainId()); } } }</code><technical_language>I messing parameters references, please extract a local variable</technical_language>

Target:
protected void setQcowCompatForSnapshot(DiskImage snapshot, DiskImage volInfo) { DiskImage info = volInfo; if (snapshot.getVolumeFormat().equals(VolumeFormat.COW)) { try { if (info == null) { info = getVolumeInfo(snapshot.getStoragePoolId(), getParameters().getStorageDomainId(), snapshot.getId(), snapshot.getImageId()); } if (info != null) { setQcowCompatByQemuImageInfo(snapshot.getStoragePoolId(), snapshot.getId(), snapshot.getImageId(), getParameters().getStorageDomainId(), snapshot); } imageDao.update(snapshot.getImage()); } catch (EngineException e) { log.error("Unable to update the image info for image '{}' (image group: '{}') on domain '{}'", snapshot.getImageId(), snapshot.getId(), getParameters().getStorageDomainId()); } } }
Source:
<code>private void doTest(StreamDefinition routerDefinition) throws InterruptedException { assertEquals(0, streamRepository.count()); streamDeployer.save(routerDefinition); deploy(routerDefinition); <START> Thread.sleep(1000); <END> assertEquals(1, streamRepository.count()); assertModuleRequest("router", false); final Module module = getModule("router", 0); MessageBus bus = module.getComponent(MessageBus.class); QueueChannel fooChannel = new QueueChannel(); QueueChannel barChannel = new QueueChannel(); queues.add(queueRoute); queues.add(queueFoo); bus.bindConsumer(queueFoo, fooChannel, Collections.singletonList(MediaType.ALL), true); queues.add(queueBar); bus.bindConsumer(queueBar, barChannel, Collections.singletonList(MediaType.ALL), true); DirectChannel testChannel = new DirectChannel(); bus.bindProducer(queueRoute, testChannel, true); testChannel.send(MessageBuilder.withPayload("a").build()); testChannel.send(MessageBuilder.withPayload("b").build()); final Message<?> fooMessage = fooChannel.receive(10000); final Message<?> barMessage = barChannel.receive(10000); assertEquals("a", fooMessage.getPayload()); assertEquals("b", barMessage.getPayload()); bus.unbindProducer(queueRoute, testChannel); bus.unbindConsumer(queueFoo, fooChannel); bus.unbindConsumer(queueBar, barChannel); }</code><technical_language>this sleep added</technical_language>

Target:
private void doTest(StreamDefinition routerDefinition) throws InterruptedException { assertEquals(0, streamRepository.count()); streamDeployer.save(routerDefinition); deploy(routerDefinition); Thread.sleep(1000); assertEquals(1, streamRepository.count()); assertModuleRequest("router", false); final Module module = getModule("router", 0); MessageBus bus = module.getComponent(MessageBus.class); QueueChannel fooChannel = new QueueChannel(); QueueChannel barChannel = new QueueChannel(); bus.bindConsumer(queueFoo, fooChannel, Collections.singletonList(MediaType.ALL), true); bus.bindConsumer(queueBar, barChannel, Collections.singletonList(MediaType.ALL), true); DirectChannel testChannel = new DirectChannel(); bus.bindProducer(queueRoute, testChannel, true); testChannel.send(MessageBuilder.withPayload("a").build()); testChannel.send(MessageBuilder.withPayload("b").build()); final Message<?> fooMessage = fooChannel.receive(10000); final Message<?> barMessage = barChannel.receive(10000); assertEquals("a", fooMessage.getPayload()); assertEquals("b", barMessage.getPayload()); bus.unbindProducer(queueRoute, testChannel); bus.unbindConsumer(queueFoo, fooChannel); bus.unbindConsumer(queueBar, barChannel); }
Source:
<code>private void optimizeConsecutiveExitWhen(ImExitwhen lookback, ImExitwhen element) { <START> lookback.getCondition().replaceBy(JassIm.ImOperatorCall(WurstOperator.OR, JassIm.ImExprs(lookback.getCondition().copy(), element.getCondition().copy()))); <END> element.replaceBy(JassIm.ImNull()); }</code><technical_language>copy avoided here, if remove current parent</technical_language>

Target:
private void optimizeConsecutiveExitWhen(ImExitwhen lookback, ImExitwhen element) { element.getCondition().setParent(null); lookback.setCondition(JassIm.ImOperatorCall(WurstOperator.OR, JassIm.ImExprs(lookback.getCondition().copy(), element.getCondition()))); element.replaceBy(JassIm.ImNull()); totalRewrites++; }
Source:
<code>private void postConstruct() { classToMapperMap.put(EventMessageDataResponseDto.class, this.managementMapper); classToMapperMap.put(MeterReadsResponseDto.class, this.monitoringMapper); classToMapperMap.put(MeterReadsGasResponseDto.class, this.monitoringMapper); classToMapperMap.put(ActionResponseDto.class, this.commonMapper); classToMapperMap.put(FaultResponseDto.class, this.commonMapper); classToMapperMap.put(AlarmRegisterResponseDto.class, this.commonMapper); classToMapperMap.put(AdministrativeStatusTypeResponseDto.class, this.configurationMapper); classToMapperMap.put(PeriodicMeterReadsResponseDto.class, this.monitoringMapper); classToMapperMap.put(PeriodicMeterReadGasResponseDto.class, this.monitoringMapper); classToMapperMap.put(GetAttributeValuesResponseDto.class, this.configurationMapper); classToMapperMap.put(FirmwareVersionResponseDto.class, this.configurationMapper); classToMapperMap.put(UpdateFirmwareResponseDto.class, this.configurationMapper); classToMapperMap.put(AssociationLnObjectsResponseDto.class, this.commonMapper); <START> classToMapperMap.put(GetConfigurationObjectResponseDto.class, this.configurationMapper); <END> classToMapperMap.put(ProfileGenericDataResponseDto.class, this.monitoringMapper); }</code><technical_language>longer a custom converter, this line is superfluous</technical_language>

Target:
private void postConstruct() { classToMapperMap.put(EventMessageDataResponseDto.class, this.managementMapper); classToMapperMap.put(MeterReadsResponseDto.class, this.monitoringMapper); classToMapperMap.put(MeterReadsGasResponseDto.class, this.monitoringMapper); classToMapperMap.put(ActionResponseDto.class, this.commonMapper); classToMapperMap.put(FaultResponseDto.class, this.commonMapper); classToMapperMap.put(AlarmRegisterResponseDto.class, this.commonMapper); classToMapperMap.put(AdministrativeStatusTypeResponseDto.class, this.configurationMapper); classToMapperMap.put(PeriodicMeterReadsResponseDto.class, this.monitoringMapper); classToMapperMap.put(PeriodicMeterReadGasResponseDto.class, this.monitoringMapper); classToMapperMap.put(GetAttributeValuesResponseDto.class, this.configurationMapper); classToMapperMap.put(FirmwareVersionResponseDto.class, this.configurationMapper); classToMapperMap.put(UpdateFirmwareResponseDto.class, this.configurationMapper); classToMapperMap.put(AssociationLnObjectsResponseDto.class, this.commonMapper); classToMapperMap.put(ProfileGenericDataResponseDto.class, this.monitoringMapper); }
Source:
<code>private void putValuesToQuestion(final Question question, final QuestionViewHolder holder) { holder.question.setText(question.getName()); holder.value.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { mOnInteractionListener.onQuestionAnswered(question, holder.value.getText().toString()); } @Override public void afterTextChanged(Editable editable) { } }); <START> mOnInteractionListener.onQuestionAnswered(question, <END> holder.value.getText().toString().isEmpty() ? holder.value.getHint().toString() : holder.value.getText().toString()); }</code><technical_language>logic initialize zero questions in presenter is realized in adapter, refactor it</technical_language>

Target:
private void putValuesToQuestion(final Question question, final QuestionViewHolder holder) { holder.question.setText(question.getName()); holder.value.setHint(mDefValue); holder.value.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { mOnInteractionListener.onQuestionAnswered(question, holder.value.getText().toString()); } @Override public void afterTextChanged(Editable editable) { } }); mOnInteractionListener.onQuestionAnswered(question, holder.value.getText().toString()); }
Source:
<code>private void serialize(final String taskUrl) { new Job(LABEL_SERIALIZE_JOB_NAME) { @Override protected IStatus run(IProgressMonitor monitor) { try { String repositoryUrl = TasksUiPlugin.getRepositoryManager() .getConnectorForRepositoryTaskUrl(taskUrl) .getRepositoryUrlFromTaskUrl(taskUrl); repositoryUrl = URLEncoder.encode(repositoryUrl); File file = new File(getSaveFileName(), repositoryUrl); file.mkdirs(); file = new File(file, URLEncoder.encode(taskUrl) + ".json"); OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file)); gson.toJson(new TempMapping(taskUrl, taskReviewsMap.get(taskUrl)), writer); <START> writer.close(); <END> } catch (IOException e) { e.printStackTrace(); } return Status.OK_STATUS; } }.schedule(); }</code><technical_language>this in finally</technical_language>

Target:
private void serialize(final String taskUrl) { new Job(LABEL_SERIALIZE_JOB_NAME) { @Override protected IStatus run(IProgressMonitor monitor) { String repositoryUrl = repositoryManager.getConnectorForRepositoryTaskUrl(taskUrl) .getRepositoryUrlFromTaskUrl(taskUrl); repositoryUrl = URLEncoder.encode(repositoryUrl); File file = new File(getSaveFileName(), repositoryUrl); file.mkdirs(); file = new File(file, URLEncoder.encode(taskUrl) + ".json"); try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file))) { gson.toJson(new SerializationMapping(taskUrl, taskReviewsMap.get(taskUrl)), writer); } catch (IOException e) { e.printStackTrace(); } return Status.OK_STATUS; } }.schedule(); }
Source:
<code>public File getUploadedImage() { waitForElementByElement(thumbnailImage); File uploadedImageFile = new File(PageContent.resourcesPath + "shouldBeDeleted.png"); try { URL url = new URL(thumbnailImage.getAttribute("src")); BufferedImage bufImgOne = ImageIO.read(url); ImageIO.write(bufImgOne, "png", uploadedImageFile); } catch (IOException e) { <START> e.printStackTrace(); <END> } return uploadedImageFile; }</code><technical_language>instead of printing stack trace console throw RuntimeException? declared if wrong notified in right - need for in logs</technical_language>

Target:
public File getUploadedImage() { waitForElementByElement(thumbnailImage); File uploadedImageFile = new File(PageContent.resourcesPath + "shouldBeDeleted.png"); try { URL url = new URL(thumbnailImage.getAttribute("src")); BufferedImage bufImgOne = ImageIO.read(url); ImageIO.write(bufImgOne, "png", uploadedImageFile); } catch (IOException e) { throw new RuntimeException(); } return uploadedImageFile; }
Source:
<code>private List<Key> optionsOfQuestion(DatastoreService ds, Long qId) { <START> final Query optq = new Query("QuestionOptions").setFilter(new Query.FilterPredicate("questionId", FilterOperator.EQUAL, qId)); <END> final PreparedQuery pqopt = ds.prepare(optq); List<Key> result = new ArrayList<>(); for (Entity qa : pqopt.asIterable(FetchOptions.Builder.withChunkSize(500))) { result.add(qa.getKey()); } return result; }</code><technical_language>Ditto keys needed</technical_language>

Target:
private List<Key> optionsOfQuestion(DatastoreService ds, Long qId) { final Query optq = new Query("QuestionOptions") .setFilter(new Query.FilterPredicate("questionId", FilterOperator.EQUAL, qId)) .setKeysOnly(); final PreparedQuery pqopt = ds.prepare(optq); List<Key> result = new ArrayList<>(); for (Entity qa : pqopt.asIterable(FetchOptions.Builder.withChunkSize(500))) { result.add(qa.getKey()); } return result; }
Source:
<code>private String getUpToDateRuleElement() { final String template = "<rule name=\"%s\"\n" + " language=\"%s\"\n" + " message=\"%s\"\n" + " class=\"net.sourceforge.pmd.lang.rule.XPathRule\"\n" + " <!-- externalInfoUrl=\"%s\"--> >\n" + " <description>\n" + "%s\n" + " </description>\n" + " <priority>%d</priority>\n" + " <properties>\n" + " <property name=\"xpath\">\n" + " <value>\n" + "<![CDATA[\n" + "%s" + "]]>\n" + " </value>\n" + " </property>\n" + " </properties>\n" <START> + " <!--<example><![CDATA[]]></example>-->\n" <END> + "</rule>"; return String.format(template, nameField.getText(), languageChoiceBox.getSelectionModel().getSelectedItem().getTerseName(), messageField.getText(), "TODO", descriptionField.getText(), (int) prioritySlider.getValue(), xpathExpression.getValue() ); }</code><technical_language>example source panel, code user tested rule</technical_language>

Target:
private String getUpToDateRuleElement() { final String template = "<rule name=\"%s\"\n" + " language=\"%s\"\n" + " message=\"%s\"\n" + " class=\"net.sourceforge.pmd.lang.rule.XPathRule\"\n" + " <!-- externalInfoUrl=\"%s\"--> >\n" + " <description>\n" + "%s\n" + " </description>\n" + " <priority>%d</priority>\n" + " <properties>\n" + " <property name=\"xpath\">\n" + " <value>\n" + "<![CDATA[\n" + "%s\n" + "]]>\n" + " </value>\n" + " </property>\n" + " </properties>\n" + " <!--<example><![CDATA[]]></example>-->\n" + "</rule>"; return String.format(template, nameField.getText(), languageChoiceBox.getSelectionModel().getSelectedItem().getTerseName(), messageField.getText(), "TODO", descriptionField.getText(), (int) prioritySlider.getValue(), xpathExpression.getValue() ); }
Source:
<code>public void start(Map<String, String> props) { try { HdfsSinkConnectorConfig connectorConfig = new HdfsSinkConnectorConfig(props); boolean hiveIntegration = connectorConfig.getBoolean(HdfsSinkConnectorConfig.HIVE_INTEGRATION_CONFIG); if (hiveIntegration) { Compatibility compatibility = SchemaUtils.getCompatibility( connectorConfig.getString(HdfsSinkConnectorConfig.SCHEMA_COMPATIBILITY_CONFIG)); if (compatibility == Compatibility.NONE) { throw new ConfigException("Hive Integration requires schema compatibility to be BACKWARD, FORWARD or FULL"); } } int schemaCacheSize = connectorConfig.getInt(HdfsSinkConnectorConfig.SCHEMA_CACHE_SIZE_CONFIG); avroData = new AvroData(schemaCacheSize); hdfsWriter = new DataWriter(connectorConfig, context, avroData); Set<TopicPartition> assignment = context.assignment(); recover(assignment); if (hiveIntegration) { syncWithHive(); } } catch (ConfigException e) { throw new ConnectException("Couldn't start HdfsSinkConnector due to configuration error.", e); } catch (ConnectException e) { <START> log.info("Couldn't start HdfsSinkConnector due to {}", e.getMessage()); <END> log.info("Shutting down HdfsSinkConnector."); if (hdfsWriter != null) { hdfsWriter.close(); } } }</code><technical_language>log.info("Couldn't start HdfsSinkConnector:", e); give stack trace well</technical_language>

Target:
public void start(Map<String, String> props) { try { HdfsSinkConnectorConfig connectorConfig = new HdfsSinkConnectorConfig(props); boolean hiveIntegration = connectorConfig.getBoolean(HdfsSinkConnectorConfig.HIVE_INTEGRATION_CONFIG); if (hiveIntegration) { Compatibility compatibility = SchemaUtils.getCompatibility( connectorConfig.getString(HdfsSinkConnectorConfig.SCHEMA_COMPATIBILITY_CONFIG)); if (compatibility == Compatibility.NONE) { throw new ConfigException("Hive Integration requires schema compatibility to be BACKWARD, FORWARD or FULL"); } } int schemaCacheSize = connectorConfig.getInt(HdfsSinkConnectorConfig.SCHEMA_CACHE_SIZE_CONFIG); avroData = new AvroData(schemaCacheSize); hdfsWriter = new DataWriter(connectorConfig, context, avroData); Set<TopicPartition> assignment = context.assignment(); recover(assignment); if (hiveIntegration) { syncWithHive(); } } catch (ConfigException e) { throw new ConnectException("Couldn't start HdfsSinkConnector due to configuration error.", e); } catch (ConnectException e) { log.info("Couldn't start HdfsSinkConnector:", e); log.info("Shutting down HdfsSinkConnector."); if (hdfsWriter != null) { hdfsWriter.close(); } } }
Source:
<code>private JiraSession createSession() { if (StringUtils.isEmpty(credentialsId)) { LOGGER.warning("Jira session could not be created. No credentials supplied."); return null; } final URI uri; try { uri = url.toURI(); } catch (URISyntaxException e) { LOGGER.warning("convert URL to URI error: " + e.getMessage()); throw new RuntimeException("failed to create JiraSession due to convert URI error"); } LOGGER.fine("creating Jira Session: " + uri); StandardUsernamePasswordCredentials credentials = CredentialsHelper.lookupSystemCredentials(credentialsId, url); String userName = credentials.getUsername(); Secret password = credentials.getPassword(); final ExtendedJiraRestClient jiraRestClient = new ExtendedAsynchronousJiraRestClientFactory() .create(uri, new BasicHttpAuthenticationHandler( userName, password.getPlainText()),getHttpClientOptions()); <START> return new JiraSession(this, new JiraRestService(uri, jiraRestClient, userName, password.getPlainText(), readTimeout, sendAssigneeAsName)); <END> }</code><technical_language>if this is needed if send fields</technical_language>

Target:
private JiraSession createSession() { if (StringUtils.isEmpty(credentialsId)) { LOGGER.warning("Jira session could not be created. No credentials supplied."); return null; } final URI uri; try { uri = url.toURI(); } catch (URISyntaxException e) { LOGGER.warning("convert URL to URI error: " + e.getMessage()); throw new RuntimeException("failed to create JiraSession due to convert URI error"); } LOGGER.fine("creating Jira Session: " + uri); StandardUsernamePasswordCredentials credentials = CredentialsHelper.lookupSystemCredentials(credentialsId, url); String userName = credentials.getUsername(); Secret password = credentials.getPassword(); final ExtendedJiraRestClient jiraRestClient = new ExtendedAsynchronousJiraRestClientFactory() .create(uri, new BasicHttpAuthenticationHandler( userName, password.getPlainText()),getHttpClientOptions()); return new JiraSession(this, new JiraRestService(uri, jiraRestClient, userName, password.getPlainText(), readTimeout)); }
Source:
<code>public void afterPropertiesSet() { InvalidationListener modDirectoryChangedListener = observable -> { modsDirectory = preferencesService.getPreferences().getForgedAlliance().getModsDirectory(); if (modsDirectory != null) { installedModVersions.clear(); onModDirectoryReady(); } }; taskService.submitTask(new CompletableTask<Void>(Priority.LOW) { @Override protected Void call() throws Exception { updateTitle(i18n.get("modVault.loadingMaps")); modDirectoryChangedListener.invalidated(preferencesService.getPreferences().getForgedAlliance().modsDirectoryProperty()); return null; } <START> }); <END> JavaFxUtil.addListener(preferencesService.getPreferences().getForgedAlliance().modsDirectoryProperty(), modDirectoryChangedListener); }</code><technical_language>a task invalidate manually? is this maps</technical_language>

Target:
public void afterPropertiesSet() { InvalidationListener modDirectoryChangedListener = observable -> { modsDirectory = preferencesService.getPreferences().getForgedAlliance().getModsDirectory(); if (modsDirectory != null) { installedModVersions.clear(); onModDirectoryReady(); } }; taskService.submitTask(new CompletableTask<Void>(Priority.LOW) { @Override protected Void call() throws Exception { updateTitle(i18n.get("modVault.loadingMods")); modDirectoryChangedListener.invalidated(preferencesService.getPreferences().getForgedAlliance().modsDirectoryProperty()); return null; } }); JavaFxUtil.addListener(preferencesService.getPreferences().getForgedAlliance().modsDirectoryProperty(), modDirectoryChangedListener); }
Source:
<code>private void fillInBases(final SAMRecord rec) { final int length = getReadLengthFromCigar(rec); <START> final byte[] bases = SequenceUtil.getRandomBases(random, length); <END> rec.setReadBases(bases); }</code><technical_language>I get rid of BASES now</technical_language>

Target:
private void fillInBases(final SAMRecord rec) { rec.setReadBases(SequenceUtil.getRandomBases(random, getReadLengthFromCigar(rec))); }
Source:
<code>private static boolean canConvert(ParameterDefinition def, ParameterValue v) { return def instanceof SimpleParameterDefinition && !(def instanceof StringParameterDefinition) && v instanceof StringParameterValue; <START> } <END></code><technical_language>This results conversion applyed subclass of StringParameterValue. applied exact StringParameterValue</technical_language>

Target:
private static boolean canConvert(ParameterDefinition def, ParameterValue v) { return def instanceof SimpleParameterDefinition && !(def instanceof StringParameterDefinition) && v.getClass().equals(StringParameterValue.class); }
Source:
<code>public static CharSequence getFormattedString(@NonNull String pattern, @NonNull Map<String, ? extends CharSequence> keyValMap) { Phrase resourceString = Phrase.from(pattern); Set<String> keys = keyValMap.keySet(); for (String key : keys) { final CharSequence val = keyValMap.get(key); if (val == null) { logger.warn(String.format("Value for key %s is null", key)); <START> resourceString.putOptional(key, ""); <END> } else { resourceString.putOptional(key, val); } } return resourceString.format(); }</code><technical_language>This optional, if usages implemented wrongly (that this PR) fixed well</technical_language>

Target:
public static CharSequence getFormattedString(@NonNull String pattern, @NonNull Map<String, ? extends CharSequence> keyValMap) { Phrase resourceString = Phrase.from(pattern); Set<String> keys = keyValMap.keySet(); for (String key : keys) { final CharSequence val = keyValMap.get(key); if (val == null) { logger.warn(String.format("Value for key %s is null", key)); resourceString.put(key, ""); } else { resourceString.put(key, val); } } return resourceString.format(); }
Source:
<code>public PartitionMetadata withColumnStatistics(Map<String, HiveColumnStatistics> columnStatistics) { <START> requireNonNull(columnStatistics, "columnStatistics is null"); <END> return new PartitionMetadata(columns, parameters, storageFormat, bucketProperty, serdeParameters, externalLocation, columnStatistics); }</code><technical_language>This is needed, constructor checks</technical_language>

Target:
public PartitionMetadata withColumnStatistics(Map<String, HiveColumnStatistics> columnStatistics) { return new PartitionMetadata(columns, parameters, storageFormat, bucketProperty, serdeParameters, externalLocation, columnStatistics); }
Source:
<code>protected Iterable<String> getChoices(CommandSource source) { return Arrays.stream(this.type.getEnumConstants()) <START> .map(input -> input == null ? null : input.name()) <END> .collect(Collectors.toList()); }</code><technical_language>optimize this line java .map(input::name) elements of array is guaranteed non-null</technical_language>

Target:
protected Iterable<String> getChoices(CommandSource source) { return this.values.keySet(); }
Source:
<code>public void InteractiveMaps_033_PalantirSetHugeZoomVerifyError() { InteractiveMapPageObject selectedMap = new InteractiveMapPageObject(driver); <START> selectedMap.openMap(wikiURL, 3); <END> selectedMap.verifyMapOpened(); PalantirComponentObject poi = new PalantirComponentObject(driver); PalantirContent handle = new PalantirContent(); handle = poi.setAndVerifyPlayerPosition(-40, -10, 3000, true); poi.verifyWrongZoomLevel(handle.success, handle.responseCode, handle.message); poi.verifyPoiNotAppearOnMap(); }</code><technical_language>Suggest move 2nd param a class variable I other tests value</technical_language>

Target:
public void InteractiveMaps_033_PalantirSetHugeZoomVerifyError() { InteractiveMapsPageObject specialMap = new InteractiveMapsPageObject(driver); InteractiveMapPageObject selectedMap = specialMap.openMap(wikiURL, PalantirContent.PALANTIR_MAP); selectedMap.verifyMapOpened(); PalantirComponentObject poi = new PalantirComponentObject(driver); PalantirContent handle = poi.setAndVerifyPlayerPosition(-40, -10, 3000, true); poi.verifyWrongZoomLevel(handle); poi.verifyPoiNotAppearOnMap(); }
Source:
<code>public void removePlayer(ProxiedPlayer player) { Preconditions.checkNotNull( player, "player" ); <START> players.remove( player ); <END> if ( player.isConnected() && visible ) { player.unsafe().sendPacket( removePacket() ); } }</code><technical_language>Check if in list</technical_language>

Target:
public void removePlayer(ProxiedPlayer player) { Preconditions.checkNotNull( player, "player" ); players.remove( player ); if ( player.isConnected() && visible ) { sendPacket( player, removePacket ); } }
Source:
<code>public static Set<GeneNumber> getGeneNumberListWithLevels(Set<Gene> genes, Set<LevelOfEvidence> levels) { if (levels == null) { return getGeneNumberList(genes); } Map<Gene, Set<Evidence>> evidences = EvidenceUtils.getEvidenceByGenes(genes); Set<GeneNumber> geneNumbers = new HashSet<>(); Iterator it = evidences.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Gene, Set<Evidence>> pair = (Map.Entry) it.next(); GeneNumber geneNumber = new GeneNumber(); geneNumber.setGene(pair.getKey()); LevelOfEvidence highestSensitiveLevel = LevelUtils.getHighestLevelFromEvidenceByLevels(pair.getValue(), new HashSet<>(CollectionUtils.intersection(levels, LevelUtils.getPublicSensitiveLevels()))); LevelOfEvidence highestResistanceLevel = LevelUtils.getHighestLevelFromEvidenceByLevels(pair.getValue(), new HashSet<>(CollectionUtils.intersection(levels, LevelUtils.getPublicResistanceLevels()))); geneNumber.setHighestSensitiveLevel(highestSensitiveLevel != null ? highestSensitiveLevel.name() : null); <START> geneNumber.setHighestResistenceLevel(highestResistanceLevel != null ? highestSensitiveLevel.name() : null); <END> Set<Alteration> alterations = AlterationUtils.getAllAlterations(pair.getKey()); List<Alteration> excludeVUS = AlterationUtils.excludeVUS(pair.getKey(), new ArrayList<>(alterations)); geneNumber.setAlteration(excludeVUS.size()); geneNumbers.add(geneNumber); } return geneNumbers; }</code><technical_language>highestResistanceLevel instead of highestSensitiveLevel</technical_language>

Target:
public static Set<GeneNumber> getGeneNumberListWithLevels(Set<Gene> genes, Set<LevelOfEvidence> levels) { if (levels == null) { return getGeneNumberList(genes); } Map<Gene, Set<Evidence>> evidences = EvidenceUtils.getEvidenceByGenes(genes); Set<GeneNumber> geneNumbers = new HashSet<>(); Iterator it = evidences.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Gene, Set<Evidence>> pair = (Map.Entry) it.next(); GeneNumber geneNumber = new GeneNumber(); geneNumber.setGene(pair.getKey()); LevelOfEvidence highestSensitiveLevel = LevelUtils.getHighestLevelFromEvidenceByLevels(pair.getValue(), new HashSet<>(CollectionUtils.intersection(levels, LevelUtils.getPublicSensitiveLevels()))); LevelOfEvidence highestResistanceLevel = LevelUtils.getHighestLevelFromEvidenceByLevels(pair.getValue(), new HashSet<>(CollectionUtils.intersection(levels, LevelUtils.getPublicResistanceLevels()))); geneNumber.setHighestSensitiveLevel(highestSensitiveLevel != null ? highestSensitiveLevel.name() : null); geneNumber.setHighestResistenceLevel(highestResistanceLevel != null ? highestResistanceLevel.name() : null); Set<Alteration> alterations = AlterationUtils.getAllAlterations(pair.getKey()); List<Alteration> excludeVUS = AlterationUtils.excludeVUS(pair.getKey(), new ArrayList<>(alterations)); geneNumber.setAlteration(excludeVUS.size()); geneNumbers.add(geneNumber); } return geneNumbers; }
Source:
<code>private boolean isVisibilitySetToAnonymousToRecipientVisibleToInstructors(FeedbackQuestionAttributes question) { boolean responsesVisibleOnlyToRecipientAndInstructors; <START> if (question.questionType.equals(FeedbackQuestionType.CONTRIB)) { <END> responsesVisibleOnlyToRecipientAndInstructors = question.showResponsesTo.size() == 4 && question.showResponsesTo.contains(FeedbackParticipantType.RECEIVER) && question.showResponsesTo.contains(FeedbackParticipantType.OWN_TEAM_MEMBERS) && question.showResponsesTo.contains(FeedbackParticipantType.RECEIVER_TEAM_MEMBERS) && question.showResponsesTo.contains(FeedbackParticipantType.INSTRUCTORS); } else { responsesVisibleOnlyToRecipientAndInstructors = question.showResponsesTo.size() == 2 && question.showResponsesTo.contains(FeedbackParticipantType.RECEIVER) && question.showResponsesTo.contains(FeedbackParticipantType.INSTRUCTORS); } boolean giverNameVisibleOnlyToInstructors = question.showGiverNameTo.size() == 1 && question.showGiverNameTo.contains(FeedbackParticipantType.INSTRUCTORS); return responsesVisibleOnlyToRecipientAndInstructors && giverNameVisibleOnlyToInstructors; }</code><technical_language>I if want treat this a special case for AnonymousToRecipientVisibleToInstructors. @junhaoyap do think? create another name for this case</technical_language>

Target:
private boolean isVisibilitySetToAnonymousToRecipientVisibleToInstructors(FeedbackQuestionAttributes question) { boolean responsesVisibleOnlyToRecipientAndInstructors = question.showResponsesTo.size() == 2 && question.showResponsesTo.contains(FeedbackParticipantType.INSTRUCTORS) && question.showResponsesTo.contains(FeedbackParticipantType.RECEIVER); boolean giverNameVisibleOnlyToInstructors = question.showGiverNameTo.size() == 1 && question.showGiverNameTo.contains(FeedbackParticipantType.INSTRUCTORS); return responsesVisibleOnlyToRecipientAndInstructors && giverNameVisibleOnlyToInstructors; }
Source:
<code>public boolean shouldBeAnEclipseProject(IContainer container, IProgressMonitor monitor) { <START> return container.getFile(new Path("feature.xml")).exists(); <END> }</code><technical_language>missing non-nls warning</technical_language>

Target:
public boolean shouldBeAnEclipseProject(IContainer container, IProgressMonitor monitor) { return container.getFile(new Path(ICoreConstants.FEATURE_FILENAME_DESCRIPTOR)).exists(); }
Source:
<code>public RemoteReplicaInfo(ReplicaId replicaId, Store localStore, FindToken token, long tokenPersistIntervalInMs) { this.replicaId = replicaId; this.currentToken = token; if (tokenToPersist == null) { this.tokenToPersist = token; timeTokenSetInMs = SystemTime.getInstance().milliseconds(); } this.tokenPersistIntervalInMs = tokenPersistIntervalInMs; <START> this.totalBytesReadFromLocalStore = new Long(0); <END> this.localStore = localStore; }</code><technical_language>"= 0" is sufficient initialize 'long totalBytesReadFromLocalStore;'</technical_language>

Target:
public RemoteReplicaInfo(ReplicaId replicaId, Store localStore, FindToken token, long tokenPersistIntervalInMs) { this.replicaId = replicaId; this.currentToken = token; if (tokenToPersist == null) { this.tokenToPersist = token; timeTokenSetInMs = SystemTime.getInstance().milliseconds(); } this.tokenPersistIntervalInMs = tokenPersistIntervalInMs; this.totalBytesReadFromLocalStore = 0; this.localStore = localStore; }
Source:
<code>protected List<Edge> getEdgeList(DDiagram representation) { List<Edge> edges = new ArrayList<Edge>(); TreeIterator<EObject> eAllContents = <START> representation.eAllContents(); <END> while (eAllContents.hasNext()) { EObject element = eAllContents.next(); if (element instanceof Edge) { edges.add((Edge) element); eAllContents.prune(); } } return edges; }</code><technical_language>avoid eAllContents, for example : DiagramCreationUtil diagramCreationUtil = new DiagramCreationUtil(dDiagram); if (diagramCreationUtil.findAssociatedGMFDiagram()) { Diagram gmfDiagram = diagramCreationUtil.getAssociatedGMFDiagram(); gmfDiagram.getEdges()..</technical_language>

Target:
protected List<Edge> getEdgeList(DDiagram representation) { List<Edge> edges = new ArrayList<Edge>(); DiagramCreationUtil diagramCreationUtil = new DiagramCreationUtil(representation); if (diagramCreationUtil.findAssociatedGMFDiagram()) { Diagram gmfDiagram = diagramCreationUtil.getAssociatedGMFDiagram(); edges = gmfDiagram.getEdges(); } return edges; }
Source:
<code>public RuleClass build(RuleClass.Builder builder, RuleDefinitionEnvironment env) { return builder .requiresConfigurationFragments(CppConfiguration.class) .add(attr("compile_only_deps", LABEL_LIST) <START> .allowedRuleClasses(BazelCppRuleClasses.DEPS_ALLOWED_RULES) <END> .allowedFileTypes(CppFileTypes.LINKER_SCRIPT) .skipAnalysisTimeFileTypeCheck()) .add(attr("alwayslink", BOOLEAN)) .override(attr("linkstatic", BOOLEAN).value(false)) .build(); }</code><technical_language>Please change this allow rule provider CcInfo. Do allow linker scripts</technical_language>

Target:
public RuleClass build(RuleClass.Builder builder, RuleDefinitionEnvironment env) { return builder .requiresConfigurationFragments(CppConfiguration.class) .add(attr("compile_only_deps", LABEL_LIST) .allowedFileTypes() .allowedRuleClasses(BazelCppRuleClasses.DEPS_ALLOWED_RULES) .skipAnalysisTimeFileTypeCheck() .mandatoryProviders(SkylarkProviderIdentifier.forKey(CcInfo.PROVIDER.getKey()))) .add(attr("alwayslink", BOOLEAN)) .override(attr("linkstatic", BOOLEAN).value(false)) .build(); }
Source:
<code>private AsyncTaskManager() { _tasks = new ConcurrentHashMap<Guid, SPMAsyncTask>(); SchedulerUtil scheduler = SchedulerUtilQuartzImpl.getInstance(); scheduler.scheduleAFixedDelayJob(this, "_timer_Elapsed", new Class[] {}, new Object[] {}, Config.<Integer> GetValue(ConfigValues.AsyncTaskPollingRate), Config.<Integer> GetValue(ConfigValues.AsyncTaskPollingRate), TimeUnit.SECONDS); scheduler.scheduleAFixedDelayJob(this, "_cacheTimer_Elapsed", new Class[] {}, new Object[] {}, Config.<Integer> GetValue(ConfigValues.AsyncTaskStatusCacheRefreshRateInSeconds), Config.<Integer> GetValue(ConfigValues.AsyncTaskStatusCacheRefreshRateInSeconds), TimeUnit.SECONDS); _cacheTimeInMinutes = Config.<Integer> GetValue(ConfigValues.AsyncTaskStatusCachingTimeInMinutes); tasksInDbAfterRestart = new ConcurrentHashMap<Guid, List<AsyncTasks>>(); for (AsyncTasks task: DbFacade.getInstance().getAsyncTaskDao().getAll()) { <START> if (task.getVdsmTaskId().equals(NGuid.Empty)) { <END> failTaskWithoutVdsmId(task); continue; } tasksInDbAfterRestart.putIfAbsent(task.getStoragePoolId(), new ArrayList<AsyncTasks>()); List<AsyncTasks> tasksPerStoragePool = tasksInDbAfterRestart.get(task.getStoragePoolId()); tasksInDbAfterRestart.put(task.getStoragePoolId(), tasksPerStoragePool); tasksPerStoragePool.add(task); } }</code><technical_language>NGuid.Empty.equals(task.getVdsmTaskId()) a practice I a log helpful</technical_language>

Target:
private AsyncTaskManager() { _tasks = new ConcurrentHashMap<Guid, SPMAsyncTask>(); SchedulerUtil scheduler = SchedulerUtilQuartzImpl.getInstance(); scheduler.scheduleAFixedDelayJob(this, "_timer_Elapsed", new Class[] {}, new Object[] {}, Config.<Integer> GetValue(ConfigValues.AsyncTaskPollingRate), Config.<Integer> GetValue(ConfigValues.AsyncTaskPollingRate), TimeUnit.SECONDS); scheduler.scheduleAFixedDelayJob(this, "_cacheTimer_Elapsed", new Class[] {}, new Object[] {}, Config.<Integer> GetValue(ConfigValues.AsyncTaskStatusCacheRefreshRateInSeconds), Config.<Integer> GetValue(ConfigValues.AsyncTaskStatusCacheRefreshRateInSeconds), TimeUnit.SECONDS); _cacheTimeInMinutes = Config.<Integer> GetValue(ConfigValues.AsyncTaskStatusCachingTimeInMinutes); tasksInDbAfterRestart = new ConcurrentHashMap<Guid, List<AsyncTasks>>(); for (AsyncTasks task: DbFacade.getInstance().getAsyncTaskDao().getAll()) { if (NGuid.Empty.equals(task.getVdsmTaskId())) { log.infoFormat("Failing task {0} as it does not have a vdsm id.", task.getTaskId()); failTaskWithoutVdsmId(task); continue; } tasksInDbAfterRestart.putIfAbsent(task.getStoragePoolId(), new ArrayList<AsyncTasks>()); List<AsyncTasks> tasksPerStoragePool = tasksInDbAfterRestart.get(task.getStoragePoolId()); tasksInDbAfterRestart.put(task.getStoragePoolId(), tasksPerStoragePool); tasksPerStoragePool.add(task); } }
Source:
<code>public static boolean isSchedulable(JobCurator jobCurator, JobStatus status) { Class<? extends KingpinJob> jobClass; try { jobClass = (Class<? extends KingpinJob>) Class.forName(status.getJobClass()); } catch (ClassNotFoundException cnfe) { log.warn("Could not schedule job of class {}. The class was not found.", status.getJobClass()); return false; } JobStatus nextJob = jobCurator.getNextByClassAndTarget(status.getTargetId(), <START> HypervisorUpdateJob.class); <END> return nextJob != null && nextJob.getId().equals(status.getId()); }</code><technical_language>this UniqueByEntityJob</technical_language>

Target:
public static boolean isSchedulable(JobCurator jobCurator, JobStatus status) { Class<? extends KingpinJob> jobClass; try { jobClass = (Class<? extends KingpinJob>) Class.forName(status.getJobClass()); } catch (ClassNotFoundException cnfe) { log.warn("Could not schedule job of class {}. The class was not found.", status.getJobClass()); return false; } long running = jobCurator.findNumRunningByClassAndTarget( status.getTargetId(), jobClass); return running == 0; }