auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Response info(@PathParam("date") String date) throws Exception { Instant instant = DateUtil.parseInstant(date); List<BackupMetadata> metadataList = backupStatusMgr.getLatestBackupMetadata( SnapshotMetaService.BACKUP_VERSION, new DateRange( instant, instant.plus(1, ChronoUnit.DAYS).truncatedTo(ChronoUnit.DAYS))); return Response.ok(metadataList.toString(), MediaType.APPLICATION_JSON).build(); }

Target:
public Response info(@PathParam("date") String date) { Instant instant = DateUtil.parseInstant(date); List<BackupMetadata> metadataList = backupStatusMgr.getLatestBackupMetadata( BackupVersion.SNAPSHOT_META_SERVICE, new DateRange( instant, instant.plus(1, ChronoUnit.DAYS).truncatedTo(ChronoUnit.DAYS))); return Response.ok(metadataList).build(); }
Source:
public V get(final K key) throws CacheLoaderException { getObserver.begin(); checkNonNull(key); final Function<K, V> mappingFunction = memoize( new Function<K, V>() { @Override public V apply(final K k) { V loaded = null; try { if (cacheLoader != null) { loaded = cacheLoader.load(k); } } catch (Exception e) { throw newCacheLoaderException(e); } return loaded; } }); try { final Store.ValueHolder<V> valueHolder = store.computeIfAbsent(key, mappingFunction); if (valueHolder == null) { getObserver.end(GetOutcome.MISS_NOT_FOUND); return null; } else { getObserver.end(GetOutcome.HIT); return valueHolder.value(); } } catch (CacheAccessException e) { getObserver.end(GetOutcome.MISS_NOT_FOUND); try { store.remove(key); resilienceStrategy.recoveredFrom(key, e); } catch (CacheAccessException e1) { resilienceStrategy.possiblyInconsistent(key, e1, e); } return mappingFunction.apply(key); } }

Target:
public V get(final K key) throws CacheLoaderException { statusTransitioner.checkAvailable(); checkNonNull(key); final Function<K, V> mappingFunction = memoize( new Function<K, V>() { @Override public V apply(final K k) { V loaded = null; try { if (cacheLoader != null) { loaded = cacheLoader.load(k); } } catch (Exception e) { throw newCacheLoaderException(e); } return loaded; } }); try { final Store.ValueHolder<V> valueHolder = store.computeIfAbsent(key, mappingFunction); return valueHolder == null ? null : valueHolder.value(); } catch (CacheAccessException e) { try { store.remove(key); resilienceStrategy.recoveredFrom(key, e); } catch (CacheAccessException e1) { resilienceStrategy.possiblyInconsistent(key, e1, e); } return mappingFunction.apply(key); } }
Source:
public void removeAllAppLauncher() { appLauncherItemViews.destroyAll(); }

Target:
public void removeAllAppLauncher() { appLauncherItemViews.destroyAll(); removeAllNodes(leftColumn); removeAllNodes(rightColumn); }
Source:
private void feedDataToExtractor( DataSource dataSource, DataSpec dataSpec, boolean dataIsEncrypted) throws IOException { DataSpec loadDataSpec; boolean skipLoadedBytes; if (dataIsEncrypted) { loadDataSpec = dataSpec; skipLoadedBytes = nextLoadPosition != 0; } else { loadDataSpec = dataSpec.subrange(nextLoadPosition); skipLoadedBytes = false; } try { ExtractorInput input = prepareExtraction(dataSource, loadDataSpec); if (skipLoadedBytes) { input.skipFully(nextLoadPosition); } try { int result = Extractor.RESULT_CONTINUE; while (result == Extractor.RESULT_CONTINUE && !loadCanceled) { result = extractor.read(input, DUMMY_POSITION_HOLDER); } } catch (UnexpectedDiscontinuityException e) { Log.d(TAG, "UnexpectedDiscontinuityException - recovering by discarding balance of segment", e); throw new IOException("load aborted for segment - " + e.dataSpec + " unexpected discontinuity", e); } finally { nextLoadPosition = (int) (input.getPosition() - dataSpec.position); } } finally { Util.closeQuietly(dataSource); } }

Target:
private void feedDataToExtractor( DataSource dataSource, DataSpec dataSpec, boolean dataIsEncrypted) throws IOException { DataSpec loadDataSpec; boolean skipLoadedBytes; if (dataIsEncrypted) { loadDataSpec = dataSpec; skipLoadedBytes = nextLoadPosition != 0; } else { loadDataSpec = dataSpec.subrange(nextLoadPosition); skipLoadedBytes = false; } try { ExtractorInput input = prepareExtraction(dataSource, loadDataSpec); if (skipLoadedBytes) { input.skipFully(nextLoadPosition); } try { int result = Extractor.RESULT_CONTINUE; while (result == Extractor.RESULT_CONTINUE && !loadCanceled) { result = extractor.read(input, DUMMY_POSITION_HOLDER); } } finally { nextLoadPosition = (int) (input.getPosition() - dataSpec.position); } } catch (UnexpectedDiscontinuityException e) { Log.d(TAG, "UnexpectedDiscontinuityException - recovering by discarding balance of segment", e); throw new IOException("load aborted for segment - " + e.dataSpec + " unexpected discontinuity", e); } finally { Util.closeQuietly(dataSource); } }
Source:
public void setUp() throws Exception { doInHibernate( this::sessionFactory, s -> { Post post = new Post(); post.setDetails(new PostDetails()); post.getDetails().setCreatedBy("ME"); post.getDetails().setCreatedOn(new Date()); post.setTitle("title"); s.persist(post); s.flush(); s.clear(); } ); }

Target:
public void setUp() throws Exception { doInHibernate( this::sessionFactory, s -> { Post post = new Post(); post.setDetails( new PostDetails() ); post.getDetails().setCreatedBy( "ME" ); post.getDetails().setCreatedOn( new Date() ); post.setTitle( "title" ); s.persist( post ); } ); }
Source:
public CreateAccountResponse doSendInvite(String accountEmail, String currentUserEmail, String instructorName) { M_log.debug("Friend doSendInvite() called"); CreateAccountResponse response = CreateAccountResponse.RUNTIME_PROBLEM; int rv = 0; try { HashMap<String, String> map = new HashMap<String,String>(); map.put(INSTRUCTOR_NAME_TAG, instructorName); map.put(CONTACT_EMAIL_TAG, contactEmail); emailMessage = Utils.readFile(friendEmailFile, StandardCharsets.UTF_8); emailMessage = Utils.replacePlaceHolders(emailMessage, map); Object[] params = new Object[]{contactEmail, referrerUrl, emailMessage, new String[]{accountEmail}, currentUserEmail}; Object[] results = (Object[]) Xclient.execute(SEND_INVITES_WS, params); if (results != null && results.length == 1) { rv = ((Integer) results[0]).intValue(); } } catch (Exception e) { M_log.warn("Friend doSendInvite(): email address=" + accountEmail + " " + e.getMessage()); } if(rv == -1){ response = CreateAccountResponse.INVALID_EMAIL; } if(rv == 0){ response = CreateAccountResponse.RUNTIME_PROBLEM; } if(rv == 1){ response = CreateAccountResponse.INVITATION_SUCCESSFULLY_SENT; } return response; }

Target:
public CreateAccountResponse doSendInvite(String accountEmail, String currentUserEmail, String instructorName) { M_log.debug("Friend doSendInvite() called"); CreateAccountResponse response = CreateAccountResponse.RUNTIME_PROBLEM; int rv = 0; try { HashMap<String, String> map = new HashMap<String,String>(); map.put(INSTRUCTOR_NAME_TAG, instructorName); map.put(CONTACT_EMAIL_TAG, contactEmail); emailMessage=Utils.readEmailTemplateAndReplacePlaceHolders(map,friendEmailFile); Object[] params = new Object[]{contactEmail, referrerUrl, emailMessage, new String[]{accountEmail}, currentUserEmail}; Object[] results = (Object[]) Xclient.execute(SEND_INVITES_WS, params); if (results != null && results.length == 1) { rv = ((Integer) results[0]).intValue(); } } catch (Exception e) { M_log.warn("Friend doSendInvite(): email address=" + accountEmail + " " + e.getMessage()); } if(rv == -1){ response = CreateAccountResponse.INVALID_EMAIL; } if(rv == 0){ response = CreateAccountResponse.RUNTIME_PROBLEM; } if(rv == 1){ response = CreateAccountResponse.INVITATION_SUCCESSFULLY_SENT; } return response; }
Source:
public void remove(String userName, UserStoreManager userStoreManager) throws IdentityException { Cache<String, UserIdentityClaimsDO> cache = getCache(); if (userName == null) { return; } if (userStoreManager instanceof org.wso2.carbon.user.core.UserStoreManager) { String caseInsensitiveUsername = ((org.wso2.carbon.user.core.UserStoreManager) userStoreManager) .getRealmConfiguration().getUserStoreProperty("CaseInsensitiveUsername"); if (!StringUtils.isBlank(caseInsensitiveUsername) && "true".equalsIgnoreCase(caseInsensitiveUsername.trim ())) { if (log.isDebugEnabled()) { log.debug("Case insensitive user store found. Changing username from : " + userName + " to : " + userName.toLowerCase()); } userName = userName.toLowerCase(); } } org.wso2.carbon.user.core.UserStoreManager store = (org.wso2.carbon.user.core.UserStoreManager) userStoreManager; String domainName = store.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME); cache.remove(domainName + CarbonContext.getThreadLocalCarbonContext().getTenantId() + userName); }

Target:
public void remove(String userName, UserStoreManager userStoreManager) throws IdentityException { Cache<String, UserIdentityClaimsDO> cache = getCache(); if (userName == null) { return; } if (userStoreManager instanceof org.wso2.carbon.user.core.UserStoreManager) { if (!IdentityUtil.isUserStoreCaseSensitive((org.wso2.carbon.user.core.UserStoreManager) userStoreManager)) { if (log.isDebugEnabled()) { log.debug("Case insensitive user store found. Changing username from : " + userName + " to : " + userName.toLowerCase()); } userName = userName.toLowerCase(); } } org.wso2.carbon.user.core.UserStoreManager store = (org.wso2.carbon.user.core.UserStoreManager) userStoreManager; String domainName = store.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig .PROPERTY_DOMAIN_NAME); cache.remove(domainName + CarbonContext.getThreadLocalCarbonContext().getTenantId() + userName); }
Source:
private SortedSet<ActionParameterRequest> buildActionParameters(FormSchemaJson form) { SortedSet<ActionParameterRequest> parameters = new TreeSet<>(); int order = 0; String displayName; for (FormSchemaQuestionJson question : form.getQuestions()) { ActionParameterRequestBuilder builder = new ActionParameterRequestBuilder(); displayName = ("").equals(question.getQuestionLabel()) ? question.getQuestionValue() : question.getQuestionLabel(); if (displayName.length() > MAX_LABEL_LENGHT) { displayName = displayName.substring(0, MAX_LABEL_LENGHT); } builder.setDisplayName(displayName) .setKey(question.getQuestionValue()) .setOrder(order++); if (question.getOptions() != null && !question.getOptions().isEmpty()) { builder.setType(ParameterType.SELECT.getValue()); builder.setOptions(convertCommcareoptionsToTaskActionOptions(question.getOptions())); } else { builder.setType(ParameterType.UNICODE.getValue()); } parameters.add(builder.createActionParameterRequest()); } return parameters; }

Target:
private SortedSet<ActionParameterRequest> buildActionParameters(FormSchemaJson form) { SortedSet<ActionParameterRequest> parameters = new TreeSet<>(); int order = 0; for (FormSchemaQuestionJson question : form.getQuestions()) { ActionParameterRequestBuilder builder = new ActionParameterRequestBuilder(); String displayName = StringUtils.isBlank(question.getQuestionLabel()) ? question.getQuestionValue() : question.getQuestionLabel(); if (displayName.length() > MAX_LABEL_LENGTH) { displayName = displayName.substring(0, MAX_LABEL_LENGTH); } builder.setDisplayName(displayName) .setKey(question.getQuestionValue()) .setOrder(order++); if (question.getOptions() != null && !question.getOptions().isEmpty()) { builder.setType(ParameterType.SELECT.getValue()); builder.setOptions(convertCommcareoptionsToTaskActionOptions(question.getOptions())); } else { builder.setType(ParameterType.UNICODE.getValue()); } parameters.add(builder.createActionParameterRequest()); } return parameters; }
Source:
public void panic(String reason) { LOG.error("PANICKING: {}", reason); }

Target:
public void panic(String reason) { panic(reason, new Throwable("Mock Panicker")); }
Source:
public static FirstWant fromLine(String line) { String wantLine; Set<String> options; if (line.length() > 45) { final HashSet<String> opts = new HashSet<>(); String opt = line.substring(45); if (opt.startsWith(" ")) { opt = opt.substring(1); } for (String c : opt.split(" ")) { opts.add(c); } wantLine = line.substring(0, 45); options = Collections.unmodifiableSet(opts); } else { wantLine = line; options = Collections.emptySet(); } return new FirstWant(wantLine, options); }

Target:
public static FirstWant fromLine(String line) { String wantLine; Set<String> capabilities; if (line.length() > 45) { final HashSet<String> opts = new HashSet<>(); String opt = line.substring(45); if (opt.startsWith(" ")) { opt = opt.substring(1); } for (String c : opt.split(" ")) { opts.add(c); } wantLine = line.substring(0, 45); capabilities = Collections.unmodifiableSet(opts); } else { wantLine = line; capabilities = Collections.emptySet(); } return new FirstWant(wantLine, capabilities); }
Source:
public LuceneHdfsDirectory(Path path, FileSystem fs) { this.fs = Preconditions.checkNotNull(fs); dir = path; index_input_list = new ArrayList<HDFSIndexInput>(); }

Target:
public LuceneHdfsDirectory(Path path, FileSystem fs) { this.fs = Preconditions.checkNotNull(fs); dir = path; }
Source:
public static Collection<Converter<?, ?>> getConvertersToRegister() { List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>(); boolean useISOStringConverterForDate = Boolean.parseBoolean( System.getProperty("org.springframework.data.couchbase.useISOStringConverterForDate", "false")); if (useISOStringConverterForDate) { converters.add(DateToStringConverter.INSTANCE); converters.add(StringToDateConverter.INSTANCE); } else { converters.add(DateToLongConverter.INSTANCE); converters.add(NumberToDateConverter.INSTANCE); } converters.add(CalendarToLongConverter.INSTANCE); converters.add(NumberToCalendarConverter.INSTANCE); if (JODA_TIME_IS_PRESENT) { converters.add(LocalDateToLongConverter.INSTANCE); converters.add(LocalDateTimeToLongConverter.INSTANCE); converters.add(DateTimeToLongConverter.INSTANCE); converters.add(DateMidnightToLongConverter.INSTANCE); converters.add(NumberToLocalDateConverter.INSTANCE); converters.add(NumberToLocalDateTimeConverter.INSTANCE); converters.add(NumberToDateTimeConverter.INSTANCE); converters.add(NumberToDateMidnightConverter.INSTANCE); } return converters; }

Target:
public static Collection<Converter<?, ?>> getConvertersToRegister() { List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>(); boolean useISOStringConverterForDate = Boolean.parseBoolean( System.getProperty("org.springframework.data.couchbase.useISOStringConverterForDate", "false")); if (useISOStringConverterForDate) { converters.add(DateToStringConverter.INSTANCE); } else { converters.add(DateToLongConverter.INSTANCE); } converters.add(SerializedObjectToDateConverter.INSTANCE); converters.add(CalendarToLongConverter.INSTANCE); converters.add(NumberToCalendarConverter.INSTANCE); if (JODA_TIME_IS_PRESENT) { converters.add(LocalDateToLongConverter.INSTANCE); converters.add(LocalDateTimeToLongConverter.INSTANCE); converters.add(DateTimeToLongConverter.INSTANCE); converters.add(DateMidnightToLongConverter.INSTANCE); converters.add(NumberToLocalDateConverter.INSTANCE); converters.add(NumberToLocalDateTimeConverter.INSTANCE); converters.add(NumberToDateTimeConverter.INSTANCE); converters.add(NumberToDateMidnightConverter.INSTANCE); } return converters; }
Source:
public String createGist(final String title, final String extension, final String gist, final GitHubCredentials credentials) throws GitHubServiceException, IOException { PostMethod method = null; try { method = new PostMethod(gistPostURL); final NameValuePair name = new NameValuePair("file_name[gistfile1]", title); final NameValuePair ext = new NameValuePair("file_ext[gistfile1]", extension); final NameValuePair content = new NameValuePair("file_contents[gistfile1]", gist); final NameValuePair login = new NameValuePair("login", credentials.getUsername()); final NameValuePair token = new NameValuePair("token", credentials.getApiToken()); method.addParameters(new NameValuePair[] { name, ext, content, login, token }); executeMethod(method); if (LOG.isDebugEnabled()) { LOG.debug("Response: " + method.getResponseBodyAsString()); LOG.debug("URL: " + method.getURI()); } return method.getResponseHeader("Location").getValue(); } catch (GitHubServiceException e) { throw e; } catch (final RuntimeException runTimeException) { throw runTimeException; } catch (final Exception e) { throw new GitHubServiceException(e); } finally { if (method != null) { method.releaseConnection(); } } }

Target:
public String createGist(final String title, final String extension, final String gist, final GitHubCredentials credentials) throws GitHubServiceException, IOException { PostMethod method = null; try { setCredentials(credentials); method = new PostMethod(gistPostURL); final NameValuePair name = new NameValuePair("file_name[gistfile1]", title); final NameValuePair ext = new NameValuePair("file_ext[gistfile1]", extension); final NameValuePair content = new NameValuePair("file_contents[gistfile1]", gist); method.addParameters(new NameValuePair[] { name, ext, content }); executeMethod(method); return method.getResponseHeader("Location").getValue(); } catch (GitHubServiceException e) { throw e; } catch (final RuntimeException runTimeException) { throw runTimeException; } catch (final Exception e) { throw new GitHubServiceException(e); } finally { if (method != null) { method.releaseConnection(); } } }
Source:
public void init() { DocumentModel domain = session.createDocumentModel("/", "domain", "Domain"); session.createDocument(domain); doc = session.createDocumentModel("/domain", "test", "File"); doc = session.createDocument(doc); domain = session.createDocumentModel("/", "Folder", "Folder"); domain = session.createDocument(domain); DocumentModel fileDoc = session.createDocumentModel(domain.getPathAsString(), "File", "File"); session.createDocument(fileDoc); DocumentModel container = session.createDocumentModel(domain.getPathAsString(), "CommentContainer", "Folder"); session.createDocument(container); session.save(); createUser(AUTHOR_OF_COMMENT); }

Target:
public void init() { DocumentModel domain = session.createDocumentModel("/", "Folder", "Folder"); domain = session.createDocument(domain); DocumentModel doc = session.createDocumentModel(domain.getPathAsString(), "File", "File"); session.createDocument(doc); DocumentModel container = session.createDocumentModel(domain.getPathAsString(), "CommentContainer", "Folder"); session.createDocument(container); session.save(); createUser(AUTHOR_OF_COMMENT); }
Source:
public List<String> getObjectIdsByAnalysisId(@NonNull String programId, @NonNull String analysisId) { val url = new URL(serverUrl + "/studies/" + programId + "/analysis/" + analysisId + "/files"); log.error("Fetching analysis files from url '{}'", url); val result = MAPPER.readValue(url, ArrayNode.class); val objectIds=new ArrayList<String>(); log.error("Got result {}",result); result.forEach(x-> objectIds.add(x.path("objectId").textValue())); return objectIds; }

Target:
public List<String> getObjectIdsByAnalysisId(@NonNull String programId, @NonNull String analysisId) { val url = new URL(serverUrl + "/studies/" + programId + "/analysis/" + analysisId + "/files"); log.debug("Fetching analysis files from url '{}'", url); return Stream.of(MAPPER.readValue(url, ArrayNode.class)). peek(r -> log.debug("Got result {}", r)). map(x -> x.path("objectId")). map(JsonNode::textValue). collect(toImmutableList()); }
Source:
public void onActivity() { long currentTime = System.currentTimeMillis(); if (currentTime < (lastUpdateTime + threshold)) { activeDuringThreshold.set(true); } else { Thread activityRequestThread = new Thread(this::notifyActivity); activityRequestThread.setDaemon(true); activityRequestThread.start(); lastUpdateTime = currentTime; } }

Target:
public void onActivity() { long currentTime = System.currentTimeMillis(); if (currentTime < (lastUpdateTime + threshold)) { activeDuringThreshold.set(true); } else { Thread activityRequestThread = new Thread(this::notifyActivity); activityRequestThread.setName("WorkspaceActivityRequestThread"); activityRequestThread.setDaemon(true); activityRequestThread.start(); lastUpdateTime = currentTime; } }
Source:
public static FirstWant fromLine(String line) { String realLine; Set<String> options; if (line.length() > 45) { final HashSet<String> opts = new HashSet<>(); String opt = line.substring(45); if (opt.startsWith(" ")) opt = opt.substring(1); for (String c : opt.split(" ")) opts.add(c); realLine = line.substring(0, 45); options = Collections.unmodifiableSet(opts); } else { realLine = line; options = Collections.emptySet(); } return new FirstWant(realLine, options); }

Target:
public static FirstWant fromLine(String line) { String wantLine; Set<String> options; if (line.length() > 45) { final HashSet<String> opts = new HashSet<>(); String opt = line.substring(45); if (opt.startsWith(" ")) { opt = opt.substring(1); } for (String c : opt.split(" ")) { opts.add(c); } wantLine = line.substring(0, 45); options = Collections.unmodifiableSet(opts); } else { wantLine = line; options = Collections.emptySet(); } return new FirstWant(wantLine, options); }
Source:
public AdapterFactory createAdapterFactory() { final ComposedAdapterFactory factory = new ComposedAdapterFactory(); for (final IDiagramTypeDescriptor diagramTypeDescriptor : DiagramTypeDescriptorRegistry.getInstance().getAllDiagramTypeDescriptors()) { AdapterFactory aFactory = diagramTypeDescriptor.getDiagramDescriptionProvider().getAdapterFactory(); if (aFactory != null) { factory.addAdapterFactory(aFactory); } } factory.addAdapterFactory(new DescriptionItemProviderAdapterFactory()); factory.addAdapterFactory(new DiagramItemProviderAdapterFactory()); factory.addAdapterFactory(new StyleItemProviderAdapterFactory()); factory.addAdapterFactory(new ToolItemProviderAdapterFactory()); factory.addAdapterFactory(new FilterItemProviderAdapterFactory()); factory.addAdapterFactory(new ValidationItemProviderAdapterFactory()); factory.addAdapterFactory(new ConcernItemProviderAdapterFactory()); return factory; }

Target:
public AdapterFactory createAdapterFactory() { final ComposedAdapterFactory factory = new ComposedAdapterFactory(); for (final IDiagramTypeDescriptor diagramTypeDescriptor : DiagramTypeDescriptorRegistry.getInstance().getAllDiagramTypeDescriptors()) { AdapterFactory aFactory = diagramTypeDescriptor.getDiagramDescriptionProvider().getAdapterFactory(); if (aFactory != null) { factory.addAdapterFactory(aFactory); } } factory.addAdapterFactory(new DescriptionItemProviderAdapterFactory()); factory.addAdapterFactory(new DiagramItemProviderAdapterFactory()); factory.addAdapterFactory(new StyleItemProviderAdapterFactory()); factory.addAdapterFactory(new ToolItemProviderAdapterFactory()); factory.addAdapterFactory(new FilterItemProviderAdapterFactory()); factory.addAdapterFactory(new ConcernItemProviderAdapterFactory()); return factory; }
Source:
public void testConcurrentConfigurationReloads() throws InterruptedException, ExecutionException { final ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT); List<Future<?>> futures = new LinkedList<>(); for (int i = 0; i < TASK_COUNT; i++) { futures.add(threadPool.submit(() -> { Response put = target("configuration") .path("projectsEnabled") .request() .put(Entity.text("true")); Assert.assertEquals(204, put.getStatus()); assertTestedProjects(); })); } threadPool.shutdown(); threadPool.awaitTermination(100, TimeUnit.MINUTES); for (Future<?> future : futures) { future.get(); } }

Target:
public void testConcurrentConfigurationReloads() throws InterruptedException, ExecutionException { final ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT); List<Future<?>> futures = new LinkedList<>(); for (int i = 0; i < TASK_COUNT; i++) { futures.add(threadPool.submit(() -> { Response put = target("configuration") .path("projectsEnabled") .request() .put(Entity.text("true")); Assert.assertEquals(204, put.getStatus()); assertTestedProjects(); })); } threadPool.shutdown(); threadPool.awaitTermination(1, TimeUnit.MINUTES); for (Future<?> future : futures) { future.get(); } }
Source:
public int readBytesOrFewer(final byte[] buffer, final int offset, final int length) { if (isWriting) { throw new IllegalStateException("Calling read method on BinaryCodec open for write."); } try { if (length == 0) return 0; else return inputStream.read(buffer, offset, length); } catch (IOException e) { throw new RuntimeIOException(constructErrorMessage("Read error"), e); } }

Target:
public int readBytesOrFewer(final byte[] buffer, final int offset, final int length) { if (isWriting) { throw new IllegalStateException("Calling read method on BinaryCodec open for write."); } try { return (length == 0) ? 0 : inputStream.read(buffer, offset, length); } catch (IOException e) { throw new RuntimeIOException(constructErrorMessage("Read error"), e); } }
Source:
private static <R extends BaseResource> BaseResource getParent(R model, Class<?> parentType) { for (Method method : getRelevantMethods(model.getClass())) { try { Object potentialParent = method.invoke(model); if (potentialParent != null && parentType.isAssignableFrom(potentialParent.getClass())) { return (BaseResource)potentialParent; } } catch (Exception e) { continue; } } return null; }

Target:
private static <R extends BaseResource> BaseResource getParent(R model, Class<?> parentType) { for (Method method : getRelevantMethods(model.getClass())) { try { Object potentialParent = method.invoke(model); if (potentialParent != null && parentType.isAssignableFrom(potentialParent.getClass())) { return (BaseResource)potentialParent; } } catch (Exception e) { log.error("Error invoking method when adding links to an API entity", e); continue; } } return null; }
Source:
private Boolean evaluateBoolean(BinaryOperator statement, Boolean leftBoolean, Boolean rightBoolean) { switch(statement.getOperator()) { case and: return leftBoolean & rightBoolean; case or: if(leftBoolean == null && rightBoolean == null) { return null; } else if (leftBoolean == null) { return rightBoolean; } else if (rightBoolean == null) { return leftBoolean; } return leftBoolean | rightBoolean; case xor: return leftBoolean ^ rightBoolean; default: throw new IllegalArgumentException("Not a boolean operator: " + statement.getOperator()); } }

Target:
private Boolean evaluateBoolean(BinaryOperator statement, Boolean leftBoolean, Boolean rightBoolean) { switch(statement.getOperator()) { case and: return leftBoolean & rightBoolean; case or: if(leftBoolean == null && rightBoolean == null) { return null; } else if (leftBoolean == null) { if(rightBoolean) { return rightBoolean; } return null; } else if (rightBoolean == null) { if(leftBoolean) { return leftBoolean; } return null; } return leftBoolean | rightBoolean; case xor: return leftBoolean ^ rightBoolean; default: throw new IllegalArgumentException("Not a boolean operator: " + statement.getOperator()); } }
Source:
public List<String> getSections() { List<String> sectionNames = new ArrayList<>(); for (String section : bundle.sectionsInCourse()) { if (!section.equals(Const.DEFAULT_SECTION)) { sectionNames.add(section); } } Collections.sort(sectionNames); return sectionNames; }

Target:
public List<String> getSections() { return sections; }
Source:
private List<String> getFilterInFromFormData(JSONObject formData) { String stringIn = formData.optString("filterIn"); List<String> filter = null; String[] arrayIn = null; if (!stringIn.equals("null")) { filter = new ArrayList<>(); arrayIn = stringIn.split(" "); filter = Arrays.asList(arrayIn); } return filter; }

Target:
private List<String> getFilterInFromFormData(JSONObject formData) { String stringIn = formData.optString("filterIn", null); List<String> filter = null; String[] arrayIn = null; if (stringIn != null && !stringIn.equals("null")) { filter = new ArrayList<>(); arrayIn = stringIn.split("\\s+"); filter = Arrays.asList(arrayIn); } return filter; }
Source:
public TaskStatus run(final TaskToolbox toolbox) throws Exception { final boolean determineIntervals = !ingestionSchema.getDataSchema() .getGranularitySpec() .bucketIntervals() .isPresent(); final FirehoseFactory delegateFirehoseFactory = ingestionSchema.getIOConfig().getFirehoseFactory(); if (delegateFirehoseFactory instanceof IngestSegmentFirehoseFactory) { ((IngestSegmentFirehoseFactory) delegateFirehoseFactory).setTaskToolbox(toolbox); } final FirehoseFactory firehoseFactory = delegateFirehoseFactory; final Map<Interval, List<ShardSpec>> shardSpecs = determineShardSpecs(toolbox, firehoseFactory); final String version; final DataSchema dataSchema; if (determineIntervals) { Interval interval = JodaUtils.umbrellaInterval(shardSpecs.keySet()); TaskLock lock = toolbox.getTaskActionClient().submit(new LockAcquireAction(interval)); version = lock.getVersion(); dataSchema = ingestionSchema.getDataSchema().withGranularitySpec( ingestionSchema.getDataSchema() .getGranularitySpec() .withIntervals( JodaUtils.condenseIntervals( shardSpecs.keySet() ) ) ); } else { version = Iterables.getOnlyElement(getTaskLocks(toolbox)).getVersion(); dataSchema = ingestionSchema.getDataSchema(); } if (generateAndPublishSegments(toolbox, dataSchema, shardSpecs, version, firehoseFactory)) { return TaskStatus.success(getId()); } else { return TaskStatus.failure(getId()); } }

Target:
public TaskStatus run(final TaskToolbox toolbox) throws Exception { final boolean determineIntervals = !ingestionSchema.getDataSchema() .getGranularitySpec() .bucketIntervals() .isPresent(); final FirehoseFactory firehoseFactory = ingestionSchema.getIOConfig().getFirehoseFactory(); if (firehoseFactory instanceof IngestSegmentFirehoseFactory) { ((IngestSegmentFirehoseFactory) firehoseFactory).setTaskToolbox(toolbox); } final File firehoseTempDir = toolbox.getFirehoseTemporaryDir(); FileUtils.forceMkdir(firehoseTempDir); final Map<Interval, List<ShardSpec>> shardSpecs = determineShardSpecs(toolbox, firehoseFactory, firehoseTempDir); final String version; final DataSchema dataSchema; if (determineIntervals) { Interval interval = JodaUtils.umbrellaInterval(shardSpecs.keySet()); TaskLock lock = toolbox.getTaskActionClient().submit(new LockAcquireAction(interval)); version = lock.getVersion(); dataSchema = ingestionSchema.getDataSchema().withGranularitySpec( ingestionSchema.getDataSchema() .getGranularitySpec() .withIntervals( JodaUtils.condenseIntervals( shardSpecs.keySet() ) ) ); } else { version = Iterables.getOnlyElement(getTaskLocks(toolbox)).getVersion(); dataSchema = ingestionSchema.getDataSchema(); } if (generateAndPublishSegments(toolbox, dataSchema, shardSpecs, version, firehoseFactory, firehoseTempDir)) { return TaskStatus.success(getId()); } else { return TaskStatus.failure(getId()); } }
Source:
public static Set<IPluginModelBase> parsePlugins(ILaunchConfiguration configuration, String attribute) throws CoreException { HashSet<IPluginModelBase> set = new HashSet<>(); List<String> entries = configuration.getAttribute(attribute, (List<String>) null); if (entries != null) { Map<String, IPluginModelBase> unmatchedEntries = new HashMap<>(); for (int i = 0; i < entries.size(); i++) { String token = entries.get(i); int index = token.indexOf('@'); if (index < 0) { token = token.concat("@default:default"); entries.set(i, token); index = token.indexOf('@'); } String idVersion = token.substring(0, index); int versionIndex = token.indexOf(BundleLauncherHelper.VERSION_SEPARATOR); String id = (versionIndex > 0) ? idVersion.substring(0, versionIndex) : idVersion; String version = (versionIndex > 0) ? idVersion.substring(versionIndex + 1) : null; ModelEntry entry = PluginRegistry.findEntry(id); if (entry != null) { IPluginModelBase matchingModels[] = attribute.equals(IPDELauncherConstants.SELECTED_TARGET_PLUGIN_LIST) ? entry.getExternalModels() : entry.getWorkspaceModels(); for (IPluginModelBase matchingModel : matchingModels) { if (matchingModel.isEnabled()) { if (version == null || matchingModel.getPluginBase().getVersion().equals(version)) { set.add(matchingModel); } else if (matchingModels.length == 1) { if (unmatchedEntries.remove(id) == null) { unmatchedEntries.put(id, matchingModel); } } } } } } set.addAll(unmatchedEntries.values()); } return set; }

Target:
public static Set<IPluginModelBase> parsePlugins(ILaunchConfiguration configuration, String attribute) throws CoreException { HashSet<IPluginModelBase> set = new HashSet<>(); Map<String, IPluginModelBase> unmatchedEntries = new HashMap<>(); List<String> entries = configuration.getAttribute(attribute, Collections.emptyList()); for (String token : entries) { int index = token.indexOf('@'); if (index < 0) { token = token.concat("@default:default"); index = token.indexOf('@'); } String idVersion = token.substring(0, index); int versionIndex = token.indexOf(BundleLauncherHelper.VERSION_SEPARATOR); String id = (versionIndex > 0) ? idVersion.substring(0, versionIndex) : idVersion; String version = (versionIndex > 0) ? idVersion.substring(versionIndex + 1) : null; ModelEntry entry = PluginRegistry.findEntry(id); if (entry != null) { IPluginModelBase matchingModels[] = attribute.equals(IPDELauncherConstants.SELECTED_TARGET_BUNDLES) ? entry.getExternalModels() : entry.getWorkspaceModels(); for (IPluginModelBase matchingModel : matchingModels) { if (matchingModel.isEnabled()) { if (version == null || matchingModel.getPluginBase().getVersion().equals(version)) { set.add(matchingModel); } else if (matchingModels.length == 1) { if (unmatchedEntries.remove(id) == null) { unmatchedEntries.put(id, matchingModel); } } } } } } set.addAll(unmatchedEntries.values()); return set; }
Source:
private T waitForCompletionAndThrowIfUploadFailed() throws IOException { try { return uploadOperation.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); uploadOperation.cancel(true); IOException exception = new ClosedByInterruptException(); exception.addSuppressed(e); throw exception; } catch (ExecutionException e) { if (ignoreConditionFailureForUpload(new IOException(e.getCause()))) { logger.atWarning().withCause(e.getCause()).log( "412 Precondition failure was ignored for resource %s.", getResourceString()); return null; } else if (e.getCause() instanceof Error) { throw (Error) e.getCause(); } else { throw new IOException( String.format("Upload failed for '%s'", getResourceString()), e.getCause()); } } }

Target:
private T waitForCompletionAndThrowIfUploadFailed() throws IOException { try { return uploadOperation.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); uploadOperation.cancel(true); IOException exception = new ClosedByInterruptException(); exception.addSuppressed(e); throw exception; } catch (ExecutionException e) { if (e.getCause() instanceof Error) { throw (Error) e.getCause(); } throw new IOException( String.format("Upload failed for '%s'", getResourceString()), e.getCause()); } }
Source:
public void nodeExplicitIndexDrop( String indexName ) throws ExplicitIndexNotFoundKernelException { ktx.assertOpen(); allStoreHolder.explicitIndexTxState().nodeChanges( indexName ).drop(); allStoreHolder.explicitIndexTxState().deleteIndex( IndexEntityType.Node, indexName ); }

Target:
public void nodeExplicitIndexDrop( String indexName ) throws ExplicitIndexNotFoundKernelException { ktx.assertOpen(); ExplicitIndexTransactionState txState = allStoreHolder.explicitIndexTxState(); txState.nodeChanges( indexName ).drop(); txState.deleteIndex( IndexEntityType.Node, indexName ); }
Source:
void setSymbols(List<SymbolStyleSearchResult> symbols) { if (symbols.size() > 0) { mSymbols = symbols; setChanged(); notifyObservers(); } }

Target:
void setSymbols(List<SymbolStyleSearchResult> symbols) { if (!symbols.isEmpty()) { mSymbols = symbols; setChanged(); notifyObservers(); } }
Source:
public ItemStreamWriter<VariantWrapper> vepAnnotationFileWriter(AnnotationParameters annotationParameters, ChunkSizeParameters chunkSizeParameters) { long timeoutInSeconds = 600L; return new VepAnnotationFileWriter(annotationParameters, chunkSizeParameters.getChunkSize(), timeoutInSeconds); }

Target:
public ItemWriter<VariantWrapper> vepAnnotationFileWriter(AnnotationParameters annotationParameters, ChunkSizeParameters chunkSizeParameters) { return new VepAnnotationFileWriter(annotationParameters, chunkSizeParameters.getChunkSize(), annotationParameters.getTimeout()); }
Source:
public void setUp() throws Exception { accountsPayableService = Mockito.mock(AccountsPayableService.class); Mockito.when(accountsPayableService.getExpiredOrClosedAccountList(creditMemoDocument)).thenReturn(new HashMap<>()); dataDictionaryService = Mockito.mock(DataDictionaryService.class); Mockito.when(dataDictionaryService.getAttributeMaxLength(DocumentHeader.class, KRADPropertyConstants.DOCUMENT_DESCRIPTION)).thenReturn(200); dateTimeService = new DateTimeServiceImpl(); documentService = buildMockDocumentService(); noteService = Mockito.mock(NoteService.class); purapService = Mockito.mock(PurapService.class); vendorService = new MockVendorServiceImpl(); creditMemoServiceImpl = PowerMockito.spy(new TestCuCreditMemoServiceImpl()); PowerMockito.doNothing().when(creditMemoServiceImpl, "reIndexDocument", Mockito.any()); creditMemoServiceImpl.setDocumentService(documentService); creditMemoServiceImpl.setNoteService(noteService); creditMemoServiceImpl.setPurapService(purapService); creditMemoServiceImpl.setAccountsPayableService(accountsPayableService); creditMemoServiceImpl.setVendorService(vendorService); creditMemoServiceImpl.setDataDictionaryService(dataDictionaryService); creditMemoDocument = setupVendorCreditMemoDocument(); mo14Person = MockPersonUtil.createMockPerson(UserNameFixture.mo14); mo14Session = MockPersonUtil.createMockUserSession(mo14Person); GlobalVariables.setUserSession(mo14Session); }

Target:
public void setUp() throws Exception { accountsPayableService = Mockito.mock(AccountsPayableService.class); Mockito.when(accountsPayableService.getExpiredOrClosedAccountList(Mockito.any())).thenReturn(new HashMap<>()); dataDictionaryService = Mockito.mock(DataDictionaryService.class); Mockito.when(dataDictionaryService.getAttributeMaxLength(DocumentHeader.class, KRADPropertyConstants.DOCUMENT_DESCRIPTION)).thenReturn(200); dateTimeService = new DateTimeServiceImpl(); documentService = buildMockDocumentService(); noteService = Mockito.mock(NoteService.class); purapService = Mockito.mock(PurapService.class); vendorService = new MockVendorServiceImpl(); creditMemoServiceImpl = PowerMockito.spy(new TestCuCreditMemoServiceImpl()); PowerMockito.doNothing().when(creditMemoServiceImpl, "reIndexDocument", Mockito.any()); creditMemoServiceImpl.setDocumentService(documentService); creditMemoServiceImpl.setNoteService(noteService); creditMemoServiceImpl.setPurapService(purapService); creditMemoServiceImpl.setAccountsPayableService(accountsPayableService); creditMemoServiceImpl.setVendorService(vendorService); creditMemoServiceImpl.setDataDictionaryService(dataDictionaryService); creditMemoDocument = setupVendorCreditMemoDocument(); mo14Person = MockPersonUtil.createMockPerson(UserNameFixture.mo14); mo14Session = MockPersonUtil.createMockUserSession(mo14Person); GlobalVariables.setUserSession(mo14Session); }
Source:
static SSLFactory getNewInstance(SSLConfig sslConfig) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { return Utils.getObj(sslConfig.sslFactory, sslConfig); }

Target:
static SSLFactory getNewInstance(SSLConfig sslConfig) throws Exception { return Utils.getObj(sslConfig.sslFactory, sslConfig); }
Source:
public CommandApi endDate(String endDate) { parameters.put("end_date", String.valueOf(endDate)); return this; }

Target:
public CommandApi endDate(String endDate) { parameters.put("end_date", endDate); return this; }
Source:
private void assertValidJson(String snippet) { DU_SCHEMA.validate(new JSONObject(snippet)); assertTrue(true); }

Target:
private void assertValidJson(String snippet) { try { DU_SCHEMA.validate(new JSONObject(snippet)); assertTrue(true); } catch (ValidationException e) { fail("snippet <" + snippet + "> did not pass validation: " + e.getMessage()); } }
Source:
static Optional<String> getErrorMessageFromTask(String cluster, String taskArn, EcsClient client) { Optional<String> errorMessage; try { final Task task = client.getTask(cluster, taskArn); if (task.getContainers().size() > 0) { errorMessage = Optional.of(task.getContainers().get(0).getReason()); } else { errorMessage = Optional.of("No container information"); } } catch (TaskSetNotFoundException e) { errorMessage = Optional.of(e.getErrorMessage()); } catch (RuntimeException re) { errorMessage = Optional.of(re.getMessage()); } return errorMessage; }

Target:
static Optional<String> getErrorMessageFromTask(String cluster, String taskArn, EcsClient client) { Optional<String> errorMessage = Optional.absent(); try { final Task task = client.getTask(cluster, taskArn); final List<String> reasons = task.getContainers().stream() .map(c -> c.getReason()) .filter(r -> !Strings.isNullOrEmpty(r)) .collect(Collectors.toList()); if (reasons.size() > 0) { errorMessage = Optional.of(String.join(",", reasons)); } else { errorMessage = Optional.of("No container information"); } } catch (TaskSetNotFoundException e) { errorMessage = Optional.fromNullable(e.getErrorMessage()); } return errorMessage; }
Source:
protected ChannelPool createChannelPool(final String hostString, int count) throws IOException { ChannelPool.ChannelFactory channelFactory = new ChannelPool.ChannelFactory() { @Override public ManagedChannel create() throws IOException { return createNettyChannel(hostString, options.build(), clientInterceptors); } }; return new ChannelPool(channelFactory, count); }

Target:
protected ManagedChannel createChannelPool(final String hostString, int count) throws IOException { ChannelPool.ChannelFactory channelFactory = new ChannelPool.ChannelFactory() { @Override public ManagedChannel create() throws IOException { return createNettyChannel(hostString, options.build(), clientInterceptors); } }; return createChannelPool(channelFactory, count); }
Source:
public Future<String> loadNetworkWithPopularTerms() throws QStoreStorageException { String query = env.getProperty("allNetworks"); String queryID = env.getProperty("allNetworks_id"); executeQuery(query, queryID); long delay = Long.parseLong(env.getProperty("qstore.rest.delay")); String res = getQueryResult(queryID); while (res != null && res.contains("<message>") && res.contains(RUNNING.name())) { try { Thread.sleep(delay); res = getQueryResult(queryID); } catch (InterruptedException e) { throw new QStoreStorageException(e); } } return new AsyncResult<String>(res); }

Target:
public Future<String> loadNetworkWithPopularTerms() throws AsyncExecutionException { String query = env.getProperty("allNetworks"); ResponseEntity<String> response = executeQuery(query); HttpStatus status = response.getStatusCode(); String resbody = response.getBody(); if (status == HttpStatus.BAD_REQUEST || status == HttpStatus.INTERNAL_SERVER_ERROR) { String errorMessage = resbody.substring(resbody.indexOf("<message>"), resbody.indexOf("</message>")); throw new AsyncExecutionException(errorMessage); } QStoreAsyncResult asyncResult = getResponseFromXML(resbody); String pollURL = asyncResult.getPollurl(); long delay = Long.parseLong(env.getProperty("qstore.rest.delay")); String res = getQueryResult(pollURL); asyncResult = getResponseFromXML(res); while (asyncResult != null && asyncResult.getQueryStatus().equals(RUNNING.name())) { try { Thread.sleep(delay); res = getQueryResult(pollURL); asyncResult = getResponseFromXML(res); } catch (InterruptedException e) { throw new AsyncExecutionException(e); } } return new AsyncResult<String>(asyncResult.getResult()); }
Source:
public GroupWait(TimePeriod timeout, WaitWrapper... waitings) { remainingTimeout = timeout; if (waitings == null || waitings.length == 0) { throw new IllegalArgumentException("There are no waiting to wait for, pass one or more waitings " + "as a constructor arguments to start waiting"); } for (WaitWrapper waitWrapper: waitings) { if (WaitType.WHILE.equals(waitWrapper.getWaitType())) { long startTimeOfWait = System.currentTimeMillis(); new WaitWhile(waitWrapper.getWaitCondition(), remainingTimeout, waitWrapper.throwRuntimeException()); remainingTimeout = getRemainingTimeoutPeriod(remainingTimeout, startTimeOfWait); } else { if (WaitType.UNTIL.equals(waitWrapper.getWaitType())) { long startTimeOfWait = System.currentTimeMillis(); new WaitUntil(waitWrapper.getWaitCondition(), remainingTimeout, waitWrapper.throwRuntimeException()); remainingTimeout = getRemainingTimeoutPeriod(remainingTimeout, startTimeOfWait); } } } }

Target:
public GroupWait(TimePeriod timeout, WaitWrapper... waitings) { remainingTimeout = timeout; if (waitings == null || waitings.length == 0) { throw new IllegalArgumentException("There are no waiting to wait for, pass one or more waitings " + "as a constructor arguments to start waiting"); } for (WaitWrapper waitWrapper: waitings) { long startTimeOfWait = System.currentTimeMillis(); if (WaitType.WHILE.equals(waitWrapper.getWaitType())) { new WaitWhile(waitWrapper.getWaitCondition(), remainingTimeout, waitWrapper.throwRuntimeException()); } else if (WaitType.UNTIL.equals(waitWrapper.getWaitType())) { new WaitUntil(waitWrapper.getWaitCondition(), remainingTimeout, waitWrapper.throwRuntimeException()); } remainingTimeout = getRemainingTimeoutPeriod(remainingTimeout, startTimeOfWait); } }
Source:
public Session getSession() { Session session = null; if (sessionRef == null || sessionRef.get() == null) { URI sessionModelURI = getURI().trimFragment(); if (sessionResourceURI != null) { sessionModelURI = sessionResourceURI; } Session newSession = getSession(sessionModelURI); if (newSession != null) { session = newSession; this.sessionRef = new WeakReference<Session>(newSession); } } else { session = sessionRef.get(); } return session; }

Target:
public Session getSession() { Session session = sessionRef != null ? sessionRef.get() : null; if (session == null) { URI sessionModelURI = getURI().trimFragment(); if (sessionResourceURI != null) { sessionModelURI = sessionResourceURI; } session = getSession(sessionModelURI); if (session != null) { this.sessionRef = new WeakReference<Session>(session); } } return session; }
Source:
public void returnsExplicitCollections() throws IOException { JiraSession session = mock(JiraSession.class); JiraSite site = mock(JiraSite.class); when(site.getSession(null)).thenReturn(session); ExplicitIssueSelector jqlUpdaterIssueSelector = new ExplicitIssueSelector( Collections.singletonList(TEST_KEY)); Set<String> foundIssueIds = jqlUpdaterIssueSelector.findIssueIds(null, site, null); assertThat(foundIssueIds, hasSize(1)); assertThat(foundIssueIds.iterator().next(), equalTo(TEST_KEY)); }

Target:
public void returnsExplicitCollections() throws IOException { ExplicitIssueSelector jqlUpdaterIssueSelector = new ExplicitIssueSelector(Collections.singletonList(TEST_KEY)); Set<String> foundIssueIds = jqlUpdaterIssueSelector.findIssueIds(null, null, null); assertThat(foundIssueIds, hasSize(1)); assertThat(foundIssueIds.iterator().next(), equalTo(TEST_KEY)); }