auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void maybeSplit(SolGame game) { if (MIN_SPLIT_SZ > size) { return; } float sclSum = 0; while (sclSum < .7f * size * size) { float speedAngle = SolRandom.randomFloat(180); <START> Vector2 splittedSpeed = new Vector2(); <END> SolMath.fromAl(splittedSpeed, speedAngle, SolRandom.randomFloat(0, .5f) * MAX_SPLIT_SPD); splittedSpeed.add(splittedSpeed); Vector2 newPos = new Vector2(); SolMath.fromAl(newPos, speedAngle, SolRandom.randomFloat(0, size / 2)); newPos.add(position); float sz = size * SolRandom.randomFloat(.25f, .5f); Asteroid a = game.getAsteroidBuilder().buildNew(game, newPos, splittedSpeed, sz, removeController); game.getObjectManager().addObjDelayed(a); sclSum += a.size * a.size; } float thrMoney = size * 40f * SolRandom.randomFloat(.3f, 1); List<MoneyItem> moneyItems = game.getItemMan().moneyToItems(thrMoney); for (MoneyItem mi : moneyItems) { throwLoot(game, mi); } }</code><technical_language>splitSpeed splittedSpeed more gramatical sense</technical_language>

Target:
private void maybeSplit(SolGame game) { if (MIN_SPLIT_SZ > size) { return; } float sclSum = 0; while (sclSum < .7f * size * size) { float speedAngle = SolRandom.randomFloat(180); Vector2 splitSpeed = new Vector2(); SolMath.fromAl(splitSpeed, speedAngle, SolRandom.randomFloat(0, .5f) * MAX_SPLIT_SPD); splitSpeed.add(splitSpeed); Vector2 newPos = new Vector2(); SolMath.fromAl(newPos, speedAngle, SolRandom.randomFloat(0, size / 2)); newPos.add(position); float sz = size * SolRandom.randomFloat(.25f, .5f); Asteroid a = game.getAsteroidBuilder().buildNew(game, newPos, splitSpeed, sz, removeController); game.getObjectManager().addObjDelayed(a); sclSum += a.size * a.size; } float thrMoney = size * 40f * SolRandom.randomFloat(.3f, 1); List<MoneyItem> moneyItems = game.getItemMan().moneyToItems(thrMoney); for (MoneyItem mi : moneyItems) { throwLoot(game, mi); } }
Source:
<code>private void finishFetch() { try { <START> int cursorLen = dis==null?0:dis.readInt(); <END> if (cursorLen == 0) { close(); return; } if (this.cursorBin == null || cursorLen > this.cursorBin.length) { this.cursorBin = new byte[cursorLen]; } dis.readFully(this.cursorBin,0,cursorLen); } catch (IOException e) { prefetchException = new HpccFileException("Error during read block", e); try { close(); } catch(Exception ie){} } if (this.simulateFail) this.handle = -1; String readAheadTrans = (this.forceCursorUse) ? this.getCursorTrans() : this.getHandleTrans(); try { int lenTrans = readAheadTrans.length(); this.dos.writeInt(lenTrans); this.dos.write(readAheadTrans.getBytes(HPCCCharSet), 0, lenTrans); this.dos.flush(); } catch (IOException e) { prefetchException = new HpccFileException("Failure sending read ahead transaction", e); try { close(); } catch(Exception ie){} } }</code><technical_language>Hey @drealeed thanks for PR! move this check beginning of finishFetch() call close return if dis is null</technical_language>

Target:
private void finishFetch() { try { if (dis==null) { return; } int cursorLen = dis.readInt(); if (cursorLen == 0) { close(); return; } if (this.cursorBin == null || cursorLen > this.cursorBin.length) { this.cursorBin = new byte[cursorLen]; } dis.readFully(this.cursorBin,0,cursorLen); } catch (IOException e) { prefetchException = new HpccFileException("Error during read block", e); try { close(); } catch(Exception ie){} } if (this.simulateFail) this.handle = -1; String readAheadTrans = (this.forceCursorUse) ? this.getCursorTrans() : this.getHandleTrans(); try { int lenTrans = readAheadTrans.length(); this.dos.writeInt(lenTrans); this.dos.write(readAheadTrans.getBytes(HPCCCharSet), 0, lenTrans); this.dos.flush(); } catch (IOException e) { prefetchException = new HpccFileException("Failure sending read ahead transaction", e); try { close(); } catch(Exception ie){} } }
Source:
<code><START> public Component getOwner() { <END> Objects.requireNonNull(listenOnComponents, "listenOnComponents must be initialized " + "(by calling listenOn()) before calling this method!"); if (listenOnComponents.length <= 0 || listenOnComponents[0] == null) { throw new IllegalStateException("listenOnComponents must not be empty!"); } return listenOnComponents[0]; }</code><technical_language>![INFO](<LINK_1> 'Severity: INFO') Do forget remove this deprecated code someday. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
public Component getOwner() { if (listenOnComponents == null) { return null; } if (listenOnComponents.length <= 0 || listenOnComponents[0] == null) { throw new IllegalStateException("listenOnComponents must not be empty!"); } return listenOnComponents[0]; }
Source:
<code>public static String getCPU() { if (!isPlatformAvailable()) <START> throw new UnsupportedOperationException("JNR Platform class not loaded"); <END> return PlatformLoader.PLATFORM.getCPU().toString(); }</code><technical_language>I similar methods in this class IllegalStateException, do here</technical_language>

Target:
public static String getCPU() { if (!isPlatformAvailable()) throw new IllegalStateException( "JNR Platform class not loaded. " + "Check isPlatformAvailable() before calling this method."); return PlatformLoader.PLATFORM.getCPU().toString(); }
Source:
<code>public String executeRequest(String urlString, ParamsMap params, Method method, ContentType contentTypeFormat) throws MambuApiException { String applicationKey = MambuAPIFactory.getApplicationKey(); if (applicationKey != null) { if (params == null) params = new ParamsMap(); <START> params.addParam(APPLICATION_KEY, applicationKey); <END> if (LOGGER.isLoggable(Level.INFO)) { final int keyLength = applicationKey.length(); final int printLength = 3; if (keyLength >= printLength) { LOGGER.info("Added Application key=" + applicationKey.substring(0, printLength) + "..." + applicationKey.substring(keyLength - printLength, keyLength)); } } } String response = ""; try { switch (method) { case GET: response = executeGetRequest(urlString, params); break; case POST: response = executePostRequest(urlString, params, contentTypeFormat); break; case DELETE: response = executeDeleteRequest(urlString, params); break; default: throw new IllegalArgumentException("Only methods GET, POST and DELETE are supported, not " + method.name() + "."); } } catch (MalformedURLException e) { LOGGER.severe("MalformedURLException: " + e.getMessage()); throw new MambuApiException(e); } catch (IOException e) { LOGGER.warning("IOException: message= " + e.getMessage()); throw new MambuApiException(e); } return response; }</code><technical_language>Please add wrap line "params = new .."</technical_language>

Target:
public String executeRequest(String urlString, ParamsMap params, Method method, ContentType contentTypeFormat) throws MambuApiException { logApiRequest(method, contentTypeFormat, urlString, params); String applicationKey = MambuAPIFactory.getApplicationKey(); if (applicationKey != null) { if (params == null) { params = new ParamsMap(); } params.addParam(APPLICATION_KEY, applicationKey); logAppKey(applicationKey); } String response = ""; try { switch (method) { case GET: response = executeGetRequest(urlString, params); break; case POST: response = executePostRequest(urlString, params, contentTypeFormat); break; case DELETE: response = executeDeleteRequest(urlString, params); break; default: throw new IllegalArgumentException("Only methods GET, POST and DELETE are supported, not " + method.name() + "."); } } catch (MalformedURLException e) { LOGGER.severe("MalformedURLException: " + e.getMessage()); throw new MambuApiException(e); } catch (IOException e) { LOGGER.warning("IOException: message= " + e.getMessage()); throw new MambuApiException(e); } return response; }
Source:
<code>public static void main(String[] args) { System.out.println(" +----------------------------------------------+"); <START> System.out.println(" | XBee Java Library Reset Module Data Sample |"); <END> System.out.println(" +----------------------------------------------+\n"); ZigBeeDevice myDevice = new ZigBeeDevice(PORT, BAUD_RATE); try { myDevice.open(); myDevice.reset(); System.out.println(">> XBee module reset successfully"); } catch (XBeeException e) { e.printStackTrace(); System.exit(1); } finally { myDevice.close(); } }</code><technical_language>Remove **Data** word</technical_language>

Target:
public static void main(String[] args) { System.out.println(" +-----------------------------------------+"); System.out.println(" | XBee Java Library Reset Module Sample |"); System.out.println(" +-----------------------------------------+\n"); ZigBeeDevice myDevice = new ZigBeeDevice(PORT, BAUD_RATE); try { myDevice.open(); myDevice.reset(); System.out.println(">> XBee module reset successfully"); } catch (XBeeException e) { e.printStackTrace(); System.exit(1); } finally { myDevice.close(); } }
Source:
<code>public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { <START> _collector = collector; <END> }</code><technical_language>this.collector = collector</technical_language>

Target:
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { this.collector = collector; }
Source:
<code>private static boolean isSingleTopic(ReadableConfig tableOptions) { <START> return tableOptions.getOptional(TOPIC).isPresent() && tableOptions.get(TOPIC).split(",").length == 1; <END> }</code><technical_language>community recommend List ConfigOption for list values, framework handle parsing. This change ; separator, this is more align other list options. declare a List ConfigOption : java public static final ConfigOption<List<String>> TOPIC = ConfigOptions .key("topic") .stringType() .asList() .noDefaultValue() .withDescription("..."); call return tableOptions.getOptional(TOPIC).map(t -> t.size() == 1).orElse(false); here. for late reminder</technical_language>

Target:
private static boolean isSingleTopic(ReadableConfig tableOptions) { return tableOptions.getOptional(TOPIC).map(t -> t.size() == 1).orElse(false); }
Source:
<code>protected void afterRead(final int n) throws IOException { <START> if (n == EOF && !marked) { <END> close(); } }</code><technical_language>I do point rephrase I understand: implement mark/reset APIs properly implement markSupported() return false. concern remains for this case, today: - I open a stream - I read - I call mark() read() - I read end of stream stream closes - I do bother call close() - is this change, random calls mark() I read end of stream stream remain open. a leak. Granted, I _should_ close a stream I open in a try-with-resources block this class lives of this case. simplest solution for markSupported() return false. WDYT? create a new class</technical_language>

Target:
protected void afterRead(final int n) throws IOException { if (n == EOF) { close(); } }
Source:
<code>private DBCursor prepareCursor(final FindOptions findOptions) { final DBObject query = getQueryObject(); if (LOG.isTraceEnabled()) { LOG.trace(String.format("Running query(%s) : %s, options: %s,", dbColl.getName(), query, findOptions)); } final DBCursor cursor = dbColl.find(query, findOptions.getOptions() .sort(getSortObject()) .projection(getFieldsObject())); cursor.setDecoderFactory(ds.getDecoderFact()); <START> switch (findOptions.getCursorType()) { <END> case TailableAwait: cursor.addOption(Bytes.QUERYOPTION_AWAITDATA); case Tailable: cursor.addOption(Bytes.QUERYOPTION_TAILABLE); break; default: break; } if (options.isSnapshot() && (findOptions.getSortDBObject() != null || findOptions.hasHint())) { LOG.warning("Snapshotted query should not have hint/sort."); } if (findOptions.getCursorType() != NonTailable && (findOptions.getSortDBObject() != null)) { LOG.warning("Sorting on tail is not allowed."); } return cursor; }</code><technical_language><LINK_0> is fixed in master now</technical_language>

Target:
private DBCursor prepareCursor(final FindOptions findOptions) { final DBObject query = getQueryObject(); if (LOG.isTraceEnabled()) { LOG.trace(String.format("Running query(%s) : %s, options: %s,", dbColl.getName(), query, findOptions)); } final DBCursor cursor = dbColl.find(query, findOptions.getOptions() .sort(getSortObject()) .projection(getFieldsObject())); cursor.setDecoderFactory(ds.getDecoderFact()); switch (findOptions.getCursorType()) { case TailableAwait: cursor.addOption(Bytes.QUERYOPTION_AWAITDATA); cursor.addOption(Bytes.QUERYOPTION_TAILABLE); break; case Tailable: cursor.addOption(Bytes.QUERYOPTION_TAILABLE); break; default: break; } if (options.isSnapshot() && (findOptions.getSortDBObject() != null || findOptions.hasHint())) { LOG.warning("Snapshotted query should not have hint/sort."); } if (findOptions.getCursorType() != NonTailable && (findOptions.getSortDBObject() != null)) { LOG.warning("Sorting on tail is not allowed."); } return cursor; }
Source:
<code>public Mediator createSpecificMediator(OMElement elem, Properties properties) { CallMediator callMediator = new CallMediator(); processAuditStatus(callMediator,elem); OMElement epElement = elem.getFirstChildWithName(ENDPOINT_Q); if (epElement != null) { Endpoint endpoint = EndpointFactory.getEndpointFromElement(epElement, true, properties); if (endpoint != null) { callMediator.setEndpoint(endpoint); } } OMAttribute blocking=elem.getAttribute(BLOCKING_Q); if (blocking!=null) { boolean EndpointType = epElement.toString().contains("endpoint key"); <START> callMediator.setBlocking(Boolean.parseBoolean(blocking.getAttributeValue())); <END> callMediator.setEndpointType(EndpointType); }else { callMediator.setBlocking(false); } return callMediator; }</code><technical_language>explain need a logic this get EndpointType</technical_language>

Target:
public Mediator createSpecificMediator(OMElement elem, Properties properties) { CallMediator callMediator = new CallMediator(); processAuditStatus(callMediator, elem); OMElement epElement = elem.getFirstChildWithName(ENDPOINT_Q); if (epElement != null) { Endpoint endpoint = EndpointFactory.getEndpointFromElement(epElement, true, properties); if (endpoint != null) { callMediator.setEndpoint(endpoint); } } OMAttribute blocking = elem.getAttribute(BLOCKING_Q); if (blocking != null) { callMediator.setBlocking(Boolean.parseBoolean(blocking.getAttributeValue())); } else { callMediator.setBlocking(false); } return callMediator; }
Source:
<code>public CompletableFuture<CoordinationResponse> handleCoordinationRequest(CoordinationRequest request) { Preconditions.checkArgument( request instanceof CollectCoordinationRequest, "Coordination request must be a CollectCoordinationRequest"); <START> <END> CompletableFuture<CoordinationResponse> responseFuture = new CompletableFuture<>(); executorService.submit(() -> handleRequestImpl((CollectCoordinationRequest) request, responseFuture)); return responseFuture; }</code><technical_language>call closeCurrentConnection instead</technical_language>

Target:
public CompletableFuture<CoordinationResponse> handleCoordinationRequest(CoordinationRequest request) { Preconditions.checkArgument( request instanceof CollectCoordinationRequest, "Coordination request must be a CollectCoordinationRequest"); CollectCoordinationRequest collectRequest = (CollectCoordinationRequest) request; CompletableFuture<CoordinationResponse> responseFuture = new CompletableFuture<>(); if (address == null) { completeWithEmptyResponse(collectRequest, responseFuture); return responseFuture; } executorService.submit(() -> handleRequestImpl(collectRequest, responseFuture, address)); return responseFuture; }
Source:
<code>public static ObjectElement marshalFrom(Attribute attribute) throws CatalogTransformerException { ObjectElement element = new ObjectElement(); element.setName(attribute.getName()); if (attribute.getValue() != null) { for (Serializable value : attribute.getValues()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos; try { oos = new ObjectOutputStream(baos); oos.writeObject(value); oos.close(); } catch (IOException e) { throw new CatalogTransformerException( "Could not transform Metacard to XML. Could not serialize Attribute Object value.", e); } <START> (element).getValue().add(baos.toByteArray()); <END> } } return element; }</code><technical_language>get rid of parans element</technical_language>

Target:
public static ObjectElement marshalFrom(Attribute attribute) throws CatalogTransformerException { ObjectElement element = new ObjectElement(); element.setName(attribute.getName()); if (attribute.getValue() != null) { for (Serializable value : attribute.getValues()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos; try { oos = new ObjectOutputStream(baos); oos.writeObject(value); oos.close(); } catch (IOException e) { throw new CatalogTransformerException( "Could not transform Metacard to XML. Could not serialize Attribute Object value.", e); } element.getValue().add(baos.toByteArray()); } } return element; }
Source:
<code>public void testGetRequiredTokens() { final MatchXpathCheck matchXpathCheck = new MatchXpathCheck(); assertThat("Expected empty array", <START> matchXpathCheck.getRequiredTokens(), is(CommonUtil.EMPTY_INT_ARRAY)); <END> }</code><technical_language>Please Truth assertions below: assertWithMessage("Expected empty array") .that(matchXpathCheck.getDefaultTokens()) .isEmpty();</technical_language>

Target:
public void testGetRequiredTokens() { final MatchXpathCheck matchXpathCheck = new MatchXpathCheck(); assertWithMessage("Expected empty array") .that(matchXpathCheck.getRequiredTokens()) .isEmpty(); }
Source:
<code>switch (platform) { case "win32": COLUMN_TRIM= 4; break; case "carbon": COLUMN_TRIM= 24; break; <START> case "cocoa": END> default: COLUMN_TRIM= 3; break; }</code><technical_language>handle cocoa carbon remove carbon fly change "carbon" "cocoa" separate change before? carbon is unsupported</technical_language>

Target:
switch (platform) { case "win32": COLUMN_TRIM= 4; break; case "cocoa": COLUMN_TRIM= 24; break; default: COLUMN_TRIM= 3; break; }
Source:
<code>public void init(HelixManager manager, String workflowName, String jobName, String taskName) { if (participant != null) { <START> participant.registerRunningTask(this); <END> } super.init(manager, workflowName, jobName, taskName); try { TaskUtil.deserializeTaskData(this, this.callbackContext.getTaskConfig().getConfigMap()); } catch (IllegalAccessException | InstantiationException e) { e.printStackTrace(); } }</code><technical_language>Print a warn log mentioning registration happen if participant is null</technical_language>

Target:
public void init(HelixManager manager, String workflowName, String jobName, String taskName) { if (participant != null) { participant.registerRunningTask(this); } else { logger.warn("Task with id: " + taskId + " is not registered since the participant is not set"); } super.init(manager, workflowName, jobName, taskName); try { TaskUtil.deserializeTaskData(this, this.callbackContext.getTaskConfig().getConfigMap()); } catch (IllegalAccessException | InstantiationException e) { e.printStackTrace(); } }
Source:
<code>private Node reduceTrueFalse(Node n) { switch (n.getParent().getType()) { <START> case Token.EQ: <END> case Token.GT: case Token.GE: case Token.LE: case Token.LT: case Token.NE: Node number = IR.number(n.isTrue() ? 1 : 0); n.getParent().replaceChild(n, number); reportCodeChange(); return number; } if (late) { Node not = IR.not(IR.number(n.isTrue() ? 0 : 1)); not.copyInformationFromForTree(n); n.getParent().replaceChild(n, not); reportCodeChange(); return not; } return n; }</code><technical_language>do this "late"? Otherwise, is a denormalization disable some optimizations</technical_language>

Target:
private Node reduceTrueFalse(Node n) { if (late) { switch (n.getParent().getType()) { case Token.EQ: case Token.GT: case Token.GE: case Token.LE: case Token.LT: case Token.NE: Node number = IR.number(n.isTrue() ? 1 : 0); n.getParent().replaceChild(n, number); reportCodeChange(); return number; } Node not = IR.not(IR.number(n.isTrue() ? 0 : 1)); not.copyInformationFromForTree(n); n.getParent().replaceChild(n, not); reportCodeChange(); return not; } return n; }
Source:
<code>private void sendPostJoinOperationsBackToMaster() { final ClusterServiceImpl clusterService = getService(); final NodeEngineImpl nodeEngine = clusterService.getNodeEngine(); Collection<Operation> postJoinOperations = nodeEngine.getPostJoinOperations(); if (postJoinOperations != null && !postJoinOperations.isEmpty()) { final OperationService operationService = nodeEngine.getOperationService(); <START> final Collection<Member> members = clusterService.getMembers(); <END> Address masterAddress = clusterService.getMasterAddress(); OnJoinOp operation = new OnJoinOp(postJoinOperations); operationService.invokeOnTarget(ClusterServiceImpl.SERVICE_NAME, operation, masterAddress); } }</code><technical_language>Minor: members longer needed</technical_language>

Target:
private void sendPostJoinOperationsBackToMaster() { final ClusterServiceImpl clusterService = getService(); final NodeEngineImpl nodeEngine = clusterService.getNodeEngine(); Collection<Operation> postJoinOperations = nodeEngine.getPostJoinOperations(); if (postJoinOperations != null && !postJoinOperations.isEmpty()) { final OperationService operationService = nodeEngine.getOperationService(); Address masterAddress = clusterService.getMasterAddress(); OnJoinOp operation = new OnJoinOp(postJoinOperations); operationService.invokeOnTarget(ClusterServiceImpl.SERVICE_NAME, operation, masterAddress); } }
Source:
<code>public void testCreateDataCenterWithIllegalArguments() throws Exception { String[] names = {"JCl@ouds", "JC|ouds", "^clouds", ""}; for (String name : names) try { DataCenter.Request.CreatePayload.create(name, Location.US_LAS); fail("Should have failed for name: ".concat(name)); } catch (Exception ex) { <START> assertTrue(ex instanceof IllegalArgumentException); <END> } }</code><technical_language>catching IllegalArgumentException</technical_language>

Target:
public void testCreateDataCenterWithIllegalArguments() throws Exception { String[] names = {"JCl@ouds", "JC|ouds", "^clouds", ""}; for (String name : names) { try { DataCenter.Request.CreatePayload.create(name, Location.US_LAS); fail("Should have failed for name: ".concat(name)); } catch (IllegalArgumentException ex) { } } }
Source:
<code>public String toString() { <START> return getName() + ": " + getType() + " = " + getValue(); <END> }</code><technical_language>please avoid code duplication: public String toString(boolean shortenTypes) { String type = getType(); if (shortenTypes) { type = shorten(type); } return getName() + ": " + type + " = " + getValue(); } @Override public String toString() { return toString(false); }</technical_language>

Target:
public String toString() { return toString(false); }
Source:
<code>void addPathParam(String name, String value, boolean encoded) { if (relativeUrl == null) { throw new AssertionError(); } String replacement = canonicalizeForPath(value, encoded); <START> if (PATH_TRAVERSAL.matcher(replacement).matches()) { <END> throw new IllegalArgumentException( "@Path parameters shouldn't perform path traversal ('.' or '..'): " + value); } relativeUrl = relativeUrl.replace("{" + name + "}", replacement); }</code><technical_language>this apply URL _after_ path replacement. @GET("foo{bar}baz") marked invalid call "." ".." valid URL path traversal. waiting full relative URL is built escape /../? problematic able escape do slashes. require forbidding in annotation string</technical_language>

Target:
void addPathParam(String name, String value, boolean encoded) { if (relativeUrl == null) { throw new AssertionError(); } String replacement = canonicalizeForPath(value, encoded); String newRelativeUrl = relativeUrl.replace("{" + name + "}", replacement); if (PATH_TRAVERSAL.matcher(newRelativeUrl).matches()) { throw new IllegalArgumentException( "@Path parameters shouldn't perform path traversal ('.' or '..'): " + value); } relativeUrl = newRelativeUrl; }
Source:
<code>public void auditLogMacInUse(final VmNetworkInterface iface) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { AuditLogableBase logable = new AuditLogableBase(); logable.addCustomValue("MACAddr", iface.getMacAddress()); log(logable, AuditLogType.MAC_ADDRESS_IS_IN_USE); <START> log.warnFormat("VmInterfaceManager::Network Interface {0} has MAC address {1} which is in use, " + <END> "therefore the action failed.", iface.getName(), iface.getMacAddress()); return null; } }); }</code><technical_language>prefix of VmInterfaceManager:: is redundant. In addition, message parts squashed instead of concatenating them</technical_language>

Target:
public void auditLogMacInUse(final VmNetworkInterface iface) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { AuditLogableBase logable = createAuditLog(iface); log(logable, AuditLogType.MAC_ADDRESS_IS_IN_USE); log.warnFormat("Network Interface {0} has MAC address {1} which is in use, " + "therefore the action for VM {2} failed.", iface.getName(), iface.getMacAddress(), iface.getVmId()); return null; } }); }
Source:
<code>public int intermediateComputeSizeBytes() { int sizeBytesConfigured = intermediateComputeSizeBytesConfigured(); if (sizeBytesConfigured != DEFAULT_PROCESSING_BUFFER_SIZE_BYTES) { return sizeBytesConfigured; } else if (computedBufferSizeBytes.get() != null) { return computedBufferSizeBytes.get(); } long directSizeBytes = JvmUtils.getRuntimeInfo().getDirectMemorySizeBytes(); int numProcessingThreads = getNumThreads(); int numMergeBuffers = getNumMergeBuffers(); int totalNumBuffers = numMergeBuffers + numProcessingThreads; <START> int sizePerBuffer = (int) ((double) directSizeBytes / (double) (totalNumBuffers + 1)); <END> int rem = sizePerBuffer % (1 << 16); sizePerBuffer -= rem; final int computedSizePerBuffer = Math.min(sizePerBuffer, (1 << 31) - 1); if (computedBufferSizeBytes.compareAndSet(null, computedSizePerBuffer)) { log.info( "Auto sizing buffers to [%,d] bytes for [%,d] processing buffers and [%,d] merge buffers", computedSizePerBuffer, numProcessingThreads, numMergeBuffers ); } return computedSizePerBuffer; }</code><technical_language>(int) ((double) directSizeBytes / (totalNumBuffers + 1)); ok</technical_language>

Target:
public int intermediateComputeSizeBytes() { int sizeBytesConfigured = intermediateComputeSizeBytesConfigured(); if (sizeBytesConfigured != DEFAULT_PROCESSING_BUFFER_SIZE_BYTES) { return sizeBytesConfigured; } else if (computedBufferSizeBytes.get() != null) { return computedBufferSizeBytes.get(); } long directSizeBytes = JvmUtils.getRuntimeInfo().getDirectMemorySizeBytes(); int numProcessingThreads = getNumThreads(); int numMergeBuffers = getNumMergeBuffers(); int totalNumBuffers = numMergeBuffers + numProcessingThreads; int sizePerBuffer = (int) ((double) directSizeBytes / (double) (totalNumBuffers + 1)); final int computedSizePerBuffer = Math.min(sizePerBuffer, MAX_DEFAULT_PROCESSING_BUFFER_SIZE_BYTES); if (computedBufferSizeBytes.compareAndSet(null, computedSizePerBuffer)) { log.info( "Auto sizing buffers to [%,d] bytes each for [%,d] processing and [%,d] merge buffers " + "out of [%,d] max direct memory", computedSizePerBuffer, numProcessingThreads, numMergeBuffers, directSizeBytes ); } return computedSizePerBuffer; }
Source:
<code>private void trackCampaignOpenedIfNeeded(Intent intent) { if (intent == null) { return; } try { <START> if (intent.hasExtra("campaignId") && intent.hasExtra("messageId")) { <END> String campaignId = intent.getStringExtra("campaignId"); String messageId = intent.getStringExtra("messageId"); String extraLogData = intent.getStringExtra("extraLogData"); try { JSONObject pushProps; if (extraLogData != null) { pushProps = new JSONObject(extraLogData); } else { pushProps = new JSONObject(); } pushProps.put("campaign_id", Integer.valueOf(campaignId).intValue()); pushProps.put("message_id", Integer.valueOf(messageId).intValue()); pushProps.put("message_type", "push"); mMpInstance.track("$app_open", pushProps); } catch (JSONException e) } } catch (BadParcelableException e) { } }</code><technical_language>i problems this: - generic names perfectly in app (or in future) extra starts activity - some developers do tracking passing mp_campaign_id mp_message_id this break existing implementations</technical_language>

Target:
private void trackCampaignOpenedIfNeeded(Intent intent) { if (intent == null) { return; } if (intent.hasExtra("mp_campaign_id") && intent.hasExtra("mp_message_id")) { MixpanelAPI.trackPushNotificationEventFromIntent(mMpInstance.getContext(), intent, "$app_open"); } }
Source:
<code>public FSDataInputStream openFile(Path path, HiveFileContext hiveFileContext) throws Exception { <START> return dataTier.openFile(path, hiveFileContext); <END> }</code><technical_language>need do caching here</technical_language>

Target:
public FSDataInputStream openFile(Path path, HiveFileContext hiveFileContext) throws Exception { if (hiveFileContext.isCacheable()) { return new CachingInputStream(dataTier.openFile(path, hiveFileContext), cacheManager, path, cacheValidationEnabled); } return dataTier.openFile(path, hiveFileContext); }
Source:
<code>public NakadiCursor(final String topic, final String partition, final String offset) { <START> assert null != topic && null != partition && null != offset; <END> this.topic = topic; this.partition = partition; this.offset = offset; }</code><technical_language>do check for nulls here? If nulls passed - please define params Nullable. If nulls expected - I remove checks</technical_language>

Target:
public NakadiCursor(final String topic, final String partition, final String offset) { this.topic = topic; this.partition = partition; this.offset = offset; }
Source:
<code>protected String removeRelation(String edgeName){ if(edgeName != null && edgeName.contains(", ")){ <START> edgeName = edgeName.substring(0, edgeName.lastIndexOf(',')); <END> } return edgeName; }</code><technical_language>Nice hack :)</technical_language>

Target:
private String removeRelation(String edgeName){ if(edgeName != null && edgeName.contains(", ")){ edgeName = edgeName.substring(0, edgeName.lastIndexOf(',')); } return edgeName; }
Source:
<code>private final Map<String, S> newStrategyMap() { final Map<String, S> map = new TreeMap<String, S>(); <START> final List<P> providers = getProviderFinder().find(); <END> Collections.sort(providers, ProviderPriority.COMPARATOR); for (final P provider : providers) { try { map.putAll(getStrategies(provider)); } catch (final Exception e) { LOG.warn("Could not load strategies for provider: {}, because of: {}. It will be skipped.", provider, e.getMessage()); } } overrideDefaultStrategyMap(map); return map; }</code><technical_language>if ProviderFinder returned sorted list</technical_language>

Target:
private final Map<String, S> newStrategyMap() { final Map<String, S> map = new TreeMap<String, S>(); final List<P> providers = getProviderFinder().find(); for (final P provider : providers) { try { map.putAll(getStrategies(provider)); } catch (final Exception e) { LOG.warn("Could not load strategies for provider: {}, because of: {}. It will be skipped.", provider, e.getMessage()); } } overrideDefaultStrategyMap(map); return map; }
Source:
<code>public void hook(ExtensionHook extensionHook) { super.hook(extensionHook); extensionHook.addOptionsParamSet(getOptions()); extensionHook.addAddonFilesChangedListener(addonFilesChangedListener); if (getView() != null) { extensionHook.getHookView().addOptionPanel(getOptionsPanel()); extensionHook.getHookMenu().addPopupMenuItem(new PopupMenuOpenInBrowser(this)); } extensionHook.addApiImplementor(seleniumApi); <START> ExtensionScript extScript = <END> Control.getSingleton().getExtensionLoader().getExtension(ExtensionScript.class); if (extScript != null) { extScript.registerScriptType( new ScriptType( SCRIPT_TYPE_SELENIUM, "selenium.scripts.type.selenium", createScriptIcon(), true)); } }</code><technical_language>moved instance variable avoid extension time in getWebDriverImpl</technical_language>

Target:
public void hook(ExtensionHook extensionHook) { super.hook(extensionHook); extensionHook.addOptionsParamSet(getOptions()); extensionHook.addAddonFilesChangedListener(addonFilesChangedListener); if (getView() != null) { extensionHook.getHookView().addOptionPanel(getOptionsPanel()); extensionHook.getHookMenu().addPopupMenuItem(new PopupMenuOpenInBrowser(this)); } extensionHook.addApiImplementor(seleniumApi); if (getExtScript() != null) { seleniumScriptType = new ScriptType( SCRIPT_TYPE_SELENIUM, "selenium.scripts.type.selenium", createScriptIcon(), true); extScript.registerScriptType(seleniumScriptType); } }
Source:
<code>protected void basicClear(RegionEventImpl regionEvent) { <START> getDataView().checkSupportsRegionClear(); <END> basicClear(regionEvent, false); }</code><technical_language>LocalRegionDataView. checkSupportsRegionClear() nothing. other data views, including transactions related data views throw exception. Is expected</technical_language>

Target:
protected void basicClear(RegionEventImpl regionEvent) { basicClear(regionEvent, false); }
Source:
<code>private void disposeImages() { <START> for (Image image : images) { <END> image.dispose(); } images = null; }</code><technical_language>images.foreach(i -> i.dispose());</technical_language>

Target:
private void disposeImages() { images.forEach(i -> i.dispose()); images.clear(); }
Source:
<code>public void removeCompareInputChangeListener(ICompareInputChangeListener listener) { <START> if (containsListener(listener)) { <END> listeners.remove(listener); } }</code><technical_language>checking if list contains() remove(), avoid double iterations</technical_language>

Target:
public void removeCompareInputChangeListener(ICompareInputChangeListener listener) { listeners.remove(listener); }
Source:
<code>public void testStoreResults() { String responseBody = "responseBody"; byte[] testResponse = responseBody.getBytes(); <START> Blob result = null; <END> try { result = new SerialBlob(testResponse); } catch (SQLException throwables) { throwables.printStackTrace(); } URL url = defaultResultStorageEngine.storeResults( asyncQueryResultStorage.getId(), testResponse); assertEquals(url.getClass(), URL.class); }</code><technical_language>I L-81 87 is needed</technical_language>

Target:
public void testStoreResults() throws SerialException, SQLException { String responseBody = "responseBody"; byte[] testResponse = responseBody.getBytes(); AsyncQueryResult result = new AsyncQueryResult(); result = defaultResultStorageEngine.storeResults(result, responseBody, "ID"); assertEquals(new SerialBlob(testResponse), result.getAttachment()); }
Source:
<code>private static String ensureEndsWithSlash(String path) { <START> if (path.charAt(path.length() - 1) == '/') { <END> return path; } else { return path + '/'; } }</code><technical_language>path.endsWith("/")</technical_language>

Target:
private static String ensureEndsWithSlash(String path) { return path.endsWith("/") ? path : path + '/'; }
Source:
<code>public boolean appliesToTraceType(Class<? extends ITmfTrace> traceclass) { <START> return !TmfExperiment.class.isAssignableFrom(traceclass); <END> }</code><technical_language>This test analysis non-experiment traces (even non-test ones)</technical_language>

Target:
public boolean appliesToTraceType(Class<? extends ITmfTrace> traceclass) { return TmfTraceStub.class.isAssignableFrom(traceclass); }
Source:
<code>protected void saveMedia(RawPacket p) { RawPacket newMedia; if (mediaPackets.size() < MEDIA_BUF_SIZE) { newMedia = new RawPacket(); newMedia.setBuffer(new byte[FECTransformEngine.INITIAL_BUFFER_SIZE]); newMedia.setOffset(0); } else { newMedia = mediaPackets.remove(mediaPackets.firstKey()); } int pLen = p.getLength(); if (pLen > newMedia.getBuffer().length) { newMedia.setBuffer(new byte[pLen]); } System.arraycopy(p.getBuffer(), p.getOffset(), newMedia.getBuffer(), 0, pLen); <START> newMedia.setLength(pLen); <END> mediaPackets.put(newMedia.getSequenceNumber(), newMedia); }</code><technical_language>I suppose packets offset 0 (and I realize this existing code moved), I explicit setOffset(0) good have</technical_language>

Target:
protected void saveMedia(RawPacket p) { RawPacket newMedia; if (mediaPackets.size() < MEDIA_BUF_SIZE) { newMedia = new RawPacket(); newMedia.setBuffer(new byte[FECTransformEngine.INITIAL_BUFFER_SIZE]); newMedia.setOffset(0); } else { newMedia = mediaPackets.remove(mediaPackets.firstKey()); } int pLen = p.getLength(); if (pLen > newMedia.getBuffer().length) { newMedia.setBuffer(new byte[pLen]); } System.arraycopy(p.getBuffer(), p.getOffset(), newMedia.getBuffer(), 0, pLen); newMedia.setLength(pLen); newMedia.setOffset(0); mediaPackets.put(newMedia.getSequenceNumber(), newMedia); }
Source:
<code>private Document readXMLResource(Resource resource) { try { <START> return db.parse(resource.openInputStream()); <END> } catch (Throwable t) { return db.newDocument(); } }</code><technical_language>try-with-resource resource's inputstream</technical_language>

Target:
private Document readXMLResource(Resource resource) { try (InputStream is = resource.openInputStream()) { return db.parse(is); } catch (Throwable t) { return db.newDocument(); } }
Source:
<code><START> public MetadataCollector getMetadataCollector() { <END> return metadataCollector; }</code><technical_language>public instead of protected</technical_language>

Target:
protected MetadataCollector getMetadataCollector() { return metadataCollector; }
Source:
<code><START> public Operation exec(Prolog engine, UserIdentity userId) throws PrologException { <END> engine.setB0(); Term a1 = arg1.dereference(); Term a2 = arg2.dereference(); Term a3 = arg3.dereference(); Term idTerm; Term nameTerm = Prolog.Nil; Term emailTerm = Prolog.Nil; Account.Id id = userId.getAccount(); if (id == null) { idTerm = anonymous; } else { idTerm = new IntegerTerm(id.get()); } String name = userId.getName(); if (name != null && !name.equals("")) { nameTerm = SymbolTerm.create(name); } String email = userId.getEmail(); if (email != null && !email.equals("")) { emailTerm = SymbolTerm.create(email); } if (!a1.unify(new StructureTerm(user, idTerm), engine.trail)) { return engine.fail(); } if (!a2.unify(nameTerm, engine.trail)) { return engine.fail(); } if (!a3.unify(emailTerm, engine.trail)) { return engine.fail(); } return cont; }</code><technical_language>This public, subclass call it. protected instead</technical_language>

Target:
protected Operation exec(Prolog engine, UserIdentity userId) throws PrologException { engine.setB0(); Term a1 = arg1.dereference(); Term a2 = arg2.dereference(); Term a3 = arg3.dereference(); Term idTerm; Term nameTerm = Prolog.Nil; Term emailTerm = Prolog.Nil; Account.Id id = userId.getAccount(); if (id == null) { idTerm = anonymous; } else { idTerm = new IntegerTerm(id.get()); } String name = userId.getName(); if (name != null && !name.equals("")) { nameTerm = SymbolTerm.create(name); } String email = userId.getEmail(); if (email != null && !email.equals("")) { emailTerm = SymbolTerm.create(email); } if (!a1.unify(new StructureTerm(user, idTerm), engine.trail)) { return engine.fail(); } if (!a2.unify(nameTerm, engine.trail)) { return engine.fail(); } if (!a3.unify(emailTerm, engine.trail)) { return engine.fail(); } return cont; }
Source:
<code>public Instant parse(String value) { if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL")) return null; <START> if (value.charAt(0) == '\'' && value.charAt(value.length() - 1) == '\'') <END> value = unquote(value); if (isLongLiteral(value)) { try { return ofEpochMilli(parseLong(value)); } catch (NumberFormatException e) { throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", value)); } } try { return Instant.from(PARSER.parse(value)); } catch (DateTimeParseException e) { throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", value)); } }</code><technical_language>ParseUtils.isQuoted good for this</technical_language>

Target:
public Instant parse(String value) { if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL")) return null; if (isQuoted(value)) value = unquote(value); if (isLongLiteral(value)) { try { return ofEpochMilli(parseLong(value)); } catch (NumberFormatException e) { throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", value)); } } try { return Instant.from(PARSER.parse(value)); } catch (DateTimeParseException e) { throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", value)); } }
Source:
<code>public synchronized void write(final byte[] data, final int off, final int length) throws IOException { maybeThrowLastError(); Preconditions.checkArgument(data != null, "null data"); if (off < 0 || length < 0 || length > data.length - off) { throw new IndexOutOfBoundsException(); } if (lease != null && lease.isFreed()) { <START> throw new IOException("Attempted to write to file without lease: " + path); <END> } int currentOffset = off; int writableBytes = bufferSize - bufferIndex; int numberOfBytesToWrite = length; while (numberOfBytesToWrite > 0) { if (writableBytes <= numberOfBytesToWrite) { System.arraycopy(data, currentOffset, buffer, bufferIndex, writableBytes); bufferIndex += writableBytes; writeCurrentBufferToService(false, false); currentOffset += writableBytes; numberOfBytesToWrite = numberOfBytesToWrite - writableBytes; } else { System.arraycopy(data, currentOffset, buffer, bufferIndex, numberOfBytesToWrite); bufferIndex += numberOfBytesToWrite; numberOfBytesToWrite = 0; } writableBytes = bufferSize - bufferIndex; } }</code><technical_language>PathIOException path; error string a const matching in tests. Consider a new LeaseRequiredException if helps testing</technical_language>

Target:
public synchronized void write(final byte[] data, final int off, final int length) throws IOException { maybeThrowLastError(); Preconditions.checkArgument(data != null, "null data"); if (off < 0 || length < 0 || length > data.length - off) { throw new IndexOutOfBoundsException(); } if (lease != null && lease.isFreed()) { throw new PathIOException(path, ERR_WRITE_WITHOUT_LEASE); } int currentOffset = off; int writableBytes = bufferSize - bufferIndex; int numberOfBytesToWrite = length; while (numberOfBytesToWrite > 0) { if (writableBytes <= numberOfBytesToWrite) { System.arraycopy(data, currentOffset, buffer, bufferIndex, writableBytes); bufferIndex += writableBytes; writeCurrentBufferToService(); currentOffset += writableBytes; numberOfBytesToWrite = numberOfBytesToWrite - writableBytes; } else { System.arraycopy(data, currentOffset, buffer, bufferIndex, numberOfBytesToWrite); bufferIndex += numberOfBytesToWrite; numberOfBytesToWrite = 0; } writableBytes = bufferSize - bufferIndex; } incrementWriteOps(); }
Source:
<code><START> public CouchProfileService(final CouchDbConnector couchDbConnector, final String attributes, final PasswordEncoder passwordEncoder) { <END> setIdAttribute(COUCH_ID); this.couchDbConnector = couchDbConnector; setAttributes(attributes); setPasswordEncoder(passwordEncoder); }</code><technical_language>other constructor defer this this(...) in order repeat construction logic</technical_language>

Target:
public CouchProfileService(final CouchDbConnector couchDbConnector, final String attributes, final PasswordEncoder passwordEncoder) { setIdAttribute(COUCH_ID); objectMapper = new ObjectMapper(); this.couchDbConnector = couchDbConnector; setAttributes(attributes); setPasswordEncoder(passwordEncoder); }
Source:
<code>public T waitForResponse() { try { <START> boolean timeEllapsed = false; <END> if (timeout != null) { timeEllapsed = !latch.await(timeout, TimeUnit.MILLISECONDS); } else { latch.await(); } if (timeEllapsed || coapTimeout.get()) { coapRequest.cancel(); if (exception.get() != null) { throw exception.get(); } else { if (timeout != null) throw new RequestTimeoutException(coapRequest.toString(), timeout); else throw new RequestTimeoutException(coapRequest.toString()); } } } catch (final InterruptedException e) { LOG.debug("Caught an unexpected InterruptedException during execution of CoAP request", e); } finally { coapRequest.removeMessageObserver(this); } if (exception.get() != null) { throw exception.get(); } return ref.get(); }</code><technical_language>'timeElapsed'</technical_language>

Target:
public T waitForResponse() { try { boolean timeElapsed = false; if (timeout != null) { timeElapsed = !latch.await(timeout, TimeUnit.MILLISECONDS); } else { latch.await(); } if (timeElapsed || coapTimeout.get()) { coapRequest.cancel(); if (exception.get() != null) { throw exception.get(); } } } catch (final InterruptedException e) { LOG.debug("Caught an unexpected InterruptedException during execution of CoAP request", e); } finally { coapRequest.removeMessageObserver(this); } if (exception.get() != null) { throw exception.get(); } return ref.get(); }
Source:
<code>private void invalidateHashForClient(ClientDescriptor originatingClientDescriptor, String cacheId, long key) { int invalidationId = invalidationIdGenerator.getAndIncrement(); Set<ClientDescriptor> clientsToInvalidate = Collections.newSetFromMap(new ConcurrentHashMap<ClientDescriptor, Boolean>()); clientsToInvalidate.addAll(storeClientMap.get(cacheId)); if (originatingClientDescriptor != null) { clientsToInvalidate.remove(originatingClientDescriptor); } InvalidationHolder invalidationHolder = null; <START> invalidationHolder = new InvalidationHolder(originatingClientDescriptor, clientsToInvalidate, cacheId, key); <END> clientsWaitingForInvalidation.put(invalidationId, invalidationHolder); LOGGER.debug("SERVER: requesting client(s) invalidation of hash in cache (ID {})", clientsToInvalidate.size(), key, cacheId, invalidationId); for (ClientDescriptor clientDescriptorThatHasToInvalidate : clientsToInvalidate) { LOGGER.debug("SERVER: asking client to invalidate hash from cache (ID {})", clientDescriptorThatHasToInvalidate, key, cacheId, invalidationId); try { clientCommunicator.sendNoResponse(clientDescriptorThatHasToInvalidate, clientInvalidateHash(cacheId, key, invalidationId)); } catch (MessageCodecException mce) { LOGGER.error("Codec error", mce); } } if (invalidationHolder != null && clientsToInvalidate.isEmpty()) { clientInvalidated(invalidationHolder.clientDescriptorWaitingForInvalidation, invalidationId); } }</code><technical_language>This change means null check line 552 is longer relevant</technical_language>

Target:
private void invalidateHashForClient(ClientDescriptor originatingClientDescriptor, String cacheId, long key) { int invalidationId = invalidationIdGenerator.getAndIncrement(); Set<ClientDescriptor> clientsToInvalidate = Collections.newSetFromMap(new ConcurrentHashMap<ClientDescriptor, Boolean>()); clientsToInvalidate.addAll(storeClientMap.get(cacheId)); if (originatingClientDescriptor != null) { clientsToInvalidate.remove(originatingClientDescriptor); } InvalidationHolder invalidationHolder = new InvalidationHolder(originatingClientDescriptor, clientsToInvalidate, cacheId, key); clientsWaitingForInvalidation.put(invalidationId, invalidationHolder); LOGGER.debug("SERVER: requesting client(s) invalidation of hash in cache (ID {})", clientsToInvalidate.size(), key, cacheId, invalidationId); for (ClientDescriptor clientDescriptorThatHasToInvalidate : clientsToInvalidate) { LOGGER.debug("SERVER: asking client to invalidate hash from cache (ID {})", clientDescriptorThatHasToInvalidate, key, cacheId, invalidationId); try { clientCommunicator.sendNoResponse(clientDescriptorThatHasToInvalidate, clientInvalidateHash(cacheId, key, invalidationId)); } catch (MessageCodecException mce) { throw new AssertionError("Codec error", mce); } } if (clientsToInvalidate.isEmpty()) { clientInvalidated(invalidationHolder.clientDescriptorWaitingForInvalidation, invalidationId); } }