auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static SrlBankProblem extractBankProblem(final DBObject dbObject, final String problemBankId, final boolean isAdmin) { final SrlBankProblem.Builder exactProblem = SrlBankProblem.newBuilder(); exactProblem.setId(problemBankId); exactProblem.setQuestionText((String) dbObject.get(QUESTION_TEXT)); exactProblem.setImage((String) dbObject.get(IMAGE)); if (isAdmin) { exactProblem.setSolutionId((String) dbObject.get(SOLUTION_ID)); } exactProblem.setCourseTopic((String) dbObject.get(COURSE_TOPIC)); exactProblem.setSubTopic((String) dbObject.get(SUB_TOPIC)); exactProblem.setSource((String) dbObject.get(SOURCE)); exactProblem.setQuestionType(Util.QuestionType.valueOf((Integer) dbObject.get(QUESTION_TYPE))); try { <START> exactProblem.setBaseSketch(Commands.SrlUpdateList.parseFrom((byte[]) dbObject.get(BASESKETCH))); <END> } catch (InvalidProtocolBufferException e) { e.printStackTrace(); } exactProblem.addAllOtherKeywords((ArrayList) dbObject.get(KEYWORDS)); final SrlPermission.Builder permissions = SrlPermission.newBuilder(); if (isAdmin) { permissions.addAllAdminPermission((ArrayList) dbObject.get(ADMIN)); permissions.addAllUserPermission((ArrayList) dbObject.get(USERS)); exactProblem.setAccessPermission(permissions.build()); } if (dbObject.get(SCRIPT) != null) { exactProblem.setScript((String) dbObject.get(SCRIPT)); } return exactProblem.build(); }</code><technical_language>check for null parsing. (that dont cast a null object)</technical_language>

Target:
private static SrlBankProblem extractBankProblem(final DBObject dbObject, final String problemBankId, final boolean isAdmin) { final SrlBankProblem.Builder exactProblem = SrlBankProblem.newBuilder(); exactProblem.setId(problemBankId); exactProblem.setQuestionText((String) dbObject.get(QUESTION_TEXT)); exactProblem.setImage((String) dbObject.get(IMAGE)); if (isAdmin) { exactProblem.setSolutionId((String) dbObject.get(SOLUTION_ID)); } exactProblem.setCourseTopic((String) dbObject.get(COURSE_TOPIC)); exactProblem.setSubTopic((String) dbObject.get(SUB_TOPIC)); exactProblem.setSource((String) dbObject.get(SOURCE)); exactProblem.setQuestionType(Util.QuestionType.valueOf((Integer) dbObject.get(QUESTION_TYPE))); try { if (dbObject.get(BASE_SKETCH) != null) { exactProblem.setBaseSketch(Commands.SrlUpdateList.parseFrom((byte[]) dbObject.get(BASE_SKETCH))); } } catch (InvalidProtocolBufferException e) { e.printStackTrace(); } exactProblem.addAllOtherKeywords((ArrayList) dbObject.get(KEYWORDS)); final SrlPermission.Builder permissions = SrlPermission.newBuilder(); if (isAdmin) { permissions.addAllAdminPermission((ArrayList) dbObject.get(ADMIN)); permissions.addAllUserPermission((ArrayList) dbObject.get(USERS)); exactProblem.setAccessPermission(permissions.build()); } if (dbObject.get(SCRIPT) != null) { exactProblem.setScript((String) dbObject.get(SCRIPT)); } return exactProblem.build(); }
Source:
<code>private String getGeneratedSetResponseForCodes(int minResponseCode, String minResponseType, String responseSectionString) { return "\nvar response501json = {\n" + "\"code\" : 501," + "\n\"description\" : " + "\"Not Implemented\"\n" + "}\n\n" + "var responseCode = mc.getProperty('query.param.responseCode');\n\n" + responseSectionString + " if (responseCode == null) {\n\n" + " mc.setProperty('HTTP_SC', \"" + minResponseCode + "\");\n" + " mc.setProperty('CONTENT_TYPE', 'application/" + minResponseType + "');\n" + " mc.setPayload" + minResponseType.toUpperCase() + "(response" + minResponseCode + minResponseType + ");\n\n" + <START> "} else " + "{\n\n" + <END> " mc.setProperty('CONTENT_TYPE', 'application/json');\n" + " mc.setPayloadJSON(response501json);\n\n" + "}"; }</code><technical_language>suggestion "} else {\n\n" +</technical_language>

Target:
private String getGeneratedSetResponseForCodes(int minResponseCode, String minResponseType, String responseSectionString) { return "\nvar response501json = {\n" + "\"code\" : 501," + "\n\"description\" : " + "\"Not Implemented\"\n" + "}\n\n" + "var responseCode = mc.getProperty('query.param.responseCode');\n\n" + responseSectionString + " if (responseCode == null) {\n\n" + " mc.setProperty('HTTP_SC', \"" + minResponseCode + "\");\n" + " mc.setProperty('CONTENT_TYPE', 'application/" + minResponseType + "');\n" + " mc.setPayload" + minResponseType.toUpperCase() + "(response" + minResponseCode + minResponseType + ");\n\n" + "} else {\n\n" + " mc.setProperty('CONTENT_TYPE', 'application/json');\n" + " mc.setPayloadJSON(response501json);\n\n" + "}"; }
Source:
<code>private void applyRecoveredUpdates() throws IOException, IndexEntryConflictException { if ( log.isDebugEnabled() ) { log.debug( "Applying recovered updates: " + recoveredNodeIds ); } monitor.applyingRecoveredData( recoveredNodeIds ); if ( !recoveredNodeIds.isEmpty() ) { try ( IndexUpdaterMap updaterMap = indexMapRef.createIndexUpdaterMap( IndexUpdateMode.RECOVERY ) ) { for ( IndexUpdater updater : updaterMap ) { updater.remove( recoveredNodeIds ); } Iterator<NodeUpdates> updates = recoveredNodeUpdatesIterator(); Iterator<IndexEntryUpdate<LabelSchemaDescriptor>> indexEntryUpdates = Iterators.flatMap( nodeUpdates -> convertToIndexUpdates( nodeUpdates ).iterator(), updates ); while ( indexEntryUpdates.hasNext() ) { IndexEntryUpdate<LabelSchemaDescriptor> indexUpdate = indexEntryUpdates.next(); monitor.applyingRecoveredUpdate( indexUpdate ); IndexUpdater updater = updaterMap.getUpdater( indexUpdate.indexKey().schema() ); if ( updater != null ) { updater.process( indexUpdate ); <START> } <END> } monitor.recoveredUpdatesApplied(); } } recoveredNodeIds.clear(); }</code><technical_language>This code is in apply( Iterable<IndexEntryUpdate<LabelSchemaDescriptor>> updates, IndexUpdateMode updateMode ). extract it? IndexUpdater updater = updaterMap.getUpdater( indexUpdate.indexKey().schema() ); if ( updater != null ) { updater.process( indexUpdate ); }</technical_language>

Target:
private void applyRecoveredUpdates() throws IOException, IndexEntryConflictException { if ( log.isDebugEnabled() ) { log.debug( "Applying recovered updates: " + recoveredNodeIds ); } monitor.applyingRecoveredData( recoveredNodeIds ); if ( !recoveredNodeIds.isEmpty() ) { try ( IndexUpdaterMap updaterMap = indexMapRef.createIndexUpdaterMap( IndexUpdateMode.RECOVERY ) ) { for ( IndexUpdater updater : updaterMap ) { updater.remove( recoveredNodeIds ); } Iterator<NodeUpdates> updates = recoveredNodeUpdatesIterator(); Iterator<IndexEntryUpdate<LabelSchemaDescriptor>> indexEntryUpdates = Iterators.flatMap( nodeUpdates -> convertToIndexUpdates( nodeUpdates ).iterator(), updates ); while ( indexEntryUpdates.hasNext() ) { IndexEntryUpdate<LabelSchemaDescriptor> indexUpdate = indexEntryUpdates.next(); monitor.applyingRecoveredUpdate( indexUpdate ); processUpdate( updaterMap, indexUpdate ); } monitor.recoveredUpdatesApplied(); } } recoveredNodeIds.clear(); }
Source:
<code>public Order saveRevisedOrder(Order revisedOrder) throws APIException { <START> <END> Order previousOrder = revisedOrder.getPreviousOrder(); if (previousOrder == null) { throw new APIException("Previous order cannot be null"); } if (OrderUtil.isOrderActive(previousOrder, null)) { markAsRevised(previousOrder, new Date()); } else { throw new APIException("Cannot revise an inactive order."); } return saveOrderInternal(revisedOrder); }</code><technical_language>need revisedOrder correct action of REVISE</technical_language>

Target:
public Order saveRevisedOrder(Order revisedOrder) throws APIException { if (!Order.Action.REVISE.equals(revisedOrder.getAction())) { throw new APIException("Action has to be 'REVISE'"); } Order previousOrder = revisedOrder.getPreviousOrder(); if (previousOrder == null) { throw new APIException("Previous order cannot be null"); } if (Order.Action.DISCONTINUE.equals(previousOrder.getAction())) { throw new APIException("Cannot revise a discontinued order"); } if (OrderUtil.isOrderActive(previousOrder, null)) { markAsDiscontinued(previousOrder, new Date()); } else { throw new APIException("Cannot revise an inactive order."); } return saveOrderInternal(revisedOrder); }
Source:
<code>private void showMultiSelectOfflineStateChangeSnackbar(List<ReadingListPage> pages, boolean offline) { String message = pages.size() == 1 ? String.format(singularOfflineStateChangeString(offline), pages.get(0).title()) <START> : String.format(pluralOfflineStateChangeString(offline), pages.size()); <END> }</code><technical_language>snackbar? :)</technical_language>

Target:
private void showMultiSelectOfflineStateChangeSnackbar(List<ReadingListPage> pages, boolean offline) { String message = offline ? getQuantityString(R.plurals.reading_list_article_offline_message, pages.size()) : getQuantityString(R.plurals.reading_list_article_not_offline_message, pages.size()); FeedbackUtil.showMessage(getActivity(), message); }
Source:
<code>private boolean isInPowerSaveMode() { PowerManager powerManager = (PowerManager) requireActivity().getSystemService(Context.POWER_SERVICE); <START> if (powerManager != null) { return powerManager.isPowerSaveMode(); } else { return false; } <END> }</code><technical_language>is simpler this way, think? return (powerManager != null) && powerManager.isPowerSaveMode();</technical_language>

Target:
private boolean isInPowerSaveMode() { PowerManager powerManager = (PowerManager) requireActivity().getSystemService(Context.POWER_SERVICE); return (powerManager != null) && powerManager.isPowerSaveMode(); }
Source:
<code>public void setEnableSmallFileFeatures(final boolean on) { enableSmallFileFeatures = on; if (enableSmallFileFeatures) { syntaxHighlighting.setValue(getValue().isSyntaxHighlighting()); } else { syntaxHighlighting.setValue(false); } NodeList<OptionElement> options = context.getElement().<SelectElement>cast().getOptions(); for (int i = 0; i < options.getLength(); i++) { OptionElement currOption = options.getItem(i); if (Short.valueOf(currOption.getValue()) == AccountDiffPreference.WHOLE_FILE_CONTEXT) { if (enableSmallFileFeatures) { currOption.setDisabled(false); } else { currOption.setDisabled(true); <START> if (AccountDiffPreference.CONTEXT_CHOICES[context.getSelectedIndex()] == AccountDiffPreference.WHOLE_FILE_CONTEXT) { for (int j = 0; i < AccountDiffPreference.CONTEXT_CHOICES.length; j++) { if (AccountDiffPreference.CONTEXT_CHOICES[j] == PatchScreen.LARGE_FILE_CONTEXT) { context.setSelectedIndex(j); break; } } } <END> } } } toggleEnabledStatus(save.isEnabled()); }</code><technical_language>is this for loop</technical_language>

Target:
public void setEnableSmallFileFeatures(final boolean on) { enableSmallFileFeatures = on; if (enableSmallFileFeatures) { syntaxHighlighting.setValue(getValue().isSyntaxHighlighting()); } else { syntaxHighlighting.setValue(false); } NodeList<OptionElement> options = context.getElement().<SelectElement>cast().getOptions(); for (int i = 0; i < options.getLength(); i++) { OptionElement currOption = options.getItem(i); if (Short.parseShort(currOption.getValue()) == AccountDiffPreference.WHOLE_FILE_CONTEXT) { if (enableSmallFileFeatures) { currOption.setDisabled(false); } else { currOption.setDisabled(true); if (context.getSelectedIndex() > -1 && AccountDiffPreference.CONTEXT_CHOICES[context.getSelectedIndex()] == AccountDiffPreference.WHOLE_FILE_CONTEXT) { for (int j = 0; i < AccountDiffPreference.CONTEXT_CHOICES.length; j++) { if (AccountDiffPreference.CONTEXT_CHOICES[j] == PatchScreen.LARGE_FILE_CONTEXT) { context.setSelectedIndex(j); break; } } } } break; } } toggleEnabledStatus(save.isEnabled()); }
Source:
<code>public void cancel(Handler<AsyncResult<Void>> cancelResult) { AsyncResult<Void> operationResult; try { <START> log.info("Cancelling " + consumerTag()); <END> cancelled = true; consumerHandler.getChannel().basicCancel(consumerTag()); operationResult = Future.succeededFuture(); } catch (IOException e) { operationResult = Future.failedFuture(e); } if (cancelResult != null) { cancelResult.handle(operationResult); } handleEnd(); }</code><technical_language>debug info is verbose</technical_language>

Target:
public void cancel(Handler<AsyncResult<Void>> cancelResult) { AsyncResult<Void> operationResult; try { log.debug("Cancelling " + consumerTag()); cancelled = true; consumerHandler.getChannel().basicCancel(consumerTag()); operationResult = Future.succeededFuture(); } catch (IOException e) { operationResult = Future.failedFuture(e); } if (cancelResult != null) { cancelResult.handle(operationResult); } handleEnd(); }
Source:
<code>List getNetworkInterfaces(VM vm){ <START> List<Map> net = new ArrayList(); <END> Map<String, Object> resultMap = new HashMap(); List Inet6List = new ArrayList(); List Inet4List = new ArrayList(); resultMap.put("name", "eth0"); Inet6List.add("fe80::21a:4aff:fe16:2016"); Inet6List.add("2620:52:0:2380:21a:4aff:fe16:2016"); resultMap.put("inet6", Inet6List); Inet4List.add(vm.getIp()); resultMap.put("inet", Inet4List); resultMap.put("hw", vm.getMacAddress()); net.add(resultMap); log.debug("network list is {}", net.toString()); return net; }</code><technical_language>Please generics properly: List<Map<String, Object> nets = new ArrayList<>();</technical_language>

Target:
List<Map<String, Object>> getNetworkInterfaces(VM vm){ Map<String, Object> resultMap = new HashMap(); List<String> inet6Adsreess = new ArrayList<>(); List<String> inet4Adsress = new ArrayList<>(); List<Map<String, Object>> nets = new ArrayList<>(); resultMap.put("name", "eth0"); inet6Adsreess.add("fe80::21a:4aff:fe16:2016"); inet6Adsreess.add("2620:52:0:2380:21a:4aff:fe16:2016"); resultMap.put("inet6", inet6Adsreess); inet4Adsress.add(vm.getIp()); resultMap.put("inet", inet4Adsress); resultMap.put("hw", vm.getMacAddress()); nets.add(resultMap); log.debug("network list is {}", nets.toString()); return nets; }
Source:
<code>public DeleteResult executeAsBlocking() { try { return deleteResolver.performDelete(storIOContentResolver, deleteQuery); <START> } catch (Throwable throwable) { <END> throw new StorIOException(throwable); } }</code><technical_language>Hm, wrap Throwables StorIOException? expect Exceptions. Imagine if poorly written app a lot of memory performing operation in StorIO produces OutOfMemoryError - I want reports problems in issues tracker :smile: catch Exception</technical_language>

Target:
public DeleteResult executeAsBlocking() { try { return deleteResolver.performDelete(storIOContentResolver, deleteQuery); } catch (Exception exception) { throw new StorIOException(exception); } }
Source:
<code>public void checkTransform( int protocol, String localAddress, IpSecAlgorithm crypt, IpSecAlgorithm auth, boolean doUdpEncap, int sendCount, boolean useJavaSockets) throws Exception { StatsChecker.initStatsChecker(); InetAddress local = InetAddress.getByName(localAddress); <START> try (IpSecManager.UdpEncapsulationSocket encapSocket = mISM.openUdpEncapsulationSocket(); <END> IpSecManager.SecurityParameterIndex spi = mISM.allocateSecurityParameterIndex(local)) { IpSecTransform.Builder transformBuilder = new IpSecTransform.Builder(mContext) .setSpi(spi) .setEncryption(crypt) .setAuthentication(auth); if (doUdpEncap) { transformBuilder = transformBuilder.setIpv4Encapsulation(encapSocket, encapSocket.getPort()); } int ipHdrLen = local instanceof Inet6Address ? IP6_HDRLEN : IP4_HDRLEN; int transportHdrLen = 0; int udpEncapLen = doUdpEncap ? UDP_HDRLEN : 0; try (IpSecTransform transform = transformBuilder.buildTransportModeTransform( InetAddress.getByName(localAddress))) { if (protocol == IPPROTO_TCP) { transportHdrLen = TCP_HDRLEN_WITH_OPTIONS; checkTcp(transform, local, sendCount, useJavaSockets); } else if (protocol == IPPROTO_UDP) { transportHdrLen = UDP_HDRLEN; checkUnconnectedUdp(transform, local, sendCount, useJavaSockets); } else { throw new IllegalArgumentException("Invalid protocol"); } } checkStatsChecker( protocol, ipHdrLen, transportHdrLen, udpEncapLen, sendCount, auth.getTruncationLengthBits()); } }</code><technical_language>Wow nicer</technical_language>

Target:
public void checkTransform( int protocol, String localAddress, IpSecAlgorithm crypt, IpSecAlgorithm auth, boolean doUdpEncap, int sendCount, boolean useJavaSockets) throws Exception { StatsChecker.initStatsChecker(); InetAddress local = InetAddress.getByName(localAddress); try (IpSecManager.UdpEncapsulationSocket encapSocket = mISM.openUdpEncapsulationSocket(); IpSecManager.SecurityParameterIndex spi = mISM.allocateSecurityParameterIndex(local)) { IpSecTransform.Builder transformBuilder = new IpSecTransform.Builder(mContext) .setEncryption(crypt) .setAuthentication(auth); if (doUdpEncap) { transformBuilder = transformBuilder.setIpv4Encapsulation(encapSocket, encapSocket.getPort()); } int ipHdrLen = local instanceof Inet6Address ? IP6_HDRLEN : IP4_HDRLEN; int transportHdrLen = 0; int udpEncapLen = doUdpEncap ? UDP_HDRLEN : 0; try (IpSecTransform transform = transformBuilder.buildTransportModeTransform(local, spi)) { if (protocol == IPPROTO_TCP) { transportHdrLen = TCP_HDRLEN_WITH_OPTIONS; checkTcp(transform, local, sendCount, useJavaSockets); } else if (protocol == IPPROTO_UDP) { transportHdrLen = UDP_HDRLEN; checkUnconnectedUdp(transform, local, sendCount, useJavaSockets); } else { throw new IllegalArgumentException("Invalid protocol"); } } checkStatsChecker( protocol, ipHdrLen, transportHdrLen, udpEncapLen, sendCount, auth.getTruncationLengthBits()); } }
Source:
<code>public EurekaArchaius2InstanceConfig(Config config, String namespace) { <START> this(config, "eureka", new DataCenterInfo() { <END> @Override public Name getName() { return Name.MyOwn; } }); }</code><technical_language>namespace instead of "eureka"</technical_language>

Target:
public EurekaArchaius2InstanceConfig(Config config, String namespace) { this(config, namespace, new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }); }
Source:
<code>private String createTempPropFile() throws ManageDomainsResult { File propFile = null; try { propFile = File.createTempFile("engine-config", "properties"); propFile.deleteOnExit(); } catch (IOException ex) { throw new ManageDomainsResult(ManageDomainsResultEnum.ERROR_CREATING_PROPERTIES_FILE, ex.getMessage()); } <START> try (BufferedWriter fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(propFile), Charset.defaultCharset().displayName()))) { <END> fw.write(new StringBuilder() .append(ConfigValues.AdUserName.name()) .append("=\n") .append(ConfigValues.AdUserPassword.name()) .append(".type=CompositePassword\n") .append(ConfigValues.LDAPSecurityAuthentication.name()) .append("=\n") .append(ConfigValues.DomainName.name()) .append("=\n") .append(ConfigValues.AdUserId.name()) .append("=\n") .append(ConfigValues.LdapServers.name()) .append("=\n") .append(ConfigValues.LDAPProviderTypes.name()) .append("=\n") .append(ConfigValues.LDAPServerPort.name()) .append("=\n") .append(ConfigValues.ChangePasswordMsg.name()) .append("=\n") .toString()); fw.flush(); } catch (IOException ex) { throw new ManageDomainsResult(ManageDomainsResultEnum.ERROR_CREATING_PROPERTIES_FILE, ex.getMessage()); } return propFile.getAbsolutePath(); }</code><technical_language>I new BufferedWriter(new FileWriter(propFile)) FileWriter conversion Unicode platform default encoding</technical_language>

Target:
private String createTempPropFile() throws ManageDomainsResult { File propFile = null; try { propFile = File.createTempFile("engine-config", "properties"); propFile.deleteOnExit(); } catch (IOException ex) { throw new ManageDomainsResult(ManageDomainsResultEnum.ERROR_CREATING_PROPERTIES_FILE, ex.getMessage()); } try (FileWriter fw = new FileWriter(propFile)) { fw.write(new StringBuilder() .append(ConfigValues.AdUserName.name()) .append("=\n") .append(ConfigValues.AdUserPassword.name()) .append(".type=CompositePassword\n") .append(ConfigValues.LDAPSecurityAuthentication.name()) .append("=\n") .append(ConfigValues.DomainName.name()) .append("=\n") .append(ConfigValues.AdUserId.name()) .append("=\n") .append(ConfigValues.LdapServers.name()) .append("=\n") .append(ConfigValues.LDAPProviderTypes.name()) .append("=\n") .append(ConfigValues.LDAPServerPort.name()) .append("=\n") .append(ConfigValues.ChangePasswordMsg.name()) .append("=\n") .toString()); fw.flush(); } catch (IOException ex) { throw new ManageDomainsResult(ManageDomainsResultEnum.ERROR_CREATING_PROPERTIES_FILE, ex.getMessage()); } return propFile.getAbsolutePath(); }
Source:
<code>protected void initChannel(Channel ch) throws Exception { final ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new PassportStateOriginHandler()); pipeline.addLast(HTTP_CODEC_HANDLER_NAME, new HttpClientCodec( BaseZuulChannelInitializer.MAX_INITIAL_LINE_LENGTH.get(), BaseZuulChannelInitializer.MAX_HEADER_SIZE.get(), BaseZuulChannelInitializer.MAX_CHUNK_SIZE.get(), false, false )); pipeline.addLast(PassportStateHttpClientHandler.PASSPORT_STATE_HTTP_CLIENT_HANDLER_NAME, new PassportStateHttpClientHandler()); pipeline.addLast("originNettyLogger", nettyLogger); pipeline.addLast(httpMetricsHandler); addMethodBindingHandler(pipeline); pipeline.addLast("httpLifecycle", new HttpClientLifecycleChannelHandler()); pipeline.addLast("connectionPoolHandler", connectionPoolHandler); <START> if(connectionPoolConfig.isSecure()) { <END> pipeline.addFirst("ssl", getClientSslContext().newHandler(ch.alloc())); } }</code><technical_language>For consistency, move this passport http handlers (line 65) change method addLast</technical_language>

Target:
protected void initChannel(Channel ch) throws Exception { final ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new PassportStateOriginHandler()); if(connectionPoolConfig.isSecure()) { pipeline.addLast("ssl", getClientSslContext().newHandler(ch.alloc())); } pipeline.addLast(HTTP_CODEC_HANDLER_NAME, new HttpClientCodec( BaseZuulChannelInitializer.MAX_INITIAL_LINE_LENGTH.get(), BaseZuulChannelInitializer.MAX_HEADER_SIZE.get(), BaseZuulChannelInitializer.MAX_CHUNK_SIZE.get(), false, false )); pipeline.addLast(PassportStateHttpClientHandler.PASSPORT_STATE_HTTP_CLIENT_HANDLER_NAME, new PassportStateHttpClientHandler()); pipeline.addLast("originNettyLogger", nettyLogger); pipeline.addLast(httpMetricsHandler); addMethodBindingHandler(pipeline); pipeline.addLast("httpLifecycle", new HttpClientLifecycleChannelHandler()); pipeline.addLast("connectionPoolHandler", connectionPoolHandler); }
Source:
<code>public static boolean hasStatus(byte[] receivedApdu, byte[] statusCode) throws IOException { byte[] receivedStatus = statusBytes(receivedApdu); <START> return receivedStatus[0] == statusCode[0] && receivedStatus[0] == statusCode[0]; <END> }</code><technical_language>guess is this be: return receivedStatus[0] == statusCode[0] && receivedStatus[1] == statusCode[1];</technical_language>

Target:
public static boolean hasStatus(byte[] receivedApdu, byte[] statusCode) throws IOException { byte[] receivedStatus = statusBytes(receivedApdu); return receivedStatus[0] == statusCode[0] && receivedStatus[1] == statusCode[1]; }
Source:
<code>void handleData(Buffer data) { synchronized (conn) { <START> bytesRead += data.getByteBuf().readableBytes(); <END> if (decoder != null) { try { decoder.offer(new DefaultHttpContent(data.getByteBuf())); } catch (HttpPostRequestDecoder.ErrorDataDecoderException e) { handleException(e); } } if (dataHandler != null) { dataHandler.handle(data); } } }</code><technical_language>data.length()</technical_language>

Target:
void handleData(Buffer data) { synchronized (conn) { bytesRead += data.length(); if (decoder != null) { try { decoder.offer(new DefaultHttpContent(data.getByteBuf())); } catch (HttpPostRequestDecoder.ErrorDataDecoderException e) { handleException(e); } } if (dataHandler != null) { dataHandler.handle(data); } } }
Source:
<code>public IStatus validate(IProject project, String path) { File file = new File(path); if (!file.exists()) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "File not found: " + path); } if (!file.isFile()) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Not a file. It's a directory: " + path); } int confidence = 0; try { if (!TmfTraceUtils.isText(file)) { return new TraceValidationStatus(confidence, Activator.PLUGIN_ID); } } catch (IOException e) { Activator.getInstance().logError("Error validating file: " + path, e); return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "IOException validating file: " + path, e); } try (BufferedRandomAccessFile rafile = new BufferedRandomAccessFile(path, "r")) { int lineCount = 0; int matches = 0; String line = readNextEventString(() -> (char) rafile.read()); while ((line != null) && (lineCount++ < MAX_LINES)) { try { TraceEventField field = TraceEventEvent.parseJson(line); if (field != null) { matches++; } } catch (RuntimeException e) { confidence = Integer.MIN_VALUE; } confidence = MAX_CONFIDENCE * matches / lineCount; line = readNextEventString(() -> (char) rafile.read()); } if (matches == 0) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Most assuredly NOT a <START> traceevevent trace"); <END> } } catch (IOException e) { Activator.getInstance().logError("Error validating file: " + path, e); return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "IOException validating file: " + path, e); } return new TraceValidationStatus(confidence, Activator.PLUGIN_ID); }</code><technical_language>Seriously, overwrote edit this :p *facepalm*</technical_language>

Target:
public IStatus validate(IProject project, String path) { File file = new File(path); if (!file.exists()) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "File not found: " + path); } if (!file.isFile()) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Not a file. It's a directory: " + path); } int confidence = 0; try { if (!TmfTraceUtils.isText(file)) { return new TraceValidationStatus(confidence, Activator.PLUGIN_ID); } } catch (IOException e) { Activator.getInstance().logError("Error validating file: " + path, e); return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "IOException validating file: " + path, e); } try (BufferedRandomAccessFile rafile = new BufferedRandomAccessFile(path, "r")) { int lineCount = 0; int matches = 0; String line = readNextEventString(() -> (char) rafile.read()); while ((line != null) && (lineCount++ < MAX_LINES)) { try { TraceEventField field = TraceEventEvent.parseJson(line); if (field != null) { matches++; } } catch (RuntimeException e) { confidence = Integer.MIN_VALUE; } confidence = MAX_CONFIDENCE * matches / lineCount; line = readNextEventString(() -> (char) rafile.read()); } if (matches == 0) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Most assuredly NOT a traceevent trace"); } } catch (IOException e) { Activator.getInstance().logError("Error validating file: " + path, e); return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "IOException validating file: " + path, e); } return new TraceValidationStatus(confidence, Activator.PLUGIN_ID); }
Source:
<code>public boolean moveCellsUp() { boolean <START> dirty = <END> false; if (moveCellsUpLoop()) { dirty = true; } for (int i = 0; i < GRID_WIDTH; i++) { for (int j = 0; j < (GRID_WIDTH - 1); j++) { int nextJ = j + 1; dirty = combineCells(i, nextJ, i, j, dirty); } } if (moveCellsUpLoop()) { dirty = true; } return dirty; }</code><technical_language>is clear name,</technical_language>

Target:
public boolean moveCellsUp() { boolean actionSuccess = false; if (moveCellsUpLoop()) { actionSuccess = true; } for (int i = 0; i < GRID_WIDTH; i++) { for (int j = 0; j < (GRID_WIDTH - 1); j++) { int nextJ = j + 1; actionSuccess = combineCells(i, nextJ, i, j, actionSuccess); } } if (moveCellsUpLoop()) { actionSuccess = true; } return actionSuccess; }
Source:
<code>public void warning(String message, String sourceName, int line, String lineSource, int lineOffset) { <START> System.out.println("Warning : " + message); <END> }</code><technical_language>Logger instead of System.out.println</technical_language>

Target:
public void warning(String message, String sourceName, int line, String lineSource, int lineOffset) { log.warn("Warning : " + message); }
Source:
<code>private static void waitForStreamState(AmazonKinesisClient kinesisClient, String streamName, @Nullable StreamStatus expectedStatus) { long waitTime = System.currentTimeMillis() + TIMEOUT; while (System.currentTimeMillis() < waitTime) { try { <START> TimeUnit.MILLISECONDS.sleep(SLEEP_INTERVAL); <END> } catch (InterruptedException e) { Thread.currentThread().interrupt(); } StreamStatus streamState = streamExists(kinesisClient, streamName) ? getStreamState(kinesisClient, streamName) : null; if (expectedStatus == streamState) { return; } } throw new IllegalStateException(String.format("Timed out waiting for stream to be in %s state", expectedStatus)); }</code><technical_language>this logic, means sleep for 10 seconds checking status? Also, sleeping 10 seconds awe fully long</technical_language>

Target:
private static void waitForStreamState(AmazonKinesisClient kinesisClient, String streamName, @Nullable StreamStatus expectedStatus) { StreamStatus streamStatus = getStreamState(kinesisClient, streamName); long waitTime = System.currentTimeMillis() + TIMEOUT; while (streamStatus != expectedStatus && waitTime > System.currentTimeMillis()) { Uninterruptibles.sleepUninterruptibly(SLEEP_INTERVAL, TimeUnit.MILLISECONDS); streamStatus = getStreamState(kinesisClient, streamName); } if (!(streamStatus == expectedStatus)) { throw new IllegalStateException(String.format("Timed out waiting for stream to be in %s state", expectedStatus)); } }
Source:
<code>protected Object execute(Object[] data) { <START> if (data[0]!=null & data[0].equals(Boolean.TRUE)) <END> return data[1]; else return data[2]; }</code><technical_language>& is correct need &&. if data[0]==null data[0].equals(Boolean.TRUE) a null pointer</technical_language>

Target:
protected Object execute(Object[] data) { if (data[0]!=null && data[0].equals(Boolean.TRUE)) return data[1]; else return data[2]; }
Source:
<code>private void flush() throws IOException { if(curBufferPos == 0) { return; } try { Collection<ResultSetFeature> features = Arrays.asList(Arrays.copyOfRange(buffer, 0, curBufferPos)); dataStore.insert(features, featureType, st.getConnection()); for (ResultSetFeature cur : features) { final String fid = (String) cur.getUserData().get("fid"); cur.setID(fid); final SimpleFeature orig = (SimpleFeature)cur.getUserData().get("_original_"); if (orig != null) { ((FeatureIdImpl)orig.getIdentifier()).setID(fid); orig.getUserData().putAll(cur.getUserData()); orig.getUserData().remove("_original_"); } final ContentEntry entry = featureSource.getEntry(); final ContentState state = entry.getState(this.tx); <START> state.fireFeatureAdded(featureSource, cur); <END> } } catch (SQLException e) { throw new IOException(e); } finally { curBufferPos = 0; } }</code><technical_language>I uDig pays attention events, @jodygarnett , is a delayed notification of insert (e.g., 100 write calls) issues</technical_language>

Target:
private void flush() throws IOException { if(curBufferPos == 0) { return; } try { Collection<ResultSetFeature> features = Arrays.asList(Arrays.copyOfRange(buffer, 0, curBufferPos)); dataStore.insert(features, featureType, st.getConnection()); for (ResultSetFeature cur : features) { final String fid = (String) cur.getUserData().get("fid"); cur.setID(fid); final SimpleFeature orig =(SimpleFeature)cur.getUserData(). get(ContentFeatureStore.ORIGINAL_FEATURE_KEY); if (orig != null) { ((FeatureIdImpl)orig.getIdentifier()).setID(fid); orig.getUserData().putAll(cur.getUserData()); orig.getUserData().remove(ContentFeatureStore.ORIGINAL_FEATURE_KEY); } final ContentEntry entry = featureSource.getEntry(); final ContentState state = entry.getState(this.tx); state.fireFeatureAdded(featureSource, cur); } } catch (SQLException e) { throw new IOException(e); } finally { curBufferPos = 0; } }
Source:
<code>private boolean hasPersistentPower() { final PackageManager pm = <START> this.getPackageManager(); <END> return (pm != null && (pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK) || pm.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE))); }</code><technical_language>Nit: while it, this "this." is necessary, I think</technical_language>

Target:
private boolean hasPersistentPower() { final PackageManager pm = getPackageManager(); return (pm != null && (pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK) || pm.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE))); }
Source:
<code>public StarlarkList<E> repeat(StarlarkInt n, Mutability mutability) throws EvalException { if (n.signum() <= 0) { return wrap(mutability, EMPTY_ARRAY); } int ni = n.toInt("repeat"); <START> Object[] res = new Object[StarlarkInt.multiplyExact(ni, size, "repeat")]; <END> for (int i = 0; i < ni; i++) { System.arraycopy(elems, 0, res, i * size, size); } return wrap(mutability, res); }</code><technical_language>reject excessive requests time. need new helper functions do that. logic (ported) go.starlark.net: // overeat in small bites // try stop swallowing world in gulp. static final MAX_ALLOC = 1 << 30; ... // Inv: ni > 0, size > 0 int sz = size * ni; if (sz < 0 || sz >= MAX_ALLOC) { // sz < 0 => overflow // print sz. throw Starlark.errorf("excessive repeat (%d * %d elements)", size, ni); }</technical_language>

Target:
public StarlarkList<E> repeat(StarlarkInt n, Mutability mutability) throws EvalException { if (n.signum() <= 0) { return wrap(mutability, EMPTY_ARRAY); } int ni = n.toInt("repeat"); long sz = (long) ni * size; if (sz > MAX_ALLOC) { throw Starlark.errorf("excessive repeat (%d * %d elements)", size, ni); } Object[] res = new Object[(int) sz]; for (int i = 0; i < ni; i++) { System.arraycopy(elems, 0, res, i * size, size); } return wrap(mutability, res); }
Source:
<code>public static String getFacetFileType(DataFile dataFile) { String fileType = dataFile.getContentType(); if (!StringUtil.isEmpty(fileType)) { if (fileType.contains(";")) { fileType = fileType.substring(0, fileType.indexOf(";")); } try { return ResourceBundle.getBundle("MimeTypeFacets").getString(fileType); } catch (MissingResourceException e) { String typeClass = fileType.split("/")[0]; <START> return Character.toUpperCase(typeClass.charAt(0)) + typeClass.substring(1); <END> } } return "Unknown"; }</code><technical_language>confused this capitalization is happening in this "MissingResourceException" catch. I assumed plan adjust case in MimeTypeFacets.properties consistent naming want. Right 50 lowercase entries spaces "networkdata" 1 title case, is "Tabular Data"</technical_language>

Target:
public static String getFacetFileType(DataFile dataFile) { String fileType = dataFile.getContentType(); if (!StringUtil.isEmpty(fileType)) { if (fileType.contains(";")) { fileType = fileType.substring(0, fileType.indexOf(";")); } try { return ResourceBundle.getBundle("MimeTypeFacets").getString(fileType); } catch (MissingResourceException e) { String typeClass = fileType.split("/")[0]; return Character.toUpperCase(typeClass.charAt(0)) + typeClass.substring(1); } } return ResourceBundle.getBundle("MimeTypeFacets").getString("application/octet-stream"); }
Source:
<code>public void testObjectDefinePropertiesQuoted() { String js = LINE_JOINER.join( " var Bar = function(){};", "Bar.prototype.bar = 0;", " var Foo = function() {", " this.bar_ = 'bar';", "};", " Foo.prototype['bar'];", "Object.defineProperties(Foo.prototype, {", <START> " 'bar': {", <END> " configurable: true,", " enumerable: true,", " get: function() { return this.bar_;},", " set: function(value) { this.bar_ = value; }", " }", "});"); String result = LINE_JOINER.join( " var Bar = function(){};", "Bar.prototype.a = 0;", " var Foo = function() {", " this.a = 'bar';", "};", " Foo.prototype['bar'];", "Object.defineProperties(Foo.prototype, {", " 'bar': {", " configurable: true,", " enumerable: true,", " get: function() { return this.a;},", " set: function(value) { this.a = value; }", " }", "});"); test (js, result); }</code><technical_language>If this quoted prop 'a', get a test of new case. squash commits one? Other that, LGTM</technical_language>

Target:
public void testObjectDefinePropertiesQuoted() { String js = LINE_JOINER.join( " var Bar = function(){};", "Bar.prototype.bar = 0;", " var Foo = function() {", " this.bar_ = 'bar';", "};", " Foo.prototype['bar'];", "Object.defineProperties(Foo.prototype, {", " 'a': {", " configurable: true,", " enumerable: true,", " get: function() { return this.bar_;},", " set: function(value) { this.bar_ = value; }", " }", "});"); String result = LINE_JOINER.join( " var Bar = function(){};", "Bar.prototype.b = 0;", " var Foo = function() {", " this.b = 'bar';", "};", " Foo.prototype['bar'];", "Object.defineProperties(Foo.prototype, {", " 'a': {", " configurable: true,", " enumerable: true,", " get: function() { return this.b;},", " set: function(value) { this.b = value; }", " }", "});"); test (js, result); }
Source:
<code>public void testGetResponseInvalidKey() throws Exception { GroupRequest groupRequest = new GroupRequest(); groupRequest.setTable(TestUtils.TEST_TABLE_NAME); groupRequest.setNesting(Arrays.asList("os", "device", "version")); AsyncDataToken dataToken = getQueryExecutor().executeAsync(groupRequest); Thread.sleep(1000); try { resources.client().target(String.format("/foxtrot/v1/async/%s/dummy", dataToken.getAction())).request().get(GroupResponse.class); <START> } catch (WebApplicationException ex) { <END> assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), ex.getResponse().getStatus()); } }</code><technical_language>add fail() catch statement</technical_language>

Target:
public void testGetResponseInvalidKey() throws Exception { GroupRequest groupRequest = new GroupRequest(); groupRequest.setTable(TestUtils.TEST_TABLE_NAME); groupRequest.setNesting(Arrays.asList("os", "device", "version")); AsyncDataToken dataToken = getQueryExecutor().executeAsync(groupRequest); Thread.sleep(1000); GroupResponse response = resources.client().target(String.format("/foxtrot/v1/async/%s/dummy", dataToken.getAction())).request().get(GroupResponse.class); assertNull(response); }
Source:
<code>protected ValidationResult validateConnectionProperties() { if (StringUtils.isEmpty(hostPort) || StringUtils.isBlank(hostPort)) { return new ValidationResult(Result.ERROR, messages.getMessage("error.hostUrl.shouldNotBeEmpty")); } else { try { new URL(hostPort); } catch (MalformedURLException e) { return new ValidationResult(Result.ERROR, messages.getMessage("error.hostUrl.notValid", hostPort)); } } if (StringUtils.isEmpty(userId) || StringUtils.isBlank(userId)) { return new ValidationResult(Result.ERROR, messages.getMessage("error.userId.shouldNotBeEmpty")); <START> } <END> if (StringUtils.isEmpty(userPassword) || StringUtils.isBlank(userPassword)) { return new ValidationResult(Result.ERROR, messages.getMessage("error.password.shouldNotBeEmpty")); } return ValidationResult.OK; }</code><technical_language>empty user allowed. Jira server supports anonymous users</technical_language>

Target:
protected ValidationResult validateConnectionProperties() { if (StringUtils.isEmpty(hostPort) || StringUtils.isBlank(hostPort)) { return new ValidationResult(Result.ERROR, messages.getMessage("error.hostUrl.shouldNotBeEmpty")); } else { try { new URL(hostPort); } catch (MalformedURLException e) { return new ValidationResult(Result.ERROR, messages.getMessage("error.hostUrl.notValid", hostPort)); } } if (userId == null || (!userId.isEmpty() && StringUtils.isBlank(userId))) { return new ValidationResult(Result.ERROR, messages.getMessage("error.userId.shouldNotBeNullOrBlank")); } if (userPassword == null || (!userPassword.isEmpty() && StringUtils.isBlank(userPassword))) { return new ValidationResult(Result.ERROR, messages.getMessage("error.password.shouldNotBeNullOrBlank")); } return ValidationResult.OK; }
Source:
<code>protected void execute(Context context) throws SQLException { <START> if (0 == context.prepareSelect("select count(uuid) from quality_gates where is_built_in = ?") <END> .setBoolean(1, true) .get(row -> row.getLong(1))) { context.prepareUpsert("insert into quality_gates (uuid, name, is_built_in, created_at) values (?,?,?,?)") .setString(1, uuidFactory.create()) .setString(2, SONAR_WAY_QUALITY_GATE) .setBoolean(3, true) .setDate(4, new Date(system2.now())) .execute() .commit(); } }</code><technical_language>I tend prefer code level => if (0 != context.prepareSelect("select count(uuid) quality_gates is_built_in = ?".setBoolean(1, true).get(row -> row.getLong(1))) { return; } context.prepareUpsert("insert quality_gates (uuid, name, is_built_in, created_at) values (?,?,?,?)") ..</technical_language>

Target:
protected void execute(Context context) throws SQLException { Long nbOfBuiltInQualityGates = context.prepareSelect("select count(uuid) from quality_gates where is_built_in = ?") .setBoolean(1, true) .get(row -> row.getLong(1)); if (nbOfBuiltInQualityGates == 0) { final Date now = new Date(system2.now()); context.prepareUpsert("insert into quality_gates (uuid, name, is_built_in, created_at) values (?,?,?,?)") .setString(1, uuidFactory.create()) .setString(2, SONAR_WAY_QUALITY_GATE) .setBoolean(3, true) .setDate(4, now) .execute() .commit(); } }
Source:
<code>private SchemaPlus getRootSchema(@Named(INCOMPLETE_SCHEMA) SchemaPlus rootSchema, InformationSchema informationSchema) { <START> String name = "INFORMATION_SCHEMA"; <END> rootSchema.add(name, informationSchema); return rootSchema; }</code><technical_language>Extract a constant</technical_language>

Target:
private SchemaPlus getRootSchema(@Named(INCOMPLETE_SCHEMA) SchemaPlus rootSchema, InformationSchema informationSchema) { rootSchema.add(INFORMATION_SCHEMA_NAME, informationSchema); return rootSchema; }
Source:
<code>public void setDiskStorageMap(HashMap<Guid, ArrayList<Guid>> value) { diskStorageMap = value; <START> raiseDiskEvent(); <END> }</code><technical_language>raiseDiskEvent sounds exception. else (the name)</technical_language>

Target:
public void setDiskStorageMap(HashMap<Guid, ArrayList<Guid>> value) { diskStorageMap = value; }
Source:
<code>public void onEvent(Event event, Object source, Object data) { XWikiDocument doc = (XWikiDocument) source; List<BaseObject> variantXWikiObjects = doc.getXObjects(VARIANT_CLASS_REFERENCE); if (variantXWikiObjects == null || variantXWikiObjects.isEmpty()) { return; } variantXWikiObjects.stream().filter(Objects::nonNull) .filter(variant -> !StringUtils.isBlank(variant.getStringValue(VARIANT_KEY))) .forEach(variant -> { <START> String cdna = variant.getStringValue(VARIANT_KEY).trim().replaceFirst("^C\\.", "c\\."); <END> variant.setStringValue(VARIANT_KEY, cdna); }); }</code><technical_language>is need for \\ in replacement string, is a regular expression</technical_language>

Target:
public void onEvent(Event event, Object source, Object data) { XWikiDocument doc = (XWikiDocument) source; List<BaseObject> variantXWikiObjects = doc.getXObjects(VARIANT_CLASS_REFERENCE); if (variantXWikiObjects == null || variantXWikiObjects.isEmpty()) { return; } variantXWikiObjects.stream().filter(Objects::nonNull) .filter(variant -> !StringUtils.isBlank(variant.getStringValue(VARIANT_KEY))) .forEach(variant -> { String cdna = variant.getStringValue(VARIANT_KEY).trim().replaceFirst("^C\\.", "c."); variant.setStringValue(VARIANT_KEY, cdna); }); }
Source:
<code>public KafkaMirrorMakerConnector(String connectorName, Properties config, String clusterName) { super(connectorName, config, new KafkaMirrorMakerGroupIdConstructor( Boolean.parseBoolean(config.getProperty(IS_GROUP_ID_HASHING_ENABLED, Boolean.FALSE.toString())), clusterName), clusterName, LOG); _isFlushlessModeEnabled = Boolean.parseBoolean(config.getProperty(IS_FLUSHLESS_MODE_ENABLED, Boolean.FALSE.toString())); _partitionFetchIntervalMs = Long.parseLong(config.getProperty(PARTITION_FETCH_INTERVAL, Long.toString(DEFAULT_PARTITION_FETCH_INTERVAL))); VerifiableProperties verifiableProperties = new VerifiableProperties(config); _consumerProperties = verifiableProperties.getDomainProperties(KafkaBasedConnectorConfig.DOMAIN_KAFKA_CONSUMER); _listenerConsumerFactory = new KafkaConsumerFactoryImpl(); <START> _enablePartitionAssignment = _config.getEnablePartitionAssignment(); <END> _dynamicMetricsManager = DynamicMetricsManager.getInstance(); _shutdown = false; }</code><technical_language>log configs passed connector atleast enablePartitionAssignment config is a critical config decides this connector behaves</technical_language>

Target:
public KafkaMirrorMakerConnector(String connectorName, Properties config, String clusterName) { super(connectorName, config, new KafkaMirrorMakerGroupIdConstructor( Boolean.parseBoolean(config.getProperty(IS_GROUP_ID_HASHING_ENABLED, Boolean.FALSE.toString())), clusterName), clusterName, LOG); _isFlushlessModeEnabled = Boolean.parseBoolean(config.getProperty(IS_FLUSHLESS_MODE_ENABLED, Boolean.FALSE.toString())); _partitionFetchIntervalMs = Long.parseLong(config.getProperty(PARTITION_FETCH_INTERVAL, Long.toString(DEFAULT_PARTITION_FETCH_INTERVAL))); VerifiableProperties verifiableProperties = new VerifiableProperties(config); _consumerProperties = verifiableProperties.getDomainProperties(KafkaBasedConnectorConfig.DOMAIN_KAFKA_CONSUMER); _listenerConsumerFactory = new KafkaConsumerFactoryImpl(); _enablePartitionAssignment = _config.getEnablePartitionAssignment(); _dynamicMetricsManager = DynamicMetricsManager.getInstance(); _shutdown = false; if (_enablePartitionAssignment) { LOG.info("PartitionAssignment enabled for KafkaMirrorConnector"); } }
Source:
<code>public void onEvent(StatusUpdateEvent event, long sequence, boolean endOfBatch) throws Exception { TaskStatus status = event.getStatus(); this.schedulerState.updateTask(status); TaskID taskId = status.getTaskId(); NodeTask task = schedulerState.getTask(taskId); if (task == null) { <START> LOGGER.warn("Task: not found, status: {}", taskId.getValue(), status.getState()); <END> return; } LOGGER.info("Status Update for task: | state: {}", taskId.getValue(), status.getState()); TaskState state = status.getState(); switch (state) { case TASK_STAGING: schedulerState.makeTaskStaging(taskId); break; case TASK_STARTING: schedulerState.makeTaskStaging(taskId); break; case TASK_RUNNING: schedulerState.makeTaskActive(taskId); break; case TASK_FINISHED: offerLifecycleManager.declineOutstandingOffers(task.getHostname()); schedulerState.removeTask(taskId); break; case TASK_FAILED: offerLifecycleManager.declineOutstandingOffers(task.getHostname()); schedulerState.makeTaskPending(taskId); break; case TASK_KILLED: offerLifecycleManager.declineOutstandingOffers(task.getHostname()); schedulerState.removeTask(taskId); break; case TASK_LOST: offerLifecycleManager.declineOutstandingOffers(task.getHostname()); schedulerState.makeTaskPending(taskId); break; default: LOGGER.error("Invalid state: {}", state); break; } }</code><technical_language>do schedulerState.removeTask(taskId)</technical_language>

Target:
public void onEvent(StatusUpdateEvent event, long sequence, boolean endOfBatch) throws Exception { TaskStatus status = event.getStatus(); this.schedulerState.updateTask(status); TaskID taskId = status.getTaskId(); NodeTask task = schedulerState.getTask(taskId); if (task == null) { LOGGER.warn("Task: not found, status: {}", taskId.getValue(), status.getState()); schedulerState.removeTask(taskId); return; } LOGGER.info("Status Update for task: | state: {}", taskId.getValue(), status.getState()); TaskState state = status.getState(); switch (state) { case TASK_STAGING: schedulerState.makeTaskStaging(taskId); break; case TASK_STARTING: schedulerState.makeTaskStaging(taskId); break; case TASK_RUNNING: schedulerState.makeTaskActive(taskId); break; case TASK_FINISHED: offerLifecycleManager.declineOutstandingOffers(task.getHostname()); schedulerState.removeTask(taskId); break; case TASK_FAILED: offerLifecycleManager.declineOutstandingOffers(task.getHostname()); schedulerState.makeTaskPending(taskId); break; case TASK_KILLED: offerLifecycleManager.declineOutstandingOffers(task.getHostname()); schedulerState.removeTask(taskId); break; case TASK_LOST: offerLifecycleManager.declineOutstandingOffers(task.getHostname()); schedulerState.makeTaskPending(taskId); break; default: LOGGER.error("Invalid state: {}", state); break; } }