auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public CamusRequest popRequest() { if (requests.size() > 0){ for (int i = 0; i < requests.size(); i++) { <START> if (requests.get(i).getTopic().equals(currentTopic)) <END> return requests.remove(i); } return requests.remove(requests.size() - 1); } else return null; }</code><technical_language>is 'currentTopic' set</technical_language>

Target:
public CamusRequest popRequest() { if (requests.size() > 0){ for (int i = 0; i < requests.size(); i++) { if (requests.get(i).getTopic().equals(currentTopic)) return requests.remove(i); } CamusRequest cr = requests.remove(requests.size() - 1); currentTopic = cr.getTopic(); return cr; } else return null; }
Source:
<code>public InputKind getKind() { String[] pathComponents = this.path.split("/"); int offset = 0; <START> while (true) { <END> if (pathComponents[offset].equals("inputs")) { break; } else { offset += 1; } } List<String> toJoin = new ArrayList<String>(); for (int i = offset+1; i < pathComponents.length; i++) { toJoin.add(pathComponents[i]); } String relpath = InputCollection.join("/", toJoin); return InputKind.makeInputKind(relpath); }</code><technical_language>simpler as: while (!pathComponents[offset].equals("inputs")) { offset += 1 }</technical_language>

Target:
public InputKind getKind() { String[] pathComponents = this.path.split("/"); int offset = 0; while (!pathComponents[offset].equals("inputs")) { offset += 1; } List<String> toJoin = new ArrayList<String>(); for (int i = offset+1; i < pathComponents.length; i++) { toJoin.add(pathComponents[i]); } String relpath = Util.join("/", toJoin); return InputKind.create(relpath); }
Source:
<code>private String copyJarsToDfs(String jars, String destDir) { String dfsAppRoot = config.getDfsRoot() + "/" + config.getApplicationName(); String dfsDestDir = dfsAppRoot + "/" + destDir; FileSystem fs = null; try { fs = FileSystem.get(new URI(config.getDfsRoot()), new Configuration()); fs.mkdirs(new Path(dfsDestDir)); } catch (Exception e) { throw new IllegalStateException(e); } finally { if (fs != null) { <START> try { <END> fs.close(); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } } StringBuilder classpath = new StringBuilder(); for (String jarPath : jars.split(",")) { File jarFile = new File(jarPath); String jarName = jarFile.getName(); try { fs.copyFromLocalFile(new Path(jarPath), new Path(dfsDestDir)); } catch (IOException e) { logger.error("Failed to copy file to DFS directory {}", jarPath, dfsDestDir); try { fs.close(); } catch (IOException ioe) { throw new IllegalStateException(ioe); } throw new IllegalStateException(e); } if (classpath.length() != 0) { classpath.append(","); } classpath.append(dfsDestDir).append("/").append(jarName); } try { fs.close(); } catch (IOException e) { throw new IllegalStateException(e); } return classpath.toString(); }</code><technical_language>fs variable is in method closed in finally block. of fs in method wrapped a try-with-resources block</technical_language>

Target:
private String copyJarsToDfs(String jars, String destDir) { String dfsAppRoot = config.getDfsRoot() + "/" + config.getApplicationName(); String dfsDestDir = dfsAppRoot + "/" + destDir; FileSystem fs = null; try { fs = FileSystem.get(new URI(config.getDfsRoot()), new Configuration()); fs.mkdirs(new Path(dfsDestDir)); } catch (Exception e) { logger.error("Failed to create DFS directory {}", dfsDestDir); if (fs != null) { try { fs.close(); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } throw new IllegalStateException(e); } StringBuilder classpath = new StringBuilder(); for (String jarPath : jars.split(",")) { File jarFile = new File(jarPath); String jarName = jarFile.getName(); try { fs.copyFromLocalFile(new Path(jarPath), new Path(dfsDestDir)); } catch (IOException e) { logger.error("Failed to copy file to DFS directory {}", jarPath, dfsDestDir); try { fs.close(); } catch (IOException ioe) { throw new IllegalStateException(ioe); } throw new IllegalStateException(e); } if (classpath.length() != 0) { classpath.append(","); } classpath.append(dfsDestDir).append("/").append(jarName); } try { fs.close(); } catch (IOException e) { throw new IllegalStateException(e); } return classpath.toString(); }
Source:
<code>public Optional<IncrementalResultExporter> build(Context context) throws IncrementalExporterFactoryException, ConfigurationException { final KafkaExportParameters exportParams = new KafkaExportParameters(context.getObserverConfiguration().toMap()); <START> System.out.println("KafkaResultExporterFactory.build(): params.isExportToKafka()=" + exportParams.isExportToKafka()); <END> if (exportParams.isExportToKafka()) { KafkaProducer<String, VisibilityBindingSet> producer = new KafkaProducer<String, VisibilityBindingSet>(exportParams.getProducerConfig()); final IncrementalResultExporter exporter = new KafkaResultExporter(producer); return Optional.of(exporter); } else { return Optional.absent(); } }</code><technical_language>log.debug</technical_language>

Target:
public Optional<IncrementalResultExporter> build(Context context) throws IncrementalExporterFactoryException, ConfigurationException { final KafkaExportParameters exportParams = new KafkaExportParameters(context.getObserverConfiguration().toMap()); log.debug("KafkaResultExporterFactory.build(): params.isExportToKafka()=" + exportParams.isExportToKafka()); if (exportParams.isExportToKafka()) { KafkaProducer<String, VisibilityBindingSet> producer = new KafkaProducer<String, VisibilityBindingSet>(exportParams.getProducerConfig()); final IncrementalResultExporter exporter = new KafkaResultExporter(producer); return Optional.of(exporter); } else { return Optional.absent(); } }
Source:
<code>public EvalEvaluation(String type, String owner, String title, String instructions, Date startDate, Date dueDate, Date stopDate, Date viewDate, Boolean studentViewResults, Date studentsDate, Boolean instructorViewResults, Boolean instructorViewAllResults, Date instructorsDate, String state, String resultsSharing, String instructorOpt, Integer reminderDays, String reminderFromEmail, String termId, EvalEmailTemplate availableEmailTemplate, EvalEmailTemplate reminderEmailTemplate, EvalTemplate template, Set<EvalResponse> responses, Boolean blankResponsesAllowed, Boolean modifyResponsesAllowed, Boolean unregisteredAllowed, Boolean locked, String authControl, String evalCategory, String selectionSettings, Boolean emailOpenNotification){ this(type, owner, title, instructions, startDate, dueDate, stopDate, viewDate, studentViewResults, studentsDate, instructorViewResults, instructorViewAllResults, instructorsDate, state, resultsSharing, instructorOpt, reminderDays, reminderFromEmail, termId, availableEmailTemplate, reminderEmailTemplate, template, responses, blankResponsesAllowed, modifyResponsesAllowed, unregisteredAllowed, Boolean.FALSE ,locked, authControl, <START> evalCategory, selectionSettings, Boolean.TRUE, null); <END> }</code><technical_language>pass null instead of a default (false I imagine in this case)</technical_language>

Target:
public EvalEvaluation(String type, String owner, String title, String instructions, Date startDate, Date dueDate, Date stopDate, Date viewDate, Boolean studentViewResults, Date studentsDate, Boolean instructorViewResults, Boolean instructorViewAllResults, Date instructorsDate, String state, String resultsSharing, String instructorOpt, Integer reminderDays, String reminderFromEmail, String termId, EvalEmailTemplate availableEmailTemplate, EvalEmailTemplate reminderEmailTemplate, EvalTemplate template, Set<EvalResponse> responses, Boolean blankResponsesAllowed, Boolean modifyResponsesAllowed, Boolean unregisteredAllowed, Boolean locked, String authControl, String evalCategory, String selectionSettings, Boolean emailOpenNotification){ this(type, owner, title, instructions, startDate, dueDate, stopDate, viewDate, studentViewResults, studentsDate, instructorViewResults, instructorViewAllResults, instructorsDate, state, resultsSharing, instructorOpt, reminderDays, reminderFromEmail, termId, availableEmailTemplate, reminderEmailTemplate, template, responses, blankResponsesAllowed, modifyResponsesAllowed, unregisteredAllowed, Boolean.FALSE ,locked, authControl, evalCategory, selectionSettings, Boolean.TRUE, Boolean.FALSE); }
Source:
<code>private void checkForParseError(String name, String stream, XDDSLMessages msg, int pos, String... inserts) { try { StreamsNode sn = parse(name, stream); fail("expected to fail but parsed " + sn.stringify()); } catch (DSLException e) { <START> e.printStackTrace(); <END> assertEquals(msg, e.getMessageCode()); assertEquals(pos, e.getPosition()); if (inserts != null) { for (int i = 0; i < inserts.length; i++) { assertEquals(inserts[i], e.getInserts()[i]); } } } }</code><technical_language>print stack trace test</technical_language>

Target:
private void checkForParseError(String name, String stream, XDDSLMessages msg, int pos, String... inserts) { try { StreamsNode sn = parse(name, stream); fail("expected to fail but parsed " + sn.stringify()); } catch (DSLException e) { assertEquals(msg, e.getMessageCode()); assertEquals(pos, e.getPosition()); if (inserts != null) { for (int i = 0; i < inserts.length; i++) { assertEquals(inserts[i], e.getInserts()[i]); } } } }
Source:
<code>protected long getDelayMs(int currentAttempt) { <START> return RANDOM.nextInt(_rangeUpper) * Integer.MAX_VALUE + RANDOM.nextInt(_rangeLower) + _minDelayMs; <END> }</code><technical_language>simpler do: return _minDelayMs + (long)((_maxDelayMs - _minDelayMs) * RANDOM.nextDouble())</technical_language>

Target:
protected long getDelayMs(int currentAttempt) { return _minDelayMs + (long) (RANDOM.nextDouble() * (_maxDelayMs - _minDelayMs)); }
Source:
<code>private ValidationResult hostStatusLegalForSetupNetworks() { boolean hostStatusLegalForSetupNetworks = LEGAL_STATUSES.contains(host.getStatus()) || host.getStatus() == VDSStatus.Installing && internalExecution; if (!hostStatusLegalForSetupNetworks) { logger.error( "Unable to setup network: operation can only be done when Host status is one of: {};" + " current status is {}", LEGAL_STATUSES_STR, <START> host.getStatus()); <END> return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_VDS_STATUS_ILLEGAL, ReplacementUtils.replaceWith(VAR_HOST_STATUS, LEGAL_STATUSES, ",", LEGAL_STATUSES.size())); } return ValidationResult.VALID; }</code><technical_language>this is raceful: evaluation end 'Up', get a bogus log line. evaluation, of line 42, in a temporary variable</technical_language>

Target:
private ValidationResult hostStatusLegalForSetupNetworks() { VDSStatus hostStatus = host.getStatus(); boolean hostStatusLegalForSetupNetworks = LEGAL_STATUSES.contains(hostStatus) || hostStatus == VDSStatus.Installing && internalExecution; if (!hostStatusLegalForSetupNetworks) { logger.error( "Unable to setup network: operation can only be done when Host status is one of: {};" + " current status is {}", LEGAL_STATUSES_STR, hostStatus); return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_VDS_STATUS_ILLEGAL, ReplacementUtils.replaceWith(VAR_HOST_STATUS, LEGAL_STATUSES, ",", LEGAL_STATUSES.size())); } return ValidationResult.VALID; }
Source:
<code>public static NodeType fromByte(byte rep) throws IOException { <START> switch (rep) { <END> case 1: return CORE; case 2: return LEAF; default: throw new IOException(); } }</code><technical_language>I array of 2 index. check. this is OK a reverse seek</technical_language>

Target:
public static NodeType fromByte(byte rep) { switch (rep) { case 1: return CORE; case 2: return LEAF; default: throw new IllegalArgumentException("The NodeType byte " + rep + " is not a valid type"); } }
Source:
<code>Builder() { sparkProperties.put("spark.ui.enabled", "false"); sparkProperties.put("es.index.read.missing.as.empty", "true"); sparkProperties.put("es.nodes.wan.only", getEnv("ES_NODES_WAN_ONLY", "false")); sparkProperties.put("es.nodes", getEnv("ES_HOSTS", "127.0.0.1")); sparkProperties.put("es.net.ssl", getEnv("ES_SSL", "false")); final String username = getEnv("ES_USERNAME", null); if (username != null && !username.trim().isEmpty()) { sparkProperties.put("es.net.http.auth.user", username); } <START> final String password = getEnv("ES_PASSWORD", null); <END> if (password != null && !password.trim().isEmpty()) { sparkProperties.put("es.net.http.auth.pass", password); } }</code><technical_language>for testability, extract this a static method takes Map<String, String> System.getenv()</technical_language>

Target:
Builder() { sparkProperties.put("spark.ui.enabled", "false"); sparkProperties.put("es.index.read.missing.as.empty", "true"); sparkProperties.put("es.nodes.wan.only", getEnv("ES_NODES_WAN_ONLY", "false")); }
Source:
<code>public void registerAnalysis(final DAnalysis analysis) { <START> if (!analysis.eAdapters().contains(this)) { <END> analysis.eAdapters().add(this); } for (final DView view : analysis.getOwnedViews()) { registerView(view); } }</code><technical_language>This reveals a more impacting problem. registerAnalysis is called twice? this change hide consequence of problem cause</technical_language>

Target:
public void registerAnalysis(final DAnalysis analysis) { analysis.eAdapters().add(this); for (final DView view : analysis.getOwnedViews()) { registerView(view); } }
Source:
<code>public List<Class> getSupportedTypes() { <START> return new ArrayList<>(Arrays.asList(LocalDateTime.class)); <END> }</code><technical_language>Collections.singletonList</technical_language>

Target:
public List<Class> getSupportedTypes() { return Collections.singletonList(LocalDateTime.class); }
Source:
<code>public boolean hasExtra(ChatComponent component, boolean recursive) { <START> $lock.readLock().lock(); <END> if (extra.contains(component)) { $lock.readLock().unlock(); return true; } if (!recursive) { $lock.readLock().unlock(); return false; } for (ChatComponent child : extra) { if (child.hasExtra(component, true)) { $lock.readLock().unlock(); return true; } } $lock.readLock().unlock(); return false; }</code><technical_language>THREAD-SAFETY need mind (lol), thread safe collection lock. Please try-finally idiom explicit locks well. put lock unlocks everywhere, a try-finally automatically release lock for you</technical_language>

Target:
public boolean hasExtra(ChatComponent component, boolean recursive) { if (extra.contains(component)) { return true; } if (!recursive) { return false; } for (ChatComponent child : extra) { if (child.hasExtra(component, true)) { return true; } } return false; }
Source:
<code>private JSONObject handleGetRequest() throws AddressException, UnknownHostException, RPCException { StorageController storage = Node.getStorageController(); JSONObject responseObject = new JSONObject(); GetRpc rpc = (GetRpc) Rpc.fromJsonString(this.rpc.toString()); JSONArray json = new JSONArray(); try{ int index = rpc.getIndex(); if (index != 0){ NavigableSet<Address> keys = storage.getBucket(index); for (Address key: keys){ json.put(key); } } if (index == 0){ if(storage.containsValue(rpc.getDestination())){ FileAddress value = storage.get(rpc.getDestination()); <START> json.put(value); <END> } if (!storage.containsValue(rpc.getDestination())){ handleLookupRequest(); } } responseObject = RPCBuilder.RPCResponseFactory(rpc.getId(), true, json, null);} catch(JSONException e){ errorData = e.getMessage(); } return responseObject; }</code><technical_language>needs base 64 representation of</technical_language>

Target:
private JSONObject handleGetRequest() throws RPCException, UnknownHostException, AddressException { StorageController storage = Node.getStorageController(); JSONObject responseObject = new JSONObject(); GetRpc rpc = (GetRpc) Rpc.fromJsonString(this.rpc.toString()); JSONArray json = new JSONArray(); try{ int index = rpc.getIndex(); if (index != 0){ NavigableSet<Address> keys = storage.getBucket(index); for (Address key: keys){ json.put(key); } } if (index == 0){ if(storage.containsValue(rpc.getDestination())){ FileAddress value = storage.get(rpc.getDestination()); File file = value.getFile(); try{ byte[] byteArray = Files.readAllBytes(file.toPath()); json.put(Base64.encode(byteArray)); } catch(IOException e){ throw new RPCException(JSONRPCError.NODE_STORAGE_ERROR); } } if (!storage.containsValue(rpc.getDestination())){ return handleLookupRequest(); } } responseObject = RPCBuilder.RPCResponseFactory(rpc.getId(), true, json, null);} catch(JSONException e){ errorData = e.getMessage(); } return responseObject; }
Source:
<code>public Subscriber<? super T> call(final Subscriber<? super T> subscriber) { return new Subscriber<T>(subscriber) { <START> private final Deque<T> deque = new LinkedList<T>(); <END> @Override public void onCompleted() { subscriber.onCompleted(); } @Override public void onError(Throwable e) { subscriber.onError(e); } @Override public void onNext(T value) { if (count == 0) { subscriber.onNext(value); return; } deque.offerLast(value); if (deque.size() > count) { subscriber.onNext(deque.removeFirst()); } } }; }</code><technical_language>a ringbuffer instead of linkedlist while it</technical_language>

Target:
public Subscriber<? super T> call(final Subscriber<? super T> subscriber) { return new Subscriber<T>(subscriber) { private final NotificationLite<T> on = NotificationLite.instance(); private final Deque<Object> deque = new ArrayDeque<Object>(); @Override public void onCompleted() { subscriber.onCompleted(); } @Override public void onError(Throwable e) { subscriber.onError(e); } @Override public void onNext(T value) { if (count == 0) { subscriber.onNext(value); return; } if (deque.size() == count) { subscriber.onNext(on.getValue(deque.removeFirst())); } deque.offerLast(on.next(value)); } }; }
Source:
<code>public CommandCallback getCallback() { return ImagesHandler.filterDisksBasedOnCinder(images).isEmpty() ? <START> null : new GenericCinderCommandCallback<AddVmTemplateCommand<T>>(); <END> }</code><technical_language>Basically filter correlated execute phase : This is filter Cinder disks executing ImagesHandler.filterDisksBasedOnCinder(getVm().getDiskMap().values())</technical_language>

Target:
public CommandCallback getCallback() { return getCinderDisks().isEmpty() ? null : new ConcurrentChildCommandsExecutionCallback(); }
Source:
<code>public void testIPv6() { <START> HostPort hostPort = new HostPort("1:2::3:4:5555"); <END> assertThat(hostPort.getHost(), is("1:2::3:4")); assertThat(hostPort.getPort(), is(5555)); }</code><technical_language>want support square bracket syntax</technical_language>

Target:
public void testIPv6() { HostPort hostPort = new HostPort("[1:2::3:4]:5555"); assertThat(hostPort.getHost(), is("1:2::3:4")); assertThat(hostPort.getPort(), is(5555)); }
Source:
<code>static void processBatch( EncodingTransactionService delegate, List<BatchElement<TimestampPair, Void>> batchElements) { Map<Long, Long> accumulatedRequest = Maps.newConcurrentMap(); <START> Map<Long, SettableFuture<Void>> futures = Maps.newConcurrentMap(); <END> failDuplicateRequestsOnStartTimestamp(batchElements, accumulatedRequest, futures); while (!accumulatedRequest.isEmpty()) { try { delegate.putUnlessExistsMultiple(accumulatedRequest); batchElements.forEach(element -> element.result().set(null)); return; } catch (KeyAlreadyExistsException exception) { Set<Long> failedTimestamps = getAlreadyExistingStartTimestamps(delegate, exception); failedTimestamps.forEach(timestamp -> futures.get(timestamp).setException(exception)); accumulatedRequest = Maps.filterKeys( accumulatedRequest, timestamp -> !failedTimestamps.contains(timestamp)); } } }</code><technical_language>give a bit more detail retrying here, possibly opt for alternative approaches</technical_language>

Target:
static void processBatch( EncodingTransactionService delegate, List<BatchElement<TimestampPair, Void>> batchElements) { Map<Long, Long> accumulatedRequest = Maps.newConcurrentMap(); Map<Long, SettableFuture<Void>> futures = Maps.newConcurrentMap(); failDuplicateRequestsOnStartTimestamp(batchElements, accumulatedRequest, futures); while (!accumulatedRequest.isEmpty()) { try { delegate.putUnlessExistsMultiple(accumulatedRequest); batchElements.forEach(element -> markSuccessful(element.result())); return; } catch (KeyAlreadyExistsException exception) { Set<Long> failedTimestamps = getAlreadyExistingStartTimestamps(delegate, accumulatedRequest, exception); failedTimestamps.forEach(timestamp -> futures.get(timestamp).setException(exception)); Set<Long> successfulTimestamps = getTimestampsSuccessfullyPutUnlessExists(delegate, exception); successfulTimestamps.forEach(timestamp -> markSuccessful(futures.get(timestamp))); accumulatedRequest = Maps.filterKeys(accumulatedRequest, timestamp -> !failedTimestamps.contains(timestamp) && !successfulTimestamps.contains(timestamp)); } } }
Source:
<code>public ElasticsearchContainer waitingForShards() { <START> waitingFor((new HttpWaitStrategy()) <END> .forPath("/_cat/shards") .forPort(ELASTICSEARCH_DEFAULT_PORT) .forResponsePredicate(response -> response.contains("STARTED") && !response.contains("INITIALIZING")) .withStartupTimeout(Duration.ofMinutes(2))); return self(); }</code><technical_language>suggestion waitingFor(new HttpWaitStrategy()</technical_language>

Target:
public ElasticsearchContainer waitingForShards() { waitingFor(new HttpWaitStrategy() .forPath("/_cat/shards") .forPort(ELASTICSEARCH_DEFAULT_PORT) .forResponsePredicate(response -> response.contains("STARTED") && !response.contains("INITIALIZING")) .withStartupTimeout(Duration.ofMinutes(2))); return self(); }
Source:
<code>public static void removeMembers(AccountGroup.UUID groupUUID, Set<Account.Id> ids, AsyncCallback<VoidResult> cb) { RestApi call = new RestApi(membersBase(groupUUID)); MemberInput input = MemberInput.create(); for (Account.Id id : ids) { <START> input.add_member(Integer.toString(id.get())); <END> } call.data(input).delete(cb); }</code><technical_language>id.toString() is valid here. :-)</technical_language>

Target:
public static void removeMembers(AccountGroup.UUID groupUUID, Set<Account.Id> ids, AsyncCallback<VoidResult> cb) { RestApi call = new RestApi(membersBase(groupUUID)); MemberInput input = MemberInput.create(); for (Account.Id id : ids) { input.add_member(id.toString()); } call.data(input).delete(cb); }
Source:
<code>private void queryVideos(String query) { List<UUID> ids; try { <START> ids = VideoInfoRepository.FindResult.toIds(App.videoInfoRepository.getAllSorted()); <END> } catch (IOException e) { e.printStackTrace(); return; } for (UUID id : ids) { try { if (isMatch(id, query)) { this.matches.add(id); } } catch (IOException e) { e.printStackTrace(); } } this.browserFragment.setVideos(this.matches); }</code><technical_language>a custom collection for neater syntax</technical_language>

Target:
private void queryVideos(String query) { FindResults results; try { results = App.videoInfoRepository.getAll(); } catch (IOException e) { e.printStackTrace(); return; } FindResults matching = new FindResults(new ArrayList<FindResult>(results.size())); for (FindResult result : results) { try { if (isMatch(result.getId(), query)) { matching.add(result); } } catch (IOException e) { e.printStackTrace(); } } this.matches.addAll(matching.sortDescending().getIDs()); this.browserFragment.setVideos(this.matches); }
Source:
<code>public void setup() { Function<Map<String, Result>, Set<String>> titles = m -> m.entrySet() .stream() .map(Map.Entry::getValue) .map(Result::getMetacard) .map(Metacard::getTitle) .collect(Collectors.toSet()); Set<String> queryTitles = queryAsAdmin(FormAttributes.Query.TAG, titles); Set<String> resultTitles = queryAsAdmin(FormAttributes.Result.TAG, titles); List<Metacard> initialTemplates = config().get(); initialTemplates .stream() .filter(QueryTemplateMetacardImpl::isQueryTemplateMetacard) <START> .filter(m -> !queryTitles.contains(m.getTitle())) <END> .forEach(this::saveMetacard); initialTemplates .stream() .filter(ResultTemplateMetacardImpl::isResultTemplateMetacard) .filter(m -> !resultTitles.contains(m.getTitle())) .forEach(this::saveMetacard); }</code><technical_language>rename m metacard for clarity</technical_language>

Target:
public void setup() { List<Metacard> systemTemplates = SearchFormsLoader.config().get(); if (systemTemplates.isEmpty()) { return; } SearchFormsLoader.bootstrap(catalogFramework, util, systemTemplates); }
Source:
<code>private List<LanguageRange> getMetadataLanguage() { User user = ServiceManager.getUserService().getAuthenticatedUser(); String metadataLanguage = user != null ? user.getMetadataLanguage() : Helper.getRequestParameter("Accept-Language"); return LanguageRange <START> .parse(Objects.nonNull(metadataLanguage) && !metadataLanguage.isEmpty() ? metadataLanguage : "en"); <END> }</code><technical_language>suggestion .parse(StringUtils.isBlank(metadataLanguage) ? metadataLanguage : "en");</technical_language>

Target:
private List<LanguageRange> getMetadataLanguage() { User user = ServiceManager.getUserService().getAuthenticatedUser(); String metadataLanguage = user != null ? user.getMetadataLanguage() : Helper.getRequestParameter("Accept-Language"); return LanguageRange .parse(StringUtils.isBlank(metadataLanguage) ? metadataLanguage : "en"); }
Source:
<code>public String replaceSingle(String line, RegexFindReplace findReplace, String startTag, String endTag) { int currPos = 0; StringBuilder replacedLine = new StringBuilder(); <START> Matcher patternMatcher = Pattern.compile(findReplace.find()).matcher(line); <END> while (patternMatcher.find()) { String replacedString = patternMatcher.group().replaceFirst(findReplace.find(), findReplace.replace()); currPos = appendReplacedTextFragmentInHTML(startTag, endTag, replacedLine, line, currPos, replacedString, patternMatcher); } replacedLine.append(line.substring(currPos)); line = replacedLine.toString(); return line; }</code><technical_language>this method called for regex visitStringNode called multiple times. Therefore, compiling of set of regular expressions happen for invocation of visitStringNode. sense cache compiled Patterns Matchers</technical_language>

Target:
public String replaceSingle(String line, RegexFindReplace findReplace, String startTag, String endTag) { int currPos = 0; StringBuilder replacedLine = new StringBuilder(); Matcher patternMatcher = regexPatterns.get(findReplace.find()).matcher(line); while (patternMatcher.find()) { String replacedString = patternMatcher.group().replaceFirst(findReplace.find(), findReplace.replace()); currPos = appendReplacedTextFragmentInHTML(startTag, endTag, replacedLine, line, currPos, replacedString, patternMatcher); } replacedLine.append(line.substring(currPos)); line = replacedLine.toString(); return line; }
Source:
<code>void addNutrient() { String[] nutrients = getResources().getStringArray(R.array.nutrients_array); <START> Arrays.sort(nutrients, Collator.getInstance(Locale.US)); <END> new MaterialDialog.Builder(activity) .title(R.string.choose_nutrient) .items(nutrients) .itemsCallback((dialog, itemView, position, text) -> { if (!index.contains(position)) { index.add(position); final CustomValidatingEditTextView textView = addNutrientRow(position, text, false, null, 0); allEditViews.add(textView); addValidListener(textView); } else { Toast.makeText(activity, getString(R.string.nutrient_already_added, nutrients[position]), Toast.LENGTH_SHORT).show(); } }) .show(); }</code><technical_language>I bet wanted StringComparator. :P</technical_language>

Target:
void addNutrient() { String[] nutrients = getResources().getStringArray(R.array.nutrients_array); Stringi18nUtils.sortAlphabetically(nutrients, Collator.getInstance(Locale.getDefault())); new MaterialDialog.Builder(activity) .title(R.string.choose_nutrient) .items(nutrients) .itemsCallback((dialog, itemView, position, text) -> { if (!index.contains(position)) { index.add(position); final CustomValidatingEditTextView textView = addNutrientRow(position, text, false, null, 0); allEditViews.add(textView); addValidListener(textView); } else { Toast.makeText(activity, getString(R.string.nutrient_already_added, nutrients[position]), Toast.LENGTH_SHORT).show(); } }) .show(); }
Source:
<code>public Result apply(LateralJoinNode parent, Captures captures, Context context) { List<ValuesNode> values = searchFrom(parent.getSubquery(), context.getLookup()) .recurseOnlyWhen(ProjectNode.class::isInstance) .where(ValuesNode.class::isInstance) .findAll(); if (values.size() != 1 || !isSingleRowValuesWithNoColumns(values.get(0))) { return Result.empty(); } List<ProjectNode> subqueryProjections = searchFrom(parent.getSubquery(), context.getLookup()) <START> .where(ProjectNode.class::isInstance) <END> .findAll(); List<ProjectNode> mutableSubQueryProjections = new ArrayList<>(subqueryProjections); if (mutableSubQueryProjections.size() > 1) { for (int i = 0; i < mutableSubQueryProjections.size(); i++) { ProjectNode currentProjectNode = mutableSubQueryProjections.get(i); if (parent.getInput().getOutputSymbols().containsAll(currentProjectNode.getOutputSymbols())) { mutableSubQueryProjections.remove(i); } } } if (mutableSubQueryProjections.size() == 0) { return Result.ofPlanNode(parent.getInput()); } else if (mutableSubQueryProjections.size() == 1) { Assignments assignments = Assignments.builder() .putIdentities(parent.getInput().getOutputSymbols()) .putAll(mutableSubQueryProjections.get(0).getAssignments()) .build(); return Result.ofPlanNode(projectNode(parent.getInput(), assignments, context)); } return Result.empty(); }</code><technical_language>Use: where(node -> node instanceof ProjectNode && !node.getOutputSymbols().equals(parent.getCorrelation())) please remove changes below</technical_language>

Target:
public Result apply(LateralJoinNode parent, Captures captures, Context context) { List<ValuesNode> values = searchFrom(parent.getSubquery(), context.getLookup()) .recurseOnlyWhen(ProjectNode.class::isInstance) .where(ValuesNode.class::isInstance) .findAll(); if (values.size() != 1 || !isSingleRowValuesWithNoColumns(values.get(0))) { return Result.empty(); } List<ProjectNode> subqueryProjections = searchFrom(parent.getSubquery(), context.getLookup()) .where(node -> node instanceof ProjectNode && !node.getOutputSymbols().equals(parent.getCorrelation())) .findAll(); if (subqueryProjections.size() == 0) { return Result.ofPlanNode(parent.getInput()); } else if (subqueryProjections.size() == 1) { Assignments assignments = Assignments.builder() .putIdentities(parent.getInput().getOutputSymbols()) .putAll(subqueryProjections.get(0).getAssignments()) .build(); return Result.ofPlanNode(projectNode(parent.getInput(), assignments, context)); } return Result.empty(); }
Source:
<code>public static ViewHighlighter newInstance() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { return new OverlayHighlighter(); } else { <START> return new NullHighlighter(); <END> } }</code><technical_language>This represents a poor API. If provide a working implementation for versions, newInstance method marked @Nullable return null. This callers explicitly write: java if (mHighlighter != null) { mHighlighter.highlight(...) } alternative strategy is add isSupported method NullHighlighter (prefer NoopHighlighter null semantic context here) implements returns false, throws other methods, forcing callers write: java if (mHighlighter.isSupported()) { mHighlighter.highlight(...); } reason for explicit is readers of highlighting code plainly supported explain working for a naive/quick read of source code. Forcing folks dig implementation possibility is frustrating</technical_language>

Target:
public static ViewHighlighter newInstance() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { return new OverlayHighlighter(); } else { LogUtil.w(TAG, "Running on pre-JBMR2: View highlighting is not supported"); return new NoopHighlighter(); } }
Source:
<code>protected Function<Object, IterableWithMarker<Router>> markerToNextForArg0(Optional<Object> arg0) { String zone = arg0.isPresent() ? arg0.get().toString() : null; final RouterApi routerApi = api.getRouterExtensionForZone(zone).get(); return new Function<Object, IterableWithMarker<Router>>() { @SuppressWarnings("unchecked") @Override public IterableWithMarker<Router> apply(Object input) { return IterableWithMarker.class.cast(routerApi.listInDetail(marker(input.toString()))); } @Override public String toString() { <START> return "list()"; <END> } }; }</code><technical_language>Remove toString give a more descriptive result</technical_language>

Target:
protected Function<Object, IterableWithMarker<Router>> markerToNextForArg0(Optional<Object> arg0) { String zone = arg0.isPresent() ? arg0.get().toString() : null; final RouterApi routerApi = api.getRouterExtensionForZone(zone).get(); return new Function<Object, IterableWithMarker<Router>>() { @SuppressWarnings("unchecked") @Override public IterableWithMarker<Router> apply(Object input) { return IterableWithMarker.class.cast(routerApi.listInDetail(marker(input.toString()))); } @Override public String toString() { return "listRoutersInDetail()"; } }; }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { Timber.d("onCreate()"); super.onCreate(savedInstanceState); Bundle parameters = savedInstanceState; if (parameters == null) { parameters = getIntent().getExtras(); } mEditedModelFileName = parameters.getString(CardTemplateEditor.INTENT_MODEL_FILENAME); mCardList = parameters.getLongArray("cardList"); mIndex = parameters.getInt("index"); if (mEditedModelFileName != null) { Timber.d("onCreate() loading edited model from %s", mEditedModelFileName); mEditedModel = CardTemplateEditor.getTempModel(mEditedModelFileName); } if (mEditedModel != null && mIndex != -1) { Timber.d("onCreate() Previewer started with edited model and template index, displaying blank to preview formatting"); <START> mCurrentCard = getDummyCard(mEditedModel, mIndex); <END> if (mCurrentCard == null) { UIUtils.showSimpleSnackbar(this, R.string.invalid_template, false); finishWithoutAnimation(); return; } } if (mCurrentCard == null && (mCardList == null || mCardList.length == 0 || mIndex < 0 || mIndex > mCardList.length - 1)) { Timber.e("Previewer started with empty card list or invalid index"); finishWithoutAnimation(); return; } showBackIcon(); disableDrawerSwipe(); startLoadingCollection(); }</code><technical_language>getDummyCard() calls getCol(), supposed called onCollectionLoaded(), handling cases of loading mCurrentCard in places is readable IMO. move onCollectionLoaded()</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { Timber.d("onCreate()"); super.onCreate(savedInstanceState); mCardList = getIntent().getLongArrayExtra("cardList"); mIndex = getIntent().getIntExtra("index", -1); if (savedInstanceState != null){ mIndex = savedInstanceState.getInt("index", mIndex); mShowingAnswer = savedInstanceState.getBoolean("showingAnswer", mShowingAnswer); } if (mCardList.length == 0 || mIndex < 0 || mIndex > mCardList.length - 1) { Timber.e("Previewer started with empty card list or invalid index"); finishWithoutAnimation(); return; } showBackIcon(); disableDrawerSwipe(); startLoadingCollection(); }
Source:
<code>public void getClaimAsInstantWhenISODateStringThenReturnInstant() { <START> Instant expectedClaimValue = Instant.now(); <END> String claimName = "isoDate"; this.claims.put(claimName, expectedClaimValue.toString()); assertThat(this.claimAccessor.getClaimAsInstant(claimName)).isBetween( expectedClaimValue.minusSeconds(1), expectedClaimValue.plusSeconds(1)); }</code><technical_language>explicitly provide String for test, for example, 2011-12-03T10:15:30+01:00</technical_language>

Target:
public void getClaimAsInstantWhenISODateStringThenReturnInstant() { Instant expectedClaimValue = Instant.parse("2011-12-03T09:15:30Z"); String claimName = "isoDate"; this.claims.put(claimName, "2011-12-03T09:15:30Z"); assertThat(this.claimAccessor.getClaimAsInstant(claimName)).isBetween( expectedClaimValue.minusSeconds(1), expectedClaimValue.plusSeconds(1)); this.claims.put(claimName, "2011-12-03T10:15:30+01:00"); assertThat(this.claimAccessor.getClaimAsInstant(claimName)).isBetween( expectedClaimValue.minusSeconds(1), expectedClaimValue.plusSeconds(1)); this.claims.put(claimName, "2011-12-03T10:15:30+01:00[Europe/Paris]"); assertThat(this.claimAccessor.getClaimAsInstant(claimName)).isBetween( expectedClaimValue.minusSeconds(1), expectedClaimValue.plusSeconds(1)); }
Source:
<code>public void authenticateWithWrongAuthentication() throws SecurityException, SecurityProviderNotFoundException { when(provider.authenticate(authentication)).thenThrow(UnauthorisedException.class); manager.addProvider(provider); expected.expect(UnauthorisedException.class); <START> manager.authenticate(authentication); <END> verify(provider).authenticate(authentication); }</code><technical_language>wrap this in a try..</technical_language>

Target:
public void authenticateWithWrongAuthentication() throws SecurityException, SecurityProviderNotFoundException { when(provider.authenticate(authentication)).thenThrow(UnauthorisedException.class); manager.addProvider(provider); expected.expect(UnauthorisedException.class); try { manager.authenticate(authentication); } finally { verify(provider).authenticate(authentication); } }
Source:
<code>public void readData(SaveHandler handler, WorldInfo info, Map<String, NBTBase> propertyMap, NBTTagCompound tag) { DimensionManager.loadDimensionDataMap(tag.hasKey("DimensionData") ? tag.getCompoundTag("DimensionData") : null); if (tag.hasKey("DefaultFluidList", 9)) { PersistentRegistryManager.GameDataSnapshot snapshot = PersistentRegistryManager.takeSnapshot(); PersistentRegistryManager.GameDataSnapshot.Entry entry = new PersistentRegistryManager.GameDataSnapshot.Entry(); snapshot.entries.put(PersistentRegistryManager.FLUIDS, entry); NBTTagList fluidList = tag.getTagList("DefaultFluidList", 8); for (int id = 0; id < fluidList.tagCount(); id++) <START> entry.ids.put(new ResourceLocation(fluidList.getStringTagAt(id).toLowerCase()), id); <END> PersistentRegistryManager.injectSnapshot(snapshot, true, true); } }</code><technical_language>toLowerCase is missing Locale</technical_language>

Target:
public void readData(SaveHandler handler, WorldInfo info, Map<String, NBTBase> propertyMap, NBTTagCompound tag) { DimensionManager.loadDimensionDataMap(tag.hasKey("DimensionData") ? tag.getCompoundTag("DimensionData") : null); if (tag.hasKey("DefaultFluidList", 9)) { Map<ResourceLocation, ForgeRegistry.Snapshot> snapshots = RegistryManager.ACTIVE.takeSnapshot(true); ForgeRegistry.Snapshot snapshot = new ForgeRegistry.Snapshot(); snapshots.put(GameData.FLUIDS, snapshot); NBTTagList fluidList = tag.getTagList("DefaultFluidList", 8); for (int id = 0; id < fluidList.tagCount(); id++) snapshot.ids.put(new ResourceLocation(fluidList.getStringTagAt(id).toLowerCase(Locale.ENGLISH)), id); GameData.injectSnapshot(snapshots, true, true); } }
Source:
<code>public void setUp() throws Exception { Jdbi jdbi = Jdbi.create("jdbc:sqlite::memory:"); jdbi.installPlugin(new SQLitePlugin()); handle = jdbi.open(); handle.useTransaction(handle -> { <START> handle.execute("DROP TABLE IF EXISTS foo"); <END> handle.execute("CREATE TABLE foo(url URL);"); }); }</code><technical_language>I foo exist here, right, opens a unique in-memory db</technical_language>

Target:
public void setUp() throws Exception { Jdbi jdbi = Jdbi.create("jdbc:sqlite::memory:"); jdbi.installPlugin(new SQLitePlugin()); handle = jdbi.open(); handle.useTransaction(handle -> handle.execute("CREATE TABLE foo(url URL);")); }
Source:
<code>public AbstractMessageInterpolator(ResourceBundleLocator userResourceBundleLocator, ResourceBundleLocator contributorResourceBundleLocator, boolean cacheMessages) { this( userResourceBundleLocator, contributorResourceBundleLocator, Collections.emptySet(), Locale.getDefault(), cacheMessages ); <START> } <END></code><technical_language>a heads-up: removing this constructor is incompatible change for user classes extending this one</technical_language>

Target:
public AbstractMessageInterpolator(ResourceBundleLocator userResourceBundleLocator, ResourceBundleLocator contributorResourceBundleLocator, boolean cacheMessages) { this( userResourceBundleLocator, contributorResourceBundleLocator, Collections.emptySet(), Locale.getDefault(), new DefaultLocaleResolver(), cacheMessages ); }
Source:
<code>public void testReportDoneOncePerSchedule() throws InterruptedException { BusyLoopJob job = new BusyLoopJob(); EventCount eventCount = new EventCount(); job.addJobChangeListener(eventCount); try { for (int i = 0; i < 10000; i++) { job.schedule(); job.cancel(); } assertTrue(job.join(5000, null)); <START> Thread.sleep(100); <END> assertEquals("Job should be completed once per schedule.", eventCount.scheduledCount.get(), eventCount.doneCount.get()); } finally { job.cancelWithoutRelyingOnFramework = true; waitForCompletion(job); } }</code><technical_language>I thought of waiting for assertion. is higher delay is fine too. test failed of some runs I problematic</technical_language>

Target:
public void testReportDoneOncePerSchedule() throws InterruptedException { BusyLoopJob job = new BusyLoopJob(); EventCount eventCount = new EventCount(); job.addJobChangeListener(eventCount); try { for (int i = 0; i < 10000; i++) { job.schedule(); job.cancel(); } assertTrue(job.join(5000, null)); Thread.sleep(200); assertEquals("Job should be completed once per schedule.", eventCount.scheduledCount.get(), eventCount.doneCount.get()); } finally { job.cancelWithoutRelyingOnFramework = true; waitForCompletion(job); } }
Source:
<code>public HealthCheckResult(Collection<ProbeInfo> probesToCheck) { this.probes = probesToCheck; for (ProbeInfo probeInfo : probesToCheck) { <START> healthy = healthy && probeInfo.getStatus().isSuccess(); <END> } }</code><technical_language>healty = probes.stream().allMatch(p -> p.getStatus().isSuccess()); remove healthy field initialization</technical_language>

Target:
public HealthCheckResult(Collection<ProbeInfo> probesToCheck) { this.probes = probesToCheck; healthy = probes.stream().allMatch(p -> p.getStatus().isSuccess()); }
Source:
<code>public void test_unzipInMemory_zip() { ArrayByteSource source1 = ArrayByteSource.ofUtf8("Hello World").withFileName("TestFile1.txt"); ArrayByteSource source2 = ArrayByteSource.ofUtf8("Hello Planet").withFileName("TestFile2.txt"); ArrayByteSource zipFile = ZipUtils.zipInMemory(ImmutableList.of(source1, source2)).withFileName("Test.foo"); <START> ZipUtils.unzipInMemory(zipFile, (name, extracted) -> { <END> if (name.equals("TestFile1.txt")) { assertThat(extracted.getFileName()).hasValue("TestFile1.txt"); assertThat(extracted.readUtf8()).isEqualTo("Hello World"); } else if (name.equals("TestFile2.txt")) { assertThat(extracted.getFileName()).hasValue("TestFile2.txt"); assertThat(extracted.readUtf8()).isEqualTo("Hello Planet"); } else { fail("Unexpected file: " + name); } }); }</code><technical_language>If BiConsumer invoked this test pass</technical_language>

Target:
public void test_unzipInMemory_zip() { ArrayByteSource source1 = ArrayByteSource.ofUtf8("Hello World").withFileName("TestFile1.txt"); ArrayByteSource source2 = ArrayByteSource.ofUtf8("Hello Planet").withFileName("TestFile2.txt"); ArrayByteSource zipFile = ZipUtils.zipInMemory(ImmutableList.of(source1, source2)).withFileName("Test.foo"); AtomicInteger counter = new AtomicInteger(); ZipUtils.unzipInMemory(zipFile, (name, extracted) -> { counter.incrementAndGet(); if (name.equals("TestFile1.txt")) { assertThat(extracted.getFileName()).hasValue("TestFile1.txt"); assertThat(extracted.readUtf8()).isEqualTo("Hello World"); } else if (name.equals("TestFile2.txt")) { assertThat(extracted.getFileName()).hasValue("TestFile2.txt"); assertThat(extracted.readUtf8()).isEqualTo("Hello Planet"); } else { fail("Unexpected file: " + name); } }); assertThat(counter).hasValue(2); }
Source:
<code><START> public T injectItems( final T input, final Actionable mode, final IActionSource src ) <END> { if( mode == Actionable.SIMULATE ) { return null; } if( input != null ) { this.target.addPower( input.getStackSize() / this.channel.transferFactor() ); } return null; }</code><technical_language>![BLOCKER](<LINK_0> 'Severity: BLOCKER') Refactor this method return value. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public T injectItems( final T input, final Actionable mode, final IActionSource src ) { if( mode == Actionable.SIMULATE ) { return null; } if( input != null ) { this.target.addPower( input.getStackSize() / (double) this.channel.transferFactor() ); } return null; }
Source:
<code>public GenericShuffleProducer construct(ConstructArgs args) throws MyriaApiException { return new GenericShuffleProducer( null, getRealOperatorIds().toArray(new ExchangePairID[] {}), MyriaUtils.integerSetToIntArray( <START> args.getServer().getRandomWorkers(distributeFunction.getAllDestinations().size())), <END> distributeFunction); }</code><technical_language>I understand want pick a random subset of workers for load balancing, this getAllDestinations() returns explicit list of worker IDs in place</technical_language>

Target:
public GenericShuffleProducer construct(ConstructArgs args) throws MyriaApiException { return new GenericShuffleProducer( null, getRealOperatorIds().toArray(new ExchangePairID[] {}), Ints.toArray( args.getServer().getRandomWorkers(distributeFunction.getAllDestinations().size())), distributeFunction); }
Source:
<code>private void applyFilter() { SWTBotToolbarButton filterButton = fViewBot.toolbarButton(FILTER_ACTION); filterButton.click(); SWTBotShell shell = fBot.shell(FILTER_DIALOG_TITLE).activate(); SWTBot bot = shell.bot(); SWTBotTree treeBot = bot.tree(); bot.button(UNCHECK_ALL).click(); <START> Integer checked <END> = SWTBotUtils.getTreeCheckedItemCount(treeBot); assertEquals("default", 0, checked.intValue()); checkFilterTreeItems(bot, treeBot, SYSTEMD_PROCESS_NAME); checkFilterTreeItems(bot, treeBot, KTHREAD_PROCESS_NAME); checkFilterTreeItems(bot, treeBot, LTTNG_CONSUMER_PROCESS_NAME); bot.button(OK_BUTTON).click(); }</code><technical_language>int</technical_language>

Target:
private void applyFilter() { SWTBotToolbarButton filterButton = fViewBot.toolbarButton(FILTER_ACTION); filterButton.click(); SWTBotShell shell = fBot.shell(FILTER_DIALOG_TITLE).activate(); SWTBot bot = shell.bot(); SWTBotTree treeBot = bot.tree(); bot.button(UNCHECK_ALL).click(); int checked = SWTBotUtils.getTreeCheckedItemCount(treeBot); assertEquals("default", 0, checked); checkFilterTreeItems(bot, treeBot, SYSTEMD_PROCESS_NAME); checkFilterTreeItems(bot, treeBot, KTHREAD_PROCESS_NAME); checkFilterTreeItems(bot, treeBot, LTTNG_CONSUMER_PROCESS_NAME); bot.button(OK_BUTTON).click(); }
Source:
<code>public static void setupAccountAsNeeded(Context context) { try { AccountManager manager = AccountManager.get(context); Account[] accounts = manager.getAccountsByType(Constants.ACCOUNT_TYPE); if (accounts.length == 0) { Account account = new Account(Constants.ACCOUNT_NAME, Constants.ACCOUNT_TYPE); if (manager.addAccountExplicitly(account, null, null)) { ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 1); ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true); KeyserverSyncAdapterService.enableKeyserverSync(context); } else { Log.e(Constants.TAG, "Adding account failed!"); } } else { if (!Preferences.getPreferences(context).isKeyserverSyncInitialized()) { KeyserverSyncAdapterService.enableKeyserverSync(context); <START> } <END> } } catch (SecurityException e) { Log.e(Constants.TAG, "SecurityException when adding the account", e); Toast.makeText(context, R.string.reinstall_openkeychain, Toast.LENGTH_LONG).show(); } }</code><technical_language>Instead of this check introducing SYNC_KEYSERVER_SETUP, I prefer increase Constants.default.PREF_VERSION do KeyserverSyncAdapterService.enableKeyserverSync(context); in Preferences.upgradePreferences. I know, strictly speaking, enabling sync adapter is a new preference, upgrade mechanism, fits there</technical_language>

Target:
public static void setupAccountAsNeeded(Context context) { try { AccountManager manager = AccountManager.get(context); Account[] accounts = manager.getAccountsByType(Constants.ACCOUNT_TYPE); if (accounts.length == 0) { Account account = new Account(Constants.ACCOUNT_NAME, Constants.ACCOUNT_TYPE); if (manager.addAccountExplicitly(account, null, null)) { ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 1); ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true); KeyserverSyncAdapterService.enableKeyserverSync(context); } else { Log.e(Constants.TAG, "Adding account failed!"); } } } catch (SecurityException e) { Log.e(Constants.TAG, "SecurityException when adding the account", e); Toast.makeText(context, R.string.reinstall_openkeychain, Toast.LENGTH_LONG).show(); } }