auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Set<InternetAddress> convertRecipientString(String recipientList, EnvVars envVars, int type) throws AddressException, UnsupportedEncodingException { final Set<InternetAddress> internetAddresses = new LinkedHashSet<>(); if (!StringUtils.isBlank(recipientList)) { final String expandedRecipientList = fixupDelimiters(envVars.expand(recipientList)); InternetAddress[] all = InternetAddress.parse(expandedRecipientList.replace("bcc:", "").replace("cc:", "")); String[] recipients = StringUtils.stripAll(expandedRecipientList.split(",")); if (recipients.length != all.length) { throw new IllegalArgumentException("Unsupported format in expanded recipient list string: " + expandedRecipientList); } final Set<InternetAddress> to = new LinkedHashSet<>(); final Set<InternetAddress> cc = new LinkedHashSet<>(); final Set<InternetAddress> bcc = new LinkedHashSet<>(); final String defaultSuffix = ExtendedEmailPublisher.descriptor().getDefaultSuffix(); for (int i = 0; i < recipients.length; i++) { String recipient = recipients[i]; InternetAddress address = all[i]; if (recipient.startsWith("bcc:")) { bcc.add(address); } else if (recipient.startsWith("cc:")) { cc.add(address); } else { to.add(address); } } if(type == BCC) { internetAddresses.addAll(bcc); } else if(type == CC) { internetAddresses.addAll(cc); } else { internetAddresses.addAll(to); } for(InternetAddress address : internetAddresses) { if(!address.getAddress().contains("@")) { User u = User.get(address.getAddress(), false, null); String userEmail; if(u != null) { userEmail = getUserConfiguredEmail(u); if(userEmail != null){ address.setAddress(userEmail); } } } if(!address.getAddress().contains("@") && defaultSuffix != null && defaultSuffix.contains("@")) { address.setAddress(address.getAddress() + defaultSuffix); } if(address.getPersonal() != null) { address.setPersonal(address.getPersonal(), ExtendedEmailPublisher.descriptor().getCharset()); } } } return internetAddresses; }

Target:
public static Set<InternetAddress> convertRecipientString(String recipientList, EnvVars envVars, int type) throws AddressException, UnsupportedEncodingException { return convertRecipientString(recipientList, envVars, type, null); }
Source:
public FieldInjector(ContainerImpl container, Field field, String name) throws MissingDependencyException { this.field = field; if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) && !field.isAccessible()) { SecurityManager sm = System.getSecurityManager(); try { if (sm != null) { sm.checkPermission(new ReflectPermission("suppressAccessChecks")); } field.setAccessible(true); } catch (AccessControlException e) { throw new DependencyException("Security manager in use, could not access field: " + field.getDeclaringClass().getName() + "(" + field.getName() + ")", e); } } Key<?> key = Key.newInstance(field.getType(), name); factory = container.getFactory(key); if (factory == null) { throw new MissingDependencyException("No mapping found for dependency " + key + " in " + field + "."); } this.externalContext = ExternalContext.newInstance(field, key, container); }

Target:
public FieldInjector(ContainerImpl container, Field field, String name) throws MissingDependencyException { this.field = field; if (isNotPublic(field) && !field.isAccessible()) { SecurityManager sm = System.getSecurityManager(); try { if (sm != null) { sm.checkPermission(new ReflectPermission("suppressAccessChecks")); } field.setAccessible(true); } catch (AccessControlException e) { throw new DependencyException("Security manager in use, could not access field: " + field.getDeclaringClass().getName() + "(" + field.getName() + ")", e); } } Key<?> key = Key.newInstance(field.getType(), name); factory = container.getFactory(key); if (factory == null) { throw new MissingDependencyException("No mapping found for dependency " + key + " in " + field + "."); } this.externalContext = ExternalContext.newInstance(field, key, container); }
Source:
private UserDTO getUserDtoFromJson(String json, Long dtoId) { UserDTO userDTO = null; try { if (json != null && json != "") { jsonMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); userDTO = jsonMapper.readValue(json, UserDTO.class); } } catch (final Exception ex) { LOGGER.error("Could not parse activity ID " + dtoId + " original data. " + "JSON was: " + json, ex); } return userDTO; }

Target:
private UserDTO getUserDtoFromJson(String json, Long dtoId) { UserDTO userDTO = null; try { if (json != null && json != "") { userDTO = jsonMapper.readValue(json, UserDTO.class); } } catch (final Exception ex) { LOGGER.error("Could not parse activity ID " + dtoId + " original data. " + "JSON was: " + json, ex); } return userDTO; }
Source:
public void setup() throws Exception { queryExecutor = MoreExecutors.newDirectExecutorService(); when(preQueryPlugin.process(any(), any())) .thenAnswer(invocation -> invocation.getArguments()[1]); strategy = new SortedFederationStrategy( queryExecutor, Arrays.asList(preQueryPlugin), new ArrayList<>()); federateStrategy = new SortedFederationStrategy( queryExecutor, Arrays.asList(preQueryPlugin), new ArrayList<>()); responseArgumentCaptor = ArgumentCaptor.forClass(QueryResponseImpl.class); requestArgumentCaptor = ArgumentCaptor.forClass(QueryRequestImpl.class); when(mockSortedQueryMonitorFactory.createMonitor( any(CompletionService.class), any(Map.class), responseArgumentCaptor.capture(), requestArgumentCaptor.capture(), any(List.class))) .thenReturn(mockSortedQueryMonitor); strategy.setSortedQueryMonitorFactory(mockSortedQueryMonitorFactory); when(mockQuery.getTimeoutMillis()).thenReturn(LONG_TIMEOUT); when(mockQuery.getPageSize()).thenReturn(-1); metacard = new MetacardImpl(); metacard.setId("mock metacard"); Result mockResult = new ResultImpl(metacard); List<Result> results = Collections.singletonList(mockResult); when(mockResponse.getResults()).thenReturn(results); properties = new HashMap<>(); }

Target:
public void setup() throws Exception { queryExecutor = MoreExecutors.newDirectExecutorService(); when(preQueryPlugin.process(any(), any())) .thenAnswer(invocation -> invocation.getArguments()[1]); strategy = new SortedFederationStrategy( queryExecutor, Arrays.asList(preQueryPlugin), new ArrayList<>()); responseArgumentCaptor = ArgumentCaptor.forClass(QueryResponseImpl.class); requestArgumentCaptor = ArgumentCaptor.forClass(QueryRequestImpl.class); when(mockQuery.getTimeoutMillis()).thenReturn(LONG_TIMEOUT); when(mockQuery.getPageSize()).thenReturn(-1); metacard = new MetacardImpl(); metacard.setId("mock metacard"); Result mockResult = new ResultImpl(metacard); List<Result> results = Collections.singletonList(mockResult); when(mockResponse.getResults()).thenReturn(results); properties = new HashMap<>(); }
Source:
public ListenableFuture<Void> write(ByteBuffer buffer, Map<String, String> headers) throws IllegalArgumentException { if (buffer != null) { byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); return write(new ByteArrayEntity(bytes), headers); } else { throw new IllegalArgumentException("ByteBuffer parameter is empty."); } }

Target:
public ListenableFuture<Void> write(ByteBuffer buffer, Map<String, String> headers) throws IllegalArgumentException { Preconditions.checkArgument(buffer != null, "ByteBuffer parameter is empty."); HttpEntity content; if (buffer.hasArray()) { content = new ByteArrayEntity(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()); } else { byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); content = new ByteArrayEntity(bytes); } return write(content, headers); }
Source:
public static Optional<Cookie> getCookie(final Collection<Cookie> cookies, final String name) { if (cookies != null) { for (final Cookie cookie : cookies) { if (cookie != null && CommonHelper.areEquals(name, cookie.getName())) { return Optional.of(cookie); } } } return Optional.empty(); }

Target:
public static Optional<Cookie> getCookie(final Collection<Cookie> cookies, final String name) { if (cookies != null) { return cookies.stream().filter( cookie -> cookie != null && CommonHelper.areEquals(name, cookie.getName()) ).findFirst(); } return Optional.empty(); }
Source:
public int[] transformToIntValuesSV(ProjectionBlock projectionBlock) { if (_results == null) { _results = new int[DocIdSetPlanNode.MAX_DOC_PER_CALL]; } byte[][] firstValues = _firstArgument.transformToBytesValuesSV(projectionBlock); byte[][] secondValues = _secondArgument.transformToBytesValuesSV(projectionBlock); for (int i = 0; i < projectionBlock.getNumDocs(); i++) { Geometry firstGeometry = GeometrySerializer.deserialize(firstValues[i]); Geometry secondGeometry = GeometrySerializer.deserialize(secondValues[i]); if (GeometryUtils.isGeography(firstGeometry) || GeometryUtils.isGeography(secondGeometry)) { throw new RuntimeException( String.format("%s is available for Geometry objects only", FUNCTION_NAME)); } _results[i] = firstGeometry.equals(secondGeometry) ? 1 : 0; } return _results; }

Target:
public int[] transformToIntValuesSV(ProjectionBlock projectionBlock) { if (_results == null) { _results = new int[DocIdSetPlanNode.MAX_DOC_PER_CALL]; } byte[][] firstValues = _firstArgument.transformToBytesValuesSV(projectionBlock); byte[][] secondValues = _secondArgument.transformToBytesValuesSV(projectionBlock); for (int i = 0; i < projectionBlock.getNumDocs(); i++) { Geometry firstGeometry = GeometrySerializer.deserialize(firstValues[i]); Geometry secondGeometry = GeometrySerializer.deserialize(secondValues[i]); _results[i] = firstGeometry.equals(secondGeometry) ? 1 : 0; } return _results; }
Source:
private void recreateStudentWithNewEmail( CourseStudent newCourseStudent, String lastName, CourseStudent courseStudent, boolean hasDocument, boolean keepUpdateTimestamp, String courseId, String email) throws InvalidParametersException, EntityDoesNotExistException { newCourseStudent.setLastName(lastName); newCourseStudent.setCreatedAt(courseStudent.getCreatedAt()); if (keepUpdateTimestamp) { newCourseStudent.setLastUpdate(courseStudent.getUpdatedAt()); } try { createStudent(new StudentAttributes(newCourseStudent), hasDocument); } catch (EntityAlreadyExistsException e) { CourseStudent existingStudent = (CourseStudent) getEntity(new StudentAttributes(newCourseStudent)); String error = ERROR_UPDATE_EMAIL_ALREADY_USED + existingStudent.getName() + "/" + existingStudent.getEmail(); throw new InvalidParametersException(error); } deleteStudent(courseId, email); }

Target:
private void recreateStudentWithNewEmail( CourseStudent newCourseStudent, String lastName, CourseStudent courseStudent, boolean hasDocument, boolean keepUpdateTimestamp, String courseId, String email) throws InvalidParametersException { newCourseStudent.setLastName(lastName); newCourseStudent.setCreatedAt(courseStudent.getCreatedAt()); if (keepUpdateTimestamp) { newCourseStudent.setLastUpdate(courseStudent.getUpdatedAt()); } StudentAttributes newCourseStudentAttributes = new StudentAttributes(newCourseStudent); try { createStudent(newCourseStudentAttributes, hasDocument); } catch (EntityAlreadyExistsException e) { CourseStudent existingStudent = (CourseStudent) getEntity(newCourseStudentAttributes); String error = ERROR_UPDATE_EMAIL_ALREADY_USED + existingStudent.getName() + "/" + existingStudent.getEmail(); throw new InvalidParametersException(error); } deleteStudent(courseId, email); }
Source:
public void setUp() { GwtMockito.initMocks(this); view = GWT.create(TimeZonePickerViewImpl.class); doCallRealMethod().when(view).setLocalTimeZone(); doCallRealMethod().when(view).setValue(anyString()); doCallRealMethod().when(view).populateTzSelector(); doCallRealMethod().when(tzSelect).setValue(anyString()); doCallRealMethod().when(tzSelect).setValue(anyString(), anyBoolean()); view.tzSelect = tzSelect; tested = spy(new TimeZonePicker(view)); }

Target:
public void setUp() { view = GWT.create(TimeZonePickerViewImpl.class); doCallRealMethod().when(view).setValue(anyString()); doCallRealMethod().when(view).populateTzSelector(); doCallRealMethod().when(tzSelect).setValue(anyString()); doCallRealMethod().when(tzSelect).setValue(anyString(), anyBoolean()); view.tzSelect = tzSelect; tested = spy(new TimeZonePicker(view)); }
Source:
public void testGetIntentForBrokerActivityHasIntent() throws NameNotFoundException, OperationCanceledException, IOException, AuthenticatorException { final AuthenticationRequest authRequest = createAuthenticationRequest("<LINK_0>", "resource", "client", "redirect", "loginhint", PromptBehavior.Auto, "", UUID.randomUUID(), false); final AccountManager mockAcctManager = getMockedAccountManager(AuthenticationConstants.Broker.BROKER_ACCOUNT_TYPE, AuthenticationConstants.Broker.COMPANY_PORTAL_APP_PACKAGE_NAME); final Bundle expected = new Bundle(); final Intent expectedIntent = new Intent(); expectedIntent.putExtra(AuthenticationConstants.Broker.BROKER_REQUEST, AuthenticationConstants.Broker.BROKER_REQUEST); expected.putParcelable(AccountManager.KEY_INTENT, expectedIntent); prepareAddAccount(mockAcctManager, expected); final FileMockContext context = new FileMockContext(InstrumentationRegistry.getContext()); context.setMockedAccountManager(mockAcctManager); context.setMockedPackageManager(getMockedPackageManagerWithBrokerAccountServiceDisabled(mock(Signature.class), AuthenticationConstants.Broker.COMPANY_PORTAL_APP_PACKAGE_NAME, true)); final BrokerProxy brokerProxy = new BrokerProxy(context); try { final Intent intent = brokerProxy.getIntentForBrokerActivity(authRequest, null); assertNotNull("intent is not null", intent); assertEquals("intent is not null", AuthenticationConstants.Broker.BROKER_REQUEST, intent.getStringExtra(AuthenticationConstants.Broker.BROKER_REQUEST)); } catch (final AuthenticationException exc) { fail("Not expected."); } }

Target:
public void testGetIntentForBrokerActivityHasIntent() throws NameNotFoundException, OperationCanceledException, IOException, AuthenticatorException, AuthenticationException { final AuthenticationRequest authRequest = createAuthenticationRequest("<LINK_0>", "resource", "client", "redirect", "loginhint", PromptBehavior.Auto, "", UUID.randomUUID(), false); final AccountManager mockAcctManager = getMockedAccountManager(AuthenticationConstants.Broker.BROKER_ACCOUNT_TYPE, AuthenticationConstants.Broker.COMPANY_PORTAL_APP_PACKAGE_NAME); final Bundle expected = new Bundle(); final Intent expectedIntent = new Intent(); expectedIntent.putExtra(AuthenticationConstants.Broker.BROKER_REQUEST, AuthenticationConstants.Broker.BROKER_REQUEST); expected.putParcelable(AccountManager.KEY_INTENT, expectedIntent); prepareAddAccount(mockAcctManager, expected); final FileMockContext context = new FileMockContext(InstrumentationRegistry.getContext()); context.setMockedAccountManager(mockAcctManager); context.setMockedPackageManager(getMockedPackageManagerWithBrokerAccountServiceDisabled(mock(Signature.class), AuthenticationConstants.Broker.COMPANY_PORTAL_APP_PACKAGE_NAME, true)); final BrokerProxy brokerProxy = new BrokerProxy(context); final Intent intent = brokerProxy.getIntentForBrokerActivity(authRequest, null); assertNotNull("intent is not null", intent); assertEquals("intent is not null", AuthenticationConstants.Broker.BROKER_REQUEST, intent.getStringExtra(AuthenticationConstants.Broker.BROKER_REQUEST)); }
Source:
@Override public <Resp> void response(HttpAdapter<?, Resp> adapter, Resp res, Throwable error, SpanCustomizer customizer) { HttpResponse response; if (res instanceof HttpClientResponse) { response = new HttpClientResponse.FromHttpAdapter((HttpClientAdapter) adapter, res); } else if (adapter instanceof HttpClientResponse.ToHttpAdapter) { response = ((HttpClientResponse.ToHttpAdapter) adapter).delegate; } else { throw new AssertionError("programming bug"); } errorParser.error(error, customizer); responseParser.parse(response, error, currentTraceContext.get(), customizer); }

Target:
@Override public <Resp> void response(HttpAdapter<?, Resp> adapter, Resp res, Throwable error, SpanCustomizer customizer) { HttpResponse response; if (res instanceof HttpClientResponse) { response = new HttpClientAdapters.FromResponseAdapter<>((HttpClientAdapter) adapter, res); } else if (adapter instanceof HttpClientAdapters.ToResponseAdapter) { response = ((HttpClientAdapters.ToResponseAdapter) adapter).delegate; } else { throw new AssertionError("programming bug"); } responseParser.parse(response, currentTraceContext.get(), customizer); }
Source:
public Host update(Host incoming) { validateEnums(Host.class, incoming); QueryIdResolver<Guid> hostResolver = new QueryIdResolver<Guid>(VdcQueryType.GetVdsByVdsId, GetVdsByVdsIdParameters.class); VDS entity = getEntity(hostResolver, true); if (incoming.isSetCluster() && (incoming.getCluster().isSetId() || incoming.getCluster().isSetName())) { Guid clusterId = lookupClusterId(incoming); performAction(VdcActionType.ChangeVDSCluster, new ChangeVDSClusterParameters(clusterId, guid)); } return performUpdate(incoming, entity, map(entity), hostResolver, VdcActionType.UpdateVds, new UpdateParametersProvider()); }

Target:
public Host update(Host incoming) { validateEnums(Host.class, incoming); QueryIdResolver<Guid> hostResolver = new QueryIdResolver<Guid>(VdcQueryType.GetVdsByVdsId, GetVdsByVdsIdParameters.class); VDS entity = getEntity(hostResolver, true); if (incoming.isSetCluster() && (incoming.getCluster().isSetId() || incoming.getCluster().isSetName())) { Guid clusterId = lookupClusterId(incoming); if (!clusterId.equals(entity.getvds_group_id())) { performAction(VdcActionType.ChangeVDSCluster, new ChangeVDSClusterParameters(clusterId, guid)); } } return performUpdate(incoming, entity, map(entity), hostResolver, VdcActionType.UpdateVds, new UpdateParametersProvider()); }
Source:
public MappingCodec( @NonNull TypeCodec<InnerT> innerCodec, @NonNull GenericType<OuterT> outerJavaType) { this.innerCodec = Objects.requireNonNull(innerCodec, "innerCodec cannot be null"); this.outerJavaType = Objects.requireNonNull(outerJavaType, "outerJavaType cannot be null"); }

Target:
protected MappingCodec( @NonNull TypeCodec<InnerT> innerCodec, @NonNull GenericType<OuterT> outerJavaType) { this.innerCodec = Objects.requireNonNull(innerCodec, "innerCodec cannot be null"); this.outerJavaType = Objects.requireNonNull(outerJavaType, "outerJavaType cannot be null"); }
Source:
public void invitesAndKicks() throws Exception { final MkBase base = new MkBase(); final Bout bout = base.randomBout(); final Friends friends = bout.friends(); final String friend = base.randomBout().friends().iterate().iterator() .next().alias(); friends.invite(friend); final String someone = base.randomBout().friends().iterate().iterator() .next().alias(); friends.invite(someone); friends.kick(friend); MatcherAssert.assertThat( friends.iterate(), Matchers.not( Matchers.hasItem(new Friend.HasAlias(Matchers.is(friend))) ) ); }

Target:
public void invitesAndKicks() throws Exception { final MkBase base = new MkBase(); final Bout bout = base.randomBout(); final Friends friends = bout.friends(); final String friend = base.randomAlias().name(); friends.invite(friend); final String someone = base.randomAlias().name(); friends.invite(someone); friends.kick(friend); MatcherAssert.assertThat( friends.iterate(), Matchers.not( Matchers.hasItem(new Friend.HasAlias(Matchers.is(friend))) ) ); }
Source:
public ArtifactInputStream getInputStream(String storageId, String repositoryId, String path) throws IOException, NoSuchAlgorithmException, ArtifactTransportException { Storage storage = getConfiguration().getStorage(storageId); logger.debug("Checking in " + storage.getId() + ":" + repositoryId + "..."); Repository repository = storage.getRepository(repositoryId); StorageProvider storageProvider = storageProviderRegistry.getProvider(repository.getImplementation()); final File repoPath = storageProvider.getFileImplementation(storage.getRepository(repositoryId).getBasedir()); final File artifactFile = storageProvider.getFileImplementation(repoPath.getPath(), path).getCanonicalFile(); logger.debug(" -> Checking for " + artifactFile.getCanonicalPath() + "..."); if (artifactFile.exists()) { logger.debug("Resolved " + artifactFile.getCanonicalPath() + "!"); ArtifactInputStream ais = storageProvider.getInputStreamImplementation(artifactFile.getAbsolutePath()); ais.setLength(artifactFile.length()); return ais; } return null; }

Target:
public ArtifactInputStream getInputStream(String storageId, String repositoryId, String path) throws IOException, NoSuchAlgorithmException, ArtifactTransportException { Storage storage = getConfiguration().getStorage(storageId); logger.debug("Checking in " + storage.getId() + ":" + repositoryId + "..."); Repository repository = storage.getRepository(repositoryId); StorageProvider storageProvider = storageProviderRegistry.getProvider(repository.getImplementation()); String storagePath = storage.getRepository(repositoryId).getBasedir() + '/' + path; ArtifactInputStream ais = storageProvider.getInputStreamImplementation(storagePath); return ais; }
Source:
public static KHyperLogLog newInstance(Slice serialized) { requireNonNull(serialized, "serialized is null"); SliceInput input = serialized.getInput(); checkArgument(input.readByte() == UNCOMPRESSED_FORMAT, "Unexpected version"); int maxSize = input.readInt(); int hllBuckets = input.readInt(); int minhashSize = input.readInt(); Long2ObjectRBTreeMap<HyperLogLog> minhash = new Long2ObjectRBTreeMap<>(); SliceInput valuesInput = serialized.getInput(); valuesInput.setPosition(input.position() + minhashSize * SIZE_OF_LONG); int hllLength; Slice serializedHll; for (int i = 0; i < minhashSize; i++) { hllLength = valuesInput.readInt(); serializedHll = Slices.allocate(hllLength); valuesInput.readBytes(serializedHll, hllLength); minhash.put(input.readLong(), HyperLogLog.newInstance(serializedHll)); } return new KHyperLogLog(maxSize, hllBuckets, minhash); }

Target:
public static KHyperLogLog newInstance(Slice serialized) { requireNonNull(serialized, "serialized is null"); SliceInput input = serialized.getInput(); checkArgument(input.readByte() == VERSION_BYTE, "Unexpected version"); Long2ObjectRBTreeMap<HyperLogLog> minhash = new Long2ObjectRBTreeMap<>(); int maxSize = input.readInt(); int hllBuckets = input.readInt(); int minhashSize = input.readInt(); int totalHllSize = input.readInt(); int[] hllSizes = new int[minhashSize]; long[] keys = new long[minhashSize]; input.readBytes(wrappedIntArray(hllSizes)); input.readBytes(wrappedLongArray(keys)); Slice allSerializedHlls = input.readSlice(totalHllSize); int hllLength; int index = 0; for (int i = 0; i < minhashSize; i++) { Slice serializedHll; hllLength = hllSizes[i]; serializedHll = allSerializedHlls.slice(index, hllLength); index += hllLength; minhash.put(keys[i], HyperLogLog.newInstance(serializedHll)); } return new KHyperLogLog(maxSize, hllBuckets, minhash); }
Source:
public Item handle(Context context, HttpServletRequest request, List<String> uriList) throws SQLException, AuthorizeException { ExternalDataObject dataObject = getExternalDataObjectFromUriList(uriList); String owningCollectionUuid = request.getParameter("owningCollection"); Collection collection = null; Item item = null; try { collection = collectionService.find(context, UUID.fromString(owningCollectionUuid)); item = externalDataService.createItemFromExternalDataObject(context, dataObject, collection); } catch (AuthorizeException | SQLException e) { log.error(e.getMessage(), e); throw e; } return item; }

Target:
public Item handle(Context context, HttpServletRequest request, List<String> uriList) throws SQLException, AuthorizeException { ExternalDataObject dataObject = getExternalDataObjectFromUriList(uriList); String owningCollectionUuid = request.getParameter("owningCollection"); Collection collection = null; Item item = null; try { collection = collectionService.find(context, UUID.fromString(owningCollectionUuid)); item = externalDataService.createItemFromExternalDataObject(context, dataObject, collection); } catch (AuthorizeException | SQLException e) { log.error("An error occured when trying to create item in collection with uuid: " + owningCollectionUuid, e); throw e; } return item; }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Service service = (Service) o; if (binary != null ? !binary.equals(service.binary) : service.binary != null) return false; if (host != null ? !host.equals(service.host) : service.host != null) return false; if (state != null ? !state.equals(service.state) : service.state != null) return false; if (status != null ? !status.equals(service.status) : service.status != null) return false; if (disabledReason != null ? !disabledReason.equals(service.disabledReason) : service.disabledReason != null) return false; if (updated != null ? !updated.equals(service.updated) : service.updated != null) return false; if (zone != null ? !zone.equals(service.zone) : service.zone != null) return false; if (id != null ? !id.equals(service.id) : service.id != null) return false; return true; }

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Service service = (Service) o; return Objects.equal(this.id, service.id) && Objects.equal(this.binary, service.binary) && Objects.equal(this.host, service.host) && Objects.equal(this.state, service.state) && Objects.equal(this.status, service.status) && Objects.equal(this.disabledReason, service.disabledReason) && Objects.equal(this.updated, service.updated) && Objects.equal(this.zone, service.zone); }
Source:
public void compact(OutputStream out) throws IOException { MergedReftable mr = new MergedReftable(new ArrayList<>(tables)); mr.setIncludeDeletes(includeDeletes); minUpdateIndex = Math.max(minUpdateIndex, 0); writer.setMinUpdateIndex(minUpdateIndex); writer.setMaxUpdateIndex(maxUpdateIndex); writer.begin(out); mergeRefs(mr); mergeLogs(mr); writer.finish(); stats = writer.getStats(); }

Target:
public void compact(OutputStream out) throws IOException { MergedReftable mr = new MergedReftable(new ArrayList<>(tables)); mr.setIncludeDeletes(includeDeletes); writer.setMinUpdateIndex(Math.max(minUpdateIndex, 0)); writer.setMaxUpdateIndex(maxUpdateIndex); writer.begin(out); mergeRefs(mr); mergeLogs(mr); writer.finish(); stats = writer.getStats(); }
Source:
public boolean performFinish() { final CreatePatchOperation operation = new CreatePatchOperation(db, commit); boolean useGitFormat = optionsPage.gitFormat.getSelection(); operation.useGitFormat(useGitFormat); operation.setContextLines(Integer.parseInt(optionsPage.contextLines.getText())); final File file = !locationPage.fsRadio.getSelection()? locationPage.getFile() : null; if (!(file == null || validateFile(file))) { return false; } try { getContainer().run(true, true, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException { try { operation.execute(monitor); String content = operation.getPatchContent(); if (file != null) { writeToFile(file, content); } else { copyToClipboard(content); } } catch (IOException e) { throw new InvocationTargetException(e); } catch (CoreException e) { throw new InvocationTargetException(e); } } }); } catch (InvocationTargetException e) { ((WizardPage) getContainer().getCurrentPage()).setErrorMessage(e .getMessage() == null ? e.getMessage() : UIText.GitCreatePatchWizard_InternalError); Activator.logError("Patch file was not written", e); return false; } catch (InterruptedException e) { Activator.logError("Patch file was not written", e); return false; } return true; }

Target:
public boolean performFinish() { final CreatePatchOperation operation = new CreatePatchOperation(db, commit); boolean useGitFormat = optionsPage.gitFormat.getSelection(); operation.useGitFormat(useGitFormat); operation.setContextLines(Integer.parseInt(optionsPage.contextLines.getText())); final File file = !locationPage.fsRadio.getSelection() ? locationPage .getFile() : null; if (!(file == null || validateFile(file))) return false; try { getContainer().run(true, true, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException { try { operation.execute(monitor); String content = operation.getPatchContent(); if (file != null) { writeToFile(file, content); } else { copyToClipboard(content); } } catch (IOException e) { throw new InvocationTargetException(e); } catch (CoreException e) { throw new InvocationTargetException(e); } } }); } catch (InvocationTargetException e) { ((WizardPage) getContainer().getCurrentPage()).setErrorMessage(e .getMessage() == null ? e.getMessage() : UIText.GitCreatePatchWizard_InternalError); Activator.logError("Patch file was not written", e); return false; } catch (InterruptedException e) { Activator.logError("Patch file was not written", e); return false; } return true; }
Source:
public MotionScoreAlgorithm(final Map<Long, List<AmplitudeData>> dataMatrix, final int dimensionCount, final int rowCount, final List<SleepDataScoringFunction> scoringFunctions){ super(null, 0); checkNotNull(dataMatrix); if(scoringFunctions.size() != dimensionCount){ throw new IllegalArgumentException("Number of scoring function must be the same with data dimension."); } this.scoringFunctions.addAll(scoringFunctions); this.dimensions = dataMatrix; this.dimensionCount = dimensionCount; this.rowCount = rowCount; }

Target:
public MotionScoreAlgorithm(final Map<Long, List<AmplitudeData>> dataMatrix, final int dimensionCount, final int rowCount, final List<SleepDataScoringFunction> scoringFunctions){ super(null, 0); checkNotNull(dataMatrix, "dataMatrix cannot be null"); if(scoringFunctions.size() != dimensionCount){ throw new IllegalArgumentException("Number of scoring function must be the same with data dimension."); } this.scoringFunctions.addAll(scoringFunctions); this.dimensions = dataMatrix; this.dimensionCount = dimensionCount; this.rowCount = rowCount; }
Source:
private static Optional<List> validateQueryParams(List<Pair<String, Long>> nonNegativePairMap) { Map<String, String> invalidQueryParams = new HashMap<>(); nonNegativePairMap.forEach(param -> { if (param.getRight() != null && param.getRight() < 1) { invalidQueryParams.put(param.getLeft(), "query param '%s' should be a non zero positive integer"); } }); if (!invalidQueryParams.isEmpty()) { List<String> invalidResponse = newArrayList(); invalidResponse.addAll(invalidQueryParams.keySet() .stream() .map(param -> String.format(invalidQueryParams.get(param), param)) .collect(Collectors.toList())); return Optional.of(invalidResponse); } return Optional.empty(); }

Target:
private static List<String> validateQueryParams(List<Pair<String, Long>> nonNegativePairMap) { Map<String, String> invalidQueryParams = new HashMap<>(); List<String> invalidResponse = newArrayList(); nonNegativePairMap.forEach(param -> { if (param.getRight() != null && param.getRight() < 1) { invalidQueryParams.put(param.getLeft(), "query param '%s' should be a non zero positive integer"); } }); if (!invalidQueryParams.isEmpty()) { invalidResponse = invalidQueryParams.keySet().stream() .map(param -> String.format(invalidQueryParams.get(param), param)) .collect(Collectors.toList()); } return invalidResponse; }
Source:
public CompletableFuture<CommitStatus> commit() { Set<TransactionParticipant<?>> participants = this.participants.stream() .filter(p -> !p.log().records().isEmpty()) .collect(Collectors.toSet()); Set<ParticipantInfo> participantInfo = participants.stream() .map(participant -> new ParticipantInfo( participant.name(), participant.type().name(), participant.protocol().type().name(), participant.protocol().group())) .collect(Collectors.toSet()); CompletableFuture<CommitStatus> status = transactionService.preparing(transactionId, participantInfo) .thenCompose(v -> prepare(participants)) .thenCompose(result -> result ? transactionService.committing(transactionId) .thenCompose(v -> commit(participants)) .thenApply(v -> CommitStatus.SUCCESS) : transactionService.aborting(transactionId) .thenCompose(v -> rollback(participants)) .thenApply(v -> CommitStatus.FAILURE)); return status.thenCompose(v -> transactionService.complete(transactionId) .thenRun(() -> participants.forEach(TransactionParticipant::close)) .thenApply(u -> v)); }

Target:
public CompletableFuture<CommitStatus> commit() { Set<TransactionParticipant<?>> participants = this.participants.stream() .filter(p -> !p.log().records().isEmpty()) .collect(Collectors.toSet()); Set<ParticipantInfo> participantInfo = participants.stream() .map(participant -> new ParticipantInfo( participant.name(), participant.type().name(), participant.protocol().type().name(), participant.protocol().group())) .collect(Collectors.toSet()); CompletableFuture<CommitStatus> status = transactionService.preparing(transactionId, participantInfo) .thenCompose(v -> prepare(participants)) .thenCompose(result -> result ? transactionService.committing(transactionId) .thenCompose(v -> commit(participants)) .thenApply(v -> CommitStatus.SUCCESS) : transactionService.aborting(transactionId) .thenCompose(v -> rollback(participants)) .thenApply(v -> CommitStatus.FAILURE)); return status.thenCompose(v -> transactionService.complete(transactionId) .thenRun(() -> participants.forEach(p -> p.close().exceptionally(e -> null))) .thenApply(u -> v)); }
Source:
public String toString() { return "CoverageModelCopyRatioEmissionData{" + "mu=" + mu + ", psi=" + psi + ", readCount=" + readCount + ", poissonAdditiveNoise=" + poissonAdditiveNoise + ", copyRatioCallingMetadata=" + copyRatioCallingMetadata + '}'; }

Target:
public String toString() { return "CoverageModelCopyRatioEmissionData{" + "mu=" + mu + ", psi=" + psi + ", readCount=" + readCount + ", mappingErrorProbability=" + mappingErrorProbability + ", copyRatioCallingMetadata=" + copyRatioCallingMetadata + '}'; }
Source:
private double calculateSegmentMeanBiasInCRSpace(final List<ACNVModeledSegment> segments) { Utils.nonNull(segments); final Percentile percentile = new Percentile(); final double modeInCRSpace = percentile.evaluate(segments.stream() .filter(s -> Math.abs(s.getSegmentMeanInCRSpace() - 1) < 0.1) .mapToDouble(s -> s.getSegmentMeanInCRSpace()).toArray(), 50); return modeInCRSpace - 1; }

Target:
private double calculateSegmentMeanBiasInCRSpace(final List<ACNVModeledSegment> segments) { Utils.nonNull(segments); final double neutralCRApprox = 1; final double[] neutralSegmentMeans = segments.stream().mapToDouble(ACNVModeledSegment::getSegmentMeanInCRSpace) .filter(x -> Math.abs(x - neutralCRApprox) < CLOSE_ENOUGH_TO_COPY_NEUTRAL_IN_CR) .toArray(); return new Percentile().evaluate(neutralSegmentMeans) - 1; }
Source:
public Mono<Lease> createLeaseIfNotExist(String leaseToken, String continuationToken) { if (leaseToken == null) throw Exceptions.propagate(new IllegalArgumentException("leaseToken")); String leaseDocId = this.getDocumentId(leaseToken); ServiceItemLease documentServiceLease = new ServiceItemLease() .withId(leaseDocId) .withLeaseToken(leaseToken) .withContinuationToken(continuationToken); return this.leaseDocumentClient.createItem(this.settings.getLeaseCollectionLink(), documentServiceLease, null, false) .onErrorResume( ex -> { if (ex instanceof CosmosClientException) { CosmosClientException e = (CosmosClientException) ex; if (e.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT) { logger.info("Some other host created lease for {}.", leaseToken); return Mono.empty(); } } return Mono.error(ex); }) .map(documentResourceResponse -> { if (documentResourceResponse == null) return null; CosmosItemProperties document = documentResourceResponse.properties(); logger.info("Created lease for partition {}.", leaseToken); return documentServiceLease .withId(document.id()) .withEtag(document.etag()) .withTs(document.getString(Constants.Properties.LAST_MODIFIED)); }); }

Target:
public Mono<Lease> createLeaseIfNotExist(String leaseToken, String continuationToken) { if (leaseToken == null) { throw new IllegalArgumentException("leaseToken"); } String leaseDocId = this.getDocumentId(leaseToken); ServiceItemLease documentServiceLease = new ServiceItemLease() .withId(leaseDocId) .withLeaseToken(leaseToken) .withContinuationToken(continuationToken); return this.leaseDocumentClient.createItem(this.settings.getLeaseCollectionLink(), documentServiceLease, null, false) .onErrorResume( ex -> { if (ex instanceof CosmosClientException) { CosmosClientException e = (CosmosClientException) ex; if (e.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT) { logger.info("Some other host created lease for {}.", leaseToken); return Mono.empty(); } } return Mono.error(ex); }) .map(documentResourceResponse -> { if (documentResourceResponse == null) { return null; } CosmosItemProperties document = documentResourceResponse.properties(); logger.info("Created lease for partition {}.", leaseToken); return documentServiceLease .withId(document.id()) .withEtag(document.etag()) .withTs(document.getString(Constants.Properties.LAST_MODIFIED)); }); }
Source:
public <A> void assertHasAllNullFieldsOrPropertiesExcept(AssertionInfo info, A actual, String... propertiesOrFieldsToIgnore) { assertNotNull(info, actual); Set<Field> declaredFieldsIncludingInherited = getDeclaredFieldsIncludingInherited(actual.getClass()); Set<String> ignoredFields = newLinkedHashSet(propertiesOrFieldsToIgnore); List<String> notNullFieldNames = new LinkedList<>(); for (Field field : declaredFieldsIncludingInherited) { String fieldName = field.getName(); if (ignoredFields.contains(fieldName) || !canReadFieldValue(field, actual)) { continue; } Object actualFieldValue = getPropertyOrFieldValue(actual, fieldName); if (actualFieldValue != null) { notNullFieldNames.add(fieldName); } } if (!notNullFieldNames.isEmpty()) { throw failures.failure(info, shouldHaveAllNullFields( actual, notNullFieldNames, newArrayList(propertiesOrFieldsToIgnore) )); } }

Target:
public <A> void assertHasAllNullFieldsOrPropertiesExcept(AssertionInfo info, A actual, String... propertiesOrFieldsToIgnore) { assertNotNull(info, actual); Set<Field> declaredFieldsIncludingInherited = getDeclaredFieldsIncludingInherited(actual.getClass()); Set<String> ignoredFields = newLinkedHashSet(propertiesOrFieldsToIgnore); List<String> notNullFieldNames = new LinkedList<>(); for (Field field : declaredFieldsIncludingInherited) { String fieldName = field.getName(); if (ignoredFields.contains(fieldName) || !canReadFieldValue(field, actual)) { continue; } Object actualFieldValue = getPropertyOrFieldValue(actual, fieldName); if (actualFieldValue != null) { notNullFieldNames.add(fieldName); } } if (!notNullFieldNames.isEmpty()) { throw failures.failure(info, shouldHaveAllNullFields( actual, notNullFieldNames, list(propertiesOrFieldsToIgnore) )); } }
Source:
public List<String> getLocalesWithTranslation(final Resources resources) { String[] languageList = BuildConfig.TRANSLATION_ARRAY; Set<String> availableLanguagesSet = new HashSet<>(); String[] translatedLanguages = resources.getStringArray(R.array.available_languages); Set<String> translatedLanguageSet = new HashSet<>(); Collections.addAll(translatedLanguageSet, translatedLanguages); for (String language : languageList) { int isCountryCodeNeeded = 2; if (language.contains("-")) { isCountryCodeNeeded = 4; } if (translatedLanguageSet.contains(language.substring(0, isCountryCodeNeeded))) availableLanguagesSet.add(language); } List<String> availableLanguagesList = new ArrayList<>(availableLanguagesSet); Collections.sort(availableLanguagesList); return availableLanguagesList; }

Target:
public List<String> getLocalesWithTranslation(final Resources resources) { String[] languageList = BuildConfig.TRANSLATION_ARRAY; Set<String> availableLanguagesSet = new HashSet<>(); availableLanguagesSet.add("en"); String[] translatedLanguages = resources.getStringArray(R.array.available_languages); Set<String> translatedLanguageSet = new HashSet<>(); Collections.addAll(translatedLanguageSet, translatedLanguages); for (String language : languageList) { if (translatedLanguageSet.contains(language.substring(0, 5))) availableLanguagesSet.add(language); } List<String> availableLanguagesList = new ArrayList<>(availableLanguagesSet); Collections.sort(availableLanguagesList); return availableLanguagesList; }
Source:
private ReplicaList filterForEachQuorum(Keyspace keyspace, ReplicaList liveReplicas) { NetworkTopologyStrategy strategy = (NetworkTopologyStrategy) keyspace.getReplicationStrategy(); Map<String, ReplicaList> dcsReplicas = new HashMap<>(); for (String dc: strategy.getDatacenters()) dcsReplicas.put(dc, new ReplicaList()); for (Replica replica : liveReplicas) { String dc = DatabaseDescriptor.getEndpointSnitch().getDatacenter(replica); dcsReplicas.get(dc).add(replica); } ReplicaList waitSet = new ReplicaList(); for (Map.Entry<String, ReplicaList> dcEndpoints : dcsReplicas.entrySet()) { ReplicaList dcEndpoint = dcEndpoints.getValue(); waitSet.addAll(dcEndpoint.subList(0, Math.min(localQuorumFor(keyspace, dcEndpoints.getKey()), dcEndpoint.size()))); } return waitSet; }

Target:
private ReplicaList filterForEachQuorum(Keyspace keyspace, ReplicaList liveReplicas) { NetworkTopologyStrategy strategy = (NetworkTopologyStrategy) keyspace.getReplicationStrategy(); Map<String, ReplicaList> dcsReplicas = new HashMap<>(); for (String dc: strategy.getDatacenters()) dcsReplicas.put(dc, ReplicaList.withMaxSize(liveReplicas.size())); for (Replica replica : liveReplicas) { String dc = DatabaseDescriptor.getEndpointSnitch().getDatacenter(replica); dcsReplicas.get(dc).add(replica); } ReplicaList waitSet = new ReplicaList(ReplicaList.withMaxSize(liveReplicas.size())); for (Map.Entry<String, ReplicaList> dcEndpoints : dcsReplicas.entrySet()) { ReplicaList dcEndpoint = dcEndpoints.getValue(); waitSet.addAll(dcEndpoint.subList(0, Math.min(localQuorumFor(keyspace, dcEndpoints.getKey()), dcEndpoint.size()))); } return waitSet; }
Source:
protected void handleComponentDetached(Component comp) { comp.addEventListener(10000, BinderImpl.ON_BIND_CLEAN, new EventListener<Event>() { public void onEvent(Event event) throws Exception { final Component comp = event.getTarget(); comp.removeAttribute(REMOVE_MARK); comp.removeEventListener(BinderImpl.ON_BIND_CLEAN, this); if (comp.hasAttribute(BinderImpl.VAR)) { Object ref = comp.getAttribute((String) comp.getAttribute(BinderImpl.VAR)); if (ref instanceof ReferenceBinding) { BinderUtil.markHandling(comp, ((ReferenceBinding) ref).getBinder()); } } removeBindings(comp); } }); if (((AbstractComponent) comp).getAnnotations("veiwModel") != null) { Binder binder = BinderUtil.getBinder(comp, comp.hasAttribute(BinderCtrl.IS_TEMPLATE_MODEL_ENABLED_ATTR)); binder.destroy(comp, binder.getViewModel(), null); } comp.setAttribute(REMOVE_MARK, Boolean.TRUE); if (comp.removeAttribute(BinderCtrl.CHILDREN_BINDING_RENDERED_COMPONENTS) != null) { ListModel<?> model = (ListModel<?>) comp.getAttribute(BinderCtrl.CHILDREN_BINDING_MODEL); ListDataListener listener = (ListDataListener) comp .removeAttribute(BinderCtrl.CHILDREN_BINDING_MODEL_LISTENER); if (model != null && listener != null) { model.removeListDataListener(listener); } } comp.setAttribute(SKIP_BIND_INIT, false); Events.postEvent(new Event(BinderImpl.ON_BIND_CLEAN, comp)); }

Target:
protected void handleComponentDetached(Component comp) { comp.addEventListener(10000, BinderImpl.ON_BIND_CLEAN, new EventListener<Event>() { public void onEvent(Event event) throws Exception { final Component comp = event.getTarget(); comp.removeAttribute(REMOVE_MARK); comp.removeEventListener(BinderImpl.ON_BIND_CLEAN, this); if (comp.hasAttribute(BinderImpl.VAR)) { Object ref = comp.getAttribute((String) comp.getAttribute(BinderImpl.VAR)); if (ref instanceof ReferenceBinding) { BinderUtil.markHandling(comp, ((ReferenceBinding) ref).getBinder()); } } removeBindings(comp); } }); if (((AbstractComponent) comp).getAnnotations("viewModel") != null) { Binder binder = BinderUtil.getBinder(comp); binder.destroy(comp, binder.getViewModel()); } comp.setAttribute(REMOVE_MARK, Boolean.TRUE); if (comp.removeAttribute(BinderCtrl.CHILDREN_BINDING_RENDERED_COMPONENTS) != null) { ListModel<?> model = (ListModel<?>) comp.getAttribute(BinderCtrl.CHILDREN_BINDING_MODEL); ListDataListener listener = (ListDataListener) comp .removeAttribute(BinderCtrl.CHILDREN_BINDING_MODEL_LISTENER); if (model != null && listener != null) { model.removeListDataListener(listener); } } comp.setAttribute(SKIP_BIND_INIT, false); Events.postEvent(new Event(BinderImpl.ON_BIND_CLEAN, comp)); }
Source:
public void testReelectionOfDispatcher() throws Exception { final CompletableFuture<JobSubmissionResult> submissionFuture = miniCluster.submitJob(jobGraph); submissionFuture.get(); CommonTestUtils.waitUntilJobManagerIsInitialized(() -> miniCluster.getJobStatus(jobId).get()); CompletableFuture<JobResult> jobResultFuture = miniCluster.requestJobResult(jobId); highAvailabilityServices.revokeDispatcherLeadership().get(); try { jobResultFuture.get(); fail("Expected JobNotFinishedException"); } catch (ExecutionException ee) { assertThat(ExceptionUtils.findThrowable(ee, JobNotFinishedException.class).isPresent(), is(true)); } highAvailabilityServices.grantDispatcherLeadership(); BlockingOperator.isBlocking = false; final CompletableFuture<JobSubmissionResult> submissionFuture2 = miniCluster.submitJob(jobGraph); submissionFuture2.get(); final CompletableFuture<JobResult> jobResultFuture2 = miniCluster.requestJobResult(jobId); JobResult jobResult = jobResultFuture2.get(); JobResultUtils.assertSuccess(jobResult); }

Target:
public void testReelectionOfDispatcher() throws Exception { final CompletableFuture<JobSubmissionResult> submissionFuture = miniCluster.submitJob(jobGraph); submissionFuture.get(); CompletableFuture<JobResult> jobResultFuture = miniCluster.requestJobResult(jobId); highAvailabilityServices.revokeDispatcherLeadership().get(); try { jobResultFuture.get(); fail("Expected JobNotFinishedException"); } catch (ExecutionException ee) { assertThat(ExceptionUtils.findThrowable(ee, JobNotFinishedException.class).isPresent(), is(true)); } highAvailabilityServices.grantDispatcherLeadership(); BlockingOperator.isBlocking = false; final CompletableFuture<JobSubmissionResult> submissionFuture2 = miniCluster.submitJob(jobGraph); submissionFuture2.get(); final CompletableFuture<JobResult> jobResultFuture2 = miniCluster.requestJobResult(jobId); JobResult jobResult = jobResultFuture2.get(); JobResultUtils.assertSuccess(jobResult); }
Source:
public void createSignatures(JavaClass javaClass, Service service, Method method) { for (JavaClass innerClass : javaClass.getNestedClasses()) { assert innerClass.isInterface(); Method childMethod = createMethod(innerClass, service); analyzeInputDetail(javaClass, method, service); childMethod.setBase(method); } }

Target:
public void createSignatures(JavaClass javaClass, Service service, Method method) { for (JavaClass innerClass : javaClass.getNestedClasses()) { assert innerClass.isInterface(); Method childMethod = createMethod(innerClass, service); copyParameters(childMethod, method); analyzeInputDetail(innerClass, childMethod, service); childMethod.setBase(method); service.addMethod(childMethod); } }