auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static Object[] satelReadEvent( @ParamDoc(name = "eventIndex", text = "index of event to read, -1 for the most recent") int eventIndex) { if (!satelIsConnected()) { return null; } ReadEventCommand cmd = new ReadEventCommand(eventIndex); if (!SatelActionService.satelCommModule.sendCommand(cmd)) { logger.error("Unable to read record for given index: {}", eventIndex); return null; } else if (cmd.isEmpty()) { <START> logger.warn("No record under given index: {}", eventIndex); <END> return null; } else { EventDescription desc = getEventDescription(cmd.getEventCode(), cmd.isRestore()); return new Object[] { new DateTimeType(cmd.getTimestamp()), cmd.getPartition(), cmd.getEventClass(), cmd.getEventCode(), cmd.isRestore(), desc.eventText, desc.descKind, cmd.getSource(), cmd.getObject(), cmd.getUserControlNumber(), cmd.getNextIndex(), cmd.getCurrentIndex() }; } }</code><technical_language>warn here, error above</technical_language>

Target:
public static Object[] satelReadEvent( @ParamDoc(name = "eventIndex", text = "index of event to read, -1 for the most recent") int eventIndex) { if (!satelIsConnected()) { logger.warn("Not connected to communication module or Satel binding not available."); return null; } ReadEventCommand cmd = new ReadEventCommand(eventIndex); if (!SatelActionService.satelCommModule.sendCommand(cmd)) { logger.error("Unable to read record for given index: {}", eventIndex); return null; } else if (cmd.isEmpty()) { logger.warn("No record under given index: {}", eventIndex); return null; } else { EventDescription desc = getEventDescription(cmd.getEventCode(), cmd.isRestore()); return new Object[] { new DateTimeType(cmd.getTimestamp()), cmd.getPartition(), cmd.getEventClass(), cmd.getEventCode(), cmd.isRestore(), desc.eventText, desc.descKind, cmd.getSource(), cmd.getObject(), cmd.getUserControlNumber(), cmd.getNextIndex(), cmd.getCurrentIndex() }; } }
Source:
<code>public void waitForTooYoungErrorMsg() { <START> wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(tooYoungErrorMsg))); <END> Assertion.assertTrue(tooYoungError.isDisplayed()); PageObjectLogging.log("typeInBirthDate ", "BirthDate field selected", true, driver); }</code><technical_language>expectedConditions. Instead waits BasePageObject</technical_language>

Target:
public void waitForTooYoungErrorMsg() { waitForElementByElement(tooYoungError); Assertion.assertTrue(tooYoungError.isDisplayed()); PageObjectLogging.log("typeInBirthDate ", "BirthDate field selected", true); }
Source:
<code>public static Slice invalidReason(@SqlType(GEOMETRY_TYPE_NAME) Slice input) { GeometryCursor cursor = deserialize(input).getEsriGeometryCursor(); NonSimpleResult result = new NonSimpleResult(); <START> while (true) { <END> com.esri.core.geometry.Geometry geometry = cursor.next(); if (geometry == null) { return null; } if (!OperatorSimplifyOGC.local().isSimpleOGC(geometry, null, true, result, null)) { String reasonText = NON_SIMPLE_REASONS.getOrDefault(result.m_reason, result.m_reason.name()); MultiVertexGeometry multiVertexGeometry = (MultiVertexGeometry) geometry; if (result.m_vertexIndex1 >= 0 && result.m_vertexIndex2 >= 0) { Point point1 = multiVertexGeometry.getPoint(result.m_vertexIndex1); Point point2 = multiVertexGeometry.getPoint(result.m_vertexIndex2); return utf8Slice(format("%s at or near (%s %s) and (%s %s)", reasonText, point1.getX(), point1.getY(), point2.getX(), point2.getY())); } if (result.m_vertexIndex1 >= 0) { Point point = multiVertexGeometry.getPoint(result.m_vertexIndex1); return utf8Slice(format("%s at or near (%s %s)", reasonText, point.getX(), point.getY())); } return utf8Slice(format("%s", reasonText)); } } }</code><technical_language>Move closer</technical_language>

Target:
public static Slice invalidReason(@SqlType(GEOMETRY_TYPE_NAME) Slice input) { GeometryCursor cursor = deserialize(input).getEsriGeometryCursor(); NonSimpleResult result = new NonSimpleResult(); while (true) { com.esri.core.geometry.Geometry geometry = cursor.next(); if (geometry == null) { return null; } if (!OperatorSimplifyOGC.local().isSimpleOGC(geometry, null, true, result, null)) { String reasonText = NON_SIMPLE_REASONS.getOrDefault(result.m_reason, result.m_reason.name()); if (!(geometry instanceof MultiVertexGeometry)) { return utf8Slice(reasonText); } MultiVertexGeometry multiVertexGeometry = (MultiVertexGeometry) geometry; if (result.m_vertexIndex1 >= 0 && result.m_vertexIndex2 >= 0) { Point point1 = multiVertexGeometry.getPoint(result.m_vertexIndex1); Point point2 = multiVertexGeometry.getPoint(result.m_vertexIndex2); return utf8Slice(format("%s at or near (%s %s) and (%s %s)", reasonText, point1.getX(), point1.getY(), point2.getX(), point2.getY())); } if (result.m_vertexIndex1 >= 0) { Point point = multiVertexGeometry.getPoint(result.m_vertexIndex1); return utf8Slice(format("%s at or near (%s %s)", reasonText, point.getX(), point.getY())); } return utf8Slice(reasonText); } } }
Source:
<code>private int outputLicense(Configuration config) { File licFH = new VoltFile(config.m_voltdbRoot.getParent(), "license.xml"); try { if (!licFH.isFile() || !licFH.canRead()) { consoleLog.fatal("Failed to get license. " + licFH.getAbsolutePath()); return -1; } config.m_pathToLicense = licFH.getCanonicalPath(); } catch (IOException e) { consoleLog.fatal("Failed to read license: " + e.getMessage()); return -1; } try { if ((new File(config.m_getOutput)).exists() && !config.m_forceGetCreate) { consoleLog.fatal("Failed to save license.xml, file already exists: " + config.m_getOutput); return -1; } try { <START> File target = new File("./license.xml"); <END> InputStream is = null; OutputStream os = null; try { is = new FileInputStream(licFH); os = new FileOutputStream(target); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } } finally { is.close(); os.close(); } } catch (IOException e) { consoleLog.fatal("Failed to copy license to " + config.m_getOutput + " : " + e.getMessage()); return -1; } consoleLog.info("license.xml saved in " + config.m_getOutput.trim()); } catch (Exception e) { consoleLog.fatal("Failed to get license. " + "Please make sure voltdbroot is a valid directory. " + e.getMessage()); return -1; } return 0; }</code><technical_language>Is suppose config.m_getOutput path for target file</technical_language>

Target:
private int outputLicense(Configuration config) { File licFH = new VoltFile(config.m_pathToLicense); if (!licFH.isFile() || !licFH.canRead()) { consoleLog.fatal("Failed to get license. " + licFH.getAbsolutePath()); return -1; } try { if ((new File(config.m_getOutput)).exists() && !config.m_forceGetCreate) { consoleLog.fatal("Failed to save license.xml, file already exists: " + config.m_getOutput); return -1; } try { File target = new File(config.m_getOutput); InputStream is = null; OutputStream os = null; try { is = new FileInputStream(licFH); os = new FileOutputStream(target); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } } finally { is.close(); os.close(); } } catch (IOException e) { consoleLog.fatal("Failed to copy license to " + config.m_getOutput + " : " + e.getMessage()); return -1; } consoleLog.info("license saved as " + config.m_getOutput.trim()); } catch (Exception e) { consoleLog.fatal("Failed to get license. " + "Please make sure voltdbroot is a valid directory. " + e.getMessage()); return -1; } return 0; }
Source:
<code>public DataRegistration<M, I> build() { validate(); <START> this.container = Sponge.getCauseStackManager().getCurrentCause().first(PluginContainer.class).get(); <END> return new SpongeDataRegistration<>(this); }</code><technical_language>a more proper exception for this get call</technical_language>

Target:
public DataRegistration<M, I> build() { validate(); this.container = Sponge.getCauseStackManager().getCurrentCause().first(PluginContainer.class) .orElseThrow(() -> new IllegalStateException("Cannot find a PluginContainer in the current Cause.")); return new SpongeDataRegistration<>(this); }
Source:
<code>protected void onAddElement(Rule rule) throws IllegalArgumentException { Rule ruleWithUID = rule; if (rule.getUID() == null) { ruleWithUID = ruleEngine.initRuleId(rule); } String rUID = ruleWithUID.getUID(); <START> postRuleAddedEvent(ruleWithUID); <END> ruleEngine.addRule(ruleWithUID, (disabledRulesStorage != null && disabledRulesStorage.get(rUID) == null)); Rule resolvedRule = resolveRuleByTemplate(ruleWithUID); if (ruleWithUID != resolvedRule) { super.update(resolvedRule); } }</code><technical_language>rule added event fire adding rule ruleengine</technical_language>

Target:
protected void onAddElement(Rule rule) throws IllegalArgumentException { String uid = rule.getUID(); ruleEngine.addRule(rule, (disabledRulesStorage != null && disabledRulesStorage.get(uid) == null)); String templateUID = rule.getTemplateUID(); if (templateUID != null) { synchronized (this) { Set<String> ruleUIDs = mapTemplateToRules.get(templateUID); if (ruleUIDs == null) { ruleUIDs = new HashSet<String>(11); mapTemplateToRules.put(templateUID, ruleUIDs); } ruleUIDs.add(uid); } } }
Source:
<code>public void shutdown(final String taskId) { if (!started) { log.info("This TaskRunner is stopped. Ignoring shutdown command for task: %s", taskId); } else if (pendingTasks.remove(taskId) != null) { pendingTaskPayloads.remove(taskId); log.info("Removed task from pending queue: %s", taskId); } else if (completeTasks.containsKey(taskId)) { cleanup(taskId); } else { final ZkWorker zkWorker = findWorkerRunningTask(taskId); if (zkWorker == null) { log.info("Can't shutdown! No worker running task %s", taskId); return; } URL url = null; try { url = makeWorkerURL(zkWorker.getWorker(), String.format("/task/%s/shutdown", taskId)); final StatusResponseHolder response = httpClient.go( new Request(HttpMethod.POST, url), RESPONSE_HANDLER <START> ).get(config.getTaskCleanupTimeout().getMillis(), TimeUnit.MILLISECONDS); <END> log.info( "Sent shutdown message to worker: %s, status %s, response: %s", zkWorker.getWorker().getHost(), response.getStatus(), response.getContent() ); if (!response.getStatus().equals(HttpResponseStatus.ACCEPTED)) { log.error("Shutdown failed for %s! Are you sure the task was running?", taskId); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RE(e, "Timed out posting shutdown to [%s] for task [%s]", url, taskId); } catch (Exception e) { throw new RE(e, "Error in handling post to [%s] for task [%s]", zkWorker.getWorker().getHost(), taskId); } } }</code><technical_language>taskShutdownTimeout</technical_language>

Target:
public void shutdown(final String taskId) { if (!started) { log.info("This TaskRunner is stopped. Ignoring shutdown command for task: %s", taskId); } else if (pendingTasks.remove(taskId) != null) { pendingTaskPayloads.remove(taskId); log.info("Removed task from pending queue: %s", taskId); } else if (completeTasks.containsKey(taskId)) { cleanup(taskId); } else { final ZkWorker zkWorker = findWorkerRunningTask(taskId); if (zkWorker == null) { log.info("Can't shutdown! No worker running task %s", taskId); return; } URL url = null; try { url = makeWorkerURL(zkWorker.getWorker(), String.format("/task/%s/shutdown", taskId)); final StatusResponseHolder response = httpClient.go( new Request(HttpMethod.POST, url), RESPONSE_HANDLER, shutdownTimeout ).get(); log.info( "Sent shutdown message to worker: %s, status %s, response: %s", zkWorker.getWorker().getHost(), response.getStatus(), response.getContent() ); if (!response.getStatus().equals(HttpResponseStatus.ACCEPTED)) { log.error("Shutdown failed for %s! Are you sure the task was running?", taskId); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RE(e, "Interrupted posting shutdown to [%s] for task [%s]", url, taskId); } catch (Exception e) { throw new RE(e, "Error in handling post to [%s] for task [%s]", zkWorker.getWorker().getHost(), taskId); } } }
Source:
<code>private void startTaskExecutorInContainer(Container container, TaskExecutorProcessSpec taskExecutorProcessSpec, ResourceID resourceId, CompletableFuture<YarnWorkerNode> requestResourceFuture) { final YarnWorkerNode yarnWorkerNode = new YarnWorkerNode(container, resourceId); try { ContainerLaunchContext taskExecutorLaunchContext = createTaskExecutorLaunchContext( resourceId, container.getNodeId().getHost(), taskExecutorProcessSpec); nodeManagerClient.startContainerAsync(container, taskExecutorLaunchContext); } catch (Throwable t) { requestResourceFuture.completeExceptionally(t); } <START> requestResourceFuture.complete(yarnWorkerNode); <END> }</code><technical_language>nit: logic more clear move this line try-block</technical_language>

Target:
private void startTaskExecutorInContainer(Container container, TaskExecutorProcessSpec taskExecutorProcessSpec, ResourceID resourceId, CompletableFuture<YarnWorkerNode> requestResourceFuture) { final YarnWorkerNode yarnWorkerNode = new YarnWorkerNode(container, resourceId); try { ContainerLaunchContext taskExecutorLaunchContext = createTaskExecutorLaunchContext( resourceId, container.getNodeId().getHost(), taskExecutorProcessSpec); nodeManagerClient.startContainerAsync(container, taskExecutorLaunchContext); requestResourceFuture.complete(yarnWorkerNode); } catch (Throwable t) { requestResourceFuture.completeExceptionally(t); } }
Source:
<code>public Void call() throws Exception { try { <START> this.trigger.initialize(this.getJobContext().getWorkingMemory().getKnowledgeRuntime()); <END> this.trigger.nextFireTime(); if ( handle.isCancel() ) { return null; } this.job.execute( this.ctx ); if ( handle.isCancel() ) { return null; } Date date = this.trigger.hasNextFireTime(); if ( date != null ) { scheduler.internalSchedule( this ); } } catch(Exception e) { logger.warn("Unable to execute timer job!", e); throw e; } return null; }</code><technical_language>if is chance a trigger context context=null. In case, this throw a NPE. wdyt</technical_language>

Target:
public Void call() throws Exception { try { this.trigger.initialize(this.getJobContext().getInternalKnowledgeRuntime().orElse(null)); this.trigger.nextFireTime(); if ( handle.isCancel() ) { return null; } this.job.execute( this.ctx ); if ( handle.isCancel() ) { return null; } Date date = this.trigger.hasNextFireTime(); if ( date != null ) { scheduler.internalSchedule( this ); } } catch(Exception e) { logger.warn("Unable to execute timer job!", e); throw e; } return null; }
Source:
<code>public Set<Diff> getDirectResultingMerges(Diff target, boolean mergeRightToLeft) { final Set<Diff> resulting = new LinkedHashSet<Diff>(); if (mergeRightToLeft) { if (DifferenceSource.LEFT == target.getSource()) { resulting.addAll(target.getImpliedBy()); } else { resulting.addAll(target.getImplies()); } } else { if (DifferenceSource.LEFT == target.getSource()) { resulting.addAll(target.getImplies()); } else { resulting.addAll(target.getImpliedBy()); } } if (target.getEquivalence() != null) { resulting.addAll(target.getEquivalence().getDifferences()); resulting.remove(target); } if (target.getConflict() != null && target.getConflict().getKind() == ConflictKind.PSEUDO) { resulting.addAll(target.getConflict().getDifferences()); resulting.remove(target); } for (Diff refine : target.getRefines()) { Set<Diff> tmp = Sets.newHashSet(resulting); tmp.add(target); <START> Collection<Diff> notUnresolvedRefinedBy = Collections2.filter(refine.getRefinedBy(), <END> EMFComparePredicates.hasState(DifferenceState.UNRESOLVED)); if (tmp.containsAll(notUnresolvedRefinedBy)) { resulting.add(refine); } } if (target instanceof ReferenceChange) { final ReferenceChange refTarget = (ReferenceChange)target; if (isOneToOneAndChange(refTarget)) { resulting.addAll(findInterlockedOneToOneDiffs(refTarget, mergeRightToLeft)); } } return resulting; }</code><technical_language>name of variable contradicts is created. called "unresolvedRefinedDiffs" sth diffs UNRESOLVED, aren't..</technical_language>

Target:
public Set<Diff> getDirectResultingMerges(Diff target, boolean mergeRightToLeft) { final Set<Diff> resulting = new LinkedHashSet<Diff>(); if (mergeRightToLeft) { if (DifferenceSource.LEFT == target.getSource()) { resulting.addAll(target.getImpliedBy()); } else { resulting.addAll(target.getImplies()); } } else { if (DifferenceSource.LEFT == target.getSource()) { resulting.addAll(target.getImplies()); } else { resulting.addAll(target.getImpliedBy()); } } if (target.getEquivalence() != null) { resulting.addAll(target.getEquivalence().getDifferences()); resulting.remove(target); } if (target.getConflict() != null && target.getConflict().getKind() == ConflictKind.PSEUDO) { resulting.addAll(target.getConflict().getDifferences()); resulting.remove(target); } for (Diff refine : target.getRefines()) { Set<Diff> tmp = Sets.newHashSet(resulting); tmp.add(target); Collection<Diff> unresolvedRefinedDiffs = Collections2.filter(refine.getRefinedBy(), EMFComparePredicates.hasState(DifferenceState.UNRESOLVED)); if (tmp.containsAll(unresolvedRefinedDiffs)) { resulting.add(refine); } } if (target instanceof ReferenceChange) { final ReferenceChange refTarget = (ReferenceChange)target; if (isOneToOneAndChange(refTarget)) { resulting.addAll(findInterlockedOneToOneDiffs(refTarget, mergeRightToLeft)); } } return resulting; }
Source:
<code>private String normalizeWindowGlobals(String name) { <START> if (name.startsWith("window.") || name.startsWith("this.")) { <END> return name.replaceAll("^(window|this)\\.", ""); } return name; }</code><technical_language>'if' check needed here, right? replaceAll match if true</technical_language>

Target:
private String normalizeWindowGlobals(String name) { return name.replaceAll("^(window|this)\\.", ""); }
Source:
<code>public static float seededRandomFloat(float min, float max) { float result = max; if (min == max) { <START> Gdx.app.log("SolMath", "rnd was called with bad parameters! Min " + min + " matches max " + max + ", accepting max."); <END> Gdx.app.log("SolMath", "Please review appropriate code in the stack dump:"); for (StackTraceElement ste : Thread.currentThread().getStackTrace()) { Gdx.app.log("SolMath", ste.toString()); } return result; } return seededRandom.nextFloat() * (max - min) + min; }</code><technical_language>method is rnd anymore</technical_language>

Target:
public static float seededRandomFloat(float min, float max) { if (min >= max) { Gdx.app.log("SolMath", "seededRandomFloat was called with bad parameters! Min " + min + " >= max " + max + "."); Gdx.app.log("SolMath", "Please review appropriate code in the stack dump:"); for (StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace()) { Gdx.app.log("SolMath", stackTraceElement.toString()); } return max; } return seededRandom.nextFloat() * (max - min) + min; }
Source:
<code>public void execute() throws Exception { if (!CassandraMonitor.hasCassadraStarted()) { logger.debug("Cassandra has not started, hence SnapshotMetaService will not run"); return; } if (!lock.tryLock()) { <START> logger.error("SnapshotMetaService is already running! Try again later."); <END> throw new Exception("SnapshotMetaService already running"); } try { Instant snapshotInstant = DateUtil.getInstant(); snapshotName = generateSnapshotName(snapshotInstant); logger.info("Initializing SnapshotMetaService for taking a snapshot {}", snapshotName); metaFileManager.cleanupOldMetaFiles(); cassandraOperations.takeSnapshot(snapshotName); processSnapshot(snapshotInstant).uploadMetaFile(true); logger.info("Finished processing snapshot meta service"); } catch (Exception e) { logger.error("Error while executing SnapshotMetaService", e); } finally { lock.unlock(); } }</code><technical_language>similar warn logging</technical_language>

Target:
public void execute() throws Exception { if (!CassandraMonitor.hasCassadraStarted()) { logger.debug("Cassandra has not started, hence SnapshotMetaService will not run"); return; } if (!lock.tryLock()) { logger.warn("SnapshotMetaService is already running! Try again later."); throw new Exception("SnapshotMetaService already running"); } try { Instant snapshotInstant = DateUtil.getInstant(); snapshotName = generateSnapshotName(snapshotInstant); logger.info("Initializing SnapshotMetaService for taking a snapshot {}", snapshotName); metaFileManager.cleanupOldMetaFiles(); cassandraOperations.takeSnapshot(snapshotName); processSnapshot(snapshotInstant).uploadMetaFile(true); logger.info("Finished processing snapshot meta service"); } catch (Exception e) { logger.error("Error while executing SnapshotMetaService", e); } finally { lock.unlock(); } }
Source:
<code>void onStart(ConfigurationPropertySource propertySource) { if ( clientImplementor == null ) { clientImplementor = clientFactoryHolder.get().create( propertySource, threadPoolProvider, defaultGsonProvider ); clientFactoryHolder.close(); if ( versionCheckEnabled ) { elasticsearchVersion = ElasticsearchClientUtils.getElasticsearchVersion( clientImplementor ); if ( configuredVersionOptional.isPresent() ) { ElasticsearchVersion configuredVersion = configuredVersionOptional.get(); if ( !configuredVersion.matches( elasticsearchVersion ) ) { throw log.unexpectedElasticsearchVersion( configuredVersion, elasticsearchVersion ); } } } else if ( configuredVersionOptional.isPresent() ) { ElasticsearchVersion configuredVersion = configuredVersionOptional.get(); <START> if ( configuredVersion.getMinor().isPresent() && configuredVersion.getMicro().isPresent() ) { <END> elasticsearchVersion = configuredVersion; } else { throw log.invalidElasticsearchVersionCheckConfiguration( configuredVersion.toString() ); } } else { throw log.invalidElasticsearchVersionCheckConfiguration( null ); } ElasticsearchProtocolDialect protocolDialect = dialectFactory.createProtocolDialect( elasticsearchVersion ); gsonProvider = GsonProvider.create( GsonBuilder::new, logPrettyPrinting ); indexMetadataSyntax = protocolDialect.createIndexMetadataSyntax(); searchSyntax = protocolDialect.createSearchSyntax(); workBuilderFactory = protocolDialect.createWorkBuilderFactory( gsonProvider ); searchResultExtractorFactory = protocolDialect.createSearchResultExtractorFactory(); } }</code><technical_language>Ideally this (and case "no version is configured") checked earlier, in ElasticsearchBackendFactory. This is especially important for Quarkus, configuration is checked compile-time. Also, I relax constraint allow micro missing: Elasticsearch team mess big time for behave differently based micro</technical_language>

Target:
void onStart(ConfigurationPropertySource propertySource) { if ( clientImplementor == null ) { clientImplementor = clientFactoryHolder.get().create( propertySource, threadPoolProvider, defaultGsonProvider ); clientFactoryHolder.close(); if ( versionCheckEnabled ) { elasticsearchVersion = ElasticsearchClientUtils.getElasticsearchVersion( clientImplementor ); if ( configuredVersionOptional.isPresent() ) { ElasticsearchVersion configuredVersion = configuredVersionOptional.get(); if ( !configuredVersion.matches( elasticsearchVersion ) ) { throw log.unexpectedElasticsearchVersion( configuredVersion, elasticsearchVersion ); } } } else { configuredVersionOptional.ifPresent( version -> elasticsearchVersion = version ); } ElasticsearchProtocolDialect protocolDialect = dialectFactory.createProtocolDialect( elasticsearchVersion ); gsonProvider = GsonProvider.create( GsonBuilder::new, logPrettyPrinting ); indexMetadataSyntax = protocolDialect.createIndexMetadataSyntax(); searchSyntax = protocolDialect.createSearchSyntax(); workBuilderFactory = protocolDialect.createWorkBuilderFactory( gsonProvider ); searchResultExtractorFactory = protocolDialect.createSearchResultExtractorFactory(); } }
Source:
<code>public AEColor[] toColors( short frequency ) { <START> final AEColor[] colours = new AEColor[4]; <END> for( int i = 0; i < 4; i++ ) { int nibble = ( frequency >> 4 * ( 3 - i ) ) & 0xF; colours[i] = AEColor.values()[nibble]; } return colours; }</code><technical_language>missed colours :)</technical_language>

Target:
public AEColor[] toColors( short frequency ) { final AEColor[] colors = new AEColor[4]; for( int i = 0; i < 4; i++ ) { int nibble = ( frequency >> 4 * ( 3 - i ) ) & 0xF; colors[i] = AEColor.values()[nibble]; } return colors; }
Source:
<code>public void saveOrUpdateShouldThrowIAEWhenUserCannotBeFoundById() { given(this.userRepository.findOne(USER_ID)).willReturn(NULL_USER_ENTITY); <START> given(this.passwordHistoryRepository.findByUserEntity(NULL_USER_ENTITY)).willThrow(IllegalArgumentException.class); <END> this.passwordChangeService.saveOrUpdate(passwordHistoryDtoWithUserId); }</code><technical_language>This statement is necessary Assert.notNull(userEntity) throw IAE control passwordHistoryRepository</technical_language>

Target:
public void saveOrUpdateShouldThrowIAEWhenUserCannotBeFoundById() { given(this.userRepository.findOne(USER_ID)).willReturn(NULL_USER_ENTITY); this.passwordChangeService.saveOrUpdate(passwordHistoryDtoWithUserId); }
Source:
<code>public Page getNextPage() { PrestoSparkSerializedPage prestoSparkSerializedPage = null; synchronized (this) { while (prestoSparkSerializedPage == null) { if (currentIteratorIndex >= serializedPageIterators.size()) { return null; } Iterator<PrestoSparkSerializedPage> currentIterator = serializedPageIterators.get(currentIteratorIndex); <START> if (!currentIterator.hasNext()) { currentIteratorIndex++; continue; } prestoSparkSerializedPage = currentIterator.next(); <END> } } return pagesSerde.deserialize(toSerializedPage(prestoSparkSerializedPage)); }</code><technical_language>I prefer this if (currentIterator.hasNext()) { prestoSparkSerializedPage = currentIterator.next(); } else { currentIteratorIndex++; }</technical_language>

Target:
public Page getNextPage() { PrestoSparkSerializedPage prestoSparkSerializedPage = null; synchronized (this) { while (prestoSparkSerializedPage == null) { if (currentIteratorIndex >= serializedPageIterators.size()) { return null; } Iterator<PrestoSparkSerializedPage> currentIterator = serializedPageIterators.get(currentIteratorIndex); if (currentIterator.hasNext()) { prestoSparkSerializedPage = currentIterator.next(); } else { currentIteratorIndex++; } } } return pagesSerde.deserialize(toSerializedPage(prestoSparkSerializedPage)); }
Source:
<code>protected Set<Value.Immutable<?>> api$getVanillaValues() { Set<Value.Immutable<?>> vanillaValues = super.api$getVanillaValues(); <START> if (this.caughtEntity != null) { <END> this.targetEntity().map(Value::asImmutable).ifPresent(vanillaValues::add); } return vanillaValues; }</code><technical_language>Delete if, covered ifPresent</technical_language>

Target:
protected Set<Value.Immutable<?>> api$getVanillaValues() { final Set<Value.Immutable<?>> values = super.api$getVanillaValues(); values.add(this.shooter().asImmutable()); this.targetEntity().map(Value::asImmutable).ifPresent(values::add); return values; }
Source:
<code>public void requestItems() { if (requestCount > 0) { <START> Iterator<LoadedItem> iter = this.loadedItems.iterator(); <END> while (iter.hasNext()) { LoadedItem item = iter.next(); if (item.isSelected() && item.isDisplayed()) { MainProxy.sendPacketToServer(PacketHandler.getPacket(SubmitFluidRequestPacket.class).setDimension(dimension).setStack(item.getStack().getItem().makeStack(requestCount)).setPosX(xCoord).setPosY(yCoord).setPosZ(zCoord)); } } } }</code><technical_language>a for here</technical_language>

Target:
public void requestItems() { if (requestCount > 0) { ArrayList<ItemIdentifierStack> stacks = new ArrayList<ItemIdentifierStack>(); for (LoadedItem item : loadedItems){ if (item.isSelected() && item.isDisplayed()) { stacks.add(item.getStack().getItem().makeStack(requestCount)); } } if (stacks.size() > 0){ MainProxy.sendPacketToServer(PacketHandler.getPacket(SubmitFluidRequestPacket.class).setDimension(dimension) .setStacks(stacks.toArray(new ItemIdentifierStack[stacks.size()])).setPosX(xCoord).setPosY(yCoord).setPosZ(zCoord)); } } }
Source:
<code>private static void convert(String e, Properties p) { <START> String[] kv = e.split(">"); <END> String key; String value = null; if(kv.length == 0) { key = e; } else { key = kv[0]; } if(kv.length > 1) { value = kv[1]; } p.put(urlDecode(key), urlDecode(value)); }</code><technical_language>constant for key/value separator</technical_language>

Target:
private static void convert(String e, Properties p) { String[] kv = e.split(PROPERTIES_KV_SEPARATOR); String key = kv[0]; String value = null; if(kv.length == 2) { value = kv[1]; } p.put(urlDecode(key), urlDecode(value)); }
Source:
<code>public Preview.PreviewSurfaceProvider getPreviewSurfaceProvider() { return <START> (resolution, surfaceReleaseFuture) -> { <END> mResolution = resolution; initInternal(); mSurfaceReleaseFuture = surfaceReleaseFuture; return CallbackToFutureAdapter.getFuture( (CallbackToFutureAdapter.Resolver<Surface>) completer -> { cancelSurfaceCompleters(); mCompleterMap.put(completer, surfaceReleaseFuture); completer.addCancellationListener(() -> onCompleterCancelled(completer), ContextCompat.getMainExecutor(mTextureView.getContext())); mSurfaceCompleter = completer; tryToProvidePreviewSurface(); return "provide preview surface"; }); }; }</code><technical_language>long this is run main thread need concurrency primitives in this class. simply put a precondition check ensure this code is running main thread control is registered Preview a main thread executor</technical_language>

Target:
public Preview.PreviewSurfaceProvider getPreviewSurfaceProvider() { Threads.checkMainThread(); return (resolution, surfaceReleaseFuture) -> { mResolution = resolution; initInternal(); mSurfaceReleaseFuture = surfaceReleaseFuture; return CallbackToFutureAdapter.getFuture( (CallbackToFutureAdapter.Resolver<Surface>) completer -> { cancelSurfaceCompleters(); mCompleterMap.put(completer, surfaceReleaseFuture); completer.addCancellationListener(() -> onCompleterCancelled(completer), ContextCompat.getMainExecutor(mTextureView.getContext())); mSurfaceCompleter = completer; tryToProvidePreviewSurface(); return "provide preview surface"; }); }; }
Source:
<code><START> public void testTokenForDisabledUser() <END> { UserDetails userDetails = mock(UserDetails.class); runAsUserTokenFactory.create("test", userDetails, null); verify(userDetailsChecker).check(userDetails); }</code><technical_language>test name match case more</technical_language>

Target:
public void testTokenForDisabledUser() { UserDetails userDetails = mock(UserDetails.class); doThrow(new DisabledException("User is disabled.")).when(userDetailsChecker).check(userDetails); runAsUserTokenFactory.create("test", userDetails, null); }
Source:
<code>private Option<String> serializeValue(Object value) { if (value == null) { return Option.empty(); } String rawValue; try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (serializer == null) { <START> if (DEFAULT_SERIALIZER == null) { <END> synchronized (SERIALIZER_INSTANTIATION_SYNCHRONIZER) { if (DEFAULT_SERIALIZER == null) { DEFAULT_SERIALIZER = JsonSerializerProviders.createInstance(); } } } DEFAULT_SERIALIZER.serialize(outputStream, value); } else { serializer.serialize(outputStream, value); } rawValue = outputStream.toString("UTF-8"); } catch (IOException ex) { throw logger.logExceptionAsError(new UncheckedIOException(ex)); } return Option.of(rawValue); }</code><technical_language>static + DCL is safe in latest version of java, I remember spot bug alerting DCL in past. jfyi, is init-on-demand-holder [pattern](<LINK_0> for cases require explicit lock</technical_language>

Target:
private Option<String> serializeValue(Object value) { if (value == null) { return Option.empty(); } String rawValue; try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (serializer == null) { if (defaultSerializer == null) { synchronized (SERIALIZER_INSTANTIATION_SYNCHRONIZER) { if (defaultSerializer == null) { defaultSerializer = JsonSerializerProviders.createInstance(); } } } defaultSerializer.serialize(outputStream, value); } else { serializer.serialize(outputStream, value); } rawValue = outputStream.toString("UTF-8"); } catch (IOException ex) { throw logger.logExceptionAsError(new UncheckedIOException(ex)); } return Option.of(rawValue); }
Source:
<code>public void transform(ColumnVector outputColVector, ColumnVector inputVector, int idx) { boolean isBooleanType = this.getInputTypeInfos()[0].getTypeName().equals(serdeConstants.BOOLEAN_TYPE_NAME); <START> if(inputVector.isNull[idx] || isBooleanType) { <END> outputColVector.isNull[idx] = true; outputColVector.noNulls = false; return; } outputColVector.isNull[idx] = false; long[] inputCol = ((LongColumnVector)inputVector).vector; long[] outputCol = ((LongColumnVector)outputColVector).vector; long value = inputCol[idx]; long val = value; if(value < 0) { val *= -1; } long ret = 0; long pos = 1; for(int i = 0; val != 0; i++) { ret += maskedNumber * pos; val /= 10; pos *= 10; } if(value < 0) { ret *= -1; } outputCol[idx] = ret; }</code><technical_language>noNulls checking</technical_language>

Target:
public void transform(ColumnVector outputColVector, ColumnVector inputVector, int idx) { boolean isBooleanType = this.getInputTypeInfos()[0].getTypeName().equals(serdeConstants.BOOLEAN_TYPE_NAME); if(isBooleanType) { outputColVector.isNull[idx] = true; outputColVector.noNulls = false; return; } outputColVector.isNull[idx] = false; long[] inputCol = ((LongColumnVector)inputVector).vector; long[] outputCol = ((LongColumnVector)outputColVector).vector; long value = inputCol[idx]; long val = value; if(value < 0) { val *= -1; } long ret = 0; long pos = 1; for(int i = 0; val != 0; i++) { ret += maskedNumber * pos; val /= 10; pos *= 10; } if(value < 0) { ret *= -1; } outputCol[idx] = ret; }
Source:
<code>public void removeProject(DiffProject project) { DiffProject[] temp = new DiffProject[fDiffProjects.length - 1]; int counter = 0; for (DiffProject <START> fDiffProject : <END> fDiffProjects) { if (fDiffProject != project) { temp[counter++] = fDiffProject; } } fDiffProjects = temp; }</code><technical_language>a field</technical_language>

Target:
public void removeProject(DiffProject project) { DiffProject[] temp = new DiffProject[fDiffProjects.length - 1]; int counter = 0; for (DiffProject diffProject : fDiffProjects) { if (diffProject != project) { temp[counter++] = diffProject; } } fDiffProjects = temp; }
Source:
<code><START> public Data getCore() { <END> IPv4 ipv4 = (IPv4) getPayload(); UDP udp = (UDP) ipv4.getPayload(); return (Data) udp.getPayload(); }</code><technical_language>return ElasticData, support a payload. avoids casts in callers</technical_language>

Target:
public ElasticData getCore() { IPv4 ipv4 = (IPv4) getPayload(); UDP udp = (UDP) ipv4.getPayload(); return (ElasticData) udp.getPayload(); }
Source:
<code>private Response evalVelocity(final HttpServletRequest request, final HttpServletResponse response, final Reader velocityReader, final Map<String, Object> contextParams, final User user, final DotJSONCache cache) throws Exception { final org.apache.velocity.context.Context context = VelocityUtil.getInstance().getContext(request, response); contextParams.forEach(context::put); context.put("dotJSON", new DotJSON()); final StringWriter evalResult = new StringWriter(); try { VelocityUtil.getEngine().evaluate(context, evalResult, "", velocityReader); } catch(MethodInvocationException e) { if(e.getCause() instanceof DotToolException) { <START> throw (Exception) (e.getCause()).getCause(); <END> } } final DotJSON dotJSON = (DotJSON) context.get("dotJSON"); if(dotJSON.size()==0) { return Response.ok(evalResult.toString()).build(); } else { if(UtilMethods.isSet(dotJSON.get("errors"))) { return Response.status(Response.Status.BAD_REQUEST).entity(dotJSON.get("errors")).build(); } cache.add(request, user, dotJSON); return Response.ok(dotJSON.getMap()).build(); } }</code><technical_language>a Logger.error here</technical_language>

Target:
private Response evalVelocity(final HttpServletRequest request, final HttpServletResponse response, final Reader velocityReader, final Map<String, Object> contextParams, final User user, final DotJSONCache cache) throws Exception { final org.apache.velocity.context.Context context = VelocityUtil.getInstance().getContext(request, response); contextParams.forEach(context::put); context.put("dotJSON", new DotJSON()); final StringWriter evalResult = new StringWriter(); try { VelocityUtil.getEngine().evaluate(context, evalResult, "", velocityReader); } catch(MethodInvocationException e) { if(e.getCause() instanceof DotToolException) { Logger.error(this,"Error evaluating velocity: " + (e.getCause()).getCause().getMessage()); throw (Exception) (e.getCause()).getCause(); } } final DotJSON dotJSON = (DotJSON) context.get("dotJSON"); if(dotJSON.size()==0) { return Response.ok(evalResult.toString()).build(); } else { if(UtilMethods.isSet(dotJSON.get("errors"))) { return Response.status(Response.Status.BAD_REQUEST).entity(dotJSON.get("errors")).build(); } cache.add(request, user, dotJSON); return Response.ok(dotJSON.getMap()).build(); } }
Source:
<code>public PropertyHandle<T> getHandle() { if ( handle == null ) { try { <START> handle = introspector.createPropertyHandle( name, member ); <END> } catch (IllegalAccessException | RuntimeException e) { throw log.errorRetrievingPropertyTypeModel( getName(), holderTypeModel, e ); } } return handle; }</code><technical_language>This effectively hides problem carpet. problem is introspector (and, that, factory) guarantee property handle of type PropertyHandle<T> for member. this solution pass a method representing toString request a PropertyHandle<Integer> compile fine. runtime get exception eventually, compile. nice solution here, I a more readable one: remove this entire commit, replace beginning of this method this: @SuppressWarnings("unchecked") // construction, member returns values of type T public PropertyHandle<T> getHandle() { if ( handle == null ) { try { handle = (PropertyHandle<T>) introspector.createPropertyHandle( name, member ); do similar in org.hibernate.search.mapper.javabean.model.impl.JavaBeanPropertyModel#getHandle</technical_language>

Target:
public PropertyHandle<T> getHandle() { if ( handle == null ) { try { handle = (PropertyHandle<T>) introspector.createPropertyHandle( name, member ); } catch (IllegalAccessException | RuntimeException e) { throw log.errorRetrievingPropertyTypeModel( getName(), holderTypeModel, e ); } } return handle; }
Source:
<code>public void canDoActionFailsOnNullCluster() { cmd = spy(new EnableGlusterHookCommand(new GlusterHookParameters(null, HOOK_ID))); setupMocks(); <START> assertFalse(cmd.canDoAction()); <END> }</code><technical_language>is verify exact error message well. example: UpdateVdsGroupCommandTest#canDoActionFailedWithReason()</technical_language>

Target:
public void canDoActionFailsOnNullCluster() { cmd = spy(new EnableGlusterHookCommand(new GlusterHookParameters(null, HOOK_ID))); setupMocks(); assertFalse(cmd.canDoAction()); assertTrue(cmd.getReturnValue().getCanDoActionMessages().contains(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_IS_NOT_VALID.toString())); }
Source:
<code>public List<Destination> getDestinations(FilterType filterType) { Predicate<Destination> filter; switch (filterType) { case PROJECT_CREATION : <START> filter = FOR_CREATION; <END> break; case PROJECT_DELETION : filter = FOR_DELETION; break; case ALL : return destinations; default : filter = null; break; } return FluentIterable.from(destinations).filter(filter).toList(); }</code><technical_language>optional: inline predicate code (and in line 108). code is quire short avoid mappings: PROJECT_CREATION > FOR_CREATION, PROJECT_DELETION > FOR_DELETION</technical_language>

Target:
public List<Destination> getDestinations(FilterType filterType) { Predicate<Destination> filter; switch (filterType) { case PROJECT_CREATION : filter = new Predicate<Destination>() { @Override public boolean apply(Destination dest) { if (dest == null || !dest.isCreateMissingRepos()) { return false; } return true; } }; break; case PROJECT_DELETION : filter = new Predicate<Destination>() { @Override public boolean apply(Destination dest) { if (dest == null || !dest.isReplicateProjectDeletions()) { return false; } return true; } }; break; case ALL : return destinations; default : return destinations; } return FluentIterable.from(destinations).filter(filter).toList(); }
Source:
<code>synchronized void recordScanStop() { if (!isScanning) return; this.scansStopped++; isScanning = false; stopTime = System.currentTimeMillis(); long scanDuration = stopTime - startTime; minScanTime = Math.min(scanDuration, minScanTime); maxScanTime = Math.max(scanDuration, maxScanTime); totalScanTime += scanDuration; LastScan curr = lastScans.get(lastScans.size() - 1); curr.duration = scanDuration; if (lastScans.size() > NUM_SCAN_DURATIONS_KEPT) { lastScans.remove(0); } BluetoothProto.ScanEvent scanEvent = new BluetoothProto.ScanEvent(); scanEvent.setScanEventType(BluetoothProto.ScanEvent.SCAN_EVENT_STOP); scanEvent.setScanTechnologyType(BluetoothProto.ScanEvent.SCAN_TECH_TYPE_LE); scanEvent.setEventTimeMillis(System.currentTimeMillis()); <START> String initiator = appName; String[] nameSplit = initiator.split("\\."); if (nameSplit.length > 3) { initiator = nameSplit[0] + "." + nameSplit[1] + "." + nameSplit[2]; } <END> scanEvent.setInitiator(initiator); gattService.addScanEvent(scanEvent); }</code><technical_language>+1 also, logic apply so: one.two.three.four.five ==> one.two.three one.two.three.four ==> com.one.two.three one.two.three ==> one.two one.two ==> one.two</technical_language>

Target:
synchronized void recordScanStop() { if (!isScanning) return; this.scansStopped++; isScanning = false; stopTime = System.currentTimeMillis(); long scanDuration = stopTime - startTime; minScanTime = Math.min(scanDuration, minScanTime); maxScanTime = Math.max(scanDuration, maxScanTime); totalScanTime += scanDuration; LastScan curr = lastScans.get(lastScans.size() - 1); curr.duration = scanDuration; if (lastScans.size() > NUM_SCAN_DURATIONS_KEPT) { lastScans.remove(0); } BluetoothProto.ScanEvent scanEvent = new BluetoothProto.ScanEvent(); scanEvent.setScanEventType(BluetoothProto.ScanEvent.SCAN_EVENT_STOP); scanEvent.setScanTechnologyType(BluetoothProto.ScanEvent.SCAN_TECH_TYPE_LE); scanEvent.setEventTimeMillis(System.currentTimeMillis()); scanEvent.setInitiator(fixAppName(appName)); gattService.addScanEvent(scanEvent); }
Source:
<code>public void visitFileInput(PyFileInputTree pyFileInputTree) { scopesByRootTree = new HashMap<>(); pyFileInputTree.accept(new FirstPhaseVisitor()); pyFileInputTree.accept(new SecondPhaseVisitor()); scopesByRootTree.values().stream() .filter(scope -> scope.rootTree.is(Kind.FUNCDEF)) .forEach(scope -> { <START> PyFunctionDefTree funcDef = (PyFunctionDefTree) scope.rootTree; <END> for (TreeSymbol symbol : scope.symbols()) { ((PyFunctionDefTreeImpl) funcDef).addLocalVariableSymbol(symbol); } }); }</code><technical_language>This cast useless</technical_language>

Target:
public void visitFileInput(PyFileInputTree pyFileInputTree) { scopesByRootTree = new HashMap<>(); pyFileInputTree.accept(new FirstPhaseVisitor()); pyFileInputTree.accept(new SecondPhaseVisitor()); scopesByRootTree.values().stream() .filter(scope -> scope.rootTree instanceof PyFunctionLikeTree) .forEach(scope -> { PyFunctionLikeTree funcDef = (PyFunctionLikeTree) scope.rootTree; for (TreeSymbol symbol : scope.symbols()) { if (funcDef.is(Kind.LAMBDA)) { ((PyLambdaExpressionTreeImpl) funcDef).addLocalVariableSymbol(symbol); } else { ((PyFunctionDefTreeImpl) funcDef).addLocalVariableSymbol(symbol); } } }); }
Source:
<code>public void run() { File configFile = new File(fileName); if (!configFile.exists()) { LOGGER.debug("No config file located, cannot load from it."); return; } <START> try (InputStream is = new FileInputStream(configFile)) { <END> Properties props = new Properties(); props.load(is); if (props.isEmpty()) { LOGGER.debug("No applications were found in the configuration file."); return; } LOGGER.debug("Found applications to install from config."); for (Entry<Object, Object> curApp : props.entrySet()) { String appName = curApp.getKey().toString(); String appLocation = curApp.getValue().toString(); LOGGER.debug("Starting app at location: {}", appName, appLocation); startApp(appName, appLocation); } LOGGER.debug("Finished installing applications, uninstalling installer module..."); installAndUninstallFeatures(); } catch (FileNotFoundException fnfe) { LOGGER.warn("Could not file the configuration file at " + configFile.getAbsolutePath(), fnfe); } catch (IOException ioe) { LOGGER.warn("Could not load file as property list.", ioe); } }</code><technical_language>try-with-resources input stream throw exception if fails close stream end point, needed it. This is original code IOUtils.closeQuietly(). Although, putting in a finaly clause good enough. This is a good candidate for a suppression</technical_language>

Target:
public void run() { Properties props = PropertiesLoader.getInstance().loadProperties(fileName, null); if (props.isEmpty()) { LOGGER.debug("No applications were found in the configuration file."); return; } LOGGER.trace("Found applications to install from config."); for (Entry<Object, Object> curApp : props.entrySet()) { String appName = (String) curApp.getKey(); String appLocation = (String) curApp.getValue(); LOGGER.debug("Starting app at location: {}", appName, appLocation); startApp(appName, appLocation); } LOGGER.trace("Finished installing applications, uninstalling installer module..."); installAndUninstallFeatures(); }
Source:
<code>public static boolean isFeatureEnabled(@NonNull Context context, @NonNull String namespace, @NonNull String name) { <START> final int propertyVersion = getDeviceConfigPropertyInt(namespace, name, 0 ); return isFeatureVersionEnabled(context, propertyVersion); <END> }</code><technical_language>This be: return isFeatureEnabled(context, namespace, name, false); clearer 2 methods do a potential difference in default</technical_language>

Target:
public static boolean isFeatureEnabled(@NonNull Context context, @NonNull String namespace, @NonNull String name) { final int propertyVersion = getDeviceConfigPropertyInt(namespace, name, 0 ); return isFeatureEnabled(context, namespace, name, false); }
Source:
<code>protected void setup(Binder binder) { <START> configBinder(binder).bindConfig(FileSystemConfig.class); <END> String provider = buildConfigObject(FileSystemConfig.class).getProvider(); Module module = providers.get(provider); if (module == null) { binder.addError("Unknown filesystem provider: %s", provider); } else if (module instanceof ConfigurationAwareModule) { install(module); } else { binder.install(module); } }</code><technical_language>StorageManagerConfig.class</technical_language>

Target:
protected void setup(Binder binder) { configBinder(binder).bindConfig(StorageManagerConfig.class); String fileSystemProvider = buildConfigObject(StorageManagerConfig.class).getFileSystemProvider(); Module module = providers.get(fileSystemProvider); if (module == null) { binder.addError("Unsupported file system: %s", fileSystemProvider); } else if (module instanceof ConfigurationAwareModule) { install(module); } else { binder.install(module); } }
Source:
<code>public Iterable<User> getUsersByRole(String role, String... roles) { final StringBuilder uriBuilder = new StringBuilder("/users.json"); if (roles.length == 0) { <START> uriBuilder.append("?role=").append(role); <END> } else { uriBuilder.append("?role[]=").append(role); } for (final String curRole : roles) { uriBuilder.append("&role[]=").append(curRole); } logger.info(uriBuilder.toString()); return new PagedIterable<User>(cnst(uriBuilder.toString()), handleList(User.class, "users")); }</code><technical_language>do need uri encode role</technical_language>

Target:
public Iterable<User> getUsersByRole(String role, String... roles) { final StringBuilder uriBuilder = new StringBuilder("/users.json"); if (roles.length == 0) { uriBuilder.append("?role=").append(encodeUrl(role)); } else { uriBuilder.append("?role[]=").append(encodeUrl(role)); } for (final String curRole : roles) { uriBuilder.append("&role[]=").append(encodeUrl(curRole)); } return new PagedIterable<User>(cnst(uriBuilder.toString()), handleList(User.class, "users")); }