auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected File getTargetFile(String suffix) { String filename = String.format("test%s.properties", suffix == null ? "" : suffix); return new File(Environment.getDefault().getConfig(), filename); }

Target:
protected File getTargetFile(String suffix) { String filename = String.format("test%s.properties", suffix); return new File(Environment.getDefault().getConfig(), filename); }
Source:
public void testCreateTableWithArrayColumn() throws Exception { String tableName = generateUniqueName(); String schemaName = generateUniqueName(); Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); try (Connection conn = DriverManager.getConnection(getUrl(), props)) { String pTableFullName = SchemaUtil.getQualifiedTableName(schemaName, tableName); String query = "create table " + pTableFullName + "(a_char CHAR(15) NOT NULL, " + "b_char CHAR(10) NOT NULL, " + "c_var_array VARCHAR ARRAY, " + "d_char_array CHAR(15) ARRAY[3] CONSTRAINT PK PRIMARY KEY (a_char, b_char)) " + "TTL=2592000, IMMUTABLE_STORAGE_SCHEME=ONE_CELL_PER_COLUMN, DISABLE_TABLE_SOR=true, REPLICATION_SCOPE=1"; conn.createStatement().execute(query); conn.commit(); String[] args = {"-tb", tableName, "-s", schemaName}; SchemaExtractionTool set = new SchemaExtractionTool(); set.setConf(conn.unwrap(PhoenixConnection.class).getQueryServices().getConfiguration()); set.run(args); Assert.assertEquals(query.toUpperCase(), set.getOutput().toUpperCase()); } }

Target:
public void testCreateTableWithArrayColumn() throws Exception { String tableName = generateUniqueName(); String schemaName = generateUniqueName(); String pTableFullName = SchemaUtil.getQualifiedTableName(schemaName, tableName); String query = "create table " + pTableFullName + "(a_char CHAR(15) NOT NULL, " + "b_char CHAR(10) NOT NULL, " + "c_var_array VARCHAR ARRAY, " + "d_char_array CHAR(15) ARRAY[3] CONSTRAINT PK PRIMARY KEY (a_char, b_char)) " + "TTL=2592000, IMMUTABLE_STORAGE_SCHEME=ONE_CELL_PER_COLUMN, REPLICATION_SCOPE=1"; List<String> queries = new ArrayList<String>(){}; queries.add(query); String result = runSchemaExtractionTool(schemaName, tableName, null, queries); Assert.assertEquals(query.toUpperCase(), result.toUpperCase()); }
Source:
public void testMigrationTranslator() throws Exception { ResearchProject researchProject = new ResearchProject(); String id = "101"; researchProject.setId(id); Submission submission = new Submission(); submission.setResearchProjectSnapshot(researchProject); DBOSubmission backup = new DBOSubmission(); backup.setAccessRequirementId(1L); backup.setCreatedBy(2L); backup.setCreatedOn(3L); backup.setDataAccessRequestId(4L); backup.setEtag("etag"); backup.setId(5L); backup.setSubmissionSerialized(JDOSecondaryPropertyUtils.compressObject(X_STREAM, submission)); assertNull(backup.getResearchProjectId()); DBOSubmission dbo = backup.getTranslator().createDatabaseObjectFromBackup(backup); assertEquals(Long.parseLong(id), dbo.getResearchProjectId().longValue()); assertEquals(dbo, backup); }

Target:
public void testMigrationTranslator() throws Exception { ResearchProject researchProject = new ResearchProject(); String id = "101"; researchProject.setId(id); Submission submission = new Submission(); submission.setResearchProjectSnapshot(researchProject); DBOSubmission backup = new DBOSubmission(); backup.setAccessRequirementId(1L); backup.setCreatedBy(2L); backup.setCreatedOn(3L); backup.setDataAccessRequestId(4L); backup.setEtag("etag"); backup.setId(5L); backup.setSubmissionSerialized(JDOSecondaryPropertyUtils.compressObject(X_STREAM, submission)); assertNull(backup.getResearchProjectId()); DBOSubmission dbo = (new DBOSubmission()).getTranslator().createDatabaseObjectFromBackup(backup); assertEquals(Long.parseLong(id), dbo.getResearchProjectId().longValue()); assertEquals(dbo, backup); }
Source:
@Test public void shouldOpenCompareEditorInWorkspaceModel() throws Exception { resetRepository(PROJ1); createTag(PROJ1, "compare2"); changeFilesInProject(); showDialog(PROJ1, "Team", "Synchronize..."); bot.shell("Synchronize repository: " + REPO1 + File.separator + ".git") .activate(); bot.comboBox(2) .setSelection(UIText.SynchronizeWithAction_tagsName); bot.comboBox(3).setSelection("compare2"); bot.button(IDialogConstants.OK_LABEL).click(); SWTBotView syncView = bot.viewByTitle("Synchronize"); syncView.toolbarDropDownButton("Show File System Resources").click() .menuItem("Workspace").click(); SWTBotTree syncViewTree = syncView.bot().tree(); TestUtil.waitUntilTreeHasNodeWithText(bot, syncViewTree, "> GeneralProject", 10000); syncViewTree.getAllItems()[0].expand().getItems()[0].expand() .getItems()[0].doubleClick(); SWTBot compare = bot.editorByTitle(FILE1).bot(); assertNotNull(compare); }

Target:
@Test public void shouldOpenCompareEditorInWorkspaceModel() throws Exception { resetRepository(PROJ1); createTag(PROJ1, "compare2"); changeFilesInProject(); showDialog(PROJ1, "Team", "Synchronize..."); bot.shell("Synchronize repository: " + REPO1 + File.separator + ".git") .activate(); bot.comboBox(2) .setSelection(UIText.SynchronizeWithAction_tagsName); bot.comboBox(3).setSelection("compare2"); bot.button(IDialogConstants.OK_LABEL).click(); SWTBotView syncView = bot.viewByTitle("Synchronize"); syncView.toolbarDropDownButton("Show File System Resources").click() .menuItem("Workspace").click(); SWTBotTree syncViewTree = syncView.bot().tree(); TestUtil.waitUntilTreeHasNodeWithText(bot, syncViewTree, "> " + PROJ1, 10000); syncViewTree.getAllItems()[0].expand().getItems()[0].expand() .getItems()[0].doubleClick(); SWTBot compare = bot.editorByTitle(FILE1).bot(); assertNotNull(compare); }
Source:
String getAttributeValue(int idx) { final QName attribute = getAttribute(idx); switch (attribute.getLocalPart()) { case XJConstants.TYPE_HINT_NAME: return this.name; case XJConstants.TYPE_HINT_TYPE: return XJConstants.JSONTYPE_TYPE_MAP.get(this.jsonToken); default: throw new IllegalArgumentException("Unknown attribute"); } }

Target:
String getAttributeValue(int idx) { final QName attribute = getAttribute(idx); switch (attribute.getLocalPart()) { case XJConstants.TYPE_HINT_NAME: return this.name; case XJConstants.TYPE_HINT_TYPE: return XJConstants.JSONTYPE_TYPE_MAP.get(this.jsonToken); default: throw new IllegalArgumentException("Unknown attribute " + attribute.getLocalPart()); } }
Source:
public InputStream openInput(String arg) throws IOException { if (arg.equals(STDIN_MARKER)) return new BufferedInputStream(System.in, IN_BUF_SZ); InputStream infile = new BufferedInputStream(new FileInputStream(arg), IN_BUF_SZ); if (arg.endsWith(".gz")) return new GZIPInputStream(infile); else if (arg.endsWith(".bz2")) return new BZip2CompressorInputStream(infile); else return infile; }

Target:
public InputStream openInput(String arg) throws IOException { arg = Objects.requireNonNull(arg); if (arg.equals(STDIN_MARKER)) { return new BufferedInputStream(System.in, IN_BUF_SZ); } InputStream infile = new BufferedInputStream(new FileInputStream(arg), IN_BUF_SZ); if (arg.endsWith(".gz")) { return new GZIPInputStream(infile); } else if (arg.endsWith(".bz2")) { return new BZip2CompressorInputStream(infile); } else { return infile; } }
Source:
private BufferCachingGrpcDataReader(WorkerNetAddress address, CloseableResource<BlockWorkerClient> client, long dataTimeoutMs, ReadRequest readRequest, GrpcBlockingStream<ReadRequest, ReadResponse> stream) { mAddress = address; mClient = client; mDataTimeoutMs = dataTimeoutMs; mMarshaller = new ReadResponseMarshaller(); mPosToRead = readRequest.getOffset(); mReadRequest = readRequest; mStream = stream; mCloser = Closer.create(); mCloser.register(mClient); mCloser.register(() -> { mStream.close(); mStream.waitForComplete(mDataTimeoutMs); }); long blockSize = mReadRequest.getLength() + mReadRequest.getOffset(); long chunkSize = mReadRequest.getChunkSize(); int buffCount = (int) (blockSize / chunkSize); if ((blockSize % chunkSize) != 0) { buffCount += 1; } mDataBuffers = new DataBuffer[buffCount]; }

Target:
private BufferCachingGrpcDataReader(WorkerNetAddress address, CloseableResource<BlockWorkerClient> client, long dataTimeoutMs, ReadRequest readRequest, GrpcBlockingStream<ReadRequest, ReadResponse> stream) { mAddress = address; mClient = client; mDataTimeoutMs = dataTimeoutMs; mPosToRead = readRequest.getOffset(); mReadRequest = readRequest; mStream = stream; long blockSize = mReadRequest.getLength() + mReadRequest.getOffset(); long chunkSize = mReadRequest.getChunkSize(); int buffCount = (int) (blockSize / chunkSize); if ((blockSize % chunkSize) != 0) { buffCount += 1; } mDataBuffers = new DataBuffer[buffCount]; }
Source:
public DataSource get() { final BoneCPDataSource src = new BoneCPDataSource(); src.setDriverClass("org.postgresql.Driver"); src.setJdbcUrl(this.jdbc); if (this.user != null) { src.setUser("postgres"); } src.setPassword(this.password); src.setPartitionCount(Tv.THREE); src.setMaxConnectionsPerPartition(1); src.setMinConnectionsPerPartition(1); src.setAcquireIncrement(1); src.setDisableConnectionTracking(true); return src; }

Target:
public DataSource get() { final BoneCPDataSource src = new BoneCPDataSource(); src.setDriverClass("org.postgresql.Driver"); src.setJdbcUrl(this.jdbc); if (this.user != null) { src.setUser(this.user); } src.setPassword(this.password); src.setPartitionCount(Tv.THREE); src.setMaxConnectionsPerPartition(1); src.setMinConnectionsPerPartition(1); src.setAcquireIncrement(1); src.setDisableConnectionTracking(true); return src; }
Source:
public Segment decodeNext(ParsingProgress progress) { StringBuilder currentId = new StringBuilder(); String currentTypeString = null; int state = 0; loop: while (!progress.isFinished()) { char c = progress.getNextChar(); switch (state) { case 0: switch (c) { case TYPE_DELIM: if (currentId.length() == 0) { throw new IllegalArgumentException("Unspecified entity type id at pos " + progress.getPos() + " in '" + progress.getSource() + "'."); } currentTypeString = currentId.toString(); currentId.delete(0, currentId.length()); state = 1; break; case PATH_DELIM: currentTypeString = currentId.toString(); currentId.delete(0, currentId.length()); break loop; default: currentId.append(c); } break; case 1: switch (c) { case PATH_DELIM: break loop; default: currentId.append(c); } break; } } String currentIdString = currentId.toString(); if (currentIdString.isEmpty()) { currentIdString = currentTypeString; currentTypeString = null; if (state == 1) { currentIdString += TYPE_DELIM; } } currentIdString = PathSegmentCodec.decode(currentIdString); Segment ret = typeProvider.deduceSegment(currentTypeString, currentIdString, progress.isFinished()); if (ret == null) { throw new IllegalArgumentException("Unrecognized entity type '" + currentTypeString + "' for segment" + " with id: '" + currentIdString + "' in source '" + progress.getSource() + "'. The following types are recognized: " + typeProvider.getValidTypeName()); } typeProvider.segmentParsed(ret); return ret; }

Target:
public Segment decodeNext(ParsingProgress progress) { StringBuilder currentId = new StringBuilder(); String currentTypeString = null; int state = 0; loop: while (!progress.isFinished()) { char c = progress.getNextChar(); switch (state) { case 0: switch (c) { case TYPE_DELIM: if (currentId.length() == 0) { throw new IllegalArgumentException("Unspecified entity type id at pos " + progress.getPos() + " in '" + progress.getSource() + "'."); } currentTypeString = currentId.toString(); currentId.delete(0, currentId.length()); state = 1; break; case PATH_DELIM: currentTypeString = currentId.toString(); currentId.delete(0, currentId.length()); break loop; default: currentId.append(c); } break; case 1: switch (c) { case PATH_DELIM: break loop; default: currentId.append(c); } break; } } String currentIdString = currentId.toString(); if (currentIdString.isEmpty()) { currentIdString = currentTypeString; currentTypeString = null; if (state == 1) { currentIdString += TYPE_DELIM; } } currentIdString = PathSegmentCodec.decode(currentIdString); Segment ret = typeProvider.deduceSegment(currentTypeString, currentIdString, progress.isFinished()); if (ret == null) { throw new IllegalArgumentException("Unrecognized entity type '" + currentTypeString + "' for segment" + " with id: '" + currentIdString + "' in path '" + progress.getSource() + "'. The following types are recognized: " + typeProvider.getValidTypeName()); } typeProvider.segmentParsed(ret); return ret; }
Source:
private static int parseInt(String value, int beginIndex, int endIndex) throws NumberFormatException { if (beginIndex < 0 || endIndex > value.length() || beginIndex > endIndex) { throw new NumberFormatException(value); } int i = beginIndex; int result = 0; int digit; if (i < endIndex) { digit = Character.digit(value.charAt(i++), 10); if (digit < 0) { throw new NumberFormatException("Invalid number: " + value); } result = -digit; } while (i < endIndex) { digit = Character.digit(value.charAt(i++), 10); if (digit < 0) { throw new NumberFormatException("Invalid number: " + value); } result *= 10; result -= digit; } return -result; }

Target:
private static int parseInt(String value, int beginIndex, int endIndex) throws NumberFormatException { if (beginIndex < 0 || endIndex > value.length() || beginIndex > endIndex) { throw new NumberFormatException(value); } int i = beginIndex; int result = 0; int digit; if (i < endIndex) { digit = Character.digit(value.charAt(i++), 10); if (digit < 0) { throw new NumberFormatException("Invalid number: " + value.substring(beginIndex, endIndex)); } result = -digit; } while (i < endIndex) { digit = Character.digit(value.charAt(i++), 10); if (digit < 0) { throw new NumberFormatException("Invalid number: " + value.substring(beginIndex, endIndex)); } result *= 10; result -= digit; } return -result; }
Source:
private boolean hasMoreActivationsThisTurn(Game game) { ActivationInfo activationInfo = getActivationInfo(game); return activationInfo == null || activationInfo.turnNum != game.getTurnNum() || activationInfo.activationCounter < maxActivationsPerTurn; }

Target:
protected boolean hasMoreActivationsThisTurn(Game game) { if (maxActivationsPerTurn == Integer.MAX_VALUE) { return true; } ActivationInfo activationInfo = getActivationInfo(game); return activationInfo == null || activationInfo.turnNum != game.getTurnNum() || activationInfo.activationCounter < maxActivationsPerTurn; }
Source:
final public void run() { int sleepMillis = config.getIntegerProperty(CoreConfig.EXCESS_ENUM_READER_SLEEP); while (true) { try { Set<Locator> excess = IOContainer.fromConfig().getExcessEnumIO().getExcessEnumMetrics(); synchronized (this) { excessEnumMetrics = excess; } readMeter.mark(); Thread.sleep(sleepMillis); } catch (Exception e) { log.error("ExcessEnumReader failed with exception " + e); readErrMeter.mark(); } } }

Target:
final public void run() { int sleepMillis = config.getIntegerProperty(CoreConfig.EXCESS_ENUM_READER_SLEEP); while (true) { try { Set<Locator> excess = IOContainer.fromConfig().getExcessEnumIO().getExcessEnumMetrics(); excessEnumMetrics = excess; readMeter.mark(); Thread.sleep(sleepMillis); } catch (Exception e) { log.error("ExcessEnumReader failed with exception " + e); readErrMeter.mark(); } } }
Source:
public Iterable<VirtualMachine> listNodes() { Closer closer = Closer.create(); VSphereServiceInstance instance = serviceInstance.get(); closer.register(instance); try { try { return listNodes(instance); } catch (Throwable e) { logger.error("Can't find vm", e); throw closer.rethrow(e); } finally { closer.close(); } } catch (Throwable t) { return ImmutableSet.of(); } }

Target:
public Iterable<VirtualMachine> listNodes() { try (VSphereServiceInstance instance = serviceInstance.get();) { return listNodes(instance); } catch (Throwable e) { logger.error("Can't find vm", e); Throwables.propagateIfPossible(e); return ImmutableSet.of(); } }
Source:
private List<Iterable<Range>> divideRangesByGroup( Granularity g, long from, long to ) { List<Iterable<Range>> listRange = new ArrayList<Iterable<Range>>(); long rangeSize = ROLLUP_ON_READ_REPAIR_SIZE_PER_THREAD * g.milliseconds(); for ( long start = g.snapMillis( from ); start < to ; ) { long end = (start + rangeSize) < to ? (start + rangeSize ) : to; listRange.add( Range.rangesForInterval( g, start, end ) ); start = end; } return listRange; }

Target:
private List<Iterable<Range>> divideRangesByGroup( Granularity g, long from, long to ) { List<Iterable<Range>> listRange = new ArrayList<Iterable<Range>>(); long rangeSize = ROLLUP_ON_READ_REPAIR_SIZE_PER_THREAD * g.milliseconds(); for ( long start = from; start < to ; ) { long end = (start + rangeSize) < to ? (start + rangeSize ) : to; listRange.add( Range.rangesForInterval( g, start, end ) ); start = end; } return listRange; }
Source:
public Object processInvocation(final InterceptorContext context) throws Exception { if (MDC.getMap() != null) { for (String str : MDC.getMap().keySet()) { MDC.remove(str); } } final StoredLogDiagnosticContext data = (StoredLogDiagnosticContext) context.getPrivateData(KEY); context.putPrivateData(KEY, null); if (data != null && data.getMdc() != null) { for (Map.Entry<String, Object> entry : data.getMdc().entrySet()) { MDC.put(entry.getKey(), entry.getValue()); } final int depth = NDC.getDepth(); NDC.push(data.getNdc()); try { return context.proceed(); } finally { NDC.setMaxDepth(depth); for (String str : MDC.getMap().keySet()) { MDC.remove(str); } } } return context.proceed(); }

Target:
public Object processInvocation(final InterceptorContext context) throws Exception { final Map<String, Object> mdc = MDC.getMap(); if (mdc != null) { for (String str : mdc.keySet()) { MDC.remove(str); } } final StoredLogDiagnosticContext data = (StoredLogDiagnosticContext) context.getPrivateData(KEY); context.putPrivateData(KEY, null); if (data != null && data.getMdc() != null) { for (Map.Entry<String, Object> entry : data.getMdc().entrySet()) { MDC.put(entry.getKey(), entry.getValue()); } final int depth = NDC.getDepth(); NDC.push(data.getNdc()); try { return context.proceed(); } finally { NDC.setMaxDepth(depth); for (String str : MDC.getMap().keySet()) { MDC.remove(str); } } } return context.proceed(); }
Source:
public void setConfiguration(Configuration configuration, List<String> subFileList, boolean interactive) { this.configuration = configuration; register(); HistoryGuru histGuru = HistoryGuru.getInstance(); try { generateProjectRepositoriesMap(); } catch (IOException ex) { LOGGER.log(Level.SEVERE, "Cannot generate project - repository map", ex); } populateGroups(getGroups(), new TreeSet<>(getProjects().values())); if (subFileList != null) { histGuru.invalidateRepositories( configuration.getRepositories(), subFileList, interactive); } else { histGuru.invalidateRepositories(configuration.getRepositories(), interactive); } configuration.setRepositories(new ArrayList<>(histGuru.getRepositories())); configuration.getBodyIncludeFileContent(true); configuration.getHeaderIncludeFileContent(true); configuration.getFooterIncludeFileContent(true); configuration.getForbiddenIncludeFileContent(true); }

Target:
public void setConfiguration(Configuration configuration, List<String> subFileList, boolean interactive) { this.configuration = configuration; register(); HistoryGuru histGuru = HistoryGuru.getInstance(); try { generateProjectRepositoriesMap(); } catch (IOException ex) { LOGGER.log(Level.SEVERE, "Cannot generate project - repository map", ex); } populateGroups(getGroups(), new TreeSet<>(getProjects().values())); if (subFileList != null) { histGuru.invalidateRepositories( configuration.getRepositories(), subFileList, interactive); } else { histGuru.invalidateRepositories(configuration.getRepositories(), interactive); } configuration.setRepositories(new ArrayList<>(histGuru.getRepositories())); reloadIncludeFiles(configuration); }
Source:
public boolean configure(StaplerRequest request, JSONObject object) throws FormException { nativeLibraryPath = object.getString("nativeLibraryPath"); master = object.getString("master"); description = object.getString("description"); frameworkName = object.getString("frameworkName"); slaveAttributes = object.getString("slaveAttributes"); checkpoint = object.getBoolean("checkpoint"); slaveInfos = new ArrayList<MesosSlaveInfo>(); JSONArray labels = object.getJSONArray("slaveInfos"); if (labels != null) { for (int i = 0; i < labels.size(); i++) { JSONObject label = labels.getJSONObject(i); if (label != null) { MesosSlaveInfo slaveInfo = new MesosSlaveInfo( object.getString("labelString"), object.getString("slaveCpus"), object.getString("slaveMem"), object.getString("maxExecutors"), object.getString("executorCpus"), object.getString("executorMem"), object.getJSONObject("hasCustomRemoteFSRoot"), object.getString("idleTerminationMinutes"), object.getString("slaveAttributes"), object.getString("jvmArgs")); slaveInfos.add(slaveInfo); } } } save(); return super.configure(request, object); }

Target:
public boolean configure(StaplerRequest request, JSONObject object) throws FormException { nativeLibraryPath = object.getString("nativeLibraryPath"); master = object.getString("master"); description = object.getString("description"); frameworkName = object.getString("frameworkName"); slaveAttributes = object.getString("slaveAttributes"); checkpoint = object.getBoolean("checkpoint"); slaveInfos = new ArrayList<MesosSlaveInfo>(); JSONArray labels = object.getJSONArray("slaveInfos"); if (labels != null) { for (int i = 0; i < labels.size(); i++) { JSONObject label = labels.getJSONObject(i); if (label != null) { MesosSlaveInfo slaveInfo = new MesosSlaveInfo( object.getString("labelString"), object.getString("slaveCpus"), object.getString("slaveMem"), object.getString("maxExecutors"), object.getString("executorCpus"), object.getString("executorMem"), object.getString("remoteFSRoot"), object.getString("idleTerminationMinutes"), object.getString("slaveAttributes"), object.getString("jvmArgs"), object.getString("containerImage"), object.getString("containerOptions")); slaveInfos.add(slaveInfo); } } } save(); return super.configure(request, object); }
Source:
public void onPostValidation(boolean valid) { FormViewUtil.setupBackground(getContext(), valid, textEditText); boolean isRepeatableField = getParent() instanceof DDMFieldRepeatableItemView; if (!isRepeatableField) { View errorView = findViewById(R.id.error_view); if (errorView != null) { errorView.setVisibility(valid ? GONE : VISIBLE); } } }

Target:
public void onPostValidation(boolean valid) { FormViewUtil.setupBackground(getContext(), valid, textEditText); boolean isRepeatableField = getParent() instanceof DDMFieldRepeatableItemView; if (!isRepeatableField) { FormViewUtil.setupErrorView(valid, findViewById(R.id.error_view)); } }
Source:
public void setExtractPayload(boolean extractPayload) { if (this.payloadExpression == null) { setPayloadExpression(extractPayload ? EXPRESSION_PARSER.parseExpression("payload") : EXPRESSION_PARSER.parseExpression("#this")); } }

Target:
public void setExtractPayload(boolean extractPayload) { if (this.payloadExpression == null) { setPayloadExpression(extractPayload ? null : EXPRESSION_PARSER.parseExpression("#this")); } }
Source:
private void loadWindowsContent(RequestBuilder.Method method) { String host = com.google.gwt.user.client.Window.Location.getHostName(); String user = LoginModel.getInstance().getLogin(); String requestUrl = null; if ("http".equals(SchedulerConfig.get().getCalendarServerProtocol())) { requestUrl = "http://" + host + ":" + SchedulerConfig.get().getCalendarServerPort() + "/calendar-service/private-urls/" + user + "/"; } else { requestUrl = "https://" + host + "/calendar-service/private-urls/" + user + "/"; } RequestBuilder rb = new RequestBuilder(method, requestUrl); rb.setCallback(new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { if (200 == response.getStatusCode()) { text.setContents(contentBuilder.buildContentString(response.getText())); } else { text.setContents("Error : status code " + response.getStatusCode()); } refreshWindow(text); } private void refreshWindow(HTMLPane text) { pane.clear(); root.clear(); window.clear(); pane.addMember(img); pane.addMember(text); root.addMember(pane); root.addMember(buttons); window.addItem(root); window.show(); } @Override public void onError(Request request, Throwable exception) { text.setContents("Exception : " + exception.getMessage()); refreshWindow(text); } }); try { rb.send(); } catch (RequestException e) { com.google.gwt.user.client.Window.alert("error = " + e.getMessage()); } }

Target:
private void loadWindowsContent(RequestBuilder.Method method) { String host = com.google.gwt.user.client.Window.Location.getHostName(); String user = LoginModel.getInstance().getLogin(); StringBuilder requestUrl = new StringBuilder(); if ("http".equals(SchedulerConfig.get().getCalendarServerProtocol())) { requestUrl.append("http://" + host + ":" + SchedulerConfig.get().getCalendarServerPort()); } else { requestUrl.append("https://" + host); } requestUrl.append("/calendar-service/private-urls/" + user + "/"); RequestBuilder rb = new RequestBuilder(method, requestUrl.toString()); rb.setCallback(new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { if (200 == response.getStatusCode()) { text.setContents(contentBuilder.buildContentString(response.getText())); } else { text.setContents("Error : status code " + response.getStatusCode()); } refreshWindow(text); } private void refreshWindow(HTMLPane text) { pane.clear(); root.clear(); window.clear(); pane.addMember(img); pane.addMember(text); root.addMember(pane); root.addMember(buttons); window.addItem(root); window.show(); } @Override public void onError(Request request, Throwable exception) { text.setContents("Exception : " + exception.getMessage()); refreshWindow(text); } }); try { rb.send(); } catch (RequestException e) { com.google.gwt.user.client.Window.alert("error = " + e.getMessage()); } }
Source:
protected void onDemotion() { managementContext.getRebindManager().stop(); for (Application app: managementContext.getApplications()) Entities.unmanage(app); Collection<Exception> exceptions = MutableSet.of(); int tasks = 0; LOG.debug("Cancelling tasks on demotion"); try { for (Entity entity: managementContext.getEntityManager().getEntities()) { for (Task<?> t: managementContext.getExecutionContext(entity).getTasks()) { if (!t.isDone()) { tasks++; try { LOG.debug("Cancelling "+t+" on "+entity); t.cancel(true); } catch (Exception e) { Exceptions.propagateIfFatal(e); exceptions.add(e); } } } } } catch (Exception e) { Exceptions.propagateIfFatal(e); LOG.warn("Error inspecting tasks to cancel on demotion: "+e, e); } if (!exceptions.isEmpty()) LOG.warn("Error when cancelling tasks on demotion: "+Exceptions.create(exceptions)); if (tasks>0) LOG.info("Cancelled "+tasks+" tasks on demotion"); }

Target:
protected void onDemotion() { managementContext.getRebindManager().stop(); for (Application app: managementContext.getApplications()) Entities.unmanage(app); Collection<Exception> exceptions = MutableSet.of(); int tasks = 0; LOG.debug("Cancelling tasks on demotion"); try { for (Entity entity: managementContext.getEntityManager().getEntities()) { for (Task<?> t: managementContext.getExecutionContext(entity).getTasks()) { if (!t.isDone()) { tasks++; try { LOG.debug("Cancelling "+t+" on "+entity); t.cancel(true); } catch (Exception e) { Exceptions.propagateIfFatal(e); LOG.debug("Error cancelling "+t+" on "+entity+" (will warn when all tasks are cancelled): "+e, e); exceptions.add(e); } } } } } catch (Exception e) { Exceptions.propagateIfFatal(e); LOG.warn("Error inspecting tasks to cancel on demotion: "+e, e); } if (!exceptions.isEmpty()) LOG.warn("Error when cancelling tasks on demotion: "+Exceptions.create(exceptions)); if (tasks>0) LOG.info("Cancelled "+tasks+" tasks on demotion"); }
Source:
public void testGetModulesByClass() { Iterable<IAnalysisModule> modules = fTrace.getAnalysisModules(); assertFalse(modules.iterator().hasNext()); fTrace.traceOpened(new TmfTraceOpenedSignal(this, fTrace, null)); modules = fTrace.getAnalysisModules(); Iterable<TestAnalysis> testModules = TmfTraceUtils.getAnalysisModulesOfClass(fTrace, TestAnalysis.class); assertTrue(modules.iterator().hasNext()); assertTrue(testModules.iterator().hasNext()); for (IAnalysisModule module : modules) { if (module instanceof TestAnalysis) { IAnalysisModule otherModule = fTrace.getAnalysisModule(module.getId()); assertNotNull(otherModule); assertTrue(otherModule.equals(module)); } } }

Target:
public void testGetModulesByClass() { fTrace.traceOpened(new TmfTraceOpenedSignal(this, fTrace, null)); Iterable<TestAnalysis> testModules = TmfTraceUtils.getAnalysisModulesOfClass(fTrace, TestAnalysis.class); assertTrue(testModules.iterator().hasNext()); int count = 0; for (TestAnalysis module : testModules) { assertNotNull(module); count++; } assertEquals(2, count); TestAnalysis module = TmfTraceUtils.getAnalysisModuleOfClass(fTrace, TestAnalysis.class, AnalysisManagerTest.MODULE_PARAM); assertNotNull(module); IAnalysisModule traceModule = fTrace.getAnalysisModule(AnalysisManagerTest.MODULE_PARAM); assertNotNull(traceModule); assertEquals(module, traceModule); }
Source:
public void arrow_function_expression_scope() throws Exception { Scope scope = getScopeFor(Kind.ARROW_FUNCTION_EXPRESSION); assertThat(scope.getSymbols(Symbol.Kind.PARAMETER)).extracting(Symbol::name).containsExactly("$a"); assertThat(scope.getSymbols(Symbol.Kind.VARIABLE)).isEmpty(); assertThat(scope.getSymbol("$c", Symbol.Kind.VARIABLE)).isNotNull(); }

Target:
public void arrow_function_expression_scope() throws Exception { Scope scope = getScopeFor(Kind.ARROW_FUNCTION_EXPRESSION); assertThat(scope.getSymbols(Symbol.Kind.PARAMETER)).extracting(Symbol::name).containsExactlyInAnyOrder("$a", "$d"); assertThat(scope.getSymbols(Symbol.Kind.VARIABLE)).isEmpty(); Symbol symbolC = scope.getSymbol("$c"); Symbol symbolD = scope.getSymbol("$d"); assertThat(symbolC).isNotNull(); assertThat(symbolC.kind()).isEqualTo(Symbol.Kind.VARIABLE); assertThat(symbolD).isNotNull(); assertThat(scope.getSymbol("$d", Symbol.Kind.PARAMETER)).isEqualTo(symbolD); assertThat(scope.getSymbol("$d", Symbol.Kind.VARIABLE)).isNull(); Scope functionScope = getScopeFor(Kind.FUNCTION_DECLARATION); assertThat(symbolC).isEqualTo(functionScope.getSymbol("$c")); assertThat(symbolD).isNotEqualTo(functionScope.getSymbol("$d")); }
Source:
public CompletableFuture<Optional<InetAddress>> lookup(String hostname) { if (lookupEnabled) { return circuitBreaker.executeCompletionStage(() -> { final NettyResolverContext resolverContext = iterator.next(); final Timer.Context timerContext = lookupTimer.time(); return resolverContext.lookup(hostname).whenComplete((res, ex) -> { timerContext.stop(); }); }).toCompletableFuture(); } else { return CompletableFuture.completedFuture(Optional.empty()); } }

Target:
public CompletableFuture<Optional<InetAddress>> lookup(String hostname) { return circuitBreaker.executeCompletionStage(() -> { final NettyResolverContext resolverContext = iterator.next(); final Timer.Context timerContext = lookupTimer.time(); return resolverContext.lookup(hostname).whenComplete((res, ex) -> { timerContext.stop(); }); }).toCompletableFuture(); }
Source:
public int hashCode() { int result = dataStoreName != null ? dataStoreName.hashCode() : 0; result = 31 * result + (ascending ? 1 : 0); return result; }

Target:
public int hashCode() { int result = dataStoreName != null ? dataStoreName.hashCode() : 0; result = 31 * result + (ascending ? 1 : 0); result = ~~result; return result; }
Source:
public PlanNode visitSemiJoin(SemiJoinNode node, RewriteContext<RowExpression> context) { RowExpression inheritedPredicate = context.get(); if (!extractConjuncts(inheritedPredicate).contains(new SymbolReference(node.getSemiJoinOutput().getName()))) { return visitNonFilteringSemiJoin(node, context); } return visitFilteringSemiJoin(node, context); }

Target:
public PlanNode visitSemiJoin(SemiJoinNode node, RewriteContext<RowExpression> context) { RowExpression inheritedPredicate = context.get(); if (!extractConjuncts(inheritedPredicate).contains(node.getSemiJoinOutput())) { return visitNonFilteringSemiJoin(node, context); } return visitFilteringSemiJoin(node, context); }
Source:
public void testSuccess() throws Exception { Parameter param = new Parameter(); param.setName("param1"); param.setValue("abs"); param.setSessionKey("*"); session1.put("param1","yarr"); pipe.addParameter(param); pipe.setLookupAtRuntime(true); pipe.setFileName(sourceFolderPath); pipe.setReplaceFrom("param1"); pipe.setReplaceTo("kar"); pipe.setReturnString("${param1}andandandparam2"); pipe.configure(); PipeRunResult res = doPipe(pipe, "whatisthis", session1); assertEquals(res.getResult().toString(), "String: inside the file"); }

Target:
public void testSuccess() throws Exception { Parameter param = setUp(session1); pipe.addParameter(param); pipe.setLookupAtRuntime(true); pipe.setFileName(sourceFolderPath); pipe.setReplaceFrom("param1"); pipe.setReplaceTo("kar"); pipe.setReturnString("${param1}andandandparam2"); pipe.configure(); PipeRunResult res = doPipe(pipe, "whatisthis", session1); assertEquals(res.getResult().asString(), "inside the file"); }
Source:
public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(name); out.writeInt(backupCount); out.writeInt(asyncBackupCount); out.writeInt(timeToLiveSeconds); out.writeInt(maxIdleSeconds); out.writeObject(maxSizeConfig); out.writeUTF(evictionPolicy.name()); out.writeObject(mapEvictionPolicy); out.writeObject(mapStoreConfig); out.writeObject(nearCacheConfig); out.writeBoolean(readBackupData); out.writeUTF(cacheDeserializedValues.name()); out.writeObject(mergePolicyConfig); out.writeUTF(inMemoryFormat.name()); out.writeObject(wanReplicationRef); writeNullableList(entryListenerConfigs, out); writeNullableList(partitionLostListenerConfigs, out); writeNullableList(mapIndexConfigs, out); writeNullableList(mapAttributeConfigs, out); writeNullableList(queryCacheConfigs, out); out.writeBoolean(statisticsEnabled); out.writeObject(partitioningStrategyConfig); out.writeUTF(quorumName); out.writeObject(hotRestartConfig); out.writeShort(preprocessingPolicy.getId()); }

Target:
public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(name); out.writeInt(backupCount); out.writeInt(asyncBackupCount); out.writeInt(timeToLiveSeconds); out.writeInt(maxIdleSeconds); out.writeObject(maxSizeConfig); out.writeUTF(evictionPolicy.name()); out.writeObject(mapEvictionPolicy); out.writeObject(mapStoreConfig); out.writeObject(nearCacheConfig); out.writeBoolean(readBackupData); out.writeUTF(cacheDeserializedValues.name()); out.writeObject(mergePolicyConfig); out.writeUTF(inMemoryFormat.name()); out.writeObject(wanReplicationRef); writeNullableList(entryListenerConfigs, out); writeNullableList(partitionLostListenerConfigs, out); writeNullableList(mapIndexConfigs, out); writeNullableList(mapAttributeConfigs, out); writeNullableList(queryCacheConfigs, out); out.writeBoolean(statisticsEnabled); out.writeObject(partitioningStrategyConfig); out.writeUTF(quorumName); out.writeObject(hotRestartConfig); if (out.getVersion().isGreaterOrEqual(Versions.V3_12)) { out.writeShort(metadataPolicy.getId()); } }
Source:
public void close() { if (enabled.compareAndSet(true, false)) { List<Runnable> pendingTasks = scheduler.shutdownNow(); for (Runnable task : pendingTasks) { if (task instanceof CryptoJob) { ((CryptoJob) task).closeJob(CLOSED_EXCEPTION); } else { logger.error("Unknown type of job seen : " + task.getClass()); } } try { scheduler.awaitTermination(10000, TimeUnit.MILLISECONDS); } catch (Exception e) { logger.error("Unexpected exception while waiting for crypto jobs to terminate", e); } } }

Target:
public void close() { if (enabled.compareAndSet(true, false)) { List<Runnable> pendingTasks = scheduler.shutdownNow(); for (Runnable task : pendingTasks) { if (task instanceof CryptoJob) { ((CryptoJob) task).closeJob(CLOSED_EXCEPTION); } else { logger.error("Unknown type of job seen : " + task.getClass()); } } try { scheduler.awaitTermination(1000, TimeUnit.MILLISECONDS); } catch (Exception e) { logger.error("Unexpected exception while waiting for crypto jobs to terminate", e); } } }
Source:
public void start() { synchronized (stateLock) { Preconditions.checkState(!started, "already started"); DataSourceMetadata metadata = metadataStorageCoordinator.getDataSourceMetadata(dataSource); if (null == metadata) { metadataStorageCoordinator.insertDataSourceMetadata( dataSource, new DerivativeDataSourceMetadata(spec.getBaseDataSource(), spec.getDimensions(), spec.getMetrics()) ); } exec = MoreExecutors.listeningDecorator(Execs.scheduledSingleThreaded(supervisorId)); final Duration delay = config.getTaskCheckDuration().toStandardDuration(); future = exec.scheduleWithFixedDelay( new Runnable() { @Override public void run() { try { DataSourceMetadata metadata = metadataStorageCoordinator.getDataSourceMetadata(dataSource); if (metadata != null && metadata instanceof DerivativeDataSourceMetadata && spec.getBaseDataSource().equals(((DerivativeDataSourceMetadata) metadata).getBaseDataSource()) && spec.getDimensions().equals(((DerivativeDataSourceMetadata) metadata).getDimensions()) && spec.getMetrics().equals(((DerivativeDataSourceMetadata) metadata).getMetrics())) { checkSegmentsAndSubmitTasks(); } else { log.error("Failed to start %s. Metadata in database(%s) is different from new dataSource metadata(%s)", supervisorId, metadata, spec); } } catch (Exception e) { log.makeAlert(e, StringUtils.format("uncaught exception in %s.", supervisorId)).emit(); } } }, 0, delay.getMillis(), TimeUnit.MILLISECONDS ); started = true; } }

Target:
public void start() { synchronized (stateLock) { Preconditions.checkState(!started, "already started"); DataSourceMetadata metadata = metadataStorageCoordinator.getDataSourceMetadata(dataSource); if (null == metadata) { metadataStorageCoordinator.insertDataSourceMetadata( dataSource, new DerivativeDataSourceMetadata(spec.getBaseDataSource(), spec.getDimensions(), spec.getMetrics()) ); } exec = MoreExecutors.listeningDecorator(Execs.scheduledSingleThreaded(supervisorId)); final Duration delay = config.getTaskCheckDuration().toStandardDuration(); future = exec.scheduleWithFixedDelay( new Runnable() { @Override public void run() { try { DataSourceMetadata metadata = metadataStorageCoordinator.getDataSourceMetadata(dataSource); if (metadata instanceof DerivativeDataSourceMetadata && spec.getBaseDataSource().equals(((DerivativeDataSourceMetadata) metadata).getBaseDataSource()) && spec.getDimensions().equals(((DerivativeDataSourceMetadata) metadata).getDimensions()) && spec.getMetrics().equals(((DerivativeDataSourceMetadata) metadata).getMetrics())) { checkSegmentsAndSubmitTasks(); } else { log.error( "Failed to start %s. Metadata in database(%s) is different from new dataSource metadata(%s)", supervisorId, metadata, spec ); } } catch (Exception e) { log.makeAlert(e, StringUtils.format("uncaught exception in %s.", supervisorId)).emit(); } } }, 0, delay.getMillis(), TimeUnit.MILLISECONDS ); started = true; } }
Source:
public void syncHeight(final boolean scrollToBottom, final boolean ensureVisible) { if (!options_.include() && !hasErrors_ && execScope_ == NotebookQueueUnit.EXEC_SCOPE_CHUNK) { if (isVisible()) { setVisible(false); host_.onOutputHeightChanged(this, 0, ensureVisible); } return; } if (!isVisible() && (state_ == CHUNK_EMPTY || state_ == CHUNK_PRE_OUTPUT)) return; setVisible(true); int height = ChunkOutputUi.CHUNK_COLLAPSED_HEIGHT; if (expansionState_.getValue() == EXPANDED) { int contentHeight = root_.getElement().getOffsetHeight() + 19; height = Math.max(ChunkOutputUi.MIN_CHUNK_HEIGHT, contentHeight); height = Math.min(height, 650); if (pendingRenders_ > 0 && height < renderedHeight_) return; } if (height == renderedHeight_ && !ensureVisible) return; renderedHeight_ = height; if (scrollToBottom) root_.getElement().setScrollTop(root_.getElement().getScrollHeight()); if (chunkOutputSize_ != ChunkOutputSize.Full) frame_.getElement().getStyle().setHeight(height, Unit.PX); host_.onOutputHeightChanged(this, height + 7, ensureVisible); }

Target:
public void syncHeight(final boolean scrollToBottom, final boolean ensureVisible) { if (!options_.include() && !hasErrors_ && execScope_ == NotebookQueueUnit.EXEC_SCOPE_CHUNK) { if (isVisible()) { setVisible(false); host_.onOutputHeightChanged(this, 0, ensureVisible); } return; } if (!isVisible() && (state_ == CHUNK_EMPTY || state_ == CHUNK_PRE_OUTPUT)) return; setVisible(true); int height = ChunkOutputUi.CHUNK_COLLAPSED_HEIGHT; if (expansionState_.getValue() == EXPANDED) { int contentHeight = root_.getElement().getOffsetHeight() + 19; height = Math.max(ChunkOutputUi.MIN_CHUNK_HEIGHT, contentHeight); height = Math.min(height, ChunkOutputUi.MAX_CHUNK_HEIGHT); if (pendingRenders_ > 0 && height < renderedHeight_) return; } if (height == renderedHeight_ && !ensureVisible) return; renderedHeight_ = height; if (scrollToBottom) root_.getElement().setScrollTop(root_.getElement().getScrollHeight()); if (chunkOutputSize_ != ChunkOutputSize.Full) frame_.getElement().getStyle().setHeight(height, Unit.PX); host_.onOutputHeightChanged(this, height + 7, ensureVisible); }
Source:
private void generateAspects(ITmfEventField[] fieldsArray) { ImmutableList.Builder<ITmfEventAspect> builder = new ImmutableList.Builder<>(); builder.add(ITmfEventAspect.BaseAspects.TIMESTAMP); builder.add(ITmfEventAspect.BaseAspects.EVENT_TYPE); for (ITmfEventField field : fieldsArray) { String name = field.getName(); if (name == null) { break; } ITmfEventAspect aspect = ITmfEventAspect.BaseAspects.CONTENTS.createAspect(name, name); if (name.equals(ASPECT_CPU)) { aspect = new XmlStubCpuAspect((TmfEventFieldAspect) aspect); } builder.add(aspect); } builder.add(ITmfEventAspect.BaseAspects.CONTENTS); @SuppressWarnings("null") @NonNull Collection<ITmfEventAspect> aspectList = builder.build(); fAspects = aspectList; }

Target:
private void generateAspects(ITmfEventField[] fieldsArray) { ImmutableList.Builder<ITmfEventAspect> builder = new ImmutableList.Builder<>(); builder.add(ITmfEventAspect.BaseAspects.TIMESTAMP); builder.add(ITmfEventAspect.BaseAspects.EVENT_TYPE); for (ITmfEventField field : fieldsArray) { String name = field.getName(); if (name == null) { break; } final ITmfEventAspect aspect = ITmfEventAspect.BaseAspects.CONTENTS.createAspect(name, name); if (name.equals(ASPECT_CPU)) { builder.add(new TmfCpuAspect() { @Override public @Nullable Integer resolve(ITmfEvent event) { Object result = aspect.resolve(event); if (result instanceof Number) { return ((Number) result).intValue(); } return null; } }); } else { builder.add(aspect); } } builder.add(ITmfEventAspect.BaseAspects.CONTENTS); @SuppressWarnings("null") @NonNull Collection<ITmfEventAspect> aspectList = builder.build(); fAspects = aspectList; }
Source:
public Collection<ThingUID> removeOlderResults(DiscoveryService source, long timestamp, Collection<ThingTypeUID> thingTypeUIDs) { HashSet<ThingUID> removedThings = new HashSet<>(); String sourceName = source.getClass().getName(); for (DiscoveryResult discoveryResult : getAll()) { String discovererName = resultDiscovererMap.get(discoveryResult); if (thingTypeUIDs.contains(discoveryResult.getThingTypeUID()) && discoveryResult.getTimestamp() < timestamp && sourceName.equals(discovererName)) { ThingUID thingUID = discoveryResult.getThingUID(); removedThings.add(thingUID); remove(thingUID); logger.debug("Removed from inbox because it was older than {}", thingUID, new Date(timestamp)); } } return removedThings; }

Target:
public Collection<ThingUID> removeOlderResults(DiscoveryService source, long timestamp, Collection<ThingTypeUID> thingTypeUIDs) { HashSet<ThingUID> removedThings = new HashSet<>(); for (DiscoveryResult discoveryResult : getAll()) { Class<?> discoverer = resultDiscovererMap.get(discoveryResult); if (thingTypeUIDs.contains(discoveryResult.getThingTypeUID()) && discoveryResult.getTimestamp() < timestamp && (discoverer == null || source.getClass() == discoverer)) { ThingUID thingUID = discoveryResult.getThingUID(); removedThings.add(thingUID); remove(thingUID); logger.debug("Removed from inbox because it was older than {}", thingUID, new Date(timestamp)); } } return removedThings; }
Source:
public DelegatingResourceDescription getUpdatableProperties() throws ResourceDoesNotSupportOperationException { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addRequiredProperty("diagnosis"); description.addRequiredProperty("encounter"); description.addRequiredProperty("uuid"); description.addRequiredProperty("condition"); description.addRequiredProperty("rank"); description.removeProperty("patient"); description.addRequiredProperty("patient"); description.addRequiredProperty("voided"); return description; }

Target:
public DelegatingResourceDescription getUpdatableProperties() throws ResourceDoesNotSupportOperationException { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addRequiredProperty("diagnosis"); description.addRequiredProperty("condition"); description.addRequiredProperty("rank"); description.removeProperty("patient"); description.addRequiredProperty("voided"); description.addRequiredProperty("certainty"); description.addRequiredProperty("encounter"); return description; }
Source:
public void obviousCallsTest() { final double[] weights = new double[] {0.5, 0.5}; final double[] minorAlleleFractions = new double[] {0.1, 0.5}; final double memoryLength = 1e3; AlleleFractionHiddenMarkovModel model = new AlleleFractionHiddenMarkovModel(minorAlleleFractions, weights, memoryLength, AllelicPanelOfNormals.EMPTY_PON, NO_BIAS_OR_OUTLIERS_PARAMS); final Random random = new Random(13); final int chainLength = 10000; final List<SimpleInterval> positions = new ArrayList<>(); final List<AllelicCount> data = new ArrayList<>(); int position = 1; for (int n = 0; n < chainLength; n++) { position += random.nextInt((int) (2*memoryLength)) + (int) memoryLength; final SimpleInterval interval = new SimpleInterval("chr1", position, position); positions.add(interval); if ( n < 2500) { data.add(new AllelicCount(interval, 10, 90)); } else if ( n < 5000) { data.add(new AllelicCount(interval, 50, 50)); } else if ( n < 7500) { data.add(new AllelicCount(interval, 90, 10)); } else { data.add(new AllelicCount(interval, 40, 60)); } } List<Integer> states = ViterbiAlgorithm.apply(data, positions, model); for (int pos = 0; pos < chainLength; pos++) { if ( pos < 2500) { Assert.assertEquals((int) states.get(pos), 0); } else if ( pos < 5000) { Assert.assertEquals((int) states.get(pos), 1); } else if ( pos < 7500) { Assert.assertEquals((int) states.get(pos), 0); } else { Assert.assertEquals((int) states.get(pos), 1); } } }

Target:
public void obviousCallsTest() { final double[] weights = new double[] {0.5, 0.5}; final double[] minorAlleleFractions = new double[] {0.1, 0.5}; final double memoryLength = 1e3; final AlleleFractionHiddenMarkovModel model = new AlleleFractionHiddenMarkovModel(minorAlleleFractions, weights, memoryLength, AllelicPanelOfNormals.EMPTY_PON, NO_BIAS_OR_OUTLIERS_PARAMS); final Random random = new Random(13); final int chainLength = 10000; final List<SimpleInterval> positions = new ArrayList<>(); final List<AllelicCount> data = new ArrayList<>(); int position = 1; for (int n = 0; n < chainLength; n++) { position += random.nextInt((int) (2*memoryLength)) + (int) memoryLength; final SimpleInterval interval = new SimpleInterval("chr1", position, position); positions.add(interval); if (n < 2500) { data.add(new AllelicCount(interval, 10, 90)); } else if ( n < 5000) { data.add(new AllelicCount(interval, 50, 50)); } else if ( n < 7500) { data.add(new AllelicCount(interval, 90, 10)); } else { data.add(new AllelicCount(interval, 40, 60)); } } final List<Integer> states = ViterbiAlgorithm.apply(data, positions, model); for (int pos = 0; pos < chainLength; pos++) { if (pos < 2500) { Assert.assertEquals((int) states.get(pos), 0); } else if (pos < 5000) { Assert.assertEquals((int) states.get(pos), 1); } else if (pos < 7500) { Assert.assertEquals((int) states.get(pos), 0); } else { Assert.assertEquals((int) states.get(pos), 1); } } }
Source:
public C requestMatchers(RequestMatcher... requestMatchers) { if (!Objects.equals(requestMatchers[0], AnyRequestMatcher.INSTANCE)){ Assert.state(!this.anyRequestConfigured, "Can't configure requestMatchers after anyRequest"); } return chainRequestMatchers(Arrays.asList(requestMatchers)); }

Target:
public C requestMatchers(RequestMatcher... requestMatchers) { Assert.state(!this.anyRequestConfigured, "Can't configure requestMatchers after anyRequest"); return chainRequestMatchers(Arrays.asList(requestMatchers)); }