auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private EvaluationResult anyOfAny(EvaluationCtx context, Function function, List<AttributeValue> args, List<BagAttribute> bagArgs) { EvaluationResult result = new EvaluationResult(BooleanAttribute.getInstance(false)); <START> if (args.size() > 0) { <END> for (int i = 0; i < args.size() - 1; i++) { AttributeValue value = args.get(i); List<AttributeValue> bagValue = new ArrayList<>(); bagValue.add(value); BagAttribute bagArg = new BagAttribute(value.getType(), bagValue); result = anyAndAllHelper(context, function, args.subList(i + 1, args.size()), bagArg, false); if (result.indeterminate() || ((BooleanAttribute) (result.getAttributeValue())).getValue()) { return result; } } return new EvaluationResult(BooleanAttribute.getInstance(false)); } if (bagArgs.size() > 0) { for (int i = 0; i < bagArgs.size(); i++) { for (int j = i + 1; j < bagArgs.size(); j++) { Iterator iIterator = bagArgs.get(i).iterator(); while (iIterator.hasNext()) { AttributeValue iValue = (AttributeValue) (iIterator.next()); Iterator jIterator = bagArgs.get(j).iterator(); while (jIterator.hasNext()) { AttributeValue jValue = (AttributeValue) (jIterator.next()); result = getEvaluationResult(context, function, jValue, iValue, false); if (result != null && (result.indeterminate() || ((BooleanAttribute) (result.getAttributeValue())).getValue())) { return result; } } } } } return new EvaluationResult(BooleanAttribute.getInstance(false)); } return null; }</code><technical_language>redundant for loop checks this</technical_language>

Target:
private EvaluationResult anyOfAny(EvaluationCtx context, Function function, List<AttributeValue> args, List<BagAttribute> bagArgs) { EvaluationResult result = new EvaluationResult(BooleanAttribute.getInstance(false)); if (!args.isEmpty()) { for (int i = 0; i < args.size() - 1; i++) { AttributeValue value = args.get(i); List<AttributeValue> bagValue = new ArrayList<>(); bagValue.add(value); BagAttribute bagArg = new BagAttribute(value.getType(), bagValue); result = anyAndAllHelper(context, function, args.subList(i + 1, args.size()), bagArg, false); if (result.indeterminate() || ((BooleanAttribute) (result.getAttributeValue())).getValue()) { return result; } } return new EvaluationResult(BooleanAttribute.getInstance(false)); } if (!bagArgs.isEmpty()) { for (int i = 0; i < bagArgs.size(); i++) { for (int j = i + 1; j < bagArgs.size(); j++) { Iterator iIterator = bagArgs.get(i).iterator(); while (iIterator.hasNext()) { AttributeValue iValue = (AttributeValue) (iIterator.next()); Iterator jIterator = bagArgs.get(j).iterator(); while (jIterator.hasNext()) { AttributeValue jValue = (AttributeValue) (jIterator.next()); result = getEvaluationResult(context, function, jValue, iValue, false); if (result != null && (result.indeterminate() || ((BooleanAttribute) (result.getAttributeValue())).getValue())) { return result; } } } } } return new EvaluationResult(BooleanAttribute.getInstance(false)); } return null; }
Source:
<code><START> public void setUp() throws Exception { <END> tested = new SwitchViewControl("COLUMNS", "Case View", caseViewSwitchHandler, "SITEMAP", "Process View", processViewSwitchHandler); }</code><technical_language>Exception is thrown</technical_language>

Target:
public void setUp() { tested = new SwitchViewControl("COLUMNS", "Case View", caseViewSwitchHandler, "SITEMAP", "Process View", processViewSwitchHandler); }
Source:
<code>public JobId reSubmit(JobId currentJobId, Map<String, String> jobVariables, Map<String, String> jobGenericInfos) throws NotConnectedException, UnknownJobException, PermissionException, JobCreationException, SubmissionClosedException { <START> final String jobContent = getJobContent(currentJobId); <END> final Job job = JobFactory.getFactory().createJob(jobContent, jobVariables, jobGenericInfos); return submit(job); }</code><technical_language>![MINOR](<LINK_2> 'Severity: MINOR') Remove redundant '!unknownSymbol!' thrown exception declaration(s). [![rule](<LINK_1>](<LINK_0></technical_language>

Target:
public JobId reSubmit(JobId currentJobId, Map<String, String> jobVariables, Map<String, String> jobGenericInfos) throws NotConnectedException, UnknownJobException, PermissionException, JobCreationException, SubmissionClosedException { final String jobContent = getJobContent(currentJobId); final Job job = JobFactory.getFactory().createJob(IOUtils.toInputStream(jobContent, Charset.forName("UTF-8")), jobVariables, jobGenericInfos); return submit(job); }
Source:
<code>private static boolean isSkippable( final Class<?> handlerType, final String methodName, final Class<?>... paramTypes) throws Exception { return AccessController.doPrivileged(new PrivilegedExceptionAction<Boolean>() { @Override public Boolean run() throws Exception { Method m; try { m = handlerType.getMethod(methodName, paramTypes); } catch (NoSuchMethodException e) { <START> logger.debug("Class missing method {}.", handlerType, methodName, e); <END> return false; } return m.isAnnotationPresent(Skip.class); } }); }</code><technical_language>e is thrown away. do logger.debug(e) instead? (Yes, a bit data, I expect extra data much.)</technical_language>

Target:
private static boolean isSkippable( final Class<?> handlerType, final String methodName, final Class<?>... paramTypes) throws Exception { return AccessController.doPrivileged(new PrivilegedExceptionAction<Boolean>() { @Override public Boolean run() throws Exception { Method m; try { m = handlerType.getMethod(methodName, paramTypes); } catch (NoSuchMethodException e) { logger.debug( "Class missing method {}, assume we can not skip execution", handlerType, methodName, e); return false; } return m.isAnnotationPresent(Skip.class); } }); }
Source:
<code>private void doPaint(GC gc) { <START> if (fCanvas.isVisible()) { <END> return; } ILineRange visibleModelLines= computeVisibleModelLines(); if (visibleModelLines == null) return; fSensitiveToTextChanges= isViewerCompletelyShown(); fScrollPos= fCachedTextWidget.getTopPixel(); fRevisionPainter.paint(gc, visibleModelLines); if (!fRevisionPainter.hasInformation()) fDiffPainter.paint(gc, visibleModelLines); }</code><technical_language>visible</technical_language>

Target:
private void doPaint(GC gc) { if (!fCanvas.isVisible()) { return; } ILineRange visibleModelLines= computeVisibleModelLines(); if (visibleModelLines == null) return; fSensitiveToTextChanges= isViewerCompletelyShown(); fScrollPos= fCachedTextWidget.getTopPixel(); fRevisionPainter.paint(gc, visibleModelLines); if (!fRevisionPainter.hasInformation()) fDiffPainter.paint(gc, visibleModelLines); }
Source:
<code>public void testSanitizeForHtmlList() { List<String> input = new ArrayList<>(); input.add("apple <"); input.add("banana ' dogs "); input.add("rollercoasters & tycoons"); input.add(""); input.add(null); List<String> expected = new ArrayList<>(); expected.add("apple &lt;"); expected.add("banana &#39; dogs "); expected.add("rollercoasters &amp; tycoons"); expected.add(""); expected.add(null); assertEquals(expected, SanitizationHelper.sanitizeForHtml(input)); <START> assertEquals(new ArrayList<String>(), SanitizationHelper.sanitizeForHtml(new ArrayList<>())); <END> assertEquals(null, SanitizationHelper.sanitizeForHtml((List<String>) null)); }</code><technical_language>true fine then</technical_language>

Target:
public void testSanitizeForHtmlList() { List<String> unsanitizedHtml = new ArrayList<>(Arrays.asList( "apple <", "banana ' dogs ", "rollercoasters & tycoons", "", null) ); List<String> sanitizedHtml = new ArrayList<>(Arrays.asList( "apple &lt;", "banana &#39; dogs ", "rollercoasters &amp; tycoons", "", null) ); assertEquals(sanitizedHtml, SanitizationHelper.sanitizeForHtml(unsanitizedHtml)); assertEquals(new ArrayList<>(), SanitizationHelper.sanitizeForHtml(new ArrayList<>())); assertNull(SanitizationHelper.sanitizeForHtml((List<String>) null)); }
Source:
<code>public void init(RuntimeServices rs) { <START> final String logfile = DfBuildProperties.getInstance().getWorkDir() + "log/velocity.log"; <END> try { logger = Logger.getLogger(getClass().getName()); logger.setAdditivity(false); logger.setLevel(Level.DEBUG); final DfFlutistRollingFileAppender appender = createOriginalRollingFileAppender(logfile); appender.setMaxBackupIndex(2); appender.setMaximumFileSize(300000); logger.addAppender(appender); log(0, ""); log(0, DfTypeUtil.toClassTitle(this) + " initialized using logfile '" + logfile + "'"); } catch (Exception e) { System.out.println("PANIC : error configuring " + DfTypeUtil.toClassTitle(this)); e.printStackTrace(); } }</code><technical_language>DfEngineWorkDir? workDir variables trouble. this: DfEngineWorkDir.toPath("log/velocity.log"); DfEngineWorkDir DfBuildProperties in it</technical_language>

Target:
public void init(RuntimeServices rs) { final String logfile = DfEngineWorkDir.toPath("./log/velocity.log"); try { logger = Logger.getLogger(getClass().getName()); logger.setAdditivity(false); logger.setLevel(Level.DEBUG); final DfFlutistRollingFileAppender appender = createOriginalRollingFileAppender(logfile); appender.setMaxBackupIndex(2); appender.setMaximumFileSize(300000); logger.addAppender(appender); log(0, ""); log(0, DfTypeUtil.toClassTitle(this) + " initialized using logfile '" + logfile + "'"); } catch (Exception e) { System.out.println("PANIC : error configuring " + DfTypeUtil.toClassTitle(this)); e.printStackTrace(); } }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_review); ButterKnife.bind(this); initDrawer(); yesButton=findViewById(R.id.yesButton); noButton=findViewById(R.id.noButton); <START> <END> reviewController = new ReviewController(); reviewPagerAdapter = new ReviewPagerAdapter(getSupportFragmentManager()); reviewPager.setAdapter(reviewPagerAdapter); reviewPagerAdapter.getItem(0); pagerIndicator.setViewPager(reviewPager); progressBar.setVisibility(View.VISIBLE); runRandomizer(); skip_image_button.setOnClickListener(view -> runRandomizer()); }</code><technical_language>@BindView for referencing variables, for other views. Please remove findViewById methods preserve consistency in code</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_review); ButterKnife.bind(this); initDrawer(); reviewController = new ReviewController(); reviewPagerAdapter = new ReviewPagerAdapter(getSupportFragmentManager()); reviewPager.setAdapter(reviewPagerAdapter); reviewPagerAdapter.getItem(0); pagerIndicator.setViewPager(reviewPager); progressBar.setVisibility(View.VISIBLE); runRandomizer(); skip_image_button.setOnClickListener(view -> runRandomizer()); }
Source:
<code>private boolean isExpansionChange(Notification notification) { <START> return notification.getFeature() == TreePackage.Literals.DTREE_ITEM__EXPANDED && notification.getNotifier() instanceof DTreeItem; <END> }</code><technical_language>Nitpick: instanceof check is redundant here</technical_language>

Target:
private boolean isExpansionChange(Notification notification) { return notification.getFeature() == TreePackage.Literals.DTREE_ITEM__EXPANDED; }
Source:
<code>private List<Long> getSortedBatchedStartTimestamps(UUID requestorUuid, int numRequestedTimestamps) { BatchedStartTransactionRequest request = BatchedStartTransactionRequest.createForRequestor( requestorUuid, numRequestedTimestamps); BatchedStartTransactionResponse response = CLUSTER.timelockRpcClient().batchedStartTransaction(request); return response.timestamps().stream() .boxed() <START> .sorted() END> .collect(Collectors.toList()); }</code><technical_language>kill lines; wire format means effectively guarantee sort order..</technical_language>

Target:
private List<Long> getSortedBatchedStartTimestamps(UUID requestorUuid, int numRequestedTimestamps) { StartTransactionRequestV4 request = StartTransactionRequestV4.createForRequestor( requestorUuid, numRequestedTimestamps); StartTransactionResponseV4 response = CLUSTER.timelockRpcClient().startTransactions(request); return response.timestamps().stream() .boxed() .collect(Collectors.toList()); }
Source:
<code>protected Map<String, List<ObservationUnitRow>> groupObservationUnitRowsByRangeAndColumn( final List<ObservationUnitRow> observationUnitRows) { final Map<String, List<ObservationUnitRow>> fieldmapExperiments = new HashMap(); for (final ObservationUnitRow observationUnitRow : observationUnitRows) { <START> final String range = observationUnitRow.getVariables().get(ExperimentDao.FIELD_MAP_RANGE).getValue(); <END> final String column = observationUnitRow.getVariables().get(ExperimentDao.FIELD_MAP_COLUMN).getValue(); if (range != null && column != null) { final String key = coordinateKey(Integer.valueOf(column), Integer.valueOf(range)); if (!fieldmapExperiments.containsKey(key)) { fieldmapExperiments.put(key, new LinkedList<ObservationUnitRow>()); } fieldmapExperiments.get(key).add(observationUnitRow); } } return fieldmapExperiments; }</code><technical_language>Please do Dao class in BMSAPI</technical_language>

Target:
protected Map<String, List<ObservationUnitRow>> groupObservationUnitRowsByRangeAndColumn( final List<ObservationUnitRow> observationUnitRows) { final Map<String, List<ObservationUnitRow>> fieldmapExperiments = new HashMap(); for (final ObservationUnitRow observationUnitRow : observationUnitRows) { final String range = observationUnitRow.getVariables().get(FIELDMAP_RANGE).getValue(); final String column = observationUnitRow.getVariables().get(FIELDMAP_COLUMN).getValue(); if (range != null && column != null) { final String key = coordinateKey(Integer.valueOf(column), Integer.valueOf(range)); if (!fieldmapExperiments.containsKey(key)) { fieldmapExperiments.put(key, new LinkedList<ObservationUnitRow>()); } fieldmapExperiments.get(key).add(observationUnitRow); } } return fieldmapExperiments; }
Source:
<code><START> private RoundViewModel createViewModel(Sequence updatedSequence) { <END> int nextNotesPosition = updatedSequence.position(); List<String> notations = getNotations(nextNotesPosition); String statusMessage = getStatusMessage(); return new RoundViewModel(notations, statusMessage); }</code><technical_language>yeah a Converter converts in model Domain objects ViewModel, done yet. understand Domain stuff wrote :-). // edit atual</technical_language>

Target:
private RoundViewModel createViewModel(Sequence updatedSequence) { int nextNotesPosition = updatedSequence.position(); List<String> notations = getNotations(nextNotesPosition); String statusMessage = getStatusMessage(updatedSequence); return new RoundViewModel(notations, statusMessage); }
Source:
<code>@Test public void testParse() throws NoSuchAuthorityCodeException { final URN_Parser parser = URN_Parser.buildParser("urn:ogc:def:CRS:EPSG:6.11.2:4326"); assertEquals("crs", parser.type.name); assertEquals("EPSG", parser.authority); assertEquals("6.11.2", parser.version.toString()); <START> assertEquals("4326", parser.code); <END> assertEquals("EPSG:4326", parser.getAuthorityCode()); }</code><technical_language>this is white space changes right</technical_language>

Target:
public void testParse() throws NoSuchAuthorityCodeException { final URN_Parser parser = URN_Parser.buildParser("urn:ogc:def:CRS:EPSG:6.11.2:4326"); assertEquals("crs", parser.type.name); assertEquals("EPSG", parser.authority); assertEquals("6.11.2", parser.version.toString()); assertEquals("4326", parser.code); assertEquals("EPSG:4326", parser.getAuthorityCode()); }
Source:
<code>private void setAboutThisCourse() { getCourseDetailTask = new GetCourseDetailTask(getActivity(), courseDetail.course_id) { @Override protected void onSuccess(CourseDetail courseDetail) throws Exception { super.onSuccess(courseDetail); if (courseDetail.overview != null && !courseDetail.overview.isEmpty()) { setAboutThisCourse(courseDetail.overview); } else { courseAbout.setVisibility(View.GONE); } } @Override protected void onException(Exception e) throws RuntimeException { super.onException(e); showErrorMessage(e); } }; <START> getCourseDetailTask.execute(); <END> }</code><technical_language>hide default (centered on-screen) loading indicator inline indicator: getCourseDetailTask.setProgressCallback(null)</technical_language>

Target:
private void setAboutThisCourse() { getCourseDetailTask = new GetCourseDetailTask(getActivity(), courseDetail.course_id) { @Override protected void onSuccess(CourseDetail courseDetail) throws Exception { super.onSuccess(courseDetail); if (courseDetail.overview != null && !courseDetail.overview.isEmpty()) { setAboutThisCourse(courseDetail.overview); } else { courseAbout.setVisibility(View.GONE); } } @Override protected void onException(Exception e) throws RuntimeException { super.onException(e); showErrorMessage(e); } }; getCourseDetailTask.setProgressCallback(null); getCourseDetailTask.execute(); }
Source:
<code>public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if (!(req instanceof HttpServletRequest) || !(res instanceof HttpServletResponse)) { throw new ServletException( "VRaptor must be run inside a Servlet environment. Portlets and others aren't supported."); } final HttpServletRequest baseRequest = (HttpServletRequest) req; final HttpServletResponse baseResponse = (HttpServletResponse) res; if (staticHandler.requestingStaticFile(baseRequest)) { staticHandler.deferProcessingToContainer(chain, baseRequest, baseResponse); } else { logger.debug("VRaptor received a new request"); logger.trace("Request: {}", req); VRaptorRequest mutableRequest = new VRaptorRequest(baseRequest); VRaptorResponse mutableResponse = new VRaptorResponse(baseResponse); final RequestInfo request = new RequestInfo(servletContext, chain, mutableRequest, mutableResponse); try { encodingHandler.setEncoding(baseRequest, baseResponse); provider.provideForRequest(request); <START> provider.getContainer().instanceFor(RequestExecution.class).execute(); <END> } catch (ApplicationLogicException e) { throw new ServletException(e.getMessage(), e.getCause()); } logger.debug("VRaptor ended the request"); } }</code><technical_language>Method instanceFor remove is a bottleneck. this, performance issues again</technical_language>

Target:
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if (!(req instanceof HttpServletRequest) || !(res instanceof HttpServletResponse)) { throw new ServletException( "VRaptor must be run inside a Servlet environment. Portlets and others aren't supported."); } final HttpServletRequest baseRequest = (HttpServletRequest) req; final HttpServletResponse baseResponse = (HttpServletResponse) res; if (staticHandler.requestingStaticFile(baseRequest)) { staticHandler.deferProcessingToContainer(chain, baseRequest, baseResponse); } else { logger.debug("VRaptor received a new request"); logger.trace("Request: {}", req); VRaptorRequest mutableRequest = new VRaptorRequest(baseRequest); VRaptorResponse mutableResponse = new VRaptorResponse(baseResponse); final RequestInfo request = new RequestInfo(servletContext, chain, mutableRequest, mutableResponse); try { encodingHandler.setEncoding(baseRequest, baseResponse); provider.provideForRequest(request); execution.execute(); } catch (ApplicationLogicException e) { throw new ServletException(e.getMessage(), e.getCause()); } logger.debug("VRaptor ended the request"); } }
Source:
<code>public Response doGetLog( @PathParam("taskid") String taskid, @QueryParam("offset") @DefaultValue("0") long offset ) { if (!(taskRunner instanceof TaskLogStreamer)) { <START> return Response.status(501).entity("Log streaming not supported").build(); <END> } try { final Optional<ByteSource> stream = ((TaskLogStreamer) taskRunner).streamTaskLog(taskid, offset); if (stream.isPresent()) { return Response.ok(stream.get().openStream()).build(); } else { return Response.status(Response.Status.NOT_FOUND).build(); } } catch (IOException e) { log.warn(e, "Failed to read log for task: %s", taskid); return Response.serverError().build(); } }</code><technical_language>Include TaskRunner class name,</technical_language>

Target:
public Response doGetLog( @PathParam("taskid") String taskid, @QueryParam("offset") @DefaultValue("0") long offset ) { if (!(taskRunner instanceof TaskLogStreamer)) { return Response.status(501) .entity(String.format( "Log streaming not supported by [%s]", taskRunner.getClass().getCanonicalName() )) .build(); } try { final Optional<ByteSource> stream = ((TaskLogStreamer) taskRunner).streamTaskLog(taskid, offset); if (stream.isPresent()) { return Response.ok(stream.get().openStream()).build(); } else { return Response.status(Response.Status.NOT_FOUND).build(); } } catch (IOException e) { log.warn(e, "Failed to read log for task: %s", taskid); return Response.serverError().build(); } }
Source:
<code>private void createToken() throws NoSuchAlgorithmException { <START> SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); <END> setToken(new BigInteger(130, random).toString(32)); }</code><technical_language>Is alternative SHA1PRNG? SHA-1 is considered insecure</technical_language>

Target:
private void createToken() { try { CryptoRandomGenerator randomGenerator = CryptoRandomGenerator.getInstance(); token = randomGenerator.createToken(); if (!token.equals("login")) { setToken(token); } } catch (Exception ex) { LOG.debug("CSRFToken Generation failed :" + ex.getMessage(), ex); } }
Source:
<code>default Optional<Question> getCurrentQuestion() { <START> return this.getCurrentDialogue().flatMap(inst -> inst.getCurrentQuestionFor(this)); <END> }</code><technical_language>inst -> dialogue</technical_language>

Target:
default Optional<Question> getCurrentQuestion() { return this.getCurrentDialogue().flatMap(dialogue -> dialogue.getCurrentQuestionFor(this)); }
Source:
<code>public void testCommandMandatoryConstructorsExistence() { Predicate<Constructor<?>> classForcesCompensation = constructor -> constructor.getDeclaringClass().isAnnotationPresent(NonTransactiveCommandAttribute.class) && constructor.getDeclaringClass().getAnnotation(NonTransactiveCommandAttribute.class) .forceCompensation(); Predicate<Class<CommandBase<? extends VdcActionParametersBase>>> classLacksParamsAndContextCtor = getPredicateForNoCtorMatchesGivenPredicate(parametersAndContextConstructorSignature); Predicate<Class<CommandBase<? extends VdcActionParametersBase>>> classLacksGuidCtor = getPredicateForNoCtorMatchesGivenPredicate(classForcesCompensation.negate().or(guidConstructorSignature)); List<String> commandsWithoutMandatoryConstructor = commandClasses.stream() .filter(classLacksParamsAndContextCtor.or(classLacksGuidCtor)) .map(Class::getSimpleName) .sorted() .collect(Collectors.toList()); assertThat("There are commands that don't contain at least one of the mandatory constructors:" + System.lineSeparator() + "1. A constructor that receives parameters and context objects." + System.lineSeparator() + "2. A constructor that receives a Guid object, its class is annotated with " + <START> "'NonTransactiveCommandAttribute' and <END> the annotation's 'forceCompensation' attribute is set to true.", commandsWithoutMandatoryConstructor, empty()); }</code><technical_language>this replace actual annotation name NonTransactiveCommandAttribute.getClass().getSimpleName() prevent mismatch in case of changing class name in future</technical_language>

Target:
public void testCommandMandatoryConstructorsExistence() { Predicate<Constructor<?>> classForcesCompensation = constructor -> constructor.getDeclaringClass().isAnnotationPresent(NonTransactiveCommandAttribute.class) && constructor.getDeclaringClass().getAnnotation(NonTransactiveCommandAttribute.class) .forceCompensation(); Predicate<Class<CommandBase<? extends VdcActionParametersBase>>> classLacksParamsAndContextCtor = getPredicateForNoCtorMatchesGivenPredicate(parametersAndContextConstructorSignature); Predicate<Class<CommandBase<? extends VdcActionParametersBase>>> classLacksGuidCtor = getPredicateForNoCtorMatchesGivenPredicate(classForcesCompensation.negate().or(guidConstructorSignature)); List<String> commandsWithoutMandatoryConstructor = commandClasses.stream() .filter(classLacksParamsAndContextCtor.or(classLacksGuidCtor)) .map(Class::getSimpleName) .sorted() .collect(Collectors.toList()); assertThat("There are commands that don't contain at least one of the mandatory constructors:" + System.lineSeparator() + "1. A constructor that receives parameters and context objects." + System.lineSeparator() + "2. A constructor that receives a Guid object, its class is annotated with '" + NonTransactiveCommandAttribute.class.getSimpleName() + "' and the annotation's " + "'forceCompensation' attribute is set to true.", commandsWithoutMandatoryConstructor, empty()); }
Source:
<code>public List<PhonePlanGroup> getPhonePlanGroups() { String countryCode = "US"; String locale = "en-us"; try { PhoneNumberClient phoneNumberClient = createPhoneNumberClient(); <START> List<PhonePlanGroup> phonePlanGroups = phoneNumberClient <END> .listPhonePlanGroups(countryCode, locale, true) .stream() .collect(Collectors.toList()); for (PhonePlanGroup phonePlanGroup: phonePlanGroups) { System.out.println("Phone Plan GroupId: " + phonePlanGroup.getPhonePlanGroupId()); System.out.println("Phone Plan NumberType: " + phonePlanGroup.getPhoneNumberType()); } return phonePlanGroups; } catch (Exception e) { e.printStackTrace(); } return null; }</code><technical_language>phoneNumberClient.listPhonePlanGroups returns Iterable, able for loop directly. PagedIterable<PhonePlanGroup> pagedIterable = phoneNumberClient.listPhonePlanGroups(countryCode, locale, true); for (PhonePlanGroup phonePlanGroup: pagedIterable) { System.out.println("Phone Plan GroupId: " + phonePlanGroup.getPhonePlanGroupId()); System.out.println("Phone Plan NumberType: " + phonePlanGroup.getPhoneNumberType()); } do for other examples instead of collecting a list first</technical_language>

Target:
public PagedIterable<PhonePlanGroup> getPhonePlanGroups() { String countryCode = "US"; String locale = "en-us"; try { PhoneNumberClient phoneNumberClient = createPhoneNumberClient(); PagedIterable<PhonePlanGroup> phonePlanGroups = phoneNumberClient .listPhonePlanGroups(countryCode, locale, true); for (PhonePlanGroup phonePlanGroup : phonePlanGroups) { System.out.println("Phone Plan GroupId: " + phonePlanGroup.getPhonePlanGroupId()); System.out.println("Phone Plan NumberType: " + phonePlanGroup.getPhoneNumberType()); } return phonePlanGroups; } catch (Exception e) { e.printStackTrace(); } return null; }
Source:
<code>private void addHeaderParams(DetailedLink link, Action action) { if (action.getRequest().getHeaders() != null && !action.getRequest().getHeaders().isEmpty()) { link.getRequest().setHeaders(new Headers()); for (Object key : action.getRequest().getHeaders().keySet()) { Header header = new Header(); header.setName(key.toString()); Object value = action.getRequest().getHeaders().get(key); if (value != null) { ParamData paramData = (ParamData) value; header.setValue(paramData.getValue()); <START> header.setRequired(paramData.getRequired() == null ? new Boolean(false) : paramData.getRequired()); <END> } link.getRequest().getHeaders().getHeaders().add(header); } } }</code><technical_language>Boolean.FALSE</technical_language>

Target:
private void addHeaderParams(DetailedLink link, Action action) { if (action.getRequest().getHeaders() != null && !action.getRequest().getHeaders().isEmpty()) { link.getRequest().setHeaders(new Headers()); for (Object key : action.getRequest().getHeaders().keySet()) { Header header = new Header(); header.setName(key.toString()); Object value = action.getRequest().getHeaders().get(key); if (value != null) { ParamData paramData = (ParamData) value; header.setValue(paramData.getValue()); header.setRequired(paramData.getRequired() == null ? Boolean.FALSE : paramData.getRequired()); } link.getRequest().getHeaders().getHeaders().add(header); } } }
Source:
<code>public void getDescription_NewAnnotation() throws NoSuchMethodException { <START> String actualResult = getDescriptionWithMethodNameAndParamIndex(TEST_METHOD_6, FIRST_INDEX); <END> assertEquals(SECOND_DESCRIPTION_PARAM_ANNOTATION, actualResult); }</code><technical_language>Abbreviation for variable name: Result -> res. abbreviation rules</technical_language>

Target:
public void getDescription_NewAnnotation() throws NoSuchMethodException { String actualRes = getDescriptionWithMethodNameAndParamIndex(TEST_METHOD_6, FIRST_INDEX); assertEquals(SECOND_DESCRIPTION_PARAM_ANNOTATION, actualRes); }
Source:
<code>public Map<String, PortSelection> getPortSelectionMap() { <START> Map<String, PortSelection> res = Arrays.stream(environment.getProperty("ot.httpserver.active-connectors", "default-http").split(",")) <END> .map(connectorName -> { if (connectorName.equals(BOOT_CONNECTOR_NAME)) { final boolean sslEnabled = Boolean.parseBoolean(environment.getProperty(SERVER_SSL_ENABLED, "true")) && environment.getProperty("server.ssl.key-store") != null; return getWithDefault(SERVER_PORT, sslEnabled ? "PORT_HTTPS" : "PORT_HTTP", 8080); } if (connectorName.equals(DEFAULT_CONNECTOR_NAME)) { final boolean sslEnabled = "https".equalsIgnoreCase(environment.getProperty("ot.httpserver.connector." + connectorName + ".protocol", "http")); return getWithDefault("ot.httpserver.connector." + connectorName + ".port", sslEnabled ? "PORT_HTTPS" : "PORT_HTTP", 0); } return getWithDefault("ot.httpserver.connector." + connectorName + ".port", "PORT_" + connectorName.toUpperCase(Locale.US), 0); }).collect(Collectors.toMap(i -> i.name, Function.identity())); res.put(JMX_PORT, getJMXPort()); res.put(MANAGEMENT_SERVER_PORT, getActuatorPort()); return res; }</code><technical_language>trim whitespace. Whitespace is mean</technical_language>

Target:
public Map<String, PortSelection> getPortSelectionMap() { Map<String, PortSelection> res = Arrays.stream(environment.getProperty("ot.httpserver.active-connectors", "default-http").split(",")) .map(String::trim) .map(connectorName -> { if (connectorName.equals(BOOT_CONNECTOR_NAME)) { final boolean sslEnabled = Boolean.parseBoolean(environment.getProperty(SERVER_SSL_ENABLED, "true")) && environment.getProperty("server.ssl.key-store") != null; String namedPort = sslEnabled ? "PORT_HTTPS" : "PORT_HTTP"; if (environment.containsProperty("PORT_BOOT")) { namedPort = "PORT_BOOT"; } return getWithDefault(SERVER_PORT, namedPort, 8080); } if (connectorName.equals(DEFAULT_CONNECTOR_NAME)) { final boolean sslEnabled = "https".equalsIgnoreCase(environment.getProperty("ot.httpserver.connector." + connectorName + ".protocol", "http")); return getWithDefault("ot.httpserver.connector." + connectorName + ".port", sslEnabled ? "PORT_HTTPS" : "PORT_HTTP", 0); } return getWithDefault("ot.httpserver.connector." + connectorName + ".port", "PORT_" + connectorName.toUpperCase(Locale.US), 0); }).collect(Collectors.toMap(i -> i.originalPropertyName, Function.identity())); PortSelection serverPort = res.get(PortSelector.SERVER_PORT); PortSelection defaultHttpPort = res.get(PortSelector.HTTPSERVER_CONNECTOR_DEFAULT_HTTP_PORT); if (serverPort != null && defaultHttpPort != null && serverPort.getSourceInfo() != null && serverPort.getSourceInfo().equals(defaultHttpPort.getSourceInfo())) { LOG.warn("You have defined both the spring boot connector and the default http connector. Under Kubernetes this doesn't function correctly\n.Define a variable PORT_BOOT to workaround this."); } res.put(JMX_PORT, getJMXPort()); res.put(MANAGEMENT_SERVER_PORT, getActuatorPort()); return res; }
Source:
<code>@Test public void injectingExtra_keysAreSanitized() { JavaFileObject source = JavaFileObjects.forSourceString("test.Test", Joiner.on('\n').join( "package test;", "import android.app.Activity;", "import com.f2prateek.dart.InjectExtra;", "public class Test extends Activity {", " @InjectExtra(\"a.b\") String extra;", "}" )); ASSERT.about(javaSource()) .that(source) .processedWith(ProcessorTestUtilities.hensonProcessors()) <START> .failsToCompile(); <END> }</code><technical_language>if assert more specific better</technical_language>

Target:
@Test public void injectingExtra_keysAreSanitized() { JavaFileObject source = JavaFileObjects.forSourceString("test.Test", Joiner.on('\n').join( "package test;", "import android.app.Activity;", "import com.f2prateek.dart.InjectExtra;", "public class Test extends Activity {", " @InjectExtra(\"a.b\") String extra;", "}" )); ASSERT.about(javaSource()) .that(source) .processedWith(ProcessorTestUtilities.hensonProcessors()) .failsToCompile() .withErrorContaining("Keys have to be valid java variable identifiers.") .in(source) .onLine(5); }
Source:
<code>private void centerMapOnUserLocation() { LatLng position = null; LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); <START> criteria.setAccuracy(Criteria.ACCURACY_FINE); <END> String provider = manager.getBestProvider(criteria, true); if (provider != null) { Location location = manager.getLastKnownLocation(provider); if (location != null) { position = new LatLng(location.getLatitude(), location.getLongitude()); } } positionMap(position); }</code><technical_language>discuss use-case for understand more, I wondering need ACCURACY_FINE serve purpose. this level of accuracy consume more battery</technical_language>

Target:
private void centerMapOnUserLocation() { LatLng position = null; LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_COARSE); String provider = manager.getBestProvider(criteria, true); if (provider != null) { Location location = manager.getLastKnownLocation(provider); if (location != null) { position = new LatLng(location.getLatitude(), location.getLongitude()); } } positionMap(position); }
Source:
<code>private void addToGoal(Collection<TeamWorkFlowArtifact> newTeamArts, SkynetTransaction transaction) throws OseeCoreException { if (toGoal != null) { <START> GoalArtifact goal = (GoalArtifact) AtsClientService.get().getArtifact(toGoal); <END> for (Artifact art : newTeamArts) { goal.addMember(art); } goal.persist(transaction); } }</code><technical_language>this goal variable null here</technical_language>

Target:
private void addToGoal(Collection<TeamWorkFlowArtifact> newTeamArts, SkynetTransaction transaction) throws OseeCoreException { if (toGoal != null) { GoalArtifact goal = (GoalArtifact) AtsClientService.get().getArtifact(toGoal); if (goal == null) { throw new OseeArgumentException("Goal artifact does not exist for goal %s", toGoal.toStringWithId()); } for (Artifact art : newTeamArts) { goal.addMember(art); } goal.persist(transaction); } }
Source:
<code>public String getVertexId(Direction direction) { if (direction.equals(Direction.IN)) { return inVertexId; } else if (direction.equals(Direction.OUT)) { return outVertexId; } <START> return null; <END> }</code><technical_language>throw a VertexiumNotSupportedException exception here? I expect blow if I passed in Direction.BOTH</technical_language>

Target:
public String getVertexId(Direction direction) { if (direction.equals(Direction.IN)) { return inVertexId; } else if (direction.equals(Direction.OUT)) { return outVertexId; } throw new VertexiumNotSupportedException(direction.name() + " is not supported"); }
Source:
<code>public ValidationResult validate(Object value) { <START> assert value==null ||value instanceof String; <END> String cidr = (String) value; ValidationResult result = new ValidationResult(); result.setSuccess(true); if (!CidrValidator.isCidrFormatValid(cidr)) { failWith(result, getThisFieldMustContainCidrInFormatMsg()); } else if (!CidrValidator.isCidrNetworkAddressValid(cidr)) { failWith(result, getCidrNotNetworkAddress()); } return result; }</code><technical_language>Please add spacing side of "==" operator</technical_language>

Target:
public ValidationResult validate(Object value) { assert value == null ||value instanceof String; String cidr = (String) value; ValidationResult result = new ValidationResult(); if (!CidrValidator.isCidrFormatValid(cidr)) { failWith(result, getThisFieldMustContainCidrInFormatMsg()); } else if (!CidrValidator.isCidrNetworkAddressValid(cidr)) { failWith(result, getCidrNotNetworkAddress()); } return result; }
Source:
<code>@Override protected Propagation.Setter<Headers, String> setter() { <START> return null; END> }</code><technical_language>suggestion throw new AssertionError("FIXME SETTER");</technical_language>

Target:
@Override protected Propagation.Setter<Headers, String> setter() { return HEADERS_SETTER; }
Source:
<code>public JsonStructure parse(String value) throws IllegalArgumentException { <START> if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL")) return null; <END> if (!Strings.isQuoted(value)) throw new IllegalArgumentException("JSON strings must be enclosed by single quotes"); String json = Strings.unquote(value); try (StringReader sr = new StringReader(json)) { JsonReader reader = readerFactory.createReader(sr); return reader.read(); } catch (JsonException e) { throw new IllegalArgumentException(e.getMessage(), e); } }</code><technical_language>Nit: please add enclosing braces in next line</technical_language>

Target:
public JsonStructure parse(String value) throws IllegalArgumentException { if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL")) { return null; } if (!Strings.isQuoted(value)) { throw new IllegalArgumentException("JSON strings must be enclosed by single quotes"); } String json = Strings.unquote(value); try (StringReader sr = new StringReader(json)) { JsonReader reader = readerFactory.createReader(sr); return reader.read(); } catch (JsonException e) { throw new IllegalArgumentException(e.getMessage(), e); } }
Source:
<code>public DeviceStatusBreakdown getDeviceStatusBreakdown(@Scope(OAuthScope.ADMINISTRATION_READ) final AccessToken accessToken) { final Jedis jedis = jedisPool.getResource(); final DateTime currentTs = DateTime.now(DateTimeZone.UTC); Long normalCount = 0L; try { normalCount = jedis.zcount("devices", currentTs.minusDays(1).getMillis(), currentTs.getMillis()); } catch (Exception e) { <START> LOGGER.error("Failed to get active senses count", e.getMessage()); <END> } finally { jedisPool.returnResource(jedis); } return new DeviceStatusBreakdown(normalCount, -1L, -1L); }</code><technical_language>missing for string substitution</technical_language>

Target:
public DeviceStatusBreakdown getDeviceStatusBreakdown(@Scope(OAuthScope.ADMINISTRATION_READ) final AccessToken accessToken) { final Jedis jedis = jedisPool.getResource(); final DateTime currentTs = DateTime.now(DateTimeZone.UTC); Long normalCount = 0L; try { normalCount = jedis.zcount("devices", currentTs.minusDays(1).getMillis(), currentTs.getMillis()); } catch (Exception e) { LOGGER.error("Failed to get active senses count because {}", e.getMessage()); } finally { jedisPool.returnResource(jedis); } return new DeviceStatusBreakdown(normalCount, -1L, -1L); }
Source:
<code>public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); ChoiceColor choice = new ChoiceColor(); if (controller != null && controller.choose(outcome, choice, game)) { <START> FilterCreaturePermanent filter = new FilterCreaturePermanent(choice.getColor().getDescription()+" creatures"); <END> filter.add(new ColorPredicate(choice.getColor())); for (UUID playerId : game.getState().getPlayersInRange(controller.getId(), game)) { int amount = game.getBattlefield().countAll(filter , playerId, game); if (amount > 0) { Player player = game.getPlayer(playerId); if (player != null) { player.damage(amount, source.getSourceId(), game, false, true); } } } return true; } return false; }</code><technical_language>check choice.getColor() null values, get player connection problem. #4263</technical_language>

Target:
public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); ChoiceColor choice = new ChoiceColor(); if (controller != null && controller.choose(outcome, choice, game) && choice.getColor() != null) { FilterCreaturePermanent filter = new FilterCreaturePermanent(choice.getColor().getDescription()+" creatures"); filter.add(new ColorPredicate(choice.getColor())); for (UUID playerId : game.getState().getPlayersInRange(controller.getId(), game)) { int amount = game.getBattlefield().countAll(filter , playerId, game); if (amount > 0) { Player player = game.getPlayer(playerId); if (player != null) { player.damage(amount, source.getSourceId(), game, false, true); } } } return true; } return false; }
Source:
<code>private void fillTableHeaders(List<DataColumn> columns) { for (int i = 0; i < columns.size(); i++) { <START> TableColumn<ObservableList<StringProperty>, String> fxColumn = createColumn(i, columns.get(i).getName()); <END> fxColumn.setPrefWidth(100); tableView.getColumns().add(fxColumn); } }</code><technical_language>| line | > 100</technical_language>

Target:
private void fillTableHeaders(List<DataColumn> columns) { for (int i = 0; i < columns.size(); i++) { TableColumn<ObservableList<StringProperty>, String> fxColumn = createColumn(i, columns.get(i).getName()); fxColumn.getStyleClass().add("table-column"); tableView.getColumns().add(fxColumn); } }
Source:
<code>DeploymentHandlerUtil.ContentItem addFromContentAdditionParameter(OperationContext context, ModelNode contentItemNode, String name) throws OperationFailedException { byte[] hash; InputStream in = getInputStream(context, contentItemNode); InputStream transformed = null; try { try { transformed = deploymentTransformer == null ? in : deploymentTransformer.transform(in, name); hash = contentRepository.addContent(transformed); } catch (IOException e) { throw createFailureException(e.toString()); <START> } catch(Throwable t) { END> InputStream originalInput = getInputStream(context, contentItemNode); try { hash = contentRepository.addContent(originalInput); } catch (IOException e){ throw createFailureException(e.toString()); } finally { StreamUtils.safeClose(originalInput); } } } finally { StreamUtils.safeClose(in); StreamUtils.safeClose(transformed); } return new DeploymentHandlerUtil.ContentItem(hash); }</code><technical_language>I assume catch is a RuntimeException thrown EclipseTransformer, a java.lang.Error. this catch limited RuntimeException. a general code standard of avoiding suppressing Error, this matters if bypass for deployments DeploymentAttributes.CONTENT_INPUT_STREAM_INDEX, for rethrow exception</technical_language>

Target:
DeploymentHandlerUtil.ContentItem addFromContentAdditionParameter(OperationContext context, ModelNode contentItemNode, String name) throws OperationFailedException { byte[] hash; InputStream in = getInputStream(context, contentItemNode); InputStream transformed = null; try { try { transformed = deploymentTransformer == null ? in : doTransformation(context, contentItemNode, name, in); hash = contentRepository.addContent(transformed); } catch (IOException e) { throw createFailureException(e.toString()); } } finally { StreamUtils.safeClose(in); StreamUtils.safeClose(transformed); } return new DeploymentHandlerUtil.ContentItem(hash); }
Source:
<code>private Function<PollingContext<OperationResult>, Mono<OperationResult>> streamActivationOperation( Function<ContentType, Mono<OperationResult>> activationOperation, Flux<ByteBuffer> form, FormContentType contentType) { return pollingContext -> { Mono<OperationResult> operationResultMono; try { if (contentType != null) { final ContentType givenContentType = ContentType.fromString(contentType.toString()); operationResultMono = activationOperation.apply(givenContentType); } else { operationResultMono = detectContentType(form) <START> .flatMap(detectedContentType -> activationOperation.apply(detectedContentType)); <END> } operationResultMono.onErrorMap(Utility::mapToHttpResponseExceptionIfExist); } catch (RuntimeException ex) { operationResultMono = monoError(logger, ex); } return operationResultMono; }; }</code><technical_language>nit: activationOperation::apply</technical_language>

Target:
private Function<PollingContext<OperationResult>, Mono<OperationResult>> streamActivationOperation( Function<ContentType, Mono<OperationResult>> activationOperation, Flux<ByteBuffer> form, FormContentType contentType) { return pollingContext -> { try { Objects.requireNonNull(form, "'form' is required and cannot be null."); if (contentType != null) { return activationOperation.apply(ContentType.fromString(contentType.toString())) .onErrorMap(Utility::mapToHttpResponseExceptionIfExist); } else { return detectContentType(form) .flatMap(activationOperation::apply) .onErrorMap(Utility::mapToHttpResponseExceptionIfExist); } } catch (RuntimeException ex) { return monoError(logger, ex); } }; }
Source:
<code>public void setIOSamplingRate(int rate) throws TimeoutException, XBeeException { <START> if (rate < 0) <END> throw new IllegalArgumentException("Rate must be >= 0."); if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); ATCommandResponse response = null; try { if (isRemote()) response = sendATCommand(new ATCommand("IR", ByteUtils.intToByteArray(rate)), XBeeTransmitOptions.APPLY_CHANGES); else response = sendATCommand(new ATCommand("IR", ByteUtils.intToByteArray(rate))); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } checkATCommandResponseIsValid(response); }</code><technical_language>I **IR** command a maximum of 0xFFFF, add a maximum checker throw IllegalArgumentException is greater</technical_language>

Target:
public void setIOSamplingRate(int rate) throws TimeoutException, XBeeException { if (rate < 0 || rate > 0xFFFF) throw new IllegalArgumentException("Rate must be between 0 and 0xFFFF."); if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); ATCommandResponse response = null; try { if (isRemote()) response = sendATCommand(new ATCommand("IR", ByteUtils.intToByteArray(rate)), XBeeTransmitOptions.APPLY_CHANGES); else response = sendATCommand(new ATCommand("IR", ByteUtils.intToByteArray(rate))); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } checkATCommandResponseIsValid(response); }
Source:
<code>public int read(ByteBuffer dst, long position) throws IOException { <START> int readBytes = sageFileChannel.read(dst, position - fileOffsets[currFileIndex]); <END> if (dst.hasRemaining()) { ensureProperFile(false); if (readBytes == -1) readBytes = 0; readBytes += sageFileChannel.read(dst, position + readBytes - fileOffsets[currFileIndex]); } return readBytes; }</code><technical_language>This missing a call ensureProperFile(false, position) reads argument is absolute position</technical_language>

Target:
public int read(ByteBuffer dst, long position) throws IOException { int readBytes = 0; int count = (int)Math.min(size() - position, (long)dst.remaining()); try { while (count > readBytes) { ensureProperFile(false, position); readBytes += sageFileChannel.read(dst, position + readBytes - fileOffsets[currFileIndex]); } } finally { ensureProperFile(false); } return readBytes; }