auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private String getDescription(long masterKeyId) { CachedPublicKeyRing cachedPublicKeyRing = mKeyRepository.getCachedPublicKeyRing(masterKeyId); String description = ""; long authSubKeyId = Constants.key.none; try { authSubKeyId = cachedPublicKeyRing.getSecretAuthenticationId(); description += cachedPublicKeyRing.getPrimaryUserId(); } catch (PgpKeyNotFoundException e) { // should never happen, since this is always called after existence of the subkey is assured START e.printStackTrace(); END } description += " ("+ Long.toHexString(authSubKeyId) +")"; return description; } Log.e or maybe throw a AssertionError if this should never happen.

Target:
private String getDescription(long masterKeyId) throws PgpKeyNotFoundException { CachedPublicKeyRing cachedPublicKeyRing = mKeyRepository.getCachedPublicKeyRing(masterKeyId); String description = ""; long authSubKeyId = cachedPublicKeyRing.getSecretAuthenticationId(); description += cachedPublicKeyRing.getPrimaryUserId(); description += " (" + Long.toHexString(authSubKeyId) + ")"; return description; }
Source:
public static OrbotStatusReceiver getInstance() { START if(instance == null) instance = new OrbotStatusReceiver(); END return instance; } if else always with

Target:
public static OrbotStatusReceiver getInstance() { if(instance == null) { instance = new OrbotStatusReceiver(); } return instance; }
Source:
public boolean getWifiOnlySync() { START return mSharedPreferences.getBoolean(Pref.ENABLE_WIFI_SYNC_ONLY, false); END } should this be enabled by default maybe? @dschuermann thoughts?

Target:
public boolean getWifiOnlySync() { return mSharedPreferences.getBoolean(Pref.ENABLE_WIFI_SYNC_ONLY, true); }
Source:
START public static void enableKeyserverSync(Context context) {] END Account account = KeychainApplication.createAccountIfNecessary(context); if (account == null) { // account failed to be created for some reason, nothing we can do here return; } ContentResolver.setIsSyncable(account, Constants.PROVIDER_AUTHORITY, 1); ContentResolver.setSyncAutomatically(account, Constants.PROVIDER_AUTHORITY, true); ContentResolver.addPeriodicSync( account, Constants.PROVIDER_AUTHORITY, new Bundle(), SYNC_INTERVAL ); } A little curious as to how compile errors are sneaking in to your commits.

Target:
public static void enableKeyserverSync(Context context) { Account account = KeychainApplication.createAccountIfNecessary(context); if (account == null) { // account failed to be created for some reason, nothing we can do here return; } ContentResolver.setIsSyncable(account, Constants.PROVIDER_AUTHORITY, 1); ContentResolver.setSyncAutomatically(account, Constants.PROVIDER_AUTHORITY, true); ContentResolver.addPeriodicSync( account, Constants.PROVIDER_AUTHORITY, new Bundle(), SYNC_INTERVAL ); }
Source:
private void scanQrCode() { Intent scanQrCode = new Intent(getActivity(), ImportKeysProxyActivity.class); scanQrCode.setAction(ImportKeysProxyActivity.ACTION_SCAN_IMPORT); START scanQrCode.putExtra(ImportKeysProxyActivity.EXTRA_IS_INTERNAL, true); END startActivityForResult(scanQrCode, REQUEST_ACTION); } this can then be removed again

Target:
private void scanQrCode() { Intent scanQrCode = new Intent(getActivity(), ImportKeysProxyActivity.class); scanQrCode.setAction(ImportKeysProxyActivity.ACTION_SCAN_IMPORT); startActivityForResult(scanQrCode, REQUEST_ACTION); }
Source:
private static PendingIntent buildIntent(Context context, long keyId) { Intent intent = new Intent(BROADCAST_ACTION_PASSPHRASE_CACHE_SERVICE); intent.putExtra(EXTRA_KEY_ID, keyId); Long _id = System.currentTimeMillis(); START return PendingIntent.getBroadcast(context, _id.intValue(), intent, END PendingIntent.FLAG_CANCEL_CURRENT); } Does this fix the problem? I don't see how the requestId parameter you changed is related, could you please explain?

Target:
private static PendingIntent buildIntent(Context context, long keyId) { Intent intent = new Intent(BROADCAST_ACTION_PASSPHRASE_CACHE_SERVICE); intent.putExtra(EXTRA_KEY_ID, keyId); //request code should be unique for each call for pending intent so we have taken requestcode //as keyId which is unique for each call as keyId is unique for each passphrase return PendingIntent.getBroadcast(context, (int)keyId, intent, PendingIntent.FLAG_CANCEL_CURRENT); }
Source:
public JobPropertyImpl(Set<String> activeProcessNames) throws Descriptor.FormException, IOException { START this.activeProcessNames.addAll(activeProcessNames); END } I would move validation/modification code from another constructor here. On the other hand you can remove exception throwing and annotate this constructor as <code>@Restricted(NoExternalUse.class)</code>

Target:
public JobPropertyImpl(Set<String> activeProcessNames) { this.activeProcessNames.addAll(activeProcessNames); }
Source:
START public DescriptorImpl getDescriptor() { END Jenkins jenkins = Jenkins.getInstance(); if(jenkins != null){ return (DescriptorImpl)jenkins.getDescriptorOrDie(getClass()); } return null; } Descriptor should be never null. Better to throw exception here

Target:
public DescriptorImpl getDescriptor() { return (DescriptorImpl)Jenkins.getInstance().getDescriptorOrDie(getClass()); }
Source:
public String getUserId() { START if (authenticationName == null) END return "N/A"; return authenticationName; } God kills a kitty every time a developer writes an "if" without braces.

Target:
public String getUserId() { if (authenticationName == null) { return "N/A"; } return authenticationName; }
Source:
public boolean uses(final Use u) { START return u == Use.X30 || u == Use.NDT || super.uses(u); END } `u == Use.NDT ||` needs to be removed (otherwise, all math functions will be treated as non-deterministic)

Target:
public boolean uses(final Use u) { return u == Use.X30 || super.uses(u); }
Source:
START public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { END f.deleteOnExit(); return null; } Please revert. `@Override` is permitted here, even with `-source 5`. (`-source 6` should come with an updated parent POM.)

Target:
@Override public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { f.deleteOnExit(); return null; }
Source:
START protected void buildEnvVarsFromActionable(Actionable build, Map<String, String> env) { END MercurialTagAction a = findTag(build); if (a != null) { env.put("MERCURIAL_REVISION", a.id); env.put("MERCURIAL_REVISION_SHORT", a.getShortId()); env.put("MERCURIAL_REVISION_NUMBER", a.rev); } } Better to be package-private. `protected` implies that you expect it to be called by, or overridden by, subclasses, which is not the case here.

Target:
void buildEnvVarsFromActionable(Actionable build, Map<String, String> env) { MercurialTagAction a = findTag(build); if (a != null) { env.put("MERCURIAL_REVISION", a.id); env.put("MERCURIAL_REVISION_SHORT", a.getShortId()); env.put("MERCURIAL_REVISION_NUMBER", a.rev); } }
Source:
START public String getSource(EnvVars env) { END return env.expand(source); } Does this need to be public? Please do not introduce new public members without cause.

Target:
private String getSource(EnvVars env) { return env.expand(source); }
Source:
public NodeInstanceList getProcessInstanceFullHistoryByType(long processInstanceId, String entryType, Integer page, Integer pageSize) { logger.debug("About to search for node instances with page and page size {}", page, pageSize); Collection<NodeInstanceDesc> result = null; result = runtimeDataService.getProcessInstanceFullHistoryByType(processInstanceId, EntryType.valueOf(entryType), buildQueryContext(page, pageSize)); NodeInstanceList nodeInstanceList = convertToNodeInstanceList(result); START logger.debug("Returning result of node instances search: {}", nodeInstanceList); END return nodeInstanceList; } Not really useful as it will print out memory address only - no `toString` method is implemented in `NodeInstanceList` class

Target:
public NodeInstanceList getProcessInstanceFullHistoryByType(long processInstanceId, String entryType, Integer page, Integer pageSize) { logger.debug("About to search for node instances with page and page size {}", page, pageSize); Collection<NodeInstanceDesc> result = null; result = runtimeDataService.getProcessInstanceFullHistoryByType(processInstanceId, EntryType.valueOf(entryType), buildQueryContext(page, pageSize)); return convertToNodeInstanceList(result); }
Source:
public void askAKafkaConsumerWithoutServerUpTest(){ START SnapshotOnDemandUtils snapshotOnDemandUtils = new SnapshotOnDemandUtilsImpl(); END EnvConfig config = EnvConfig.getDefaultEnvConfig(); config.local(false); config.underTest(false); KafkaConsumer consumer = snapshotOnDemandUtils.getConfiguredSnapshotConsumer(config); assertNull(consumer); } You can create a field for this variable (and instantiate it a `@Before` method`)

Target:
public void askAKafkaConsumerWithoutServerUpTest(){ KafkaConsumer consumer = snapshotOnDemandUtils.getConfiguredSnapshotConsumer(config); assertNull(consumer); }
Source:
public void clearTaskChangeTimes(LocalDateTime untilLocalDateTime) { if (untilLocalDateTime != null) { final List<Long> removableChanges = taskChangeTimes.entrySet().stream() .filter(entry -> untilLocalDateTime.compareTo(entry.getValue()) > 0) .map(Map.Entry::getKey) .collect(Collectors.toList()); START removableChanges.forEach(removableChange -> taskChangeTimes.remove(removableChange)); END } } I think the `forEach` can be called directly from the stream, right after the `map` call.

Target:
public void clearTaskChangeTimes(LocalDateTime untilLocalDateTime) { if (untilLocalDateTime != null) { taskChangeTimes.entrySet().stream() .filter(entry -> untilLocalDateTime.compareTo(entry.getValue()) > 0) .map(Map.Entry::getKey) .collect(Collectors.toList()) .forEach(removableChange -> taskChangeTimes.remove(removableChange)); } }
Source:
private void assertResponse(Response response) { assertEquals(200, response.getStatus()); assertNotNull(response.getEntity()); START responseStr = response.readEntity(String.class); END } Can you please remove this line from assertResponse and place it for example directly to test methods? It is a side effect and is unrelated to meaning of assertResponse method - according to its name I would expect it just to check response, not setting some method variable.

Target:
private void assertResponse(Response response) { assertNotNull(response); assertEquals(200, response.getStatus()); assertNotNull(response.getEntity()); }
Source:
protected Response invokeGet(String docsUri) { START logger.info("[GET] " + docsUri); END WebTarget clientRequest = httpClient.target(docsUri); return clientRequest.request().get(); } Can you please change the log level to debug?

Target:
protected Response invokeGet(String docsUri) { logger.debug("[GET] " + docsUri); WebTarget clientRequest = httpClient.target(docsUri); return clientRequest.request().get(); }
Source:
public ContainerSpec(ContainerSpec other) { super(other.getId(), other.getContainerName(), other.getServerTemplateKey()); this.releasedId = other.releasedId; this.status = other.status; START this.configs = other.getConfigs().isEmpty() ? new EnumMap<Capability, ContainerConfig>(Capability.class) : new EnumMap<>(other.getConfigs()); END } Here we use `EnumMap` but the initializer is set to `HashMap`, see: https://github.com/kiegroup/droolsjbpm-integration/blob/1b42ad1f1009442f13a500842c97b16e19d06648/kie-server-parent/kie-server-controller/kie-server-controller-api/src/main/java/org/kie/server/controller/api/model/spec/ContainerSpec.java#L36

Target:
public ContainerSpec(ContainerSpec other) { super(other.getId(), other.getContainerName(), other.getServerTemplateKey()); this.releasedId = other.releasedId; this.status = other.status; this.configs = other.getConfigs().isEmpty() ? new EnumMap<>(Capability.class) : new EnumMap<>(other.getConfigs()); }
Source:
public Map<Capability, ServerConfig> getConfigs() { if (configs == null) { configs = new EnumMap<>(Capability.class); } Map<Capability, ServerConfig> resultMap = new EnumMap<>(Capability.class); resultMap.putAll(configs); START return resultMap; END } You can just use copy constructor for better readability. The result is the same.

Target:
public Map<Capability, ServerConfig> getConfigs() { if (configs == null) { configs = new EnumMap<>(Capability.class); } return new EnumMap<>(configs); }
Source:
public void createClient() { START config.setCapabilities(List.of(KieServerConstants.CAPABILITY_BPM_UI)); END uiClient = KieServicesFactory.newKieServicesClient(config).getServicesClient(UIServicesClient.class); } Our code needs to be compatible with Java 8. List.of() was brought in Java 9. Can you please refactor the code to be Java 8 compatible?

Target:
public void createClient() { config.setCapabilities(Arrays.asList(KieServerConstants.CAPABILITY_BPM_UI)); uiClient = KieServicesFactory.newKieServicesClient(config).getServicesClient(UIServicesClient.class); }
Source:
private static void assertValue(int priority) { if (priority < 0 || priority > 10) { START throw new TaskAssigningRuntimeException(String.format("Task priority %s is out of range. " + END "A valid priority value must be between 0 (inclusive) " + " and 10 (inclusive)", priority)); } } Standard exception should be preferred most of the time, especially for unchecked exceptions. For the purpose if input validation, `IllegalArgumentException` is typically used.

Target:
private static void assertValue(int priority) { if (priority < 0 || priority > 10) { throw new IllegalArgumentException(String.format("Task priority %s is out of range. " + "A valid priority value must be between 0 (inclusive) " + " and 10 (inclusive)", priority)); } }
Source:
START public int acceptsAssignedUser() { END if (User.PLANNING_USER.getEntityId().equals(getUser().getEntityId())) { //planning user belongs to all the groups by definition. return 0; } //the user is a potential owner. return TaskHelper.isPotentialOwner(this, getUser()) ? 0 : -1; } This method seem to return just two states - `boolean` would be much suitable here and in the DRL rule when this method is called, we can penalize directly by -1 for each task that does not accept the assigned user.

Target:
public boolean acceptsAssignedUser() { if (User.PLANNING_USER.getEntityId().equals(getUser().getEntityId())) { //planning user belongs to all the groups by definition. return true; } return TaskHelper.isPotentialOwner(this, getUser()); }
Source:
public KieServerRouter() { configRepositoryServiceLoader.forEach(repo -> repository = repo); log.info("KIE Server router repository implementation is " + repository); START MANAGEMENT_SECURED = Boolean.parseBoolean(System.getProperty(KIE_ROUTER_MANAGEMENT_SECURED, "false")); END IDENTITY_PROVIDER = System.getProperty(KieServerRouterConstants.KIE_ROUTER_IDENTITY_PROVIDER, "default"); } Is there a specific reason to keep the initialization of attributes in constructor and not among other constants?

Target:
public KieServerRouter() { this(MANAGEMENT_SECURED, IDENTITY_PROVIDER); }
Source:
private KieServerInstanceAccount getAccount(String id) { Map<String, KieServerInstanceAccount> users = new HashMap<>(); Properties file = loadKieServerInstanceData(); START file.stringPropertyNames().forEach(name -> users.put(name, new KieServerInstanceAccount(name, file.getProperty(name)))); END return users.get(id); } What about just doing `String pwd = file.getProperty(id)` here and then create an instance of KieServerInstanceAccount from it using `return new KieServerInstanceAccount(id, pwd)`? We don't need to iterate over the whole file all the time, do we?

Target:
private KieServerInstanceAccount getAccount(String id) { Properties file = loadKieServerInstanceData(); if (!file.containsKey(id)) { return null; } return new KieServerInstanceAccount(id, file.getProperty(id)); }
Source:
private static boolean hasNotBeenInvoked(String pwdKeyAliasProperty, String pwdKeyPasswordProperty, String passwordKey) { final String key = pwdKeyAliasProperty + "-" + pwdKeyPasswordProperty; String oldPwd = invocationCache.get(key); invocationCache.put(key, passwordKey); START return oldPwd == null; END } Should we always overwrite the HashMap? I mean we could put there a new value just in case `oldPwd == null` and return true, otherwise return false. Not sure what has a bigger performance impact. We also store password here, maybe just an empty String would be sufficient as a value?

Target:
private static boolean hasNotBeenInvoked(String pwdKeyAliasProperty, String pwdKeyPasswordProperty, String passwordKey) { if (invocationCache.contains(pwdKeyAliasProperty)) { return false; } invocationCache.add(pwdKeyAliasProperty); return true; }
Source:
private static boolean hasNotBeenInvoked(String pwdKeyAliasProperty, String pwdKeyPasswordProperty, String passwordKey) { START final String key = pwdKeyAliasProperty + "-" + pwdKeyPasswordProperty; END if (invocationCache.contains(key)) { return false; } invocationCache.add(key); return true; } I just noticed that we concatenate 2 properties, but do we need them both? Maybe `pwdKeyAliasProperty` would be enough to distinguish between server and controller keys?

Target:
private static boolean hasNotBeenInvoked(String pwdKeyAliasProperty, String pwdKeyPasswordProperty, String passwordKey) { if (invocationCache.contains(pwdKeyAliasProperty)) { return false; } invocationCache.add(pwdKeyAliasProperty); return true; }
Source:
public void testPrometheusCaseMetrics() { String caseId = startUserTaskCase(USER_YODA, USER_JOHN); assertThat(caseId).isNotEmpty(); assertThat(getMetrics()).contains( "kie_server_case_started_total{case_definition_id=\"" + CASE_DEF_ID + "\",", "kie_server_case_running_total{case_definition_id=\"" + CASE_DEF_ID + "\",} 1.0" ); caseClient.cancelCaseInstance(CONTAINER_ID_CASE, caseId); assertThat(getMetrics()).contains( "kie_server_case_started_total{case_definition_id=\"" + CASE_DEF_ID + "\",", "kie_server_case_running_total{case_definition_id=\"" + CASE_DEF_ID + "\",} 0.0", "kie_server_case_duration_seconds_count{case_definition_id=\"" + CASE_DEF_ID + "\",", START "kie_server_case_duration_seconds_sum{case_definition_id=\"" + CASE_DEF_ID + "\"," END ); } @sutaakar Any potential timing issues here to get the counter to be 0?

Target:
public void testPrometheusCaseMetrics() { String caseId = startUserTaskCase(USER_YODA, USER_JOHN); assertThat(caseId).isNotEmpty(); assertThat(getMetrics()).contains( "kie_server_case_started_total{case_definition_id=\"" + CASE_DEF_ID + "\",", "kie_server_case_running_total{case_definition_id=\"" + CASE_DEF_ID + "\"," ); caseClient.cancelCaseInstance(CONTAINER_ID_CASE, caseId); assertThat(getMetrics()).contains( "kie_server_case_started_total{case_definition_id=\"" + CASE_DEF_ID + "\",", "kie_server_case_running_total{case_definition_id=\"" + CASE_DEF_ID + "\",", "kie_server_case_duration_seconds_count{case_definition_id=\"" + CASE_DEF_ID + "\",", "kie_server_case_duration_seconds_sum{case_definition_id=\"" + CASE_DEF_ID + "\"," ); }
Source:
public boolean isActive() { START return disabled == false; END } Nitpicking this change here - isn't this antipattern?

Target:
public boolean isActive() { return !disabled; }
Source:
START public void resumeMigrations() { END logger.info("Resuming ongoing migrations ..."); TypedQuery<Migration> query = em.createNamedQuery("Migration.findByStatus", Migration.class); query.setParameter("statuses", PENDING_STATUSES); query.getResultList().stream().forEach(m -> { try { migrationService.migrate(m); } catch (InvalidMigrationException e) { logger.warn("Unable to resume migration with id: " + m.getId(), e); } }); } what's the purpose of this? Is this to resume migrations that were not done (or service did not receive result) and crashed? If so that is too optimistic I'd say ... we cannot just assume that kie server didn't finish it while this service went down. So I'd say if we want this to be automatic then we should first check if migration has not finished successfully first.

Target:
public void resumeMigrations() { logger.info("Resuming ongoing migrations ..."); TypedQuery<Migration> query = em.createNamedQuery("Migration.findByStatus", Migration.class); query.setParameter("statuses", PENDING_STATUSES); query.getResultList().forEach(m -> { try { migrationService.migrate(m); } catch (InvalidMigrationException e) { logger.warn("Unable to resume migration with id: " + m.getId(), e); } }); }
Source:
public Response delete(@ApiParam(value = "Plan Id to update") @PathParam("id") Long id) throws PlanNotFoundException { planService.delete(id); START return Response.ok().build(); END } Maybe it would be good to be consistent with MigrationResource and return the deleted entity in a response here as well.

Target:
public Response delete(@ApiParam(value = "Plan Id to update") @PathParam("id") Long id) throws PlanNotFoundException { return Response.ok(planService.delete(id)).build(); }
Source:
public void testCallRemoteKieServerOperationWhenServerTemplateHasMoreThanZeroServerInstanceKeys() { final ServerInstanceKey serverInstanceKey = mock(ServerInstanceKey.class); final Collection<ServerInstanceKey> serverInstanceKeys = Collections.singletonList(serverInstanceKey); when(serverTemplate.getServerInstanceKeys()).thenReturn(serverInstanceKeys); doReturn(client).when(instanceManager).getClient(any()); final List<Container> containers = instanceManager.callRemoteKieServerOperation(serverTemplate, containerSpec, operation); START assertFalse(containers.isEmpty()); END } I think we should assert precise size of the `containers` collection.

Target:
public void testCallRemoteKieServerOperationWhenServerTemplateHasMoreThanZeroServerInstanceKeys() { final ServerInstanceKey serverInstanceKey = mock(ServerInstanceKey.class); final Collection<ServerInstanceKey> serverInstanceKeys = Collections.singletonList(serverInstanceKey); when(serverTemplate.getServerInstanceKeys()).thenReturn(serverInstanceKeys); doReturn(client).when(instanceManager).getClient(any()); final List<Container> containers = instanceManager.callRemoteKieServerOperation(serverTemplate, containerSpec, operation); assertEquals(1, containers.size()); }
Source:
public void configure() { if(templateStorage.isUnsatisfied()){ logger.warn("Unable to find template storage implementation, using in memory"); } else { setTemplateStorage(templateStorage.get()); } if(notificationService.isUnsatisfied()) { START setNotificationService(notificationService.get()); END } else { logger.warn("Unable to find notification service implementation, using logging only"); } } Shouldn't be here a warning log and in else branch the actual code - setNotificationService(notificationService.get()); ?

Target:
public void configure() { if(templateStorage.isUnsatisfied()){ logger.warn("Unable to find template storage implementation, using in memory"); } else { setTemplateStorage(templateStorage.get()); } if(notificationService.isUnsatisfied()) { logger.warn("Unable to find notification service implementation, using logging only"); } else { setNotificationService(notificationService.get()); } }
Source:
public KieServerTypePermission(Set<Class<?>> classes) { super(patterns()); START this.classes = classes; END } @mswiderski if you want you could prevent a NPE by creating a new Set in case you're passed a null one. Also I think that it could be a good idea to declare the Set classes final.

Target:
public KieServerTypePermission(Set<Class<?>> classes) { super(patterns()); this.classes = classes == null ? new HashSet<>() : classes; }
Source:
public void testRegexpForPackagesDefault() { String[] inputConfig = new String[]{"*"}; List<String> config = convertAllToPkgRegExps(inputConfig); START logger.info(Arrays.asList(config).toString()); END assertTrue(isPackageNameIncluded(Object.class.getPackage().getName(), config)); assertTrue(isPackageNameIncluded(ReactiveObject.class.getPackage().getName(), config)); assertTrue(isPackageNameIncluded("xyz.my", config)); } No need to covert list to list as above..

Target:
public void testRegexpForPackagesDefault() { String[] inputConfig = new String[]{"*"}; List<String> config = convertAllToPkgRegExps(inputConfig); logger.info(config.toString()); assertTrue(isPackageNameIncluded(Object.class.getPackage().getName(), config)); assertTrue(isPackageNameIncluded(ReactiveObject.class.getPackage().getName(), config)); assertTrue(isPackageNameIncluded("xyz.my", config)); }
Source:
public PojoWithCollections(Collection fieldCollection, List fieldList, Set fieldSet) { START super(); END this.fieldCollection = fieldCollection; this.fieldList = fieldList; this.fieldSet = fieldSet; } redundant call to `super();` as it's automatically inserted by the compiler. Also this class is child of `Object`.

Target:
public PojoWithCollections(Collection fieldCollection, List fieldList, Set fieldSet) { this.fieldCollection = fieldCollection; this.fieldList = fieldList; this.fieldSet = fieldSet; }
Source:
public CaseCommentList getComments(String containerId, String caseId, Integer page, Integer pageSize) { START Collection<CommentInstance> caseComments = caseService.getCaseComments(caseId, page, pageSize, ConvertUtils.buildQueryContext(page, pageSize)); END logger.debug("Comments for case are {}", caseId, caseComments); List<CaseComment> comments = ConvertUtils.transformCaseComments(caseComments); CaseCommentList commentsList = new CaseCommentList(comments); return commentsList; } These page and pageSize is not needed here as same info is already set on he query context

Target:
public CaseCommentList getComments(String containerId, String caseId, Integer page, Integer pageSize) { Collection<CommentInstance> caseComments = caseService.getCaseComments(caseId, ConvertUtils.buildQueryContext(page, pageSize)); logger.debug("Comments for case are {}", caseId, caseComments); List<CaseComment> comments = ConvertUtils.transformCaseComments(caseComments); CaseCommentList commentsList = new CaseCommentList(comments); return commentsList; }
Source:
public List<ServerTemplateKey> loadKeys() { if (templateKeyMap.isEmpty()) { START loadTemplateMapsFromFile(); END } return new ArrayList<ServerTemplateKey>(templateKeyMap.values()); } I'd say this should be loaded when new instance of this class is being initialized otherwise there is a chance that multiple loads will be performed in multi threaded environment - e.g. when several kie servers connects at pretty much same time.

Target:
public List<ServerTemplateKey> loadKeys() { return new ArrayList<ServerTemplateKey>(templateKeyMap.values()); }
Source:
START public synchronized ServerTemplateKey getTemplateKey(String id) { END return templateKeyMap.get(id); } Why is this synchronized? We only read from the map

Target:
public ServerTemplateKey getTemplateKey(String id) { return templateKeyMap.get(id); }
Source:
public ServerTemplate update(ServerTemplate serverTemplate) { ServerTemplate updated = null; synchronized (templateMap) { if (templateKeyMap.isEmpty()) { START loadTemplateMapsFromFile(); END } templateKeyMap.put(serverTemplate.getId(), new ServerTemplateKey(serverTemplate.getId(),serverTemplate.getName())); updated = templateMap.put(serverTemplate.getId(),serverTemplate); writeTemplateMap(); } return updated; } In that case do we need this loadTemplateMapsFromFile here?

Target:
public ServerTemplate update(ServerTemplate serverTemplate) { ServerTemplate updated = null; synchronized (templateMap) { templateKeyMap.put(serverTemplate.getId(), new ServerTemplateKey(serverTemplate.getId(),serverTemplate.getName())); updated = templateMap.put(serverTemplate.getId(),serverTemplate); writeTemplateMap(); } return updated; }
Source:
public DynamicJaxbContextManager() { if( ! instanceCreated.compareAndSet(0, 1) ) { START logger.debug("Instance of the created!", instanceCreated.incrementAndGet(), DynamicJaxbContext.class.getSimpleName() ); END } } does this prevent of creating another class or was it just for debugging?

Target:
public DynamicJaxbContextManager() { if( ! instanceCreated.compareAndSet(0, 1) ) { logger.error("Instance of the created!", instanceCreated.incrementAndGet(), DynamicJaxbContext.class.getSimpleName() ); } }
Source:
public synchronized void clear() { START this.store.clear(); END this.storeKeys.clear(); } same thing, while you are cleaning, other thread could store other key.

Target:
public void clear() { synchronized (store) { this.store.clear(); this.storeKeys.clear(); } }
Source:
public void onLinkClicked(QBAttachment qbAttachment, int position) { START if (!TextUtils.isEmpty(qbAttachment.getUrl())) { END AttachmentImageActivity.start(ChatActivity.this, qbAttachment.getUrl()); } else { String url = QBFile.getPrivateUrlForUID(qbAttachment.getId()); AttachmentImageActivity.start(ChatActivity.this, url); } } please keep only code from "else" block, since QBAttachment format is the same with iOS right now

Target:
public void onLinkClicked(QBAttachment qbAttachment, int position) { if (qbAttachment != null) { String url = QBFile.getPrivateUrlForUID(qbAttachment.getId()); AttachmentImageActivity.start(ChatActivity.this, url); } }
Source:
public void displayAvatarImage(String uri, ImageView imageView) { int prefSize = (int) (20 * Resources.getSystem().getDisplayMetrics().density); START Glide.with(context) END .load(uri) .listener(null) .override(prefSize, prefSize) .dontTransform() .error(R.drawable.ic_error) .into(imageView); } delete

Target:
public void displayAvatarImage(String uri, ImageView imageView) { }
Source:
START private boolean initFields() { END sessionManager = WebRtcSessionManager.getInstance(this); dbManager = QbUsersDbManager.getInstance(getApplicationContext()); currentSession = sessionManager.getCurrentSession(); if (currentSession == null) { return false; } opponentsIdsList = currentSession.getOpponents(); return true; } с методов инит возвращать результат плохой тон, Если уж он возвращает результат, то по названию метода следует что он возвращает true если все поля инициализированы, и false наоборот, А как посмотришь в метод, он вообще не понятно что за результат возвращает,

Target:
private void initFields() { dbManager = QbUsersDbManager.getInstance(getApplicationContext()); opponentsIdsList = currentSession.getOpponents(); }
Source:
public void enableDynamicToggle(boolean plugged) { headsetPlugged = plugged; if (isStarted) { START if (plugged) { END audioSwitchToggleButton.setEnabled(false); audioSwitchToggleButton.setChecked(true); } else { audioSwitchToggleButton.setEnabled(true); audioSwitchToggleButton.setChecked(audioSwitchToggleButton.isChecked()); } } } как на счет записи в одну строку audioSwitchToggleButton.setEnabled(!plugged);

Target:
public void enableDynamicToggle(boolean plugged) { headsetPlugged = plugged; if (isStarted) { audioSwitchToggleButton.setEnabled(!plugged); if (plugged) { audioSwitchToggleButton.setChecked(true); } else { audioSwitchToggleButton.setChecked(audioSwitchToggleButton.isChecked()); } } }
Source:
private boolean isEnteredRoomNameValid() { return ValidationUtils.isRoomNameValid(this, chatRoomNameEditText, START String.valueOf(chatRoomNameEditText.getText())); END } editText.getText().toString() уже возвращает стринг

Target:
private boolean isEnteredRoomNameValid() { return ValidationUtils.isRoomNameValid(this, chatRoomNameEditText, chatRoomNameEditText.getText().toString()); }
Source:
protected void proceedToTheNextActivity() { START if (sharedPrefsHelper.hasQbUser()) { END OpponentsActivity.start(this, false); } else { LoginActivity.start(this); } finish(); } так ты ж в onCreate сделал проверку на sharedPrefsHelper.hasQbUser()

Target:
protected void proceedToTheNextActivity() { LoginActivity.start(this); finish(); }
Source:
public void onCallStarted() { START mainHandler.post(new Runnable() { END @Override public void run() { hideOutgoingScreen(); startTimer(); actionButtonsEnabled(true); } }); } если эти колбеки в активити вызывать через runOnUiThread, тут уже никаких хендлеров не нужно будет

Target:
public void onCallStarted() { hideOutgoingScreen(); startTimer(); actionButtonsEnabled(true); }
Source:
START public void startTimer() { END if (!isStarted) { timerChronometer.setVisibility(View.VISIBLE); timerChronometer.setBase(SystemClock.elapsedRealtime()); timerChronometer.start(); isStarted = true; } } зачем public ?

Target:
private void startTimer() { if (!isStarted) { timerChronometer.setVisibility(View.VISIBLE); timerChronometer.setBase(SystemClock.elapsedRealtime()); timerChronometer.start(); isStarted = true; } }
Source:
START public void stopTimer() { END if (timerChronometer != null) { timerChronometer.stop(); isStarted = false; } } public ?

Target:
private void stopTimer() { if (timerChronometer != null) { timerChronometer.stop(); isStarted = false; } }
Source:
private void startTimer() { if (!isStarted) { START getActivity().runOnUiThread(new Runnable() { END @Override public void run() { timerABWithTimer.setVisibility(View.VISIBLE); timerABWithTimer.setBase(SystemClock.elapsedRealtime()); timerABWithTimer.start(); isStarted = true; } }); } } там есть mainHandler во фрагменте и метод runOnUiThread, без привязки к активити. И вообще метод лучше вынести из контекста runOnUiThread, А там где нужно вызывать метод вставить его в runOnUiThread,

Target:
private void startTimer() { if (!isStarted) { timerABWithTimer.setVisibility(View.VISIBLE); timerABWithTimer.setBase(SystemClock.elapsedRealtime()); timerABWithTimer.start(); isStarted = true; } }
Source:
public void initCurrentSession(QBRTCSession session) { if (session != null) { Log.d(TAG, "Init new QBRTCSession"); this.currentSession = session; this.currentSession.addSessionCallbacksListener(CallActivity.this); this.currentSession.addSignalingCallback(CallActivity.this); } else { START OpponentsActivity.start(this); END finish(); } } этого здесь точно не должно быть, Метод init отвечает за инициализацию сессии и подписки на нее, а не что-то другое, Во вторых никаких манипуляций с CallActiivty на OpponentsActivity не должно быть, мы ж это обсуждали,

Target:
public void initCurrentSession(QBRTCSession session) { if (session != null) { Log.d(TAG, "Init new QBRTCSession"); this.currentSession = session; this.currentSession.addSessionCallbacksListener(CallActivity.this); this.currentSession.addSignalingCallback(CallActivity.this); } }
Source:
public void onBackPressed() { START Fragment fragment = getFragmentManager().findFragmentByTag(CONVERSATION_CALL_FRAGMENT); END if (fragment == null) { super.onBackPressed(); // logoutSession(); } } логику onBackPressed нужно пересмотреть Может ее вообще не нужно трогать

Target:
public void onBackPressed() { }
Source:
private void setDisplayedTypeCall(QBRTCTypes.QBConferenceType conferenceType) { boolean isVideoCall = conferenceType == QBRTCTypes.QBConferenceType.QB_CONFERENCE_TYPE_VIDEO; START callTypeTextView.setText(getString(isVideoCall ? R.string.incoming_video_call : R.string.incoming_audio_call)); END takeButton.setImageResource(isVideoCall ? R.drawable.ic_video_white : R.drawable.ic_call); } у textView есть метод принимающий id строки

Target:
private void setDisplayedTypeCall(QBRTCTypes.QBConferenceType conferenceType) { boolean isVideoCall = conferenceType == QBRTCTypes.QBConferenceType.QB_CONFERENCE_TYPE_VIDEO; callTypeTextView.setText(isVideoCall ? R.string.incoming_video_call : R.string.incoming_audio_call); takeButton.setImageResource(isVideoCall ? R.drawable.ic_video_white : R.drawable.ic_call); }
Source:
private static MoPubErrorCode toMoPubErrorCode(final int applovinErrorCode) { if ( applovinErrorCode == AppLovinErrorCodes.NO_FILL ) { return MoPubErrorCode.NETWORK_NO_FILL; } START else if ( applovinErrorCode == AppLovinErrorCodes.UNSPECIFIED_ERROR ) END { return MoPubErrorCode.NETWORK_INVALID_STATE; } else if ( applovinErrorCode == AppLovinErrorCodes.NO_NETWORK ) { return MoPubErrorCode.NO_CONNECTION; } else if ( applovinErrorCode == AppLovinErrorCodes.FETCH_AD_TIMEOUT ) { return MoPubErrorCode.NETWORK_TIMEOUT; } else { return MoPubErrorCode.UNSPECIFIED; } } This should be mapped to MoPubErrorCode.UNSPECIFIED.

Target:
private static MoPubErrorCode toMoPubErrorCode(final int applovinErrorCode) { if ( applovinErrorCode == AppLovinErrorCodes.NO_FILL ) { return MoPubErrorCode.NETWORK_NO_FILL; } else if ( applovinErrorCode == AppLovinErrorCodes.UNSPECIFIED_ERROR ) { return MoPubErrorCode.UNSPECIFIED; } else if ( applovinErrorCode == AppLovinErrorCodes.NO_NETWORK ) { return MoPubErrorCode.NO_CONNECTION; } else if ( applovinErrorCode == AppLovinErrorCodes.FETCH_AD_TIMEOUT ) { return MoPubErrorCode.NETWORK_TIMEOUT; } else { return MoPubErrorCode.UNSPECIFIED; } }
Source:
private double getHeightAt(BufferedImage image, int x, int y) { int rgb = image.getRGB(x, y); int red = rgb >>> 16 & 0xFF; int green = rgb >>> 8 & 0xFF; int blue = rgb & 0xFF; START if (red == 0 && green == 0 && blue == 0) { END return 0; } double scale = (red + blue + green) / 3D / 255D; return scale * intensity; } Is there a reason for this short circuit? I know I'm probably nit-picking here, but I feel that this would be "slower" than not having it, due to extra complexity preventing JVM optimisations.

Target:
private double getHeightAt(BufferedImage image, int x, int y) { int rgb = image.getRGB(x, y); if (rgb == 0) { return 0; } int red = rgb >>> 16 & 0xFF; int green = rgb >>> 8 & 0xFF; int blue = rgb & 0xFF; double scale = (red + blue + green) / 3D / 255D; return scale * intensity; }
Source:
public static BlockType asBlockType(Material material) { checkNotNull(material); START if (!material.isBlock()) { END throw new IllegalArgumentException(material.getKey().toString() + " is not a block!"); } return materialBlockTypeCache.computeIfAbsent(material, new Function<Material, BlockType>() { @Nullable @Override public BlockType apply(@Nullable Material input) { return BlockTypes.get(material.getKey().toString()); } }); } might be able to skip this (and the `isItem` below) as the EnumMap stores a `null` object for us and can just skip `Material`'s switches.

Target:
public static BlockType asBlockType(Material material) { checkNotNull(material); return materialBlockTypeCache.computeIfAbsent(material, input -> BlockTypes.get(material.getKey().toString())); }
Source:
public FabricConfiguration(FabricWorldEdit mod) { START super(new File(mod.getWorkingDir() + File.separator + "worldedit.properties")); END } Why not use `new File(mod.getWorkingDir(), "worldedit.properties")`?

Target:
public FabricConfiguration(FabricWorldEdit mod) { super(new File(mod.getWorkingDir(), "worldedit.properties")); }
Source:
public String getName(ItemType itemType) { if (FMLLoader.getDist().isClient()) { final Item item = RegistryManager.ACTIVE.getRegistry(Item.class) .getValue(ResourceLocation.tryCreate(itemType.getId())); START if (item == null) { END return super.getName(itemType); } return I18n.format(item.getTranslationKey()); } return super.getName(itemType); } Perhaps swap the branches here, so you can drop the repeated return?

Target:
public String getName(ItemType itemType) { if (FMLLoader.getDist().isClient()) { final Item item = RegistryManager.ACTIVE.getRegistry(Item.class) .getValue(ResourceLocation.tryCreate(itemType.getId())); if (item != null) { return I18n.format(item.getTranslationKey()); } } return super.getName(itemType); }
Source:
public Iterable<Component> getStatusMessages() { START return Lists.newArrayList(TranslatableComponent.of("worldedit.operation.deform.expression", END TextComponent.of(expression).color(TextColor.LIGHT_PURPLE))); } Would prefer `ImmutableList.of` here, and in other `getStatusMessages` as well.

Target:
public Iterable<Component> getStatusMessages() { return ImmutableList.of(TranslatableComponent.of("worldedit.operation.deform.expression", TextComponent.of(expression).color(TextColor.LIGHT_PURPLE))); }
Source:
public static URL getResourceRoot(String name) throws IOException { URL url = ResourceLoader.class.getResource("/" + name); if (url == null) { try { return getResourceForgeHack(name); } catch (Exception e) { START throw new IOException("Could not find " + name); END } } return url; } Move the try-catch into the `getResourceForgeHack`?

Target:
public static URL getResourceRoot(String name) throws IOException { URL url = ResourceLoader.class.getResource("/" + name); if (url == null) { return getResourceForgeHack(name); } return url; }
Source:
public Builder type(BlockType type) { checkNotNull(type); START internalState = type.getDefaultState(); END return this; } I would prefer `return type(type.getDefaultState())` instead, to be less repetitive.

Target:
public Builder type(BlockType type) { checkNotNull(type); this.type = type; return this; }
Source:
public Mask parseFromInput(String input, ParserContext context) throws InputParseException { START if (input.startsWith("##")) { END Extent extent = Request.request().getEditSession(); // This means it's a tag mask. BlockCategory category = BlockCategories.get(input.substring(2).toLowerCase()); if (category == null) { throw new InputParseException("Unrecognised tag '" + input.substring(2) + '\''); } else { return new BlockCategoryMask(extent, category); } } return null; } Use `!input.startsWith` to align with the parser above?

Target:
public Mask parseFromInput(String input, ParserContext context) throws InputParseException { if (!input.startsWith("##")) { return null; } Extent extent = Request.request().getEditSession(); // This means it's a tag mask. BlockCategory category = BlockCategories.get(input.substring(2).toLowerCase()); if (category == null) { throw new InputParseException("Unrecognised tag '" + input.substring(2) + '\''); } else { return new BlockCategoryMask(extent, category); } }
Source:
public void run() { Set<UUID> onlineIds = new HashSet<>(); for (Player player : Sponge.getServer().getOnlinePlayers()) { onlineIds.add(player.getUniqueId()); } START this.onlineIds = new CopyOnWriteArraySet<>(onlineIds); END } Why not just build an immutable set if you're going to copy it anyways?

Target:
public void run() { List<UUID> onlineIds = new ArrayList<>(); for (Player player : Sponge.getServer().getOnlinePlayers()) { onlineIds.add(player.getUniqueId()); } this.onlineIds = new CopyOnWriteArraySet<>(onlineIds); }
Source:
START public boolean mappingExists(String alias, Map<String, Tag> idMap) { END return alias != null && idMap != null && idMap.containsKey(alias); } this looks like a static method.

Target:
public static boolean mappingExists(String alias, Map<String, Tag> idMap) { return alias != null && idMap != null && idMap.containsKey(alias); }
Source:
public void phaseOriginal() { EntitySelectorConfig entitySelectorConfig = new EntitySelectorConfig(); entitySelectorConfig.setCacheType(SelectionCacheType.PHASE); entitySelectorConfig.setSelectionOrder(SelectionOrder.ORIGINAL); EntitySelector entitySelector = entitySelectorConfig.buildEntitySelector( buildHeuristicConfigPolicy(), SelectionCacheType.JUST_IN_TIME, SelectionOrder.RANDOM); START assertThat((Object) entitySelector) END .isInstanceOf(FromSolutionEntitySelector.class); assertThat((Object) entitySelector) .isNotInstanceOf(ShufflingEntitySelector.class); assertThat(entitySelector.getCacheType()).isEqualTo(SelectionCacheType.PHASE); } Redundant cast. It seems this is done automatically by your IDE. Please check if you can avoid that.

Target:
public void phaseOriginal() { EntitySelectorConfig entitySelectorConfig = new EntitySelectorConfig(); entitySelectorConfig.setCacheType(SelectionCacheType.PHASE); entitySelectorConfig.setSelectionOrder(SelectionOrder.ORIGINAL); EntitySelector entitySelector = entitySelectorConfig.buildEntitySelector( buildHeuristicConfigPolicy(), SelectionCacheType.JUST_IN_TIME, SelectionOrder.RANDOM); assertThat(entitySelector) .isInstanceOf(FromSolutionEntitySelector.class); assertThat(entitySelector) .isNotInstanceOf(ShufflingEntitySelector.class); assertThat(entitySelector.getCacheType()).isEqualTo(SelectionCacheType.PHASE); }
Source:
Stream<DynamicTest> runFastAndFullAssert() { START checkRunTurtleTests(); END CommonApp<Solution_> commonApp = createCommonApp(); ProblemFactory<Solution_> problemFactory = createProblemFactory(commonApp); return getSolutionFiles(commonApp).stream() .map(solutionFile -> DynamicTest.dynamicTest(solutionFile.getName(), () -> runFastAndFullAssert( buildSolverConfig(commonApp.getSolverConfigResource()), problemFactory.loadProblem(solutionFile) ))); } Thank you for pointing out. Makes sense. Make sure that the skipped tests count comparison take this into account and ignores that difference - that's fine.

Target:
Stream<DynamicTest> runFastAndFullAssert() { CommonApp<Solution_> commonApp = createCommonApp(); ProblemFactory<Solution_> problemFactory = createProblemFactory(commonApp); return getSolutionFiles(commonApp).stream() .map(solutionFile -> dynamicTest(solutionFile.getName(), () -> runFastAndFullAssert( buildSolverConfig(commonApp.getSolverConfigResource()), problemFactory.loadProblem(solutionFile) ))); }
Source:
START public Constraint vehicleCapacity(ConstraintFactory factory) { END return factory.from(Customer.class) .groupBy(Customer::getVehicle, sum(Customer::getDemand)) .filter((vehicle, demand) -> demand > vehicle.getCapacity()) .penalizeLong("vehicleCapacity", HardSoftLongScore.ONE_HARD, (vehicle, demand) -> demand - vehicle.getCapacity()); } Any reason why this one is public, yet all the others are protected?

Target:
protected Constraint vehicleCapacity(ConstraintFactory factory) { return factory.from(Customer.class) .groupBy(Customer::getVehicle, sum(Customer::getDemand)) .filter((vehicle, demand) -> demand > vehicle.getCapacity()) .penalizeLong("vehicleCapacity", HardSoftLongScore.ONE_HARD, (vehicle, demand) -> demand - vehicle.getCapacity()); }
Source:
public void setWorkingSolution(Solution_ workingSolution) { START Objects.requireNonNull(workingSolution); END this.workingSolution = workingSolution; SolutionDescriptor<Solution_> solutionDescriptor = getSolutionDescriptor(); workingInitScore = - solutionDescriptor.countUninitializedVariables(workingSolution); if (lookUpEnabled) { lookUpManager.resetWorkingObjects(solutionDescriptor.getAllFacts(workingSolution)); } variableListenerSupport.resetWorkingSolution(); setWorkingEntityListDirty(); } [TIP] I like to do this: ![output](https://user-images.githubusercontent.com/673386/77458942-3dd9e680-6dff-11ea-8fb5-d772440d8d33.gif)

Target:
public void setWorkingSolution(Solution_ workingSolution) { this.workingSolution = Objects.requireNonNull(workingSolution); SolutionDescriptor<Solution_> solutionDescriptor = getSolutionDescriptor(); workingInitScore = - solutionDescriptor.countUninitializedVariables(workingSolution); if (lookUpEnabled) { lookUpManager.resetWorkingObjects(solutionDescriptor.getAllFacts(workingSolution)); } variableListenerSupport.resetWorkingSolution(); setWorkingEntityListDirty(); }
Source:
public Constraint[] getConstraints() { START return Arrays.copyOf(constraints, constraints.length); END } ConstraintStreamScoreDirectorFactory.getConstraints is non-public API. We avoid defensive copies in non-public API, unless it's a probably-one-day-public-API, to avoid performance surprises and to reduce the code size. Note that even though the array is defensively copied, the constraint instances are not. So it's not watertight. This method will never be part of a public API I'd argue.

Target:
public Constraint[] getConstraints() { return constraints; }
Source:
public Solution_ read(File inputSolutionFile) { START try(InputStream inputSolutionStream = Files.newInputStream(inputSolutionFile.toPath())) { END return read(inputSolutionStream); } catch (IOException e) { throw new IllegalArgumentException("Failed reading inputSolutionFile (" + inputSolutionFile + ").", e); } } code style: space before (

Target:
public Solution_ read(File inputSolutionFile) { try (InputStream inputSolutionStream = Files.newInputStream(inputSolutionFile.toPath())) { return read(inputSolutionStream); } catch (Exception e) { throw new IllegalArgumentException("Failed reading inputSolutionFile (" + inputSolutionFile + ").", e); } }
Source:
default <B> BiConstraintStream<A, B> join(Class<B> otherClass, BiJoiner<A, B> joiner) { if (joiner instanceof FilteringBiJoiner) { FilteringBiJoiner<A, B> filteringJoiner = (FilteringBiJoiner<A, B>) joiner; return join(otherClass) .filter(filteringJoiner.getFilter()); } else { START return join(getConstraintFactory().from(otherClass), joiner); END } } Why do we need to handle the FilteringJoiner here already? The join(UniStream, BiJoiner) method must also deal with wether or not that BiJoiner is a FilteringBiJoiner? I believe you can keep the original code on this change. And if that fails the test, then the problem is not in this method, but in the delegating method.

Target:
default <B> BiConstraintStream<A, B> join(Class<B> otherClass, BiJoiner<A, B> joiner) { return join(getConstraintFactory().from(otherClass), joiner); }