auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private boolean navigate(WebElement dateBox, Calendar date) { dateBox.click(); Calendar selectedDate = Calendar.getInstance(); String month = date.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH); String year = Integer.toString(date.get(Calendar.YEAR)); SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); try { selectedDate.setTime(dateFormat.parse(dateBox.getAttribute("value"))); } catch (ParseException e) { <START> e.printStackTrace(); <END> } if (selectedDate.after(date)) { while (!getDatepickerMonth().equals(month) || !getDatepickerYear().equals(year)) { WebElement previousButton = browser.driver.findElement(By.className("ui-datepicker-prev")); if (previousButton.getAttribute("class").contains("ui-state-disabled")) { return false; } else { previousButton.click(); } } } else { while (!getDatepickerMonth().equals(month) || !getDatepickerYear().equals(year)) { WebElement nextButton = browser.driver.findElement(By.className("ui-datepicker-next")); if (nextButton.getAttribute("class").contains("ui-state-disabled")) { return false; } else { nextButton.click(); } } } return true; }</code><technical_language>test continue if parse fails, test fail instead of silencing it</technical_language>

Target:
private boolean navigate(WebElement dateBox, Calendar date) throws ParseException { dateBox.click(); Calendar selectedDate = Calendar.getInstance(); String month = date.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH); String year = Integer.toString(date.get(Calendar.YEAR)); SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); selectedDate.setTime(dateFormat.parse(dateBox.getAttribute("value"))); if (selectedDate.after(date)) { while (!getDatepickerMonth().equals(month) || !getDatepickerYear().equals(year)) { WebElement previousButton = browser.driver.findElement(By.className("ui-datepicker-prev")); if (previousButton.getAttribute("class").contains("ui-state-disabled")) { return false; } else { previousButton.click(); } } } else { while (!getDatepickerMonth().equals(month) || !getDatepickerYear().equals(year)) { WebElement nextButton = browser.driver.findElement(By.className("ui-datepicker-next")); if (nextButton.getAttribute("class").contains("ui-state-disabled")) { return false; } else { nextButton.click(); } } } return true; }
Source:
<code>public void setClipOverlappingReads(final boolean clipOverlappingReads) { this.clipOverlappingReads = clipOverlappingReads; <START> this.hardClipOverlappingReads = false; <END> }</code><technical_language>I I this is changing a public API...but good. set* methods change variable named for. add a setClipWithHardClips method avoid changing in method</technical_language>

Target:
public void setClipOverlappingReads(final boolean clipOverlappingReads) { this.clipOverlappingReads = clipOverlappingReads; }
Source:
<code>private boolean isGMFSpecificEditPart(EditPart editPart) { return editPart instanceof NoteEditPart || editPart instanceof <START> TextEdit || <END> editPart instanceof NoteAttachmentEditPart; }</code><technical_language>TextEdit</technical_language>

Target:
private boolean isGMFSpecificEditPart(EditPart editPart) { return editPart instanceof SiriusNoteEditPart || editPart instanceof SiriusTextEditPart || editPart instanceof NoteAttachmentEditPart; }
Source:
<code>public void setUp() throws IOException, InterruptedException, ParseException, ConceptNameAlreadyInUseException { <START> openMRSTasksNotifier = (OpenMRSTasksNotifier) ServiceRetriever <END> .getWebAppContext(bundleContext, OPENMRS_CHANNEL_NAME) .getBean("openMrsTasksNotifier"); setUpSecurityContext("motech", "motech", "manageTasks", "manageOpenMRS"); waitForChannel(OPENMRS_CHANNEL_NAME); waitForChannel(MDS_CHANNEL_NAME); createPatientTestData(); createEncounterTestData(); }</code><technical_language>remove</technical_language>

Target:
public void setUp() throws IOException, InterruptedException, ParseException, ConceptNameAlreadyInUseException { setUpSecurityContext("motech", "motech", "manageTasks", "manageOpenMRS"); waitForChannel(OPENMRS_CHANNEL_NAME); waitForChannel(MDS_CHANNEL_NAME); createPatientTestData(); createEncounterTestData(); }
Source:
<code>private void loadView() { try { FXMLLoader loader = new FXMLLoader(UI.class.getResource("fxml/PickerBoardItem.fxml")); loader.setRoot(this); loader.setController(this); loader.load(); } catch (Exception e) { <START> e.printStackTrace(); <END> } }</code><technical_language>Is good swallow exceptions this</technical_language>

Target:
private void loadView() { try { FXMLLoader loader = new FXMLLoader(UI.class.getResource("fxml/PickerBoardItem.fxml")); loader.setRoot(this); loader.setController(this); loader.load(); } catch (IOException e) { logger.error("Failure to load FXML. " + e.getMessage()); } }
Source:
<code>public static void run(ISafeRunnable code) { <START> run(new ISafeRunnableWithResult<Object>() { <END> @Override public Object runWithResult() throws Exception { code.run(); return null; } @Override public void handleException(Throwable exception) { code.handleException(exception); } }); }</code><technical_language>Void instead of Object clear intention is</technical_language>

Target:
public static void run(ISafeRunnable code) { run(new ISafeRunnableWithResult<Void>() { @Override public Void runWithResult() throws Exception { code.run(); return null; } @Override public void handleException(Throwable exception) { code.handleException(exception); } }); }
Source:
<code>private void addToRecentAdapter(final View view) { if (adapter == null) { return; } logger.debug("reloading adapter..."); final String selectedId = adapter.getVideoId(); if (getRecentDownloadedVideosTask != null) { getRecentDownloadedVideosTask.cancel(true); } else { getRecentDownloadedVideosTask = new GetRecentDownloadedVideosTask(getActivity()) { @Override protected void onSuccess(List<SectionItemInterface> list) throws Exception { super.onSuccess(list); if (list != null) { adapter.clear(); <START> for (SectionItemInterface m : list) { <END> adapter.add(m); } logger.debug("reload done"); } if (adapter.getCount() <= 0) { hideDeletePanel(view); } videoListView.setOnItemClickListener(adapter); if (selectedId != null) { adapter.setVideoId(selectedId); } notifyAdapter(); if (playerFragment != null) { playerFragment.setNextPreviousListeners(getNextListener(), getPreviousListener()); } } }; } getRecentDownloadedVideosTask.execute(); }</code><technical_language>nit-pick: for loop replaced adapter.addAll(list)</technical_language>

Target:
private void addToRecentAdapter(final View view) { if (adapter == null) { return; } logger.debug("reloading adapter..."); final String selectedId = adapter.getVideoId(); if (getRecentDownloadedVideosTask != null) { getRecentDownloadedVideosTask.cancel(true); } else { getRecentDownloadedVideosTask = new GetRecentDownloadedVideosTask(getActivity()) { @Override protected void onSuccess(List<SectionItemInterface> list) throws Exception { super.onSuccess(list); if (list != null && !list.isEmpty()) { adapter.clear(); adapter.addAll(list); logger.debug("reload done"); } if (adapter.getCount() <= 0) { hideDeletePanel(view); } videoListView.setOnItemClickListener(adapter); if (selectedId != null) { adapter.setVideoId(selectedId); } notifyAdapter(); if (playerFragment != null) { playerFragment.setNextPreviousListeners(getNextListener(), getPreviousListener()); } } }; } getRecentDownloadedVideosTask.execute(); }
Source:
<code>public void secondary_id_not_found() throws Exception { <START> thrown.expectMessage("Invalid test file: precise secondary location is provided for ID 'B' but no issue is asserted with such ID"); <END> check( "foo(); "x = bar();\n" + " TestIssue.create("msg1", 1).secondary("Secondary message", 3, 5, 8)); }</code><technical_language>@vilchik-elena message give line number</technical_language>

Target:
public void secondary_id_not_found() throws Exception { thrown.expectMessage("Invalid test file: precise secondary location is provided for ID 'B' but no issue is asserted with such ID (line 3)"); check( "foo(); "x = bar();\n" + " TestIssue.create("msg1", 1).secondary("Secondary message", 3, 5, 8)); }
Source:
<code>public void checkAttributeSyntax(PerunSessionImpl perunSession, String key, Attribute attribute) throws WrongAttributeValueException { if(attribute.getValue() == null) return; Map<String, String> map = attribute.valueAsMap(); <START> if(map.isEmpty()) return; <END> Set<String> mapKeys = map.keySet(); for(String mapKey: mapKeys) { String value = map.get(mapKey); if (value == null || value.isEmpty()) throw new WrongAttributeValueException(attribute, "AUPs for key: '"+mapKey+"' can't be empty."); try { JSONArray array = new JSONArray(value); for (int i = 0; i < array.length(); i++) { JSONObject object = array.getJSONObject(i); if (!object.has("version")) throw new WrongAttributeValueException(attribute, "AUP for key: '"+mapKey+"' is missing key version in JSON."); if (!object.has("date")) throw new WrongAttributeValueException(attribute, "AUP for key: '"+mapKey+"' is missing key date in JSON."); if (!object.has("link")) throw new WrongAttributeValueException(attribute, "AUP for key: '"+mapKey+"' is missing key link in JSON."); if (!object.has("text")) throw new WrongAttributeValueException(attribute, "AUP for key: '"+mapKey+"' is missing key text in JSON."); } } catch (JSONException ex) { throw new WrongAttributeValueException(attribute, "AUP for key: '"+mapKey+"' is not valid JSON.", ex); } } }</code><technical_language>Map empty. remove it</technical_language>

Target:
public void checkAttributeSyntax(PerunSessionImpl perunSession, String key, Attribute attribute) throws WrongAttributeValueException { if(attribute.getValue() == null) return; Map<String, String> map = attribute.valueAsMap(); Set<String> mapKeys = map.keySet(); for(String mapKey: mapKeys) { String value = map.get(mapKey); if (value == null || value.isEmpty()) throw new WrongAttributeValueException(attribute, "AUPs for key: '"+mapKey+"' can't be empty."); try { JSONArray array = new JSONArray(value); for (int i = 0; i < array.length(); i++) { JSONObject object = array.getJSONObject(i); if (!object.has("version")) throw new WrongAttributeValueException(attribute, "AUP for key: '"+mapKey+"' is missing key version in JSON."); if (!object.has("date")) throw new WrongAttributeValueException(attribute, "AUP for key: '"+mapKey+"' is missing key date in JSON."); if (!object.has("link")) throw new WrongAttributeValueException(attribute, "AUP for key: '"+mapKey+"' is missing key link in JSON."); if (!object.has("text")) throw new WrongAttributeValueException(attribute, "AUP for key: '"+mapKey+"' is missing key text in JSON."); } } catch (JSONException ex) { throw new WrongAttributeValueException(attribute, "AUP for key: '"+mapKey+"' is not valid JSON.", ex); } } }
Source:
<code>public KafkaFuture<Void> all() { <START> final KafkaFutureImpl<Void> result = new KafkaFutureImpl<>(); <END> this.future.whenComplete((topicPartitions, throwable) -> { if (throwable != null) { result.completeExceptionally(throwable); } else for (TopicPartition partition : partitions) { if (hasPartitionLevelError(topicPartitions, partition, result)) { return; } } result.complete(null); }); return result; }</code><technical_language>worth mentioning if is a partition-level failure, is returned</technical_language>

Target:
public KafkaFuture<Void> all() { final KafkaFutureImpl<Void> result = new KafkaFutureImpl<>(); this.future.whenComplete((topicPartitions, throwable) -> { if (throwable != null) { result.completeExceptionally(throwable); } else { for (TopicPartition partition : partitions) { if (maybeCompleteExceptionally(topicPartitions, partition, result)) { return; } } result.complete(null); } }); return result; }
Source:
<code>public Record<K,V>[] createStorage(int size) { <START> return (Record<K,V>[])new Record[size]; <END> }</code><technical_language>Cast</technical_language>

Target:
public Record<K,V>[] createStorage(int size) { return new Record[size]; }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(StringUtils.getStringRobust(this, R.string.application_name) + " > " + StringUtils.getStringRobust(this, R.string.get_location)); <START> locationController = CommCareLocationControllerFactory.Companion.getLocationController(this, this); <END> setupLocationDialog(); long mLong = -1; if (savedInstanceState != null) { mLong = savedInstanceState.getLong("millisRemaining", -1); } if (mLong > 0) { mTimer = new TimeoutTimer(mLong, this); } else { mTimer = new TimeoutTimer(HiddenPreferences.getGpsWidgetTimeoutInMilliseconds(), this); } mTimer.start(); }</code><technical_language>provide a @JvmStatic annotation for getLocationController avoid Companion in references</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(StringUtils.getStringRobust(this, R.string.application_name) + " > " + StringUtils.getStringRobust(this, R.string.get_location)); locationController = CommCareLocationControllerFactory.getLocationController(this, this); setupLocationDialog(); long mLong = -1; if (savedInstanceState != null) { mLong = savedInstanceState.getLong("millisRemaining", -1); } if (mLong > 0) { mTimer = new TimeoutTimer(mLong, this); } else { mTimer = new TimeoutTimer(HiddenPreferences.getGpsWidgetTimeoutInMilliseconds(), this); } mTimer.start(); }
Source:
<code>public boolean valueOfIsValid(String place) { T element = getElementToRetrieveValue(place, null); List<T> invalidElements = findAllByCss("input:invalid"); <START> Collection<String> attributesToCompare = Arrays.asList("name", "id"); <END> return !containsElement(invalidElements, element, attributesToCompare); }</code><technical_language>this work for elements id name</technical_language>

Target:
public boolean valueOfIsValid(String place) { T element = waitUntil(d -> getElementToRetrieveValue(place, null)); List<T> invalidElements = findAllByCss("input:invalid"); return !invalidElements.contains(element); }
Source:
<code>protected Map<String, ZuulRoute> getRoutesMap() { if (this.routes.get() == null) { this.routes.set(locateRoutes()); } <START> return Collections.unmodifiableMap(this.routes.get()); <END> }</code><technical_language>I unmodifiableMap stay in getRoutes()</technical_language>

Target:
protected Map<String, ZuulRoute> getRoutesMap() { if (this.routes.get() == null) { this.routes.set(locateRoutes()); } return this.routes.get(); }
Source:
<code>public static <E extends Extent> Predicate<BlockRayHit<E>> blockTypeFilter(final BlockType... types) { return lastHit -> { for (BlockType type : types) { <START> if (lastHit.getExtent().getBlockType(lastHit.getBlockX(), lastHit.getBlockY(), lastHit.getBlockZ()).equals(type)) { <END> return true; } } return false; }; }</code><technical_language>Move lastHit.getExtent().getBlockType(lastHit.getBlockX(), lastHit.getBlockY(), lastHit.getBlockZ()) loop</technical_language>

Target:
public static <E extends Extent> Predicate<BlockRayHit<E>> blockTypeFilter(final BlockType... types) { return lastHit -> { final BlockType targetBlockType = lastHit.getExtent().getBlockType(lastHit.getBlockX(), lastHit.getBlockY(), lastHit.getBlockZ()); for (final BlockType type : types) { if (targetBlockType.equals(type)) { return true; } } return false; }; }
Source:
<code>public DruidStorageHandler() { <START> final String base = SessionState.getSessionConf().get("hive.druid.metadata.base", "druid"); <END> final String dbType = SessionState.getSessionConf().get("hive.druid.metadata.db.type", "mysql"); final String username = SessionState.getSessionConf().get("hive.druid.metadata.username", ""); final String password = SessionState.getSessionConf().get("hive.druid.metadata.password", ""); final String uri = SessionState.getSessionConf() .get("hive.druid.metadata.uri", "jdbc:mysql://localhost/druid"); druidMetadataStorageTablesConfig = MetadataStorageTablesConfig.fromBase(base); final Supplier<MetadataStorageConnectorConfig> storageConnectorConfigSupplier = Suppliers.<MetadataStorageConnectorConfig>ofInstance( new MetadataStorageConnectorConfig() { @Override public String getConnectURI() { return uri; } @Override public String getUser() { return username; } @Override public String getPassword() { return password; } }); if (dbType.equals("mysql")) { connector = new MySQLConnector(storageConnectorConfigSupplier, Suppliers.ofInstance(druidMetadataStorageTablesConfig) ); } else if (dbType.equals("postgres")) { connector = new PostgreSQLConnector(storageConnectorConfigSupplier, Suppliers.ofInstance(druidMetadataStorageTablesConfig) ); } else { throw new IllegalStateException(String.format("Unknown metadata storage type [%s]", dbType)); } druidSqlMetadataStorageUpdaterJobHandler = new SQLMetadataStorageUpdaterJobHandler(connector); }</code><technical_language>properties moved HiveConf descriptions added file. Otherwise, basically hidden final user</technical_language>

Target:
public DruidStorageHandler() { final String base = HiveConf .getVar(SessionState.getSessionConf(), HiveConf.ConfVars.DRUID_METADATA_BASE); final String dbType = HiveConf .getVar(SessionState.getSessionConf(), HiveConf.ConfVars.DRUID_METADATA_DB_TYPE); final String username = HiveConf .getVar(SessionState.getSessionConf(), HiveConf.ConfVars.DRUID_METADATA_DB_USERNAME); final String password = HiveConf .getVar(SessionState.getSessionConf(), HiveConf.ConfVars.DRUID_METADATA_DB_PASSWORD); final String uri = HiveConf .getVar(SessionState.getSessionConf(), HiveConf.ConfVars.DRUID_METADATA_DB_URI); druidMetadataStorageTablesConfig = MetadataStorageTablesConfig.fromBase(base); final Supplier<MetadataStorageConnectorConfig> storageConnectorConfigSupplier = Suppliers.<MetadataStorageConnectorConfig>ofInstance( new MetadataStorageConnectorConfig() { @Override public String getConnectURI() { return uri; } @Override public String getUser() { return username; } @Override public String getPassword() { return password; } }); if (dbType.equals("mysql")) { connector = new MySQLConnector(storageConnectorConfigSupplier, Suppliers.ofInstance(druidMetadataStorageTablesConfig) ); } else if (dbType.equals("postgres")) { connector = new PostgreSQLConnector(storageConnectorConfigSupplier, Suppliers.ofInstance(druidMetadataStorageTablesConfig) ); } else { throw new IllegalStateException(String.format("Unknown metadata storage type [%s]", dbType)); } druidSqlMetadataStorageUpdaterJobHandler = new SQLMetadataStorageUpdaterJobHandler(connector); }
Source:
<code>public List<TestPosition> detectTests(TestDetectionContext context) { List<TestPositionDto> testPositionDtos = extensionManager.detectTest( prefixURI(context.getFilePath()), getTestAnnotation(), context.getOffset()); return testPositionDtos .stream() .map( it -> <START> newDto(TestPosition.class) <END> .withFrameworkName(getName()) .withTestName(it.getTestName()) .withTestNameLength(it.getTestNameLength()) .withTestBodyLength(it.getTestBodyLength()) .withTestNameStartOffset(it.getTestNameStartOffset())) .collect(Collectors.toList()); }</code><technical_language>Is this class a service? If not, create DTO's? If want guarantee this methods returns Dto's, put in method signature</technical_language>

Target:
public List<TestPosition> detectTests(TestDetectionContext context) { List<TestPositionDto> testPositionDtos = extensionService.detectTest( prefixURI(context.getFilePath()), testMethodAnnotation, context.getOffset()); return testPositionDtos .stream() .map( it -> newDto(TestPosition.class) .withFrameworkName(getName()) .withTestName(it.getTestName()) .withTestNameLength(it.getTestNameLength()) .withTestBodyLength(it.getTestBodyLength()) .withTestNameStartOffset(it.getTestNameStartOffset())) .collect(Collectors.toList()); }
Source:
<code>private Patient getPatient(String lookupName, Map<String, String> lookupFields, String configName) { Patient patient = null; try { switch (lookupName) { case BY_MOTECH_ID: patient = patientService.getPatientByMotechId(configName, lookupFields.get(MOTECH_ID)); break; case BY_UUID: patient = patientService.getPatientByUuid(configName, lookupFields.get(UUID)); break; default: if (lookupFields != null) { patient = patientService.getPatientByIdentifier(configName, lookupFields.get(IDENTIFIER_ID), lookupName); } else { LOGGER.error("Lookup with name doesn't exist for patient object", lookupName); } break; } } catch (OpenMRSException e) { <START> LOGGER.warn(e.getMessage()); <END> } return patient; }</code><technical_language>please error level log stacktrace exception (use exception object a argument)</technical_language>

Target:
private Patient getPatient(String lookupName, Map<String, String> lookupFields, String configName) { Patient patient = null; try { switch (lookupName) { case BY_MOTECH_ID: patient = patientService.getPatientByMotechId(configName, lookupFields.get(MOTECH_ID)); break; case BY_UUID: patient = patientService.getPatientByUuid(configName, lookupFields.get(UUID)); break; default: if (lookupFields != null) { patient = patientService.getPatientByIdentifier(configName, lookupFields.get(IDENTIFIER_ID), lookupName); } else { LOGGER.error("Lookup with name doesn't exist for patient object", lookupName); } break; } } catch (OpenMRSException e) { LOGGER.error(e.getMessage(), e); } return patient; }
Source:
<code>public void initParam(Object obj) { final OptionsParam options = (OptionsParam) obj; final BreakpointsParam param = options.getParamSet(BreakpointsParam.class); getCheckBoxConfirmDropMessage().setSelected(param.isConfirmDropMessage()); <START> getCheckBoxAlwaysOnTop().setSelected(!param.getAlwaysOnTop().equals(Boolean.FALSE)); <END> getCheckBoxInScopeOnly().setSelected(param.isInScopeOnly()); getButtonMode().setSelectedIndex(param.getButtonMode() - 1); }</code><technical_language>This lead NPE, swap check</technical_language>

Target:
public void initParam(Object obj) { final OptionsParam options = (OptionsParam) obj; final BreakpointsParam param = options.getParamSet(BreakpointsParam.class); getCheckBoxConfirmDropMessage().setSelected(param.isConfirmDropMessage()); getCheckBoxAlwaysOnTop().setSelected(!Boolean.FALSE.equals(param.getAlwaysOnTop())); getCheckBoxInScopeOnly().setSelected(param.isInScopeOnly()); getButtonMode().setSelectedIndex(param.getButtonMode() - 1); }
Source:
<code>public Long defaultValue() { <START> return 0L; <END> }</code><technical_language>Hmm, this tricky warm cool checks this</technical_language>

Target:
public Long defaultValue() { return Long.MAX_VALUE; }
Source:
<code>protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String resourceStr = getMyParameter("resource", request); String formatStr = getMyParameter("format", request); String alias = getMyParameter("alias", request); try { if (resourceStr == null) { throw new IllegalArgumentException("Missing resource name"); } PKIResources.Resource resource = resources.get(resourceStr); if (resource == null) { throw new IllegalArgumentException(String.format("Resource '%1$s' is invalid", resourceStr)); } PKIResources.Format format = null; if (formatStr != null) { format = formats.get(formatStr); if (format == null) { throw new IllegalArgumentException(String.format("Format '%1$s' is invalid", formatStr)); } } try (PrintWriter out = response.getWriter()) { response.setContentType(resource.getContentType(format)); out.print(resource.toString(format, alias)); } } catch(Exception e) { <START> log.error("Cannot send public key resource '{}' format '{}'", resourceStr, formatStr); <END> log.error("Exception", e); response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } }</code><technical_language>add : e.getMessage()</technical_language>

Target:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String resourceStr = getMyParameter("resource", request); String formatStr = getMyParameter("format", request); String alias = getMyParameter("alias", request); try { if (resourceStr == null) { throw new IllegalArgumentException("Missing resource name"); } PKIResources.Resource resource = resources.get(resourceStr); if (resource == null) { throw new IllegalArgumentException(String.format("Resource '%1$s' is invalid", resourceStr)); } PKIResources.Format format = null; if (formatStr != null) { format = formats.get(formatStr); if (format == null) { throw new IllegalArgumentException(String.format("Format '%1$s' is invalid", formatStr)); } } try (PrintWriter out = response.getWriter()) { response.setContentType(resource.getContentType(format)); out.print(resource.toString(format, alias)); } } catch(Exception e) { log.error("Cannot send public key resource '{}' format '{}': {}", resourceStr, formatStr, e.getMessage()); log.debug("Exception", e); response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } }
Source:
<code>private EObject precedingSiblingOrContainer(EObject context) { EObject container = context.eContainer(); EStructuralFeature containingFeature = context.eContainingFeature(); if (container != null && containingFeature != null) { Object val = container.eGet(containingFeature); if (val instanceof Collection) { <START> List<EObject> childs = Lists.newArrayList(Iterables.filter((Collection) val, EObject.class)); <END> int contextPositionInContainingList = childs.indexOf(context); if (contextPositionInContainingList > 0) { EObject sibling = childs.get(contextPositionInContainingList - 1); if (sibling != null) { return sibling; } } } } return container; }</code><technical_language>a filter a ArrayList instantiation is useful</technical_language>

Target:
private EObject precedingSiblingOrContainer(EObject context) { EObject container = context.eContainer(); EStructuralFeature containingFeature = context.eContainingFeature(); if (container != null && containingFeature != null) { Object val = container.eGet(containingFeature); if (val instanceof EList<?>) { EList<?> childs = (EList<?>) val; int contextPositionInContainingList = childs.indexOf(context); if (contextPositionInContainingList > 0) { Object sibling = childs.get(contextPositionInContainingList - 1); if (sibling instanceof EObject) { return (EObject)sibling; } } } } return container; }
Source:
<code>public void setQuota(Path src, final long namespaceQuota, final long storagespaceQuota) throws IOException { <START> throw new UnsupportedOperationException(getClass().getCanonicalName() + <END> "does not support setQuota"); }</code><technical_language>This is a pattern in places. I a static method do this. I easiest get function name is get stack trace</technical_language>

Target:
public void setQuota(Path src, final long namespaceQuota, final long storagespaceQuota) throws IOException { methodNotSupported(); }
Source:
<code><START> static <T> Task<T> withSideEffect(final String desc, final Callable<Task<T>> func) { <END> ArgumentUtil.requireNotNull(func, "function"); final Task<T> sideEffectWrapper = async(desc, ctx -> { Task<?> sideEffect = func.call(); ctx.runSideEffect(sideEffect); return Promises.value(null); }); sideEffectWrapper.getShallowTraceBuilder().setTaskType(TaskType.WITH_SIDE_EFFECT.getName()); return sideEffectWrapper; }</code><technical_language>this return a Task<Void> instead? This task depend side effect task</technical_language>

Target:
static <T> Task<Void> withSideEffect(final String desc, final Callable<Task<T>> func) { ArgumentUtil.requireNotNull(func, "function"); final Task<Void> sideEffectWrapper = async(desc, ctx -> { Task<?> sideEffect = func.call(); ctx.runSideEffect(sideEffect); return Promises.value(null); }); sideEffectWrapper.getShallowTraceBuilder().setTaskType(TaskType.WITH_SIDE_EFFECT.getName()); return sideEffectWrapper; }
Source:
<code><START> private void uncheckElement(Object element) { <END> fViewer.setChecked(element, false); for (Object child : fContentProvider.getChildren(element)) { uncheckElement(child); } }</code><technical_language>I noticed a behavior I is correct not. If apply a filter, uncheck a parent in filtered result, uncheck children of this parent, currently visible due filter. If is want, a solution to: 1) uncheck visible children 2) filter is cleared, recompute check state parent regain checked state visible checked children. is opinion intended behavior</technical_language>

Target:
private void uncheckElement(Object element) { fTree.setChecked(element, false); for (Object child : fContentProvider.getChildren(element)) { uncheckElement(child); } }
Source:
<code>public void applyTitle(final String title, final W element, final MutationContext mutationContext) { <START> if (title.trim().length() > 0) { <END> viewHandler.applyTitle(title, mutationContext); applyFont(element, mutationContext); } }</code><technical_language>This condition is covered tests, I need this condition here</technical_language>

Target:
public void applyTitle(final String title, final W element, final MutationContext mutationContext) { viewHandler.applyTitle(title, mutationContext); applyFont(element, mutationContext); }
Source:
<code>public void addKeysSync(Set<String> changes) { changes.stream().forEach(change -> { String[] changeSplited = change.split(":"); String envname = changeSplited[1]; <START> String objname = changeSplited[2]; <END> String objid = changeSplited[3]; redisTemplate.opsForSet().add("sync:" + envname + ":" + objname + ":" + objid, String.valueOf(System.currentTimeMillis())); }); }</code><technical_language>If renamed name ":"</technical_language>

Target:
public void addKeysSync(Set<String> changes) { changes.stream().forEach(change -> { String[] changeSplited = change.split(":"); String envname = changeSplited[1]; String objname = changeSplited[2]; String objid = changeSplited[3]; redisTemplate.opsForSet().add(SYNC_PREFIX + envname + ":" + objname + ":" + objid, String.valueOf(System.currentTimeMillis())); }); }
Source:
<code>public void onAddAccountsToGroup(Account.Id me, Collection<AccountGroupMember> added) { List<AccountGroupMemberAudit> auditInserts = Lists.newLinkedList(); for (AccountGroupMember m : added) { AccountGroupMemberAudit audit = new AccountGroupMemberAudit(m, me, TimeUtil.nowTs()); auditInserts.add(audit); } <START> ReviewDb db = null; try { db = schema.open(); db.accountGroupMembersAudit().insert(auditInserts); } catch (OrmException e) { logOrmExceptionForAccounts( "Cannot log add accounts to group event performed by user", me, added, e); } finally { if (db != null) { db.close(); } } <END> }</code><technical_language>avoid init null null check in finally block: try { ReviewDb db = schema.open(); try { db.accountGroupMembersAudit().insert(auditInserts); } finally { db.close(); } } catch (OrmException e) { logOrmExceptionForAccounts( "Cannot log add accounts group event performed user", me, added, e); } in other places below..</technical_language>

Target:
public void onAddAccountsToGroup(Account.Id me, Collection<AccountGroupMember> added) { List<AccountGroupMemberAudit> auditInserts = Lists.newLinkedList(); for (AccountGroupMember m : added) { AccountGroupMemberAudit audit = new AccountGroupMemberAudit(m, me, TimeUtil.nowTs()); auditInserts.add(audit); } try { ReviewDb db = schema.open(); try { db.accountGroupMembersAudit().insert(auditInserts); } finally { db.close(); } } catch (OrmException e) { logOrmExceptionForAccounts( "Cannot log add accounts to group event performed by user", me, added, e); } }
Source:
<code>public Boolean call() throws Exception { long sleepBackoff = 200L; do { final PoolEntry poolEntry = createPoolEntry(); <START> if (poolEntry == PoolEntry.MAXED_POOL_MARKER) { <END> return Boolean.FALSE; } else if (poolEntry != null) { connectionBag.add(poolEntry); return Boolean.TRUE; } quietlySleep(sleepBackoff); sleepBackoff = Math.min(connectionTimeout / 2, (long) (sleepBackoff * 1.3)); } while (true); }</code><technical_language>I prefer static import</technical_language>

Target:
public Boolean call() throws Exception { long sleepBackoff = 200L; do { final PoolEntry poolEntry = createPoolEntry(); if (poolEntry == MAXED_POOL_MARKER) { return Boolean.FALSE; } else if (poolEntry != null) { connectionBag.add(poolEntry); return Boolean.TRUE; } quietlySleep(sleepBackoff); sleepBackoff = Math.min(connectionTimeout / 2, (long) (sleepBackoff * 1.3)); } while (true); }
Source:
<code>protected void doStart(Collection<? extends Location> locations) { try { Task<?> clusterTask = DependentConfiguration.attributeWhenReady(router, AbstractGroup.FIRST); Entities.submit(this, clusterTask); clusterTask.get(); <START> } catch (Exception e) { <END> Exceptions.propagateIfFatal(e); } MongoDBAuthenticationUtils.setAuthenticationConfig(router, this); router.sensors().set(MongoDBAuthenticationMixins.ROOT_PASSWORD, router.config().get(MongoDBAuthenticationMixins.ROOT_PASSWORD)); router.sensors().set(MongoDBAuthenticationMixins.ROOT_USERNAME, router.config().get(MongoDBAuthenticationMixins.ROOT_USERNAME)); router.sensors().set(MongoDBAuthenticationMixins.AUTHENTICATION_DATABASE, router.config().get(MongoDBAuthenticationMixins.AUTHENTICATION_DATABASE)); Entities.manage(router); addEnricher(Enrichers.builder().propagating(MongoDBRouter.PORT).from(router).build()); super.doStart(locations); sensors().set(Startable.SERVICE_UP, true); }</code><technical_language>exceptions swallowed here? If task interrupted execution exceptions call getUnchecked</technical_language>

Target:
protected void doStart(Collection<? extends Location> locations) { MongoDBRouter router = sensors().get(ROUTER); Task<?> clusterTask = DependentConfiguration.attributeWhenReady(router, AbstractGroup.FIRST); Entities.submit(this, clusterTask); clusterTask.getUnchecked(); MongoDBAuthenticationUtils.setAuthenticationConfig(router, this); router.sensors().set(MongoDBAuthenticationMixins.ROOT_PASSWORD, router.config().get(MongoDBAuthenticationMixins.ROOT_PASSWORD)); router.sensors().set(MongoDBAuthenticationMixins.ROOT_USERNAME, router.config().get(MongoDBAuthenticationMixins.ROOT_USERNAME)); router.sensors().set(MongoDBAuthenticationMixins.AUTHENTICATION_DATABASE, router.config().get(MongoDBAuthenticationMixins.AUTHENTICATION_DATABASE)); addEnricher(Enrichers.builder().propagating(MongoDBRouter.PORT).from(router).build()); super.doStart(locations); sensors().set(Startable.SERVICE_UP, true); }
Source:
<code>private void pingSession( @Nonnull final MemcachedBackupSession session, @Nonnull final BackupSessionService backupSessionService ) { boolean touchResult; try { touchResult = _memcached.add( _storageKeyFormat.format(session.getIdInternal()), 5, BYTE_1 ); <START> } catch ( final IOException e ) { <END> _log.warn( "An exception occurred when trying to ping session " + session.getIdInternal(), e ); return; } if ( touchResult ) { _stats.nonStickySessionsPingFailed(); _log.warn( "The session " + session.getIdInternal() + " should be touched in memcached, but it does not exist" + " therein. Will store in memcached again." ); updateSession( session, backupSessionService ); } else _log.debug( "The session was ping'ed successfully." ); }</code><technical_language>Catch Exception</technical_language>

Target:
private void pingSession( @Nonnull final MemcachedBackupSession session, @Nonnull final BackupSessionService backupSessionService ) throws InterruptedException { final Future<Boolean> touchResult = _memcached.add( _storageKeyFormat.format(session.getIdInternal()), 5, BYTE_1 ); try { if ( touchResult.get() ) { _stats.nonStickySessionsPingFailed(); _log.warn( "The session " + session.getIdInternal() + " should be touched in memcached, but it does not exist" + " therein. Will store in memcached again." ); updateSession( session, backupSessionService ); } else _log.debug( "The session was ping'ed successfully." ); } catch ( final ExecutionException e ) { _log.warn( "An exception occurred when trying to ping session " + session.getIdInternal(), e ); } }
Source:
<code>protected void load(WebContext webContext, BaseEntity<?> entity, List<Mapping> properties) { boolean hasError = false; for (Mapping columnProperty : properties) { Property property = entity.getDescriptor().getProperty(columnProperty); String propertyName = property.getName(); final Value parameterValue = webContext.get(propertyName); if (parameterValue.isNull()) { <START> continue; <END> } try { property.parseValues(entity, Values.of(parameterValue.get(List.class, Collections.singletonList(parameterValue.get())))); ensureTenantMatch(entity, property); } catch (HandledException exception) { UserContext.setFieldError(propertyName, parameterValue); UserContext.setErrorMessage(propertyName, exception.getMessage()); hasError = true; } } if (hasError) { throw Exceptions.createHandled().withNLSKey("BizController.illegalArgument").handle(); } }</code><technical_language>this handled a stream + filter a method + return</technical_language>

Target:
protected void load(WebContext webContext, BaseEntity<?> entity, List<Mapping> properties) { boolean hasError = false; for (Mapping columnProperty : properties) { Property property = entity.getDescriptor().getProperty(columnProperty); if (!tryLoadProperty(webContext, entity, property)) { hasError = true; } } if (hasError) { throw Exceptions.createHandled().withNLSKey("BizController.illegalArgument").handle(); } }
Source:
<code>public void testCheckWrongArgumentForFormat() throws Exception { OracleExportAction.OracleExportActionConfig oracleExportActionConfig = new OracleExportAction.OracleExportActionConfig(sshServer.getHost(), sshServer.getPort(), USER, PASSPHRASE, "system", "cask", "home", "sid", "/tmp/junit.csv", "select * from test;", "format"); OracleExportAction oracleExportAction = new OracleExportAction(oracleExportActionConfig); MockActionContext mockActionContext = new MockActionContext(); try { oracleExportAction.run(mockActionContext); } catch (IllegalArgumentException e) { <START> Assert.assertEquals("Invalid format 'format'. Must be one of [csv, tsv, psv]", e.getMessage()); <END> } }</code><technical_language>construct this message in is constructed exception is thrown</technical_language>

Target:
public void testCheckWrongArgumentForFormat() throws Exception { OracleExportAction.OracleExportActionConfig oracleExportActionConfig = new OracleExportAction.OracleExportActionConfig(sshServer.getHost(), sshServer.getPort(), USER, "Password", PASSPHRASE, "", "", "system", "cask", "home", "sid", "/tmp/junit.csv", "select * from test;", "", "/tmp", "format"); try { MockPipelineConfigurer configurer = new MockPipelineConfigurer(null); new OracleExportAction(oracleExportActionConfig).configurePipeline(configurer); } catch (IllegalArgumentException e) { Assert.assertEquals(String.format("Invalid format '%s'. Must be one of %s", "format", EnumSet.allOf(OracleExportAction.SeparatorFormat.class)), e.getMessage()); } }
Source:
<code>public void configurePipeline(PipelineConfigurer pipelineConfigurer) { <START> pipelineConfigurer.createDataset(config.fileSetName, FileSet.class, FileSetProperties.builder() <END> .setInputFormat(TextInputFormat.class) .setOutputFormat(TextOutputFormat.class) .setOutputProperty(TextOutputFormat.SEPERATOR, ":").build()); }</code><technical_language>do some validation too. For example, if input schema is non-null, fieldToClassify exists is of type String, predictionField exists is of type double</technical_language>

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) { pipelineConfigurer.createDataset(config.fileSetName, FileSet.class); Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); if (inputSchema != null) { validateSchema(inputSchema); } }
Source:
<code>public void sentMessageIsReceivedWithHeadersRouting() throws InterruptedException, IOException, TimeoutException { to.expectedMessageCount(1); Channel channel = connection().createChannel(); channel.basicPublish(HEADERS_EXCHANGE, "", propertiesWithHeader("foo", "bar"), MSG.getBytes()); channel.basicPublish(HEADERS_EXCHANGE, "", null, MSG.getBytes()); channel.basicPublish(HEADERS_EXCHANGE, "", propertiesWithHeader("foo", "bra"), MSG.getBytes()); <START> Thread.sleep(500); <END> to.assertIsSatisfied(); }</code><technical_language>Awaitility for this purpose</technical_language>

Target:
public void sentMessageIsReceivedWithHeadersRouting() throws InterruptedException, IOException, TimeoutException { to.expectedMessageCount(1); Channel channel = connection().createChannel(); channel.basicPublish(HEADERS_EXCHANGE, "", propertiesWithHeader("foo", "bar"), MSG.getBytes()); channel.basicPublish(HEADERS_EXCHANGE, "", null, MSG.getBytes()); channel.basicPublish(HEADERS_EXCHANGE, "", propertiesWithHeader("foo", "bra"), MSG.getBytes()); Awaitility.await() .during(1000, TimeUnit.MILLISECONDS) .atMost(2000, TimeUnit.MILLISECONDS) .until(() -> to.getReceivedCounter() >= 1); to.assertIsSatisfied(); }
Source:
<code>public ListenableFuture<JobStatus<Ticket>> createTicketAsync(Ticket ticket) { <START> return submit(req("POST", cnst("/tickets.json?async=true"), <END> JSON, json(Collections.singletonMap("ticket", ticket))), handleJobStatus(Ticket.class)); }</code><technical_language>Is create a ticket async=true a ListenableFuture a return type</technical_language>

Target:
public ListenableFuture<Ticket> createTicketAsync(Ticket ticket) { return submit(req("POST", cnst("/tickets.json"), JSON, json(Collections.singletonMap("ticket", ticket))), handle(Ticket.class, "ticket")); }
Source:
<code>public List<Folder> findSubFoldersRecursively(Folder folder, User user, boolean respectFrontEndPermissions) throws DotDataException, DotSecurityException { if (!permissionAPI.doesUserHavePermission(folder, PermissionAPI.PERMISSION_READ, user, respectFrontEndPermissions)) { throw new DotSecurityException("User " + user.getUserId() != null?user.getUserId():"" + " does not have permission to read Folder " + folder.getPath()); } <START> List<Folder> subFolders = findSubFolders(folder, user, respectFrontEndPermissions); <END> List<Folder> toIterateOver = new ArrayList<Folder>(subFolders); for (Folder f : toIterateOver) { if (permissionAPI.doesUserHavePermission(f, PermissionAPI.PERMISSION_READ, user, respectFrontEndPermissions)) { subFolders.addAll(findSubFoldersRecursively(f, user, respectFrontEndPermissions)); } } return subFolders; }</code><technical_language>of stream</technical_language>

Target:
public List<Folder> findSubFoldersRecursively(Folder folder, User user, boolean respectFrontEndPermissions) throws DotDataException, DotSecurityException { if (!doesUserHavePermissions(folder, PermissionAPI.PERMISSION_READ, user, respectFrontEndPermissions)) { throw new DotSecurityException("User " + user.getUserId() != null?user.getUserId():"" + " does not have permission to read Folder " + folder.getPath()); } List<Folder> subFolders = findSubFolders(folder, user, respectFrontEndPermissions); List<Folder> toIterateOver = new ArrayList<Folder>(subFolders); for (final Folder subFolder : toIterateOver) { if (doesUserHavePermissions(subFolder, PermissionAPI.PERMISSION_READ, user, respectFrontEndPermissions)) { subFolders.addAll(findSubFoldersRecursively(subFolder, user, respectFrontEndPermissions)); } } return subFolders; }
Source:
<code>public void destroyAllPersistenceContext() { if(recursiveDeleteDirectoryContent(rootDirectory)){ <START> LOGGER.info("Destroying all file based persistence context"); <END> } else { LOGGER.warn("Could not delete all file based persistence context"); } }</code><technical_language>log "Destroyed file based persistence context" instead of "Destroying..." logging deletion done</technical_language>

Target:
public void destroyAllPersistenceContext() { if(recursiveDeleteDirectoryContent(rootDirectory)){ LOGGER.info("Destroyed all file based persistence context"); } else { LOGGER.warn("Could not delete all file based persistence context"); } }
Source:
<code>public void intercept(IMethodInvocation invocation) throws Throwable { <START> if (invocation.getMethod().getKind() == interceptPoint) { <END> invoke(invocation); } }</code><technical_language>right now. :-) is need test injection point. inject instances of this interceptor injection points do work anyway. of is unnecessary provide check injection point. delete this method field constructor parameter change java private void invoke(IMethodInvocation invocation) throws Throwable { java @Override public void intercept(IMethodInvocation invocation) throws Throwable { fine. :-)</technical_language>

Target:
public void intercept(IMethodInvocation invocation) throws Throwable { setUp(invocation); try { invocation.proceed(); } finally { destroy(); } }
Source:
<code>public void initializeDefaultPreferences() { <START> if (!getProfilingType().equals("generic")) { <END> super.performDefaults(); String providerId = ProfileLaunchShortcut .getDefaultLaunchShortcutProviderId(getProfilingType()); configScopeInstance.getNode(getPluginID()) .put(getKey(), providerId); } }</code><technical_language>Hmm.. I a confused setup of this code. do check if type is generic ? this class correspond "generic" profiling type ? is orthogonal</technical_language>

Target:
public void initializeDefaultPreferences() { if (!getProfilingType().equals("generic")) { super.performDefaults(); String providerId = ProfileLaunchShortcut .getDefaultLaunchShortcutProviderId(getProfilingType()); configScopeInstance.getNode(getProfilingType()) .put(PREFS_KEY, providerId); } }
Source:
<code>public String toString() { <START> return null; <END> }</code><technical_language>Add reasonable toString() method, returning null proper way</technical_language>

Target:
public String toString() { return "Command for adding JMS Bridge named '" + name + "\' with attributes: {" + "replaceExisting=" + replaceExisting + ", qualityOfService=" + qualityOfService + ", failureRetryInterval=" + failureRetryInterval + ", maxRetries=" + maxRetries + ", maxBatchSize=" + maxBatchSize + ", maxBatchTime=" + maxBatchTime + ", sourceConnectionFactory='" + sourceConnectionFactory + '\'' + ", sourceDestination='" + sourceDestination + '\'' + ", sourceContext=" + sourceContext + ", targetConnectionFactory='" + targetConnectionFactory + '\'' + ", targetDestination='" + targetDestination + '\'' + ", targetContext=" + targetContext + '}'; }
Source:
<code>public StatementExecution toStatementExecution() throws SQLException { <START> System.out.println("DbStoredProcedureCall: toStatementExecution"); <END> StatementExecution cs = new StatementExecution( this.environment.getConnection().prepareCall(toSqlString()), isFunction() ? this.environment.functionReturnValueViaResultSet() : false, isFunction() ? this.environment.discountFunctionReturnValueParameter() : false); bindParametersTo(cs); return cs; }</code><technical_language>Do need System.out.println</technical_language>

Target:
public StatementExecution toStatementExecution() throws SQLException { StatementExecution cs = new StatementExecution( this.environment.getConnection().prepareCall(toSqlString()), isFunction() ? this.environment.functionReturnValueViaResultSet() : false, isFunction() ? this.environment.discountFunctionReturnValueParameter() : false); bindParametersTo(cs); return cs; }
Source:
<code>protected SashForm createSash(Composite parent) { <START> final Composite sashComposite = new Composite(parent, SWT.FILL); <END> final GridLayout sashLayout = GridLayoutFactory.fillDefaults().create(); sashLayout.marginWidth = 0; sashComposite.setLayout(sashLayout); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(sashComposite); final SashForm sash = new SashForm(sashComposite, SWT.VERTICAL); sash.setBackground(parent.getBackground()); GridDataFactory.fillDefaults().grab(true, true).align(SWT.FILL, SWT.FILL).applyTo(sash); sash.setSashWidth(5); return sash; }</code><technical_language>do need this composite? border composite</technical_language>

Target:
protected SashForm createSash(Composite parent) { final SashForm sash = new SashForm(parent, SWT.VERTICAL); sash.setBackground(parent.getBackground()); GridDataFactory.fillDefaults().grab(true, true).align(SWT.FILL, SWT.FILL).applyTo(sash); sash.setSashWidth(5); return sash; }