auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public IASTName[] getNames() { IASTName[] result = new IASTName[fQualifierPos + (fLastName == null ? 1 : 2)]; int idx = 0; for (ICPPASTNameSpecifier nameSpecifier : getQualifier()) if (nameSpecifier instanceof IASTName) result[idx++] = (IASTName) nameSpecifier; else throw new UnsupportedOperationException("Can't use getNames() on a " + //$NON-NLS-1$ "qualified name that includes a decltype-specifier. Use " + //$NON-NLS-1$ "getQualifier() and getLastName() instead"); //$NON-NLS-1$ if (fLastName != null) result[fQualifierPos + 1] = fLastName; return result; }

Target:
public IASTName[] getNames() { IASTName[] result = new IASTName[fQualifierPos + (fLastName == null ? 1 : 2)]; int idx = 0; for (ICPPASTNameSpecifier nameSpecifier : getQualifier()) { if (nameSpecifier instanceof IASTName) { result[idx++] = (IASTName) nameSpecifier; } else { throw new UnsupportedOperationException("Can't use getNames() on a " + //$NON-NLS-1$ "qualified name that includes a decltype-specifier. Use " + //$NON-NLS-1$ "getQualifier() and getLastName() instead"); //$NON-NLS-1$ } } if (fLastName != null) result[fQualifierPos + 1] = fLastName; return result; }
Source:
private String getConsoleModelErrorMessage(Object sender, ErrorCodeEventArgs e) { String translatedError = consoleErrorCodeTranslator.translateErrorCode(e.getErrorCode()); if (sender instanceof SpiceConsoleModel) { return ConstantsManager.getInstance() .getMessages() .errConnectingVmUsingSpiceMsg(translatedError); } else if (sender instanceof RdpConsoleModel) { return ConstantsManager.getInstance() .getMessages() .errConnectingVmUsingRdpMsg(translatedError); } throw new IllegalArgumentException("Message recieved from an unknown model " + sender.getClass().getName()); //$NON-NLS-1$ }

Target:
private String getConsoleModelErrorMessage(Object sender, ErrorCodeEventArgs e) { String translatedError = consoleErrorCodeTranslator.translateErrorCode(e.getErrorCode()); if (sender instanceof SpiceConsoleModel) { return ConstantsManager.getInstance() .getMessages() .errConnectingVmUsingSpiceMsg(translatedError); } else if (sender instanceof RdpConsoleModel) { return ConstantsManager.getInstance() .getMessages() .errConnectingVmUsingRdpMsg(translatedError); } return translatedError; }
Source:
private static PendingIntent buildIntent(Context context, long keyId) { Intent intent = new Intent(BROADCAST_ACTION_PASSPHRASE_CACHE_SERVICE); intent.putExtra(EXTRA_KEY_ID, keyId); //request code should be unique for each call for pending intent so we have taken requestcode //as keyId which is unique for each call as keyId is unique for each passphrase long requestcode = keyId; return PendingIntent.getBroadcast(context, (int)requestcode, intent, PendingIntent.FLAG_CANCEL_CURRENT); }

Target:
private static PendingIntent buildIntent(Context context, long keyId) { Intent intent = new Intent(BROADCAST_ACTION_PASSPHRASE_CACHE_SERVICE); intent.putExtra(EXTRA_KEY_ID, keyId); //request code should be unique for each call for pending intent so we have taken requestcode //as keyId which is unique for each call as keyId is unique for each passphrase return PendingIntent.getBroadcast(context, (int)keyId, intent, PendingIntent.FLAG_CANCEL_CURRENT); }
Source:
public String getUserNameForChannel(UUID channelId) throws UnauthenticatedException { try (LockResource clientsLockShared = new LockResource(mClientsLock.readLock())) { if (mChannels.containsKey(channelId)) { AuthenticatedChannelInfo clientInfo = mChannels.get(channelId); return mChannels.get(channelId).getUserName(); } else { throw new UnauthenticatedException( String.format("Client:%s needs to be authenticated", channelId.toString())); } } }

Target:
public String getUserNameForChannel(UUID channelId) throws UnauthenticatedException { if (mChannels.containsKey(channelId)) { AuthenticatedChannelInfo clientInfo = mChannels.get(channelId); return clientInfo.getUserName(); } else { throw new UnauthenticatedException( String.format("Client:%s needs to be authenticated", channelId.toString())); } }
Source:
public void handle(DataServerConnection connection, int rpcType, ByteBuf pBody, ByteBuf dBody, ResponseSender sender) throws RpcException { switch (rpcType) { case RpcType.REQ_RUNTIME_FILTER_VALUE : { handleRuntimeFilterRequest(pBody, dBody, sender); } case RpcType.REQ_RECORD_BATCH_VALUE : { handleRecordBatchRequest(pBody, dBody, sender); } default: throw new RpcException("Not yet supported."); } }

Target:
public void handle(DataServerConnection connection, int rpcType, ByteBuf pBody, ByteBuf dBody, ResponseSender sender) throws RpcException { switch (rpcType) { case RpcType.REQ_RUNTIME_FILTER_VALUE : { handleRuntimeFilterRequest(pBody, dBody, sender); break; } case RpcType.REQ_RECORD_BATCH_VALUE : { handleRecordBatchRequest(pBody, dBody, sender); break; } default: throw new RpcException("Not yet supported."); } }
Source:
public void process(CtElement element) { if(element instanceof CtPackage && element != getFactory().Package().getRootPackage()){ ((CtPackage) element).setSimpleName("newtest"); } }

Target:
public void process(CtElement element) { if(element instanceof CtPackage){ ((CtPackage) element).setSimpleName("newtest"); } }
Source:
public void testGenerateGroupId() { String user = System.getProperty("user.name"); String vcloudGroupId = JcloudsLocation.generateGroupId("vcloud"); assertTrue(vcloudGroupId.startsWith("br-")); String fooGroupId = JcloudsLocation.generateGroupId("foo"); if (!"brooklyn".equals(user)) assertTrue(fooGroupId.startsWith("brooklyn-"+user)); }

Target:
public void testGenerateGroupId() { String user = System.getProperty("user.name"); String vcloudGroupId = JcloudsLocation.generateGroupId("vcloud"); assertTrue(vcloudGroupId.startsWith("br-")); String fooGroupId = JcloudsLocation.generateGroupId("foo"); if ("brooklyn".equals(user)) { // skip check -- we don't write brooklyn-brooklyn- because that looks funny // (and running as user brooklyn is common) } else { assertTrue(fooGroupId.startsWith("brooklyn-"+user)); } }
Source:
public void populateExpressionProperty(FactModelTree factModelTree) { if (factModelTree.getSimpleProperties().containsValue(ConstantsHolder.EXPRESSION_CLASSNAME)) { return; } final String expressionName = factModelTree.getFactName() + ConstantsHolder.EXPRESSION_SUFFIX; long count = factModelTree.getSimpleProperties().keySet().stream().filter(key -> key.startsWith(expressionName)).count(); factModelTree.addSimpleProperty(count > 0 ? expressionName + "_" + count : expressionName, ConstantsHolder.EXPRESSION_CLASSNAME); }

Target:
public void populateExpressionProperty(FactModelTree factModelTree) { factModelTree.addSimpleProperty(factModelTree.getFactName() + ConstantsHolder.EXPRESSION_SUFFIX, ConstantsHolder.EXPRESSION_CLASSNAME); }
Source:
private SelectionListener createListener() { final SelectionListener listener = new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { resetProperties(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // nothing to do } }; return listener; }

Target:
private SelectionListener createListener() { final SelectionListener listener = new SelectionListener() { @Override public void widgetSelected(final SelectionEvent e) { resetProperties(); } @Override public void widgetDefaultSelected(final SelectionEvent e) { // nothing to do } }; return listener; }
Source:
public void testOur404Handler(String wiki, String inputPath, String expectedPath) { String wikiBase = urlBuilder.getUrlForWiki(wiki); String inputUrl = wikiBase + inputPath; String expectedUrl = expectedPath; if (!expectedUrl.startsWith("http://")) { expectedUrl = wikiBase + expectedUrl; } driver.get(inputUrl); String actualUrl = driver.getCurrentUrl(); Assertion.assertEquals(actualUrl, expectedUrl); }

Target:
public void testOur404Handler(String wiki, String inputPath, String expectedPath) { String wikiBase = urlBuilder.getUrlForWiki(wiki); String inputUrl = wikiBase + inputPath; String expectedUrl = wikiBase + expectedPath; // Special case for favicon: if (expectedPath.startsWith("http://")) { expectedUrl = expectedPath; } driver.get(inputUrl); String actualUrl = driver.getCurrentUrl(); Assertion.assertEquals(actualUrl, expectedUrl); }
Source:
public void add(Key k, Value v) { if (key == null) { key = k; timeStamps.add(k.getTimestamp()); values.add(v); size++; } else if (key.compareRow(k.getRow()) == 0 && key.compareColumnFamily(k.getColumnFamily()) == 0) { timeStamps.add(k.getTimestamp()); values.add(v); } else { //TODO: what happens here } }

Target:
public void add(Key k, Value v) throws IllegalArgumentException { add(k, v.get()); }
Source:
public List getArquivosOriginais() { return arquivosIniciais; }

Target:
public List<File> getArquivosOriginais() { return arquivosIniciais; }
Source:
private boolean matchExpressionAndColumnRef(AbstractExpression statementExpr, ColumnRef indexColRef, StmtTableScan tableScan) { if (statementExpr instanceof TupleValueExpression) { TupleValueExpression tve = (TupleValueExpression)statementExpr; if (tve.getTableAlias().equals(tableScan.getTableAlias()) && tve.getColumnName().equals(indexColRef.getColumn().getTypeName())) { // NB: m_emptyBindings is a null list. That means // we matched, but with no bindings. return true; } } return false; }

Target:
private static boolean matchExpressionAndColumnRef(AbstractExpression statementExpr, ColumnRef indexColRef, StmtTableScan tableScan) { if (statementExpr instanceof TupleValueExpression) { TupleValueExpression tve = (TupleValueExpression)statementExpr; if (tve.getTableAlias().equals(tableScan.getTableAlias()) && tve.getColumnName().equals(indexColRef.getColumn().getTypeName())) { return true; } } return false; }
Source:
private boolean isNotTimeshiftedOrHd(Channel channel) { boolean timeshifted = MoreObjects.firstNonNull(channel.getTimeshifted(), false); boolean hd = MoreObjects.firstNonNull(channel.getHighDefinition(), false); return !(timeshifted || hd); }

Target:
boolean isNotTimeshiftedOrHd(Channel channel) { boolean timeshifted = MoreObjects.firstNonNull(channel.getTimeshifted(), false); boolean hd = MoreObjects.firstNonNull(channel.getHighDefinition(), false); return !(timeshifted || hd); }
Source:
public String toString() { return toStringHelper(this) .omitNullValues() .add("outputSymbolAliases", this.outputSymbolAliases) .add("expectedOutputSymbolCount", expectedOutputSymbolCount) .add("expectedRows", expectedRows) .toString(); }

Target:
public String toString() { return toStringHelper(this) .omitNullValues() .add("outputSymbolAliases", outputSymbolAliases) .add("expectedOutputSymbolCount", expectedOutputSymbolCount) .add("expectedRows", expectedRows) .toString(); }
Source:
public UpdateSite createDefaultUpdateSite() { return new UpdateSite(PREDEFINED_UPDATE_SITE_ID, config.getUpdateCenterUrl() + "update-center.json"); }

Target:
protected UpdateSite createDefaultUpdateSite() { return new UpdateSite(PREDEFINED_UPDATE_SITE_ID, config.getUpdateCenterUrl() + "update-center.json"); }
Source:
public void buildDependencyGraph(AbstractProject owner, DependencyGraph graph) { // Can only add dependencies in Hudson 1.341 or higher if (!canDeclare(owner)) return; for (BuildTriggerConfig config : configs) { List<AbstractProject> projectList = Util.filter(config.getProjectList(owner.getParent(), null), AbstractProject.class); for (AbstractProject project : projectList) ParameterizedDependency.add(owner, project, config, graph); } }

Target:
public void buildDependencyGraph(AbstractProject owner, DependencyGraph graph) { // Can only add dependencies in Hudson 1.341 or higher if (!canDeclare(owner)) return; for (BuildTriggerConfig config : configs) { List<AbstractProject> projectList = config.getProjectList(owner.getParent(), null); for (AbstractProject project : projectList) { ParameterizedDependency.add(owner, project, config, graph); } } }
Source:
public static boolean hasPushStatusBug(int[] version) { int cmp = compare(version, v1_7_8_6); if (cmp < 0) return true; // Everything before 1.7.8.6 is known broken. else if (cmp == 0) return false; // 1.7.8.6 contained the bug fix. if (compare(version, v1_7_9) <= 0) return true; // 1.7.9 shipped before 1.7.8.6 and has the bug. return false; // 1.7.9.1 and later are fixed. }

Target:
public static boolean hasPushStatusBug(int[] version) { return false; }
Source:
public static Long getTimeFromDateString(String dateString) { try { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); Date date = dateFormatter.parse(dateString); return date.getTime(); } catch (ParseException e) { logger.warn("Could not parse milliseconds from an HTTP date header (" + dateString + ")."); return null; } }

Target:
public static Long getTimeFromDateString(String dateString) { try { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); return dateFormatter.parse(dateString).getTime(); } catch (ParseException e) { logger.warn("Could not parse milliseconds from an HTTP date header (" + dateString + ")."); return null; } }
Source:
static boolean isFixedWidth(ValueVector vv) { return (vv instanceof FixedWidthVector); }

Target:
private static boolean isFixedWidth(ValueVector vv) { return (vv instanceof FixedWidthVector); }
Source:
public static Mono<byte[]> downloadFileAsync(String url, HttpPipeline httpPipeline) { FileService service = RestProxy.create(FileService.class, httpPipeline); try { return service.download(getHost(url), getPathAndQuery(url)) .flatMap(response -> FluxUtil.collectBytesInByteBufferStream(response.getValue())); } catch (MalformedURLException ex) { return Mono.empty(); } }

Target:
public static Mono<byte[]> downloadFileAsync(String url, HttpPipeline httpPipeline) { FileService service = RestProxy.create(FileService.class, httpPipeline); try { return service.download(getHost(url), getPathAndQuery(url)) .flatMap(response -> FluxUtil.collectBytesInByteBufferStream(response.getValue())); } catch (MalformedURLException ex) { return Mono.error(() -> ex); } }
Source:
public long getOldestWriteTimstamp() { // When there is no data in the buffer return the max possible timestamp // so that no query's timestamp is less than this timestamp if(writes.size() == 0) { return Long.MAX_VALUE; } Write oldestWrite = writes.get(0); return oldestWrite.getVersion(); }

Target:
public long getOldestWriteTimstamp() { // When there is no data in the buffer return the max possible timestamp // so that no query's timestamp is less than this timestamp if(writes.size() == 0) { return Long.MAX_VALUE; } else { Write oldestWrite = writes.get(0); return oldestWrite.getVersion(); } }
Source:
public ScanningMode enter(CtElement element) { CtElement ele = element; if (ele.hasParent(ignoredParent)) { if (element.hasParent(ignoredParent)) { return ScanningMode.SKIP_ALL; } } if (element instanceof CtType) { nrOfNestedLocalClasses++; } return ScanningMode.NORMAL; }

Target:
public ScanningMode enter(CtElement element) { if (element.hasParent(ignoredParent)) { return ScanningMode.SKIP_ALL; } if (element instanceof CtType) { nrOfNestedLocalClasses++; } return ScanningMode.NORMAL; }
Source:
public boolean isComplex() { if (metadata.getType().getMinorType() == MinorType.MAP || metadata.getType().getMinorType() == MinorType.UNION || metadata.getType().getMinorType() == MinorType.LIST) { return true; } return false; }

Target:
public boolean isComplex() { return metadata.getType().getMinorType() == MinorType.MAP || metadata.getType().getMinorType() == MinorType.UNION || metadata.getType().getMinorType() == MinorType.LIST; }
Source:
protected Builder() { super(ShipyardApi.class); id("shipyard") .name("Shipyard Remote Docker Management API") .identityName("<shipyard-service-key>") .credentialName("not used") .documentation(URI.create("http://shipyard-project.com/docs/api/")) .version("2.0.4") .defaultEndpoint("https://127.0.0.1:8080") .defaultProperties(ShipyardApiMetadata.defaultProperties()) .defaultModules(ImmutableSet.<Class<? extends Module>>of( OkHttpCommandExecutorServiceModule.class, ShipyardHttpApiModule.class)); }

Target:
protected Builder() { super(ShipyardApi.class); id("shipyard") .name("Shipyard Remote Docker Management API") .identityName("<shipyard-service-key>") .credentialName("not used") .documentation(URI.create("http://shipyard-project.com/docs/api/")) .version("2.0.4") .defaultEndpoint("https://127.0.0.1:8080") .defaultProperties(ShipyardApiMetadata.defaultProperties()) .defaultModules(ImmutableSet.<Class<? extends Module>>of( ShipyardHttpApiModule.class)); }
Source:
public void selectAll(){ int numberOfFiles = mAdapter.getCount(); for(int i = 0; i < numberOfFiles; i++){ File file = (File) mAdapter.getItem(i); if (file != null) { /// Click on a directory if (file.isDirectory()) { } else { /// Click on a file getListView().setItemChecked(i, true); // notify the change to the container Activity mContainerActivity.onFileClick(file); } } } }

Target:
public void selectAll(){ int numberOfFiles = mAdapter.getCount(); for(int i = 0; i < numberOfFiles; i++){ File file = (File) mAdapter.getItem(i); if (file != null) { if (!file.isDirectory()) { /// Click on a file getListView().setItemChecked(i, true); // notify the change to the container Activity mContainerActivity.onFileClick(file); } } } }
Source:
public Result apply(N node, Captures captures, Context context) { Map<DereferenceExpression, VariableReferenceExpression> expressions = getDereferenceSymbolMap(ExpressionExtractor.extractExpressionsNonRecursive(node), context, metadata, sqlParser); if (expressions.isEmpty()) { return Result.empty(); } return Result.ofPlanNode(new ProjectNode(context.getIdAllocator().getNextId(), rewrite(context, node, HashBiMap.create(expressions)), identityAssignmentsAsSymbolReferences(node.getOutputVariables()))); }

Target:
public Result apply(N node, Captures captures, Context context) { Map<DereferenceExpression, VariableReferenceExpression> expressions = getDereferenceSymbolMap(extractExpressionsNonRecursive(node), context, metadata, sqlParser); if (expressions.isEmpty()) { return Result.empty(); } return Result.ofPlanNode(new ProjectNode(context.getIdAllocator().getNextId(), rewrite(context, node, HashBiMap.create(expressions)), identityAssignmentsAsSymbolReferences(node.getOutputVariables()))); }
Source:
protected void onResume() { String action = getIntent().getAction(); if (action == null || !action.equals("Already created")) { // don't restart if action is present Intent intent = new Intent(this, AddBudgetActivity.class); startActivity(intent); finish(); } else { // remove the unique action so the next time onResume // call will force restart getIntent().setAction(null); } super.onResume(); }

Target:
protected void onResume() { super.onResume(); String action = getIntent().getAction(); if (action == null || !action.equals("Already created")) { // don't restart if action is present Intent intent = new Intent(this, AddBudgetActivity.class); startActivity(intent); finish(); } else { // remove the unique action so the next time onResume // call will force restart getIntent().setAction(null); } }
Source:
private void mapNodes() { if (fNodesList == null) { fNodesMap = new HashMap<>(1); return; } // Create a map with capacity for all child nodes. fNodesMap = new HashMap<>(fNodesList.size() * 4 / 3); for (ModelDelta element : fNodesList) { mapNode( element ); } }

Target:
private void mapNodes() { if (fNodesList == null) { fNodesMap = new HashMap<>(1); return; } // Create a map with capacity for all child nodes. fNodesMap = new HashMap<>(fNodesList.size() * 4 / 3); for (ModelDelta node : fNodesList) { mapNode( node ); } }
Source:
protected void onSuccess(List<Question> questions) { if (questions == null) { showAlert("GetQuestion", "質問がありません。"); } else { for (Question q : questions) { questionList.add(q); } } // スクロールを確認するため追加 for (int i = 0; i < 20; i++) questionList.add(new Question("タイトル" + i, "本文" + i, "作者" + i)); adapter.notifyDataSetChanged(); }

Target:
protected void onSuccess(List<Question> questions) { if (questions == null) { showAlert("GetQuestion", "質問がありません。"); } else { adapter.clear(); // Robolectric does not implement addAll, // so we use add method and a loop instead for the time being. // https://github.com/pivotal/robolectric/issues/281 for (Question q : questions) { adapter.add(q); } adapter.notifyDataSetChanged(); } }
Source:
public AssociationOrderBy(String expression, String order) { columnName = expression.substring( 1, expression.length() - 1 ); kind = ( "desc".equalsIgnoreCase( order ) ) ? Order.DESC : Order.ASC; }

Target:
public AssociationOrderBy(String expression, String order) { // extract column name from expression, such as "{columnName}" columnName = expression.substring( 1, expression.length() - 1 ); kind = "desc".equalsIgnoreCase( order ) ? Order.DESC : Order.ASC; }
Source:
public FloatSelectiveStreamReader( StreamDescriptor streamDescriptor, Optional<TupleDomainFilter> filter, boolean outputRequired, LocalMemoryContext systemMemoryContext) { this.streamDescriptor = requireNonNull(streamDescriptor, "streamDescriptor is null"); this.filter = filter.orElse(null); this.outputRequired = outputRequired; this.systemMemoryContext = requireNonNull(systemMemoryContext, "systemMemoryContext is null"); this.nonDeterministicFilter = this.filter != null && !this.filter.isDeterministic(); this.nullsAllowed = this.filter == null || this.filter.testNull(); }

Target:
public FloatSelectiveStreamReader( StreamDescriptor streamDescriptor, Optional<TupleDomainFilter> filter, boolean outputRequired, LocalMemoryContext systemMemoryContext) { this.streamDescriptor = requireNonNull(streamDescriptor, "streamDescriptor is null"); this.filter = filter.orElse(null); this.outputRequired = outputRequired; this.systemMemoryContext = requireNonNull(systemMemoryContext, "systemMemoryContext is null"); this.nonDeterministicFilter = this.filter != null && !this.filter.isDeterministic(); this.nullsAllowed = this.filter == null || nonDeterministicFilter || this.filter.testNull(); }
Source:
private String getBundleVersion() { ClassLoader cl = getClass().getClassLoader(); if (cl instanceof URLClassLoader) { URL url = ((URLClassLoader) cl).findResource(JarFile.MANIFEST_NAME); try { Manifest manifest = new Manifest(url.openStream()); return manifest.getMainAttributes().getValue("Bundle-Version"); } catch (IOException e) { // do nothing - will return null } } return null; }

Target:
private String getBundleVersion() { ClassLoader cl = getClass().getClassLoader(); if (cl instanceof URLClassLoader) { URL url = ((URLClassLoader) cl).findResource(JarFile.MANIFEST_NAME); if (url != null) return getBundleVersion(url); } return null; }
Source:
public void onSkipInWrite(S item, Throwable t) { if(skipWriteDelegate != null && t instanceof Exception) { try { skipWriteDelegate.onSkipWriteItem(Collections.<Object>singletonList(item), (Exception) t); } catch (Exception e) { throw new BatchRuntimeException(e); } } }

Target:
public void onSkipInWrite(S item, Throwable t) { if(skipWriteDelegate != null && t instanceof Exception) { try { /* * assuming this SkipListenerAdapter will only be called from JsrFaultTolerantChunkProcessor, * which calls onSkipInWrite() with the whole chunk (List) of items instead of single item */ skipWriteDelegate.onSkipWriteItem((List<Object>) item, (Exception) t); } catch (Exception e) { throw new BatchRuntimeException(e); } } }
Source:
public static boolean sqSupportsExternalIssues() { return orchestrator.getServer().version().isGreaterThanOrEquals(7, 2); }

Target:
private static boolean sqSupportsExternalIssues() { return orchestrator.getServer().version().isGreaterThanOrEquals(7, 2); }
Source:
public void testMakeTimeZone_All() throws IOException { ZoneInfoDB.TzData instance = ZoneInfoDB.getInstance(); String[] availableIDs = instance.getAvailableIDs(); Arrays.sort(availableIDs); for (String id : availableIDs) { BufferIterator bufferIterator = instance.getBufferIterator(id); // Create a ZoneInfo at the earliest possible time to allow us to use the // useDaylightTime() method to check whether it ever has or ever will support daylight // savings time. ZoneInfo zoneInfo = ZoneInfo.makeTimeZone(id, bufferIterator, Long.MIN_VALUE); assertNotNull("TimeZone " + id + " was not created", zoneInfo); assertEquals(id, zoneInfo.getID()); } }

Target:
public void testMakeTimeZone_All() throws Exception { ZoneInfoDB.TzData instance = ZoneInfoDB.getInstance(); String[] availableIDs = instance.getAvailableIDs(); Arrays.sort(availableIDs); for (String id : availableIDs) { BufferIterator bufferIterator = instance.getBufferIterator(id); // Create a ZoneInfo at the earliest possible time to allow us to use the // useDaylightTime() method to check whether it ever has or ever will support daylight // savings time. ZoneInfo zoneInfo = ZoneInfo.makeTimeZone(id, bufferIterator, Long.MIN_VALUE); assertNotNull("TimeZone " + id + " was not created", zoneInfo); assertEquals(id, zoneInfo.getID()); } }
Source:
public Integer getDefaultAutoLimit() { return defaultAutoLimit; }

Target:
public int getDefaultAutoLimit() { return defaultAutoLimit; }
Source:
public byte getFormatVersion() { return formatVersion; }

Target:
byte getFormatVersion() { return formatVersion; }
Source:
public void load(LazyBlock lazyBlock) { if (block == null) { return; } while (block instanceof LazyBlock) { block = ((LazyBlock) block).getBlock(); } Block coercedBlock = coercer.apply(block); lazyBlock.setBlock(coercedBlock); // clear reference to loader to free resources, since load was successful block = null; }

Target:
public void load(LazyBlock lazyBlock) { if (block == null) { return; } if (block instanceof LazyBlock) { block = ((LazyBlock) block).getBlock(); } Block coercedBlock = coercer.apply(block); lazyBlock.setBlock(coercedBlock); // clear reference to loader to free resources, since load was successful block = null; }
Source:
public void saveContainer(String id) { HashMap<String, String> map = new HashMap<>(); //setting the node id in case it exists on graph Optional.ofNullable(canvasHandler.getGraphIndex().get(id)).ifPresent(node -> { map.put(DEFAULT_NODE_ID, id); map.put(svgNodeId, id); }); context.saveGroup(map); }

Target:
public void saveContainer(String id) { HashMap<String, String> map = new HashMap<>(); //setting the node id in case it exists on graph if (canvasHandler.getGraphIndex().get(id) != null) { map.put(DEFAULT_NODE_ID, id); map.put(svgNodeId, id); } context.saveGroup(map); }
Source:
public static boolean isDomainSocketSupported(WorkerNetAddress workerNetAddress) { boolean isDomainSocketSupported = !workerNetAddress.getDomainSocketPath().isEmpty(); if (isDomainSocketSupported) { if (Configuration.getBoolean(PropertyKey.WORKER_DATA_SERVER_DOMAIN_SOCKET_AS_UUID)) { isDomainSocketSupported = FileUtils.exists(workerNetAddress.getDomainSocketPath()); } else { isDomainSocketSupported = workerNetAddress.getHost().equals(NetworkAddressUtils.getClientHostName()); } } return isDomainSocketSupported && CHANNEL_TYPE == ChannelType.EPOLL; }

Target:
public static boolean isDomainSocketSupported(WorkerNetAddress workerNetAddress) { if (workerNetAddress.getDomainSocketPath().isEmpty() || CHANNEL_TYPE != ChannelType.EPOLL) { return false; } if (Configuration.getBoolean(PropertyKey.WORKER_DATA_SERVER_DOMAIN_SOCKET_AS_UUID)) { return FileUtils.exists(workerNetAddress.getDomainSocketPath()); } else { return workerNetAddress.getHost().equals(NetworkAddressUtils.getClientHostName()); } }
Source:
public static GrpcDataWriter create(FileSystemContext context, WorkerNetAddress address, long id, long length, RequestType type, OutStreamOptions options) throws IOException { long chunkSize = Configuration.getBytes(PropertyKey.USER_NETWORK_WRITER_CHUNK_SIZE_BYTES); BlockWorkerClient grpcClient = context.acquireBlockWorkerClient(address); try { return new GrpcDataWriter(context, address, id, length, chunkSize, type, options, grpcClient); } catch (Exception e) { // Close the client before releasing in order to get it removed from the pool. grpcClient.close(); context.releaseBlockWorkerClient(address, grpcClient); throw e; } }

Target:
public static GrpcDataWriter create(FileSystemContext context, WorkerNetAddress address, long id, long length, RequestType type, OutStreamOptions options) throws IOException { long chunkSize = Configuration.getBytes(PropertyKey.USER_NETWORK_WRITER_CHUNK_SIZE_BYTES); BlockWorkerClient grpcClient = context.acquireBlockWorkerClient(address); try { return new GrpcDataWriter(context, address, id, length, chunkSize, type, options, grpcClient); } catch (Exception e) { context.releaseBlockWorkerClient(address, grpcClient); throw e; } }
Source:
public boolean isRelevant() { if (!jenkins.hasPermission(Jenkins.RUN_SCRIPTS))) { return false; } if (rule.getMasterKillSwitch()) { return true; // always relevant if it is enabled. } return jenkins.isUseSecurity() // if security is off, there's no point && (jenkins.getComputers().length>1 // if there's no slave, || !jenkins.clouds.isEmpty() // and no clouds, likewise this is pointless || Relevance.fromExtension() // unless a plugin thinks otherwise ) ; }

Target:
public boolean isRelevant() { return jenkins.hasPermission(Jenkins.RUN_SCRIPTS) && jenkins.isUseSecurity(); }
Source:
public final void validateNullUser() { final AuthKeys authKeys = new AuthKeys(); final String user = null; final String password = "password"; authKeys.authenticate(user, password); }

Target:
public final void validateNullUser() throws Exception { final AuthKeys authKeys = new AuthKeys(); authKeys.authenticate(null, "password"); }
Source:
protected boolean validateScreenDescriptor() { if (screenBackgroundColor >= screenColors) { // Not in the specification, but here the background color would refer to a color // index not within the bounds of the Global Color Table. return false; } return true; }

Target:
protected boolean validateScreenDescriptor() { // Not in the specification, but check whether the background color index is within // the bounds of the Global Color Table just to be sure. return screenBackgroundColor < screenColors; }
Source:
public void testEmptyKeyDefaults() { for (PropertyKey key : PropertyKey.defaultKeys()) { assertNotEquals(key.getDefaultValue(), "", String.format( "Property keys cannot have a default value of \"\". Offending key: %s", key.getName())); } }

Target:
public void testEmptyKeyDefaults() { for (PropertyKey key : PropertyKey.defaultKeys()) { assertNotEquals(String.format( "Property keys cannot have a default value of \"\". Offending key: %s", key.getName()), key.getDefaultValue(), ""); } }
Source:
private boolean shouldAdd(String dimName) { final boolean belowThreshold = pQueue.size() < this.threshold; final boolean belowMax = belowThreshold || this.comparator.compare(pQueue.peek().getTopNMetricVal(), dimName) < 0; return belowMax && comparator.compare(dimName, previousStop) > 0; }

Target:
private boolean shouldAdd(String dimName) { final boolean belowThreshold = pQueue.size() < threshold; final boolean belowMax = belowThreshold || comparator.compare(pQueue.peek().getTopNMetricVal(), dimName) < 0; // Only add if dimName is after previousStop return belowMax && (previousStop == null || comparator.compare(dimName, previousStop) > 0); }
Source:
public static int getValue(String text) { if (text == null || text.isEmpty() || text.equals("build")) { //$NON-NLS-1$ return BUILD; } if (text.equals("codan")) { //$NON-NLS-1$ return CODAN; } if (text.equals("build,codan")) { //$NON-NLS-1$ return BUILD_AND_CODAN; } throw new IllegalArgumentException("Unknown context value: " + text); //$NON-NLS-1$ }

Target:
public static int getValue(String text) { if (text == null || text.isEmpty() || text.equals("build")) { //$NON-NLS-1$ return BUILD; } if (text.equals("codan")) { //$NON-NLS-1$ return CODAN; } throw new IllegalArgumentException("Unknown context value: " + text); //$NON-NLS-1$ }
Source:
public String getResourceContent(String name) throws IOException { if (getEngineContext() != null) { try (InputStream is = getResourceAsStream(name)) { if (is == null) { // Resources should always be encoded as UTF-8, to reduce the dependency on the system encoding return FileUtils.readFileToString(new File(name), DEFAULT_ENCODING); } return IOUtils.toString(is, DEFAULT_ENCODING); } catch (Exception e) { } } return null; }

Target:
public String getResourceContent(String name) throws IOException { if (getEngineContext() != null) { try (InputStream is = getResourceAsStream(name)) { if (is != null) { return IOUtils.toString(is, DEFAULT_ENCODING); } } } // Resources should always be encoded as UTF-8, to reduce the dependency on the system encoding return FileUtils.readFileToString(new File(name), DEFAULT_ENCODING); }
Source:
public void testGetLevel() throws Exception { assertEquals(building.getLevel(0), levelA); assertNotSame(building.getLevel(0), levelB); }

Target:
public void testGetLevel() throws Exception { assertEquals(building.getLevel(0), levelA); assertNotSame(building.getLevel(0), levelB); assertEquals(building.getLevel(1), levelB); assertNotSame(building.getLevel(1), levelA); }
Source:
public UUID send(Iterable<? extends MimeMessage> messages, Session session) throws MessagingException { MailListener listener = getListener("memory"); UUID batchID = sendAsynchronously(messages, session, listener); waitTillSent(Long.MAX_VALUE); Iterator<MailStatus> errors = listener.getErrors(); if (errors.hasNext()) { throw new MessagingException( String.format("Failed to send mail message [%s] ", errors.next().getException())); } return batchID; }

Target:
public UUID send(Iterable<? extends MimeMessage> messages, Session session) throws MessagingException { MailListener listener = getListener("memory"); UUID batchID = sendAsynchronously(messages, session, listener); waitTillSent(Long.MAX_VALUE); return batchID; }
Source:
public java.io.File toLocalFile(int options, IProgressMonitor monitor) throws CoreException { SubMonitor subMonitor = SubMonitor.convert(monitor); //caching is the only recognized option if (options != EFS.CACHE) return null; return FileCache.getCache().cache(this, subMonitor); }

Target:
public java.io.File toLocalFile(int options, IProgressMonitor monitor) throws CoreException { //caching is the only recognized option if (options != EFS.CACHE) return null; return FileCache.getCache().cache(this, monitor); }
Source:
public static void invalidateThumbnail(PublishedInfo layer) { //Allow a bit of leeway, to support GetMap composer format //(in case of getMap returning before put layer) Date d = new Date(new Date().getTime()-1000); if (Metadata.modified(layer) != null && d.before(Metadata.modified(layer))) { return; } Metadata.map(layer).remove(Metadata.THUMBNAIL); }

Target:
public static void invalidateThumbnail(PublishedInfo layer) { Metadata.map(layer).remove(Metadata.THUMBNAIL); }
Source:
private static URL deploymentStaticOne() throws Throwable { System.out.println("deploymentStatic"); return new URL("http://blah.com/static"); }

Target:
private static URL deploymentStaticOne() throws Throwable { return new URL("http://blah.com/static"); }
Source:
private void validateStateOfWrittenEntry(long address, @Nonnull ILogData ld) { ILogData logData; try { logData = read(address, defaultReadOptions); } catch (TrimmedException te) { // We cannot know if the write went through or not throw new UnrecoverableCorfuError("We cannot determine state of an update because of a trim."); } if (!logData.equals(ld)){ throw new OverwriteException(OverwriteCause.DIFF_DATA); } }

Target:
private void validateStateOfWrittenEntry(long address, @Nonnull ILogData ld) { ILogData logData; try { logData = read(address); } catch (TrimmedException te) { // We cannot know if the write went through or not throw new UnrecoverableCorfuError("We cannot determine state of an update because of a trim."); } if (!logData.equals(ld)){ throw new OverwriteException(OverwriteCause.DIFF_DATA); } }
Source:
void addRevisionType(Element anyMapping, Element anyMappingEnd, boolean isKey) { final Element revTypeProperty = MetadataTools.addProperty( anyMapping, verEntCfg.getRevisionTypePropName(), verEntCfg.getRevisionTypePropType(), true, isKey ); revTypeProperty.addAttribute( "type", "org.hibernate.envers.internal.entities.RevisionTypeType" ); // Add further columns to the aud table addAdditionalColumns( anyMappingEnd ); }

Target:
void addRevisionType(Element anyMapping, Element anyMappingEnd, boolean isKey) { final Element revTypeProperty = MetadataTools.addProperty( anyMapping, verEntCfg.getRevisionTypePropName(), verEntCfg.getRevisionTypePropType(), true, isKey ); revTypeProperty.addAttribute( "type", "org.hibernate.envers.internal.entities.RevisionTypeType" ); }
Source:
public void walk(Consumer<Node> consumer) { treeIterable(TreeTraversal.PREORDER).forEach(consumer); }

Target:
public void walk(Consumer<Node> consumer) { walk(PREORDER, consumer); }
Source:
public void testMapSubscript() { assertQuery("SELECT map(array[1], array['aa'])[1]", "SELECT 'aa'"); assertQuery("SELECT map(array['a'], array['aa'])['a']", "SELECT 'aa'"); assertQuery("SELECT map(array[array[1,1]], array['a'])[array[1,1]]", "SELECT 'a'"); assertQuery("SELECT map(array[(1,2)], array['a'])[(1,2)]", "SELECT 'a'"); // Force the last value in the key BlockBuilder to the end of the internal Slice, so that searching for longer key values can be tested. // 'idv_fail' and 'request_fail' has the same hash value. assertQuery("SELECT map(array['0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456', 'idv_fail'], array['aa', 'bb'])['request_fail']", "SELECT NULL"); assertQuery("SELECT map(array['0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456', 'idv_fail'], array['aa', 'bb'])['idv_fail']", "SELECT 'bb'"); }

Target:
public void testMapSubscript() { assertQuery("SELECT map(array[1], array['aa'])[1]", "SELECT 'aa'"); assertQuery("SELECT map(array['a'], array['aa'])['a']", "SELECT 'aa'"); assertQuery("SELECT map(array[array[1,1]], array['a'])[array[1,1]]", "SELECT 'a'"); assertQuery("SELECT map(array[(1,2)], array['a'])[(1,2)]", "SELECT 'a'"); }
Source:
public void run() { Socket socket; OutputStream outputStream = null; try { socket = serverSocket.accept(); String response = getResponse(socket); outputStream = socket.getOutputStream(); writeResponseHeader(outputStream); write(response.getBytes(), outputStream); outputStream.flush(); } catch (IOException e) { // e.printStackTrace(); } finally { // we should not close the connection, let the client close the // connection StreamUtils.quietlyClose(outputStream); } }

Target:
public void run() { Socket socket = null; OutputStream outputStream = null; try { socket = serverSocket.accept(); String response = getResponse(socket); outputStream = socket.getOutputStream(); writeResponseHeader(outputStream); write(response.getBytes(), outputStream); outputStream.flush(); } catch (IOException e) { // e.printStackTrace(); } finally { // we should not close the connection, let the client close the // connection StreamUtils.quietlyClose(outputStream); } }
Source:
public final boolean mightBeRacilyClean(final int smudge_s, final int smudge_ns) { // If the index has a modification time then it came from disk // and was not generated from scratch in memory. In such cases // the entry is 'racily clean' if the entry's cached modification // time is equal to or later than the index modification time. In // such cases the work file is too close to the index to tell if // it is clean or not based on the modification time alone. // final int base = infoOffset + P_MTIME; final int mtime = NB.decodeInt32(info, base); if (smudge_s < mtime) return true; if (smudge_s == mtime) return smudge_ns <= NB.decodeInt32(info, base + 4); return false; }

Target:
public final boolean mightBeRacilyClean(final int smudge_s, final int smudge_ns) { // If the index has a modification time then it came from disk // and was not generated from scratch in memory. In such cases // the entry is 'racily clean' if the entry's cached modification // time is equal to or later than the index modification time. In // such cases the work file is too close to the index to tell if // it is clean or not based on the modification time alone. // final int base = infoOffset + P_MTIME; final int mtime = NB.decodeInt32(info, base); if (smudge_s == mtime) return smudge_ns <= NB.decodeInt32(info, base + 4); return false; }
Source:
private int distanceUntilTurn() { final GeoPoint whereIam = whereIAm(); final int fromEnd; if (whereIam == null) { fromEnd = Integer.MAX_VALUE;} else { // Get distance to end of active segment final Segment activeSeg = Route.journey().activeSegment(); fromEnd = activeSeg.distanceFromEnd(whereIam); } return fromEnd; }

Target:
private Integer distanceUntilTurn() { final GeoPoint whereIam = whereIAm(); if (whereIam != null) { // Get distance to end of active segment final Segment activeSeg = Route.journey().activeSegment(); return activeSeg.distanceFromEnd(whereIam); } return null; }
Source:
public COL get() { // load upon the first use if (parsed==null) { synchronized (this) { if (parsed==null) { try { load(); } catch (IOException e) { throw new RuntimeException(e); } } } } return parsed; }

Target:
public COL get() { // load upon the first use if (parsed==null) { synchronized (this) { if (parsed==null) { load(); } } } return parsed; }
Source:
public Object poll() { Object value = queue.poll(); if (capacity != null) { capacity.incrementAndGet(); } return value; }

Target:
public Object poll() { Object value = queue.poll(); if (capacity != null && value != null) { capacity.incrementAndGet(); } return value; }
Source:
public PropertyValue getValue(ClassPropertyReference propertyReference, Object rawValue) throws XWikiRestException { String reference = ""; if (rawValue != null) { reference = rawValue.toString(); } if (StringUtils.isEmpty(reference)) { return null; } DocumentReference documentReference = documentReferenceResolver.resolve(reference, EntityType.DOCUMENT); PropertyValue propertyValue = this.getValueFromQueryResult(documentReference, getPropertyDefinition(propertyReference)); if (propertyValue != null) { propertyValue.setValue(reference); } return propertyValue; }

Target:
public PropertyValue getValue(ClassPropertyReference propertyReference, Object rawValue) throws XWikiRestException { String reference = ""; if (rawValue != null) { reference = rawValue.toString(); } if (StringUtils.isEmpty(reference)) { return null; } DocumentReference documentReference = documentReferenceResolver.resolve(reference, EntityType.DOCUMENT); PropertyValue propertyValue = super.getValue(propertyReference, documentReference); if (propertyValue != null) { propertyValue.setValue(reference); } return propertyValue; }
Source:
public void tearDown() throws Exception { super.tearDown(); lfuJedis.disconnect(); }

Target:
public void tearDown() throws Exception { lfuJedis.disconnect(); super.tearDown(); }
Source:
public static void configureSentry(ApplicationContext context) { FileSettings settings = context.getBean(FileSettings.class); String sentryDsn = ofNullable(settings.getString("sentry.dsn")).orElse("none"); if (!sentryDsn.equals("none")) { Sentry.init(sentryDsn); } }

Target:
public static void configureSentry(ApplicationContext context) { FileSettings settings = context.getBean(FileSettings.class); Sentry.init(settings.getString("sentry.dsn")); }
Source:
protected static void assertAttAuthzStatements(final Assertion assertion) throws WSSecurityException { if (CollectionUtils.isEmpty(assertion.getAttributeStatements()) && (assertion.getAuthnStatements() == null || assertion.getAuthnStatements().isEmpty())) { assertAuthzDecisionStatements(assertion); } }

Target:
protected static void assertAttAuthzStatements(final Assertion assertion) throws WSSecurityException { if (CollectionUtils.isEmpty(assertion.getAttributeStatements()) && CollectionUtils.isEmpty(assertion.getAuthnStatements())) { assertAuthzDecisionStatements(assertion); } }
Source:
private MavenProject getSiblingModule(Artifact artifact) { @SuppressWarnings("unchecked") List<MavenProject> modules = (List<MavenProject>)project.getParent().getModules(); for (MavenProject module : modules) { if (module.getId().equals(artifact.getId())) { return module; } } return null; }

Target:
private MavenProject getSiblingModule(Artifact artifact) { if (project.getParent() == null) { return null; } @SuppressWarnings("unchecked") List<MavenProject> modules = (List<MavenProject>)project.getParent().getModules(); for (MavenProject module : modules) { if (module.getId().equals(artifact.getId())) { return module; } } return null; }
Source:
public String getExpression() { // The escaped CSS content has to be escaped to be a valid Java literal return "\"" + Generator.escape(toCss()) + "\""; }

Target:
public String getExpression() { // The escaped CSS content has to be escaped to be a valid Java literal return "\"" + toCss() + "\""; }
Source:
protected void handleDemandLoadException(Resource resource, IOException exception) { try { super.handleDemandLoadException(resource, exception); // CHECKSTYLE:OFF } catch (Exception e) { // CHECKSTYLE:ON // do nothing. The errors are added to the Resource#getErrors() in super(). } }

Target:
protected void handleDemandLoadException(Resource resource, IOException exception) { try { super.handleDemandLoadException(resource, exception); // CHECKSTYLE:OFF } catch (RuntimeException e) { // CHECKSTYLE:ON // do nothing. The errors are added to the Resource#getErrors() in super(). } }
Source:
public static void sendResponse(ChannelHandlerContext channel, HttpRequest request, String messageBody, HttpResponseStatus status) { sendResponse(channel, request, messageBody, null); }

Target:
public static void sendResponse(ChannelHandlerContext channel, HttpRequest request, String messageBody, HttpResponseStatus status) { sendResponse(channel, request, messageBody, status, null); }
Source:
private LanguageMapping computeInheritedMapping(IProject project, IFile file, ICConfigurationDescription configuration) throws CoreException { LanguageMapping mappings[] = LanguageMappingResolver.computeLanguage(project, file.getProjectRelativePath().toPortableString(), configuration, fContentType.getId(), true); LanguageMapping inheritedMapping = mappings[0]; // Skip over the file mapping because we want to know what mapping the file // mapping overrides. int index = 1; while (inheritedMapping.inheritedFrom == LanguageMappingResolver.FILE_MAPPING) { inheritedMapping = mappings[index++]; } return inheritedMapping; }

Target:
private LanguageMapping computeInheritedMapping(IProject project, IFile file, ICConfigurationDescription configuration) throws CoreException { LanguageMapping mappings[] = LanguageMappingResolver.computeLanguage(project, file.getProjectRelativePath().toPortableString(), configuration, fContentType.getId(), true); // Skip over the file mapping because we want to know what mapping the file // mapping overrides. for (int i = 0; i < mappings.length; i++) { if (mappings[i].inheritedFrom != LanguageMappingResolver.FILE_MAPPING) { return mappings[i]; } } return null; }
Source:
public void registerCache(String name) { CacheDescriptor defaultDescriptor = getCacheDescriptor(DEFAULT_CACHE_ID); if (defaultDescriptor == null) { defaultDescriptor = new CacheDescriptor(); defaultDescriptor.options.put(CacheDescriptor.OPTION_MAX_SIZE, String.valueOf(CacheDescriptor.DEFAULT_MAX_SIZE)); register(XP_CACHES, defaultDescriptor); } CacheDescriptor newDescriptor = (CacheDescriptor) new CacheDescriptor().merge(defaultDescriptor); newDescriptor.name = name; // add to registry (merging if needed) register(XP_CACHES, newDescriptor); // start if needed maybeStart(name); }

Target:
public void registerCache(String name) { CacheDescriptor defaultDescriptor = getCacheDescriptor(DEFAULT_CACHE_ID); if (defaultDescriptor == null) { defaultDescriptor = new CacheDescriptor(); defaultDescriptor.options.put(OPTION_MAX_SIZE, String.valueOf(DEFAULT_MAX_SIZE)); register(XP_CACHES, defaultDescriptor); } CacheDescriptor newDescriptor = (CacheDescriptor) new CacheDescriptor().merge(defaultDescriptor); newDescriptor.name = name; // add to registry (merging if needed) register(XP_CACHES, newDescriptor); // start if needed maybeStart(name); }