auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Instant toIndexedValue(Date value, ValueBridgeToIndexedValueContext context) { if ( value == null ) { return null; } return value instanceof java.sql.Date ? Instant.ofEpochMilli( value.getTime() ) : value.toInstant(); }

Target:
public Instant toIndexedValue(Date value, ValueBridgeToIndexedValueContext context) { if ( value == null ) { return null; } return Instant.ofEpochMilli( value.getTime() ); }
Source:
public void onTextAvailable(@NotNull ProcessEvent event, Key outputType) { ElixirCompilerError error = ElixirCompilerError.create(myCompileTargetRootPath, event.getText()); if(error != null){ boolean isError = error.getCategory() == CompilerMessageCategory.ERROR; BuildMessage.Kind kind = isError ? BuildMessage.Kind.ERROR : BuildMessage.Kind.WARNING; CompilerMessage msg = new CompilerMessage(myBuilderName, kind, error.getErrorMessage(), VirtualFileManager.extractPath(error.getUrl()), -1, -1, -1, error.getLine(), -1); myContext.processMessage(msg); } }

Target:
public void onTextAvailable(@NotNull ProcessEvent event, Key outputType) { ElixirCompilerError error = ElixirCompilerError.create(myCompileTargetRootPath, event.getText()); if(error != null){ boolean isError = error.getCategory() == CompilerMessageCategory.ERROR; BuildMessage.Kind kind = isError ? BuildMessage.Kind.ERROR : BuildMessage.Kind.WARNING; CompilerMessage msg = new CompilerMessage(myBuilderName, kind, error.getErrorMessage(), VirtualFileManager.extractPath(error.getUrl()), DEFAULT_PROBLEM_BEGIN_OFFSET, DEFAULT_PROBLEM_END_OFFSET, DEFAULT_PROBLEM_LOCATION_OFFSET, error.getLine(), DEFAULT_LOCATION_COLUMN); myContext.processMessage(msg); } }
Source:
public void testRemoveExistingRelationship() throws Exception { final Node diagram = createNode(CaseManagementDiagram.class); final Node stage = createNode(AdHocSubprocess.class); final Node start = createNode(StartNoneEvent.class); final Node end = createNode(EndNoneEvent.class); createChildEdge(diagram, start); createChildEdge(diagram, stage); createChildEdge(diagram, end); createSequenceFlow(start, stage); createSequenceFlow(stage, end); final CaseManagementSetChildNodeGraphCommand command = new CaseManagementSetChildNodeGraphCommand(diagram, stage, index, Optional.of(diagram), originalIndex); command.removeExistingRelationship(context); assertTrue(command.originalIn.isPresent()); assertEquals(start, command.originalIn.get()); assertTrue(command.originalOut.isPresent()); assertEquals(end, command.originalOut.get()); assertEquals(2, diagram.getOutEdges().size()); assertEquals(1, start.getOutEdges().size()); assertEquals(2, end.getInEdges().size()); assertEquals(end, ((Edge) start.getOutEdges().get(0)).getTargetNode()); }

Target:
public void testRemoveExistingRelationship() { final Node diagram = createNode(CaseManagementDiagram.class); final Node stage = createNode(AdHocSubprocess.class); final Node start = createNode(StartNoneEvent.class); final Node end = createNode(EndNoneEvent.class); createChildEdge(diagram, start); createChildEdge(diagram, stage); createChildEdge(diagram, end); createSequenceFlow(start, stage); createSequenceFlow(stage, end); final CaseManagementSetChildNodeGraphCommand command = new CaseManagementSetChildNodeGraphCommand(diagram, stage, index, Optional.of(diagram), originalIndex); command.removeExistingRelationship(context); assertTrue(command.originalIn.isPresent()); assertEquals(start, command.originalIn.get()); assertTrue(command.originalOut.isPresent()); assertEquals(end, command.originalOut.get()); assertEquals(2, diagram.getOutEdges().size()); assertEquals(1, start.getOutEdges().size()); assertEquals(2, end.getInEdges().size()); assertEquals(end, ((Edge) start.getOutEdges().get(0)).getTargetNode()); }
Source:
private void _publishTemplates(ActionRequest req, User user) throws Exception { String[] publishInode = req.getParameterValues("publishInode"); if (publishInode == null) return; ActionRequestImpl reqImpl = (ActionRequestImpl)req; Set relatedPages = new HashSet(); for (int i=0;i<publishInode.length;i++) { Template template = (Template) InodeFactory.getInode(publishInode[i],Template.class); if (InodeUtils.isSet(template.getInode())) { try{ PublishFactory.publishAsset(template,reqImpl.getHttpServletRequest()); ActivityLogger.logInfo(this.getClass(), "Publish Template action", "User " + user.getPrimaryKey() + " publishing template" + template.getTitle(), HostUtil.hostNameUtil(req, _getUser(req))); SessionMessages.add(req, "message", "message.template_list.published"); }catch(WebAssetException wax){ Logger.error(this, wax.getMessage(),wax); SessionMessages.add(req, "error", "message.webasset.published.failed"); } List<HTMLPageAsset> pagesForThisTemplate = APILocator.getTemplateAPI().getPagesUsingTemplate(template, user, false); relatedPages.addAll(pagesForThisTemplate); } } Iterator iterPages = relatedPages.iterator(); while (iterPages.hasNext()) { PageServices.invalidateAll((HTMLPageAsset) iterPages.next()); } }

Target:
private void _publishTemplates(ActionRequest req, User user) throws Exception { String[] publishInode = req.getParameterValues("publishInode"); if (publishInode == null) return; ActionRequestImpl reqImpl = (ActionRequestImpl)req; for (int i=0;i<publishInode.length;i++) { Template template = (Template) InodeFactory.getInode(publishInode[i],Template.class); if (InodeUtils.isSet(template.getInode())) { try{ PublishFactory.publishAsset(template,reqImpl.getHttpServletRequest()); ActivityLogger.logInfo(this.getClass(), "Publish Template action", "User " + user.getPrimaryKey() + " publishing template" + template.getTitle(), HostUtil.hostNameUtil(req, _getUser(req))); SessionMessages.add(req, "message", "message.template_list.published"); }catch(WebAssetException wax){ Logger.error(this, wax.getMessage(),wax); SessionMessages.add(req, "error", "message.webasset.published.failed"); } } } }
Source:
public Attribute fillAttribute(PerunSession sess, Resource resource, Attribute attribute) throws InternalErrorException { ResourceAttributesModuleImplApi attributeModule = getResourceAttributeModule(sess, attribute); if (attributeModule == null) { log.debug("fillAttribute - There's no attribute module for this attribute. Attribute wasn't filled.", attribute); return attribute; } try { return attributeModule.fillAttribute((PerunSessionImpl) sess, resource, attribute); } catch (WrongAttributeAssignmentException ex) { throw new InternalErrorException(ex); } }

Target:
public Attribute fillAttribute(PerunSession sess, Resource resource, Attribute attribute) throws InternalErrorException { ResourceAttributesModuleImplApi attributeModule = getResourceAttributeModule(sess, attribute); if (attributeModule == null) { log.debug("Attribute wasn't filled. There is no module for: {}.", attribute.getName()); return attribute; } try { return attributeModule.fillAttribute((PerunSessionImpl) sess, resource, attribute); } catch (WrongAttributeAssignmentException ex) { throw new InternalErrorException(ex); } }
Source:
public Map<K, V> getAll(Set<K> keys) { if (trace) log.tracef("GET_ALL cache=%s keys=%s", forceReturn.getName(), keys); Map<K, V> result = new HashMap<>(keys.size()); if (preferAsync) { Map<K, Future<V>> futureMap = new HashMap<>(keys.size()); for (K key : keys) { futureMap.put(key, forceReturn.getAsync(key)); } for (Map.Entry<K, Future<V>> entry : futureMap.entrySet()) { try { V value = entry.getValue().get(); if (value != null) { result.put(entry.getKey(), value); } } catch (Exception e) { throw new RuntimeException(e); } } } else { for (K key : keys) { result.put(key, forceReturn.get(key)); } } return result; }

Target:
public Map<K, V> getAll(Set<K> keys) { if (trace) log.tracef("GET_ALL cache=%s keys=%s", forceReturn.getName(), keys); Map<K, V> result = new HashMap<>(keys.size()); Map<K, Future<V>> futureMap = new HashMap<>(keys.size()); for (K key : keys) { futureMap.put(key, forceReturn.getAsync(key)); } for (Map.Entry<K, Future<V>> entry : futureMap.entrySet()) { try { V value = entry.getValue().get(); if (value != null) { result.put(entry.getKey(), value); } } catch (Exception e) { throw new RuntimeException(e); } } return result; }
Source:
public RegistrationWindows() { registryWriter = new RegistryWriter(); }

Target:
public RegistrationWindows() { this(new RegistryWriter()); }
Source:
public boolean shutdownVpc(Vpc vpc, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { if (vpc.getState().equals(Vpc.State.Inactive)) { try { Domain vpcDomain = _domainDao.findById(vpc.getDomainId()); HostVO nuageVspHost = getNuageVspHost(getPhysicalNetworkId(vpc.getZoneId())); String preConfiguredDomainTemplateName = _configDao.getValue(NuageVspManager.NuageVspVpcDomainTemplateName.key()); ShutDownVpcVspCommand cmd = new ShutDownVpcVspCommand(vpcDomain.getUuid(), vpc.getUuid(), preConfiguredDomainTemplateName); ShutDownVpcVspAnswer answer = (ShutDownVpcVspAnswer) _agentMgr.easySend(nuageVspHost.getId(), cmd); if (answer == null || !answer.getResult()) { s_logger.error("ShutDownVpcVspCommand for VPC " + vpc.getUuid() + " failed"); if ((null != answer) && (null != answer.getDetails())) { throw new ResourceUnavailableException(answer.getDetails(), Vpc.class, vpc.getId()); } } } catch (Exception e) { s_logger.warn("Failed to destroy VPC in Vsp " + e.getMessage()); } } return true; }

Target:
public boolean shutdownVpc(Vpc vpc, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { if (vpc.getState().equals(Vpc.State.Inactive)) { Domain vpcDomain = _domainDao.findById(vpc.getDomainId()); HostVO nuageVspHost = getNuageVspHost(getPhysicalNetworkId(vpc.getZoneId())); String preConfiguredDomainTemplateName = _configDao.getValue(NuageVspManager.NuageVspVpcDomainTemplateName.key()); ShutDownVpcVspCommand.Builder cmdBuilder = new ShutDownVpcVspCommand.Builder() .domainUuid(vpcDomain.getUuid()) .vpcUuid(vpc.getUuid()) .domainTemplateName(preConfiguredDomainTemplateName); Answer answer = _agentMgr.easySend(nuageVspHost.getId(), cmdBuilder.build()); if (answer == null || !answer.getResult()) { s_logger.error("ShutDownVpcVspCommand for VPC " + vpc.getUuid() + " failed on Nuage VSD " + nuageVspHost.getDetail("hostname")); if ((null != answer) && (null != answer.getDetails())) { throw new ResourceUnavailableException(answer.getDetails(), Vpc.class, vpc.getId()); } } } return true; }
Source:
protected void executeQueryCommand() { VM vm = vmDao.get(getParameters().getId()); if (vm == null || vm.getDynamicData().getFqdn() == null) { getQueryReturnValue().setReturnValue(ErrataData.emptyData()); return; } Provider<?> provider = providerDao.get(vm.getProviderId()); if (provider != null) { HostProviderProxy proxy = providerProxyFactory.create(provider); ErrataData errataForVm = proxy.getErrataForHost(vm.getId().toString(), vm.getDynamicData().getFqdn(), vm.getName(), getParameters().getErrataFilter()); getQueryReturnValue().setReturnValue(errataForVm); } else { getQueryReturnValue().setReturnValue(ErrataData.emptyData()); } }

Target:
protected void executeQueryCommand() { VM vm = vmDao.get(getParameters().getId()); if (vm == null) { getQueryReturnValue().setReturnValue(ErrataData.emptyData()); return; } Provider<?> provider = providerDao.get(vm.getProviderId()); if (provider != null) { HostProviderProxy proxy = providerProxyFactory.create(provider); ErrataData errataForVm = proxy.getErrataForHost(vm.getId().toString(), vm.getDynamicData().getFqdn(), vm.getName(), getParameters().getErrataFilter()); getQueryReturnValue().setReturnValue(errataForVm); } else { getQueryReturnValue().setReturnValue(ErrataData.emptyData()); } }
Source:
public Team update(Long teamId, TeamDTO input) { Team current = getTeamById(teamId); if (!Strings.isNullOrEmpty(input.getTeamName())) { current.setTeamName(input.getTeamName()); } String captainUsername = input.getCaptainUsername(); if (!Strings.isNullOrEmpty(captainUsername)) { User captain = userService.getUserByUsername(captainUsername) .orElseThrow(() -> new UserNotFoundException(captainUsername)); current.setCaptain(captain); } return teamRepository.saveAndFlush(current); }

Target:
public Team update(Long teamId, TeamDTO input) { Team current = getTeamById(teamId); if (!Strings.isNullOrEmpty(input.getTeamName())) { current.setTeamName(input.getTeamName()); } String captainUsername = input.getCaptainUsername(); if (!Strings.isNullOrEmpty(captainUsername) && !captainUsername.equals(current.getCaptain().getUsername())) { User captain = userService.getUserByUsername(captainUsername) .orElseThrow(() -> new UserNotFoundException(captainUsername)); current.setCaptain(captain); } return teamRepository.saveAndFlush(current); }
Source:
public void createProjectRequest(final CreateProjectJobRequest jobRequest, final Map<String, Object> headers) { final Map<String, Object> params = getContext(jobRequest); params.put("Space", jobRequest.getSpaceName()); params.put("Project", jobRequest.getProjectName()); params.put("Operation", "createProject"); params.put("acceptLanguage", headers.get("acceptLanguage")); scheduleJob(jobRequest, new CreateProjectCmd(jobRequestHelper, jobResultManager, params)); }

Target:
public void createProjectRequest(final CreateProjectJobRequest jobRequest, final Map<String, Object> headers) { final Map<String, Object> params = getContext(jobRequest); params.put("Space", jobRequest.getSpaceName()); params.put("Project", jobRequest.getProjectName()); params.put("Operation", "createProject"); params.put(ACCEPT_LANGUAGE, headers.get(ACCEPT_LANGUAGE)); scheduleJob(jobRequest, new CreateProjectCmd(jobRequestHelper, jobResultManager, params)); }
Source:
public ASTValue eval(WordsEnvironment environment) throws WordsRuntimeException { WordsObject obj = children.get(0).eval(environment).objValue; String propertyName = children.get(1).eval(environment).stringValue; ASTValue propertyASTValue = children.get(2).eval(environment); WordsProperty wordsProp = null; switch (propertyASTValue.type) { case NUM: wordsProp = new WordsProperty(propertyASTValue.numValue); break; case STRING: wordsProp = new WordsProperty(propertyASTValue.stringValue); break; case OBJ: wordsProp = new WordsProperty(propertyASTValue.objValue); break; case NOTHING: wordsProp = new WordsProperty(WordsProperty.PropertyType.NOTHING); break; default: throw new AssertionError("Shouldn't get here"); } obj.setProperty(propertyName, wordsProp); return null; }

Target:
public ASTValue eval(WordsEnvironment environment) throws WordsRuntimeException { WordsObject obj = children.get(0).eval(environment).objValue; if (obj == null) { throw new AssertionError("Obj should never be null here"); } String propertyName = children.get(1).eval(environment).stringValue; ASTValue propertyASTValue = children.get(2).eval(environment); WordsProperty wordsProp = null; switch (propertyASTValue.type) { case NUM: wordsProp = new WordsProperty(propertyASTValue.numValue); break; case STRING: wordsProp = new WordsProperty(propertyASTValue.stringValue); break; case OBJ: wordsProp = new WordsProperty(propertyASTValue.objValue); break; case NOTHING: wordsProp = new WordsProperty(WordsProperty.PropertyType.NOTHING); break; default: throw new AssertionError("Shouldn't get here"); } obj.setProperty(propertyName, wordsProp); return null; }
Source:
public void testInstallFeatureCallIsPrivileged() throws Exception { final AtomicReference<StackTraceElement[]> stackTraceElements = new AtomicReference<>(); doAnswer( AdditionalAnswers.answerVoid( o -> stackTraceElements.set(Thread.currentThread().getStackTrace()))) .when(mockFeaturesService) .installFeature(anyString(), any(EnumSet.class)); ApplicationServiceBean serviceBean = new ApplicationServiceBean( testAppService, testConfigAdminExt, mBeanServer, mockFeaturesService); serviceBean.installFeature("profile-name"); assertThat( Arrays.stream(stackTraceElements.get()) .anyMatch(e -> e.toString().startsWith(DO_PRIVILEGED_STACK_ELEMENT)), is(true)); }

Target:
public void testInstallFeatureCallIsPrivileged() throws Exception { StackCaptor stackCaptor = new StackCaptor(); stackCaptor .doCaptureStack() .when(mockFeaturesService) .installFeature(anyString(), any(EnumSet.class)); ApplicationServiceBean serviceBean = new ApplicationServiceBean( testAppService, testConfigAdminExt, mBeanServer, mockFeaturesService); serviceBean.installFeature("profile-name"); assertThat(stackCaptor.getStack(), stackContainsDoPrivilegedCall()); }
Source:
public void collect(GenericRow genericRow) { Object[] key = new Object[_keySize]; for (int i = 0; i < _keySize; i++) { key[i] = genericRow.getValue(_keyColumns[i]); } Record keyRecord = new Record(key); GenericRow prev = _collection.get(keyRecord); if (prev == null) { _collection.put(keyRecord, genericRow); } else { for (int i = 0; i < _valueSize; i++) { String valueColumn = _valueColumns[i]; Object aggregate = _valueAggregators[i] .aggregate(prev.getValue(valueColumn), genericRow.getValue(valueColumn), _metricFieldSpecs[i]); prev.putValue(valueColumn, aggregate); } } }

Target:
public void collect(GenericRow genericRow) { Object[] key = new Object[_keySize]; for (int i = 0; i < _keySize; i++) { key[i] = genericRow.getValue(_keyColumns[i]); } Record keyRecord = new Record(key); GenericRow prev = _collection.get(keyRecord); if (prev == null) { _collection.put(keyRecord, genericRow); } else { for (int i = 0; i < _valueSize; i++) { String valueColumn = _valueColumns[i]; Object aggregate = _valueAggregators[i].aggregate(prev.getValue(valueColumn), genericRow.getValue(valueColumn)); prev.putValue(valueColumn, aggregate); } } }
Source:
public void addProjectToImport( final ExampleProject exampleProject ) { Button button = (Button) document.createElement( "button" ); button.getClassList().add( "btn" ); button.getClassList().add( "btn-lg" ); button.setTextContent( exampleProject.getName() ); button.setAttribute( "alt", exampleProject.getDescription() ); button.setOnclick( event -> presenter.importProject( exampleProject ) ); importContainer.appendChild( button ); }

Target:
public void addProjectToImport( final ExampleProject exampleProject ) { final ImportExampleButtonWidget importExampleButton = importExampleButtonWidgets.get(); importExampleButton.init( exampleProject.getName(), exampleProject.getDescription(), () -> presenter.importProject( exampleProject ) ); importContainer.appendChild( importExampleButton.getElement() ); }
Source:
public Options getOpts() { Options opts = new Options(); opts.addOption("appname", true, "Application Name. Default value - Storm-on-Yarn"); opts.addOption("queue", true, "RM Queue in which this application is to be submitted"); opts.addOption("rmAddr", true, "YARN RM's IPC address"); opts.addOption("schedulerAddr", true, "YARN scheduler's IPC address"); opts.addOption("stormHome", true, "Storm Home Directory"); opts.addOption("output", true, "Output file"); opts.addOption("stormZip", true, "file path of storm.zip"); return opts; }

Target:
public Options getOpts() { Options opts = new Options(); opts.addOption("appname", true, "Application Name. Default value - Storm-on-Yarn"); opts.addOption("queue", true, "RM Queue in which this application is to be submitted"); opts.addOption("stormHome", true, "Storm Home Directory"); opts.addOption("output", true, "Output file"); opts.addOption("stormZip", true, "file path of storm.zip"); return opts; }
Source:
public static GenomicVariant fromHgvs(String hgvs) { if (!isHgvs(hgvs)) throw new InvalidHgvsException(); String chr = getPattern("^\\d+(?=:)", hgvs); RefType ref_type = getRefTypeFromHgvs(hgvs); Integer start = Integer.parseInt(getPattern("(?<=\\.)\\d+(?=[_ATGC])", hgvs)); Integer end = getEndFromHgvs(hgvs, start); Type type = getTypeFromHgvs(hgvs); String ref = getRefFromHgvs(hgvs, type); String alt = getAltFromHgvs(hgvs, type); return new GenomicVariant(chr, ref_type, start, end, type, ref, alt); }

Target:
public static GenomicVariant fromHgvs(String hgvs) { if (!isHgvs(hgvs)) { throw new InvalidHgvsException(); } String chr = getPattern("^\\d+(?=:)", hgvs); RefType ref_type = getRefTypeFromHgvs(hgvs); Integer start = Integer.parseInt(getPattern("(?<=\\.)\\d+(?=[_ATGC])", hgvs)); Integer end = getEndFromHgvs(hgvs, start); Type type = getTypeFromHgvs(hgvs); String ref = getRefFromHgvs(hgvs, type); String alt = getAltFromHgvs(hgvs, type); return new GenomicVariant(chr, ref_type, start, end, type, ref, alt); }
Source:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String contentType = request.getParameter("contenttype"); String fileName = request.getParameter("filename"); Boolean cache = Boolean.parseBoolean(request.getParameter("cache")); String encodingType = request.getParameter("encodingtype"); String content = request.getParameter("content"); if (contentType != null) { response.setContentType(contentType); } if (fileName == null) { fileName = "attachment"; } response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); if (!cache) { response.setHeader("Cache-Control", "no-cache, must-revalidate"); response.setHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); } if (content == null) { return; } if ("binary".equals(encodingType)) { response.getOutputStream().write(Base64.decodeBase64(content)); } else { response.getWriter().write(content); if (response.getWriter().checkError()) { throw new IOException("Error when writing to response stream"); } } }

Target:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String contentType = request.getParameter("contenttype"); String fileName = request.getParameter("filename"); Boolean cache = Boolean.parseBoolean(request.getParameter("cache")); String encodingType = request.getParameter("encodingtype"); String content = request.getParameter("content"); if (contentType != null) { response.setContentType(contentType); } if (fileName == null) { fileName = "attachment"; } response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); if (!cache) { response.setHeader("Cache-Control", "no-cache, must-revalidate"); response.setHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); } if (content == null) { return; } if ("binary".equals(encodingType)) { response.getOutputStream().write(Base64.decodeBase64(content)); } else if ("plain".equals(encodingType)) { response.getWriter().write(content); if (response.getWriter().checkError()) { throw new IOException("Error when writing to response stream"); } } else { throw new ServletException(String.format("Unsupported encoding type {0}", encodingType)); } }
Source:
public static Object structAccess(Object structObject, int index, String fieldName) { if (structObject == null) { return null; } if (structObject instanceof Object[]) { return ((Object[]) structObject)[index]; } else if (structObject instanceof List) { return ((List) structObject).get(index); } else if (structObject instanceof Row) { return ((Row) structObject).getObject(index); } else { Class<?> beanClass = structObject.getClass(); try { Field structField; if (index >= 0 && index < beanClass.getDeclaredFields().length) { structField = beanClass.getDeclaredFields()[index]; } else { structField = beanClass.getDeclaredField(fieldName); } return structField.get(structObject); } catch (NoSuchFieldException | IllegalAccessException ex) { throw RESOURCE.failedToAccessField(fieldName, beanClass.getName()).ex(ex); } } }

Target:
public static Object structAccess(Object structObject, int index, String fieldName) { if (structObject == null) { return null; } if (structObject instanceof Object[]) { return ((Object[]) structObject)[index]; } else if (structObject instanceof List) { return ((List) structObject).get(index); } else if (structObject instanceof Row) { return ((Row) structObject).getObject(index); } else { Class<?> beanClass = structObject.getClass(); try { Field structField; if (fieldName == null) { structField = beanClass.getDeclaredFields()[index]; } else { structField = beanClass.getDeclaredField(fieldName); } return structField.get(structObject); } catch (NoSuchFieldException | IllegalAccessException ex) { throw RESOURCE.failedToAccessField(fieldName, beanClass.getName()).ex(ex); } } }
Source:
abstract public void validate() throws IndexBuilderException; abstract public void loadIntoTaxonomy(Taxonomy taxonomy) throws IndexBuilderException; abstract public Citation getCitation() throws IndexBuilderException; abstract public Collection<Country> getCountries() throws IndexBuilderException; abstract public Collection<Contact> getContacts() throws IndexBuilderException; public static NameSource create(String f) throws IndexBuilderException { try { File nf = new File(f); NameSource ns; if (!nf.exists()) throw new IndexBuilderException("Name source " + nf + " does not exist"); if (nf.isDirectory()) ns = new DwcaNameSource(nf); else ns = new CSVNameSource(new InputStreamReader(new FileInputStream(nf), "UTF-8")); ns.validate(); return ns; } catch (IOException ex) { throw new UncheckedIOException(ex); } }

Target:
abstract public void validate() throws IndexBuilderException; abstract public void loadIntoTaxonomy(Taxonomy taxonomy) throws IndexBuilderException; abstract public Citation getCitation() throws IndexBuilderException; abstract public Collection<Country> getCountries() throws IndexBuilderException; abstract public Collection<Contact> getContacts() throws IndexBuilderException; public static NameSource create(String f) throws IndexBuilderException { try { File nf = new File(f); NameSource ns; if (!nf.exists()) throw new IndexBuilderException("Name source " + nf + " does not exist"); if (nf.isDirectory()) ns = new DwcaNameSource(nf); else ns = new CSVNameSource(Files.newReader(nf, Charset.forName("UTF-8"))); ns.validate(); return ns; } catch (IOException ex) { throw new UncheckedIOException(ex); } }
Source:
public ScriptedAnalysis createScriptedAnalysis(@Nullable ITmfTrace trace, String analysisName) { if (trace == null) { throw new NullPointerException("Trace should not be null"); } return new ScriptedAnalysis(trace, analysisName); }

Target:
public ScriptedAnalysis createScriptedAnalysis(@Nullable ITmfTrace trace, String analysisName) { return new ScriptedAnalysis(Objects.requireNonNull(trace, "Trace should not be null"), analysisName); }
Source:
public AuthorizationFramework getAuthorizationFramework() { try { authFrameworkLock.readLock().lock(); if (authFramework == null) { authFramework = new AuthorizationFramework(getPluginDirectory(), getPluginStack()); } return authFramework; } finally { authFrameworkLock.readLock().unlock(); } }

Target:
public AuthorizationFramework getAuthorizationFramework() { synchronized (authFrameworkLock) { if (authFramework == null) { authFramework = new AuthorizationFramework(getPluginDirectory(), getPluginStack()); } return authFramework; } }
Source:
public void importProject( final ExampleProject exampleProject ) { busyIndicatorView.showBusyIndicator( ts.getTranslation( LibraryConstants.Importing ) ); libraryService.call( new RemoteCallback<Project>() { @Override public void callback( final Project project ) { busyIndicatorView.hideBusyIndicator(); notificationEvent.fire( new NotificationEvent( ts.getTranslation( LibraryConstants.ProjectImportedSuccessfully ), NotificationEvent.NotificationType.SUCCESS ) ); newProjectEvent.fire( new NewProjectEvent( project, sessionInfo.getId(), sessionInfo.getIdentity().getIdentifier() ) ); goToProject( project ); } }, ( o, throwable ) -> { busyIndicatorView.hideBusyIndicator(); notificationEvent.fire( new NotificationEvent( ts.getTranslation( LibraryConstants.ProjectImportError ), NotificationEvent.NotificationType.ERROR ) ); return false; } ).importProject( libraryPlaces.getSelectedOrganizationalUnit(), libraryPlaces.getSelectedRepository(), exampleProject ); }

Target:
public void importProject( final ExampleProject exampleProject ) { busyIndicatorView.showBusyIndicator( ts.getTranslation( LibraryConstants.Importing ) ); libraryService.call( ( Project project ) -> { busyIndicatorView.hideBusyIndicator(); notificationEvent.fire( new NotificationEvent( ts.getTranslation( LibraryConstants.ProjectImportedSuccessfully ), NotificationEvent.NotificationType.SUCCESS ) ); newProjectEvent.fire( new NewProjectEvent( project, sessionInfo.getId(), sessionInfo.getIdentity().getIdentifier() ) ); goToProject( project ); }, ( o, throwable ) -> { busyIndicatorView.hideBusyIndicator(); notificationEvent.fire( new NotificationEvent( ts.getTranslation( LibraryConstants.ProjectImportError ), NotificationEvent.NotificationType.ERROR ) ); return false; } ).importProject( libraryPlaces.getSelectedOrganizationalUnit(), libraryPlaces.getSelectedRepository(), exampleProject ); }
Source:
public static Pair<String, String[]> createWhere(String[] fieldNames, Object[] values, EncryptedModel em, Persistable p) throws IllegalArgumentException { Set<String> fields = null; if(p instanceof IMetaData) { IMetaData m = (IMetaData)p; String[] thefields = m.getMetaDataFields(); fields = new HashSet<String>(); for(String s : thefields) { fields.add(TableBuilder.scrubName(s)); } } if(em instanceof IMetaData) { IMetaData m = (IMetaData)em; String[] thefields = m.getMetaDataFields(); fields = new HashSet<String>(); for(String s : thefields) { fields.add(TableBuilder.scrubName(s)); } } String ret = ""; ArrayList<String> arguments = new ArrayList<String>(); boolean set = false; for(int i = 0 ; i < fieldNames.length; ++i) { String columnName = TableBuilder.scrubName(fieldNames[i]); if(fields != null) { if(!fields.contains(columnName)) { continue; } } if(set){ ret += " AND "; } ret += columnName + "=?"; arguments.add(values[i].toString()); set = true; } String[] retArray = new String[arguments.size()]; for(int i =0; i< arguments.size(); i++){ retArray[i] = arguments.get(i); } return new Pair<String, String[]>(ret, retArray); }

Target:
public static Pair<String, String[]> createWhere(String[] fieldNames, Object[] values, EncryptedModel em, Persistable p) throws IllegalArgumentException { Set<String> fields = null; if(p instanceof IMetaData) { IMetaData m = (IMetaData)p; String[] thefields = m.getMetaDataFields(); fields = new HashSet<String>(); for(String s : thefields) { fields.add(TableBuilder.scrubName(s)); } } if(em instanceof IMetaData) { IMetaData m = (IMetaData)em; String[] thefields = m.getMetaDataFields(); fields = new HashSet<String>(); for(String s : thefields) { fields.add(TableBuilder.scrubName(s)); } } StringBuilder stringBuilder = new StringBuilder(); ArrayList<String> arguments = new ArrayList<String>(); boolean set = false; for(int i = 0 ; i < fieldNames.length; ++i) { String columnName = TableBuilder.scrubName(fieldNames[i]); if(fields != null) { if(!fields.contains(columnName)) { continue; } } if(set){ stringBuilder.append(" AND "); } stringBuilder.append(columnName); stringBuilder.append("=?"); arguments.add(values[i].toString()); set = true; } String[] retArray = new String[arguments.size()]; for(int i =0; i< arguments.size(); i++){ retArray[i] = arguments.get(i); } return new Pair<String, String[]>(stringBuilder.toString(), retArray); }
Source:
public DiscoveryConfiguration getDiscoveryConfigurationByNameOrDso(final String configurationName, final IndexableObject dso) { if (dso instanceof Community && configurationName.contentEquals("showUnDiscoverableItems")) { if (getMap().containsKey(configurationName + "." + ((Community) dso).getHandle())) { return getMap().get(configurationName + "." + ((Community) dso).getHandle()); } else { return getMap().get(configurationName); } } else if (StringUtils.isNotBlank(configurationName) && getMap().containsKey(configurationName)) { return getMap().get(configurationName); } else { return getDiscoveryConfiguration(dso); } }

Target:
public DiscoveryConfiguration getDiscoveryConfigurationByNameOrDso(final String configurationName, final IndexableObject dso) { if (StringUtils.isNotBlank(configurationName) && getMap().containsKey(configurationName)) { return getMap().get(configurationName); } else { return getDiscoveryConfiguration(dso); } }
Source:
public void testAuthenticityFail() { when(context.getParameter(NinjaConstant.AUTHENTICITY_TOKEN)).thenReturn("foo"); when(context.getSession()).thenReturn(session); when(context.getSession().getAuthenticityToken()).thenReturn("bar"); when(ninjaDefault.getForbiddenResult(context)).thenReturn(forbidden); Result failed = this.authenticityFilter.filter(filterChain, context); assertNotNull(failed); assertEquals(403, failed.getStatusCode()); }

Target:
public void testAuthenticityFail() { when(context.getParameter(NinjaConstant.AUTHENTICITY_TOKEN)).thenReturn("foo"); when(context.getSession()).thenReturn(session); when(context.getSession().getAuthenticityToken()).thenReturn("bar"); this.authenticityFilter.filter(filterChain, context); Mockito.verify(ninjaDefault).getForbiddenResult(context); }
Source:
public void fill(final Menu menu, int index) { final MenuItem item = new MenuItem(menu, SWT.NONE, index); item.setEnabled(false); if (info == null){ item.setText(Messages.notImplemented); return; } item.setText(Messages.computing); CodeLensParams param = new CodeLensParams(new TextDocumentIdentifier(info.getFileUri().toString()));; info.getInitializedLanguageClient().thenAccept(languageServer -> { final CompletableFuture<List<? extends CodeLens>> codeLens = languageServer .getTextDocumentService().codeLens(param); codeLens.whenComplete(new BiConsumer<List<? extends CodeLens>, Throwable>() { @Override public void accept(List<? extends CodeLens> t, Throwable u) { UIJob job = new UIJob(menu.getDisplay(), Messages.updateCodelensMenu_job) { @Override public IStatus runInUIThread(IProgressMonitor monitor) { if (u != null) { item.setText(u.getMessage()); } else if (t != null) { for (CodeLens lens : t) { if (lens != null && lens.getCommand() != null) { final MenuItem item = new MenuItem(menu, SWT.NONE, index); item.setText(lens.getCommand().getTitle()); item.setEnabled(false); } } } if (menu.getItemCount() == 1) { item.setText(Messages.codeLens_emptyMenu); } else { item.dispose(); } return Status.OK_STATUS; } }; job.schedule(); } }); }); super.fill(menu, index); }

Target:
public void fill(final Menu menu, int index) { final MenuItem item = new MenuItem(menu, SWT.NONE, index); item.setEnabled(false); if (info == null){ item.setText(Messages.notImplemented); return; } item.setText(Messages.computing); CodeLensParams param = new CodeLensParams(new TextDocumentIdentifier(info.getFileUri().toString()));; info.getInitializedLanguageClient().thenAccept(languageServer -> { final CompletableFuture<List<? extends CodeLens>> codeLens = languageServer .getTextDocumentService().codeLens(param); codeLens.whenComplete((t, u) -> { UIJob job = new UIJob(menu.getDisplay(), Messages.updateCodelensMenu_job) { @Override public IStatus runInUIThread(IProgressMonitor monitor) { if (u != null) { item.setText(u.getMessage()); } else if (t != null) { for (CodeLens lens : t) { if (lens != null && lens.getCommand() != null) { final MenuItem item = new MenuItem(menu, SWT.NONE, index); item.setText(lens.getCommand().getTitle()); item.setEnabled(false); } } } if (menu.getItemCount() == 1) { item.setText(Messages.codeLens_emptyMenu); } else { item.dispose(); } return Status.OK_STATUS; } }; job.schedule(); }); }); super.fill(menu, index); }
Source:
private String dumpTaskRequest(final RunTaskRequest request) { final StringBuilder sb = new StringBuilder(); sb.append("{"); if (request.getCluster() != null) { sb.append("Cluster: ").append(request.getCluster()).append(","); } if (request.getTaskDefinition() != null) { sb.append("TaskDefinition: ").append(request.getTaskDefinition()).append(","); } if (request.getLaunchType() != null) { sb.append("LaunchType: ").append(request.getLaunchType()).append(","); } if (request.getCapacityProviderStrategy() != null) { sb.append("CapacityProviderStrategy: ").append(request.getCapacityProviderStrategy()).append(","); } if (request.getPlacementConstraints() != null) { sb.append("PlacementConstraints: ").append(request.getPlacementConstraints()).append(","); } if (request.getPlacementStrategy() != null) { sb.append("PlacementStrategy: ").append(request.getPlacementStrategy()).append(","); } if (request.getPlatformVersion() != null) { sb.append("PlatformVersion: ").append(request.getPlatformVersion()).append(","); } TaskOverride overrides = request.getOverrides(); if (overrides != null) { if (overrides.getCpu() != null) { sb.append("CPU: ").append(overrides.getCpu()).append(","); } if (overrides.getCpu() != null) { sb.append("Memory: ").append(overrides.getMemory()); } } sb.append("}"); return sb.toString(); }

Target:
private static String dumpTaskRequest(final RunTaskRequest request) { final StringBuilder sb = new StringBuilder(); sb.append("{"); if (request.getCluster() != null) { sb.append("Cluster: ").append(request.getCluster()).append(","); } if (request.getTaskDefinition() != null) { sb.append("TaskDefinition: ").append(request.getTaskDefinition()).append(","); } if (request.getLaunchType() != null) { sb.append("LaunchType: ").append(request.getLaunchType()).append(","); } if (request.getCapacityProviderStrategy() != null) { sb.append("CapacityProviderStrategy: ").append(request.getCapacityProviderStrategy()).append(","); } if (request.getPlacementConstraints() != null) { sb.append("PlacementConstraints: ").append(request.getPlacementConstraints()).append(","); } if (request.getPlacementStrategy() != null) { sb.append("PlacementStrategy: ").append(request.getPlacementStrategy()).append(","); } if (request.getPlatformVersion() != null) { sb.append("PlatformVersion: ").append(request.getPlatformVersion()).append(","); } TaskOverride overrides = request.getOverrides(); if (overrides != null) { if (overrides.getCpu() != null) { sb.append("CPU: ").append(overrides.getCpu()).append(","); } if (overrides.getCpu() != null) { sb.append("Memory: ").append(overrides.getMemory()); } } sb.append("}"); return sb.toString(); }
Source:
private static void wrapHttpRequest(HttpUriRequest httpRequest, String username, String password) { if (httpRequest instanceof HttpGet || httpRequest instanceof HttpPut || httpRequest instanceof HttpPost) { try { byte[] authBytes = (username + ":" + password).getBytes("UTF-8"); String authString = Base64.getEncoder().encodeToString(authBytes); httpRequest.addHeader("Authorization", "Basic " + authString); } catch (Exception e) { LOG.error(e.getMessage(), e); } } }

Target:
private static void wrapHttpRequest(HttpUriRequest httpRequest, String username, String password) { try { byte[] authBytes = (username + ":" + password).getBytes("UTF-8"); String authString = Base64.getEncoder().encodeToString(authBytes); httpRequest.setHeader("Authorization", "Basic " + authString); } catch (UnsupportedEncodingException e) { LOG.error("The charset is not supported.", e); } }
Source:
public void validateHashtags(Change change, Set<String> toAdd, Set<String> toRemove) throws ValidationException { try { if (toRemove != null && !toRemove.isEmpty()) { Set<String> intersection = Sets.intersection( hashtagsUtil.getHashtagsInCurrentPSCommitMessage(change), toRemove); if (!intersection.isEmpty()) { throw new ValidationException(String.format( "Need delete [ %s ] from commit message firstly", intersection.toArray())); } } } catch (OrmException | IOException e) { log.error("Can not valid removed hashtags", e); throw new ValidationException("Can not valid removed hashtags", e); } }

Target:
public void validateHashtags(Change change, Set<String> toAdd, Set<String> toRemove) throws ValidationException { try { if (toRemove != null && !toRemove.isEmpty()) { Set<String> intersection = Sets.intersection( hashtagsUtil.getHashtagsInCurrentPSCommitMessage(change), toRemove); if (!intersection.isEmpty()) { throw new ValidationException(String.format( "Need delete [ %s ] from commit message firstly", intersection.toArray())); } } } catch (OrmException | IOException e) { log.error("Can not valid removed hashtags", e); throw new ValidationException("Can remove hashtags in commit message", e); } }
Source:
public boolean isAdmin(final String username) { final String sql = "select role from lobby_user where username = ?"; try (Connection con = connection.get(); PreparedStatement ps = con.prepareStatement(sql)) { ps.setString(1, username); try (ResultSet rs = ps.executeQuery()) { if (!rs.next()) { return false; } final String role = rs.getString("role"); return "ADMIN".equals(role) || "MODERATOR".equals(role); } } catch (final SQLException e) { throw new DatabaseException("Error getting admin flag for user: " + username, e); } }

Target:
public boolean isAdmin(final String username) { final String sql = "select role from lobby_user where username = ?"; try (Connection con = connection.get(); PreparedStatement ps = con.prepareStatement(sql)) { ps.setString(1, username); try (ResultSet rs = ps.executeQuery()) { if (!rs.next()) { return false; } final String role = rs.getString("role"); return UserRole.ADMIN.equals(role) || UserRole.MODERATOR.equals(role); } } catch (final SQLException e) { throw new DatabaseException("Error getting admin flag for user: " + username, e); } }
Source:
public void setAltitude(double altitude) { this.altitude = altitude; if(altitude > 121.92 && previousAltitude <= 121.92){ myDrone.notifyDroneEvent(DroneInterfaces.DroneEventsType.WARNING_400FT_EXCEEDED); } previousAltitude = altitude; }

Target:
public void setAltitude(double altitude) { this.altitude = altitude; if(altitude > FOUR_HUNDRED_FEET_IN_METERS && previousAltitude <= FOUR_HUNDRED_FEET_IN_METERS){ myDrone.notifyDroneEvent(DroneInterfaces.DroneEventsType.WARNING_400FT_EXCEEDED); } previousAltitude = altitude; }
Source:
public void verifyRequestWithOneToOneRelationship() { String expected = "{\"data\":{\"type\":\"blog\",\"id\":\"1\"," + "\"attributes\":{\"title\":\"title\"}," + "\"relationships\":{\"author\":{\"data\":{\"type\":\"author\",\"id\":\"1\"}}}}}"; String actual = datum( resource( type("blog"), id("1"), attributes( attr("title", "title") ), relationships( toOneRelation("author", linkage(type("author"), id("1")) ) ) ) ).toJSON(); assertEquals(actual, expected); }

Target:
public void verifyRequestWithOneToOneRelationship() { String expected = "{\"data\":{\"type\":\"blog\",\"id\":\"1\"," + "\"attributes\":{\"title\":\"title\"}," + "\"relationships\":{\"author\":{\"data\":{\"type\":\"author\",\"id\":\"1\"}}}}}"; String actual = datum( resource( type("blog"), id("1"), attributes( attr("title", "title") ), relationships( relation("author", TO_ONE, linkage(type("author"), id("1")) ) ) ) ).toJSON(); assertEquals(actual, expected); }
Source:
public void init(IEditorSite site, IEditorInput input) { super.init(site, input); TaskData taskData = getModel().getTaskData(); if (taskData != null) { GerritChange change = GerritUtil.getChange(taskData); final ChangeDetailX detail = change.getChangeDetail(); try { review = GerritUtil.toReview(detail); } catch (GerritException e) { throw new RuntimeException(e); } } }

Target:
public void init(IEditorSite site, IEditorInput input) { super.init(site, input); TaskData taskData = getModel().getTaskData(); if (taskData != null) { GerritChange change = GerritUtil.getChange(taskData); final ChangeDetailX detail = change.getChangeDetail(); review = GerritUtil.toReview(detail); } }
Source:
public void testRemoveKeyWordsFollowedByNewLineChar() { String selectWithSpace = "SELECT\nid, 'yes', false"; String fromWithSpace = "FROM\ntest.verification_table"; String whereWithSpace = "WHERE\nTRUE"; pagingQueryProvider.setSelectClause( selectWithSpace ); pagingQueryProvider.setFromClause( fromWithSpace ); pagingQueryProvider.setWhereClause( whereWithSpace ); assertEquals("id, 'yes', false", pagingQueryProvider.getSelectClause()); assertEquals("test.verification_table", pagingQueryProvider.getFromClause()); assertEquals("TRUE", pagingQueryProvider.getWhereClause()); }

Target:
public void testRemoveKeyWordsFollowedByNewLineChar() { String selectClause = "SELECT\nid, 'yes', false"; String fromClause = "FROM\ntest.verification_table"; String whereClause = "WHERE\nTRUE"; pagingQueryProvider.setSelectClause( selectClause ); pagingQueryProvider.setFromClause( fromClause ); pagingQueryProvider.setWhereClause( whereClause ); assertEquals("id, 'yes', false", pagingQueryProvider.getSelectClause()); assertEquals("test.verification_table", pagingQueryProvider.getFromClause()); assertEquals("TRUE", pagingQueryProvider.getWhereClause()); }
Source:
protected void sendHealthCheckResponse(HttpServletResponse resp, HealthCheckResult result) throws IOException { if (result.healthy) { resp.setStatus(HttpServletResponse.SC_OK); } else { resp.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } sendResponse(resp, result.toJson()); }

Target:
protected void sendHealthCheckResponse(HttpServletResponse resp, HealthCheckResult result) throws IOException { if (result.healthy) { resp.setStatus(HttpServletResponse.SC_OK); } else { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } sendResponse(resp, result.toJson()); }
Source:
public TapTargetBottomBar(LinearLayout tapTargetView, View fadeView, WelcomeActivity activity, int bottomScrollBarResourceId) { super(tapTargetView, fadeView, activity, bottomScrollBarResourceId); bottomScrollBar = activity.findViewById(R.id.pocketpaint_intro_tools_bottom_bar) .findViewById(R.id.pocketpaint_intro_bottom_bar_scroll_view); }

Target:
public TapTargetBottomBar(LinearLayout tapTargetView, View fadeView, WelcomeActivity activity, int bottomScrollBarResourceId) { super(tapTargetView, fadeView, activity, bottomScrollBarResourceId); bottomScrollBar = (BottomBarHorizontalScrollView) activity.findViewById(R.id.pocketpaint_intro_tools_bottom_bar) .findViewById(R.id.pocketpaint_intro_bottom_bar_scroll_view); }
Source:
private void playerDies() { State.getTrack().getPlayer().die(); sleep(20 * InternalTicker.NANOS_PER_TICK / InternalTicker.E6); letPlayerSurvive(); sleep(LONG); }

Target:
private void playerDies() { State.getTrack().getPlayer().die(); sleep(SLEEP_FACTOR * InternalTicker.NANOS_PER_TICK / InternalTicker.E6); letPlayerSurvive(); sleep(LONG); }