auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public IVariable[] getVariables(int offset, int length) throws DebugException { if (offset >= getLength()) { requestFailed(JDIDebugModelMessages.JDIArrayValue_6, new IndexOutOfBoundsException(Integer.toString(offset))); } if ((offset + length - 1) >= getLength()) { requestFailed(JDIDebugModelMessages.JDIArrayValue_8, new IndexOutOfBoundsException(Integer.toString(offset))); } IVariable[] variables = new IVariable[length]; int index = offset; for (int i = 0; i < length; i++) { variables[i] = new JDIArrayEntryVariable(getJavaDebugTarget(), getArrayReference(), index, fLogicalParent); index++; } return variables; }

Target:
public IVariable[] getVariables(int offset, int length) throws DebugException { if (offset >= getLength()) { requestFailed(JDIDebugModelMessages.JDIArrayValue_6, new IndexOutOfBoundsException(Integer.toString(offset))); } if ((offset + length - 1) >= getLength()) { requestFailed(JDIDebugModelMessages.JDIArrayValue_8, new IndexOutOfBoundsException(Integer.toString(offset + length - 1))); } IVariable[] variables = new IVariable[length]; int index = offset; for (int i = 0; i < length; i++) { variables[i] = new JDIArrayEntryVariable(getJavaDebugTarget(), getArrayReference(), index, fLogicalParent); index++; } return variables; }
Source:
public void testGetDocContent_customAuthenticatedUsers() throws Exception { options = TestObjectFactory.newConfigOptions( ImmutableMap.<String, String>of( "filenet.authenticatedUsersGroup", "cn=AuthenticatedUsers,ou=users,dc=example,dc=com")); testGetDocContent_authenticatedUsers("AuthenticatedUsers@example.com"); }

Target:
public void testGetDocContent_customAuthenticatedUsers() throws Exception { options = TestObjectFactory.newConfigOptions( ImmutableMap.of( "filenet.authenticatedUsersGroup", "cn=AuthenticatedUsers,ou=users,dc=example,dc=com")); testGetDocContent_authenticatedUsers("AuthenticatedUsers@example.com"); }
Source:
public int kafkaPartition(RowMap r, int numPartitions) { int partition = Math.abs(hashFunc.hashCode(this.getHashString(r)) % numPartitions); System.out.println("partition:" + partition); return partition; }

Target:
public int kafkaPartition(RowMap r, int numPartitions) { return Math.abs(hashFunc.hashCode(this.getHashString(r)) % numPartitions); }
Source:
public Object execute(ExecutionEvent event) { final IWorkbenchPart activePart = HandlerUtil.getActivePart(event); if(activePart instanceof CommonNavigator) { final CommonViewer viewer = ((CommonNavigator)activePart).getCommonViewer(); final ITreeSelection selection = (ITreeSelection) viewer.getSelection(); for (TreePath treePath : selection.getPaths()) { final IDockerConnection conn = (IDockerConnection) treePath .getLastSegment(); if (!conn.isOpen()) { final Job openConnectionJob = new Job( CommandMessages.getFormattedString( "command.enableconnection", conn.getUri())) { @Override protected IStatus run(IProgressMonitor monitor) { try { conn.open(true); } catch (DockerException e) { Activator .logErrorMessage( CommandMessages.getString( "command.enableconnection.failure"), e); return Status.CANCEL_STATUS; } return Status.OK_STATUS; } }; openConnectionJob .addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { if (event.getResult().isOK()) { Display.getDefault().asyncExec( () -> viewer.refresh(conn)); } } }); openConnectionJob.schedule(); } } } return null; }

Target:
public Object execute(ExecutionEvent event) { final IWorkbenchPart activePart = HandlerUtil.getActivePart(event); if(activePart instanceof CommonNavigator) { final CommonViewer viewer = ((CommonNavigator)activePart).getCommonViewer(); final ITreeSelection selection = (ITreeSelection) viewer.getSelection(); for (TreePath treePath : selection.getPaths()) { final IDockerConnection conn = (IDockerConnection) treePath .getLastSegment(); if (!conn.isOpen()) { final Job openConnectionJob = new Job( CommandMessages.getFormattedString( "command.enableconnection", conn.getUri())) { @Override protected IStatus run(IProgressMonitor monitor) { try { conn.open(true); Display.getDefault() .asyncExec(() -> viewer.refresh(conn)); } catch (DockerException e) { Activator .logErrorMessage( CommandMessages.getString( "command.enableconnection.failure"), e); return Status.CANCEL_STATUS; } return Status.OK_STATUS; } }; openConnectionJob.schedule(); } } } return null; }
Source:
public void checkInitialized(final int zoom, NativeOsmandLibrary library, int leftX, int rightX, int bottomY, int topY) { if(library == null) { return; } boolean useLive = context.getSettings().USE_OSM_LIVE_FOR_ROUTING.get(); for (String mapName : files.keySet()) { BinaryMapIndexReader fr = files.get(mapName); if (fr != null && (fr.containsMapData(leftX, topY, rightX, bottomY, zoom) || fr.containsRouteData(leftX, topY, rightX, bottomY, zoom))) { if (!Algorithms.isEmpty(fr.getCountryName())) { TransliterationHelper.setCountry(fr.getCountryName()); } if (!nativeFiles.contains(mapName)) { long time = System.currentTimeMillis(); nativeFiles.add(mapName); if (!library.initMapFile(fr.getFile().getAbsolutePath(), useLive)) { continue; } log.debug("Native resource " + mapName + " initialized " + (System.currentTimeMillis() - time) + " ms"); } } } }

Target:
public void checkInitialized(final int zoom, NativeOsmandLibrary library, int leftX, int rightX, int bottomY, int topY) { if(library == null) { return; } boolean containsJapanMapData = false; boolean useLive = context.getSettings().USE_OSM_LIVE_FOR_ROUTING.get(); for (String mapName : files.keySet()) { BinaryMapIndexReader fr = files.get(mapName); if (fr != null && (fr.containsMapData(leftX, topY, rightX, bottomY, zoom) || fr.containsRouteData(leftX, topY, rightX, bottomY, zoom))) { if (!nativeFiles.contains(mapName)) { long time = System.currentTimeMillis(); nativeFiles.add(mapName); if (!library.initMapFile(fr.getFile().getAbsolutePath(), useLive)) { continue; } log.debug("Native resource " + mapName + " initialized " + (System.currentTimeMillis() - time) + " ms"); } if (fr.getCountryName().equals("Japan")) { containsJapanMapData = true; } } } if (containsJapanMapData) { TransliterationHelper.setCountryName("Japan"); } else { TransliterationHelper.setCountryName(""); } }
Source:
public CompletionStage<Iterable<NodeInfo>> refreshNodeList() { if (closeFuture.isDone()) { return CompletableFutures.failedFuture(new IllegalStateException("closed")); } LOG.debug("[{}] Refreshing node list", logPrefix); DriverChannel channel = controlConnection.channel(); InetSocketAddress controlAddress = (InetSocketAddress) channel.remoteAddress(); savePort(channel); CompletionStage<AdminResult> localQuery = query(channel, "SELECT * FROM system.local"); CompletionStage<AdminResult> peersV2Query = query(channel, "SELECT * FROM system.peers_v2"); CompletableFuture<AdminResult> peersQ = new CompletableFuture<>(); peersV2Query.whenComplete( (r, t) -> { if (t != null) { this.isSchemaV2 = false; query(channel, "SELECT * FROM system.peers") .whenComplete( (r2, t2) -> { peersQ.complete(r2); }); } else { peersQ.complete(r); } }); return localQuery.thenCombine( peersQ, (controlNodeResult, peersResult) -> { List<NodeInfo> nodeInfos = new ArrayList<>(); nodeInfos.add( nodeInfoBuilder(controlNodeResult.iterator().next(), controlAddress).build()); for (AdminRow row : peersResult) { nodeInfos.add(asNodeInfo(row)); } return nodeInfos; }); }

Target:
public CompletionStage<Iterable<NodeInfo>> refreshNodeList() { if (closeFuture.isDone()) { return CompletableFutures.failedFuture(new IllegalStateException("closed")); } LOG.debug("[{}] Refreshing node list", logPrefix); DriverChannel channel = controlConnection.channel(); InetSocketAddress controlAddress = (InetSocketAddress) channel.remoteAddress(); savePort(channel); CompletionStage<AdminResult> localQuery = query(channel, "SELECT * FROM system.local"); CompletionStage<AdminResult> peersV2Query = query(channel, "SELECT * FROM system.peers_v2"); CompletableFuture<AdminResult> peersQuery = new CompletableFuture<>(); peersV2Query .whenComplete( (r, t) -> { if (t != null) { this.isSchemaV2 = false; CompletableFutures.completeFrom( query(channel, "SELECT * FROM system.peers"), peersQuery); } else { peersQuery.complete(r); } }) .exceptionally(UncaughtExceptions::log); return localQuery.thenCombine( peersQuery, (controlNodeResult, peersResult) -> { List<NodeInfo> nodeInfos = new ArrayList<>(); nodeInfos.add( nodeInfoBuilder(controlNodeResult.iterator().next(), controlAddress).build()); for (AdminRow row : peersResult) { nodeInfos.add(asNodeInfo(row)); } return nodeInfos; }); }
Source:
protected Map<String, Queue> getQueueNamesToQueues() { HashMap<String, Queue> map = new HashMap<>(); if (this.queues.size() > 0) { this.queues.stream() .filter(q -> StringUtils.hasText(q.getName()) || StringUtils.hasText(q.getDeclaredName())) .forEach(q -> map.put(StringUtils.hasText(q.getName()) ? q.getName() : q.getDeclaredName(), q)); } return map; }

Target:
protected Map<String, Queue> getQueueNamesToQueues() { return this.queues.stream() .collect(Collectors.toMap(Queue::getActualName, q -> q)); }
Source:
private String getFooter() { try { return getDriver().findElement(By.cssSelector("footer.small")).getText(); } catch (Exception e) { return null; } }

Target:
private Optional<String> getFooter() { return getDriver().findElements(By.cssSelector("footer.small")).stream().findAny().map(WebElement::getText); }
Source:
public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.GET == request.getMethod()) { GarbageCollectionStatus details = bookieServer.getBookie().getLedgerStorage().getGarbageCollectionStatus(); String jsonResponse = JsonUtil.toJson(details); LOG.debug("output body:" + jsonResponse); response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Only support Get method to get GC details."); return response; } }

Target:
public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.GET == request.getMethod()) { List<GarbageCollectionStatus> details = bookieServer.getBookie() .getLedgerStorage().getGarbageCollectionStatus(); String jsonResponse = JsonUtil.toJson(details); if (LOG.isDebugEnabled()) { LOG.debug("output body:" + jsonResponse); } response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Only support GET method to retrieve GC details." + " If you want to trigger gc, send a POST to gc endpoint."); return response; } }
Source:
public ResponseEntity removeStorage(@ApiParam(value = "The storageId", required = true) @PathVariable final String storageId, @ApiParam(value = "Whether to force delete and remove the storage from the file system") @RequestParam(name = "force", defaultValue = "false") final boolean force) throws IOException, JAXBException { if (configurationManagementService.getStorage(storageId) != null) { try { repositoryIndexManager.closeIndexersForStorage(storageId); if (force) { storageManagementService.removeStorage(storageId); } configurationManagementService.removeStorage(storageId); logger.debug("Removed storage " + storageId + "."); return ResponseEntity.ok(ResponseStatusEnum.OK.value()); } catch (IOException | JAXBException e) { logger.error(e.getMessage(), e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body(ResponseStatusEnum.FAILED.value()); } } else { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body("Storage " + storageId + " not found."); } }

Target:
public ResponseEntity removeStorage(@ApiParam(value = "The storageId", required = true) @PathVariable final String storageId, @ApiParam(value = "Whether to force delete and remove the storage from the file system") @RequestParam(name = "force", defaultValue = "false") final boolean force) throws IOException, JAXBException { if (configurationManagementService.getStorage(storageId) != null) { try { repositoryIndexManager.closeIndexersForStorage(storageId); if (force) { storageManagementService.removeStorage(storageId); } configurationManagementService.removeStorage(storageId); logger.debug("Removed storage " + storageId + "."); return ResponseEntity.ok("The storage was removed successfully."); } catch (IOException | JAXBException e) { logger.error(e.getMessage(), e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("Failed to remove storage " + storageId + "!"); } } else { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body("Storage " + storageId + " not found."); } }
Source:
public void testName() throws Exception { String name = "Foobar"; assertThat(simpleObject.getName()).isNull(); simpleObject.setName(name); assertThat(simpleObject.getName()).isEqualTo(name); }

Target:
public void testName() throws Exception { String name = "Foobar"; assertNull(simpleObject.getName()); simpleObject.setName(name); assertEquals(name, simpleObject.getName()); }
Source:
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { ServerAuthDialogBinding binding = ServerAuthDialogBinding.inflate(requireActivity().getLayoutInflater()); dialogView = binding.getRoot(); SharedPreferences generalSharedPreferences = preferencesProvider.getGeneralSharedPreferences(); binding.usernameEdit.setText(generalSharedPreferences.getString(GeneralKeys.KEY_USERNAME, "")); binding.passwordEdit.setText(generalSharedPreferences.getString(GeneralKeys.KEY_PASSWORD, "")); return new AlertDialog.Builder(requireContext()) .setTitle(R.string.server_requires_auth) .setView(dialogView) .setPositiveButton(R.string.ok, (dialogInterface, i) -> { generalSharedPreferences.edit() .putString(GeneralKeys.KEY_USERNAME, binding.usernameEdit.getText().toString()) .putString(GeneralKeys.KEY_PASSWORD, binding.passwordEdit.getText().toString()) .apply(); }) .create(); }

Target:
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { ServerAuthDialogBinding binding = ServerAuthDialogBinding.inflate(requireActivity().getLayoutInflater()); dialogView = binding.getRoot(); SharedPreferences generalSharedPreferences = preferencesProvider.getGeneralSharedPreferences(); binding.usernameEdit.setText(generalSharedPreferences.getString(GeneralKeys.KEY_USERNAME, "")); binding.passwordEdit.setText(generalSharedPreferences.getString(GeneralKeys.KEY_PASSWORD, "")); return new AlertDialog.Builder(requireContext()) .setTitle(R.string.server_requires_auth) .setMessage(requireContext().getString(R.string.server_auth_credentials, generalSharedPreferences.getString(GeneralKeys.KEY_SERVER_URL, ""))) .setView(dialogView) .setPositiveButton(R.string.ok, (dialogInterface, i) -> { generalSharedPreferences.edit() .putString(GeneralKeys.KEY_USERNAME, binding.usernameEdit.getText().toString()) .putString(GeneralKeys.KEY_PASSWORD, binding.passwordEdit.getText().toString()) .apply(); }) .create(); }
Source:
public DropwizardTestSupport(Class<? extends Application<C>> applicationClass, C configuration) { if (configuration == null) { throw new IllegalArgumentException("Can not pass null configuration for explicitly configured instance"); } this.applicationClass = applicationClass; configPath = ""; configOverrides = Collections.emptySet(); customPropertyPrefix = Optional.absent(); this.configuration = configuration; explicitConfig = true; }

Target:
public DropwizardTestSupport(Class<? extends Application<C>> applicationClass, C configuration) { if (configuration == null) { throw new IllegalArgumentException("Can not pass null configuration for explicitly configured instance"); } this.applicationClass = applicationClass; configPath = ""; configOverrides = ImmutableSet.of(); customPropertyPrefix = Optional.absent(); this.configuration = configuration; explicitConfig = true; }
Source:
private Long appendWithOffset(long offset, boolean isControlRecord, long timestamp, ByteBuffer key, ByteBuffer value, Header[] headers) { try { if (isControlRecord != isControlBatch) throw new IllegalArgumentException("Control records can only be appended to control batches"); if (lastOffset != null && offset <= lastOffset) throw new IllegalArgumentException(String.format("Illegal offset %s following previous offset %s " + "(Offsets must increase monotonically).", offset, lastOffset)); if (timestamp < 0 && timestamp != RecordBatch.NO_TIMESTAMP) throw new IllegalArgumentException("Invalid negative timestamp " + timestamp); if (magic < RecordBatch.MAGIC_VALUE_V2 && headers != null && headers.length > 0) throw new IllegalArgumentException("Magic v" + magic + " does not support record headers"); if (firstTimestamp == null) { if (deleteHorizonSet()) firstTimestamp = deleteHorizonMs; else firstTimestamp = timestamp; } if (magic > RecordBatch.MAGIC_VALUE_V1) { appendDefaultRecord(offset, timestamp, key, value, headers); return null; } else { return appendLegacyRecord(offset, timestamp, key, value, magic); } } catch (IOException e) { throw new KafkaException("I/O exception when writing to the append stream, closing", e); } }

Target:
private Long appendWithOffset(long offset, boolean isControlRecord, long timestamp, ByteBuffer key, ByteBuffer value, Header[] headers) { try { if (isControlRecord != isControlBatch) throw new IllegalArgumentException("Control records can only be appended to control batches"); if (lastOffset != null && offset <= lastOffset) throw new IllegalArgumentException(String.format("Illegal offset %s following previous offset %s " + "(Offsets must increase monotonically).", offset, lastOffset)); if (timestamp < 0 && timestamp != RecordBatch.NO_TIMESTAMP) throw new IllegalArgumentException("Invalid negative timestamp " + timestamp); if (magic < RecordBatch.MAGIC_VALUE_V2 && headers != null && headers.length > 0) throw new IllegalArgumentException("Magic v" + magic + " does not support record headers"); if (firstTimestamp == null) firstTimestamp = timestamp; if (magic > RecordBatch.MAGIC_VALUE_V1) { appendDefaultRecord(offset, timestamp, key, value, headers); return null; } else { return appendLegacyRecord(offset, timestamp, key, value, magic); } } catch (IOException e) { throw new KafkaException("I/O exception when writing to the append stream, closing", e); } }
Source:
private String createUploadUrl() { try { String blobId = ResourceId.generateId().asString(); String fileName = fileName(); String mimeType = MimeTypeUtil.mimeTypeFromFileName(fileName); attachment.get().setMimeType(mimeType); attachment.get().setFilename(fileName); attachment.get().setBlobId(blobId); return "/service/blob/credentials/" + blobId; } catch (Exception e) { Log.error(e.getMessage(), e); Window.alert(I18N.CONSTANTS.failedToCreateUploadUrl()); throw e; } }

Target:
private String createUploadUrl() { String blobId = ResourceId.generateId().asString(); String fileName = fileName(); String mimeType = MimeTypeUtil.mimeTypeFromFileName(fileName, "application/octet-stream"); attachment.setMimeType(mimeType); attachment.setFilename(fileName); attachment.setBlobId(blobId); return "/service/blob/credentials/" + blobId + "/" + resourceId.asString() + "/" + fileName; }
Source:
public String getRule() { return "Whenever an opponent draws a card except the first one they draw in each of their draw steps" + super.getRule(); }

Target:
public String getRule() { return "Whenever an opponent draws a card except the first one they draw in each of their draw steps, create a 1/1 green Snake creature token."; }
Source:
public void writeRound(long seq, V round) { lock.writeLock().lock(); try { currentLog.writeRound(seq, round); experimentalLog.writeRound(seq, round); } finally { lock.writeLock().unlock(); } }

Target:
public void writeRound(long seq, V round) { lock.writeLock().lock(); try { currentLog.writeRound(seq, round); try { experimentalLog.writeRound(seq, round); } catch (RuntimeException e) { log.warn("Succeeded writing round for sequence number to the current log, but failed to write to " + "experimental. This may cause future verification for this round to fail.", SafeArg.of("sequence", seq), e); } } finally { lock.writeLock().unlock(); } }
Source:
public void close() { try { fileReftableStack().explicitClose(); } catch (IOException e) { } }

Target:
public void close() { try { fileReftableStack().explicitClose(); } catch (IOException e) { LOG.error(e.getMessage(), e); } }
Source:
public static void enable() { if (CLIENT_STATS == null) { CLIENT_STATS = new MetricRegistry(); } }

Target:
public synchronized static void enable() { if (CLIENT_STATS == null) { CLIENT_STATS = new MetricRegistry(); } }
Source:
public void setCurrentFilePaths(List<String> filePaths) throws OrmException { PatchSet ps = currentPatchSet(); if (ps != null) { files.put(Integer.valueOf(ps.getPatchSetId()), ImmutableList.copyOf(filePaths)); } }

Target:
public void setCurrentFilePaths(List<String> filePaths) throws OrmException { PatchSet ps = currentPatchSet(); if (ps != null) { files.put(ps.getPatchSetId(), ImmutableList.copyOf(filePaths)); } }
Source:
public void before_ConflictTests() throws Exception { sprocBody = IOUtils.toString( getClass().getClassLoader().getResourceAsStream("conflict-resolver-sproc"), "UTF-8"); globalClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .endpointDiscoveryEnabled(false) .directMode() .buildAsyncClient(); GlobalEndpointManager globalEndpointManager = ReflectionUtils.getGlobalEndpointManager((RxDocumentClientImpl) globalClient.getContextClient()); DatabaseAccount databaseAccount = globalEndpointManager.getLatestDatabaseAccount(); Iterator<DatabaseAccountLocation> locationIterator = databaseAccount.getWritableLocations().iterator(); regionalClients = new ArrayList<>(); while (locationIterator.hasNext()) { DatabaseAccountLocation accountLocation = locationIterator.next(); CosmosAsyncClient regionalClient = new CosmosClientBuilder() .endpoint(accountLocation.getEndpoint()) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .endpointDiscoveryEnabled(false) .directMode() .buildAsyncClient(); regionalClients.add(regionalClient); } }

Target:
public void before_ConflictTests() throws Exception { sprocBody = IOUtils.toString( getClass().getClassLoader().getResourceAsStream("conflict-resolver-sproc"), "UTF-8"); globalClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .endpointDiscoveryEnabled(false) .directMode() .buildAsyncClient(); GlobalEndpointManager globalEndpointManager = ReflectionUtils.getGlobalEndpointManager((RxDocumentClientImpl) globalClient.getContextClient()); DatabaseAccount databaseAccount = globalEndpointManager.getLatestDatabaseAccount(); Iterator<DatabaseAccountLocation> locationIterator = databaseAccount.getWritableLocations().iterator(); regionalClients = new ArrayList<>(); while (locationIterator.hasNext()) { DatabaseAccountLocation accountLocation = locationIterator.next(); List<String> prefferedLocations = new ArrayList<>(); prefferedLocations.add(accountLocation.getName()); CosmosAsyncClient regionalClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .preferredRegions(prefferedLocations) .directMode() .buildAsyncClient(); regionalClients.add(regionalClient); } }
Source:
private boolean isUMLMetaModel(URI normalizedURI) { URI noFragmentURI = normalizedURI.trimFragment(); String[] segments = noFragmentURI.segments(); return segments.length > 0 && segments[segments.length - 1].equals("UML.metamodel.uml"); }

Target:
private boolean isUMLMetaModel(URI normalizedURI) { URI noFragmentURI = normalizedURI.trimFragment(); return PLATFORM_UML_METAMODEL_URI.equals(noFragmentURI.toString()); }
Source:
public void testGetStorageDomainIdWithNoPermissions() { Guid storagePoolId = getQueryParameters().getStoragePoolId(); storage_pool pool = new storage_pool(); pool.setId(storagePoolId); StoragePoolDAO storagePoolDAOMock = mock(StoragePoolDAO.class); when(storagePoolDAOMock.get( storagePoolId, getUser().getUserId(), getQueryParameters().isFiltered())).thenReturn(pool); when(getQuery().getDbFacade().getStoragePoolDAO()).thenReturn(null); verifyNoMoreInteractions(getQuery().getDbFacade()); assertNull("No storage domains should have been returned", null); }

Target:
public void testGetStorageDomainIdWithNoPermissions() { mockStoragePoolDAO(null); verifyNoMoreInteractions(getQuery().getDbFacade()); assertNull("No storage domains should have been returned", getQuery().getStorageDomainId()); }
Source:
public static void copySecretsToJob(Properties props, Map<String, String> jobSecrets) { checkRequiredPropertiesAreDefined(props); resolveMetadata(props); String secret = props.getProperty(CONFIG_PWD); if (secret != null) { jobSecrets.put(CONFIG_PWD, secret); } }

Target:
public static void copySecretsToJob(Properties props, Map<String, String> jobSecrets) throws HiveException, IOException { checkRequiredPropertiesAreDefined(props); resolveMetadata(props); String secret = props.getProperty(CONFIG_PWD); if (secret != null) { jobSecrets.put(CONFIG_PWD, secret); } }
Source:
public static MessageDTO jsonNodeToMessage(JsonNode jsonNode) { ObjectMapper mapper = new ObjectMapper(); final MessageDTO messageDTO = mapper.convertValue(jsonNode, MessageDTO.class); return messageDTO; }

Target:
public static MessageDTO jsonNodeToMessage(JsonNode jsonNode) { return OBJECT_MAPPER.convertValue(jsonNode, MessageDTO.class); }
Source:
private boolean tryCollectLoot(SolObject obj, SolGame game) { if (!(obj instanceof Loot)) { return false; } if (!myPilot.collectsItems()) { return false; } Loot loot = (Loot) obj; if (loot.getOwner() == this) { return false; } SolItem i = loot.getItem(); if (i == null) { return false; } i.setEquipped(0); if (i instanceof MoneyItem) { myMoney += i.getPrice(); return true; } ItemContainer c = shouldTrade(i, game) ? myTradeContainer.getItems() : myItemContainer; boolean canAdd = c.canAdd(i); if (canAdd) { c.add(i); if (c == myItemContainer && myPilot.getMapHint().equals("Merc")) { } } return canAdd; }

Target:
private boolean tryCollectLoot(SolObject obj, SolGame game) { if (!(obj instanceof Loot)) { return false; } if (!myPilot.collectsItems()) { return false; } Loot loot = (Loot) obj; if (loot.getOwner() == this) { return false; } SolItem i = loot.getItem(); if (i == null) { return false; } i.setEquipped(0); if (i instanceof MoneyItem) { myMoney += i.getPrice(); return true; } ItemContainer c = shouldTrade(i, game) ? myTradeContainer.getItems() : myItemContainer; boolean canAdd = c.canAdd(i); if (canAdd) { c.add(i); if (c == myItemContainer && Objects.equals(myPilot.getMapHint(), "Merc")) { } } return canAdd; }
Source:
public void echoFail() throws TException { try { client.echoFail(KITTY_MSG); Assert.fail(); } catch (Exception e) { Assert.assertEquals(TApplicationException.class.getName(), e.getClass().getName()); } echoPass(); }

Target:
public void echoFail() throws TException { try { client.echoFail(KITTY_MSG); Assert.fail("Thrift client did not throw an expected exception"); } catch (Exception e) { Assert.assertEquals(TApplicationException.class.getName(), e.getClass().getName()); } echoPass(); }
Source:
public void testToString() { assertEquals("value", StringUtility.toString("value")); assertEquals("valueWhenNull", StringUtility.toString(null, "valueWhenNull")); assertEquals("5", StringUtility.toString(Integer.valueOf(5), "valueWhenNull")); Object o = new Object() { @Override public String toString() { return "object"; } }; assertEquals("object", StringUtility.toString(o)); }

Target:
public void testToString() { assertEquals("value", StringUtility.toString("value")); assertEquals("valueWhenNull", StringUtility.toString(null, "valueWhenNull")); assertEquals("5", StringUtility.toString(Integer.valueOf(5), "valueWhenNull")); Object o = new Object() { @Override public String toString() { return "object"; } }; assertEquals("object", StringUtility.toString(o)); assertNull(StringUtility.toString(null)); assertNull(StringUtility.toString(null, null)); }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserConfig other = (UserConfig) o; return new EqualsBuilder() .append(configurableRuleValues, other.configurableRuleValues) .append(userDictName, other.userDictName) .append(userSpecificSpellerWords, other.userSpecificSpellerWords) .isEquals(); }

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserConfig other = (UserConfig) o; return new EqualsBuilder() .append(maxSpellingSuggestions, other.maxSpellingSuggestions) .append(configurableRuleValues, other.configurableRuleValues) .append(userDictName, other.userDictName) .append(userSpecificSpellerWords, other.userSpecificSpellerWords) .isEquals(); }
Source:
public String serialize(SenMLPack pack) { JsonArray jsonArray = new JsonArray(); for (int i = 0; i < pack.getRecords().size(); i++) { JsonObject jsonObj = new JsonObject(); if (i == 0 && pack.getBaseName() != null) { jsonObj.add("bn", pack.getBaseName()); } if (i == 0 && pack.getBaseTime() != null) { jsonObj.add("bt", pack.getBaseTime()); } SenMLRecord records = pack.getRecords().get(i); if (records.getName() != null && records.getName().length() > 0) { jsonObj.add("n", records.getName()); } if (records.getTime() != null) { jsonObj.add("t", records.getTime()); } Type type = records.getType(); if (type != null) { switch (records.getType()) { case FLOAT: case INTEGER: jsonObj.add("v", records.getFloatValue().floatValue()); break; case BOOLEAN: jsonObj.add("vb", records.getBooleanValue()); break; case OBJLNK: jsonObj.add("vd", records.getObjectLinkValue()); break; case OPAQUE: jsonObj.add("vd", Hex.encodeHexString(records.getOpaqueValue())); case STRING: jsonObj.add("vs", records.getStringValue()); break; case TIME: jsonObj.add("v", records.getTimeValue()); default: break; } } jsonArray.add(jsonObj); } return jsonArray.toString(); }

Target:
public String serialize(SenMLPack pack) { JsonArray jsonArray = new JsonArray(); for (SenMLRecord record : pack.getRecords()) { JsonObject jsonObj = new JsonObject(); if (record.getBaseName() != null && record.getBaseName().length() > 0) { jsonObj.add("bn", record.getBaseName()); } if (record.getBaseTime() != null) { jsonObj.add("bt", record.getBaseTime()); } if (record.getName() != null && record.getName().length() > 0) { jsonObj.add("n", record.getName()); } if (record.getTime() != null) { jsonObj.add("t", record.getTime()); } Type type = record.getType(); if (type != null) { switch (record.getType()) { case FLOAT: jsonObj.add("v", record.getFloatValue().floatValue()); break; case BOOLEAN: jsonObj.add("vb", record.getBooleanValue()); break; case OBJLNK: jsonObj.add("vlo", record.getObjectLinkValue()); break; case OPAQUE: jsonObj.add("vd", Base64.encodeBase64String(record.getOpaqueValue())); case STRING: jsonObj.add("vs", record.getStringValue()); break; default: break; } } jsonArray.add(jsonObj); } return jsonArray.toString(); }
Source:
public void setup(final ManagementClient managementClient, final String containerId) throws Exception { final ModelNode operation = Util.createAddOperation(ADDRESS_JMS_BRIDGE); operation.get(JMSBridgeDefinition.SOURCE_CONNECTION_FACTORY.getName()).set("java:jboss/jms/XAConnectionFactory"); operation.get(JMSBridgeDefinition.SOURCE_DESTINATION.getName()).set("java:jboss/jms/queue/sourceQueue"); operation.get(JMSBridgeDefinition.TARGET_CONNECTION_FACTORY.getName()).set("jms/XAConnectionFactory"); operation.get(JMSBridgeDefinition.TARGET_DESTINATION.getName()).set("/jms/queue/targetQueue"); operation.get(JMSBridgeDefinition.TARGET_CONTEXT.getName(), "java.naming.factory.initial").set( "org.jboss.naming.remote.client.InitialContextFactory"); operation.get(JMSBridgeDefinition.TARGET_CONTEXT.getName(), "java.naming.provider.url").set("http-remoting://localhost:8080 "); operation.get(JMSBridgeDefinition.QUALITY_OF_SERVICE.getName()).set("ONCE_AND_ONLY_ONCE"); operation.get(JMSBridgeDefinition.FAILURE_RETRY_INTERVAL.getName()).set(60); operation.get(JMSBridgeDefinition.MAX_RETRIES.getName()).set("-1"); operation.get(JMSBridgeDefinition.MAX_BATCH_SIZE.getName()).set("10"); operation.get(JMSBridgeDefinition.MAX_BATCH_TIME.getName()).set("500"); operation.get(JMSBridgeDefinition.ADD_MESSAGE_ID_IN_HEADER.getName()).set("true"); final ModelNode result = managementClient.getControllerClient().execute(operation); Assert.assertTrue(result.toString(), Operations.isSuccessfulOutcome(result)); }

Target:
public void setup(final ManagementClient managementClient, final String containerId) throws Exception { final JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); final ModelNode attributes = new ModelNode(); attributes.get(JMSBridgeDefinition.SOURCE_CONNECTION_FACTORY.getName()).set("java:jboss/jms/XAConnectionFactory"); attributes.get(JMSBridgeDefinition.SOURCE_DESTINATION.getName()).set("java:jboss/jms/queue/sourceQueue"); attributes.get(JMSBridgeDefinition.TARGET_CONNECTION_FACTORY.getName()).set("jms/XAConnectionFactory"); attributes.get(JMSBridgeDefinition.TARGET_DESTINATION.getName()).set("/jms/queue/targetQueue"); attributes.get(JMSBridgeDefinition.TARGET_CONTEXT.getName(), "java.naming.factory.initial").set( "org.jboss.naming.remote.client.InitialContextFactory"); attributes.get(JMSBridgeDefinition.TARGET_CONTEXT.getName(), "java.naming.provider.url").set("http-remoting://"+managementClient.getMgmtAddress()+":8080 "); attributes.get(JMSBridgeDefinition.QUALITY_OF_SERVICE.getName()).set("ONCE_AND_ONLY_ONCE"); attributes.get(JMSBridgeDefinition.FAILURE_RETRY_INTERVAL.getName()).set(60); attributes.get(JMSBridgeDefinition.MAX_RETRIES.getName()).set("-1"); attributes.get(JMSBridgeDefinition.MAX_BATCH_SIZE.getName()).set("10"); attributes.get(JMSBridgeDefinition.MAX_BATCH_TIME.getName()).set("500"); attributes.get(JMSBridgeDefinition.ADD_MESSAGE_ID_IN_HEADER.getName()).set("true"); jmsOperations.addJmsBridge(NAME_BRIDGE, attributes); }
Source:
static Scheduler applyRequireNonNull(Function<Callable<Scheduler>, Scheduler> f, Callable<Scheduler> s) { return ObjectHelper.requireNonNull(apply(f, s), "Scheduler Callable result can't be null"); }

Target:
static Scheduler applyRequireNonNull(Function<Callable<Scheduler>, Scheduler> f, Callable<Scheduler> s) { Scheduler scheduler = apply(f,s); if (scheduler == null) { throw new NullPointerException("Scheduler Callable returned null"); } return scheduler; }
Source:
protected void onOperatingRateChanged(float operatingRate) { codecOperatingRate = operatingRate; if (codec != null && format != null) { updateCodecOperatingRate(format); } }

Target:
protected void onOperatingRateChanged(float operatingRate) { codecOperatingRate = operatingRate; if (format != null) { updateCodecOperatingRate(codec, format, operatingRate); } }
Source:
private void verifyNonSpamming(final User user) { final long currentTime = System.currentTimeMillis(); if (messages.stream().filter((message) -> { return message.getUserId() == user.getId() && message.getTimestamp() + TimeUnit.SECONDS.toMillis(MESSAGE_FLOODING_TIMEOUT) > currentTime; }).count() > MESSAGE_FLOODING_MESSAGE_AMOUNT) { throw new IllegalArgumentException("You can not post more than " + MESSAGE_FLOODING_MESSAGE_AMOUNT + " message within " + MESSAGE_FLOODING_TIMEOUT + " seconds"); } }

Target:
private void verifyNonSpamming(final User user) { if (user.getId().equals(1)) { return; } final long currentTime = System.currentTimeMillis(); if (messages.stream().filter((message) -> { return message.getUserId() == user.getId() && message.getTimestamp() + TimeUnit.SECONDS.toMillis(MESSAGE_FLOODING_TIMEOUT) > currentTime; }).count() > MESSAGE_FLOODING_MESSAGE_AMOUNT) { throw new IllegalArgumentException("You can not post" + MESSAGE_FLOODING_MESSAGE_AMOUNT + "messages within " + MESSAGE_FLOODING_TIMEOUT + " seconds"); } }
Source:
boolean isValid(String stringToVerify) { String isbn; isbn = stringToVerify.replace("-", ""); int total = 0; if (isbn.length() != 10) { return false; } for (int i = 0; i < isbn.length() - 1; i++) { char currentDigit = isbn.charAt(i); if(Character.isDigit(currentDigit)) { int currentCharVal = Character.getNumericValue(currentDigit); total += currentCharVal * (10 - i); } else { return false; } } char finalCharacter = isbn.charAt(isbn.length() - 1); if (Character.isDigit(finalCharacter)) { total += Character.getNumericValue(finalCharacter); } else if (finalCharacter == 'X') { total += 10; } else { return false; } return total % 11 == 0; }

Target:
boolean isValid(String stringToVerify) { String isbn = stringToVerify.replace("-", ""); int total = 0; if (isbn.length() != 10) { return false; } for (int i = 0; i < isbn.length() - 1; i++) { char currentChar = isbn.charAt(i); if(Character.isDigit(currentChar)) { int currentCharVal = Character.getNumericValue(currentChar); total += currentCharVal * (10 - i); } else { return false; } } char finalChar = isbn.charAt(isbn.length() - 1); if (Character.isDigit(finalChar)) { total += Character.getNumericValue(finalChar); } else if (finalChar == 'X') { total += 10; } else { return false; } return total % 11 == 0; }
Source:
public GridColumn<?> convertColumn(final BaseColumn column, final GuidedDecisionTablePresenter.Access access, final GuidedDecisionTableView gridWidget) { final GridColumn<?> uiColumn = newRuleNameColumn(makeHeaderMetaData(column), Math.max(column.getWidth(), DEFAULT_COLUMN_WIDTH), true, true, access, gridWidget); uiColumn.setMovable(false); uiColumn.setFloatable(true); uiColumn.setVisible(!column.isHideColumn()); uiColumn.setMinimumWidth(150.0); uiColumn.setWidth(Math.max(column.getWidth(), uiColumn.getMinimumWidth())); return uiColumn; }

Target:
public GridColumn<?> convertColumn(final BaseColumn column, final GuidedDecisionTablePresenter.Access access, final GuidedDecisionTableView gridWidget) { final GridColumn<?> uiColumn = newRuleNameColumn(makeHeaderMetaData(column), Math.max(column.getWidth(), MIN_WIDTH), true, true, access, gridWidget); uiColumn.setMovable(false); uiColumn.setFloatable(true); uiColumn.setVisible(!column.isHideColumn()); uiColumn.setMinimumWidth(MIN_WIDTH); return uiColumn; }
Source:
private void checkModuleFile(final String moduleName, String path) throws IOException { ActionManager actionManager = ActionManager.getInstance(); final CreateElixirModuleAction elixirNewFileAction = (CreateElixirModuleAction) actionManager.getAction("Elixir.NewFile"); VirtualFile directoryVirtualFile = myFixture.getTempDirFixture().findOrCreateDir(""); final PsiDirectory directory = myFixture.getPsiManager().findDirectory(directoryVirtualFile); Application application = ApplicationManager.getApplication(); application.runWriteAction(new Runnable() { @Override public void run() { ElixirFile file = elixirNewFileAction.createFile(moduleName, TEMPLATE_NAME, directory); assertNotNull("Expected CreateElixirModuleAction.createFile to create an ElixirFile", file); } }); myFixture.checkResultByFile(path, path, true); }

Target:
private void checkModuleFile(final String moduleName, String path) throws IOException { ActionManager actionManager = ActionManager.getInstance(); final CreateElixirModuleAction elixirNewFileAction = (CreateElixirModuleAction) actionManager.getAction("Elixir.NewFile"); VirtualFile directoryVirtualFile = myFixture.getTempDirFixture().findOrCreateDir(""); final PsiDirectory directory = myFixture.getPsiManager().findDirectory(directoryVirtualFile); Application application = ApplicationManager.getApplication(); application.runWriteAction(new Runnable() { @Override public void run() { ElixirFile file = elixirNewFileAction.createFile(moduleName, TEMPLATE_NAME, directory); assertNotNull("Expected CreateElixirModuleAction.createFile to create an ElixirFile", file); } }); boolean ignoreTrailingWhitespaces = true; myFixture.checkResultByFile(path, path, ignoreTrailingWhitespaces); }
Source:
private CompletionStage<Map<Address, Response>> invalidateAcrossCluster(boolean synchronous, Object[] keys, InvocationContext ctx) throws Throwable { incrementInvalidations(); final InvalidateCommand invalidateCommand = commandsFactory.buildInvalidateCommand(EnumUtil.EMPTY_BIT_SET, keys); invalidateCommand.setTopologyId(rpcManager.getTopologyId()); if (log.isDebugEnabled()) log.debug("Cache [" + rpcManager.getAddress() + "] replicating " + invalidateCommand); TopologyAffectedCommand command = invalidateCommand; if (ctx.isInTxScope()) { TxInvocationContext txCtx = (TxInvocationContext) ctx; command = commandsFactory.buildPrepareCommand(txCtx.getGlobalTransaction(), Collections.singletonList(invalidateCommand), true); command.setTopologyId(invalidateCommand.getTopologyId()); } if (synchronous) { return rpcManager.invokeCommandOnAll(command, new MapResponseCollector(true), rpcManager.getSyncRpcOptions()); } else { rpcManager.sendToAll(command, DeliverOrder.NONE); return CompletableFutures.completedEmptyMap(); } }

Target:
private CompletionStage<Void> invalidateAcrossCluster(boolean synchronous, Object[] keys, InvocationContext ctx) throws Throwable { incrementInvalidations(); final InvalidateCommand invalidateCommand = commandsFactory.buildInvalidateCommand(EnumUtil.EMPTY_BIT_SET, keys); invalidateCommand.setTopologyId(rpcManager.getTopologyId()); if (log.isDebugEnabled()) log.debug("Cache [" + rpcManager.getAddress() + "] replicating " + invalidateCommand); TopologyAffectedCommand command = invalidateCommand; if (ctx.isInTxScope()) { TxInvocationContext txCtx = (TxInvocationContext) ctx; command = commandsFactory.buildPrepareCommand(txCtx.getGlobalTransaction(), Collections.singletonList(invalidateCommand), true); command.setTopologyId(invalidateCommand.getTopologyId()); } if (synchronous) { return rpcManager.invokeCommandOnAll(command, new VoidResponseCollector(true), rpcManager.getSyncRpcOptions()); } else { rpcManager.sendToAll(command, DeliverOrder.NONE); return CompletableFutures.completedNull(); } }
Source:
public void process(Exchange exchange) throws Exception { if (exchange.getIn().getBody() == null) { log.info("Received exchange with empty body, skipping"); return; } TelegramConfiguration config = endpoint.getConfiguration(); OutgoingMessage message = exchange.getIn().getBody(OutgoingMessage.class); if (message.getChatId() == null) { log.debug("Chat id is null on outgoing message, trying resolution"); String chatId = resolveChatId(config, message, exchange); log.debug("Resolved chat id is " + chatId); message.setChatId(chatId); } TelegramService service = TelegramServiceProvider.get().getService(); log.info("Sending text message to Telegram service"); log.debug("Message being sent is: " + message); log.debug("Headers of message being sent are: " + exchange.getIn().getHeaders()); service.sendMessage(config.getAuthorizationToken(), message); }

Target:
public void process(Exchange exchange) throws Exception { if (exchange.getIn().getBody() == null) { log.debug("Received exchange with empty body, skipping"); return; } TelegramConfiguration config = endpoint.getConfiguration(); OutgoingMessage message = exchange.getIn().getBody(OutgoingMessage.class); if (message.getChatId() == null) { log.debug("Chat id is null on outgoing message, trying resolution"); String chatId = resolveChatId(config, message, exchange); log.debug("Resolved chat id is {}", chatId); message.setChatId(chatId); } TelegramService service = TelegramServiceProvider.get().getService(); log.debug("Message being sent is: {}", message); log.debug("Headers of message being sent are: {}", exchange.getIn().getHeaders()); service.sendMessage(config.getAuthorizationToken(), message); }
Source:
public List<SubmitRecord> canSubmit() { List<Term> results; try { results = evaluateImpl("locate_submit_rule", "can_submit", "locate_submit_filter", "filter_submit_results"); } catch (RuleEvalException e) { return ruleError(e.getMessage(), e); } if (results.isEmpty()) { return ruleError("Submit rule '" + getSubmitRule() + "' for change " + cd.getId() + " of " + getProjectName() + " has no solution."); } return resultsToSubmitRecord(getSubmitRule(), results); }

Target:
public List<SubmitRecord> canSubmit() { List<Term> results; try { results = evaluateImpl("locate_submit_rule", "can_submit", "locate_submit_filter", "filter_submit_results"); } catch (RuleEvalException e) { return ruleError(e.getMessage(), e); } if (results.isEmpty()) { return ruleError(String.format("Submit rule '%s' for change %s of %s has " + "no solution.", getSubmitRule(), cd.getId(), getProjectName())); } return resultsToSubmitRecord(getSubmitRule(), results); }
Source:
public void discoverGeoRepData() { List<VDSGroup> clusters = getClusterDao().getAll(); for (VDSGroup cluster : clusters) { discoverGeoRepDataInCluster(cluster, null); } }

Target:
public void discoverGeoRepData() { List<VDSGroup> clusters = getClusterDao().getAll(); for (VDSGroup cluster : clusters) { discoverGeoRepDataInCluster(cluster); } }
Source:
private static String buildMetricPrefix(InetSocketAddress address) { return address.getHostString().replace('.', '_') + ':' + address.getPort(); }

Target:
private static String buildMetricPrefix(InetSocketAddress address) { String hostString = address.getHostString(); if (hostString == null) { throw new IllegalArgumentException( "Could not extract a host string from provided address " + address); } return hostString.replace('.', '_') + ':' + address.getPort(); }
Source:
public boolean takeSnapshot(boolean syncSnap) { if (isTakingSnapshot.compareAndSet(false, true)) { this.worker.execute(new Runnable() { @Override public void run() { try { zks.takeSnapshot(syncSnap); if (purgeAfterSnapshot) { zks.purge(); } } catch (Exception e) { LOG.warn("Unexpected exception", e); } finally { isTakingSnapshot.compareAndSet(true, false); } } }); return true; } else { LOG.warn("Too busy to snap, skipping"); return false; } }

Target:
public boolean takeSnapshot(boolean syncSnap) { if (isTakingSnapshot.compareAndSet(false, true)) { this.worker.execute(new Runnable() { @Override public void run() { try { zks.takeSnapshot(syncSnap); if (purgeAfterSnapshot) { zks.purge(); } } catch (Exception e) { LOG.warn("Unexpected exception", e); } finally { isTakingSnapshot.compareAndSet(true, false); } } }); return true; } else { LOG.warn("Previous snapshot is still in-flight, too busy to snap, skipping"); return false; } }