auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Object evaluate(String js, IPageContext pageContext) { JSPMultiPageEditor editor = WebUiPlugin.getActiveMultiPageEditor(); if(editor!=null) { IVisualEditor ve = editor.getVisualEditor(); if(ve!=null) { ve.initBrowser(); Object obj = ve.getVisualEditor(); if(obj instanceof VpvEditor) { VpvEditor vpv = (VpvEditor)obj; Browser browser = vpv.getBrowser(); if(browser!=null && !browser.isDisposed()) { Map<String, String> parameters = new HashMap<String, String>(); parameters.put(BrowserDataProviderManager.ELEMENT_ID_PARAM, VpvDomBuilder.ATTR_VPV_ID); Long id = vpv.getCurrentSelectedElementId(); if(id!=null) { <START> parameters.put(BrowserDataProviderManager.ELEMENT_ID_VALUE_PARAM, id.toString()); <END> js = BrowserDataProviderManager.format(js, parameters); return browser.evaluate(js); } } } } } return ""; }</code><technical_language>interesting - I thought snippet injected page upfront is done dynamically in page</technical_language>

Target:
public Object evaluate(String js, IPageContext pageContext) { JSPMultiPageEditor editor = WebUiPlugin.getActiveMultiPageEditor(); if(editor!=null) { IVisualEditor ve = editor.getVisualEditor(); if(ve!=null) { ve.initBrowser(); Object obj = ve.getVisualEditor(); if(obj instanceof VpvEditor) { VpvEditor vpv = (VpvEditor)obj; Browser browser = vpv.getBrowser(); if(browser!=null && !browser.isDisposed()) { Map<String, String> parameters = new HashMap<String, String>(); parameters.put(BrowserDataProviderManager.ELEMENT_ID_PARAM, VpvDomBuilder.ATTR_VPV_ID); Long id = vpv.getCurrentSelectedElementId(); if(id!=null) { parameters.put(BrowserDataProviderManager.ELEMENT_ID_VALUE_PARAM, id.toString()); js = BrowserDataProviderManager.format(js, parameters); try { return browser.evaluate(js); } catch(SWTException e) { if(e.code != SWT.ERROR_FAILED_EVALUATE && e.code != SWT.ERROR_INVALID_RETURN_VALUE) { Activator.logError(e); } } } } } } } return ""; }
Source:
<code>public Message getValue(Message object) { final Message fieldValue; final Message result; try { fieldValue = (Message) getter.invoke(object); result = fieldValue instanceof Any <START> ? AnyPacker.unpack((Any) fieldValue) <END> : fieldValue; } catch (IllegalAccessException | InvocationTargetException e) { throw wrappedCause(e); } return result; }</code><technical_language>Please check if is Any.getDefaultInstance(). If I remember right, AnyPacker throw exception in case</technical_language>

Target:
public Optional<Message> getValue(Message object) { final Message fieldValue; final Message result; try { fieldValue = (Message) getter.invoke(object); if (fieldValue instanceof Any) { final Any any = (Any)fieldValue; if (isDefault(any)) { return Optional.absent(); } result = AnyPacker.unpack(any); } else { result = fieldValue; } } catch (IllegalAccessException | InvocationTargetException e) { throw wrappedCause(e); } return Optional.fromNullable(result); }
Source:
<code>public boolean equals(Object o) { boolean equals = this == o || o instanceof <START> URIEditorInput && <END> getURI().equals(((URIEditorInput) o).getURI()); if (equals && o instanceof SessionEditorInput) { EObject input = getInput(false); if (input != null) { SessionEditorInput otherSessionEditorInput = (SessionEditorInput) o; return input.equals(otherSessionEditorInput.getInput(false)); } } return equals; }</code><technical_language>this SessionEditorInput? equals() return true for instances of subclasses of URIEditorInput point URI. I checked, happen if aird opened time a non-Sirius editor</technical_language>

Target:
public boolean equals(Object o) { boolean equals = this == o || o instanceof SessionEditorInput && getURI().equals(((SessionEditorInput) o).getURI()); if (equals && o instanceof SessionEditorInput) { EObject input = getInput(false); if (input != null) { SessionEditorInput otherSessionEditorInput = (SessionEditorInput) o; return input.equals(otherSessionEditorInput.getInput(false)); } } return equals; }
Source:
<code>public void renderHead(Component component, IHeaderResponse response) { super.renderHead(component, response); response.render(JavaScriptHeaderItem.forReference(FileUploadGlueJavaScriptResourceReference.get())); response.render(OnDomReadyHeaderItem.forScript(statement(component).render())); Component adresse = new WebMarkupContainer("adresse"); Component complement = new WebMarkupContainer("complement"); int ADRESSE_MAXIMUM_LENGTH = 36; response.render(OnDomReadyHeaderItem.forScript( new JsStatement().$(null).chain( EventsHelper.keyup().chainLabel(), new JsStatement().append("suivant(" + adresse.getMarkupId() + "," + complement.getMarkupId() + "," + ADRESSE_MAXIMUM_LENGTH + ")").render() ).render() <START> )); <END> }</code><technical_language>removed... :)</technical_language>

Target:
public void renderHead(Component component, IHeaderResponse response) { super.renderHead(component, response); response.render(JavaScriptHeaderItem.forReference(FileUploadGlueJavaScriptResourceReference.get())); response.render(OnDomReadyHeaderItem.forScript(statement(component).render())); }
Source:
<code>public VariantSourceMongo(IVariantSource variantSource) { this.fileId = variantSource.getFileId(); this.fileName = variantSource.getFileName(); this.studyId = variantSource.getStudyId(); this.studyName = variantSource.getStudyName(); this.type = variantSource.getType(); this.aggregation = variantSource.getAggregation(); this.samplesPosition = new HashMap<>(); Map<String,Integer> samplesPosition = variantSource.getSamplesPosition(); if (samplesPosition != null && !samplesPosition.isEmpty()) { this.samplesPosition.putAll(samplesPosition); } this.metadata = new HashMap<>(); Map<String, Object> metadata = variantSource.getMetadata(); if (metadata != null && !metadata.isEmpty()) { this.metadata.putAll(metadata); } <START> this.stats = (VariantGlobalStatsMongo)(variantSource.getStats()); <END> this.date = variantSource.getDate(); }</code><technical_language>This cast write wrong field names if instance is a regular VariantGlobalStats. create a new instance of VariantGlobalStatsMongo copying attributes of variantSource.getStats()</technical_language>

Target:
public VariantSourceMongo(IVariantSource variantSource) { this(variantSource.getFileId(), variantSource.getFileName(), variantSource.getStudyId(), variantSource.getStudyName(), variantSource.getType(), variantSource.getAggregation(), variantSource.getSamplesPosition(), variantSource.getMetadata(), new VariantGlobalStatsMongo(variantSource.getStats())); }
Source:
<code>public ItemMarkingInfo getItemMarkingInfo(Context context, Item item) throws SQLException { if (metadataField != null && mapping!=null) { <START> DCValue[] vals = item.getMetadata(metadataField); <END> if (vals.length > 0) { for (DCValue value : vals){ String type = value.value; if (mapping.containsKey(type)){ return mapping.get(type); } } } } return null; }</code><technical_language>Compile error occurs this line. current master. DCValue[] vals = item.getMetadataByMetadataString(metadaField);</technical_language>

Target:
public ItemMarkingInfo getItemMarkingInfo(Context context, Item item) throws SQLException { if (metadataField != null && mapping!=null) { DCValue[] vals = item.getMetadataByMetadataString(metadataField); if (vals.length > 0) { for (DCValue value : vals){ String type = value.value; if (mapping.containsKey(type)){ return mapping.get(type); } } } } return null; }
Source:
<code>public void test_futureValueSensitivity_ISDA() { RateObservationFn<RateObservation> mockObs = mock(RateObservationFn.class); PricingEnvironment mockEnv = mock(PricingEnvironment.class); ExpandedFra fraExp = FRA.expand(); double forwardRate = 0.05; LocalDate fixingDate = FRA.getStartDate(); PointSensitivityBuilder snese = IborRateSensitivity.of(FRA.getIndex(), fixingDate, 1d); when(mockObs.rateSensitivity(mockEnv, fraExp.getFloatingRate(), fraExp.getStartDate(), fraExp.getEndDate())) .thenReturn(snese); when(mockObs.rate(mockEnv, fraExp.getFloatingRate(), FRA.getStartDate(), FRA.getEndDate())) .thenReturn(forwardRate); DiscountingExpandedFraPricerFn test = new DiscountingExpandedFraPricerFn(mockObs); PointSensitivities sensitivity = test.futureValueSensitivity(mockEnv, fraExp); double eps = 1.e-7; double fdSense = futureValueFwdSensitivity(FRA, forwardRate, eps); <START> assertEquals(sensitivity.getSensitivities().size(), 1); <END> assertEquals(sensitivity.getSensitivities().get(0).getCurveKey(), FRA.getIndex()); assertEquals(sensitivity.getSensitivities().get(0).getDate(), fixingDate); assertEquals(sensitivity.getSensitivities().get(0).getSensitivity(), fdSense, FRA.getNotional() * eps); }</code><technical_language>Stick sensitivity.getSensitivities() in a var</technical_language>

Target:
public void test_futureValueSensitivity_ISDA() { RateObservationFn<RateObservation> mockObs = mock(RateObservationFn.class); PricingEnvironment mockEnv = mock(PricingEnvironment.class); ExpandedFra fraExp = FRA.expand(); double forwardRate = 0.05; LocalDate fixingDate = FRA.getStartDate(); PointSensitivityBuilder sens = IborRateSensitivity.of(FRA.getIndex(), fixingDate, 1d); when(mockObs.rateSensitivity(mockEnv, fraExp.getFloatingRate(), fraExp.getStartDate(), fraExp.getEndDate())) .thenReturn(sens); when(mockObs.rate(mockEnv, fraExp.getFloatingRate(), FRA.getStartDate(), FRA.getEndDate())) .thenReturn(forwardRate); DiscountingExpandedFraPricerFn test = new DiscountingExpandedFraPricerFn(mockObs); PointSensitivities sensitivity = test.futureValueSensitivity(mockEnv, fraExp); double eps = 1.e-7; double fdSense = futureValueFwdSensitivity(FRA, forwardRate, eps); ImmutableList<PointSensitivity> sensitivities = sensitivity.getSensitivities(); assertEquals(sensitivities.size(), 1); PointSensitivity sensitivity0 = sensitivities.get(0); assertEquals(sensitivity0.getCurveKey(), FRA.getIndex()); assertEquals(sensitivity0.getDate(), fixingDate); assertEquals(sensitivity0.getSensitivity(), fdSense, FRA.getNotional() * eps); }
Source:
<code>public SearchQueryBuilder query(Map<String, Object> q, boolean caseSensitive) { <START> querySpec = new ContainsSearchQuerySpec((String) q.get("value"), caseSensitive); <END> return this; }</code><technical_language>Suggest querySpec = new ContainsSearchQuerySpec(Preconditions.checkNotNull(q.get("value"), "no value").toString(), caseSensitive); similar</technical_language>

Target:
public SearchQueryBuilder query(Map<String, Object> q, boolean caseSensitive) { String value = Preconditions.checkNotNull(q.get("value"), "no value").toString(); querySpec = new ContainsSearchQuerySpec(value, caseSensitive); return this; }
Source:
<code><START> public static void setVerbose(int n) { <END> m_verbose = n; }</code><technical_language><test> node verbose value, m_verbose non-static</technical_language>

Target:
public void setVerbose(int n) { m_verbose = n; }
Source:
<code>public int addOfficial(Member official) { <START> if(official == null || this.officials.contains(official) || official.getUserType()!=Member.UserType.OFFICIAL) { <END> return -1; } if(this.officials.size() == tournament.getOfficialsPerGame()) { return 0; } this.officials.add(official); return 1; }</code><technical_language>coordinators allowed officials</technical_language>

Target:
public int addOfficial(Member official) { if(official == null || this.officials.contains(official) || MemberUtils.atLeastOfficial(official)) { return -1; } if(this.officials.size() == tournament.getOfficialsPerGame()) { return 0; } this.officials.add(official); return 1; }
Source:
<code>public double hitRatio() { <START> return ((double) hits()) / (hits() + faults()); <END> }</code><technical_language>I extract hits local variable if return calls</technical_language>

Target:
public double hitRatio() { return MathUtil.portion( hits(), faults() ); }
Source:
<code>public int getErrorCode() { if (isSuccessful()) { <START> return Activity.RESULT_OK; <END> } else if (mException instanceof NetworkException) { return ErrorCodes.NO_NETWORK; } else { return ErrorCodes.UNKNOWN_ERROR; } }</code><technical_language>for this method return RESULT_OK before? poorly named getErrorCode getResultCode. if this worth breaking API fix it</technical_language>

Target:
public int getErrorCode() { if (isSuccessful()) { return Activity.RESULT_OK; } else { return mException.getErrorCode(); } }
Source:
<code>public void writeLine(String line) throws IOException { <START> try { <END> if (line != null) { writer.write(line); } writer.write('\n'); writer.flush(); } catch (IOException e) { if("Stream closed".equals(e.getMessage())) { throw new ConsumerAlreadyClosedException(e.getMessage()); } throw e; } }</code><technical_language>please check closing status</technical_language>

Target:
public void writeLine(String line) throws IOException { if (isOpen) { try { if (line != null) { writer.write(line); } writer.write('\n'); writer.flush(); } catch (IOException e) { if ("Stream closed".equals(e.getMessage())) { throw new ConsumerAlreadyClosedException(e.getMessage()); } throw e; } } }
Source:
<code>public void setUp() throws IOException, InterruptedException { ttsService = new TTSServiceStub(); hliStub = new HumanLanguageInterpreterStub(); voice = new VoiceStub(); registerService(voice); registerService(hliStub); registerService(ttsService); Dictionary<String, Object> config = new Hashtable<String, Object>(); config.put(CONFIG_DEFAULT_TTS, ttsService.getId()); config.put(CONFIG_DEFAULT_HLI, hliStub.getId()); config.put(CONFIG_DEFAULT_VOICE, voice.getUID()); ConfigurationAdmin configAdmin = super.getService(ConfigurationAdmin.class); String pid = "org.eclipse.smarthome.voice"; Configuration configuration = configAdmin.getConfiguration(pid); configuration.update(config); <START> Thread.sleep(100); <END> }</code><technical_language>try find a detect if configuration applied successfully put a waitForAssert-Block</technical_language>

Target:
public void setUp() throws IOException, InterruptedException { ttsService = new TTSServiceStub(); hliStub = new HumanLanguageInterpreterStub(); voice = new VoiceStub(); registerService(voice); registerService(hliStub); registerService(ttsService); Dictionary<String, Object> config = new Hashtable<String, Object>(); config.put(CONFIG_DEFAULT_TTS, ttsService.getId()); config.put(CONFIG_DEFAULT_HLI, hliStub.getId()); config.put(CONFIG_DEFAULT_VOICE, voice.getUID()); ConfigurationAdmin configAdmin = super.getService(ConfigurationAdmin.class); String pid = "org.eclipse.smarthome.voice"; Configuration configuration = configAdmin.getConfiguration(pid); configuration.update(config); }
Source:
<code><START> public static void initializeIndexIfNeeded(Directory directory, EventContext eventContext) throws IOException { <END> if ( DirectoryReader.indexExists( directory ) ) { return; } try { IndexWriterConfig iwriterConfig = new IndexWriterConfig( AnalyzerConstants.KEYWORD_ANALYZER ) .setOpenMode( OpenMode.CREATE_OR_APPEND ); SleepingLockWrapper delayedDirectory = new SleepingLockWrapper( directory, 2000, 20 ); IndexWriter iw = new IndexWriter( delayedDirectory, iwriterConfig ); iw.close(); } catch (LockObtainFailedException lofe) { log.lockingFailureDuringInitialization( directory.toString() ); } }</code><technical_language>parameter eventContext is in method body</technical_language>

Target:
public static void initializeIndexIfNeeded(Directory directory, EventContext eventContext) throws IOException { if ( DirectoryReader.indexExists( directory ) ) { return; } try { IndexWriterConfig iwriterConfig = new IndexWriterConfig( AnalyzerConstants.KEYWORD_ANALYZER ) .setOpenMode( OpenMode.CREATE_OR_APPEND ); SleepingLockWrapper delayedDirectory = new SleepingLockWrapper( directory, 2000, 20 ); IndexWriter iw = new IndexWriter( delayedDirectory, iwriterConfig ); iw.close(); } catch (LockObtainFailedException lofe) { log.lockingFailureDuringInitialization( directory.toString(), eventContext ); } }
Source:
<code>public JSONObject isSerialNumberUnique(HttpSession session, JSONObject json) { if (!json.has("serialNumber") || (json.has("serialNumber") && isStringEmptyOrNull(json.getString("serialNumber")))) { return JSONUtils.SimpleJSONError("Please supply a barcode to lookup."); } try { String serialNumber = json.getString("serialNumber"); String containerId = json.getString("containerId"); Collection<SequencerPartitionContainer<SequencerPoolPartition>> containers = requestManager .listSequencerPartitionContainersByBarcode(serialNumber); Map<String, Object> responseMap = new HashMap<String, Object>(); if (containers.isEmpty()) { responseMap.put("isSerialNumberUnique", true); } else { SequencerPartitionContainer<SequencerPoolPartition> container = new ArrayList<>(containers).get(0); if (containerId != null && !containerId.equals("null") && Long.valueOf(containerId).longValue() == container.getId()) { responseMap.put("isSerialNumberUnique", true); } else { responseMap.put("isSerialNumberUnique", false); } } return JSONUtils.JSONObjectResponse(responseMap); } catch (IOException e) { log.error("unable to lookup barcode", e); <START> return JSONUtils.JSONObjectResponse("error", "Unable to lookup barcode."); <END> } }</code><technical_language>barcode changed serial number this is user-facing text. (same above, line 937) (would extra nice if change instances of barcode serial number lines 795-805, a requirement for this ticket :) )</technical_language>

Target:
public JSONObject isSerialNumberUnique(HttpSession session, JSONObject json) { if (!json.has("serialNumber") || (json.has("serialNumber") && isStringEmptyOrNull(json.getString("serialNumber")))) { return JSONUtils.SimpleJSONError("Please supply a serial number to lookup."); } String serialNumber = json.getString("serialNumber"); String containerId = json.getString("containerId"); Map<String, Object> responseMap = new HashMap<String, Object>(); try { Collection<SequencerPartitionContainer<SequencerPoolPartition>> containers = requestManager .listSequencerPartitionContainersByBarcode(serialNumber); if (containers.isEmpty()) { responseMap.put("isSerialNumberUnique", true); } else { SequencerPartitionContainer<SequencerPoolPartition> container = new ArrayList<>(containers).get(0); if (containerId != null && !containerId.equals("null") && Long.valueOf(containerId).longValue() == container.getId()) { responseMap.put("isSerialNumberUnique", true); } else { responseMap.put("isSerialNumberUnique", false); } } return JSONUtils.JSONObjectResponse(responseMap); } catch (IOException e) { String err = String.format("Unable to lookup serial number %s.", serialNumber); log.error(err, e); responseMap.put("error", err); responseMap.put("isSerialNumberUnique", false); return JSONUtils.JSONObjectResponse(responseMap); } }
Source:
<code>public Map<String, Integer> getNumberOfTasksAdded() { Map<String, Integer> numberOfTasksAdded = new HashMap<>(); for (TaskWrapper task : tasksAdded) { String queueName = task.getQueueName(); <START> int oldTaskCount = numberOfTasksAdded.computeIfAbsent(queueName, (String key) -> 0); <END> numberOfTasksAdded.put(queueName, oldTaskCount + 1); } return numberOfTasksAdded; }</code><technical_language>This a job for getOrDefault computeIfAbsent</technical_language>

Target:
public Map<String, Integer> getNumberOfTasksAdded() { Map<String, Integer> numberOfTasksAdded = new HashMap<>(); for (TaskWrapper task : tasksAdded) { String queueName = task.getQueueName(); int oldTaskCount = numberOfTasksAdded.getOrDefault(queueName, 0); numberOfTasksAdded.put(queueName, oldTaskCount + 1); } return numberOfTasksAdded; }
Source:
<code>public Collection<PresentationMessage> getPresentations() { Collection<PresentationMessage> allMessages = new ArrayList<PresentationMessage>(); <START> for (Entry<String, Locale> entry : localizedMap.entrySet()) { <END> PresentationMessageMap codeMessageMap = entry.getValue(); allMessages.addAll(codeMessageMap.values()); } return allMessages; }</code><technical_language>'for' simply replaced allMessages.addAll(localizedMap.values());</technical_language>

Target:
public Collection<PresentationMessage> getPresentations() { Collection<PresentationMessage> allMessages = new Vector<PresentationMessage>(); for (Locale locale : localizedMap.keySet()) { PresentationMessageMap codeMessageMap = localizedMap.get(locale); allMessages.addAll(codeMessageMap.values()); } return allMessages; }
Source:
<code>public static Expr applyUnappliedIdentifiers(Expr expr, Expr.BindingDetails bindingDetails, List<String> toApply) { if (toApply.size() == 0) { return expr; } List<String> unapplied = toApply.stream() <START> .filter(x -> bindingDetails.getRequiredColumnsList().contains(x)) <END> .collect(Collectors.toList()); Expr newExpr = expr.visit( childExpr -> { if (childExpr instanceof ApplyFunctionExpr) { return liftApplyLambda((ApplyFunctionExpr) childExpr, unapplied); } else if (childExpr instanceof FunctionExpr) { FunctionExpr fnExpr = (FunctionExpr) childExpr; Set<Expr> arrayInputs = fnExpr.function.getArrayInputs(fnExpr.args); List<Expr> newArgs = new ArrayList<>(); for (Expr arg : fnExpr.args) { if (arg.getIdentifierIfIdentifier() == null && arrayInputs.contains(arg)) { Expr newArg = applyUnappliedIdentifiers(arg, bindingDetails, unapplied); newArgs.add(newArg); } else { newArgs.add(arg); } } FunctionExpr newFnExpr = new FunctionExpr(fnExpr.function, fnExpr.function.name(), newArgs); return newFnExpr; } return childExpr; } ); Expr.BindingDetails newExprBindings = newExpr.analyzeInputs(); final Set<String> expectedArrays = newExprBindings.getArrayVariables(); List<String> remainingUnappliedArgs = unapplied.stream().filter(x -> !expectedArrays.contains(x)).collect(Collectors.toList()); if (remainingUnappliedArgs.size() == 0) { return newExpr; } return applyUnapplied(newExpr, remainingUnappliedArgs); }</code><technical_language>Suggest getRequiredColumns here, contains cheaper Set ArrayList if lots of columns (and skip ArrayList creation too)</technical_language>

Target:
public static Expr applyUnappliedIdentifiers(Expr expr, Expr.BindingDetails bindingDetails, List<String> toApply) { if (toApply.size() == 0) { return expr; } List<String> unapplied = toApply.stream() .filter(x -> bindingDetails.getRequiredColumns().contains(x)) .collect(Collectors.toList()); Expr newExpr = expr.visit( childExpr -> { if (childExpr instanceof ApplyFunctionExpr) { return liftApplyLambda((ApplyFunctionExpr) childExpr, unapplied); } else if (childExpr instanceof FunctionExpr) { FunctionExpr fnExpr = (FunctionExpr) childExpr; Set<Expr> arrayInputs = fnExpr.function.getArrayInputs(fnExpr.args); List<Expr> newArgs = new ArrayList<>(); for (Expr arg : fnExpr.args) { if (arg.getIdentifierIfIdentifier() == null && arrayInputs.contains(arg)) { Expr newArg = applyUnappliedIdentifiers(arg, bindingDetails, unapplied); newArgs.add(newArg); } else { newArgs.add(arg); } } FunctionExpr newFnExpr = new FunctionExpr(fnExpr.function, fnExpr.function.name(), newArgs); return newFnExpr; } return childExpr; } ); Expr.BindingDetails newExprBindings = newExpr.analyzeInputs(); final Set<String> expectedArrays = newExprBindings.getArrayVariables(); List<String> remainingUnappliedArgs = unapplied.stream().filter(x -> !expectedArrays.contains(x)).collect(Collectors.toList()); if (remainingUnappliedArgs.size() == 0) { return newExpr; } return applyUnapplied(newExpr, remainingUnappliedArgs); }
Source:
<code>protected void executeQueryCommand() { SSHClient client = null; try { client = connect(getParameters().getServerName()); validateFingerprint(client); String glusterServers = executeCommand(client); if (StringUtils.isNotEmpty(glusterServers)) { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder; docBuilder = docBuilderFactory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(glusterServers)); Document doc = docBuilder.parse(is); doc.getDocumentElement().normalize(); NodeList listOfPeers = doc.getElementsByTagName(PEER); extractServers(listOfPeers); <START> getQueryReturnValue().setReturnValue(getServerFingerPrintMap()); <END> } else { String errMsg = "Could not get the peer list form the host: " + getParameters().getServerName(); log.error(errMsg); throw new RuntimeException(errMsg); } } catch (ParserConfigurationException e1) { log.errorFormat("There is problem in parsing xml." + e1.getMessage()); throw new RuntimeException(e1); } catch (SAXException e2) { log.errorFormat("Error in parsing xml." + e2.getMessage()); throw new RuntimeException(e2); } catch (IOException e3) { log.errorFormat("There is problem in reading the file." + e3.getMessage()); throw new RuntimeException(e3); } finally { if(client != null) { client.disconnect(); } } }</code><technical_language>I understand need words variables for small task... getQueryReturnValue().setReturnValue( getGlusterFingerprints(doc.getElementsByTagName(PEER)) ) do need this.hostNamesOrIp, is a state, pass parameter. need this.fingerprints reason. Please try reduce size of this code</technical_language>

Target:
protected void executeQueryCommand() { SSHClient client = null; try { client = connect(getParameters().getServerName()); validateFingerprint(client); String glusterServers = authenticateAndExecuteCommand(client); if (StringUtils.isNotEmpty(glusterServers)) { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(glusterServers)); Document doc = docBuilder.parse(is); doc.getDocumentElement().normalize(); getQueryReturnValue().setReturnValue(getGlusterFingerprints(doc.getElementsByTagName(PEER))); } else { String errMsg = "Could not get the peer list form the host: " + getParameters().getServerName(); log.error(errMsg); throw new RuntimeException(errMsg); } } catch (ParserConfigurationException e1) { log.errorFormat("There is problem in parsing xml." + e1.getMessage()); throw new RuntimeException(e1); } catch (SAXException e2) { log.errorFormat("Error in parsing xml." + e2.getMessage()); throw new RuntimeException(e2); } catch (IOException e3) { log.errorFormat("There is problem in reading the file." + e3.getMessage()); throw new RuntimeException(e3); } finally { if(client != null) { client.disconnect(); } } }
Source:
<code><START> private void openRealms() { <END> if (openInProgress) { return; } else { openInProgress = true; managementRealmOpenTask = Realm.getInstanceAsync(managementRealmConfig, new Realm.Callback() { @Override public void onSuccess(Realm realm) { managementRealm = realm; checkIfRealmsAreOpened(); } @Override public void onError(Throwable exception) { synchronized (errorLock) { managementRealmError = new ObjectServerError(ErrorCode.UNKNOWN, exception); } checkIfRealmsAreOpened(); } }); permissionRealmOpenTask = Realm.getInstanceAsync(permissionRealmConfig, new Realm.Callback() { @Override public void onSuccess(Realm realm) { permissionRealm = realm; checkIfRealmsAreOpened(); } @Override public void onError(Throwable exception) { synchronized (errorLock) { permissionRealmError = new ObjectServerError(ErrorCode.UNKNOWN, exception); } checkIfRealmsAreOpened(); } }); } }</code><technical_language>Single threaded</technical_language>

Target:
private void openRealms() { if (!openInProgress) { openInProgress = true; managementRealmOpenTask = Realm.getInstanceAsync(managementRealmConfig, new Realm.Callback() { @Override public void onSuccess(Realm realm) { managementRealm = realm; checkIfRealmsAreOpenedAndRunDelayedTasks(); } @Override public void onError(Throwable exception) { synchronized (errorLock) { managementRealmError = new ObjectServerError(ErrorCode.UNKNOWN, exception); checkIfRealmsAreOpenedAndRunDelayedTasks(); } } }); permissionRealmOpenTask = Realm.getInstanceAsync(permissionRealmConfig, new Realm.Callback() { @Override public void onSuccess(Realm realm) { permissionRealm = realm; checkIfRealmsAreOpenedAndRunDelayedTasks(); } @Override public void onError(Throwable exception) { synchronized (errorLock) { permissionRealmError = new ObjectServerError(ErrorCode.UNKNOWN, exception); checkIfRealmsAreOpenedAndRunDelayedTasks(); } } }); } }
Source:
<code>private void validateDirectPrerequisite( Attribute attribute, ConfiguredTargetAndData prerequisite) { <START> if (RuleContextConstraintSemantics.checkForIncompatibility(prerequisite.getConfiguredTarget()) <END> .isIncompatible) { return; } validateDirectPrerequisiteType(prerequisite, attribute); validateDirectPrerequisiteFileTypes(prerequisite, attribute); if (attribute.performPrereqValidatorCheck()) { prerequisiteValidator.validate(this, prerequisite, attribute); } }</code><technical_language>Is reason this put in checkRuleDependencyMandatoryProviders? of other checks (like checking valid rule type) affected incompatible targets</technical_language>

Target:
private void validateDirectPrerequisite( Attribute attribute, ConfiguredTargetAndData prerequisite) { if (RuleContextConstraintSemantics.checkForIncompatibility(prerequisite.getConfiguredTarget()) .isIncompatible()) { return; } validateDirectPrerequisiteType(prerequisite, attribute); validateDirectPrerequisiteFileTypes(prerequisite, attribute); if (attribute.performPrereqValidatorCheck()) { prerequisiteValidator.validate(this, prerequisite, attribute); } }
Source:
<code>public Map<String, String> getEnv(IProject project) throws CoreException { String scheme = mapping.getSchemeFromNature(project); if (scheme!=null) { <START> IRemoteEnvProxyManager manager = getRemoteManager(scheme); <END> return manager.getEnv(project); } URI projectURI = project.getLocationURI(); return getEnv(projectURI); }</code><technical_language>I getEnv assume IRemoteProxyManager, call getEnv if manager is instance of IRemoteEnvProxyManager. If isn't, default (maybe System.getenv()) used</technical_language>

Target:
public Map<String, String> getEnv(IProject project) throws CoreException { String scheme = mapping.getSchemeFromNature(project); if (scheme!=null) { IRemoteProxyManager manager = getRemoteManager(scheme); IRemoteEnvProxyManager envManager; if (manager instanceof IRemoteEnvProxyManager) { envManager = (IRemoteEnvProxyManager) manager; return envManager.getEnv(project); } } URI projectURI = project.getLocationURI(); return getEnv(projectURI); }
Source:
<code>public static boolean isIUPAC(final byte base) { <START> return bases[base] != 0; <END> }</code><technical_language>useful define a symbolic constant NON_IUPAC_CODE in bases initialization code, instead of 0, reinforce related</technical_language>

Target:
public static boolean isIUPAC(final byte base) { return bases[base] != NON_IUPAC_CODE; }
Source:
<code><START> public boolean accept(final Object element) { <END> if (element instanceof ILabelProviderContextElementWrapper) { final Object object = ((ILabelProviderContextElementWrapper) element).getObject(); if (object instanceof ITreeItemAxis) { ITreeItemAxis curr = (ITreeItemAxis) object; Object el = curr.getElement(); if (el instanceof TreeFillingConfiguration) { final IAxis axis = ((TreeFillingConfiguration) el).getAxisUsedAsAxisProvider(); return axis instanceof EOperation || axis instanceof EOperationAxis; } } } return false; }</code><technical_language>Multi returns avoid</technical_language>

Target:
public boolean accept(final Object element) { boolean result = false; if (element instanceof ILabelProviderContextElementWrapper) { final Object object = ((ILabelProviderContextElementWrapper) element).getObject(); if (object instanceof ITreeItemAxis) { ITreeItemAxis curr = (ITreeItemAxis) object; Object el = curr.getElement(); if (el instanceof TreeFillingConfiguration) { final IAxis axis = ((TreeFillingConfiguration) el).getAxisUsedAsAxisProvider(); result = axis instanceof EOperation || axis instanceof EOperationAxis; } } } return result; }
Source:
<code>public static ExecutionConfigAccessor fromProgramOptions(final ProgramOptions options, final List<URL> jobJars) { checkNotNull(options); checkNotNull(jobJars); final Configuration configuration = new Configuration(); if (options.getParallelism() != ExecutionConfig.PARALLELISM_DEFAULT) { configuration.setInteger(CoreOptions.DEFAULT_PARALLELISM, options.getParallelism()); } configuration.setBoolean(DeploymentOptions.ATTACHED, !options.getDetachedMode()); configuration.setBoolean(DeploymentOptions.SHUTDOWN_IF_ATTACHED, options.isShutdownOnAttachedExit()); ConfigUtils.encodeCollectionToConfig(configuration, PipelineOptions.CLASSPATHS, options.getClasspaths(), URL::toString); ConfigUtils.encodeCollectionToConfig(configuration, PipelineOptions.JARS, jobJars, URL::toString); SavepointRestoreSettings.toConfiguration(options.getSavepointRestoreSettings(), configuration); <START> if (options instanceof PythonProgramOptions) { <END> configuration.addAll(((PythonProgramOptions) options).getPythonConfiguration()); } return new ExecutionConfigAccessor(configuration); }</code><technical_language>Instead of instanceof here, I add a method ProgramOptions for adding additional configuration. (addToConfiguration(Configuration). base ProgramOptions this do in PythonProgramOptions this add additional python configuration. If want do nicely, though, add current code in this method new ProgramOptions.addToConfiguration(). This treat same</technical_language>

Target:
public static ExecutionConfigAccessor fromProgramOptions(final ProgramOptions options, final List<URL> jobJars) { checkNotNull(options); checkNotNull(jobJars); final Configuration configuration = new Configuration(); options.applyToConfiguration(configuration); ConfigUtils.encodeCollectionToConfig(configuration, PipelineOptions.JARS, jobJars, URL::toString); return new ExecutionConfigAccessor(configuration); }
Source:
<code>public void testAddBindingsToScriptHandlerContainsVariables() throws InvalidScriptException, NodeException, NoSuchFieldException, IllegalAccessException { ScriptHandler scriptHandler = new ScriptHandler(); Map<String, Serializable> variables = new HashMap<>(); variables.put(testVariable1Key, testVariable1Value); VariablesMap variablesMap = new VariablesMap(); variablesMap.setInheritedMap(variables); validateThatScriptHandlerBindingsContain(scriptHandler, createTaskContext(null), variablesMap, <START> new ConcurrentHashMap<>(), <END> new HashMap<String, String>(), new HashMap<String, String>(), SchedulerConstants.VARIABLES_BINDING_NAME, variablesMap); }</code><technical_language>need for concurrent</technical_language>

Target:
public void testAddBindingsToScriptHandlerContainsVariables() throws InvalidScriptException, NodeException, NoSuchFieldException, IllegalAccessException { ScriptHandler scriptHandler = new ScriptHandler(); Map<String, Serializable> variables = new HashMap<>(); variables.put(testVariable1Key, testVariable1Value); VariablesMap variablesMap = new VariablesMap(); variablesMap.setInheritedMap(variables); validateThatScriptHandlerBindingsContain(scriptHandler, createTaskContext(null), variablesMap, new HashMap<>(), new HashMap<String, String>(), new HashMap<String, String>(), SchedulerConstants.VARIABLES_BINDING_NAME, variablesMap); }
Source:
<code>@Override public RelDataType deriveType(SqlValidator validator, SqlValidatorScope scope, SqlCall call) { List<SqlNode> sqlIdentifiers = call.getOperandList(); for (SqlNode node : sqlIdentifiers) { if (!(node instanceof SqlIdentifier)) { throw SqlUtil.newContextException(node.getParserPosition(), RESOURCE.aliasMustBeSimpleIdentifier()); } <START> SqlIdentifier identifier = (SqlIdentifier) node; <END> if (scope.resolveColumn(identifier.getSimple(), node) == null) { throw SqlUtil.newContextException(node.getParserPosition(), RESOURCE.unknownIdentifier(identifier.getSimple())); } } return validator.getTypeFactory().createSqlType(SqlTypeName.COLUMN_LIST); }</code><technical_language>validation in checkOperandTypes</technical_language>

Target:
@Override public RelDataType deriveType( SqlValidator validator, SqlValidatorScope scope, SqlCall call) { return validator.getTypeFactory().createSqlType(SqlTypeName.COLUMN_LIST); }
Source:
<code><START> public void listRevisionsWithPaginationAndRepeatIterator() { <END> final int numberExpected = 50; List<ConfigurationSetting> settings = new ArrayList<>(numberExpected); for (int value = 0; value < numberExpected; value++) { settings.add(new ConfigurationSetting().key(keyPrefix).value("myValue" + value).label(labelPrefix)); } List<Mono<Response<ConfigurationSetting>>> results = new ArrayList<>(); for (ConfigurationSetting setting : settings) { results.add(client.setSettingWithResponse(setting)); } SettingSelector filter = new SettingSelector().keys(keyPrefix).labels(labelPrefix); Flux.merge(results).blockLast(); List<ConfigurationSetting> configurationSettingList1 = new ArrayList<>(); List<ConfigurationSetting> configurationSettingList2 = new ArrayList<>(); PagedFlux<ConfigurationSetting> configurationSettingPagedFlux = client.listSettingRevisions(filter); configurationSettingPagedFlux.toIterable().forEach(configurationSetting -> configurationSettingList1.add(configurationSetting)); assertEquals(numberExpected, configurationSettingList1.size()); configurationSettingPagedFlux.toIterable().forEach(configurationSetting -> configurationSettingList2.add(configurationSetting)); assertEquals(numberExpected, configurationSettingList2.size()); }</code><technical_language>here/ Missing test annotation</technical_language>

Target:
public void listRevisionsWithPaginationAndRepeatIterator() { final int numberExpected = 50; List<ConfigurationSetting> settings = new ArrayList<>(numberExpected); List<Mono<Response<ConfigurationSetting>>> results = new ArrayList<>(); for (int value = 0; value < numberExpected; value++) { ConfigurationSetting setting = new ConfigurationSetting().key(keyPrefix).value("myValue" + value).label(labelPrefix); settings.add(setting); results.add(client.setSettingWithResponse(setting)); } SettingSelector filter = new SettingSelector().keys(keyPrefix).labels(labelPrefix); Flux.merge(results).blockLast(); List<ConfigurationSetting> configurationSettingList1 = new ArrayList<>(); List<ConfigurationSetting> configurationSettingList2 = new ArrayList<>(); PagedFlux<ConfigurationSetting> configurationSettingPagedFlux = client.listSettingRevisions(filter); configurationSettingPagedFlux.toIterable().forEach(configurationSetting -> configurationSettingList1.add(configurationSetting)); assertEquals(numberExpected, configurationSettingList1.size()); configurationSettingPagedFlux.toIterable().forEach(configurationSetting -> configurationSettingList2.add(configurationSetting)); assertEquals(numberExpected, configurationSettingList2.size()); }
Source:
<code>public void openFile(final SBlock fail, final BlockDispatchNode dispatchHandler) { long[] storage = new long[bufferSize]; buffer = new SMutableArray(storage, Classes.arrayClass); try { this.access = AccessModes.valueOf(mode.getString()); } catch (Exception e) { <START> dispatchHandler.executeDispatch(new Object[] {fail, "invalid access mode"}); <END> } try { raf = new RandomAccessFile(f, access.getMode()); } catch (FileNotFoundException e) { dispatchHandler.executeDispatch(new Object[] {fail, e.toString()}); } open = true; }</code><technical_language>error include wrong value, mode? easier debug</technical_language>

Target:
public Object openFile(final SBlock fail, final BlockDispatchNode dispatchHandler) { long[] storage = new long[bufferSize]; buffer = new SMutableArray(storage, Classes.arrayClass); try { raf = new RandomAccessFile(f, accessMode.mode); } catch (FileNotFoundException e) { return dispatchHandler.executeDispatch(new Object[] {fail, FILE_NOT_FOUND}); } return this; }
Source:
<code>public SuccessResponse toggleQueryRateLimiting( @ApiParam(value = "Broker instance name", required = true, example = "Broker_my.broker.com_30000") @PathParam("instanceName") String brokerInstanceName, @ApiParam(value = "ENABLE|DISABLE", allowableValues = "ENABLE, DISABLE", required = true) @QueryParam("state") String state) { if (brokerInstanceName == null || !brokerInstanceName.startsWith("Broker_")) { LOGGER.info("{} isn't a valid broker instance name", brokerInstanceName); throw new ControllerApplicationException(LOGGER, <START> String.format("'%s' is not a valid broker instance name.", brokerInstanceName), Response.Status.BAD_REQUEST); <END> } validateQueryQuotaStateChange(state); List<String> liveInstances = _pinotHelixResourceManager.getOnlineInstanceList(); if (!liveInstances.contains(brokerInstanceName)) { LOGGER.info("Broker instance: not found from live instances", brokerInstanceName); throw new ControllerApplicationException(LOGGER, String.format("Instance '%s' not found.", brokerInstanceName), Response.Status.NOT_FOUND); } _pinotHelixResourceManager.toggleQueryQuotaStateForBroker(brokerInstanceName, state); String msg = String.format("Set query rate limiting to: %s for all tables in broker: %s", state, brokerInstanceName); LOGGER.info(msg); return new SuccessResponse(msg); }</code><technical_language>nit: Create error string, in log exeption. in other places well, repeat</technical_language>

Target:
public SuccessResponse toggleQueryRateLimiting( @ApiParam(value = "Broker instance name", required = true, example = "Broker_my.broker.com_30000") @PathParam("instanceName") String brokerInstanceName, @ApiParam(value = "ENABLE|DISABLE", allowableValues = "ENABLE, DISABLE", required = true) @QueryParam("state") String state) { if (brokerInstanceName == null || !brokerInstanceName.startsWith("Broker_")) { throw new ControllerApplicationException(LOGGER, String.format("'%s' is not a valid broker instance name.", brokerInstanceName), Response.Status.BAD_REQUEST); } validateQueryQuotaStateChange(state); List<String> liveInstances = _pinotHelixResourceManager.getOnlineInstanceList(); if (!liveInstances.contains(brokerInstanceName)) { throw new ControllerApplicationException(LOGGER, String.format("Instance '%s' not found.", brokerInstanceName), Response.Status.NOT_FOUND); } _pinotHelixResourceManager.toggleQueryQuotaStateForBroker(brokerInstanceName, state); String msg = String.format("Set query rate limiting to: %s for all tables in broker: %s", state, brokerInstanceName); LOGGER.info(msg); return new SuccessResponse(msg); }
Source:
<code>private PhysicalOperation planGlobalAggregation(int operatorId, AggregationNode node, PhysicalOperation source) { int outputChannel = 0; ImmutableMap.Builder<Symbol, Integer> outputMappings = ImmutableMap.builder(); List<AccumulatorFactory> accumulatorFactories = new ArrayList<>(); for (Map.Entry<Symbol, Aggregation> entry : node.getAssignments().entrySet()) { Symbol symbol = entry.getKey(); Aggregation aggregation = entry.getValue(); accumulatorFactories.add(buildAccumulatorFactory(source, aggregation.getSignature(), aggregation.getCall(), <START> aggregation.getMask().orElse(null))); <END> outputMappings.put(symbol, outputChannel); outputChannel++; } OperatorFactory operatorFactory = new AggregationOperatorFactory(operatorId, node.getId(), node.getStep(), accumulatorFactories); return new PhysicalOperation(operatorFactory, outputMappings.build(), source); }</code><technical_language>buildAccumulatorFactory accept Optional mask instead</technical_language>

Target:
private PhysicalOperation planGlobalAggregation(int operatorId, AggregationNode node, PhysicalOperation source) { int outputChannel = 0; ImmutableMap.Builder<Symbol, Integer> outputMappings = ImmutableMap.builder(); List<AccumulatorFactory> accumulatorFactories = new ArrayList<>(); for (Map.Entry<Symbol, Aggregation> entry : node.getAggregations().entrySet()) { Symbol symbol = entry.getKey(); Aggregation aggregation = entry.getValue(); accumulatorFactories.add(buildAccumulatorFactory(source, aggregation.getSignature(), aggregation.getCall(), aggregation.getMask())); outputMappings.put(symbol, outputChannel); outputChannel++; } OperatorFactory operatorFactory = new AggregationOperatorFactory(operatorId, node.getId(), node.getStep(), accumulatorFactories); return new PhysicalOperation(operatorFactory, outputMappings.build(), source); }
Source:
<code>protected List<EmailWrapper> prepareMailToBeSent() { FeedbackSessionAttributes feedbackObject = FeedbackSessionsLogic.inst() .getFeedbackSession(feedbackSessionName, courseId); log.info("Fetching feedback session object for feedback session name : " <START> + feedbackSessionName + " and course : " + courseId); <END> if (feedbackObject == null) { log.severe("Feedback session object for feedback session name : " + feedbackSessionName + " for course : " + courseId + " could not be fetched"); return null; } return new EmailGenerator().generateFeedbackSessionClosedEmails(feedbackObject); }</code><technical_language>if this code similar actions, I point of logging here. remove this</technical_language>

Target:
protected List<EmailWrapper> prepareMailToBeSent() { FeedbackSessionAttributes feedbackSession = FeedbackSessionsLogic.inst() .getFeedbackSession(feedbackSessionName, courseId); if (feedbackSession == null) { log.severe("Feedback session object for feedback session name : " + feedbackSessionName + " for course : " + courseId + " could not be fetched"); return null; } return new EmailGenerator().generateFeedbackSessionClosedEmails(feedbackSession); }
Source:
<code>private void doBucketProbing() throws IOException { int bucketProbe = this.getConf() .getInt(S3A_BUCKET_PROBE, S3A_BUCKET_PROBE_DEFAULT); Preconditions.checkArgument(bucketProbe >= 0 && bucketProbe <= 2, "Value of " + S3A_BUCKET_PROBE + " should be between 0 to 2"); switch (bucketProbe) { case 0: break; case 1: verifyBucketExists(); break; case 2: verifyBucketExistsV2(); <START> break; <END> default: break; } }</code><technical_language>add a RetryPolicy @ methods calls do a retry() calling operations retry anyway, explodes #of retries place. ok once() of them, exception translating stuff is a no-op translated exceptions</technical_language>

Target:
private void doBucketProbing() throws IOException { int bucketProbe = getConf() .getInt(S3A_BUCKET_PROBE, S3A_BUCKET_PROBE_DEFAULT); Preconditions.checkArgument(bucketProbe >= 0, "Value of " + S3A_BUCKET_PROBE + " should be >= 0"); switch (bucketProbe) { case 0: LOG.debug("skipping check for bucket existence"); break; case 1: verifyBucketExists(); break; case 2: verifyBucketExistsV2(); break; default: LOG.warn("Unknown bucket probe option {}: {}; falling back to check #2", S3A_BUCKET_PROBE, bucketProbe); verifyBucketExistsV2(); break; } }
Source:
<code><START> private boolean isNotCyclicEdge(final Edge edge) { <END> final String sourceId = edge.getSourceNode() != null ? edge.getSourceNode().getUUID() : null; final String targetId = edge.getTargetNode() != null ? edge.getTargetNode().getUUID() : null; return !Objects.equals(sourceId, targetId); }</code><technical_language>static</technical_language>

Target:
private static boolean isNotCyclicEdge(final Edge edge) { final String sourceId = edge.getSourceNode() != null ? edge.getSourceNode().getUUID() : null; final String targetId = edge.getTargetNode() != null ? edge.getTargetNode().getUUID() : null; return !Objects.equals(sourceId, targetId); }