auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public @Nullable Object resolve(@NonNull ISegment segment) { if (segment instanceof CalledFunction) { CalledFunction calledFunction = (CalledFunction) segment; ITmfTrace trace = TmfTraceManager.getInstance().getActiveTrace(); if (trace != null) { String symbolText; ISymbolProvider provider = SymbolProviderManager.getInstance().getSymbolProvider(trace); <START> if (calledFunction.getSymbol() instanceof ITmfStateValue) { <END> ITmfStateValue symbol = ((ITmfStateValue) calledFunction.getSymbol()); switch (symbol.getType()) { case LONG: Long longAddress = symbol.unboxLong(); symbolText = provider.getSymbolText(longAddress); if (symbolText == null) { return "0x" + Long.toHexString(longAddress); } return symbolText; case STRING: return symbol.unboxStr(); case INTEGER: Integer intAddress = symbol.unboxInt(); symbolText = provider.getSymbolText(intAddress); if (symbolText == null) { return "0x" + Integer.toHexString(intAddress); } return symbolText; case DOUBLE: case NULL: case CUSTOM: default: break; } } } } return null; }</code><technical_language>symbol ITmfStateValue, remain Object? Also, is symbol term for 'function name address'</technical_language>

Target:
public @Nullable Object resolve(@NonNull ISegment segment) { if (segment instanceof ICalledFunction) { ICalledFunction calledFunction = (ICalledFunction) segment; ITmfTrace trace = TmfTraceManager.getInstance().getActiveTrace(); if (trace != null) { String symbolText; ISymbolProvider provider = SymbolProviderManager.getInstance().getSymbolProvider(trace); if (calledFunction.getSymbol() instanceof ITmfStateValue) { ITmfStateValue symbol = ((ITmfStateValue) calledFunction.getSymbol()); switch (symbol.getType()) { case LONG: Long longAddress = symbol.unboxLong(); symbolText = provider.getSymbolText(longAddress); if (symbolText == null) { return "0x" + Long.toHexString(longAddress); } return symbolText; case STRING: return symbol.unboxStr(); case INTEGER: Integer intAddress = symbol.unboxInt(); symbolText = provider.getSymbolText(intAddress); if (symbolText == null) { return "0x" + Integer.toHexString(intAddress); } return symbolText; case DOUBLE: case NULL: case CUSTOM: default: break; } } } } return null; }
Source:
<code>protected Object innerCall() throws Exception { final TransactionContext context = endpoint.getTransactionContext(parameters.txnId); final TransactionalQueue queue = context.getQueue(parameters.name); <START> return queue.addAll(parameters.items); <END> }</code><technical_language>do utilize timeout</technical_language>

Target:
protected Object innerCall() throws Exception { final TransactionContext context = endpoint.getTransactionContext(parameters.txnId); final TransactionalQueue queue = context.getQueue(parameters.name); return queue.addAll(parameters.items, parameters.timeout, TimeUnit.MILLISECONDS); }
Source:
<code>public void rconLogoutCallback(CallbackInfo ci) { if (this.loggedIn) { <START> ((SpongeScheduler) Sponge.getServer().getScheduler()).callSync(() -> { <END> final CauseStackManager causeStackManager = Sponge.getCauseStackManager(); causeStackManager.pushCause(this); causeStackManager.pushCause(this.source); final RconConnectionEvent.Disconnect event = SpongeEventFactory.createRconConnectionEventDisconnect( causeStackManager.getCurrentCause(), (RconSource) this.source); SpongeImpl.postEvent(event); causeStackManager.popCauses(2); return event; }); } }</code><technical_language>this a method already..... skip casting...</technical_language>

Target:
public void rconLogoutCallback(CallbackInfo ci) { if (this.loggedIn) { ServerInternal.SCHEDULER.callSync(() -> { final CauseStackManager causeStackManager = Sponge.getCauseStackManager(); causeStackManager.pushCause(this); causeStackManager.pushCause(this.source); final RconConnectionEvent.Disconnect event = SpongeEventFactory.createRconConnectionEventDisconnect( causeStackManager.getCurrentCause(), (RconSource) this.source); SpongeImpl.postEvent(event); causeStackManager.popCauses(2); return event; }); } }
Source:
<code>public int hashCode() { <START> int hashCode = name.hashCode(); <END> hashCode += Boolean.valueOf(exclusiveGroup).hashCode(); for (final PermissionRule r : rules) { hashCode += r.hashCode(); } return hashCode; }</code><technical_language>name enough for hash code of permission. a container of Permission objects tend object Permission. rules nested contribute hash code. bad form mutable state part of hashcode. name change. rules are</technical_language>

Target:
public int hashCode() { return name.hashCode(); }
Source:
<code>public ClientType getClientType() { <START> return null; <END> }</code><technical_language>this problems on? define "UNKNOWN" for example</technical_language>

Target:
public ClientType getClientType() { return ClientType.UNKNOWN; }
Source:
<code>public static <E extends RealmModel> void addChangeListener(E object, RealmChangeListener<E> listener) { if (listener == null) { throw new IllegalArgumentException("Listener should not be null"); } if (object instanceof RealmObjectProxy) { RealmObjectProxy proxy = (RealmObjectProxy) object; BaseRealm realm = proxy.realmGet$proxyState().getRealm$realm(); realm.checkIfValid(); if (realm.handler == null) { throw new IllegalStateException("You can't register a listener from a non-Looper thread "); } List<RealmChangeListener> listeners = proxy.realmGet$proxyState().getListeners$realm(); if (!listeners.contains(listener)) { listeners.add(listener); } if (isLoaded(object)) { <START> realm.handlerController.addToRealmObjects((RealmObjectProxy)object); <END> } } else { throw new IllegalArgumentException("Cannot add listener from this unmanaged RealmObject (created outside of Realm)"); } }</code><technical_language>cast object proxy, instead</technical_language>

Target:
public static <E extends RealmModel> void addChangeListener(E object, RealmChangeListener<E> listener) { if (listener == null) { throw new IllegalArgumentException("Listener should not be null"); } if (object instanceof RealmObjectProxy) { RealmObjectProxy proxy = (RealmObjectProxy) object; BaseRealm realm = proxy.realmGet$proxyState().getRealm$realm(); realm.checkIfValid(); if (realm.handler == null) { throw new IllegalStateException("You can't register a listener from a non-Looper thread "); } List<RealmChangeListener> listeners = proxy.realmGet$proxyState().getListeners$realm(); if (!listeners.contains(listener)) { listeners.add(listener); } if (isLoaded(proxy)) { realm.handlerController.addToRealmObjects(proxy); } } else { throw new IllegalArgumentException("Cannot add listener from this unmanaged RealmObject (created outside of Realm)"); } }
Source:
<code>protected @NonNull TmfViewer createLeftChildViewer(@Nullable Composite parent) { String analysisId = fViewInfo.getViewAnalysisId(); return new AbstractSegmentStoreScatterChartTreeViewer(Objects.requireNonNull(parent), <START> String.valueOf(analysisId)); <END> }</code><technical_language>analysisId is a String</technical_language>

Target:
protected @NonNull TmfViewer createLeftChildViewer(@Nullable Composite parent) { String analysisId = fViewInfo.getViewAnalysisId(); return new AbstractSegmentStoreScatterChartTreeViewer(Objects.requireNonNull(parent), String.valueOf(analysisId)) { @Override protected @NonNull String getAnalysisId() { String viewAnalysisId = fViewInfo.getViewAnalysisId(); return viewAnalysisId == null ? super.getAnalysisId() : viewAnalysisId; } }; }
Source:
<code>public static Optional<InsightCard> processSleepAlarm(final Long accountId, final List<Integer> wakeTimeList, final Integer userAge) { if (wakeTimeList.isEmpty()) { LOGGER.debug("Got nothing in wakeTimeList"); <START> return Optional.absent(); <END> } else if (wakeTimeList.size() <= 2) { LOGGER.debug("Size of wakeTimeList is less than 2 for accountId {}", accountId); return Optional.absent(); } final DescriptiveStatistics stats = new DescriptiveStatistics(); for (final int wakeTime : wakeTimeList) { stats.addValue(wakeTime); } final Boolean passSafeGuards = checkSafeGuards(stats); if (!passSafeGuards) { return Optional.absent(); } final Double wakeAvgDouble = stats.getMean(); final int wakeAvg = (int) Math.round(wakeAvgDouble); final int recSleepDurationMins = getRecommendedSleepDurationMinutes(userAge); final int recommendedSleepMinutesTime = wakeAvg - recSleepDurationMins; final String wakeTime = InsightUtils.timeConvert(wakeAvg); final String preSleepTime = InsightUtils.timeConvert((recommendedSleepMinutesTime - PRE_SLEEP_TIME)); final String sleepTime = InsightUtils.timeConvert(recommendedSleepMinutesTime); final Text text = SleepAlarmMsgEN.getSleepAlarmMessage(wakeTime, recSleepDurationMins, preSleepTime, sleepTime); return Optional.of(new InsightCard(accountId, text.title, text.message, InsightCard.Category.SLEEP_TIME, InsightCard.TimePeriod.MONTHLY, DateTime.now(DateTimeZone.UTC), InsightCard.InsightType.DEFAULT)); }</code><technical_language>LOGGER.info, key=value format</technical_language>

Target:
public static Optional<InsightCard> processSleepAlarm(final Long accountId, final List<Integer> wakeTimeList, final Integer userAge) { if (wakeTimeList.isEmpty()) { LOGGER.info("account_id={}-insight=sleep_alarm-action=wake_time_list_empty", accountId); return processSleepAlarmFallBack(accountId); } else if (wakeTimeList.size() <= 2) { LOGGER.info("account_id={}-insight=sleep_alarm-action=wake_time_list_too_small", accountId); return processSleepAlarmFallBack(accountId); } final DescriptiveStatistics stats = new DescriptiveStatistics(); for (final int wakeTime : wakeTimeList) { stats.addValue(wakeTime); } final Boolean passSafeGuards = checkSafeGuards(stats); if (!passSafeGuards) { LOGGER.info("insight=sleep_alarm-account_id={}-action=fail_safe_guard"); return processSleepAlarmFallBack(accountId); } final Double wakeAvgDouble = stats.getMean(); final int wakeAvg = (int) Math.round(wakeAvgDouble); final int recSleepDurationMins = getRecommendedSleepDurationMinutes(userAge); final int recommendedSleepMinutesTime = wakeAvg - recSleepDurationMins; final String wakeTime = InsightUtils.timeConvert(wakeAvg); final String preSleepTime = InsightUtils.timeConvert((recommendedSleepMinutesTime - PRE_SLEEP_TIME)); final String sleepTime = InsightUtils.timeConvert(recommendedSleepMinutesTime); final Text text = SleepAlarmMsgEN.getSleepAlarmMessage(wakeTime, recSleepDurationMins, preSleepTime, sleepTime); return Optional.of(new InsightCard(accountId, text.title, text.message, InsightCard.Category.SLEEP_TIME, InsightCard.TimePeriod.MONTHLY, DateTime.now(DateTimeZone.UTC), InsightCard.InsightType.DEFAULT)); }
Source:
<code>RequestBuilder createKeepAliveRequest() { RequestBuilder builder = createRequest(); <START> builder.setHeader(ENGINE_REFRESH_HEADER, "refresh-only"); END> return builder; }</code><technical_language>good check server side perform refresh if specific is provided</technical_language>

Target:
RequestBuilder createKeepAliveRequest() { return createRequest(); }
Source:
<code>private Optional<Widget> toWidget(Object item) { if (item == null) { return handleNull(); } <START> if (item instanceof EasyForm) { <END> return of(((EasyForm) item).getView()); } Widget widget = MIMEContainerFactory.getTableDisplay(item); if (widget != null) { return of(widget); } if (item instanceof Widget) { return of((Widget) item); } if (item instanceof MIMEContainer) { return of(createHTML(((MIMEContainer) item).getData().toString())); } return of(createHTMLPre(item.toString())); }</code><technical_language>I suggest create interface "WidgetItem" getAsWIdget() method, EasyForm Widget implement interface. This allow get rid of "if statement" for Widget EasyForm</technical_language>

Target:
private Optional<Widget> toWidget(Object item) { if (item == null) { return handleNull(); } if (item instanceof WidgetItem) { return of(((WidgetItem) item).asWidget()); } Widget widget = MIMEContainerFactory.getTableDisplay(item); if (widget != null) { return of(widget); } if (item instanceof MIMEContainer) { return of(createHTML(((MIMEContainer) item).getData().toString())); } return of(createHTMLPre(item.toString())); }
Source:
<code>private boolean isWritable(ModelNode attrDescr) { <START> return !attrDescr.has(Util.ACCESS_TYPE) || !(Util.READ_ONLY.equals(attrDescr.get(Util.ACCESS_TYPE).asString()) || Util.METRIC.equals(attrDescr.get(Util.ACCESS_TYPE).asString())); <END> }</code><technical_language>I this condition starts a bit complex. rewritten in a more explicit way: private boolean isWritable(ModelNode attrDescr) { return !isReadOnly(attrDescr); } private boolean isReadOnly(ModelNode attrDescr) { return attrDescr.has(Util.ACCESS_TYPE) && (Util.READ_ONLY.equals(attrDescr.get(Util.ACCESS_TYPE).asString()) || Util.METRIC.equals(attrDescr.get(Util.ACCESS_TYPE).asString())); }</technical_language>

Target:
private boolean isWritable(ModelNode attrDescr) { return !isReadOnly(attrDescr); }
Source:
<code>private void internalDoFetch(RefSpec spec, String uri, boolean doCheckout, boolean doCreateTag, boolean doCreateBranch, boolean doActivateAdditionalRefs, String textForTag, String textForBranch, IProgressMonitor monitor) { int totalWork = 1; if (doCheckout) totalWork++; if (doCreateTag || doCreateBranch) totalWork++; monitor.beginTask( UIText.FetchGerritChangePage_GetChangeTaskName, totalWork); try { RevCommit commit = fetchChange(uri, spec, monitor); <START> if (doCreateTag) { <END> createTag(spec, textForTag, commit, monitor); } if (doCreateBranch) { createBranch(textForBranch, commit, monitor); } if (doCheckout || doCreateTag) { checkout(commit, monitor); } if (doActivateAdditionalRefs) { activateAdditionalRefs(); } storeLastUsedUri(uri); } catch (Exception e) { Activator .handleError(e.getCause().getMessage(), e.getCause(), true); } finally { monitor.done(); } }</code><technical_language>style nit: braces single line blocks</technical_language>

Target:
private void internalDoFetch(RefSpec spec, String uri, boolean doCheckout, boolean doCreateTag, boolean doCreateBranch, boolean doActivateAdditionalRefs, String textForTag, String textForBranch, IProgressMonitor monitor) { int totalWork = 1; if (doCheckout) totalWork++; if (doCreateTag || doCreateBranch) totalWork++; monitor.beginTask( UIText.FetchGerritChangePage_GetChangeTaskName, totalWork); try { RevCommit commit = fetchChange(uri, spec, monitor); if (doCreateTag) createTag(spec, textForTag, commit, monitor); if (doCreateBranch) createBranch(textForBranch, commit, monitor); if (doCheckout || doCreateTag) checkout(commit, monitor); if (doActivateAdditionalRefs) activateAdditionalRefs(); storeLastUsedUri(uri); } catch (Exception e) { Activator .handleError(e.getCause().getMessage(), e.getCause(), true); } finally { monitor.done(); } }
Source:
<code>public static int getMajorVersion(String stringToParse){ String fullVersion = getVersion(stringToParse); if(fullVersion != null) { int firstDot = fullVersion.indexOf('.'); if(firstDot >= 0) { return Integer.valueOf(fullVersion.substring(0, firstDot)); } } <START> return 0; <END> }</code><technical_language>0 is a bad exception I think, versions easily 0-based. -1</technical_language>

Target:
public static int getMajorVersion(String stringToParse){ String fullVersion = getVersion(stringToParse); if(fullVersion != null) { int firstDot = fullVersion.indexOf('.'); if(firstDot >= 0) { return Integer.valueOf(fullVersion.substring(0, firstDot)); } } return -1; }
Source:
<code>private void asyncProcessUploadedEnrichmentTags() { new Thread(new Runnable() { public void run() { uploadEnrichmentTagProcessor.processUploadedEnrichmentTags(); <START> runTagPostUploadProcessingJob(); <END> }; }).start(); }</code><technical_language>I move job execution processUploadedEnrichmentTags</technical_language>

Target:
private void asyncProcessUploadedEnrichmentTags() { new Thread(new Runnable() { public void run() { uploadEnrichmentTagProcessor.processUploadedEnrichmentTags(); }; }).start(); }
Source:
<code>public void testGetDefaultPool() throws Exception { final MacPool defaultPool = dao.getDefaultPool(); assertThat(defaultPool, notNullValue()); <START> assertThat(defaultPool.getId(), is(FixturesTool.DEFAULT_MAC_POOL_ID)); <END> }</code><technical_language>I additionally check isDefault is true</technical_language>

Target:
public void testGetDefaultPool() throws Exception { final MacPool defaultPool = dao.getDefaultPool(); assertThat(defaultPool, notNullValue()); assertThat(defaultPool.getId(), is(FixturesTool.DEFAULT_MAC_POOL_ID)); assertThat(defaultPool.isDefaultPool(), is(true)); }
Source:
<code>private void updateVmDeviceWithDataReturnedFromHost(VDSReturnValue vdsReturnValue) { if (vdsReturnValue.getSucceeded() && getParameters().getAction() == PlugAction.PLUG) { VmInfoReturn vmInfoReturn = (VmInfoReturn) vdsReturnValue.getReturnValue(); if (vmInfoReturn.getVmInfo() != null) { Map<String, Object> vmInfo = (Map<String, Object>) vmInfoReturn.getVmInfo(); for (Object o : (Object[]) vmInfo.get(VdsProperties.Devices)) { Map<String, Object> vdsmDevice = (Map<String, Object>) o; if (vmDevice.getId() .getDeviceId() .toString() <START> .equals((String) vdsmDevice.get(VdsProperties.DeviceId))) <END> { vmDevice.setAddress(vdsmDevice.get(VdsProperties.Address).toString()); vmDevice.setAlias(StringUtils.defaultString((String) vdsmDevice.get(VdsProperties.Alias))); } } } } }</code><technical_language>is casting needed here</technical_language>

Target:
private void updateVmDeviceWithDataReturnedFromHost(VDSReturnValue vdsReturnValue) { if (vdsReturnValue.getSucceeded() && getParameters().getAction() == PlugAction.PLUG) { VmInfoReturn vmInfoReturn = (VmInfoReturn) vdsReturnValue.getReturnValue(); if (vmInfoReturn.getVmInfo() != null) { Map<String, Object> vmInfo = (Map<String, Object>) vmInfoReturn.getVmInfo(); for (Object o : (Object[]) vmInfo.get(VdsProperties.Devices)) { Map<String, Object> vdsmDevice = (Map<String, Object>) o; if (vmDevice.getId().getDeviceId().toString().equals(vdsmDevice.get(VdsProperties.DeviceId))) { vmDevice.setAddress(vdsmDevice.get(VdsProperties.Address).toString()); vmDevice.setAlias(StringUtils.defaultString((String) vdsmDevice.get(VdsProperties.Alias))); } } } } }
Source:
<code>public boolean equalsToClassName(String name) { <START> return memberName == null && className != null && className.equals(name); <END> }</code><technical_language>This returns false if memberName is set. I expect, though, function name. comparing class name, I expect test class name class name, of state of other members</technical_language>

Target:
private boolean equalsToClassName(String name) { return memberName == null && className != null && className.equals(name); }
Source:
<code>public RequestMatcher value(String parameter, String... expectedValues) { List<Matcher<? super String>> matcherList = Arrays.stream(expectedValues) .map(Matchers::equalTo) .collect(Collectors.toList()); <START> return this.value(parameter, matcherList); <END> }</code><technical_language>this" for methods</technical_language>

Target:
public RequestMatcher value(String parameter, String... expectedValues) { List<Matcher<? super String>> matcherList = Arrays.stream(expectedValues) .map(Matchers::equalTo) .collect(Collectors.toList()); return value(parameter, matcherList); }
Source:
<code>protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) throws NotEnoughArgumentsException, ChargeException, MaxMoneyException { switch (cmd) { case GIVE: if (isPercent) <START> player.percentHandler(amount, sender, UserBalanceUpdateEvent.Cause.COMMAND_ECO, 0); <END> else player.giveMoney(amount, sender, UserBalanceUpdateEvent.Cause.COMMAND_ECO); break; case TAKE: take(amount, player, sender); break; case RESET: case SET: set(amount, player, sender); break; } }</code><technical_language>Please refactor lines of 'giveMoneyPercent' instead of magic values a switch</technical_language>

Target:
protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) throws NotEnoughArgumentsException, ChargeException, MaxMoneyException { if (isPercent && cmd != EcoCommands.RESET) { amount = player.getMoney().multiply(amount).scaleByPowerOfTen(-2); } switch (cmd) { case GIVE: player.giveMoney(amount, sender, UserBalanceUpdateEvent.Cause.COMMAND_ECO); break; case TAKE: take(amount, player, sender); break; case RESET: case SET: set(amount, player, sender); break; } }
Source:
<code>public final Object visitGetKeysInGroupCommand(InvocationContext ctx, GetKeysInGroupCommand command) throws Throwable { if (command.isGroupOwner()) { return invokeNext(ctx, command); } Address primaryOwner = dm.getCacheTopology().getDistribution(command.getGroupName()).primary(); CompletionStage<Map<Address, Response>> future = <START> rpcManager.invokeCommand(primaryOwner, command, new MapResponseCollector(false, 1), <END> rpcManager.getSyncRpcOptions()); return asyncInvokeNext(ctx, command, future.thenAccept(responses -> { if (!responses.isEmpty()) { Response response = responses.values().iterator().next(); if (response instanceof SuccessfulResponse) { List<CacheEntry> cacheEntries = (List<CacheEntry>) ((SuccessfulResponse) response).getResponseValue(); for (CacheEntry entry : cacheEntries) { wrapRemoteEntry(ctx, entry.getKey(), entry, false); } } } })); }</code><technical_language>SingleResponseCollector</technical_language>

Target:
public final Object visitGetKeysInGroupCommand(InvocationContext ctx, GetKeysInGroupCommand command) throws Throwable { if (command.isGroupOwner()) { return invokeNext(ctx, command); } Address primaryOwner = dm.getCacheTopology().getDistribution(command.getGroupName()).primary(); CompletionStage<ValidResponse> future = rpcManager.invokeCommand(primaryOwner, command, SingleResponseCollector.validOnly(), rpcManager.getSyncRpcOptions()); return asyncInvokeNext(ctx, command, future.thenAccept(response -> { if (response instanceof SuccessfulResponse) { List<CacheEntry> cacheEntries = (List<CacheEntry>) response.getResponseValue(); for (CacheEntry entry : cacheEntries) { wrapRemoteEntry(ctx, entry.getKey(), entry, false); } } })); }
Source:
<code>public Collection<String> getArchitectureViewpointIds() { ArchitectureDescriptionPreferences preferences = SashModelUtils.getArchitectureDescriptionPreferences(modelSet); if (preferences != <START> null) <END> return preferences.getViewpointIds(); Set<String> viewpointIds = new LinkedHashSet<String>(); MergedArchitectureContext context = getArchitectureContext(); if (context != null) { Collection<MergedArchitectureViewpoint> viewpoints = context.getDefaultViewpoints(); if (viewpoints.isEmpty()) viewpoints = context.getViewpoints(); for (MergedArchitectureViewpoint viewpoint : viewpoints) { viewpointIds.add(viewpoint.getId()); } } return viewpointIds; }</code><technical_language>missing loop. formater applied</technical_language>

Target:
public Collection<String> getArchitectureViewpointIds() { ArchitectureDescriptionPreferences preferences = SashModelUtils.getArchitectureDescriptionPreferences(modelSet); if (preferences != null) { return preferences.getViewpointIds(); } Set<String> viewpointIds = new LinkedHashSet<String>(); MergedArchitectureContext context = getArchitectureContext(); if (context != null) { Collection<MergedArchitectureViewpoint> viewpoints = context.getDefaultViewpoints(); if (viewpoints.isEmpty()) { viewpoints = context.getViewpoints(); } for (MergedArchitectureViewpoint viewpoint : viewpoints) { viewpointIds.add(viewpoint.getId()); } } return viewpointIds; }
Source:
<code>private ColumnChunk readPrimitive(PrimitiveField field) throws IOException { ColumnDescriptor columnDescriptor = field.getDescriptor(); PrimitiveColumnReader columnReader = columnReaders[field.getId()]; if (columnReader.getPageReader() == null) { validateParquet(currentBlockMetadata.getRowCount() > 0, "Row group has 0 rows"); ColumnChunkMetaData metadata = getColumnChunkMetaData(columnDescriptor); long startingPosition = metadata.getStartingPos(); int totalSize = toIntExact(metadata.getTotalSize()); byte[] buffer = allocateBlock(totalSize); dataSource.readFully(startingPosition, buffer); ColumnChunkDescriptor descriptor = new ColumnChunkDescriptor(columnDescriptor, metadata, totalSize); ParquetColumnChunk columnChunk = new ParquetColumnChunk(descriptor, buffer, 0); columnReader.setPageReader(columnChunk.readAllPages()); } try { return columnReader.readPrimitive(field); } catch (UnsupportedOperationException e) { <START> throw new PrestoException(INVALID_SCHEMA_PROPERTY, format("There is a mismatch between file schema and partition schema. The column %s in file %s is declared as type %s but parquet file declared column type as %s.", <END> Joiner.on(".").join(columnDescriptor.getPath()), dataSource.getId(), field.getType(), columnDescriptor.getType())); } }</code><technical_language>about: column %s is declared type %s, Parquet file %s declares column type %s</technical_language>

Target:
private ColumnChunk readPrimitive(PrimitiveField field) throws IOException { ColumnDescriptor columnDescriptor = field.getDescriptor(); PrimitiveColumnReader columnReader = columnReaders[field.getId()]; if (columnReader.getPageReader() == null) { validateParquet(currentBlockMetadata.getRowCount() > 0, "Row group has 0 rows"); ColumnChunkMetaData metadata = getColumnChunkMetaData(columnDescriptor); long startingPosition = metadata.getStartingPos(); int totalSize = toIntExact(metadata.getTotalSize()); byte[] buffer = allocateBlock(totalSize); dataSource.readFully(startingPosition, buffer); ColumnChunkDescriptor descriptor = new ColumnChunkDescriptor(columnDescriptor, metadata, totalSize); ParquetColumnChunk columnChunk = new ParquetColumnChunk(descriptor, buffer, 0); columnReader.setPageReader(columnChunk.readAllPages()); } return columnReader.readPrimitive(field); }
Source:
<code>public byte[] getAPIData() { ByteArrayOutputStream data = new ByteArrayOutputStream(); try { if (rfData != null) data.write(rfData); } catch (IOException e) { <START> e.printStackTrace(); <END> } return data.toByteArray(); }</code><technical_language>if want print out exception</technical_language>

Target:
public byte[] getAPIData() { ByteArrayOutputStream data = new ByteArrayOutputStream(); try { if (rfData != null) data.write(rfData); } catch (IOException e) { } return data.toByteArray(); }
Source:
<code>protected void updateEmulatedMachines() { if (getModel().getSelectedCluster() == null) { return; } EmulatedMachine oldVal = getModel().getEmulatedMachine().getSelectedItem(); Collection<EmulatedMachine> emList = new ArrayList<>(); if (getModel().getSelectedCluster().getArchitecture().getFamily() == ArchitectureType.ppc) { emList.add(EmulatedMachine.pseries); <START> } else { <END> emList.add(EmulatedMachine.i440fx_seabios); emList.add(EmulatedMachine.q35_ovmf); emList.add(EmulatedMachine.q35_secureboot); } getModel().getEmulatedMachine().setItems(emList); if (oldVal != null) { getModel().getEmulatedMachine().setSelectedItem(oldVal); } }</code><technical_language>need explicitely add null if want selectable. - this account selected OS. Ideally, fill this list values returned osinfo</technical_language>

Target:
protected void updateEmulatedMachines() { if (getModel().getSelectedCluster() == null) { return; } Collection<EmulatedMachine> emList = new ArrayList<>(); emList.add(null); if (!getModel().getEmulatedMachine().getIsChangable()) { getModel().getEmulatedMachine().setItems(emList); return; } if (getModel().getSelectedCluster().getArchitecture().getFamily() == ArchitectureType.ppc) { emList.add(EmulatedMachine.pseries); } else { emList.add(EmulatedMachine.i440fx_seabios); emList.add(EmulatedMachine.q35_ovmf); emList.add(EmulatedMachine.q35_secureboot); } getModel().getEmulatedMachine().setItems(emList); EmulatedMachine em = AsyncDataProvider.getInstance().emulatedMachineByOs(getModel().getOSType().getSelectedItem()); if (emList.contains(em)) { getModel().getEmulatedMachine().setSelectedItem(em); } }
Source:
<code>public void preprocess(DataSetLookup lookup) { if (identityProvider == null) { return; } final List<Comparable> orgEntities = new ArrayList<Comparable>(identityProvider.getRoles()); orgEntities.add(identityProvider.getName()); final ColumnFilter columnFilter = equalsTo(COLUMN_ORGANIZATIONAL_ENTITY, orgEntities); LOGGER.debug("Adding column filter: {}", columnFilter); if (lookup.getFirstFilterOp() != null) { lookup.getFirstFilterOp().addFilterColumn(columnFilter); } else { DataSetFilter filter = new DataSetFilter(); filter.addFilterColumn(columnFilter); lookup.addOperation(filter); } <START> if (lookup.getLastGroupOp() == null) { <END> DataSetGroup gOp = new DataSetGroup(); gOp.setColumnGroup(new ColumnGroup(COLUMN_TASKID, COLUMN_TASKID)); for (String columnId : metadata.getColumnIds()) { AggregateFunctionType functionType = null; if (columnId.equals(COLUMN_TASKID)) { functionType = AggregateFunctionType.DISTINCT; } gOp.addGroupFunction(new GroupFunction(columnId, columnId, functionType)); } lookup.addOperation(gOp); } }</code><technical_language>extracted in util method reusable logic</technical_language>

Target:
public void preprocess(DataSetLookup lookup) { if (identityProvider == null) { return; } final List<Comparable> orgEntities = new ArrayList<Comparable>(identityProvider.getRoles()); orgEntities.add(identityProvider.getName()); final ColumnFilter columnFilter = equalsTo(COLUMN_ORGANIZATIONAL_ENTITY, orgEntities); LOGGER.debug("Adding column filter: {}", columnFilter); if (lookup.getFirstFilterOp() != null) { lookup.getFirstFilterOp().addFilterColumn(columnFilter); } else { DataSetFilter filter = new DataSetFilter(); filter.addFilterColumn(columnFilter); lookup.addOperation(filter); } super.preprocess(lookup); }
Source:
<code>public Seq<T> next() { if (!hasNext()) { throw new NoSuchElementException(); } final Seq<T> result = buffer; <START> buffer = that.hasNext() ? that.drop(gap).take(step).toList().prependAll(buffer.drop(step)) : buffer.take(0); <END> return result; }</code><technical_language>* drop(...).take(...) a slice * appendAll also, more intuitive start prefix (it's implemented prependAll in List anyway)</technical_language>

Target:
public Seq<T> next() { if (buffer.length == 0) { throw new NoSuchElementException(); } final Object[] result = buffer; if (that.hasNext()) { buffer = new Object[size]; if (preserve > 0) { System.arraycopy(result, step, buffer, 0, preserve); } if (gap > 0) { drop(that, gap); buffer = take(that, buffer, preserve, size); } else { buffer = take(that, buffer, preserve, step); } } else { buffer = new Object[0]; } return Array.wrap(result); }
Source:
<code>@Override public void execute(final Callback callback) { new Thread(new Runnable() { @Override public void run() { try { String apiKey = IMGUR_apiKey; <START> if (new Random().nextInt(2) == 1) { <END> apiKey = "foobar"; } HttpRequest request = post(IMGUR_UPLOAD_URL) .part("key", apiKey) .part("image", file); if (request.ok()) { Matcher m = IMGUR_URL_REGEX.matcher(request.body()); m.find(); final String url = m.group(1); Log.i(TAG, "Upload success! " + url); MAIN_THREAD.post(new Runnable() { @Override public void run() { callback.onSuccess(url); } }); } else { Log.i(TAG, String.format( "Upload failed :( Will retry in %d seconds.", RETRY_WAIT / 1000)); try { Thread.sleep(RETRY_WAIT); } catch (InterruptedException e) { e.printStackTrace(); } MAIN_THREAD.post(new Runnable() { @Override public void run() { callback.onFailure(); } }); } } catch (RuntimeException e) { e.printStackTrace(); throw e; } } }).start(); }</code><technical_language>new Random().nextBoolean()</technical_language>

Target:
@Override public void execute(final Callback callback) { new Thread(new Runnable() { @Override public void run() { try { String apiKey = IMGUR_API_KEY; if (new Random().nextBoolean()) { apiKey = "foobar"; } HttpRequest request = post(IMGUR_UPLOAD_URL) .part("key", apiKey) .part("image", file); if (request.ok()) { Matcher m = IMGUR_URL_REGEX.matcher(request.body()); m.find(); final String url = m.group(1); Log.i(TAG, "Upload success! " + url); MAIN_THREAD.post(new Runnable() { @Override public void run() { callback.onSuccess(url); } }); } else { Log.i(TAG, String.format( "Upload failed :( Will retry in %d seconds.", RETRY_WAIT / 1000)); try { Thread.sleep(RETRY_WAIT); } catch (InterruptedException e) { e.printStackTrace(); throw new RuntimeException(e); } MAIN_THREAD.post(new Runnable() { @Override public void run() { callback.onFailure(); } }); } } catch (RuntimeException e) { e.printStackTrace(); throw e; } } }).start(); }
Source:
<code>public Void visitInsert(Insert<?> node, Integer indent) { append(indent, "INSERT"); builder.append(' '); append(indent, "INTO"); builder.append(' '); node.table().accept(this, indent); builder.append(' '); var columns = node.columns().iterator(); if (columns.hasNext()) { builder.append('('); while (columns.hasNext()) { builder.append(columns.next()); if (columns.hasNext()) { builder.append(", "); } } builder.append(')'); } builder.append(' '); node.insertSource().accept(this, indent); <START> var returning = node.returningClause().iterator(); <END> if (returning.hasNext()) { append(indent, "RETURNING"); while (returning.hasNext()) { builder.append(' '); returning.next().accept(this, indent); if (returning.hasNext()) { builder.append(','); } } } return null; }</code><technical_language>onConflict missing here</technical_language>

Target:
public Void visitInsert(Insert<?> node, Integer indent) { append(indent, "INSERT"); builder.append(' '); append(indent, "INTO"); builder.append(' '); node.table().accept(this, indent); builder.append(' '); var columns = node.columns().iterator(); if (columns.hasNext()) { builder.append('('); while (columns.hasNext()) { builder.append(columns.next()); if (columns.hasNext()) { builder.append(", "); } } builder.append(')'); } builder.append(' '); node.insertSource().accept(this, indent); var duplicateKeyContext = node.duplicateKeyContext(); if (duplicateKeyContext.getType() != NONE) { builder.append(" ON CONFLICT"); var constraintColumns = duplicateKeyContext.getConstraintColumns().iterator(); if (constraintColumns.hasNext()) { builder.append(" ("); while (constraintColumns.hasNext()) { builder.append(constraintColumns.next()); if (constraintColumns.hasNext()) { builder.append(", "); } } builder.append(')'); } switch (duplicateKeyContext.getType()) { case ON_CONFLICT_DO_NOTHING: builder.append(" DO NOTHING"); break; case ON_CONFLICT_DO_UPDATE_SET: builder.append(" DO UPDATE"); var assignments = duplicateKeyContext.getAssignments().iterator(); if (assignments.hasNext()) { builder.append(" SET "); while (assignments.hasNext()) { assignments.next().accept(this, indent); if (assignments.hasNext()) { builder.append(", "); } } } break; case NONE: default: } } var returning = node.returningClause().iterator(); if (returning.hasNext()) { append(indent, "RETURNING"); while (returning.hasNext()) { builder.append(' '); returning.next().accept(this, indent); if (returning.hasNext()) { builder.append(','); } } } return null; }
Source:
<code>public static void loadSortListFromJSONArray(List<AbstractExpression> sortExpressions, List<SortDirectionType> sortDirections, JSONObject jobj) throws JSONException { if (jobj.has(AbstractExpression.SortMembers.SORT_COLUMNS.name())) { sortExpressions.clear(); if (sortDirections != null) { sortDirections.clear(); } JSONArray jarray = jobj.getJSONArray(SortMembers.SORT_COLUMNS.name()); int size = jarray.length(); for (int ii = 0; ii < size; ii += 1) { JSONObject tempObj = jarray.getJSONObject(ii); <START> if (sortDirections != null) { <END> sortExpressions.add( AbstractExpression.fromJSONChild(tempObj, SortMembers.SORT_EXPRESSION.name()) ); if (sortDirections != null && tempObj.has(SortMembers.SORT_DIRECTION.name())) { sortDirections.add( SortDirectionType.get(tempObj.getString( SortMembers.SORT_DIRECTION.name())) ); } } } } assert(sortDirections == null || sortExpressions.size() == sortDirections.size()); }</code><technical_language>If sortDirections list is provided, bother collecting sortExpressions? More point, real bug is of callers this function is calling explicit null pointer easily pass sortDirections List corresponds sortExpressions List is using. This more consistent closely related callers, worry a slightly call sequence violate asserts a WindowedExpression sortExpressions sortDirections length. Also, a test case</technical_language>

Target:
public static void loadSortListFromJSONArray(List<AbstractExpression> sortExpressions, List<SortDirectionType> sortDirections, JSONObject jobj) throws JSONException { if (jobj.has(AbstractExpression.SortMembers.SORT_COLUMNS.name())) { sortExpressions.clear(); if (sortDirections != null) { sortDirections.clear(); } JSONArray jarray = jobj.getJSONArray(SortMembers.SORT_COLUMNS.name()); int size = jarray.length(); for (int ii = 0; ii < size; ii += 1) { JSONObject tempObj = jarray.getJSONObject(ii); sortExpressions.add( AbstractExpression.fromJSONChild(tempObj, SortMembers.SORT_EXPRESSION.name()) ); if (sortDirections != null) { if (sortDirections != null && tempObj.has(SortMembers.SORT_DIRECTION.name())) { sortDirections.add( SortDirectionType.get(tempObj.getString( SortMembers.SORT_DIRECTION.name())) ); } } } } assert(sortDirections == null || sortExpressions.size() == sortDirections.size()); }
Source:
<code>public Set<Type> getImportTypes() { <START> Set<Type> imported = new HashSet<Type>( getAssignment().getImportTypes().size() + 1 ); <END> imported.addAll( getAssignment().getImportTypes() ); imported.add( enumType ); return imported; }</code><technical_language>require a resize of underlying map, default load factor is 0.75... new HashSet<Type>( getAssignment().getImportTypes() ) .add( enumType )</technical_language>

Target:
public Set<Type> getImportTypes() { Set<Type> imported = new HashSet<Type>( getAssignment().getImportTypes() ); imported.add( enumType ); return imported; }
Source:
<code>public void prepareServerOnce() throws Exception { if(!serverConfigDone) { log.trace("*** preparing server configuration"); ManagementClient managementClient; log.trace("*** starting server"); container.start(DEFAULT_JBOSSAS); final ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient(); managementClient = new ManagementClient(client, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http"); <START> log.info("*** will configure server now"); <END> SSLRealmSetupTool.setup(managementClient); log.trace("*** restarting server"); container.stop(DEFAULT_JBOSSAS); container.start(DEFAULT_JBOSSAS); managementClient = new ManagementClient(client, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http"); SSLRealmSetupTool.readSSLRealmConfig(managementClient); serverConfigDone = true; } else { log.trace("*** Server already prepared, skipping config procedure"); } }</code><technical_language>log.trace</technical_language>

Target:
public void prepareServerOnce() throws Exception { if(!serverConfigDone) { log.trace("*** preparing server configuration"); ManagementClient managementClient; log.trace("*** starting server"); container.start(DEFAULT_JBOSSAS); final ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient(); managementClient = new ManagementClient(client, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http"); log.trace("*** will configure server now"); SSLRealmSetupTool.setup(managementClient); log.trace("*** restarting server"); container.stop(DEFAULT_JBOSSAS); container.start(DEFAULT_JBOSSAS); managementClient = new ManagementClient(client, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http"); SSLRealmSetupTool.readSSLRealmConfig(managementClient); serverConfigDone = true; } else { log.trace("*** Server already prepared, skipping config procedure"); } }
Source:
<code>public Optional<RuntimeModel> registerFile(String fileName) { if (fileName == null || fileName.trim().isEmpty()) { logger.error("Invalid file name: {}", fileName); throw new IllegalArgumentException("Invalid file name."); } File file = new File(fileName); if (!file.exists()) { logger.error("File does not exist: {}", fileName); throw new IllegalArgumentException("File does not exist"); } if (!importValidationService.validate(fileName)) { logger.error("File does not have a valid structure: {}", fileName); throw new IllegalArgumentException("Not a valid file structure."); } try (FileInputStream fis = new FileInputStream(fileName)) { <START> String importId = file.getName().replaceAll(".zip", ""); <END> return register(importId, fis); } catch (IOException e) { logger.error("Not able to load file {}", fileName, e); throw new IllegalArgumentException("Error loading import file: " + fileName, e); } }</code><technical_language>Another option [FilenameUtils#getBaseName](<LINK_0></technical_language>

Target:
public Optional<RuntimeModel> registerFile(String fileName) { if (fileName == null || fileName.trim().isEmpty()) { logger.error("Invalid file name: {}", fileName); throw new IllegalArgumentException("Invalid file name."); } File file = new File(fileName); if (!file.exists()) { logger.error("File does not exist: {}", fileName); throw new IllegalArgumentException("File does not exist"); } if (!importValidationService.validate(fileName)) { logger.error("File does not have a valid structure: {}", fileName); throw new IllegalArgumentException("Not a valid file structure."); } try (FileInputStream fis = new FileInputStream(fileName)) { String importId = FilenameUtils.getBaseName(file.getPath()); return register(importId, fis); } catch (IOException e) { logger.error("Not able to load file {}", fileName, e); throw new IllegalArgumentException("Error loading import file: " + fileName, e); } }
Source:
<code>public static List<TelemetryBis.TelemetryField> getRowsFromTable(Telemetry msg, String name) { Objects.requireNonNull(msg); for (TelemetryBis.TelemetryField field : msg.getDataGpbkvList()) { TelemetryBis.TelemetryField subField = findFieldWithName(field, "ROW_" + name); if (subField != null) { return subField.getFieldsList(); } } <START> return null; <END> }</code><technical_language>return empty list instead of null</technical_language>

Target:
public static List<TelemetryBis.TelemetryField> getRowsFromTable(Telemetry msg, String name) { if (Objects.isNull(msg) || Objects.isNull(name)) { return Collections.emptyList(); } for (TelemetryBis.TelemetryField field : msg.getDataGpbkvList()) { TelemetryBis.TelemetryField subField = findFieldWithName(field, "ROW_" + name); if (subField != null) { return subField.getFieldsList(); } } return Collections.emptyList(); }
Source:
<code>private static HashMap<String, String> extractJsonObjects(final String jsonStr) throws JSONException { final JSONObject jsonObject = new JSONObject(jsonStr); <START> final HashMap<String, String> responseItems = new HashMap<>(); <END> final Iterator<?> i = jsonObject.keys(); while (i.hasNext()) { final String key = (String) i.next(); responseItems.put(key, jsonObject.getString(key)); } return responseItems; }</code><technical_language>Map</technical_language>

Target:
private static Map<String, String> extractJsonObjects(final String jsonStr) throws JSONException { final JSONObject jsonObject = new JSONObject(jsonStr); final Map<String, String> responseItems = new HashMap<>(); final Iterator<?> i = jsonObject.keys(); while (i.hasNext()) { final String key = (String) i.next(); responseItems.put(key, jsonObject.getString(key)); } return responseItems; }
Source:
<code>public void serialize(Writer writer) throws IOException { for (Entry<String, HeadRule> entry : headRules.entrySet()) { <START> final String type = entry.getKey(); <END> final HeadRule headRule = entry.getValue(); writer.write(Integer.toString(headRule.tags.length + 2)); writer.write(' '); writer.write(type); writer.write(' '); if (headRule.leftToRight) writer.write("1"); else writer.write("0"); for (String tag : headRule.tags) { writer.write(' '); writer.write(tag); } writer.write('\n'); } writer.flush(); }</code><technical_language>final here</technical_language>

Target:
public void serialize(Writer writer) throws IOException { for (Entry<String, HeadRule> entry : headRules.entrySet()) { String type = entry.getKey(); HeadRule headRule = entry.getValue(); writer.write(Integer.toString(headRule.tags.length + 2)); writer.write(' '); writer.write(type); writer.write(' '); if (headRule.leftToRight) writer.write("1"); else writer.write("0"); for (String tag : headRule.tags) { writer.write(' '); writer.write(tag); } writer.write('\n'); } writer.flush(); }
Source:
<code>public String getCustomDefaultContributorRoleDescription(){ if (dvObject instanceof Dataverse && isCustomDefaultConributorRole()){ <START> return defaultContributorRoleAlias.equals("none") ? BundleUtil.getStringFromBundle("permission.default.contributor.role.none" ) :roleService.findCustomRoleByAliasAndOwner(defaultContributorRoleAlias,dvObject.getId() ).getDescription(); <END> } else { return ""; } }</code><technical_language>this English word "none" moved bundle translated</technical_language>

Target:
public String getCustomDefaultContributorRoleDescription(){ if (dvObject instanceof Dataverse && isCustomDefaultContributorRole()){ return defaultContributorRoleAlias.equals(DataverseRole.NONE) ? BundleUtil.getStringFromBundle("permission.default.contributor.role.none.decription" ) :roleService.findCustomRoleByAliasAndOwner(defaultContributorRoleAlias,dvObject.getId() ).getDescription(); } else { return ""; } }
Source:
<code>HiveCompressionCodec( Class<? extends CompressionCodec> codec, CompressionKind orcCompressionKind, CompressionCodecName parquetCompressionCodec, Predicate<HiveStorageFormat> supportedStorageFormats) { this.codec = Optional.ofNullable(codec); this.orcCompressionKind = requireNonNull(orcCompressionKind, "orcCompressionKind is null"); this.parquetCompressionCodec = Optional.ofNullable(parquetCompressionCodec); <START> this.supportedStorageFormats = requireNonNull(supportedStorageFormats); <END> }</code><technical_language>@jainxrohit tend add a message this: requireNonNull(supportedStorageFormats, "supportedStorageFormats is null")</technical_language>

Target:
HiveCompressionCodec( Class<? extends CompressionCodec> codec, CompressionKind orcCompressionKind, CompressionCodecName parquetCompressionCodec, Predicate<HiveStorageFormat> supportedStorageFormats) { this.codec = Optional.ofNullable(codec); this.orcCompressionKind = requireNonNull(orcCompressionKind, "orcCompressionKind is null"); this.parquetCompressionCodec = Optional.ofNullable(parquetCompressionCodec); this.supportedStorageFormats = requireNonNull(supportedStorageFormats, "supportedStorageFormats is null"); }