auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public int parseArguments(Parameters params) throws CmdLineException { String param = params.getParameter(0); Result v = fromString(param.replace('-', '_')); <START> setter.addValue(v); <END> return 1; }</code><technical_language>is a regression introduced some point. This method accept argument fallback FAILURE. a user pass SUCESS in CLI argument get a zero code unexpected result</technical_language>

Target:
public int parseArguments(Parameters params) throws CmdLineException { String param = params.getParameter(0); Result v = fromString(param.replace('-', '_')); if (v== FAILURE) { throw new CmdLineException(owner,"No such status '"+param+"'. Did you mean "+ EditDistance.findNearest(param.replace('-', '_').toUpperCase(), getNames())); } setter.addValue(v); return 1; }
Source:
<code><START> private void mockSSHClient() { <END> try { doNothing().when(sshclient).connect(); doNothing().when(sshclient).authenticate(); } catch(Exception e) }</code><technical_language>throw exception upwards.</technical_language>

Target:
private void mockSSHClient() { try { doNothing().when(sshclient).connect(); doNothing().when(sshclient).authenticate(); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>public NonDdlBatch setInferPartitioning(boolean value) { value = m_batchToDecorate.getTaskCount() == 1 && value; <START> if (m_inferPartitioning ^ value) { <END> m_inferPartitioning = value; updateStatementPartitioning(); } return this; }</code><technical_language>m_inferPartitioning != value</technical_language>

Target:
public NonDdlBatch setInferPartitioning(boolean value) { value = m_batchToDecorate.getTaskCount() == 1 && value; if (m_inferPartitioning != value) { m_inferPartitioning = value; updateStatementPartitioning(); } return this; }
Source:
<code>public final void initialize(boolean initializeAsync) { assertNeverCalledInitialize(); if (!initializeAsync) { tryInitializeInternal(); return; } try { <START> tryInitializeInternal(); <END> } catch (Throwable throwable) { log.info("Failed to initialize in the first attempt, will initialize asynchronously.", SafeArg.of("className", getInitializingClassName()), throwable); cleanUpOnInitFailure(); scheduleInitialization(); } }</code><technical_language>this executor, sort of breaks guarantees of cancelInitialization method (i.e. call cancelInitialization while this is running callback get executed. ok that? this try/catch/cleanup logic is duplicated in scheduleInitialization - want refactor a method</technical_language>

Target:
public final void initialize(boolean initializeAsync) { assertNeverCalledInitialize(); initializationStartTime = System.currentTimeMillis(); if (!initializeAsync) { tryInitializeInternal(); return; } tryInitializationLoop(); }
Source:
<code>public String getModelHosts() throws PermissionRestException { RMStateFull state = orThrowRpe(RMStateCaching.getRMStateFull()); <START> return "PA:LIST(," + <END> state.getNodesEvents() .stream() .map(event -> event.getHostName()) .distinct() .collect(Collectors.joining(",")) + ")"; }</code><technical_language>this method return REMOVED node events</technical_language>

Target:
public String getModelHosts() throws PermissionRestException { RMStateFull state = orThrowRpe(RMStateCaching.getRMStateFull()); return String.format("PA:LIST(,%s)", state.getNodesEvents() .stream() .map(RMNodeEvent::getHostName) .distinct() .collect(Collectors.joining(","))); }
Source:
<code>public void clickFbWindowTriggerButton() { waitForElementByElement(loginFbButton); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } <START> clickAndWait(loginFbButton); <END> try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } PageObjectLogging.log("clickFbWindowTriggerButton", "facebook button clicked in login drop-down", true, driver); }</code><technical_language>click element</technical_language>

Target:
public void clickFbWindowTriggerButton() { waitForElementByElement(loginFbButton); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } scrollAndClick(loginFbButton); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } PageObjectLogging.log("clickFbWindowTriggerButton", "facebook button clicked in login drop-down", true, driver); }
Source:
<code>public void widgetSelected(@Nullable SelectionEvent e) { VirtualTableLine selectedLine = <START> (VirtualTableLine) NonNullUtils.checkNotNull(e).item.getData(); <END> ITmfTimestamp start = TmfTimestamp.fromNanos(Long.parseLong(selectedLine.getLine().get(0))); ITmfTimestamp end = TmfTimestamp.fromNanos(Long.parseLong(selectedLine.getLine().get(1))); TmfSignalManager.dispatchSignal(new TmfSelectionRangeUpdatedSignal(AbstractSegmentStoreTableViewer.this, start, end, fTrace)); }</code><technical_language>check casting</technical_language>

Target:
public void widgetSelected(@Nullable SelectionEvent e) { Object line = NonNullUtils.checkNotNull(e).item.getData(); if (!(line instanceof SegmentStoreTableLine)) { return; } SegmentStoreTableLine selectedLine = (SegmentStoreTableLine) line; ITmfTimestamp start = TmfTimestamp.fromNanos(selectedLine.getStartTime()); ITmfTimestamp end = TmfTimestamp.fromNanos(selectedLine.getEndTime()); TmfSignalManager.dispatchSignal(new TmfSelectionRangeUpdatedSignal(AbstractSegmentStoreTableViewer.this, start, end, fTrace)); }
Source:
<code>private void dumpMetrics(FileDescriptor fd) { Log.i(TAG, "dumpMetrics"); BluetoothProto.BluetoothLog metrics = new BluetoothProto.BluetoothLog(); metrics.setNumBondedDevices(getBondedDevices().length); for (ProfileService profile : mProfiles) { profile.dumpProto(metrics); } byte[] nativeMetricsBytes = dumpMetricsNative(); <START> Log.i(TAG, <END> "dumpMetrics, native metrics size is " + nativeMetricsBytes.length); try { metrics.mergeFrom(nativeMetricsBytes); } catch (InvalidProtocolBufferMicroException ex) { Log.w(TAG, "dumpMetrics, problem parsing metrics protobuf: " + ex.getMessage()); return; } byte[] metricsBytes = Base64.encode(metrics.toByteArray(), Base64.DEFAULT); Log.i(TAG, "dumpMetrics, combined metrics size is " + metricsBytes.length); try (FileOutputStream protoOut = new FileOutputStream(fd)) { protoOut.write(metricsBytes); } catch (IOException e) { errorLog("dumpMetrics, Unable to write combined protobuf to file descriptor."); } }</code><technical_language>this pretty verbose. Log.d</technical_language>

Target:
private void dumpMetrics(FileDescriptor fd) { BluetoothProto.BluetoothLog metrics = new BluetoothProto.BluetoothLog(); metrics.setNumBondedDevices(getBondedDevices().length); for (ProfileService profile : mProfiles) { profile.dumpProto(metrics); } byte[] nativeMetricsBytes = dumpMetricsNative(); debugLog("dumpMetrics: native metrics size is " + nativeMetricsBytes.length); try { metrics.mergeFrom(nativeMetricsBytes); } catch (InvalidProtocolBufferMicroException ex) { Log.w(TAG, "dumpMetrics: problem parsing metrics protobuf, " + ex.getMessage()); return; } byte[] metricsBytes = Base64.encode(metrics.toByteArray(), Base64.DEFAULT); debugLog("dumpMetrics: combined metrics size is " + metricsBytes.length); try (FileOutputStream protoOut = new FileOutputStream(fd)) { protoOut.write(metricsBytes); } catch (IOException e) { errorLog("dumpMetrics: error writing combined protobuf to fd, " + e.getMessage()); } }
Source:
<code>private WallabagServiceEndpoint getServiceEndpoint() { if(serviceEndpoint == null) { if(this.wallabagMajorVersion == -1) { this.wallabagMajorVersion = guessWallabagVersion(); } switch (this.wallabagMajorVersion) { <START> case 2: <END> serviceEndpoint = new WallabagServiceEndpointV2(endpoint, username, password, client); break; default: Log.w(TAG, "Falling back to V1 endpoint; wallabagMajorVersion=" + this.wallabagMajorVersion); case 1: serviceEndpoint = new WallabagServiceEndpointV1(endpoint, username, password, client); break; } } return serviceEndpoint; }</code><technical_language>case ordered. a problem in Java</technical_language>

Target:
private WallabagServiceEndpoint getServiceEndpoint() { if(serviceEndpoint == null) { switch(getWallabagVersion()) { case 1: serviceEndpoint = new WallabagServiceEndpointV1(endpoint, username, password, client); break; default: Log.w(TAG, "Falling back to V2 endpoint; wallabagVersion=" + this.wallabagVersion); case 2: serviceEndpoint = new WallabagServiceEndpointV2(endpoint, username, password, client); break; } } return serviceEndpoint; }
Source:
<code>public void shouldParseAcceptScriptWithOptions() throws Exception { String script = "# tcp.client.accept-then-close\n" + "accept option transport \"localhost:8000\"\n" + <START> "accept tcp://localhost:7788\n" + <END> "accepted\n" + "connected\n" + "close\n" + "closed\n"; ScriptParserImpl parser = new ScriptParserImpl(); AstScriptNode actual = parser.parseWithStrategy(script, SCRIPT); }</code><technical_language>discuss syntax a bit more. starting feel imperative programming language setup option state issue accept connect. deliberately avoid that, for example looping in K3PO script language. anticipated options part of accept accept (but accepted). thoughts that</technical_language>

Target:
public void shouldParseAcceptScriptWithOptions() throws Exception { String script = "# tcp.client.accept-then-close\n" + "accept http://localhost:7788\n" + " option transport tcp://localhost:8000\n" + "accepted\n" + "connected\n" + "close\n" + "closed\n"; ScriptParserImpl parser = new ScriptParserImpl(); AstScriptNode actual = parser.parseWithStrategy(script, SCRIPT); AstLocation location = new AstLocationLiteral(URI.create("http://localhost:7788")); AstLocation transport = new AstLocationLiteral(URI.create("tcp://localhost:8000")); AstScriptNode expected = new AstScriptNodeBuilder() .addAcceptStream() .setLocation(location) .setTransport(transport) .done() .addAcceptedStream() .addConnectedEvent().done() .addCloseCommand().done() .addClosedEvent().done() .done() .done(); assertEquals(expected, actual); }
Source:
<code>public void testIterateThroughDocumentVectorComputeBM25() throws Exception { Directory dir = FSDirectory.open(tempDir1); IndexReader reader = DirectoryReader.open(dir); IndexSearcher searcher = new IndexSearcher(reader); searcher.setSimilarity(new BM25Similarity()); int numDocs = reader.numDocs(); for (int i=0; i<numDocs; i++) { String docid = reader.document(i).getField("docid").stringValue(); System.out.println(reader.document(i)); System.out.println(i+ ": " + docid); Terms terms = reader.getTermVector(i, "text"); TermsEnum te = terms.iterator(); while (te.next() != null) { String term = new Term("text", te.term()).bytes().utf8ToString(); <START> String stemmed = AnalyzerUtils.tokenize(new EnglishAnalyzer(), term).get(0); <END> long tf = te.totalTermFreq(); Query filterQuery = new TermQuery(new Term("docid", docid)); Query termQuery = new TermQuery(new Term("text", term)); BooleanQuery.Builder builder = new BooleanQuery.Builder(); builder.add(filterQuery, BooleanClause.Occur.MUST); builder.add(termQuery, BooleanClause.Occur.MUST); Query finalQuery = builder.build(); TopDocs rs = searcher.search(finalQuery, 1); System.out.println(stemmed + " " + tf + " " + rs.getMaxScore()); } } }</code><technical_language>This is redundant. term stored in Lucene index tokenized stemmed</technical_language>

Target:
public void testIterateThroughDocumentVectorComputeBM25() throws Exception { Directory dir = FSDirectory.open(tempDir1); IndexReader reader = DirectoryReader.open(dir); IndexSearcher searcher = new IndexSearcher(reader); searcher.setSimilarity(new BM25Similarity()); int numDocs = reader.numDocs(); for (int i=0; i<numDocs; i++) { String docid = reader.document(i).getField("docid").stringValue(); System.out.println(reader.document(i)); System.out.println(i+ ": " + docid); Terms terms = reader.getTermVector(i, "text"); TermsEnum te = terms.iterator(); while (te.next() != null) { String term = new Term("text", te.term()).bytes().utf8ToString(); long tf = te.totalTermFreq(); Query filterQuery = new TermQuery(new Term("docid", docid)); Query termQuery = new TermQuery(new Term("text", term)); BooleanQuery.Builder builder = new BooleanQuery.Builder(); builder.add(filterQuery, BooleanClause.Occur.MUST); builder.add(termQuery, BooleanClause.Occur.MUST); Query finalQuery = builder.build(); TopDocs rs = searcher.search(finalQuery, 1); System.out.println(term + " " + tf + " " + rs.getMaxScore()); } } }
Source:
<code>private void createConfigurationForCluster(String clusterId) throws LoadBalancerExtensionException { log.info("Creating configuration for cluster"); GCEClusterConfigurationHolder gceClusterConfigurationHolder = clusterToLoadBalancerConfigurationMap.get(clusterId); gceOperations.createHealthCheck(gceClusterConfigurationHolder.getHealthCheckName()); gceOperations.createTargetPool(gceClusterConfigurationHolder.getTargetPoolName(), gceClusterConfigurationHolder.getHealthCheckName()); gceOperations.addInstancesToTargetPool(gceClusterConfigurationHolder.getMemberList(), gceClusterConfigurationHolder.getTargetPoolName()); List<Integer> ipList = gceClusterConfigurationHolder.getIpList(); String portRange; if (ipList.isEmpty()) { log.warn("Ip list is null"); portRange = "1-65535"; } else if (ipList.size() == 1) { portRange = Integer.toString(ipList.get(0)) + "-" + Integer.toString(ipList.get(0)); } else { Collections.sort(ipList); portRange = Integer.toString(ipList.get(0)) + "-" + Integer.toString(ipList.get(ipList.size() - 1)); } if (log.isDebugEnabled()) { log.debug("Port range set as: " + portRange); } gceOperations.createForwardingRule(gceClusterConfigurationHolder.getForwardingRuleName(), gceClusterConfigurationHolder.getTargetPoolName(), PROTOCOL, portRange); <START> log.info("Created configuration for cluster"); <END> }</code><technical_language>log more meaningful, log cluster id well</technical_language>

Target:
private void createConfigurationForCluster(String clusterId) throws LoadBalancerExtensionException { log.info("Creating configuration for cluster " + clusterId + "..."); GCEClusterConfigurationHolder gceClusterConfigurationHolder = clusterToLoadBalancerConfigurationMap.get(clusterId); List<Integer> ipList = gceClusterConfigurationHolder.getIpList(); String portRange; if (ipList.isEmpty()) { log.warn("Ip list is null"); portRange = Constants.DEFAULT_PORT_RANGE; } else if (ipList.size() == 1) { portRange = Integer.toString(ipList.get(0)) + "-" + Integer.toString(ipList.get(0)); } else { Collections.sort(ipList); portRange = Integer.toString(ipList.get(0)) + "-" + Integer.toString(ipList.get(ipList.size() - 1)); } if (log.isDebugEnabled()) { log.debug("Port range set as: " + portRange); } Map healthCheckMap = gceClusterConfigurationHolder.getHealthCheckMap(); Iterator iterator = healthCheckMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry portMapNamePair = (Map.Entry) iterator.next(); gceOperations.createHealthCheck((Integer) portMapNamePair.getKey(), (String) portMapNamePair.getValue()); } gceOperations.createTargetPool(gceClusterConfigurationHolder.getTargetPoolName(), gceClusterConfigurationHolder.getHealthCheckNames()); gceOperations.addInstancesToTargetPool(gceClusterConfigurationHolder.getMemberList(), gceClusterConfigurationHolder.getTargetPoolName()); gceOperations.createForwardingRule(gceClusterConfigurationHolder.getForwardingRuleName(), gceClusterConfigurationHolder.getTargetPoolName(), Constants.PROTOCOL, portRange); log.info("Created configuration for cluster" + clusterId); }
Source:
<code>public void run(IProgressMonitor m) throws CoreException { if (m == null) { m = new NullProgressMonitor(); } m.beginTask(CoreText.ConnectProviderOperation_connecting, 100 * projects.size()); try { for (Iterator iterator = projects.keySet().iterator(); iterator.hasNext();) { IProject project = (IProject) iterator.next(); m.setTaskName(NLS.bind( CoreText.ConnectProviderOperation_ConnectingProject, project.getName())); Activator.trace("Locating repository for " + project); Collection<RepositoryMapping> repos = new RepositoryFinder( project).find(new SubProgressMonitor(m, 40)); Iterator<RepositoryMapping> mi = repos.iterator(); <START> RepositoryMapping actualMapping = mi.hasNext() ? mi.next() : null; <END> if (actualMapping != null) { GitProjectData projectData = new GitProjectData(project); try { projectData.setRepositoryMappings(Arrays.asList(actualMapping)); projectData.store(); } catch (CoreException ce) { GitProjectData.delete(project); throw ce; } catch (RuntimeException ce) { GitProjectData.delete(project); throw ce; } RepositoryProvider .map(project, GitProvider.class.getName()); projectData = GitProjectData.get(project); project.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(m, 50)); m.worked(10); } else { Activator .trace("Attempted to share project without repository ignored :" + project); m.worked(60); } } } finally { m.done(); } }</code><technical_language>this pick one, time? if null</technical_language>

Target:
public void run(IProgressMonitor m) throws CoreException { if (m == null) { m = new NullProgressMonitor(); } m.beginTask(CoreText.ConnectProviderOperation_connecting, 100 * projects.size()); try { for (Iterator iterator = projects.keySet().iterator(); iterator.hasNext();) { IProject project = (IProject) iterator.next(); m.setTaskName(NLS.bind( CoreText.ConnectProviderOperation_ConnectingProject, project.getName())); Activator.trace("Locating repository for " + project); Collection<RepositoryMapping> repos = new RepositoryFinder( project).find(new SubProgressMonitor(m, 40)); File suggestedRepo = projects.get(project); RepositoryMapping actualMapping= findActualRepository(repos, suggestedRepo); if (actualMapping != null) { GitProjectData projectData = new GitProjectData(project); try { projectData.setRepositoryMappings(Arrays.asList(actualMapping)); projectData.store(); } catch (CoreException ce) { GitProjectData.delete(project); throw ce; } catch (RuntimeException ce) { GitProjectData.delete(project); throw ce; } RepositoryProvider .map(project, GitProvider.class.getName()); projectData = GitProjectData.get(project); project.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(m, 50)); m.worked(10); } else { Activator .trace("Attempted to share project without repository ignored :" + project); m.worked(60); } } } finally { m.done(); } }
Source:
<code>public void setup() { <START> context.turnOffAuthorisationSystem(); <END> configurationService.setProperty("webui.user.assumelogin", true); context.restoreAuthSystemState(); }</code><technical_language>is needed, simplify code</technical_language>

Target:
public void setup() { configurationService.setProperty("webui.user.assumelogin", true); }
Source:
<code>protected ContentSecurityPolicy addOrAppend(String key, String value) { if (m_directives.containsKey(key)) { String existingSource = m_directives.get(key); <START> if ((existingSource != null || value != null) && !StringUtility.containsString(existingSource, value)) { <END> m_directives.put(key, StringUtility.join(SOURCE_SEPARATOR, existingSource, value)); } } else { m_directives.put(key, value); } return this; }</code><technical_language>write simpler? if (value == null) { return; } if (m_directives.containKey(key)) { ... if (!StringUtility.containsString(existingSource, value)) { ..</technical_language>

Target:
protected ContentSecurityPolicy addOrAppend(String key, String value) { if (value == null) { return this; } if (m_directives.containsKey(key)) { String existingSource = m_directives.get(key); if (!StringUtility.containsString(existingSource, value)) { m_directives.put(key, StringUtility.join(SOURCE_SEPARATOR, existingSource, value)); } } else { m_directives.put(key, value); } return this; }
Source:
<code><START> public AppendBlobClientBuilder credential(SharedKeyCredential credential) { <END> this.sharedKeyCredential = credential; return this; }</code><technical_language>Is base type interface for credentials? need overloads</technical_language>

Target:
public AppendBlobClientBuilder credential(SharedKeyCredential credential) { this.sharedKeyCredential = credential; this.tokenCredential = null; this.sasTokenCredential = null; return this; }
Source:
<code>public boolean canRefresh(DRepresentation representation) { return isSupported(representation) && <START> hasRelatedViewpointEnabled(representation); <END> }</code><technical_language>areRelatedViewpoint[s]Enabled</technical_language>

Target:
public boolean canRefresh(DRepresentation representation) { return isSupported(representation) && hasRequiredViewpointsEnabled(representation); }
Source:
<code>public static Set<String> authorityListToSet( Collection<? extends GrantedAuthority> userAuthorities) { <START> if (userAuthorities == null) { <END> return Collections.emptySet(); } Set<String> set = new HashSet<>(userAuthorities.size()); for (GrantedAuthority authority : userAuthorities) { set.add(authority.getAuthority()); } return set; }</code><technical_language>Actually, please this error? represents a programmer error if application is handing a null Collection this method. instead suggest like: suggestion Assert.notNull(userAuthorities, "userAuthorities null");</technical_language>

Target:
public static Set<String> authorityListToSet( Collection<? extends GrantedAuthority> userAuthorities) { Assert.notNull(userAuthorities, "userAuthorities cannot be null"); Set<String> set = new HashSet<>(userAuthorities.size()); for (GrantedAuthority authority : userAuthorities) { set.add(authority.getAuthority()); } return set; }
Source:
<code>protected Control createDialogArea(Composite parent) { Composite main = new Composite(parent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, true).applyTo(main); main.setLayout(new GridLayout(1, false)); TableViewer <START> projectsViewer = <END> new TableViewer(main, SWT.BORDER | SWT.V_SCROLL); GridDataFactory.fillDefaults().grab(true, true) .applyTo(projectsViewer.getControl()); projectsViewer.setLabelProvider( WorkbenchLabelProvider.getDecoratingWorkbenchLabelProvider()); projectsViewer.setContentProvider(ArrayContentProvider.getInstance()); projectsViewer.setInput(groupsToDelete); setTitle(UIText.RepositoriesView_RepoGroup_Delete_Title); setMessage(UIText.RepositoriesView_RepoGroup_Delete_Confirm); return main; }</code><technical_language>groupsViewer</technical_language>

Target:
protected Control createDialogArea(Composite parent) { Composite main = new Composite(parent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, true).applyTo(main); main.setLayout(new GridLayout(1, false)); TreeViewer groupsViewer = new TreeViewer(main, SWT.BORDER | SWT.V_SCROLL); GridDataFactory.fillDefaults().grab(true, true) .applyTo(groupsViewer.getControl()); groupsViewer.setLabelProvider( WorkbenchLabelProvider.getDecoratingWorkbenchLabelProvider()); groupsViewer.setContentProvider( new DeleteRepositoryGroupTreeContentProvider()); groupsViewer.setInput(groupsToDelete); setTitle(UIText.RepositoriesView_RepoGroup_Delete_Title); setMessage(UIText.RepositoriesView_RepoGroup_Delete_Confirm); return main; }
Source:
<code>public void setUp() throws Exception { super.setUp(); gitDir = new File(project.getProject() .getLocationURI().getPath(), Constants.DOT_GIT); testRepository = new TestRepository(gitDir); testRepository.connect(project.getProject()); <START> testRepository.commit("initial commit"); <END> }</code><technical_language>Please remove line. changes tests</technical_language>

Target:
public void setUp() throws Exception { super.setUp(); gitDir = new File(project.getProject() .getLocationURI().getPath(), Constants.DOT_GIT); testRepository = new TestRepository(gitDir); testRepository.connect(project.getProject()); }
Source:
<code><START> private Map<NodeId, Double> calculateFactors(WorkloadExecutionStatus status, Map<NodeId, WorkloadConfiguration> configurations) { <END> Map<NodeId, Double> result = new HashMap<NodeId, Double>(); Map<NodeId, Double> scores = new HashMap<NodeId, Double>(); int nodesCount = status.getNodes().size(); double scoreSum = 0; for (NodeId nodeId: status.getNodes()) { double totalSamplesRate = (status.getTotalSamples() == 0) ? (1d / nodesCount) : (double) status.getSamples(nodeId) / status.getTotalSamples(); double ownSamplesRate = (configurations.get(nodeId) == null || configurations.get(nodeId).getSamples() == 0) ? 1d : (double) status.getSamples(nodeId) / configurations.get(nodeId).getSamples(); double score = totalSamplesRate + ownSamplesRate * 10; scores.put(nodeId, score); scoreSum += score; } for (NodeId nodeId: status.getNodes()) { result.put(nodeId, scores.get(nodeId) / scoreSum); } return result; }</code><technical_language>need implement scoring algorithm based node's tps</technical_language>

Target:
private Map<NodeId, Double> calculateFactors(WorkloadExecutionStatus status, Map<NodeId, WorkloadConfiguration> configurations) { Map<NodeId, Double> result = new HashMap<NodeId, Double>(); Map<NodeId, Double> scores = new HashMap<NodeId, Double>(); int nodesCount = status.getNodes().size(); double scoreSum = 0; for (NodeId nodeId: status.getNodes()) { double totalSamplesRate = (status.getTotalSamples() == 0) ? (1d / nodesCount) : (double) status.getSamples(nodeId) / status.getTotalSamples(); double score = totalSamplesRate; scores.put(nodeId, score); scoreSum += score; } for (NodeId nodeId: status.getNodes()) { result.put(nodeId, scores.get(nodeId) / scoreSum); } return result; }
Source:
<code>protected void configure() { DynamicMap.mapOf(binder(), CONFIG_KIND); DynamicMap.mapOf(binder(), CAPABILITY_KIND); <START> DynamicMap.mapOf(binder(), CapabilityDefinition.class); <END> child(CONFIG_KIND, "capabilities").to(CapabilitiesCollection.class); }</code><technical_language>This sort of binding in GerritGlobalModule. line 244 in current master</technical_language>

Target:
protected void configure() { DynamicMap.mapOf(binder(), CONFIG_KIND); DynamicMap.mapOf(binder(), CAPABILITY_KIND); child(CONFIG_KIND, "capabilities").to(CapabilitiesCollection.class); }
Source:
<code>public void stop(final BundleContext context) throws Exception { SelectionRepositoryStateCache.INSTANCE.dispose(); if (focusListener != null) { if (PlatformUI.isWorkbenchRunning()) { PlatformUI.getWorkbench().removeWindowListener(focusListener); } focusListener = null; } if (GitTraceLocation.REPOSITORYCHANGESCANNER.isActive()) { GitTraceLocation.getTrace().trace( GitTraceLocation.REPOSITORYCHANGESCANNER.getLocation(), "Trying to cancel " + rcs.getName() + " job"); } getPreferenceStore().removePropertyChangeListener(rcs); <START> rcs.setReschedule(false); <END> rcs.cancel(); refreshJob.cancel(); if (GitTraceLocation.REPOSITORYCHANGESCANNER.isActive()) { GitTraceLocation.getTrace().trace( GitTraceLocation.REPOSITORYCHANGESCANNER.getLocation(), "Jobs terminated"); } if (resourceManager != null) { resourceManager.dispose(); resourceManager = null; } super.stop(context); plugin = null; }</code><technical_language>please add a NP check here? a headless application lot of xtext initializes lot of UI bundles in theory trigger egit ui activation, proper workbench startup. I fear end case this code is called service activated</technical_language>

Target:
public void stop(final BundleContext context) throws Exception { SelectionRepositoryStateCache.INSTANCE.dispose(); if (focusListener != null) { if (PlatformUI.isWorkbenchRunning()) { PlatformUI.getWorkbench().removeWindowListener(focusListener); } focusListener = null; } if (GitTraceLocation.REPOSITORYCHANGESCANNER.isActive()) { GitTraceLocation.getTrace().trace( GitTraceLocation.REPOSITORYCHANGESCANNER.getLocation(), "Trying to cancel " + rcs.getName() + " job"); } if (rcs != null) { getPreferenceStore().removePropertyChangeListener(rcs); rcs.setReschedule(false); rcs.cancel(); } refreshJob.cancel(); if (GitTraceLocation.REPOSITORYCHANGESCANNER.isActive()) { GitTraceLocation.getTrace().trace( GitTraceLocation.REPOSITORYCHANGESCANNER.getLocation(), "Jobs terminated"); } if (resourceManager != null) { resourceManager.dispose(); resourceManager = null; } super.stop(context); plugin = null; }
Source:
<code>public Node<View<?>, Edge> getParent(final double x, final double y) { <START> return CaseManagementBuilderControlHelper.getParent((CaseManagementCanvasHandler) canvasHandler, x, y); <END> }</code><technical_language>I is need create a helper class for this... I "original" code relying canvasHandler.getElementAt(x,y), this method is returning right element location. signature for canvasHandler#getElementAt, abstract method in class AbstractCanvasHandler, exist a case management concrete implementation CaseManagementCanvasHandler, overriding getElementAt method in CaseManagementCanvasHandler fix issue in CaseManagementBuilderControlHelper? This is need change lines, fix overriding getElementAt method in CaseManagementCanvasHandler</technical_language>

Target:
public Node<View<?>, Edge> getParent(final double x, final double y) { final Optional<Node<View<?>, Edge>> parent = canvasHandler.getElementAt(x, y); return parent.orElse(null); }
Source:
<code>public void addWall(Coordinate coordinate) { <START> if (!wallParts.add(coordinate)) <END> throw new IllegalArgumentException("There's already a wall at this coordinate"); if (playerStartingPositions.contains(coordinate)) throw new IllegalArgumentException("a startingpos cannot contain a wall"); this.squares.remove(coordinate); }</code><technical_language>This checked playerStartingPositions.contains(coordinate)</technical_language>

Target:
public void addWall(Coordinate coordinate) { if (playerStartingPositions.contains(coordinate)) throw new IllegalArgumentException("a startingpos cannot contain a wall"); if (!wallParts.add(coordinate)) throw new IllegalArgumentException("There's already a wall at this coordinate"); this.squares.remove(coordinate); }
Source:
<code>protected Object convert(Object in, Object cached) { Object o; try { o = outputClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { logger.error("Failed to create new instance of output POJO", e); <START> return null; <END> } for (Map.Entry<PojoUtils.Getter, PojoUtils.Setter> entry : fieldMap.entrySet()) { entry.getValue().set(o, entry.getKey().get(in)); } if (cached == null) { return null; } ArrayList<Object> includeObjects = (ArrayList<Object>)cached; int idx = 0; for (PojoUtils.Setter includeSetter : includeSetters) { try { includeSetter.set(o, includeObjects.get(idx++)); } catch (RuntimeException e) { logger.error("Failed to set the property. Continuing with default.", e); } } return o; }</code><technical_language>add metric here</technical_language>

Target:
protected Object convert(Object in, Object cached) { Object o; try { o = outputClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { logger.error("Failed to create new instance of output POJO", e); errorTupleCount++; error.emit(in); return null; } try { for (Map.Entry<PojoUtils.Getter, PojoUtils.Setter> entry : fieldMap.entrySet()) { entry.getValue().set(o, entry.getKey().get(in)); } } catch (RuntimeException e) { logger.error("Failed to set the property. Continuing with default.", e); errorTupleCount++; error.emit(in); return null; } if (cached == null) { return o; } ArrayList<Object> includeObjects = (ArrayList<Object>)cached; for (int i = 0; i < includeSetters.size(); i++) { try { includeSetters.get(i).set(o, includeObjects.get(i)); } catch (RuntimeException e) { logger.error("Failed to set the property. Continuing with default.", e); errorTupleCount++; error.emit(in); return null; } } return o; }
Source:
<code>public boolean addPlayer(ProxiedPlayer player) { Preconditions.checkNotNull( player, "player" ); if ( !players.contains( player ) ) { <START> players.add( player ); <END> } if ( player.isConnected() && visible ) { return sendPacket( player, addPacket() ); } return false; }</code><technical_language>Return if list contains</technical_language>

Target:
public void addPlayer(ProxiedPlayer player) { Preconditions.checkNotNull( player, "player" ); Preconditions.checkArgument( canBeAdded( player ), player.getName() + " cannot be added to BossBar ( make sure to use canBeAdded to avoid such errors )" ); if ( !canBeAdded( player ) ) { return; } players.add( player ); if ( player.isConnected() && visible ) { sendPacket( player, addPacket() ); } }
Source:
<code>public void updateNode(final OnmsNode node, String rescanExisting) { updateLocation(node); final OnmsNode dbNode = m_nodeDao.getHierarchy(node.getId()); String prevLocation = dbNode.getLocation().getLocationName(); String currentLocation = node.getLocation().getLocationName(); node.setCategories(dbNode.getCategories()); final EventAccumulator accumulator = new EventAccumulator(m_eventForwarder); dbNode.mergeNode(node, accumulator, false); updateNodeHostname(dbNode); m_nodeDao.update(dbNode); m_nodeDao.flush(); if(!prevLocation.equals(currentLocation)) { <START> accumulator.sendNow(EventUtils.createNodeLocationChangedEvent("Provisiond", dbNode.getId(), dbNode.getLabel(), prevLocation, currentLocation)); <END> } accumulator.flush(); final EntityVisitor eventAccumlator = new UpdateEventVisitor(m_eventForwarder, rescanExisting); dbNode.visit(eventAccumlator); }</code><technical_language>Is a constant instead "Provisiond" literal? (Similar bellow too)</technical_language>

Target:
public void updateNode(final OnmsNode node, String rescanExisting) { updateLocation(node); final OnmsNode dbNode = m_nodeDao.getHierarchy(node.getId()); String prevLocation = dbNode.getLocation().getLocationName(); String currentLocation = node.getLocation().getLocationName(); node.setCategories(dbNode.getCategories()); final EventAccumulator accumulator = new EventAccumulator(m_eventForwarder); dbNode.mergeNode(node, accumulator, false); updateNodeHostname(dbNode); m_nodeDao.update(dbNode); m_nodeDao.flush(); if(!prevLocation.equals(currentLocation)) { accumulator.sendNow(EventUtils.createNodeLocationChangedEvent(PROVISIOND, dbNode.getId(), dbNode.getLabel(), prevLocation, currentLocation)); } accumulator.flush(); final EntityVisitor eventAccumlator = new UpdateEventVisitor(m_eventForwarder, rescanExisting); dbNode.visit(eventAccumlator); }
Source:
<code>private void discoverEntities(final StatementPattern pattern, final List<StatementPattern> unmatched) { final Var subj = pattern.getSubjectVar(); final String subjStr = subj.getName(); final RyaURI predURI = getPredURI(pattern); if(new URIImpl(predURI.getData()).equals(RDF.TYPE)) { final Var obj = pattern.getObjectVar(); final RyaURI objURI = new RyaURI(obj.getValue().stringValue()); try { final Optional<Type> optType = typeStorage.get(objURI); if(optType.isPresent()) { final Type type = optType.get(); typeMap.put(type, pattern); subjectTypeMap.put(subjStr, type); for(final StatementPattern propertyPattern : unmatched) { final RyaURI property = getPredURI(propertyPattern); <START> final Var typeSubVar = getTypeSubject(type); <END> final Var patternSubVar = propertyPattern.getSubjectVar(); if (type.getPropertyNames().contains(property) && typeSubVar.equals(patternSubVar)) { typeMap.put(type, propertyPattern); } } } } catch (final TypeStorageException e) { e.printStackTrace(); } } else { if(subjectTypeMap.containsKey(subjStr)) { final Type type = subjectTypeMap.get(subjStr); if(type.getPropertyNames().contains(predURI)) { typeMap.put(type, pattern); } else { unmatched.add(pattern); } } else { unmatched.add(pattern); } } }</code><technical_language>call getTypeSubject extract subject Var typeMap? access subjStr. call propertyPattern.getSubjectVar().getName() do a String comparison in if clause in line 103</technical_language>

Target:
private void discoverEntities(final StatementPattern pattern, final List<StatementPattern> unmatched) { final Var subj = pattern.getSubjectVar(); final String subjStr = subj.getName(); final RyaURI predURI = getPredURI(pattern); if(new URIImpl(predURI.getData()).equals(RDF.TYPE)) { final Var obj = pattern.getObjectVar(); final RyaURI objURI = new RyaURI(obj.getValue().stringValue()); try { final Optional<Type> optType = typeStorage.get(objURI); if(optType.isPresent()) { final Type type = optType.get(); typeMap.put(type, pattern); subjectTypeMap.put(subjStr, type); for(final StatementPattern propertyPattern : unmatched) { final RyaURI property = getPredURI(propertyPattern); final Var typeSubVar = getTypeSubject(type); final Var patternSubVar = propertyPattern.getSubjectVar(); if (type.getPropertyNames().contains(property) && typeSubVar.equals(patternSubVar)) { typeMap.put(type, propertyPattern); } } } } catch (final TypeStorageException e) { e.printStackTrace(); } } else { if(subjectTypeMap.containsKey(subjStr)) { final Type type = subjectTypeMap.get(subjStr); if(type.getPropertyNames().contains(predURI)) { if(!typeMap.containsKey(type)) { typeMap.put(type, pattern); } } else { unmatched.add(pattern); } } else { unmatched.add(pattern); } } }
Source:
<code>public String toString() { String prefix = service.getClass().getCanonicalName() + "#" + method.getName() + "("; return Stream .of(method.getParameters()) .map(Parameter::getType) .map(Class::getSimpleName) <START> .collect(joining(", ", prefix, ")")); <END> }</code><technical_language>This .toString is confusing. simpler. line 144 "(" string. concat service.getClass().getCanonicalName() + "#" + method.getName() updated joined string</technical_language>

Target:
public String toString() { String classAndMethod = service.getClass().getCanonicalName() + "#" + method.getName(); String args = Stream.of(method.getParameters()) .map(Parameter::getType) .map(Class::getSimpleName) .collect(Collectors.joining(", ", "(", ")")); return classAndMethod + args; }
Source:
<code>public void onNext(T t) { if (index++ % skip == 0) { U b; try { <START> b = ObjectHelper.requireNonNull(bufferSupplier.call(), "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); <END> } catch (Throwable e) { buffers.clear(); s.dispose(); actual.onError(e); return; } buffers.offer(b); } Iterator<U> it = buffers.iterator(); while (it.hasNext()) { U b = it.next(); b.add(t); if (count <= b.size()) { it.remove(); actual.onNext(b); } } }</code><technical_language>"onNext" --> "bufferSupplier"</technical_language>

Target:
public void onNext(T t) { if (index++ % skip == 0) { U b; try { b = ObjectHelper.requireNonNull(bufferSupplier.call(), "The bufferSupplier returned a null collection. Null values are generally not allowed in 2.x operators and sources."); } catch (Throwable e) { buffers.clear(); s.dispose(); actual.onError(e); return; } buffers.offer(b); } Iterator<U> it = buffers.iterator(); while (it.hasNext()) { U b = it.next(); b.add(t); if (count <= b.size()) { it.remove(); actual.onNext(b); } } }
Source:
<code><START> private static int getTsValue(ByteBuffer pcapPacketHeader, int blockLength, int option) { <END> int count = 0; int optionCode; int optionValue; int optionLength; int optionBufferLength = blockLength - PcapFileValues.INTERFACE_DESCRIPTION_SIZE * 2 - 4; if (optionBufferLength == 0) { return 6; } pcapPacketHeader.position(16); while (count < optionBufferLength) { optionCode = ConversionHelper.unsignedShortToInt(pcapPacketHeader.getShort()); if (optionCode < 2 || optionCode > 14) { return 0; } count = count + 2; optionLength = ConversionHelper.unsignedShortToInt(pcapPacketHeader.getShort()); count += 2; if (optionLength <= 4) { optionValue = pcapPacketHeader.getInt(); if (optionCode == option) { return optionValue; } count += 4; } else { for (int i = 0; i <= optionLength; i++) { pcapPacketHeader.get(); } count += optionLength + 1; } } if (option == PcapFileValues.PCAPNG_IFTSRESOL_CODE) { return 6; } return 0; }</code><technical_language>this method receive Options block ByteBuffer instead? I this easily done ByteBuffer.slice() in parseIDBBlock() method is parsing IDB body is positioned beginning of Options</technical_language>

Target:
private static int getTsValue(ByteBuffer pcapPacketHeader, int blockLength, int option) { int count = 0; int optionCode; int optionValue; int optionLength; int optionBufferLength = blockLength - PcapFileValues.INTERFACE_DESCRIPTION_SIZE * 2 - 4; if (optionBufferLength == 0) { return 6; } pcapPacketHeader.position(16); while (count < optionBufferLength) { optionCode = ConversionHelper.unsignedShortToInt(pcapPacketHeader.getShort()); if (optionCode < 2 || optionCode > 14) { break; } count = count + 2; optionLength = ConversionHelper.unsignedShortToInt(pcapPacketHeader.getShort()); count += 2; if (optionLength <= 4) { optionValue = pcapPacketHeader.getInt(); if (optionCode == option) { return optionValue; } count += 4; } else { for (int i = 0; i <= optionLength; i++) { pcapPacketHeader.get(); } count += optionLength + 1; } } if (option == PcapFileValues.PCAPNG_IFTSRESOL_CODE) { return 6; } return 0; }
Source:
<code>protected Symbol visitLikePredicate(LikePredicate node, ExpressionAnalysisContext context) { if (node.getEscape() != null) { throw new UnsupportedOperationException("ESCAPE is not supported."); } Symbol expression = node.getValue().accept(this, context); Symbol pattern = node.getPattern().accept(this, context); <START> Symbol ignoreCase = Literal.of(node.getIgnoreCase() ? "true" : "false"); <END> return allocateFunction( LikeOperator.NAME, ImmutableList.of(expression, pattern, ignoreCase), context); }</code><technical_language>create a boolean string literal convert a boolean? a Literal.of(node.getIgnoreCase()) boolean</technical_language>

Target:
protected Symbol visitLikePredicate(LikePredicate node, ExpressionAnalysisContext context) { if (node.getEscape() != null) { throw new UnsupportedOperationException("ESCAPE is not supported."); } Symbol expression = node.getValue().accept(this, context); Symbol pattern = node.getPattern().accept(this, context); Symbol ignoreCase = Literal.of(node.getIgnoreCase()); return allocateFunction( LikeOperator.NAME, ImmutableList.of(expression, pattern, ignoreCase), context); }
Source:
<code>private void addMacPool(final DataCenterModel dcModel) { SharedMacPoolModel macPoolModel = new NewSharedMacPoolModel(this) { @Override protected void postSave(Guid macPoolId) { super.postSave(macPoolId); ArrayList<MacPool> macPools = new ArrayList<MacPool>(dcModel.getMacPoolListModel().getItems()); <START> macPools.add(1, getEntity()); <END> dcModel.getMacPoolListModel().setItems(macPools); dcModel.getMacPoolListModel().setSelectedItem(getEntity()); } }; setConfirmWindow(macPoolModel); }</code><technical_language>I reason add element of list. IMO, added natural place SharedMacPoolComparator</technical_language>

Target:
private void addMacPool(final DataCenterModel dcModel) { SharedMacPoolModel macPoolModel = new NewSharedMacPoolModel(this) { @Override protected void onActionSucceeded(Guid macPoolId) { MacPool macPool = getEntity(); macPool.setId(macPoolId); dcModel.getMacPoolListModel().getItems().add(macPool); dcModel.getMacPoolListModel().setSelectedItem(macPool); DataCenterListModel.this.setConfirmWindow(null); } }; macPoolModel.setEntity(new MacPool()); setConfirmWindow(macPoolModel); }
Source:
<code>public void attach(ServoController controller, Integer pin, Double pos, Double speed) throws Exception { if (controller == null) { log.error("{}.attach(null)", getName()); return; } if (controllers.contains(controller.getName())) { log.info("{}.attach({}) controller already attached", getName(), controller.getName()); return; } if (pin != null) { setPin(pin); } if (pos != null) { targetPos = pos; lastPos = targetPos; } if (speed != null) { <START> setSpeed(speed); <END> } controllers.add(controller.getName()); controller.attach(this); }</code><technical_language>velocity.</technical_language>

Target:
public void attach(ServoController controller, Integer pin, Double pos, Double speed) throws Exception { attach(controller, pin, pos, speed, null); }
Source:
<code>private void trackSessionIfNeeded(final Session session) { boolean notifyForRelease = configuration.shouldNotifyForReleaseStage(getReleaseStage()); if (notifyForRelease && (configuration.shouldAutoCaptureSessions() || !session.isAutoCaptured()) && session.isTracked().compareAndSet(false, true)) { try { final String endpoint = configuration.getSessionEndpoint(); Async.run(new Runnable() { @Override public void run() { flushStoredSessions(); SessionTrackingPayload payload = new SessionTrackingPayload(session, client.appData); try { configuration.getDelivery().deliver(payload, configuration); } catch (NetworkException exception) { <START> Logger.info("Failed to post session payload"); <END> sessionStore.write(session); } catch (BadResponseException exception) { Logger.warn("Invalid session tracking payload", exception); } } }); } catch (RejectedExecutionException exception) { sessionStore.write(session); } } }</code><technical_language>exception logged</technical_language>

Target:
private void trackSessionIfNeeded(final Session session) { boolean notifyForRelease = configuration.shouldNotifyForReleaseStage(getReleaseStage()); if (notifyForRelease && (configuration.shouldAutoCaptureSessions() || !session.isAutoCaptured()) && session.isTracked().compareAndSet(false, true)) { try { final String endpoint = configuration.getSessionEndpoint(); Async.run(new Runnable() { @Override public void run() { flushStoredSessions(); SessionTrackingPayload payload = new SessionTrackingPayload(session, client.appData); try { configuration.getDelivery().deliver(payload, configuration); } catch (DeliveryFailureException exception) { Logger.warn("Storing session payload for future delivery", exception); sessionStore.write(session); } catch (Exception exception) { Logger.warn("Dropping invalid session tracking payload", exception); } } }); } catch (RejectedExecutionException exception) { sessionStore.write(session); } } }
Source:
<code>public void setTTL(K key, long ttl, TimeUnit timeunit) { <START> if (getNodeEngine().getClusterService().getClusterVersion().isLessThan(Versions.V3_11)) { <END> throw new UnsupportedOperationException("setTTL method is available when cluster version is 3.11 or higher"); } checkNotNull(key); setTTLInternal(key, ttl, timeunit); }</code><technical_language>If add this version check default-record-store, client initiated operations caught</technical_language>

Target:
public void setTTL(K key, long ttl, TimeUnit timeunit) { checkNotNull(key); checkNotNull(timeunit); setTTLInternal(key, ttl, timeunit); }
Source:
<code>protected void buildTagList(File directory, boolean interactive) { <START> this.tagList = new TreeSet<>(); <END> ArrayList<String> argv = new ArrayList<>(); ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK); argv.add(RepoCommand); argv.add("tags"); Executor executor = new Executor(argv, directory, RuntimeEnvironment.getInstance().getInteractiveCommandTimeout()); MercurialTagParser parser = new MercurialTagParser(); int status = executor.exec(true, parser); if (status != 0) { LOGGER.log(Level.WARNING, "Failed to get tags for: \"{0}\" Exit code: {1}", new Object[]{directory.getAbsolutePath(), String.valueOf(status)}); } else { this.tagList = parser.getEntries(); } }</code><technical_language>new interactive in method</technical_language>

Target:
protected void buildTagList(File directory, boolean interactive) { this.tagList = new TreeSet<>(); ArrayList<String> argv = new ArrayList<>(); ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK); argv.add(RepoCommand); argv.add("tags"); Executor executor = new Executor(argv, directory, interactive ? RuntimeEnvironment.getInstance().getInteractiveCommandTimeout() : RuntimeEnvironment.getInstance().getCommandTimeout()); MercurialTagParser parser = new MercurialTagParser(); int status = executor.exec(true, parser); if (status != 0) { LOGGER.log(Level.WARNING, "Failed to get tags for: \"{0}\" Exit code: {1}", new Object[]{directory.getAbsolutePath(), String.valueOf(status)}); } else { this.tagList = parser.getEntries(); } }