auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private <T> BinaryContent transformSourceResponse( SourceResponse response, Map<String, Serializable> transformerArguments, String identString, Function<T, List<QueryResponseTransformer>> func, T id) throws CatalogTransformerException { if (response == null) { throw new IllegalArgumentException("SourceResponse is null."); } List<QueryResponseTransformer> transformers = func.apply(id); if (CollectionUtils.isEmpty(transformers)) { throw new IllegalArgumentException( "Transformers mathcing " + identString + " " + id + " not found"); } List<String> stackTraceList = new LinkedList<>(); BinaryContent binaryContent = transformSourceResponse(response, transformerArguments, transformers, stackTraceList::add); if (binaryContent == null) { throw new CatalogTransformerException( String.format( <START> "Could not transform source response: " + identString + "=%s : %s", <END> id, StringUtils.join(stackTraceList, "\n"))); } return binaryContent; }</code><technical_language>Mixing string concatenation format() is confusing. another %s for identString</technical_language>

Target:
private <T> BinaryContent transformSourceResponse( SourceResponse response, Map<String, Serializable> transformerArguments, String identString, Function<T, List<QueryResponseTransformer>> func, T id) throws CatalogTransformerException { if (response == null) { throw new IllegalArgumentException("SourceResponse is null."); } List<QueryResponseTransformer> transformers = func.apply(id); if (CollectionUtils.isEmpty(transformers)) { throw new IllegalArgumentException( "Transformers matching " + identString + " " + id + " not found"); } List<String> stackTraceList = new LinkedList<>(); BinaryContent binaryContent = transformSourceResponse(response, transformerArguments, transformers, stackTraceList::add); if (binaryContent == null) { throw new CatalogTransformerException( String.format( "Could not transform source response: %s=%s : %s", identString, id, StringUtils.join(stackTraceList, "\n"))); } return binaryContent; }
Source:
<code>public Scope getScopeForService(final Integer nodeId, final InetAddress ipAddress, final String serviceName) { if (nodeId == null || ipAddress == null || Strings.isNullOrEmpty(serviceName)) { return EmptyScope.EMPTY; } final Scope metaDataScope = this.transactions.execute((tx) -> { final OnmsMonitoredService monitoredService = this.monitoredServiceDao.get(nodeId, ipAddress, serviceName); if (monitoredService == null) { return EmptyScope.EMPTY; } return new FallbackScope(transform(monitoredService.getMetaData()), new ObjectScope<>(monitoredService) .map("service", "name", (s) -> Optional.of(s.getServiceName())) <START> .map("service", "type", (s) -> Optional.of(s.getServiceType().getName())) <END> ); }); return metaDataScope; }</code><technical_language>getServiceName() == getServiceType().getName() this sense</technical_language>

Target:
public Scope getScopeForService(final Integer nodeId, final InetAddress ipAddress, final String serviceName) { if (nodeId == null || ipAddress == null || Strings.isNullOrEmpty(serviceName)) { return EmptyScope.EMPTY; } final Scope metaDataScope = this.transactions.execute((tx) -> { final OnmsMonitoredService monitoredService = this.monitoredServiceDao.get(nodeId, ipAddress, serviceName); if (monitoredService == null) { return EmptyScope.EMPTY; } return new FallbackScope(transform(monitoredService.getMetaData()), new ObjectScope<>(monitoredService) .map("service", "name", (s) -> Optional.of(s.getServiceName())) ); }); return metaDataScope; }
Source:
<code>public abstract FetchConnection openFetch() throws NotSupportedException, TransportException; public abstract PushConnection openPush() throws NotSupportedException, TransportException; public SubscribeConnection openSubscribe() throws NotSupportedException, TransportException { <START> throw new NotSupportedException("Subscribe not supported"); <END> }</code><technical_language>a text properties file</technical_language>

Target:
public abstract FetchConnection openFetch() throws NotSupportedException, TransportException; public abstract PushConnection openPush() throws NotSupportedException, TransportException; public SubscribeConnection openSubscribe() throws NotSupportedException, TransportException { throw new NotSupportedException(JGitText.get().subscribeNotSupported); }
Source:
<code>public void checkAttributeValue(PerunSessionImpl perunSession, Resource resource, Attribute attribute) throws InternalErrorException, WrongAttributeValueException { String role = (String)attribute.getValue(); if (role == null) { throw new WrongAttributeValueException(attribute, resource, "Attribute value is null."); } <START> else if ((!role.equals("Manager") || !role.equals("Reporter") || !role.equals("Developer")) { <END> throw new WrongAttributeValueException(attribute, resource, "Attribute value is invalid."); } }</code><technical_language>This condition true</technical_language>

Target:
public void checkAttributeValue(PerunSessionImpl perunSession, Resource resource, Attribute attribute) throws InternalErrorException, WrongAttributeValueException { String role = (String)attribute.getValue(); if (role == null) { throw new WrongAttributeValueException(attribute, resource, "Attribute value is null."); } else if (!role.equals("Manager") && !role.equals("Reporter") && !role.equals("Developer")) { throw new WrongAttributeValueException(attribute, resource, "Attribute value is invalid.The role can be either Manager, Reporter or Developer"); } }
Source:
<code>public String toString() { <START> this.format.setTimeZone(TimeZone.getTimeZone("GMT")); <END> return this.format.format(this.expires); }</code><technical_language>@t-izbassar do yo SimpleDateFormat is thread-safe? ThreadLocal new instance time</technical_language>

Target:
public String toString() { final SimpleDateFormat fmt = this.format.get(); fmt.setTimeZone(TimeZone.getTimeZone("GMT")); return fmt.format(this.expires); }
Source:
<code>private String invalidCursorMessage(final CursorError error, final Cursor cursor) { switch (error) { case PARTITION_NOT_FOUND: return "non existing partition " + cursor.getPartition(); case EMPTY_PARTITION: return "partition " + cursor.getPartition() + " is empty"; case UNAVAILABLE: <START> return "offset " + cursor.getOffset() + " for partition " + cursor.getPartition() + " unavailable"; <END> default: return "invalid offset " + cursor.getOffset() + " for partition " + cursor.getPartition(); } }</code><technical_language>**is** unavailable</technical_language>

Target:
private String invalidCursorMessage(final CursorError error, final Cursor cursor) { switch (error) { case PARTITION_NOT_FOUND: return "non existing partition " + cursor.getPartition(); case EMPTY_PARTITION: return "partition " + cursor.getPartition() + " is empty"; case UNAVAILABLE: return "offset " + cursor.getOffset() + " for partition " + cursor.getPartition() + " is unavailable"; default: return "invalid offset " + cursor.getOffset() + " for partition " + cursor.getPartition(); } }
Source:
<code>public StorageQuotaConfig(VerifiableProperties verifiableProperties) { helixPropertyRootPath = verifiableProperties.getString(HELIX_PROPERTY_ROOT_PATH); zkClientConnectAddress = verifiableProperties.getString(ZK_CLIENT_CONNECT_ADDRESS); <START> refresherPollingIntervalMs = <END> verifiableProperties.getIntInRange(REFRESHER_POLLING_INTERVAL_MS, 30 * 60 * 1000, 0, Integer.MAX_VALUE); containerStorageQuotaInJson = verifiableProperties.getString(CONTAINER_STORAGE_QUOTA_IN_JSON, ""); sourcePollingIntervalMs = verifiableProperties.getInt(SOURCE_POLLING_INTERVAL_MS, 30 * 60 * 1000); }</code><technical_language>Minor: getIntInRange for sourcePollingIntervalMs well</technical_language>

Target:
public StorageQuotaConfig(VerifiableProperties verifiableProperties) { helixPropertyRootPath = verifiableProperties.getString(HELIX_PROPERTY_ROOT_PATH); zkClientConnectAddress = verifiableProperties.getString(ZK_CLIENT_CONNECT_ADDRESS); refresherPollingIntervalMs = verifiableProperties.getIntInRange(REFRESHER_POLLING_INTERVAL_MS, 30 * 60 * 1000, 0, Integer.MAX_VALUE); containerStorageQuotaInJson = verifiableProperties.getString(CONTAINER_STORAGE_QUOTA_IN_JSON, ""); sourcePollingIntervalMs = verifiableProperties.getIntInRange(SOURCE_POLLING_INTERVAL_MS, 30 * 60 * 1000, 0, Integer.MAX_VALUE); }
Source:
<code>public static void showActivityResultError(Activity activity, int requestCode, int actResp, int errorCode, int errorDescription) { if (activity == null) { Log.e("BaseGameUtils", "*** No Activity. Can't show failure dialog!"); return; } Dialog errorDialog = null; switch (actResp) { case GamesActivityResultCodes.RESULT_APP_MISCONFIGURED: errorDialog = makeSimpleDialog(activity, GameHelperUtils_old.getString( <START> activity, GameHelperUtils_old.R_APP_MISCONFIGURED)); <END> break; case GamesActivityResultCodes.RESULT_SIGN_IN_FAILED: errorDialog = makeSimpleDialog(activity, GameHelperUtils_old.getString( activity, GameHelperUtils_old.R_SIGN_IN_FAILED)); break; case GamesActivityResultCodes.RESULT_LICENSE_FAILED: errorDialog = makeSimpleDialog(activity, GameHelperUtils_old.getString( activity, GameHelperUtils_old.R_LICENSE_FAILED)); break; default: errorDialog = GooglePlayServicesUtil.getErrorDialog(errorCode, activity, requestCode, null); if (errorDialog == null) { Log.e("GameHelper", "No standard error dialog available. Making fallback dialog."); errorDialog = makeSimpleDialog( activity, activity.getString(errorCode) + " " + activity.getString(errorDescription)); } } errorDialog.show(); }</code><technical_language>GameHelperUtils_old is present for me</technical_language>

Target:
public static void showActivityResultError(Activity activity, int requestCode, int actResp, int errorCode, int errorDescription) { if (activity == null) { Log.e("BaseGameUtils", "*** No Activity. Can't show failure dialog!"); return; } Dialog errorDialog; switch (actResp) { case GamesActivityResultCodes.RESULT_APP_MISCONFIGURED: errorDialog = makeSimpleDialog(activity, activity.getString(R.string.gamehelper_app_misconfigured)); break; case GamesActivityResultCodes.RESULT_SIGN_IN_FAILED: errorDialog = makeSimpleDialog(activity, activity.getString(R.string.gamehelper_sign_in_failed)); break; case GamesActivityResultCodes.RESULT_LICENSE_FAILED: errorDialog = makeSimpleDialog(activity, activity.getString(R.string.gamehelper_license_failed)); break; default: errorDialog = GooglePlayServicesUtil.getErrorDialog(errorCode, activity, requestCode, null); if (errorDialog == null) { Log.e("BaseGamesUtils", "No standard error dialog available. Making fallback dialog."); errorDialog = makeSimpleDialog( activity, activity.getString(errorCode) + " " + activity.getString(errorDescription)); } } errorDialog.show(); }
Source:
<code>protected List<EventRecord> dispatchCommand(Message command, CommandContext context) throws InvocationTargetException { <START> checkNotNull(command, "command is null"); <END> checkNotNull(context, "command context is null"); init(); final Class<? extends Message> commandClass = command.getClass(); final Method method = commandHandlers.get(commandClass); if (method == null) { throw missingCommandHandler(commandClass); } final CommandHandlerMethod commandHandler = new CommandHandlerMethod(this, method); final List<? extends Message> events = commandHandler.invoke(command, context); final List<EventRecord> eventRecords = toEventRecords(events, context.getCommandId()); return eventRecords; }</code><technical_language>"command". information nullity in fact of NPE in stack trace</technical_language>

Target:
protected List<EventRecord> dispatchCommand(Message command, CommandContext context) throws InvocationTargetException { checkNotNull(command, "command"); checkNotNull(context, "context"); init(); final Class<? extends Message> commandClass = command.getClass(); final Method method = commandHandlers.get(commandClass); if (method == null) { throw missingCommandHandler(commandClass); } final CommandHandlerMethod commandHandler = new ProcessManagerCommandHandler(this, method); final List<? extends Message> events = commandHandler.invoke(command, context); final List<EventRecord> eventRecords = toEventRecords(events, context.getCommandId()); return eventRecords; }
Source:
<code>public AppiumDriver createInstance(WebDriverConfiguration configuration) { Capabilities capabilities = getCapabilities(configuration); String platform = (String)capabilities.getCapability(MobileCapabilityType.PLATFORM_NAME); if (StringUtils.isBlank(platform)) { throw new IllegalArgumentException("You have to specify " + MobileCapabilityType.PLATFORM_NAME); } platform = platform.toLowerCase(); Class<? extends AppiumDriver> driverClass; if (MobilePlatform.ANDROID.toLowerCase().equals(platform)) driverClass = AndroidDriver.class; else if (MobilePlatform.IOS.toLowerCase().equals(platform)) driverClass = IOSDriver.class; else if (MobilePlatform.WINDOWS.toLowerCase().equals(platform)) driverClass = WindowsDriver.class; <START> else driverClass = AppiumDriver.class; <END> URL remoteAddress = configuration.getRemoteAddress(); try { if (remoteAddress == null) return driverClass.getConstructor(Capabilities.class).newInstance(capabilities); else return driverClass.getConstructor(URL.class, Capabilities.class).newInstance(remoteAddress, capabilities); } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>reformat curly brackets format. switch statement if possible</technical_language>

Target:
public AppiumDriver createInstance(WebDriverConfiguration configuration) { Capabilities capabilities = getCapabilities(configuration); String platform = (String)capabilities.getCapability(MobileCapabilityType.PLATFORM_NAME); if (Validate.empty(platform)) { throw new IllegalArgumentException("You have to specify " + MobileCapabilityType.PLATFORM_NAME); } platform = platform.toLowerCase(); Class<? extends AppiumDriver> driverClass; if (MobilePlatform.ANDROID.toLowerCase().equals(platform)) { driverClass = AndroidDriver.class; } else if (MobilePlatform.IOS.toLowerCase().equals(platform)) { driverClass = IOSDriver.class; } else if (MobilePlatform.WINDOWS.toLowerCase().equals(platform)) { driverClass = WindowsDriver.class; } else { driverClass = AppiumDriver.class; } URL remoteAddress = configuration.getRemoteAddress(); try { if (remoteAddress == null) { return driverClass.getConstructor(Capabilities.class).newInstance(capabilities); } else { return driverClass.getConstructor(URL.class, Capabilities.class).newInstance(remoteAddress, capabilities); } } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>private String toDoc(ChangeData cd) throws IOException { XContentBuilder builder = jsonBuilder().startObject(); for (Values<ChangeData> values : schema.buildFields(cd, fillArgs)) { String name = values.getField().getName(); if (values.getField().isRepeatable()) { builder.array(name, values.getValues()); } else { for (Object value : values.getValues()) { if <START> (value.equals("")) { <END> continue; } builder.field(name, value); } } } return builder.endObject().string(); }</code><technical_language>Do need cast this String? null</technical_language>

Target:
private String toDoc(ChangeData cd) throws IOException { XContentBuilder builder = jsonBuilder().startObject(); for (Values<ChangeData> values : schema.buildFields(cd, fillArgs)) { String name = values.getField().getName(); if (values.getField().isRepeatable()) { builder.array(name, values.getValues()); } else { for (Object value : values.getValues()) { if (value == null || ((String)value).isEmpty()) { continue; } builder.field(name, value); } } } return builder.endObject().string(); }
Source:
<code>public void onNewUser(User user) { boolean createAccount = mActivityHelper.getFlowParams().createAccountIfEmailNotExists; if (createAccount) { RegisterEmailFragment fragment = RegisterEmailFragment.getInstance( mActivityHelper.getFlowParams(), user); FragmentTransaction ft = getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_register_email, fragment, RegisterEmailFragment.TAG); View v = findViewById(R.id.email_layout); if (v != null) ft.addSharedElement(v, "email_field"); ft.disallowAddToBackStack().commit(); } else { <START> finish(ResultCodes.NO_EMAIL_ACCOUNT, IdpResponse.getErrorCodeIntent(ErrorCodes.UNKNOWN_ERROR)); <END> } }</code><technical_language>I calling finish() is a severe, user reach this state a result of a typo. add error email text field account exists for this email address similar</technical_language>

Target:
public void onNewUser(User user) { boolean createAccount = mActivityHelper.getFlowParams().allowNewEmailAccounts; TextInputLayout mEmailLayout = (TextInputLayout) findViewById(R.id.email_layout); if (createAccount) { RegisterEmailFragment fragment = RegisterEmailFragment.getInstance( mActivityHelper.getFlowParams(), user); FragmentTransaction ft = getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_register_email, fragment, RegisterEmailFragment.TAG); if (mEmailLayout != null) ft.addSharedElement(mEmailLayout, "email_field"); ft.disallowAddToBackStack().commit(); } else { mEmailLayout.setError(getString(R.string.error_email_does_not_exist)); } }
Source:
<code>protected FixedBlock getOrCreateCurrentBlock() { FixedBlock block = blocks.get(currentBlockIndex); if (block == null) { block = new FixedBlock(blockCapacity); blocks.put(currentBlockIndex, block); if (blocks.size() % 50 == 0) { <START> logger.info("blocks: {}, size of each block: {}", blocks.size(), blockCapacity); <END> } } return block; }</code><technical_language>debug</technical_language>

Target:
protected FixedBlock getOrCreateCurrentBlock() { FixedBlock block = blocks.get(currentBlockIndex); if (block == null) { block = new FixedBlock(blockCapacity); blocks.put(currentBlockIndex, block); if (blocks.size() % 50 == 0) { logger.info("Assigned blocks: {}, size of each block: {}", blocks.size(), blockCapacity); } } return block; }
Source:
<code>public void extendTicket(Guid ticketUUID, long timeout) { BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest( "PATCH", TICKETS_URI + ticketUUID, HttpVersion.HTTP_1_1); Map<String, Object> timeoutDict = new HashMap<>(); timeoutDict.put("timeout", timeout); StringEntity entity = new StringEntity(new Gson().toJson(timeoutDict), StandardCharsets.UTF_8); request.setEntity(entity); request.setHeader("content-length", String.valueOf(entity.getContentLength())); DefaultBHttpClientConnection conn = getConnection(); HttpEntity response = executeRequest(request, conn); <START> finalize(response, conn); <END> }</code><technical_language>above, try resources</technical_language>

Target:
public void extendTicket(Guid ticketUUID, long timeout) { BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest( "PATCH", TICKETS_URI + ticketUUID, HttpVersion.HTTP_1_1); try (DefaultBHttpClientConnection conn = getConnection()) { Map<String, Object> timeoutDict = new HashMap<>(); timeoutDict.put("timeout", timeout); StringEntity entity = new StringEntity( new ObjectMapper().writeValueAsString(timeoutDict), StandardCharsets.UTF_8); request.setEntity(entity); request.setHeader("content-length", String.valueOf(entity.getContentLength())); consumeResponse(executeRequest(request, conn)); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } }
Source:
<code>public int getCodeReviewScore() { String reviewScore = review.getAttribute(Messages.TaskEditorReviewsPart_CodeReviewAttribute); if (reviewScore.equals("")) { return 0; } else { <START> return Integer.parseInt(reviewScore); <END> } }</code><technical_language>Catch exception return 0</technical_language>

Target:
public int getCodeReviewScore() { String reviewScore = review.getAttribute(Messages.TaskEditorReviewsPart_CodeReviewAttribute); try { return Integer.parseInt(reviewScore); } catch (NumberFormatException e) { return 0; } }
Source:
<code>public boolean isHostExists(List<GlusterServerInfo> glusterServers, VDS server) { if (GlusterFeatureSupported.glusterHostUuidSupported(server.getVdsGroupCompatibilityVersion())) { GlusterServer glusterServer = DbFacade.getInstance().getGlusterServerDao().getByServerId(server.getId()); if (glusterServer != null) { for (GlusterServerInfo glusterServerInfo : glusterServers) { if (glusterServerInfo.getUuid().equals(glusterServer.getGlusterServerUuid())) { return true; } } } } else { for (GlusterServerInfo glusterServer : glusterServers) { if (glusterServer.getHostnameOrIp().equals(server.getHostName())) { return true; } try { String glusterHostAddr = InetAddress.getByName(glusterServer.getHostnameOrIp()).getHostAddress(); for (VdsNetworkInterface vdsNwInterface : getVdsInterfaces(server.getId())) { if (glusterHostAddr.equals(vdsNwInterface.getAddress())) { return true; } } } catch (UnknownHostException e) { <START> log.errorFormat("Could not resole IP address of the host {0}. Error: {1}", <END> glusterServer.getHostnameOrIp(), e.getMessage()); } } } return false; }</code><technical_language>%s/resole/resolve/g</technical_language>

Target:
public boolean isHostExists(List<GlusterServerInfo> glusterServers, VDS server) { if (GlusterFeatureSupported.glusterHostUuidSupported(server.getVdsGroupCompatibilityVersion())) { GlusterServer glusterServer = DbFacade.getInstance().getGlusterServerDao().getByServerId(server.getId()); if (glusterServer != null) { for (GlusterServerInfo glusterServerInfo : glusterServers) { if (glusterServerInfo.getUuid().equals(glusterServer.getGlusterServerUuid())) { return true; } } } } else { for (GlusterServerInfo glusterServer : glusterServers) { if (glusterServer.getHostnameOrIp().equals(server.getHostName())) { return true; } try { String glusterHostAddr = InetAddress.getByName(glusterServer.getHostnameOrIp()).getHostAddress(); for (VdsNetworkInterface vdsNwInterface : getVdsInterfaces(server.getId())) { if (glusterHostAddr.equals(vdsNwInterface.getAddress())) { return true; } } } catch (UnknownHostException e) { log.errorFormat("Could not resolve IP address of the host {0}. Error: {1}", glusterServer.getHostnameOrIp(), e.getMessage()); } } } return false; }
Source:
<code>private @Nullable Product parseLineProductFromMode(final String modeId) { final String modeType = modeId.replace("physical_mode:", ""); final PhysicalMode physicalMode = PhysicalMode.valueOf(modeType.toUpperCase()); switch (physicalMode) { case BUS: case NA: <START> return Product.SUBWAY; <END> case BUSRAPIDTRANSIT: case COACH: case SHUTTLE: return Product.BUS; case RAPIDTRANSIT: case TRAIN: case LOCALTRAIN: case LONGDISTANCETRAIN: case VAL: return Product.SUBURBAN_TRAIN; case TRAMWAY: case TRAM: return Product.TRAM; case METRO: return Product.SUBWAY; case FERRY: return Product.FERRY; case FUNICULAR: return Product.CABLECAR; case TAXI: return Product.ON_DEMAND; case OTHER: return null; default: throw new IllegalArgumentException("Unhandled physical mode: " + modeId); } }</code><technical_language>sense add this for *all* Navitia providers. NA stand for? If means "not available", subway. Also, Skytrain in Vancover is more SUBURBAN_TRAIN TRAM SUBWAY argue</technical_language>

Target:
private @Nullable Product parseLineProductFromMode(final String modeId) { final String modeType = modeId.replace("physical_mode:", ""); final PhysicalMode physicalMode = PhysicalMode.valueOf(modeType.toUpperCase()); switch (physicalMode) { case BUS: case BUSRAPIDTRANSIT: case COACH: case SHUTTLE: return Product.BUS; case RAPIDTRANSIT: case TRAIN: case LOCALTRAIN: case LONGDISTANCETRAIN: case VAL: return Product.SUBURBAN_TRAIN; case TRAMWAY: case TRAM: return Product.TRAM; case METRO: return Product.SUBWAY; case FERRY: return Product.FERRY; case FUNICULAR: return Product.CABLECAR; case TAXI: return Product.ON_DEMAND; case OTHER: return null; case NA: return null; default: throw new IllegalArgumentException("Unhandled physical mode: " + modeId); } }
Source:
<code>private static void addBundleToMap(Map<IPluginModelBase, String> map, IPluginModelBase bundle, String sl) { BundleDescription desc = bundle.getBundleDescription(); boolean defaultsl = (sl == null || sl.equals("default:default")); <START> if (cfgIniBundleStartInfo.isEmpty()) { <END> if (desc != null && defaultsl) { String runLevelText = resolveSystemRunLevelText(bundle); String autoText = resolveSystemAutoText(bundle); if (runLevelText != null && autoText != null) { map.put(bundle, runLevelText + ":" + autoText); } else { map.put(bundle, sl); } } else { map.put(bundle, sl); } } else { sl = resolveConfigIni(bundle); map.put(bundle, sl); } }</code><technical_language>this resolve system startlevel/autostart defaults, bundle is present in supplied config.ini simply overwrite 'sl' map</technical_language>

Target:
private static void addBundleToMap(Map<IPluginModelBase, String> map, IPluginModelBase bundle, String sl) { BundleDescription desc = bundle.getBundleDescription(); boolean defaultsl = (sl == null || sl.equals("default:default")); if (cfgIniBundleStartInfo != null && cfgIniBundleStartInfo.isEmpty()) { if (desc != null && defaultsl) { String runLevelText = resolveSystemRunLevelText(bundle); String autoText = resolveSystemAutoText(bundle); if (runLevelText != null && autoText != null) { map.put(bundle, runLevelText + ":" + autoText); } else { map.put(bundle, sl); } } else { map.put(bundle, sl); } } else { sl = resolveConfigIni(bundle); map.put(bundle, sl); } }
Source:
<code>protected String createPayload(FirewallRule.Request.UpdatePayload payload) { checkNotNull(payload, "payload"); checkNotNull(payload.dataCenterId(), "dataCenterId"); checkNotNull(payload.serverId(), "serverId"); checkNotNull(payload.nicId(), "nicId"); checkNotNull(payload.id(), "id"); dataCenterId = payload.dataCenterId(); serverId = payload.serverId(); nicId = payload.nicId(); id = payload.id(); if (payload.name() != null) requestBuilder.put("name", payload.name()); if (payload.sourceMac() != null) requestBuilder.put("sourceMac", payload.sourceMac()); if (payload.sourceIp() != null) requestBuilder.put("sourceIp", payload.sourceIp()); if (payload.targetIp() != null) requestBuilder.put("targetIp", payload.targetIp()); if (payload.icmpCode() != null) requestBuilder.put("icmpCode", payload.icmpCode()); if (payload.icmpType() != null) requestBuilder.put("icmpType", payload.icmpType()); if (payload.portRangeStart() != null) requestBuilder.put("portRangeStart", payload.portRangeStart()); if (payload.portRangeEnd() != null) <START> requestBuilder.put("portRangeEnd", payload.portRangeEnd()); <END> return jsonBinder.toJson(requestBuilder); }</code><technical_language>This pattern is introduces verbosity code. Consider making a method int base class puIfPresent so, remove boilerplate</technical_language>

Target:
protected String createPayload(FirewallRule.Request.UpdatePayload payload) { checkNotNull(payload, "payload"); checkNotNull(payload.dataCenterId(), "dataCenterId"); checkNotNull(payload.serverId(), "serverId"); checkNotNull(payload.nicId(), "nicId"); checkNotNull(payload.id(), "id"); dataCenterId = payload.dataCenterId(); serverId = payload.serverId(); nicId = payload.nicId(); id = payload.id(); putIfPresent(requestBuilder, "name", payload.name()); putIfPresent(requestBuilder, "sourceMac", payload.sourceMac()); putIfPresent(requestBuilder, "sourceIp", payload.sourceIp()); putIfPresent(requestBuilder, "targetIp", payload.targetIp()); putIfPresent(requestBuilder, "icmpCode", payload.icmpCode()); putIfPresent(requestBuilder, "icmpType", payload.icmpType()); putIfPresent(requestBuilder, "portRangeStart", payload.portRangeStart()); putIfPresent(requestBuilder, "portRangeEnd", payload.portRangeEnd()); return jsonBinder.toJson(requestBuilder); }
Source:
<code>protected void thisApplyNext(final IConfig config, final IConfig prevFull) { final String systemName = _sysConfig.getSystemName(); final Collection<IParameter> sysConfig = _sysConfig.getParameters(); for (final IParameter param : sysConfig) { config.putParameter(systemName, DefaultParameter.getInstance(param.getName(), param.getValue())); } config.putParameter(systemName, StringParameter.getInstance(InstConstants.INSTRUMENT_NAME_PROP, Gpi.INSTRUMENT_NAME_PROP)); final ISPObsComponent targetcomp = SPTreeUtil.findTargetEnvNode(getObsComponent().getContextObservation()); if (targetcomp != null) { final TargetObsComp toc = (TargetObsComp) targetcomp.getDataObject(); if (toc != null) { toc.getAsterism().allSpTargetsJava().headOption().foreach(base -> { final ImList<Magnitude> magnitudes = base.getMagnitudesJava(); MAG_PROPERTIES.forEach((band, propName) -> magnitudes.find(m -> m.band().equals(band)). <START> foreach(mag -> config.putParameter(systemName, DefaultParameter.getInstance(propName, mag)))); <END> }); } } }</code><technical_language>changed type of object storing in sequence? java config.putParameter(systemName, DefaultParameter.getInstance(magProp, magnitude.value())); is a Double is Magnitude instance itself</technical_language>

Target:
protected void thisApplyNext(final IConfig config, final IConfig prevFull) { final String systemName = _sysConfig.getSystemName(); final Collection<IParameter> sysConfig = _sysConfig.getParameters(); for (final IParameter param : sysConfig) { config.putParameter(systemName, DefaultParameter.getInstance(param.getName(), param.getValue())); } config.putParameter(systemName, StringParameter.getInstance(InstConstants.INSTRUMENT_NAME_PROP, Gpi.INSTRUMENT_NAME_PROP)); final ISPObsComponent targetcomp = SPTreeUtil.findTargetEnvNode(getObsComponent().getContextObservation()); if (targetcomp != null) { final TargetObsComp toc = (TargetObsComp) targetcomp.getDataObject(); if (toc != null) { toc.getAsterism().allSpTargetsJava().headOption().foreach(base -> { final ImList<Magnitude> magnitudes = base.getMagnitudesJava(); MAG_PROPERTIES.forEach((band, propName) -> magnitudes.find(m -> m.band().equals(band)). foreach(mag -> config.putParameter(systemName, DefaultParameter.getInstance(propName, mag.value())))); }); } } }
Source:
<code>protected boolean validate() { oldHost = vdsDao.get(getVdsId()); boolean validateAgents=true; <START> if (getParameters().getFenceAgents() == null || getParameters().getFenceAgents().isEmpty()) { <END> getParameters().setFenceAgents(fenceAgentDao.getFenceAgentsForHost(getVdsId())); validateAgents = false; } UpdateHostValidator validator = getUpdateHostValidator(oldHost, getParameters().getvds(), getParameters().isInstallHost()); return validate(validator.hostExists()) && validate(validator.hostStatusValid()) && validate(validator.nameNotEmpty()) && validate(validator.nameLengthIsLegal()) && validate(validator.updateHostAddressAllowed()) && validate(validator.nameNotUsed()) && validate(validator.hostNameNotUsed()) && validate(validator.statusSupportedForHostInstallation()) && validate(validator.passwordProvidedForHostInstallation(getParameters().getAuthMethod(), getParameters().getPassword())) && validate(validator.updatePortAllowed()) && validate(validator.clusterNotChanged()) && validate(validator.hostProviderExists()) && validate(validator.hostProviderTypeMatches()) && validateNetworkProviderConfiguration() && isPowerManagementLegal(getParameters().getVdsStaticData().isPmEnabled(), getParameters().getFenceAgents(), oldHost.getClusterCompatibilityVersion().toString(), validateAgents) && validate(validator.supportsDeployingHostedEngine( getParameters().getHostedEngineDeployConfiguration())); }</code><technical_language>Hmm, please a updateFenceAgents method, if fence agents list is empty, means want remove fence agents, setting db values break this removal</technical_language>

Target:
protected boolean validate() { oldHost = vdsDao.get(getVdsId()); boolean validateAgents=true; if (getParameters().getFenceAgents() == null) { getParameters().setFenceAgents(fenceAgentDao.getFenceAgentsForHost(getVdsId())); validateAgents = false; } UpdateHostValidator validator = getUpdateHostValidator(oldHost, getParameters().getvds(), getParameters().isInstallHost()); return validate(validator.hostExists()) && validate(validator.hostStatusValid()) && validate(validator.nameNotEmpty()) && validate(validator.nameLengthIsLegal()) && validate(validator.updateHostAddressAllowed()) && validate(validator.nameNotUsed()) && validate(validator.hostNameNotUsed()) && validate(validator.statusSupportedForHostInstallation()) && validate(validator.passwordProvidedForHostInstallation(getParameters().getAuthMethod(), getParameters().getPassword())) && validate(validator.updatePortAllowed()) && validate(validator.clusterNotChanged()) && validate(validator.hostProviderExists()) && validate(validator.hostProviderTypeMatches()) && validateNetworkProviderConfiguration() && isPowerManagementLegal(getParameters().getVdsStaticData().isPmEnabled(), getParameters().getFenceAgents(), oldHost.getClusterCompatibilityVersion().toString(), validateAgents) && validate(validator.supportsDeployingHostedEngine( getParameters().getHostedEngineDeployConfiguration())); }
Source:
<code>public DbMetaData() { HikariDataSource h = Yank.getDefaultConnectionPool(); DatabaseMetaData meta; try { meta = h.getConnection().getMetaData(); try { dbMajorVersion = meta.getDatabaseMajorVersion(); logger.debug("dbMajorVersion = '{}'", dbMajorVersion); } catch (Exception e) { <START> logger.error("Asking for 'dbMajorVersion' is a unsupported: '{}'", e); <END> } try { dbMinorVersion = meta.getDatabaseMinorVersion(); logger.debug("dbMinorVersion = '{}'", dbMinorVersion); } catch (Exception e) { logger.error("Asking for 'dbMajorVersion' is a unsupported: '{}'", e); } driverMajorVersion = meta.getDriverMajorVersion(); logger.debug("driverMajorVersion = '{}'", driverMajorVersion); driverMinorVersion = meta.getDriverMinorVersion(); logger.debug("driverMinorVersion = '{}'", driverMinorVersion); dbProductName = meta.getDatabaseProductName(); logger.debug("dbProductName = '{}'", dbProductName); dbProductVersion = meta.getDatabaseProductVersion(); logger.debug("dbProductVersion = '{}'", dbProductVersion); } catch (SQLException e1) { logger.error("Asking for 'dbMajorVersion' seams to be unsupported: '{}'", e1); } }</code><technical_language>Do e.getMessage() dump stack trace, in message string</technical_language>

Target:
public DbMetaData() { HikariDataSource h = Yank.getDefaultConnectionPool(); DatabaseMetaData meta; try { meta = h.getConnection().getMetaData(); try { dbMajorVersion = meta.getDatabaseMajorVersion(); logger.debug("dbMajorVersion = '{}'", dbMajorVersion); } catch (Exception e) { logger.error("Asking for 'dbMajorVersion' is a unsupported: '{}'", e.getMessage()); } try { dbMinorVersion = meta.getDatabaseMinorVersion(); logger.debug("dbMinorVersion = '{}'", dbMinorVersion); } catch (Exception e) { logger.error("Asking for 'dbMajorVersion' is a unsupported: '{}'", e.getMessage()); } driverMajorVersion = meta.getDriverMajorVersion(); logger.debug("driverMajorVersion = '{}'", driverMajorVersion); driverMinorVersion = meta.getDriverMinorVersion(); logger.debug("driverMinorVersion = '{}'", driverMinorVersion); dbProductName = meta.getDatabaseProductName(); logger.debug("dbProductName = '{}'", dbProductName); dbProductVersion = meta.getDatabaseProductVersion(); logger.debug("dbProductVersion = '{}'", dbProductVersion); } catch (SQLException e1) { logger.error("Asking for 'dbMajorVersion' seems to be unsupported: '{}'", e1.getMessage()); } }
Source:
<code>private ConfigurationServiceImplService getConfigService() throws ConnectionManagerException, MalformedURLException{ String url = oProxyHelper.getAdapterEndPointFromConnectionManager(DirectConfigConstants.DIRECT_CONFIG_SERVICE_NAME); if(cfService == null) { <START> cfService = new ConfigurationServiceImplService(new URL(url+"?wsdl")); <END> } return cfService; }</code><technical_language>this initialized in a static / thread-safe context</technical_language>

Target:
protected ConfigurationServiceImplService getConfigService() throws ConnectionManagerException, MalformedURLException{ return cfService; }
Source:
<code>public void andThenError() { TestSubscriber<String> ts = new TestSubscriber<>(0); AtomicBoolean hasRun = new AtomicBoolean(false); Exception e = new Exception(); <START> Completable.create(cs -> cs.onError(e)) <END> .andThen(Observable.<String>create(s-> { hasRun.set(true); s.onNext("foo"); s.onCompleted(); })) .subscribe(ts); ts.assertNoValues(); ts.assertError(e); Assert.assertFalse("Should not have subscribed to observable when completable errors", hasRun.get()); }</code><technical_language>Lambdas Java 8. Besides, is a Completable.error() call cs.onSubscribe(Subscriptions.unsubscribed()) first</technical_language>

Target:
public void andThenError() { TestSubscriber<String> ts = new TestSubscriber<String>(0); final AtomicBoolean hasRun = new AtomicBoolean(false); final Exception e = new Exception(); Completable.create(new CompletableOnSubscribe() { @Override public void call(CompletableSubscriber cs) { cs.onError(e); } }) .andThen(Observable.<String>create(new OnSubscribe<String>() { @Override public void call(Subscriber<? super String> s) { hasRun.set(true); s.onNext("foo"); s.onCompleted(); } })) .subscribe(ts); ts.assertNoValues(); ts.assertError(e); Assert.assertFalse("Should not have subscribed to observable when completable errors", hasRun.get()); }
Source:
<code>public <T> QueryRunner<T> getQueryRunnerForSegments(final Query<T> query, final Iterable<SegmentDescriptor> specs) { final QueryRunnerFactory<T, Query<T>> factory = conglomerate.findFactory(query); final List<QueryRunner<T>> runners = new ArrayList<>(); for (String dataSource : query.getDataSource().getNames()) { final Map<Integer, FireChief> partitionChiefs = chiefs.get(dataSource); if (partitionChiefs == null) { continue; } final QueryToolChest<T, Query<T>> toolchest = factory.getToolchest(); final Iterable<QueryRunner<T>> subRunners = Iterables.transform( specs, new Function<SegmentDescriptor, QueryRunner<T>>() { @Nullable @Override public QueryRunner<T> apply(SegmentDescriptor spec) { FireChief retVal = partitionChiefs.get(spec.getPartitionNumber()); return retVal == null ? new NoopQueryRunner<T>() : retVal.getQueryRunner(query); } } ); runners.add( toolchest.mergeResults(factory.mergeRunners(MoreExecutors.sameThreadExecutor(), subRunners)) ); } <START> return new UnionQueryRunner<>(factory.mergeRunners(MoreExecutors.sameThreadExecutor(), runners)); <END> }</code><technical_language>if UnionQueryRunner is necessary, becoz covered broker. Realtime node receiving union queries</technical_language>

Target:
public <T> QueryRunner<T> getQueryRunnerForSegments(final Query<T> query, final Iterable<SegmentDescriptor> specs) { final QueryRunnerFactory<T, Query<T>> factory = conglomerate.findFactory(query); final Map<Integer, FireChief> partitionChiefs = chiefs.get(Iterables.getOnlyElement(query.getDataSource() .getNames())); return partitionChiefs == null ? new NoopQueryRunner<T>() : factory.getToolchest().mergeResults( factory.mergeRunners( MoreExecutors.sameThreadExecutor(), Iterables.transform( specs, new Function<SegmentDescriptor, QueryRunner<T>>() { @Override public QueryRunner<T> apply(SegmentDescriptor spec) { final FireChief retVal = partitionChiefs.get(spec.getPartitionNumber()); return retVal == null ? new NoopQueryRunner<T>() : retVal.getQueryRunner(query); } } ) ) ); }
Source:
<code>public String toString() { <START> return "TaskInstance{" + <END> "id=" + id + ", name='" + name + '\'' + ", description='" + description + '\'' + ", status='" + status + '\'' + ", actualOwner='" + actualOwner + '\'' + ", processInstanceId=" + processInstanceId + ", processId='" + processId + '\'' + ", containerId='" + containerId + '\'' + '}'; }</code><technical_language>worth altering confused main TaskInstance</technical_language>

Target:
public String toString() { return "TaskWithProcessDescription{" + "id=" + id + ", name='" + name + '\'' + ", description='" + description + '\'' + ", status='" + status + '\'' + ", actualOwner='" + actualOwner + '\'' + ", processInstanceId=" + processInstanceId + ", processId='" + processId + '\'' + ", containerId='" + containerId + '\'' + ", lastModificationDate='" + lastModificationDate + '\'' + ", lastModificationUser='" + lastModificationUser + '\'' + ", processInstanceDescription='" + processInstanceDescription + '\'' + '}'; }
Source:
<code>private Map<String, FetchInfo> makeFetchMap(ChangeData cd, PatchSet in) throws OrmException { Map<String, FetchInfo> r = Maps.newLinkedHashMap(); <START> for (String pluginName : downloadSchemes.plugins()) { for (Entry<String, Provider<DownloadScheme>> e : downloadSchemes.byPlugin(pluginName).entrySet()) { <END> DownloadScheme scheme = e.getValue().get(); if (!scheme.isEnabled() || (scheme.isAuthRequired() && !userProvider.get().isIdentifiedUser())) { continue; } ChangeControl ctl = control(cd); if (!scheme.isAuthRequired() && !ctl.forUser(anonymous).isPatchVisible(in, db.get())) { continue; } String projectName = ctl.getProject().getNameKey().get(); String url = scheme.getUrl(projectName); String refName = in.getRefName(); FetchInfo fetchInfo = new FetchInfo(url, refName); r.put(e.getKey(), fetchInfo); if (has(DOWNLOAD_COMMANDS)) { for (String pluginName2 : downloadCommands.plugins()) { for (Entry<String, Provider<DownloadCommand>> e2 : downloadCommands.byPlugin(pluginName2).entrySet()) { String c = e2.getValue().get().getCommand(scheme, projectName, refName); if (c != null) { fetchInfo.addCommand(e2.getKey(), c); } } } } } } return r; }</code><technical_language>write this shorter: for (DynamicMap.Entry<DownloadScheme> e : downloadSchemes) { String name = e.getExportName(); DownloadScheme scheme = e.getProvider().get();</technical_language>

Target:
private Map<String, FetchInfo> makeFetchMap(ChangeData cd, PatchSet in) throws OrmException { Map<String, FetchInfo> r = Maps.newLinkedHashMap(); for (DynamicMap.Entry<DownloadScheme> e : downloadSchemes) { String schemeName = e.getExportName(); DownloadScheme scheme = e.getProvider().get(); if (!scheme.isEnabled() || (scheme.isAuthRequired() && !userProvider.get().isIdentifiedUser())) { continue; } ChangeControl ctl = control(cd); if (!scheme.isAuthRequired() && !ctl.forUser(anonymous).isPatchVisible(in, db.get())) { continue; } String projectName = ctl.getProject().getNameKey().get(); String url = scheme.getUrl(projectName); String refName = in.getRefName(); FetchInfo fetchInfo = new FetchInfo(url, refName); r.put(schemeName, fetchInfo); if (has(DOWNLOAD_COMMANDS)) { for (DynamicMap.Entry<DownloadCommand> e2 : downloadCommands) { String commandName = e2.getExportName(); DownloadCommand command = e2.getProvider().get(); String c = command.getCommand(scheme, projectName, refName); if (c != null) { fetchInfo.addCommand(commandName, c); } } } } return r; }
Source:
<code>public KafkaConsumerMetrics(Metrics metrics, String metricGrpPrefix) { this.metrics = metrics; String metricGroupName = metricGrpPrefix + "-metrics"; Measurable lastPoll = (mConfig, now) -> { if (lastPollMs == 0L) return -1d; else return TimeUnit.SECONDS.convert(now - lastPollMs, TimeUnit.MILLISECONDS); }; metrics.addMetric(metrics.metricName("last-poll-seconds-ago", metricGroupName, "The number of seconds since the last poll() invocation."), lastPoll); this.timeBetweenPollSensor = metrics.sensor("time-between-poll"); this.timeBetweenPollSensor.add(metrics.metricName("time-between-poll-avg", metricGroupName, "The average delay between invocations of poll()."), new Avg()); this.timeBetweenPollSensor.add(metrics.metricName("time-between-poll-max", metricGroupName, "The max delay between invocations of poll()."), new Max()); this.pollIdleSensor = metrics.sensor("poll-idle-ratio"); <START> this.pollIdleSensor.add(metrics.metricName("poll-idle-ratio", <END> metricGroupName, "The average fraction of time the consumer's poll() is idle as opposed to waiting for the user code to process records."), new Avg()); }</code><technical_language>this poll-idle-ratio-avgto explicit</technical_language>

Target:
public KafkaConsumerMetrics(Metrics metrics, String metricGrpPrefix) { this.metrics = metrics; String metricGroupName = metricGrpPrefix + "-metrics"; Measurable lastPoll = (mConfig, now) -> { if (lastPollMs == 0L) return -1d; else return TimeUnit.SECONDS.convert(now - lastPollMs, TimeUnit.MILLISECONDS); }; metrics.addMetric(metrics.metricName("last-poll-seconds-ago", metricGroupName, "The number of seconds since the last poll() invocation."), lastPoll); this.timeBetweenPollSensor = metrics.sensor("time-between-poll"); this.timeBetweenPollSensor.add(metrics.metricName("time-between-poll-avg", metricGroupName, "The average delay between invocations of poll()."), new Avg()); this.timeBetweenPollSensor.add(metrics.metricName("time-between-poll-max", metricGroupName, "The max delay between invocations of poll()."), new Max()); this.pollIdleSensor = metrics.sensor("poll-idle-ratio-avg"); this.pollIdleSensor.add(metrics.metricName("poll-idle-ratio-avg", metricGroupName, "The average fraction of time the consumer's poll() is idle as opposed to waiting for the user code to process records."), new Avg()); }
Source:
<code>protected void doSetUserAttributes(String userName, Map<String, List<String>> claimAttributesToAdd, Map<String, List<String>> claimAttributesToDelete, Map<String, List<String>> claimAttributesToReplace, String profileName) throws UserStoreException, NotImplementedException { if (log.isDebugEnabled()) { log.debug("doSetUserAttributes operation is not implemented in: " + this.getClass()); } <START> throw new NotImplementedException("doSetUserAttributes operation is not implemented in: " + this.getClass()); <END> }</code><technical_language>In opinion, do need this log. WDYT</technical_language>

Target:
protected void doSetUserAttributes(String userName, Map<String, List<String>> claimAttributesToAdd, Map<String, List<String>> claimAttributesToDelete, Map<String, List<String>> claimAttributesToReplace, String profileName) throws UserStoreException, NotImplementedException { throw new NotImplementedException("doSetUserAttributes operation is not implemented in: " + this.getClass()); }
Source:
<code>public ConfigManager() { launcherDir = resolveLauncherDir(); configPath = launcherDir.resolve(CONFIG_FILE); gson = new GsonBuilder() .registerTypeAdapter(Path.class, new PathAdapter()) .registerTypeAdapter(Package.class, new PackageAdapter()) <START> .disableHtmlEscaping() <END> .setPrettyPrinting() .create(); loadService = new ConfigLoadService(this); saveService = new ConfigSaveService(this); }</code><technical_language>is this disabled</technical_language>

Target:
private ConfigManager() { if (instance != null) { throw new RuntimeException("Cannot create second instance of a singleton class"); } launcherDir = resolveLauncherDir(); configPath = launcherDir.resolve(CONFIG_FILE); config = createDefaultConfig(); gson = new GsonBuilder() .registerTypeAdapter(Path.class, new PathAdapter()) .registerTypeAdapter(Package.class, new PackageAdapter()) .disableHtmlEscaping() .setPrettyPrinting() .create(); reader = new ConfigReader(this); writer = new ConfigWriter(this); }
Source:
<code>private Response<ShareStatistics> mapGetStatisticsResponse(SharesGetStatisticsResponse response) { ShareStatistics shareStatistics = <START> new ShareStatistics((int) (response.getValue().getShareUsageBytes() / (Constants.GB)), <END> response.getValue().getShareUsageBytes()); return new SimpleResponse<>(response, shareStatistics); }</code><technical_language>want Math.ceil() of values up</technical_language>

Target:
private Response<ShareStatistics> mapGetStatisticsResponse(SharesGetStatisticsResponse response) { ShareStatistics shareStatistics = new ShareStatistics(response.getValue().getShareUsageBytes()); return new SimpleResponse<>(response, shareStatistics); }