auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void handleError(final HttpCommand command, final HttpResponse response) { Exception exception = null; try { switch (response.getStatusCode()) { case 400: case 405: exception = new IllegalArgumentException(response.getMessage(), exception); break; case 401: exception = new AuthorizationException("This request requires authentication.", exception); break; case 402: case 409: exception = new IllegalStateException(response.getMessage(), exception); break; case 404: case 410: if (!command.getCurrentRequest().getMethod().equals("DELETE")) exception = new ResourceNotFoundException(response.getMessage(), exception); break; case 413: case 503: if (response.getMessage().equals("OK")) exception = new HttpResponseException("The OneAndOne team is currently carrying out maintenance.", command, response); else exception = new InsufficientResourcesException(response.getMessage(), exception); break; <START> } <END> } finally { closeQuietly(response.getPayload()); command.setException(exception); } }</code><technical_language>exception set y default, setting a null if of codes is returned. cover case</technical_language>

Target:
public void handleError(final HttpCommand command, final HttpResponse response) { Exception exception = null; try { switch (response.getStatusCode()) { case 400: case 405: exception = new IllegalArgumentException(response.getMessage(), exception); break; case 401: exception = new AuthorizationException("This request requires authentication.", exception); break; case 402: case 409: exception = new IllegalStateException(response.getMessage(), exception); break; case 404: case 410: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(response.getMessage(), exception); } break; case 413: case 503: if (response.getMessage().equals("OK")) { exception = new HttpResponseException("The OneAndOne team is currently carrying out maintenance.", command, response); } else { exception = new InsufficientResourcesException(response.getMessage(), exception); } break; default: exception = new HttpResponseException("A generic error occured.", command, response); break; } } finally { closeQuietly(response.getPayload()); command.setException(exception); } }
Source:
<code>private boolean collectElementData(String id, Field field) { idByField.put(field, id); if (templateRoot != null) { Optional<Element> element = Optional .ofNullable(templateRoot.getElementById(id)); Optional<String> tagName = element .map(org.jsoup.nodes.Element::tagName); if (element.isPresent()) { <START> tagById.put(id, tagName.get()); <END> fetchAttributes(id, element.get().attributes()); } return tagName.isPresent(); } return true; }</code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') Call "tagName.isPresent()" accessing value. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private boolean collectElementData(String id, Field field) { idByField.put(field, id); if (templateRoot != null) { Optional<Element> element = Optional .ofNullable(templateRoot.getElementById(id)); Optional<String> tagName = element .map(org.jsoup.nodes.Element::tagName); if (element.isPresent()) { tagById.put(id, tagName.get()); fetchAttributes(id, element.get().attributes()); } return element.isPresent(); } return true; }
Source:
<code>public void execute(TinkerpopGraphManager graphManager) throws IOException { DataStoreOperations dataStoreOperations = new DataStoreOperations( graphManager, new DeafListener(), new GremlinEntityFetcher(), null, new Neo4jIndexHandler(graphManager) ); Vres vres = dataStoreOperations.loadVres(); Neo4jIndexHandler indexHandler = new Neo4jIndexHandler(graphManager); ObjectMapper mapper = new ObjectMapper(); GraphTraversalSource traversalSource = graphManager.getGraph().traversal(); traversalSource .V() .has("types") .forEachRemaining(vertex -> { try { String[] types = mapper.readValue(vertex.<String>value("types"), String[].class); for (String type : types) { if (TYPES_TO_IGNORE.contains(type)) { continue; } if (vres.getCollectionForType(type).isPresent()) { VertexProperty<String> timIdProp = vertex.property("tim_id"); if (timIdProp.isPresent()) { <START> UUID timId = UUID.fromString(timIdProp.value()); <END> indexHandler.addToIdIndex(timId, vertex); } else { LOG.error("Vertex with id '{}' has no 'tim_id' property", vertex.id()); } } else { LOG.error("'{}' is not a known entity type.", type); } } } catch (IOException e) { LOG.error("And exception occurred while indexing vertex with vertex id '{}'.", vertex.id()); } }); }</code><technical_language>this throw</technical_language>

Target:
public void execute(TinkerpopGraphManager graphManager) throws IOException { DataStoreOperations dataStoreOperations = new DataStoreOperations( graphManager, new DeafListener(), new GremlinEntityFetcher(), null, new Neo4jIndexHandler(graphManager) ); Vres vres = dataStoreOperations.loadVres(); Neo4jIndexHandler indexHandler = new Neo4jIndexHandler(graphManager); ObjectMapper mapper = new ObjectMapper(); GraphTraversalSource traversalSource = graphManager.getGraph().traversal(); traversalSource .V() .has("types") .forEachRemaining(vertex -> { try { String[] types = mapper.readValue(vertex.<String>value("types"), String[].class); for (String type : types) { if (TYPES_TO_IGNORE.contains(type)) { continue; } if (vres.getCollectionForType(type).isPresent()) { VertexProperty<String> timIdProp = vertex.property("tim_id"); if (timIdProp.isPresent()) { try { UUID timId = UUID.fromString(timIdProp.value()); indexHandler.insertIntoIdIndex(timId, vertex); } catch (IllegalArgumentException e) { LOG.error("'{}' is not a valid id", timIdProp.value()); } } else { LOG.error("Vertex with id '{}' has no 'tim_id' property", vertex.id()); } } else { LOG.error("'{}' is not a known entity type.", type); } } } catch (IOException e) { LOG.error("And exception occurred while indexing vertex with vertex id '{}'.", vertex.id()); } }); }
Source:
<code>public GroupCreateRequest(User creator, Group group) { super(); mCreator = creator; <START> mGroup = group; <END> }</code><technical_language>add null checks</technical_language>

Target:
public GroupCreateRequest(User creator, Group group) { super(); Objects.requireNonNull(creator); Objects.requireNonNull(group); mCreator = creator; mGroup = group; }
Source:
<code><START> private synchronized void instantiateInvalidType(Environment env) { <END> if(invalidType != UNINITIALIZED) { return; } @SuppressWarnings("LocalVariableHidesMemberVariable") String fqcn = this.fqcn.getFQCN(); try { if("auto".equals(fqcn)) { invalidType = null; } else if("ms.lang.ClassType".equals(fqcn)) { invalidType = new Mixed[]{this}; } else { invalidType = new Mixed[types.size()]; for(int i = 0; i < invalidType.length; i++) { if(NativeTypeList.getNativeTypeList().contains(this.fqcn)) { invalidType[i] = NativeTypeList.getInvalidInstanceForUse(this.fqcn); } else { ObjectDefinitionTable odt = env.getEnv(CompilerEnvironment.class).getObjectDefinitionTable(); ObjectDefinition od = odt.get(this.fqcn); invalidType[i] = new UserObject(Target.UNKNOWN, null, env, od, null); } } } } catch (ClassNotFoundException | ObjectDefinitionNotFoundException ex) { throw new Error(ex); } }</code><technical_language>This is heavy. a double checked locking paradigm: java if(invalidType == UNINITIALIZED) { synchronized(this) { if(invalidType == UNININTIALIZED) { // Do method body } } } This reads synchronized, time this is called. that, non-blocking</technical_language>

Target:
private void instantiateInvalidType(Environment env) { if(this.invalidType != UNINITIALIZED) { return; } synchronized(this) { if(this.invalidType != UNINITIALIZED) { return; } @SuppressWarnings("LocalVariableHidesMemberVariable") String fqcn = this.fqcn.getFQCN(); try { Mixed[] invalidType; if("auto".equals(fqcn)) { invalidType = null; } else if("ms.lang.ClassType".equals(fqcn)) { invalidType = new Mixed[]{this}; } else { invalidType = new Mixed[this.types.size()]; for(int i = 0; i < invalidType.length; i++) { if(NativeTypeList.getNativeTypeList().contains(this.fqcn)) { invalidType[i] = NativeTypeList.getInvalidInstanceForUse(this.fqcn); } else { ObjectDefinitionTable odt = env.getEnv(CompilerEnvironment.class).getObjectDefinitionTable(); ObjectDefinition od = odt.get(this.fqcn); invalidType[i] = new UserObject(Target.UNKNOWN, null, env, od, null); } } } this.invalidType = invalidType; } catch (ClassNotFoundException | ObjectDefinitionNotFoundException ex) { throw new Error(ex); } } }
Source:
<code>private void fireDataChangedEvents(final String path, Set<IZkDataListenerEntry> listeners, final OptionalLong notificationTime, boolean pathExists) { try { final ZkPathStatRecord pathStatRecord = new ZkPathStatRecord(path); for (final IZkDataListenerEntry listener : listeners) { _eventThread.send(new ZkEventThread.ZkEvent( "Data of " + path + " changed sent to " + listener.getDataListener() + " prefetch data: " + listener.isPrefetchData()) { @Override public void run() throws Exception { if (!pathStatRecord.pathChecked()) { <START> if (!pathExists) { <END> pathStatRecord.recordPathStat(getStat(path, false), notificationTime); } else { pathStatRecord.recordPathStat(getStat(path, true, true), notificationTime); } } if (!pathStatRecord.pathExists()) { listener.getDataListener().handleDataDeleted(path); } else { Object data = null; if (listener.isPrefetchData()) { if (LOG.isDebugEnabled()) { LOG.debug("Prefetch data for path: {}", path); } try { data = readData(path, null, true); } catch (ZkNoNodeException e) { LOG.warn("Prefetch data for path: failed.", path, e); listener.getDataListener().handleDataDeleted(path); return; } } listener.getDataListener().handleDataChange(path, data); } } }); } } catch (Exception e) { LOG.error("Failed to fire data changed event for path: {}", path, e); } }</code><technical_language>Put getStat call recordPathStat parameter list is longer clean. Please create a local var for state pass record method</technical_language>

Target:
private void fireDataChangedEvents(final String path, Set<IZkDataListenerEntry> listeners, final OptionalLong notificationTime, boolean pathExists) { try { final ZkPathStatRecord pathStatRecord = new ZkPathStatRecord(path); for (final IZkDataListenerEntry listener : listeners) { _eventThread.send(new ZkEventThread.ZkEvent( "Data of " + path + " changed sent to " + listener.getDataListener() + " prefetch data: " + listener.isPrefetchData()) { @Override public void run() throws Exception { if (!pathStatRecord.pathChecked()) { Stat stat = null; if (!pathExists) { stat = getStat(path, false); } else { stat = installWatchOnlyPathExist(path); } pathStatRecord.recordPathStat(stat, notificationTime); } if (!pathStatRecord.pathExists()) { listener.getDataListener().handleDataDeleted(path); } else { Object data = null; if (listener.isPrefetchData()) { if (LOG.isDebugEnabled()) { LOG.debug("Prefetch data for path: {}", path); } try { data = readData(path, null, true); } catch (ZkNoNodeException e) { LOG.warn("Prefetch data for path: failed.", path, e); listener.getDataListener().handleDataDeleted(path); return; } } listener.getDataListener().handleDataChange(path, data); } } }); } } catch (Exception e) { LOG.error("Failed to fire data changed event for path: {}", path, e); } }
Source:
<code>public void tearDown() throws Exception { super.tearDown(); <START> mIccRecords.dispose(); <END> }</code><technical_language>is this removed</technical_language>

Target:
public void tearDown() throws Exception { super.tearDown(); }
Source:
<code>public void setupProperties() { super.setupProperties(); name.setValue(""); applicationName.setValue(""); oAuthMethod.setPossibleValues(OAuthMethod.values()); oAuthMethod.setValue(OAuthMethod.InstalledApplicationWithIdAndSecret); accessToken.setValue(""); clientId.setValue(""); clientSecret.setValue(""); clientSecretFile.setValue(""); serviceAccountFile.setValue(""); dsPath = ".credentials/talend-googledrive"; try { <START> dsPath = Paths.get(System.getProperty("user.home"), ".credentials/talend-googledrive").toAbsolutePath().toString(); <END> dsPath = dsPath.replace("\\", "/"); } catch (Exception e) { } datastorePath.setValue(dsPath); useProxy.setValue(false); proxyHost.setValue("127.0.0.1"); proxyPort.setValue(8087); useSSL.setValue(false); sslAlgorithm.setValue("SSL"); }</code><technical_language>Ok 'user.home' overloaded if job is executed account home. -Duser.home="/what/you/want/" is possible</technical_language>

Target:
public void setupProperties() { super.setupProperties(); name.setValue(""); applicationName.setValue(""); oAuthMethod.setPossibleValues(OAuthMethod.values()); oAuthMethod.setValue(OAuthMethod.InstalledApplicationWithIdAndSecret); accessToken.setValue(""); clientId.setValue(""); clientSecret.setValue(""); clientSecretFile.setValue(""); serviceAccountFile.setValue(""); dsPath = Paths.get(System.getProperty("user.home", "."), PATH_CREDENTIALS_TALEND_GOOGLEDRIVE); datastorePath.setValue(dsPath.toAbsolutePath().toString()); useProxy.setValue(false); proxyHost.setValue("127.0.0.1"); proxyPort.setValue(8087); useSSL.setValue(false); sslAlgorithm.setValue("SSL"); }
Source:
<code>protected void sendReplies(Object processorResult, Message message) { Object replyChannelHeader = null; if (message != null) { replyChannelHeader = message.getHeaders().getReplyChannel(); } <START> Object replyChannel = super.getOutputChannel(); <END> if (super.getOutputChannel() == null) { replyChannel = replyChannelHeader; } Assert.notNull(replyChannel, "no outputChannel or replyChannel header available"); if (processorResult instanceof Iterable<?> && shouldSendMultipleReplies((Iterable<?>) processorResult)) { for (Object next : (Iterable<?>) processorResult) { this.sendReplyMessage(next, replyChannel); } } else { this.sendReplyMessage(processorResult, replyChannel); } }</code><technical_language>need explicit super. in places</technical_language>

Target:
protected void sendReplies(Object processorResult, Message message) { Object replyChannelHeader = null; if (message != null) { replyChannelHeader = message.getHeaders().getReplyChannel(); } if (getOutputChannelName() != null) { synchronized (this) { if (getOutputChannelName() != null) { try { setOutputChannel(getBeanFactory().getBean(getOutputChannelName(), MessageChannel.class)); setOutputChannelName(null); } catch (BeansException e) { throw new DestinationResolutionException("Failed to look up MessageChannel with name '" + getOutputChannelName() + "' in the BeanFactory."); } } } } Object replyChannel = getOutputChannel(); if (replyChannel == null) { replyChannel = replyChannelHeader; } Assert.notNull(replyChannel, "no outputChannel or replyChannel header available"); if (processorResult instanceof Iterable<?> && shouldSendMultipleReplies((Iterable<?>) processorResult)) { for (Object next : (Iterable<?>) processorResult) { this.sendReplyMessage(next, replyChannel); } } else { this.sendReplyMessage(processorResult, replyChannel); } }
Source:
<code>private void initAudioTrackIndexIfNeeded() { if (!mProto.hasAudioTrackIndex()) { mProto = <START> mProto.toBuilder().setAudioTrackIndex(mProto.getAudioTrackIndex()).build(); <END> } }</code><technical_language>This wrong, is blindly setting Index zero, if track list is empty. call .setAudioTrackIndex(audioPids.isEmpty() ? -1 : 0) get errored getAudioPid is called is trackList empty in this case? If is empty need a fix for this</technical_language>

Target:
private void initAudioTrackIndexIfNeeded() { if (!mProto.hasAudioTrackIndex()) { selectAudioTrack(mProto.getAudioTrackIndex()); } }
Source:
<code>private List<ChangeLogSet<? extends Entry>> getChanges(Run<?,?> run) { if(run instanceof AbstractBuild) return ((AbstractBuild<?,?>) run).getChangeSets(); else if(run instanceof WorkflowRun) <START> return ((WorkflowRun)run).getChangeSets(); <END> else throw new IllegalArgumentException("Unsupported job type "+run.getClass().getName()); }</code><technical_language>Pending this aspect of [JENKINS-24141](<LINK_0>, I recommend for a getChangeSets method reflection, adding (even optional) plugin dependency workflow-job</technical_language>

Target:
private static List<ChangeLogSet<? extends Entry>> getChanges(Run<?,?> run) { if(run instanceof AbstractBuild) { return ((AbstractBuild<?,?>) run).getChangeSets(); } else if(run == null) { throw new IllegalStateException("run cannot be null!"); } else { return getChangesUsingReflection(run); } }
Source:
<code>public static void startNewConv(){ boolean match = false; System.out.println(getConvReceiver((String)Global.list.getSelectedValue()).getPhoneNumber()); for(int i = 0; i < currentConvs.size(); i++){ if(getConvReceiver((String)Global.list.getSelectedValue()).getFirstName().equals(currentConvs.get(i).getFirstName()) && getConvReceiver((String)Global.list.getSelectedValue()).getPhoneNumber().equals(currentConvs.get(i).getPhoneNumber())){ <START> match = true; <END> } } if(!match){ currentConvs.add(getConvReceiver((String)Global.list.getSelectedValue())); createTab(getConvReceiver((String)Global.list.getSelectedValue())); } }</code><technical_language>add a break well</technical_language>

Target:
public static void startNewConv(){ boolean match = false; System.out.println(getConvReceiver((String)Global.list.getSelectedValue()).getPhoneNumber()); for(int i = 0; i < currentConvs.size(); i++){ if(getConvReceiver((String)Global.list.getSelectedValue()).getFirstName().equals(currentConvs.get(i).getFirstName()) && getConvReceiver((String)Global.list.getSelectedValue()).getPhoneNumber().equals(currentConvs.get(i).getPhoneNumber())){ match = true; break; } } if(!match){ currentConvs.add(getConvReceiver((String)Global.list.getSelectedValue())); createTab(getConvReceiver((String)Global.list.getSelectedValue())); } }
Source:
<code>public void contains_customEqualMethod() { RealmCollection<CustomMethods> collection = createCustomMethodsCollection(realm, collectionClass); <START> CustomMethods unmanaged = new CustomMethods("Child0"); <END> assertTrue(collection.contains(unmanaged)); }</code><technical_language>test element? testing Child + TEST_SIZE - 1 (checking iterators)</technical_language>

Target:
public void contains_customEqualMethod() { RealmCollection<CustomMethods> collection = createCustomMethodsCollection(realm, collectionClass); assertTrue(collection.contains(new CustomMethods("Child0"))); assertTrue(collection.contains(new CustomMethods("Child" + (TEST_SIZE - 1)))); assertFalse(collection.contains(new CustomMethods("Child" + TEST_SIZE))); }
Source:
<code>public void updatePatientNoAccessReturnsForbiddenCode() throws ComponentLookupException, XWikiRestException { when(this.repository.getPatientByExternalId(this.eid)).thenReturn(this.patient); when(this.access.hasAccess(Right.EDIT, null, null)).thenReturn(false); Response response = this.component.updatePatient("json", this.eid); <START> verify(this.logger).debug("Updating patient record with external ID via REST", this.eid); <END> verify(this.logger).debug("Edit access denied to user on patient record [{}]", null, this.patient.getId()); assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus()); }</code><technical_language>If method expects exception, this line executed</technical_language>

Target:
public void updatePatientNoAccessReturnsForbiddenCode() throws ComponentLookupException { when(this.access.hasAccess(Right.EDIT, this.userReference, this.patientReference)).thenReturn(false); Response response = this.component.updatePatient("json", this.eid); verify(this.logger).debug("Edit access denied to user on patient record [{}]", null, this.patient.getId()); assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus()); }
Source:
<code>public int hashCode() { return Objects.hash( snapshotId, clusterId, volumeId, snapshotName, status, description, <START> status <END> ); }</code><technical_language>status repeated twice. I guess in original code too</technical_language>

Target:
public int hashCode() { return Objects.hash( snapshotId, clusterId, volumeId, snapshotName, description, status ); }
Source:
<code>void sendPage(String page, HttpServerRequest request, HttpServerResponse response) throws HttpAuthenticationException { if (response.forward(page)) { return; <START> } <END> HttpScope application = request.getScope(Scope.APPLICATION); if (application != null && application.supportsResources()) { try (InputStream pageStream = application.getResource(page)) { if (pageStream != null) { OutputStream responseStream = response.getOutputStream(); if (responseStream != null) { byte[] content = new byte[1024]; int length; while ((length = pageStream.read(content)) > 0) { responseStream.write(content, 0, length); } return; } } } catch (IOException e) { throw new HttpAuthenticationException(e); } } sendRedirect(response, contextPath + page); }</code><technical_language>I needed remove this need cope a direct resource access sendPage end of sendPage fall sendRedirect I need a URI point</technical_language>

Target:
void sendPage(String page, HttpServerRequest request, HttpServerResponse response) throws HttpAuthenticationException { if (response.forward(page)) { return; } HttpScope application = request.getScope(Scope.APPLICATION); if (application != null && application.supportsResources()) { try (InputStream pageStream = application.getResource(page)) { if (pageStream != null) { OutputStream responseStream = response.getOutputStream(); if (responseStream != null) { byte[] content = new byte[1024]; int length; while ((length = pageStream.read(content)) > 0) { responseStream.write(content, 0, length); } return; } } } catch (IOException e) { throw new HttpAuthenticationException(e); } } URI requestURI = request.getRequestURI(); StringBuilder sb = new StringBuilder(); sb.append(requestURI.getScheme()); sb.append("://"); sb.append(requestURI.getHost()); sb.append(':').append(requestURI.getPort()); sb.append(contextPath); sb.append(page); sendRedirect(response, sb.toString()); }
Source:
<code>private static List<String> getSimilarTables(User user, String tableName, Iterable<TableInfo> tables) { <START> LevenshteinDistance levenshteinDistance = new LevenshteinDistance(); ArrayList<String> candidates = new ArrayList<>(); for (TableInfo table : tables) { if (user.hasAnyPrivilege(Privilege.Clazz.TABLE, table.ident().fqn())) { String candidate = table.ident().name(); if (levenshteinDistance.getDistance(tableName, candidate) > 0.7f || tableName.equalsIgnoreCase(candidate)) { candidates.add(candidate); } } } return candidates; <END> }</code><technical_language>sounds nice! users overwhelmed hints. add a change log entry for this schema hints</technical_language>

Target:
private static List<String> getSimilarTables(User user, String tableName, Iterable<TableInfo> tables) { LevenshteinDistance levenshteinDistance = new LevenshteinDistance(); ArrayList<Candidate> candidates = new ArrayList<>(); for (TableInfo table : tables) { if (user.hasAnyPrivilege(Privilege.Clazz.TABLE, table.ident().fqn())) { String candidate = table.ident().name(); float score = levenshteinDistance.getDistance(tableName.toLowerCase(Locale.ENGLISH), candidate.toLowerCase(Locale.ENGLISH)); if (score > 0.7f) { candidates.add(new Candidate(score, candidate)); } } } candidates.sort(Comparator.comparing((Candidate x) -> x.score).reversed()); return candidates.stream() .limit(5) .map(x -> x.name) .collect(Collectors.toList()); }
Source:
<code>public void getListOfObjectsAsSingleOnlyInitialValue() { final TestSubscriber<Changes> changesTestSubscriber = new TestSubscriber<Changes>(); storIOContentResolver .observeChangesOfUri(TestItem.CONTENT_URI) .take(1) .subscribe(changesTestSubscriber); TestItem testItemToInsert = TestItem.create(null, "value"); contentResolver.insert(TestItem.CONTENT_URI, testItemToInsert.toContentValues()); final TestSubscriber<List<TestItem>> listTestSubscriber = new TestSubscriber<List<TestItem>>(); storIOContentResolver .get() .listOfObjects(TestItem.class) .withQuery(Query.builder() .uri(TestItem.CONTENT_URI) .build()) .prepare() .asRxSingle() .subscribe(listTestSubscriber); listTestSubscriber.awaitTerminalEvent(60, SECONDS); listTestSubscriber.assertNoErrors(); assertThat(listTestSubscriber.getOnNextEvents()).hasSize(1); <START> assertThat(testItemToInsert.equalsWithoutId(listTestSubscriber.getOnNextEvents().get(0).get(0))) <END> .isTrue(); changesTestSubscriber.awaitTerminalEvent(60, SECONDS); changesTestSubscriber.assertNoErrors(); changesTestSubscriber.assertValues(Changes.newInstance(TestItem.CONTENT_URI)); }</code><technical_language>please check list of objects size == 1</technical_language>

Target:
public void getListOfObjectsAsSingleOnlyInitialValue() { final TestSubscriber<Changes> changesTestSubscriber = new TestSubscriber<Changes>(); storIOContentResolver .observeChangesOfUri(TestItem.CONTENT_URI) .take(1) .subscribe(changesTestSubscriber); TestItem testItemToInsert = TestItem.create(null, "value"); contentResolver.insert(TestItem.CONTENT_URI, testItemToInsert.toContentValues()); final TestSubscriber<List<TestItem>> listTestSubscriber = new TestSubscriber<List<TestItem>>(); storIOContentResolver .get() .listOfObjects(TestItem.class) .withQuery(Query.builder() .uri(TestItem.CONTENT_URI) .build()) .prepare() .asRxSingle() .subscribe(listTestSubscriber); listTestSubscriber.awaitTerminalEvent(60, SECONDS); listTestSubscriber.assertNoErrors(); List<List<TestItem>> listOfObjects = listTestSubscriber.getOnNextEvents(); assertThat(listOfObjects).hasSize(1); assertThat(listTestSubscriber.getOnNextEvents()).hasSize(1); assertThat(testItemToInsert.equalsWithoutId(listTestSubscriber.getOnNextEvents().get(0).get(0))) .isTrue(); changesTestSubscriber.awaitTerminalEvent(60, SECONDS); changesTestSubscriber.assertNoErrors(); changesTestSubscriber.assertValues(Changes.newInstance(TestItem.CONTENT_URI)); }
Source:
<code><START> private void loadImplementations() { <END> ServiceLoader<DirectorySpi> loader = ServiceLoader.load(DirectorySpi.class); for (DirectorySpi implementation : loader) { implementations.add(implementation); log.info( "Loaded directory implementation \"" + implementation.getClass().getName() + "\"." ); } }</code><technical_language>in separate directory classpath? is easier maintain externally</technical_language>

Target:
private void loadImplementations() { ServiceLoader<DirectorySpi> loader = ServiceLoader.load(DirectorySpi.class); for (DirectorySpi implementation : loader) { implementations.put(implementation.getType(), implementation); log.info( "Loaded directory service implementation \"" + implementation.getType() + "\"." ); } }
Source:
<code>protected Object doGetValue(Object columnElement, Object rowElement, INattableModelManager tableManager) { final List<Object> objects = organizeAndResolvedObjects(columnElement, rowElement, null); final EObject eobject = (EObject) objects.get(0); final EOperation operation = (EOperation) objects.get(1); if (eobject.eClass().getEAllOperations().contains(operation)) { try { return eobject.eInvoke(operation, null); } catch (InvocationTargetException e) { <START> e.printStackTrace(); <END> } } return NOT_AVALAIBLE; }</code><technical_language>I assume is operation is implemented... In this case i return a string : "Not Implemented"</technical_language>

Target:
protected Object doGetValue(Object columnElement, Object rowElement, INattableModelManager tableManager) { final List<Object> objects = organizeAndResolvedObjects(columnElement, rowElement, null); final EObject eobject = (EObject) objects.get(0); final EOperation operation = (EOperation) objects.get(1); if (eobject.eClass().getEAllOperations().contains(operation)) { try { return eobject.eInvoke(operation, null); } catch (InvocationTargetException e) { Activator.log.error(NOT_IMPLEMENTED_MESSAGE, e); } } return NOT_AVALAIBLE; }
Source:
<code>private String getTransactionListStr(List<TransactionId> transactions) { StringBuilder transStrs = new StringBuilder(); for (TransactionId transactionId : transactions) { <START> transStrs.append(String.format("Tranaction Id [%s] Comment [%s]\n", transactionId.getId(), <END> TransactionManager.getComment(transactionId.getId()))); } return transStrs.toString(); }</code><technical_language>limit number of rows dialog a reasonable size</technical_language>

Target:
private String getTransactionListStr(List<TransactionId> transactions) { StringBuilder transStrs = new StringBuilder(); int count = 1; for (TransactionId transactionId : transactions) { transStrs.append(String.format("Tranaction Id [%s] Comment [%s]\n", transactionId, TransactionManager.getComment(transactionId))); if (count++ > 30) { transStrs.append("(truncated at 25)..."); break; } } return transStrs.toString(); }
Source:
<code>public StyledString <START> buildTextFromEventIndex(int <END> index, ITaskAttachment attachment) { StyledString text = new StyledString(); switch (index) { case 0: if (AttachmentUtil.isContext(attachment)) { text.append("Task_Context"); } else if (attachment.isPatch()) { text.append("Patch"); } else { text.append(" " + attachment.getFileName()); } break; case 1: text.append(attachment.getDescription()); break; case 2: Long length = attachment.getLength(); if (length < 0) { text.append("-"); } text.append(sizeFormatter.format(length)); break; case 3: String autherText = (attachment.getAuthor() != null) ? attachment.getAuthor().toString() : ""; String[] autherPart = autherText.split(" <"); text.append(autherPart[0] + " ", StyledString.COUNTER_STYLER); if (autherPart.length > 1) { text.append("<" + autherPart[1], StyledString.COUNTER_STYLER); } break; case 4: text.append((attachment.getCreationDate() != null) ? EditorUtil.formatDateTime(attachment.getCreationDate()) : ""); break; case 5: text.append(getAttachmentId(attachment)); break; default: text.append("unrecognized column"); break; } return text; }</code><technical_language>method order closer previous revision, gerrit diffs match them</technical_language>

Target:
public StyledString buildTextFromEventIndex(int index, ITaskAttachment attachment) { StyledString text = new StyledString(); switch (index) { case 0: if (AttachmentUtil.isContext(attachment)) { text.append(Messages.AttachmentTableLabelProvider_Task_Context); } else if (attachment.isPatch()) { text.append(Messages.AttachmentTableLabelProvider_Patch); } else { text.append(" " + attachment.getFileName()); } break; case 1: text.append(attachment.getDescription()); break; case 2: Long length = attachment.getLength(); if (length < 0) { text.append("-"); } text.append(sizeFormatter.format(length)); break; case 3: String autherText = (attachment.getAuthor() != null) ? attachment.getAuthor().toString() : ""; String[] autherPart = autherText.split(" <"); text.append(autherPart[0] + " ", StyledString.COUNTER_STYLER); if (autherPart.length > 1) { text.append("<" + autherPart[1], StyledString.COUNTER_STYLER); } break; case 4: text.append((attachment.getCreationDate() != null) ? EditorUtil.formatDateTime(attachment.getCreationDate()) : ""); break; case 5: text.append(getAttachmentId(attachment)); break; default: text.append("unrecognized column"); break; } return text; }
Source:
<code>protected BaseVariant getBaseVariant() { LibraryExtension libraryExtension = (LibraryExtension) getAndroidExtension(); Optional<LibraryVariant> baseVariantOptional = libraryExtension .getLibraryVariants() .stream() <START> .filter(i -> i.getName().equals(getName())) <END> .findFirst(); Preconditions.checkArgument(baseVariantOptional.isPresent()); return baseVariantOptional.get(); }</code><technical_language>rename i more meaningful</technical_language>

Target:
protected BaseVariant getBaseVariant() { LibraryExtension libraryExtension = (LibraryExtension) getAndroidExtension(); Optional<LibraryVariant> baseVariantOptional = libraryExtension .getLibraryVariants() .stream() .filter(variant -> variant.getName().equals(getName())) .findFirst(); Preconditions.checkArgument(baseVariantOptional.isPresent()); return baseVariantOptional.get(); }
Source:
<code>private Document createDocument() { Document document = null; try { DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder(); document = documentBuilder.newDocument(); } catch (ParserConfigurationException pce) { <START> pce.printStackTrace(); <END> } return document; }</code><technical_language>dont do this exception propagated a error reporting generate jacoco report due .... methods static methods</technical_language>

Target:
private static Document createDocument() throws ParserConfigurationException { Document document = null; DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder(); document = documentBuilder.newDocument(); return document; }
Source:
<code>public void addWriteNotificationLog(AcidWriteEvent acidWriteEvent) throws MetaException { Connection dbConn = null; try { try { lockInternal(); dbConn = getDbConn(Connection.TRANSACTION_READ_COMMITTED); MetaStoreListenerNotifier.notifyEventWithDirectSql(transactionalListeners, EventMessage.EventType.ACID_WRITE, acidWriteEvent, dbConn, sqlGenerator); LOG.debug("Going to commit"); dbConn.commit(); return; } catch (SQLException e) { LOG.debug("Going to rollback"); rollbackDBConn(dbConn); if (isDuplicateKeyError(e)) { <START> if (waitForRetry("allocateTableWriteIds(" + acidWriteEvent + ")", e.getMessage())) { <END> throw new RetryException(); } retryNum = 0; throw new MetaException(e.getMessage()); } checkRetryable(dbConn, e, "allocateTableWriteIds(" + acidWriteEvent + ")"); throw new MetaException("Unable to update transaction database " + StringUtils.stringifyException(e)); } finally{ closeDbConn(dbConn); unlockInternal(); } } catch (RetryException e) { addWriteNotificationLog(acidWriteEvent); } }</code><technical_language>Incorrect method name. addWriteNotificationLog</technical_language>

Target:
public void addWriteNotificationLog(AcidWriteEvent acidWriteEvent) throws MetaException { Connection dbConn = null; try { try { lockInternal(); dbConn = getDbConn(Connection.TRANSACTION_READ_COMMITTED); MetaStoreListenerNotifier.notifyEventWithDirectSql(transactionalListeners, EventMessage.EventType.ACID_WRITE, acidWriteEvent, dbConn, sqlGenerator); LOG.debug("Going to commit"); dbConn.commit(); return; } catch (SQLException e) { LOG.debug("Going to rollback"); rollbackDBConn(dbConn); if (isDuplicateKeyError(e)) { if (waitForRetry("addWriteNotificationLog(" + acidWriteEvent + ")", e.getMessage())) { throw new RetryException(); } retryNum = 0; throw new MetaException(e.getMessage()); } checkRetryable(dbConn, e, "addWriteNotificationLog(" + acidWriteEvent + ")"); throw new MetaException("Unable to add write notification event " + StringUtils.stringifyException(e)); } finally{ closeDbConn(dbConn); unlockInternal(); } } catch (RetryException e) { addWriteNotificationLog(acidWriteEvent); } }
Source:
<code>public static boolean isRetryableException(Exception exception) { if (exception == null) { <START> throw new IllegalArgumentException("exception cannot be null."); <END> } if (exception instanceof EventHubException) { return ((EventHubException) exception).getIsTransient(); } return false; }</code><technical_language>Replace Objects.requireNotNull</technical_language>

Target:
public static boolean isRetryableException(Exception exception) { if (exception == null) { throw new IllegalArgumentException("exception cannot be null"); } if (exception instanceof EventHubException) { return ((EventHubException) exception).getIsTransient(); } return false; }
Source:
<code>public void getThreadData() throws Throwable { for (int i = 0; i < 5; i++) { SyncUtil.addBreakpoint(SOURCE_NAME + ":" + getLineForTag("LINE_MAIN_AFTER_THREAD_START")); <START> SyncUtil.resumeUntilStopped(); <END> } SyncUtil.addBreakpoint(SOURCE_NAME + ":" + getLineForTag("LINE_MAIN_ALL_THREADS_STARTED")); SyncUtil.resumeUntilStopped(); IThreadDMData mainThreadData = SyncUtil.getThreadData(1); Pattern pattern = Pattern.compile("\\d*", Pattern.MULTILINE); Matcher matcher = pattern.matcher(mainThreadData.getId()); assertTrue("Thread ID is a series of number", matcher.matches()); final String names[] = { EXEC_NAME, "monday", "tuesday", "wednesday", "thursday", "friday" }; for (int i = 1; i <= 6; i++) { IThreadDMData threadData = SyncUtil.getThreadData(i); String name = threadData.getName(); String expectedName = threadNamesSupported() ? names[i - 1] : ""; assertEquals("Thread name of thread " + i, expectedName, name); } }</code><technical_language>runToLocation() above</technical_language>

Target:
public void getThreadData() throws Throwable { for (int i = 0; i < 5; i++) { SyncUtil.runToLocation(SOURCE_NAME + ":" + getLineForTag("LINE_MAIN_AFTER_THREAD_START")); } SyncUtil.runToLocation(SOURCE_NAME + ":" + getLineForTag("LINE_MAIN_ALL_THREADS_STARTED")); IThreadDMData mainThreadData = SyncUtil.getThreadData(1); Pattern pattern = Pattern.compile("\\d*", Pattern.MULTILINE); Matcher matcher = pattern.matcher(mainThreadData.getId()); assertTrue("Thread ID is a series of number", matcher.matches()); final String names[] = { EXEC_NAME, "monday", "tuesday", "wednesday", "thursday", "friday" }; for (int i = 1; i <= 6; i++) { IThreadDMData threadData = SyncUtil.getThreadData(i); String name = threadData.getName(); String expectedName = threadNamesSupported() ? names[i - 1] : ""; assertEquals("Thread name of thread " + i, expectedName, name); } }
Source:
<code>protected boolean canDoAction() { setVmId((Guid) (getParameters().getSlaParameter(VmSlaPolicyParameters.Params.VM_ID))); setVdsId((Guid) getParameters().getSlaParameter(VmSlaPolicyParameters.Params.VDS_ID)); <START> setVdsGroupId(getVds().getVdsGroupId()); <END> if (!FeatureSupported.vmSlaPolicy(getVdsGroup().getcompatibility_version())) { return failCanDoAction(VdcBllMessages.VM_SLA_POLICY_NOT_SUPPORTED); } if (getVm() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_EXIST); } if (getVm() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_EXIST); } if (getVm().getStatus() != VMStatus.Up) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_STATUS_ILLEGAL, LocalizedVmStatus.from(getVm().getStatus())); } return true; }</code><technical_language>3 lines in constructor + get NPE getVds().getVdsGroupId(), need null-check (and canDoAction check)</technical_language>

Target:
protected boolean canDoAction() { if (!FeatureSupported.vmSlaPolicy(getVdsGroup().getcompatibility_version())) { return failCanDoAction(VdcBllMessages.VM_SLA_POLICY_NOT_SUPPORTED); } if (getVm() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_EXIST); } if (getVm() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_EXIST); } if (getVm().getStatus() != VMStatus.Up) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_STATUS_ILLEGAL, LocalizedVmStatus.from(getVm().getStatus())); } return true; }
Source:
<code>public void setupProperties() { super.setupProperties(); <START> batchSize.setValue(300); <END> dieOnError.setValue(true); outputOperation.setPossibleValues((Object[]) OutputOperation.values()); outputOperation.setValue(syncLead); operationType.setPossibleValues((Object[]) values()); operationType.setValue(createOnly); lookupField.setPossibleValues((Object[]) RESTLookupFields.values()); lookupField.setValue(RESTLookupFields.email); customLookupField.setValue(""); deDupeEnabled.setValue(false); deleteLeadsInBatch.setValue(false); customObjectDeleteBy.setValue(CustomObjectDeleteBy.idField); customObjectDedupeBy.setValue("dedupeFields"); customObjectSyncAction.setPossibleValues((Object[]) CustomObjectSyncAction.values()); customObjectSyncAction.setValue(CustomObjectSyncAction.createOrUpdate); schemaInput.schema.setValue(MarketoConstants.getRESTOutputSchemaForSyncLead()); beforeMappingInput(); setSchemaListener(new ISchemaListener() { @Override public void afterSchema() { schemaFlow.schema.setValue(null); schemaReject.schema.setValue(null); beforeMappingInput(); updateOutputSchemas(); } }); }</code><technical_language>Constant for this</technical_language>

Target:
public void setupProperties() { super.setupProperties(); batchSize.setValue(REST_API_LIMIT); dieOnError.setValue(true); outputOperation.setPossibleValues((Object[]) OutputOperation.values()); outputOperation.setValue(syncLead); operationType.setPossibleValues((Object[]) values()); operationType.setValue(createOnly); lookupField.setPossibleValues((Object[]) RESTLookupFields.values()); lookupField.setValue(RESTLookupFields.email); customLookupField.setValue(""); deDupeEnabled.setValue(false); deleteLeadsInBatch.setValue(false); customObjectDeleteBy.setValue(CustomObjectDeleteBy.idField); customObjectDedupeBy.setValue("dedupeFields"); customObjectSyncAction.setPossibleValues((Object[]) CustomObjectSyncAction.values()); customObjectSyncAction.setValue(CustomObjectSyncAction.createOrUpdate); schemaInput.schema.setValue(MarketoConstants.getRESTOutputSchemaForSyncLead()); beforeMappingInput(); setSchemaListener(new ISchemaListener() { @Override public void afterSchema() { schemaFlow.schema.setValue(null); schemaReject.schema.setValue(null); beforeMappingInput(); updateOutputSchemas(); } }); }
Source:
<code>private void display(final PatchSetPublishDetail r) { setPageTitle(Util.M.publishComments(r.getChange().getKey().abbreviate(), patchSetId.get())); descBlock.display(r.getChange(), r.getPatchSetInfo(), r.getAccounts()); if (r.getChange().getStatus().isOpen()) { initApprovals(r, approvalPanel); } if (lastState != null && patchSetId.equals(lastState.patchSetId)) { message.setText(lastState.message); } draftsPanel.clear(); commentEditors = new ArrayList<CommentEditorPanel>(); if (!r.getDrafts().isEmpty()) { draftsPanel.add(new SmallHeading(Util.C.headingPatchComments())); Panel panel = null; String priorFile = ""; for (final PatchLineComment c : r.getDrafts()) { final Patch.Key patchKey = c.getKey().getParentKey(); final String fn = patchKey.get(); if (!fn.equals(priorFile)) { panel = new FlowPanel(); panel.addStyleName(Gerrit.RESOURCES.css().patchComments()); draftsPanel.add(panel); panel.add(new PatchLink.SideBySide(PatchTable .getDisplayFileName(patchKey), patchKey, 0, null, null)); priorFile = fn; } final CommentEditorPanel editor = new CommentEditorPanel(c); editor.setAuthorNameText(Util.M.lineHeader(c.getLine())); editor.setOpen(true); commentEditors.add(editor); panel.add(editor); } } submit.setVisible(r.canSubmit()); if (Gerrit.getConfig().testChangeMerge()) { submit.setEnabled(r.getChange().isMergeable()); <START> errorlabel.setVisible(r.getChange().isMergeable()); <END> } }</code><technical_language>this test negated</technical_language>

Target:
private void display(final PatchSetPublishDetail r) { setPageTitle(Util.M.publishComments(r.getChange().getKey().abbreviate(), patchSetId.get())); descBlock.display(r.getChange(), r.getPatchSetInfo(), r.getAccounts()); if (r.getChange().getStatus().isOpen()) { initApprovals(r, approvalPanel); } if (lastState != null && patchSetId.equals(lastState.patchSetId)) { message.setText(lastState.message); } draftsPanel.clear(); commentEditors = new ArrayList<CommentEditorPanel>(); if (!r.getDrafts().isEmpty()) { draftsPanel.add(new SmallHeading(Util.C.headingPatchComments())); Panel panel = null; String priorFile = ""; for (final PatchLineComment c : r.getDrafts()) { final Patch.Key patchKey = c.getKey().getParentKey(); final String fn = patchKey.get(); if (!fn.equals(priorFile)) { panel = new FlowPanel(); panel.addStyleName(Gerrit.RESOURCES.css().patchComments()); draftsPanel.add(panel); panel.add(new PatchLink.SideBySide(PatchTable .getDisplayFileName(patchKey), patchKey, 0, null, null)); priorFile = fn; } final CommentEditorPanel editor = new CommentEditorPanel(c); editor.setAuthorNameText(Util.M.lineHeader(c.getLine())); editor.setOpen(true); commentEditors.add(editor); panel.add(editor); } } submit.setVisible(r.canSubmit()); if (Gerrit.getConfig().testChangeMerge()) { submit.setEnabled(r.getChange().isMergeable()); errorlabel.setVisible(!r.getChange().isMergeable()); } }
Source:
<code>protected boolean createKeys(List<BlackboardArtifact.Type> list) { if (skCase != null) { try { <START> List<BlackboardArtifact.Type> types = (datasourceObjId > 0) ? <END> blackboard.getArtifactTypesInUse(datasourceObjId) : skCase.getArtifactTypesInUse() ; types.removeAll(doNotShow); Collections.sort(types, new Comparator<BlackboardArtifact.Type>() { @Override public int compare(BlackboardArtifact.Type a, BlackboardArtifact.Type b) { return a.getDisplayName().compareTo(b.getDisplayName()); } }); list.addAll(types); for (BlackboardArtifact.Type art : types) { TypeNode node = typeNodeList.get(art); if (node != null) { node.updateDisplayName(); } } } catch (TskCoreException ex) { Logger.getLogger(TypeFactory.class.getName()).log(Level.SEVERE, "Error getting list of artifacts in use: " + ex.getLocalizedMessage()); } } return true; }</code><technical_language>change Objects CasePreferences unused imports</technical_language>

Target:
protected boolean createKeys(List<BlackboardArtifact.Type> list) { if (skCase != null) { try { List<BlackboardArtifact.Type> types = (filteringDSObjId > 0) ? blackboard.getArtifactTypesInUse(filteringDSObjId) : skCase.getArtifactTypesInUse() ; types.removeAll(doNotShow); Collections.sort(types, new Comparator<BlackboardArtifact.Type>() { @Override public int compare(BlackboardArtifact.Type a, BlackboardArtifact.Type b) { return a.getDisplayName().compareTo(b.getDisplayName()); } }); list.addAll(types); for (BlackboardArtifact.Type art : types) { TypeNode node = typeNodeList.get(art); if (node != null) { node.updateDisplayName(); } } } catch (TskCoreException ex) { Logger.getLogger(TypeFactory.class.getName()).log(Level.SEVERE, "Error getting list of artifacts in use: " + ex.getLocalizedMessage()); } } return true; }
Source:
<code><START> public void aggregationSortingTest() throws Exception { <END> String graphQLRequest = document( selection( field( "playerStats", arguments( argument("sort", "\"-highScore\"") ), selections( field("highScore"), field( "country", selections( field("name"), field("id") ) ) ) ) ) ).toQuery(); String expected = document( selections( field( "playerStats", selections( field("highScore", 2412), field( "country", selections( field("name", "United States"), field("id", "840") ) ) ), selections( field("highScore", 1000), field( "country", selections( field("name", "Hong Kong"), field("id", "344") ) ) ) ) ) ).toResponse(); runQueryWithExpectedResult(graphQLRequest, expected); }</code><technical_language>a test sorting 2 fields? 1 is metric 1 is dimension</technical_language>

Target:
public void aggregationSortingTest() throws Exception { String graphQLRequest = document( selection( field( "playerStats", arguments( argument("sort", "\"-highScore\"") ), selections( field("highScore"), field( "country", selections( field("name") ) ) ) ) ) ).toQuery(); String expected = document( selections( field( "playerStats", selections( field("highScore", 2412), field( "country", selections( field("name", "United States") ) ) ), selections( field("highScore", 1000), field( "country", selections( field("name", "Hong Kong") ) ) ) ) ) ).toResponse(); runQueryWithExpectedResult(graphQLRequest, expected); }