auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testKalmanMinStreamProcessorExtension1() throws InterruptedException { log.info("KalmanMin TestCase with test attributeExpressionExecutor's length"); SiddhiManager siddhiManager = new SiddhiManager(); String inStreamDefinition = "define stream inputStream (id int ,price double);"; String query = ("@info(name = 'query1') from inputStream#timeseries:kalmanMinMax(price, 0.000001,0.0001, " + "'min') select price, extremaType, id insert into outputStream;"); ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); executionPlanRuntime.start(); executionPlanRuntime.shutdown(); }

Target:
public void testKalmanMinStreamProcessorExtension1() throws InterruptedException { log.info("KalmanMin TestCase with test attributeExpressionExecutor's length"); SiddhiManager siddhiManager = new SiddhiManager(); String inStreamDefinition = "define stream inputStream (id int ,price double);"; String query = ("@info(name = 'query1') from inputStream#timeseries:kalmanMinMax(price, 0.000001,0.0001, " + "'min') select price, extremaType, id insert into outputStream;"); ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); }
Source:
public boolean executeConnectStoragePoolCommand(Guid storagePoolId) { try { return Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.ConnectStoragePool, new ConnectStoragePoolVDSCommandParameters(getVds() .getId(), storagePoolId, getVds() .getvds_spm_id(), getMasterDomainIdFromDb(), getStoragePool().getmaster_domain_version())) .getSucceeded(); } catch (RuntimeException exp) { log.errorFormat("Could not connect host {0} to pool {1}", getVds() .getvds_name(), getStoragePool().getname()); return false; } }

Target:
private boolean executeConnectStoragePoolCommand(Guid storagePoolId) { try { return runVdsCommand( VDSCommandType.ConnectStoragePool, new ConnectStoragePoolVDSCommandParameters(getVds() .getId(), storagePoolId, getVds() .getvds_spm_id(), getMasterDomainIdFromDb(), getStoragePool().getmaster_domain_version())) .getSucceeded(); } catch (RuntimeException exp) { log.errorFormat("Could not connect host {0} to pool {1}", getVds() .getvds_name(), getStoragePool().getname()); return false; } }
Source:
public String apply(@Nullable SegmentStoreStatisticsEntry stat) { String original = (stat == null) ? "null" : stat.getName(); Collection<ISymbolProvider> symbolProviders = fSymbolProviders; for (ISymbolProvider symbol : symbolProviders) { try { Long address = Long.decode(original); String res = symbol.getSymbolText(address); if (res != null) { return res; } return "0x" + Long.toHexString(address); } catch (NumberFormatException e) { } } return original; }

Target:
public String apply(@Nullable SegmentStoreStatisticsEntry stat) { String original = (stat == null) ? "null" : stat.getName(); Collection<ISymbolProvider> symbolProviders = fSymbolProviders; Long address = null; for (ISymbolProvider symbol : symbolProviders) { try { address = Long.decode(original); String res = symbol.getSymbolText(address); if (res != null) { return res; } } catch (NumberFormatException e) { } } return address != null ? "0x" + Long.toHexString(address) : original; }
Source:
public DocumentModel getEntryFromSource(String id, boolean fetchReferences) throws DirectoryException { String idFieldName = directory.getSchemaFieldMap().get(getIdField()).getName().getPrefixedName(); DocumentModelList result = doQuery(Collections.singletonMap(idFieldName, id), Collections.emptySet(), Collections.emptyMap(), true, -1, 0, false); if (result.isEmpty()) { return null; } DocumentModel docModel = result.get(0); if (isMultiTenant()) { String tenantId = getCurrentTenantId(); if (StringUtils.isNotBlank(tenantId)) { String entryTenantId = (String) docModel.getProperty(schemaName, TENANT_ID_FIELD); if (StringUtils.isNotBlank(entryTenantId) && !entryTenantId.equals(tenantId)) { return null; } } } return docModel; }

Target:
public DocumentModel getEntryFromSource(String id, boolean fetchReferences) throws DirectoryException { String idFieldName = directory.getSchemaFieldMap().get(getIdField()).getName().getPrefixedName(); DocumentModelList result = doQuery(Collections.singletonMap(idFieldName, id), Collections.emptySet(), Collections.emptyMap(), true, 1, 0, false); if (result.isEmpty()) { return null; } DocumentModel docModel = result.get(0); if (isMultiTenant()) { if (!checkEntryTenantId((String) docModel.getProperty(schemaName, TENANT_ID_FIELD))) { return null; } } return docModel; }
Source:
private static boolean isStringLength(ExpressionTree str, ExpressionTree tree) { Symbol symbol = symbol(str); if (symbol != null && tree.is(Kind.METHOD_INVOCATION)) { MethodInvocationTree invocation = (MethodInvocationTree) tree; if (STRING_LENGTH.matches(invocation) && invocation.methodSelect().is(Kind.MEMBER_SELECT)) { return symbol.equals(symbol(((MemberSelectExpressionTree) invocation.methodSelect()).expression())); } } return false; }

Target:
private static boolean isStringLength(ExpressionTree str, ExpressionTree tree) { if (tree.is(Kind.METHOD_INVOCATION)) { MethodInvocationTree invocation = (MethodInvocationTree) tree; if (STRING_LENGTH.matches(invocation) && invocation.methodSelect().is(Kind.MEMBER_SELECT)) { return isSameSymbol(str, ((MemberSelectExpressionTree) invocation.methodSelect()).expression()); } } return false; }
Source:
public void flushHeadEvenWhenExceptionHappens() throws IOException { final OutputStream output = Mockito.mock(OutputStream.class); final IOException exception = new IOException("Failure"); Mockito.doThrow(exception).when(output) .write( Mockito.any(byte[].class), Mockito.anyInt(), Mockito.anyInt() ); try { new RsPrint(new RsText("World!")) .printHead(output); } catch (final IOException ex) { if (!ex.equals(exception)) { throw ex; } } Mockito.verify(output).flush(); }

Target:
public void flushHeadEvenWhenExceptionHappens() throws IOException { final IOException exception = new IOException("Error"); final FailOutputStream output = new FailOutputStream(exception); try { new RsPrint(new RsText("World!")) .printHead(output); } catch (final IOException ex) { if (!ex.equals(exception)) { throw ex; } } MatcherAssert.assertThat( output.haveFlushed(), Matchers.is(true) ); }
Source:
@Test public void testRequestSuccess() throws Throwable { enqueueFromFile("announce_2016_11_21.json"); AnnouncementClient.Callback cb = mock(AnnouncementClient.Callback.class); request(cb); server().takeRequest(); verify(cb).success(eq(new ArrayList<Card>())); verify(cb, never()).error(any(Throwable.class)); }

Target:
@Test public void testRequestSuccess() throws Throwable { enqueueFromFile("announce_2016_11_21.json"); Callback cb = mock(Callback.class); request(cb); server().takeRequest(); verify(cb).success(anyListOf(Card.class)); verify(cb, never()).error(any(Throwable.class)); }
Source:
public RealmIdentity getRealmIdentity(final Principal principal) throws RealmUnavailableException { if (principal instanceof NamePrincipal) { return new KeyStoreRealmIdentity(principal.getName()); } else { final X500Principal x500Principal = X500PrincipalUtil.asX500Principal(principal); if (x500Principal == null) { return RealmIdentity.NON_EXISTENT; } else { final KeyStore keyStore = this.keyStore; try { final Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { final String alias = aliases.nextElement(); if (keyStore.isCertificateEntry(alias)) { final Certificate certificate = keyStore.getCertificate(alias); if (certificate instanceof X509Certificate && X500PrincipalUtil.asX500Principal(((X509Certificate) certificate).getSubjectX500Principal()).equals(x500Principal)) { return new KeyStoreRealmIdentity(alias); } } } } catch (KeyStoreException e) { throw ElytronMessages.log.failedToReadKeyStore(e); } return RealmIdentity.NON_EXISTENT; } } }

Target:
public RealmIdentity getRealmIdentity(final Principal principal) throws RealmUnavailableException { if (principal instanceof NamePrincipal) { return new KeyStoreRealmIdentity(principal.getName()); } else { final X500Principal x500Principal = X500PrincipalUtil.asX500Principal(principal); if (x500Principal == null) { return RealmIdentity.NON_EXISTENT; } else { final KeyStore keyStore = this.keyStore; try { final Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { final String alias = aliases.nextElement(); if (keyStore.isCertificateEntry(alias)) { final Certificate certificate = keyStore.getCertificate(alias); if (certificate instanceof X509Certificate && x500Principal.equals(X500PrincipalUtil.asX500Principal(((X509Certificate) certificate).getSubjectX500Principal()))) { return new KeyStoreRealmIdentity(alias); } } } } catch (KeyStoreException e) { throw ElytronMessages.log.failedToReadKeyStore(e); } return RealmIdentity.NON_EXISTENT; } } }
Source:
private void collectReferencedTables(ASTIterator iterator, Set<String> result) { while ( iterator.hasNext() ) { AST node = iterator.nextNode(); if ( node instanceof FromReferenceNode ) { FromReferenceNode fromReferenceNode = (FromReferenceNode) node; String[] tables = fromReferenceNode.getReferencedTables(); if ( tables != null ) { Collections.addAll(result, tables); } } else if (node instanceof SqlFragment) { SqlFragment sqlFragment = (SqlFragment) node; FromElement fromElement = sqlFragment.getFromElement(); String role = fromElement.getRole(); if ( role != null ) { result.add( fromElement.getOrigin().getPropertyTableName(role.substring(role.lastIndexOf('.') + 1)) ); } AST withClauseAst = fromElement.getWithClauseAst(); if ( withClauseAst != null ) { collectReferencedTables( new ASTIterator( withClauseAst ), result ); } } } }

Target:
private void collectReferencedTables(ASTIterator iterator, Set<String> result) { while ( iterator.hasNext() ) { AST node = iterator.nextNode(); if ( node instanceof FromReferenceNode ) { FromReferenceNode fromReferenceNode = (FromReferenceNode) node; String[] tables = fromReferenceNode.getReferencedTables(); if ( tables != null ) { Collections.addAll(result, tables); } } else if (node instanceof SqlFragment) { SqlFragment sqlFragment = (SqlFragment) node; FromElement fromElement = sqlFragment.getFromElement(); if (fromElement != null) { String role = fromElement.getRole(); if ( role != null ) { result.add( fromElement.getOrigin().getPropertyTableName(role.substring(role.lastIndexOf('.') + 1)) ); } AST withClauseAst = fromElement.getWithClauseAst(); if ( withClauseAst != null ) { collectReferencedTables( new ASTIterator( withClauseAst ), result ); } } } } }
Source:
private void setSalienceByRowNumbers( final AttributeCol52 modelColumn, final int iModelColumn ) { int salience = (modelColumn.isReverseOrder() ? model.getData().size() : 1); for (int rowNumber = 0; rowNumber < model.getData().size(); rowNumber++) { final List<DTCellValue52> modelRow = model.getData().get( rowNumber ); final DTCellValue52 modelCell = modelRow.get( iModelColumn ); modelCell.setNumericValue( salience ); uiModel.setCellValueInternal(rowNumber, iModelColumn, gridWidgetCellFactory.convertCell( modelCell, modelColumn, cellUtilities, columnUtilities ) ); if ( modelColumn.isReverseOrder() ) { salience--; } else { salience++; } } uiModel.indexColumn( iModelColumn ); }

Target:
private void setSalienceByRowNumbers( final AttributeCol52 modelColumn, final int iModelColumn ) { int salience = modelColumn.isReverseOrder() ? model.getData().size() : 1; for (int rowNumber = 0; rowNumber < model.getData().size(); rowNumber++) { final List<DTCellValue52> modelRow = model.getData().get( rowNumber ); final DTCellValue52 modelCell = modelRow.get( iModelColumn ); modelCell.setNumericValue( salience ); uiModel.setCellValueInternal(rowNumber, iModelColumn, gridWidgetCellFactory.convertCell( modelCell, modelColumn, cellUtilities, columnUtilities ) ); if ( modelColumn.isReverseOrder() ) { salience--; } else { salience++; } } uiModel.indexColumn( iModelColumn ); }
Source:
public void saveOrUpdate(ChannelDTO channel) { Assert.notNull(channel); Assert.notNull(channel.getId()); Assert.notNull(channel.getName()); ChannelEntity entity = modelMapper.map(channel, ChannelEntity.class); try { channelRepository.save(entity); } catch (ConstraintViolationException | DataIntegrityViolationException ex) { log.error("Save to repository failed.", ex); String channelName = channel.getName(); throw new DuplicateRecordException(channelName, "Duplication occurred when saving channel: " + channelName, ex); } }

Target:
public void saveOrUpdate(ChannelDTO channel) { Assert.notNull(channel); Assert.notNull(channel.getName()); ChannelEntity entity = modelMapper.map(channel, ChannelEntity.class); try { channelRepository.save(entity); } catch (ConstraintViolationException | DataIntegrityViolationException ex) { log.error("Save to repository failed.", ex); String channelName = channel.getName(); throw new DuplicateRecordException(channelName, "Duplication occurred when saving channel: " + channelName, ex); } }
Source:
private ScriptEngine buildEngine() throws ScriptException, IOException { ScriptEngine nashorn = new ScriptEngineManager().getEngineByName("nashorn"); Map<String, Object> data = Maps.newHashMap(); this._bindings = new SimpleBindings(data); data.put("__tapestry", buildNashornModuleLoader(nashorn)); nashorn.eval(read("META-INF/modules/eddyson/react/isomorphic/polyfill.js"), this._bindings); nashorn.eval(read("META-INF/modules/eddyson/react/isomorphic/r.js"), this._bindings); nashorn.eval(read("META-INF/modules/eddyson/react/isomorphic/r-config.js"), this._bindings); return nashorn; }

Target:
private ScriptEngine buildEngine() throws ScriptException, IOException { ScriptEngine nashorn = new ScriptEngineManager().getEngineByName("nashorn"); nashorn.getBindings(ScriptContext.ENGINE_SCOPE).put("__tapestry", this.moduleLoaderFactory.buildModuleLoader(nashorn)); nashorn.eval(read(classpathResource("de/eddyson/tapestry/react/services/isomorphic/polyfill.js"))); nashorn.eval(read(classpathResource("de/eddyson/tapestry/react/services/isomorphic/r-patched.js"))); nashorn.eval(read(classpathResource("de/eddyson/tapestry/react/services/isomorphic/r-config.js"))); nashorn.eval(read(classpathResource("de/eddyson/tapestry/react/services/isomorphic/run.js"))); return nashorn; }
Source:
public void acceptsNoContentLengthOnClosedConnection() throws Exception { final String text = "Close Test"; final ByteArrayOutputStream output = new ByteArrayOutputStream(); final String greetings = "Hi everyone"; try (ServerSocket server = new ServerSocket(0)) { new Thread( new Runnable() { @Override public void run() { try { new BkBasic(new TkText(text)).accept( server.accept() ); } catch (final IOException exception) { throw new IllegalStateException(exception); } } } ).start(); try (Socket socket = new Socket( server.getInetAddress(), server.getLocalPort() ) ) { socket.getOutputStream().write( new JoinedText( BkBasicTest.CRLF, BkBasicTest.POST, BkBasicTest.HOST, "Connection: Close", "", greetings ).asString().getBytes() ); final InputStream input = socket.getInputStream(); final byte[] buffer = new byte[4096]; for (int count = input.read(buffer); count != -1; count = input.read(buffer)) { output.write(buffer, 0, count); } } } MatcherAssert.assertThat( output.toString(), Matchers.containsString(text) ); }

Target:
public void acceptsNoContentLengthOnClosedConnection() throws Exception { final String text = "Close Test"; final ByteArrayOutputStream output = new ByteArrayOutputStream(); final String greetings = "Hi everyone"; try (ServerSocket server = new ServerSocket(0)) { new Thread( new Runnable() { @Override public void run() { try { new BkBasic(new TkText(text)).accept( server.accept() ); } catch (final IOException exception) { throw new IllegalStateException(exception); } } } ).start(); try (Socket socket = new Socket( server.getInetAddress(), server.getLocalPort() ) ) { socket.getOutputStream().write( new BytesOf( new JoinedText( BkBasicTest.CRLF, BkBasicTest.POST, BkBasicTest.HOST, "Connection: Close", "", greetings ) ).asBytes() ); final InputStream input = socket.getInputStream(); final byte[] buffer = new byte[4096]; for (int count = input.read(buffer); count != -1; count = input.read(buffer)) { output.write(buffer, 0, count); } } } MatcherAssert.assertThat( output.toString(), Matchers.containsString(text) ); }
Source:
public void init(FeedbackSessionResultsBundle bundle) { if (bundle == null) { return; } questionCommentsMap = new LinkedHashMap<>(); for (Map.Entry<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> responseEntries : bundle.getQuestionResponseMap().entrySet()) { FeedbackQuestionAttributes question = bundle.questions.get(responseEntries.getKey().getId()); Map<FeedbackParticipantType, Boolean> responseVisibilityMap = getResponseVisibilityMap(question); List<InstructorFeedbackResponseComment> responseCommentList = buildInstructorFeedbackResponseComments( responseEntries.getValue(), bundle, question, responseVisibilityMap); questionCommentsMap.put(question, responseCommentList); } }

Target:
private void init(FeedbackSessionResultsBundle bundle) { if (bundle == null) { return; } questionCommentsMap = new LinkedHashMap<>(); for (Map.Entry<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> responseEntries : bundle.getQuestionResponseMap().entrySet()) { FeedbackQuestionAttributes question = bundle.questions.get(responseEntries.getKey().getId()); Map<FeedbackParticipantType, Boolean> responseVisibilityMap = getResponseVisibilityMap(question); List<InstructorFeedbackResponseComment> responseCommentList = buildInstructorFeedbackResponseComments( responseEntries.getValue(), bundle, question, responseVisibilityMap); questionCommentsMap.put(question, responseCommentList); } }
Source:
protected int run() throws Exception { boolean errorOccurred = false; final Jenkins jenkins = Jenkins.getActiveInstance(); final HashSet<String> hs = new HashSet<String>(); hs.addAll(nodes); List<String> names = null; for (String node_s : hs) { Computer computer = null; try { computer = jenkins.getComputer(node_s); if (computer == null) { if (names == null) { names = new ArrayList<String>(); for (Computer c : jenkins.getComputers()) if (!c.getName().isEmpty()) names.add(c.getName()); } String adv = EditDistance.findNearest(node_s, names); throw new IllegalArgumentException(adv == null ? hudson.model.Messages.Computer_NoSuchSlaveExistsWithoutAdvice(node_s) : hudson.model.Messages.Computer_NoSuchSlaveExists(node_s, adv)); } computer.cliDisconnect(cause); } catch (Exception e) { if (hs.size() == 1) { throw e; } final String errorMsg = String.format(node_s + ": " + e.getMessage()); stderr.println(errorMsg); errorOccurred = true; continue; } } if (errorOccurred) { throw new AbortException("Error occured while performing this command, see previous stderr output."); } return 0; }

Target:
protected int run() throws Exception { boolean errorOccurred = false; final Jenkins jenkins = Jenkins.getActiveInstance(); final HashSet<String> hs = new HashSet<String>(); hs.addAll(nodes); List<String> names = null; for (String node_s : hs) { Computer computer = null; try { computer = jenkins.getComputer(node_s); if (computer == null) { if (names == null) { names = new ArrayList<String>(); for (Computer c : jenkins.getComputers()) { if (!c.getName().isEmpty()) { names.add(c.getName()); } } } String adv = EditDistance.findNearest(node_s, names); throw new IllegalArgumentException(adv == null ? hudson.model.Messages.Computer_NoSuchSlaveExistsWithoutAdvice(node_s) : hudson.model.Messages.Computer_NoSuchSlaveExists(node_s, adv)); } computer.cliDisconnect(cause); } catch (Exception e) { if (hs.size() == 1) { throw e; } stderr.println(String.format(node_s + ": " + e.getMessage())); errorOccurred = true; continue; } } if (errorOccurred) { throw new AbortException("Error occured while performing this command, see previous stderr output."); } return 0; }
Source:
CacheManagerWrapper() { manager = Caching.getCachingProvider().getCacheManager(); constructCache(manager, ASSET_FILENAME_CACHE, String.class, String.class, config -> { config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 15))); }); constructCache(manager, ASSET_CONTENT_CACHE, String.class, Object.class, config -> { config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 15))); }); constructCache(manager, TAXONOMY_GRAPH_CACHE, String.class, TaxonomyGraph.class, config -> { }); constructCache(manager, TAXONOMY_COUNT_TABLE_CACHE, String.class, TaxonomyCountTable.class, config -> { }); constructCache(manager, RECENT_ARTICLE_CACHE, String.class, List.class, config -> { config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 30))); }); constructCache(manager, REMOTE_SERVICE_CACHE, RemoteCacheKey.class, Object.class, config -> { config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.HOURS, 1))); }); }

Target:
CacheManagerWrapper() { manager = Caching.getCachingProvider().getCacheManager(); constructCache(manager, ASSET_FILENAME_CACHE, String.class, String.class, config -> { config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 15))); }); constructCache(manager, ASSET_CONTENT_CACHE, String.class, Object.class, config -> { config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 15))); }); constructCache(manager, TAXONOMY_GRAPH_CACHE, String.class, TaxonomyGraph.class, config -> { config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(DEFAULT_TTL)); }); constructCache(manager, TAXONOMY_COUNT_TABLE_CACHE, String.class, TaxonomyCountTable.class, config -> { config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(DEFAULT_TTL)); }); constructCache(manager, RECENT_ARTICLE_CACHE, String.class, List.class, config -> { config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 30))); }); for (RemoteCacheSpace remoteCacheSpace : RemoteCacheSpace.values()) { constructCache(manager, remoteCacheSpace.getCacheName(), RemoteCacheKey.class, Object.class, config -> { config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(remoteCacheSpace.getTimeToLive())); }); } }
Source:
public void claim(String deploymentId, Long taskId, String userId) { UserTaskInstanceDesc task = dataService.getTaskById(taskId); validateTask(deploymentId, taskId, task); RuntimeManager manager = getRuntimeManager(task); if (manager == null) { logger.warn("Cannot find runtime manager for task {}", taskId); return; } RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(task.getProcessInstanceId())); try { TaskService taskService = engine.getTaskService(); taskService.claim(taskId, userId); } catch(PermissionDeniedException e){ throw new PermissionDeniedException(e.getMessage()); } catch(TaskNotFoundException e){ throw new TaskNotFoundException(e.getMessage()); } finally { disposeRuntimeEngine(manager, engine); } }

Target:
public void claim(String deploymentId, Long taskId, String userId) { UserTaskInstanceDesc task = dataService.getTaskById(taskId); validateTask(deploymentId, taskId, task); RuntimeManager manager = getRuntimeManager(task); if (manager == null) { logger.warn("Cannot find runtime manager for task {}", taskId); return; } RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(task.getProcessInstanceId())); try { TaskService taskService = engine.getTaskService(); taskService.claim(taskId, userId); } finally { disposeRuntimeEngine(manager, engine); } }
Source:
protected void addHeaders(HttpServletRequest request, HttpServletResponse response, RequestFilterConfig config) { addConfiguredHeaders(response); if (request.getMethod().equals("GET")) { if (config.isCached()) { addCacheHeaders(response, config.isPrivate(), config.getCacheTime()); } else if (config.isPrivate()) { response.setHeader("Cache-Control", "private, no-cache, no-store"); } } }

Target:
protected void addHeaders(HttpServletRequest request, HttpServletResponse response, RequestFilterConfig config) { addConfiguredHeaders(response); if (request.getMethod().equals("GET")) { addCacheHeaders(response, config); } }
Source:
public static IIrsServer createIrsServer(VdsProtocol vdsProtocol, String hostname, int port, int clientTimeOut, int connectionTimeOut, int clientRetries, int heartbeat) { IIrsServer irsServer = null; if (VdsProtocol.STOMP == vdsProtocol) { irsServer = new JsonRpcIIrsServer(JsonRpcUtils.createStompClient(hostname, port, connectionTimeOut, clientTimeOut, clientRetries, heartbeat, Config.<Boolean> getValue(ConfigValues.EncryptHostCommunication), Config.<String> getValue(ConfigValues.VdsmSLLProtocol))); } else if (VdsProtocol.XML == vdsProtocol){ Pair<IrsServerConnector, HttpClient> returnValue = XmlRpcUtils.getConnection(hostname, port, clientTimeOut, connectionTimeOut, clientRetries, IrsServerConnector.class, Config.<Boolean> getValue(ConfigValues.EncryptHostCommunication)); irsServer = new IrsServerWrapper(returnValue.getFirst(), returnValue.getSecond()); } return irsServer; }

Target:
public static IIrsServer createIrsServer(VdsProtocol vdsProtocol, String hostname, int port, int clientTimeOut, int connectionTimeOut, int clientRetries, int heartbeat) { IIrsServer irsServer = null; if (VdsProtocol.STOMP == vdsProtocol) { irsServer = new JsonRpcIIrsServer(JsonRpcUtils.createStompClient(hostname, port, connectionTimeOut, clientTimeOut, clientRetries, heartbeat, Config.<Boolean> getValue(ConfigValues.EncryptHostCommunication), Config.<String> getValue(ConfigValues.VdsmSSLProtocol))); } else if (VdsProtocol.XML == vdsProtocol){ Pair<IrsServerConnector, HttpClient> returnValue = XmlRpcUtils.getConnection(hostname, port, clientTimeOut, connectionTimeOut, clientRetries, IrsServerConnector.class, Config.<Boolean> getValue(ConfigValues.EncryptHostCommunication)); irsServer = new IrsServerWrapper(returnValue.getFirst(), returnValue.getSecond()); } return irsServer; }
Source:
protected void onResume() { super.onResume(); disposable = realm.where(Person.class).isNotNull("githubUserName").findAllSortedAsync("name").asFlowable() .filter(people -> people.isLoaded()) .flatMap(people -> Flowable.fromIterable(people)) .flatMap(person -> api.user(person.getGithubUserName())) .map(gitHubUser -> new UserViewModel(gitHubUser.name, gitHubUser.public_repos, gitHubUser.public_gists)) .observeOn(AndroidSchedulers.mainThread()) .subscribe(user -> { TextView userView = new TextView(RetrofitExample.this); userView.setText( String.format(Locale.US, "%s : %d/%d", user.getUsername(), user.getPublicRepos(), user.getPublicGists())); container.addView(userView); }, throwable -> throwable.printStackTrace()); }

Target:
protected void onResume() { super.onResume(); disposable = realm.where(Person.class).isNotNull("githubUserName").findAllSortedAsync("name").asFlowable() .filter(people -> people.isLoaded()) .switchMap(people -> Flowable.fromIterable(people)) .flatMap(person -> api.user(person.getGithubUserName())) .map(gitHubUser -> new UserViewModel(gitHubUser.name, gitHubUser.public_repos, gitHubUser.public_gists)) .observeOn(AndroidSchedulers.mainThread()) .subscribe(user -> { TextView userView = new TextView(RetrofitExample.this); userView.setText( String.format(Locale.US, "%s : %d/%d", user.getUsername(), user.getPublicRepos(), user.getPublicGists())); container.addView(userView); }, throwable -> throwable.printStackTrace()); }
Source:
protected Token listToken() { Token token = new Token(); if (SecurityConstants.AUTH_PROVIDER.get() == null || SecurityConstants.NO_PROVIDER.equalsIgnoreCase(SecurityConstants.AUTH_PROVIDER.get())) { return token; } if (SecurityConstants.INTERNAL_AUTH_PROVIDERS.contains(SecurityConstants.AUTH_PROVIDER.get())) { for (TokenCreator tokenCreator : tokenCreators) { if (tokenCreator.isConfigured() && tokenCreator.providerType().equalsIgnoreCase(SecurityConstants.AUTH_PROVIDER.get())) { if (!SecurityConstants.SECURITY.get()) { tokenCreator.reset(); } token = tokenCreator.getCurrentToken(); break; } } return token; } else { if (externalAuthProvider.isConfigured()) { return externalAuthProvider.readCurrentToken(); } } return token; }

Target:
protected Token listToken() { Token token = new Token(); if (SecurityConstants.AUTH_PROVIDER.get() == null || SecurityConstants.NO_PROVIDER.equalsIgnoreCase(SecurityConstants.AUTH_PROVIDER.get())) { return token; } if (SecurityConstants.INTERNAL_AUTH_PROVIDERS.contains(SecurityConstants.AUTH_PROVIDER.get())) { for (TokenCreator tokenCreator : tokenCreators) { if (tokenCreator.isConfigured() && tokenCreator.providerType().equalsIgnoreCase(SecurityConstants.AUTH_PROVIDER.get())) { token = tokenCreator.getCurrentToken(); break; } } return token; } else { if (externalAuthProvider.isConfigured()) { return externalAuthProvider.readCurrentToken(); } } return token; }
Source:
public void addStreamStoreDefinition(StreamStoreDefinition streamStoreDefinition) { streamStoreDefinition.getTables().forEach(this::addTableDefinition); StreamStoreRenderer renderer = streamStoreDefinition.getRenderer(packageName, name); Multimap<String, Supplier<OnCleanupTask>> streamStoreCleanupTasks = streamStoreDefinition.getCleanupTasks( packageName, name, renderer, namespace); StreamStoreCleanupMetadata metadata = ImmutableStreamStoreCleanupMetadata.builder() .numHashedRowComponents(streamStoreDefinition.getNumberOfRowComponentsHashed()) .streamIdType(streamStoreDefinition.getIdType()) .build(); streamStoreDefinition.getTables().forEach( (tableName, definition) -> { streamStoreCleanupMetadata.put(tableName, metadata); }); cleanupTasks.putAll(streamStoreCleanupTasks); streamStoreRenderers.add(renderer); }

Target:
public void addStreamStoreDefinition(StreamStoreDefinition streamStoreDefinition) { streamStoreDefinition.getTables().forEach(this::addTableDefinition); StreamStoreRenderer renderer = streamStoreDefinition.getRenderer(packageName, name); Multimap<String, Supplier<OnCleanupTask>> streamStoreCleanupTasks = streamStoreDefinition.getCleanupTasks( packageName, name, renderer, namespace); StreamStoreCleanupMetadata metadata = ImmutableStreamStoreCleanupMetadata.builder() .numHashedRowComponents(streamStoreDefinition.getNumberOfRowComponentsHashed()) .streamIdType(streamStoreDefinition.getIdType()) .build(); streamStoreDefinition.getTables().forEach( (tableName, definition) -> streamStoreCleanupMetadata.put(tableName, metadata)); cleanupTasks.putAll(streamStoreCleanupTasks); streamStoreRenderers.add(renderer); }
Source:
private Object getService() throws InterruptedException { if (timeout < 0) { tracker.open(); try { return tracker.getService(); } finally { tracker.close(); } } return getServiceFromTracker(tracker, timeout); }

Target:
private Object getService() throws InterruptedException { if (timeout < 0) { tracker.open(); try { return tracker.getService(); } finally { tracker.close(); } } return waitForServiceFromTracker(tracker, timeout); }
Source:
private IRequirement getRequirement(SiteIU iu) { String id = iu.getID(); String range = iu.getRange(); String type = iu.getQueryType(); String expression = iu.getQueryExpression(); String[] params = iu.getQueryParams(); if (id != null) { VersionRange vRange = new VersionRange(range); return MetadataFactory.createRequirement(IInstallableUnit.NAMESPACE_IU_ID, id, vRange, null, false, false); } else if (type.equals("match")) { String[] allArgs = new String[(params == null ? 0 : params.length) + 1]; allArgs[0] = id; if (params != null) System.arraycopy(params, 0, allArgs, 1, params.length); IMatchExpression<IInstallableUnit> iuMatcher = ExpressionUtil.getFactory() .<IInstallableUnit> matchExpression(ExpressionUtil.parse(expression), id); return MetadataFactory.createRequirement(iuMatcher, null, 0, 1, true); } else if (type.equals("context")) { throw new IllegalStateException("Context iu queries are not supported in Tycho. Faulty expression is " + expression); } return null; }

Target:
private IRequirement getRequirement(SiteIU iu) { String id = iu.getID(); String range = iu.getRange(); String type = iu.getQueryType(); String expression = iu.getQueryExpression(); String[] params = iu.getQueryParams(); if (id != null) { VersionRange vRange = new VersionRange(range); return MetadataFactory.createRequirement(IInstallableUnit.NAMESPACE_IU_ID, id, vRange, null, false, false); } else if ("match".equals(type)) { String[] allArgs = new String[(params == null ? 0 : params.length) + 1]; allArgs[0] = id; if (params != null) System.arraycopy(params, 0, allArgs, 1, params.length); IMatchExpression<IInstallableUnit> iuMatcher = ExpressionUtil.getFactory() .<IInstallableUnit> matchExpression(ExpressionUtil.parse(expression), params); return MetadataFactory.createRequirement(iuMatcher, null, 0, 1, true); } else if ("context".equals(type)) { throw new IllegalStateException( "Context iu queries are not supported in Tycho. Faulty expression is " + expression); } return null; }
Source:
public static Logger getLogger(Class<?> key) { return LOGGERS.computeIfAbsent(key.getName(), name -> new FailsafeLogger(LOGGER_ADAPTER.getLogger(key))); }

Target:
public static Logger getLogger(Class<?> key) { return LOGGERS.computeIfAbsent(key.getName(), name -> new FailsafeLogger(LOGGER_ADAPTER.getLogger(name))); }
Source:
public void setResponse(ClearReplyMessage response) { if (response.getException() == null) { this.returnValue = (Boolean) response.getReturnValue(); } }

Target:
public void setResponse(ClearReplyMessage response) { if (response.getException() == null) { this.returnValue = (boolean) response.getReturnValue(); } }
Source:
private void displayBrowserCompatibilityWarning() { if (!internalConfiguration.isCurrentBrowserSupported() && DisplayBrowserCompatibilityWarning.getValue()) { final AlertPanel alert = getAlertManager().showAlert(Type.WARNING, SafeHtmlUtils.fromSafeConstant( messages.browserNotSupported(dynamicMessages.compatibleBrowserDocsUrl()))); final Timer timer = new Timer() { @Override public void run() { getAlertManager().detachAlert(alert); } }; alert.getWidget().addCloseHandler(new AlertCloseHandler() { @Override public void onClose(AlertCloseEvent evt) { timer.cancel(); } }); timer.schedule(5000); } }

Target:
private void displayBrowserCompatibilityWarning() { if (!internalConfiguration.isCurrentBrowserSupported() && DisplayBrowserCompatibilityWarning.getValue()) { getAlertManager().showAlert(Type.WARNING, SafeHtmlUtils.fromSafeConstant( messages.browserNotSupported(dynamicMessages.compatibleBrowserDocsUrl())), 5000); } }
Source:
public void ensureUnsignedInteger_isDecodedWithCorrectSignum() { byte[] bigNumberByteArray = {-13, -75, 19, 86, -119, 67, 112, -4, 118, -86, 98, -46, 103, -42, -126, 63, -60, -15, -87, 57, 43, 11, -17, -52, 0, 3, -65, 14, -67, -40, 65, 119}; SolidityType testObject = new SolidityType.UnsignedIntType("uint256"); Object decode = testObject.decode(bigNumberByteArray); assertEquals(decode.getClass(), BigInteger.class); BigInteger actualBigInteger = (BigInteger) decode; BigInteger expectedBigInteger = new BigInteger("f3b51356894370fc76aa62d267d6823fc4f1a9392b0befcc0003bf0ebdd84177", 16); assertEquals(expectedBigInteger, actualBigInteger); }

Target:
public void ensureUnsignedInteger_isDecodedWithCorrectSignum() { byte[] bigNumberByteArray = { -13, -75, 19, 86, -119, 67, 112, -4, 118, -86, 98, -46, 103, -42, -126, 63, -60, -15, -87, 57, 43, 11, -17, -52, 0, 3, -65, 14, -67, -40, 65, 119 }; SolidityType testObject = new SolidityType.UnsignedIntType("uint256"); Object decode = testObject.decode(bigNumberByteArray); assertEquals(decode.getClass(), BigInteger.class); BigInteger actualBigInteger = (BigInteger) decode; BigInteger expectedBigInteger = new BigInteger(Hex.toHexString(bigNumberByteArray), 16); assertEquals(expectedBigInteger, actualBigInteger); }
Source:
public ObjectTable.Writer getObjectWriter(Object obj) { BiConsumer<ObjectOutput, Object> writer = null; Class<?> clazz = obj.getClass(); AdvancedExternalizer internalExt = getExternalizer(internalExts, clazz); if (internalExt != null) writer = (out, object) -> writeInternalClean(object, internalExt, out); AdvancedExternalizer externalExt = getExternalizer(externalExts, clazz); if (externalExt != null) writer = (out, object) -> writeExternalClean(object, externalExt, out); boolean isMarshallable; try { isMarshallable = persistenceMarshaller.isMarshallable(obj); } catch (Exception ignore) { isMarshallable = false; } if (isMarshallable) writer = (out, object) -> writeUnknownClean(persistenceMarshaller, obj, out); return writer != null ? writer::accept : null; }

Target:
public ObjectTable.Writer getObjectWriter(Object obj) { Class<?> clazz = obj.getClass(); AdvancedExternalizer internalExt = getExternalizer(internalExts, clazz); if (internalExt != null) return (out, object) -> writeInternalClean(object, internalExt, out); AdvancedExternalizer externalExt = getExternalizer(externalExts, clazz); if (externalExt != null) return (out, object) -> writeExternalClean(object, externalExt, out); try { if (persistenceMarshaller.isMarshallable(obj)) return (out, object) -> writeUnknownClean(persistenceMarshaller, obj, out); } catch (Exception ignore) { } return null; }
Source:
public void tearDown() throws Exception { workspaceServiceClient.delete(ws.getName(), user.getName()); }

Target:
public void tearDown() throws Exception { workspaceServiceClient.delete(workspaceName, user.getName()); workspaceServiceClient.delete(MIN_WORKSPACE_NAME, user.getName()); workspaceServiceClient.delete(MAX_WORKSPACE_NAME, user.getName()); }
Source:
private LRNLayer(@Parameter(LayerIndex.class) final int index, @Parameter(LayerInputShape.class) final String inputShape, @Parameter(LocalSize.class) final int localSize, @Parameter(Alpha.class) final float alpha, @Parameter(Beta.class) final float beta, @Parameter(K.class) final float k, final MatrixFactory matrixFactory) { super(index, inputShape); this.localSize = localSize; this.alpha = alpha; this.beta = beta; this.k = k; this.paddingSize = (localSize - 1) / 2; this.matrixFactory = matrixFactory; this.scale = null; this.layerError = null; if (getInputShape().length == 2) { this.inputChannel = 1; this.inputSize = getInputShape()[0] * getInputShape()[1]; } else { this.inputChannel = getInputShape()[0]; this.inputSize = getInputShape()[1] * getInputShape()[2]; } }

Target:
private LRNLayer(@Parameter(LayerIndex.class) final int index, @Parameter(LayerInputShape.class) final String inputShape, @Parameter(LocalSize.class) final int localSize, @Parameter(Alpha.class) final float alpha, @Parameter(Beta.class) final float beta, @Parameter(K.class) final float k, final MatrixFactory matrixFactory) { super(index, inputShape); this.localSize = localSize; this.alpha = alpha; this.beta = beta; this.k = k; this.paddingSize = (localSize - 1) / 2; this.matrixFactory = matrixFactory; if (getInputShape().length == 2) { this.inputChannel = 1; this.inputSize = getInputShape()[0] * getInputShape()[1]; } else { this.inputChannel = getInputShape()[0]; this.inputSize = getInputShape()[1] * getInputShape()[2]; } }
Source:
public Object getAllColumnsModeratelyWideRowWithManyUncommitted( DirtyModeratelyWideRowTable table, Blackhole blackhole) { return getAllRowsAndAssert(table, blackhole, count -> Preconditions.checkState(count == table.getNumReadableCols(), "Should be %s columns, but was: %s", table.getNumReadableCols(), count)); }

Target:
public void getAllColumnsModeratelyWideRowWithManyUncommitted( DirtyModeratelyWideRowTable table, Blackhole blackhole) { getAllRowsAndAssert(table, blackhole, count -> Preconditions.checkState(count == table.getNumReadableCols(), "Should be %s columns, but was: %s", table.getNumReadableCols(), count)); }
Source:
protected void createClient(Section section, FormToolkit toolkit) { section.setLayout(FormLayoutFactory.createClearGridLayout(false, 1)); GridData data = new GridData(GridData.FILL_HORIZONTAL); data.verticalAlignment = SWT.TOP; data.horizontalSpan = 2; section.setLayoutData(data); section.setText(PDEUIMessages.InformationSection_0); Composite client = toolkit.createComposite(section); client.setLayout(FormLayoutFactory.createSectionClientGridLayout(false, 2)); client.setLayoutData(new GridData(GridData.FILL_BOTH)); fNameText = toolkit.createText(client, getTarget().getName()); fNameText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fNameText.addModifyListener(e -> { String value = fNameText.getText().trim(); String name = getTarget().getName(); if(value!=null) { if (!value.equals(name)) { getTarget().setName(value.length() > 0 ? value : null); markDirty(); } } }); fNameTextValidator = new TextValidator(fPage.getManagedForm(), fNameText, null, true) { @Override protected boolean autoEnable() { if (getText().getEditable() == false) { return false; } return true; } @Override protected boolean validateControl() { return ControlValidationUtility.validateRequiredField(fNameText.getText(), fNameTextValidator, IMessageProvider.ERROR); } }; toolkit.paintBordersFor(client); section.setClient(client); }

Target:
protected void createClient(Section section, FormToolkit toolkit) { section.setLayout(FormLayoutFactory.createClearGridLayout(false, 1)); GridData data = new GridData(GridData.FILL_HORIZONTAL); data.verticalAlignment = SWT.TOP; data.horizontalSpan = 2; section.setLayoutData(data); section.setText(PDEUIMessages.InformationSection_0); Composite client = toolkit.createComposite(section); client.setLayout(FormLayoutFactory.createSectionClientGridLayout(false, 2)); client.setLayoutData(new GridData(GridData.FILL_BOTH)); fNameText = toolkit.createText(client, getTarget().getName()); fNameText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fNameText.addModifyListener(e -> { String value = fNameText.getText().trim(); String name = getTarget().getName(); if (!value.equals(name)) { getTarget().setName(value.length() > 0 ? value : null); markDirty(); } }); fNameTextValidator = new TextValidator(fPage.getManagedForm(), fNameText, null, true) { @Override protected boolean autoEnable() { if (getText().getEditable() == false) { return false; } return true; } @Override protected boolean validateControl() { return ControlValidationUtility.validateRequiredField(fNameText.getText(), fNameTextValidator, IMessageProvider.ERROR); } }; toolkit.paintBordersFor(client); section.setClient(client); }
Source:
public void testComplexTypeWithProperties() { RecordDataSchema mainRecordSchema = (RecordDataSchema) parsePdlSchema("ComplexTypeWithProperties.pdl"); RecordDataSchema.Field arrayField = mainRecordSchema.getField("arrayField"); Assert.assertNotNull(arrayField); Assert.assertFalse(arrayField.getType().getProperties().isEmpty()); DataMap expectedProperty = new DataMap(); DataMap validate = new DataMap(); validate.put("minSize", 1); expectedProperty.put("validate", validate); Assert.assertEquals(arrayField.getType().getProperties(), expectedProperty); RecordDataSchema.Field mapField = mainRecordSchema.getField("mapField"); Assert.assertNotNull(mapField); Assert.assertFalse(mapField.getType().getProperties().isEmpty()); Assert.assertEquals(mapField.getType().getProperties(), expectedProperty); RecordDataSchema.Field unionField = mainRecordSchema.getField("unionField"); Assert.assertNotNull(unionField); Assert.assertFalse(unionField.getType().getProperties().isEmpty()); validate.clear(); validate.put("minValue", 0); Assert.assertEquals(unionField.getType().getProperties(), expectedProperty); }

Target:
public void testComplexTypeWithProperties() { RecordDataSchema mainRecordSchema = (RecordDataSchema) parsePdlSchema("ComplexTypeWithProperties.pdl"); RecordDataSchema.Field arrayField = mainRecordSchema.getField("arrayField"); Assert.assertNotNull(arrayField); Assert.assertFalse(arrayField.getType().getProperties().isEmpty()); DataMap expectedProperty = new DataMap(); DataMap validate = new DataMap(); validate.put("minSize", 1); expectedProperty.put("validate", validate); Assert.assertTrue(arrayField.getProperties().isEmpty()); Assert.assertEquals(arrayField.getType().getProperties(), expectedProperty); RecordDataSchema.Field mapField = mainRecordSchema.getField("mapField"); Assert.assertNotNull(mapField); Assert.assertTrue(mapField.getProperties().isEmpty()); Assert.assertFalse(mapField.getType().getProperties().isEmpty()); Assert.assertEquals(mapField.getType().getProperties(), expectedProperty); RecordDataSchema.Field unionField = mainRecordSchema.getField("unionField"); Assert.assertNotNull(unionField); Assert.assertTrue(unionField.getProperties().isEmpty()); Assert.assertFalse(unionField.getType().getProperties().isEmpty()); validate.clear(); validate.put("minValue", 0); Assert.assertEquals(unionField.getType().getProperties(), expectedProperty); }
Source:
public boolean add(Object o) { if(!(o instanceof Profile)) { return false; } Profile profile = EMFHelper.reloadIntoContext((Profile)o, umlSource); Command command = new ApplyProfileCommand(umlSource, profile, (TransactionalEditingDomain)domain); commands.add(command); commands.add(new ApplyProfileCommand(umlSource, profile, (TransactionalEditingDomain)domain)); return wrappedList.add(o); }

Target:
public boolean add(Object o) { if(!(o instanceof Profile)) { return false; } Profile profile = EMFHelper.reloadIntoContext((Profile)o, umlSource); Command command = new ApplyProfileCommand(umlSource, profile, (TransactionalEditingDomain)domain); commands.add(command); return wrappedList.add(o); }
Source:
private JobModel generateNewJobModel(List<String> processors) { Map<TaskName, Integer> changeLogToPartitionMap = new HashMap<>(); String existingJobModelVersion = zkUtils.getJobModelVersion(); if (existingJobModelVersion != null) { JobModel existingJobModel = zkUtils.getJobModel(existingJobModelVersion); for (ContainerModel containerModel : existingJobModel.getContainers().values()) { containerModel.getTasks().forEach((taskName, taskModel) -> changeLogToPartitionMap.put(taskName, taskModel.getChangelogPartition().getPartitionId())); } } return JobModelManager.readJobModel(this.config, changeLogToPartitionMap, null, streamMetadataCache, processors); }

Target:
private JobModel generateNewJobModel(List<String> processors) { String zkJobModelVersion = zkUtils.getJobModelVersion(); if (zkJobModelVersion != null && !Objects.equals(cachedJobModelVersion, zkJobModelVersion)) { JobModel jobModel = zkUtils.getJobModel(zkJobModelVersion); for (ContainerModel containerModel : jobModel.getContainers().values()) { containerModel.getTasks().forEach((taskName, taskModel) -> changeLogPartitionMap.put(taskName, taskModel.getChangelogPartition().getPartitionId())); } cachedJobModelVersion = zkJobModelVersion; } return JobModelManager.readJobModel(this.config, changeLogPartitionMap, null, streamMetadataCache, processors); }