auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private int getPatternArgumentIndex(FunctionCallTree tree) { int index = 0; if (tree.callee().toString().equalsIgnoreCase(MB_EREG_SEARCH_INIT)) { index = 1; } <START> return index; <END> }</code><technical_language>personal preference (so suggestion account) I for : if(cond) { return 1; } return 0;</technical_language>

Target:
private int getPatternArgumentIndex(FunctionCallTree tree) { if (tree.callee().toString().equalsIgnoreCase(MB_EREG_SEARCH_INIT)) { return 1; } return 0; }
Source:
<code>private void startAsync( WorkspaceImpl workspace, @Nullable String envName, Map<String, String> options) throws ConflictException, NotFoundException, ServerException { try { runtimes.validate(workspace, envName); } catch (ValidationException e) { throw new ConflictException(e.getMessage(), e); } <START> if (isNullOrEmpty( <END> workspace.getAttributes().get(WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE))) { RuntimeTarget target = new RuntimeTarget(workspace.getId(), EnvironmentContext.getCurrent().getSubject(), null); try { String namespace = runtimes.getInfrastructureNamespace(target); workspace.getAttributes().put(WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE, namespace); } catch (InfrastructureException e) { throw new ServerException(e); } } workspace.getAttributes().put(UPDATED_ATTRIBUTE_NAME, Long.toString(currentTimeMillis())); workspaceDao.update(workspace); runtimes .startAsync(workspace, envName, firstNonNull(options, Collections.emptyMap())) .thenAccept(aVoid -> handleStartupSuccess(workspace.getId())) .exceptionally( ex -> { if (workspace.isTemporary()) { removeWorkspaceQuietly(workspace.getId()); } else { handleStartupError(workspace.getId(), ex.getCause()); } return null; }); }</code><technical_language>fix workspace object soon in chain, avoid ifs this in code later</technical_language>

Target:
private void startAsync( WorkspaceImpl workspace, @Nullable String envName, Map<String, String> options) throws ConflictException, NotFoundException, ServerException { try { runtimes.validate(workspace, envName); } catch (ValidationException e) { throw new ConflictException(e.getMessage(), e); } if (isNullOrEmpty( workspace.getAttributes().get(WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE))) { try { String namespace = runtimes.evalLegacyInfrastructureNamespace(buildResolutionContext(workspace)); workspace.getAttributes().put(WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE, namespace); } catch (InfrastructureException e) { throw new ServerException(e); } } workspace.getAttributes().put(UPDATED_ATTRIBUTE_NAME, Long.toString(currentTimeMillis())); workspaceDao.update(workspace); runtimes .startAsync(workspace, envName, firstNonNull(options, Collections.emptyMap())) .thenAccept(aVoid -> handleStartupSuccess(workspace.getId())) .exceptionally( ex -> { if (workspace.isTemporary()) { removeWorkspaceQuietly(workspace.getId()); } else { handleStartupError(workspace.getId(), ex.getCause()); } return null; }); }
Source:
<code>public void removeEnvironmentVariable(String containerName, String name) { String defaultedContainerName = StringUtils.defaultIfBlank(containerName, ""); ModelNode specContainers = get(SPEC_TEMPLATE_CONTAINERS); if(specContainers.isDefined()) { List<ModelNode> containers = specContainers.asList(); if(!containers.isEmpty()) { Optional<ModelNode> opt = containers.stream().filter(n->defaultedContainerName.equals(asString(n, NAME))).findFirst(); ModelNode node = opt.isPresent() ? opt.get() : containers.get(0); ModelNode envNode = get(node, ENV); List<ModelNode> varList = new ArrayList<>(); if (ModelType.LIST.equals(envNode.getType())){ varList.addAll(envNode.asList()); } <START> Optional<ModelNode> targetVar = varList.stream().filter(n->name.equals(asString(n, NAME))).findFirst(); <END> ModelNode var; if (targetVar.isPresent()) { var = targetVar.get(); int i = varList.indexOf(var); varList.remove(i); envNode.set(varList); } else { } } } }</code><technical_language>do a checko for null name</technical_language>

Target:
public void removeEnvironmentVariable(String containerName, String name) { if(name == null) { throw new IllegalArgumentException("Name cannot be null."); } String defaultedContainerName = StringUtils.defaultIfBlank(containerName, ""); ModelNode specContainers = get(SPEC_TEMPLATE_CONTAINERS); if(specContainers.isDefined()) { List<ModelNode> containers = specContainers.asList(); if(!containers.isEmpty()) { Optional<ModelNode> opt = containers.stream().filter(n->defaultedContainerName.equals(asString(n, NAME))).findFirst(); ModelNode node = opt.isPresent() ? opt.get() : containers.get(0); ModelNode envNode = get(node, ENV); List<ModelNode> varList = new ArrayList<>(); if (ModelType.LIST.equals(envNode.getType())){ varList.addAll(envNode.asList()); } Optional<ModelNode> targetVar = varList.stream().filter(n->name.equals(asString(n, NAME))).findFirst(); ModelNode var; if (targetVar.isPresent()) { var = targetVar.get(); int i = varList.indexOf(var); varList.remove(i); envNode.set(varList); } else { } } } }
Source:
<code>public void serialize(ProcessVariablesMap<String, Object> processVariablesMap, JsonGenerator gen, SerializerProvider serializers) throws IOException { HashMap<String, ProcessVariableValue> map = new HashMap<>(); for (Map.Entry<String, Object> entry: processVariablesMap.entrySet()) { String name = entry.getKey(); Object value = entry.getValue(); if(value != null) { Class<?> entryTypeClass = entry.getValue() .getClass(); <START> Object entryObjectValue = entry.getValue(); <END> String entryType; if (scalarTypes.contains(entryTypeClass)) { entryType = entryTypeClass.getName(); } else if (Map.class.isInstance(value)) { entryType = Map.class.getName(); } else if (JsonNode.class.isInstance(value)) { entryType = JsonNode.class.getName(); } else { entryType = Map.class.getName(); entryObjectValue = objectMapper.writeValueAsString(entryObjectValue); } String entryValue = conversionService.convert(entryObjectValue, String.class); ProcessVariableValue variableValue = new ProcessVariableValue(entryType, entryValue); map.put(name, variableValue); } else { map.put(name, null); } } gen.writeObject(map); }</code><technical_language>entryObjectValue is value, right</technical_language>

Target:
public void serialize(ProcessVariablesMap<String, Object> processVariablesMap, JsonGenerator gen, SerializerProvider serializers) throws IOException { HashMap<String, ProcessVariableValue> map = new HashMap<>(); for (Map.Entry<String, Object> entry : processVariablesMap.entrySet()) { String name = entry.getKey(); Object value = entry.getValue(); map.put(name, buildProcessVariableValue(value)); } gen.writeObject(map); }
Source:
<code>public void generate(final Ds3ApiSpec spec, final FileUtils fileUtils, final Path destDir) throws IOException { this.spec = spec; this.fileUtils = fileUtils; try { generateDs3_H(); generateDs3_C(); } catch (final TemplateException e) { e.printStackTrace(); } catch (final ParseException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>this a good place LOG instead of printStackTrace, a reason chose this method</technical_language>

Target:
public void generate(final Ds3ApiSpec spec, final FileUtils fileUtils, final Path destDir) throws IOException { this.spec = spec; this.fileUtils = fileUtils; try { final ImmutableList<Enum> allEnums = getAllEnums(spec); final ImmutableList<Struct> allStructs = getStructsOrderedList(spec); final ImmutableList<Request> allRequests = getAllRequests(spec); generateHeader(allEnums, allStructs, allRequests); generateSource(allEnums, allStructs, allRequests); } catch (final ParseException e) { LOG.error("Caught exception: ", e); } }
Source:
<code>public long getSize(File file) throws IOException { <START> Path folder = Paths.get(file.getAbsolutePath()); <END> return Files.walk(folder) .filter(p -> p.toFile().isFile()) .mapToLong(p -> p.toFile().length()) .sum(); }</code><technical_language>add assertInDirectory(file);</technical_language>

Target:
public long getSize(File file) throws IOException { assertInDirectory(file); Path folder = Paths.get(file.getAbsolutePath()); return Files.walk(folder) .filter(p -> p.toFile().isFile()) .mapToLong(p -> p.toFile().length()) .sum(); }
Source:
<code>public FEELFnResult<BigDecimal> invoke(@ParameterName( "number" ) BigDecimal number) { if ( number == null ) { return FEELFnResult.ofError( new InvalidParametersEvent( FEELEvent.Severity.ERROR, "number", "cannot be null" ) ); } if ( number.signum() < 0 ) { return FEELFnResult.ofError( new InvalidParametersEvent( FEELEvent.Severity.ERROR, "number", "is negative" ) ); } <START> return FEELFnResult.ofResult( new BigDecimal( Math.sqrt( number.doubleValue() ) ) ); <END> }</code><technical_language>convert double value, reason</technical_language>

Target:
public FEELFnResult<BigDecimal> invoke(@ParameterName( "number" ) BigDecimal number) { if ( number == null ) { return FEELFnResult.ofError( new InvalidParametersEvent( FEELEvent.Severity.ERROR, "number", "cannot be null" ) ); } if ( number.signum() < 0 ) { return FEELFnResult.ofError( new InvalidParametersEvent( FEELEvent.Severity.ERROR, "number", "is negative" ) ); } return FEELFnResult.ofResult( sqrt( EvalHelper.getBigDecimalOrNull( number ) ) ); }
Source:
<code>private static String getMessageClass(ReceiveCommand.Type type) { <START> switch (type) { <END> case CREATE: return "newBranch"; case UPDATE: return "modifyBranch"; case DELETE: return "deleteBranch"; default: return "errorBranch"; } }</code><technical_language>type 'UPDATE_NONFASTFORWARD'</technical_language>

Target:
private static String getMessageClass(ReceiveCommand.Type type) { switch (type) { case CREATE: return "newBranch"; case UPDATE: case UPDATE_NONFASTFORWARD: return "modifyBranch"; case DELETE: return "deleteBranch"; default: return "errorBranch"; } }
Source:
<code>public void testEqualsDifferentTypes() { List<Object> a = MutableList.<Object>of("a", 1, "b", false); List<Object> b = Arrays.<Object>asList("a", 1, "b", false); <START> Assert.assertEquals(a, b); <END> }</code><technical_language>do assertEquals(b, a). rely a impl of assertEquals do firstArg.equals(secondArg) in case..</technical_language>

Target:
public void testEqualsDifferentTypes() { List<Object> a = MutableList.<Object>of("a", 1, "b", false); List<Object> b = Arrays.<Object>asList("a", 1, "b", false); Assert.assertEquals(a, b); Assert.assertEquals(b, a); }
Source:
<code>private void unifyWith(TypeInstance other) throws HaskellTypeError { <START> if (this == other) { <END> return; } if (this.isRigid && other.isRigid) { throw new HaskellTypeError("Can not unify a rigid type variable " + this.name + " with another rigid type variable " + other.name); } other.constraints.mergeConstraintsWith(this.constraints); if (this.isRigid && ! this.constraints.equals(other.constraints)) { throw new HaskellTypeError("Can not add extra constraints to a rigid type variable " + this.name); } other.unifiedVars.addAll(this.unifiedVars); for (ListIterator<WeakReference<TypeVar>> iter = this.unifiedVars.listIterator(); iter.hasNext();) { TypeVar referer = iter.next().get(); if (referer == null) { iter.remove(); } else { referer.instance = other; } } }</code><technical_language>reference isomorphic type</technical_language>

Target:
private void unifyWith(TypeInstance other) throws HaskellTypeError { if (this == other) { return; } if (this.isRigid && other.isRigid) { throw new HaskellTypeError("Can not unify a rigid type variable " + this.name + " with another rigid type variable " + other.name); } other.constraints.mergeConstraintsWith(this.constraints); if ((this.isRigid || other.isRigid) && ! this.constraints.equals(other.constraints)) { throw new HaskellTypeError("Can not add extra constraints to a rigid type variable " + this.name); } other.unifiedVars.addAll(this.unifiedVars); for (ListIterator<WeakReference<TypeVar>> iter = this.unifiedVars.listIterator(); iter.hasNext();) { TypeVar referer = iter.next().get(); if (referer == null) { iter.remove(); } else { referer.instance = other; } } }
Source:
<code>public String produceDts(Compiler compiler) { Set<String> provides = new HashSet<>(); for (CompilerInput compilerInput : compiler.getInputsById().values()) { provides.addAll(compilerInput.getProvides()); } out = new StringWriter(); TypedScope topScope = compiler.getTopScope(); Iterable<TypedVar> allSymbols = topScope.getAllSymbols(); for (String provide : provides) { TypedVar symbol = topScope.getOwnSlot(provide); checkArgument(symbol != null, "goog.provide not defined: %s", provide); String namespace = provide; boolean isDefault = false; if (symbol.getType() != null) { if (!symbol.getType().isObject() || symbol.getType().isInterface() || symbol.getType().isFunctionType()) { int lastDot = symbol.getName().lastIndexOf('.'); namespace = lastDot >= 0 ? symbol.getName().substring(0, lastDot) : ""; isDefault = true; } } <START> currentNamespace = namespace; <END> declareNamespace(provide, symbol, isDefault, allSymbols); declareModule(provide, isDefault); } checkState(indent == 0, "indent must be zero after printing, but is %s", indent); return out.toString(); }</code><technical_language>This IMHO introduces a surprising piece of global state translation. extracting a relativeTo(namespace) method returns Function</technical_language>

Target:
public String produceDts(Compiler compiler) { Set<String> provides = new HashSet<>(); for (CompilerInput compilerInput : compiler.getInputsById().values()) { provides.addAll(compilerInput.getProvides()); } out = new StringWriter(); TypedScope topScope = compiler.getTopScope(); Iterable<TypedVar> allSymbols = topScope.getAllSymbols(); for (String provide : provides) { TypedVar symbol = topScope.getOwnSlot(provide); checkArgument(symbol != null, "goog.provide not defined: %s", provide); checkArgument(symbol.getType() != null, "all symbols should have a type"); String namespace = provide; boolean isDefault = !symbol.getType().isObject() || symbol.getType().isInterface() || symbol.getType().isFunctionType(); if (isDefault) { int lastDot = symbol.getName().lastIndexOf('.'); namespace = lastDot >= 0 ? symbol.getName().substring(0, lastDot) : ""; } declareNamespace(namespace, provide, symbol, isDefault, allSymbols); declareModule(provide, isDefault); } checkState(indent == 0, "indent must be zero after printing, but is %s", indent); return out.toString(); }
Source:
<code>public void testCreateKeyWithTTL() { String localKey = UUID.randomUUID().toString().replaceAll("-", ""); String localValue = UUID.randomUUID().toString().replaceAll("-", ""); Key createdKey = api().createKey(localKey, localValue, 1); assertNotNull(createdKey); assertNotNull(createdKey.node().expiration()); try { Thread.sleep(3000); } catch (InterruptedException e) { <START> e.printStackTrace(); <END> } createdKey = api().getKey(localKey); assertNull(createdKey); }</code><technical_language>Remove this. test propagate exception fail</technical_language>

Target:
public void testCreateKeyWithTTL() { String localKey = randomString(); String localValue = randomString(); Key createdKey = api().createKey(localKey, localValue, 1); assertNotNull(createdKey); assertNotNull(createdKey.node().expiration()); assertTrue(createdKey.node().ttl() == 1); try { Thread.sleep(3000); } catch (InterruptedException e) { Throwables.propagate(e); } createdKey = api().getKey(localKey); assertNull(createdKey); }
Source:
<code>public boolean isValid(String passportNumber) { <START> return passportNumber.matches("^[CFGHJK][0-9]{8}$"); <END> }</code><technical_language>Please extract constant</technical_language>

Target:
public boolean isValid(String passportNumber) { return passportNumber.matches(VALID_NUMBER_PATTERN); }
Source:
<code><START> public XMLHighlighting(File file, Charset charset) throws Exception{ <END> content = Files.toString(file, charset); highlightXML(new FileInputStream(file)); }</code><technical_language>![MAJOR](<LINK_0> Define throw a dedicated exception instead of a generic one. [![rule](<LINK_2>](<LINK_1></technical_language>

Target:
public XMLHighlighting(File file, Charset charset) throws Exception{ content = Files.toString(file, charset); highlightXML(new InputStreamReader(new FileInputStream(file), charset)); }
Source:
<code>private void checkFileExistence(AssetFileIdentity fileIdentity, boolean expectedToExist) throws IOException { try (InputStream stream = contentRepoService.getLatestRepoObject(fileIdentity.getFilePath())) { assertNotNull(stream); assertTrue(expectedToExist); } catch (NotFoundException nfe) { <START> throw entityNotFound(nfe.getMessage() + ": " + fileIdentity); <END> } }</code><technical_language>This throw exception before. This is removing assertFalse(expectedToExist); functionality</technical_language>

Target:
private void checkFileExistence(AssetFileIdentity fileIdentity, boolean expectedToExist) throws IOException { try (InputStream stream = contentRepoService.getLatestRepoObject(fileIdentity.getFilePath())) { assertNotNull(stream); assertTrue(expectedToExist); } catch (ContentRepoException e) { throw e; } catch (NotFoundException nfe) { assertFalse(expectedToExist); } }
Source:
<code><START> public void GetByCourtIdSuccessful() throws NotFoundException { <END> Court court = dao.getByCourtId(1L); assertThat(court, is(notNullValue())); assertThat(court.municipality, is("Ballwin")); }</code><technical_language>able remove changes change aforementioned</technical_language>

Target:
public void GetByCourtIdSuccessful(){ Court court = dao.getByCourtId(1L); assertThat(court, is(notNullValue())); assertThat(court.municipality, is("Ballwin")); }
Source:
<code>public ListenableFuture<?> truncateExportToTxnId(final long txnId) { RunnableWithES runnable = new RunnableWithES("truncateExportToTxnId") { @Override public void run() { try { if (m_mastershipAccepted.get()) { <START> exportLog.info("Export generation " + getGeneration() + " Table " + getTableName() + " mastership already accepted for partition skipping truncation." + getPartitionId()); <END> return; } m_committedBuffers.truncateToTxnId(txnId, m_nullArrayLength); if (m_committedBuffers.isEmpty() && m_endOfStream) { if (m_pollFuture != null) { m_pollFuture.set(null); m_pollFuture = null; } if (m_onDrain != null) { m_drainTraceForDebug = new Exception("Truncation txnId " + txnId); m_onDrain.run(); } } } catch (Throwable t) { VoltDB.crashLocalVoltDB("Error while trying to truncate export to txnid " + txnId, true, t); } } }; return stashOrSubmitTask(runnable, false, true); }</code><technical_language>messages helpful meaningful users. Export generates a lot of messages if partition count table count high. careful putting INFO level above</technical_language>

Target:
public ListenableFuture<?> truncateExportToTxnId(final long txnId) { RunnableWithES runnable = new RunnableWithES("truncateExportToTxnId") { @Override public void run() { try { if (m_mastershipAccepted.get()) { if (exportLog.isDebugEnabled()) { exportLog.debug("Export generation " + getGeneration() + " Table " + getTableName() + " mastership already accepted for partition skipping truncation." + getPartitionId()); } return; } m_committedBuffers.truncateToTxnId(txnId, m_nullArrayLength); if (m_committedBuffers.isEmpty() && m_endOfStream) { if (m_pollFuture != null) { m_pollFuture.set(null); m_pollFuture = null; } if (m_onDrain != null) { m_drainTraceForDebug = new Exception("Truncation txnId " + txnId); m_onDrain.run(); } } } catch (Throwable t) { VoltDB.crashLocalVoltDB("Error while trying to truncate export to txnid " + txnId, true, t); } } }; return stashOrSubmitTask(runnable, false, true); }
Source:
<code>public JSONObject getSlaveAttributeForLabel(String labelName) { for (MesosSlaveInfo slaveInfo : slaveInfos) { <START> if(labelName != null) { <END> if (labelName.equals(slaveInfo.getLabelString())) { return slaveInfo.getSlaveAttributes(); } } else { if (slaveInfo.getLabelString() == null) { return slaveInfo.getSlaveAttributes(); } } } return null; }</code><technical_language>ant: StringUtils.equals for clarity</technical_language>

Target:
public JSONObject getSlaveAttributeForLabel(String labelName) { for (MesosSlaveInfo slaveInfo : slaveInfos) { if (StringUtils.equals(labelName, slaveInfo.getLabelString())) { return slaveInfo.getSlaveAttributes(); } } return null; }
Source:
<code>public String toString() { <START> return Objects.toString(getFirst(), null) + '.' + Objects.toString(getSecond(), null); <END> }</code><technical_language>Objects.toString(getFirst()) Objects.toString(getSecond()), behavior</technical_language>

Target:
public String toString() { return Objects.toString(getFirst()) + '.' + Objects.toString(getSecond()); }
Source:
<code>public int crateNodesCount() throws UnirestException { List<String> crateHosts = crateActiveHosts(); if (crateHosts.isEmpty()) { return 0; } <START> JSONArray rows = Unirest.post(String.format("http://%s:4200/_sql", crateHosts.get(0))) <END> .header("Content-Type", "application/json") .body("{\"stmt\": \"select count(*) from sys.nodes\"}") .asJson().getBody().getObject().getJSONArray("rows"); return rows.getJSONArray(0).getInt(0); }</code><technical_language>Crate HTTP port a static field</technical_language>

Target:
public int crateNodesCount() throws UnirestException { List<String> crateHosts = crateActiveHosts(); if (crateHosts.isEmpty()) { return 0; } JSONArray rows = Unirest.post(String.format("http://%s:%d/_sql", crateHosts.get(0), HTTP_PORT)) .header("Content-Type", "application/json") .body("{\"stmt\": \"select count(*) from sys.nodes\"}") .asJson().getBody().getObject().getJSONArray("rows"); return rows.getJSONArray(0).getInt(0); }
Source:
<code>public void onReceive(Context context, Intent intent) { if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) { KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT); if (event.getAction() == KeyEvent.ACTION_UP) { int keycode = event.getKeyCode(); PendingIntent pendingIntent = null; <START> if (keycode == KeyEvent.KEYCODE_MEDIA_NEXT) { <END> pendingIntent = PendingIntent.getBroadcast(context, NOTIFICATION_ID, new Intent(ACTION_PLAY_NEXT), PendingIntent.FLAG_UPDATE_CURRENT); } else if (keycode == KeyEvent.KEYCODE_MEDIA_PREVIOUS) { pendingIntent = PendingIntent.getBroadcast(context, NOTIFICATION_ID, new Intent(ACTION_PLAY_PREVIOUS), PendingIntent.FLAG_UPDATE_CURRENT); } else if (keycode == KeyEvent.KEYCODE_HEADSETHOOK) { pendingIntent = PendingIntent.getBroadcast(context, NOTIFICATION_ID, new Intent(ACTION_PLAY_PAUSE), PendingIntent.FLAG_UPDATE_CURRENT); } if (pendingIntent != null) { try { pendingIntent.send(); } catch (Exception e) { Log.e(TAG, "Error Sending intent MediaButtonReceiver", e); } } } } }</code><technical_language>a good idea add fast rewind, some media buttons support long-pressed</technical_language>

Target:
public void onReceive(Context context, Intent intent) { if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) { KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT); if (event.getAction() == KeyEvent.ACTION_UP) { int keycode = event.getKeyCode(); PendingIntent pendingIntent = null; if (keycode == KeyEvent.KEYCODE_MEDIA_NEXT) { pendingIntent = PendingIntent.getBroadcast(context, NOTIFICATION_ID, new Intent(ACTION_PLAY_NEXT), PendingIntent.FLAG_UPDATE_CURRENT); } else if (keycode == KeyEvent.KEYCODE_MEDIA_PREVIOUS) { pendingIntent = PendingIntent.getBroadcast(context, NOTIFICATION_ID, new Intent(ACTION_PLAY_PREVIOUS), PendingIntent.FLAG_UPDATE_CURRENT); } else if (keycode == KeyEvent.KEYCODE_HEADSETHOOK || keycode == KeyEvent.KEYCODE_MEDIA_PAUSE || keycode == KeyEvent.KEYCODE_MEDIA_PLAY) { pendingIntent = PendingIntent.getBroadcast(context, NOTIFICATION_ID, new Intent(ACTION_PLAY_PAUSE), PendingIntent.FLAG_UPDATE_CURRENT); } else if (keycode == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD) { pendingIntent = PendingIntent.getBroadcast(context, NOTIFICATION_ID, new Intent(ACTION_FAST_FORWARD), PendingIntent.FLAG_UPDATE_CURRENT); } else if (keycode == KeyEvent.KEYCODE_MEDIA_REWIND) { pendingIntent = PendingIntent.getBroadcast(context, NOTIFICATION_ID, new Intent(ACTION_FAST_REWIND), PendingIntent.FLAG_UPDATE_CURRENT); } if (pendingIntent != null) { try { pendingIntent.send(); } catch (Exception e) { Log.e(TAG, "Error Sending intent MediaButtonReceiver", e); } } } } }
Source:
<code>public void testCommitMessage() { assertTrue("should not accept commit message with periods on end", !ACCEPTED_COMMIT_MESSAGE_PATTERN.matcher("minor: Test. Test.").matches()); assertTrue("should not accept commit message with spaces on end", !ACCEPTED_COMMIT_MESSAGE_PATTERN.matcher("minor: Test. ").matches()); <START> assertTrue("should not accept commit message with tabs on end", <END> !ACCEPTED_COMMIT_MESSAGE_PATTERN.matcher("minor: Test.\t").matches()); assertTrue("should not accept commit message with newline on end", !ACCEPTED_COMMIT_MESSAGE_PATTERN.matcher("minor: Test.\n").matches()); assertTrue("should not accept commit message with missing prefix", !ACCEPTED_COMMIT_MESSAGE_PATTERN.matcher("Test. Test").matches()); assertTrue("should accept commit message that ends properly", ACCEPTED_COMMIT_MESSAGE_PATTERN.matcher("minor: Test. Test").matches()); }</code><technical_language>![Codacy](<LINK_0> Issue found: [assertTrue(!expr) replaced assertFalse(expr)](<LINK_1></technical_language>

Target:
public void testCommitMessage() { assertFalse("should not accept commit message with periods on end", ACCEPTED_COMMIT_MESSAGE_PATTERN.matcher("minor: Test. Test.").matches()); assertFalse("should not accept commit message with spaces on end", ACCEPTED_COMMIT_MESSAGE_PATTERN.matcher("minor: Test. ").matches()); assertFalse("should not accept commit message with tabs on end", ACCEPTED_COMMIT_MESSAGE_PATTERN.matcher("minor: Test.\t").matches()); assertFalse("should not accept commit message with newline on end", ACCEPTED_COMMIT_MESSAGE_PATTERN.matcher("minor: Test.\n").matches()); assertFalse("should not accept commit message with missing prefix", ACCEPTED_COMMIT_MESSAGE_PATTERN.matcher("Test. Test").matches()); assertTrue("should accept commit message that ends properly", ACCEPTED_COMMIT_MESSAGE_PATTERN.matcher("minor: Test. Test").matches()); }
Source:
<code>private void attemptConsensus(Layout layout) throws OutrankedException { try { runtime.getLayoutView().updateLayout(layout, prepareRank); prepareRank = 1L; } catch (OutrankedException oe) { log.error("Conflict in updating layout by attemptConsensus: {}", oe); prepareRank = oe.getNewRank() + 1; throw oe; } for (int x = 0; x < runtime.getParameters().getInvalidateRetry(); x++) { runtime.invalidateLayout(); if (runtime.getLayoutView().getLayout().equals(layout)) { log.info("New Layout Committed = {}", layout); return; } else { log.warn("Runtime recovered with a different layout = {}", runtime.getLayoutView().getLayout()); } log.warn("attemptConsensus: Checking if has been accepted, retry {}", layout, x); } <START> throw new IllegalStateException(String.format("Layout %s was not accepted. " + <END> "Accepted layout is %s", layout, runtime.getLayoutView().getLayout())); }</code><technical_language>I remember Zeeshan mentioned expected throw exception here. Please double check this @medhavidhawan @Maithem. I feel throw else committed a new layout</technical_language>

Target:
private void attemptConsensus(Layout layout) throws OutrankedException { try { runtime.getLayoutView().updateLayout(layout, prepareRank); prepareRank = 1L; } catch (OutrankedException oe) { log.error("Conflict in updating layout by attemptConsensus: {}", oe); prepareRank = oe.getNewRank() + 1; throw oe; } for (int x = 0; x < runtime.getParameters().getInvalidateRetry(); x++) { runtime.invalidateLayout(); if (runtime.getLayoutView().getLayout().equals(layout)) { log.info("New Layout Committed = {}", layout); return; } else { log.warn("Runtime recovered with a different layout = {}", runtime.getLayoutView().getLayout()); } log.warn("attemptConsensus: Checking if has been accepted, retry {}", layout, x); } }
Source:
<code>protected Object invalidRemoteTxReturnValue() { <START> TransactionTable.CompletedTransactionStatus txStatus = txTable.getCompletedTransactionStatus(globalTx); <END> if (txStatus == TransactionTable.CompletedTransactionStatus.COMMITTED) { return null; } else if (txStatus == TransactionTable.CompletedTransactionStatus.ABORTED) { throw new CacheException("Remote transaction already rolled back: " + globalTx); } else if (txStatus == TransactionTable.CompletedTransactionStatus.EXPIRED) { throw new TimeoutException("Remote transaction status missing, please increase transaction.completedTxTimeout: " + globalTx); } else { throw new IllegalStateException("Remote transaction not found: " + globalTx); } }</code><technical_language>a switch/case is more beautiful, I live it</technical_language>

Target:
protected Object invalidRemoteTxReturnValue() { TransactionTable.CompletedTransactionStatus txStatus = txTable.getCompletedTransactionStatus(globalTx); switch (txStatus) { case COMMITTED: return null; case ABORTED: throw log.remoteTransactionAlreadyRolledBack(globalTx); case EXPIRED: throw log.remoteTransactionStatusMissing(globalTx); default: throw new IllegalStateException("Remote transaction not found: " + globalTx); } }
Source:
<code>protected void pollRecords() { if (isPolled) { return; } try { if (isPollerPartition) { nextOffset = getRecordsCount(); while (lastOffset < nextOffset) { <START> PreparedStatement preparedStatement = store.getConnection().prepareStatement(buildRangeQuery(lastOffset, rangeSize), <END> TYPE_FORWARD_ONLY, CONCUR_READ_ONLY); insertResultsInQueue(preparedStatement); lastOffset = lastOffset + rangeSize; } lastOffset = nextOffset; } else { insertResultsInQueue(ps); } isPolled = true; } catch (SQLException ex) { execute = false; threadException = new AtomicReference<Throwable>(ex); } catch (InterruptedException e) { threadException = new AtomicReference<Throwable>(e); } finally { if (!isPollerPartition) { store.disconnect(); } } isPolled = true; }</code><technical_language>(lastoffset, (nextOffset > rangeSize) ? rangeSize : nextOffset)</technical_language>

Target:
protected void pollRecords() { if (isPolled) { return; } try { if (isPollerPartition) { int nextOffset = getRecordsCount(); while (lastOffset < nextOffset) { PreparedStatement preparedStatement = store.getConnection().prepareStatement(buildRangeQuery(lastOffset, resultLimit), TYPE_FORWARD_ONLY, CONCUR_READ_ONLY); insertDbDataInQueue(preparedStatement); lastOffset = lastOffset + resultLimit; } lastOffset = nextOffset; } else { insertDbDataInQueue(ps); } isPolled = true; } catch (SQLException ex) { execute = false; threadException = new AtomicReference<Throwable>(ex); } catch (InterruptedException e) { threadException = new AtomicReference<Throwable>(e); } finally { if (!isPollerPartition) { store.disconnect(); } } isPolled = true; }
Source:
<code>public static boolean canVmsBePaused(List<VM> items) { boolean result = true; for (VM vm : items) { result &= AsyncDataProvider.isSuspendSupportedByArchitecture(vm.getClusterArch(), <START> vm.getVdsGroupCompatibilityVersion()); <END> } return result; }</code><technical_language>Please check result break if false , values , is point continue if false</technical_language>

Target:
public static boolean canVmsBePaused(List<VM> items) { for (VM vm : items) { if (!AsyncDataProvider.isSuspendSupportedByArchitecture(vm.getClusterArch(), vm.getVdsGroupCompatibilityVersion())) { return false; } } return true; }
Source:
<code>public void invalidateConnectionState() { <START> for (InputAnchor input : ((InputBlock) this).getAllInputs()) { <END> if (!input.isPrimaryConnected() || !getPane().getErrorOccured()) { input.setErrorState(false); } } }</code><technical_language>Cast is redundant</technical_language>

Target:
public void invalidateConnectionState() { for (InputAnchor input : this.getAllInputs()) { if (!input.isPrimaryConnected()) { input.setErrorState(false); } else if (!getPane().getErrorOccured()) { input.setErrorState(false); } } }
Source:
<code>private void handle(ReturnIpMsg msg) { ReturnIpReply reply = new ReturnIpReply(); <START> UsedIpVO ipvo = dbf.findByUuid(msg.getUsedIpUuid(), UsedIpVO.class); <END> if(ipvo != null){ dbf.remove(ipvo); logger.debug(String.format("Successfully released used ip[%s]", msg.getUsedIpUuid())); }else { logger.debug(String.format("used ip[%s] has been released, skip it", msg.getUsedIpUuid())); } bus.reply(msg, reply); }</code><technical_language>SQL(UsedIpVO.class).eq(xxx).hardDelete();</technical_language>

Target:
private void handle(ReturnIpMsg msg) { ReturnIpReply reply = new ReturnIpReply(); SQL.New(UsedIpVO.class).eq(UsedIpVO_.uuid, msg.getUsedIpUuid()).hardDelete(); logger.debug(String.format("Successfully released used ip[%s]", msg.getUsedIpUuid())); bus.reply(msg, reply); }
Source:
<code>public AbfsInputStream( final AbfsClient client, final Statistics statistics, final String path, final long contentLength, final AbfsInputStreamContext abfsInputStreamContext, final String eTag) { this.client = client; this.statistics = statistics; this.path = path; this.contentLength = contentLength; this.bufferSize = abfsInputStreamContext.getReadBufferSize(); this.readAheadQueueDepth = abfsInputStreamContext.getReadAheadQueueDepth(); this.tolerateOobAppends = abfsInputStreamContext.isTolerateOobAppends(); this.eTag = eTag; this.readAheadEnabled = true; this.alwaysReadBufferSize = abfsInputStreamContext.shouldReadBufferSizeAlways(); this.cachedSasToken = new CachedSASToken( abfsInputStreamContext.getSasTokenRenewPeriodForStreamsInSeconds()); this.streamStatistics = abfsInputStreamContext.getStreamStatistics(); readAheadBlockSize = abfsInputStreamContext.getReadAheadBlockSize(); <START> if (this.bufferSize > readAheadBlockSize) { <END> LOG.debug( "fs.azure.read.request.size[={}] is configured for higher size than " + "fs.azure.read.readahead.blocksize[={}]. Auto-align " + "readAhead block size to be same as readRequestSize.", bufferSize, readAheadBlockSize); readAheadBlockSize = this.bufferSize; } ReadBufferManager.setReadBufferManagerConfigs(readAheadBlockSize); }</code><technical_language>this LOG/validation moved AbfsInputStreamContext.build()</technical_language>

Target:
public AbfsInputStream( final AbfsClient client, final Statistics statistics, final String path, final long contentLength, final AbfsInputStreamContext abfsInputStreamContext, final String eTag) { this.client = client; this.statistics = statistics; this.path = path; this.contentLength = contentLength; this.bufferSize = abfsInputStreamContext.getReadBufferSize(); this.readAheadQueueDepth = abfsInputStreamContext.getReadAheadQueueDepth(); this.tolerateOobAppends = abfsInputStreamContext.isTolerateOobAppends(); this.eTag = eTag; this.readAheadEnabled = true; this.alwaysReadBufferSize = abfsInputStreamContext.shouldReadBufferSizeAlways(); this.cachedSasToken = new CachedSASToken( abfsInputStreamContext.getSasTokenRenewPeriodForStreamsInSeconds()); this.streamStatistics = abfsInputStreamContext.getStreamStatistics(); readAheadBlockSize = abfsInputStreamContext.getReadAheadBlockSize(); ReadBufferManager.setReadBufferManagerConfigs(readAheadBlockSize); }
Source:
<code><START> public void saveForm_wontRunMultipleSavesAtOnce() { <END> viewModel.saveForm(Uri.parse("file://form"), true, "", false); LiveData<FormSaveViewModel.SaveResult> saveResult1 = viewModel.getSavedResult(); assertThat(saveResult1.getValue().getState(), equalTo(SAVING)); viewModel.saveForm(Uri.parse("file://form"), true, "", false); LiveData<FormSaveViewModel.SaveResult> saveResult2 = viewModel.getSavedResult(); assertThat(saveResult2.getValue().getState(), equalTo(ALREADY_SAVING)); assertThat(Robolectric.getBackgroundThreadScheduler().size(), equalTo(1)); whenFormSaverFinishes(SaveFormToDisk.SAVED); assertThat(saveResult1.getValue().getState(), equalTo(SAVED)); }</code><technical_language>I if this sense anymore? return saving setting result ALREADY_SAVING a weird for SaveResult LiveData SAVING ALREADY_SAVING state</technical_language>

Target:
public void saveForm_wontRunMultipleSavesAtOnce() { viewModel.saveForm(Uri.parse("file://form"), true, "", false); viewModel.saveForm(Uri.parse("file://form"), true, "", false); whenFormSaverFinishes(SaveFormToDisk.SAVED); verify(formSaver).save(any(), any(), anyBoolean(), anyBoolean(), any(), any()); Robolectric.getBackgroundThreadScheduler().advanceToLastPostedRunnable(); verify(formSaver, times(1)).save(any(), any(), anyBoolean(), anyBoolean(), any(), any()); }
Source:
<code>public static <A> Strategy<A> errorStrategy(final Strategy<A> s, final Effect1<Error> e) { <START> return s.comap(a -> new P1<A>() { <END> public A _1() { try { return a._1(); } catch (Throwable t) { final Error error = new Error(t); e.f(error); throw error; } } }); }</code><technical_language>P.lazy</technical_language>

Target:
public static <A> Strategy<A> errorStrategy(final Strategy<A> s, final Effect1<Error> e) { return s.comap(a -> P.lazy(u -> { try { return a._1(); } catch (Throwable t) { final Error error = new Error(t); e.f(error); throw error; } }) ); }
Source:
<code>protected void sendEvent(Event event) { if (traceEnabled) { trace.info(afterTracerPrefix + event); } if (statisticsEnabled) { statisticsMonitor.incrementRequest(); } if ((!(mode == Mode.Distributed) || !isEventDuplicatedInCluster || EventReceiverServiceValueHolder.getCarbonEventReceiverManagementService().isReceiverCoordinator()) <START> && !isManagerNode) { <END> this.inputEventDispatcher.onEvent(event); } }</code><technical_language>@dilini-muthumala Dilini, optimize logic of if condition !isManagerNode is checked if CEP is running in distributed mode? Checking 'isManagerNode' && means right operand evaluated if left operand is true. I || conditions if a true condition is matched, expression true immediately. restructure if below? java if (mode != Mode.Distributed || !isManagerNode && (!isEventDuplicatedInCluster || isReceiverCoordinator)) This way, isManagerNode check happen in non-distributed mode, a minor optimization, useful this is in critical path of sending events. WDYT? Also, if is pre-calculate some of boolean variable combinations in distributed mode, able reduce evaluations time of sending events. if is pre-calculate some of variables optimize this if condition? Some variables mode, isEventDuplicatedInCluster change lifetime of EventReceiver instance AFAIU, able pre-calculate a boolean var check instead of checking multiple conditions time of sending event</technical_language>

Target:
protected void sendEvent(Event event) { if (traceEnabled) { trace.info(afterTracerPrefix + event); } if (statisticsEnabled) { statisticsMonitor.incrementRequest(); } if (sufficientToSend || (!isManagerNode && EventReceiverServiceValueHolder.getCarbonEventReceiverManagementService().isReceiverCoordinator())) { this.inputEventDispatcher.onEvent(event); } }
Source:
<code><START> public static List<String> getActualPropertyName(final SimpleFeatureType featureType, final List<String> propertyNames) { <END> assert featureType != null : "featureType cannot be null"; assert propertyNames != null : "propertyName != cannot be null"; List<String> nameList = new LinkedList<String>(); for (String property : propertyNames) { String name = getActualPropertyName(featureType, property); if (name != null) { nameList.add(name); } } return nameList; }</code><technical_language>this function is used. Do need for this feature</technical_language>

Target:
public static List<String> getActualPropertyName(final SimpleFeatureType featureType, final List<String> propertyNames) { if (featureType == null) { throw new IllegalArgumentException("featureType cannot be null"); } if (propertyNames == null) { throw new IllegalArgumentException("propertyName cannot be null"); } List<String> nameList = new LinkedList<String>(); for (String property : propertyNames) { String name = getActualPropertyName(featureType, property); if (name != null) { nameList.add(name); } } return nameList; }
Source:
<code>private void validateKeys(final PublicKey pubKey, final PrivateKey privKey) { if (pubKey.getAlgorithm() != privKey.getAlgorithm()) { throw new IllegalArgumentException("Public and private key have different algorithms"); <START> } <END> if (pubKey.getAlgorithm() != "RSA") { return; } try { final String data = "ENCRYPT_DATA"; final SecureRandom random = new SecureRandom(); final Cipher cipher = Cipher.getInstance(pubKey.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, privKey, random); final byte[] encryptedData = cipher.doFinal(data.getBytes()); cipher.init(Cipher.DECRYPT_MODE, pubKey, random); final String decreptedData = new String(cipher.doFinal(encryptedData)); if (!decreptedData.equals(data)) { throw new IllegalArgumentException("Bad public-private key"); } } catch (final BadPaddingException e) { throw new IllegalArgumentException("Bad public-private key", e); } catch (final IllegalBlockSizeException e) { throw new IllegalArgumentException("Bad public-private key", e); } catch (final NoSuchPaddingException e) { throw new IllegalArgumentException("Bad public-private key", e); } catch (final InvalidKeyException e) { throw new IllegalArgumentException("Invalid public-private key", e); } catch (final NoSuchAlgorithmException e) { throw new IllegalArgumentException("Invalid algorithm for public-private key", e); } }</code><technical_language>Please consider refactoring Preconditions.checkArgument DRY code. Also, please add a check pubKey is null</technical_language>

Target:
private void validateKeys(final PublicKey pubKey, final PrivateKey privKey) { Preconditions.checkNotNull(pubKey); Preconditions.checkNotNull(privKey); if (!pubKey.getAlgorithm().equals(privKey.getAlgorithm())) { throw new IllegalArgumentException("Public and private key have different algorithms"); } if (pubKey.getAlgorithm() != "RSA") { return; } try { final String data = "ENCRYPT_DATA"; final SecureRandom random = new SecureRandom(); final Cipher cipher = Cipher.getInstance(pubKey.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, privKey, random); final byte[] encryptedData = cipher.doFinal(data.getBytes()); cipher.init(Cipher.DECRYPT_MODE, pubKey, random); final String decreptedData = new String(cipher.doFinal(encryptedData)); if (!decreptedData.equals(data)) { throw new IllegalStateException("Bad public-private key"); } } catch (final BadPaddingException | IllegalBlockSizeException | InvalidKeyException | NoSuchPaddingException e) { throw new IllegalStateException("Bad public-private key", e); } catch (final NoSuchAlgorithmException e) { throw new IllegalStateException("Invalid algorithm for public-private key", e); } }
Source:
<code>public void onError(Session session, Throwable ex) { <START> if (ex instanceof SecureWebSocketException) { <END> SecurityLogger.audit("Received WebSockets request for user that is not logged in."); handleMessage( session, ((SecureWebSocketException) ex).getWsMessage(), (message, id) -> error(NOT_LOGGED_IN_ERROR, ex.getMessage())); } else { } }</code><technical_language>A SecureWebSocketException sounds pretty general. Do guarantees a SecureWebSocketException means user is logged in</technical_language>

Target:
public void onError(Session session, Throwable ex) { if (ex instanceof WebSocketAuthenticationException) { SecurityLogger.audit("Received WebSockets request for user that is not logged in."); handleMessage( session, ((WebSocketAuthenticationException) ex).getWsMessage(), (message, id) -> error(NOT_LOGGED_IN_ERROR, ex.getMessage())); } else { } }
Source:
<code>public List<FeedbackSessionAttributes> getFeedbackSessionsWithinTimeRange(Instant rangeStart, Instant rangeEnd) { <START> List<FeedbackSession> lst = new LinkedList<>(); <END> List<FeedbackSession> startEntities = load() .filter("startTime >=", rangeStart) .filter("startTime <", rangeEnd) .list(); List<FeedbackSession> endEntities = load() .filter("endTime >=", rangeStart) .filter("endTime <", rangeEnd) .list(); List<FeedbackSession> resultsVisibleEntities = load() .filter("resultsVisibleFromTime >", rangeStart) .filter("resultsVisibleFromTime <=", rangeEnd) .list(); endEntities.removeAll(startEntities); resultsVisibleEntities.removeAll(startEntities); resultsVisibleEntities.removeAll(endEntities); lst.addAll(startEntities); lst.addAll(endEntities); lst.addAll(resultsVisibleEntities); return makeAttributes(lst).stream() .sorted(Comparator.comparing(FeedbackSessionAttributes::getStartTime)) .filter(fs -> !fs.isSessionDeleted()) .collect(Collectors.toList()); }</code><technical_language>Typo in lst? feedbackSessions/feedbackSessionList a name</technical_language>

Target:
public List<FeedbackSessionAttributes> getFeedbackSessionsWithinTimeRange(Instant rangeStart, Instant rangeEnd) { List<FeedbackSession> feedbackSessionList = new LinkedList<>(); List<FeedbackSession> startEntities = load() .filter("startTime >=", rangeStart) .filter("startTime <", rangeEnd) .list(); List<FeedbackSession> endEntities = load() .filter("endTime >=", rangeStart) .filter("endTime <", rangeEnd) .list(); List<FeedbackSession> resultsVisibleEntities = load() .filter("resultsVisibleFromTime >", rangeStart) .filter("resultsVisibleFromTime <=", rangeEnd) .list(); endEntities.removeAll(startEntities); resultsVisibleEntities.removeAll(startEntities); resultsVisibleEntities.removeAll(endEntities); feedbackSessionList.addAll(startEntities); feedbackSessionList.addAll(endEntities); feedbackSessionList.addAll(resultsVisibleEntities); return makeAttributes(feedbackSessionList).stream() .sorted(Comparator.comparing(FeedbackSessionAttributes::getStartTime)) .filter(fs -> !fs.isSessionDeleted()) .collect(Collectors.toList()); }
Source:
<code>public Statement apply(Statement base, Description description) { if (description.getAnnotation(SuppressUndeliverable.class) != null) { return new Statement() { @Override public void evaluate() throws Throwable { try { <START> RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() { <END> @Override public void accept(Throwable throwable) throws Throwable { if (!(throwable instanceof UndeliverableException)) { RxJavaPlugins.getDefaultErrorHandler().accept(throwable); } } }); base.evaluate(); } finally { RxJavaPlugins.setErrorHandler(null); } } }; } else { return base; } }</code><technical_language>Java 8 lambdas in tests</technical_language>

Target:
public Statement apply(Statement base, Description description) { if (description.getAnnotation(SuppressUndeliverable.class) != null) { return new Statement() { @Override public void evaluate() throws Throwable { try { RxJavaPlugins.setErrorHandler(throwable -> { if (!(throwable instanceof UndeliverableException)) { throwable.printStackTrace(); Thread currentThread = Thread.currentThread(); currentThread.getUncaughtExceptionHandler().uncaughtException(currentThread, throwable); } }); base.evaluate(); } finally { RxJavaPlugins.setErrorHandler(null); } } }; } else { return base; } }
Source:
<code><START> public AsyncContext startAsync() throws IllegalStateException { <END> throw new UnsupportedOperationException(); }</code><technical_language>Java lets drop throws arguments implemented methods if implemented method throw exception, drop this throws if want compile ok</technical_language>

Target:
public AsyncContext startAsync() { throw new UnsupportedOperationException(); }