auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public <T> CompletionStage<T> invokeCommand(Address target, ReplicableCommand command, ResponseCollector<T> collector, RpcOptions rpcOptions) { <START> checkTopologyId(command); <END> CacheRpcCommand cacheRpc = toCacheRpcCommand(command); if (!statisticsEnabled) { return t.invokeCommand(target, cacheRpc, collector, rpcOptions.deliverOrder(), rpcOptions.timeout(), rpcOptions.timeUnit()); } long startTimeNanos = timeService.time(); CompletionStage<T> invocation; try { invocation = t.invokeCommand(target, cacheRpc, collector, rpcOptions.deliverOrder(), rpcOptions.timeout(), rpcOptions.timeUnit()); } catch (Exception e) { return errorReplicating(e); } return invocation.handle((response, throwable) -> updateStatistics(startTimeNanos, response, throwable)); }</code><technical_language>of method same. avoid code duplication? invokeCommand(Address...) invokeCommand(Collection<Address> targets...) invokeCommandOnAll(...) invokeCommandStaggered(...)</technical_language>

Target:
public <T> CompletionStage<T> invokeCommand(Address target, ReplicableCommand command, ResponseCollector<T> collector, RpcOptions rpcOptions) { CacheRpcCommand cacheRpc = toCacheRpcCommand(command); if (!statisticsEnabled) { return t.invokeCommand(target, cacheRpc, collector, rpcOptions.deliverOrder(), rpcOptions.timeout(), rpcOptions.timeUnit()); } long startTimeNanos = timeService.time(); CompletionStage<T> invocation; try { invocation = t.invokeCommand(target, cacheRpc, collector, rpcOptions.deliverOrder(), rpcOptions.timeout(), rpcOptions.timeUnit()); } catch (Exception e) { return errorReplicating(e); } return invocation.handle((response, throwable) -> updateStatistics(startTimeNanos, response, throwable)); }
Source:
<code>private void doUnmarshal() { <START> try { <END> if(this.response != null && this.response.trim().startsWith("{")){ unmarshal(); } } catch (Exception e) { e.printStackTrace(); if(this.exception == null){ this.exception = e; } } }</code><technical_language>if this.exception != null || this. response == null || !this.response.trim().startsWith("{"){ return; } try ... catch ..</technical_language>

Target:
private void doUnmarshal() { if (this.exception != null || this.response == null || !this.response.trim().startsWith("{")) { return; } try { unmarshal(); } catch (Exception e) { e.printStackTrace(); if (this.exception == null) { this.exception = e; } } }
Source:
<code>public static void setup() { int[] availablePorts = AvailablePortHelper.getRandomAvailableTCPPorts(4); server1Port = availablePorts[0]; server2Port = availablePorts[1]; <START> client1Port = availablePorts[2]; <END> client2Port = availablePorts[3]; int localServer1Port = server1Port; int localServer2Port = server2Port; int localClient1Port = client1Port; int localClient2Port = client2Port; locator = cluster.startLocatorVM(indexOfLocator); redisPropsForServer1 = new Properties(); redisPropsForServer1.setProperty("redis-bind-address", "localHost"); redisPropsForServer1.setProperty("redis-port", Integer.toString(server1Port)); redisPropsForServer1.setProperty("log-level", "warn"); redisPropsForServer2 = new Properties(); redisPropsForServer2.setProperty("redis-bind-address", "localHost"); redisPropsForServer2.setProperty("redis-port", Integer.toString(server2Port)); redisPropsForServer2.setProperty("log-level", "warn"); cluster.startServerVM(indexOfServer1, redisPropsForServer1, locator.getPort()); cluster.startServerVM(indexOfServer2, redisPropsForServer2, locator.getPort()); client1 = cluster.getVM(indexOfClient1); client2 = cluster.getVM(indexOfClient2); client1.invoke("start a spring app", () -> { System.setProperty("server.port", Integer.toString(localClient1Port)); System.setProperty("spring.redis.port", Integer.toString(localServer1Port)); SpringApplication.run( RedisSpringTestApplication.class, "" + localServer1Port, "" + localServer2Port); }); client2.invoke("start a spring app", () -> { System.setProperty("server.port", Integer.toString(localClient2Port)); System.setProperty("spring.redis.port", Integer.toString(localServer2Port)); springApplicationContext = SpringApplication.run( RedisSpringTestApplication.class, "" + localServer1Port, "" + localServer2Port); }); restTemplate = new RestTemplate(); jedis = new Jedis("localHost", server1Port, JEDIS_TIMEOUT); }</code><technical_language>values names, do buy clarity? more confusing used</technical_language>

Target:
public static void setup() { int[] availablePorts = AvailablePortHelper.getRandomAvailableTCPPorts(4); ports.put(SERVER1, availablePorts[0]); ports.put(SERVER2, availablePorts[1]); ports.put(APP1, availablePorts[2]); ports.put(APP2, availablePorts[3]); cluster.startLocatorVM(LOCATOR); startRedisServer(SERVER1); startRedisServer(SERVER2); startSpringApp(APP1, SERVER1, SERVER2); startSpringApp(APP2, SERVER2, SERVER1); jedis = new Jedis("localhost", ports.get(SERVER1), JEDIS_TIMEOUT); }
Source:
<code>protected String getActiveTaskStatusString(int verbosity) { StringBuilder rv = new StringBuilder("Scheduler"); if (runCount > 0) { rv.append(", iteration ").append(runCount + 1); } if (recentRun != null) { Duration start = Duration.sinceUtc(recentRun.getStartTimeUtc()); <START> rv.append(", last run ").append(start).append(" ms ago"); <END> } if (truth(getNextScheduled())) { Duration untilNext = Duration.millis(getNextScheduled().getDelay(TimeUnit.MILLISECONDS)); if (untilNext.isPositive()) rv.append(", next in ").append(untilNext); else rv.append(", next imminent"); } return rv.toString(); }</code><technical_language>toString of duration include units, remove "ms"</technical_language>

Target:
protected String getActiveTaskStatusString(int verbosity) { StringBuilder rv = new StringBuilder("Scheduler"); if (runCount > 0) { rv.append(", iteration ").append(runCount + 1); } if (recentRun != null) { Duration start = Duration.sinceUtc(recentRun.getStartTimeUtc()); rv.append(", last run ").append(start).append(" ago"); } if (truth(getNextScheduled())) { Duration untilNext = Duration.millis(getNextScheduled().getDelay(TimeUnit.MILLISECONDS)); if (untilNext.isPositive()) rv.append(", next in ").append(untilNext); else rv.append(", next imminent"); } return rv.toString(); }
Source:
<code>private String[] getSQLTypeNames(Class[] classes, Connection cx) throws SQLException { int[] sqlTypes = new int[classes.length]; String[] sqlTypeNames = new String[sqlTypes.length]; for (int i = 0; i < classes.length; i++) { Class clazz = classes[i]; Integer sqlType = getMapping(clazz); if (sqlType == null) { LOGGER.warning("No sql type mapping for: " + clazz); sqlType = Types.OTHER; } sqlTypes[i] = sqlType; if (Geometry.class.isAssignableFrom(clazz)) { String sqlTypeName = dialect.getGeometryTypeName(sqlType); if (sqlTypeName != null) { sqlTypeNames[i] = sqlTypeName; } } String sqlTypeName = getSqlTypeToSqlTypeNameOverrides().get(sqlType); if (sqlTypeName != null) { sqlTypeNames[i] = sqlTypeName; } } boolean allTypesFound = !ArrayUtils.contains(sqlTypeNames, null); <START> if(allTypesFound) return sqlTypeNames; <END> DatabaseMetaData metaData = cx.getMetaData(); ResultSet types = metaData.getTypeInfo(); try { while (types.next()) { int sqlType = types.getInt("DATA_TYPE"); String sqlTypeName = types.getString("TYPE_NAME"); for (int i = 0; i < sqlTypes.length; i++) { if (sqlTypeNames[i] != null) { continue; } if (sqlType == sqlTypes[i]) { sqlTypeNames[i] = sqlTypeName; } } } } finally { closeSafe(types); } Map<Integer, String> overrides = getSqlTypeToSqlTypeNameOverrides(); for (int i = 0; i < sqlTypes.length; i++) { String override = overrides.get(sqlTypes[i]); if (override != null) sqlTypeNames[i] = override; } return sqlTypeNames; }</code><technical_language>I add a log messages (level warning) if type exist need database</technical_language>

Target:
private String[] getSQLTypeNames(Class[] classes, Connection cx) throws SQLException { int[] sqlTypes = new int[classes.length]; String[] sqlTypeNames = new String[sqlTypes.length]; for (int i = 0; i < classes.length; i++) { Class clazz = classes[i]; Integer sqlType = getMapping(clazz); if (sqlType == null) { LOGGER.warning("No sql type mapping for: " + clazz); sqlType = Types.OTHER; } sqlTypes[i] = sqlType; if (Geometry.class.isAssignableFrom(clazz)) { String sqlTypeName = dialect.getGeometryTypeName(sqlType); if (sqlTypeName != null) { sqlTypeNames[i] = sqlTypeName; } } String sqlTypeDBName = getDBsqlTypesCache().get(sqlType); if (sqlTypeDBName != null) { sqlTypeNames[i] = sqlTypeDBName; } } boolean allTypesFound = !ArrayUtils.contains(sqlTypeNames, null); if (!allTypesFound) { LOGGER.log(Level.WARNING, "Fetching fields from Database"); DatabaseMetaData metaData = cx.getMetaData(); ResultSet types = metaData.getTypeInfo(); try { while (types.next()) { int sqlType = types.getInt("DATA_TYPE"); String sqlTypeName = types.getString("TYPE_NAME"); for (int i = 0; i < sqlTypes.length; i++) { if (sqlTypeNames[i] != null) { continue; } if (sqlType == sqlTypes[i]) { sqlTypeNames[i] = sqlTypeName; getDBsqlTypesCache().putIfAbsent(sqlType, sqlTypeName); } } } } finally { closeSafe(types); } } Map<Integer, String> overrides = getSqlTypeToSqlTypeNameOverrides(); for (int i = 0; i < sqlTypes.length; i++) { String override = overrides.get(sqlTypes[i]); if (override != null) sqlTypeNames[i] = override; } return sqlTypeNames; }
Source:
<code>public void testRollbackSelf() throws Exception { TestTransaction tx1 = new TestTransaction(env); tx1.set("bob", BALANCE, "10"); tx1.set("joe", BALANCE, "20"); tx1.set("jill", BALANCE, "60"); tx1.done(); TestTransaction tx2 = new TestTransaction(env, "jill", BALANCE, 1); TestTransaction tx3 = new TestTransaction(env); <START> tx3.set("bob", BALANCE, "15"); <END> tx3.set("joe", BALANCE, "15"); tx3.done(); tx2.set("bob", BALANCE, "14"); tx2.set("jill", BALANCE, "55"); try { tx2.commit(); Assert.fail("Expected commit exception"); } catch (CommitException ce) { } boolean sawExpected = wasRolledBackPrimary(tx2.getStartTimestamp(), "jill"); Assert.assertTrue(sawExpected); TestTransaction tx4 = new TestTransaction(env); Assert.assertEquals("15", tx4.gets("bob", BALANCE)); Assert.assertEquals("15", tx4.gets("joe", BALANCE)); Assert.assertEquals("60", tx4.gets("jill", BALANCE)); tx4.close(); }</code><technical_language>test util increment method test better</technical_language>

Target:
public void testRollbackSelf() throws Exception { TestTransaction tx1 = new TestTransaction(env); tx1.set("bob", BALANCE, "10"); tx1.set("joe", BALANCE, "20"); tx1.set("jill", BALANCE, "60"); tx1.done(); TestTransaction tx2 = new TestTransaction(env, "jill", BALANCE, 1); TestTransaction tx3 = new TestTransaction(env); TestUtil.increment(tx3, "bob", BALANCE, 5); TestUtil.increment(tx3, "joe", BALANCE, -5); tx3.done(); TestUtil.increment(tx2, "bob", BALANCE, 5); TestUtil.increment(tx2, "jill", BALANCE, -5); try { tx2.commit(); Assert.fail("Expected commit exception"); } catch (CommitException ce) { } boolean sawExpected = wasRolledBackPrimary(tx2.getStartTimestamp(), "jill"); Assert.assertTrue(sawExpected); TestTransaction tx4 = new TestTransaction(env); Assert.assertEquals("15", tx4.gets("bob", BALANCE)); Assert.assertEquals("15", tx4.gets("joe", BALANCE)); Assert.assertEquals("60", tx4.gets("jill", BALANCE)); tx4.close(); }
Source:
<code>public List<IBaseEventInfo> getKernelProvider(IProgressMonitor monitor) throws ExecutionException { List<String> command = createCommand(LTTngControlServiceConstants.COMMAND_LIST, LTTngControlServiceConstants.OPTION_KERNEL); ICommandResult result = executeCommand(command, monitor, false); List<IBaseEventInfo> events = new ArrayList<>(); if (isError(result) && <START> result.getErrorOutput().size() > <END> 0) { if (ignoredPattern(result.getErrorOutput(), LTTngControlServiceConstants.LIST_KERNEL_NO_KERNEL_PROVIDER_PATTERN)) { return events; } throw new ExecutionException(Messages.TraceControl_CommandError + toCommandString(command)); } Document document = getDocumentFromStrings(result.getOutput()); NodeList rawEvents = document.getElementsByTagName(MIStrings.EVENT); getBaseEventInfo(rawEvents, events); return events; }</code><technical_language>isEmpty</technical_language>

Target:
public List<IBaseEventInfo> getKernelProvider(IProgressMonitor monitor) throws ExecutionException { List<String> command = createCommand(LTTngControlServiceConstants.COMMAND_LIST, LTTngControlServiceConstants.OPTION_KERNEL); ICommandResult result = executeCommand(command, monitor, false); List<IBaseEventInfo> events = new ArrayList<>(); if (isError(result)) { if (ignoredPattern(result.getErrorOutput(), LTTngControlServiceConstants.LIST_KERNEL_NO_KERNEL_PROVIDER_PATTERN)) { return events; } throw new ExecutionException(Messages.TraceControl_CommandError + toCommandString(command)); } Document document = getDocumentFromStrings(result.getOutput()); NodeList rawEvents = document.getElementsByTagName(MIStrings.EVENT); getBaseEventInfo(rawEvents, events); return events; }
Source:
<code>protected void loadSchemasIntoSchemasDatabase(CommandContext context) { if (schemasLoader == null) { initializeDefaultSchemasLoader(context); } AppConfig config = context.getAppConfig(); DatabaseClient client = config.newSchemasDatabaseClient(); try { <START> File baseDir = config.getConfigDir().getBaseDir(); <END> logger.info("Loading schemas database data from dir: " + baseDir); schemasLoader.loadSchemas(baseDir, new DefaultSchemasFinder(), client); } finally { client.release(); } }</code><technical_language>This is line I referring in ml-javaclient-util PR - this command is for schemas src/main/ml-config/schemas. If intuitive - if schemas typically considered part of "config" of app "code" of app - good it. potential downside is means src/main/ml-config schemas is loaded Management API, schemas loaded Client API. "src/main/ml-schemas"?? I know</technical_language>

Target:
protected void loadSchemasIntoSchemasDatabase(CommandContext context) { if (schemasLoader == null) { initializeDefaultSchemasLoader(context); } AppConfig config = context.getAppConfig(); DatabaseClient client = config.newSchemasDatabaseClient(); try { String schemasPath = config.getSchemasPath(); logger.info("Loading schemas database data from path: " + schemasPath); schemasLoader.loadSchemas(new File(schemasPath), new DefaultSchemasFinder(), client); } finally { client.release(); } }
Source:
<code>public void setAcceptableValues(Collection<List<T>> newValues) { if (newValues == null) { newValues = Collections.emptyList(); } <START> List<T> val = newValues.isEmpty() ? null : newValues.iterator().next(); <END> super.setValue(val, false); super.setAcceptableValues(newValues); typedItemList.clear(); for (List<T> value : newValues) { addToItems(value); } }</code><technical_language>instead of null pass in empty list ValueListBox a null passed it</technical_language>

Target:
public void setAcceptableValues(Collection<List<T>> newValues) { if (newValues == null) { newValues = Collections.emptyList(); } List<T> val = newValues.isEmpty() ? Collections.<T>emptyList() : newValues.iterator().next(); super.setValue(val, false); super.setAcceptableValues(newValues); typedItemList.clear(); for (List<T> value : newValues) { addToItems(value); } }
Source:
<code><START> public void validate(JobParameters parameters) throws JobParametersInvalidException { <END> ParametersValidatorUtil.checkDirectory(parameters.getString(JobParametersNames.OUTPUT_DIR_ANNOTATION), JobParametersNames.OUTPUT_DIR_ANNOTATION); }</code><technical_language>directory writable</technical_language>

Target:
public void validate(JobParameters parameters) throws JobParametersInvalidException { ParametersValidatorUtil.checkDirectoryExists(parameters.getString(JobParametersNames.OUTPUT_DIR_ANNOTATION), JobParametersNames.OUTPUT_DIR_ANNOTATION); ParametersValidatorUtil.checkFileIsWritable(parameters.getString(JobParametersNames.OUTPUT_DIR_ANNOTATION), JobParametersNames.OUTPUT_DIR_ANNOTATION); }
Source:
<code><START> public static void register() { <END> try { final DeploymentStructureChangeListener listener = new DeploymentStructureChangeListener(); final IWorkspace ws = ResourcesPlugin.getWorkspace(); ws.addResourceChangeListener(listener, IResourceChangeEvent.POST_CHANGE | IResourceChangeEvent.PRE_BUILD); } catch(Exception e) { ClasspathCorePlugin.log("Unable to add jboss-deployment-structure.xml change listener", e); } }</code><technical_language>deregister</technical_language>

Target:
public static void register() { try { listener = new DeploymentStructureChangeListener(); final IWorkspace ws = ResourcesPlugin.getWorkspace(); ws.addResourceChangeListener(listener, IResourceChangeEvent.POST_CHANGE | IResourceChangeEvent.PRE_BUILD); } catch(Exception e) { ClasspathCorePlugin.log("Unable to add jboss-deployment-structure.xml change listener", e); } }
Source:
<code>private static int getUsedFlagBufferCapacity(int cardinalityWithMissingValue) { <START> return (cardinalityWithMissingValue + 7) / 8; <END> }</code><technical_language>suggested replace 7 Byte.SIZE - 1 8 Byte.SIZE</technical_language>

Target:
private static int getUsedFlagBufferCapacity(int cardinalityWithMissingValue) { return (cardinalityWithMissingValue + Byte.SIZE - 1) / Byte.SIZE; }
Source:
<code>private Assignment forgeMapping(SourceRHS sourceRHS, Type sourceType, Type targetType) { <START> <END> ForgedMethodHistory forgedMethodHistory = null; if ( method instanceof ForgedMethod ) { forgedMethodHistory = ( (ForgedMethod) method ).getHistory(); } String name = getName( sourceType, targetType ); forgedMethod = new ForgedMethod( name, sourceType, targetType, method.getMapperConfiguration(), method.getExecutable(), forgedMethodHistory ); Assignment assignment = new MethodReference( forgedMethod, null, ParameterBinding.fromParameters( forgedMethod.getParameters() ) ); assignment.setAssignment( sourceRHS ); return assignment; }</code><technical_language>a small thing: some superfluous empty lines this there</technical_language>

Target:
private Assignment forgeMapping(SourceRHS sourceRHS, Type sourceType, Type targetType) { ForgedMethodHistory forgedMethodHistory = null; if ( method instanceof ForgedMethod ) { forgedMethodHistory = ( (ForgedMethod) method ).getHistory(); } String name = getName( sourceType, targetType ); forgedMethod = new ForgedMethod( name, sourceType, targetType, method.getMapperConfiguration(), method.getExecutable(), method.getContextParameters(), forgedMethodHistory ); Assignment assignment = new MethodReference( forgedMethod, null, ParameterBinding.fromParameters( forgedMethod.getParameters() ) ); assignment.setAssignment( sourceRHS ); return assignment; }
Source:
<code>public AcknowledgementType auditLog(LogEventRequestType request, AssertionType assertion) { securedRequest.setAuditMessage(request.getAuditMessage()); securedRequest.setDirection(request.getDirection()); securedRequest.setRemoteHCID(request.getRemoteHCID()); securedRequest.setEventType(request.getEventType()); securedRequest.setEventID(request.getEventID()); securedRequest.setEventOutcomeIndicator(request.getEventOutcomeIndicator()); securedRequest.setEventTimestamp(request.getEventTimestamp()); securedRequest.setUserId(request.getUserId()); securedRequest.setRelatesTo(request.getRelatesTo()); securedRequest.setRequestMessageId(request.getRequestMessageId()); <START> return getAuditRepositoryOrchImpl().logAudit(securedRequest, assertion); <END> }</code><technical_language>This secureRequest built in a separate method passing assertion</technical_language>

Target:
public AcknowledgementType auditLog(LogEventRequestType request, AssertionType assertion) { return getAuditRepositoryOrchImpl().logAudit(createLogSecureEventRequestType(request), assertion); }
Source:
<code><START> private static boolean setConsumerSchema(final List<PlanFragmentEncoding> fragments, <END> final Map<Integer, Operator> allOperators) { boolean done = true; for (PlanFragmentEncoding fragment : fragments) { for (OperatorEncoding<?> encoding : fragment.operators) { if (encoding instanceof AbstractConsumerEncoding<?>) { Consumer consumer = (Consumer) allOperators.get(encoding.opId); if (consumer.getSchema() != null) { continue; } Operator producingOp = allOperators.get(((AbstractConsumerEncoding<?>) encoding).argOperatorId); if (producingOp instanceof IDBController) { consumer.setSchema(IDBController.EOI_REPORT_SCHEMA); } else if (producingOp instanceof EOSController) { consumer.setSchema(EOSController.EOS_REPORT_SCHEMA); } else { consumer.setSchema(producingOp.getSchema()); } if (consumer.getSchema() == null) { done = false; } } } } return done; }</code><technical_language>this need called in a loop? some kind of recursive propagation I understand</technical_language>

Target:
private static boolean setConsumerSchema(final List<PlanFragmentEncoding> fragments, final Map<Integer, Operator> allOperators) { boolean changed = false; for (PlanFragmentEncoding fragment : fragments) { for (OperatorEncoding<?> encoding : fragment.operators) { if (encoding instanceof AbstractConsumerEncoding<?>) { Consumer consumer = (Consumer) allOperators.get(encoding.opId); if (consumer.getSchema() != null) { continue; } Operator producingOp = allOperators.get(((AbstractConsumerEncoding<?>) encoding).argOperatorId); if (producingOp instanceof IDBController) { consumer.setSchema(IDBController.EOI_REPORT_SCHEMA); } else if (producingOp instanceof EOSController) { consumer.setSchema(EOSController.EOS_REPORT_SCHEMA); } else { consumer.setSchema(producingOp.getSchema()); } if (consumer.getSchema() != null) { changed = true; } } } } return changed; }
Source:
<code>public void abort() throws IOException { close(); <START> Files.deleteIfExists(tmpFile); <END> }</code><technical_language>Move delete finally block</technical_language>

Target:
public void abort() throws IOException { closeAndDeleteTempFile(); }
Source:
<code>private void fireChildChangedEvents(final String path, Set<IZkChildListener> childListeners, boolean pathExists) { try { for (final IZkChildListener listener : childListeners) { _eventThread.send(new ZkEvent("Children of " + path + " changed sent to " + listener) { @Override public void run() throws Exception { List<String> children = null; if (pathExists) { try { children = getChildren(path); <START> if (children != null) { <END> for (String child : children) { watchForData(path + "/" + child); } } } catch (ZkNoNodeException e) { LOG.warn("Get children under path: failed.", path, e); } } listener.handleChildChange(path, children); } }); } } catch (Exception e) { LOG.error("Failed to fire child changed event. Unable to getChildren.", e); } }</code><technical_language>This remove previous improvement for multiple listeners. remove it</technical_language>

Target:
private void fireChildChangedEvents(final String path, Set<IZkChildListener> childListeners, boolean pathExists) { try { final ZkPathStatRecord pathStatRecord = new ZkPathStatRecord(path); for (final IZkChildListener listener : childListeners) { _eventThread.send(new ZkEvent("Children of " + path + " changed sent to " + listener) { @Override public void run() throws Exception { if (!pathStatRecord.pathChecked()) { pathStatRecord.recordPathStat(getStat(path, hasListeners(path) && pathExists), OptionalLong.empty()); } List<String> children = null; if (pathStatRecord.pathExists()) { try { children = getChildren(path); } catch (ZkNoNodeException e) { LOG.warn("Get children under path: failed.", path, e); } } listener.handleChildChange(path, children); } }); } } catch (Exception e) { LOG.error("Failed to fire child changed event. Unable to getChildren.", e); } }
Source:
<code>public static MaybeAliasedStatement analyze(AnalyzedRelation relation) { if (relation instanceof AliasedAnalyzedRelation) { return new MaybeAliasedStatement((AliasedAnalyzedRelation) relation); } <START> return new NoopAliasedStatement(relation); <END> }</code><technical_language>add some docs explains this a bit? is is more of a workaround</technical_language>

Target:
public static MaybeAliasedStatement analyze(AnalyzedRelation relation) { if (relation instanceof AliasedAnalyzedRelation) { AliasedAnalyzedRelation aliasedAnalyzedRelation = (AliasedAnalyzedRelation) relation; return new MaybeAliasedStatement( aliasedAnalyzedRelation.relation(), FieldReplacer.bind(f -> f.relation().equals(aliasedAnalyzedRelation) ? f.pointer() : f) ); } return new MaybeAliasedStatement(relation, s -> s); }
Source:
<code>public SizeCachedByteBufferKeyValue(ByteBuffer buf, int offset, int length, long seqId, int keyLen) { <START> super(buf, offset, length); <END> rowLen = super.getRowLength(); this.keyLen = keyLen; setSequenceId(seqId); }</code><technical_language>call next this() constructor</technical_language>

Target:
public SizeCachedByteBufferKeyValue(ByteBuffer buf, int offset, int length, long seqId, int keyLen) { super(buf, offset, length); this.rowLen = super.getRowLength(); this.keyLen = keyLen; setSequenceId(seqId); }
Source:
<code>public boolean comapareBaseEncodedImagesBasedOnBytes(String base1, String base2) { Base64 coder = new Base64(); byte[] baseInBytes1 = coder.decode(base1); byte[] baseInBytes2 = coder.decode(base2); boolean isTheSame = false; if (Arrays.equals(baseInBytes1, baseInBytes2)) { <START> isTheSame = true; <END> } return isTheSame; }</code><technical_language>return true;</technical_language>

Target:
public boolean comapareBaseEncodedImagesBasedOnBytes(String base1, String base2) { Base64 coder = new Base64(); byte[] baseInBytes1 = coder.decode(base1); byte[] baseInBytes2 = coder.decode(base2); if (Arrays.equals(baseInBytes1, baseInBytes2)) { return true; } return false; }
Source:
<code>private boolean checkIfModelIsDuplicate(FenceAgentModel model, FenceAgentModel concurrentExistingModel) { if (model.getManagementIp().getEntity().equals(concurrentExistingModel.getManagementIp().getEntity())) { model.getManagementIp().setIsValid(true); <START> model.getManagementIp().getInvalidityReasons().clear(); <END> model.getManagementIp().getInvalidityReasons().add(constants.duplicateFenceAgentManagementIp()); model.getManagementIp().setIsValid(false); } return model.getManagementIp().getIsValid(); }</code><technical_language>This getInvalidityReasons().clear() is done Model.setIsValid == true. Do need it? Also, put model.getManagementIp().getInvalidityReasons() bottom for readability model.getManagementIp().setIsValid(true) model.getManagementIp().setIsValid(false) model.getManagementIp().getInvalidityReasons().add(...)</technical_language>

Target:
private boolean checkIfModelIsDuplicate(FenceAgentModel model, FenceAgentModel concurrentExistingModel) { if (model.getManagementIp().getEntity().equals(concurrentExistingModel.getManagementIp().getEntity())) { model.getManagementIp().setIsValid(true); model.getManagementIp().getInvalidityReasons().add(constants.duplicateFenceAgentManagementIp()); model.getManagementIp().setIsValid(false); } return model.getManagementIp().getIsValid(); }
Source:
<code>private RepositorySystemSession newSession(RepositorySystem system) { ArtifactRepositoryPreference artifactRepositoryPreference = new ArtifactRepositoryPreference(); artifactRepositoryPreference.defaultValue(artifactRepositoryPreference); DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); String global = artifactRepositoryPreference.getGlobalM2RepoDir(); if (global == null) { <START> global = "repositories" + File.separator + "kie" + File.separator + "global"; <END> log.info("using fallback {}", global); } LocalRepository localRepo = new LocalRepository(global); session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo)); return session; }</code><technical_language>happy default global spread around. please centralize in place</technical_language>

Target:
private RepositorySystemSession newSession(RepositorySystem system) { DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); LocalRepository localRepo = new LocalRepository(ArtifactRepositoryPreference.getGlobalM2RepoDirWithFallback()); session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo)); return session; }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.logs); setupToolbar(); <START> RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this); <END> mLogsRecycler = findViewById(R.id.log_recycler); mLogsRecycler.setHasFixedSize(true); mLogsRecycler.setLayoutManager(mLayoutManager); setTitle(getText(R.string.actionbar_logger)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); Button deleteHistoryButton = findViewById(R.id.deleteLogHistoryButton); Button sendHistoryButton = findViewById(R.id.sendLogHistoryButton); deleteHistoryButton.setOnClickListener(v -> { Log_OC.deleteHistoryLogging(); finish(); }); sendHistoryButton.setOnClickListener(v -> sendMail()); if (savedInstanceState == null) { if (mLogPath != null) { mLogDIR = new File(mLogPath); } if (mLogDIR != null && mLogDIR.isDirectory()) { showLoadingDialog(); LoadingLogTask task = new LoadingLogTask(); task.execute(); } } }</code><technical_language>Rename mLayoutManager layoutManager</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.logs); setupToolbar(); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); mLogsRecycler = findViewById(R.id.log_recycler); mLogsRecycler.setHasFixedSize(true); mLogsRecycler.setLayoutManager(layoutManager); setTitle(getText(R.string.actionbar_logger)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); Button deleteHistoryButton = findViewById(R.id.deleteLogHistoryButton); Button sendHistoryButton = findViewById(R.id.sendLogHistoryButton); deleteHistoryButton.setOnClickListener(v -> { Log_OC.deleteHistoryLogging(); finish(); }); sendHistoryButton.setOnClickListener(v -> sendMail()); if (savedInstanceState == null) { if (mLogPath != null) { mLogDIR = new File(mLogPath); } if (mLogDIR != null && mLogDIR.isDirectory()) { showLoadingDialog(); LoadingLogTask task = new LoadingLogTask(); task.execute(); } } }
Source:
<code>private void save(File dir) { File f = new File(dir, MAP_FILE); try { try (AtomicFileWriter w = new AtomicFileWriter(f)) { <START> try { <END> for (Map.Entry<String, Integer> entry : idToNumber.entrySet()) { w.write(entry.getKey() + ' ' + entry.getValue() + '\n'); } w.commit(); } finally { w.abort(); } } } catch (IOException x) { LOGGER.log(WARNING, "could not save changes to " + f, x); } }</code><technical_language>I doubt new try is needed here, add above</technical_language>

Target:
private void save(File dir) { File f = new File(dir, MAP_FILE); try (AtomicFileWriter w = new AtomicFileWriter(f)) { try { for (Map.Entry<String,Integer> entry : idToNumber.entrySet()) { w.write(entry.getKey() + ' ' + entry.getValue() + '\n'); } w.commit(); } finally { w.abort(); } } catch (IOException x) { LOGGER.log(WARNING, "could not save changes to " + f, x); } }
Source:
<code>private JsonObject getEffectiveFilter(JsonArray typeFilters) { JsonArray filters = new JsonArray(); JsonObject tenantFilter = getTenantIdFilter(); if ( tenantFilter != null ) { filters.add( tenantFilter ); } filters.add( ToElasticsearch.condition( "should", typeFilters ) ); QueryFilterset facetFilter = getFacetManager().getFacetFilterset(); if ( ! facetFilter.isEmpty() ) { <START> filters.add( ToElasticsearch.fromQueryFilterset( facetFilter ) ); <END> } return ToElasticsearch.condition( "must", filters ); }</code><technical_language>I simply do like: for ( Query query : getFacetManager().getFacetFilterset().filterQueries() ) { filters.add( ToElasticSearch.fromLuceneQuery( query ) ); }</technical_language>

Target:
private JsonObject getEffectiveFilter(JsonArray typeFilters) { JsonArray filters = new JsonArray(); JsonObject tenantFilter = getTenantIdFilter(); if ( tenantFilter != null ) { filters.add( tenantFilter ); } filters.add( ToElasticsearch.condition( "should", typeFilters ) ); for ( Query query : getFacetManager().getFacetFilters().getFilterQueries() ) { filters.add( ToElasticsearch.fromLuceneQuery( query ) ); } return ToElasticsearch.condition( "must", filters ); }
Source:
<code>public void onMatch(RelOptRuleCall call) { final Filter filter = call.rel(0); final Correlate corr = call.rel(1); final List<RexNode> aboveFilters = RelOptUtil.conjunctions(filter.getCondition()); final List<RexNode> leftFilters = new ArrayList<>(); final List<RexNode> rightFilters = new ArrayList<>(); RelOptUtil.classifyFilters( corr, aboveFilters, JoinRelType.INNER, false, corr.getJoinType().returnsJustFirstInput() || !corr.getJoinType().toJoinType().generatesNullsOnLeft(), !corr.getJoinType().returnsJustFirstInput() <START> && !corr.getJoinType().toJoinType().generatesNullsOnRight(), <END> aboveFilters, leftFilters, rightFilters); if (leftFilters.isEmpty() && rightFilters.isEmpty()) { return; } final RexBuilder rexBuilder = corr.getCluster().getRexBuilder(); final RelBuilder relBuilder = call.builder(); final RelNode leftRel = relBuilder.push(corr.getLeft()).filter(leftFilters).build(); final RelNode rightRel = relBuilder.push(corr.getRight()).filter(rightFilters).build(); RelNode newCorrRel = corr.copy(corr.getTraitSet(), ImmutableList.of(leftRel, rightRel)); call.getPlanner().onCopy(corr, newCorrRel); if (!leftFilters.isEmpty()) { call.getPlanner().onCopy(filter, leftRel); } if (!rightFilters.isEmpty()) { call.getPlanner().onCopy(filter, rightRel); } relBuilder.push(newCorrRel); relBuilder.filter( RexUtil.fixUp(rexBuilder, aboveFilters, RelOptUtil.getFieldTypeList(relBuilder.peek().getRowType()))); call.transformTo(relBuilder.build()); }</code><technical_language>I do, a while understand. :)</technical_language>

Target:
public void onMatch(RelOptRuleCall call) { final Filter filter = call.rel(0); final Correlate corr = call.rel(1); final List<RexNode> aboveFilters = RelOptUtil.conjunctions(filter.getCondition()); final List<RexNode> leftFilters = new ArrayList<>(); final List<RexNode> rightFilters = new ArrayList<>(); RelOptUtil.classifyFilters( corr, aboveFilters, JoinRelType.INNER, false, true, corr.getJoinType() == SemiJoinType.INNER, aboveFilters, leftFilters, rightFilters); if (leftFilters.isEmpty() && rightFilters.isEmpty()) { return; } final RexBuilder rexBuilder = corr.getCluster().getRexBuilder(); final RelBuilder relBuilder = call.builder(); final RelNode leftRel = relBuilder.push(corr.getLeft()).filter(leftFilters).build(); final RelNode rightRel = relBuilder.push(corr.getRight()).filter(rightFilters).build(); RelNode newCorrRel = corr.copy(corr.getTraitSet(), ImmutableList.of(leftRel, rightRel)); call.getPlanner().onCopy(corr, newCorrRel); if (!leftFilters.isEmpty()) { call.getPlanner().onCopy(filter, leftRel); } if (!rightFilters.isEmpty()) { call.getPlanner().onCopy(filter, rightRel); } relBuilder.push(newCorrRel); relBuilder.filter( RexUtil.fixUp(rexBuilder, aboveFilters, RelOptUtil.getFieldTypeList(relBuilder.peek().getRowType()))); call.transformTo(relBuilder.build()); }
Source:
<code>public void testBoldWithWhitespace() { String html; Pattern expectedPattern = Pattern.compile("<body><p>normal\\s*<b>\\s*bold text\\s*</b>\\s*normal</p></body>"); html = parser.parseToHtml("normal ''' bold text''' normal"); TestUtil.println(html); <START> assertTrue(expectedPattern.matcher(html).find()); <END> html = parser.parseToHtml("normal '''bold text ''' normal"); TestUtil.println(html); assertTrue(expectedPattern.matcher(html).find()); html = parser.parseToHtml("normal ''' bold text ''' normal"); TestUtil.println(html); assertTrue(expectedPattern.matcher(html).find()); }</code><technical_language>assert html.contains("<p>normal <b> bold text</b> normal</p>")</technical_language>

Target:
public void testBoldWithWhitespace() { String html; html = parser.parseToHtml("normal ''' bold text''' normal"); TestUtil.println(html); assertTrue(html.contains("<body><p>normal <b> bold text</b> normal</p></body>")); html = parser.parseToHtml("normal '''bold text ''' normal"); TestUtil.println(html); assertTrue(html.contains("<body><p>normal <b>bold text </b> normal</p></body>")); html = parser.parseToHtml("normal ''' bold text ''' normal"); TestUtil.println(html); assertTrue(html.contains("<body><p>normal <b> bold text </b> normal</p></body>")); }
Source:
<code>public SecurityGroup getSecurityGroupById(String id) { checkNotNull(id, "id"); ZoneAndId zoneAndId = ZoneAndId.fromSlashEncoded(id); String zone = zoneAndId.getZone(); String groupId = zoneAndId.getId(); Optional<? extends SecurityGroupApi> sgApi = client.getSecurityGroupExtensionForZone(zone); if (!sgApi.isPresent()) { return null; } SecurityGroupInZone rawGroup = new SecurityGroupInZone(sgApi.get().get(groupId), zone); <START> return groupConverter.apply(rawGroup); <END> }</code><technical_language>Is "groupInZone2group" a bit more descriptive "groupConverter"</technical_language>

Target:
public SecurityGroup getSecurityGroupById(String id) { ZoneAndId zoneAndId = ZoneAndId.fromSlashEncoded(checkNotNull(id, "id")); String zone = zoneAndId.getZone(); String groupId = zoneAndId.getId(); Optional<? extends SecurityGroupApi> sgApi = api.getSecurityGroupExtensionForZone(zone); if (!sgApi.isPresent()) { return null; } SecurityGroupInZone rawGroup = new SecurityGroupInZone(sgApi.get().get(groupId), zone); return groupConverter.apply(rawGroup); }
Source:
<code>private Runnable createRunnable(final Pair<HttpRequest, List<Message>> request) { return new Runnable() { @Override public void run() { Stopwatch stopwatch = timer.start(); try { HttpResponse response = client.executeWithLoadBalancer(request.first()); byte[] bytes = IOUtils.toByteArray(response.getInputStream()); <START> Map<String, Object> result = jsonMapper.readValue(bytes, new TypeReference<Map<String, Object>>(){}); <END> List items = (List) result.get("items"); for (int i = 0; i < items.size(); ++i) { String routingKey = request.second().get(i).getRoutingKey(); Map<String, Object> resPerMessage = (Map)((Map)(items.get(i))).get("create"); if (isFailed(resPerMessage) && !getErrorMessage(resPerMessage).contains("DocumentAlreadyExistsException")) { log.error("Failed with: " + resPerMessage.get("error")); Servo.getCounter( MonitorConfig.builder(REJECTED_ROW) .withTag(SINK_ID, getSinkId()) .withTag(TagKey.ROUTING_KEY, routingKey) .build()).increment(); recover(request.second().get(i)); } else { Servo.getCounter( MonitorConfig.builder(INDEXED_ROW) .withTag(SINK_ID, getSinkId()) .withTag(TagKey.ROUTING_KEY, routingKey) .build()).increment(); } } throughput.increment(items.size()); } catch (Exception e) { log.error("Exception on bulk execute: " + e.getMessage(), e); for (Message m : request.second()) { Servo.getCounter( MonitorConfig.builder(REJECTED_ROW) .withTag(SINK_ID, getSinkId()) .withTag(TagKey.ROUTING_KEY, m.getRoutingKey()) .build()).increment(); } } finally { stopwatch.stop(); } } }; }</code><technical_language>need get bytes. ObjectMapper read InputStream</technical_language>

Target:
private Runnable createRunnable(final Pair<HttpRequest, List<Message>> request) { return new Runnable() { @Override public void run() { Stopwatch stopwatch = timer.start(); HttpResponse response = null; try { response = client.executeWithLoadBalancer(request.first()); Map<String, Object> result = jsonMapper.readValue( response.getInputStream(), new TypeReference<Map<String, Object>>(){}); List items = (List) result.get("items"); for (int i = 0; i < items.size(); ++i) { String routingKey = request.second().get(i).getRoutingKey(); Map<String, Object> resPerMessage = (Map)((Map)(items.get(i))).get("create"); if (isFailed(resPerMessage) && !getErrorMessage(resPerMessage).contains("DocumentAlreadyExistsException")) { log.error("Failed with: " + resPerMessage.get("error")); Servo.getCounter( MonitorConfig.builder(REJECTED_ROW) .withTag(SINK_ID, getSinkId()) .withTag(TagKey.ROUTING_KEY, routingKey) .build()).increment(); recover(request.second().get(i)); } else { Servo.getCounter( MonitorConfig.builder(INDEXED_ROW) .withTag(SINK_ID, getSinkId()) .withTag(TagKey.ROUTING_KEY, routingKey) .build()).increment(); } } throughput.increment(items.size()); } catch (Exception e) { log.error("Exception on bulk execute: " + e.getMessage(), e); Servo.getCounter("bulkException").increment(); for (Message m : request.second()) { writeTo(new DefaultMessageContainer(m, jsonMapper)); } } finally { if (response != null) { response.close(); } stopwatch.stop(); } } }; }
Source:
<code>private void createOpenShiftService(String workspaceID, Set<String> exposedPorts, Map<String, String> additionalLabels) { <START> Map<String, String> selector = new HashMap<>(); <END> selector.put(OPENSHIFT_DEPLOYMENT_LABEL, CHE_OPENSHIFT_RESOURCES_PREFIX + workspaceID); List<ServicePort> ports = kubernetesService.getServicePortsFrom(exposedPorts); Service service = openShiftClient .services() .inNamespace(this.cheOpenShiftProjectName) .createNew() .withNewMetadata() .withName(CHE_OPENSHIFT_RESOURCES_PREFIX + workspaceID) .withAnnotations(kubernetesLabelConverter.labelsToNames(additionalLabels)) .endMetadata() .withNewSpec() .withType(OPENSHIFT_SERVICE_TYPE_NODE_PORT) .withSelector(selector) .withPorts(ports) .endSpec() .done(); LOG.info(String.format("OpenShift service %s created", service.getMetadata().getName())); }</code><technical_language>if is entry in map a singletonmap</technical_language>

Target:
private void createOpenShiftService(String workspaceID, Set<String> exposedPorts, Map<String, String> additionalLabels) { Map<String, String> selector = Collections.singletonMap(OPENSHIFT_DEPLOYMENT_LABEL, CHE_OPENSHIFT_RESOURCES_PREFIX + workspaceID); List<ServicePort> ports = kubernetesService.getServicePortsFrom(exposedPorts); Service service = openShiftClient .services() .inNamespace(this.openShiftCheProjectName) .createNew() .withNewMetadata() .withName(CHE_OPENSHIFT_RESOURCES_PREFIX + workspaceID) .withAnnotations(kubernetesLabelConverter.labelsToNames(additionalLabels)) .endMetadata() .withNewSpec() .withType(OPENSHIFT_SERVICE_TYPE_NODE_PORT) .withSelector(selector) .withPorts(ports) .endSpec() .done(); LOG.info("OpenShift service created", service.getMetadata().getName()); }
Source:
<code>public void saveOrder_shouldFailIfDrugNonCodedInPreviousDrugOrderDoesNotMatchThatOfTheRevisedDrugOrder() throws Exception { executeDataSet("org/openmrs/api/include/OrderServiceTest-nonCodedDrugs.xml"); DrugOrder previousOrder = (DrugOrder)orderService.getOrder(584); DrugOrder order = previousOrder.cloneForRevision(); <START> String drugNonCodedParacetemol = "non coded paracetemol"; <END> order.setDateActivated(new Date()); order.setOrderer(providerService.getProvider(1)); order.setEncounter(encounterService.getEncounter(6)); assertFalse(previousOrder.getDrugNonCoded().equals(drugNonCodedParacetemol)); order.setDrugNonCoded(drugNonCodedParacetemol); order.setPreviousOrder(previousOrder); expectedException.expect(APIException.class); expectedException.expectMessage("The orderable of the previous order and the new one order don't match"); orderService.saveOrder(order, null); }</code><technical_language>nice asssertion this equal previous' coded</technical_language>

Target:
public void saveOrder_shouldFailIfDrugNonCodedInPreviousDrugOrderDoesNotMatchThatOfTheRevisedDrugOrder() throws Exception { executeDataSet("org/openmrs/api/include/OrderServiceTest-nonCodedDrugs.xml"); DrugOrder previousOrder = (DrugOrder) orderService.getOrder(584); DrugOrder order = previousOrder.cloneForRevision(); String drugNonCodedParacetemol = "non coded aspirin"; order.setDateActivated(new Date()); order.setOrderer(providerService.getProvider(1)); order.setEncounter(encounterService.getEncounter(6)); assertFalse(previousOrder.getDrugNonCoded().equals(drugNonCodedParacetemol)); order.setDrugNonCoded(drugNonCodedParacetemol); order.setPreviousOrder(previousOrder); expectedException.expect(APIException.class); expectedException.expectMessage("The orderable of the previous order and the new one order don't match"); orderService.saveOrder(order, null); }
Source:
<code>private void relinkThumbs() { <START> if (RelinkImagesTask.getInstance() != null && RelinkImagesTask.getInstance().getStatus() == Status.RUNNING) { <END> UIHelper.createYesNoDialog( this , getResources().getString(R.string.relink_stop_question) , getResources().getString(R.string.relink_stop_question2) , new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) { RelinkImagesTask.getInstance().cancel(true); } } }).show(); return; } final DisplaySettingsActivity dsa = this; UIHelper.createYesNoDialog( this , getResources().getString(R.string.relink_question) , getResources().getString(R.string.relink_question2) , new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) { String rootPath = UIHelper.getImageRoot(dsa); RelinkImagesTask task = RelinkImagesTask.getInstance(rootPath, dsa, Constants.PREF_RELINK_THUMB_IMAGES); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else task.execute(); } } }).show(); }</code><technical_language>move YesNo dialog <LINK_0> function is clean UI method</technical_language>

Target:
private void relinkThumbs() { String rootPath = UIHelper.getImageRoot(this); RelinkImagesTask task = RelinkImagesTask.getInstance(rootPath, this, Constants.PREF_RELINK_THUMB_IMAGES); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else task.execute(); }
Source:
<code>public String getTitle() { while (session.getFrame().getSteps().size() > 0 && (!SessionFrame.STATE_DATUM_VAL.equals(session.getNeededData()) || !(session.getNeededDatum() != null && <START> session.getNeededDatum().getLongDetail() != null))) { <END> session.stepBack(); } if(session.getFrame().getSteps().size() == 0) { return null;} EvaluationContext ec = getEvaluationContext(); String value = session.getPoppedStep().getValue(); SessionDatum datum = session.getNeededDatum(); TreeReference nodesetRef = datum.getNodeset().clone(); Vector<XPathExpression> predicates = nodesetRef.getPredicate(nodesetRef.size() -1); predicates.add(new XPathEqExpr(true, XPathReference.getPathExpr(datum.getValue()), new XPathStringLiteral(value))); Vector<TreeReference> elements = ec.expandReference(nodesetRef); if(elements.size() != 1 ) { return null;} EvaluationContext element = new EvaluationContext(ec, elements.firstElement()); Text t = session.getDetail(datum.getLongDetail()).getTitle().getText(); boolean isPrettyPrint = true; try { String outcome = t.evaluate(); if(outcome != null) { isPrettyPrint = false; } } catch(Exception e) { } if(isPrettyPrint) { return t.evaluate(element); } else { SqlStorage<ACase> storage = CommCareApplication._().getUserStorage(ACase.STORAGE_KEY, ACase.class); try { ACase ourCase = storage.getRecordForValue(ACase.INDEX_CASE_ID, value); if(ourCase != null) { return ourCase.getName(); } else { return null; } } catch(Exception e) { return null; } } }</code><technical_language>Is a specific reason? If session.getNeededData() is returning a datum getNeededDatum() is null feels a pretty serious issue. I suggest failing getNeededData structurally nature of error more clear bubbling here</technical_language>

Target:
public String getTitle() { while (session.getFrame().getSteps().size() > 0 && (!SessionFrame.STATE_DATUM_VAL.equals(session.getNeededData()) || session.getNeededDatum().getLongDetail() == null)) { session.stepBack(); } if(session.getFrame().getSteps().size() == 0) { return null;} EvaluationContext ec = getEvaluationContext(); String value = session.getPoppedStep().getValue(); SessionDatum datum = session.getNeededDatum(); TreeReference nodesetRef = datum.getNodeset().clone(); Vector<XPathExpression> predicates = nodesetRef.getPredicate(nodesetRef.size() -1); predicates.add(new XPathEqExpr(true, XPathReference.getPathExpr(datum.getValue()), new XPathStringLiteral(value))); Vector<TreeReference> elements = ec.expandReference(nodesetRef); if(elements.size() != 1 ) { return null;} EvaluationContext element = new EvaluationContext(ec, elements.firstElement()); Text t = session.getDetail(datum.getLongDetail()).getTitle().getText(); boolean isPrettyPrint = true; try { String outcome = t.evaluate(); if(outcome != null) { isPrettyPrint = false; } } catch(Exception e) { } if(isPrettyPrint) { return t.evaluate(element); } else { SqlStorage<ACase> storage = CommCareApplication._().getUserStorage(ACase.STORAGE_KEY, ACase.class); try { ACase ourCase = storage.getRecordForValue(ACase.INDEX_CASE_ID, value); if(ourCase != null) { return ourCase.getName(); } else { return null; } } catch(Exception e) { return null; } } }