auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public long getAuditorLedgerVerificationPercentage() { return getLong(AUDITOR_LEDGER_VERIFICATION_PERCENTAGE, 100); }

Target:
shall we make the default value as `0`, which by default this feature is not enabled.
Source:
public static ByteBuf generatePacket(long ledgerId, long entryId, long lastAddConfirmed, long length, byte[] data, int offset, int len) { DigestManager dm = null; try { // CRC32 need not password, and is support definitely currently. dm = DigestManager.instantiate(ledgerId, new byte[2], CRC32); } catch (GeneralSecurityException gse) { } return dm.computeDigestAndPackageForSending(entryId, lastAddConfirmed, length, Unpooled.wrappedBuffer(data, offset, len)); }

Target:
Rethrow or at least log
Source:
private void handleLedgerEviction(RemovalNotification<Long, CachedFileInfo> notification) { CachedFileInfo fileInfo = notification.getValue(); Long ledgerId = notification.getKey(); if (null == fileInfo || null == notification.getKey()) { return; } if (notification.wasEvicted()) { evictedLedgersCounter.inc(); } fileInfo.release(); }

Target:
This is the same extreme situation that could happen in https://github.com/apache/bookkeeper/pull/513, if you think it's unlikely to happen then we can ignore it.
Source:
private Set<String> getNetworkLocations(Set<Node> bookieNodes) { Set<String> networkLocs = new HashSet<String>(); for (Node bookieNode : bookieNodes) { networkLocs.add(bookieNode.getNetworkLocation()); } return networkLocs; }

Target:
static ?
Source:
BookieStateManager(ServerConfiguration conf, RegistrationManager registrationManager) throws IOException { this.conf = conf; this.registrationManager = registrationManager; this.statsLogger = null; this.ledgerDirsManager = new LedgerDirsManager(conf, conf.getLedgerDirs(), new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold()), NullStatsLogger.INSTANCE); // ZK ephemeral node for this Bookie. this.bookieId = getMyId(); }

Target:
use NullStatsLogger.INSTANCE rather than plain `null` Also I think this constructor use this other constructor ``` this(conf, NullStatsLogger.INSTANCE, registrationManager, new LedgerDirsManager(...)); ```
Source:
public void keySmallerThanTotalSize() { try { new ArrayGroupSort(3, 2); fail("should have failed"); } catch (IllegalArgumentException e) { // ok } }

Target:
Nit: This can be put in @Test(expected=IllegalArgumentException.class) Same for below checks
Source:
void monitorPendingAddOps() { int timedOut = 0; for (PendingAddOp op : pendingAddOps) { if (op.maybeTimeout()) { timedOut++; } } LOG.info("Timed out add ops", timedOut); }

Target:
make this private if it is not used outside.
Source:
public void monitorPendingOperations() { for (PerChannelBookieClientPool clientPool : channels.values()) { clientPool.checkTimeoutOnPendingOperations(); } }

Target:
channels.values().forEach ?
Source:
protected EntryLoggerAllocator getEntryLoggerAllocator() { return entryLoggerAllocator; }

Target:
nit: you can remove `protected` to make this method package private, because the test and class are in the same package.
Source:
public void testGetWriteFlagsNone() { assertEquals(EnumSet.noneOf(WriteFlag.class), WriteFlag.getWriteFlags(0)); }

Target:
give a meaningful name for value `0`
Source:
public LedgerEntryImpl duplicate() { LedgerEntryImpl other = RECYCLER.get(); other.ledgerId = ledgerId; other.entryId = entryId; other.length = length; other.entryBuf = entryBuf.retainedSlice(); return other; }

Target:
this can be simplified with ``` return duplicate(this); ```
Source:
private void releaseByteBuf() { if (entries != null) { for (LedgerEntry entry : entries) { entry.getEntryBuffer().release(1); } } }

Target:
entries.forEach(LedgerEntry::close()); entries.clear(); entries = null;
Source:
public void onRotateEntryLog() { // for interleaved ledger storage, we request a checkpoint when rotating a entry log file. // the checkpoint represent the point that all the entries added before this point are already // in ledger storage and ready to be synced to disk. // TODO: we could consider remove checkpointSource and checkpointSouce#newCheckpoint // later if we provide kind of LSN (Log/Journal Squeuence Number) // mechanism when adding entry. {@link https://github.com/apache/bookkeeper/issues/279} if (null != checkpointer) { Checkpoint checkpoint = checkpointSource.newCheckpoint(); checkpointer.startCheckpoint(checkpoint); } }

Target:
in which case it can be null? and is it ok to be null?
Source:
public void start() throws IOException, UnavailableException, InterruptedException, KeeperException, BKException { this.bookie.start(); // fail fast, when bookie startup is not successful if (!this.bookie.isRunning()) { exitCode = bookie.getExitCode(); return; } this.nettyServer.start(); running = true; deathWatcher = new DeathWatcher(conf); deathWatcher.start(); }

Target:
can we remove `KeeperException` here?
Source:
public void setUp() throws Exception { super.setUp(); LOG.info("setUp"); zkUtil.createBKEnsemble("/" + runtime.getMethodName()); rm = new ZKRegistrationManager(); }

Target:
remove this?
Source:
private String requestToString(Object request) { if (request instanceof BookkeeperProtocol.Request) { BookkeeperProtocol.BKPacketHeader header = ((BookkeeperProtocol.Request)request).getHeader(); return String.format("Req(txnId=%d,op=%s,version=%s)", header.getTxnId(), header.getOperation(), header.getVersion()); } else { return request.toString(); } }

Target:
nit: static ?
Source:
public static <T> T fromJson(String jsonStr, Class<T> valueType) throws ParseJsonException { try { return mapper.readValue(jsonStr, valueType); } catch (Exception e) { e.printStackTrace(); throw new ParseJsonException("Failed to deserialize Object from Json string"); } }

Target:
remove
Source:
public BookKeeper.DigestType getDigestType() { if (digestType.equals(LedgerMetadataFormat.DigestType.HMAC)) { return BookKeeper.DigestType.MAC; } else { return BookKeeper.DigestType.CRC32; } }

Target:
why is this made public?
Source:
public CreateAdvBuilder makeAdv() { if(advBuilder == null) { advBuilder = new CreateAdvBuilderImpl(this); } return advBuilder; }

Target:
why do we need separate advbuilder? cannt we just assume / implement the logic as if it is advbuilder if ledger id is provided
Source:
public BookieNode selectFromNetworkLocation( String networkLoc, Set<Node> excludeBookies, Predicate<BookieNode> predicate, Ensemble<BookieNode> ensemble) throws BKNotEnoughBookiesException { // select one from local rack try { return selectRandomFromRack(networkLoc, excludeBookies, predicate, ensemble); } catch (BKNotEnoughBookiesException e) { LOG.warn("Failed to choose a bookie from : " + "excluded {}, fallback to choose bookie randomly from the cluster.", networkLoc, excludeBookies); LOG.warn("Predicate Ensemble {}", predicate, ensemble); // randomly choose one from whole cluster, ignore the provided predicate. return selectRandom(1, excludeBookies, predicate, ensemble).get(0); } }

Target:
This line doesn't give any useful information for debugging, isn't it?
Source:
HttpServer.Method convertMethod(HttpServerRequest request) { switch (request.method()) { case GET: return HttpServer.Method.GET; case POST: return HttpServer.Method.POST; case DELETE: return HttpServer.Method.DELETE; case PUT: return HttpServer.Method.PUT; default: return HttpServer.Method.GET; } }

Target:
Could just omit first case GET and let it default.
Source:
private void writeToFile(File file, String body) throws IOException { FileOutputStream fos = new FileOutputStream(file); BufferedWriter bw = null; try { bw = new BufferedWriter(new OutputStreamWriter(fos, UTF_8)); bw.write(body); } finally { if (bw != null) { bw.close(); } fos.close(); } }

Target:
it is better to use try(FileOutputStream ....)
Source:
private BookieStatus readFromFile(File file) throws IOException, IllegalArgumentException { if (!file.exists()) { return null; } BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(file), UTF_8)); try { return parse(reader); } finally { reader.close(); } }

Target:
we can use try(BufferedReader...)
Source:
public ClientAuthProvider newProvider(ClientConnectionPeer connection, AuthCallbacks.GenericCallback<Void> completeCb) { return new ClientAuthProvider() { @Override public void process(AuthToken m, AuthCallbacks.GenericCallback<AuthToken> cb) { } @Override public void close() { closeCountersOnConnections.incrementAndGet(); } public void init(AuthCallbacks.GenericCallback<AuthToken> cb) { initCountersOnConnections.incrementAndGet(); completeCb.operationComplete(BKException.Code.OK, null); } }; }

Target:
do we need '@Override' here?
Source:
public BookKeeper build() throws IOException, InterruptedException, KeeperException { Preconditions.checkNotNull(statsLogger, "No stats logger provided"); if (eventLoopGroup == null) { eventLoopGroup = getDefaultEventLoopGroup(); } return new BookKeeper(conf, zk, eventLoopGroup, statsLogger, dnsResolver, requestTimer, featureProvider); }

Target:
This will cause the eventLoopGroup to leak. We need to be sure that ownChanelFactory (or ownEventLoopGroup) is set to true when we are the ones that create the eventLoopGroup.
Source:
public void operationComplete(int rc, Void v) { if (rc == BKException.Code.OK) { authenticated = true; LOG.error("Authentication success on server side"); } else { LOG.debug("Authentication failed on server side"); } }

Target:
'info'?
Source:
public ArrayList<BookieSocketAddress> newEnsemble(int ensembleSize, int writeQuorumSize) throws BKNotEnoughBookiesException { try { // we try to only get from the healthy bookies first return placementPolicy.newEnsemble(ensembleSize, writeQuorumSize, quarantinedBookies.asMap().keySet()); } catch (BKNotEnoughBookiesException e) { if (logger.isDebugEnabled()) { logger.debug("Not enough healthy bookies available, using quarantined bookies"); } return placementPolicy.newEnsemble(ensembleSize, writeQuorumSize, EMPTY_SET); } }

Target:
the key set will be modified in #newEnsembel(). It seems to me you have to create a new set from current quarantinedBookies's key set
Source:
public RevTree getTree(ObjectId id) { return getIfPresent(id, RevTree.class); }

Target:
all the type specific getters should call get instead of getIfPresent, as they're supposed to fail if the object is not found, instead of returning null
Source:
public void add(DiffObjectCount toAdd) { treesCount += toAdd.getTreesCount(); featuresCount += toAdd.getFeaturesCount(); }

Target:
This class should ideally be immutable. I see the convenience in having these add\* methods while computing the sizes, but can you at least make them package private in order to reduce the class' public interface to the immutable part?
Source:
public void addRecentPage(int page) { BookmarksWidget.updateWidget(context); addRecentPage(page, true); }

Target:
take a look at `BookmarkPresenter` i think - there's an rx observable there. we can just subscribe to it and refresh then - not sure what the right place to subscribe is, but in worst case, some object that subscribes whenever there is at least one active widget
Source:
public void onPause() { scrollPosition = translationView.findFirstCompletelyVisibleItemPosition(); ayahTrackerPresenter.unbind(this); presenter.unbind(this); super.onPause(); }

Target:
can we move this into `onSaveInstanceState`?
Source:
public String getTranslatorName() { final String result; if (this.translatorForeign != null) { result = this.translator; } else if (this.translator != null) { result = this.translator; } else { result = this.name; } return result; }

Target:
You probably wanted to put `result = this.translatorForeign;`?
Source:
public void testLongParseDefaultSuccess() { Long num = NumberParser.parseLong("Non Long", 1L); assertTrue(num == 1L); num = NumberParser.parseLong("0", 1L); assertTrue(num == 0L); }

Target:
This method returns primitive `long`, no need for boxing. Same for the other method like this.
Source:
protected RequestBuilder applyAuth(RequestBuilder request) throws NexmoClientException { AuthMethod authMethod = getAuthMethod(getAcceptableAuthMethods()); if (isUseBasicAuth()) { return authMethod.applyAsBasicAuth(request); } return authMethod.apply(request); }

Target:
I think overiding `applyAuth` in `RedactMethod` is probably a better approach. I think that kind of thing was why I implemented it.
Source:
private void attachedFile() throws ApiError { this.deliveriesBackend.attach(delivery, fileName, in); assertEquals(1, delivery.getAttachments().size()); // Because a simple get did not return the correct deliveryAttachment, we had to do it the fancy way. assertEquals(1, delivery.getAttachments().stream() .map((attachment) -> attachment.getFileName().equals(fileName) ).count()); }

Target:
assertEquals(fileName, delivery.getAttachments().iterator().next().getFileName()) did not do the trick? Or `assertThat(delivery.getAttachments(), Matchers.contains(attachment))`? (Don't know what the `equals()` for attachment currently checks for though, and it might require that you instantiate it manually instead of mocking it)
Source:
public boolean exists( String fileSystem, String path ) { PathMap pathMap = getPathMap( fileSystem, path ); if ( pathMap != null ) { return true; } return false; }

Target:
nitpick. Just single one statement is enough: return getPathMap(fileSystem, path)!=null
Source:
public SpecialPathInfo getSpecialPathInfo( Transfer transfer, String pkgType ) { if ( transfer != null ) { return getSpecialPathInfo( transfer.getLocation(), transfer.getStoragePath(), pkgType ); } // TODO: Return SpecialPathConstants.DEFAULT_FILE or SpecialPathConstants.DEFAULT_DIR or something non-null? return null; }

Target:
This looks like it will result in getPathInfo(..) executing and calculating the storage path of this storage path...I think we need to pass in the logical path here (the getPath() output).
Source:
public void copyFrom( final Transfer f ) throws IOException { provider.waitForWriteUnlock( resource ); provider.lockWrite( resource ); try { if ( decorator != null ) { decorator.decorateCopyFrom( f, this, new EventMetadata( ) ); } provider.copy( f.getResource(), resource ); } finally { provider.unlockWrite( resource ); } }

Target:
another place where a variant of `copyFrom()` may need event metadata eventually
Source:
public void registerSpecialPathInfo( SpecialPathInfo pathInfo, final String pkgType ) { for ( Map.Entry<String, SpecialPathSet> entry : pkgtypes.entrySet() ) { if ( pkgType.equals( entry.getKey() ) ) { entry.getValue().registerSpecialPathInfo( pathInfo ); } } }

Target:
Can you just do `pkgtypes.get(pkgType)` here?
Source:
public void deregisterSpecialPathInfo( SpecialPathInfo pathInfo, String pkgType ) { for ( Map.Entry<String, SpecialPathSet> entry : pkgtypes.entrySet() ) { if ( pkgType.equals( entry.getKey() ) ) { entry.getValue().deregisterSpecialPathInfo( pathInfo ); } } }

Target:
`pkgtypes.get(pkgType)`...
Source:
public void deregesterSpecialPathSet( SpecialPathSet pathSet ) { if ( !pkgtypes.containsKey( pathSet.getPackageType() ) ) { logger.warn( "[Galley] The package does not contain the path set for this package type {}, no deregister operation there", pathSet.getPackageType() ); } pkgtypes.remove( pathSet.getPackageType() ); }

Target:
IMO we should return the removed SpecialPathSet. It's similar to Map semantics, and if people don't need the return value they can just discard it.
Source:
public String resolveExpressions( final String value, final String... activeProfileIds ) { if ( !containsExpression( value ) ) { return value; } List<String> prefixs = new ArrayList<>(); prefixs.add( PrefixAwareRecursionInterceptor.DEFAULT_START_TOKEN ); PrefixAwareRecursionInterceptor ri = new PrefixAwareRecursionInterceptor( prefixs ); return resolveExpressions( value, ri, activeProfileIds ); }

Target:
Since you have to do the null check in `resolveExpressions(String, RecursionInterceptor, String...)` anyway, you could probably move this down to that method, and call with a null `ri` here...
Source:
public String get(String name, ParcelableProxy proxy) throws QueryFailedException { throw new UnsupportedOperationException("Returning armored key from Web Key Directory not supported"); }

Target:
why here you still want to return an empty entry array?
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 e.printStackTrace(); } description += " ("+ Long.toHexString(authSubKeyId) +")"; return description; }

Target:
Log.e or maybe throw a AssertionError if this should never happen.
Source:
public static OrbotStatusReceiver getInstance() { if(instance == null) instance = new OrbotStatusReceiver(); return instance; }

Target:
if else always with
Source:
public boolean getWifiOnlySync() { return mSharedPreferences.getBoolean(Pref.ENABLE_WIFI_SYNC_ONLY, false); }

Target:
should this be enabled by default maybe? @dschuermann thoughts?
Source:
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 ); }

Target:
A little curious as to how compile errors are sneaking in to your commits.
Source:
private void scanQrCode() { Intent scanQrCode = new Intent(getActivity(), ImportKeysProxyActivity.class); scanQrCode.setAction(ImportKeysProxyActivity.ACTION_SCAN_IMPORT); scanQrCode.putExtra(ImportKeysProxyActivity.EXTRA_IS_INTERNAL, true); startActivityForResult(scanQrCode, REQUEST_ACTION); }

Target:
this can then be removed again
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(); return PendingIntent.getBroadcast(context, _id.intValue(), intent, PendingIntent.FLAG_CANCEL_CURRENT); }

Target:
Does this fix the problem? I don't see how the requestId parameter you changed is related, could you please explain?
Source:
public JobPropertyImpl(Set<String> activeProcessNames) throws Descriptor.FormException, IOException { this.activeProcessNames.addAll(activeProcessNames); }

Target:
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>
Source:
public DescriptorImpl getDescriptor() { Jenkins jenkins = Jenkins.getInstance(); if(jenkins != null){ return (DescriptorImpl)jenkins.getDescriptorOrDie(getClass()); } return null; }

Target:
Descriptor should be never null. Better to throw exception here
Source:
public String getUserId() { if (authenticationName == null) return "N/A"; return authenticationName; }

Target:
God kills a kitty every time a developer writes an "if" without braces.
Source:
public boolean uses(final Use u) { return u == Use.X30 || u == Use.NDT || super.uses(u); }

Target:
`u == Use.NDT ||` needs to be removed (otherwise, all math functions will be treated as non-deterministic)
Source:
public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { f.deleteOnExit(); return null; }

Target:
Please revert. `@Override` is permitted here, even with `-source 5`. (`-source 6` should come with an updated parent POM.)
Source:
protected 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); } }

Target:
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.
Source:
public String getSource(EnvVars env) { return env.expand(source); }

Target:
Does this need to be public? Please do not introduce new public members without cause.
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); logger.debug("Returning result of node instances search: {}", nodeInstanceList); return nodeInstanceList; }

Target:
Not really useful as it will print out memory address only - no `toString` method is implemented in `NodeInstanceList` class
Source:
public void askAKafkaConsumerWithoutServerUpTest(){ SnapshotOnDemandUtils snapshotOnDemandUtils = new SnapshotOnDemandUtilsImpl(); EnvConfig config = EnvConfig.getDefaultEnvConfig(); config.local(false); config.underTest(false); KafkaConsumer consumer = snapshotOnDemandUtils.getConfiguredSnapshotConsumer(config); assertNull(consumer); }

Target:
You can create a field for this variable (and instantiate it a `@Before` method`)
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()); removableChanges.forEach(removableChange -> taskChangeTimes.remove(removableChange)); } }

Target:
I think the `forEach` can be called directly from the stream, right after the `map` call.
Source:
private void assertResponse(Response response) { assertEquals(200, response.getStatus()); assertNotNull(response.getEntity()); responseStr = response.readEntity(String.class); }

Target:
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.
Source:
protected Response invokeGet(String docsUri) { logger.info("[GET] " + docsUri); WebTarget clientRequest = httpClient.target(docsUri); return clientRequest.request().get(); }

Target:
Can you please change the log level to debug?
Source:
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, ContainerConfig>(Capability.class) : new EnumMap<>(other.getConfigs()); }

Target:
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
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); return resultMap; }

Target:
You can just use copy constructor for better readability. The result is the same.
Source:
public void createClient() { config.setCapabilities(List.of(KieServerConstants.CAPABILITY_BPM_UI)); uiClient = KieServicesFactory.newKieServicesClient(config).getServicesClient(UIServicesClient.class); }

Target:
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?
Source:
private static void assertValue(int priority) { if (priority < 0 || priority > 10) { throw new TaskAssigningRuntimeException(String.format("Task priority %s is out of range. " + "A valid priority value must be between 0 (inclusive) " + " and 10 (inclusive)", priority)); } }

Target:
Standard exception should be preferred most of the time, especially for unchecked exceptions. For the purpose if input validation, `IllegalArgumentException` is typically used.
Source:
public int acceptsAssignedUser() { 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; }

Target:
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.
Source:
public KieServerRouter() { configRepositoryServiceLoader.forEach(repo -> repository = repo); log.info("KIE Server router repository implementation is " + repository); MANAGEMENT_SECURED = Boolean.parseBoolean(System.getProperty(KIE_ROUTER_MANAGEMENT_SECURED, "false")); IDENTITY_PROVIDER = System.getProperty(KieServerRouterConstants.KIE_ROUTER_IDENTITY_PROVIDER, "default"); }

Target:
Is there a specific reason to keep the initialization of attributes in constructor and not among other constants?
Source:
private KieServerInstanceAccount getAccount(String id) { Map<String, KieServerInstanceAccount> users = new HashMap<>(); Properties file = loadKieServerInstanceData(); file.stringPropertyNames().forEach(name -> users.put(name, new KieServerInstanceAccount(name, file.getProperty(name)))); return users.get(id); }

Target:
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?
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); return oldPwd == null; }

Target:
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?
Source:
private static boolean hasNotBeenInvoked(String pwdKeyAliasProperty, String pwdKeyPasswordProperty, String passwordKey) { final String key = pwdKeyAliasProperty + "-" + pwdKeyPasswordProperty; if (invocationCache.contains(key)) { return false; } invocationCache.add(key); return true; }

Target:
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?
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 + "\",", "kie_server_case_duration_seconds_sum{case_definition_id=\"" + CASE_DEF_ID + "\"," ); }

Target:
@sutaakar Any potential timing issues here to get the counter to be 0?
Source:
public boolean isActive() { return disabled == false; }

Target:
Nitpicking this change here - isn't this antipattern?
Source:
public void resumeMigrations() { 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); } }); }

Target:
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.
Source:
public Response delete(@ApiParam(value = "Plan Id to update") @PathParam("id") Long id) throws PlanNotFoundException { planService.delete(id); return Response.ok().build(); }

Target:
Maybe it would be good to be consistent with MigrationResource and return the deleted entity in a response here as well.
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); assertFalse(containers.isEmpty()); }

Target:
I think we should assert precise size of the `containers` collection.
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()) { setNotificationService(notificationService.get()); } else { logger.warn("Unable to find notification service implementation, using logging only"); } }

Target:
Shouldn't be here a warning log and in else branch the actual code - setNotificationService(notificationService.get()); ?
Source:
public KieServerTypePermission(Set<Class<?>> classes) { super(patterns()); this.classes = classes; }

Target:
@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.
Source:
public void testRegexpForPackagesDefault() { String[] inputConfig = new String[]{"*"}; List<String> config = convertAllToPkgRegExps(inputConfig); logger.info(Arrays.asList(config).toString()); assertTrue(isPackageNameIncluded(Object.class.getPackage().getName(), config)); assertTrue(isPackageNameIncluded(ReactiveObject.class.getPackage().getName(), config)); assertTrue(isPackageNameIncluded("xyz.my", config)); }

Target:
No need to covert list to list as above..
Source:
public PojoWithCollections(Collection fieldCollection, List fieldList, Set fieldSet) { super(); this.fieldCollection = fieldCollection; this.fieldList = fieldList; this.fieldSet = fieldSet; }

Target:
redundant call to `super();` as it's automatically inserted by the compiler. Also this class is child of `Object`.
Source:
public CaseCommentList getComments(String containerId, String caseId, Integer page, Integer pageSize) { Collection<CommentInstance> caseComments = caseService.getCaseComments(caseId, page, pageSize, 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; }

Target:
These page and pageSize is not needed here as same info is already set on he query context
Source:
public List<ServerTemplateKey> loadKeys() { if (templateKeyMap.isEmpty()) { loadTemplateMapsFromFile(); } return new ArrayList<ServerTemplateKey>(templateKeyMap.values()); }

Target:
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.
Source:
public synchronized ServerTemplateKey getTemplateKey(String id) { return templateKeyMap.get(id); }

Target:
Why is this synchronized? We only read from the map
Source:
public ServerTemplate update(ServerTemplate serverTemplate) { ServerTemplate updated = null; synchronized (templateMap) { if (templateKeyMap.isEmpty()) { loadTemplateMapsFromFile(); } templateKeyMap.put(serverTemplate.getId(), new ServerTemplateKey(serverTemplate.getId(),serverTemplate.getName())); updated = templateMap.put(serverTemplate.getId(),serverTemplate); writeTemplateMap(); } return updated; }

Target:
In that case do we need this loadTemplateMapsFromFile here?
Source:
public DynamicJaxbContextManager() { if( ! instanceCreated.compareAndSet(0, 1) ) { logger.debug("Instance of the created!", instanceCreated.incrementAndGet(), DynamicJaxbContext.class.getSimpleName() ); } }

Target:
does this prevent of creating another class or was it just for debugging?
Source:
public synchronized void clear() { this.store.clear(); this.storeKeys.clear(); }

Target:
same thing, while you are cleaning, other thread could store other key.
Source:
public void onLinkClicked(QBAttachment qbAttachment, int position) { if (!TextUtils.isEmpty(qbAttachment.getUrl())) { AttachmentImageActivity.start(ChatActivity.this, qbAttachment.getUrl()); } else { String url = QBFile.getPrivateUrlForUID(qbAttachment.getId()); AttachmentImageActivity.start(ChatActivity.this, url); } }

Target:
please keep only code from "else" block, since QBAttachment format is the same with iOS right now
Source:
public void displayAvatarImage(String uri, ImageView imageView) { int prefSize = (int) (20 * Resources.getSystem().getDisplayMetrics().density); Glide.with(context) .load(uri) .listener(null) .override(prefSize, prefSize) .dontTransform() .error(R.drawable.ic_error) .into(imageView); }

Target:
delete
Source:
private boolean initFields() { sessionManager = WebRtcSessionManager.getInstance(this); dbManager = QbUsersDbManager.getInstance(getApplicationContext()); currentSession = sessionManager.getCurrentSession(); if (currentSession == null) { return false; } opponentsIdsList = currentSession.getOpponents(); return true; }

Target:
с методов инит возвращать результат плохой тон, Если уж он возвращает результат, то по названию метода следует что он возвращает true если все поля инициализированы, и false наоборот, А как посмотришь в метод, он вообще не понятно что за результат возвращает,
Source:
public void enableDynamicToggle(boolean plugged) { headsetPlugged = plugged; if (isStarted) { if (plugged) { audioSwitchToggleButton.setEnabled(false); audioSwitchToggleButton.setChecked(true); } else { audioSwitchToggleButton.setEnabled(true); audioSwitchToggleButton.setChecked(audioSwitchToggleButton.isChecked()); } } }

Target:
как на счет записи в одну строку audioSwitchToggleButton.setEnabled(!plugged);
Source:
private boolean isEnteredRoomNameValid() { return ValidationUtils.isRoomNameValid(this, chatRoomNameEditText, String.valueOf(chatRoomNameEditText.getText())); }

Target:
editText.getText().toString() уже возвращает стринг
Source:
protected void proceedToTheNextActivity() { if (sharedPrefsHelper.hasQbUser()) { OpponentsActivity.start(this, false); } else { LoginActivity.start(this); } finish(); }

Target:
так ты ж в onCreate сделал проверку на sharedPrefsHelper.hasQbUser()
Source:
public void onCallStarted() { mainHandler.post(new Runnable() { @Override public void run() { hideOutgoingScreen(); startTimer(); actionButtonsEnabled(true); } }); }

Target:
если эти колбеки в активити вызывать через runOnUiThread, тут уже никаких хендлеров не нужно будет
Source:
public void startTimer() { if (!isStarted) { timerChronometer.setVisibility(View.VISIBLE); timerChronometer.setBase(SystemClock.elapsedRealtime()); timerChronometer.start(); isStarted = true; } }

Target:
зачем public ?
Source:
public void stopTimer() { if (timerChronometer != null) { timerChronometer.stop(); isStarted = false; } }

Target:
public ?
Source:
private void startTimer() { if (!isStarted) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { timerABWithTimer.setVisibility(View.VISIBLE); timerABWithTimer.setBase(SystemClock.elapsedRealtime()); timerABWithTimer.start(); isStarted = true; } }); } }

Target:
там есть mainHandler во фрагменте и метод runOnUiThread, без привязки к активити. И вообще метод лучше вынести из контекста runOnUiThread, А там где нужно вызывать метод вставить его в runOnUiThread,
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 { OpponentsActivity.start(this); finish(); } }

Target:
этого здесь точно не должно быть, Метод init отвечает за инициализацию сессии и подписки на нее, а не что-то другое, Во вторых никаких манипуляций с CallActiivty на OpponentsActivity не должно быть, мы ж это обсуждали,
Source:
public void onBackPressed() { Fragment fragment = getFragmentManager().findFragmentByTag(CONVERSATION_CALL_FRAGMENT); if (fragment == null) { super.onBackPressed(); // logoutSession(); } }

Target:
логику onBackPressed нужно пересмотреть Может ее вообще не нужно трогать
Source:
private void setDisplayedTypeCall(QBRTCTypes.QBConferenceType conferenceType) { boolean isVideoCall = conferenceType == QBRTCTypes.QBConferenceType.QB_CONFERENCE_TYPE_VIDEO; callTypeTextView.setText(getString(isVideoCall ? R.string.incoming_video_call : R.string.incoming_audio_call)); takeButton.setImageResource(isVideoCall ? R.drawable.ic_video_white : R.drawable.ic_call); }

Target:
у textView есть метод принимающий id строки
Source:
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.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; } }

Target:
This should be mapped to 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; if (red == 0 && green == 0 && blue == 0) { return 0; } double scale = (red + blue + green) / 3D / 255D; return scale * intensity; }

Target:
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.
Source:
public static BlockType asBlockType(Material material) { checkNotNull(material); if (!material.isBlock()) { 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()); } }); }

Target:
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.
Source:
public FabricConfiguration(FabricWorldEdit mod) { super(new File(mod.getWorkingDir() + File.separator + "worldedit.properties")); }

Target:
Why not use `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())); if (item == null) { return super.getName(itemType); } return I18n.format(item.getTranslationKey()); } return super.getName(itemType); }

Target:
Perhaps swap the branches here, so you can drop the repeated return?
Source:
public Iterable<Component> getStatusMessages() { return Lists.newArrayList(TranslatableComponent.of("worldedit.operation.deform.expression", TextComponent.of(expression).color(TextColor.LIGHT_PURPLE))); }

Target:
Would prefer `ImmutableList.of` here, and in other `getStatusMessages` as well.
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) { throw new IOException("Could not find " + name); } } return url; }

Target:
Move the try-catch into the `getResourceForgeHack`?
Source:
public Builder type(BlockType type) { checkNotNull(type); internalState = type.getDefaultState(); return this; }

Target:
I would prefer `return type(type.getDefaultState())` instead, to be less repetitive.
Source:
public Mask parseFromInput(String input, ParserContext context) throws InputParseException { if (input.startsWith("##")) { 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; }

Target:
Use `!input.startsWith` to align with the parser above?
Source:
public void run() { Set<UUID> onlineIds = new HashSet<>(); for (Player player : Sponge.getServer().getOnlinePlayers()) { onlineIds.add(player.getUniqueId()); } this.onlineIds = new CopyOnWriteArraySet<>(onlineIds); }

Target:
Why not just build an immutable set if you're going to copy it anyways?
Source:
public boolean mappingExists(String alias, Map<String, Tag> idMap) { return alias != null && idMap != null && idMap.containsKey(alias); }

Target:
this looks like a static method.
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); assertThat((Object) entitySelector) .isInstanceOf(FromSolutionEntitySelector.class); assertThat((Object) entitySelector) .isNotInstanceOf(ShufflingEntitySelector.class); assertThat(entitySelector.getCacheType()).isEqualTo(SelectionCacheType.PHASE); }

Target:
Redundant cast. It seems this is done automatically by your IDE. Please check if you can avoid that.
Source:
Stream<DynamicTest> runFastAndFullAssert() { checkRunTurtleTests(); 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) ))); }

Target:
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.
Source:
public 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()); }

Target:
Any reason why this one is public, yet all the others are protected?
Source:
public void setWorkingSolution(Solution_ workingSolution) { Objects.requireNonNull(workingSolution); this.workingSolution = workingSolution; SolutionDescriptor<Solution_> solutionDescriptor = getSolutionDescriptor(); workingInitScore = - solutionDescriptor.countUninitializedVariables(workingSolution); if (lookUpEnabled) { lookUpManager.resetWorkingObjects(solutionDescriptor.getAllFacts(workingSolution)); } variableListenerSupport.resetWorkingSolution(); setWorkingEntityListDirty(); }

Target:
[TIP] I like to do this: ![output](https://user-images.githubusercontent.com/673386/77458942-3dd9e680-6dff-11ea-8fb5-d772440d8d33.gif)
Source:
public Constraint[] getConstraints() { return Arrays.copyOf(constraints, constraints.length); }

Target:
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.
Source:
public Solution_ read(File inputSolutionFile) { try(InputStream inputSolutionStream = Files.newInputStream(inputSolutionFile.toPath())) { return read(inputSolutionStream); } catch (IOException e) { throw new IllegalArgumentException("Failed reading inputSolutionFile (" + inputSolutionFile + ").", e); } }

Target:
code style: space before (
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 { return join(getConstraintFactory().from(otherClass), joiner); } }

Target:
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.
Source:
public int compareTo(SimpleScore other) { if (initScore != other.getInitScore()) { return initScore < other.getInitScore() ? -1 : 1; } else { return Integer.compare(score, other.getScore()); } }

Target:
Nitpick: we can use return Integer.compare(initScore, other.getInitScore()); here too
Source:
public List<Object> getJustificationList() { return Collections.unmodifiableList(justificationList); }

Target:
We're duplicating it in the constructor and wrapping it here in an unmodifiable List on every call? Can we do that in the constructor then too? Still not sure if it's worth it though. This costs performance wise. 2 proposals: Proposal A): in constructor: Collections.unmodifiableList(new ArrayList<>(justificationList)) Proposal B: in constructor: Collections.unmodifiableList(justificationList) I suspect that for DRL and CS-B, proposal B is bugfree, so the duplication cost of proposal A is a perf loss. For CS-D we can duplicate before giving it to that constructor?
Source:
public static <Solution_> SolverFactory<Solution_> create(SolverConfig solverConfig) { return new DefaultSolverFactory<>(solverConfig); }

Target:
I prefer shorter method names, when the important information can be said by the argument type - which is the case here. LGTM.
Source:
public DroolsFilterUniConstraintStream(DroolsConstraintFactory<Solution_> constraintFactory, DroolsAbstractUniConstraintStream<Solution_, A> parent, Predicate<A> predicate) { super(constraintFactory, parent.getAnchor().filter(predicate)); this.parent = parent; }

Target:
ow, this could be dangerous. We need to bluejeans to discuss.
Source:
public CompositeBiJoiner(List<SingleBiJoiner<A, B>> joinerList) { this.joinerList = joinerList; if (joinerList.isEmpty()) { throw new IllegalArgumentException("The joinerList (" + joinerList + ") must not be empty."); } }

Target:
Perhaps switch the store and the check?