auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void resumeAnsSuspendParallel() throws Exception { brothers = new Brother[4]; prism.getClusterHelper().submitEntity(URLS.SUBMIT_URL, bundles[0].getClusters().get(0)); prism.getFeedHelper().submitEntity(URLS.SUBMIT_URL, bundles[0].getDataSets().get(0)); <START> prism.getFeedHelper().schedule(URLS.SCHEDULE_URL, bundles[0].getDataSets().get(0)); <END> Thread.sleep(15000); prism.getFeedHelper().suspend(URLS.SUSPEND_URL, bundles[0].getDataSets().get(0)); Thread.sleep(15000); for (int i = 1; i <= 2; i++) { brothers[i - 1] = new Brother("brother" + i, "resume", ENTITY_TYPE.DATA, brotherGrimm, bundles[0], prism, URLS.RESUME_URL); } for (int i = 3; i <= 4; i++) { brothers[i - 1] = new Brother("brother" + i, "suspend", ENTITY_TYPE.DATA, brotherGrimm, bundles[0], prism, URLS.SUSPEND_URL); } for (Brother brother : brothers) { brother.start(); } for (Brother brother : brothers) { brother.join(); } for (Brother brother : brothers) { logger.info(brother.getName() + " output: \n" + Util.prettyPrintXml(brother.getOutput().getMessage())); AssertUtil.assertSucceeded(brother.getOutput()); } }</code><technical_language>add assertion response</technical_language>

Target:
public void resumeAnsSuspendParallel() throws Exception { brothers = new Brother[4]; prism.getClusterHelper().submitEntity(URLS.SUBMIT_URL, bundles[0].getClusters().get(0)); prism.getFeedHelper().submitEntity(URLS.SUBMIT_URL, bundles[0].getDataSets().get(0)); AssertUtil.assertSucceeded(prism.getFeedHelper().schedule(URLS.SCHEDULE_URL, bundles[0].getDataSets().get(0))); Thread.sleep(15000); prism.getFeedHelper().suspend(URLS.SUSPEND_URL, bundles[0].getDataSets().get(0)); Thread.sleep(15000); for (int i = 1; i <= 2; i++) { brothers[i - 1] = new Brother("brother" + i, "resume", ENTITY_TYPE.DATA, brotherGrimm, bundles[0], prism, URLS.RESUME_URL); } for (int i = 3; i <= 4; i++) { brothers[i - 1] = new Brother("brother" + i, "suspend", ENTITY_TYPE.DATA, brotherGrimm, bundles[0], prism, URLS.SUSPEND_URL); } for (Brother brother : brothers) { brother.start(); } for (Brother brother : brothers) { brother.join(); } for (Brother brother : brothers) { logger.info(brother.getName() + " output: \n" + Util.prettyPrintXml(brother.getOutput().getMessage())); AssertUtil.assertSucceeded(brother.getOutput()); } }
Source:
<code><START> public synchronized StreamBuildListener createEventsListener() { <END> File eventsFile = getEventsFile(); if (!eventsFile.getParentFile().isDirectory() && !eventsFile.getParentFile().mkdirs()) { LOGGER.log(Level.WARNING, "Could not create directory {0} for {1}", new Object[]{eventsFile.getParentFile(), folder.getFullName()}); } if (eventStreams == null || !eventsFile.equals(eventStreams.getFile())) { eventStreams = new EventOutputStreams(eventsFile, 250, TimeUnit.MILLISECONDS, 1024, true, EVENT_LOG_MAX_SIZE * 1024, BACKUP_LOG_COUNT == null ? 0 : Math.max(0, BACKUP_LOG_COUNT) ); } return new StreamBuildListener(eventStreams.get(), Charsets.UTF_8); }</code><technical_language>If need expose Closeable _[sic]_ aspect, declare type StreamTaskListener. BuildListener sense in this context-it is a build</technical_language>

Target:
public synchronized StreamTaskListener createEventsListener() { File eventsFile = getEventsFile(); if (!eventsFile.getParentFile().isDirectory() && !eventsFile.getParentFile().mkdirs()) { LOGGER.log(Level.WARNING, "Could not create directory {0} for {1}", new Object[]{eventsFile.getParentFile(), folder.getFullName()}); } if (eventStreams == null) { eventStreams = new EventOutputStreams(new EventOutputStreams.OutputFile() { @NonNull @Override public File get() { return getEventsFile(); } @Override public boolean canWriteNow() { GregorianCalendar timestamp = new GregorianCalendar(); timestamp.setTimeInMillis(System.currentTimeMillis() - 10000L); Queue.Item probe = new Queue.WaitingItem(timestamp, folder, Collections.<Action>emptyList()); for (QueueTaskDispatcher d: QueueTaskDispatcher.all()) { if (d.canRun(probe) != null) { return false; } } return true; } }, 250, TimeUnit.MILLISECONDS, 1024, true, EVENT_LOG_MAX_SIZE * 1024, BACKUP_LOG_COUNT == null ? 0 : Math.max(0, BACKUP_LOG_COUNT) ); } return new StreamTaskListener(eventStreams.get(), Charsets.UTF_8); }
Source:
<code>public void setup() { System.out.println("AbstractRepositorySettingsPageTest.setup()"); <START> TasksUiTestUtil.ensureTasksUiInitialization(); <END> System.out.println("called ensureTasksUiInitialization"); TasksUiPlugin.getRepositoryManager().addRepositoryConnector(new BugzillaRestConnector()); TasksUiPlugin.getDefault().addRepositoryConnectorUi(new BugzillaRestRepositoryConnectorUi()); }</code><technical_language>sounds require major changes. thinking of mocking tasks ui model? I get builds green soon can. If fix this test major changes, disable changes made. I idea test fails</technical_language>

Target:
public void setup() { TasksUiPlugin.getDefault().addRepositoryConnectorUi(new BugzillaRestRepositoryConnectorUi()); }
Source:
<code>protected void handleResult(InvocationResult resultArg, Message request, Channel channel, Object source) { if (channel != null) { if (resultArg.getReturnValue() instanceof ListenableFuture) { ((ListenableFuture<?>) resultArg.getReturnValue()).addCallback( r -> asyncSuccess(resultArg, request, channel, source, r), t -> asyncFailure(request, channel, t)); } <START> else if (resultArg.getReturnValue() instanceof Mono) { <END> ((Mono<?>) resultArg.getReturnValue()).subscribe( r -> asyncSuccess(resultArg, request, channel, source, r), t -> asyncFailure(request, channel, t)); } else { doHandleResult(resultArg, request, channel, source); } } else if (this.logger.isWarnEnabled()) { this.logger.warn("Listener method returned result [" + resultArg + "]: not generating response message for it because no Rabbit Channel given"); } }</code><technical_language>I if some wrapper solution a Reactor dependency optional..</technical_language>

Target:
protected void handleResult(InvocationResult resultArg, Message request, Channel channel, Object source) { if (channel != null) { if (resultArg.getReturnValue() instanceof ListenableFuture) { ((ListenableFuture<?>) resultArg.getReturnValue()).addCallback( r -> asyncSuccess(resultArg, request, channel, source, r), t -> asyncFailure(request, channel, t)); } else if (monoPresent && MonoHandler.isMono(resultArg.getReturnValue())) { MonoHandler.subscribe(resultArg.getReturnValue(), r -> asyncSuccess(resultArg, request, channel, source, r), t -> asyncFailure(request, channel, t)); } else { doHandleResult(resultArg, request, channel, source); } } else if (this.logger.isWarnEnabled()) { this.logger.warn("Listener method returned result [" + resultArg + "]: not generating response message for it because no Rabbit Channel given"); } }
Source:
<code>public void testInvalidXsdTargetNamespace() { final String drl1 = "package org.drools.compiler\n" + "rule R1 when\n" + " $m : Message()\n" + "then\n" + "end\n"; final String kmodule = "<kmodule xmlns:xsi=\"<LINK_1>\" \n" + " xmlns=\"<LINK_0>\">\n" + " <kbase name=\"kbase1\">\n" + " <ksession name=\"ksession1\" default=\"true\"/>\n" + " </kbase>\n" + "</kmodule>"; final KieServices ks = KieServices.Factory.get(); final ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-kie-builder", "1.0.0" ); final Resource r1 = ResourceFactory.newByteArrayResource( drl1.getBytes() ).setResourceType( ResourceType.DRL ).setSourcePath( "kbase1/drl1.drl" ); try { final KieModule km = createAndDeployJar(ks, kmodule, releaseId1, r1); Assertions.fail("Test should throw a validation exception!"); } catch (IllegalStateException ex) { <START> Assertions.assertThat(ex).hasMessageContaining("XSD validation failed"); <END> } }</code><technical_language>I suggest instead? Assertions.assertThatThrownBy(() -> yourCode()) .isIntanceOf(SomeException.class) .hasMessageContaining(...) try-catch, need Assertions.fail()</technical_language>

Target:
public void testInvalidXsdTargetNamespace() { final String drl1 = "package org.drools.compiler\n" + "rule R1 when\n" + " $m : Message()\n" + "then\n" + "end\n"; final String kmodule = "<kmodule xmlns:xsi=\"<LINK_1>\" \n" + " xmlns=\"<LINK_0>\">\n" + " <kbase name=\"kbase1\">\n" + " <ksession name=\"ksession1\" default=\"true\"/>\n" + " </kbase>\n" + "</kmodule>"; final KieServices ks = KieServices.Factory.get(); final ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-kie-builder", "1.0.0" ); final Resource r1 = ResourceFactory.newByteArrayResource( drl1.getBytes() ).setResourceType( ResourceType.DRL ).setSourcePath( "kbase1/drl1.drl" ); Assertions.assertThatThrownBy(() -> createAndDeployJar(ks, kmodule, releaseId1, r1)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("XSD validation failed"); }
Source:
<code>public boolean isBalanced(ClusterCacheStatus cacheStatus) { if(cacheStatus == null){ return true; } synchronized(cacheStatus){ CacheTopology cacheTopology = cacheStatus.getCacheTopology(); ConsistentHashFactory chFactory = cacheStatus.getJoinInfo().getConsistentHashFactory(); ConsistentHash currentCH = cacheTopology.getCurrentCH(); ConsistentHash updatedMembersCH = chFactory.updateMembers(currentCH, cacheStatus.getMembers()); ConsistentHash balancedCH = chFactory.rebalance(updatedMembersCH); <START> if (currentCH == null || balancedCH.equals(currentCH)) { <END> return true; } return false; } }</code><technical_language>If currentCH == null, updateMembers(currentCH, ...) throw a NPE. check for null before, remove check here. I a CacheTopology a currentCH == null, is it</technical_language>

Target:
public boolean isBalanced(ClusterCacheStatus cacheStatus) { if(cacheStatus == null){ return true; } synchronized(cacheStatus){ CacheTopology cacheTopology = cacheStatus.getCacheTopology(); ConsistentHashFactory chFactory = cacheStatus.getJoinInfo().getConsistentHashFactory(); ConsistentHash currentCH = cacheTopology.getCurrentCH(); ConsistentHash updatedMembersCH = chFactory.updateMembers(currentCH, cacheStatus.getMembers()); ConsistentHash balancedCH = chFactory.rebalance(updatedMembersCH); if (balancedCH.equals(currentCH)) { return true; } return false; } }
Source:
<code>public void testManualRegistrationId() throws InterruptedException, JSONException { SwrveConfig config = new SwrveConfig(); initLocalHttpServer(activity, config); config.setSenderId("12345"); config.setObtainRegistrationIdEnabled(false); Swrve swrve = (Swrve) SwrveSDK.createInstance(activity, 1, "apiKey", config); swrve.onCreate(activity); swrve.setRegistrationId("manual_reg_id"); boolean foundPost = false; int retries = 10; while(!foundPost && (retries--) > 0) { Iterator<TestHttpServer.TestHttpPostRequest> it = httpEventServer.postRequests.iterator(); while(it.hasNext()) { TestHttpServer.TestHttpPostRequest request = it.next(); if (request.body.contains("swrve.gcm_token")) { JSONArray jsonEvents = request.getEventsJSON(); if (jsonEvents != null && jsonEvents.length() > 0) { for (int i = 0; i < jsonEvents.length() && !foundPost; i++) { JSONObject jsonEvent = jsonEvents.getJSONObject(i); if (jsonEvent.get("type").equals("user")) { JSONObject jsonAttributes = jsonEvent.getJSONObject("attributes"); if (jsonAttributes.has("swrve.gcm_token")) { foundPost = jsonAttributes.get("swrve.gcm_token").equals("manual_reg_id"); } } } } } } if (!foundPost) { <START> Thread.sleep(1000); <END> } } assertTrue(foundPost); swrve.onDestroy(activity); }</code><technical_language>NO!!!! remove this? more sleeps in unit tests. flaky</technical_language>

Target:
public void testManualRegistrationId() throws InterruptedException, JSONException { SwrveConfig config = new SwrveConfig(); config.setSenderId("12345"); config.setPushRegistrationAutomatic(false); Swrve swrve = (Swrve) SwrveSDK.createInstance(activity, 1, "apiKey", config); swrve.onCreate(activity); swrve.setRegistrationId("manual_reg_id"); JSONObject deviceValuesToSend = swrve.getDeviceInfo(); assertEquals("manual_reg_id", deviceValuesToSend.get("swrve.gcm_token")); swrve.onDestroy(activity); }
Source:
<code>public void testRepartitionedJoin() { JoinNode join = join("join", tableScan("ts1", "orderkey"), tableScan("ts2", "orderkey_0"), JoinNode.DistributionType.PARTITIONED, "orderkey", "orderkey_0"); Map<String, PlanNodeCostEstimate> costs = ImmutableMap.of( "ts1", cpuCost(6000), "ts2", cpuCost(1000)); Map<String, PlanNodeStatsEstimate> stats = ImmutableMap.of( "join", statsEstimate(12000), "ts1", statsEstimate(6000), "ts2", statsEstimate(1000)); assertCost( join, costs, stats) .cpu(12000 + 6000 + 1000 + 6000 + 1000); assertCostEstimatedExchanges( join, <START> costs, <END> stats) .cpu(12000 + 6000 + 1000 + 6000 + 1000 + 6000 + 1000 + 1000); assertCostHasUnknownComponentsForUnknownStats(join); }</code><technical_language>memory network costs</technical_language>

Target:
public void testRepartitionedJoin() { TableScanNode ts1 = tableScan("ts1", "orderkey"); TableScanNode ts2 = tableScan("ts2", "orderkey_0"); JoinNode join = join("join", ts1, ts2, JoinNode.DistributionType.PARTITIONED, "orderkey", "orderkey_0"); Map<String, PlanNodeCostEstimate> costs = ImmutableMap.of( "ts1", cpuCost(6000), "ts2", cpuCost(1000)); Map<String, PlanNodeStatsEstimate> stats = ImmutableMap.of( "join", statsEstimate(join, 12000), "ts1", statsEstimate(ts1, 6000), "ts2", statsEstimate(ts2, 1000)); assertCost(join, costs, stats) .cpu(12000 + 6000 + 1000 + 6000 + 1000) .memory(1000) .network(0); assertCostEstimatedExchanges(join, costs, stats) .cpu(12000 + 6000 + 1000 + 6000 + 1000 + 6000 + 1000 + 1000) .memory(1000) .network(6000 + 1000); assertCostHasUnknownComponentsForUnknownStats(join); }
Source:
<code>protected Control createDialogArea(Composite parent) { Composite control = (Composite)super.createDialogArea(parent); Text text = null; <START> for (Control c: control.getChildren()) { <END> if(c instanceof Text) { text = (Text)c; break; } } if(text != null) { IObservableValue modelObservable = BeanProperties.value(InputModel.VALUE).observe(model); IObservableValue textObservable = WidgetProperties.text(SWT.Modify).observe(text); ValueBindingBuilder.bind(textObservable).to(modelObservable).in(dbc); ValidationStatusProvider validator = new ValidationStatusProvider(textObservable); getValidator().setProvider(validator); dbc.addValidationStatusProvider(validator); ControlDecorationSupport.create(validator, SWT.LEFT | SWT.TOP); setErrorMessage(getValidator().isValid(initialValue)); } else { OpenShiftUIActivator.getDefault().getLogger().logError(new NullPointerException("Cannot find text widget.")); } return control; }</code><technical_language>this code a nice candidate for a method #getTextInput(Control[] controls)</technical_language>

Target:
protected Control createDialogArea(Composite parent) { Composite control = (Composite)super.createDialogArea(parent); Text text = getFirstTextControl(control.getChildren()); if(text != null) { IObservableValue modelObservable = BeanProperties.value(InputModel.VALUE).observe(model); IObservableValue textObservable = WidgetProperties.text(SWT.Modify).observe(text); ValueBindingBuilder.bind(textObservable).to(modelObservable).in(dbc); ValidationStatusProvider validator = new ValidationStatusProvider(textObservable); getValidator().setProvider(validator); dbc.addValidationStatusProvider(validator); ControlDecorationSupport.create(validator, SWT.LEFT | SWT.TOP); setErrorMessage(getValidator().isValid(initialValue)); } else { OpenShiftUIActivator.getDefault().getLogger().logError(new NullPointerException("Cannot find text widget.")); } return control; }
Source:
<code>public App(String name, String contextPath, Set<Component> components, Set<Theme> themes, Configuration configuration, Bindings bindings, I18nResources i18nResources, SessionManager sessionManager) { this.name = name; this.contextPath = contextPath; this.components = components.stream().collect(Collectors.toMap(Component::getContextPath, cmp -> cmp)); this.rootComponent = this.components.get(Component.ROOT_COMPONENT_CONTEXT_PATH); this.themes = themes.stream().collect(Collectors.toMap(Theme::getName, theme -> theme)); this.defaultTheme = configuration.getThemeName() .map(configuredThemeName -> { Theme configuredTheme = App.this.themes.get(configuredThemeName); if (configuredTheme == null) { throw new IllegalArgumentException( "Theme '" + configuredThemeName + "' which is configured for app '" + name + "' does not exists. Available themes: " + themes); } return configuredTheme; }).orElse(null); this.lookup = new Lookup(components, configuration, bindings, i18nResources); this.configuration = configuration; this.sessionManager = sessionManager; <START> this.sessionManager.init(configuration); <END> }</code><technical_language>if sessionManager.init() throw exception</technical_language>

Target:
public App(String name, String contextPath, Set<Component> components, Set<Theme> themes, Configuration configuration, Bindings bindings, I18nResources i18nResources, SessionManager sessionManager) { this.name = name; this.contextPath = contextPath; this.components = components.stream().collect(Collectors.toMap(Component::getContextPath, cmp -> cmp)); this.rootComponent = this.components.get(Component.ROOT_COMPONENT_CONTEXT_PATH); this.themes = themes.stream().collect(Collectors.toMap(Theme::getName, theme -> theme)); this.defaultTheme = configuration.getThemeName() .map(configuredThemeName -> { Theme configuredTheme = App.this.themes.get(configuredThemeName); if (configuredTheme == null) { throw new IllegalArgumentException( "Theme '" + configuredThemeName + "' which is configured for app '" + name + "' does not exists. Available themes: " + themes); } return configuredTheme; }).orElse(null); this.lookup = new Lookup(components, configuration, bindings, i18nResources); this.configuration = configuration; this.sessionManager = sessionManager; }
Source:
<code>public ModelAndView pluginStatusReport(Request request, Response response) { String pluginId = request.params("plugin_id"); try { String pluginStatusReport = elasticAgentPluginService.getPluginStatusReport(pluginId); Map<Object, Object> object = new HashMap<>() {{ put("viewTitle", "Plugin Status Report"); put("viewFromPlugin", pluginStatusReport); }}; return new ModelAndView(object, "status_reports/index.ftlh"); } catch (RecordNotFoundException e) { return errorPage(response, 404, "Plugin Status Report", e.getMessage()); } catch (UnsupportedOperationException e) { String message = String.format("Status Report for plugin with id: '%s' is not found.", pluginId); return errorPage(response, 404, "Plugin Status Report", message); } catch (RulesViolationException | SecretResolutionFailureException e) { LOGGER.error(e.getMessage(), e); <START> return errorPage(response, 422, "Plugin Status Report", e.getMessage()); <END> } catch (Exception e) { LOGGER.error(e.getMessage(), e); return errorPage(response, 500, "Plugin Status Report", UNKNOWN_ERROR_MESSAGE); } }</code><technical_language>This 422, a user error</technical_language>

Target:
public ModelAndView pluginStatusReport(Request request, Response response) { String pluginId = request.params("plugin_id"); try { String pluginStatusReport = elasticAgentPluginService.getPluginStatusReport(pluginId); Map<Object, Object> object = new HashMap<>() {{ put("viewTitle", "Plugin Status Report"); put("viewFromPlugin", pluginStatusReport); }}; return new ModelAndView(object, "status_reports/index.ftlh"); } catch (RecordNotFoundException e) { return errorPage(response, 404, "Plugin Status Report", e.getMessage()); } catch (UnsupportedOperationException e) { String message = String.format("Status Report for plugin with id: '%s' is not found.", pluginId); return errorPage(response, 404, "Plugin Status Report", message); } catch (RulesViolationException | SecretResolutionFailureException e) { LOGGER.error(e.getMessage(), e); return errorPage(response, 500, "Plugin Status Report", e.getMessage()); } catch (Exception e) { LOGGER.error(e.getMessage(), e); return errorPage(response, 500, "Plugin Status Report", UNKNOWN_ERROR_MESSAGE); } }
Source:
<code>private VmStatic getVmStatic() { VmStatic vmStatic = new VmStatic(); <START> vmStatic.setOs(0); <END> vmStatic.setMemSizeMb(300); vmStatic.setStateless(false); vmStatic.setVmtGuid(vmTemplateId); return vmStatic; }</code><technical_language>I .setOs(0); // 0 = Unassigned I do this if relevant unitests. however, in multiple places in code IDs - please define constants for in a single place (OsRepo?)</technical_language>

Target:
private VmStatic getVmStatic() { VmStatic vmStatic = new VmStatic(); vmStatic.setOs(OsRepository.DEFAULT_OS); vmStatic.setMemSizeMb(300); vmStatic.setStateless(false); vmStatic.setVmtGuid(vmTemplateId); return vmStatic; }
Source:
<code>public static UserNameAndPassword getBasicAuthenticationCredentials(HttpServletRequest httpRequest) { String header = httpRequest.getHeader(AuthorizationConstants.AUTHORIZATION_HEADER_NAME); if (StringUtils.isBlank(header) || !header.startsWith(AuthorizationConstants.BASIC_PREFIX)) { return null; } String base64EncodedCredentials = header.substring(AuthorizationConstants.BASIC_PREFIX.length()).trim(); String basicCredentials = null; try { basicCredentials = new String(BASE64_DECODER.decode(base64EncodedCredentials), StandardCharsets.UTF_8); } catch(IllegalArgumentException e) { <START> return null; <END> } int colon = basicCredentials.indexOf(":"); if (colon>0 && colon<basicCredentials.length()-1) { String name = basicCredentials.substring(0, colon); String password = basicCredentials.substring(colon+1); return new UserNameAndPassword(name, password); } return null; }</code><technical_language>consider throw new IllegalArgumentException("Invalid Basic authentication header", e);</technical_language>

Target:
public static Optional<UserNameAndPassword> getBasicAuthenticationCredentials(HttpServletRequest httpRequest) throws IllegalArgumentException { String header = httpRequest.getHeader(AuthorizationConstants.AUTHORIZATION_HEADER_NAME); if (StringUtils.isBlank(header)) { return Optional.empty(); } if (!header.startsWith(AuthorizationConstants.BASIC_PREFIX)) { throw new IllegalArgumentException(String.format(INVALID_AUTH_MSG_FORMAT, "Missing \"" + AuthorizationConstants.BASIC_PREFIX + "\" prefix")); } String base64EncodedCredentials = header.substring(AuthorizationConstants.BASIC_PREFIX.length()).trim(); String basicCredentials = null; try { basicCredentials = new String(BASE64_DECODER.decode(base64EncodedCredentials), StandardCharsets.UTF_8); } catch (IllegalArgumentException e) { throw new IllegalArgumentException( String.format(INVALID_AUTH_MSG_FORMAT, "Malformed Base64 encoding: " + e.getMessage()), e); } int colon = basicCredentials.indexOf(":"); if (colon > 0 && colon < basicCredentials.length() - 1) { String name = basicCredentials.substring(0, colon); String password = basicCredentials.substring(colon + 1); return Optional.of(new UserNameAndPassword(name, password)); } throw new IllegalArgumentException( String.format(INVALID_AUTH_MSG_FORMAT, "Decoded credentials should be colon separated")); }
Source:
<code>private static com.netflix.genie.proto.JobSpecification toProtoJobSpecification( final JobSpecification jobSpecification ) { final com.netflix.genie.proto.JobSpecification.Builder builder = com.netflix.genie.proto.JobSpecification.newBuilder(); builder.addAllCommandArgs(jobSpecification.getCommandArgs()); builder.setJob(toProtoExecutionResource(jobSpecification.getJob())); builder.setCluster(toProtoExecutionResource(jobSpecification.getCluster())); builder.setCommand(toProtoExecutionResource(jobSpecification.getCommand())); builder.addAllApplications( jobSpecification .getApplications() .stream() .map(JobServiceProtoConverter::toProtoExecutionResource) .collect(Collectors.toList()) ); builder.putAllEnvironmentVariables(jobSpecification.getEnvironmentVariables()); builder.setIsInteractive(jobSpecification.isInteractive()); builder.setJobDirectoryLocation(jobSpecification.getJobDirectoryLocation().getAbsolutePath()); <START> builder.setArchiveLocation(jobSpecification.getArchiveLocation()); <END> return builder.build(); }</code><technical_language>This throw if argument is null</technical_language>

Target:
private static com.netflix.genie.proto.JobSpecification toProtoJobSpecification( final JobSpecification jobSpecification ) { final com.netflix.genie.proto.JobSpecification.Builder builder = com.netflix.genie.proto.JobSpecification.newBuilder(); builder.addAllCommandArgs(jobSpecification.getCommandArgs()); builder.setJob(toProtoExecutionResource(jobSpecification.getJob())); builder.setCluster(toProtoExecutionResource(jobSpecification.getCluster())); builder.setCommand(toProtoExecutionResource(jobSpecification.getCommand())); builder.addAllApplications( jobSpecification .getApplications() .stream() .map(JobServiceProtoConverter::toProtoExecutionResource) .collect(Collectors.toList()) ); builder.putAllEnvironmentVariables(jobSpecification.getEnvironmentVariables()); builder.setIsInteractive(jobSpecification.isInteractive()); builder.setJobDirectoryLocation(jobSpecification.getJobDirectoryLocation().getAbsolutePath()); jobSpecification.getArchiveLocation().ifPresent( archiveLocation -> builder.setArchiveLocation(archiveLocation) ); return builder.build(); }
Source:
<code>private boolean setupNoUpstreamNotification() { final Resources res = getResourcesForSubId(mContext, mActiveDataSubId); final int timeToShowUpstreamNotification = res.getInteger(R.integer.time_to_show_no_upstream_after_no_backhaul); if <START> (timeToShowUpstreamNotification <END> <= 0) return NO_NOTIFY; final TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); final String mccmnc = tm.getSimOperator(); final String gid1 = tm.getGroupIdLevel1(); if (mccmnc.equals("20404") && !gid1.equals("BAE0000000000000")) return NO_NOTIFY; mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_SHOW_NO_UPSTREAM), timeToShowUpstreamNotification); return NOTIFY_DONE; }</code><technical_language>delay</technical_language>

Target:
private boolean setupNoUpstreamNotification() { final Resources res = getResourcesForSubId(mContext, mActiveDataSubId); final int delayToShowUpstreamNotification = res.getInteger(R.integer.delay_to_show_no_upstream_after_no_backhaul); if (delayToShowUpstreamNotification <= 0) return NO_NOTIFY; final TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); final String mccmnc = tm.getSimOperator(); final String gid1 = tm.getGroupIdLevel1(); if (mccmnc.equals("20404") && !gid1.equals("BAE0000000000000")) return NO_NOTIFY; getHandler().sendMessageDelayed(getHandler().obtainMessage(EVENT_SHOW_NO_UPSTREAM), delayToShowUpstreamNotification); return NOTIFY_DONE; }
Source:
<code>public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { this.viewer = (TreeViewer) viewer; this.info = (LSPDocumentInfo) newInput; info.getDocument().addDocumentListener(this); resource = LSPEclipseUtils.findResourceFor(info.getFileUri().toString()); resource.getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE); refreshTreeContentFromLS(); <START> preferences = InstanceScope.INSTANCE.getNode(outlineID+'.'+info.getFileUri()); <END> IEditorPart editorPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor(); if(editorPart instanceof AbstractTextEditor) { AbstractTextEditor editor = (AbstractTextEditor)editorPart; ((StyledText)editor.getAdapter(Control.class)).addCaretListener(selectByEditorCaretListener); } }</code><technical_language>this set in outline page? This LSSymbolsContentProvider class is intended build outline model. UI interactions other stuff more sense in CNFOutlinePage. Moreover, CNFOutlinePage access editor instance</technical_language>

Target:
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { this.viewer = (TreeViewer) viewer; this.info = (LSPDocumentInfo) newInput; info.getDocument().addDocumentListener(this); resource = LSPEclipseUtils.findResourceFor(info.getFileUri().toString()); resource.getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE); refreshTreeContentFromLS(); }
Source:
<code>private String getMergeResolveMessage(Repository mergeRepository) { File mergeMsg = new File(mergeRepository.getDirectory(), Constants.MERGE_MSG); FileReader reader; try { reader = new FileReader(mergeMsg); BufferedReader br = new BufferedReader(reader); try { StringBuilder message = new StringBuilder(); String s; String newLine = newLine(); while ((s = br.readLine()) != null) { message.append(s).append(newLine); <START> } <END> return message.toString(); } catch (IOException e) { throw new IllegalStateException(e); } finally { try { br.close(); } catch (IOException e) { } } } catch (FileNotFoundException e) { throw new IllegalStateException(e); } }</code><technical_language>Style nit: unneeded curlies</technical_language>

Target:
private String getMergeResolveMessage(Repository mergeRepository) { File mergeMsg = new File(mergeRepository.getDirectory(), Constants.MERGE_MSG); FileReader reader; try { reader = new FileReader(mergeMsg); BufferedReader br = new BufferedReader(reader); try { StringBuilder message = new StringBuilder(); String s; String newLine = newLine(); while ((s = br.readLine()) != null) message.append(s).append(newLine); return message.toString(); } catch (IOException e) { throw new IllegalStateException(e); } finally { try { br.close(); } catch (IOException e) { } } } catch (FileNotFoundException e) { throw new IllegalStateException(e); } }
Source:
<code>Hit<String> bestMatchingSynonym(OntologyTerm ontologyTerm, Set<String> searchTerms) { Optional<Hit<String>> bestSynonym = ontologyTerm .getSynonyms() .stream() .map(synonym -> Hit.create(synonym, distanceFrom(synonym, searchTerms))) .max(Comparator.naturalOrder()); <START> if (bestSynonym.isPresent()) { <END> return bestSynonym.get(); } else { throw new IllegalStateException("ontologyTerm.getSynonyms() shouldn't return an empty list"); } }</code><technical_language>Nicer: java .orElseThrow(() -> new IllegalStateException("ontologyTerm.getSynonyms() return empty list"));</technical_language>

Target:
Hit<String> bestMatchingSynonym(OntologyTerm ontologyTerm, Set<String> searchTerms) { Optional<Hit<String>> bestSynonym = ontologyTerm .getSynonyms() .stream() .map(synonym -> Hit.create(synonym, distanceFrom(synonym, searchTerms))) .max(Comparator.naturalOrder()); return bestSynonym.orElseThrow( () -> new IllegalStateException("ontologyTerm.getSynonyms() shouldn't return an empty list")); }
Source:
<code>public Object deserialize(Object object) { if (object instanceof byte[]) { return new AdaptiveCounting((byte[])object); } else if (object instanceof ByteBuffer) { ByteBuffer buf = (ByteBuffer)object; <START> int size = buf.capacity(); <END> byte[] bytes = new byte[size]; buf.get(bytes); return new AdaptiveCounting(bytes); } return object; }</code><technical_language>ByteBuffer.capacity is total capacity of backing data structure, ByteBuffer objects represent slices windows structure. Thus, is generally more correct do buf.remaining()</technical_language>

Target:
public Object deserialize(Object object) { if (object instanceof byte[]) { return new AdaptiveCounting((byte[])object); } else if (object instanceof ByteBuffer) { ByteBuffer buf = (ByteBuffer)object; int size = buf.remaining(); byte[] bytes = new byte[size]; buf.get(bytes); return new AdaptiveCounting(bytes); } return object; }
Source:
<code>protected LinkedList<TransactionOutput> calculateAllSpendCandidatesFromUTXOProvider(boolean excludeImmatureCoinbases){ <START> LinkedList<TransactionOutput> candidates = Lists.newLinkedList(); <END> try { int chainHeight = utxoProvider.getChainHeadHeight(); for (StoredTransactionOutput output : getStoredOutputsFromUTXOProvider()) { boolean coinbase = output.isCoinbase(); int depth = chainHeight - output.getHeight(); if (!excludeImmatureCoinbases || !coinbase || depth >= params.getSpendableCoinbaseDepth()) { candidates.add(new FreeStandingTransactionOutput(params, output, chainHeight)); } } } catch (UTXOProviderException e) { throw new RuntimeException("UTXO provider error", e); } for (Transaction tx : Iterables.concat(pending.values())) { for(TransactionInput input : tx.getInputs()) { if (input.getConnectedOutput().isMine(this)) { candidates.remove(input.getConnectedOutput()); } } if (!excludeImmatureCoinbases || tx.isMature()) { for (TransactionOutput output : tx.getOutputs()) { if (output.isAvailableForSpending() && output.isMine(this)) { candidates.add(output); } } } } return candidates; }</code><technical_language>add a checkState(lock.isHeldByCurrentThread()) here</technical_language>

Target:
protected LinkedList<TransactionOutput> calculateAllSpendCandidatesFromUTXOProvider(boolean excludeImmatureCoinbases){ checkState(lock.isHeldByCurrentThread()); LinkedList<TransactionOutput> candidates = Lists.newLinkedList(); try { int chainHeight = vUTXOProvider.getChainHeadHeight(); for (UTXO output : getStoredOutputsFromUTXOProvider()) { boolean coinbase = output.isCoinbase(); int depth = chainHeight - output.getHeight() + 1; if (!excludeImmatureCoinbases || !coinbase || depth >= params.getSpendableCoinbaseDepth()) { candidates.add(new FreeStandingTransactionOutput(params, output, chainHeight)); } } } catch (UTXOProviderException e) { throw new RuntimeException("UTXO provider error", e); } for (Transaction tx : Iterables.concat(pending.values())) { for(TransactionInput input : tx.getInputs()) { if (input.getConnectedOutput().isMine(this)) { candidates.remove(input.getConnectedOutput()); } } if (!excludeImmatureCoinbases || tx.isMature()) { for (TransactionOutput output : tx.getOutputs()) { if (output.isAvailableForSpending() && output.isMine(this)) { candidates.add(output); } } } } return candidates; }
Source:
<code><START> public void setNextRingTime(final String deviceId, final RingTime ringTime){ <END> final HashMap<String, AttributeValue> items = new HashMap<String, AttributeValue>(); items.put(MORPHEUS_ID_ATTRIBUTE_NAME, new AttributeValue().withS(deviceId)); final ObjectMapper mapper = new ObjectMapper(); try { final String ringTimeJSON = mapper.writeValueAsString(ringTime); items.put(CREATED_AT_ATTRIBUTE_NAME, new AttributeValue().withN(String.valueOf(DateTime.now().getMillis()))); items.put(RING_TIME_ATTRIBUTE_NAME, new AttributeValue().withS(ringTimeJSON)); final PutItemRequest putItemRequest = new PutItemRequest(this.tableName, items); final PutItemResult result = this.dynamoDBClient.putItem(putItemRequest); } catch (JsonProcessingException ex) { LOGGER.error("Set ring time for device failed, error: {}", deviceId, ex.getMessage()); } }</code><technical_language>pass DateTime object instead of DateTime.now()</technical_language>

Target:
public void setNextRingTime(final String deviceId, final RingTime ringTime){ this.setNextRingTime(deviceId, ringTime, DateTime.now()); }
Source:
<code><START> private PeriodicNotificationClient getPeriodicNotificationClient(String topic, String brokers) throws MalformedQueryException { <END> return new KafkaNotificationRegistrationClient(topic, getProducer(brokers)); }</code><technical_language>static</technical_language>

Target:
private static PeriodicNotificationClient getPeriodicNotificationClient(String topic, String brokers) throws MalformedQueryException { return new KafkaNotificationRegistrationClient(topic, createProducer(brokers)); }
Source:
<code>public boolean isComputeResourceExists(String resourceId) throws AppCatalogException { if(isExists(resourceId)){ ComputeResourceDescription computeResourceDescription = getComputeResource(resourceId); if(computeResourceDescription.isDeleted()){ return false; } else{ return true; } } <START> return true; <END> }</code><technical_language>return false if isExists() returns false</technical_language>

Target:
public boolean isComputeResourceExists(String resourceId) throws AppCatalogException { if(isExists(resourceId)){ ComputeResourceDescription computeResourceDescription = getComputeResource(resourceId); if(computeResourceDescription.isDeleted()){ return false; } else{ return true; } } return false; }
Source:
<code>public void call(final Subscriber<? super T> subscriber) { <START> source.subscribe(new Subscriber<T>(subscriber) { <END> private int currentIndex = 0; @Override public void onNext(T value) { if (currentIndex == index) { subscriber.onNext(value); subscriber.onCompleted(); } currentIndex++; } @Override public void onError(Throwable e) { subscriber.onError(e); } @Override public void onCompleted() { if (currentIndex <= index) { if (hasDefault) { subscriber.onNext(defaultValue); subscriber.onCompleted(); } else { subscriber.onError(new IndexOutOfBoundsException(index + " is out of bounds")); } } } }); }</code><technical_language>implemented Operator lift. way, need wrap source</technical_language>

Target:
public Subscriber<? super T> call(final Subscriber<? super T> subscriber) { return new Subscriber<T>(subscriber) { private int currentIndex = 0; @Override public void onNext(T value) { if (currentIndex == index) { subscriber.onNext(value); subscriber.onCompleted(); } currentIndex++; } @Override public void onError(Throwable e) { subscriber.onError(e); } @Override public void onCompleted() { if (currentIndex <= index) { if (hasDefault) { subscriber.onNext(defaultValue); subscriber.onCompleted(); } else { subscriber.onError(new IndexOutOfBoundsException(index + " is out of bounds")); } } } }; }
Source:
<code>public void writeJSON(Patient patient, JSONObject json, Collection<String> selectedFieldNames) { if (selectedFieldNames != null) { boolean hasAny = false; for (String selectedFieldName : selectedFieldNames) { <START> if (StringUtils.startsWithIgnoreCase(selectedFieldName, this.getName())) { <END> hasAny = true; break; } } if (!hasAny) { return; } } PatientData<Integer> data = patient.getData(getName()); if (data == null || !data.isNamed()) { return; } Iterator<Entry<String, Integer>> iterator = data.dictionaryIterator(); if (!iterator.hasNext()) { return; } JSONObject container = json.getJSONObject(DATA_NAME); if (container == null || container.isNullObject()) { json.put(DATA_NAME, new JSONObject()); container = json.getJSONObject(DATA_NAME); } while (iterator.hasNext()) { Entry<String, Integer> item = iterator.next(); if (selectedFieldNames == null || selectedFieldNames.contains(item.getKey())) { container.put(item.getKey(), item.getValue()); } } }</code><technical_language>Why</technical_language>

Target:
public void writeJSON(Patient patient, JSONObject json, Collection<String> selectedFieldNames) { if (selectedFieldNames != null && !hasAnySelected(selectedFieldNames)) { return; } PatientData<Integer> data = patient.getData(getName()); if (data == null || !data.isNamed()) { return; } Iterator<Entry<String, Integer>> iterator = data.dictionaryIterator(); if (!iterator.hasNext()) { return; } JSONObject container = json.getJSONObject(DATA_NAME); if (container == null || container.isNullObject()) { json.put(DATA_NAME, new JSONObject()); container = json.getJSONObject(DATA_NAME); } while (iterator.hasNext()) { Entry<String, Integer> item = iterator.next(); container.put(item.getKey(), item.getValue()); } }
Source:
<code>protected List<? extends Module> getModules() { return ImmutableList.<Module>of( new JettyHttpClientModule("druid.router.http", Router.class), new Module() { @Override public void configure(Binder binder) { binder.bindConstant().annotatedWith(Names.named("serviceName")).to("druid/router"); binder.bindConstant().annotatedWith(Names.named("servicePort")).to(8888); JsonConfigProvider.bind(binder, "druid.router", TieredBrokerConfig.class); binder.bind(CoordinatorRuleManager.class); LifecycleModule.register(binder, CoordinatorRuleManager.class); binder.bind(TieredBrokerHostSelector.class).in(ManageLifecycle.class); binder.bind(QueryHostFinder.class).in(LazySingleton.class); binder.bind(new TypeLiteral<List<TieredBrokerSelectorStrategy>>(){}) .toProvider(TieredBrokerSelectorStrategiesProvider.class) .in(LazySingleton.class); binder.bind(JettyServerInitializer.class).to(RouterJettyServerInitializer.class).in(LazySingleton.class); LifecycleModule.register(binder, Server.class); DiscoveryModule.register(binder, Self.class); <START> binder.install(new LookupModule()); <END> } @Provides @ManageLifecycle public ServerDiscoverySelector getCoordinatorServerDiscoverySelector( TieredBrokerConfig config, ServerDiscoveryFactory factory ) { return factory.createSelector(config.getCoordinatorServiceName()); } } ); }</code><technical_language>suggest moving in list of modules explicit binder.install</technical_language>

Target:
protected List<? extends Module> getModules() { return ImmutableList.<Module>of( new JettyHttpClientModule("druid.router.http", Router.class), new Module() { @Override public void configure(Binder binder) { binder.bindConstant().annotatedWith(Names.named("serviceName")).to("druid/router"); binder.bindConstant().annotatedWith(Names.named("servicePort")).to(8888); JsonConfigProvider.bind(binder, "druid.router", TieredBrokerConfig.class); binder.bind(CoordinatorRuleManager.class); LifecycleModule.register(binder, CoordinatorRuleManager.class); binder.bind(TieredBrokerHostSelector.class).in(ManageLifecycle.class); binder.bind(QueryHostFinder.class).in(LazySingleton.class); binder.bind(new TypeLiteral<List<TieredBrokerSelectorStrategy>>() { }) .toProvider(TieredBrokerSelectorStrategiesProvider.class) .in(LazySingleton.class); binder.bind(JettyServerInitializer.class).to(RouterJettyServerInitializer.class).in(LazySingleton.class); LifecycleModule.register(binder, Server.class); DiscoveryModule.register(binder, Self.class); } @Provides @ManageLifecycle public ServerDiscoverySelector getCoordinatorServerDiscoverySelector( TieredBrokerConfig config, ServerDiscoveryFactory factory ) { return factory.createSelector(config.getCoordinatorServiceName()); } }, new LookupModule() ); }
Source:
<code>public void verifyKeyValues(String slotName, String adapter, String size, String price) { WebElement slotContainer = driver.findElement( By.cssSelector(AdsContent.getSlotSelector(slotName)) ); WebElement gptNode = slotContainer.findElement(By.cssSelector(GPT_NODE)); try { JSONObject keyValues = new JSONObject(gptNode.getAttribute("data-gpt-slot-params")); assertKeyValue(keyValues, "hb_bidder", adapter, "Bidder passed in slot key-values"); assertKeyValue(keyValues, "hb_size", size, "Size passed in slot key-values"); assertKeyValue(keyValues, "hb_pb", price, "Price passed in slot key-values"); } catch (JSONException exception) { <START> PageObjectLogging.log("Prebid.js key-values", exception, false); <END> } }</code><technical_language>adding more logging a description wrong? afraid exception stack trace descriptive. proposal: PageObjectLogging.log("Prebid.js key-values", "Prebid.js key-values in slot div", false); PageObjectLogging.log("Prebid.js key-values", exception, false);</technical_language>

Target:
public void verifyKeyValues(String slotName, String adapter, String size, String price) { WebElement slotContainer = driver.findElement( By.cssSelector(AdsContent.getSlotSelector(slotName)) ); WebElement gptNode = slotContainer.findElement(By.cssSelector(GPT_NODE)); try { JSONObject keyValues = new JSONObject(gptNode.getAttribute("data-gpt-slot-params")); assertKeyValue(keyValues, "hb_bidder", adapter, "Bidder passed in slot key-values"); assertKeyValue(keyValues, "hb_size", size, "Size passed in slot key-values"); assertKeyValue(keyValues, "hb_pb", price, "Price passed in slot key-values"); } catch (JSONException exception) { PageObjectLogging .log("Prebid.js key-values", "Prebid.js key-values not found in slot div", false); PageObjectLogging.log("Prebid.js key-values", exception, false); } }
Source:
<code>public void fillPushAttribute(long t, Object value, int attributeQuark) throws TimeRangeException, StateValueTypeException { int stackDepth; int subAttributeQuark; Object previousSV = transState.getOngoingStateValue(attributeQuark); if (previousSV == null) { stackDepth = 0; } else if (previousSV instanceof Integer) { stackDepth = (int) previousSV; } else { throw new StateValueTypeException(getSSID() + " Quark:" + attributeQuark + ", Type:" + previousSV.getClass() + ", Expected:" + Type.INTEGER); } if (stackDepth >= MAX_STACK_DEPTH) { String message = " Stack limit reached, not pushing"; throw new IllegalStateException(getSSID() + " Quark:" + attributeQuark + message); } int <START> freeSpaceDepth <END> = stackDepth + 1; for (int i = 1; i <= stackDepth; i++) { try { ITmfStateValue stateValue = queryOngoingState(getQuarkRelative(attributeQuark, String.valueOf(i))); if (stateValue.isNull()) { freeSpaceDepth = i; break; } } catch (AttributeNotFoundException e) { } } stackDepth++; subAttributeQuark = getQuarkRelativeAndAdd(attributeQuark, String.valueOf(freeSpaceDepth)); modifyAttribute(t, stackDepth, attributeQuark); modifyAttribute(t, value, subAttributeQuark); }</code><technical_language>for a minute there, I thought this copy pasted Matthew's space compass :p</technical_language>

Target:
public void fillPushAttribute(long t, Object value, int attributeQuark) throws TimeRangeException, StateValueTypeException { int stackDepth; int subAttributeQuark; Object previousSV = transState.getOngoingStateValue(attributeQuark); if (previousSV == null) { stackDepth = 0; } else if (previousSV instanceof Integer) { stackDepth = (int) previousSV; } else { throw new StateValueTypeException(getSSID() + " Quark:" + attributeQuark + ", Type:" + previousSV.getClass() + ", Expected:" + Type.INTEGER); } if (stackDepth >= MAX_STACK_DEPTH) { String message = " Stack limit reached, not pushing"; throw new IllegalStateException(getSSID() + " Quark:" + attributeQuark + message); } int emptySpaceDepth = stackDepth + 1; for (int i = 1; i <= stackDepth; i++) { try { ITmfStateValue stateValue = queryOngoingState(getQuarkRelative(attributeQuark, String.valueOf(i))); if (stateValue.isNull()) { emptySpaceDepth = i; break; } } catch (AttributeNotFoundException e) { } } stackDepth++; subAttributeQuark = getQuarkRelativeAndAdd(attributeQuark, String.valueOf(emptySpaceDepth)); modifyAttribute(t, stackDepth, attributeQuark); modifyAttribute(t, value, subAttributeQuark); }
Source:
<code>private String convertPartitionKeyToString(Object partitionKey) { <START> String ret; <END> if (partitionKey instanceof String) { ret = (String) partitionKey; } else if (partitionKey instanceof Integer) { ret = String.valueOf(partitionKey); } else if (partitionKey instanceof byte[]) { ret = new String((byte[]) partitionKey, Charset.defaultCharset()); } else { throw new SamzaException("Unsupported key type: " + partitionKey.getClass().toString()); } if (ret != null && ret.length() > ClientConstants.MAX_PARTITION_KEY_LENGTH) { LOG.debug("length of partitioning key ({}) exceeds limit: {}. Will truncate the key...", ret.length(), ClientConstants.MAX_PARTITION_KEY_LENGTH); ret = ret.substring(0, ClientConstants.MAX_PARTITION_KEY_LENGTH); } return ret; }</code><technical_language>s/ret/partitionKeyStr maybe</technical_language>

Target:
private String convertPartitionKeyToString(Object partitionKey) { String partitionKeyStr; if (partitionKey instanceof String) { partitionKeyStr = (String) partitionKey; } else if (partitionKey instanceof Integer) { partitionKeyStr = String.valueOf(partitionKey); } else if (partitionKey instanceof byte[]) { partitionKeyStr = new String((byte[]) partitionKey, Charset.defaultCharset()); } else { throw new SamzaException("Unsupported key type: " + partitionKey.getClass().toString()); } if (partitionKeyStr != null && partitionKeyStr.length() > ClientConstants.MAX_PARTITION_KEY_LENGTH) { LOG.debug("Length of partition key: exceeds limit: {}. Truncating.", partitionKeyStr.length(), ClientConstants.MAX_PARTITION_KEY_LENGTH); partitionKeyStr = partitionKeyStr.substring(0, ClientConstants.MAX_PARTITION_KEY_LENGTH); } return partitionKeyStr; }