auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>@Test public void testDivideWraperPrimitive() throws Exception { final CalciteAssert.AssertThat with = CalciteAssert.that().withSchema("s", CATCHALL); with.query("select \"wrapperLong\" / \"primitiveLong\" as c\n" + " from \"s\".\"everyTypes\" where \"primitiveLong\" <> 0") .planContains( "final Long input_value = current.wrapperLong;") .planContains( "final boolean input_isNull = input_value == null;") .planContains( <START> "return input_isNull ? (Long) null : Long.valueOf(input_isNull ? 0L : input_value / Long.valueOf(current.primitiveLong));") <END> .returns("C=null\n"); }</code><technical_language>Technically speaking check of input_isNull is required in Long.valueOf(input_isNull</technical_language>

Target:
@Test public void testDivideWraperPrimitive() throws Exception { final CalciteAssert.AssertThat with = CalciteAssert.that().withSchema("s", CATCHALL); with.query("select \"wrapperLong\" / \"primitiveLong\" as c\n" + " from \"s\".\"everyTypes\" where \"primitiveLong\" <> 0") .planContains( "final Long input_value = current.wrapperLong;") .planContains( "return input_value == null ? (Long) null : Long.valueOf(input_value.longValue() / current.primitiveLong);") .returns("C=null\n"); }
Source:
<code>public void validatesInMultipleThreads() throws Exception { final int zero = 0; final int ten = 10; final int hundred = 100; final int fifty = 50; final Random rand = new SecureRandom(); final Callable<Void> callable = new Callable<Void>() { @Override public Void call() throws Exception { final int cnt = rand.nextInt(hundred); final XSD xsd = new XSDDocument( StringUtils.join( "<xs:schema ", "xmlns:xs='<LINK_0>' >", "<xs:element name='root'><xs:complexType>", "<xs:sequence>", "<xs:element name='a' type='xs:integer'", " minOccurs='0' maxOccurs='unbounded'/>", "</xs:sequence></xs:complexType></xs:element>", "</xs:schema>" ) ); MatcherAssert.assertThat( xsd.validate( new DOMSource( new XMLDocument( StringUtils.join( "<root>", StringUtils.repeat("<a>hey you</a>", cnt), "</root>" ) ).node() ) ), Matchers.hasSize(cnt << 1) ); return null; } }; final ExecutorService executorService = Executors.newFixedThreadPool(5); <START> for (int count = zero; count < fifty; count = count + 1) { <END> executorService.submit(callable); } executorService.awaitTermination(ten, TimeUnit.SECONDS); executorService.shutdown(); }</code><technical_language>@tmjee create Callable instances ant submit ExecutorService#invokeAll()</technical_language>

Target:
public void validatesInMultipleThreads() throws Exception { final int timeout = 10; final int random = 100; final int loop = 50; final Random rand = new SecureRandom(); final Callable<Void> callable = new Callable<Void>() { @Override public Void call() throws Exception { final int cnt = rand.nextInt(random); final XSD xsd = new XSDDocument( StringUtils.join( "<xs:schema ", "xmlns:xs='<LINK_0>' >", "<xs:element name='root'><xs:complexType>", "<xs:sequence>", "<xs:element name='a' type='xs:integer'", " minOccurs='0' maxOccurs='unbounded'/>", "</xs:sequence></xs:complexType></xs:element>", "</xs:schema>" ) ); MatcherAssert.assertThat( xsd.validate( new DOMSource( new XMLDocument( StringUtils.join( "<root>", StringUtils.repeat("<a>hey you</a>", cnt), "</root>" ) ).node() ) ), Matchers.hasSize(cnt << 1) ); return null; } }; final ExecutorService executorService = Executors.newFixedThreadPool(5); for (int count = 0; count < loop; count = count + 1) { executorService.submit(callable); } executorService.shutdown(); MatcherAssert.assertThat( executorService.awaitTermination(timeout, TimeUnit.SECONDS), Matchers.is(true) ); executorService.shutdownNow(); }
Source:
<code>public CompletableFuture<Acknowledge> sendSlotReport(ResourceID taskManagerResourceId, InstanceID taskManagerRegistrationId, SlotReport slotReport, Time timeout) { final WorkerRegistration<WorkerType> workerTypeWorkerRegistration = taskExecutors.get(taskManagerResourceId); if (workerTypeWorkerRegistration.getInstanceID().equals(taskManagerRegistrationId)) { slotManager.registerTaskManager(workerTypeWorkerRegistration, slotReport); <START> onTaskManagerRegistration(workerTypeWorkerRegistration); <END> return CompletableFuture.completedFuture(Acknowledge.get()); } else { return FutureUtils.completedExceptionally(new ResourceManagerException(String.format("Unknown TaskManager registration id %s.", taskManagerRegistrationId))); } }</code><technical_language>I call onTaskManagerRegistration multiple times if TM decides call sendSlotReport repeatedly</technical_language>

Target:
public CompletableFuture<Acknowledge> sendSlotReport(ResourceID taskManagerResourceId, InstanceID taskManagerRegistrationId, SlotReport slotReport, Time timeout) { final WorkerRegistration<WorkerType> workerTypeWorkerRegistration = taskExecutors.get(taskManagerResourceId); if (workerTypeWorkerRegistration.getInstanceID().equals(taskManagerRegistrationId)) { if (slotManager.registerTaskManager(workerTypeWorkerRegistration, slotReport)) { onTaskManagerRegistration(workerTypeWorkerRegistration); } return CompletableFuture.completedFuture(Acknowledge.get()); } else { return FutureUtils.completedExceptionally(new ResourceManagerException(String.format("Unknown TaskManager registration id %s.", taskManagerRegistrationId))); } }
Source:
<code>public String getFormattedValue(float value, AxisBase axis) { int days = (int) value; int year = determineYear(days); int month = determineMonth(days); String monthName = mMonths[month % mMonths.length]; String yearName = String.valueOf(year); if (chart.getVisibleXRange() > 30 * 6) { return monthName + " " + yearName; } else { int dayOfMonth = determineDayOfMonth(days, month + 12 * (year - 2016)); String appendix = "th"; <START> switch (dayOfMonth) { <END> case 1: appendix = "st"; break; case 2: appendix = "nd"; break; case 3: appendix = "rd"; break; case 21: appendix = "st"; break; case 22: appendix = "nd"; break; case 23: appendix = "rd"; break; case 31: appendix = "st"; break; } return dayOfMonth == 0 ? "" : dayOfMonth + appendix + " " + monthName; } }</code><technical_language>Nice work! Brownie points for thoughtful UX</technical_language>

Target:
public String getFormattedValue(float value, AxisBase axis) { int intValue = (int) value; Date vitalDate = DateUtils.getDateFromString(dates.get(Math.abs(intValue))); DateFormat dateFormat = new SimpleDateFormat("MMM d, ''yy"); return dateFormat.format(vitalDate); }
Source:
<code>public String show(@RequestParam(value = "name", required = true) String name, ModelMap model) { long start = System.currentTimeMillis(); try{ ClusterConfig config = UIUtils.clusterConfig.get(name); <START> StringBuffer builder = new StringBuffer(""); <END> for (String ip:config.getZkServers()){ builder.append(ip).append(","); } builder.substring(0, builder.length() -1); builder.append(":"); builder.append(config.getZkPort()); model.addAttribute("zkServers", builder.toString()); model.addAttribute("clusterName",name); model.addAttribute("requestUri", "/zookeeper/node"); }catch (Exception e){ LOG.error(e.getMessage(), e); UIUtils.addErrorAttribute(model, e); } LOG.info("zookeeper page show cost:{}ms", System.currentTimeMillis() - start); return "zookeeper"; }</code><technical_language>StringBuilder</technical_language>

Target:
public String show(@RequestParam(value = "name", required = true) String name, ModelMap model) { long start = System.currentTimeMillis(); try{ ClusterConfig config = UIUtils.clusterConfig.get(name); StringBuilder builder = new StringBuilder(""); for (String ip:config.getZkServers()){ builder.append(ip).append(","); } builder.deleteCharAt(builder.length() - 1); builder.append(":"); builder.append(config.getZkPort()); model.addAttribute("zkRoot", config.getZkRoot()); model.addAttribute("zkServers", builder.toString()); model.addAttribute("clusterName",name); }catch (Exception e){ LOG.error(e.getMessage(), e); UIUtils.addErrorAttribute(model, e); } LOG.info("zookeeper page show cost:{}ms", System.currentTimeMillis() - start); return "zookeeper"; }
Source:
<code>public boolean commitCursors(final String subscriptionId, final List<SubscriptionCursor> cursors) throws NakadiException, InvalidCursorException { final Subscription subscription = subscriptionRepository.getSubscription(subscriptionId); boolean allCommitted = true; for (final String eventTypeName : subscription.getEventTypes()) { final EventType eventType = eventTypeRepository.findByName(eventTypeName); <START> createSubscriptionInZkIfNeeded(subscription); <END> final List<SubscriptionCursor> eventTypeCursors = cursors.stream() .filter(cursor -> eventTypeName.equals(cursor.getEventType())) .collect(Collectors.toList()); topicRepository.validateCommitCursors(eventType.getTopic(), eventTypeCursors); for (final SubscriptionCursor cursor : eventTypeCursors) { final boolean cursorCommitted = commitCursor(subscriptionId, eventType.getTopic(), cursor); allCommitted = allCommitted && cursorCommitted; } } return allCommitted; }</code><technical_language>is required do for event type in subscription</technical_language>

Target:
public boolean commitCursors(final String subscriptionId, final List<SubscriptionCursor> cursors) throws NakadiException, InvalidCursorException { final Subscription subscription = subscriptionRepository.getSubscription(subscriptionId); createSubscriptionInZkIfNeeded(subscription); boolean allCommitted = true; for (final SubscriptionCursor cursor: cursors) { final EventType eventType = eventTypeRepository.findByName(cursor.getEventType()); topicRepository.validateCommitCursors(eventType.getTopic(), ImmutableList.of(cursor)); final boolean cursorCommitted = commitCursor(subscriptionId, eventType.getTopic(), cursor); allCommitted = allCommitted && cursorCommitted; } return allCommitted; }
Source:
<code>public void addPacketInterceptor(StanzaListener packetInterceptor, StanzaFilter packetFilter) { <START> if (packetInterceptor == null) { <END> throw new NullPointerException("Packet interceptor is null."); } InterceptorWrapper interceptorWrapper = new InterceptorWrapper(packetInterceptor, packetFilter); synchronized (interceptors) { interceptors.put(packetInterceptor, interceptorWrapper); } }</code><technical_language>This simply invoke new method</technical_language>

Target:
public void addPacketInterceptor(StanzaListener packetInterceptor, StanzaFilter packetFilter) { addStanzaInterceptor(packetInterceptor, packetFilter); }
Source:
<code>public int readCallback(String path, ByteBuffer buf, long size, long offset, ByteBuffer fibuf) { try { return read(path, buf, size, offset, FuseFileInfo.wrap(fibuf)); } catch (Exception e) { <START> e.printStackTrace(); <END> return -ErrorCodes.EIO(); } }</code><technical_language>LOG.error("Failed read {}, size {}, offset {}: ", path, size, offset, e)</technical_language>

Target:
public int readCallback(String path, ByteBuffer buf, long size, long offset, ByteBuffer fibuf) { try { return read(path, buf, size, offset, FuseFileInfo.wrap(fibuf)); } catch (Exception e) { LOG.error("Failed to read {}, size {}, offset {}: ", path, size, offset, e); return -ErrorCodes.EIO(); } }
Source:
<code>public Server2ControllerSegmentUploader(Logger segmentLogger, FileUploadDownloadClient fileUploadDownloadClient, String controllerSegmentUploadCommitUrl, String segmentName, int segmentUploadRequestTimeoutMs, ServerMetrics serverMetrics) { _segmentLogger = segmentLogger; _fileUploadDownloadClient = fileUploadDownloadClient; <START> _controllerSegmentUploadCommitUrl = controllerSegmentUploadCommitUrl; <END> _segmentName = segmentName; _segmentUploadRequestTimeoutMs = segmentUploadRequestTimeoutMs; _serverMetrics = serverMetrics; }</code><technical_language>Please parse URI save a member, throw exception if URI parse</technical_language>

Target:
public Server2ControllerSegmentUploader(Logger segmentLogger, FileUploadDownloadClient fileUploadDownloadClient, String controllerSegmentUploadCommitUrl, String segmentName, int segmentUploadRequestTimeoutMs, ServerMetrics serverMetrics) throws URISyntaxException { _segmentLogger = segmentLogger; _fileUploadDownloadClient = fileUploadDownloadClient; _controllerSegmentUploadCommitUrl = new URI(controllerSegmentUploadCommitUrl); _segmentName = segmentName; _segmentUploadRequestTimeoutMs = segmentUploadRequestTimeoutMs; _serverMetrics = serverMetrics; }
Source:
<code>public ServiceBusReceiverAsyncClient buildAsyncClient() { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName, SubQueue.NONE); validateAndThrow(prefetchCount); final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount, sessionId, isRollingSessionReceiver(), maxConcurrentSessions); final UnnamedSessionManager sessionManager; if (CoreUtils.isNullOrEmpty(sessionId)) { sessionManager = new UnnamedSessionManager(entityPath, entityType, <START> connectionProcessor, connectionProcessor.getRetryOptions().getTryTimeout(), tracerProvider, <END> messageSerializer, receiverOptions, maxAutoRenewDuration); } else { sessionManager = new UnnamedSessionManager(entityPath, entityType, connectionProcessor, connectionProcessor.getRetryOptions().getTryTimeout(), tracerProvider, messageSerializer, receiverOptions, maxAutoRenewDuration, sessionId); } return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, maxAutoRenewDuration, sessionManager); }</code><technical_language>passing connectionProcessor connectionProcessor.getRetryOptions().getTryTimeout(). If session manager connection processor, able get retry options anyway. Also, weird retry options in connection processor</technical_language>

Target:
public ServiceBusReceiverAsyncClient buildAsyncClient() { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName, SubQueue.NONE); final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); if (receiveMode == ReceiveMode.RECEIVE_AND_DELETE) { maxAutoLockRenewDuration = Duration.ZERO; } final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount, sessionId, isRollingSessionReceiver(), maxConcurrentSessions, maxAutoLockRenewDuration); final ServiceBusSessionManager sessionManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, receiverOptions); return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager); }
Source:
<code>public void verifyNoFrameworkClassSendToClient() { val request = mock(HttpServletRequest.class); val msg = "test"; val map = CollectionUtils.<String, Throwable>wrap( UnauthorizedAuthenticationException.class.getSimpleName(), new UnauthorizedAuthenticationException(msg) ); <START> ResponseEntity<String> response = RestResourceUtils.createResponseEntityForAuthnFailure( <END> new AuthenticationException(msg, map, new HashMap<>(0)), request, context ); assertTrue(response.getStatusCode().isError()); assertFalse(response.getBody().contains(UnauthorizedAuthenticationException.class.getSimpleName())); }</code><technical_language>suggestion val response = RestResourceUtils.createResponseEntityForAuthnFailure(</technical_language>

Target:
public void verifyNoFrameworkClassSendToClient() { val request = mock(HttpServletRequest.class); val msg = "test"; val map = CollectionUtils.<String, Throwable>wrap( UnauthorizedAuthenticationException.class.getSimpleName(), new UnauthorizedAuthenticationException(msg) ); val response = RestResourceUtils.createResponseEntityForAuthnFailure( new AuthenticationException(msg, map, new HashMap<>(0)), request, context ); assertTrue(response.getStatusCode().isError()); assertFalse(response.getBody().contains(UnauthorizedAuthenticationException.class.getSimpleName())); }
Source:
<code>public BAMMediator createBAMMediator() { BAMMediatorImpl bamMediator = new BAMMediatorImpl(); bamMediator.setInputConnector(createBAMMediatorInputConnector()); bamMediator.setOutputConnector(createBAMMediatorOutputConnector()); bamMediator.setServerProfile("server_profile_name"); bamMediator.setStreamName("stream_name"); <START> bamMediator.setStreamVersion("1.0.0"); <END> return bamMediator; }</code><technical_language>externalize constants</technical_language>

Target:
public BAMMediator createBAMMediator() { BAMMediatorImpl bamMediator = new BAMMediatorImpl(); bamMediator.setInputConnector(createBAMMediatorInputConnector()); bamMediator.setOutputConnector(createBAMMediatorOutputConnector()); return bamMediator; }
Source:
<code>public GetContainerReportResponse getContainerReport( GetContainerReportRequest request) throws YarnException, IOException { ContainerId containerId = request.getContainerId(); if (containerId == null) { <START> throw new ContainerNotFoundException("ContainerId doesn't exist"); <END> } ApplicationAttemptId appAttemptId = containerId.getApplicationAttemptId(); ApplicationId appId = appAttemptId.getApplicationId(); UserGroupInformation callerUGI = getCallerUgi(appId, AuditConstants.GET_CONTAINER_REPORT); RMApp application = verifyUserAccessForRMApp(appId, callerUGI, AuditConstants.GET_CONTAINER_REPORT, ApplicationAccessType.VIEW_APP, false); boolean allowAccess = checkAccess(callerUGI, application.getUser(), ApplicationAccessType.VIEW_APP, application); GetContainerReportResponse response = null; if (allowAccess) { RMAppAttempt appAttempt = application.getAppAttempts().get(appAttemptId); if (appAttempt == null) { throw new ApplicationAttemptNotFoundException( "ApplicationAttempt with id '" + appAttemptId + "' doesn't exist in RM."); } RMContainer rmContainer = this.rmContext.getScheduler().getRMContainer( containerId); if (rmContainer == null) { throw new ContainerNotFoundException("Container with id '" + containerId + "' doesn't exist in RM."); } response = GetContainerReportResponse.newInstance(rmContainer .createContainerReport()); } else { throw new YarnException("User " + callerUGI.getShortUserName() + " does not have privilege to see this application " + appId); } return response; }</code><technical_language>Change exception message "Invalid container id: null"</technical_language>

Target:
public GetContainerReportResponse getContainerReport( GetContainerReportRequest request) throws YarnException, IOException { ContainerId containerId = request.getContainerId(); if (containerId == null) { throw new ContainerNotFoundException("Invalid container id: null"); } ApplicationAttemptId appAttemptId = containerId.getApplicationAttemptId(); ApplicationId appId = appAttemptId.getApplicationId(); UserGroupInformation callerUGI = getCallerUgi(appId, AuditConstants.GET_CONTAINER_REPORT); RMApp application = verifyUserAccessForRMApp(appId, callerUGI, AuditConstants.GET_CONTAINER_REPORT, ApplicationAccessType.VIEW_APP, false); boolean allowAccess = checkAccess(callerUGI, application.getUser(), ApplicationAccessType.VIEW_APP, application); GetContainerReportResponse response = null; if (allowAccess) { RMAppAttempt appAttempt = application.getAppAttempts().get(appAttemptId); if (appAttempt == null) { throw new ApplicationAttemptNotFoundException( "ApplicationAttempt with id '" + appAttemptId + "' doesn't exist in RM."); } RMContainer rmContainer = this.rmContext.getScheduler().getRMContainer( containerId); if (rmContainer == null) { throw new ContainerNotFoundException("Container with id '" + containerId + "' doesn't exist in RM."); } response = GetContainerReportResponse.newInstance(rmContainer .createContainerReport()); } else { throw new YarnException("User " + callerUGI.getShortUserName() + " does not have privilege to see this application " + appId); } return response; }
Source:
<code>public void addFieldViews(Context context, Detail detail, Entity entity) { this.removeAllViews(); addBuffers(context); GridCoordinate[] coordinatesOfEachField = detail.getGridCoordinates(); String[] typesOfEachField = detail.getTemplateForms(); GridStyle[] stylesOfEachField = detail.getGridStyles(); Log.v("TempForms", "Template: " + Arrays.toString(typesOfEachField) + " | Coords: " + Arrays.toString(coordinatesOfEachField) + " | Styles: " + Arrays.toString(stylesOfEachField)); setPaddingIfNotInGridView(); if (tileBeingShownInGridView()) { <START> setBackgroundColor(Color.parseColor("#ffffff")); <END> } mFieldViews = new View[coordinatesOfEachField.length]; for (int i = 0; i < mFieldViews.length; i++) { addFieldView(context, typesOfEachField[i], stylesOfEachField[i], coordinatesOfEachField[i], entity.getFieldString(i), entity.getSortField(i), i); } }</code><technical_language>Color.parseColor("#ffffff") Color.WHITE, right</technical_language>

Target:
public void addFieldViews(Context context, Detail detail, Entity entity) { this.removeAllViews(); addBuffers(context); GridCoordinate[] coordinatesOfEachField = detail.getGridCoordinates(); String[] typesOfEachField = detail.getTemplateForms(); GridStyle[] stylesOfEachField = detail.getGridStyles(); Log.v("TempForms", "Template: " + Arrays.toString(typesOfEachField) + " | Coords: " + Arrays.toString(coordinatesOfEachField) + " | Styles: " + Arrays.toString(stylesOfEachField)); setPaddingIfNotInGridView(); if (tileBeingShownInGridView()) { setBackgroundColor(Color.WHITE); } mFieldViews = new View[coordinatesOfEachField.length]; for (int i = 0; i < mFieldViews.length; i++) { addFieldView(context, typesOfEachField[i], stylesOfEachField[i], coordinatesOfEachField[i], entity.getFieldString(i), entity.getSortField(i), i); } }
Source:
<code>private static void updateOption(VdcOption option) { Map<String, Object> values = _vdcOptionCache.get(option.getoption_name()); <START> if (values != null) { <END> values.put(option.getversion(), GetValue(option)); } else { values = new HashMap<String, Object>(); values.put(option.getversion(), GetValue(option)); _vdcOptionCache.put(option.getoption_name(), values); } }</code><technical_language>I consider rewriting as: if (values == null) { values = new HashMap<String, Object>(); _vdcOptionCache.put(option.getoption_name(), values); } values.put(option.getversion(), GetValue(option));</technical_language>

Target:
private static void updateOption(VdcOption option) { Map<String, Object> values = _vdcOptionCache.get(option.getoption_name()); if (values == null) { values = new HashMap<String, Object>(); _vdcOptionCache.put(option.getoption_name(), values); } values.put(option.getversion(), GetValue(option)); }
Source:
<code>public int setBlockRangeByBounds(EntityPlayer player, String range, BlockPos offset1, BlockPos offset2) { AreaDescriptor descriptor = this.getBlockRange(range); DemonWillHolder holder = WorldDemonWillHandler.getWillHolder(world, getBlockPos()); <START> switch (this.currentRitual.canBlockRangeBeModified(range, descriptor, this, offset1, offset2, holder)) { <END> case 1: descriptor.modifyAreaByBlockPositions(offset1, offset2); return 1; case -1: return -1; case -2: return -2; default: return 0; } }</code><technical_language>pls java int modificationType = currentRitual.canBlockRangeBeModified(...); if (modificationType == 1) descriptor.modifyAreaByBlockPositions(offset1, offset2); return modificationType;</technical_language>

Target:
public EnumReaderBoundaries setBlockRangeByBounds(EntityPlayer player, String range, BlockPos offset1, BlockPos offset2) { AreaDescriptor descriptor = this.getBlockRange(range); DemonWillHolder holder = WorldDemonWillHandler.getWillHolder(world, getBlockPos()); EnumReaderBoundaries modificationType = currentRitual.canBlockRangeBeModified(range, descriptor, this, offset1, offset2, holder); if (modificationType == EnumReaderBoundaries.SUCCESS) descriptor.modifyAreaByBlockPositions(offset1, offset2); return modificationType; }
Source:
<code>public void trackUnitVideoDelete(@NonNull String courseId, @NonNull String unitId) { <START> final FirebaseEvent event = new FirebaseEvent(Events.VIDEOS_UNDO_UNIT_DELETE, Values.VIDEOS_UNDO_UNIT_DELETE); <END> event.putString(Keys.COURSE_ID, courseId); event.putString(Keys.UNIT_ID, unitId); logFirebaseEvent(event.getName(), event.getBundle()); }</code><technical_language>Wrong event name bi is passed here. **VIDEOS_UNIT_DELETE**</technical_language>

Target:
public void trackUnitVideoDelete(@NonNull String courseId, @NonNull String unitId) { final FirebaseEvent event = new FirebaseEvent(Events.VIDEOS_UNIT_DELETE, Values.VIDEOS_UNIT_DELETE); event.putString(Keys.COURSE_ID, courseId); event.putString(Keys.UNIT_ID, unitId); logFirebaseEvent(event.getName(), event.getBundle()); }
Source:
<code>private boolean isKnownCost(PlanNode node) { <START> return !Objects.equals(UNKNOWN_COST, costs.getOrDefault(node.getId(), UNKNOWN_COST)); <END> }</code><technical_language>this is comparing a constant object, need Objects.equals java return !UNKNOWN_COST.equals(costs.getOrDefault(node.getId(), UNKNOWN_COST));</technical_language>

Target:
private boolean isKnownCost(PlanNode node) { return !UNKNOWN_COST.equals(costs.getOrDefault(node.getId(), UNKNOWN_COST)); }
Source:
<code>public void exitNonReserved(SqlBaseParser.NonReservedContext context) { if (!(context.getChild(0) instanceof TerminalNode)) { int rule = ((ParserRuleContext) context.getChild(0)).getRuleIndex(); throw new AssertionError("nonReserved can only contain tokens. Found nested rule: " + ruleNames.get(rule)); } context.getParent().removeLastChild(); Token token = (Token) context.getChild(0).getPayload(); <START> if (token.getText().equalsIgnoreCase("CURRENT_ROLE")) { <END> warningConsumer.accept(new ParsingWarning(format("Reserved word used: %s", token.getText()), token.getLine(), token.getCharPositionInLine())); } if (SqlParserOptions.RESERVED_WORDS_WARNING.contains(token.getText())) { warningConsumer.accept(new ParsingWarning(format("This will soon be made a reserved word: %s", token.getText()), token.getLine(), token.getCharPositionInLine())); } context.getParent().addChild(new CommonToken( new Pair<>(token.getTokenSource(), token.getInputStream()), SqlBaseLexer.IDENTIFIER, token.getChannel(), token.getStartIndex(), token.getStopIndex())); }</code><technical_language>put CURRENT_ROLE in RESERVED_WORDS_WARNING</technical_language>

Target:
public void exitNonReserved(SqlBaseParser.NonReservedContext context) { if (!(context.getChild(0) instanceof TerminalNode)) { int rule = ((ParserRuleContext) context.getChild(0)).getRuleIndex(); throw new AssertionError("nonReserved can only contain tokens. Found nested rule: " + ruleNames.get(rule)); } context.getParent().removeLastChild(); Token token = (Token) context.getChild(0).getPayload(); if (RESERVED_WORDS_WARNING.contains(token.getText().toUpperCase())) { warningConsumer.accept(new ParsingWarning( format("%s should be a reserved word, please use double quote (\"%s\"). This will be made a reserved word in future release.", token.getText(), token.getText()), token.getLine(), token.getCharPositionInLine())); } context.getParent().addChild(new CommonToken( new Pair<>(token.getTokenSource(), token.getInputStream()), SqlBaseLexer.IDENTIFIER, token.getChannel(), token.getStartIndex(), token.getStopIndex())); }
Source:
<code>public void dontRunOnExclusiveSlave() throws Exception { List<MatrixProject> projects = new ArrayList<MatrixProject>(); for (int i = 0; i <= 10; i++) { MatrixProject m = j.createProject(MatrixProject.class); AxisList axes = new AxisList(); axes.add(new TextAxis("p", "only")); m.setAxes(axes); projects.add(m); } <START> TemporaryFolder tf = new TemporaryFolder(); <END> tf.create(); DumbSlave s = new DumbSlave( "big", "this is a big slave", tf.getRoot().getPath(), "20", EXCLUSIVE, "", j.createComputerLauncher(null), RetentionStrategy.NOOP, new ArrayList()); j.jenkins.addNode(s); s.toComputer().connect(false).get(); for (MatrixProject p : projects) { MatrixBuild b = j.assertBuildStatusSuccess(p.scheduleBuild2(2)); assertSame(b.getBuiltOn(), j.jenkins); } }</code><technical_language>This work properly a @Rule field</technical_language>

Target:
public void dontRunOnExclusiveSlave() throws Exception { List<MatrixProject> projects = new ArrayList<MatrixProject>(); for (int i = 0; i <= 10; i++) { MatrixProject m = j.createProject(MatrixProject.class); AxisList axes = new AxisList(); axes.add(new TextAxis("p", "only")); m.setAxes(axes); projects.add(m); } tmp.create(); DumbSlave s = new DumbSlave( "big", "this is a big slave", tmp.getRoot().getPath(), "20", EXCLUSIVE, "", j.createComputerLauncher(null), RetentionStrategy.NOOP, new ArrayList()); j.jenkins.addNode(s); s.toComputer().connect(false).get(); for (MatrixProject p : projects) { MatrixBuild b = j.assertBuildStatusSuccess(p.scheduleBuild2(2)); assertSame(b.getBuiltOn(), j.jenkins); } }
Source:
<code>public void updateModel(OperationContext context, ModelNode model, AttributeDefinition attributeDefinition, ModelNode attribute) throws OperationFailedException { if (attributeDefinition.getType() != ModelType.LIST || !(attributeDefinition instanceof ListAttributeDefinition)) { <START> throw new OperationFailedException("Attribute type is not list"); END> } updateModel(context, model, (ListAttributeDefinition) attributeDefinition, attribute); }</code><technical_language>Needs done this merged. "Attribute '%s' is of type '%s', is type '%s'" sounds pretty reasonable</technical_language>

Target:
public void updateModel(OperationContext context, ModelNode model, AttributeDefinition attributeDefinition, ModelNode attribute) throws OperationFailedException { if (attributeDefinition.getType() != ModelType.LIST || !(attributeDefinition instanceof ListAttributeDefinition)) { throw ControllerLogger.MGMT_OP_LOGGER.attributeIsWrongType(attributeDefinition.getName(), ModelType.LIST,attributeDefinition.getType()); } updateModel(context, model, (ListAttributeDefinition) attributeDefinition, attribute); }
Source:
<code>public void queryIsRequired() { thrown.expect(BeanCreationException.class); thrown.expectMessage("Field error in object 'target' on field 'query': rejected value [null]"); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(Conf.class); <START> context.refresh(); <END> }</code><technical_language>AnnotationConfigApplicationContext is Closeable, close()'d in end, independently of test result. STS barks :smile:</technical_language>

Target:
public void queryIsRequired() { this.thrown.expect(BeanCreationException.class); this.thrown.expectMessage("Field error in object 'target' on field 'query': rejected value [null]"); this.context.register(Conf.class); this.context.refresh(); }
Source:
<code>public void deleteSharedScope(String scopeName, String tenantDomain) throws APIManagementException { if (log.isDebugEnabled()) { log.debug("Deleting shared scope " + scopeName); } Map<String, KeyManagerDto> tenantKeyManagers = KeyManagerHolder.getTenantKeyManagers(tenantDomain); for (Map.Entry<String,KeyManagerDto> keyManagerEntry : tenantKeyManagers.entrySet()){ KeyManager keyManager = keyManagerEntry.getValue().getKeyManager(); if (keyManager != null){ try{ keyManager.deleteScope(scopeName); }catch (APIManagementException e){ log.error("Error while Deleting Shared Scope " + scopeName + " from KeyManager " + <START> keyManagerEntry.getKey(), e); <END> } } } apiMgtDAO.deleteSharedScope(scopeName, tenantDomain); scopesDAO.deleteScope(scopeName, APIUtil.getTenantIdFromTenantDomain(tenantDomain)); }</code><technical_language>here. formatting issues. Shouldnt throw exception</technical_language>

Target:
public void deleteSharedScope(String scopeName, String tenantDomain) throws APIManagementException { if (log.isDebugEnabled()) { log.debug("Deleting shared scope " + scopeName); } Map<String, KeyManagerDto> tenantKeyManagers = KeyManagerHolder.getTenantKeyManagers(tenantDomain); for (Map.Entry<String, KeyManagerDto> keyManagerEntry : tenantKeyManagers.entrySet()) { KeyManager keyManager = keyManagerEntry.getValue().getKeyManager(); if (keyManager != null) { try { keyManager.deleteScope(scopeName); } catch (APIManagementException e) { log.error("Error while Deleting Shared Scope " + scopeName + " from Key Manager " + keyManagerEntry.getKey(), e); } } } apiMgtDAO.deleteSharedScope(scopeName, tenantDomain); deleteScope(scopeName, APIUtil.getTenantIdFromTenantDomain(tenantDomain)); }
Source:
<code>public void writeSelf(File file, long pos) { fLock.readLock().lock(); try (FileOutputStream fos = new FileOutputStream(file, true); FileChannel fc = fos.getChannel();) { fc.position(pos); try (ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeInt(ATTRIB_TREE_MAGIC_NUMBER); List<String[]> list = new ArrayList<>(fAttributeList.size()); String[] prevFullAttribute = null; for (Attribute entry : fAttributeList) { String[] curFullAttribute = entry.getFullAttribute(); String[] curEncodedAttribute = encodeFullAttribute(prevFullAttribute, entry.getFullAttribute()); list.add(curEncodedAttribute); prevFullAttribute = curFullAttribute; } oos.writeObject(list); } } catch (IOException e) { e.printStackTrace(); <START> fLock.readLock().unlock(); <END> } }</code><technical_language>in finally? unlocking all</technical_language>

Target:
public void writeSelf(File file, long pos) { fLock.readLock().lock(); try (FileOutputStream fos = new FileOutputStream(file, true); FileChannel fc = fos.getChannel();) { fc.position(pos); try (ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeInt(ATTRIB_TREE_MAGIC_NUMBER); List<String[]> list = new ArrayList<>(fAttributeList.size()); String[] prevFullAttribute = null; for (Attribute entry : fAttributeList) { String[] curFullAttribute = entry.getFullAttribute(); String[] curEncodedAttribute = encodeFullAttribute(prevFullAttribute, entry.getFullAttribute()); list.add(curEncodedAttribute); prevFullAttribute = curFullAttribute; } oos.writeObject(list); } } catch (IOException e) { e.printStackTrace(); } finally { fLock.readLock().unlock(); } }
Source:
<code>public TableResult executeInternal(List<ModifyOperation> operations) { List<Transformation<?>> transformations = translate(operations); String jobName = extractJobName(operations); Pipeline pipeline = execEnv.createPipeline(transformations, tableConfig, jobName); try { JobClient jobClient = execEnv.executeAsync(pipeline); TableSchema.Builder builder = TableSchema.builder(); Object[] affectedRowCounts = new Long[operations.size()]; for (int i = 0; i < operations.size(); ++i) { <START> String fieldName = "affected_rowcount"; <END> if (operations.size() > 1) { fieldName = fieldName + "_" + i; } builder.field(fieldName, DataTypes.BIGINT()); affectedRowCounts[i] = -1L; } return TableResultImpl.builder() .jobClient(jobClient) .resultKind(ResultKind.SUCCESS_WITH_CONTENT) .tableSchema(builder.build()) .data(Collections.singletonList(Row.of(affectedRowCounts))) .build(); } catch (Exception e) { throw new TableException("Failed to execute sql", e); } }</code><technical_language>target table name column name</technical_language>

Target:
public TableResult executeInternal(List<ModifyOperation> operations) { List<Transformation<?>> transformations = translate(operations); List<String> sinkIdentifierNames = extractSinkIdentifierNames(operations); String jobName = "insert_into_" + String.join(",", sinkIdentifierNames); Pipeline pipeline = execEnv.createPipeline(transformations, tableConfig, jobName); try { JobClient jobClient = execEnv.executeAsync(pipeline); TableSchema.Builder builder = TableSchema.builder(); Object[] affectedRowCounts = new Long[operations.size()]; for (int i = 0; i < operations.size(); ++i) { builder.field(sinkIdentifierNames.get(i), DataTypes.BIGINT()); affectedRowCounts[i] = -1L; } return TableResultImpl.builder() .jobClient(jobClient) .resultKind(ResultKind.SUCCESS_WITH_CONTENT) .tableSchema(builder.build()) .data(Collections.singletonList(Row.of(affectedRowCounts))) .build(); } catch (Exception e) { throw new TableException("Failed to execute sql", e); } }
Source:
<code><START> public HashMap<String, String> getIntellijServicePrincipalDetails(String credFilePath) throws IOException { <END> BufferedReader reader = null; HashMap<String, String> servicePrincipalDetails = new HashMap<>(8); try { reader = new BufferedReader(new FileReader(credFilePath)); String line = reader.readLine(); while (line != null) { String[] split = line.split("="); split[1] = split[1].replace("\\", ""); servicePrincipalDetails.put(split[0], split[1]); line = reader.readLine(); } } finally { if (reader != null) { reader.close(); } } return servicePrincipalDetails; }</code><technical_language>Return a Map<String, String> instead</technical_language>

Target:
public Map<String, String> getIntellijServicePrincipalDetails(String credFilePath) throws IOException { BufferedReader reader = null; HashMap<String, String> servicePrincipalDetails = new HashMap<>(8); try { reader = new BufferedReader(new FileReader(credFilePath)); String line = reader.readLine(); while (line != null) { String[] split = line.split("="); split[1] = split[1].replace("\\", ""); servicePrincipalDetails.put(split[0], split[1]); line = reader.readLine(); } } finally { if (reader != null) { reader.close(); } } return servicePrincipalDetails; }
Source:
<code>public Slice slice(int index, int length) { if ((index == 0) && (length == length())) { return this; } checkIndexLength(index, length); if (length == 0) { return Slices.EMPTY_SLICE; } if (reference == COMPACT) { return new Slice(base, address + index, length, retainedSize, NOT_COMPACT); } <START> else { <END> return new Slice(base, address + index, length, retainedSize, reference); } }</code><technical_language>Nit: else is redundant, remove (thus original line remain unchanged)</technical_language>

Target:
public Slice slice(int index, int length) { if ((index == 0) && (length == length())) { return this; } checkIndexLength(index, length); if (length == 0) { return Slices.EMPTY_SLICE; } if (reference == COMPACT) { return new Slice(base, address + index, length, retainedSize, NOT_COMPACT); } return new Slice(base, address + index, length, retainedSize, reference); }
Source:
<code>private void postProcessModule(Module module) { if (this.plugins != null) { <START> for (Plugin plugin : this.plugins.values()) { <END> if (plugin.supports(module.getType())) { plugin.postProcessModule(module); } } } }</code><technical_language>worth adding a private method like: List<Plugin> getSupportedPlugins(Module); // return plugins empty list (never null) of loops simplified, as: for (Plugin plugin : this.getSupportedPlugins(module)) { plugin.removeModule(module); } need for this either: if (this.plugins != null) ...so of 4 methods 3 lines</technical_language>

Target:
private void postProcessModule(Module module) { for (Plugin plugin : this.getSupportedPlugins(module)) { plugin.postProcessModule(module); } }
Source:
<code>public CommonCourt findOneAndInitialize(int id){ <START> CommonCourt element = entityManager.find(CommonCourt.class, id); <END> if (element != null) { element.accept(new InitializingVisitor()); } return element; }</code><technical_language>name 'element' is one. rememeber is it. commonCourt here. j) right</technical_language>

Target:
public CommonCourt findOneAndInitialize(int id){ CommonCourt commonCourt = entityManager.find(CommonCourt.class, id); if (commonCourt != null) { commonCourt.accept(new InitializingVisitor()); } return commonCourt; }
Source:
<code>public BasicAuthCallBackHandler(String credentials) { if (credentials == null) { log.trace("No credentials were provided with the request"); return; } int space = credentials.indexOf(SPACE); if (space <= 0) { log.trace("Request credentials were malformed; no space present in value for authorization header"); return; } String method = credentials.substring(0, space); if (!BASIC.equalsIgnoreCase(method)) { <START> log.trace("Request credentials did not use basic authentication; ignoring"); <END> return; } credentials = credentials.substring(space + 1); credentials = new String(Base64.getDecoder().decode(credentials), StandardCharsets.UTF_8); int i = credentials.indexOf(COLON); if (i <= 0) { log.trace("Request credentials were malformed; no colon present between username and password"); return; } username = credentials.substring(0, i); password = credentials.substring(i + 1); }</code><technical_language>list method used, in case thought basic? suggestion log.trace("Request credentials authentication, supported; ignoring", BASIC, method);</technical_language>

Target:
public BasicAuthCallBackHandler(String credentials) { if (credentials == null) { log.trace("No credentials were provided with the request"); return; } int space = credentials.indexOf(SPACE); if (space <= 0) { log.trace("Request credentials were malformed; no space present in value for authorization header"); return; } String method = credentials.substring(0, space); if (!BASIC.equalsIgnoreCase(method)) { log.trace("Request credentials used authentication, but only supported; ignoring", method, BASIC); return; } credentials = credentials.substring(space + 1); credentials = new String(Base64.getDecoder().decode(credentials), StandardCharsets.UTF_8); int i = credentials.indexOf(COLON); if (i <= 0) { log.trace("Request credentials were malformed; no colon present between username and password"); return; } username = credentials.substring(0, i); password = credentials.substring(i + 1); }
Source:
<code>public DescribeConfigsResponse getErrorResponse(int throttleTimeMs, Throwable e) { return new DescribeConfigsResponse(new DescribeConfigsResponseData() .setThrottleTimeMs(throttleTimeMs) .setResults(data.resources().stream().map(r -> { <START> Errors error = Errors.forException(e); <END> return new DescribeConfigsResponseData.DescribeConfigsResult().setErrorCode(error.code()) .setErrorMessage(error.message()) .setResourceName(r.resourceName()) .setResourceType(r.resourceType()); }).collect(Collectors.toList()) )); }</code><technical_language>move line top</technical_language>

Target:
public DescribeConfigsResponse getErrorResponse(int throttleTimeMs, Throwable e) { Errors error = Errors.forException(e); return new DescribeConfigsResponse(new DescribeConfigsResponseData() .setThrottleTimeMs(throttleTimeMs) .setResults(data.resources().stream().map(result -> { return new DescribeConfigsResponseData.DescribeConfigsResult().setErrorCode(error.code()) .setErrorMessage(error.message()) .setResourceName(result.resourceName()) .setResourceType(result.resourceType()); }).collect(Collectors.toList()) )); }
Source:
<code>private void decodePosition(JsonObject object, Position position) { Set<Map.Entry<String, JsonValue>> params = object.entrySet(); Iterator<Map.Entry<String, JsonValue>> it = params.iterator(); while (it.hasNext()) { Map.Entry<String, JsonValue> param = it.next(); String paramName = param.getKey(); JsonValue paramValue = param.getValue(); <START> if ("timestamp".equals(paramName)) { <END> Date deviceTime = new Date((long) (((JsonNumber) paramValue).doubleValue() * 1000)); position.setTime(deviceTime); } else if (paramName.startsWith("position.")) { savePosition(paramName, paramValue, position); } else if (paramName.matches("din#[\\d]{1,2}")) { saveInput(paramName, paramValue, position); } else if (paramName.matches("dout#[\\d]{1,2}")) { saveOutput(paramName, paramValue, position); } else if (saveAlarm(paramName, paramValue, position) == 0 && saveParam(paramName, paramValue, position) == 0) { saveUnknownParam(param.getKey(), param.getValue(), position); } } if (position.getLatitude() == 0 && position.getLongitude() == 0) { getLastLocation(position, position.getDeviceTime()); } }</code><technical_language>do need split methods? a big switch for everything</technical_language>

Target:
private void decodePosition(JsonObject object, Position position) { Set<Map.Entry<String, JsonValue>> params = object.entrySet(); Iterator<Map.Entry<String, JsonValue>> it = params.iterator(); while (it.hasNext()) { Map.Entry<String, JsonValue> param = it.next(); String paramName = param.getKey(); JsonValue paramValue = param.getValue(); int index = -1; if (paramName.contains("#")) { String[] parts = paramName.split("#"); paramName = parts[0]; index = Integer.parseInt(parts[1]); } if (!saveParam(paramName, index, paramValue, position)) { saveUnknownParam(param.getKey(), param.getValue(), position); } } if (position.getLatitude() == 0 && position.getLongitude() == 0) { getLastLocation(position, position.getDeviceTime()); } }
Source:
<code>public void logTimings() { info().$("timings "). $("[compiler: ").$(compilerNanos). $(", count: ").$(recordCountNanos). $(", execute: ").$(nanosecondClock.getTicks() - executeStartNanos). <START> $(']').$(); <END> }</code><technical_language>need more here, fd. impossible match timings a query that. logging sql text</technical_language>

Target:
public void logTimings() { info().$("timings "). $("[compiler: ").$(compilerNanos). $(", count: ").$(recordCountNanos). $(", execute: ").$(nanosecondClock.getTicks() - executeStartNanos). $(", q=`").$(query). $("`]").$(); }
Source:
<code>public void run() { AtomicBoolean unfinished = new AtomicBoolean(false); long yieldTimeMs = app.config.deleteyieldtime; try { TimestampType dateTarget = app.getTargetDate(); long rowTarget = app.getTargetRowsPerPartition(); if (app.config.historyseconds > 0) { <START> app.client.callAllPartitionProcedure(new CallBack(unfinished), <END> "DeleteAfterDate", dateTarget, app.config.deletechunksize); } else { app.client.callAllPartitionProcedure(new CallBack(unfinished), "DeleteOldestToTarget", rowTarget, app.config.deletechunksize); } if (unfinished.get()) { yieldTimeMs = 0; } } catch (Exception e) { failureCount.incrementAndGet(); } catch (Throwable t) { t.printStackTrace(); } finally { app.scheduler.schedule(this, yieldTimeMs, TimeUnit.MILLISECONDS); } }</code><technical_language>do wait for callback called? check unfinished below, this proc done. version a latch. async api all? sync API</technical_language>

Target:
public void run() { AtomicBoolean unfinished = new AtomicBoolean(false); long yieldTimeMs = app.config.deleteyieldtime; try { TimestampType dateTarget = app.getTargetDate(); long rowTarget = app.getTargetRowsPerPartition(); ClientResponseWithPartitionKey[] responses; if (app.config.historyseconds > 0) { responses = app.client.callAllPartitionProcedure("DeleteAfterDate", dateTarget, app.config.deletechunksize); } else { responses = app.client.callAllPartitionProcedure("DeleteOldestToTarget", rowTarget, app.config.deletechunksize); } app.updatePartitionCount(responses.length); for (ClientResponseWithPartitionKey resp: responses) { if (resp.getResponse().getStatus() == ClientResponse.SUCCESS) { long tuplesDeleted = resp.getResponse().getResults()[0].asScalarLong(); app.addToDeletedTuples(tuplesDeleted); if (tuplesDeleted >= app.config.deletechunksize) { unfinished.set(true); } } else { failureCount.incrementAndGet(); } } if (unfinished.get()) { yieldTimeMs = 0; } } catch (Exception e) { failureCount.incrementAndGet(); } catch (Throwable t) { t.printStackTrace(); } finally { app.scheduler.schedule(this, yieldTimeMs, TimeUnit.MILLISECONDS); } }