auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static Map<String, String> metadata(Object... services) { <START> Map<String, String> result = new HashMap<>(); <END> for (Object service : services) { Collection<Class<?>> serviceInterfaces = serviceProcessor.extractServiceInterfaces(service); for (Class<?> serviceInterface : serviceInterfaces) { ServiceDefinition def = serviceProcessor.introspectServiceInterface(serviceInterface); result.put(def.serviceName(), "service"); } } return result; }</code><technical_language>this method more functional if want :) java return Arrays.stream(services).flatMap(service -> { Collection<Class<?>> serviceInterfaces = serviceProcessor.extractServiceInterfaces(service); return serviceInterfaces.stream().map(serviceProcessor::introspectServiceInterface); }).collect(Collectors.toMap(ServiceDefinition::serviceName,def -> "service"));</technical_language>

Target:
private static Map<String, String> metadata(Object... services) { return Arrays.stream(services).flatMap(service -> { Collection<Class<?>> serviceInterfaces = serviceProcessor.extractServiceInterfaces(service); return serviceInterfaces.stream().map(serviceProcessor::introspectServiceInterface); }).collect(Collectors.toMap(ServiceDefinition::serviceName,def -> "service")); }
Source:
<code>public void waitHttpAsAction() { String server = String.format("http://localhost:%s", serverPort); httpServer.setPort(serverPort); start(httpServer); parallel().actions( sequential().actions( waitFor() .execution() <START> .action(send(server)) <END> ), sequential().actions( http().server(httpServer).receive().post(), http().server(httpServer).receive().post(), http().server(httpServer).respond(HttpStatus.OK) ) ); doFinally().actions(stop(httpServer)); }</code><technical_language>Is this test redundant "waitAction()" test below</technical_language>

Target:
public void waitHttpAsAction() { String server = startHttpServerAndGetUrl(); parallel().actions( sequential().actions( waitFor() .execution() .action(send(server)) ), sequential().actions( http().server(httpServer).receive().post(), http().server(httpServer).receive().post(), http().server(httpServer).respond(HttpStatus.OK) ) ); doFinally().actions(stop(httpServer)); }
Source:
<code>public static Set<Language> getLanguages() { <START> return new LinkedHashSet<>(getInstance().languages.values()); <END> }</code><technical_language>Collections.unmodifiableSet instead of a new LinkedHashSet</technical_language>

Target:
public static Set<Language> getLanguages() { return getInstance().languages; }
Source:
<code>public void testUmbrellaHeader() { UmbrellaHeader header = new UmbrellaHeader(ImmutableList.of("header1.h", "header2.h")); <START> assertEquals("#import \"header1.h\"\n" + "#import \"header2.h\"\n", header.render()); <END> }</code><technical_language>This implies umbrella headers exported imports work other libraries. Do plan expose umbrella headers, non-modular libraries do #import <Module/Module.h></technical_language>

Target:
public void testUmbrellaHeader() { UmbrellaHeader header = new UmbrellaHeader("lib", ImmutableList.of("header1.h", "header2.h")); assertThat( "#import <lib/header1.h>\n#import <lib/header2.h>\n", equalToIgnoringPlatformNewlines(header.render())); }
Source:
<code>private void verifySafeObject(final AnyObjectId id, final int type, final byte[] data, long size) throws IOException { if (0 < maxObjectSizeLimit && maxObjectSizeLimit < size) { <START> throw new IOException("Object " + id.name() <END> + " is too large. Use: \"git ls-tree -r HEAD | grep " + id.name() + "\" to find out the path of the object in your Git repository"); } if (objCheck != null) { try { objCheck.check(type, data); } catch (CorruptObjectException e) { throw new IOException(MessageFormat.format( JGitText.get().invalidObject, Constants .typeString(type), id.name(), e.getMessage())); } } if (isCheckObjectCollisions()) { try { final ObjectLoader ldr = readCurs.open(id, type); final byte[] existingData = ldr.getCachedBytes(data.length); if (!Arrays.equals(data, existingData)) { throw new IOException(MessageFormat.format( JGitText.get().collisionOn, id.name())); } } catch (MissingObjectException notLocal) { } } }</code><technical_language>this deserves exception type applications want handle this case in a special way. Text externalized MessageFormat for proper formatting in case this translated</technical_language>

Target:
private void verifySafeObject(final AnyObjectId id, final int type, final byte[] data, long size) throws IOException { if (0 < maxObjectSizeLimit && maxObjectSizeLimit < size) { throw new IOException(MessageFormat.format( JGitText.get().receivePackObjectTooLarge, id.name())); } if (data == null) return; if (objCheck != null) { try { objCheck.check(type, data); } catch (CorruptObjectException e) { throw new IOException(MessageFormat.format( JGitText.get().invalidObject, Constants .typeString(type), id.name(), e.getMessage())); } } if (isCheckObjectCollisions()) { try { final ObjectLoader ldr = readCurs.open(id, type); final byte[] existingData = ldr.getCachedBytes(data.length); if (!Arrays.equals(data, existingData)) { throw new IOException(MessageFormat.format( JGitText.get().collisionOn, id.name())); } } catch (MissingObjectException notLocal) { } } }
Source:
<code>public void writeData(ObjectDataOutput out) throws IOException { out.writeByte(schemaVersion); out.writeObject(targetAddress); out.writeBoolean(reply); <START> out.writeLong(uuid.getMostSignificantBits()); <END> out.writeLong(uuid.getLeastSignificantBits()); int size = (localAddresses == null) ? 0 : localAddresses.size(); out.writeInt(size); if (size == 0) { return; } for (Map.Entry<ProtocolType, Collection<Address>> addressEntry : localAddresses.entrySet()) { out.writeInt(addressEntry.getKey().ordinal()); writeCollection(addressEntry.getValue(), out); } }</code><technical_language>minor: UUIDSerializationUtil (which handles null UUIDs additional boolean)</technical_language>

Target:
public void writeData(ObjectDataOutput out) throws IOException { out.writeByte(schemaVersion); out.writeObject(targetAddress); out.writeBoolean(reply); writeUUID(out, uuid); int size = (localAddresses == null) ? 0 : localAddresses.size(); out.writeInt(size); if (size == 0) { return; } for (Map.Entry<ProtocolType, Collection<Address>> addressEntry : localAddresses.entrySet()) { out.writeInt(addressEntry.getKey().ordinal()); writeCollection(addressEntry.getValue(), out); } }
Source:
<code>public void nonHtmlStringWithPercentageReturnsEmptyMap() { MapConverter cnv = new MapConverter(); <START> assertEquals(new HashMap<>(), cnv.fromString("1%")); <END> }</code><technical_language>mapMap() done in other tests</technical_language>

Target:
public void nonHtmlStringWithPercentageReturnsEmptyMap() { makeMap("1%"); assertEquals(0, result.size()); }
Source:
<code>private Value getOutputPort( OutputPortInfo portInfo ) { Value response = Value.create(); response.getFirstChild( "name" ).setValue( portInfo.id() ); if( portInfo.location() != null ) { response.getFirstChild( "location" ).setValue( portInfo.location().toString() ); } else { response.getFirstChild( "location" ).setValue( "undefined" ); } if( portInfo.protocol() != null ) { <START> response.getFirstChild( "protocol" ).setValue( portInfo.protocol().toString() ); <END> } else { response.getFirstChild( "protocol" ).setValue( "" ); } for( int intf_index = 0; intf_index < portInfo.getInterfaceList().size(); intf_index++ ) { InterfaceDefinition interfaceDefinition = portInfo.getInterfaceList().get( intf_index ); response.getChildren( "interfaces" ).get( intf_index ) .deepCopy( getInterfaceAndInsertTypes( interfaceDefinition, null, null ) ); } return response; }</code><technical_language>I invoke OLSyntaxNode.toString(), this is misleading, expect InlineTreeExpression print out entire tree, root. Consider keeping protocolId method do this maybe</technical_language>

Target:
private Value getOutputPort( OutputPortInfo portInfo ) { Value response = Value.create(); response.getFirstChild( "name" ).setValue( portInfo.id() ); if( portInfo.location() != null ) { response.getFirstChild( "location" ).setValue( portInfo.location().toString() ); } else { response.getFirstChild( "location" ).setValue( "undefined" ); } if( portInfo.protocolId() != null ) { response.getFirstChild( "protocol" ).setValue( portInfo.protocolId() ); } else { response.getFirstChild( "protocol" ).setValue( "" ); } for( int intf_index = 0; intf_index < portInfo.getInterfaceList().size(); intf_index++ ) { InterfaceDefinition interfaceDefinition = portInfo.getInterfaceList().get( intf_index ); response.getChildren( "interfaces" ).get( intf_index ) .deepCopy( getInterfaceAndInsertTypes( interfaceDefinition, null, null ) ); } return response; }
Source:
<code>protected void onStoreCollection(RecordStore recordStore) { assertRunningOnPartitionThread(); <START> ((DefaultRecordStore) recordStore).clearOtherResourcesThanStorage(true); <END> }</code><technical_language>in addition clearing indexes, do this: clearMapStore(); clearLockStore(); clearIndexedData(true); clear lock store collected LockService. if this is ok</technical_language>

Target:
protected void onStoreCollection(RecordStore recordStore) { assertRunningOnPartitionThread(); ((DefaultRecordStore) recordStore).clearOtherDataThanStorage(true); }
Source:
<code>protected Object getResponseBody(Exchange exchange) throws Exception { HttpResponse response; Message answer; if (exchange.hasOut()) { response = consumer.getEndpoint().getNettyHttpBinding().toNettyResponse(exchange.getOut(), consumer.getConfiguration()); answer = exchange.getOut(); } else { response = consumer.getEndpoint().getNettyHttpBinding().toNettyResponse(exchange.getIn(), consumer.getConfiguration()); answer = exchange.getIn(); } <START> handleNoContent(exchange, answer, response); <END> return response; }</code><technical_language>Do if handle status code here: <LINK_0>, is method sole responsibility produce correct HTTP response need logic</technical_language>

Target:
protected Object getResponseBody(Exchange exchange) throws Exception { return consumer.getEndpoint().getNettyHttpBinding().toNettyResponse(exchange.getMessage(), consumer.getConfiguration()); }
Source:
<code>public void acceptsNonProperlyEncodedURL() { <START> final String url = <END> "<LINK_0>[foo/bar]/read?file=%5B%5D%28%29.txt"; final String result = "<LINK_0>%5Bfoo/bar%5D/read?file=%5B%5D%28%29.txt"; MatcherAssert.assertThat( new Href(url).toString(), Matchers.equalTo(result) ); }</code><technical_language>@essobedo inline this variable</technical_language>

Target:
public void acceptsNonProperlyEncodedURL() { MatcherAssert.assertThat( new Href("<LINK_0>[foo/bar]/read?file=%5B%5D%28%29.txt").toString(), Matchers.equalTo("<LINK_0>%5Bfoo/bar%5D/read?file=%5B%5D%28%29.txt") ); }
Source:
<code>protected List<String> getInputTables() throws FalconException { List<String> tables = new ArrayList<String>(); try { JSONArray inputs = message.getJSONObject(ADFJsonConstants.ADF_REQUEST_ACTIVITY) .getJSONArray(ADFJsonConstants.ADF_REQUEST_INPUTS); for (int i = 0; i < inputs.length(); i++) { tables.add(inputs.getJSONObject(i).getString(ADFJsonConstants.ADF_REQUEST_NAME)); } } catch (JSONException e) { <START> throw new FalconException("Error while parsing input tables in ADF request."); <END> } return tables; }</code><technical_language>print table name for error occurred while parsing</technical_language>

Target:
protected List<String> getInputTables() throws FalconException { List<String> tables = new ArrayList<String>(); try { JSONArray inputs = message.getJSONObject(ADFJsonConstants.ADF_REQUEST_ACTIVITY) .getJSONArray(ADFJsonConstants.ADF_REQUEST_INPUTS); for (int i = 0; i < inputs.length(); i++) { tables.add(inputs.getJSONObject(i).getString(ADFJsonConstants.ADF_REQUEST_NAME)); } } catch (JSONException e) { throw new FalconException("Error while reading input table names in ADF request."); } return tables; }
Source:
<code>public void update(Operator operator) { List<OperatorEntity> entities = datastore.findAllObjectsByFilter(OperatorEntity.class, Filter.where("name").is(operator.name).limit(1)); <START> if (!entities.isEmpty() && !entities.get(0).getId().equals(operator.id)) { <END> throw new OperatorException("Operator with name: " + operator.name + " already exists."); } datastore.save(adapt(operator)); }</code><technical_language>This is complicated..</technical_language>

Target:
public void update(Operator operator) { Long count = datastore.entityCount(OperatorEntity.class, Filter.where("name").is(operator.name).and("_id").isNot(operator.id)); if (count != 0) { throw new OperatorException("Operator with name: " + operator.name + " already exists."); } datastore.save(adapt(operator)); }
Source:
<code>public void createPartControl(Composite parent) { String name = getViewSite().getSecondaryId(); if (name != null) { <START> fViewInfo.setName(checkNotNull(TmfViewFactory.getBaseSecId(name))); <END> } super.createPartControl(parent); }</code><technical_language>String.valueOf()</technical_language>

Target:
public void createPartControl(Composite parent) { String name = getViewSite().getSecondaryId(); if (name != null) { name = TmfViewFactory.getBaseSecId(name); } if (name != null) { fViewInfo.setName(name); } super.createPartControl(parent); }
Source:
<code>private void cacheResultEntry( ResultLevelCachePopulator resultLevelCachePopulator, T resultEntry, Function<T, Object> cacheFn ) { int cacheLimit = cacheConfig.getResultLevelCacheLimit(); if (cacheLimit > 0 && resultLevelCachePopulator.cacheObjectStream.size() > cacheLimit) { shouldPopulate = false; return; } try (JsonGenerator gen = mapper.getFactory().createGenerator(resultLevelCachePopulator.cacheObjectStream)) { <START> gen.writeObject(cacheFn.apply(resultEntry)); <END> } catch (IOException ex) { log.error("Failed to retrieve entry to be cached. Result Level caching will not be performed!"); shouldPopulate = false; } }</code><technical_language>if element in sequence size limit, shouldPopulate stay true resulting in stored if crossed size limit. also, soon cross size limit... discard data stored in cacheObjectStream is GC'd</technical_language>

Target:
private void cacheResultEntry( ResultLevelCachePopulator resultLevelCachePopulator, T resultEntry, Function<T, Object> cacheFn ) { int cacheLimit = cacheConfig.getResultLevelCacheLimit(); try (JsonGenerator gen = mapper.getFactory().createGenerator(resultLevelCachePopulator.cacheObjectStream)) { gen.writeObject(cacheFn.apply(resultEntry)); if (cacheLimit > 0 && resultLevelCachePopulator.cacheObjectStream.size() > cacheLimit) { shouldPopulate = false; resultLevelCachePopulator.cacheObjectStream = null; return; } } catch (IOException ex) { log.error(ex, "Failed to retrieve entry to be cached. Result Level caching will not be performed!"); shouldPopulate = false; resultLevelCachePopulator.cacheObjectStream = null; } }
Source:
<code>void verifyRawQueryBehaviorForInteger(@NonNull Integer actualNumberOfResults) { assertThat(actualNumberOfResults).isNotNull(); <START> verify(storIOSQLite, times(1)).get(); <END> verify(getResolverForNumberOfResults, times(1)).performGet(storIOSQLite, rawQuery); assertThat(actualNumberOfResults).isSameAs(numberOfResults); verify(cursor).close(); verifyNoMoreInteractions(storIOSQLite, internal, cursor); }</code><technical_language>times(1) is excess</technical_language>

Target:
void verifyRawQueryBehaviorForInteger(@NonNull Integer actualNumberOfResults) { assertThat(actualNumberOfResults).isNotNull(); verify(storIOSQLite).get(); verify(getResolverForNumberOfResults).performGet(storIOSQLite, rawQuery); assertThat(actualNumberOfResults).isSameAs(numberOfResults); verify(cursor).close(); verifyNoMoreInteractions(storIOSQLite, internal, cursor); }
Source:
<code>public void close() { Closeables.closeQuietly(nettyConnectionPool); try { timer.stop(); } <START> finally { <END> } }</code><technical_language>empty finally block</technical_language>

Target:
public void close() { Closeables.closeQuietly(nettyConnectionPool); try { timer.stop(); } catch(Exception e) { } }
Source:
<code>private void setSpinnerSelection(Spinner spinner) { if (isFormulaEnabled) { oldSelectedLook = look; spinner.setSelection(FORMULA_EDITOR_POSITION); return; } if (getSprite().getLookDataList().contains(look)) { oldSelectedLook = look; spinner.setSelection(getSprite().getLookDataList().indexOf(look) + 2, true); } else { if (spinner.getAdapter() != null && spinner.getAdapter().getCount() > 1) { if (getSprite().getLookDataList().indexOf(oldSelectedLook) >= 0) { spinner.setSelection(getSprite().getLookDataList() <START> .indexOf(oldSelectedLook) + 2, true); <END> } else { spinner.setSelection(FORMULA_EDITOR_POSITION + 1, true); } } else { spinner.setSelection(NEW_LOOK_POSITION, true); } } }</code><technical_language>FORMULA_EDITOR_POSITION + 1</technical_language>

Target:
private void setSpinnerSelection(Spinner spinner) { if (isFormulaEnabled) { oldSelectedLook = look; spinner.setSelection(SPINNER_POSITION_FORMULA_EDITOR); return; } if (getSprite().getLookDataList().contains(look)) { oldSelectedLook = look; spinner.setSelection(getSprite().getLookDataList().indexOf(look) + 2, true); } else { if (spinner.getAdapter() != null && spinner.getAdapter().getCount() > 2) { if (getSprite().getLookDataList().indexOf(oldSelectedLook) >= 0) { spinner.setSelection(getSprite().getLookDataList() .indexOf(oldSelectedLook) + SPINNER_POSITION_FORMULA_EDITOR + 1, true); } else { spinner.setSelection(SPINNER_POSITION_FORMULA_EDITOR + 1, true); } } else { spinner.setSelection(SPINNER_POSITION_NEW_LOOK, true); } } }
Source:
<code>public void init(ByteBuffer buf, int position) { buf.put(position, BYTE_FLAG_IS_NOT_SET); <START> buf.putDouble(position + Byte.BYTES, NULL_VALUE); <END> }</code><technical_language>instead of NULL_VALUE NullHandling.ZERO_DOUBLE 0 this is place this is</technical_language>

Target:
public void init(ByteBuffer buf, int position) { buf.put(position, BYTE_FLAG_IS_NOT_SET); buf.putDouble(position + Byte.BYTES, NullHandling.ZERO_DOUBLE); }
Source:
<code><START> private boolean verifyChecksums(String originalFileChecksum, String replicatedFilePath) { <END> String remoteChecksum = getFileChecksum(replicatedFilePath); if (originalFileChecksum.equals(remoteChecksum)) { log.info("Local and remote checksums match for {}", replicatedFilePath); return true; } else { throw new ReplicationException("Local and remote checksums did not match {}", originalFileChecksum, remoteChecksum); } }</code><technical_language>return for this method used, switch method throwing a replication exception if fixity checking fails match</technical_language>

Target:
private void verifyChecksums(String originalFileChecksum, String replicatedFilePath) { String remoteChecksum = getFileChecksum(replicatedFilePath); if (originalFileChecksum.equals(remoteChecksum)) { log.info("Local and remote checksums match for {}", replicatedFilePath); } else { String errorMsg = String.format("Local and remote checksums did not match %s %s", originalFileChecksum, remoteChecksum); throw new ReplicationException(errorMsg); } }
Source:
<code>private double getHeight(final BaseGridRendererHelper.RenderingInformation renderingInformation) { double height = renderer.getHeaderHeight(); <START> height = height + renderingInformation.getAllRowHeights().stream().reduce(0d, Double::sum); <END> return height; }</code><technical_language>@manstis pls replace for-loop (or parallel stream) for performance</technical_language>

Target:
private double getHeight(final BaseGridRendererHelper.RenderingInformation renderingInformation) { double height = renderer.getHeaderHeight(); for (double h : renderingInformation.getAllRowHeights()) { height = height + h; } return height; }
Source:
<code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_editor_list, container, false); DroidPlannerApp app = ((DroidPlannerApp) getActivity().getApplication()); drone = app.getDrone(); missionProxy = app.missionProxy; adapter = new MissionItemProxyView(getActivity(), missionProxy.getItems()); if (savedInstanceState != null){ <START> isInDeleteMode = savedInstanceState.getBoolean(DELETE_MODE_KEY); <END> adapter.setDeleteModeEnabled(isInDeleteMode); } list = (HListView) view.findViewById(R.id.mission_item_list); list.setOnItemClickListener(this); list.setOnItemLongClickListener(this); list.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE); list.setAdapter(adapter); leftArrow = (ImageButton) view.findViewById(R.id.listLeftArrow); rightArrow = (ImageButton) view.findViewById(R.id.listRightArrow); leftArrow.setOnClickListener(this); rightArrow.setOnClickListener(this); return view; }</code><technical_language>@alextel69 Do want save DELETE state? If saving selected tool, change state line in line 182. if need save tool state, reset user switch activities</technical_language>

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_editor_list, container, false); DroidPlannerApp app = ((DroidPlannerApp) getActivity().getApplication()); drone = app.getDrone(); missionProxy = app.missionProxy; adapter = new MissionItemProxyView(getActivity(), missionProxy.getItems()); list = (HListView) view.findViewById(R.id.mission_item_list); list.setOnItemClickListener(this); list.setOnItemLongClickListener(this); list.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE); list.setAdapter(adapter); leftArrow = (ImageButton) view.findViewById(R.id.listLeftArrow); rightArrow = (ImageButton) view.findViewById(R.id.listRightArrow); leftArrow.setOnClickListener(this); rightArrow.setOnClickListener(this); return view; }
Source:
<code>public void reelIn() { if (location.getBlock().getType() == Material.WATER) { if (getShooter() instanceof Player) { world.dropItemNaturally(((Player) getShooter()).getLocation(), getRewardItem()); <START> ((Player) getShooter()).giveExp(ThreadLocalRandom.current().nextInt(1, 7)); <END> } } remove(); }</code><technical_language>I PlayerFishEvent called handled here, part of this PR</technical_language>

Target:
public void reelIn() { if (location.getBlock().getType() == Material.WATER) { ProjectileSource shooter = getShooter(); if (shooter instanceof Player) { PlayerFishEvent fishEvent = new PlayerFishEvent((Player) shooter, this, null, CAUGHT_FISH); fishEvent.setExpToDrop(ThreadLocalRandom.current().nextInt(1, 7)); fishEvent = EventFactory.callEvent(fishEvent); if (!fishEvent.isCancelled()) { world.dropItemNaturally(((Player) getShooter()).getLocation(), getRewardItem()); ((Player) getShooter()).giveExp(fishEvent.getExpToDrop()); } } } remove(); }
Source:
<code><START> public void setClientConfigs(List<ClientConfig> clientConfigs) { <END> this.clientConfigs = clientConfigs; }</code><technical_language>return ClientFailoverConfig for chaining support</technical_language>

Target:
public ClientFailoverConfig setClientConfigs(List<ClientConfig> clientConfigs) { this.clientConfigs = clientConfigs; return this; }
Source:
<code>private void maybeRefreshSchemaAndSignal(final Connection connection, final DefaultResultSetFuture future, final ResultSet rs, final String keyspace, final String table) { final boolean refreshSchema = (keyspace != null); executor.submit(new Runnable() { @Override public void run() { boolean schemaInAgreement = false; try { schemaInAgreement = ControlConnection.waitForSchemaAgreement(connection, Manager.this); if (!schemaInAgreement) logger.warn("No schema agreement from live replicas after s. The schema may not be up to date on some nodes.", configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds()); if (refreshSchema) { submitSchemaRefresh(keyspace, table); <START> Uninterruptibles.getUninterruptibly(schemaRefreshRequestDebouncer.deliverEvents()); <END> if (table == null) { Uninterruptibles.getUninterruptibly(nodeListRefreshRequestDebouncer.deliverEvents()); } } } catch (Exception e) { if (refreshSchema) { logger.error("Error during schema refresh ({}). The schema from Cluster.getMetadata() might appear stale. Asynchronously submitting job to fix.", e.getMessage()); submitSchemaRefresh(keyspace, table); } else { logger.warn("Error while waiting for schema agreement", e); } } finally { rs.getExecutionInfo().setSchemaInAgreement(schemaInAgreement); future.setResult(rs); } } }); }</code><technical_language>previous version performed refresh _current_ connection (the executed schema-altering statement), while debouncer do control connection. problem is control host date schema changes, metadata is stale statement completes. solve yet</technical_language>

Target:
private void maybeRefreshSchemaAndSignal(final Connection connection, final DefaultResultSetFuture future, final ResultSet rs, final String keyspace, final String table) { final boolean refreshSchema = (keyspace != null); executor.submit(new Runnable() { @Override public void run() { boolean schemaInAgreement = false; try { schemaInAgreement = controlConnection.waitForSchemaAgreement(); if (!schemaInAgreement) logger.warn("No schema agreement from live replicas after s. The schema may not be up to date on some nodes.", configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds()); ListenableFuture<Void> schemaReady = refreshSchema ? submitSchemaRefresh(keyspace, table) : MoreFutures.VOID_SUCCESS; final boolean finalSchemaInAgreement = schemaInAgreement; schemaReady.addListener(new Runnable() { @Override public void run() { rs.getExecutionInfo().setSchemaInAgreement(finalSchemaInAgreement); future.setResult(rs); } }, MoreExecutors.sameThreadExecutor()); } catch (Exception e) { logger.warn("Error while waiting for schema agreement", e); rs.getExecutionInfo().setSchemaInAgreement(schemaInAgreement); future.setResult(rs); } } }); }
Source:
<code>public void initSelectedProfile(ListModel<VnicProfileView> profileList, VmNetworkInterface networkInterface) { <START> Collection<VnicProfileView> profiles = Optional.ofNullable(profileList.getItems()).orElse(Collections.emptyList()); <END> if (networkInterface.getVnicProfileId() != null) { profileList.setSelectedItem(profiles.stream() .filter(profile -> Objects.equals(profile.getId(), networkInterface.getVnicProfileId())) .findAny() .orElse(VnicProfileView.EMPTY)); } else { profileList.setSelectedItem(VnicProfileView.EMPTY); } }</code><technical_language>Please move this line if/else branch, e.g. @Override public void initSelectedProfile(ListModel<VnicProfileView> profileList, VmNetworkInterface networkInterface) { if (networkInterface.getVnicProfileId() == null) { profileList.setSelectedItem(VnicProfileView.EMPTY); } else { Collection<VnicProfileView> profiles = Optional.ofNullable(profileList.getItems()).orElse(Collections.emptyList()); profileList.setSelectedItem(profiles.stream() .filter(profile -> Objects.equals(profile.getId(), networkInterface.getVnicProfileId())) .findAny() .orElse(VnicProfileView.EMPTY)); } }</technical_language>

Target:
public void initSelectedProfile(ListModel<VnicProfileView> profileList, VmNetworkInterface networkInterface) { if (networkInterface.getVnicProfileId() != null) { Collection<VnicProfileView> profiles = Optional.ofNullable(profileList.getItems()).orElse(Collections.emptyList()); profileList.setSelectedItem(profiles.stream() .filter(profile -> Objects.equals(profile.getId(), networkInterface.getVnicProfileId())) .findAny() .orElse(VnicProfileView.EMPTY)); } else { profileList.setSelectedItem(VnicProfileView.EMPTY); } }
Source:
<code>private static void restoreFromArchive(Configuration conf, String conglomId, String encodedRegionName) throws IOException{ Path region = getRegionPath(conf, conglomId, encodedRegionName); Path family = new Path(region, SIConstants.DEFAULT_FAMILY_NAME); Path regionArchive = getTmpPath(conf, conglomId, encodedRegionName); Path familyArchive = new Path(regionArchive, SIConstants.DEFAULT_FAMILY_NAME); FileSystem fs = region.getFileSystem(conf); if (fs.exists(familyArchive)) { FileStatus[] fileStatuses = fs.listStatus(familyArchive); for (FileStatus fileStatus : fileStatuses) { String name = fileStatus.getPath().getName(); Path src = fileStatus.getPath(); Path dest = new Path(family, name); SpliceLogUtils.info(LOG, "Move %s to %s", src.toString(), dest.toString()); <START> fs.rename(src, dest); <END> } fs.delete(familyArchive, true); } }</code><technical_language>check return status if this api successful not</technical_language>

Target:
private static void restoreFromArchive(Configuration conf, String conglomId, String encodedRegionName) throws IOException{ Path region = getRegionPath(conf, conglomId, encodedRegionName); Path family = new Path(region, SIConstants.DEFAULT_FAMILY_NAME); Path regionArchive = getTmpPath(conf, conglomId, encodedRegionName); Path familyArchive = new Path(regionArchive, SIConstants.DEFAULT_FAMILY_NAME); FileSystem fs = region.getFileSystem(conf); if (fs.exists(familyArchive)) { FileStatus[] fileStatuses = fs.listStatus(familyArchive); for (FileStatus fileStatus : fileStatuses) { String name = fileStatus.getPath().getName(); Path src = fileStatus.getPath(); Path dest = new Path(family, name); if (fs.rename(src, dest)) { SpliceLogUtils.info(LOG, "Moved %s to %s", src.toString(), dest.toString()); } else { SpliceLogUtils.info(LOG, "Failed to move %s to %s", src.toString(), dest.toString()); } } if (!fs.delete(familyArchive, true)) { SpliceLogUtils.error(LOG, "Failed to remove %s", familyArchive.toString()); } } }
Source:
<code>private SpockExecutionContext setCurrentFeature(FeatureInfo currentFeature) { if (this.currentFeature != currentFeature) { hadSuccess.set(false); <START> abortions.clear(); <END> failures.clear(); } this.currentFeature = currentFeature; return this; }</code><technical_language>context is designed cloned, modified copied</technical_language>

Target:
private SpockExecutionContext setCurrentFeature(FeatureInfo currentFeature) { this.currentFeature = currentFeature; return this; }
Source:
<code>public Projection<T> project(int... fieldIndexes) { if(!(this.getType() instanceof TupleTypeInfo)) { throw new UnsupportedOperationException("project() can only be applied to DataSets of Tuples."); } if(fieldIndexes.length == 0) { throw new IllegalArgumentException("project() needs to select at least one (1) field."); } else if(fieldIndexes.length > 22) { <START> throw new IllegalArgumentException("project() may to select at most twenty-two (22) fields."); <END> } int maxFieldIndex = ((TupleTypeInfo<?>)this.getType()).getArity(); for(int i=0; i<fieldIndexes.length; i++) { if(fieldIndexes[i] > maxFieldIndex - 1) { throw new IndexOutOfBoundsException("Provided field index is out of bounds of input tuple."); } } return new Projection<T>(this, fieldIndexes); }</code><technical_language>Typo? "project() select twenty-two (22) fields." "up 22 fields"</technical_language>

Target:
public Projection<T> project(int... fieldIndexes) { return new Projection<T>(this, fieldIndexes); }
Source:
<code>public void getBiome(BlockPos pos, CallbackInfoReturnable<Biome> cir) { if (!this.isCubic) return; int blockX = pos.getX(); int blockY = pos.getY(); int blockZ = pos.getZ(); int cubeX = Coords.blockToCube(blockX) - originX; int cubeY = Coords.blockToCube(blockY) - originY; int cubeZ = Coords.blockToCube(blockZ) - originZ; if (cubeX < 0 || cubeX >= dx || cubeY < 0 || cubeY >= dy || cubeZ < 0 || cubeZ >= dz) { return; } <START> Cube cube = this.cubes[cubeX][cubeY][cubeZ]; <END> cir.setReturnValue(cube.getBiome(pos, this.world.getBiomeProvider())); cir.cancel(); }</code><technical_language>Is cube guaranteed exist is a cube! = null check required</technical_language>

Target:
public void getBiome(BlockPos pos, CallbackInfoReturnable<Biome> cir) { if (!this.isCubic()) return; Cube cube = this.getCube(pos); if (cube == null) cir.setReturnValue(Biomes.PLAINS); else cir.setReturnValue(cube.getBiome(pos)); cir.cancel(); }
Source:
<code>public void setTitle(Session session) { StringBuilder strBuilder = new StringBuilder(); String sessionName = session == null ? "" : session.getSessionName(); strBuilder.append(sessionName).append(" - "); <START> if (!session.isNewState()) { <END> File file = new File(session.getFileName()); strBuilder.append(file.getName().replaceAll(".session\\z", "")).append(" - "); } strBuilder.append(Constant.PROGRAM_NAME).append(' ').append(Constant.PROGRAM_VERSION); super.setTitle(strBuilder.toString()); }</code><technical_language>requires null check (could if wrapping "session statements")</technical_language>

Target:
public void setTitle(Session session) { StringBuilder strBuilder = new StringBuilder(); if (session != null) { strBuilder.append(session.getSessionName()).append(" - "); if (!session.isNewState()) { File file = new File(session.getFileName()); strBuilder.append(file.getName().replaceAll(".session\\z", "")).append(" - "); } } strBuilder.append(Constant.PROGRAM_NAME).append(' ').append(Constant.PROGRAM_VERSION); super.setTitle(strBuilder.toString()); }
Source:
<code>public MaildirMessageName getMessageNameByUid(final MailboxSession session, final MessageUid uid) throws MailboxException { return locker.executeWithLock(session, path, () -> { FileReader fileReader = null; BufferedReader reader = null; File uidList = uidFile; try { fileReader = new FileReader(uidList); reader = new BufferedReader(fileReader); String uidString = String.valueOf(uid.asLong()); String line = reader.readLine(); int lineNumber = 1; while ((line = reader.readLine()) != null) { if (!line.equals("")) { int gap = line.indexOf(" "); if (gap == -1) { <START> LOGGER.info("Corrupted entry in uid-file line {}", uidList, lineNumber++); <END> continue; } if (line.substring(0, gap).equals(uidString)) { return newMaildirMessageName(MaildirFolder.this, line.substring(gap + 1)); } } } return null; } catch (IOException e) { throw new MailboxException("Unable to read messagename for uid " + uid, e); } finally { IOUtils.closeQuietly(reader); IOUtils.closeQuietly(fileReader); } }, true); }</code><technical_language>arguments evaluated _at all_ ? evaluating lineNumber++ a difference here</technical_language>

Target:
public MaildirMessageName getMessageNameByUid(final MailboxSession session, final MessageUid uid) throws MailboxException { return locker.executeWithLock(session, path, () -> { FileReader fileReader = null; BufferedReader reader = null; File uidList = uidFile; try { fileReader = new FileReader(uidList); reader = new BufferedReader(fileReader); String uidString = String.valueOf(uid.asLong()); String line = reader.readLine(); int lineNumber = 1; while ((line = reader.readLine()) != null) { lineNumber++; if (!line.equals("")) { int gap = line.indexOf(" "); if (gap == -1) { LOGGER.info("Corrupted entry in uid-file line {}", uidList, lineNumber); continue; } if (line.substring(0, gap).equals(uidString)) { return newMaildirMessageName(MaildirFolder.this, line.substring(gap + 1)); } } } return null; } catch (IOException e) { throw new MailboxException("Unable to read messagename for uid " + uid, e); } finally { IOUtils.closeQuietly(reader); IOUtils.closeQuietly(fileReader); } }, true); }
Source:
<code><START> public ShareClient createShare(String shareName) { <END> return createShare(shareName, null, null); }</code><technical_language>return type is suppose tobe Response<ShareClient> based design. Is change here</technical_language>

Target:
public Response<ShareClient> createShare(String shareName) { return createShare(shareName, null, null); }
Source:
<code>public void onEnter() { try { getContext().unregisterAuthorizationUpdates(); } catch (final RuntimeException ex) { getLog().error("Unexpected fail during removing callback for registration updates", ex); } try { if (null != exception) { getOut().onException(exception); } } finally { try { getContext().unregisterSession(); } finally { if (null != exception) { <START> getContext().switchStateImmediately(StreamingContext.DEAD_STATE); <END> } else{ switchState(StreamingContext.DEAD_STATE); } } try { getContext().getZkClient().close(); } catch (final IOException e) { getLog().error("Unexpected fail to release zk connection", e); } getContext().getCurrentSpan().finish(); } }</code><technical_language>means subscription switch dead state returned finish clean state. brings behaviour subscription is switched cleanup dead state, cleanup state dead state + in taskQueue for execution executed anyway. sense clean taskQueue, add fresh task, if need switch</technical_language>

Target:
public void onEnter() { try { getContext().unregisterAuthorizationUpdates(); } catch (final RuntimeException ex) { getLog().error("Unexpected fail during removing callback for registration updates", ex); } try { if (null != exception) { getOut().onException(exception); } } finally { try { getContext().unregisterSession(); } finally { switchState(StreamingContext.DEAD_STATE); } try { getContext().getZkClient().close(); } catch (final IOException e) { getLog().error("Unexpected fail to release zk connection", e); } getContext().getCurrentSpan().finish(); } }
Source:
<code>private void processErrorRequest(FilterChain filterChain, HttpServletRequest request, HttpServletResponse response, Span spanFromRequest) throws IOException, ServletException { if (log.isDebugEnabled()) { <START> log.debug("The span was already detached once and we're processing an error"); <END> } try { filterChain.doFilter(request, response); } finally { request.setAttribute(TRACE_ERROR_HANDLED_REQUEST_ATTR, true); this.tracer.close(spanFromRequest); } }</code><technical_language>add span discussed debug message</technical_language>

Target:
private void processErrorRequest(FilterChain filterChain, HttpServletRequest request, HttpServletResponse response, Span spanFromRequest) throws IOException, ServletException { if (log.isDebugEnabled()) { log.debug("The span [" + spanFromRequest + "] was already detached once and we're processing an error"); } try { filterChain.doFilter(request, response); } finally { request.setAttribute(TRACE_ERROR_HANDLED_REQUEST_ATTR, true); addResponseTags(response, null); this.tracer.close(spanFromRequest); } }
Source:
<code>private <T> Bean<?> getBeanFrom(Class<T> type) { Set<Bean<?>> beans = beanManager.getBeans(type); logger.debug("beans for is {}", type, beans); if (beans.isEmpty()) <START> return null; <END> return beanManager.resolve(beans); }</code><technical_language>inline add { }</technical_language>

Target:
private <T> Bean<?> getBeanFrom(Class<T> type) { type = (Class<T>) CDIProxies.extractRawType(type); logger.debug("asking cdi to get instance for {}", type); Set<Bean<?>> beans = beanManager.getBeans(type); logger.debug("beans for is {}", type, beans); if (beans.isEmpty()) { return null; } return beanManager.resolve(beans); }
Source:
<code>public Binder<BindIn, Object> build(final BindIn bindIn) { return (q, param, index, bind, arg) -> { String name = bindIn.value(); if (name.isEmpty()) { if (param.isNamePresent()) { <START> name = param.getName(); <END> } else { throw new UnsupportedOperationException("A @BindIn parameter was not given a name, " + "and parameter name data is not present in the class file, for: " + param.getDeclaringExecutable() + " :: " + param); } } final String key = name; if (arg == null || Util.size(arg) == 0) { switch (bindIn.onEmpty()) { case VOID: break; case NULL: q.bind("__" + key + "_0", (String) null); break; case THROW: final Exception inner = new IllegalArgumentException("argument is null; null was explicitly forbidden on this instance of BindIn"); throw new IllegalStateException("Illegal argument value was caught too late. Please report this to the jdbi developers.", inner); default: throw new IllegalStateException(EmptyHandling.valueNotHandledMessage); } } else { Type parameterType = param == null ? Object.class : param.getParameterizedType(); Type elementType = findGenericParameter(parameterType, Iterable.class) .orElse(Object.class); final Iterator<?> it = Util.toIterator(arg); for (int i = 0; it.hasNext(); i++) { q.bindByType("__" + key + "_" + i, it.next(), elementType); } } }; }</code><technical_language>This logic duplicates DefaultObjectBinder's parameter handling -- worth pulling out a util class? want again</technical_language>

Target:
public Binder<BindIn, Object> build(final BindIn bindIn) { return (q, param, index, bind, arg) -> { final String name = ParameterUtil.getParameterName(bindIn, bindIn.value(), param); if (arg == null || Util.size(arg) == 0) { switch (bindIn.onEmpty()) { case VOID: break; case NULL: q.bind("__" + name + "_0", (String) null); break; case THROW: final Exception inner = new IllegalArgumentException("argument is null; null was explicitly forbidden on this instance of BindIn"); throw new IllegalStateException("Illegal argument value was caught too late. Please report this to the jdbi developers.", inner); default: throw new IllegalStateException(EmptyHandling.valueNotHandledMessage); } } else { Type parameterType = param == null ? Object.class : param.getParameterizedType(); Type elementType = findGenericParameter(parameterType, Iterable.class) .orElse(Object.class); final Iterator<?> it = Util.toIterator(arg); for (int i = 0; it.hasNext(); i++) { q.bindByType("__" + name + "_" + i, it.next(), elementType); } } }; }
Source:
<code>public <T> T getMojoParameterValue(final MavenProject project, final String parameter, final Class<T> type, final Plugin plugin, final ConfigurationContainer configuration, final String goal, IProgressMonitor monitor) throws CoreException { return context().execute(project, new ICallable<T>() { <START> public T call(IMavenExecutionContext context, IProgressMonitor monitor) throws CoreException { <END> return getMojoParameterValue(parameter, type, context.getSession(), plugin, configuration, goal); } }, monitor); }</code><technical_language>unnecessary change</technical_language>

Target:
public <T> T getMojoParameterValue(final MavenProject project, final String parameter, final Class<T> type, final Plugin plugin, final ConfigurationContainer configuration, final String goal, IProgressMonitor monitor) throws CoreException { return context().execute(project, (context, pm) -> getMojoParameterValue(parameter, type, context.getSession(), plugin, configuration, goal), monitor); }
Source:
<code>private void recordValidTxns(HiveTxnManager txnMgr) throws LockException { String oldTxnString = conf.get(ValidTxnList.VALID_TXNS_KEY); if ((oldTxnString != null) && (oldTxnString.length() > 0)) { throw new IllegalStateException("calling recordValidTxn() more than once in the same " + JavaUtils.txnIdToString(txnMgr.getCurrentTxnId())); } ValidTxnList txnList = txnMgr.getValidTxns(); String txnStr = txnList.toString(); conf.set(ValidTxnList.VALID_TXNS_KEY, txnStr); <START> LOG.info("Encoding valid txns info " + txnStr + " txnid:" + txnMgr.getCurrentTxnId()); <END> }</code><technical_language>txnStr huge in case of large opened txns ..is safe add a info log</technical_language>

Target:
private void recordValidTxns(HiveTxnManager txnMgr) throws LockException { String oldTxnString = conf.get(ValidTxnList.VALID_TXNS_KEY); if ((oldTxnString != null) && (oldTxnString.length() > 0)) { throw new IllegalStateException("calling recordValidTxn() more than once in the same " + JavaUtils.txnIdToString(txnMgr.getCurrentTxnId())); } ValidTxnList txnList = txnMgr.getValidTxns(); String txnStr = txnList.toString(); conf.set(ValidTxnList.VALID_TXNS_KEY, txnStr); LOG.debug("Encoding valid txns info " + txnStr + " txnid:" + txnMgr.getCurrentTxnId()); }
Source:
<code>public void releaseStore(final Store<?, ?> resource) { ClusteredStore clusteredStore = (ClusteredStore)resource; <START> this.clusteringService.releaseServerStoreProxy(clusteredStore.storeProxy); <END> }</code><technical_language>other Store.Provider do some level of accounting - done here</technical_language>

Target:
public void releaseStore(final Store<?, ?> resource) { if (createdStores.remove(resource) == null) { throw new IllegalArgumentException("Given store is not managed by this provider : " + resource); } ClusteredStore clusteredStore = (ClusteredStore)resource; this.clusteringService.releaseServerStoreProxy(clusteredStore.storeProxy); }
Source:
<code>private void setSelectedNetworkQoSId(Guid networkQoSId) { for (Object item : getNetworkQoS().getItems()) { if (((NetworkQoS) item).getId().equals(networkQoSId)) { getNetworkQoS().setSelectedItem(item); return; } } <START> setSelectedNetworkQoSId(Guid.Empty); <END> }</code><technical_language>related this refactoring, do need a recursion call here? select empty item</technical_language>

Target:
private void setSelectedNetworkQoSId(Guid networkQoSId) { for (Object item : getNetworkQoS().getItems()) { if (((NetworkQoS) item).getId().equals(networkQoSId)) { getNetworkQoS().setSelectedItem(item); return; } } getNetworkQoS().setSelectedItem(getEmptyQos()); }
Source:
<code><START> String getKey() { <END> return keySet.get(random.nextInt(keySet.size())); }</code><technical_language>![Codacy](<LINK_0> Issue found: [Use explicit scoping instead of default package private level](<LINK_1></technical_language>

Target:
protected String getKey() { return keySet.get(random.nextInt(keySet.size())); }
Source:
<code>public void initialize(ResourceManager nerRm) { if (ViewNames.NER_ONTONOTES.equals(getViewName())) nerRm = new NerOntonotesConfigurator().getConfig(nerRm); else nerRm = new NerBaseConfigurator().getConfig(nerRm); ParametersForLbjCode.currentParameters.forceNewSentenceOnLineBreaks = false; Parameters.readConfigAndLoadExternalData(nerRm); String dataset; if(viewName.toLowerCase().contains("conll")) { dataset = "enron-conll"; } else { dataset = "ontonotes"; } String data_split = nerRm.getString(NerBaseConfigurator.TRAINED_ON); try { <START> Datastore ds = new Datastore(new ResourceConfigurator().getDefaultConfig()); <END> String artifact_id = "ner-model-" + dataset + "-" + data_split; File modelDir = ds.getDirectory("edu.illinois.cs.cogcomp.ner", artifact_id, 4.0, false); String model = ""; if(modelDir.getPath().contains("conll")) { model = modelDir.getPath() + "/model/EnronCoNLL.model"; } else { model = modelDir.getPath() + "/model/OntoNotes.model"; } NETaggerLevel1 tagger1 = new NETaggerLevel1(model + ".level1", model + ".level1.lex"); NETaggerLevel2 tagger2 = null; if (ParametersForLbjCode.currentParameters.featuresToUse.containsKey("PredictionsLevel1")) { tagger2 = new NETaggerLevel2(model + ".level2", model + ".level2.lex"); } this.t1 = tagger1; this.t2 = tagger2; } catch (InvalidPortException | DatastoreException | InvalidEndpointException e) { e.printStackTrace(); } }</code><technical_language>this ResourceManager argument provided constructor overwrite properties user wants configure</technical_language>

Target:
public void initialize(ResourceManager nerRm) { if (ViewNames.NER_ONTONOTES.equals(getViewName())) nerRm = new NerOntonotesConfigurator().getConfig(nerRm); else nerRm = new NerBaseConfigurator().getConfig(nerRm); ParametersForLbjCode.currentParameters.forceNewSentenceOnLineBreaks = false; Parameters.readConfigAndLoadExternalData(nerRm); String dataset; if(viewName.toLowerCase().contains("conll")) { dataset = "enron-conll"; } else { dataset = "ontonotes"; } String data_split = nerRm.getString(NerBaseConfigurator.TRAINED_ON); try { Datastore ds = new Datastore(new ResourceConfigurator().getConfig(nerRm)); String artifact_id = "ner-model-" + dataset + "-" + data_split; File modelDir = ds.getDirectory("edu.illinois.cs.cogcomp.ner", artifact_id, 4.0, false); String model = ""; if(modelDir.getPath().contains("conll")) { model = modelDir.getPath() + "/model/EnronCoNLL.model"; } else { model = modelDir.getPath() + "/model/OntoNotes.model"; } NETaggerLevel1 tagger1 = new NETaggerLevel1(model + ".level1", model + ".level1.lex"); NETaggerLevel2 tagger2 = null; if (ParametersForLbjCode.currentParameters.featuresToUse.containsKey("PredictionsLevel1")) { tagger2 = new NETaggerLevel2(model + ".level2", model + ".level2.lex"); } this.t1 = tagger1; this.t2 = tagger2; } catch (InvalidPortException | DatastoreException | InvalidEndpointException e) { e.printStackTrace(); } }