auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public final Response listAvailableServices(@Context final HttpServletRequest request, @Context final HttpServletResponse response ) { try { final InitDataObject initData = new WebResource.InitBuilder(webResource) .requiredBackendUser(true) .requiredFrontendUser(false) .requestAndResponse(request, response) .rejectWhenNoUser(true) .init(); final User user = initData.getUser(); final List<ServiceIntegrationView> integrationViews = helper.getAvailableDescriptorViews(user); if(!integrationViews.isEmpty()){ return Response.ok(new ResponseEntityView(integrationViews)).build(); } throw new DoesNotExistException("Nope. No service integration is available to configure. Try uploading a file!"); } catch (Exception e) { Logger.error(this.getClass(), "Exception on listing available service integration descriptors.", e); return ResponseUtil.mapExceptionResponse(e); } }

Target:
public final Response listAvailableServices(@Context final HttpServletRequest request, @Context final HttpServletResponse response ) { try { final InitDataObject initData = new WebResource.InitBuilder(webResource) .requiredBackendUser(true) .requiredFrontendUser(false) .requestAndResponse(request, response) .rejectWhenNoUser(true) .init(); final User user = initData.getUser(); final List<ServiceIntegrationView> integrationViews = helper.getAvailableDescriptorViews(user); if(!integrationViews.isEmpty()){ return Response.ok(new ResponseEntityView(integrationViews)).build(); } throw new DoesNotExistException("No service integration is available to configure. Try uploading a file!"); } catch (Exception e) { Logger.error(this.getClass(), "Exception on listing all available service-integrations.", e); return ResponseUtil.mapExceptionResponse(e); } }
Source:
public Object getResponseValue() { return null; }

Target:
public Object getResponseValue() { throw new UnsupportedOperationException(); }
Source:
private void getRetriesFromSettings(Task task, Map<String, Object> params, Map<String, Object> metadata) { Map<String, String> taskRetries = new HashMap<>(); List<Integer> retryInterval = new ArrayList<>(); int numberOfRetries; try { InputStream retries = settings.getRawConfig(TASK_PROPERTIES_FILE_NAME); if(retries != null) { Properties props = new Properties(); props.load(retries); if (props != null) { for (Map.Entry<Object, Object> entry : props.entrySet()) { taskRetries.put((String) entry.getKey(), (String) entry.getValue()); retryInterval.add(0, Integer.valueOf(entry.getValue().toString())); } } numberOfRetries = taskRetries.size(); } else { numberOfRetries = 0; } if (retries != null) { retries.close(); } } catch (IOException e) { throw new MotechException("Error loading raw file config to properties", e); } setRetryParameters(task, metadata, params, retryInterval, numberOfRetries); }

Target:
private void getRetriesFromSettings(Task task, Map<String, Object> params, Map<String, Object> metadata) { List<Integer> retryInterval = new ArrayList<>(); int numberOfRetries; try (InputStream retries = settings.getRawConfig(TASK_PROPERTIES_FILE_NAME)){ if(retries != null) { Properties props = new Properties(); props.load(retries); for (Map.Entry<Object, Object> entry : props.entrySet()) { retryInterval.add(0, Integer.valueOf(entry.getValue().toString())); } numberOfRetries = retryInterval.size(); } else { numberOfRetries = 0; } } catch (IOException e) { throw new MotechException("Error loading raw file config to properties", e); } setRetryParameters(task, metadata, params, retryInterval, numberOfRetries); }
Source:
public boolean isFileResolverCachingEnabled() { return fileSystemOptions.isFileResolverCachingEnabled(); }

Target:
public boolean isFileResolverCachingEnabled() { if (fileSystemOptions == null) { return DEFAULT_FILE_CACHING_ENABLED; } return fileSystemOptions.isFileResolverCachingEnabled(); }
Source:
private Resource newResourceFrom(final ItemReference reference) { final Path path = Path.valueOf(reference.getPath()); switch (reference.getType()) { case "file": return resourceFactory.newFileImpl(path, urlModifier.modify(ps.getFileContentUrl(path)), this); case "folder": return resourceFactory.newFolderImpl(path, this); case "project": final Optional<ProjectConfigDto> config = findProjectConfigDto(path); if (config.isPresent()) { return resourceFactory.newProjectImpl(config.get(), this); } else { return resourceFactory.newFolderImpl(path, this); } default: throw new IllegalArgumentException("Failed to recognize resource type to create."); } }

Target:
private Resource newResourceFrom(final ItemReference reference) { final Path path = Path.valueOf(reference.getPath()); switch (reference.getType()) { case "file": final Link link = reference.getLink(GET_CONTENT_REL); return resourceFactory.newFileImpl(path, link.getHref(), this); case "folder": return resourceFactory.newFolderImpl(path, this); case "project": final Optional<ProjectConfigDto> config = findProjectConfigDto(path); if (config.isPresent()) { return resourceFactory.newProjectImpl(config.get(), this); } else { return resourceFactory.newFolderImpl(path, this); } default: throw new IllegalArgumentException("Failed to recognize resource type to create."); } }
Source:
public void shouldSaveCondition() throws DotSecurityException, DotDataException { final Role role = new RoleDataGen().nextPersisted(); final User user = new UserDataGen().roles(role).nextPersisted(); final Host host = new SiteDataGen().nextPersisted(); final Rule rule = new RuleDataGen().host(host).nextPersisted(); final ConditionGroup conditionGroup = new ConditionGroupDataGen().rule(rule).next(); this.addRulesPermission(role, host, true); rulesAPI.saveConditionGroup(conditionGroup, user, false); List<Rule> allRules = rulesAPI.getAllRules(user, false); checkCondition(user, conditionGroup, allRules); }

Target:
public void shouldSaveCondition() throws DotSecurityException, DotDataException { final Role role = new RoleDataGen().nextPersisted(); final User user = new UserDataGen().roles(role).nextPersisted(); final Host host = new SiteDataGen().nextPersisted(); final Rule rule = new RuleDataGen().host(host).nextPersisted(); final ConditionGroup conditionGroup = new ConditionGroupDataGen().rule(rule).next(); addRulesPublishPermissions(role, host); rulesAPI.saveConditionGroup(conditionGroup, user, false); List<Rule> allRules = rulesAPI.getAllRules(user, false); createConditionAndCheck(user, conditionGroup, allRules); }
Source:
public String toString() { try { return objectMapper.writeValueAsString(this.clientSideRequestStatistics); }catch (JsonProcessingException e) { logger.error("Error while parsing diagnostics " + e.getOriginalMessage()); } return StringUtils.EMPTY; }

Target:
public String toString() { try { return objectMapper.writeValueAsString(this.clientSideRequestStatistics); }catch (JsonProcessingException e) { logger.error("Error while parsing diagnostics " + e); } return StringUtils.EMPTY; }
Source:
public AbstractApplicationRunner(Config config) { super(config); this.streamGraph = new StreamGraphImpl(this, config); this.systemAdmins = new SystemAdmins(config); this.streamManager = new StreamManager(systemAdmins); }

Target:
public AbstractApplicationRunner(Config config) { super(config); this.graphSpec = new StreamGraphSpec(this, config); this.systemAdmins = new SystemAdmins(config); this.streamManager = new StreamManager(systemAdmins); }
Source:
public void initialise() { CoreRegistry.put(BehaviorSystem.class, this); List<BehaviorNodeComponent> items = Lists.newArrayList(); Collection<Prefab> prefabs = CoreRegistry.get(PrefabManager.class).listPrefabs(BehaviorNodeComponent.class); for (Prefab prefab : prefabs) { EntityRef entityRef = CoreRegistry.get(EntityManager.class).create(prefab); items.add(entityRef.getComponent(BehaviorNodeComponent.class)); } CoreRegistry.put(BehaviorNodeFactory.class, new BehaviorNodeFactory(items)); }

Target:
public void initialise() { CoreRegistry.put(BehaviorSystem.class, this); List<BehaviorNodeComponent> items = Lists.newArrayList(); Collection<Prefab> prefabs = prefabManager.listPrefabs(BehaviorNodeComponent.class); for (Prefab prefab : prefabs) { EntityRef entityRef = entityManager.create(prefab); items.add(entityRef.getComponent(BehaviorNodeComponent.class)); } CoreRegistry.put(BehaviorNodeFactory.class, new BehaviorNodeFactory(items)); }
Source:
public SavedAttachment(String name, long revpos, long seq, byte[] key, String type, File file) { this.name = name; this.revpos = revpos; this.seq = seq; this.key = key; this.type = type; this.file = file; }

Target:
protected SavedAttachment(String name, long revpos, long seq, byte[] key, String type, File file) { this.name = name; this.revpos = revpos; this.seq = seq; this.key = key; this.type = type; this.file = file; }
Source:
protected File createPassFile(String value) throws IOException { File temp = File.createTempFile("ovirt", ".tmp"); String filePath = temp.getAbsolutePath(); File chmodFile = getChmodFile(); if (chmodFile == null) { throw new IOException("Can't find the chmod command in order to change the permissions of file \"" + filePath + "\"."); } Process chmodProcess = Runtime.getRuntime().exec(chmodFile.getAbsolutePath() + " 600 " + filePath); try { int chmodExitCode = chmodProcess.waitFor(); if (chmodExitCode != 0) { throw new IOException("Failed to change permissions for file \"" + filePath + "\", the chmod command returns exit code " + chmodExitCode + "\"."); } } catch (InterruptedException ie) { throw new IOException("Failed to change permissions for file \"" + filePath + "\"", ie); } BufferedWriter out = new BufferedWriter(new FileWriter(temp)); out.write(value); out.flush(); return temp; }

Target:
protected File createPassFile(String value) throws IOException { File temp = File.createTempFile("ovirt", ".tmp"); String filePath = temp.getAbsolutePath(); Process chmodProcess = Runtime.getRuntime().exec("chmod 600 " + filePath); try { int chmodExitCode = chmodProcess.waitFor(); if (chmodExitCode != 0) { throw new IOException("Failed to change permissions for file \"" + filePath + "\", the chmod command returns exit code " + chmodExitCode + "\"."); } } catch (InterruptedException ie) { throw new IOException("Failed to change permissions for file \"" + filePath + "\"", ie); } BufferedWriter out = new BufferedWriter(new FileWriter(temp)); out.write(value); out.flush(); return temp; }
Source:
public void onModified(List<KubernetesConfigMap> configMaps) { final KubernetesConfigMap configMap = checkConfigMaps(configMaps, configMapName); if (!configMap.getData().equals(previousData)) { if (KubernetesLeaderElector.hasLeadership(configMap, lockIdentity)) { synchronized (lock) { if (running) { leaderElectionEventHandler.onLeaderInformationChange( getLeaderInformationFromConfigMap(configMap)); } } } previousData.clear(); previousData.putAll(configMap.getData()); } }

Target:
public void onModified(List<KubernetesConfigMap> configMaps) { final KubernetesConfigMap configMap = checkConfigMaps(configMaps, configMapName); if (KubernetesLeaderElector.hasLeadership(configMap, lockIdentity)) { leaderElectionEventHandler.onLeaderInformationChange(getLeaderInformationFromConfigMap(configMap)); } }
Source:
public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = View.inflate(parent.getContext(), R.layout.menu_spinner, null); } if (mIconResource > 0) { ImageView iconView = (ImageView) convertView.findViewById(R.id.menu_spinner_icon); iconView.setImageResource(mIconResource); } TextView titleView = (TextView) convertView.findViewById(R.id.menu_spinner_title); titleView.setText(String.format(mTitle, getCount() - 2)); if (hasItems() && position < mItems.size()) { TextView nameView = (TextView) convertView.findViewById(R.id.menu_spinner_name); nameView.setText(mItems.get(position).getName()); } return convertView; }

Target:
public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = View.inflate(parent.getContext(), R.layout.menu_spinner, null); } if (mIconResource > 0) { ImageView iconView = (ImageView) convertView.findViewById(R.id.menu_spinner_icon); iconView.setImageResource(mIconResource); } TextView titleView = (TextView) convertView.findViewById(R.id.menu_spinner_title); titleView.setText(String.format(mTitle, getCount() + mDisplayBaseCount)); if (hasItems() && position < mItems.size()) { TextView nameView = (TextView) convertView.findViewById(R.id.menu_spinner_name); nameView.setText(mItems.get(position).getName()); } return convertView; }
Source:
private IStatus runWait(IProgressMonitor monitor) { boolean allStarted = false; long startTime = System.currentTimeMillis(); long endTime = startTime + maxWait; IModule[] modules = server.getModules(); monitor.beginTask("Verifying Module States for " + server.getName(), maxWait * 1000); while( !allStarted && System.currentTimeMillis() < endTime) { allStarted = true; long thisLoopStart = System.currentTimeMillis(); for( int i = 0; i < modules.length; i++ ) { IModule[] temp = new IModule[]{modules[i]}; int state = verifier.getModuleState(server, temp, new SubProgressMonitor(monitor, 1000)); ((Server)server).setModuleState(temp, state); boolean started = state == IServer.STATE_STARTED; allStarted = allStarted && started; ((Server)server).setModuleState(temp, state); } try { Thread.sleep(500); } catch(InterruptedException ie) { } long timeDif = System.currentTimeMillis() - thisLoopStart; monitor.worked((int)timeDif - (modules.length * 100)); } return Status.OK_STATUS; }

Target:
private IStatus runWait(IProgressMonitor monitor) { boolean allStarted = false; long startTime = System.currentTimeMillis(); long endTime = startTime + maxWait; IModule[] modules = server.getModules(); monitor.beginTask("Checking module states for " + server.getName(), maxWait * 1000); while( !allStarted && System.currentTimeMillis() < endTime) { allStarted = true; long thisLoopStart = System.currentTimeMillis(); for( int i = 0; i < modules.length; i++ ) { IModule[] temp = new IModule[]{modules[i]}; int state = verifier.getModuleState(server, temp, new SubProgressMonitor(monitor, 1000)); ((Server)server).setModuleState(temp, state); boolean started = state == IServer.STATE_STARTED; allStarted = allStarted && started; ((Server)server).setModuleState(temp, state); } try { Thread.sleep(500); } catch(InterruptedException ie) { } long timeDif = System.currentTimeMillis() - thisLoopStart; monitor.worked((int)timeDif - (modules.length * 100)); } return Status.OK_STATUS; }
Source:
Set<AgentInfo> selectAgent(User user, Set<AgentInfo> allFreeAgents, int agentCount) { Set<AgentInfo> recentlyUsedAgents = hazelcastService.getOrDefault(CACHE_RECENTLY_USED_AGENTS, user.getUserId(), emptySet()); Stream<AgentInfo> ownedFreeAgentStream = getFreeAgentStream(recentlyUsedAgents, allFreeAgents, agentInfo -> isOwnedAgent(agentInfo, user.getUserId())); Stream<AgentInfo> freeAgentStream = getFreeAgentStream(recentlyUsedAgents, allFreeAgents, this::isCommonAgent); return concat(ownedFreeAgentStream, freeAgentStream).limit(agentCount).collect(toSet()); }

Target:
Set<AgentInfo> selectAgent(User user, Set<AgentInfo> allFreeAgents, int agentCount) { Set<AgentInfo> recentlyUsedAgents = hazelcastService.getOrDefault(CACHE_RECENTLY_USED_AGENTS, user.getUserId(), emptySet()); Comparator<AgentInfo> recentlyUsedPriorityComparator = (agent1, agent2) -> { if (recentlyUsedAgents.contains(agent1)) { return -1; } if (recentlyUsedAgents.contains(agent2)) { return 1; } return 0; }; Stream<AgentInfo> ownedFreeAgentStream = allFreeAgents .stream() .filter(agentInfo -> isOwnedAgent(agentInfo, user.getUserId())) .sorted(recentlyUsedPriorityComparator); Stream<AgentInfo> freeAgentStream = allFreeAgents .stream() .filter(this::isCommonAgent) .sorted(recentlyUsedPriorityComparator); return concat(ownedFreeAgentStream, freeAgentStream) .limit(agentCount) .collect(toSet()); }
Source:
public void cancelResourceRequest(SamzaResourceRequest request) { synchronized (lock) { requestsQueue.remove(request); if (hostAffinityEnabled) { requestsToCountMap.get(request.getPreferredHost()).decrementAndGet(); } manager.cancelResourceRequest(request); } }

Target:
public void cancelResourceRequest(SamzaResourceRequest request) { log.info("Canceling resource request on for {}", request.getPreferredHost(), request.getContainerID()); synchronized (lock) { requestsQueue.remove(request); if (hostAffinityEnabled) { requestsToCountMap.get(request.getPreferredHost()).decrementAndGet(); } manager.cancelResourceRequest(request); } }
Source:
private static boolean causedByLocalizationException(Throwable ex) { if (ex == null) { return false; } if (ex instanceof NoLocalizedTextException) { return true; } return causedByLocalizationException(ex.getCause()); }

Target:
private static boolean causedByLocalizationException(Throwable ex) { return ex != null && (ex instanceof NoLocalizedTextException || causedByLocalizationException(ex.getCause())); }
Source:
public WorkspaceProject resolveProject(final Space space, final String projectName, final String branchName) { WorkspaceProject workspaceProject = resolveProject(space, projectName); if (branchName == null) { return workspaceProject; } if (workspaceProject != null) { for (final Branch branch : workspaceProject.getRepository().getBranches()) { if (branch.getName().equals(branchName)) { return resolveProject(space, branch); } } } return new WorkspaceProject(workspaceProject.getOrganizationalUnit(), workspaceProject.getRepository(), workspaceProject.getBranch(), null); }

Target:
public WorkspaceProject resolveProject(final Space space, final String projectName, final String branchName) { WorkspaceProject workspaceProject = resolveProject(space, projectName); if (workspaceProject == null) { throw new IllegalArgumentException("project " + projectName + " not found."); } if (branchName == null) { return workspaceProject; } for (final Branch branch : workspaceProject.getRepository().getBranches()) { if (branch.getName().equals(branchName)) { return resolveProject(space, branch); } } throw new IllegalArgumentException("branch " + branchName + " not found."); }
Source:
public Row next() { setNextBatchIfNeeded(); if (batch == null) { throw new NoSuchElementException(); } Row res = batch.get(position++); if (position == batch.size()) { batch = null; position = 0; requestNextBatch(); } return res; }

Target:
public Row next() { if (!hasNext()) { throw new NoSuchElementException(); } assert batch != null; Row res = batch.get(position++); if (position == batch.size()) { batch = null; position = 0; requestNextBatch(); } return res; }
Source:
public static void until(Callable<Boolean> condition, long timeout, TimeUnit timeUnit) { until(condition, 10, TimeUnit.SECONDS, 50); }

Target:
public static void until(Callable<Boolean> condition, long timeout, TimeUnit timeUnit) { until(condition, timeout, timeUnit, 50); }
Source:
public Response execute() throws IOException { try { return super.execute(); } catch (QosIoException e) { ListenableFuture<Response> futureResponse = exceptionHandler.handle(this, e); try { return futureResponse.get(); } catch (ExecutionException executionException) { Throwable cause = executionException.getCause(); if (cause instanceof QosIoException) { throw (QosIoException) cause; } else { throw new IOException("Failed to execute request", cause); } } catch (InterruptedException interruptedException) { throw new IOException("Failed to execute request (interrupted?)", interruptedException); } } }

Target:
public Response execute() throws IOException { try { return super.execute(); } catch (QosIoException e) { ListenableFuture<Response> futureResponse = exceptionHandler.handle(this, e); try { return futureResponse.get(); } catch (ExecutionException executionException) { Throwable cause = executionException.getCause(); if (cause instanceof QosIoException) { QosIoException qosIoException = (QosIoException) cause; throw new QosIoException(qosIoException.getQosException(), qosIoException.getResponse()); } else { throw new IOException("Failed to execute request", cause); } } catch (InterruptedException interruptedException) { Thread.currentThread().interrupt(); throw new IOException("Failed to execute request (interrupted?)", interruptedException); } } }
Source:
public void deleteTest() { try { String insertBeforeKey = "user0"; HashMap<String, ByteIterator> insertBeforeMap = insertRow(insertBeforeKey); String deleteKey = "user1"; insertRow(deleteKey); String insertAfterKey = "user2"; HashMap<String, ByteIterator> insertAfterMap = insertRow(insertAfterKey); jdbcDBClient.delete(TABLE_NAME, deleteKey); ResultSet resultSet = jdbcConnection.prepareStatement( String.format("SELECT * FROM %s", TABLE_NAME) ).executeQuery(); int totalRows = 0; while (resultSet.next()) { assertNotEquals("Assert this is not the deleted row key", deleteKey, resultSet.getString(KEY_FIELD)); totalRows++; } assertEquals("Assert we ended with the correct number of rows", totalRows, 2); resultSet.close(); } catch (SQLException e) { e.printStackTrace(); fail("Failed deleteTest"); } }

Target:
public void deleteTest() { try { insertRow("user0"); String deleteKey = "user1"; insertRow(deleteKey); insertRow("user2"); jdbcDBClient.delete(TABLE_NAME, deleteKey); ResultSet resultSet = jdbcConnection.prepareStatement( String.format("SELECT * FROM %s", TABLE_NAME) ).executeQuery(); int totalRows = 0; while (resultSet.next()) { assertNotEquals("Assert this is not the deleted row key", deleteKey, resultSet.getString(KEY_FIELD)); totalRows++; } assertEquals("Assert we ended with the correct number of rows", totalRows, 2); resultSet.close(); } catch (SQLException e) { e.printStackTrace(); fail("Failed deleteTest"); } }
Source:
public static void main(String[] args) throws IOException { String inputFile = null; if (args.length > 0) { inputFile = args[0]; } InputStream is = System.in; if (inputFile != null) { is = new FileInputStream(inputFile); } ANTLRInputStream input = new ANTLRInputStream(is); cqlLexer lexer = new cqlLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); tokens.fill(); CommentListener listener = new CommentListener(tokens); listener.rewriteTokens(); cqlParser parser = new cqlParser(listener.tokens); parser.setBuildParseTree(true); ParserRuleContext tree = parser.library(); CqlFormatterVisitor formatter = new CqlFormatterVisitor(); String output = (String)formatter.visit(tree); System.out.print(listener.refineOutput(output)); }

Target:
public static void main(String[] args) throws IOException { String inputFile = null; if (args.length > 0) { inputFile = args[0]; } InputStream is = System.in; if (inputFile != null) { is = new FileInputStream(inputFile); } System.out.print(getFormattedOutput(is)); }
Source:
Geometry(GeometryBoundingBox boundingBox, Map<String, Object> properties) { this.boundingBox = boundingBox; if (properties == null) { this.properties = Collections.emptyMap(); } else { this.properties = properties.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } }

Target:
protected Geometry(GeometryBoundingBox boundingBox, Map<String, Object> properties) { this.boundingBox = boundingBox; if (properties == null) { this.properties = null; } else { this.properties = Collections.unmodifiableMap(new HashMap<>(properties)); } }
Source:
public void beginTree(DetailAST rootAST) { currentImportControl = null; processCurrentFile = path.matcher(getFileContents().getFileName()).find(); unitName = null; for (DetailAST sibling = rootAST; sibling != null; sibling = sibling.getNextSibling()) { final int type = sibling.getType(); if (type == TokenTypes.CLASS_DEF || type == TokenTypes.ENUM_DEF || type == TokenTypes.INTERFACE_DEF || type == TokenTypes.ANNOTATION_DEF) { unitName = sibling.findFirstToken(TokenTypes.IDENT).getText(); break; } } }

Target:
public void beginTree(DetailAST rootAST) { currentImportControl = null; processCurrentFile = path.matcher(getFileContents().getFileName()).find(); fileName = getFileContents().getText().getFile().getName(); final int period = fileName.lastIndexOf('.'); if (period != -1) { fileName = fileName.substring(0, period); } }
Source:
private static void createCustomSkillset(SearchServiceClient searchServiceClient) { HashMap<String, String> headers = new HashMap<>(); headers.put("Ocp-Apim-Subscription-Key", "foobar"); List<InputFieldMappingEntry> inputs = Collections.singletonList( new InputFieldMappingEntry() .setName("text") .setSource("/document/mytext") ); List<OutputFieldMappingEntry> outputs = Collections.singletonList( new OutputFieldMappingEntry() .setName("textItems") .setTargetName("myTextItems") ); Skill webApiSkill = new WebApiSkill() .setUri("<LINK_0>") .setHttpMethod("POST") .setHttpHeaders(headers) .setInputs(inputs) .setOutputs(outputs) .setName("webapi-skill") .setDescription("A WebApi skill that can be used as a custom skillset"); Skillset skillset = new Skillset() .setName("custom-skillset") .setDescription("Skillset for testing custom skillsets") .setSkills(Collections.singletonList(webApiSkill)); System.out.println(String.format("Creating custom skillset '%s'", skillset.getName())); Skillset createdSkillset = searchServiceClient.createSkillset(skillset); System.out.println("Created custom skillset"); System.out.println(String.format("Name: %s", createdSkillset.getName())); System.out.println(String.format("ETag: %s", createdSkillset.getETag())); }

Target:
private static void createCustomSkillset(SearchServiceClient searchServiceClient) { HashMap<String, String> headers = new HashMap<>(); headers.put("Ocp-Apim-Subscription-Key", "foobar"); List<InputFieldMappingEntry> inputs = Collections.singletonList( new InputFieldMappingEntry() .setName("text") .setSource("/document/mytext") ); List<OutputFieldMappingEntry> outputs = Collections.singletonList( new OutputFieldMappingEntry() .setName("textItems") .setTargetName("myTextItems") ); Skill webApiSkill = new WebApiSkill() .setUri("<LINK_0>") .setHttpMethod("POST") .setHttpHeaders(headers) .setInputs(inputs) .setOutputs(outputs) .setName("webapi-skill") .setDescription("A WebApiSkill that can be used to call a custom web api function"); Skillset skillset = new Skillset() .setName("custom-skillset") .setDescription("Skillset for testing custom skillsets") .setSkills(Collections.singletonList(webApiSkill)); System.out.println(String.format("Creating custom skillset '%s'", skillset.getName())); Skillset createdSkillset = searchServiceClient.createSkillset(skillset); System.out.println("Created custom skillset"); System.out.println(String.format("Name: %s", createdSkillset.getName())); System.out.println(String.format("ETag: %s", createdSkillset.getETag())); }
Source:
private void recordStateChange(boolean stateChanged, boolean dataChanged, boolean sessionExpired) { if (_monitor != null) { if (stateChanged) { _monitor.increaseStateChangeEventCounter(); if (sessionExpired) { _monitor.increasExpiredSessionCounter(); } } if (dataChanged) { _monitor.increaseDataChangeEventCounter(); } } }

Target:
private void recordStateChange(boolean stateChanged, boolean dataChanged, boolean sessionExpired) { if (_monitor != null) { if (stateChanged) { _monitor.increaseStateChangeEventCounter(); } if (dataChanged) { _monitor.increaseDataChangeEventCounter(); } if (sessionExpired) { _monitor.increasExpiredSessionCounter(); } } }
Source:
public void showChanges() { diffLink.click(); }

Target:
public void showChanges() { wait.forElementClickable(diffLink); diffLink.click(); }
Source:
private static boolean isSerdeSupported(Properties schema) { String serdeName = HiveUtil.getDeserializerClassName(schema); if (!supportedSerdes.contains(serdeName)) { log.debug("Unsupported S3Select serde format found: " + serdeName); return false; } return true; }

Target:
private static boolean isSerdeSupported(Properties schema) { String serdeName = getDeserializerClassName(schema); if (!SUPPORTED_SERDES.contains(serdeName)) { return false; } return true; }
Source:
public void clickCreateAccountButton() { createAccountButton.click(); }

Target:
public void clickCreateAccountButton(){ waitForElementClickableByElement(createAccountButton); createAccountButton.click(); }
Source:
public String toString() { if (string == null) { string = new String(bytes, java.nio.charset.Charset.forName("ISO-8859-1")); } return string; }

Target:
public String toString() { if (string == null) { string = new String(bytes, java.nio.charset.StandardCharsets.US_ASCII); } return string; }
Source:
protected WebViewClient createWebViewClient(List<String> allowedURL) { if (getIntent().hasExtra(LOCAL_BLOG_ID)) { SiteModel site = mSiteStore.getSiteByLocalId(getIntent().getIntExtra(LOCAL_BLOG_ID, -1)); if (site == null) { AppLog.e(AppLog.T.UTILS, "No valid blog passed to WPWebViewActivity"); finish(); } return new WPWebViewClient(site, mAccountStore.getAccessToken(), allowedURL) { boolean mWebResourceError; @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); mWebResourceError = false; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (!mWebResourceError && mViewModel != null) { mViewModel.onUrlLoaded(); } } @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); mWebResourceError = true; if (mViewModel != null) { mViewModel.onError(); } } }; } else { return new URLFilteredWebViewClient(allowedURL) { boolean mWebResourceError; @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); mWebResourceError = false; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (!mWebResourceError && mViewModel != null) { mViewModel.onUrlLoaded(); } } @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); mWebResourceError = true; if (mViewModel != null) { mViewModel.onError(); } } }; } }

Target:
protected WebViewClient createWebViewClient(List<String> allowedURL) { URLFilteredWebViewClient webViewClient; if (getIntent().hasExtra(LOCAL_BLOG_ID)) { SiteModel site = mSiteStore.getSiteByLocalId(getIntent().getIntExtra(LOCAL_BLOG_ID, -1)); if (site == null) { AppLog.e(AppLog.T.UTILS, "No valid blog passed to WPWebViewActivity"); finish(); } webViewClient = new WPWebViewClient(site, mAccountStore.getAccessToken(), allowedURL); } else { webViewClient = new URLFilteredWebViewClient(allowedURL); } webViewClient.setMBaseWebViewClientListener(this); return webViewClient; }
Source:
public OutputStreamFlushableCommandline( String[] excludedEnvironmentVariables ) { this.excludedEnvironmentVariables = new ConcurrentLinkedDeque<>(); this.addedEnvironmentVariables = new HashSet<>( ); Collections.addAll( this.excludedEnvironmentVariables, excludedEnvironmentVariables ); }

Target:
public OutputStreamFlushableCommandline( String[] excludedEnvironmentVariables ) { this.excludedEnvironmentVariables = new ConcurrentLinkedDeque<>(); addedEnvironmentVariables = new HashSet<>(); Collections.addAll( this.excludedEnvironmentVariables, excludedEnvironmentVariables ); }
Source:
public void getClassLoaderModelByArtifact() { ClassLoaderModel pluginClassLoaderModel = new ClassLoaderModel(VERSION_100, mulePluginArtifact.getArtifactCoordinates()); Artifact otherThirdPartyArtifact = new Artifact(new ArtifactCoordinates(ORG_TESTS, "other-third-party", VERSION_100), URI.create("")); pluginClassLoaderModel.setDependencies(ImmutableList.of(otherThirdPartyArtifact)); applicationClassloaderModel.mergeDependencies(ImmutableList.of(pluginClassLoaderModel)); assertThat(applicationClassloaderModel.getArtifacts(), hasSize(3)); assertThat(applicationClassloaderModel.getArtifacts(), contains(thirdPartyArtifact, mulePluginArtifact, otherThirdPartyArtifact)); assertThat(applicationClassloaderModel.getClassLoaderModel(mulePluginArtifact), CoreMatchers.sameInstance(pluginClassLoaderModel)); }

Target:
public void getClassLoaderModelByArtifact() { ClassLoaderModel pluginClassLoaderModel = new ClassLoaderModel(VERSION_100, mulePluginArtifact.getArtifactCoordinates()); Artifact otherThirdPartyArtifact = new Artifact(new ArtifactCoordinates(ORG_TESTS, "other-third-party", VERSION_100), URI.create("")); pluginClassLoaderModel.setDependencies(ImmutableList.of(otherThirdPartyArtifact)); applicationClassloaderModel.mergeDependencies(ImmutableList.of(pluginClassLoaderModel)); assertThat(applicationClassloaderModel.getArtifacts(), hasSize(3)); assertThat(applicationClassloaderModel.getArtifacts(), contains(thirdPartyArtifact, mulePluginArtifact, otherThirdPartyArtifact)); assertThat(applicationClassloaderModel.getClassLoaderModel(mulePluginArtifact), sameInstance(pluginClassLoaderModel)); }
Source:
public void visit( InputPortInfo p ) { OLSyntaxNode protocol = null, location = null; if( p.protocol() != null ) { p.protocol().accept( this ); protocol = currNode; } if( p.location() != null ) { p.location().accept( this ); location = currNode; } InputPortInfo iport = new InputPortInfo( p.context(), p.id(), location, protocol, p.aggregationList(), p.redirectionMap() ); if( p.getDocumentation() != null && p.getDocumentation().length() > 0 ) { iport.setDocumentation( p.getDocumentation() ); } iport.operationsMap().putAll( p.operationsMap() ); iport.getInterfaceList().addAll( p.getInterfaceList() ); programChildren.add( iport ); }

Target:
public void visit( InputPortInfo p ) { OLSyntaxNode protocol = null, location = null; if( p.protocol() != null ) { protocol = optimizeNode( p.protocol() ); } if( p.location() != null ) { location = optimizeNode( p.location() ); } InputPortInfo iport = new InputPortInfo( p.context(), p.id(), location, protocol, p.aggregationList(), p.redirectionMap() ); if( p.getDocumentation() != null && p.getDocumentation().length() > 0 ) { iport.setDocumentation( p.getDocumentation() ); } iport.operationsMap().putAll( p.operationsMap() ); iport.getInterfaceList().addAll( p.getInterfaceList() ); programChildren.add( iport ); }
Source:
public static String findParameterType(ParameterContext parameterContext) { ResolvedMethodParameter resolvedMethodParameter = parameterContext.resolvedMethodParameter(); ResolvedType parameterType = resolvedMethodParameter.getParameterType(); parameterType = parameterContext.alternateFor(parameterType); if (isFileType(parameterType) || isListOfFiles(parameterType)) { return "form"; } if (resolvedMethodParameter.hasParameterAnnotation(PathVariable.class)) { return "path"; } else if (resolvedMethodParameter.hasParameterAnnotation(RequestBody.class)) { return "body"; } else if (resolvedMethodParameter.hasParameterAnnotation(RequestPart.class)) { return "formData"; } else if (resolvedMethodParameter.hasParameterAnnotation(RequestParam.class)) { return determineScalarParameterType( parameterContext.getOperationContext().consumes(), parameterContext.getOperationContext().httpMethod()); } else if (resolvedMethodParameter.hasParameterAnnotation(RequestHeader.class)) { return "header"; } else if (resolvedMethodParameter.hasParameterAnnotation(ModelAttribute.class)) { LOGGER.warn("@ModelAttribute annotated parameters should have already been expanded via " + "the ExpandedParameterBuilderPlugin"); return "body"; } return determineScalarParameterType( parameterContext.getOperationContext().consumes(), parameterContext.getOperationContext().httpMethod()); }

Target:
public static String findParameterType(ParameterContext parameterContext) { ResolvedMethodParameter resolvedMethodParameter = parameterContext.resolvedMethodParameter(); ResolvedType parameterType = resolvedMethodParameter.getParameterType(); parameterType = parameterContext.alternateFor(parameterType); if (isFileType(parameterType) || isListOfFiles(parameterType)) { return "form"; } if (resolvedMethodParameter.hasParameterAnnotation(PathVariable.class)) { return "path"; } else if (resolvedMethodParameter.hasParameterAnnotation(RequestBody.class)) { return "body"; } else if (resolvedMethodParameter.hasParameterAnnotation(RequestPart.class)) { return "formData"; } else if (resolvedMethodParameter.hasParameterAnnotation(RequestParam.class)) { return determineScalarParameterType( parameterContext.getOperationContext().consumes(), parameterContext.getOperationContext().httpMethod()); } else if (resolvedMethodParameter.hasParameterAnnotation(RequestHeader.class)) { return "header"; } else if (resolvedMethodParameter.hasParameterAnnotation(ModelAttribute.class)) { LOGGER.warn("@ModelAttribute annotated parameters should have already been expanded via " + "the ExpandedParameterBuilderPlugin"); } if (!resolvedMethodParameter.hasParameterAnnotations()) { return determineScalarParameterType( parameterContext.getOperationContext().consumes(), parameterContext.getOperationContext().httpMethod()); } return "body"; }
Source:
protected void check() { Preconditions.checkState(!(runtimeConfigSupplier().isPresent() && runtimeConfig().isPresent()), "Either Refreshable or Supplier of runtime config must be provided or none, but not both"); }

Target:
protected void check() { Preconditions.checkState(!(runtimeConfigSupplier().isPresent() && runtimeConfig().isPresent()), "Cannot provide both Refreshable and Supplier of runtime config"); }
Source:
public boolean addConfiguredRepository(File repositoryDir) throws IllegalArgumentException { synchronized (prefs) { if (!FileKey.isGitRepository(repositoryDir, FS.DETECTED)) throw new IllegalArgumentException( "Repository directory to configure does not look like a Git directory: " + repositoryDir); String dirString = getPath(repositoryDir); List<String> dirStrings = getConfiguredRepositories(); if (dirStrings.contains(dirString)) { return false; } else { Set<String> dirs = new HashSet<String>(); dirs.addAll(dirStrings); dirs.add(dirString); saveDirs(dirs); return true; } } }

Target:
public boolean addConfiguredRepository(File repositoryDir) throws IllegalArgumentException { synchronized (prefs) { if (!FileKey.isGitRepository(repositoryDir, FS.DETECTED)) throw new IllegalArgumentException(MessageFormat.format( CoreText.RepositoryUtil_DirectoryIsNotGitDirectory, repositoryDir)); String dirString = getPath(repositoryDir); List<String> dirStrings = getConfiguredRepositories(); if (dirStrings.contains(dirString)) { return false; } else { Set<String> dirs = new HashSet<String>(); dirs.addAll(dirStrings); dirs.add(dirString); saveDirs(dirs); return true; } } }
Source:
public void visitParenthesisedExpression(ParenthesisedExpressionTree tree) { if (tree.expression().is(Kind.PARENTHESISED_EXPRESSION)) { addIssue(tree, MESSAGE); } super.visitParenthesisedExpression(tree); }

Target:
public void visitParenthesisedExpression(ParenthesisedExpressionTree tree) { if (tree.expression().is(Kind.PARENTHESISED_EXPRESSION)) { addIssue(tree.openParenthesis(), MESSAGE) .secondary(tree.closeParenthesis()); } super.visitParenthesisedExpression(tree); }
Source:
public void testHeaderlessSamFormat() throws PathNotFoundException { final SAMFormat result = getSamFormat(new Configuration(), "test_headerless.sam"); assertEquals(result, SAMFormat.SAM); }

Target:
public void testHeaderlessSamFormat() throws PathNotFoundException { final SAMFormat result = getSamFormat(new Configuration(), "test_headerless.sam"); assertEquals(SAMFormat.SAM, result); }
Source:
private static String encodeChar(char ch) { return String.format("=%02X", ch & 0xff); }

Target:
private static String encodeChar(char ch) { if (ch < 16) { return "=0" + Integer.toHexString(ch).toUpperCase(); } else { return '=' + Integer.toHexString((ch&0xff)).toUpperCase(); } }
Source:
private ArrayList<ExecutorDetails> getSortedExecs(HashSet<String> spreadComps, Map<String, Map<String, Integer>> constraintMatrix, Map<String, Set<ExecutorDetails>> compToExecs) { ArrayList<ExecutorDetails> retList = new ArrayList<>(); Map<String, Integer> compConstraintCountMap = new HashMap<>(); for (Map.Entry<String, Map<String, Integer>> constraintEntry1 : constraintMatrix.entrySet()) { int count = 0; String comp = constraintEntry1.getKey(); for (Map.Entry<String, Integer> constraintEntry2 : constraintEntry1.getValue().entrySet()) { if (constraintEntry2.getValue() == 1) { count++; } } if (spreadComps.contains(constraintEntry1.getKey())) { count++; } compConstraintCountMap.put(comp, count); } NavigableMap<String, Integer> sortedCompConstraintCountMap = sortByValues(compConstraintCountMap); for (String comp : sortedCompConstraintCountMap.keySet()) { retList.addAll(compToExecs.get(comp)); } return retList; }

Target:
private ArrayList<ExecutorDetails> getSortedExecs(HashSet<String> spreadComps, Map<String, Map<String, Integer>> constraintMatrix, Map<String, Set<ExecutorDetails>> compToExecs) { ArrayList<ExecutorDetails> retList = new ArrayList<>(); Map<String, Integer> compConstraintCountMap = new HashMap<>(); constraintMatrix.forEach((comp, subMatrix) -> { int count = subMatrix.values().stream().mapToInt(Number::intValue).sum(); if (spreadComps.contains(comp)) { count++; } compConstraintCountMap.put(comp, count); }); NavigableMap<String, Integer> sortedCompConstraintCountMap = sortByValues(compConstraintCountMap); for (String comp : sortedCompConstraintCountMap.keySet()) { retList.addAll(compToExecs.get(comp)); } return retList; }
Source:
public int read(long position, final ByteBuffer buf) throws IOException { checkStream(); try { int pos = buf.position(); final int n = ((ByteBufferPositionedReadable) in).read(position, buf); if (n > 0) { decrypt(position, buf, n, pos); } return n; } catch (ClassCastException e) { throw new UnsupportedOperationException("This stream does not support " + "positioned read."); } }

Target:
public int read(long position, final ByteBuffer buf) throws IOException { checkStream(); if (!(in instanceof ByteBufferPositionedReadable)) { throw new UnsupportedOperationException("This stream does not support " + "positioned reads with byte buffers."); } int bufPos = buf.position(); final int n = ((ByteBufferPositionedReadable) in).read(position, buf); if (n > 0) { decrypt(position, buf, n, bufPos); } return n; }
Source:
protected void doAperiodicRun() { if (isActive) { try { if (originThread.isAlive()) { originThread.interrupt(); } new TcpSlaveAgentListener(port).start(); LOGGER.log(Level.INFO, "Restarted TcpSlaveAgentListener"); } catch (IOException e1) { LOGGER.log(Level.SEVERE, "Could not reschedule TcpSlaveAgentListener", cause); } isActive = false; } }

Target:
protected void doAperiodicRun() { if (isActive) { try { if (originThread.isAlive()) { originThread.interrupt(); } new TcpSlaveAgentListener(port).start(); LOGGER.log(Level.INFO, "Restarted TcpSlaveAgentListener"); isActive = false; } catch (IOException e) { LOGGER.log(Level.SEVERE, "Could not reschedule TcpSlaveAgentListener - trying again.", cause); } } }
Source:
public Block copyPositions(int[] positions, int offset, int length) { checkValidPositionsArray(positions, offset, length); IntArrayList positionsToCopy = new IntArrayList(); Map<Integer, Integer> oldIndexToNewIndex = new HashMap<>(); int[] newIds = new int[length]; for (int i = 0; i < length; i++) { int position = positions[offset + i]; int oldIndex = getId(position); if (!oldIndexToNewIndex.containsKey(oldIndex)) { oldIndexToNewIndex.put(oldIndex, positionsToCopy.size()); positionsToCopy.add(oldIndex); } newIds[i] = oldIndexToNewIndex.get(oldIndex); } return new DictionaryBlock(dictionary.copyPositions(positionsToCopy.elements(), 0, positionsToCopy.size()), newIds); }

Target:
public Block copyPositions(int[] positions, int offset, int length) { checkArrayRange(positions, offset, length); IntArrayList positionsToCopy = new IntArrayList(); Map<Integer, Integer> oldIndexToNewIndex = new HashMap<>(); int[] newIds = new int[length]; for (int i = 0; i < length; i++) { int position = positions[offset + i]; int oldIndex = getId(position); if (!oldIndexToNewIndex.containsKey(oldIndex)) { oldIndexToNewIndex.put(oldIndex, positionsToCopy.size()); positionsToCopy.add(oldIndex); } newIds[i] = oldIndexToNewIndex.get(oldIndex); } return new DictionaryBlock(dictionary.copyPositions(positionsToCopy.elements(), 0, positionsToCopy.size()), newIds); }
Source:
public Builder(String queryText) { if(queryText == null || queryText.isEmpty()) { String msg = "Query Text must not be null or empty"; logger.error(msg); throw new IllegalArgumentException(msg); } this.queryText = BinaryValue.createFromUtf8(queryText); Matcher paramMatcher = paramPattern.matcher(queryText); if(!paramMatcher.matches()) { return; } for (int i = 0; i < paramMatcher.groupCount(); i++) { knownParams.add(paramMatcher.group(i)); } }

Target:
public Builder(String queryText) { if (queryText == null || queryText.isEmpty()) { String msg = "Query Text must not be null or empty"; logger.error(msg); throw new IllegalArgumentException(msg); } this.queryText = queryText; Matcher paramMatcher = paramPattern.matcher(queryText); if (!paramMatcher.matches()) { knownParams = Collections.emptySet(); return; } knownParams = new HashSet<String>(paramMatcher.groupCount()); for (int i = 0; i < paramMatcher.groupCount(); i++) { knownParams.add(paramMatcher.group(i)); } }
Source:
private String getJobOrFlowName(SlaOption slaOption) { String jobName = (String) slaOption.getInfo().get(SlaOption.INFO_JOB_NAME); if (org.apache.commons.lang.StringUtils.isNotBlank(jobName)) { return jobName; } else { return (String) slaOption.getInfo().get(SlaOption.INFO_FLOW_NAME); } }

Target:
private String getJobOrFlowName(SlaOption slaOption) { String flowName = (String) slaOption.getInfo().get(SlaOption.INFO_FLOW_NAME); String jobName = (String) slaOption.getInfo().get(SlaOption.INFO_JOB_NAME); if (org.apache.commons.lang.StringUtils.isNotBlank(jobName)) { return flowName + ":" + jobName; } else { return flowName; } }
Source:
private boolean ensureDestinationImageMap() { if (diskInfoDestinationMap.isEmpty()) { if (getParameters().getStorageDomainId() != null && !Guid.Empty.equals(getParameters().getStorageDomainId())) { Guid storageId = getParameters().getStorageDomainId(); ArrayList<Guid> storageIds = new ArrayList<Guid>(); storageIds.add(storageId); for (DiskImage image : getVmTemplate().getDiskTemplateMap().values()) { image.setStorageIds(storageIds); setDestTypeAndFormat(image); diskInfoDestinationMap.put(image.getId(), image); } } else { ImagesHandler.fillImagesMapBasedOnTemplate(getVmTemplate(), diskInfoDestinationMap, destStorages, false); } } if (getVmTemplate().getDiskTemplateMap().values().size() != diskInfoDestinationMap.size()) { log.error("Can not found any default active domain for one of the disks of template with id '{}'", getVmTemplate().getId()); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_MISSED_STORAGES_FOR_SOME_DISKS); return false; } for (DiskImage diskImage : diskInfoDestinationMap.values()) { setDestTypeAndFormat(diskImage); } return true; }

Target:
private boolean ensureDestinationImageMap() { if (diskInfoDestinationMap.isEmpty()) { if (getParameters().getStorageDomainId() != null && !Guid.Empty.equals(getParameters().getStorageDomainId())) { Guid storageId = getParameters().getStorageDomainId(); ArrayList<Guid> storageIds = new ArrayList<Guid>(); storageIds.add(storageId); for (DiskImage image : getVmTemplate().getDiskTemplateMap().values()) { image.setStorageIds(storageIds); diskInfoDestinationMap.put(image.getId(), image); } } else { ImagesHandler.fillImagesMapBasedOnTemplate(getVmTemplate(), diskInfoDestinationMap, destStorages, false); } } if (getVmTemplate().getDiskTemplateMap().values().size() != diskInfoDestinationMap.size()) { log.error("Can not found any default active domain for one of the disks of template with id '{}'", getVmTemplate().getId()); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_MISSED_STORAGES_FOR_SOME_DISKS); return false; } for (DiskImage diskImage : diskInfoDestinationMap.values()) { setDestTypeAndFormat(diskImage); } return true; }
Source:
public String toString() { return innerList.stream().map(Node::toString).collect(Collectors.joining()); }

Target:
public String toString() { return innerList.stream().map(Node::toString).collect(Collectors.joining(", ", "[", "]")); }