auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public int hashCode() { <START> return Objects.hash(this.getKey()); <END> }</code><technical_language>cleaner Objects.hashCode for a single parameter, Objects.hash for multiple (see warning Objects.hash, matter here)</technical_language>

Target:
public int hashCode() { return Objects.hashCode(this.getKey()); }
Source:
<code>public Iterable<Range> listHistoryVerticesTableSplits() { <START> try { <END> return splitsIterableToRangeIterable(getConnector().tableOperations().listSplits(getHistoryVerticesTableName())); } catch (Exception ex) { throw new VertexiumException("Could not get splits for: " + getHistoryVerticesTableName(), ex); } }</code><technical_language>Consider making a private method listTableSplits(String tableName)? of list*TableSplits methods one-liner calls that</technical_language>

Target:
public Iterable<Range> listHistoryVerticesTableSplits() { return listTableSplits(getHistoryVerticesTableName()); }
Source:
<code>public void updateStats(final boolean isGlobal, final long start, final long end) { Thread statsThread = new Thread("Statistics update") { @Override public void run() { long total; Map<String, Long> map; <START> waitUntilBuilt(); <END> total = getEventsInRange(start, end); map = getEventTypesInRange(start, end); TmfSignal sig = new TmfStatsUpdatedSignal(this, trace, isGlobal, total, map); TmfSignalManager.dispatchSignal(sig); } }; statsThread.start(); return; }</code><technical_language>if of fails build? i.e. waitUntilBuilt() returns false. Is safe ignore? changing behavior</technical_language>

Target:
public void updateStats(final boolean isGlobal, final long start, final long end) { Thread statsThread = new Thread("Statistics update") { @Override public void run() { if (!waitUntilBuilt()) { return; } long total = getEventsInRange(start, end); Map<String, Long> map = getEventTypesInRange(start, end); TmfSignal sig = new TmfStatsUpdatedSignal(this, trace, isGlobal, total, map); TmfSignalManager.dispatchSignal(sig); } }; statsThread.start(); return; }
Source:
<code>ComponentType(String service, String distributionParameter, String distributionRepositoryValueParameter, <START> String versionParameter, String versionRepositoryValueParameter, List<String> componentLists) { <END> this.mService = service; this.mDistributionParameter = distributionParameter; this.mVersionParameter = versionParameter; this.mDistributionRepositoryValueParameter = distributionRepositoryValueParameter; this.mVersionRepositoryValueParameter = versionRepositoryValueParameter; this.mComponentList = componentLists; }</code><technical_language>doc is missing</technical_language>

Target:
ComponentType(String service, String distributionParameter, String distributionRepositoryValueParameter, String versionParameter, String versionRepositoryValueParameter, List<String> componentLists) { this.mService = service; this.mDistributionParameter = distributionParameter; this.mVersionParameter = versionParameter; this.mDistributionRepositoryValueParameter = distributionRepositoryValueParameter; this.mVersionRepositoryValueParameter = versionRepositoryValueParameter; this.mComponentList = new ArrayList<String>( componentLists ); }
Source:
<code>public void setSeparator(String separator) { if (separator.contains("\\n")) { <START> this.separator = "\n"; <END> } else { this.separator = separator; } }</code><technical_language>a (separator.equals("\\n"))</technical_language>

Target:
public void setSeparator(String separator) { if (separator.equals("\\n")) { this.separator = "\n"; } else { this.separator = separator; } }
Source:
<code>public KeyParts visitLeave(InListExpression node, List<KeyParts> childKeyExprs) { if (childKeyExprs.isEmpty()) { return null; } List<byte[]> keys = node.getKeys(); List<KeyRange> ranges = KeyRange.of(keys); KeyPart colKeyExpr = childKeyExprs.get(0).iterator().next().getKeyPart(); <START> return newKeyExpression(colKeyExpr.getDatum(), colKeyExpr.getPosition(), Collections.<Expression>emptyList(), false, ranges, node.getChildren().get(0)); <END> }</code><technical_language>Changes this to: return newKeyExpression( colKeyExpr.getDatum(), colKeyExpr.getPosition(), // This IN expression removed clause // processing continue for subsequent row key columns Collections.<Expression>singletonList(node), // I this is anymore, remove I pull change in. // Instead, extract node list is this before. this is // equality check instead of a filter min max in list list. true, ranges, node.getChildren().get(0)); 0</technical_language>

Target:
public KeyParts visitLeave(InListExpression node, List<KeyParts> childKeyExprs) { if (childKeyExprs.isEmpty()) { return null; } List<byte[]> keys = node.getKeys(); List<KeyRange> ranges = KeyRange.of(keys); KeyPart colKeyExpr = childKeyExprs.get(0).iterator().next().getKeyPart(); if (ranges.size() > 0) { if (ranges.get(0).lowerUnbound() || ranges.get(ranges.size() - 1).upperUnbound()) { ImmutableBytesWritable minKey = node.getMinKey(); ImmutableBytesWritable maxKey = node.getMaxKey(); KeyRange keyRange = KeyRange.getKeyRange(minKey.copyBytes(), true, maxKey.copyBytes(), true); return newKeyExpression(colKeyExpr.getDatum(), colKeyExpr.getPosition(), Collections.<Expression>emptyList(), false, keyRange, node.getChildren().get(0)); } } return newKeyExpression(colKeyExpr.getDatum(), colKeyExpr.getPosition(), Collections.<Expression>singletonList(node), false, ranges, node.getChildren().get(0)); }
Source:
<code>public int getLast() { if (last < first) <START> throw new IllegalStateException("last cannot be smaller than first"); <END> return last; }</code><technical_language>checkOne is unused</technical_language>

Target:
public int getLast() { checkOne(); return last; }
Source:
<code>public CopybookSourceConfig() { super(String.format("CopybookReader")); <START> this.maxSplitSize = DEFAULT_MAX_SPLIT_SIZE; <END> }</code><technical_language>DEFAULT_MAX_SPLIT_SIZE_IN_MB = 1, this.maxSplitSize = DEFAULT_MAX_SPLIT_SIZE_IN_MB * 1024 * 1024</technical_language>

Target:
public CopybookSourceConfig() { super(String.format("CopybookReader")); this.maxSplitSize = DEFAULT_MAX_SPLIT_SIZE_IN_MB * CONVERT_TO_BYTES; }
Source:
<code>public void receiveResponse(Exchange exchange, Response response) { Request request = exchange.getCurrentRequest(); <START> if(request == null){ <END> LOGGER.severe("No request tied to this response"); return; } try { if (responseShouldBeProtected(exchange, response)) { if (!isProtected(response)){ LOGGER.severe("Unprotected OSCore response received" + " for OSCore request"); LOGGER.severe("Response: " + response.toString()); return; } response = prepareReceive(response); } } catch (OSException e) { LOGGER.severe("Error while receiving OSCore response: " + e.getMessage()); EmptyMessage error = OSExceptionHandler.manageError(e, response); if(error != null){ sendEmptyMessage(exchange, error); } return; } super.receiveResponse(exchange,response); }</code><technical_language>whitespace</technical_language>

Target:
public void receiveResponse(Exchange exchange, Response response) { Request request = exchange.getCurrentRequest(); if (request == null) { LOGGER.error("No request tied to this response"); return; } try { if (responseShouldBeProtected(exchange, response)) { if (!isProtected(response)) { LOGGER.error("Unprotected OSCore response received" + " for OSCore request"); LOGGER.error("Response: " + response.toString()); return; } response = prepareReceive(response); } } catch (OSException e) { LOGGER.error("Error while receiving OSCore response: " + e.getMessage()); EmptyMessage error = CoapOSExceptionHandler.manageError(e, response); if (error != null) { sendEmptyMessage(exchange, error); } return; } super.receiveResponse(exchange, response); }
Source:
<code>public static Long estimateLibrarySize(final long readPairs, final long uniqueReadPairs) { final long readPairDuplicates = readPairs - uniqueReadPairs; if (readPairs > 0 && readPairDuplicates > 0) { double m = 1.0; double M = 100.0; if (uniqueReadPairs >= readPairs || f(m * uniqueReadPairs, uniqueReadPairs, readPairs) < 0) { throw new IllegalStateException("Invalid values for pairs and unique pairs: " + readPairs + ", " + uniqueReadPairs); } <START> while (f(M * uniqueReadPairs, uniqueReadPairs, readPairs) > 0){ <END> M *= 10.0; } for (int i = 0; i < 40; i++) { double r = (m + M) / 2.0; double u = f(r * uniqueReadPairs, uniqueReadPairs, readPairs); if (u == 0) break; else if (u > 0) m = r; else if (u < 0) M = r; } return (long) (uniqueReadPairs * (m + M) / 2.0); } else { return null; } }</code><technical_language>missed a space {</technical_language>

Target:
public static Long estimateLibrarySize(final long readPairs, final long uniqueReadPairs) { final long readPairDuplicates = readPairs - uniqueReadPairs; if (readPairs > 0 && readPairDuplicates > 0) { double m = 1.0; double M = 100.0; if (uniqueReadPairs >= readPairs || f(m * uniqueReadPairs, uniqueReadPairs, readPairs) < 0) { throw new IllegalStateException("Invalid values for pairs and unique pairs: " + readPairs + ", " + uniqueReadPairs); } while (f(M * uniqueReadPairs, uniqueReadPairs, readPairs) > 0) { M *= 10.0; } for (int i = 0; i < 40; i++) { double r = (m + M) / 2.0; double u = f(r * uniqueReadPairs, uniqueReadPairs, readPairs); if (u == 0) { break; } else if (u > 0) { m = r; } else if (u < 0) { M = r; } } return (long) (uniqueReadPairs * (m + M) / 2.0); } else { return null; } }
Source:
<code>public static RelOptRuleOperand traitPropagationOperand(Class<? extends RelNode> clazz) { <START> return operand(clazz, null, some(operand(RelSubset.class, any()))); <END> }</code><technical_language>a decrease false matchings (because 'ANY' distributed relations proto- ones)</technical_language>

Target:
public static RelOptRuleOperand traitPropagationOperand(Class<? extends RelNode> clazz) { return operand(clazz, IgniteDistributions.any(), some(operand(RelSubset.class, any()))); }
Source:
<code>public boolean deleteTransaction(Patient patient) { LOG.trace("PatientDAO.deleteTransaction() -- begin"); Session session = null; Transaction tx = null; boolean result = true; try { LOG.info("Read patient-records for delete"); Patient deletePatient = readTransaction(patient.getPatientId(), true); if (deletePatient != null) { session = hibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); LOG.info("Deleting Records..."); for (Address addressRec : deletePatient.getAddresses()) { session.delete(addressRec); } for (Phonenumber phonenumberRec : deletePatient.getPhonenumbers()) { session.delete(phonenumberRec); } for (Identifier identifierRec : deletePatient.getIdentifiers()) { session.delete(identifierRec); } for (Personname personnameRec : deletePatient.getPersonnames()) { session.delete(personnameRec); } session.delete(deletePatient); tx.commit(); LOG.debug("Patient had been deleted: {}", deletePatient.getPatientId()); } else { result = false; } } catch (HibernateException | NullPointerException e) { result = false; LOG.error("Exception during delete occured due to : {}", e.getMessage(), e); } finally { <START> if (session != null) { <END> try { session.flush(); session.close(); } catch (HibernateException e) { LOG.error("Exception while closing the session after a delete: {}", e.getMessage(), e); } } } LOG.trace("PatientDAO.deleteTransaction() - End"); return result; }</code><technical_language>try hibernateUtil.close method encapsulate method one</technical_language>

Target:
public boolean deleteTransaction(Patient patient) { LOG.trace("PatientDAO.deleteTransaction() -- begin"); Session session = null; Transaction tx = null; boolean result = true; try { LOG.info("Read patient-records for delete"); Patient deletePatient = readTransaction(patient.getPatientId(), true); if (deletePatient != null) { session = getSessionFactory().openSession(); tx = session.beginTransaction(); LOG.info("Deleting Records..."); for (Address addressRec : deletePatient.getAddresses()) { session.delete(addressRec); } for (Phonenumber phonenumberRec : deletePatient.getPhonenumbers()) { session.delete(phonenumberRec); } for (Identifier identifierRec : deletePatient.getIdentifiers()) { session.delete(identifierRec); } for (Personname personnameRec : deletePatient.getPersonnames()) { session.delete(personnameRec); } session.delete(deletePatient); tx.commit(); LOG.debug("Patient had been deleted: {}", deletePatient.getPatientId()); } else { result = false; } } catch (HibernateException | NullPointerException e) { result = false; LOG.error("Exception during delete occured due to : {}", e.getMessage(), e); } finally { HibernateUtil.closeSession(session, true); } LOG.trace("PatientDAO.deleteTransaction() - End"); return result; }
Source:
<code>public void getActionsHasPermission() throws Exception { when(view.hasPermission(any())).thenReturn(true); final List<Action> actions = newViewLink.createFor(view); assertEquals(1, actions.size()); final Action action = actions.get(0); assertEquals(Messages.NewViewLink_NewView(), action.getDisplayName()); assertEquals(NewViewLink.ICON_FILE_NAME, action.getIconFileName()); <START> } <END></code><technical_language>I rewrite assert check full URL chack URL contains name. removing check is a bit hackish</technical_language>

Target:
public void getActionsHasPermission() throws Exception { when(view.hasPermission(any())).thenReturn(true); final List<Action> actions = newViewLink.createFor(view); assertEquals(1, actions.size()); final Action action = actions.get(0); assertEquals(Messages.NewViewLink_NewView(), action.getDisplayName()); assertEquals(NewViewLink.ICON_FILE_NAME, action.getIconFileName()); assertEquals(rootUrl + NewViewLink.URL_NAME, action.getUrlName()); }
Source:
<code>public void init(ServletConfig config) throws ServletException { super.init(config); final String cacheString = config.getInitParameter(CACHE); if (cacheString == null) { cache = true; } else { cache = Boolean.parseBoolean(cacheString); } type = config.getInitParameter(TYPE); final String name = config.getInitParameter(FILE); if (name == null) { final String message = "Can't get base name from parameter \"" + FILE + "\"."; log.error(message); throw new ServletException(message); } final String expanded = EngineLocalConfig.getInstance().expandString(name.replaceAll("%\\{", "\\${")); if (StringUtils.isEmpty(expanded)) { final String message = "Refusing to serve empty location"; log.debug(message); throw new ServletException(message); } base = new File(expanded); final String isBaseRequired = config.getInitParameter(REQUIRED); if (isBaseRequired != null) { required = Boolean.parseBoolean(isBaseRequired); <START> } <END> }</code><technical_language>move this block parameters handled</technical_language>

Target:
public void init(ServletConfig config) throws ServletException { super.init(config); final String cacheString = config.getInitParameter(CACHE); if (cacheString == null) { cache = true; } else { cache = Boolean.parseBoolean(cacheString); } type = config.getInitParameter(TYPE); final String name = config.getInitParameter(FILE); if (name == null) { final String message = "Can't get base name from parameter \"" + FILE + "\"."; log.error(message); throw new ServletException(message); } final String expanded = EngineLocalConfig.getInstance().expandString(name.replaceAll("%\\{", "\\${")); if (StringUtils.isEmpty(expanded)) { final String message = "Refusing to serve empty location"; log.debug(message); throw new ServletException(message); } final String isBaseRequired = config.getInitParameter(REQUIRED); if (isBaseRequired != null) { required = Boolean.parseBoolean(isBaseRequired); } base = new File(expanded); }
Source:
<code>public void setShippingMethod() throws Exception { withShippingMethodForGermany(client(), shippingMethod -> { withCart(client(), createCartWithShippingAddress(client()), cart -> { assertThat(cart.getShippingInfo()).isNull(); final CartUpdateCommand updateCommand = CartUpdateCommand.of(cart, SetShippingMethod.of(shippingMethod)) .plusExpansionPaths(m -> m.shippingInfo().shippingMethod().taxCategory()) .plusExpansionPaths(m -> m.shippingInfo().taxCategory()); final Cart cartWithShippingMethod = client().executeBlocking(updateCommand); assertThat(cartWithShippingMethod.getShippingInfo().getShippingMethodState()).isEqualTo(ShippingMethodState.MATCHES_CART); assertThat(cartWithShippingMethod.getShippingInfo().getShippingMethod()).isEqualTo(shippingMethod.toReference()); assertThat(cartWithShippingMethod.getShippingInfo().getShippingMethod().getObj()) .as("reference expansion shippingMethod") .isEqualTo(shippingMethod); assertThat(cartWithShippingMethod.getShippingInfo().getShippingMethod().getObj().getTaxCategory().getObj()) .as("reference expansion taxCategory") <START> .isNotNull(); <END> final Cart cartWithoutShippingMethod = client().executeBlocking(CartUpdateCommand.of(cartWithShippingMethod, SetShippingMethod.ofRemove())); assertThat(cartWithoutShippingMethod.getShippingInfo()).isNull(); return cartWithoutShippingMethod; }); }); }</code><technical_language>is working anymore</technical_language>

Target:
public void setShippingMethod() throws Exception { withShippingMethodForGermany(client(), shippingMethod -> { withCart(client(), createCartWithShippingAddress(client()), cart -> { assertThat(cart.getShippingInfo()).isNull(); final CartUpdateCommand updateCommand = CartUpdateCommand.of(cart, SetShippingMethod.of(shippingMethod)) .plusExpansionPaths(m -> m.shippingInfo().shippingMethod().taxCategory()) .plusExpansionPaths(m -> m.shippingInfo().taxCategory()); final Cart cartWithShippingMethod = client().executeBlocking(updateCommand); assertThat(cartWithShippingMethod.getShippingInfo().getShippingMethodState()).isEqualTo(ShippingMethodState.MATCHES_CART); assertThat(cartWithShippingMethod.getShippingInfo().getShippingMethod()).isEqualTo(shippingMethod.toReference()); assertThat(cartWithShippingMethod.getShippingInfo().getShippingMethod().getObj()) .as("reference expansion shippingMethod") .isEqualTo(shippingMethod); assertThat(cartWithShippingMethod.getShippingInfo().getShippingMethod().getObj().getTaxCategory().getObj()) .as("reference expansion taxCategory") .isEqualTo(cartWithShippingMethod.getShippingInfo().getTaxCategory().getObj()) .isNotNull(); final Cart cartWithoutShippingMethod = client().executeBlocking(CartUpdateCommand.of(cartWithShippingMethod, SetShippingMethod.ofRemove())); assertThat(cartWithoutShippingMethod.getShippingInfo()).isNull(); return cartWithoutShippingMethod; }); }); }
Source:
<code>public UsernamePasswordAuthenticationFilter(AuthenticationManager authenticationManager) { <START> super(new AntPathRequestMatcher("/login", "POST"), authenticationManager); <END> }</code><technical_language>extract default request matcher a a static variable ensure consistency constructors</technical_language>

Target:
public UsernamePasswordAuthenticationFilter(AuthenticationManager authenticationManager) { super(DEFAULT_ANT_PATH_REQUEST_MATCHER, authenticationManager); }
Source:
<code>public void send(byte[] payload) throws TTransportException { if (!isOpen()) { throw new TTransportException(TTransportException.NOT_OPEN); } transport.write(payload); <START> transport.flush(); <END> }</code><technical_language>this need lock transport? FAdapterTransport thread-safe</technical_language>

Target:
public synchronized void send(byte[] payload) throws TTransportException { if (!isOpen()) { throw new TTransportException(TTransportException.NOT_OPEN); } transport.write(payload); transport.flush(); }
Source:
<code>public String getReplicationId() { HashMap<String, String> dict = new HashMap<String, String>(); dict.put("source", this.sourceDb.getIdentifier()); try { dict.put("target", this.targetDb.getIdentifier()); } catch (DatastoreException e){ logger.log(Level.WARNING,"Failed to get public id using default",e); <START> dict.put("target","touchdb_defaultUUID"); <END> } if(filter != null) { dict.put("filter", this.filter.toQueryString()); } byte[] sha1Bytes = Misc.getSha1(new ByteArrayInputStream(JSONUtils.serializeAsBytes(dict))); byte[] sha1Hex = new Hex().encode(sha1Bytes); return new String(sha1Hex); }</code><technical_language>This method fail if get name of target. end incorrect checkpoint docs</technical_language>

Target:
public String getReplicationId() throws DatastoreException { HashMap<String, String> dict = new HashMap<String, String>(); dict.put("source", this.sourceDb.getIdentifier()); dict.put("target", this.targetDb.getIdentifier()); if(filter != null) { dict.put("filter", this.filter.toQueryString()); } byte[] sha1Bytes = Misc.getSha1(new ByteArrayInputStream(JSONUtils.serializeAsBytes(dict))); byte[] sha1Hex = new Hex().encode(sha1Bytes); return new String(sha1Hex); }
Source:
<code>public DataFlagEncoderTest() { encoder = new DataFlagEncoder(); <START> encodingManager = new EncodingManager(Arrays.asList(encoder), 8); <END> motorVehicleInt = encoder.getAccessType("motor_vehicle"); }</code><technical_language>great if number of encoders configureable. if pass a heightlimit of 0 Configmap DataflagEncoder, register heigthEncoder. WDYT</technical_language>

Target:
public DataFlagEncoderTest() { properties = new PMap(); properties.put("store_height", true); properties.put("store_weight", true); properties.put("store_width", true); encoder = new DataFlagEncoder(properties); encodingManager = new EncodingManager(Arrays.asList(encoder), 8); motorVehicleInt = encoder.getAccessType("motor_vehicle"); }
Source:
<code>private void persistEngineSession(String sessionId) { SessionInfo sessionInfo = getSessionInfo(sessionId); if (sessionInfo != null) { EngineSession engineSession = new EngineSession(); engineSession.setEngineSessionId(sessionId); <START> DbUser user = getUser(sessionId, false); <END> engineSession.setUserId(user.getId()); engineSession.setUserName(user.getLoginName()); engineSession.setGroupIds(user.getGroupIds()); sessionInfo.contentOfSession.put(ENGINE_SESSION_SEQ_ID, getDbFacade().getEngineSessionDao().save(engineSession)); } }</code><technical_language>mu previous question... reason DbUser EngineSession remove specifics here</technical_language>

Target:
private void persistEngineSession(String sessionId) { SessionInfo sessionInfo = getSessionInfo(sessionId); if (sessionInfo != null) { EngineSession engineSession = new EngineSession(getUser(sessionId, false)); engineSession.setEngineSessionId(sessionId); sessionInfo.contentOfSession.put(ENGINE_SESSION_SEQ_ID, getDbFacade().getEngineSessionDao().save(engineSession)); } }
Source:
<code>public String convertStreamToString(InputStream is) throws IOException { if (is != null) { Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { <START> Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); <END> int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { is.close(); } return writer.toString(); } else { return ""; } }</code><technical_language>close reader input stream</technical_language>

Target:
public String convertStreamToString(InputStream is) throws IOException { if (is != null) { Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } reader.close(); } finally { is.close(); } return writer.toString(); } else { return ""; } }
Source:
<code>public PeriodicQueryMetadata readPeriodicQueryMetadata(SnapshotBase tx, String nodeId) { Optional<NodeType> type = NodeType.fromNodeId(nodeId); try { <START> checkArgument(type.isPresent() && type.get() == NodeType.PERIODIC_QUERY); <END> LOG.debug("Retrieving Metadata from Cache: {}", nodeId); return (PeriodicQueryMetadata) commonNodeMetadataCache.get(nodeId, new Callable<CommonNodeMetadata>() { @Override public CommonNodeMetadata call() throws Exception { LOG.debug("Seeking Metadata from Fluo Table: {}.", nodeId); return dao.readPeriodicQueryMetadata(tx, nodeId); } }); } catch (Exception e) { throw new RuntimeException("Unable to access PeriodicQueryMetadata for nodeId: " + nodeId, e); } }</code><technical_language>same....I'm stop wait if this caught</technical_language>

Target:
public PeriodicQueryMetadata readPeriodicQueryMetadata(SnapshotBase tx, String nodeId) { checkNotNull(nodeId); checkNotNull(tx); Optional<NodeType> type = NodeType.fromNodeId(nodeId); checkArgument(type.isPresent() && type.get() == NodeType.PERIODIC_QUERY); try { LOG.debug("Retrieving Metadata from Cache: {}", nodeId); return (PeriodicQueryMetadata) commonNodeMetadataCache.get(nodeId, () -> { LOG.debug("Seeking Metadata from Fluo Table: {}.", nodeId); return dao.readPeriodicQueryMetadata(tx, nodeId); }); } catch (Exception e) { throw new RuntimeException("Unable to access PeriodicQueryMetadata for nodeId: " + nodeId, e); } }
Source:
<code>private BuildCommand isRepoUrlChanged(String workDir) { return test("-neq", <START> new MaterialUrl(material.getUrlArgument().forCommandline()).toString(), <END> exec("hg", "showconfig", "paths.default").setWorkingDirectory(workDir)); }</code><technical_language>I this do need. :( MaterialUrl remove password. HgUrlArgument does. needs in combination</technical_language>

Target:
private BuildCommand isRepoUrlChanged(String workDir) { return test("-neq", new MaterialUrl(material.getHgUrlArgument().defaultRemoteUrl()).getUrl(), exec("hg", "showconfig", "paths.default").setWorkingDirectory(workDir)); }
Source:
<code>public Object deserialize(Object object) { <START> if (object instanceof String) { <END> return Long.parseLong((String) object); } return object; }</code><technical_language>I oversight in longSum. Try a query results in +Infinity historical level is needed deserialize broker level</technical_language>

Target:
public Object deserialize(Object object) { return object; }
Source:
<code>public int hashCode() { int result = Objects.hash(entity); <START> result = 31 * result + Arrays.hashCode(values); <END> return result; }</code><technical_language>reason this Objects.hash()? of 31 instead of 37? I ok for changing hashcode formula long violate equals contract</technical_language>

Target:
public int hashCode() { return Objects.hash(entity, Arrays.hashCode(values)); }
Source:
<code>private void removeNonExistingDecorators() { Set<String> nonExistingDecorators = getNonExistingDecorators(); updateDecoratorConfigurations(nonExistingDecorators); <START> dataService.deleteAll(DYNAMIC_DECORATOR, nonExistingDecorators.stream().map(id -> (Object) id)); <END> }</code><technical_language>map(id -> (Object) id)) unnecessary</technical_language>

Target:
private void removeNonExistingDecorators() { Set<String> nonExistingDecorators = getNonExistingDecorators(); updateDecoratorConfigurations(nonExistingDecorators); dataService.deleteAll(DYNAMIC_DECORATOR, (Stream<Object>) (Stream<?>) nonExistingDecorators.stream()); }
Source:
<code>public void testTransformWhenFileIsNotNew() { final String fileName = "file.dmn"; final String xml = "xml"; final ServiceCallback<Diagram> callback = mock(ServiceCallback.class); final String title = "title"; <START> doReturn(title).when(service).getDiagramTitle(fileName); <END> doNothing().when(service).doNewDiagram(title, callback); service.transform(fileName, xml, callback); verify(service, never()).doNewDiagram(title, callback); verify(service).doTransformation(xml, callback); }</code><technical_language>Do mock behaviour of this method!?</technical_language>

Target:
public void testTransformWhenFileIsNotNew() { final String fileName = "file.dmn"; final String xml = "xml"; final ServiceCallback<Diagram> callback = mock(ServiceCallback.class); final String title = "title"; doNothing().when(service).doNewDiagram(title, callback); service.transform(fileName, xml, callback); verify(service, never()).doNewDiagram(title, callback); verify(service).doTransformation(xml, callback); }
Source:
<code>public void insert(DbSession dbSession, WebhookDto dto) { <START> <END> checkState(dto.getOrganizationUuid() != null || dto.getProjectUuid() != null, "A webhook can not be created if not linked to an organization or a project."); checkState(dto.getOrganizationUuid() == null || dto.getProjectUuid() == null, "A webhook can not be linked to both an organization and a project."); mapper(dbSession).insert(dto.setCreatedAt(system2.now())); }</code><technical_language>blank lines method bodies strange. rules inconsistent me. valuable feedback others</technical_language>

Target:
public void insert(DbSession dbSession, WebhookDto dto) { checkState(dto.getOrganizationUuid() != null || dto.getProjectUuid() != null, "A webhook can not be created if not linked to an organization or a project."); checkState(dto.getOrganizationUuid() == null || dto.getProjectUuid() == null, "A webhook can not be linked to both an organization and a project."); mapper(dbSession).insert(dto.setCreatedAt(system2.now()).setUpdatedAt(system2.now())); }
Source:
<code>private Thing addThing(ThingTypeUID thingTypeUID, ThingUID thingUID, Configuration configuration, ThingUID bridgeUID, String label, List<String> groupNames, boolean enableChannels, Map<String, String> properties) { Thing thing = ThingFactory.createThing(thingUID, configuration, properties, bridgeUID, thingTypeUID, this.thingHandlerFactories); if (thing == null) { logger.warn("Cannot create thing. No binding found that supports creating a thing" + " of type {}.", thingTypeUID); return null; } if (properties != null) { for (String key : properties.keySet()) { thing.setProperty(key, properties.get(key)); } } addThingSafely(thing); <START> addItems(label, groupNames, thing, thingTypeUID); <END> if (enableChannels) { enableChannels(thing, thingTypeUID); } return thing; }</code><technical_language>I learned addItems adds group item for (and groups), items for channels (which is done enableChannels). I if find a name for method? "createGroupItems"</technical_language>

Target:
private Thing addThing(ThingTypeUID thingTypeUID, ThingUID thingUID, Configuration configuration, ThingUID bridgeUID, String label, List<String> groupNames, boolean enableChannels, Map<String, String> properties) { Thing thing = ThingFactory.createThing(thingUID, configuration, properties, bridgeUID, thingTypeUID, this.thingHandlerFactories); if (thing == null) { logger.warn("Cannot create thing. No binding found that supports creating a thing" + " of type {}.", thingTypeUID); return null; } if (properties != null) { for (String key : properties.keySet()) { thing.setProperty(key, properties.get(key)); } } addThingSafely(thing); createGroupItems(label, groupNames, thing, thingTypeUID); if (enableChannels) { enableChannels(thing, thingTypeUID); } return thing; }
Source:
<code>private void writeValue(Object value, ObjectOutputStream out) throws IOException{ if(value instanceof Serializable){ out.writeBoolean(false); out.writeObject(value); }else{ out.writeBoolean(true); out.writeUTF(value.getClass().getName()); <START> IndexedRecord record = (IndexedRecord)value; <END> out.writeUTF(record.getSchema().toString()); ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream(); Encoder encoder = EncoderFactory.get().binaryEncoder(byteOutStream, null); DatumWriter writer = new GenericDatumWriter(record.getSchema()); writer.write(value, encoder); byte[] bytes = byteOutStream.toByteArray(); out.writeInt(bytes.length); out.write(bytes); } }</code><technical_language>This cast fail if is Serializable IndexedRecord. test explicitly fail a message. Actually, support Avro reflect here</technical_language>

Target:
private void writeValue(Object value, ObjectOutputStream out) throws IOException{ if (value instanceof Serializable) { out.writeBoolean(false); out.writeObject(value); } else { out.writeBoolean(true); out.writeUTF(value.getClass().getName()); DatumWriter writer = null; if (value instanceof IndexedRecord) { out.writeBoolean(false); IndexedRecord record = (IndexedRecord)value; Schema schema = record.getSchema(); writer = new GenericDatumWriter(schema); } else { out.writeBoolean(true); writer = new ReflectDatumWriter(value.getClass()); } ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream(); Encoder encoder = EncoderFactory.get().binaryEncoder(byteOutStream, null); writer.write(value, encoder); byte[] bytes = byteOutStream.toByteArray(); out.writeInt(bytes.length); out.write(bytes); } }
Source:
<code>public void visitMemberAccess(MemberAccessTree tree) { <START> if (tree.is(Tree.Kind.CLASS_MEMBER_ACCESS) && "self".equals(tree.object().toString()) && !isException(tree) && !isPrivate(tree.member())) { <END> context().newIssue(this, MESSAGE).tree(tree); } super.visitMemberAccess(tree); }</code><technical_language>@ivandalbosco IMHO move call isPrivate isException</technical_language>

Target:
public void visitMemberAccess(MemberAccessTree tree) { if (tree.is(Tree.Kind.CLASS_MEMBER_ACCESS) && "self".equals(tree.object().toString()) && !isException(tree)) { context().newIssue(this, tree.object(), MESSAGE); } super.visitMemberAccess(tree); }
Source:
<code>public IndexIngestionSpec( @JsonProperty("dataSchema") DataSchema dataSchema, @JsonProperty("ioConfig") IndexIOConfig ioConfig, @JsonProperty("tuningConfig") IndexTuningConfig tuningConfig ) { super(dataSchema, ioConfig, tuningConfig); Checks.checkOneNotNullOrEmpty( ImmutableList.of( new Property<>("parser", dataSchema.getParserMap()), new Property<>("inputFormat", ioConfig.getInputFormat()) ) ); if (dataSchema.getParserMap() != null && ioConfig.getInputSource() != null) { <START> throw new IAE("Cannot use parser and inputSource together. Try use inputFormat instead of parser."); <END> } this.dataSchema = dataSchema; this.ioConfig = ioConfig; this.tuningConfig = tuningConfig == null ? new IndexTuningConfig() : tuningConfig; }</code><technical_language>Typo: Try inputFormat -> Try inputFormat</technical_language>

Target:
public IndexIngestionSpec( @JsonProperty("dataSchema") DataSchema dataSchema, @JsonProperty("ioConfig") IndexIOConfig ioConfig, @JsonProperty("tuningConfig") IndexTuningConfig tuningConfig ) { super(dataSchema, ioConfig, tuningConfig); Checks.checkOneNotNullOrEmpty( ImmutableList.of( new Property<>("parser", dataSchema.getParserMap()), new Property<>("inputFormat", ioConfig.getInputFormat()) ) ); if (dataSchema.getParserMap() != null && ioConfig.getInputSource() != null) { throw new IAE("Cannot use parser and inputSource together. Try using inputFormat instead of parser."); } this.dataSchema = dataSchema; this.ioConfig = ioConfig; this.tuningConfig = tuningConfig == null ? new IndexTuningConfig() : tuningConfig; }
Source:
<code>public void scheduleWithFixedDelay() { executor.scheduleWithFixedDelay(() -> { try { ConjureTimeLockClientFeedback feedbackReport = ConjureTimeLockClientFeedback .builder() <START> .stats(ImmutableMap.of("conjureTimelockServiceBlocking.startTransactions", <END> getEndpointStatsForStartTxn())) .atlasVersion(versionSupplier.get()) .nodeId(nodeId) .serviceName(serviceName) .build(); timeLockClientFeedbackServices .get() .forEach(service -> service.reportFeedback(AUTH_HEADER, feedbackReport)); log.info("The TimeLock client metrics for startTransaction endpoint aggregated " + "over the last 1 minute - {}", SafeArg.of("startTxnStats", feedbackReport)); } catch (Exception e) { log.warn("A problem occurred while reporting client feedback for timeLock adjudication.", e); } }, timeLockClientFeedbackReportInterval.getSeconds(), timeLockClientFeedbackReportInterval.getSeconds(), TimeUnit.SECONDS); }</code><technical_language>nit: a constant public: server needs read this eventually</technical_language>

Target:
public void scheduleWithFixedDelay() { executor.scheduleWithFixedDelay(() -> { try { ConjureTimeLockClientFeedback feedbackReport = ConjureTimeLockClientFeedback .builder() .startTransaction(getEndpointStatsForStartTxn()) .leaderTime(getEndpointStatsForLeaderTime()) .atlasVersion(versionSupplier.get()) .nodeId(nodeId) .serviceName(serviceName) .build(); timeLockClientFeedbackServices .current() .forEach(service -> reportClientFeedbackToService(feedbackReport, service)); } catch (Exception e) { log.warn("A problem occurred while reporting client feedback for timeLock adjudication.", e); } }, TIMELOCK_CLIENT_FEEDBACK_REPORT_INTERVAL.getSeconds(), TIMELOCK_CLIENT_FEEDBACK_REPORT_INTERVAL.getSeconds(), TimeUnit.SECONDS); }
Source:
<code>public byte[] getContent() { <START> return content.getBytes(); <END> }</code><technical_language>UTF-8 Charset getBytes(Charset) implementation (it throw exception). This depends default system encoder if change trouble</technical_language>

Target:
public byte[] getContent() { return content.getBytes(Charset.forName("UTF-8")); }
Source:
<code>private static boolean isInCompactConstructor(DetailAST ast) { boolean isInCompactCtor = false; if (ast.getParent() != null) { isInCompactCtor = ast.getParent().getType() == TokenTypes.COMPACT_CTOR_DEF <START> || isInCompactConstructor(ast.getParent()); <END> } return isInCompactCtor; }</code><technical_language>This easily replaced a loop. deep this recursion be</technical_language>

Target:
private static boolean isInCompactConstructor(DetailAST ast) { boolean isInCompactCtor = false; DetailAST parent = ast.getParent(); while (parent != null) { if (parent.getType() == TokenTypes.COMPACT_CTOR_DEF) { isInCompactCtor = true; break; } parent = parent.getParent(); } return isInCompactCtor; }
Source:
<code>protected void createDefaultEditPolicies() { super.createDefaultEditPolicies(); this.installEditPolicy(EditPolicyRoles.POPUPBAR_ROLE, new SiriusPopupBarEditPolicy()); <START> removeEditPolicy(EditPolicyRoles.SNAP_FEEDBACK_ROLE); <END> installEditPolicy(EditPolicyRoles.SNAP_FEEDBACK_ROLE, new SiriusSnapFeedbackPolicy()); }</code><technical_language>I tend do remove/install in code, this is needed: org.eclipse.gef.editparts.AbstractEditPart.installEditPolicy(Object, EditPolicy) remove (and deactivate) pre-existing policy in role want install new one</technical_language>

Target:
protected void createDefaultEditPolicies() { super.createDefaultEditPolicies(); this.installEditPolicy(EditPolicyRoles.POPUPBAR_ROLE, new SiriusPopupBarEditPolicy()); installEditPolicy(EditPolicyRoles.SNAP_FEEDBACK_ROLE, new SiriusSnapFeedbackPolicy()); }
Source:
<code>public List<Pair<VDS, VdsNumaNode>> getAllHostsWithVdsNumaNodeByVdsIdList(List<Guid> hostIdList) { List<Pair<VDS, VdsNumaNode>> vdsNumaNodes = <START> getCallsHandler().executeReadList("GetNumaNodeByVdsIdList", <END> hostWithVdsNumaNodeRowMapper, getCustomMapSqlParameterSource().addValue("host_ids", StringUtils.join(hostIdList, ','))); return vdsNumaNodes; }</code><technical_language>Ids, missed before</technical_language>

Target:
public List<Pair<VDS, VdsNumaNode>> getAllHostsWithVdsNumaNodeByVdsIdList(List<Guid> hostIdList) { List<Pair<VDS, VdsNumaNode>> vdsNumaNodes = getCallsHandler().executeReadList("GetNumaNodeByVdsIdsList", hostWithVdsNumaNodeRowMapper, getCustomMapSqlParameterSource().addValue("host_ids", StringUtils.join(hostIdList, ','))); return vdsNumaNodes; }
Source:
<code><START> private ProductProjection productWithNoCategories() { <END> return new ProductProjection() { @Override public Boolean hasStagedChanges() { return null; } @Override public Boolean isPublished() { return null; } @Override public Set<Reference<Category>> getCategories() { return emptySet(); } @Nullable @Override public LocalizedString getDescription() { return null; } @Override public ProductVariant getMasterVariant() { return null; } @Nullable @Override public LocalizedString getMetaDescription() { return null; } @Nullable @Override public LocalizedString getMetaKeywords() { return null; } @Nullable @Override public LocalizedString getMetaTitle() { return null; } @Override public LocalizedString getName() { return null; } @Override public LocalizedString getSlug() { return null; } @Override public List<ProductVariant> getVariants() { return null; } @Override public SearchKeywords getSearchKeywords() { return null; } @Nullable @Override public CategoryOrderHints getCategoryOrderHints() { return null; } @Nullable @Override public ReviewRatingStatistics getReviewRatingStatistics() { return null; } @Nullable @Override public Reference<State> getState() { return null; } @Nullable @Override public String getKey() { return null; } @Override public Reference<ProductType> getProductType() { return null; } @Nullable @Override public Reference<TaxCategory> getTaxCategory() { return null; } @Override public String getId() { return null; } @Override public Long getVersion() { return null; } @Override public ZonedDateTime getCreatedAt() { return null; } @Override public ZonedDateTime getLastModifiedAt() { return null; } }; }</code><technical_language>A lot of code express empty categories, I prefer: java final ProductProjection productProjection = SphereJsonUtils.readObject("{\"categories\": [], \"variants\": []}", ProductProjection.class);</technical_language>

Target:
private ProductProjection productWithNoCategories() { return SphereJsonUtils.readObject("{\"categories\": [], \"variants\": []}", ProductProjection.class); }
Source:
<code>public static int findFreePort() { ServerSocket socket = null; try { socket = new ServerSocket(0); socket.setReuseAddress(true); int port = socket.getLocalPort(); try { socket.close(); } catch (IOException e) { } logger.debug("Found free port {}", port); return port; } catch (IOException e) { } finally { if (socket != null) { try { <START> socket.close(); <END> } catch (IOException e) { } } } throw new IllegalStateException("Could not find a free TCP/IP port to start git-daemon."); }</code><technical_language>ServerSocket implements AutoCloseable means try-with-resources close it. is reason close socket twice</technical_language>

Target:
public static int findFreePort() { try (ServerSocket socket = new ServerSocket(SELECT_RANDOM_PORT_OPTION)) { socket.setReuseAddress(true); int port = socket.getLocalPort(); logger.debug("Found free port {}", port); return port; } catch (IOException e) { } throw new IllegalStateException("Could not find a free TCP/IP port to start git-daemon."); }
Source:
<code>public int getMaximumSize() { int maxSize = 0; for (IDeclaration field : fFields) { maxSize += field.getMaximumSize(); } <START> return Math.min(maxSize, Integer.MAX_VALUE); <END> }</code><technical_language>maxSize int, Math.min is unnecessary. do need overflow, Math.max(0, maxSize);</technical_language>

Target:
public int getMaximumSize() { long maxSize = 0; for (IDeclaration field : fFields) { maxSize += field.getMaximumSize(); } return (int) Math.min(maxSize, Integer.MAX_VALUE); }
Source:
<code>public String login(@FormParam("username") String username, @FormParam("password") String password) { try { <START> if ((username == null || username == "") || (password == null || password == "")) { <END> throw new LoginException("Empty login/password"); } Session session; if (IAMSessionUtil.IAM_IS_USED) { session = IAMSessionUtil.createNewSessionToken(username, password, sessionStore); } else { session = sessionStore.create(username); } session.connectToScheduler(new CredData(username, password)); logger.info("Binding user " + username + " to session " + session.getSessionId()); return session.getSessionId(); } catch (Exception e) { return "[Error] " + e.getClass() + ": " + e.getMessage(); } }</code><technical_language>Generally super safe compare string directly, e.g.: String a = "GitHub is awesome".substring(6, 6); a == "" returns false. do: username == null || username.trim().empty()</technical_language>

Target:
public String login(@FormParam("username") String username, @FormParam("password") String password) throws LoginException, SchedulerRestException { try { if ((username == null || username.trim().isEmpty()) || (password == null || password.trim().isEmpty())) { throw new LoginException("Empty login/password"); } Session session; if (IAMSessionUtil.IAM_IS_USED) { session = sessionStore.create(username, password.toCharArray()); } else { session = sessionStore.create(username); } session.connectToScheduler(new CredData(username, password)); logger.info("Binding user " + username + " to session " + session.getSessionId()); return session.getSessionId(); } catch (ActiveObjectCreationException | SchedulerException | NodeException e) { throw new SchedulerRestException(e); } }
Source:
<code>public ChunkedTileEntityList(ChunkedTileEntityList list) { this(); <START> for (Iterator<Entry<ChunkPos, List<TileEntity>>> iterator = list.entrySet().iterator(); iterator.hasNext();) { <END> Entry<ChunkPos, List<TileEntity>> entry = iterator.next(); content.put(entry.getKey(), new ArrayList<>(entry.getValue())); } }</code><technical_language>a for loop for (Entry<ChunkPos, List<TileEntity>> entry : list.entrySet()) left braces</technical_language>

Target:
public ChunkedTileEntityList(ChunkedTileEntityList list) { this(); for (Entry<ChunkPos, List<TileEntity>> entry : list.content.entrySet()) { content.put(entry.getKey(), new ArrayList<>(entry.getValue())); } updateTotalCount(); }
Source:
<code>public List<String> unapply(@Nullable final String value) { String valueEquivalent = NullHandling.nullToEmptyIfNeeded(value); if (valueEquivalent == null) { <START> return Collections.EMPTY_LIST; <END> } CacheRefKeeper cacheRefKeeper = refOfCacheKeeper.get(); if (cacheRefKeeper == null) { throw new ISE("pollingLookup id [%s] is closed", id); } PollingCache cache = cacheRefKeeper.getAndIncrementRef(); try { if (cache == null) { return this.unapply(valueEquivalent); } return cache.getKeys(valueEquivalent); } finally { if (cacheRefKeeper != null && cache != null) { cacheRefKeeper.doneWithIt(); } } }</code><technical_language>Prefer emptyList() avoid unchecked warnings</technical_language>

Target:
public List<String> unapply(@Nullable final String value) { String valueEquivalent = NullHandling.nullToEmptyIfNeeded(value); if (valueEquivalent == null) { return Collections.emptyList(); } CacheRefKeeper cacheRefKeeper = refOfCacheKeeper.get(); if (cacheRefKeeper == null) { throw new ISE("pollingLookup id [%s] is closed", id); } PollingCache cache = cacheRefKeeper.getAndIncrementRef(); try { if (cache == null) { return this.unapply(valueEquivalent); } return cache.getKeys(valueEquivalent); } finally { if (cacheRefKeeper != null && cache != null) { cacheRefKeeper.doneWithIt(); } } }
Source:
<code>public void run(TaskRequest request) { long taskId = request.getTaskId(); <START> tm.begin(() -> { <END> try (SetThreadName threadName = new SetThreadName(request.getTaskName())) { try (TaskLogger taskLogger = callback.newTaskLogger(request)) { TaskContextLogging.enter(LogLevel.DEBUG, taskLogger); try { runningTaskMap.put(taskId, request); try { runWithHeartbeat(request); } finally { runningTaskMap.remove(taskId); } } finally { TaskContextLogging.leave(); } } } return null; }); }</code><technical_language>I starting transaction is good idea task runs in a transaction. locks acquired in this transaction released user task finishes. TaskCallbackApi (and SecretProvider) interface for agents access database. Therefore, put tm.begin in TaskCallbackApi DB access tasks transactional</technical_language>

Target:
public void run(TaskRequest request) { long taskId = request.getTaskId(); try (SetThreadName threadName = new SetThreadName(request.getTaskName())) { try (TaskLogger taskLogger = callback.newTaskLogger(request)) { TaskContextLogging.enter(LogLevel.DEBUG, taskLogger); try { runningTaskMap.put(taskId, request); try { runWithHeartbeat(request); } finally { runningTaskMap.remove(taskId); } } finally { TaskContextLogging.leave(); } } } }
Source:
<code>public static boolean contains(Element a, Element b) { maybeInitializeSelectorEngine(); <START> return engine.contains(a, b); <END> }</code><technical_language>more standard getEngine() instead of maybiInitialize... return getEngine().contains ... I engine private instead of protected plugin is changed getEngine()</technical_language>

Target:
public static boolean contains(Element a, Element b) { return getSelectorEngine().contains(a, b); }
Source:
<code>public void close() throws IOException { try { release(resourceId); } catch (LightblueException e) { <START> throw new IOException("Unable to release lock: " + resourceId, e); <END> } }</code><technical_language>IOException API signature, do there. add a release() LightblueException</technical_language>

Target:
public void close() throws IOException { try { release(); } catch (LightblueException e) { throw new IOException("Unable to release lock: " + resourceId, e); } }