auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private long getCommittedWriteSize(String uploadId) throws IOException { QueryWriteStatusRequest request = QueryWriteStatusRequest.newBuilder().setUploadId(uploadId).build(); SimpleResponseObserver<QueryWriteStatusResponse> responseObserver = new SimpleResponseObserver<>(); Retryer<Boolean> retryer = <START> RetryerBuilder.<Boolean>newBuilder() <END> .retryIfExceptionOfType(IOException.class) .retryIfRuntimeException() .withWaitStrategy(WaitStrategies.exponentialWait(2, 20_000, MILLISECONDS)) .withStopStrategy(StopStrategies.stopAfterAttempt(UPLOAD_RETRIES)) .build(); try { retryer.call( () -> { stub.withDeadlineAfter(QUERY_WRITE_STATUS_TIMEOUT.toMillis(), MILLISECONDS) .queryWriteStatus(request, responseObserver); try { responseObserver.done.await(); if (responseObserver.hasError()) { throw new IOException(responseObserver.getError()); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } return null; }); } catch (Exception e) { throw new IOException( String.format("Failed to get committed write size for '%s'", getResourceString()), e); } return responseObserver.getResponse().getCommittedSize(); }</code><technical_language>If a constant, extract this in a helper method</technical_language>

Target:
private long getCommittedWriteSize(String uploadId) throws IOException { QueryWriteStatusRequest request = QueryWriteStatusRequest.newBuilder().setUploadId(uploadId).build(); SimpleResponseObserver<QueryWriteStatusResponse> responseObserver = new SimpleResponseObserver<>(); Retryer retryer = getRetryer(); try { retryer.call( () -> { stub.withDeadlineAfter(QUERY_WRITE_STATUS_TIMEOUT.toMillis(), MILLISECONDS) .queryWriteStatus(request, responseObserver); responseObserver.done.await(); if (responseObserver.hasError()) { throw new IOException(responseObserver.getError()); } return null; }); } catch (Exception e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } throw new IOException( String.format("Failed to get committed write size for '%s'", getResourceString()), e); } return responseObserver.getResponse().getCommittedSize(); }
Source:
<code>private PhysicalOperation createMergeSource(RemoteSourceNode node, LocalExecutionPlanContext context) { context.setDriverInstanceCount(1); checkArgument(node.getOrderingScheme().isPresent(), "orderingScheme is absent"); OrderingScheme orderingScheme = node.getOrderingScheme().get(); List<Type> types = getSourceOperatorTypes(node, context.getTypes()); Map<Symbol, Integer> sourceLayout = makeLayoutFromOutputSymbols(node.getOutputSymbols()); List<Symbol> orderBySymbols = orderingScheme.getOrderBy(); List<Integer> sortChannels = getChannelsForSymbols(orderBySymbols, sourceLayout); List<SortOrder> sortOrder = orderingScheme.getOrderingList(); ImmutableList<Integer> outputChannels = IntStream.range(0, types.size()).boxed().collect(toImmutableList()); OperatorFactory operatorFactory = new MergeOperatorFactory( context.getNextOperatorId(), <START> node.getId(), <END> exchangeClientSupplier, new PagesSerdeFactory(blockEncodingSerde, isExchangeCompressionEnabled(session)), new SimplePageWithPositionComparator.Factory(), types, outputChannels, sortChannels, sortOrder); return new PhysicalOperation(operatorFactory, makeLayout(node), UNGROUPED_EXECUTION); }</code><technical_language>format this as: IntStream.range(...) .boxed() .collect(...)</technical_language>

Target:
private PhysicalOperation createMergeSource(RemoteSourceNode node, LocalExecutionPlanContext context) { context.setDriverInstanceCount(1); checkArgument(node.getOrderingScheme().isPresent(), "orderingScheme is absent"); OrderingScheme orderingScheme = node.getOrderingScheme().get(); List<Type> types = getSourceOperatorTypes(node, context.getTypes()); Map<Symbol, Integer> sourceLayout = makeLayoutFromOutputSymbols(node.getOutputSymbols()); List<Symbol> orderBySymbols = orderingScheme.getOrderBy(); List<Integer> sortChannels = getChannelsForSymbols(orderBySymbols, sourceLayout); List<SortOrder> sortOrder = orderingScheme.getOrderingList(); ImmutableList<Integer> outputChannels = IntStream.range(0, types.size()) .boxed() .collect(toImmutableList()); OperatorFactory operatorFactory = new MergeOperatorFactory( context.getNextOperatorId(), node.getId(), exchangeClientSupplier, new PagesSerdeFactory(blockEncodingSerde, isExchangeCompressionEnabled(session)), orderingCompiler, types, outputChannels, sortChannels, sortOrder); return new PhysicalOperation(operatorFactory, makeLayout(node), UNGROUPED_EXECUTION); }
Source:
<code>public void init(final T model) { super.init(model); model.getPropertyChangedEvent().addListener((ev, sender, args) -> { NetworkModel <START> model1 = <END> (NetworkModel) sender; String propertyName = args.propertyName; if ("Message".equals(propertyName)) { getView().setMessageLabel(model1.getMessage()); } }); getView().toggleSubnetVisibility(model.getExport().getEntity()); model.getExport().getEntityChangedEvent().addListener((ev, sender, args) -> getView().toggleSubnetVisibility(model.getExport().getEntity())); getView().toggleProfilesVisibility(model.getProfiles().getIsAvailable()); model.getProfiles().getPropertyChangedEvent().addListener((ev, sender, args) -> { if ("IsAvailable".equals(args.propertyName)) { getView().toggleProfilesVisibility(model.getProfiles().getIsAvailable()); } }); getView().getQosButton().setCommand(model.getAddQosCommand()); getView().getQosButton().addClickHandler(event -> getView().getQosButton().getCommand().execute()); getView().addMtuEditor(); }</code><technical_language>Consider renaming this senderModel similar</technical_language>

Target:
public void init(final T model) { super.init(model); model.getPropertyChangedEvent().addListener((ev, sender, args) -> { NetworkModel senderModel = (NetworkModel) sender; String propertyName = args.propertyName; if ("Message".equals(propertyName)) { getView().setMessageLabel(senderModel.getMessage()); } }); getView().toggleSubnetVisibility(model.getExport().getEntity()); model.getExport().getEntityChangedEvent().addListener((ev, sender, args) -> getView().toggleSubnetVisibility(model.getExport().getEntity())); getView().toggleProfilesVisibility(model.getProfiles().getIsAvailable()); model.getProfiles().getPropertyChangedEvent().addListener((ev, sender, args) -> { if ("IsAvailable".equals(args.propertyName)) { getView().toggleProfilesVisibility(model.getProfiles().getIsAvailable()); } }); getView().getQosButton().setCommand(model.getAddQosCommand()); getView().getQosButton().addClickHandler(event -> getView().getQosButton().getCommand().execute()); getView().addMtuEditor(); }
Source:
<code>private void refreshExecutors() { synchronized (activeExecutors) { List<Pair<Executor, Future<String>>> futures = new ArrayList<Pair<Executor, Future<String>>>(); for (final Executor executor : activeExecutors) { Future<String> fetchExecutionInfo = executorInforRefresherService.submit(new Callable<String>() { @Override public String call() throws Exception { return callExecutorForJsonString(executor.getHost(), <START> executor.getPort(), "/serverstatistics", null); <END> } }); futures.add(new Pair<Executor, Future<String>>(executor, fetchExecutionInfo)); } boolean wasSuccess = true; for (Pair<Executor, Future<String>> refreshPair : futures) { Executor executor = refreshPair.getFirst(); try { String jsonString = refreshPair.getSecond().get(5, TimeUnit.SECONDS); executor.setExecutorInfo(ExecutorInfo.fromJSONString(jsonString)); logger.info("Successfully refreshed ExecutorInfo for executor: " + executor); } catch (TimeoutException e) { wasSuccess = false; logger.error("Timed out while waiting for ExecutorInfo refresh" + executor, e); } catch (Exception e) { wasSuccess = false; logger.error("Failed to update ExecutorInfo for executor : " + executor, e); } } if (wasSuccess) { lastSuccessfulExecutorInfoRefresh = System.currentTimeMillis(); } } }</code><technical_language>camel case</technical_language>

Target:
private void refreshExecutors() { synchronized (activeExecutors) { List<Pair<Executor, Future<String>>> futures = new ArrayList<Pair<Executor, Future<String>>>(); for (final Executor executor : activeExecutors) { Future<String> fetchExecutionInfo = executorInforRefresherService.submit(new Callable<String>() { @Override public String call() throws Exception { return callExecutorForJsonString(executor.getHost(), executor.getPort(), "/serverStatistics", null); } }); futures.add(new Pair<Executor, Future<String>>(executor, fetchExecutionInfo)); } boolean wasSuccess = true; for (Pair<Executor, Future<String>> refreshPair : futures) { Executor executor = refreshPair.getFirst(); try { String jsonString = refreshPair.getSecond().get(5, TimeUnit.SECONDS); executor.setExecutorInfo(ExecutorInfo.fromJSONString(jsonString)); logger.info("Successfully refreshed ExecutorInfo for executor: " + executor); } catch (TimeoutException e) { wasSuccess = false; logger.error("Timed out while waiting for ExecutorInfo refresh" + executor, e); } catch (Exception e) { wasSuccess = false; logger.error("Failed to update ExecutorInfo for executor : " + executor, e); } } if (wasSuccess) { lastSuccessfulExecutorInfoRefresh = System.currentTimeMillis(); } } }
Source:
<code>public void initialise() { renderingConfig = config.getRendering(); requiresCondition(() -> (renderingConfig.isVrSupport() && vrProvider != null && vrProvider.isInitialized() )); leftEye = requiresFBO(new FBOConfig(LEFT_EYE_FBO, FULL_SCALE, FBO.Type.DEFAULT).useDepthBuffer(),displayResolutionDependentFBOs); rightEye = requiresFBO(new FBOConfig(RIGHT_EYE_FBO,FULL_SCALE, FBO.Type.DEFAULT).useDepthBuffer(),displayResolutionDependentFBOs); <START> if (this.vrProvider != null) { <END> logger.info("Left eye FBOID:" + Integer.toString(leftEye.fboId)); logger.info("Right eye FBOID:" + Integer.toString(leftEye.fboId)); logger.info("OpenVR init done."); vrProvider.texType[0].handle = leftEye.colorBufferTextureId; vrProvider.texType[0].eColorSpace = JOpenVRLibrary.EColorSpace.EColorSpace_ColorSpace_Gamma; vrProvider.texType[0].eType = JOpenVRLibrary.EGraphicsAPIConvention.EGraphicsAPIConvention_API_OpenGL; vrProvider.texType[0].write(); vrProvider.texType[1].handle = rightEye.colorBufferTextureId; vrProvider.texType[1].eColorSpace = JOpenVRLibrary.EColorSpace.EColorSpace_ColorSpace_Gamma; vrProvider.texType[1].eType = JOpenVRLibrary.EGraphicsAPIConvention.EGraphicsAPIConvention_API_OpenGL; vrProvider.texType[1].write(); } addDesiredStateChange(new EnableMaterial("engine:prog.defaultTextured")); }</code><technical_language>In circumstances vrProvider is null</technical_language>

Target:
public void initialise() { renderingConfig = config.getRendering(); requiresCondition(() -> (renderingConfig.isVrSupport() && vrProvider.isInitialized() )); leftEye = requiresFBO(new FBOConfig(LEFT_EYE_FBO, FULL_SCALE, FBO.Type.DEFAULT).useDepthBuffer(),displayResolutionDependentFBOs); rightEye = requiresFBO(new FBOConfig(RIGHT_EYE_FBO,FULL_SCALE, FBO.Type.DEFAULT).useDepthBuffer(),displayResolutionDependentFBOs); if (vrProvider != null) { vrProvider.texType[0].handle = leftEye.colorBufferTextureId; vrProvider.texType[0].eColorSpace = JOpenVRLibrary.EColorSpace.EColorSpace_ColorSpace_Gamma; vrProvider.texType[0].eType = JOpenVRLibrary.EGraphicsAPIConvention.EGraphicsAPIConvention_API_OpenGL; vrProvider.texType[0].write(); vrProvider.texType[1].handle = rightEye.colorBufferTextureId; vrProvider.texType[1].eColorSpace = JOpenVRLibrary.EColorSpace.EColorSpace_ColorSpace_Gamma; vrProvider.texType[1].eType = JOpenVRLibrary.EGraphicsAPIConvention.EGraphicsAPIConvention_API_OpenGL; vrProvider.texType[1].write(); } addDesiredStateChange(new EnableMaterial("engine:prog.defaultTextured")); }
Source:
<code>private Node convertAzkabanNodeToNode(final AzkabanNode azkabanNode, final String flowName, final File flowFile) { final Node node = new Node(azkabanNode.getName()); node.setType(azkabanNode.getType()); node.setPropsSource(flowFile.getName()); <START> node.setJobSource(flowFile.getName()); <END> if (azkabanNode.getType().equals(Constants.FLOW_NODE_TYPE)) { final String embeddedFlowId = flowName + Constants.PATH_DELIMITER + node.getId(); node.setEmbeddedFlowId(embeddedFlowId); final Flow flow_node = convertAzkabanFlowToFlow((AzkabanFlow) azkabanNode, embeddedFlowId, flowFile); flow_node.setEmbeddedFlow(true); this.flowMap.put(flow_node.getId(), flow_node); } return node; }</code><technical_language>path name</technical_language>

Target:
private Node convertAzkabanNodeToNode(final AzkabanNode azkabanNode, final String flowName, final File flowFile) { final Node node = new Node(azkabanNode.getName()); node.setType(azkabanNode.getType()); node.setPropsSource(flowFile.getName()); node.setJobSource(flowFile.getName()); if (azkabanNode.getType().equals(Constants.FLOW_NODE_TYPE)) { final String embeddedFlowId = flowName + Constants.PATH_DELIMITER + node.getId(); node.setEmbeddedFlowId(embeddedFlowId); final Flow flowNode = convertAzkabanFlowToFlow((AzkabanFlow) azkabanNode, embeddedFlowId, flowFile); flowNode.setEmbeddedFlow(true); this.flowMap.put(flowNode.getId(), flowNode); } return node; }
Source:
<code>public <START> int isMicMuted() <END> { try { return mIm.isMicMuted(); } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } }</code><technical_language>boolean</technical_language>

Target:
public boolean isMicMuted() { try { return mIm.isMicMuted(); } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } }
Source:
<code>protected PGPKeysServerClientHttps(URI uri) throws URISyntaxException, CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { super(uri); <START> if ("hkps://hkps.pool.sks-keyservers.net".equalsIgnoreCase(uri.toString())) { <END> final CertificateFactory cf = CertificateFactory.getInstance("X.509"); final Certificate ca = cf.generateCertificate(getClass().getClassLoader().getResourceAsStream("sks-keyservers.netCA.pem")); final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(keyStore); final SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); this.sslSocketFactory = context.getSocketFactory(); } else { this.sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); } }</code><technical_language>uri.getHost() instead of uri.toString()</technical_language>

Target:
protected PGPKeysServerClientHttps(URI uri) throws URISyntaxException, CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { super(uri); if ("hkps.pool.sks-keyservers.net".equalsIgnoreCase(uri.getHost())) { final CertificateFactory cf = CertificateFactory.getInstance("X.509"); final Certificate ca = cf.generateCertificate(getClass().getClassLoader().getResourceAsStream("sks-keyservers.netCA.pem")); final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(keyStore); final SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); this.sslSocketFactory = context.getSocketFactory(); } else { this.sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); } }
Source:
<code>public static boolean hasChunkedEncodingRequestBug( int[] version, HttpServletRequest request) { <START> return compare(version, v1_7_5) == 0 && isChunked(request); <END> }</code><technical_language>Likewise</technical_language>

Target:
public static boolean hasChunkedEncodingRequestBug( int[] version, HttpServletRequest request) { return false; }
Source:
<code>public static boolean isPartitionsSystemTable(SchemaTableName tableName) { <START> return tableName.getTableName().endsWith(PARTITIONS_TABLE_SUFFIX) && !tableName.getTableName().equals(PARTITIONS_TABLE_SUFFIX); <END> }</code><technical_language>.. && tableName.getTableName().length() > PARTITIONS_TABLE_SUFFIX.length()</technical_language>

Target:
public static boolean isPartitionsSystemTable(SchemaTableName tableName) { return tableName.getTableName().endsWith(PARTITIONS_TABLE_SUFFIX) && tableName.getTableName().length() > PARTITIONS_TABLE_SUFFIX.length(); }
Source:
<code>private static String getFormattedMessage(String message, List<String> arguments){ <START> if (arguments == null) { <END> return message; } else { StringBuffer buffer = new StringBuffer(message); for (int i = 0; i < buffer.length(); ++i) { if (buffer.charAt(i) == '%') { if (buffer.charAt(++i) != '0' && Character.isDigit(buffer.charAt(i)) && !Character.isDigit(buffer.charAt(i + 1))) { int argumentNumber = Character.getNumericValue(buffer.charAt(i)) - 1; String argumentValue = arguments.get(argumentNumber); buffer.replace(i - 1, i + 1, argumentValue); i += argumentValue.length() - 2; } } } return buffer.toString(); } }</code><technical_language>check isEmpty</technical_language>

Target:
private static String getFormattedMessage(String message, List<String> arguments){ if (arguments == null || arguments.isEmpty()) { return message; } else { StringBuffer buffer = new StringBuffer(message); for (int i = 0; i < buffer.length(); ++i) { if (buffer.charAt(i) == '%') { if (buffer.charAt(++i) != '0' && Character.isDigit(buffer.charAt(i)) && !Character.isDigit(buffer.charAt(i + 1))) { int argumentNumber = Character.getNumericValue(buffer.charAt(i)) - 1; String argumentValue = arguments.get(argumentNumber); buffer.replace(i - 1, i + 1, argumentValue); i += argumentValue.length() - 2; } } } return buffer.toString(); } }
Source:
<code>public Obs getObs(Obs obs, String view) { File file = getComplexDataFile(obs); if (ComplexObsHandler.RAW_VIEW.equals(view)) { try { String[] names = obs.getValueComplex().split("\\|"); String originalFilename = names[0]; originalFilename = originalFilename.replace(",", "").replace(" ", ""); FileInputStream mediaStream = new FileInputStream(file); ComplexData complexData = new ComplexData(originalFilename, mediaStream); String mimeType = getMimeTypeFromFile(file); <START> mimeType = mimeType != null ? mimeType : "application/octet-stream"; <END> complexData.setMimeType(mimeType); complexData.setLength(file.length()); obs.setComplexData(complexData); } catch (FileNotFoundException e) { log.error("Trying to create media file stream from " + file.getAbsolutePath(), e); } } else { return null; } return obs; }</code><technical_language>If mimeType is null, default line 64 this change</technical_language>

Target:
public Obs getObs(Obs obs, String view) { File file = getComplexDataFile(obs); if (ComplexObsHandler.RAW_VIEW.equals(view)) { try { String[] names = obs.getValueComplex().split("\\|"); String originalFilename = names[0]; originalFilename = originalFilename.replace(",", "").replace(" ", ""); FileInputStream mediaStream = new FileInputStream(file); ComplexData complexData = new ComplexData(originalFilename, mediaStream); String mimeType = OpenmrsUtil.getFileMimeType(file); complexData.setMimeType(mimeType); complexData.setLength(file.length()); obs.setComplexData(complexData); } catch (FileNotFoundException e) { log.error("Trying to create media file stream from " + file.getAbsolutePath(), e); } } else { return null; } return obs; }
Source:
<code>public void trimMemory(int level) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "trimMemory, level=" + level); } if (level >= android.content.ComponentCallbacks2.TRIM_MEMORY_BACKGROUND) { clearMemory(); <START> } else if (level >= android.content.ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) { <END> trimToSize(getMaxSize() / 2); } else if (level == android.content.ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL) { trimToSize(getMaxSize() / 2); } }</code><technical_language>|| instead of duplicating size logic</technical_language>

Target:
public void trimMemory(int level) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "trimMemory, level=" + level); } if (level >= android.content.ComponentCallbacks2.TRIM_MEMORY_BACKGROUND) { clearMemory(); } else if (level >= android.content.ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN || level == android.content.ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL) { trimToSize(getMaxSize() / 2); } }
Source:
<code>public void run() { <START> Throttle throttle = new SustainedConnectionThrottle(1); <END> try { while (!doneFuture.isDone()) { Optional<SustainedConnection> currentConnection = SustainedConnectionWorker.this.findConnectionToMaintain(); if (currentConnection.isPresent()) { currentConnection.get().refresh(); } else { throttle.increment(); } } } catch (Exception e) { SustainedConnectionWorker.this.totalAborts.incrementAndGet(); SustainedConnectionWorker.log.error("Abort while maintaining sustained connections", e.getMessage()); } }</code><technical_language>do want achieve this throttle? Do want backoff for THROTTLE_PERIOD_MS find a connection sent? I simply a Thread.sleep call. concrete, I recommend instantiate a org.apache.kafka.common.utils.SystemTime class sleep() sleep milliseconds() get current time</technical_language>

Target:
public void run() { try { while (!doneFuture.isDone()) { Optional<SustainedConnection> currentConnection = SustainedConnectionWorker.this.findConnectionToMaintain(); if (currentConnection.isPresent()) { currentConnection.get().refresh(); } else { SustainedConnectionWorker.SYSTEM_TIME.sleep(SustainedConnectionWorker.BACKOFF_PERIOD_MS); } } } catch (Exception e) { SustainedConnectionWorker.this.totalAbortedThreads.incrementAndGet(); SustainedConnectionWorker.log.error("Aborted thread while maintaining sustained connections", e); } }
Source:
<code>public void testInstallStagedApk_VerifyPostReboot() throws Exception { <START> assumeTrue("Current user is not system user", isSystemUser()); <END> int sessionId = retrieveLastSessionId(); assertSessionApplied(sessionId); assertThat(getInstalledVersion(TEST_APP_A)).isEqualTo(1); }</code><technical_language>This method is part of test is executed device. Actual tests host/StagedInstallTest.java class, test executes a sequence of device methods. Suppressing part of a test a source of flakes, instead consider suppressing host side test suite</technical_language>

Target:
public void testInstallStagedApk_VerifyPostReboot() throws Exception { assumeSystemUser(); int sessionId = retrieveLastSessionId(); assertSessionApplied(sessionId); assertThat(getInstalledVersion(TEST_APP_A)).isEqualTo(1); }
Source:
<code>public void testList() { for (Vault vault : api().listVaults()) { assertNotNull(vault.name()); VaultProperties props = vault.properties(); <START> assertNotNull(props); <END> } }</code><technical_language>If properties nullable is need check this. Deserialization fail</technical_language>

Target:
public void testList() { for (Vault vault : api().listVaults()) { assertTrue(!vault.name().isEmpty()); } }
Source:
<code>private static void validateKafkaConfig(List<ImportConfigurationType> configs) { if (configs.isEmpty()) { return; } HashMap<String, HashSet<String>> groupidToTopics = new HashMap<>(); for (ImportConfigurationType config : configs) { String groupid = ""; HashSet<String> topics = new HashSet<>(); for (PropertyType pt : config.getProperty()) { if (pt.getName().equals("topics")) { topics.addAll(Arrays.asList(pt.getValue().split("\\s*,\\s*"))); } else if (pt.getName().equals("groupid")) { groupid = pt.getValue(); } } if (groupidToTopics.containsKey(groupid)) { HashSet<String> union = new HashSet<>(groupidToTopics.get(groupid)); union.addAll(topics); if (union.size() == topics.size() + groupidToTopics.get(groupid).size()) { groupidToTopics.put(groupid, union); } else { <START> VoltDB.crashLocalVoltDB("Two kafka configurations cannot have the same topic and groupid"); <END> } } else { groupidToTopics.put(groupid, topics); } } }</code><technical_language>Dont crash... Users do update deployment bad groupid configuration crash</technical_language>

Target:
private static void validateKafkaConfig(List<ImportConfigurationType> configs) { if (configs.isEmpty()) { return; } HashMap<String, HashSet<String>> groupidToTopics = new HashMap<>(); for (ImportConfigurationType config : configs) { String groupid = ""; HashSet<String> topics = new HashSet<>(); for (PropertyType pt : config.getProperty()) { if (pt.getName().equals("topics")) { topics.addAll(Arrays.asList(pt.getValue().split("\\s*,\\s*"))); } else if (pt.getName().equals("groupid")) { groupid = pt.getValue(); } } if (groupidToTopics.containsKey(groupid)) { HashSet<String> union = new HashSet<>(groupidToTopics.get(groupid)); union.addAll(topics); if (union.size() == (topics.size() + groupidToTopics.get(groupid).size())) { groupidToTopics.put(groupid, union); } else { throw new RuntimeException("Invalid import configuration. Two Kafka entries have the same groupid and topic."); } } else { groupidToTopics.put(groupid, topics); } } }
Source:
<code>public void setUniverse(int universe) { if (universe < 1) { this.universe = 1; logger.warn("coercing universe number to allowed minimum of 1"); } else if (universe > 63999) { this.universe = 63999; <START> logger.warn("coercing universe number to allowes maximum of 63999"); <END> } else { this.universe = universe; } rawPacket[113] = (byte) (this.universe / 256); rawPacket[114] = (byte) (this.universe % 256); String senderName = new String("openHAB DMX <" + String.format("%05d", this.universe) + ">"); byte[] senderNameBytes = senderName.getBytes(StandardCharsets.UTF_8); for (int i = 0; i < senderName.length(); i++) { rawPacket[44 + i] = senderNameBytes[i]; } broadcastNode = new E131Node(new String( "239.255." + String.format("%d", rawPacket[113]) + "." + String.format("%d", rawPacket[114]))); logger.debug("set packet universe to {}", this.universe); }</code><technical_language>*allowed</technical_language>

Target:
public void setUniverse(int universe) { if (universe < 1) { this.universe = 1; logger.warn("coercing universe number to allowed minimum of 1"); } else if (universe > 63999) { this.universe = 63999; logger.warn("coercing universe number to allowed maximum of 63999"); } else { this.universe = universe; } rawPacket[113] = (byte) (this.universe / 256); rawPacket[114] = (byte) (this.universe % 256); String senderName = new String("openHAB DMX <" + String.format("%05d", this.universe) + ">"); byte[] senderNameBytes = senderName.getBytes(StandardCharsets.UTF_8); for (int i = 0; i < senderName.length(); i++) { rawPacket[44 + i] = senderNameBytes[i]; } broadcastNode = new E131Node(new String( "239.255." + String.format("%d", rawPacket[113]) + "." + String.format("%d", rawPacket[114]))); logger.debug("set packet universe to {}", this.universe); }
Source:
<code>public WebClient() { super(BrowserVersion.FIREFOX_38); setPageCreator(HudsonPageCreator.INSTANCE); clients.add(this); setAjaxController(new AjaxController() { <START> private static final long serialVersionUID = -5844060943564822678L; <END> public boolean processSynchron(HtmlPage page, WebRequest settings, boolean async) { return false; } }); setCssErrorHandler(new ErrorHandler() { final ErrorHandler defaultHandler = new DefaultCssErrorHandler(); public void warning(CSSParseException exception) throws CSSException { if (!ignore(exception)) defaultHandler.warning(exception); } public void error(CSSParseException exception) throws CSSException { if (!ignore(exception)) defaultHandler.error(exception); } public void fatalError(CSSParseException exception) throws CSSException { if (!ignore(exception)) defaultHandler.fatalError(exception); } private boolean ignore(CSSParseException e) { String uri = e.getURI(); return uri.contains("/yui/") || uri.contains("/css/style.css") || uri.contains("/css/responsive-grid.css"); } }); getJavaScriptEngine().getContextFactory().addListener(new ContextFactory.Listener() { public void contextCreated(Context cx) { if (cx.getDebugger() == null) cx.setDebugger(jsDebugger, null); } public void contextReleased(Context cx) { } }); }</code><technical_language>serial</technical_language>

Target:
public WebClient() { super(BrowserVersion.FIREFOX_38); setPageCreator(HudsonPageCreator.INSTANCE); clients.add(this); setAjaxController(new AjaxController() { private static final long serialVersionUID = -76034615893907856L; public boolean processSynchron(HtmlPage page, WebRequest settings, boolean async) { return false; } }); setCssErrorHandler(new ErrorHandler() { final ErrorHandler defaultHandler = new DefaultCssErrorHandler(); public void warning(CSSParseException exception) throws CSSException { if (!ignore(exception)) defaultHandler.warning(exception); } public void error(CSSParseException exception) throws CSSException { if (!ignore(exception)) defaultHandler.error(exception); } public void fatalError(CSSParseException exception) throws CSSException { if (!ignore(exception)) defaultHandler.fatalError(exception); } private boolean ignore(CSSParseException e) { String uri = e.getURI(); return uri.contains("/yui/") || uri.contains("/css/style.css") || uri.contains("/css/responsive-grid.css"); } }); getJavaScriptEngine().getContextFactory().addListener(new ContextFactory.Listener() { public void contextCreated(Context cx) { if (cx.getDebugger() == null) cx.setDebugger(jsDebugger, null); } public void contextReleased(Context cx) { } }); }
Source:
<code>public int hashCode() { int result = (int) (_networkId ^ (_networkId >>> 32)); result = 31 * result + (_networkDomainUuid != null ? _networkDomainUuid.hashCode() : 0); result = 31 * result + (_networkUuid != null ? _networkUuid.hashCode() : 0); result = 31 * result + (_networkName != null ? _networkName.hashCode() : 0); result = 31 * result + (_vpcOrSubnetUuid != null ? _vpcOrSubnetUuid.hashCode() : 0); result = 31 * result + (_isL2Network ? 1 : 0); result = 31 * result + (_isL3Network ? 1 : 0); result = 31 * result + (_isVpc ? 1 : 0); result = 31 * result + (_isShared ? 1 : 0); result = 31 * result + (_domainTemplateName != null ? _domainTemplateName.hashCode() : 0); result = 31 * result + (_isFirewallServiceSupported ? 1 : 0); result = 31 * result + (_dnsServers != null ? _dnsServers.hashCode() : 0); result = 31 * result + (_ingressFirewallRules != null ? _ingressFirewallRules.hashCode() : 0); result = 31 * result + (_egressFirewallRules != null ? _egressFirewallRules.hashCode() : 0); result = 31 * result + (_acsFipUuid != null ? _acsFipUuid.hashCode() : 0); result = 31 * result + (_egressDefaultPolicy ? 1 : 0); return result; <START> } <END></code><technical_language>Please implement toString() provide debugging state information for debugging purposes</technical_language>

Target:
public int hashCode() { int result = super.hashCode(); result = 31 * result + (int) (_networkId ^ (_networkId >>> 32)); result = 31 * result + (_networkDomainUuid != null ? _networkDomainUuid.hashCode() : 0); result = 31 * result + (_networkUuid != null ? _networkUuid.hashCode() : 0); result = 31 * result + (_networkName != null ? _networkName.hashCode() : 0); result = 31 * result + (_vpcOrSubnetUuid != null ? _vpcOrSubnetUuid.hashCode() : 0); result = 31 * result + (_isL2Network ? 1 : 0); result = 31 * result + (_isL3Network ? 1 : 0); result = 31 * result + (_isVpc ? 1 : 0); result = 31 * result + (_isShared ? 1 : 0); result = 31 * result + (_domainTemplateName != null ? _domainTemplateName.hashCode() : 0); result = 31 * result + (_isFirewallServiceSupported ? 1 : 0); result = 31 * result + (_dnsServers != null ? _dnsServers.hashCode() : 0); result = 31 * result + (_ingressFirewallRules != null ? _ingressFirewallRules.hashCode() : 0); result = 31 * result + (_egressFirewallRules != null ? _egressFirewallRules.hashCode() : 0); result = 31 * result + (_acsFipUuid != null ? _acsFipUuid.hashCode() : 0); result = 31 * result + (_egressDefaultPolicy ? 1 : 0); return result; }
Source:
<code>protected EditableConfiguration transform(Configuration value) { try { EditableConfiguration val = this.getValue(); if (val != null) { val.close(); <START> }; <END> return new EditableConfiguration( value, valueOrEmptyCollection(configServer.iocs()), valueOrEmptyCollection(configServer.componentDetails()), valueOrEmptyCollection(configServer.pvs())); } catch (RuntimeException e) { LoggerUtils.logErrorWithStackTrace(LOG, e.getMessage(), e); throw e; } }</code><technical_language>suggestion }</technical_language>

Target:
protected EditableConfiguration transform(Configuration value) { try { EditableConfiguration val = this.getValue(); if (val != null) { val.close(); } return new EditableConfiguration( value, valueOrEmptyCollection(configServer.iocs()), valueOrEmptyCollection(configServer.componentDetails()), valueOrEmptyCollection(configServer.pvs())); } catch (RuntimeException e) { LoggerUtils.logErrorWithStackTrace(LOG, e.getMessage(), e); throw e; } }
Source:
<code>public void setCustomAttribute(String attributeName, String attributeValue) { <START> requireCustomAttributesEnabled("setCustomAttribute"); <END> requireNotNullOrEmpty(attributeName, "attributeName must not be null or empty"); synchronized (customAttributes) { customAttributes.put(attributeName, attributeValue); } }</code><technical_language>need check in set\* methods custom attribute name clash a common attribute name prevent users producing invalid XML. Throw IllegalArgumentException if so</technical_language>

Target:
public void setCustomAttribute(String attributeName, String attributeValue) { requireCustomAttributesEnabled(); requireNotNullOrEmpty(attributeName, "attributeName must not be null or empty"); failIfRegistered(attributeName); requireCustomAttributes(); customAttributes.put(attributeName, attributeValue); }
Source:
<code><START> private HashSet<NativeType> getTypes(TypeDefinition typeDefinition){ <END> HashSet<NativeType> choiceTypes = new HashSet<>(); if (typeDefinition instanceof TypeChoiceDefinition){ choiceTypes = getTypes(((TypeChoiceDefinition) typeDefinition).left()); HashSet<NativeType> right = getTypes(((TypeChoiceDefinition) typeDefinition).right()); if (right!=null){ choiceTypes.addAll(right); } } else if (typeDefinition instanceof TypeDefinitionLink){ return getTypes(((TypeDefinitionLink) typeDefinition).linkedType()); } else if (typeDefinition instanceof TypeInlineDefinition){ choiceTypes.add(((TypeInlineDefinition) typeDefinition).nativeType()); } return choiceTypes; }</code><technical_language>return type Set<NativeType>, expose implementation details</technical_language>

Target:
private Set<NativeType> getTypes(TypeDefinition typeDefinition){ Set<NativeType> choiceTypes = new HashSet<>(); if (typeDefinition instanceof TypeChoiceDefinition){ choiceTypes = getTypes(((TypeChoiceDefinition) typeDefinition).left()); Set<NativeType> right = getTypes(((TypeChoiceDefinition) typeDefinition).right()); if (right!=null){ choiceTypes.addAll(right); } } else if (typeDefinition instanceof TypeDefinitionLink){ return getTypes(((TypeDefinitionLink) typeDefinition).linkedType()); } else if (typeDefinition instanceof TypeInlineDefinition){ choiceTypes.add(((TypeInlineDefinition) typeDefinition).nativeType()); } return choiceTypes; }
Source:
<code>private boolean addToAssignmentRecord(AssignableReplica replica, Map<String, Set<String>> currentAssignments) { String resourceName = replica.getResourceName(); if (currentAssignments.containsKey(resourceName)) { return currentAssignments.get(resourceName).add(replica.getPartitionName()); } else { Set<String> replicaSet = new HashSet<>(); replicaSet.add(replica.getPartitionName()); currentAssignments.put(resourceName, replicaSet); return true; <START> } <END> }</code><technical_language>this function simplify computeIfAbsent? java return currentAssignments.computeIfAbsent(replica.getResourceName(), -> new HashSet<>()) .add(replica.getPartitionName());</technical_language>

Target:
private boolean addToAssignmentRecord(AssignableReplica replica, Map<String, Set<String>> currentAssignments) { return currentAssignments.computeIfAbsent(replica.getResourceName(), k -> new HashSet<>()) .add(replica.getPartitionName()); }
Source:
<code>public XYChartConsumer(List<XYSeriesConsumer> series, @Nullable IConsumerAggregator xAggregator, @Nullable IConsumerAggregator yAggregator) { <START> fSeries = series; <END> fXAggregator = xAggregator; fYAggregator = yAggregator; }</code><technical_language>store list directly, ImmutableList.copyOf(series)</technical_language>

Target:
public XYChartConsumer(List<XYSeriesConsumer> series, @Nullable IConsumerAggregator xAggregator, @Nullable IConsumerAggregator yAggregator) { fSeries = ImmutableList.copyOf(series); fXAggregator = xAggregator; fYAggregator = yAggregator; }
Source:
<code>public void testWikiExample() { final CacheManager cacheManager = newCacheManagerBuilder() .withCache("preConfigured", newCacheConfigurationBuilder().buildConfig(Long.class, String.class)) .build(); final Cache<Long, String> preConfigured = cacheManager.getCache("preConfigured", Long.class, String.class); final Cache<Long, String> myCache = cacheManager.createCache("myCache", newCacheConfigurationBuilder().buildConfig(Long.class, String.class)); myCache.put(1L, "da one!"); final String value = myCache.get(1L); cacheManager.removeCache("preConfigured"); final StandaloneCache<Long, String> standaloneCache = newCacheBuilder(Long.class, String.class, LoggerFactory.getLogger(Ehcache.class + "-" + "GettingStarted")) .build(); standaloneCache.init(); cacheManager.close(); standaloneCache.close(); PersistentCacheManager persistentCacheManager = newCacheManagerBuilder() <START> .with(persistence(System.getProperty("javaio.tmp.dir"))) END> .build(); persistentCacheManager.close(); }</code><technical_language>meant "java.io.tmpdir"</technical_language>

Target:
public void testWikiExample() { final CacheManager cacheManager = newCacheManagerBuilder() .withCache("preConfigured", newCacheConfigurationBuilder().buildConfig(Long.class, String.class)) .build(); final Cache<Long, String> preConfigured = cacheManager.getCache("preConfigured", Long.class, String.class); final Cache<Long, String> myCache = cacheManager.createCache("myCache", newCacheConfigurationBuilder().buildConfig(Long.class, String.class)); myCache.put(1L, "da one!"); final String value = myCache.get(1L); cacheManager.removeCache("preConfigured"); final StandaloneCache<Long, String> standaloneCache = newCacheBuilder(Long.class, String.class, LoggerFactory.getLogger(Ehcache.class + "-" + "GettingStarted")) .build(); standaloneCache.init(); cacheManager.close(); standaloneCache.close(); PersistentCacheManager persistentCacheManager = newCacheManagerBuilder() .with(persistence(System.getProperty("java.io.tmpdir") + "/myData")) .build(); persistentCacheManager.close(); }
Source:
<code>public DlmsConnection connect(final DlmsDevice device, final DlmsMessageListener dlmsMessageListener) throws TechnicalException, FunctionalException { this.checkDevice(device); this.checkIpAddress(device); try { return this.createConnection(device, dlmsMessageListener); } catch (final UnknownHostException e) { LOGGER.warn("The IP address is not found: {}", device.getIpAddress(), e); throw new TechnicalException(ComponentType.PROTOCOL_DLMS, "The IP address is not found: " + device.getIpAddress()); } catch (final IOException e) { if (device.hasNewSecurityKey()) { this.recoverKeyProcessInitiator.initiate(device.getDeviceIdentification(), device.getIpAddress()); } final String errorMessage = String.format("Error creating connection for %s with IP adress: %s and with device port: %d", device.getDeviceIdentification(), device.getIpAddress(), device.getPort()); LOGGER.error(errorMessage); throw new FunctionalException(FunctionalExceptionType.CONNECTION_ERROR, ComponentType.PROTOCOL_DLMS, e); } catch (final EncrypterException e) { LOGGER.error("decryption on security keys went wrong for device: {}", device.getDeviceIdentification(), e); <START> throw new FunctionalException(FunctionalExceptionType.INVALID_KEY_FORMAT, ComponentType.PROTOCOL_DLMS, e); <END> } }</code><technical_language>Hmm is INVALID_KEY_FORMAT in another scenario !</technical_language>

Target:
public DlmsConnection connect(final DlmsDevice device, final DlmsMessageListener dlmsMessageListener) throws TechnicalException, FunctionalException { this.checkDevice(device); this.checkIpAddress(device); try { return this.createConnection(device, dlmsMessageListener); } catch (final UnknownHostException e) { LOGGER.warn("The IP address is not found: {}", device.getIpAddress(), e); throw new TechnicalException(ComponentType.PROTOCOL_DLMS, "The IP address is not found: " + device.getIpAddress()); } catch (final IOException e) { if (device.hasNewSecurityKey()) { this.recoverKeyProcessInitiator.initiate(device.getDeviceIdentification(), device.getIpAddress()); } final String errorMessage = String.format("Error creating connection for %s with IP adress: %s and with device port: %d", device.getDeviceIdentification(), device.getIpAddress(), device.getPort()); LOGGER.error(errorMessage); throw new FunctionalException(FunctionalExceptionType.CONNECTION_ERROR, ComponentType.PROTOCOL_DLMS, e); } catch (final EncrypterException e) { LOGGER.error("decryption on security keys went wrong for device: {}", device.getDeviceIdentification(), e); throw new FunctionalException(FunctionalExceptionType.INVALID_DLMS_KEY_FORMAT, ComponentType.PROTOCOL_DLMS, e); } }
Source:
<code>private <V> ELEMENT_ASSERT buildAssert(V value, String description, Class<?> clazz) { try { Constructor<?>[] declaredConstructors = assertClass.getDeclaredConstructors(); for (int i = 0; i < declaredConstructors.length; i++) { Constructor<?> constructor = declaredConstructors[i]; if (constructor.getParameterTypes().length == 1 && constructor.getParameterTypes()[0].isAssignableFrom(clazz)) { @SuppressWarnings("unchecked") ELEMENT_ASSERT newAssert = (ELEMENT_ASSERT) constructor.newInstance(value); return newAssert.as(description); } } throw new RuntimeException("Fail to find a constructor matching " + value + " class to build the expected Assert class"); } catch (Exception e) { <START> throw new RuntimeException("Fail to build an assert object with " + value + ": " + e.getMessage()); <END> } }</code><technical_language>I guess more helpful add exception instead of message? (e.g. new RuntimeException("Failed build assert object " + value, e))</technical_language>

Target:
private <V> ELEMENT_ASSERT buildAssert(V value, String description, Class<?> clazz) { try { Constructor<?>[] declaredConstructors = assertClass.getDeclaredConstructors(); for (int i = 0; i < declaredConstructors.length; i++) { Constructor<?> constructor = declaredConstructors[i]; if (constructor.getParameterTypes().length == 1 && constructor.getParameterTypes()[0].isAssignableFrom(clazz)) { @SuppressWarnings("unchecked") ELEMENT_ASSERT newAssert = (ELEMENT_ASSERT) constructor.newInstance(value); return newAssert.as(description); } } throw new RuntimeException("Fail to find a constructor matching " + value + " class to build the expected Assert class"); } catch (Exception e) { throw new RuntimeException("Fail to build an assert object with " + value + ": " + e.getMessage(), e); } }
Source:
<code>public String sendEvalSubmissionConfirmationEmail(String userId, Long evaluationId) { String to = null; Boolean sendConfirmation = (Boolean) settings.get(EvalSettings.ENABLE_SUBMISSION_CONFIRMATION_EMAIL); if (sendConfirmation) { EvalEvaluation eval = getEvaluationOrFail(evaluationId); String from = getFromEmailOrFail(eval); EvalEmailTemplate emailTemplate = getEmailTemplateOrFail(EvalConstants.EMAIL_TEMPLATE_SUBMITTED, evaluationId); if (emailTemplate != null) { String subject = emailTemplate.getSubject(); <START> if (!StringUtils.isNotBlank(subject)) { <END> subject = rb.getString("submission.confirmation.email.title"); } String message = emailTemplate.getMessage(); if (!StringUtils.isNotBlank(message)) { message = rb.getString("submission.confirmation.email.message"); } EvalEmailMessage em = makeEmailMessage(message, subject, eval, null); String[] emailAddresses = sendUsersEmails(from, new String[]{userId}, em.subject, em.message); if (emailAddresses.length > 0){ LOG.info("Sent Submission Confirmation email to " + userId + ". (attempted to send to "+emailAddresses.length+")"); commonLogic.registerEntityEvent(EVENT_EMAIL_SUBMISSION, EvalEvaluation.class, eval.getId().toString()); } } } return to; }</code><technical_language>Mea culpa original code here, this more concisely if (StringUtils.isBlank(subject)) { for message</technical_language>

Target:
public String sendEvalSubmissionConfirmationEmail(String userId, Long evaluationId) { String to = null; Boolean sendConfirmation = (Boolean) settings.get(EvalSettings.ENABLE_SUBMISSION_CONFIRMATION_EMAIL); if (sendConfirmation) { EvalEvaluation eval = getEvaluationOrFail(evaluationId); String from = getFromEmailOrFail(eval); EvalEmailTemplate emailTemplate = getEmailTemplateOrFail(EvalConstants.EMAIL_TEMPLATE_SUBMITTED, evaluationId); if (emailTemplate != null) { String subject = emailTemplate.getSubject(); if (StringUtils.isBlank(subject)) { subject = rb.getString("submission.confirmation.email.title"); } String message = emailTemplate.getMessage(); if (StringUtils.isBlank(message)) { message = rb.getString("submission.confirmation.email.message"); } EvalEmailMessage em = makeEmailMessage(message, subject, eval, null); String[] emailAddresses = sendUsersEmails(from, new String[]{userId}, em.subject, em.message); if (emailAddresses.length > 0){ LOG.info("Sent Submission Confirmation email to " + userId + ". (attempted to send to "+emailAddresses.length+")"); commonLogic.registerEntityEvent(EVENT_EMAIL_SUBMISSION, EvalEvaluation.class, eval.getId().toString()); } } } return to; }