auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void handleMessageInternal(Message<?> message) throws Exception { StreamHolder inputStreamHolder = this.payloadToInputStream(message); if (inputStreamHolder != null) { Session<F> session = this.sessionFactory.getSession(); <START> String fileName = inputStreamHolder.name; <END> try { String remoteDirectory = this.directoryExpressionProcessor.processMessage(message); String temporaryRemoteDirectory = remoteDirectory; if (this.temporaryDirectoryExpressionProcessor != null){ temporaryRemoteDirectory = this.temporaryDirectoryExpressionProcessor.processMessage(message); } fileName = this.fileNameGenerator.generateFileName(message); this.sendFileToRemoteDirectory(inputStreamHolder.stream, temporaryRemoteDirectory, remoteDirectory, fileName, session); } catch (FileNotFoundException e) { throw new MessageDeliveryException(message, "File [" + inputStreamHolder.name + "] not found in local working directory; it was moved or deleted unexpectedly.", e); } catch (IOException e) { throw new MessageDeliveryException(message, "Failed to transfer file [" + inputStreamHolder.name + "->" + fileName + "] from local directory to remote directory.", e); } catch (Exception e) { throw new MessageDeliveryException(message, "Error handling message for file [" + inputStreamHolder.name + "->" + fileName + "]", e); } finally { if (session != null) { session.close(); } } } }</code><technical_language>OK it, I remember pointed out me, preferable **getter**</technical_language>

Target:
protected void handleMessageInternal(Message<?> message) throws Exception { StreamHolder inputStreamHolder = this.payloadToInputStream(message); if (inputStreamHolder != null) { Session<F> session = this.sessionFactory.getSession(); String fileName = inputStreamHolder.getName(); try { String remoteDirectory = this.directoryExpressionProcessor.processMessage(message); String temporaryRemoteDirectory = remoteDirectory; if (this.temporaryDirectoryExpressionProcessor != null){ temporaryRemoteDirectory = this.temporaryDirectoryExpressionProcessor.processMessage(message); } fileName = this.fileNameGenerator.generateFileName(message); this.sendFileToRemoteDirectory(inputStreamHolder.getStream(), temporaryRemoteDirectory, remoteDirectory, fileName, session); } catch (FileNotFoundException e) { throw new MessageDeliveryException(message, "File [" + inputStreamHolder.getName() + "] not found in local working directory; it was moved or deleted unexpectedly.", e); } catch (IOException e) { throw new MessageDeliveryException(message, "Failed to transfer file [" + inputStreamHolder.getName() + "->" + fileName + "] from local directory to remote directory.", e); } catch (Exception e) { throw new MessageDeliveryException(message, "Error handling message for file [" + inputStreamHolder.getName() + "->" + fileName + "]", e); } finally { if (session != null) { session.close(); } } } else { if (logger.isWarnEnabled()) { logger.warn("File " + message.getPayload() + " does not exist"); } } }
Source:
<code>public void attributeChanged(TaskAttribute attribute) { if (attribute.getParentAttribute() != getTaskData().getRoot()) { throw new RuntimeException( "Editing is only supported for attributes that are attached to the root of task data"); } unsavedChangedAttributes.add(attribute); if (this.listeners != null) { final TaskDataModelEvent event = new TaskDataModelEvent(this, EventKind.CHANGED, attribute); TaskDataModelListener[] listeners = this.listeners.toArray(new TaskDataModelListener[0]); for (final TaskDataModelListener listener : listeners) { SafeRunner.run(new ISafeRunnable() { public void handleException(Throwable e) { StatusHandler .log(new Status(IStatus.ERROR, ITasksCoreConstants.ID_PLUGIN, "Listener failed", e)); } public void run() throws Exception { listener.attributeChanged(event); } }); } } <START> String changedAttribute = attribute.getId(); <END> for (TaskAttribute taskAttribute : attribute.getTaskData().getRoot().getAttributes().values()) { if (changedAttribute.equals(taskAttribute.getMetaData().getDependsOn())) { attributeChanged(taskAttribute); } } }</code><technical_language>I this move AbstractAttributeEditor.modelListener. clear listener cascade this</technical_language>

Target:
public void attributeChanged(TaskAttribute attribute) { if (attribute.getParentAttribute() != getTaskData().getRoot()) { throw new RuntimeException( "Editing is only supported for attributes that are attached to the root of task data"); } unsavedChangedAttributes.add(attribute); if (this.listeners != null) { final TaskDataModelEvent event = new TaskDataModelEvent(this, EventKind.CHANGED, attribute); TaskDataModelListener[] listeners = this.listeners.toArray(new TaskDataModelListener[0]); for (final TaskDataModelListener listener : listeners) { SafeRunner.run(new ISafeRunnable() { public void handleException(Throwable e) { StatusHandler .log(new Status(IStatus.ERROR, ITasksCoreConstants.ID_PLUGIN, "Listener failed", e)); } public void run() throws Exception { listener.attributeChanged(event); } }); } } }
Source:
<code>public Mono<String> getBodyAsString(Charset charset) { Objects.requireNonNull(charset, "'charset' cannot be null."); return bodyBytes == null ? Mono.empty() <START> : Mono.just(CoreUtils.bomAwareToString(bodyBytes, getHeaderValue("Content-Type"))); <END> }</code><technical_language>want move this getBodyAsString overload parameters, in Azure Core leverages Charset overload</technical_language>

Target:
public Mono<String> getBodyAsString(Charset charset) { Objects.requireNonNull(charset, "'charset' cannot be null."); return bodyBytes == null ? Mono.empty() : Mono.just(new String(bodyBytes, charset)); }
Source:
<code>public <T> T forwardTo(final Class<T> type) { return proxifier.proxify(type, new MethodInvocation<T>() { @Override public Object intercept(T proxy, Method method, Object[] args, SuperMethod superMethod) { try { logger.debug("Executing {}", method); ControllerMethod old = methodInfo.getControllerMethod(); methodInfo.setControllerMethod(DefaultControllerMethod.instanceFor(type, method)); Object methodResult = method.invoke(container.instanceFor(type), args); methodInfo.setControllerMethod(old); Type returnType = method.getGenericReturnType(); if (!(returnType == void.class)) { request.setAttribute(extractor.nameFor(returnType), methodResult); } if (response.isCommitted() || result.used()) { <START> return null; <END> } String path = resolver.pathFor(DefaultControllerMethod.instanceFor(type, method)); logger.debug("Forwarding to {}", path); request.getRequestDispatcher(path).forward(request, response); return null; } catch (InvocationTargetException e) { propagateIfPossible(e.getCause()); throw new ProxyInvocationException(e); } catch (Exception e) { throw new ProxyInvocationException(e); } } }); }</code><technical_language>log debug here, least</technical_language>

Target:
public <T> T forwardTo(final Class<T> type) { return proxifier.proxify(type, new MethodInvocation<T>() { @Override public Object intercept(T proxy, Method method, Object[] args, SuperMethod superMethod) { try { logger.debug("Executing {}", method); ControllerMethod old = methodInfo.getControllerMethod(); methodInfo.setControllerMethod(DefaultControllerMethod.instanceFor(type, method)); Object methodResult = method.invoke(container.instanceFor(type), args); methodInfo.setControllerMethod(old); Type returnType = method.getGenericReturnType(); if (!(returnType == void.class)) { request.setAttribute(extractor.nameFor(returnType), methodResult); } if (response.isCommitted() || result.used()) { logger.debug("Response already commited, not forwarding."); return null; } String path = resolver.pathFor(DefaultControllerMethod.instanceFor(type, method)); logger.debug("Forwarding to {}", path); request.getRequestDispatcher(path).forward(request, response); return null; } catch (InvocationTargetException e) { propagateIfPossible(e.getCause()); throw new ProxyInvocationException(e); } catch (Exception e) { throw new ProxyInvocationException(e); } } }); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { getWindow().requestFeature(Window.FEATURE_ACTION_BAR); super.onCreate(savedInstanceState); Intent intent = getIntent(); if (intent != null) { Bundle extras = intent.getExtras(); if (extras != null) { this.localConversation = (SwrveBaseConversation) extras.getSerializable("conversation"); <START> this.hideToolbar = extras.getBoolean("hide_toolbar"); <END> } } if (!hideToolbar) { setTheme(R.style.Theme_ConversationsWithToolbar); } try { if (localConversation != null) { conversationFragment = ConversationFragment.create(localConversation); conversationFragment.commitConversationFragment(getSupportFragmentManager()); } else { SwrveLogger.e(LOG_TAG, "Could not render ConversationActivity. No SwrveConversation was detected"); this.finish(); } } catch (Exception ge) { SwrveLogger.e(LOG_TAG, "Could not render ConversationActivity.", ge); this.finish(); } }</code><technical_language>a key constant</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { getWindow().requestFeature(Window.FEATURE_ACTION_BAR); super.onCreate(savedInstanceState); Intent intent = getIntent(); if (intent != null) { Bundle extras = intent.getExtras(); if (extras != null) { this.localConversation = (SwrveBaseConversation) extras.getSerializable(CONVERSATION_KEY); this.hideToolbar = extras.getBoolean(HIDE_TOOLBAR_KEY); } } if (!hideToolbar) { setTheme(R.style.Theme_ConversationsWithToolbar); } try { if (localConversation != null) { conversationFragment = ConversationFragment.create(localConversation); conversationFragment.commitConversationFragment(getSupportFragmentManager()); } else { SwrveLogger.e(LOG_TAG, "Could not render ConversationActivity. No SwrveConversation was detected"); this.finish(); } } catch (Exception ge) { SwrveLogger.e(LOG_TAG, "Could not render ConversationActivity.", ge); this.finish(); } }
Source:
<code>public TaskReport ingestServiceData(PluginTask task, RecordImporter recordImporter, int taskIndex, PageBuilder pageBuilder) { if (task.getQueryBy().isPresent() && task.getQueryBy().get() == QueryBy.DATE_RANGE && task.getIncremental() && !Exec.isPreview()) { <START> OffsetDateTime latestUpdateAt = task.getLatestUpdatedAt().isPresent() ? <END> task.getLatestUpdatedAt().get().toInstant().atOffset(ZoneOffset.UTC) : OffsetDateTime.now(ZoneOffset.UTC); OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC); if (latestUpdateAt.isAfter(now)) { logger.warn("`latest_updated_at` ({}) preceded current time ({}). Will try to import next run", latestUpdateAt.format(DATE_FORMATTER), now.format(DATE_FORMATTER)); OffsetDateTime earliest = task.getEarliestUpdatedAt().isPresent() ? task.getEarliestUpdatedAt().get().toInstant().atOffset(ZoneOffset.UTC) : OffsetDateTime.now(ZoneOffset.UTC); TaskReport taskReport = Exec.newTaskReport(); taskReport.set("earliest_updated_at", earliest.format(DATE_FORMATTER)); if (task.getReportDuration().isPresent()) { taskReport.set("report_duration", task.getReportDuration().get()); } return taskReport; } } return super.ingestServiceData(task, recordImporter, taskIndex, pageBuilder); }</code><technical_language>need check LatestUpdateAt validation checked present of this</technical_language>

Target:
public TaskReport ingestServiceData(PluginTask task, RecordImporter recordImporter, int taskIndex, PageBuilder pageBuilder) { if (task.getQueryBy().isPresent() && task.getQueryBy().get() == QueryBy.DATE_RANGE && task.getIncremental() && !Exec.isPreview()) { OffsetDateTime latestUpdateAt = OffsetDateTime.ofInstant(task.getLatestUpdatedAt().get().toInstant(), ZoneOffset.UTC); OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC); if (latestUpdateAt.isAfter(now)) { logger.warn("`latest_updated_at` ({}) preceded current time ({}). Will try to import next run", latestUpdateAt.format(DATE_FORMATTER), now.format(DATE_FORMATTER)); OffsetDateTime earliest = OffsetDateTime.ofInstant(task.getEarliestUpdatedAt().get().toInstant(), ZoneOffset.UTC); TaskReport taskReport = Exec.newTaskReport(); taskReport.set("earliest_updated_at", earliest.format(DATE_FORMATTER)); if (task.getReportDuration().isPresent()) { taskReport.set("report_duration", task.getReportDuration().get()); } return taskReport; } } return super.ingestServiceData(task, recordImporter, taskIndex, pageBuilder); }
Source:
<code>public JavaWriter beginMethod(String returnType, String name, Set<Modifier> modifiers, List<String> parameters, List<String> throwsTypes) throws IOException { indent(); emitModifiers(modifiers); if (returnType != null) { emitCompressedType(returnType); out.write(" "); out.write(name); } else { emitCompressedType(name); } out.write("("); if (parameters != null) { for (int p = 0; p < parameters.size();) { if (p != 0) { out.write(", "); } emitCompressedType(parameters.get(p++)); out.write(" "); emitCompressedType(parameters.get(p++)); } } out.write(")"); if (throwsTypes != null && throwsTypes.size() > 0) { out.write("\n"); indent(); out.write(" throws "); for (int i = 0; i < throwsTypes.size(); i++) { if (i != 0) { out.write(", "); } emitCompressedType(throwsTypes.get(i)); } } <START> if (modifiers.contains(ABSTRACT) || Scope.INTERFACE_DECLARATION.equals(scopes.getFirst())) { <END> out.write(";\n"); scopes.push(Scope.ABSTRACT_METHOD); } else { out.write(" {\n"); scopes.push(returnType == null ? Scope.CONSTRUCTOR : Scope.NON_ABSTRACT_METHOD); } return this; }</code><technical_language>push() .pop() dealing scopes object this .peek() for parity</technical_language>

Target:
public JavaWriter beginMethod(String returnType, String name, Set<Modifier> modifiers, List<String> parameters, List<String> throwsTypes) throws IOException { indent(); emitModifiers(modifiers); if (returnType != null) { emitCompressedType(returnType); out.write(" "); out.write(name); } else { emitCompressedType(name); } out.write("("); if (parameters != null) { for (int p = 0; p < parameters.size();) { if (p != 0) { out.write(", "); } emitCompressedType(parameters.get(p++)); out.write(" "); emitCompressedType(parameters.get(p++)); } } out.write(")"); if (throwsTypes != null && throwsTypes.size() > 0) { out.write("\n"); indent(); out.write(" throws "); for (int i = 0; i < throwsTypes.size(); i++) { if (i != 0) { out.write(", "); } emitCompressedType(throwsTypes.get(i)); } } if (modifiers.contains(ABSTRACT) || Scope.INTERFACE_DECLARATION.equals(scopes.peek())) { out.write(";\n"); scopes.push(Scope.ABSTRACT_METHOD); } else { out.write(" {\n"); scopes.push(returnType == null ? Scope.CONSTRUCTOR : Scope.NON_ABSTRACT_METHOD); } return this; }
Source:
<code>private void waitForVdsUp(Guid vdsGuid) { VdsStatusListener vdsStatusListener = new VdsStatusListener() { @Override public void vdsStatusChanged() { synchronized(HostSetupNetworksCommand.this){ <START> HostSetupNetworksCommand.this.notify(); <END> } } }; try{ synchronized(this){ vdsEventListener.addVdsUpListener(vdsStatusListener); if (resourceManager.getVdsManager(vdsGuid).getCopyVds().getStatus() != VDSStatus.Up){ this.wait(WAIT_FOR_UPSTATUS_TIMEOUT); } } } catch(InterruptedException e) { } finally { vdsEventListener.removeVdsUpListener(vdsStatusListener); } }</code><technical_language>a long time I java.util.concurrent. I remember BlockingQueue proffered wait/notify. (<LINK_0> is reason it</technical_language>

Target:
private void waitForVdsUp(Guid vdsGuid) { VdsStatusListener vdsStatusListener = new VdsStatusListener() { @Override public void vdsStatusChanged() { synchronized(HostSetupNetworksCommand.this){ HostSetupNetworksCommand.this.notify(); } } }; try{ synchronized(this){ vdsEventListener.addVdsUpListener(vdsStatusListener); if (resourceManager.getVdsManager(vdsGuid).getCopyVds().getStatus() != VDSStatus.Up){ logMonitorLockReleased("Waiting for host to move to the Up state"); this.wait(WAIT_FOR_UPSTATUS_TIMEOUT); } } } catch(InterruptedException e) { } finally { vdsEventListener.removeVdsUpListener(vdsStatusListener); } }
Source:
<code>static String toString(int flags) { StringBuilder result = new StringBuilder(); if ((flags & FLAG_DEBUG) == FLAG_DEBUG) { result.append("DEBUG"); } else if ((flags & FLAG_SAMPLED_SET) == FLAG_SAMPLED_SET) { if ((flags & FLAG_SAMPLED) == FLAG_SAMPLED) { result.append("SAMPLED"); } else { result.append("NOT_SAMPLED"); } } if ((flags & FLAG_SAMPLED_LOCAL) == FLAG_SAMPLED_LOCAL) { if (result.length() > 0) result.append('|'); <START> result.append("SAMPLED_LOCAL"); <END> } return result.toString(); }</code><technical_language>I this produce NOT_SAMPLED|SAMPLED_LOCAL a bit weird</technical_language>

Target:
static String toString(int flags) { StringBuilder result = new StringBuilder(); if ((flags & FLAG_DEBUG) == FLAG_DEBUG) { result.append("DEBUG"); } else if ((flags & FLAG_SAMPLED_SET) == FLAG_SAMPLED_SET) { if ((flags & FLAG_SAMPLED) == FLAG_SAMPLED) { result.append("SAMPLED_REMOTE"); } else { result.append("NOT_SAMPLED_REMOTE"); } } if ((flags & FLAG_SAMPLED_LOCAL) == FLAG_SAMPLED_LOCAL) { if (result.length() > 0) result.append('|'); result.append("SAMPLED_LOCAL"); } return result.toString(); }
Source:
<code>protected int executeTimestampCommand(AtlasDbServices services) { KeyValueService kvs = services.getKeyValueService(); TransactionService transactionService = services.getTransactionService(); ClosableIterator<RowResult<Value>> range = kvs.getRange( TransactionConstants.TRANSACTION_TABLE, RangeRequest.all(), Long.MAX_VALUE); while (range.hasNext()) { RowResult<Value> row = range.next(); byte[] rowName = row.getRowName(); long startTs = TransactionConstants.getTimestampForValue(rowName); Value value; try { value = row.getOnlyColumnValue(); } catch (IllegalStateException e) { printer.error("Found a row in the transactions table that didn't have 1" + " and only 1 column value: start={}", SafeArg.of("startTs", startTs)); continue; } long commitTs = TransactionConstants.getTimestampForValue(value.getContents()); if (commitTs <= timestamp) { continue; } printer.info("Found and cleaning possibly inconsistent transaction: [start={}, commit={}]", SafeArg.of("startTs", startTs), SafeArg.of("commitTs", commitTs)); <START> transactionService.putUnlessExists(startTs, TransactionConstants.FAILED_COMMIT_TS); <END> } printer.info("Rollback of transactions completed."); return 0; }</code><technical_language>Hmm, this is super slow batching (and putUnlessExists is slow). require some hackiness put 0 timestamp (though this is a constant somewhere), modify this KVS.put multiPut</technical_language>

Target:
protected int executeTimestampCommand(AtlasDbServices services) { KeyValueService kvs = services.getKeyValueService(); ClosableIterator<RowResult<Value>> range = kvs.getRange( TransactionConstants.TRANSACTION_TABLE, RangeRequest.all(), Long.MAX_VALUE); Map<Cell, byte[]> txTableValuesToWrite = new HashMap<>(); while (range.hasNext()) { RowResult<Value> row = range.next(); byte[] rowName = row.getRowName(); long startTs = TransactionConstants.getTimestampForValue(rowName); Value value; try { value = row.getOnlyColumnValue(); } catch (IllegalStateException e) { printer.error("Found a row in the transactions table that didn't have 1" + " and only 1 column value: start={}", SafeArg.of("startTs", startTs)); continue; } long commitTs = TransactionConstants.getTimestampForValue(value.getContents()); if (commitTs <= timestamp) { continue; } printer.info("Found and cleaning possibly inconsistent transaction: [start={}, commit={}]", SafeArg.of("startTs", startTs), SafeArg.of("commitTs", commitTs)); Cell key = Cell.create(rowName, TransactionConstants.COMMIT_TS_COLUMN); byte[] valueForRollbackTimestamp = TransactionConstants.getValueForTimestamp(TransactionConstants.FAILED_COMMIT_TS); txTableValuesToWrite.put(key, valueForRollbackTimestamp); } if (!txTableValuesToWrite.isEmpty()) { Map<TableReference, Map<Cell, byte[]>> valuesToPut = new HashMap<>(); valuesToPut.put(TransactionConstants.TRANSACTION_TABLE, txTableValuesToWrite); kvs.put(TransactionConstants.TRANSACTION_TABLE, txTableValuesToWrite, services.getTimestampService().getFreshTimestamp()); printer.info("Completed rollback of transactions after the given timestamp."); } else { printer.info("Found no transactions after the given timestamp to rollback."); } return 0; }
Source:
<code>public static SerializableTransactionManager create(KeyValueService keyValueService, TimelockService timelockService, LockService lockService, TransactionService transactionService, Supplier<AtlasDbConstraintCheckingMode> constraintModeSupplier, ConflictDetectionManager conflictDetectionManager, SweepStrategyManager sweepStrategyManager, Cleaner cleaner, Supplier<Boolean> initializationPrerequisite, boolean allowHiddenTableAccess, Supplier<Long> lockAcquireTimeoutMs, int concurrentGetRangesThreadPoolSize, int defaultGetRangesConcurrency, boolean initializeAsync, Supplier<Long> timestampCacheSize) { TimestampTracker timestampTracker = TimestampTrackerImpl.createWithDefaultTrackers( <START> timelockService, cleaner, initializeAsync); <END> SerializableTransactionManager serializableTransactionManager = new SerializableTransactionManager( keyValueService, timelockService, lockService, transactionService, constraintModeSupplier, conflictDetectionManager, sweepStrategyManager, cleaner, allowHiddenTableAccess, lockAcquireTimeoutMs, timestampTracker, concurrentGetRangesThreadPoolSize, defaultGetRangesConcurrency, timestampCacheSize); return initializeAsync ? new InitializeCheckingWrapper(serializableTransactionManager, initializationPrerequisite) : serializableTransactionManager; }</code><technical_language>odd dependent objects (the TimestampTracker mixed random config parameters (starting allowHiddenTableAccess). fix for is scope of this PR (and breaking) :(</technical_language>

Target:
public static SerializableTransactionManager create(KeyValueService keyValueService, TimelockService timelockService, LockService lockService, TransactionService transactionService, Supplier<AtlasDbConstraintCheckingMode> constraintModeSupplier, ConflictDetectionManager conflictDetectionManager, SweepStrategyManager sweepStrategyManager, Cleaner cleaner, Supplier<Boolean> initializationPrerequisite, boolean allowHiddenTableAccess, Supplier<Long> lockAcquireTimeoutMs, int concurrentGetRangesThreadPoolSize, int defaultGetRangesConcurrency, boolean initializeAsync, Supplier<Long> timestampCacheSize) { TimestampTracker timestampTracker = TimestampTrackerImpl.createWithDefaultTrackers( timelockService, cleaner, initializeAsync); SerializableTransactionManager serializableTransactionManager = new SerializableTransactionManager( keyValueService, timelockService, lockService, transactionService, constraintModeSupplier, conflictDetectionManager, sweepStrategyManager, cleaner, timestampTracker, timestampCacheSize, allowHiddenTableAccess, lockAcquireTimeoutMs, concurrentGetRangesThreadPoolSize, defaultGetRangesConcurrency); return initializeAsync ? new InitializeCheckingWrapper(serializableTransactionManager, initializationPrerequisite) : serializableTransactionManager; }
Source:
<code>public MessageIdTracker(final NetworkConfig config) { exchangeLifetime = config.getLong(NetworkConfig.Keys.EXCHANGE_LIFETIME); boolean useRandomFirstMID = config.getBoolean(NetworkConfig.Keys.USE_RANDOM_MID_START); if (useRandomFirstMID) { <START> counter = new AtomicInteger(new SecureRandom().nextInt(1 << 10)); <END> } else { counter = new AtomicInteger(0); } messageIds = new HashMap<>(TOTAL_NO_OF_MIDS); }</code><technical_language>is need a cryptographically strong random in order create initial counter value. counter incremented sequentially ..</technical_language>

Target:
public MessageIdTracker(final NetworkConfig config) { exchangeLifetime = config.getLong(NetworkConfig.Keys.EXCHANGE_LIFETIME); boolean useRandomFirstMID = config.getBoolean(NetworkConfig.Keys.USE_RANDOM_MID_START); if (useRandomFirstMID) { counter = new AtomicInteger(new Random().nextInt(1 << 10)); } else { counter = new AtomicInteger(0); } messageIds = new HashMap<>(TOTAL_NO_OF_MIDS); }
Source:
<code>protected void setupVelocityContext() { String rl = "resource.loader"; String pkg = "org.apache.velocity.runtime.resource.loader"; Properties p = new Properties(); p.setProperty(rl, "file, class"); p.setProperty("file." + rl + ".class", pkg + ".FileResourceLoader"); p.setProperty("file." + rl + ".path", args.site.mail_dir.getAbsolutePath()); p.setProperty("class." + rl + ".class", pkg + ".ClasspathResourceLoader"); p.setProperty(org.apache.velocity.runtime.RuntimeConstants.RUNTIME_LOG, new File(args.site.logs_dir, "error_log").getAbsolutePath()); try { <START> Velocity.init(p); <END> } catch(Exception e) { } velocityContext = new VelocityContext(); velocityContext.put("email", this); velocityContext.put("messageClass", messageClass); velocityContext.put("StringUtils", StringUtils.class); }</code><technical_language>Velocity allows initialize multiple times, is insane. do this a LifecycleListener</technical_language>

Target:
protected void setupVelocityContext() { velocityContext = new VelocityContext(); velocityContext.put("email", this); velocityContext.put("messageClass", messageClass); velocityContext.put("StringUtils", StringUtils.class); }
Source:
<code>protected BeanDefinitionBuilder parseHandler(Element element, ParserContext parserContext) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(RedisQueueOutboundGateway.class); builder.addConstructorArgValue(element.getAttribute("control-queue")); String connectionFactory = element.getAttribute("connection-factory"); if (!StringUtils.hasText(connectionFactory)) { connectionFactory = "redisConnectionFactory"; } builder.addConstructorArgReference(connectionFactory); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "reply-channel","outputChannel"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "extract-payload"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "serializer"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "reply-timeout", "timeout"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "requires-reply"); <START> IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "order"); <END> return builder; }</code><technical_language>Redundand. AbstractConsumerEndpointParser takes care of that</technical_language>

Target:
protected BeanDefinitionBuilder parseHandler(Element element, ParserContext parserContext) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(RedisQueueOutboundGateway.class); builder.addConstructorArgValue(element.getAttribute("control-queue")); String connectionFactory = element.getAttribute("connection-factory"); if (!StringUtils.hasText(connectionFactory)) { connectionFactory = "redisConnectionFactory"; } builder.addConstructorArgReference(connectionFactory); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "reply-channel","outputChannel"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "expect-message"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "serializer"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "reply-timeout", "timeout"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "requires-reply"); return builder; }
Source:
<code>public IndependentClustersMergeTest() { this.numMembersInCluster = 2; this.mergePolicy = (preferredEntry, otherEntries) -> { <START> CacheEntry entry = preferredEntry != null ? preferredEntry : (CacheEntry) otherEntries.get(0); <END> entry.setValue(MERGE_RESULT); return entry; }; }</code><technical_language>Unnecessary cast. avoid unchecked warning declaring entry mergePolicy generic parameters <String, String></technical_language>

Target:
public IndependentClustersMergeTest() { this.numMembersInCluster = 2; this.mergePolicy = (preferredEntry, otherEntries) -> { CacheEntry<String, String> entry = preferredEntry != null ? preferredEntry : otherEntries.get(0); entry.setValue(MERGE_RESULT); return entry; }; }
Source:
<code>public JSONObject createContent() { Map<String, String> security = new TreeMap<>(); putBoolean(security, "hudson.ConsoleNote.INSECURE", false); putBoolean(security, "hudson.model.ParametersAction.keepUndefinedParameters", false); putBoolean(security, "hudson.model.User.allowNonExistentUserToLogin", false); putBoolean(security, "hudson.model.User.allowUserCreationViaUrl", false); putBoolean(security, "hudson.model.User.SECURITY_243_FULL_DEFENSE", true); putStringInfo(security, "hudson.model.ParametersAction.safeParameters"); <START> putStringInfo(security, "hudson.model.DirectoryBrowserSupport.CSP"); <END> Map<String, Object> info = new TreeMap<>(); info.put("core", Jenkins.getVersion().toString()); info.put("clientDate", clientDateString()); info.put("properties", security); return JSONObject.fromObject(info); }</code><technical_language>add JEP-200 killswitches</technical_language>

Target:
public JSONObject createContent() { Map<String, String> security = new TreeMap<>(); putBoolean(security, "hudson.ConsoleNote.INSECURE", false); putBoolean(security, "hudson.model.ParametersAction.keepUndefinedParameters", false); putBoolean(security, "hudson.model.User.allowNonExistentUserToLogin", false); putBoolean(security, "hudson.model.User.allowUserCreationViaUrl", false); putBoolean(security, "hudson.model.User.SECURITY_243_FULL_DEFENSE", true); putBoolean(security, "hudson.remoting.URLDeserializationHelper.avoidUrlWrapping", false); putBoolean(security, "jenkins.security.ClassFilterImpl.SUPPRESS_WHITELIST", false); putBoolean(security, "jenkins.security.ClassFilterImpl.SUPPRESS_ALL", false); putStringInfo(security, "hudson.model.ParametersAction.safeParameters"); putStringInfo(security, "hudson.model.DirectoryBrowserSupport.CSP"); putStringInfo(security, "hudson.security.HudsonPrivateSecurityRealm.ID_REGEX"); Map<String, Object> info = new TreeMap<>(); info.put("core", Jenkins.getVersion().toString()); info.put("clientDate", clientDateString()); info.put("properties", security); return JSONObject.fromObject(info); }
Source:
<code>public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(2, false)); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); composite.setFont(parent.getFont()); Label label = new Label(composite, SWT.NONE); label.setLayoutData(new GridData()); label.setText(Messages.rename_label); this.nameText = new Text(composite, SWT.BORDER); this.nameText.setText("newName"); this.nameText.setFont(composite.getFont()); this.nameText.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false)); this.nameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { if (!CharMatcher.whitespace().matchesAnyOf(RenameInputWizardPage.this.nameText.getText())) { setPageComplete(true); } } }); this.nameText.selectAll(); <START> this.setPageComplete(true); <END> this.setControl(composite); }</code><technical_language>WizardPages "isPageComplete()" method extenders supposed implement. code implement this isPageComplete() new name. setPageComplete(true) replaced setPageComplete(isPageComplete())</technical_language>

Target:
public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(2, false)); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); composite.setFont(parent.getFont()); Label label = new Label(composite, SWT.NONE); label.setLayoutData(new GridData()); label.setText(Messages.rename_label); this.nameText = new Text(composite, SWT.BORDER); this.nameText.setText("newName"); this.nameText.setFont(composite.getFont()); this.nameText.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false)); this.nameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { validatePage(); } }); this.nameText.selectAll(); this.setControl(composite); validatePage(); }
Source:
<code>public void stopClient() throws JMSException { if (null != connection && null != session && null != sender) { try { long threadID = Thread.currentThread().getId(); log.info("Closing publisher | ThreadID : " + threadID); this.sender.close(); this.session.close(); this.connection.close(); this.sender = null; this.session = null; this.connection = null; log.info("Publisher closed | ThreadID : " + threadID); } catch (JMSException e) { log.error("Error while stopping the publisher.", e); <START> throw e; <END> } } else { throw new NullPointerException("The connection, session and message sender is not assigned."); } }</code><technical_language>Add logged statement thrown error for context</technical_language>

Target:
public void stopClient() throws JMSException { if (null != connection && null != session && null != sender) { long threadID = Thread.currentThread().getId(); log.info("Closing publisher | ThreadID : " + threadID); this.sender.close(); this.session.close(); this.connection.close(); this.sender = null; this.session = null; this.connection = null; log.info("Publisher closed | ThreadID : " + threadID); } }
Source:
<code>public void started() { IdgenTask.setEnabled(true); <START> createLocationPrefixAttributeType(); <END> log.info("Idgen Module Started..."); }</code><technical_language>creating Location Attributes idgen module startup. This is a core function of idgen module other implications. If implementer wants LocationBasedPrefixProvider, responsibility ensuring correct LocationAttributeType LocationAttributes exist</technical_language>

Target:
public void started() { IdgenTask.setEnabled(true); log.info("Idgen Module Started..."); }
Source:
<code>private ProblemMarkerFilterManager() { IExtensionRegistry reg = Platform.getExtensionRegistry(); IConfigurationElement[] extensions = reg .getConfigurationElementsFor(PROBLEM_MARKER_FILTER_EXTENSION_POINT); for (int i = 0; i < extensions.length; i++) { IConfigurationElement element = extensions[i]; try { <START> IProblemMarkerFilter filter = (IProblemMarkerFilter) element.createExecutableExtension("class"); END> filters.add(filter); } catch (CoreException e) { CCorePlugin.log(e); } } }</code><technical_language>This call createExecutable contributing plugin activated. extension point allow enablement expression in order prevent activation in cases contribution required. PDOMASTProcessor extension point for example. is a change in .exsd enablement node (from org.eclipse.core.expressions/schema/expressionLanguage.exsd) is a change loading (here) evaluate expression calling createExecutableExtension</technical_language>

Target:
private ProblemMarkerFilterManager() { IExtensionRegistry reg = Platform.getExtensionRegistry(); IConfigurationElement[] extensions = reg .getConfigurationElementsFor(CCorePlugin.PLUGIN_ID, EXTENSION_POINT); for (int i = 0; i < extensions.length; i++) { IConfigurationElement element = extensions[i]; ProblemMarkerFilterDesc filterDesc = new ProblemMarkerFilterDesc(element); filters.add(filterDesc); } }
Source:
<code>public void render(View rowView, ListRowViewCache viewCache, SectionListItem<H, I> value) { <START> if (value.isSectionHeader()) { <END> headerRenderer.render(rowView, viewCache, value.getSectionHeader()); return; } itemRenderer.render(rowView, viewCache, value.getData()); }</code><technical_language>if else</technical_language>

Target:
public void render(View rowView, ListRowViewCache viewCache, SectionListItem<H, I> value) { if (value.isSectionHeader()) { headerRenderer.render(rowView, viewCache, value.getSectionHeader()); } else { itemRenderer.render(rowView, viewCache, value.getData()); } }
Source:
<code>List<MetricFamilySamples> fromCounter(String name, Counter counter) { MetricFamilySamples.Sample sample = new MetricFamilySamples.Sample(name, new ArrayList<String>(), new ArrayList<String>(), new Long(counter.getCount()).doubleValue()); <START> return Arrays.asList(new MetricFamilySamples(name, Type.COUNTER, GENERIC_HELP_MESSAGE, Arrays.asList(sample))); <END> }</code><technical_language>Technically, dropwizard counters counters a dec method. Gauges, untyped</technical_language>

Target:
List<MetricFamilySamples> fromCounter(String name, Counter counter) { MetricFamilySamples.Sample sample = new MetricFamilySamples.Sample(name, new ArrayList<String>(), new ArrayList<String>(), new Long(counter.getCount()).doubleValue()); return Arrays.asList(new MetricFamilySamples(name, Type.GAUGE, getHelpMessage(name, counter), Arrays.asList(sample))); }
Source:
<code>public DocumentClone(String content, String[] lineDelimiters) { super(); setTextStore(new StringTextStore(content)); boolean hasDefaultDelims= <START> true; <END> if (lineDelimiters != null && DefaultLineTracker.DELIMITERS.length == lineDelimiters.length) { hasDefaultDelims= true; for (int i= 0; i < lineDelimiters.length; i++) { if (DefaultLineTracker.DELIMITERS[i] != lineDelimiters[i]) { hasDefaultDelims= false; break; } } } ILineTracker tracker= hasDefaultDelims ? new DefaultLineTracker() : new ConfigurableLineTracker(lineDelimiters); setLineTracker(tracker); getTracker().set(content); completeInitialization(); }</code><technical_language>simply boolean hasDefaultDelims = Arrays.equals(DefaultLineTracker.DELIMITERS, lineDelimiters);</technical_language>

Target:
public DocumentClone(String content, String[] lineDelimiters) { super(); setTextStore(new StringTextStore(content)); boolean hasDefaultDelims= Arrays.equals(lineDelimiters, DefaultLineTracker.DELIMITERS); ILineTracker tracker= hasDefaultDelims ? new DefaultLineTracker() : new ConfigurableLineTracker(lineDelimiters); setLineTracker(tracker); getTracker().set(content); completeInitialization(); }
Source:
<code>public void setClassName_throwOnLongClassName() { Realm realm = Realm.getInstance(configFactory.createConfigurationBuilder().build()); realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { realm.getSchema().create(MigrationPrimaryKey.CLASS_NAME); } }); realm.close(); RealmMigration migration = new RealmMigration() { @Override public void migrate(DynamicRealm realm, long oldVersion, long newVersion) { realm.getSchema() .get(MigrationPrimaryKey.CLASS_NAME) .setClassName("MigrationNameIsLongerThan56charThisShouldThrowAnException"); } }; RealmConfiguration realmConfig = configFactory.createConfigurationBuilder() .schemaVersion(1) .migration(migration) .build(); try { Realm.getInstance(realmConfig); fail(); } catch (IllegalArgumentException expected) { <START> assertEquals("Class name is to long. Limit is 57 characters: 'MigrationNameIsLongerThan56charThisShouldThrowAnException' (57)", <END> expected.getMessage()); } }</code><technical_language>for word 57 chars long said, sentence is a bit weird. If limit is 57 I read inclusive, rephrase "Limit is 56 characters..."</technical_language>

Target:
public void setClassName_throwOnLongClassName() { Realm realm = Realm.getInstance(configFactory.createConfigurationBuilder().build()); realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { realm.getSchema().create(MigrationPrimaryKey.CLASS_NAME); } }); realm.close(); RealmMigration migration = new RealmMigration() { @Override public void migrate(DynamicRealm realm, long oldVersion, long newVersion) { realm.getSchema() .get(MigrationPrimaryKey.CLASS_NAME) .setClassName("MigrationNameIsLongerThan56charThisShouldThrowAnException"); } }; RealmConfiguration realmConfig = configFactory.createConfigurationBuilder() .schemaVersion(1) .migration(migration) .build(); try { Realm.getInstance(realmConfig); fail(); } catch (IllegalArgumentException expected) { assertEquals("Class name is to long. Limit is 56 characters: 'MigrationNameIsLongerThan56charThisShouldThrowAnException' (57)", expected.getMessage()); } }
Source:
<code><START> } catch (ClassNotFoundException onlyIfOpenTestIsNotAvailable) { <END> try { Class.forName("junit.framework.ComparisonFailure"); theFactory = new ExceptionFactoryImpl() { @Override public AssertionError create(String message, String wanted, String actual) { return new org.mockito.exceptions.verification.junit.ArgumentsAreDifferent(message, wanted, actual); } }; } catch (ClassNotFoundException onlyIfJUnitIsNotAvailable) { } }</code><technical_language>this a more robust, DRYer: java ExceptionFactoryImpl theFactory = null; String[] paths = { "org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent", "org.mockito.exceptions.verification.junit.ArgumentsAreDifferent" }; Constructor<?> constructor = null; for(String path : paths) { try { Class<?> c = Class.forName(path); constructor = c.getConstructor(String.class, String.class, String.class); } catch (ClassNotFoundException | NoSuchMethodException e) { // skip try next } } if(constructor != null) { final Constructor constructor1 = constructor; theFactory = (message, wanted, actual) -> { try { return (AssertionError) constructor1.newInstance(message, wanted, actual); } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { throw new RuntimeException("failed instantiate AssertionError", e); } }; } else { theFactory = (message, wanted, actual) -> { return new ArgumentsAreDifferent(message, wanted, actual); }; }</technical_language>

Target:
} catch (ClassNotFoundException onlyIfOpenTestIsNotAvailable) { try { Class.forName("junit.framework.ComparisonFailure"); theFactory = org.mockito.exceptions.verification.junit.ArgumentsAreDifferent::new; } catch (ClassNotFoundException onlyIfJUnitIsNotAvailable) { } }
Source:
<code>private static void spawnMob(final IEssentials ess, final Server server, final CommandSource sender, final User target, final Location sloc, List<String> parts, List<String> data) throws Exception { Mob mob; Entity spawnedMob = null; Entity spawnedMount; for (int i = 0; i < parts.size(); i++) { if (i == 0) { mob = Mob.fromName(parts.get(i)); spawnedMob = mob.spawn(sloc.getWorld(), server, sloc); defaultMobData(mob.getType(), spawnedMob); if (data.get(i) != null) { changeMobData(sender, mob.getType(), spawnedMob, data.get(i).toLowerCase(Locale.ENGLISH), target); } } int next = (i + 1); if (next < parts.size()) { Mob mMob = Mob.fromName(parts.get(next)); spawnedMount = mMob.spawn(sloc.getWorld(), server, sloc); defaultMobData(mMob.getType(), spawnedMount); if (data.get(next) != null) { changeMobData(sender, mMob.getType(), spawnedMount, data.get(next).toLowerCase(Locale.ENGLISH), target); } <START> if (spawnedMob != null) { <END> spawnedMob.setPassenger(spawnedMount); } spawnedMob = spawnedMount; } } }</code><technical_language>spawnedMob is null (or bad happen). Revert change. If want fix compiler madness, rewrite this bad</technical_language>

Target:
private static void spawnMob(final IEssentials ess, final Server server, final CommandSource sender, final User target, final Location sloc, List<String> parts, List<String> data) throws Exception { Mob mob; Entity spawnedMob = null; Entity spawnedMount; for (int i = 0; i < parts.size(); i++) { if (i == 0) { mob = Mob.fromName(parts.get(i)); spawnedMob = mob.spawn(sloc.getWorld(), server, sloc); defaultMobData(mob.getType(), spawnedMob); if (data.get(i) != null) { changeMobData(sender, mob.getType(), spawnedMob, data.get(i).toLowerCase(Locale.ENGLISH), target); } } int next = (i + 1); if (next < parts.size()) { Mob mMob = Mob.fromName(parts.get(next)); spawnedMount = mMob.spawn(sloc.getWorld(), server, sloc); defaultMobData(mMob.getType(), spawnedMount); if (data.get(next) != null) { changeMobData(sender, mMob.getType(), spawnedMount, data.get(next).toLowerCase(Locale.ENGLISH), target); } spawnedMob.setPassenger(spawnedMount); spawnedMob = spawnedMount; } } }
Source:
<code><START> public void testQuery1() throws IOException, ClassNotFoundException { <END> check("SELECT dc:title, dc:dublincore FROM Document " + "WHERE dc:created > TIMESTAMP '2007-02-03 0:0'"); }</code><technical_language>In tests throws Exception</technical_language>

Target:
public void testQuery1() throws Exception { check("SELECT dc:title, dc:dublincore FROM Document " + "WHERE dc:created > TIMESTAMP '2007-02-03 0:0'"); }
Source:
<code>public void testSubarticleDoi() throws IOException { ImmutableMap<String, ? extends Map<String, ?>> itemTable = new ImmutableMap.Builder<String, Map<String, ?>>() .put("10.1371/journal.pone.0207232.r001", ImmutableMap.of( "doi", "10.1371/journal.pone.0207232.r001", "itemType", "reviewLetter", "files", ImmutableMap.of("letter", ImmutableMap.of( "crepoKey", "info:doi/10.1371/journal.pone.0207232.r001.xml", "crepoUuid", UUID.randomUUID().toString() )) )).build(); PeerReviewService serviceWithMockedContent = getServiceWithMockedContent(); String html = serviceWithMockedContent.asHtml(itemTable); <START> System.out.println(html); <END> Document d = Jsoup.parse(html); assertThat(d.select(".review-history .review__doi").get(0).text(), containsString("<LINK_0>")); }</code><technical_language>Debugging statement</technical_language>

Target:
public void testSubarticleDoi() throws IOException { ImmutableMap<String, ? extends Map<String, ?>> itemTable = new ImmutableMap.Builder<String, Map<String, ?>>() .put("10.1371/journal.pone.0207232.r001", ImmutableMap.of( "doi", "10.1371/journal.pone.0207232.r001", "itemType", "reviewLetter", "files", ImmutableMap.of("letter", ImmutableMap.of( "crepoKey", "info:doi/10.1371/journal.pone.0207232.r001.xml", "crepoUuid", UUID.randomUUID().toString() )) )).build(); PeerReviewService serviceWithMockedContent = getServiceWithMockedContent(); String html = serviceWithMockedContent.asHtml(itemTable); Document d = Jsoup.parse(html); assertThat(d.select(".review-history .review__doi").get(0).text(), containsString("<LINK_0>")); }
Source:
<code>public Optional<TextStyle.Base> getById(String id) { if (id.equals("NONE")) { <START> return Optional.of((TextStyle.Base) TextStyles.NONE); <END> } return Optional.ofNullable(textStyleMappings.get(Namespaces.namespacedId(id))); }</code><technical_language>Potential NPE. Flip this statement</technical_language>

Target:
public Optional<TextStyle.Base> getById(String id) { if (id.equals("NONE")) { return Optional.of((TextStyle.Base) TextStyles.NONE); } return Optional.ofNullable(textStyleMappings.get(Preconditions.checkNotNull(id))); }
Source:
<code>public void write(int i) throws IOException { <START> byte[] b = ByteBuffer.allocate(4).putInt(i).array(); <END> write(b); }</code><technical_language>worries, a pair of eyes is good for</technical_language>

Target:
public void write(int i) throws IOException { singleByte[0] = (byte)(i & 0xff); write(singleByte); }
Source:
<code><START> default List<@NonNull ITmfCallsite> getCallsites() { <END> ITmfCallsite callsite = getCallsite(); if (callsite == null) { return null; } return Collections.singletonList(callsite); }</code><technical_language>line? I 'default @Nullable List'</technical_language>

Target:
default @Nullable List<@NonNull ITmfCallsite> getCallsites() { ITmfCallsite callsite = getCallsite(); if (callsite == null) { return null; } return Collections.singletonList(callsite); }