auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Date getUpdatedAt() { if (updatedAt == null) { updatedAt = new Date(Const.DEFAULT_STUDENT_CREATION_DATE); <START> } <END> return updatedAt; }</code><technical_language>issues here: 1. do if createdAt == null ? ... : ... shorter. 2. code is "if field is null, update default first, get it", match "getCreated/UpdatedAt" "seems" do? If implement 1 avoid this problem also</technical_language>

Target:
public Date getUpdatedAt() { return (updatedAt == null) ? Const.TIME_REPRESENTS_DEFAULT_TIMESTAMP : updatedAt; }
Source:
<code>public String enchantment$getName() { <START> return I18n.translateToLocal(shadow$getName()); <END> }</code><technical_language>Is this change intended</technical_language>

Target:
public String enchantment$getName() { return shadow$getName(); }
Source:
<code>public CompletableFuture<Void> handleDiscoveryTask(DiscoveryConfiguration config) { <START> this.configFactory = new DiscoveryConfigFactory(config); <END> final Map<String, List<DiscoveryJob>> jobsByLocation = rangeChunker.chunk(config); if (jobsByLocation.size() == 0) { LOG.info("No IP addresses to discover."); return CompletableFuture.completedFuture(null); } final int taskId = taskIdTracker.incrementAndGet(); final List<CompletableFuture<Void>> futures = new ArrayList<>(jobsByLocation.keySet().size()); Logging.withPrefix(Discovery.getLoggingCategory(), new Runnable() { @Override public void run() { jobsByLocation.entrySet().stream() .map(e -> triggerJobsAsync(e.getKey(), e.getValue(), taskId)) .forEach(futures::add); } }); return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])); }</code><technical_language>carry this DiscoveryJob storing a member variable - this breaks thread safety of DiscoveryTaskExecutor implementation</technical_language>

Target:
public CompletableFuture<Void> handleDiscoveryTask(DiscoveryConfiguration config) { final Map<String, List<DiscoveryJob>> jobsByLocation = rangeChunker.chunk(config); if (jobsByLocation.size() == 0) { LOG.info("No IP addresses to discover."); return CompletableFuture.completedFuture(null); } final int taskId = taskIdTracker.incrementAndGet(); final List<CompletableFuture<Void>> futures = new ArrayList<>(jobsByLocation.keySet().size()); Logging.withPrefix(Discovery.getLoggingCategory(), new Runnable() { @Override public void run() { jobsByLocation.entrySet().stream() .map(e -> triggerJobsAsync(e.getKey(), e.getValue(), taskId)) .forEach(futures::add); } }); return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])); }
Source:
<code>public EhcacheEntityMessage decodeMessage(byte[] payload) throws MessageCodecException { ByteBuffer payloadBuf = ByteBuffer.wrap(payload); if (payloadBuf.get() == 1) { <START> return LifeCycleOpCodec.decode(payloadBuf); <END> } else { return ServerStoreOpCodec.decode(payload); } }</code><technical_language>this lack symmetry w.r.t byte signifying type is coded. Also, payloadBuf.get() == 1 hardcoded affecting readability increasing brittleness,.can a const enum specifies type?. if (payloadBuf.get() == EhcacheEntityMessage.Type.LIFECYCLE_OP.getOpCode())</technical_language>

Target:
public EhcacheEntityMessage decodeMessage(byte[] payload) throws MessageCodecException { ByteBuffer payloadBuf = ByteBuffer.wrap(payload); if (payloadBuf.get() == EhcacheEntityMessage.Type.LIFECYCLE_OP.getOpCode()) { return LifeCycleOpCodec.decode(payloadBuf); } else { return ServerStoreOpCodec.decode(payload); } }
Source:
<code>private static boolean setValueIsSameAsDefaultValue(@Nullable Object defaultValue, Tree valueSet) { if (valueSet.is(Tree.Kind.STRING_LITERAL)) { return LiteralUtils.trimQuotes(((LiteralTree) valueSet).value()).equals(defaultValue); } else if (valueSet.is(Tree.Kind.INT_LITERAL)) { <START> return LiteralUtils.intLiteralValue((LiteralTree) valueSet).equals(defaultValue); <END> } return false; }</code><technical_language>This is a FP handled. @interface MyAnnotation { int myHexaInteger() default 0x000; // trigger a FP }</technical_language>

Target:
private static boolean setValueIsSameAsDefaultValue(@Nullable Object defaultValue, Tree valueSet) { if (valueSet.is(Tree.Kind.STRING_LITERAL)) { return LiteralUtils.trimQuotes(((LiteralTree) valueSet).value()).equals(defaultValue); } else if (valueSet.is(Tree.Kind.INT_LITERAL)) { Integer intLiteralValue = LiteralUtils.intLiteralValue((LiteralTree) valueSet); return intLiteralValue != null && intLiteralValue.equals(defaultValue); } return false; }
Source:
<code>public void phaseEnded(LocalSearchPhaseScope phaseScope) { super.phaseEnded(phaseScope); initialWaterLevel = null; waterLevelIncrementRatio = DEFAULT_WATER_LEVEL_INCREMENT_RATIO; <START> waterLevelIncrementScore = null; <END> }</code><technical_language>Bug: running phase (not reproducible right now) forget settings. remove 2 lines</technical_language>

Target:
public void phaseEnded(LocalSearchPhaseScope phaseScope) { super.phaseEnded(phaseScope); initialWaterLevel = null; }
Source:
<code>public void doStart() { List<StreamListener> listeners = new ArrayList<>(); listeners.add(new StreamListener() { @Override public void onTweet(Tweet tweet) { try { sendMessage(MessageBuilder.withPayload(objectMapper.writeValueAsString(tweet)).build()); } catch (JsonProcessingException e) { logger.debug("JSON processing exception while processing the tweet: " + e); } } @Override public void onDelete(StreamDeleteEvent deleteEvent) { } @Override public void onLimit(int numberOfLimitedTweets) { logger.info("The stream is being track limited for " + numberOfLimitedTweets + " tweets."); } @Override public void onWarning(StreamWarningEvent warningEvent) { logger.error("Streaming source is in the danger of being disconnected."); } }); <START> if (this.streamType.equalsIgnoreCase(TwitterStreamProperties.FIREHOSE)) { <END> twitterTemplate.streamingOperations().firehose(listeners); } else { twitterTemplate.streamingOperations().sample(listeners); } }</code><technical_language>enum</technical_language>

Target:
public void doStart() { List<StreamListener> listeners = new ArrayList<>(); listeners.add(new StreamListener() { @Override public void onTweet(Tweet tweet) { try { sendMessage(MessageBuilder.withPayload(objectMapper.writeValueAsString(tweet)).build()); } catch (JsonProcessingException e) { logger.debug("JSON processing exception while processing the tweet: " + e); } } @Override public void onDelete(StreamDeleteEvent deleteEvent) { } @Override public void onLimit(int numberOfLimitedTweets) { logger.info("The stream is being track limited for " + numberOfLimitedTweets + " tweets."); } @Override public void onWarning(StreamWarningEvent warningEvent) { logger.error("Streaming source is in the danger of being disconnected."); } }); if (this.streamType.equals(TwitterStreamType.FIREHOSE)) { twitterTemplate.streamingOperations().firehose(listeners); } else { twitterTemplate.streamingOperations().sample(listeners); } }
Source:
<code>public void testActions(final IntervalListTools.Action action, final long bases, final int intervals) throws IOException { final IntervalList il = tester(action); <START> Assert.assertEquals(il.getBaseCount(), bases, "unexpcted number of bases found."); <END> Assert.assertEquals(il.getIntervals().size(), intervals, "unexpcted number of intervals found."); }</code><technical_language>"unexpected" (and wrong in line below)</technical_language>

Target:
public void testActions(final IntervalListTools.Action action, final long bases, final int intervals) throws IOException { final IntervalList il = tester(action); Assert.assertEquals(il.getBaseCount(), bases, "unexpected number of bases found."); Assert.assertEquals(il.getIntervals().size(), intervals, "unexpected number of intervals found."); }
Source:
<code>public void test_ensureOnlyOne() { <START> assertEquals(Arrays.asList().stream().reduce(Guavate.ensureOnlyOne()), Optional.empty()); <END> assertEquals(Arrays.asList("a").stream().reduce(Guavate.ensureOnlyOne()), Optional.of("a")); assertThrowsIllegalArg(() -> Arrays.asList("a", "b").stream().reduce(Guavate.ensureOnlyOne())); }</code><technical_language>Stream.empty() instead of Arrays.asList().stream()</technical_language>

Target:
public void test_ensureOnlyOne() { assertEquals(Stream.empty().reduce(Guavate.ensureOnlyOne()), Optional.empty()); assertEquals(Stream.of("a").reduce(Guavate.ensureOnlyOne()), Optional.of("a")); assertThrowsIllegalArg(() -> Stream.of("a", "b").reduce(Guavate.ensureOnlyOne())); }
Source:
<code>private void merge(PushOneCommit.Result r) throws Exception { review(r, 2); <START> SubmitInput input = new SubmitInput(); input.waitForMerge = true; <END> revision(r).submit(input); Repository repo = repoManager.openRepository(project); try { assertEquals(r.getCommitId(), repo.getRef("refs/heads/master").getObjectId()); } finally { repo.close(); } }</code><technical_language>Remove lines, ned them. is submit() method this standard thing</technical_language>

Target:
private void merge(PushOneCommit.Result r) throws Exception { review(r, 2); revision(r).submit(); Repository repo = repoManager.openRepository(project); try { assertEquals(r.getCommitId(), repo.getRef("refs/heads/master").getObjectId()); } finally { repo.close(); } }
Source:
<code>private static boolean differentContract(JavaSymbol.MethodJavaSymbol method, JavaSymbol.MethodJavaSymbol overridee) { <START> return removingParametrizedAspect(method, overridee) <END> || differentReturnType(method, overridee) || differentParameters(method, overridee) || differentAnnotations(method, overridee) || differentThrows(method, overridee); }</code><technical_language>![MAJOR](<LINK_1> Reduce number of conditional operators (4) in expression (maximum allowed 3). [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private static boolean differentContract(JavaSymbol.MethodJavaSymbol method, JavaSymbol.MethodJavaSymbol overridee) { return removingParametrizedAspect(method, overridee) || differentThrows(method, overridee) || differentReturnType(method, overridee) || differentParameters(method, overridee) || differentAnnotations(method.metadata(), overridee.metadata()); }
Source:
<code>private void cleanUpOrphanTasks(List<Guid> runningTasksinCluster) { List<Guid> taskListInDB = getProvider().getMonitoredTaskIDsInDB(); if (taskListInDB == null) { <START> taskListInDB = new ArrayList<Guid>(); <END> } final Set<Guid> tasksNotRunning = new HashSet<Guid>(taskListInDB); tasksNotRunning.removeAll(runningTasksinCluster); for (Guid taskId: tasksNotRunning) { GlusterVolumeEntity vol= getVolumeDao().getVolumeByGlusterTask(taskId); if (vol != null && vol.getStatus() != GlusterStatus.UP) { continue; } List<Step> steps = getStepDao().getStepsByExternalId(taskId); for (Step step: steps) { step.markStepEnded(JobExecutionStatus.UNKNOWN); endStepJob(step); } releaseVolumeLock(taskId); } }</code><technical_language>if taskListInDB is empty, need</technical_language>

Target:
private void cleanUpOrphanTasks(List<Guid> runningTasksinCluster) { List<Guid> taskListInDB = getProvider().getMonitoredTaskIDsInDB(); if (taskListInDB == null) { return; } final Set<Guid> tasksNotRunning = new HashSet<Guid>(taskListInDB); tasksNotRunning.removeAll(runningTasksinCluster); for (Guid taskId: tasksNotRunning) { GlusterVolumeEntity vol= getVolumeDao().getVolumeByGlusterTask(taskId); if (vol != null && vol.getStatus() != GlusterStatus.UP) { continue; } List<Step> steps = getStepDao().getStepsByExternalId(taskId); for (Step step: steps) { step.markStepEnded(JobExecutionStatus.UNKNOWN); endStepJob(step); } releaseVolumeLock(taskId); } }
Source:
<code>public static String[] valuesWithFullNames() { LANGUAGE[] allValues = values(); ArrayList<String> result = new ArrayList<String>(allValues.length); for (int i = 0; i < allValues.length; i++) { if(allValues[i] != UNLISTED) result.add(allValues[i].fullName); } Collections.sort(result); result.add(UNLISTED.fullName); <START> return (String[])result.toArray(new String[result.size()]); <END> }</code><technical_language>need do additional (String[]) cast here, T[] toArray(T[]) is generic in T</technical_language>

Target:
public static String[] valuesWithFullNames() { LANGUAGE[] allValues = values(); ArrayList<String> result = new ArrayList<String>(allValues.length); for (int i = 0; i < allValues.length; i++) { if(allValues[i] != UNLISTED) result.add(allValues[i].fullName); } Collections.sort(result); result.add(UNLISTED.fullName); return result.toArray(new String[result.size()]); }
Source:
<code>private void writeServiceInvokeRequest( PayloadOutputChannel ch, Collection<UUID> nodeIds, Method method, Object[] args ) { ch.clientChannel().protocolCtx().checkFeatureSupported(ProtocolBitmaskFeature.SERVICE_INVOKE); try (BinaryRawWriterEx writer = utils.createBinaryWriter(ch.out())) { writer.writeString(name); writer.writeByte(FLAG_PARAMETER_TYPES_MASK); writer.writeLong(timeout); if (nodeIds == null) writer.writeInt(0); else { writer.writeInt(nodeIds.size()); for (UUID nodeId : nodeIds) <START> writer.writeUuid(nodeId); <END> } PlatformServiceMethod ann = method.getDeclaredAnnotation(PlatformServiceMethod.class); writer.writeString(ann != null ? ann.value() : method.getName()); Class<?>[] paramTypes = method.getParameterTypes(); if (F.isEmpty(args)) writer.writeInt(0); else { writer.writeInt(args.length); assert args.length == paramTypes.length : "args=" + args.length + ", types=" + paramTypes.length; for (int i = 0; i < args.length; i++) { writer.writeInt(marsh.context().typeId(paramTypes[i].getName())); writer.writeObject(args[i]); } } } }</code><technical_language>writeUuid supports null values - writes additional byte is needed here. ClientClusterGroupGetNodeIdsResponse, for example: write UUIDs 8 bytes null sense</technical_language>

Target:
private void writeServiceInvokeRequest( PayloadOutputChannel ch, Collection<UUID> nodeIds, Method method, Object[] args ) { ch.clientChannel().protocolCtx().checkFeatureSupported(ProtocolBitmaskFeature.SERVICE_INVOKE); try (BinaryRawWriterEx writer = utils.createBinaryWriter(ch.out())) { writer.writeString(name); writer.writeByte(FLAG_PARAMETER_TYPES_MASK); writer.writeLong(timeout); if (nodeIds == null) writer.writeInt(0); else { writer.writeInt(nodeIds.size()); for (UUID nodeId : nodeIds) { writer.writeLong(nodeId.getMostSignificantBits()); writer.writeLong(nodeId.getLeastSignificantBits()); } } PlatformServiceMethod ann = method.getDeclaredAnnotation(PlatformServiceMethod.class); writer.writeString(ann != null ? ann.value() : method.getName()); Class<?>[] paramTypes = method.getParameterTypes(); if (F.isEmpty(args)) writer.writeInt(0); else { writer.writeInt(args.length); assert args.length == paramTypes.length : "args=" + args.length + ", types=" + paramTypes.length; for (int i = 0; i < args.length; i++) { writer.writeInt(marsh.context().typeId(paramTypes[i].getName())); writer.writeObject(args[i]); } } } }
Source:
<code>private void translateTurnCostsParamToEdgeBased(GHRequest request, MultivaluedMap<String, String> queryParams) { if (queryParams.containsKey(TURN_COSTS)) { List<String> turnCosts = queryParams.get(TURN_COSTS); if (turnCosts.size() != 1) { throw new IllegalArgumentException("You may only specify the turn_costs parameter once"); } <START> request.putHint(EDGE_BASED, turnCosts.get(0)); <END> } }</code><technical_language>need Helper.toObject(turnCosts.get(0)), mentioned (in case missed this): <LINK_0></technical_language>

Target:
private void translateTurnCostsParamToEdgeBased(GHRequest request, MultivaluedMap<String, String> queryParams) { if (queryParams.containsKey(TURN_COSTS)) { List<String> turnCosts = queryParams.get(TURN_COSTS); if (turnCosts.size() != 1) { throw new IllegalArgumentException("You may only specify the turn_costs parameter once"); } request.putHint(EDGE_BASED, Helper.toObject(turnCosts.get(0))); } }
Source:
<code>public ListViewMaxHeight(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); if (attrs != null) { <START> TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ListViewMaxHeight); <END> maxHeight = a.getDimensionPixelSize(R.styleable.ListViewMaxHeight_maxHeight, Integer.MAX_VALUE); a.recycle(); } else { maxHeight = 0; } }</code><technical_language>a name for style attributes styleAttributes instead of a</technical_language>

Target:
public ListViewMaxHeight(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); if (attrs != null) { TypedArray styleAttributes = getContext().obtainStyledAttributes(attrs, R.styleable.ListViewMaxHeight); maxHeight = styleAttributes.getDimensionPixelSize(R.styleable.ListViewMaxHeight_maxHeight, Integer.MAX_VALUE); styleAttributes.recycle(); } else { maxHeight = 0; } }
Source:
<code><START> private void populateHash() throws SQLException { <END> hash = new HashMap<ImmutableBytesWritable, Aggregator[]>(HASH_AGG_INIT_SIZE, 0.75f); for (Tuple result = resultIterator.next(); result != null; result = resultIterator.next()) { ImmutableBytesWritable key = new ImmutableBytesWritable(UNITIALIZED_KEY_BUFFER); key = getGroupingKey(result, key); Aggregator[] rowAggregators = hash.get(key); if (rowAggregators == null) { rowAggregators = aggregators.newAggregators(); hash.put(key, rowAggregators); } aggregators.aggregate(rowAggregators, result); } }</code><technical_language>For a large result set of join, this code snippet a risk lead OOM client. add limitation is more graceful</technical_language>

Target:
private HashMap<ImmutableBytesWritable, Aggregator[]> populateHash() throws SQLException { hash = new HashMap<ImmutableBytesWritable, Aggregator[]>(HASH_AGG_INIT_SIZE, 0.75f); final int aggSize = aggregators.getEstimatedByteSize(); long keySize = 0; for (Tuple result = resultIterator.next(); result != null; result = resultIterator.next()) { ImmutableBytesWritable key = new ImmutableBytesWritable(UNITIALIZED_KEY_BUFFER); key = getGroupingKey(result, key); Aggregator[] rowAggregators = hash.get(key); if (rowAggregators == null) { keySize += key.getSize(); long hashSize = SizedUtil.sizeOfMap(hash.size() + 1, SizedUtil.IMMUTABLE_BYTES_WRITABLE_SIZE, aggSize) + keySize; if (hashSize > memoryChunk.getSize() + CLIENT_HASH_AGG_MEMORY_CHUNK_SIZE) { memoryChunk.resize(hashSize + CLIENT_HASH_AGG_MEMORY_CHUNK_SIZE); } rowAggregators = aggregators.newAggregators(); hash.put(key, rowAggregators); } aggregators.aggregate(rowAggregators, result); } return hash; }
Source:
<code>public void get() { Call<CardPageItem> call = cachedService.service(site).get(); call.enqueue(new Callback<CardPageItem>() { @Override <START> public void onResponse(Call<CardPageItem> call, Response<CardPageItem> response) { <END> responseHeaderHandler.onHeaderCheck(response); CardPageItem item = response.body(); String namespace = item.namespace() == null ? null : item.namespace().toLegacyString(); PageTitle title = new PageTitle(namespace, item.title(), site); cb.onSuccess(title); } @Override public void onFailure(Call<CardPageItem> call, Throwable t) { L.w("Failed to get random page title/summary", t); cb.onError(t); } }); }</code><technical_language>check for response.isSuccessful() here, do in other Clients? I get a crash if service times out</technical_language>

Target:
public void get() { Call<CardPageItem> call = cachedService.service(site).get(); call.enqueue(new Callback<CardPageItem>() { @Override public void onResponse(Call<CardPageItem> call, Response<CardPageItem> response) { if (response.isSuccessful()) { responseHeaderHandler.onHeaderCheck(response); CardPageItem item = response.body(); String namespace = item.namespace() == null ? null : item.namespace().toLegacyString(); PageTitle title = new PageTitle(namespace, item.title(), site); cb.onSuccess(title); } else { L.v(response.message()); cb.onError(new IOException(response.message())); } } @Override public void onFailure(Call<CardPageItem> call, Throwable t) { L.w("Failed to get random page title/summary", t); cb.onError(t); } }); }
Source:
<code>public void testLoggerExpressionValue() { localSession.getLocalSessionBrowser().perCategory().selectViewpoint("testColumnFinderExpressionLog").selectRepresentation("CrossTableDesc") <START> .selectRepresentationInstance("new CrossTableDesc", UITableRepresentation.class).open(); <END> try { openErrorLogView(); SWTBotView logViewBot = bot.viewByTitle("Error Log"); assertTrue("Find column expression error does not appear in the error log.", checkErrorLogMessage(logViewBot)); logViewBot.close(); } finally { errors.clear(); } }</code><technical_language>call "openRepresentation(localSession.getOpenedSession(), "CrossTableDesc", "new CrossTableDesc", DDTable.class);"</technical_language>

Target:
public void testLoggerExpressionValue() { openRepresentation(localSession.getOpenedSession(), "CrossTableDesc", "new CrossTableDesc", DTable.class); try { openErrorLogView(); SWTBotView logViewBot = bot.viewByTitle("Error Log"); assertTrue("Find column expression error does not appear in the error log.", checkErrorLogMessage(logViewBot)); logViewBot.close(); } finally { errors.clear(); } }
Source:
<code>public void addConstituent(Constituent constituent) { <START> <END> int start = constituent.getStartSpan(); int end = constituent.getEndSpan(); if (!allowOverlappingSpans && this.getConstituentsCoveringSpan(start, end).size() != 0) throw new IllegalArgumentException("Span [" + start + ", " + end + "] already labeled."); super.addConstituent(constituent); int size = this.constituents.size(); if (size > 1) { Constituent before = this.constituents.get(size-2); Constituent after = this.constituents.get(size-1); if (before.getStartSpan() > after.getStartSpan()) { Collections.sort(this.constituents, TextAnnotationUtilities.constituentStartComparator); } } }</code><technical_language>small improvement: please move start/end assignments if{} block, otherwise</technical_language>

Target:
public void addConstituent(Constituent constituent) { if (!allowOverlappingSpans) { int start = constituent.getStartSpan(); int end = constituent.getEndSpan(); if (this.getConstituentsCoveringSpan(start, end).size() != 0) throw new IllegalArgumentException("Span [" + start + ", " + end + "] already labeled."); } super.addConstituent(constituent); int size = this.constituents.size(); if (size > 1) { Constituent before = this.constituents.get(size-2); Constituent after = this.constituents.get(size-1); if (before.getStartSpan() > after.getStartSpan()) { Collections.sort(this.constituents, TextAnnotationUtilities.constituentStartComparator); } } }
Source:
<code>private OnlineOptions(Data data) { if (data.protocol == null && System.getProperty(CREAPER_WILDFLY) != null) { if (data.sslOptions == null) { data.protocol = ManagementProtocol.HTTP_REMOTING; } else { data.protocol = ManagementProtocol.HTTPS_REMOTING; } } if (data.localDefault) { data.host = "localhost"; if (data.protocol == ManagementProtocol.HTTP_REMOTING || data.protocol == ManagementProtocol.HTTP) { data.port = 9990; } else if (data.protocol == ManagementProtocol.HTTPS_REMOTING) { data.port = 9993; } else if (data.protocol == ManagementProtocol.HTTPS) { data.port = System.getProperty(CREAPER_WILDFLY) != null ? 9993 : 9443; } else { data.port = 9999; } } this.isStandalone = data.isStandalone; this.isDomain = data.isDomain; this.defaultProfile = data.defaultProfile; this.defaultHost = data.defaultHost; this.host = data.host; this.port = data.port; this.protocol = data.protocol; this.connectionTimeout = data.connectionTimeout; this.bootTimeout = data.bootTimeout; this.username = data.username; this.password = data.password; this.localAuthDisabled = data.localAuthDisabled; this.sslOptions = data.sslOptions; this.wrappedModelControllerClient = data.wrappedModelControllerClient; this.isWrappedClient = data.wrappedModelControllerClient != null; <START> if (protocol == ManagementProtocol.HTTPS && sslOptions == null) { <END> throw new IllegalArgumentException("SSL must be configured when HTTPS protocol is used!"); } }</code><technical_language>Right, this already. check for HTTPS_REMOTING</technical_language>

Target:
private OnlineOptions(Data data) { if (data.protocol == null && System.getProperty(CREAPER_WILDFLY) != null) { if (data.sslOptions == null) { data.protocol = ManagementProtocol.HTTP_REMOTING; } else { data.protocol = ManagementProtocol.HTTPS_REMOTING; } } if (data.localDefault) { data.host = "localhost"; if (data.protocol == ManagementProtocol.HTTP_REMOTING || data.protocol == ManagementProtocol.HTTP) { data.port = 9990; } else if (data.protocol == ManagementProtocol.HTTPS_REMOTING) { data.port = 9993; } else if (data.protocol == ManagementProtocol.HTTPS) { data.port = System.getProperty(CREAPER_WILDFLY) != null ? 9993 : 9443; } else { data.port = 9999; } } this.isStandalone = data.isStandalone; this.isDomain = data.isDomain; this.defaultProfile = data.defaultProfile; this.defaultHost = data.defaultHost; this.host = data.host; this.port = data.port; this.protocol = data.protocol; this.connectionTimeout = data.connectionTimeout; this.bootTimeout = data.bootTimeout; this.username = data.username; this.password = data.password; this.localAuthDisabled = data.localAuthDisabled; this.sslOptions = data.sslOptions; this.wrappedModelControllerClient = data.wrappedModelControllerClient; this.isWrappedClient = data.wrappedModelControllerClient != null; if ((protocol == ManagementProtocol.HTTPS || protocol == ManagementProtocol.HTTPS_REMOTING) && sslOptions == null) { throw new IllegalArgumentException("SSL must be configured when HTTPS or HTTPS_REMOTING protocol is used!"); } }
Source:
<code>public static void main(final String[] args) { final String TRACE_PATH = "testfiles/kernel"; final int NUM_LOOPS = 100; final boolean USE_TEXT = true; Long nbEvent = 0L; final Vector<Double> benchs = new Vector<Double>(); CtfTmfTrace trace = null; long start, stop; for (int loops = 0; loops < NUM_LOOPS; loops++) { nbEvent = 0L; trace = new CtfTmfTrace(); try { trace.initTrace(null, TRACE_PATH, CtfTmfEvent.class); } catch (final TmfTraceException e) { loops = NUM_LOOPS +1; break; } start = System.nanoTime(); if (nbEvent != -1) { final CtfTmfLightweightContext traceReader = (CtfTmfLightweightContext) trace.seekEvent(0); start = System.nanoTime(); CtfTmfEvent current = traceReader.getCurrentEvent(); while (current != null) { nbEvent++; if (USE_TEXT) { System.out.println("Event " + nbEvent + " Time " + current.getTimestamp().toString() + " type " + current.getEventName() + " on CPU " + current.getSource() + " " + current.getContent().toString()) ; } if(nbEvent == 30) { new Object(); } <START> boolean hasMore = traceReader.advance(); <END> current = traceReader.getCurrentEvent(); } } stop = System.nanoTime(); System.out.print('.'); final double time = (stop - start) / (double) nbEvent; benchs.add(time); } System.out.println(""); double avg = 0; for (final Double val : benchs) { avg += val; } avg /= benchs.size(); System.out.println("Time to read = " + avg + " events/ns"); for (final Double val : benchs) { System.out.print(val); System.out.print(", "); } }</code><technical_language>pedantic, do boolean hasMore; while () { ... hasMore = traceReader.advance(); } stack get pushed/popped iteration</technical_language>

Target:
public static void main(final String[] args) { final String TRACE_PATH = "testfiles/kernel"; final int NUM_LOOPS = 100; final boolean USE_TEXT = true; Long nbEvent = 0L; final Vector<Double> benchs = new Vector<Double>(); CtfTmfTrace trace = null; long start, stop; for (int loops = 0; loops < NUM_LOOPS; loops++) { nbEvent = 0L; trace = new CtfTmfTrace(); try { trace.initTrace(null, TRACE_PATH, CtfTmfEvent.class); } catch (final TmfTraceException e) { loops = NUM_LOOPS +1; break; } start = System.nanoTime(); if (nbEvent != -1) { final CtfTmfLightweightContext traceReader = (CtfTmfLightweightContext) trace.seekEvent(0); start = System.nanoTime(); CtfTmfEvent current = traceReader.getCurrentEvent(); while (current != null) { nbEvent++; if (USE_TEXT) { System.out.println("Event " + nbEvent + " Time " + current.getTimestamp().toString() + " type " + current.getEventName() + " on CPU " + current.getSource() + " " + current.getContent().toString()) ; } boolean hasMore = traceReader.advance(); if( hasMore ){ } current = traceReader.getCurrentEvent(); } } stop = System.nanoTime(); System.out.print('.'); final double time = (stop - start) / (double) nbEvent; benchs.add(time); } System.out.println(""); double avg = 0; for (final Double val : benchs) { avg += val; } avg /= benchs.size(); System.out.println("Time to read = " + avg + " events/ns"); for (final Double val : benchs) { System.out.print(val); System.out.print(", "); } }
Source:
<code>private static @Pointer long retain (ObjCObject self, @Pointer long sel) { <START> if (ObjCRuntime.int_objc_msgSend(self.getHandle(), retainCount) == 1) { <END> synchronized (CUSTOM_OBJECTS) { CUSTOM_OBJECTS.put(self.getHandle(), self); } } return ObjCRuntime.ptr_objc_msgSendSuper(new Super(self.getHandle(), NS_OBJECT_CLASS).getHandle(), sel); }</code><technical_language>== 0 instead here</technical_language>

Target:
private static @Pointer long retain(ObjCObject self, @Pointer long sel) { if (ObjCRuntime.int_objc_msgSend(self.getHandle(), retainCount) <= 1) { synchronized (CUSTOM_OBJECTS) { CUSTOM_OBJECTS.put(self.getHandle(), self); } } return ObjCRuntime.ptr_objc_msgSendSuper(new Super(self.getHandle(), NS_OBJECT_CLASS).getHandle(), sel); }
Source:
<code>public void toIntArray() throws Exception { RangeSet rs = new RangeSet(4); int[] array = rs.toIntArray(); assertEquals(4, array.length); assertEquals(0, array[0]); assertEquals(1, array[1]); assertEquals(2, array[2]); <START> assertEquals(3, array[3]); <END> }</code><technical_language>simplify assertArrayEquals(new int[]{0, 1, 2, 3}, array)</technical_language>

Target:
public void toIntArray() throws Exception { RangeSet rs = new RangeSet(4); int[] array = rs.toIntArray(); assertArrayEquals(new int[]{0, 1, 2, 3}, array); }
Source:
<code>protected Map<String, Object> getCapabilities() { String capabilitiesString = getProperty(SELENIUM_JSONCAPABILITIES); try { Map<String, Object> result = new HashMap<String, Object>(); Gson gson = new Gson(); result = (Map<String, Object>)gson.fromJson(capabilitiesString, result.getClass()); return result; } catch (Exception e) { throw new RuntimeException("Unable to parse Selenium capabilities: " + capabilitiesString <START> + "\n*", e); <END> } }</code><technical_language>+ "\n*"</technical_language>

Target:
protected Map<String, Object> getCapabilities() { String capabilitiesString = getProperty(SELENIUM_JSONCAPABILITIES); try { return Environment.getInstance().getJsonHelper().jsonStringToMap(capabilitiesString); } catch (Exception e) { throw new RuntimeException("Unable to parse Selenium capabilities: " + capabilitiesString, e); } }
Source:
<code>public void parallelLockRelease() throws Exception { story.addStep(new Statement() { @Override public void evaluate() throws Throwable { LockableResourcesManager.get().createResource("resource1"); LockableResourcesManager.get().createResource("resource2"); LockableResourcesManager.get().createResource("resource3"); LockableResourcesManager.get().createResource("resource4"); WorkflowJob j = story.j.jenkins.createProject(WorkflowJob.class, "j"); j.setDefinition(new CpsFlowDefinition( "lock(resource: 'resource1') {\n" + <START> " sleep 1\n" + <END> "}\n" + "lock(resource: 'resource2') { \n" + " sleep 3\n" + "}\n" + "lock(resource: 'resource3') { \n" + " sleep 3\n" + "}\n" + "lock(resource: 'resource4') { \n" + " sleep 3\n" + " echo 'Entering semaphore now'\n" + " semaphore 'wait-inside'\n" + "}\n", true)); WorkflowRun r1 = j.scheduleBuild2(0).waitForStart(); story.j.waitForMessage("Lock acquired on [resource1]", r1); List<WorkflowRun> nextRuns = new ArrayList<>(); WorkflowRun r2 = j.scheduleBuild2(0).waitForStart(); story.j.waitForMessage("Lock acquired on [resource1]", r2); nextRuns.add(r2); for (int i = 0; i < 10; i++) { WorkflowRun rNext = j.scheduleBuild2(0).waitForStart(); System.err.println("Waiting to acquire initial lock for " + rNext.getNumber()); story.j.waitForMessage("Lock acquired on [resource1]", rNext); nextRuns.add(rNext); } for (WorkflowRun r : nextRuns) { System.err.println("Waiting to acquire second lock for " + r.getNumber()); story.j.waitForMessage("Lock acquired on [resource2]", r); } waitAndClear(r1, 1, nextRuns); } }); }</code><technical_language>semaphore, get flaky tests</technical_language>

Target:
public void parallelLockRelease() throws Exception { story.addStep(new Statement() { @Override public void evaluate() throws Throwable { LockableResourcesManager.get().createResource("resource1"); LockableResourcesManager.get().createResource("resource2"); WorkflowJob j = story.j.jenkins.createProject(WorkflowJob.class, "j"); j.setDefinition(new CpsFlowDefinition( "lock(resource: 'resource1') {\n" + " semaphore 'wait-inside-1'\n" + "}\n" + "lock(resource: 'resource2') { \n" + " echo 'Entering semaphore now'\n" + " semaphore 'wait-inside-2'\n" + "}\n", true)); List<WorkflowRun> nextRuns = new ArrayList<>(); WorkflowRun toUnlock = null; for (int i = 0; i < 5; i++) { WorkflowRun rNext = j.scheduleBuild2(0).waitForStart(); if (toUnlock != null) { story.j.waitForMessage("[resource1] is locked, waiting...", rNext); SemaphoreStep.success("wait-inside-1/" + i, toUnlock); } SemaphoreStep.waitForStart("wait-inside-1/" + (i + 1), rNext); nextRuns.add(rNext); toUnlock = rNext; } SemaphoreStep.success("wait-inside-1/" + nextRuns.size(), toUnlock); waitAndClear(1, nextRuns); } }); }
Source:
<code>public Model read( File input, Map<String, ?> options ) throws IOException { Objects.requireNonNull( input, "input cannot be null" ); TransformerContext context = null; if ( options != null ) { context = (TransformerContext) options.get( "transformerContext" ); } final InputStream is; if ( context == null ) { is = new FileInputStream( input ); } else { try { <START> is = transformer.transform( input.toPath(), context ); <END> } catch ( TransformerConfigurationException | SAXException | ParserConfigurationException e ) { throw new IOException( "Failed to transform " + input, e ); } } Model model = read( is, options ); model.setPomFile( input ); return model; }</code><technical_language>opened input streams, closed them</technical_language>

Target:
public Model read( File input, Map<String, ?> options ) throws IOException { Objects.requireNonNull( input, "input cannot be null" ); TransformerContext context = null; if ( options != null ) { context = (TransformerContext) options.get( "transformerContext" ); } final InputStream is; if ( context == null ) { is = new FileInputStream( input ); } else { try { is = transformer.transform( input.toPath(), context ); } catch ( TransformerException e ) { throw new IOException( "Failed to transform " + input, e ); } } try ( InputStream in = is ) { Model model = read( is, options ); model.setPomFile( input ); return model; } }
Source:
<code>protected void endSuccessfully() { endCommandActions(); if (getSucceeded() && (getDiskImage().getContentType() == DiskContentType.MEMORY_DUMP_VOLUME || getDiskImage().getContentType() == DiskContentType.MEMORY_METADATA_VOLUME)) { List<Snapshot> snapshots = snapshotDao.getSnapshotsByMemoryDiskId(getDiskImage().getId()); <START> snapshots.forEach(s -> s.getMemoryVolume()); <END> } incrementDbGenerationForRelatedEntities(); }</code><technical_language>Amm... I guess meant write database afterwards</technical_language>

Target:
protected void endSuccessfully() { endCommandActions(); incrementDbGenerationForRelatedEntities(); }
Source:
<code>private void readPhoneNumber() { final String phoneNumber = SimCardReader.readPhoneNumber(this); if (!Util.isNullOrEmpty(phoneNumber)) { final String number = new SimlarNumber(phoneNumber).getNationalOnly(); <START> mEditNumber.setText(number); <END> final TextView text = (TextView) findViewById(R.id.textViewCheckOrVerifyYourNumber); text.setText(getString(R.string.verify_number_activity_verify_your_number)); } else { new Handler().postDelayed(new Runnable() { @Override public void run() { showSoftInputForEditNumber(); } }, 100); } updateButtonAccept(); }</code><technical_language>mEditNumber.setText(new SimlarNumber(phoneNumber).getNationalOnly());</technical_language>

Target:
private void readPhoneNumber() { final String phoneNumber = SimCardReader.readPhoneNumber(this); if (!Util.isNullOrEmpty(phoneNumber)) { mEditNumber.setText(new SimlarNumber(phoneNumber).getNationalOnly()); final TextView text = (TextView) findViewById(R.id.textViewCheckOrVerifyYourNumber); text.setText(getString(R.string.verify_number_activity_verify_your_number)); } else { new Handler().postDelayed(new Runnable() { @Override public void run() { showSoftInputForEditNumber(); } }, 100); } updateButtonAccept(); }
Source:
<code>public void handleTownHallBroadcast(TileTownHall tile, BlockPosition position) { validateTownHallPosition(); BlockPosition pos = getTownHallPosition(); if (pos != null) { double curDist = getDistanceSq(pos.x + 0.5d, pos.y, pos.z + 0.5d); double newDist = getDistanceSq(position.x + 0.5d, position.y, position.z + 0.5d); if (newDist < curDist) { setTownHallPosition(position); if (upkeepAutoBlock == null || upkeepAutoBlock.equals(pos)) { upkeepAutoBlock = position; } } } else { setTownHallPosition(position); if (upkeepAutoBlock == null || upkeepAutoBlock.equals(pos)) { upkeepAutoBlock = position; } } if (getTownHall().alarmActive) isAlarmed = true; else <START> isAlarmed = false; <END> }</code><technical_language>inline, this is updating a flag</technical_language>

Target:
public void handleTownHallBroadcast(TileTownHall tile, BlockPosition position) { validateTownHallPosition(); BlockPosition pos = getTownHallPosition(); if (pos != null) { double curDist = getDistanceSq(pos.x + 0.5d, pos.y, pos.z + 0.5d); double newDist = getDistanceSq(position.x + 0.5d, position.y, position.z + 0.5d); if (newDist < curDist) { setTownHallPosition(position); if (upkeepAutoBlock == null || upkeepAutoBlock.equals(pos)) { upkeepAutoBlock = position; } } } else { setTownHallPosition(position); if (upkeepAutoBlock == null || upkeepAutoBlock.equals(pos)) { upkeepAutoBlock = position; } } isAlarmed = getTownHall().alarmActive; }
Source:
<code>public String getClusterNamespace() { Connection connection = getConnection(); if(connection != null) { return connection.getClusterNamespace(); } <START> return ""; <END> }</code><technical_language>Shouldnt this defaulting common namespace (ICommonAttributes#COMMON_NAMESPACE) user this defaults to</technical_language>

Target:
public String getClusterNamespace() { Connection connection = getConnection(); if(connection != null) { return connection.getClusterNamespace(); } return ICommonAttributes.COMMON_NAMESPACE; }
Source:
<code>protected void processSpanImpl(Span span, Map<String, String[]> servletRequestParameters) { long sum = 0; for (String weaselParameterToSum : weaselParametersToSum) { final Long timing = parsedLongOrNull(getParameterValueOrNull(weaselParameterToSum, servletRequestParameters)); if (timing == null) { <START> discardSpan(span); <END> return; } else { sum += timing; } } span.setTag(TIMING_RESOURCE, sum); }</code><technical_language>remove line</technical_language>

Target:
protected void processSpanImpl(Span span, Map<String, String[]> servletRequestParameters) { long sum = 0; for (String weaselParameterToSum : weaselParametersToSum) { final Long timing = parsedLongOrNull(getParameterValueOrNull(weaselParameterToSum, servletRequestParameters)); if (timing == null) { return; } else { sum += timing; } } span.setTag(TIMING_RESOURCE, sum); }
Source:
<code>public void onMessage(Message message) { log.info(message.toString()); try { String messageBody = getMessageBody(message); Event event = new Event(messageBody); eventManager.handleEvent(event); log.info("Received Event: " + event); <START> } <END> catch (Exception e) { log.error("Failed to decode and store event ", e); } }</code><technical_language>this Listener process event a time qpid? I.e. get another event EventManager stores it? Hrm this is registers slow</technical_language>

Target:
public void onMessage(Message message) { log.info(message.toString()); try { String messageBody = getMessageBody(message); Event event = new Event(messageBody); eventManager.handle(event); log.info("Received Event: " + event); } catch (Exception e) { log.error("Failed to decode and store event ", e); } }
Source:
<code>private void recalculateTotalExperience() { <START> if (!dontRecalculateExperience.get()) { <END> this.experienceTotal = this.xpAtLevel(this.experienceLevel) + Math.round(this.experience * this.xpBarCap()); } }</code><technical_language>this is instance variable, thread local, qualified this</technical_language>

Target:
private void recalculateTotalExperience() { if (!this.dontRecalculateExperience) { int newExperienceInLevel = (int) (this.experience * this.xpBarCap()); this.experienceTotal = this.xpAtLevel(this.experienceLevel) + newExperienceInLevel; this.experience = (float) newExperienceInLevel / this.xpBarCap(); } }
Source:
<code><T> Ref<T> getOrLoadRef(DfsStreamKey key, RefLoader<T> loader) throws IOException { int slot = slot(key, 0); HashEntry e1 = table.get(slot); Ref<T> ref = scanRef(e1, key, 0); if (ref != null) { getStat(statHit, key).incrementAndGet(); return ref; } getStat(statMiss, key).incrementAndGet(); <START> ReentrantLock regionLock = lockFor(key, 0); <END> regionLock.lock(); try { HashEntry e2 = table.get(slot); if (e2 != e1) { ref = scanRef(e2, key, 0); if (ref != null) { getStat(statHit, key).incrementAndGet(); return ref; } } ref = loader.load(); reserveSpace(ref.size, key); for (;;) { HashEntry n = new HashEntry(clean(e2), ref); if (table.compareAndSet(slot, e2, n)) break; e2 = table.get(slot); } addToClock(ref, 0); } finally { regionLock.unlock(); } return ref; }</code><technical_language>configuration, default 32 locks. threads call getOrLoadRef a key, get lock, of call a lock overhead. measure time for this overhead if increase bucket size? a duration loader.load. If hits cache acquiring lock, needed</technical_language>

Target:
<T> Ref<T> getOrLoadRef(DfsStreamKey key, RefLoader<T> loader) throws IOException { int slot = slot(key, 0); HashEntry e1 = table.get(slot); Ref<T> ref = scanRef(e1, key, 0); if (ref != null) { getStat(statHit, key).incrementAndGet(); return ref; } ReentrantLock regionLock = lockFor(key, 0); regionLock.lock(); try { HashEntry e2 = table.get(slot); if (e2 != e1) { ref = scanRef(e2, key, 0); if (ref != null) { getStat(statHit, key).incrementAndGet(); return ref; } } getStat(statMiss, key).incrementAndGet(); ref = loader.load(); reserveSpace(ref.size, key); for (;;) { HashEntry n = new HashEntry(clean(e2), ref); if (table.compareAndSet(slot, e2, n)) break; e2 = table.get(slot); } addToClock(ref, 0); } finally { regionLock.unlock(); } return ref; }
Source:
<code>public void testInterrupt() throws Exception { InterruptTestRunner runner = new <START> InterruptTestRunner(); <END> runner.start(); try { runner.join(); } catch (InterruptedException ie) { fail(); } if (runner.failure != null) { throw runner.failure; } }</code><technical_language>Possibly unnecessary start new threads for this test sits waiting for InterruptTestRunner complete. of InterruptTestRunner inlined (if wanted). some purpose missing - I initially thought stop test hanging, join() indefinitely here</technical_language>

Target:
public void testInterrupt() throws Exception { final Object lock = new Object(); final CountDownLatch cdl = new CountDownLatch(1); final Waiter waiter = new Waiter(lock, cdl); waiter.start(); try { cdl.await(); } catch (InterruptedException ie) { fail(); } synchronized (lock) { waiter.interrupt(); } try { waiter.join(); } catch (InterruptedException ie) { fail(); } assertTrue(waiter.wasInterrupted()); }
Source:
<code><START> private static @CheckForNull ResourceBundle getBundle(@Nonnull String baseName, @Nonnull Locale locale, @Nonnull ClassLoader classLoader) { <END> try { return ResourceBundle.getBundle(baseName, locale, classLoader); } catch (MissingResourceException e) { logger.info(e.getMessage()); } return null; }</code><technical_language>Well, @jglick-style violates recommended code style</technical_language>

Target:
private static @CheckForNull ResourceBundle getBundle(@Nonnull String baseName, @Nonnull Locale locale, @Nonnull ClassLoader classLoader) { try { return ResourceBundle.getBundle(baseName, locale, classLoader); } catch (MissingResourceException e) { logger.warning(e.getMessage()); } return null; }
Source:
<code>public ZeroConfig read(JsonReader in) throws IOException, NumberFormatException { ZeroConfig result = new ZeroConfig(); in.beginObject(); while (in.hasNext()) { String field = in.nextName(); String value = in.nextString(); switch (field) { case "message": result.setMessage(value); break; case "background": result.setBackground(Color.parseColor(value)); break; case "foreground": result.setForeground(Color.parseColor(value)); break; case "exitTitle": result.setExitTitle(value); break; case "exitWarning": result.setExitWarning(value); break; case "partnerInfoText": result.setPartnerInfoText(value); break; case "partnerInfoUrl": result.setPartnerInfoUrl(value); break; case "bannerUrl": result.setBannerUrl(value); break; default: <START> throw new IOException("zeroconfig response contained unknown property"); <END> } } return result; }</code><technical_language>I of tenets of JSON versioning is adding fields is compatible. This breaks principle I a good reason to</technical_language>

Target:
public ZeroConfig read(JsonReader in) throws IOException, NumberFormatException { ZeroConfig result = new ZeroConfig(); in.beginObject(); while (in.hasNext()) { String field = in.nextName(); String value = in.nextString(); switch (field) { case "message": result.setMessage(value); break; case "background": result.setBackground(Color.parseColor(value)); break; case "foreground": result.setForeground(Color.parseColor(value)); break; case "exitTitle": result.setExitTitle(value); break; case "exitWarning": result.setExitWarning(value); break; case "partnerInfoText": result.setPartnerInfoText(value); break; case "partnerInfoUrl": result.setPartnerInfoUrl(Uri.parse(value)); break; case "bannerUrl": result.setBannerUrl(Uri.parse(value)); break; default: break; } } return result; }