auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void initializePublisher() { <START> mPublisher = (new Publisher.Builder(this)).build(); <END> mPublisher.setPublisherListener(this); mPublisher.getRenderer().setStyle(BaseVideoRenderer.STYLE_VIDEO_SCALE, BaseVideoRenderer.STYLE_VIDEO_FILL); mPublisherViewContainer.addView(mPublisher.getView()); }</code><technical_language>I remove a pair of parens: mPublisher = new Publisher.Builder(this).build(); (Note group additional parens differently do in Session.Builder line.)</technical_language>

Target:
private void initializePublisher() { mPublisher = new Publisher.Builder(this).build(); mPublisher.setPublisherListener(this); mPublisher.getRenderer().setStyle(BaseVideoRenderer.STYLE_VIDEO_SCALE, BaseVideoRenderer.STYLE_VIDEO_FILL); mPublisherViewContainer.addView(mPublisher.getView()); }
Source:
<code>private synchronized void generateNacksForPendingAcks(String cause) { for (Entry<Listener, SortedMap<Long, PendingConfirm>> entry : this.pendingConfirms.entrySet()) { Listener listener = entry.getKey(); Iterator<Entry<Long, PendingConfirm>> iterator = entry.getValue().entrySet().iterator(); while(iterator.hasNext()) { Entry<Long, PendingConfirm> confirmEntry = iterator.next(); confirmEntry.getValue().setCause(cause); if (logger.isDebugEnabled()) { logger.debug(this.toString() + " PC:Nack:(close):" + confirmEntry.getKey()); } processAck(confirmEntry.getKey(), false, false, false); <START> iterator.remove(); <END> } listener.revoke(this); } if (logger.isDebugEnabled()) { logger.debug("PendingConfirms cleared"); } this.pendingConfirms.clear(); this.listenerForSeq.clear(); this.listeners.clear(); }</code><technical_language>related PR, this remove() is redundant: this.pendingConfirms.clear(); in end of method anyway</technical_language>

Target:
private synchronized void generateNacksForPendingAcks(String cause) { for (Entry<Listener, SortedMap<Long, PendingConfirm>> entry : this.pendingConfirms.entrySet()) { Listener listener = entry.getKey(); for (Entry<Long, PendingConfirm> confirmEntry : entry.getValue().entrySet()) { confirmEntry.getValue().setCause(cause); if (logger.isDebugEnabled()) { logger.debug(this.toString() + " PC:Nack:(close):" + confirmEntry.getKey()); } processAck(confirmEntry.getKey(), false, false, false); } listener.revoke(this); } if (logger.isDebugEnabled()) { logger.debug("PendingConfirms cleared"); } this.pendingConfirms.clear(); this.listenerForSeq.clear(); this.listeners.clear(); }
Source:
<code>public void visitNode(Tree tree) { MethodTree methodTree = (MethodTree) tree; if(methodTree.block() == null) { return; } CFG cfg = CFG.build(methodTree); LiveVariables liveVariables = LiveVariables.analyze(cfg); for (CFG.Block block : cfg.blocks()) { Set<Symbol> out = new HashSet<>(liveVariables.getOut(block)); Set<Tree> assignmentLHS = new HashSet<>(); for (Tree element : Lists.reverse(block.elements())) { Symbol symbol; switch (element.kind()) { case ASSIGNMENT: ExpressionTree lhs = ((AssignmentExpressionTree) element).variable(); if (lhs.is(Tree.Kind.IDENTIFIER)) { symbol = ((IdentifierTree) lhs).symbol(); if (isLocalVariable(symbol) && !out.contains(symbol)) { addIssue(element, "Remove this useless assignment to local variable \"" + symbol.name() + "\"."); } assignmentLHS.add(lhs); out.remove(symbol); } break; <START> case IDENTIFIER: <END> if (!assignmentLHS.contains(element)) { symbol = ((IdentifierTree) element).symbol(); if (isLocalVariable(symbol)) { out.add(symbol); } } break; case VARIABLE: VariableTree localVar = (VariableTree) element; symbol = localVar.symbol(); if(localVar.initializer() != null && !out.contains(symbol)) { addIssue(element, "Remove this useless assignment to local variable \"" + symbol.name() + "\"."); } out.remove(symbol); } } } }</code><technical_language>@benzonico reduce reports @SonarTech? pollutes mailbox push, discussions</technical_language>

Target:
public void visitNode(Tree tree) { MethodTree methodTree = (MethodTree) tree; if (methodTree.block() == null) { return; } if (hasTryFinallyWithLocalVar(methodTree.block(), methodTree.symbol())) { return; } Symbol.MethodSymbol methodSymbol = methodTree.symbol(); CFG cfg = CFG.build(methodTree); LiveVariables liveVariables = LiveVariables.analyze(cfg); for (CFG.Block block : cfg.blocks()) { checkElements(block, liveVariables.getOut(block), methodSymbol); } }
Source:
<code>public static Collection<String> replaceWith(String propertyName, Collection<?> items, String separator, int maxNumberOfPrintedItems) { Validate.isTrue(maxNumberOfPrintedItems >= 1); Validate.isTrue(StringUtils.isNotEmpty(separator)); int maxNumOfItems = Math.min(maxNumberOfPrintedItems, items.size()); List<String> printedItems = new ArrayList<>(maxNumOfItems); String itemPrefix = <START> (separator.equals(DEFAULT_SEPARATOR)) <END> ? "\t" : " "; for (Object item : items) { if (--maxNumOfItems < 0) { break; } printedItems.add(String.format("%s%s", itemPrefix, String.valueOf(item))); } if (items.size() > maxNumberOfPrintedItems) { printedItems.add(String.format("%s...", itemPrefix)); } ArrayList<String> replacements = new ArrayList<>(); replacements.add(createSetVariableString(propertyName, StringUtils.join(printedItems, separator))); replacements.add(createSetVariableString(propertyName + COUNTER_SUFFIX, items.size())); return replacements; }</code><technical_language>surrounding brackets spared</technical_language>

Target:
public static Collection<String> replaceWith(String propertyName, Collection<?> items, String separator, int maxNumberOfPrintedItems) { Validate.isTrue(maxNumberOfPrintedItems >= 1); Validate.isTrue(StringUtils.isNotEmpty(separator)); int maxNumOfItems = Math.min(maxNumberOfPrintedItems, items.size()); List<String> printedItems = new ArrayList<>(maxNumOfItems); String itemPrefix = separator.equals(DEFAULT_SEPARATOR) ? "\t" : " "; for (Object item : items) { if (--maxNumOfItems < 0) { break; } printedItems.add(String.format("%s%s", itemPrefix, String.valueOf(item))); } if (items.size() > maxNumberOfPrintedItems) { printedItems.add(String.format("%s...", itemPrefix)); } ArrayList<String> replacements = new ArrayList<>(); replacements.add(createSetVariableString(propertyName, StringUtils.join(printedItems, separator))); replacements.add(createSetVariableString(propertyName + COUNTER_SUFFIX, items.size())); return replacements; }
Source:
<code>public void onExternalViewChange(List<ExternalView> externalViewList, NotificationContext changeContext) { HelixConstants.ChangeType changeType = changeContext.getChangeType(); if (changeType != null && !_sourceDataTypeMap.containsKey(changeType.getPropertyType())) { logger.warn( "onExternalViewChange called with mismatched change types. Source data types does not contain changed data type: {}", changeType); return; } if (externalViewList != null && externalViewList.size() > 0) { <START> String keyReference = PropertyType.EXTERNALVIEW.name() + "_" + DEFAULT_TYPE; <END> refresh(externalViewList, Collections.emptyList(), changeContext, keyReference); } else { ClusterEventType eventType; if (_sourceDataTypeMap.containsKey(PropertyType.EXTERNALVIEW)) { eventType = ClusterEventType.ExternalViewChange; } else if (_sourceDataTypeMap.containsKey(PropertyType.TARGETEXTERNALVIEW)) { eventType = ClusterEventType.TargetExternalViewChange; } else { logger.warn( "onExternalViewChange called with mismatched change types. Source data types does not contain changed data type: {}", changeType); return; } _routerUpdater.queueEvent(changeContext, eventType, changeType); } }</code><technical_language>This formula is done in a private method. Otherwise, if want replace "_", a headache</technical_language>

Target:
public void onExternalViewChange(List<ExternalView> externalViewList, NotificationContext changeContext) { HelixConstants.ChangeType changeType = changeContext.getChangeType(); if (changeType != null && !_sourceDataTypeMap.containsKey(changeType.getPropertyType())) { logger.warn( "onExternalViewChange called with mismatched change types. Source data types does not contain changed data type: {}", changeType); return; } if (externalViewList != null && externalViewList.size() > 0) { String keyReference = generateReferenceKey(PropertyType.EXTERNALVIEW.name(), DEFAULT_STATE_TYPE); HelixDataAccessor accessor = changeContext.getManager().getHelixDataAccessor(); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); List<InstanceConfig> configList = accessor.getChildValues(keyBuilder.instanceConfigs()); List<LiveInstance> liveInstances = accessor.getChildValues(keyBuilder.liveInstances()); refreshExternalView(externalViewList, configList, liveInstances, keyReference); } else { ClusterEventType eventType; if (_sourceDataTypeMap.containsKey(PropertyType.EXTERNALVIEW)) { eventType = ClusterEventType.ExternalViewChange; } else if (_sourceDataTypeMap.containsKey(PropertyType.TARGETEXTERNALVIEW)) { eventType = ClusterEventType.TargetExternalViewChange; } else { logger.warn( "onExternalViewChange called with mismatched change types. Source data types does not contain changed data type: {}", changeType); return; } _routerUpdater.queueEvent(changeContext, eventType, changeType); } }
Source:
<code>public static Slice stMultiPoint(@SqlType("array(" + GEOMETRY_TYPE_NAME + ")") Block input) { MultiPoint multipoint = new MultiPoint(); for (int i = 0; i < input.getPositionCount(); i++) { if (input.isNull(i)) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Invalid input to ST_MultiPoint: null at index %s", i + 1)); } Slice slice = GEOMETRY.getSlice(input, i); OGCGeometry geometry = deserialize(slice); if (!(geometry instanceof OGCPoint)) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Invalid input to ST_MultiPoint: geometry is not a point: %s at index %s", geometry.geometryType(), i + 1)); } OGCPoint point = (OGCPoint) geometry; if (point.isEmpty()) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Invalid input to ST_MultiPoint: empty point at index %s", i + 1)); } multipoint.add(point.X(), point.Y()); } <START> if (multipoint.getPointCount() < 1) { <END> return null; } return serialize(createFromEsriGeometry(multipoint, null, true)); }</code><technical_language>== 0</technical_language>

Target:
public static Slice stMultiPoint(@SqlType("array(" + GEOMETRY_TYPE_NAME + ")") Block input) { MultiPoint multipoint = new MultiPoint(); for (int i = 0; i < input.getPositionCount(); i++) { if (input.isNull(i)) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Invalid input to ST_MultiPoint: null at index %s", i + 1)); } Slice slice = GEOMETRY.getSlice(input, i); OGCGeometry geometry = deserialize(slice); if (!(geometry instanceof OGCPoint)) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Invalid input to ST_MultiPoint: geometry is not a point: %s at index %s", geometry.geometryType(), i + 1)); } OGCPoint point = (OGCPoint) geometry; if (point.isEmpty()) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Invalid input to ST_MultiPoint: empty point at index %s", i + 1)); } multipoint.add(point.X(), point.Y()); } if (multipoint.getPointCount() == 0) { return null; } return serialize(createFromEsriGeometry(multipoint, null, true)); }
Source:
<code>private AsyncJobStatus buildJobStatus(JobBuilder builder) { if (builder == null) { throw new IllegalArgumentException("job builder is null"); } AsyncJobStatus job = new AsyncJobStatus(); <START> job.setJobClass(builder.getJobClass()); <END> job.setName(builder.getJobName()); job.setGroup(builder.getJobGroup()); job.setOrigin(Util.getHostname()); job.setCorrelationId((String) MDC.get(LoggingFilter.CSID)); Principal principal = this.principalProvider.get(); job.setPrincipal(principal != null ? principal.getName() : null); job.setMaxAttempts(builder.getRetryCount() + 1); job.setJobData(builder.getTaskArguments()); return job; }</code><technical_language>store a job key instead of actual job class flexibility change class name if choose -- storing actual class name bitten Quartz in past. receiving a job message, candlepin Job class some sort of registry / config</technical_language>

Target:
private AsyncJobStatus buildJobStatus(JobBuilder builder) { if (builder == null) { throw new IllegalArgumentException("job builder is null"); } AsyncJobStatus job = new AsyncJobStatus(); job.setJobKey(builder.getJobKey()); job.setName(builder.getJobName()); job.setGroup(builder.getJobGroup()); job.setOrigin(Util.getHostname()); job.setCorrelationId((String) MDC.get(LoggingFilter.CSID)); Principal principal = this.principalProvider.get(); job.setPrincipal(principal != null ? principal.getName() : null); job.setMaxAttempts(builder.getRetryCount() + 1); job.setJobData(builder.getJobArguments()); return job; }
Source:
<code>public void onCompletion(RecordMetadata md, Exception e) { if ( e != null ) { this.failedMessageCount.inc(); this.failedMessageMeter.mark(); LOGGER.error(e.getClass().getSimpleName() + " @ " + position + " -- " + key); LOGGER.error(e.getLocalizedMessage()); if ( e instanceof RecordTooLargeException ) { LOGGER.error("Considering raising max.request.size broker-side."); String kafkaFallbackTopic = this.context.getConfig().kafkaFallbackTopic; if (kafkaFallbackTopic != null) { <START> publishFallbackTopic(kafkaFallbackTopic); <END> } } else if (!this.context.getConfig().ignoreProducerError) { this.context.terminate(e); return; } } else { this.succeededMessageCount.inc(); this.succeededMessageMeter.mark(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("-> key:" + key + ", partition:" + md.partition() + ", offset:" + md.offset()); LOGGER.debug(" " + this.json); LOGGER.debug(" " + position); LOGGER.debug(""); } } cc.markCompleted(); }</code><technical_language>cc.markCompleted below, fallback message published, drop in-flight messages. if returned early here, passed cc callback for fallback publish? possibly reuse this callback, long get a republish loop</technical_language>

Target:
public void onCompletion(RecordMetadata md, Exception e) { if ( e != null ) { context.failedMessageCount.inc(); context.failedMessageMeter.mark(); LOGGER.error(e.getClass().getSimpleName() + " @ " + position + " -- " + key); LOGGER.error(e.getLocalizedMessage()); boolean nonFatal = e instanceof RecordTooLargeException || context.maxwell.getConfig().ignoreProducerError; if (nonFatal) { if (context.fallbackTopic == null) { cc.markCompleted(); } else { publishFallback(md, e); } } else { context.maxwell.terminate(e); } } else { context.producedMessageCount.inc(); context.producedMessageMeter.mark(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("-> key:" + key + ", partition:" + md.partition() + ", offset:" + md.offset()); LOGGER.debug(" " + this.json); LOGGER.debug(" " + position); LOGGER.debug(""); } cc.markCompleted(); } }
Source:
<code>public synchronized String nextValue() { try { return current = reader.readLine(); } catch(NullPointerException e) { System.err.println("NullPointerException: " + filename + ':' + current); throw e; } catch(IOException e) { <START> throw new RuntimeException(e); } <END> }</code><technical_language>errors caught else? Is a reason exceptions printed instead of thrown previously</technical_language>

Target:
public synchronized String nextValue() { try { return current = reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } }
Source:
<code>public EventType getEventTypeByTopic(final String topic, final Client client) { if (!client.getClientId().equals(securitySettings.getAdminClientId())) { throw new ForbiddenAccessException("Request is forbidden for user " + client.getClientId()); } <START> final Optional<String> etName = timelineDbRepository.listTimelinesOrdered().stream() <END> .filter(tl -> tl.isActive()) .filter(tl -> tl.getTopic().equals(topic)) .findFirst() .map(Timeline::getEventType); if (etName.isPresent()) { return etName.map(etn -> { try { return eventTypeRepository.findByName(etn); } catch (final NakadiException e) { throw new NakadiRuntimeException(e); } }).get(); } return eventTypeRepository.list().stream() .filter(et -> et.getTopic().equals(topic)) .findFirst() .orElseThrow(() -> new NoTopicFoundException("No topic found: " + topic)); }</code><technical_language>I understand this operation is rare, fetch Timelines in db. some point nakadi die</technical_language>

Target:
public EventType getEventTypeByTopic(final String topic, final Client client) { if (!client.getClientId().equals(securitySettings.getAdminClientId())) { throw new ForbiddenAccessException("Request is forbidden for user " + client.getClientId()); } final Optional<String> etName = timelineDbRepository.listActiveTimelinesByTopic(topic) .map(Timeline::getEventType); if (etName.isPresent()) { return etName.map(etn -> { try { return eventTypeRepository.findByName(etn); } catch (final NakadiException e) { throw new NakadiRuntimeException(e); } }).get(); } return eventTypeRepository.list().stream() .filter(et -> et.getTopic().equals(topic)) .findFirst() .orElseThrow(() -> new NoTopicFoundException("No topic found: " + topic)); }
Source:
<code>private Content content( <START> final String path, final String ref <END> ) throws IOException { final String name = "ref"; RtContent content = null; final JsonStructure structure = this.request.method(Request.GET) .uri().path(path).queryParam(name, ref).back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(JsonResponse.class) .json().read(); if (structure instanceof JsonObject) { content = new RtContent( this.entry.uri().queryParam(name, ref).back(), this.owner, ((JsonObject) structure).getString("path") ); } return content; }</code><technical_language>@sadovnikov This put line</technical_language>

Target:
private Content content( final String path, final String ref ) throws IOException { final String name = "ref"; RtContent content = null; final JsonStructure structure = this.request.method(Request.GET) .uri().path(path).queryParam(name, ref).back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(JsonResponse.class) .json().read(); if (JsonValue.ValueType.OBJECT.equals(structure.getValueType())) { content = new RtContent( this.entry.uri().queryParam(name, ref).back(), this.owner, ((JsonObject) structure).getString("path") ); } return content; }
Source:
<code>public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ContextRefreshedEvent) { if (this.context.equals(((ContextRefreshedEvent) event).getApplicationContext())) { if (zkConnection.isConnected()) { registerWithZooKeeper(zkConnection.getClient()); } zkConnection.addListener(new ContainerConnectionListener()); } } <START> else if (event instanceof EmbeddedServletContainerInitializedEvent) { <END> this.containerAttributes.put(ContainerAttributes.PORT_KEY, String.valueOf(((EmbeddedServletContainerInitializedEvent) event).getEmbeddedServletContainer() .getPort())); containerRepository.update(new Container(containerAttributes.getId(), containerAttributes)); } }</code><technical_language>guaranteed a ZK connection EmbeddedServletContainerInitializedEvent is raised</technical_language>

Target:
public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ContextRefreshedEvent) { if (this.context.equals(((ContextRefreshedEvent) event).getApplicationContext())) { if (zkConnection.isConnected()) { registerWithZooKeeper(zkConnection.getClient()); } zkConnection.addListener(new ContainerConnectionListener()); } } else if (event instanceof EmbeddedServletContainerInitializedEvent) { String namespace = ((EmbeddedServletContainerInitializedEvent) event).getApplicationContext().getNamespace(); if (namespace != null && namespace.equals(MGMT_CONTEXT_NAMESPACE)) { managementPort = ((EmbeddedServletContainerInitializedEvent) event).getEmbeddedServletContainer().getPort(); this.containerAttributes.setManagementPort(String.valueOf(managementPort)); if (zkConnection.isConnected()) { containerRepository.update(new Container(containerAttributes.getId(), containerAttributes)); } } } }
Source:
<code>public void init(ServletConfig config) throws ServletException { super.init(config); LOG.debug("InitServlet start..."); executor = Executors.newFixedThreadPool(ExecutorServiceHelper.getInstance().getExecutorPoolSize()); largeJobExecutor = Executors.newFixedThreadPool(ExecutorServiceHelper.getInstance() .getLargeJobExecutorPoolSize()); <START> SessionFactory session = HibernateUtil.getSessionFactory(); <END> EventLoggerFactory.getInstance().registerLoggers(); }</code><technical_language>Do need local variable session anywhere? Otherwise, call getSessionFactory assigning anything</technical_language>

Target:
public void init(ServletConfig config) throws ServletException { super.init(config); executor = Executors.newFixedThreadPool(ExecutorServiceHelper.getInstance().getExecutorPoolSize()); largeJobExecutor = Executors.newFixedThreadPool(ExecutorServiceHelper.getInstance() .getLargeJobExecutorPoolSize()); HibernateUtil.getSessionFactory(); EventLoggerFactory.getInstance().registerLoggers(); }
Source:
<code>public void testFloatRead() throws Exception { MessageType requestedSchema = parseMessageType("message test { required float float_field;}"); ParquetMetadata metadata = ParquetFileReader.readFooter(conf, file); for (BlockMetaData block : metadata.getBlocks()) { Map<ColumnDescriptor, Dictionary> result = ParquetFileReader.readDictionary(block, file, conf, requestedSchema); for (Map.Entry<ColumnDescriptor, Dictionary> entry : result.entrySet()) { Dictionary dictionary = entry.getValue(); for (int i = 0; i < ENGLISH_CHARACTER_NUMBER; i++) { <START> assertEquals((float) intValues[i % ENGLISH_CHARACTER_NUMBER] * 2.0, dictionary.decodeToFloat(i), 1e-15); <END> } } } }</code><technical_language>i % invalues.length</technical_language>

Target:
public void testFloatRead() throws Exception { MessageType requestedSchema = parseMessageType("message test { required float float_field;}"); ParquetMetadata metadata = ParquetFileReader.readFooter(conf, file); ParquetFileReader fileReader = new ParquetFileReader(conf, metadata.getFileMetaData(), file, metadata.getBlocks(), requestedSchema.getColumns()); DictionaryPageReadStore dictionaryReadStore = fileReader.getCurrentRowGroupDictionaries(requestedSchema); ColumnDescriptor column = requestedSchema.getColumns().get(0); DictionaryReader dictionaryReader = new DictionaryReader(column, dictionaryReadStore); Dictionary dictionary = dictionaryReader.readDictionary(); for (int i = 0; i < intValues.length; i++) { assertEquals((float) intValues[i % intValues.length] * 2.0, dictionary.decodeToFloat(i), 1e-15); } fileReader.close(); }
Source:
<code>private void init() { Composite optionPane = (Composite) this.getControl(); optionPane.setLayout(new GridLayout()); optionPane.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, true)); final SelectionListener linkedListener = new SelectionListener() { @Override <START> public void widgetSelected(SelectionEvent e) { <END> getBatchWizard().setLinked(((Button) e.widget).getSelection()); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }; Button fLink = new Button(optionPane, SWT.RADIO); fLink.setText(Messages.ImportTraceWizardPageScan_2); fLink.setSelection(true); fLink.setLayoutData(new GridData()); fLink.addSelectionListener(linkedListener); Button fCopy = new Button(optionPane, SWT.RADIO); fCopy.setText(Messages.ImportTraceWizardPageScan_3); fCopy.setLayoutData(new GridData()); fCopy.addSelectionListener(linkedListener); Button fOverwrite = new Button(optionPane, SWT.CHECK); fOverwrite.setText(Messages.ImportTraceWizardPageScan_4); fOverwrite.setLayoutData(new GridData()); fOverwrite.setSelection(true); fOverwrite.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { getBatchWizard().setOverwrite(((Button) e.widget).getSelection()); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); }</code><technical_language>de-selection work. I able copy</technical_language>

Target:
private void init() { Composite optionPane = (Composite) this.getControl(); optionPane.setLayout(new GridLayout()); optionPane.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, true)); final SelectionListener linkedListener = new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { getBatchWizard().setLinked(((Button) e.widget).getSelection()); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }; Button fLink = new Button(optionPane, SWT.RADIO); fLink.setText(Messages.ImportTraceWizardLinkTraces); fLink.setSelection(true); fLink.setLayoutData(new GridData()); fLink.addSelectionListener(linkedListener); Button fCopy = new Button(optionPane, SWT.RADIO); fCopy.setText(Messages.ImportTraceWizardCopyTraces); fCopy.setLayoutData(new GridData()); fCopy.addSelectionListener(linkedListener); Button fOverwrite = new Button(optionPane, SWT.CHECK); fOverwrite.setText(Messages.ImportTraceWizardOverwriteTraces); fOverwrite.setLayoutData(new GridData()); fOverwrite.setSelection(true); fOverwrite.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { getBatchWizard().setOverwrite(((Button) e.widget).getSelection()); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); }
Source:
<code>private void readBatchHelper( int num, ColumnVector column, TypeInfo columnType, int rowId) throws IOException { switch (columnType.getCategory()) { case PRIMITIVE: PrimitiveTypeInfo primitiveColumnType = (PrimitiveTypeInfo) columnType; readBatchForPrimitiveType(num, column, primitiveColumnType, rowId); break; <START> case LIST: <END> break; case MAP: MapTypeInfo mapColumnType = (MapTypeInfo) columnType; MapColumnVector mapColumn = (MapColumnVector) column; readBatchHelper(num, mapColumn.keys, mapColumnType.getMapKeyTypeInfo(), rowId); readBatchHelper(num, mapColumn.values, mapColumnType.getMapKeyTypeInfo(), rowId); break; case STRUCT: StructTypeInfo structTypeInfo = (StructTypeInfo) columnType; StructColumnVector structColumn = (StructColumnVector) column; List<TypeInfo> typeInfos = structTypeInfo.getAllStructFieldTypeInfos(); for (int i = 0; i < typeInfos.size(); i++) { readBatch(num, structColumn.fields[i], typeInfos.get(i)); } break; case UNION: break; default: throw new IOException("Unsupported category " + columnType.getCategory().name()); } }</code><technical_language>If this is a primitive column reader, read complex types</technical_language>

Target:
private void readBatchHelper( int num, ColumnVector column, TypeInfo columnType, int rowId) throws IOException { PrimitiveTypeInfo primitiveColumnType = (PrimitiveTypeInfo) columnType; switch (primitiveColumnType.getPrimitiveCategory()) { case INT: case BYTE: case SHORT: readIntegers(num, (LongColumnVector) column, rowId); break; case DATE: case INTERVAL_YEAR_MONTH: case LONG: readLongs(num, (LongColumnVector) column, rowId); break; case BOOLEAN: readBooleans(num, (LongColumnVector) column, rowId); break; case DOUBLE: readDoubles(num, (DoubleColumnVector) column, rowId); break; case BINARY: case STRING: case CHAR: case VARCHAR: readBinaries(num, (BytesColumnVector) column, rowId); break; case FLOAT: readFloats(num, (DoubleColumnVector) column, rowId); break; case DECIMAL: readDecimal(num, (DecimalColumnVector) column, rowId); break; case INTERVAL_DAY_TIME: case TIMESTAMP: default: throw new IOException("Unsupported type: " + type); } }
Source:
<code>protected static KeyManagerFactory buildKeyManagerFactory(File certChainFile, File keyFile, String keyPassword, KeyManagerFactory kmf) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException, CertificateException, KeyException, IOException { String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm"); if (algorithm == null) { algorithm = "SunX509"; <START> } <END> return buildKeyManagerFactory(certChainFile, algorithm, keyFile, keyPassword, kmf, KeyStore.getDefaultType()); }</code><technical_language>remove code is done in method delegate too</technical_language>

Target:
protected static KeyManagerFactory buildKeyManagerFactory(File certChainFile, File keyFile, String keyPassword, KeyManagerFactory kmf) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException, CertificateException, KeyException, IOException { return buildKeyManagerFactory(certChainFile, keyFile, keyPassword, kmf, KeyStore.getDefaultType()); }
Source:
<code>public BigtableTable(AbstractBigtableConnection bigtableConnection, TableName tableName, BigtableOptions options, BigtableDataClient client, ExecutorService executorService) { this.bigtableConnection = bigtableConnection; this.tableName = tableName; this.options = options; this.client = client; <START> putAdapter = new PutAdapter(getConfiguration().getInt("hbase.client.keyvalue.maxsize", -1)); <END> mutationAdapter = Adapters.createMutationsAdapter(putAdapter); rowMutationsAdapter = new RowMutationsAdapter(mutationAdapter); this.executorService = MoreExecutors.listeningDecorator(executorService); this.bigtableTableName = options.getClusterName().toTableName(tableName.getNameAsString()); this.batchExecutor = new BatchExecutor( client, options, this.bigtableTableName, this.executorService, putAdapter, rowMutationsAdapter); }</code><technical_language>Adapters.createPutAdapter()</technical_language>

Target:
public BigtableTable(AbstractBigtableConnection bigtableConnection, TableName tableName, BigtableOptions options, BigtableDataClient client, ExecutorService executorService) { this.bigtableConnection = bigtableConnection; this.tableName = tableName; this.options = options; this.client = client; putAdapter = Adapters.createPutAdapter(getConfiguration()); mutationAdapter = Adapters.createMutationsAdapter(putAdapter); rowMutationsAdapter = new RowMutationsAdapter(mutationAdapter); this.executorService = MoreExecutors.listeningDecorator(executorService); this.bigtableTableName = options.getClusterName().toTableName(tableName.getNameAsString()); this.batchExecutor = new BatchExecutor( client, options, this.bigtableTableName, this.executorService, putAdapter, rowMutationsAdapter); }
Source:
<code>public void startProvisioning(ProvisioningConfiguration req) { if (!req.isValid()) { doImmediateProvisioningFailure(IpManagerEvent.ERROR_INVALID_PROVISIONING); return; } final ScanResultInfo scanResultInfo = req.mScanResultInfo; mLastBssid = <START> scanResultInfo != null <END> ? MacAddress.fromString(scanResultInfo.getBssid()) : null; sendMessage(CMD_START, new android.net.shared.ProvisioningConfiguration(req)); }</code><technical_language>Put this in parentheses for readability: mLastBssid = (scanResultInfo != null) ? MacAddress.fromString(scanResultInfo.getBssid()) : null; Or, if prefer, mLastBssid = (scanResultInfo == null) ? null : MacAddress.fromString(scanResultInfo.getBssid());</technical_language>

Target:
public void startProvisioning(ProvisioningConfiguration req) { if (!req.isValid()) { doImmediateProvisioningFailure(IpManagerEvent.ERROR_INVALID_PROVISIONING); return; } final ScanResultInfo scanResultInfo = req.mScanResultInfo; mCurrentBssid = null; if (scanResultInfo != null) { try { mCurrentBssid = MacAddress.fromString(scanResultInfo.getBssid()); } catch (IllegalArgumentException e) { Log.wtf(mTag, "Invalid BSSID: " + scanResultInfo.getBssid() + " in provisioning configuration", e); } } sendMessage(CMD_START, new android.net.shared.ProvisioningConfiguration(req)); }
Source:
<code>private void doubleBuffer(int wanted) { <START> int bufferLength = buffer.length * 2; <END> while (bufferLength < wanted) { bufferLength *= 2; } byte[] buf = new byte[bufferLength]; moveBufferTo(buf); buffer = buf; }</code><technical_language>about: //find power of 2 wanted (i.e. highest bit) shift left 1 bit final int bufferLength = Integer.highestOneBit(wanted) << 1; final byte[] buf = new byte[bufferLength];</technical_language>

Target:
private void doubleBuffer(int wanted) { final int bufferLength = Integer.highestOneBit(wanted) << 1; final byte[] buf = new byte[bufferLength]; moveBufferTo(buf); buffer = buf; }
Source:
<code>protected Collection<Integer> translateForStreamingInternal( final BroadcastStateTransformation<IN1, IN2, OUT> transformation, final Context context) { checkNotNull(transformation); checkNotNull(context); <START> CoBroadcastWithNonKeyedOperator<IN1, IN2, OUT> operator = new CoBroadcastWithNonKeyedOperator<>( <END> transformation.getUserFunction(), transformation.getBroadcastStateDescriptors()); return translateInternal( transformation, transformation.getNonBroadcastStream(), transformation.getBroadcastStream(), SimpleOperatorFactory.of(operator), null , null , null , context); }</code><technical_language>I create operator push runtime-related stuff. In future a translator gives, for example, operator sth else</technical_language>

Target:
protected Collection<Integer> translateForStreamingInternal( final BroadcastStateTransformation<IN1, IN2, OUT> transformation, final Context context) { checkNotNull(transformation); checkNotNull(context); CoBroadcastWithNonKeyedOperator<IN1, IN2, OUT> operator = new CoBroadcastWithNonKeyedOperator<>( transformation.getUserFunction(), transformation.getBroadcastStateDescriptors()); return translateInternal( transformation, transformation.getRegularInput(), transformation.getBroadcastInput(), SimpleOperatorFactory.of(operator), null , null , null , context); }
Source:
<code>public static ArchivedExecutionGraph createFromInitializingJob( JobID jobId, String jobName, JobStatus jobStatus, @Nullable Throwable throwable, long initializationTimestamp) { <START> long failureTime = System.currentTimeMillis(); <END> Map<JobVertexID, ArchivedExecutionJobVertex> archivedTasks = Collections.emptyMap(); List<ArchivedExecutionJobVertex> archivedVerticesInCreationOrder = Collections.emptyList(); final Map<String, SerializedValue<OptionalFailure<Object>>> serializedUserAccumulators = Collections.emptyMap(); StringifiedAccumulatorResult[] archivedUserAccumulators = new StringifiedAccumulatorResult[]{}; final long[] timestamps = new long[JobStatus.values().length]; timestamps[JobStatus.INITIALIZING.ordinal()] = initializationTimestamp; String jsonPlan = "{}"; ErrorInfo failureInfo = null; if (throwable != null) { Preconditions.checkState(jobStatus == JobStatus.FAILED); failureInfo = new ErrorInfo(throwable, failureTime); timestamps[JobStatus.FAILED.ordinal()] = failureTime; } return new ArchivedExecutionGraph( jobId, jobName, archivedTasks, archivedVerticesInCreationOrder, timestamps, jobStatus, failureInfo, jsonPlan, archivedUserAccumulators, serializedUserAccumulators, new ExecutionConfig().archive(), false, null, null, null); }</code><technical_language>Move this if branch</technical_language>

Target:
public static ArchivedExecutionGraph createFromInitializingJob( JobID jobId, String jobName, JobStatus jobStatus, @Nullable Throwable throwable, long initializationTimestamp) { Map<JobVertexID, ArchivedExecutionJobVertex> archivedTasks = Collections.emptyMap(); List<ArchivedExecutionJobVertex> archivedVerticesInCreationOrder = Collections.emptyList(); final Map<String, SerializedValue<OptionalFailure<Object>>> serializedUserAccumulators = Collections.emptyMap(); StringifiedAccumulatorResult[] archivedUserAccumulators = new StringifiedAccumulatorResult[]{}; final long[] timestamps = new long[JobStatus.values().length]; timestamps[JobStatus.INITIALIZING.ordinal()] = initializationTimestamp; String jsonPlan = "{}"; ErrorInfo failureInfo = null; if (throwable != null) { Preconditions.checkState(jobStatus == JobStatus.FAILED); long failureTime = System.currentTimeMillis(); failureInfo = new ErrorInfo(throwable, failureTime); timestamps[JobStatus.FAILED.ordinal()] = failureTime; } return new ArchivedExecutionGraph( jobId, jobName, archivedTasks, archivedVerticesInCreationOrder, timestamps, jobStatus, failureInfo, jsonPlan, archivedUserAccumulators, serializedUserAccumulators, new ExecutionConfig().archive(), false, null, null, null); }
Source:
<code>public void stopNoteExecution(String noteId, ServiceContext context, ServiceCallback<Note> callback) throws IOException { if (!checkPermission(noteId, Permission.RUNNER, Message.OP.STOP_NOTE_EXECUTION, context, callback)) { return; } Note note = notebook.getNote(noteId); if (note == null) { callback.onFailure(new NoteNotFoundException(noteId), context); return; } for (Paragraph paragraph : note.getParagraphs()) { if (paragraph.isRunning()) { <START> paragraph.abort(); <END> break; } } callback.onSuccess(note, context); }</code><technical_language>is a race condition? runParagraph is a loop, if abort para 1 threadpool thread runs para 2</technical_language>

Target:
public void stopNoteExecution(String noteId, ServiceContext context, ServiceCallback<Note> callback) throws IOException { if (!checkPermission(noteId, Permission.RUNNER, Message.OP.STOP_NOTE_EXECUTION, context, callback)) { return; } Note note = notebook.getNote(noteId); if (note == null) { callback.onFailure(new NoteNotFoundException(noteId), context); return; } note.abortExecution(); for (Paragraph paragraph : note.getParagraphs()) { if (paragraph.isRunning()) { paragraph.abort(); break; } } callback.onSuccess(note, context); }
Source:
<code>protected List<JsonObject> runYoutubeDL(CrawlURI uri) { ProcessBuilder pb = new ProcessBuilder("youtube-dl", "--ignore-config", "--simulate", "--dump-json", "--format=best", uri.toString()); logger.fine("running " + pb.command()); Process proc = null; try { proc = pb.start(); } catch (IOException e) { logger.log(Level.WARNING, "youtube-dl failed " + pb.command(), e); return (List<JsonObject>) Collections.EMPTY_LIST; } String stdout = null; String stderr = null; try { <START> stdout = readToEnd( <END> new InputStreamReader(proc.getInputStream(), "UTF-8")); stderr = readToEnd( new InputStreamReader(proc.getErrorStream(), "UTF-8")); } catch (IOException e) { logger.log(Level.WARNING, "problem reading output from youtube-dl " + pb.command(), e); return (List<JsonObject>) Collections.EMPTY_LIST; } try { if (proc.waitFor() != 0) { logger.fine("youtube-dl exited with status " + proc.waitFor() + " " + pb.command() + "\n=== stdout ===\n" + stdout + "\n=== stderr ===\n" + stderr); return (List<JsonObject>) Collections.EMPTY_LIST; } } catch (InterruptedException e) { proc.destroyForcibly(); } ArrayList<JsonObject> ydlJsons = new ArrayList<JsonObject>(); JsonStreamParser parser = new JsonStreamParser(stdout); try { while (parser.hasNext()) { ydlJsons.add((JsonObject) parser.next()); } } catch (JsonParseException e) { logger.log(Level.FINE, "problem parsing json from youtube-dl " + pb.command() + "\n=== stdout ===\n" + stdout + "\n=== stderr ===\n" + stderr, e); return (List<JsonObject>) Collections.EMPTY_LIST; } return ydlJsons; }</code><technical_language>a heads bitten this pattern hanging. If child process writes stderr more OS' pipe buffer size child's write syscalls block child hang. parent Java process is waiting reading stdout progresses reading stderr. I safe separately read stdout stderr in Java is do separate threads redirect of a temp file. :-(</technical_language>

Target:
protected List<JsonObject> runYoutubeDL(CrawlURI uri) { ProcessBuilder pb = new ProcessBuilder("youtube-dl", "--ignore-config", "--simulate", "--dump-json", "--format=best", uri.toString()); logger.fine("running " + pb.command()); Process proc = null; try { proc = pb.start(); } catch (IOException e) { logger.log(Level.WARNING, "youtube-dl failed " + pb.command(), e); return null; } ProcessOutput output; try { output = readOutput(proc); } catch (IOException e) { logger.log(Level.WARNING, "problem reading output from youtube-dl " + pb.command(), e); return null; } try { if (proc.waitFor() != 0) { logger.fine("youtube-dl exited with status " + proc.waitFor() + " " + pb.command() + "\n=== stdout ===\n" + output.stdout + "\n=== stderr ===\n" + output.stderr); return null; } } catch (InterruptedException e) { proc.destroyForcibly(); } List<JsonObject> ydlJsons = new ArrayList<JsonObject>(); JsonStreamParser parser = new JsonStreamParser(output.stdout); try { while (parser.hasNext()) { ydlJsons.add((JsonObject) parser.next()); } } catch (JsonParseException e) { logger.log(Level.FINE, "problem parsing json from youtube-dl " + pb.command() + "\n=== stdout ===\n" + output.stdout + "\n=== stderr ===\n" + output.stderr, e); return null; } return ydlJsons; }
Source:
<code>private int getCreditsToAdd(int linkCredits) { final CoreSubscriber<? super Message> subscriber = downstream.get(); final long r = requested; final boolean hasBackpressure = r != Long.MAX_VALUE; if (subscriber == null || r == 0) { logger.info("Not adding credits. No downstream subscribers or items requested."); return 0; } final int creditsToAdd; final int expectedTotalCredit; if (prefetch == 0) { if (r <= Integer.MAX_VALUE) { expectedTotalCredit = (int) r; } else { <START> expectedTotalCredit = Integer.MAX_VALUE; <END> } } else { expectedTotalCredit = prefetch; } synchronized (queueLock) { final int queuedMessages = pendingMessages.get(); final int pending = queuedMessages + linkCredits; if (hasBackpressure) { creditsToAdd = Math.max(expectedTotalCredit - pending, 0); } else { creditsToAdd = minimumNumberOfMessages >= queuedMessages ? Math.max(expectedTotalCredit - pending, 0) : 0; } } return creditsToAdd; }</code><technical_language>get this in this case credit need Integer.MAX_VALUE ? max</technical_language>

Target:
private int getCreditsToAdd(int linkCredits) { final CoreSubscriber<? super Message> subscriber = downstream.get(); final long r = requested; final boolean hasBackpressure = r != Long.MAX_VALUE; if (subscriber == null || r == 0) { logger.info("Not adding credits. No downstream subscribers or items requested."); return 0; } final int creditsToAdd; final int expectedTotalCredit; if (prefetch == 0) { if (r <= Integer.MAX_VALUE) { expectedTotalCredit = (int) r; } else { expectedTotalCredit = Integer.MAX_VALUE; } } else { expectedTotalCredit = prefetch; } logger.info("linkCredits: '{}', expectedTotalCredit: '{}'", linkCredits, expectedTotalCredit); synchronized (queueLock) { final int queuedMessages = pendingMessages.get(); final int pending = queuedMessages + linkCredits; if (hasBackpressure) { creditsToAdd = Math.max(expectedTotalCredit - pending, 0); } else { creditsToAdd = minimumNumberOfMessages >= queuedMessages ? Math.max(expectedTotalCredit - pending, 0) : 0; } logger.info("prefetch: '{}', requested: '{}', linkCredits: '{}', expectedTotalCredit: '{}', queuedMessages:" + "'{}', creditsToAdd: '{}', messageQueue.size(): '{}'", getPrefetch(), r, linkCredits, expectedTotalCredit, queuedMessages, creditsToAdd, messageQueue.size()); } return creditsToAdd; }
Source:
<code>public Graph load(StageIdentifier stageIdentifier, TempGraphFactory tempGraphFactory, final XSLTTransformerRegistry transformerRegistry) throws GoIntegrationException { <START> LOGGER.debug("Attempting to import stage with url <" + stageIdentifier + "> !"); <END> long importStartingTime = System.currentTimeMillis(); try { Stage stage = stageFinder.findStageWithIdentifier(stageIdentifier); String baseUri = "https://localhost:8154/go"; Graph graph = loadIsolatedStageGraph(stageIdentifier, tempGraphFactory, transformerRegistry, stage, baseUri); importPipeline(pipelineInstanceLoader.loadPipelineForShine(stage.getPipelineId()), graph, transformerRegistry, baseUri); importJobs(graph, transformerRegistry, stage, baseUri); return graph; } finally { LOGGER.debug("Done importing stage with url <" + stageIdentifier + "> with " + (System.currentTimeMillis() - importStartingTime) + " ms!"); } }</code><technical_language>fix string concatenation in this file</technical_language>

Target:
public Graph load(StageIdentifier stageIdentifier, TempGraphFactory tempGraphFactory, final XSLTTransformerRegistry transformerRegistry) throws GoIntegrationException { LOGGER.debug("Attempting to import stage with url <{}> !", stageIdentifier); long importStartingTime = System.currentTimeMillis(); try { Stage stage = stageFinder.findStageWithIdentifier(stageIdentifier); String baseUri = "https://localhost:8154/go"; Graph graph = loadIsolatedStageGraph(stageIdentifier, tempGraphFactory, transformerRegistry, stage, baseUri); importPipeline(pipelineInstanceLoader.loadPipelineForShine(stage.getPipelineId()), graph, transformerRegistry, baseUri); importJobs(graph, transformerRegistry, stage, baseUri); return graph; } finally { LOGGER.debug("Done importing stage with url <{}> with ms!", stageIdentifier, System.currentTimeMillis() - importStartingTime); } }
Source:
<code><START> private void checkProcStatistics(Client client) <END> throws NoConnectionsException, IOException, ProcCallException { VoltTable vt; vt = client.callProcedure("@Statistics", "PROCEDUREPROFILE", 1).getResults()[0]; System.out.println(vt.toString()); }</code><technical_language>This function cluttering test output. Is serving a purpose? modifed do actual validation dump output for a visual inspection that, practically speaking, happen. In general, I keeping PROVEN USEFUL visual diagnostic code quickly enabled wrong, I DISABLED is running expected for a verbose successful run clearer identification of actual problem diagnostics</technical_language>

Target:
private void checkProcStatistics(Client client) throws NoConnectionsException, IOException, ProcCallException { VoltTable vt; vt = client.callProcedure("@Statistics", "PROCEDUREPROFILE", 1).getResults()[0]; }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { Connection connection = null; IProject project = null; ISelection selection = HandlerUtil.getCurrentSelection(event); final IDockerImage image = UIUtils.getFirstElement(selection, IDockerImage.class); if (image == null <START> || OpenShiftUIUtils.hasOpenShiftExplorerSelection()) { <END> project = ResourceUtils.getProject(UIUtils.getFirstElement(selection, IResource.class)); if(project != null) { connection = ConnectionsRegistryUtil.getConnectionFor(project); } else { connection = UIUtils.getFirstElement(selection, Connection.class); } } if(connection == null) { connection = OpenShiftUIUtils.getExplorerDefaultConnection(Connection.class); } runWizard(HandlerUtil.getActiveWorkbenchWindow(event).getShell(), image, project,connection); return null; }</code><technical_language>Still, image != null, line selection = OpenShiftUIUtils.getOpenShiftExplorerSelection(); needed? image == null, yes, wizard is started explorer, current selection is ok, if image != null, wizard started Docker explorer, select project get explorer selection before</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { Connection connection = null; IProject project = null; ISelection selection = HandlerUtil.getCurrentSelection(event); final IDockerImage image = UIUtils.getFirstElement(selection, IDockerImage.class); if (image == null || OpenShiftUIUtils.hasOpenShiftExplorerSelection()) { selection = OpenShiftUIUtils.getOpenShiftExplorerSelection(); project = ResourceUtils.getProject(UIUtils.getFirstElement(selection, IResource.class)); if(project != null) { connection = ConnectionsRegistryUtil.getConnectionFor(project); } else { connection = UIUtils.getFirstElement(selection, Connection.class); } } if(connection == null) { connection = OpenShiftUIUtils.getExplorerDefaultConnection(Connection.class); } runWizard(HandlerUtil.getActiveWorkbenchWindow(event).getShell(), image, project,connection); return null; }