auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void validateLotNotes(final List<String> notes, final BindingResult errors) { if (notes.stream().anyMatch(s -> StringUtils.isBlank(s))) { errors.reject("lot.input.list.notes.null.or.empty", ""); throw new ApiRequestValidationException(errors.getAllErrors()); } <START> final List<String> filteredNotes = <END> notes.stream().filter(loteNotes -> loteNotes.length() > LOT_NOTES_MAX_LENGTH).map(s -> s).collect(Collectors.toList()); if (!Collections.isEmpty(filteredNotes)) { errors.reject("lot.notes.length", ""); throw new ApiRequestValidationException(errors.getAllErrors()); } }</code><technical_language>This validation implemented findAny, dont need in this case number of invalid notes</technical_language>

Target:
public void validateLotNotes(final List<String> notes, final BindingResult errors) { if (notes.stream().filter(s -> StringUtils.isBlank(s)).findAny().isPresent()) { errors.reject("lot.input.list.notes.null.or.empty", ""); throw new ApiRequestValidationException(errors.getAllErrors()); } final List<String> filteredNotes = notes.stream().filter(loteNotes -> loteNotes.length() > LOT_NOTES_MAX_LENGTH).map(s -> s).collect(Collectors.toList()); if (!Collections.isEmpty(filteredNotes)) { errors.reject("lot.notes.length", ""); throw new ApiRequestValidationException(errors.getAllErrors()); } }
Source:
<code>public AlteredFiles(Project project, String diff) { this.project = project; changedFilesStatuses = new LinkedHashMap<>(); <START> if (!"".equals(diff)) { <END> for (String item : diff.split("\n")) { changedFilesStatuses.put(item.substring(2, item.length()), defineStatus(item.substring(0, 1))); } } changedFilesList = new ArrayList<>(changedFilesStatuses.keySet()); }</code><technical_language>isNullOrEmpty</technical_language>

Target:
public AlteredFiles(Project project, String diff) { this.project = project; alteredFilesStatuses = new LinkedHashMap<>(); if (!isNullOrEmpty(diff)) { for (String item : diff.split("\n")) { if (item.length() < 3 || item.charAt(1) != '\t') { throw new IllegalArgumentException("Invalid git diff format. Invalid record: " + item); } alteredFilesStatuses.put( item.substring(2, item.length()), defineStatus(item.substring(0, 1))); } } alteredFilesList = new ArrayList<>(alteredFilesStatuses.keySet()); }
Source:
<code>public void deliverResult(List<Entity<TreeReference>> entities, List<TreeReference> references) { loader = null; Detail detail = session.getDetail(selectDatum.getShortDetail()); int[] order = detail.getSortOrder(); for(int i = 0 ; i < detail.getFields().length ; ++i) { String header = detail.getFields()[i].getHeader().evaluate(); if(order.length == 0 && !"".equals(header)) { order = new int[] {i}; } } ListView view = ((ListView)this.findViewById(R.id.screen_entity_select_list)); <START> System.out.println("717 in aweomse select : " + inAwesomeMode); <END> adapter = new EntityListAdapter(EntitySelectActivity.this, detail, references, entities, order, tts, this); view.setAdapter(adapter); findViewById(R.id.entity_select_loading).setVisibility(View.GONE); if(adapter != null) { adapter.applyFilter(filterString); } if(inAwesomeMode) { updateSelectedItem(true); } }</code><technical_language>oops</technical_language>

Target:
public void deliverResult(List<Entity<TreeReference>> entities, List<TreeReference> references) { loader = null; Detail detail = session.getDetail(selectDatum.getShortDetail()); int[] order = detail.getSortOrder(); for(int i = 0 ; i < detail.getFields().length ; ++i) { String header = detail.getFields()[i].getHeader().evaluate(); if(order.length == 0 && !"".equals(header)) { order = new int[] {i}; } } ListView view = ((ListView)this.findViewById(R.id.screen_entity_select_list)); adapter = new EntityListAdapter(EntitySelectActivity.this, detail, references, entities, order, tts, this); view.setAdapter(adapter); findViewById(R.id.entity_select_loading).setVisibility(View.GONE); if(adapter != null) { adapter.applyFilter(filterString); } if(inAwesomeMode) { updateSelectedItem(true); } }
Source:
<code>public Map<String, String> connectorConfig(String connName) { FutureCallback<Map<String, String>> connectorConfigCallback = new FutureCallback<>(); herder.connectorConfig(connName, connectorConfigCallback); try { <START> Map<String, String> result = connectorConfigCallback.get(herderRequestTimeoutMs, TimeUnit.MILLISECONDS); return new HashMap<>(result); <END> } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new ConnectException( String.format("Failed to retrieve configuration for connector '%s'", connName), e ); } }</code><technical_language>suggestion return new HashMap<>(connectorConfigCallback.get(herderRequestTimeoutMs, TimeUnit.MILLISECONDS););</technical_language>

Target:
public Map<String, String> connectorConfig(String connName) { FutureCallback<Map<String, String>> connectorConfigCallback = new FutureCallback<>(); herder.connectorConfig(connName, connectorConfigCallback); try { return new HashMap<>(connectorConfigCallback.get(herderRequestTimeoutMs, TimeUnit.MILLISECONDS)); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new ConnectException( String.format("Failed to retrieve configuration for connector '%s'", connName), e ); } }
Source:
<code>protected Set<byte[]> executeOperation(Transport transport) { HeaderParams params = writeHeader(transport, BULK_GET_KEYS_REQUEST); transport.flush(); <START> System.out.println("hello"); <END> readHeaderAndValidate(transport, params); System.out.println("validated"); Set<byte[]> result = new HashSet<byte[]>(); while ( transport.readByte() == 1) { result.add(transport.readArray()); } return result; }</code><technical_language>This line removed</technical_language>

Target:
protected Set<byte[]> executeOperation(Transport transport) { HeaderParams params = writeHeader(transport, BULK_GET_KEYS_REQUEST); transport.flush(); readHeaderAndValidate(transport, params); Set<byte[]> result = new HashSet<byte[]>(); while ( transport.readByte() == 1) { result.add(transport.readArray()); } return result; }
Source:
<code>public String toString() { String implKind = MethodHandleInfo.referenceKindToString(implMethodKind); <START> return String.format("SerializedLambda[%s=%s, %s=%s.%s:%s, " <END> + "%s=%s %s.%s:%s, %s=%s, %s=%d]", "capturingClass", capturingClass, "functionalInterfaceMethod", functionalInterfaceClass, functionalInterfaceMethodName, functionalInterfaceMethodSignature, "implementation", implKind, implClass, implMethodName, implMethodSignature, "instantiatedMethodType", instantiatedMethodType, "numCaptured", capturedArgs.length); }</code><technical_language>prefer string concatenation</technical_language>

Target:
public String toString() { String implKind = MethodHandleInfo.referenceKindToString(implMethodKind); return "SerializedLambda[capturingClass=" + capturingClass + ", functionalInterfaceMethod=" + functionalInterfaceClass + "." + functionalInterfaceMethodName + ":" + functionalInterfaceMethodSignature + ", " + "implementation=" + implKind + " " + implClass + "." + implMethodName + ":" + implMethodSignature + ", instantiatedMethodType=" + instantiatedMethodType + ", numCaptured=" + capturedArgs.length + "]"; }
Source:
<code>public void testSplitOmitEmptyLine() { List<String> clazzNames = Utils.splitClassNames("", ","); <START> Arrays.equals(clazzNames.toArray(new String[2]), null); <END> clazzNames = Utils.splitClassNames("a,b", ","); Arrays.equals(clazzNames.toArray(new String[2]), new String[]{"a", "b"}); clazzNames = Utils.splitClassNames("a,b,", ","); Arrays.equals(clazzNames.toArray(new String[2]), new String[]{"a", "b"}); clazzNames = Utils.splitClassNames("a, b,", ","); Arrays.equals(clazzNames.toArray(new String[2]), new String[]{"a", "b"}); }</code><technical_language>In checks, compare a list? e.g., in this case: assertEquals(Collections.<String>emptyList(), clazzNames); Arrays.asList for other tests items in class array. Also, calling asserts here, test testing anything</technical_language>

Target:
public void testSplitOmitEmptyLine() { List<String> clazzNames = Utils.splitClassNames("", ","); Assert.assertEquals(Collections.<String>emptyList(), clazzNames); clazzNames = Utils.splitClassNames("a,b", ","); Assert.assertEquals(Arrays.asList("a", "b"), clazzNames); clazzNames = Utils.splitClassNames("a,b,", ","); Assert.assertEquals(Arrays.asList("a", "b"), clazzNames); clazzNames = Utils.splitClassNames("a, b,", ","); Assert.assertEquals(Arrays.asList("a", "b"), clazzNames); }
Source:
<code>public List<Object> getJustificationList() { <START> return Collections.unmodifiableList(justificationList); <END> }</code><technical_language>duplicating in constructor wrapping in unmodifiable List call? do in constructor too? if worth though. This costs performance wise. 2 proposals: Proposal A): in constructor: Collections.unmodifiableList(new ArrayList<>(justificationList)) Proposal B: in constructor: Collections.unmodifiableList(justificationList) I suspect for DRL CS-B, proposal B is bugfree, duplication cost of proposal A is a perf loss. For CS-D duplicate giving constructor</technical_language>

Target:
public List<Object> getJustificationList() { return justificationList; }
Source:
<code>private String actResponse( final URI home, final String method, final String... headers ) throws IOException { return new RsPrint(new TkProxy( String.format( FORMAT, home.getHost(), home.getPort() ) ).act( new RqWithHeaders( new RqFake( <START> method, DASH <END> ), headers ) ) ).print(); }</code><technical_language>@aschworer DASH here, inline</technical_language>

Target:
private String actResponse( final URI home, final String method, final String... headers ) throws IOException { return new RsPrint(new TkProxy( proxy(home) ).act( new RqWithHeaders( new RqFake( method, "/" ), headers ) ) ).print(); }
Source:
<code>void write(ChannelOutboundInvoker out, ChannelPromise promise, ByteBufAllocator allocator) throws IOException { <START> Consumer<ByteBuf> consumer = (bb) -> { <END> bb.writeInt(credit); receiverId.writeTo(bb); }; writeToChannel(out, promise, allocator, consumer, ID, LENGTH); }</code><technical_language>Do avoid introducing another virtual/interface method call here, another object instantiation for lambda argument capture, is important this point? for common messages performance path (BufferResponse, AddCredit). BufferResponse is avoiding this, AddCredit well. If want avoid it, this pattern: java final ByteBuf buffer = allocateBuffer(allocator, ID, length); try { // code in consumer buffer.writeInt(....); ... out.write(result, promise); } catch (Throwable t) { handleException(buffer, t); } virtual call in exception case, extra object. minimally more verbose/duplicate</technical_language>

Target:
void write(ChannelOutboundInvoker out, ChannelPromise promise, ByteBufAllocator allocator) throws IOException { ByteBuf result = null; try { result = allocateBuffer(allocator, ID, 4 + 16); result.writeInt(credit); receiverId.writeTo(result); out.write(result, promise); } catch (Throwable t) { handleException(result, null, t); } }
Source:
<code>public AbstractFlatTextFormatParser( @Nullable final String listDelimiter, @Nullable final Map<String, String> multiValueDelimiter, final boolean hasHeaderRow, final int maxSkipHeaderRows ) { this.listDelimiter = listDelimiter != null ? listDelimiter : Parsers.DEFAULT_LIST_DELIMITER; this.multiValueDelimiter = multiValueDelimiter; this.multiValueTransformer = new Maps.EntryTransformer<String, String, Object>() { @Override public Object transformEntry(String key, String value) { String deli = null; if (AbstractFlatTextFormatParser.this.multiValueDelimiter == null) { deli = AbstractFlatTextFormatParser.this.listDelimiter; } else if (AbstractFlatTextFormatParser.this.multiValueDelimiter.get(key) != null) { deli = AbstractFlatTextFormatParser.this.multiValueDelimiter.get(key); } if (deli != null && value.contains(deli)) { <START> Splitter multiSplitter = Splitter.on(deli); <END> return StreamSupport.stream(multiSplitter.split(value).spliterator(), false) .map(Strings::emptyToNull) .collect(Collectors.toList()); } else { return Strings.emptyToNull(value); } } }; this.hasHeaderRow = hasHeaderRow; this.maxSkipHeaderRows = maxSkipHeaderRows; }</code><technical_language>a map of (delimiter -> splitter) avoid creating a splitter key</technical_language>

Target:
public AbstractFlatTextFormatParser( @Nullable final String listDelimiter, @Nullable final Map<String, String> multiValueDelimiter, final boolean hasHeaderRow, final int maxSkipHeaderRows ) { this.listDelimiter = listDelimiter != null ? listDelimiter : Parsers.DEFAULT_LIST_DELIMITER; this.multiValueDelimiter = multiValueDelimiter; this.deliSpliterMap = new HashMap<>(); this.hasHeaderRow = hasHeaderRow; this.maxSkipHeaderRows = maxSkipHeaderRows; }
Source:
<code>@Override public int read(byte[] buffer) throws IOException { if (offset + buffer.length >= limit) { <START> setLimit(2 * (offset + buffer.length)); <END> } int count = in.read(buffer); if (count != -1) { offset += count; } return count; }</code><technical_language>this behavior right. need buffering of data happen a marker is set (for reading image metadata) happen is marker (during actual full image decode). stands this a ton of allocation GC churn in case care buffering. approach killing this class for another InputStream decorator on-demand list of 2K byte[] chunks for infinite buffering a mark set. In ideal case a single 2K chunk allocated. In pathological degradation case allocate additional chunks needed reset</technical_language>

Target:
@Override public int read(byte[] buffer) throws IOException { if (!allowExpire && (offset + buffer.length > limit)) { setLimit(offset + buffer.length + limitIncrement); } int count = in.read(buffer); if (count != -1) { offset += count; } return count; }
Source:
<code>protected RowExpression visitSymbolReference(SymbolReference node, Void context) { <START> Integer field = layout.get(Symbol.from(node)); <END> if (field != null) { return field(field, getType(node)); } return new VariableReferenceExpression(node.getName(), getType(node)); }</code><technical_language>name this else? confusing field(field...)</technical_language>

Target:
protected RowExpression visitSymbolReference(SymbolReference node, Void context) { Integer channel = layout.get(Symbol.from(node)); if (channel != null) { return field(channel, getType(node)); } return new VariableReferenceExpression(node.getName(), getType(node)); }
Source:
<code>private static void registerResources( TimeLockServerConfiguration configuration, Environment environment, TimeLockServer serverImpl) { Map<String, TimeLockServices> clientToServices = ImmutableMap.copyOf(Maps.asMap( configuration.clients(), client -> serverImpl.createInvalidatingTimeLockServices(client, configuration.slowLockLogTriggerMillis()))); environment.getObjectMapper().registerModule(new Jdk8Module()); environment.jersey().register( <START> HttpRemotingJerseyFeature.with(HttpRemotingJerseyFeature.StacktracePropagation.PROPAGATE)); <END> environment.jersey().register(new TimeLockResource(clientToServices)); }</code><technical_language>remove this change</technical_language>

Target:
private static void registerResources( TimeLockServerConfiguration configuration, Environment environment, TimeLockServer serverImpl) { Map<String, TimeLockServices> clientToServices = ImmutableMap.copyOf(Maps.asMap( configuration.clients(), client -> serverImpl.createInvalidatingTimeLockServices(client, configuration.slowLockLogTriggerMillis()))); environment.getObjectMapper().registerModule(new Jdk8Module()); environment.jersey().register(HttpRemotingJerseyFeature.DEFAULT); environment.jersey().register(new TimeLockResource(clientToServices)); }
Source:
<code>public void setSizes(String... sizes) { if (this.sizes == null) { this.sizes = new ArrayList<>(); } <START> this.sizes.clear(); <END> this.sizes.addAll(Arrays.asList(sizes)); }</code><technical_language>in else</technical_language>

Target:
public void setSizes(String... sizes) { if (this.sizes == null) { this.sizes = new ArrayList<>(); } else { this.sizes.clear(); } this.sizes.addAll(Arrays.asList(sizes)); }
Source:
<code>private void handlePackError(IOException e, PackFile p) { String warnTmpl = null; if ((e instanceof CorruptObjectException) || (e instanceof PackInvalidException)) { warnTmpl = JGitText.get().corruptPack; removePack(p); } else if (e instanceof FileNotFoundException) { if (!p.getPackFile().exists()) { warnTmpl = JGitText.get().packWasDeleted; <START> } <END> removePack(p); } else if (FileUtils.isStaleFileHandle(e)) { warnTmpl = JGitText.get().packHandleIsStale; removePack(p); } if (warnTmpl != null) { if (LOG.isDebugEnabled()) { LOG.debug(MessageFormat.format(warnTmpl, p.getPackFile().getAbsolutePath()), e); } else { LOG.warn(MessageFormat.format(warnTmpl, p.getPackFile().getAbsolutePath())); } } else { LOG.error(MessageFormat.format( JGitText.get().exceptionWhileReadingPack, p.getPackFile() .getAbsolutePath()), e); } }</code><technical_language>this do } else { warnTmpl = "Pack file {0} inaccessible; removing pack list" }</technical_language>

Target:
private void handlePackError(IOException e, PackFile p) { String warnTmpl = null; if ((e instanceof CorruptObjectException) || (e instanceof PackInvalidException)) { warnTmpl = JGitText.get().corruptPack; removePack(p); } else if (e instanceof FileNotFoundException) { if (!p.getPackFile().exists()) { warnTmpl = JGitText.get().packInaccessible; } removePack(p); } else if (FileUtils.isStaleFileHandle(e)) { warnTmpl = JGitText.get().packHandleIsStale; removePack(p); } if (warnTmpl != null) { if (LOG.isDebugEnabled()) { LOG.debug(MessageFormat.format(warnTmpl, p.getPackFile().getAbsolutePath()), e); } else { LOG.warn(MessageFormat.format(warnTmpl, p.getPackFile().getAbsolutePath())); } } else { LOG.error(MessageFormat.format( JGitText.get().exceptionWhileReadingPack, p.getPackFile() .getAbsolutePath()), e); } }
Source:
<code>public void getConceptsCount_shouldGetCorrectConceptCount() { mDatabase.conceptRoomDAO().saveConcept(expectedConceptEntity1); mDatabase.conceptRoomDAO().saveConcept(expectedConceptEntity2); mDatabase.conceptRoomDAO().getConceptsCount() .test() <START> .assertValue(aLong -> Objects.equals(aLong, 2L)); <END> }</code><technical_language>A variable name is actualConceptsCount</technical_language>

Target:
public void getConceptsCount_shouldGetCorrectConceptCount() { mDatabase.conceptRoomDAO().saveConcept(expectedConceptEntity1); mDatabase.conceptRoomDAO().saveConcept(expectedConceptEntity2); mDatabase.conceptRoomDAO().getConceptsCount() .test() .assertValue(actualConceptsCount -> Objects.equals(actualConceptsCount, 2L)); }
Source:
<code>public Object perform(InvocationContext ctx) throws Throwable { MVCCEntry<Object, Object> e = (MVCCEntry) ctx.lookupEntry(key); if (e == null) { throw new IllegalStateException("Not wrapped"); } Object oldValue = e.getValue(); if (oldValue != null) { Object newValue = remappingBiFunction.apply(key, oldValue); if (newValue != null) { notifier.notifyCacheEntryModified(key, newValue, metadata, oldValue, e.getMetadata(), true, ctx, this); e.setChanged(true); e.setValue(newValue); Metadatas.updateMetadata(e, metadata); return newValue; } else { notifier.notifyCacheEntryRemoved(key, oldValue, e.getMetadata(), true, ctx, this); e.setRemoved(true); e.setValid(false); e.setChanged(true); e.setValue(null); return null; } } else if (!computeIfPresent) { Object newValue = remappingBiFunction.apply(key, oldValue); notifier.notifyCacheEntryCreated(key, newValue, metadata, true, ctx, this); e.setValue(newValue); <START> e.setChanged(true); <END> Metadatas.updateMetadata(e, metadata); if (e.isRemoved()) { e.setCreated(true); e.setExpired(false); e.setRemoved(false); e.setValid(true); } return newValue; } return oldValue; }</code><technical_language>If newValue == oldValue I call notifier update entry</technical_language>

Target:
public Object perform(InvocationContext ctx) throws Throwable { MVCCEntry<Object, Object> e = (MVCCEntry) ctx.lookupEntry(key); if (e == null) { throw new IllegalStateException("Not wrapped"); } Object oldValue = e.getValue(); Object newValue; if(computeIfPresent && oldValue == null) { successful = true; return oldValue; } try { newValue = remappingBiFunction.apply(key, oldValue); } catch (RuntimeException ex) { throw new UserRaisedFunctionalException(ex); } if (oldValue == null && newValue == null) { successful = true; return null; } Object computeResult = newValue; if (oldValue != null) { if (newValue != null) { notifier.notifyCacheEntryModified(key, newValue, metadata, oldValue, e.getMetadata(), true, ctx, this); e.setChanged(true); e.setValue(newValue); Metadatas.updateMetadata(e, metadata); } else { notifier.notifyCacheEntryRemoved(key, oldValue, e.getMetadata(), true, ctx, this); e.setRemoved(true); e.setValid(false); e.setChanged(true); e.setValue(null); } } else { notifier.notifyCacheEntryCreated(key, newValue, metadata, true, ctx, this); e.setValue(newValue); e.setChanged(true); Metadatas.updateMetadata(e, metadata); if (e.isRemoved()) { e.setCreated(true); e.setExpired(false); e.setRemoved(false); e.setValid(true); } } successful = true; return computeResult; }
Source:
<code>public T deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { JsonNode root = jsonParser.getCodec().readTree(jsonParser); <START> T tupelStore = deserialize(root); <END> ObjectNode tuplesObject = (ObjectNode) root.get("tuples"); Map<String, Collection<Tuple>> tuples = jsonParser.getCodec().readValue(jsonParser.getCodec().treeAsTokens(tuplesObject), TR); tupelStore.putAll(concat(tuples.values())); return tupelStore; }</code><technical_language>misspelling</technical_language>

Target:
public T deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { JsonNode root = jsonParser.getCodec().readTree(jsonParser); T tupleStore = deserialize(root); ObjectNode tuplesObject = (ObjectNode) root.get("tuples"); Map<String, Collection<Tuple>> tuples = jsonParser.getCodec().readValue(jsonParser.getCodec().treeAsTokens(tuplesObject), TR); tupleStore.putAll(concat(tuples.values())); return tupleStore; }
Source:
<code>public ActiveMQBuffer encode(CoreRemotingConnection connection) { if (connection != null && connection.getTransportConnection() instanceof NettyConnection) { ActiveMQBuffer buffer; int bufferSize = expectedEncodeSize(); if (fileId != -1 && dataSize > 0) { bufferSize -= dataSize; } buffer = createPacket(connection, bufferSize); encodeHeader(buffer); encodeRest(buffer, connection); encodeSize(buffer, expectedEncodeSize()); <START> return fileId != -1 && dataSize > 0 ? new FileDelegatedChannelBufferWrapper(file, offset, dataSize, buffer) : buffer; <END> } else { ActiveMQBuffer buffer = createPacket(connection); encodeHeader(buffer); encodeRest(buffer, connection); if (fileId != -1 && dataSize > 0) { readFile(buffer.toByteBuffer(buffer.writerIndex(), buffer.writableBytes())); buffer.writerIndex(buffer.capacity()); } encodeSize(buffer); return buffer; } }</code><technical_language>implies file is read lazily Netty apply zero-copy transfert, means need file moved deleted util zero-copy transfert finish</technical_language>

Target:
public ActiveMQBuffer encode(CoreRemotingConnection connection) { if (fileId != -1 && dataSize > 0) { ActiveMQBuffer buffer; int bufferSize = expectedEncodeSize(); int encodedSize = bufferSize; boolean isNetty = false; if (connection != null && connection.getTransportConnection() instanceof NettyConnection) { bufferSize -= dataSize; isNetty = true; } buffer = createPacket(connection, bufferSize); encodeHeader(buffer); encodeRest(buffer, connection); if (!isNetty) { ByteBuffer byteBuffer; if (buffer.byteBuf() != null && buffer.byteBuf().nioBufferCount() == 1) { byteBuffer = buffer.byteBuf().internalNioBuffer(buffer.writerIndex(), buffer.writableBytes()); } else { byteBuffer = buffer.toByteBuffer(buffer.writerIndex(), buffer.writableBytes()); } readFile(byteBuffer); buffer.writerIndex(buffer.capacity()); } encodeSize(buffer, encodedSize); return buffer; } else { return super.encode(connection); } }
Source:
<code>public Response putReport(@BeanParam final Coordinates coordinates, final List<JUnitFeature> root) { final MongoDatabase bdd = this.client.getDatabase("bdd"); final FeatureMapper featureMapper = new FeatureMapper(this.imageDao); this.summaryDao.updateSummary(coordinates); List<XbddFeature> mappedFeatures = root.stream().map(feature -> featureMapper.map(feature, coordinates)).collect(Collectors.toList()); this.featureDao.saveFeatures(mappedFeatures); List<XbddFeature> persistedFeatures = this.featureDao.getFeatures(coordinates); this.statsDao.updateStatsForFeatures(coordinates, persistedFeatures); <START> return Response.ok(SerializerUtil.serialise(persistedFeatures)).build(); <END> }</code><technical_language>I need call serialise anymore proper DTOs return - able return DTOs serialise itself</technical_language>

Target:
public Response putReport(@BeanParam final Coordinates coordinates, final List<JUnitFeature> root) { final FeatureMapper featureMapper = new FeatureMapper(this.imageDao); this.summaryDao.updateSummary(coordinates); List<XbddFeature> mappedFeatures = root.stream().map(feature -> featureMapper.map(feature, coordinates)).collect(Collectors.toList()); this.featureDao.saveFeatures(mappedFeatures); List<XbddFeature> persistedFeatures = this.featureDao.getFeatures(coordinates); this.statsDao.updateStatsForFeatures(coordinates, persistedFeatures); return Response.ok(persistedFeatures).build(); }
Source:
<code>public static OGCGeometry deserialize(Slice shape) { requireNonNull(shape, "shape is null"); int wkid = shape.getInt(0); ByteBuffer shapeBuffer = getShapeByteBuffer(shape); <START> if (shapeBuffer.limit() < 4) { <END> return null; } else { if (shapeBuffer.getInt(0) == Geometry.Type.Unknown.value()) { return null; } else { SpatialReference spatialReference = null; if (wkid != WKID_UNKNOWN) { spatialReference = SpatialReference.create(wkid); } Geometry esriGeom = OperatorImportFromESRIShape.local().execute(0, Geometry.Type.Unknown, shapeBuffer); OGCGeometry createdGeom = OGCGeometry.createFromEsriGeometry(esriGeom, spatialReference); return createdGeom; } } }</code><technical_language>4 -> SIZE_WKID</technical_language>

Target:
public static OGCGeometry deserialize(Slice shape) { if (shape == null) { return null; } BasicSliceInput input = shape.getInput(); int spatialReferenceId = input.readInt(); SpatialReference spatialReference = null; if (spatialReferenceId != SPATIAL_REFERENCE_UNKNOWN) { spatialReference = SpatialReference.create(spatialReferenceId); } List<OGCGeometry> geometries = new ArrayList<>(); while (input.available() > 0) { int length = input.readInt(); ByteBuffer buffer = input.readSlice(length).toByteBuffer().slice().order(LITTLE_ENDIAN); Geometry esriGeometry = local().execute(0, Unknown, buffer); OGCGeometry geometry = createFromEsriGeometry(esriGeometry, spatialReference); geometries.add(geometry); } if (geometries.isEmpty()) { return new OGCConcreteGeometryCollection(emptyList(), spatialReference); } else if (geometries.size() == 1) { return geometries.get(0); } return new OGCConcreteGeometryCollection(geometries, spatialReference); }
Source:
<code>public void onBindViewHolder(ViewHolder holder, Repository repository) { holder.tvTitle.setText(repository.owner().login() + "/" + repository.name()); if (!StringUtils.isBlank(repository.description())) { holder.tvDesc.setVisibility(View.VISIBLE); holder.tvDesc.setText( EmojiParser.parseToUnicode(StringUtils.doTeaser(repository.description()))); } else { holder.tvDesc.setVisibility(View.GONE); } holder.tvLanguage.setText(repository.language() != null ? repository.language() : mContext.getString(R.string.unknown)); holder.tvForks.setText(String.valueOf(repository.forksCount())); <START> holder.tvStars.setText(String.valueOf(repository.subscribersCount())); <END> holder.tvSize.setText(Formatter.formatFileSize(mContext, 1024L * repository.size())); holder.tvPrivate.setVisibility(repository.isPrivate() ? View.VISIBLE : View.GONE); holder.tvFork.setVisibility(repository.isFork() ? View.VISIBLE : View.GONE); }</code><technical_language>for stars count..</technical_language>

Target:
public void onBindViewHolder(ViewHolder holder, Repository repository) { holder.tvTitle.setText(repository.owner().login() + "/" + repository.name()); if (!StringUtils.isBlank(repository.description())) { holder.tvDesc.setVisibility(View.VISIBLE); holder.tvDesc.setText( EmojiParser.parseToUnicode(StringUtils.doTeaser(repository.description()))); } else { holder.tvDesc.setVisibility(View.GONE); } holder.tvLanguage.setText(repository.language() != null ? repository.language() : mContext.getString(R.string.unknown)); holder.tvForks.setText(String.valueOf(repository.forksCount())); holder.tvStars.setText(String.valueOf(repository.stargazersCount())); holder.tvSize.setText(Formatter.formatFileSize(mContext, 1024L * repository.size())); holder.tvPrivate.setVisibility(repository.isPrivate() ? View.VISIBLE : View.GONE); holder.tvFork.setVisibility(repository.isFork() ? View.VISIBLE : View.GONE); }
Source:
<code>private void convertMutations(TabletServerMutations<QCMutation> mutations, Map<Long,CMK> cmidToCm, MutableLong cmid, Map<TKeyExtent,List<TConditionalMutation>> tmutations, CompressedIterators compressedIters) { mutations.getMutations().forEach((keyExtent, mutationList) -> { <START> ArrayList<TConditionalMutation> tcondMutaions = new ArrayList<>(); <END> for (var cm : mutationList) { TMutation tm = cm.toThrift(); List<TCondition> conditions = convertConditions(cm, compressedIters); cmidToCm.put(cmid.longValue(), new CMK(keyExtent, cm)); TConditionalMutation tcm = new TConditionalMutation(conditions, tm, cmid.longValue()); cmid.increment(); tcondMutaions.add(tcm); } tmutations.put(keyExtent.toThrift(), tcondMutaions); }); }</code><technical_language>var too. :smiley_cat:</technical_language>

Target:
private void convertMutations(TabletServerMutations<QCMutation> mutations, Map<Long,CMK> cmidToCm, MutableLong cmid, Map<TKeyExtent,List<TConditionalMutation>> tmutations, CompressedIterators compressedIters) { mutations.getMutations().forEach((keyExtent, mutationList) -> { var tcondMutaions = new ArrayList<TConditionalMutation>(); for (var cm : mutationList) { TMutation tm = cm.toThrift(); List<TCondition> conditions = convertConditions(cm, compressedIters); cmidToCm.put(cmid.longValue(), new CMK(keyExtent, cm)); TConditionalMutation tcm = new TConditionalMutation(conditions, tm, cmid.longValue()); cmid.increment(); tcondMutaions.add(tcm); } tmutations.put(keyExtent.toThrift(), tcondMutaions); }); }
Source:
<code>public SolenoidSubsystem(String name, boolean isInverted, SolenoidState defaultState, DoubleSolenoid... solenoids) { <START> setName(name); <END> setDefaultCommand(new SolenoidSet(this, defaultState)); this.solenoids = solenoids; this.isInverted = isInverted; this.defaultState = defaultState; this.state = defaultState; }</code><technical_language>@Exr0n call super()</technical_language>

Target:
public SolenoidSubsystem(String name, boolean isInverted, SolenoidState defaultState, DoubleSolenoid... solenoids) { super(); setName(name); setDefaultCommand(new SolenoidSet(this, defaultState)); this.solenoids = solenoids; this.isInverted = isInverted; this.defaultState = defaultState; this.state = defaultState; }
Source:
<code>public CompletableFuture<Long> getUsage(PublicKeyHash owner) { Stat stat = state.currentView.get(owner); if (stat == null) return CompletableFuture.completedFuture(0L); <START> Usage usage = state.usage.get(stat.owner); <END> if (usage == null) return CompletableFuture.completedFuture(0L); return CompletableFuture.completedFuture(usage.usage); }</code><technical_language>change name of this variable? a confusing read usage.usage a type Usage. storageUsed</technical_language>

Target:
public CompletableFuture<Long> getUsage(PublicKeyHash owner) { Stat stat = state.currentView.get(owner); if (stat == null) return Futures.errored(new IllegalStateException("Unknown identity key: " + owner)); Usage usage = state.usage.get(stat.owner); if (usage == null) return Futures.errored(new IllegalStateException("No usage present for user: " + stat.owner)); return CompletableFuture.completedFuture(usage.totalBytes); }
Source:
<code>public Builder setPGStartupWait(Duration pgStartupWait) { if (pgStartupWait != null && pgStartupWait.isNegative()) { pgStartupWait = null; } <START> Objects.requireNonNull(pgStartupWait); <END> this.pgStartupWait = pgStartupWait; return this; }</code><technical_language>right setPGStatupWait(Duration.ofSeconds(-1)) throws NullPointerException, silently replace a zero duration, throw IllegalArgumentException</technical_language>

Target:
public Builder setPGStartupWait(Duration pgStartupWait) { Objects.requireNonNull(pgStartupWait); if (pgStartupWait.isNegative()) { throw new IllegalArgumentException("Negative durations are not permitted."); } this.pgStartupWait = pgStartupWait; return this; }
Source:
<code>private void assertJobHasStoppedOrFail(String jobName, long timeoutInMillis) throws InterruptedException { <START> long startTime = System.currentTimeMillis(); <END> long endTime = startTime + timeoutInMillis; while (startTime < endTime + 1000) { page.clickButton("Refresh"); if (page.getBatchStatusFromRow(page.selectRowForJob(jobName)).equals("STOPPED")) { return; } TimeUnit.MILLISECONDS.sleep(500); startTime = System.currentTimeMillis(); } fail("Job should have been STOPPED by now"); }</code><technical_language>startTime is changing I suggest rename currentTime loop condition more clear</technical_language>

Target:
private void assertJobHasStoppedOrFail(String jobName, long timeoutInMillis) throws InterruptedException { BatchTableRowFragment jobRow = page.selectRowForJobXmlName(jobName); long currentTime = System.currentTimeMillis(); long endTime = currentTime + timeoutInMillis; while (currentTime < endTime + 1000) { page.clickButton("Refresh"); if (jobRow.getBatchStatusValue().equals("STOPPED")) { return; } TimeUnit.MILLISECONDS.sleep(500); currentTime = System.currentTimeMillis(); } fail("Job should have been STOPPED by now"); }
Source:
<code>protected void executeVmCommand() { Guid createdSnapshotId = updateActiveSnapshotId(); setActionReturnValue(createdSnapshotId); getParameters().setCreatedSnapshotId(createdSnapshotId); MemoryImageBuilder memoryImageBuilder = getMemoryImageBuilder(); freezeVm(); ActionReturnValue actionReturnValue = createSnapshotsForDisks(); if (actionReturnValue.getSucceeded()) { memoryImageBuilder.build(); addSnapshotToDB(createdSnapshotId, memoryImageBuilder); fastForwardDisksToActiveSnapshot(); setSucceeded(true); } <START> else { setSucceeded(false); } <END> }</code><technical_language>redundant, right</technical_language>

Target:
protected void executeVmCommand() { Guid createdSnapshotId = updateActiveSnapshotId(); setActionReturnValue(createdSnapshotId); getParameters().setCreatedSnapshotId(createdSnapshotId); MemoryImageBuilder memoryImageBuilder = getMemoryImageBuilder(); freezeVm(); ActionReturnValue actionReturnValue = createSnapshotsForDisks(); if (actionReturnValue.getSucceeded()) { memoryImageBuilder.build(); addSnapshotToDB(createdSnapshotId, memoryImageBuilder); fastForwardDisksToActiveSnapshot(); setSucceeded(true); } }
Source:
<code>public UnifiedPushArchive withMessageDrivenBeans() { return addClasses(AbstractJMSMessageListener.class) .addClasses(MessageHolderWithVariantsConsumer.class, MessageHolderWithVariantsProducer.class) .addClasses(MessageHolderWithTokensConsumer.class, MessageHolderWithTokensProducer.class) .addClasses(TriggerMetricCollectionConsumer.class) <START> .addAsWebInfResource(new File("../../servers/ups-wildfly/src/main/webapp/WEB-INF/jboss-ejb3.xml"), "jboss-ejb3.xml"); <END> }</code><technical_language>paths file names extracted constants, specially if reused in more places</technical_language>

Target:
public UnifiedPushArchive withMessageDrivenBeans() { return addClasses(AbstractJMSMessageListener.class) .addClasses(MessageHolderWithVariantsConsumer.class, MessageHolderWithVariantsProducer.class) .addClasses(MessageHolderWithTokensConsumer.class, MessageHolderWithTokensProducer.class) .addClasses(TriggerMetricCollectionConsumer.class) .addAsWebInfResource(new File(WEB_RESOURCE_PATH + "jboss-ejb3.xml"), "jboss-ejb3.xml"); }
Source:
<code><START> private void writePromiseCombiner(ChannelHandlerContext ctx, CodecOutputList out, ChannelPromise promise) { <END> final PromiseCombiner combiner = new PromiseCombiner(); for (int i = 0; i < out.size(); i++) { combiner.add(ctx.write(out.getUnsafe(i))); } combiner.finish(promise); }</code><technical_language>Static</technical_language>

Target:
private static void writePromiseCombiner(ChannelHandlerContext ctx, CodecOutputList out, ChannelPromise promise) { final PromiseCombiner combiner = new PromiseCombiner(); for (int i = 0; i < out.size(); i++) { combiner.add(ctx.write(out.getUnsafe(i))); } combiner.finish(promise); }
Source:
<code>public void cleanCompletedJob() { Date now = new Date(); try { DbFacade.getInstance() <START> .getJobDao() <END> .deleteCompletedJobs(DateUtils.addMinutes(now, succeededJobTime), DateUtils.addMinutes(now, failedJobTime)); } catch (RuntimeException e) { log.error("Failed to delete completed jobs", e); } }</code><technical_language>is ugly, create a strange errors working java.uitl.Date Please System.currenttimeinmillis (whatever) + minutes * 60 * 1000 new Date(value)</technical_language>

Target:
public void cleanCompletedJob() { Date succeededJobsDeleteTime = new Date(System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(succeededJobTime, TimeUnit.MINUTES)); Date failedJobsDeleteTime = new Date(System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(failedJobTime, TimeUnit.MINUTES)); try { DbFacade.getInstance().getJobDao().deleteCompletedJobs(succeededJobsDeleteTime, failedJobsDeleteTime); } catch (RuntimeException e) { log.error("Failed to delete completed jobs", e); } }
Source:
<code>protected void initializeWatchService() { if (watchService != null) { try { watchService.close(); } catch (IOException e) { logger.warn("Cannot deactivate folder watcher", e); } } String pathToWatch = getSourcePath(); if (StringUtils.isNotBlank(pathToWatch)) { Path toWatch = Paths.get(pathToWatch); try { if (watchSubDirectories()) { watchService = FileSystems.getDefault().newWatchService(); <START> Files.walkFileTree(toWatch, Sets.newHashSet(FileVisitOption.FOLLOW_LINKS), MAX_DEPTH, <END> new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path subDir, BasicFileAttributes attrs) throws IOException { registerDirectory(subDir); return FileVisitResult.CONTINUE; } }); } else { watchService = toWatch.getFileSystem().newWatchService(); registerDirectory(toWatch); } AbstractWatchQueueReader reader = buildWatchQueueReader(watchService, toWatch); Thread qr = new Thread(reader, "Dir Watcher"); qr.start(); } catch (IOException e) { logger.error("Cannot activate folder watcher for folder '{}': {}", toWatch, e.getMessage()); } } }</code><technical_language>is max depth related "adding follow symlink option"? - do need restrict depth of abstract watch service? a specific usage if depth is limited a specific value</technical_language>

Target:
protected void initializeWatchService() { if (watchService != null) { try { watchService.close(); } catch (IOException e) { logger.warn("Cannot deactivate folder watcher", e); } } String pathToWatch = getSourcePath(); if (StringUtils.isNotBlank(pathToWatch)) { Path toWatch = Paths.get(pathToWatch); try { if (watchSubDirectories()) { watchService = FileSystems.getDefault().newWatchService(); Files.walkFileTree(toWatch, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path subDir, BasicFileAttributes attrs) throws IOException { registerDirectory(subDir); return FileVisitResult.CONTINUE; } }); } else { watchService = toWatch.getFileSystem().newWatchService(); registerDirectory(toWatch); } AbstractWatchQueueReader reader = buildWatchQueueReader(watchService, toWatch); Thread qr = new Thread(reader, "Dir Watcher"); qr.start(); } catch (IOException e) { logger.error("Cannot activate folder watcher for folder '{}': {}", toWatch, e.getMessage()); } } }
Source:
<code>public void init(List<TransformFunction> arguments, Map<String, DataSource> dataSourceMap) { _arguments = arguments; Preconditions <START> .checkState(arguments.size() > 1, String.format("Expect more than 1 argument for logical operator [%s], found %d.", getName(), arguments.size())); <END> for (TransformFunction argument : arguments) { Preconditions.checkState( argument.getResultMetadata().getDataType().isNumeric() && argument.getResultMetadata().isSingleValue(), String .format( "Unsupported data type for logical operator [%s] arguments, only supports single-valued number. Invalid argument: expression [%s], result type [%s]", getName(), argument.getName(), argument.getResultMetadata())); } }</code><technical_language>print out actual values of arguments here</technical_language>

Target:
public void init(List<TransformFunction> arguments, Map<String, DataSource> dataSourceMap) { _arguments = arguments; Preconditions.checkState(arguments.size() > 1, String .format("Expect more than 1 argument for logical operator [%s], args [%s].", getName(), Arrays.toString(arguments.toArray()))); for (TransformFunction argument : arguments) { Preconditions.checkState( argument.getResultMetadata().getDataType().isNumeric() && argument.getResultMetadata().isSingleValue(), String .format( "Unsupported data type for logical operator [%s] arguments, only supports single-valued number. Invalid argument: expression [%s], result type [%s]", getName(), argument.getName(), argument.getResultMetadata())); } }
Source:
<code><START> private static String getOriginModuleUrl(Module module) { <END> if (module == null) { throw new IllegalArgumentException("ModuleMarkupScraper:getOriginModuleUrl() - Module must be valid."); } final String origin = ExtraDataModuleExtension.getOrigin(module); if (StringUtils.isBlank(origin) && !INTERNAL_MODULES.contains(module.getId().toString())) { return DEFAULT_GITHUB_MODULE_URL + module.getId(); } return origin; }</code><technical_language>If want for a bit more type safety encode Url actual Url. This is needed main goal is produce markdown output, though</technical_language>

Target:
private static String getOriginModuleUrl(Module module) { Preconditions.checkNotNull(module); final String origin = ExtraDataModuleExtension.getOrigin(module); if (StringUtils.isBlank(origin) && !INTERNAL_MODULES.contains(module.getId().toString())) { try { return new URL(DEFAULT_GITHUB_MODULE_URL + module.getId()).toString(); }catch (MalformedURLException e) { e.printStackTrace(); } } return origin; }
Source:
<code>public ScanResultValue next() { if (ScanQuery.ResultFormat.RESULT_FORMAT_VALUE_VECTOR.equals(resultFormat)) { throw new UOE(ScanQuery.ResultFormat.RESULT_FORMAT_VALUE_VECTOR + " is not supported yet"); } if (query.getOrder() == ScanQuery.Order.NONE || <START> !query.getContextBoolean(ScanQuery.CTX_KEY_OUTERMOST, true)) { <END> ScanResultValue batch = yielder.get(); List events = (List) batch.getEvents(); if (events.size() <= limit - count) { count += events.size(); yielder = yielder.next(null); return batch; } else { int numLeft = (int) (limit - count); count = limit; return new ScanResultValue(batch.getSegmentId(), batch.getColumns(), events.subList(0, numLeft)); } } else { int batchSize = query.getBatchSize(); List<Object> eventsToAdd = new ArrayList<>(batchSize); List<String> columns = new ArrayList<>(); while (eventsToAdd.size() < batchSize && !yielder.isDone() && count < limit) { ScanResultValue srv = yielder.get(); columns = columns.isEmpty() ? srv.getColumns() : columns; eventsToAdd.add(Iterables.getOnlyElement((List) srv.getEvents())); yielder = yielder.next(null); count++; } return new ScanResultValue(null, columns, eventsToAdd); } }</code><technical_language>!query.getContextBoolean(ScanQuery.CTX_KEY_OUTERMOST, true) needs flipped query.getContextBoolean(ScanQuery.CTX_KEY_OUTERMOST, true)</technical_language>

Target:
public ScanResultValue next() { if (ScanQuery.ResultFormat.RESULT_FORMAT_VALUE_VECTOR.equals(resultFormat)) { throw new UOE(ScanQuery.ResultFormat.RESULT_FORMAT_VALUE_VECTOR + " is not supported yet"); } if (query.getOrder() == ScanQuery.Order.NONE || !query.getContextBoolean(ScanQuery.CTX_KEY_OUTERMOST, true)) { ScanResultValue batch = yielder.get(); List events = (List) batch.getEvents(); if (events.size() <= limit - count) { count += events.size(); yielder = yielder.next(null); return batch; } else { int numLeft = (int) (limit - count); count = limit; return new ScanResultValue(batch.getSegmentId(), batch.getColumns(), events.subList(0, numLeft)); } } else { int batchSize = query.getBatchSize(); List<Object> eventsToAdd = new ArrayList<>(batchSize); List<String> columns = new ArrayList<>(); while (eventsToAdd.size() < batchSize && !yielder.isDone() && count < limit) { ScanResultValue srv = yielder.get(); columns = columns.isEmpty() ? srv.getColumns() : columns; eventsToAdd.add(Iterables.getOnlyElement((List<Object>) srv.getEvents())); yielder = yielder.next(null); count++; } return new ScanResultValue(null, columns, eventsToAdd); } }
Source:
<code>public void writeString(Utf8 utf8) throws IOException { <START> out.write(utf8.getBytes(), 0, utf8.getBytesLength()); <END> }</code><technical_language>I Travis build failed a typo. method is called getByteLength() (no 's'). If fix update PR, I merge this in</technical_language>

Target:
public void writeString(Utf8 utf8) throws IOException { out.write(utf8.getBytes(), 0, utf8.getByteLength()); }
Source:
<code>public boolean condition(List<Writable> list){ PythonVariables inputs = getPyInputsFromWritables(list); try{ PythonVariables output = PythonExecutioner.getInstance().exec(pythonTransform, inputs); boolean ret = output.getIntValue("out") != 0; return ret; } catch (Exception e){ <START> System.out.println(e); <END> } return true; }</code><technical_language>Slf4j logging please</technical_language>

Target:
public boolean condition(List<Writable> list){ PythonVariables inputs = getPyInputsFromWritables(list); try{ PythonExecutioner.exec(pythonTransform.getCode(), inputs, pythonTransform.getOutputs()); boolean ret = pythonTransform.getOutputs().getIntValue("out") != 0; return ret; } catch (Exception e){ throw new RuntimeException(e); } }
Source:
<code>private void handleMachineRunning(final String machineId, final WorkspaceRuntimeDto workspaceRuntime) { final MachineEntity machine = getMachine(machineId, workspaceRuntime); if (machine == null) { return; } try { <START> eventBus.fireEvent(new MachineStateEvent(machine, RUNNING)); <END> } catch (Exception e) { Log.error(MachineStatusHandler.class, e.getMessage(), e); } }</code><technical_language>Firing event wrapped in try block... in codebase. interesting. explain, please, motivation of this</technical_language>

Target:
private void handleMachineRunning(final String machineId, final WorkspaceRuntimeDto workspaceRuntime) { final MachineEntity machine = getMachine(machineId, workspaceRuntime); if (machine == null) { return; } eventBus.fireEvent(new MachineStateEvent(machine, RUNNING)); }