auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void setUp() { request = new MockHttpServletRequest(); response = new MockHttpServletResponse(); rssViewer = new RssViewer(); rssViewer.setContentType("application/rss+xml;charset=UTF-8"); rssViewerMock = mock(RssViewer.class); channel = new Channel(); model = new HashMap<>(); modelWithSpecChars = new HashMap<>(); List<Topic> topics = new ArrayList<>(); JCUser user = new JCUser("username", "email", "password"); user.setSignature("Signature"); Post post = new Post(user, "sagjalighjh eghjwhjslhjsdfhdfhljdfh"); topic = new Topic(user, ""); topic.addPost(post); topic.setId(1L); topics.add(topic); topics.add(topic); model.put("topics", topics); List<Topic> topicsWithSpecChars = new ArrayList<>(); Post postWithSpecChars = new Post(user, "����\u000F���"); topicWithSpecChars = new Topic(user, ""); topicWithSpecChars.addPost(postWithSpecChars); topicWithSpecChars.setId(2L); topicsWithSpecChars.add(topicWithSpecChars); modelWithSpecChars.put("topics", topicsWithSpecChars); }

Target:
protected void setUp() { request = new MockHttpServletRequest(); response = new MockHttpServletResponse(); rssViewer = new RssViewer(); rssViewer.setContentType("application/rss+xml;charset=UTF-8"); rssViewerMock = mock(RssViewer.class); channel = new Channel(); newsComponents = getNewsComponents(); }
Source:
public Health[] allowedHealthstates() { return Health.values(); }

Target:
public RepositoryInfo.Health[] allowedHealthstates() { return new RepositoryInfo.Health[] { RepositoryInfo.Health.RED }; }
Source:
public static @Nullable LoggingInfo getLogging(GeoServerResourceLoader loader) throws IOException { Resource f= loader.get( "logging.xml" ); if ( f != null ) { XStreamPersister xp = new XStreamPersisterFactory().createXMLPersister(); BufferedInputStream in = new BufferedInputStream( f.in() ); try { LoggingInfo loginfo = xp.load(in,LoggingInfo.class); return loginfo; } finally { in.close(); } } else { return null; } }

Target:
public static @Nullable LoggingInfo getLogging(GeoServerResourceLoader loader) throws IOException { Resource f= loader.get( "logging.xml" ); if ( f != null ) { XStreamPersister xp = new XStreamPersisterFactory().createXMLPersister(); try (BufferedInputStream in = new BufferedInputStream(f.in())) { LoggingInfo loginfo = xp.load(in,LoggingInfo.class); return loginfo; } } else { return null; } }
Source:
public Collection<com.datatorrent.api.Partitioner.Partition<AbstractJdbcPollInputOperator<T>>> definePartitions( Collection<Partition<AbstractJdbcPollInputOperator<T>>> partitions, PartitioningContext context) { List<Partition<AbstractJdbcPollInputOperator<T>>> newPartitions = new ArrayList<>( getPartitionCount()); final List<KeyValPair<Integer, Integer>> partitionRanges; try { store.connect(); dslContext = createDSLContext(); if (getPartitionCount() > 0) { partitionRanges = getPartitionedQueryRanges(getPartitionCount()); } else { partitionRanges = new ArrayList<>(0); } } catch (SQLException e) { LOG.error("Exception in initializing the partition range", e); throw new RuntimeException(e); } finally { store.disconnect(); } KryoCloneUtils<AbstractJdbcPollInputOperator<T>> cloneUtils = KryoCloneUtils.createCloneUtils(this); int pollOffset = 0; for (KeyValPair<Integer, Integer> range : partitionRanges) { AbstractJdbcPollInputOperator<T> jdbcPoller = cloneUtils.getClone(); jdbcPoller.rangeQueryPair = range; jdbcPoller.lastEmittedRow = range.getKey(); jdbcPoller.isPollerPartition = false; newPartitions.add(new DefaultPartition<>(jdbcPoller)); pollOffset = range.getValue(); } AbstractJdbcPollInputOperator<T> jdbcPoller = cloneUtils.getClone(); jdbcPoller.rangeQueryPair = new KeyValPair<>(pollOffset, null); jdbcPoller.lastEmittedRow = pollOffset; jdbcPoller.isPollerPartition = true; newPartitions.add(new DefaultPartition<>(jdbcPoller)); return newPartitions; }

Target:
public Collection<com.datatorrent.api.Partitioner.Partition<AbstractJdbcPollInputOperator<T>>> definePartitions( Collection<Partition<AbstractJdbcPollInputOperator<T>>> partitions, PartitioningContext context) { List<Partition<AbstractJdbcPollInputOperator<T>>> newPartitions = new ArrayList<>( getPartitionCount()); final List<KeyValPair<Integer, Integer>> partitionRanges; try { store.connect(); dslContext = createDSLContext(); partitionRanges = getPartitionedQueryRanges(getPartitionCount()); } catch (SQLException e) { LOG.error("Exception in initializing the partition range", e); throw new RuntimeException(e); } finally { store.disconnect(); } KryoCloneUtils<AbstractJdbcPollInputOperator<T>> cloneUtils = KryoCloneUtils.createCloneUtils(this); int pollOffset = 0; for (KeyValPair<Integer, Integer> range : partitionRanges) { AbstractJdbcPollInputOperator<T> jdbcPoller = cloneUtils.getClone(); jdbcPoller.rangeQueryPair = range; jdbcPoller.lastEmittedRow = range.getKey(); jdbcPoller.isPollerPartition = false; newPartitions.add(new DefaultPartition<>(jdbcPoller)); pollOffset = range.getValue(); } AbstractJdbcPollInputOperator<T> jdbcPoller = cloneUtils.getClone(); jdbcPoller.rangeQueryPair = new KeyValPair<>(pollOffset, null); jdbcPoller.lastEmittedRow = pollOffset; jdbcPoller.isPollerPartition = true; newPartitions.add(new DefaultPartition<>(jdbcPoller)); return newPartitions; }
Source:
public String changeSessionId() { String oldId = delegate.getId(); String id = delegate.changeSessionId(); RBatch batch = redisson.createBatch(BatchOptions.defaults()); batch.getBucket(getExpiredKey(oldId)).remainTimeToLiveAsync(); batch.getBucket(getExpiredKey(oldId)).deleteAsync(); batch.getMap(map.getName(), map.getCodec()).readAllMapAsync(); batch.getMap(map.getName()).deleteAsync(); BatchResult<?> res = batch.execute(); List<?> list = res.getResponses(); Long remainTTL = (Long) list.get(0); Map<String, Object> oldState = (Map<String, Object>) list.get(2); if (remainTTL == -2) { remainTTL = delegate.getMaxInactiveInterval().toMillis(); } if (remainTTL > 0) { redisson.getBucket(getExpiredKey(id)).setAsync("", remainTTL, TimeUnit.MILLISECONDS); } map = redisson.getMap(keyPrefix + id, map.getCodec()); map.putAll(oldState); return id; }

Target:
public String changeSessionId() { String oldId = delegate.getId(); String id = delegate.changeSessionId(); RBatch batch = redisson.createBatch(BatchOptions.defaults()); batch.getBucket(getExpiredKey(oldId)).remainTimeToLiveAsync(); batch.getBucket(getExpiredKey(oldId)).deleteAsync(); batch.getMap(map.getName(), map.getCodec()).readAllMapAsync(); batch.getMap(map.getName()).deleteAsync(); BatchResult<?> res = batch.execute(); List<?> list = res.getResponses(); Long remainTTL = (Long) list.get(0); Map<String, Object> oldState = (Map<String, Object>) list.get(2); if (remainTTL == -2) { remainTTL = delegate.getMaxInactiveInterval().toMillis(); } RBatch batchNew = redisson.createBatch(); batchNew.getMap(keyPrefix + id, map.getCodec()).putAllAsync(oldState); if (remainTTL > 0) { batchNew.getBucket(getExpiredKey(id)).setAsync("", remainTTL, TimeUnit.MILLISECONDS); } batchNew.execute(); map = redisson.getMap(keyPrefix + id, map.getCodec()); return id; }
Source:
public LongArray newLongArray( long length, long defaultValue, long base ) { LongArray array = newDynamicLongArray( fractionOf( length ), defaultValue ); array.at( length - 1 ); return array; }

Target:
public LongArray newLongArray( long length, long defaultValue, long base ) { return newDynamicLongArray( fractionOf( length ), defaultValue ); }
Source:
public ListenableFuture<?> processFor(Duration duration) { checkLockNotHeld("Can not process for a duration while holding the driver lock"); requireNonNull(duration, "duration is null"); if (!previousDriverBlockedFuture.isDone()) { return previousDriverBlockedFuture; } long maxRuntime = duration.roundTo(TimeUnit.NANOSECONDS); Optional<ListenableFuture<?>> result = tryWithLock(100, TimeUnit.MILLISECONDS, () -> { driverContext.startProcessTimer(); driverContext.getYieldSignal().setWithDelay(maxRuntime, driverContext.getYieldExecutor()); try { long start = System.nanoTime(); do { ListenableFuture<?> future = processInternal(); if (!future.isDone()) { previousDriverBlockedFuture = wakeUpOnRevokeRequest(future); return previousDriverBlockedFuture; } } while (System.nanoTime() - start < maxRuntime && !isFinishedInternal()); } finally { driverContext.getYieldSignal().reset(); driverContext.recordProcessed(); } return NOT_BLOCKED; }); return result.orElse(NOT_BLOCKED); }

Target:
public ListenableFuture<?> processFor(Duration duration) { checkState(initialized.get(), "Driver is not initialized"); checkLockNotHeld("Can not process for a duration while holding the driver lock"); requireNonNull(duration, "duration is null"); SettableFuture<?> blockedFuture = driverBlockedFuture.get(); if (!blockedFuture.isDone()) { return blockedFuture; } long maxRuntime = duration.roundTo(TimeUnit.NANOSECONDS); Optional<ListenableFuture<?>> result = tryWithLock(100, TimeUnit.MILLISECONDS, () -> { driverContext.startProcessTimer(); driverContext.getYieldSignal().setWithDelay(maxRuntime, driverContext.getYieldExecutor()); try { long start = System.nanoTime(); do { ListenableFuture<?> future = processInternal(); if (!future.isDone()) { return updateDriverBlockedFuture(future); } } while (System.nanoTime() - start < maxRuntime && !isFinishedInternal()); } finally { driverContext.getYieldSignal().reset(); driverContext.recordProcessed(); } return NOT_BLOCKED; }); return result.orElse(NOT_BLOCKED); }
Source:
public DefaultDescriptionPreprocessorWithFiltering(Class<SIRIUS> descriptionClass, Collection<EStructuralFeature> featuresToFilter, Collection<EStructuralFeature> featuresToCopy) { super(descriptionClass); this.featuresToCopy = featuresToCopy; this.featuresToFilter = featuresToFilter; }

Target:
public DefaultDescriptionPreprocessorWithFiltering(Class<SIRIUS> descriptionClass, Collection<EStructuralFeature> featuresToFilter, Collection<EStructuralFeature> featuresToCopy) { super(descriptionClass); this.featuresToCopy.addAll(featuresToCopy); this.featuresToFilter.addAll(featuresToFilter); }
Source:
public synchronized void onDescriptorsUpdated(DescriptorProvider descriptorProvider) { final TreeNode root = (TreeNode) getModel().getRoot(); final DefaultMutableTreeNode libraryNode = (DefaultMutableTreeNode) root.getChildAt(1); libraryNode.removeAllChildren(); createLibrary(libraryNode); final DefaultTreeModel model = (DefaultTreeModel) getModel(); model.reload(libraryNode); expandStandardPaths(); }

Target:
public void onDescriptorsUpdated(DescriptorProvider descriptorProvider) { final TreeNode root = (TreeNode) getModel().getRoot(); final DefaultMutableTreeNode libraryNode = (DefaultMutableTreeNode) root.getChildAt(1); libraryNode.removeAllChildren(); createLibrary(libraryNode); final DefaultTreeModel model = (DefaultTreeModel) getModel(); model.reload(libraryNode); expandStandardPaths(); }
Source:
private ColumnSet queryColumnsRemotely(QueryModel queryModel) { String json = client.resource(root) .path("query") .path("columns") .type(MediaType.APPLICATION_JSON_TYPE) .post(String.class, queryModel); JsonObject object = new Gson().fromJson(json, JsonObject.class); int numRows = object.getAsJsonPrimitive("rows").getAsInt(); Map<String, ColumnView> columnMap = new HashMap<>(); for (Map.Entry<String, JsonElement> column : object.getAsJsonObject("columns").entrySet()) { JsonObject columnValue = column.getValue().getAsJsonObject(); String storage = columnValue.getAsJsonPrimitive("storage").getAsString(); switch (storage) { case "array": columnMap.put(column.getKey(), new ColumnViewWrapper(numRows, columnValue.getAsJsonArray("values"))); break; default: throw new UnsupportedOperationException(storage); } } return new ColumnSet(numRows, columnMap); }

Target:
private ColumnSet queryColumnsRemotely(QueryModel queryModel) { String json = client.resource(root) .path("query") .path("columns") .type(MediaType.APPLICATION_JSON_TYPE) .post(String.class, queryModel); JsonObject object = new Gson().fromJson(json, JsonObject.class); int numRows = object.getAsJsonPrimitive("rows").getAsInt(); Map<String, ColumnView> columnMap = new HashMap<>(); for (Map.Entry<String, JsonElement> column : object.getAsJsonObject("columns").entrySet()) { JsonObject columnValue = column.getValue().getAsJsonObject(); String storage = columnValue.getAsJsonPrimitive("storage").getAsString(); switch (storage) { case "array": columnMap.put(column.getKey(), new ColumnViewWrapper(numRows, columnValue.getAsJsonArray("values"))); break; case "coordinates": columnMap.put(column.getKey(), parseCoordinates(columnValue.getAsJsonArray("coordinates"))); break; case "empty": columnMap.put(column.getKey(), parseEmpty(numRows, columnValue)); break; default: throw new UnsupportedOperationException(storage); } } return new ColumnSet(numRows, columnMap); }
Source:
public void connect(InetSocketAddress address, int timeoutMillis) throws IOException { try { checkNotNull(address, "address"); checkNotNegative(timeoutMillis, "timeoutMillis can't be negative"); socketChannel.configureBlocking(true); try { if (timeoutMillis > 0) { socketChannel.socket().connect(address, timeoutMillis); } else { socketChannel.connect(address); } } catch (SocketException ex) { SocketException newEx = new SocketException(ex.getMessage() + " to address " + address); newEx.setStackTrace(ex.getStackTrace()); throw newEx; } if (logger.isFinestEnabled()) { logger.finest("Successfully connected to: " + address + " using socket " + socketChannel.socket()); } } catch (RuntimeException e) { close(); throw e; } catch (IOException e) { close(); throw e; } }

Target:
public void connect(InetSocketAddress address, int timeoutMillis) throws IOException { try { checkNotNull(address, "address"); checkNotNegative(timeoutMillis, "timeoutMillis can't be negative"); socketChannel.configureBlocking(true); try { if (timeoutMillis > 0) { socketChannel.socket().connect(address, timeoutMillis); } else { socketChannel.connect(address); } } catch (SocketException ex) { SocketException newEx = new SocketException(ex.getMessage() + " to address " + address); newEx.setStackTrace(ex.getStackTrace()); throw newEx; } if (logger.isFinestEnabled()) { logger.finest("Successfully connected to: " + address + " using socket " + socketChannel.socket()); } } catch (RuntimeException e) { IOUtil.closeResource(this); throw e; } catch (IOException e) { IOUtil.closeResource(this); throw e; } }
Source:
public void testWrongClass() throws SQLException { Statement s = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = null; try { s.executeUpdate("INSERT INTO table1(" + columnName + ") VALUES(" + originalValue + ")"); rs = s.executeQuery(TestUtil.selectSQL("table1", "table1_id, " + columnName)); rs.next(); rs.updateObject(2, 23); rs.updateRow(); rs.close(); fail("should have thrown an Exception"); } catch (PSQLException e) { assertEquals(PSQLState.DATATYPE_MISMATCH.getState(), e.getSQLState()); } finally { if (rs != null) { rs.close(); } s.close(); } }

Target:
public void testWrongClass() throws SQLException { Statement s = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = null; try { s.executeUpdate("INSERT INTO table1(" + columnName + ") VALUES(" + originalValue + ")"); rs = s.executeQuery(TestUtil.selectSQL("table1", "table1_id, " + columnName)); rs.next(); rs.updateObject(2, 23); rs.updateRow(); rs.close(); fail("should have thrown an PSQLException because integers can't represent the date"); } catch (PSQLException e) { assertEquals("Should have thrown an DATATYPE_MISMATCH error, since integers can't represent the date", PSQLState.DATATYPE_MISMATCH.getState(), e.getSQLState()); } finally { TestUtil.closeQuietly(rs); TestUtil.closeQuietly(s); } }
Source:
public double estimateVariance() { final double[] variancesPerSegment = new double[numSegments]; for (int segment = 0; segment < numSegments; segment++) { variancesPerSegment[segment] = new Variance().evaluate(Doubles.toArray(getCoveragesInSegment(segment))); } return new Mean().evaluate(variancesPerSegment); }

Target:
public double estimateVariance() { return IntStream.range(0, numSegments) .mapToDouble(s -> new Variance().evaluate(Doubles.toArray(getIndexedCoveragesInSegment(s).stream().map(IndexedCoverage::getCoverage).collect(Collectors.toList())))) .average().getAsDouble(); }
Source:
public void testGetChangedAttributesWithAttachments() { TaskAttribute attributeAttachment = newData.getRoot().createAttribute("custom"); attributeAttachment.setValue("1"); attributeAttachment.getMetaData().setType(TaskAttribute.TYPE_ATTACHMENT); TaskDataDiff diff = manager.createDiff(newData, oldData, new NullProgressMonitor()); assertEquals(diff.getNewAttachments(), Collections.singleton(attributeAttachment)); }

Target:
public void testGetChangedAttributesWithAttachments() { TaskAttribute attributeAttachment = newData.getRoot().createAttribute("custom"); attributeAttachment.setValue("1"); attributeAttachment.getMetaData().setType(TaskAttribute.TYPE_ATTACHMENT); TaskDataDiff diff = manager.createDiff(newData, oldData, new NullProgressMonitor()); assertEquals(Collections.singleton(attributeAttachment), diff.getNewAttachments()); }
Source:
private static String getPath(ConstraintViolation cv) { return new PropertyPathTranslator().translate(cv.getPropertyPath().toString()); }

Target:
private static String getPath(ConstraintViolation cv) { return translate(cv.getPropertyPath().toString()); }
Source:
private void populatePostList() { if (getThreadListTask != null) { getThreadListTask.cancel(true); } getThreadListTask = new GetThreadListTask( getActivity(), courseData.getCourse().getId(), isAllTopics() ? new ArrayList<String>() : discussionTopic.getAllTopicIds(), postsFilter, postsSort, discussionPostsAdapter.getPagination() ) { @Override public void onSuccess(TopicThreads topicThreads) { if (topicThreads != null) { logger.debug("registration success=" + topicThreads); boolean hasMore = topicThreads.next != null && topicThreads.next.length() > 0; discussionPostsAdapter.addPage(topicThreads.getResults(), hasMore); refreshListViewOnDataChange(); } discussionPostsAdapter.setVoteCountsEnabled(postsSort == DiscussionPostsSort.VoteCount); discussionPostsAdapter.notifyDataSetChanged(); checkNoResultView(); } @Override public void onException(Exception ex) { logger.error(ex); } }; getThreadListTask.execute(); }

Target:
private void populatePostList() { if (getThreadListTask != null) { getThreadListTask.cancel(true); } getThreadListTask = new GetThreadListTask( getActivity(), courseData.getCourse().getId(), isAllTopics() ? Collections.EMPTY_LIST : discussionTopic.getAllTopicIds(), postsFilter, postsSort, discussionPostsAdapter.getPagination() ) { @Override public void onSuccess(TopicThreads topicThreads) { if (topicThreads != null) { logger.debug("registration success=" + topicThreads); boolean hasMore = topicThreads.next != null && topicThreads.next.length() > 0; discussionPostsAdapter.addPage(topicThreads.getResults(), hasMore); refreshListViewOnDataChange(); } discussionPostsAdapter.setVoteCountsEnabled(postsSort == DiscussionPostsSort.VoteCount); discussionPostsAdapter.notifyDataSetChanged(); checkNoResultView(); } @Override public void onException(Exception ex) { logger.error(ex); } }; getThreadListTask.execute(); }
Source:
private static void logInQueueTime(CheckpointTriggerRequest request) { if (LOG.isDebugEnabled()) { long timeInQueue = request.timestamp - currentTimeMillis(); if (timeInQueue > LOG_TIME_IN_QUEUE_THRESHOLD_MS) { LOG.debug("checkpoint request time in queue: {}", timeInQueue); } } }

Target:
private static void logInQueueTime(CheckpointTriggerRequest request) { if (LOG.isInfoEnabled()) { long timeInQueue = request.timestamp - currentTimeMillis(); if (timeInQueue > LOG_TIME_IN_QUEUE_THRESHOLD_MS) { LOG.info("checkpoint request time in queue: {}", timeInQueue); } } }
Source:
public void setParameter(String name, String value) { if(name == null) { throw new NullPointerException("parameter name is null ! "); } if(value == null) { removeParameter(name); return; } if(isModifiable == ModifiableRule.NotModifiable) { throw new IllegalStateException("it is forbidden to modify the parameters"); } if(name.equalsIgnoreCase("tag") && (isModifiable == ModifiableRule.From || isModifiable == ModifiableRule.To)) { throw new IllegalStateException("it is forbidden to set the tag parameter on To or From Header"); } if(name.equalsIgnoreCase("branch") && isModifiable == ModifiableRule.Via) { throw new IllegalStateException("it is forbidden to set the branch parameter on the Via Header"); } this.parameters.put(name.toLowerCase(), value); if(header != null) { boolean isQuotableParameter = false; SipContext context = SipApplicationSessionCreationThreadLocal.lookupContext(); if (context != null){ Object object = context.getServletContext().getAttribute("org.restcomm.servlets.sip.QUOTABLE_PARAMETER"); if (object != null){ String quotableParameters = object.toString(); if (!quotableParameters.isEmpty()){ String[] parameters = quotableParameters.split(","); for (int i = 0; i < parameters.length; i++){ if (parameters[i].trim().equalsIgnoreCase(name)){ isQuotableParameter = true; break; } } } } } try { if (isQuotableParameter && header instanceof ParametersExt){ ((ParametersExt) header).setQuotedParameter(name, value); }else{ header.setParameter(name, "".equals(value) ? null : value); } } catch (ParseException e) { throw new IllegalArgumentException("Problem setting parameter",e); } } }

Target:
public void setParameter(String name, String value) { if(name == null) { throw new NullPointerException("parameter name is null ! "); } if(value == null) { removeParameter(name); return; } if(isModifiable == ModifiableRule.NotModifiable) { throw new IllegalStateException("it is forbidden to modify the parameters"); } if(name.equalsIgnoreCase("tag") && (isModifiable == ModifiableRule.From || isModifiable == ModifiableRule.To)) { throw new IllegalStateException("it is forbidden to set the tag parameter on To or From Header"); } if(name.equalsIgnoreCase("branch") && isModifiable == ModifiableRule.Via) { throw new IllegalStateException("it is forbidden to set the branch parameter on the Via Header"); } this.parameters.put(name.toLowerCase(), value); if(header != null) { try { if (isQuotableParam(name) && (header instanceof ParametersExt)){ ((ParametersExt) header).setQuotedParameter(name, value); }else{ header.setParameter(name, "".equals(value) ? null : value); } } catch (ParseException e) { throw new IllegalArgumentException("Problem setting parameter",e); } } }
Source:
private Uri getOutputUri() { Uri outputUri = getIntent().getParcelableExtra(MediaStore.EXTRA_OUTPUT); if (outputUri == null) { File outDir = new File(Environment.getExternalStorageDirectory(), SOUND_DIR); if (!outDir.exists()) outDir.mkdir(); else if (!outDir.isDirectory()) { outDir = getExternalCacheDir(); } SimpleDateFormat s = new SimpleDateFormat("yyyyMMdd_hhmmss"); String format = s.format(new Date()); outputUri = Uri.fromFile(new File(outDir, "SND_" + format + ".3gp")); } return outputUri; }

Target:
private Uri getOutputUri() { Uri outputUri = getIntent().getParcelableExtra(MediaStore.EXTRA_OUTPUT); if (outputUri == null) { File outDir = new File(Environment.getExternalStorageDirectory(), SOUND_DIR); if (!outDir.exists()) { outDir.mkdir(); } else if (!outDir.isDirectory()) { outDir = getExternalCacheDir(); } SimpleDateFormat s = new SimpleDateFormat("yyyyMMdd_hhmmss"); String format = s.format(new Date()); outputUri = Uri.fromFile(new File(outDir, "SND_" + format + ".3gp")); } return outputUri; }
Source:
private VariantAnnotation mapAnnotationJson(String variant, String annotationJSON) throws IOException { List<VariantAnnotation> list = Transformer.mapJsonToInstance( annotationJSON, VariantAnnotation.class, new ExternalSourceObjectMapper()); VariantAnnotation vepVariantAnnotation = list.get(0); vepVariantAnnotation.setVariant(variant); return vepVariantAnnotation; }

Target:
private VariantAnnotation mapAnnotationJson(String variant, String annotationJSON) throws IOException { List<VariantAnnotation> list = this.externalResourceTransformer.transform( annotationJSON, VariantAnnotation.class); VariantAnnotation vepVariantAnnotation = list.get(0); vepVariantAnnotation.setVariant(variant); return vepVariantAnnotation; }
Source:
public void testLiteralWhile() throws Exception { final DefaultConfiguration configurationTestLiteralWhile = createCheckConfig(WhitespaceAfterCheck.class); configurationTestLiteralWhile.addAttribute("tokens", "LITERAL_WHILE"); final String[] expected = { "39:14: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, "while"), }; verify(configurationTestLiteralWhile, getPath("InputWhitespaceAfterConditions.java"), expected); }

Target:
public void testLiteralWhile() throws Exception { final DefaultConfiguration configurationTestLiteralWhile = createCheckConfig(WhitespaceAfterCheck.class); configurationTestLiteralWhile.addAttribute("tokens", "LITERAL_WHILE"); final String[] expected = { "39:14: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, "while"), }; verify(configurationTestLiteralWhile, getPath("InputWhitespaceAfterLiteralWhile.java"), expected); }
Source:
private int doWrite( byte[] buf, int off, int len, Format format, StreamRTPManagerDesc exclusion) { int seqno = RawPacket.getSequenceNumber(buf, off, len); RTPTranslatorImpl translator = getTranslator(); if (translator == null) return 0; List<OutputDataStreamDesc> streams = _streams; boolean removeRTPHeaderExtensions = _removeRTPHeaderExtensions; int written = 0; for (int i = 0, end = streams.size(); i < end; ++i) { OutputDataStreamDesc s = streams.get(i); StreamRTPManagerDesc streamRTPManager = s.connectorDesc.streamRTPManagerDesc; RawPacket.setSequenceNumber(buf, off, seqno); if (streamRTPManager == exclusion) continue; boolean write; if (_data) { if (removeRTPHeaderExtensions) { removeRTPHeaderExtensions = false; len = removeRTPHeaderExtensions(buf, off, len); } write = willWriteData( streamRTPManager, buf, off, len, format, exclusion); } else { write = willWriteControl( streamRTPManager, buf, off, len, format, exclusion); } if (write) { write = translator.willWrite( exclusion, buf, off, len, streamRTPManager, _data); } Long ssrc = RawPacket.getSSRCAsLong(buf, off, len); SequenceNumberRewriter rewriter = s.ssrcToRewriter.get(ssrc); if (rewriter == null) { rewriter = new SequenceNumberRewriter(); s.ssrcToRewriter.put(ssrc, rewriter); } rewriter.rewrite(write, buf, off, len); if (!write) continue; int w = s.stream.write(buf, off, len); if (written < w) written = w; } return written; }

Target:
private int doWrite( byte[] buf, int off, int len, Format format, StreamRTPManagerDesc exclusion) { int originalSequenceNumber = RawPacket.getSequenceNumber(buf, off, len); RTPTranslatorImpl translator = getTranslator(); if (translator == null) return 0; List<OutputDataStreamDesc> streams = _streams; boolean removeRTPHeaderExtensions = _removeRTPHeaderExtensions; int written = 0; for (int i = 0, end = streams.size(); i < end; ++i) { OutputDataStreamDesc s = streams.get(i); StreamRTPManagerDesc streamRTPManager = s.connectorDesc.streamRTPManagerDesc; if (streamRTPManager == exclusion) continue; boolean write; if (_data) { if (removeRTPHeaderExtensions) { removeRTPHeaderExtensions = false; len = removeRTPHeaderExtensions(buf, off, len); } write = willWriteData( streamRTPManager, buf, off, len, format, exclusion); } else { write = willWriteControl( streamRTPManager, buf, off, len, format, exclusion); } if (write) { write = translator.willWrite( exclusion, buf, off, len, streamRTPManager, _data); } boolean altered = false; if (_data) { Long ssrc = RawPacket.getSSRCAsLong(buf, off, len); SequenceNumberRewriter rewriter = streamRTPManager.streamRTPManager.ssrcToRewriter.get(ssrc); if (rewriter == null) { rewriter = new SequenceNumberRewriter(); streamRTPManager .streamRTPManager.ssrcToRewriter.put(ssrc, rewriter); } altered = rewriter.rewrite(write, buf, off, len); } if (write) { int w = s.stream.write(buf, off, len); if (written < w) written = w; } if (altered) { RawPacket .setSequenceNumber(buf, off, originalSequenceNumber); } } return written; }
Source:
public static PaxosUseCase fromString(String string) { switch(string) { case PaxosTimeLockConstants.LEADER_PAXOS_NAMESPACE: return LEADER; case PaxosTimeLockConstants.CLIENT_PAXOS_NAMESPACE: return TIMESTAMP; default: throw new SafeIllegalArgumentException("unrecognized used case"); } }

Target:
public static PaxosUseCase fromString(String string) { switch(string) { case PaxosTimeLockConstants.LEADER_PAXOS_NAMESPACE: return LEADER; case PaxosTimeLockConstants.CLIENT_PAXOS_NAMESPACE: return TIMESTAMP; default: throw new SafeIllegalArgumentException("unrecognized use case"); } }
Source:
public CrossGammaMultiCurveCalculator(final double shift, final InstrumentDerivativeVisitor<MulticurveProviderInterface, MultipleCurrencyMulticurveSensitivity> curveSensitivityCalculator) { _psc = new ParameterSensitivityParameterCalculator<>(curveSensitivityCalculator); _shift = shift; }

Target:
public CrossGammaMultiCurveCalculator(final double shift, final InstrumentDerivativeVisitor<MulticurveProviderInterface, MultipleCurrencyMulticurveSensitivity> curveSensitivityCalculator) { ArgumentChecker.notNull(curveSensitivityCalculator, "sensitivity calculator"); ArgumentChecker.isTrue(Math.abs(shift) > 1.0E-10, "shift should not be larger in absolute value than 1.0E-10"); _psc = new ParameterSensitivityParameterCalculator<>(curveSensitivityCalculator); _shift = shift; }
Source:
private IDPProperties(){ }

Target:
private IDPProperties() { throw new AssertionError("Must not initiate an object of IDPProperties class"); }
Source:
public Response doImport(Action action) { validateParameters(action, "cluster.id|name"); Guid destStorageDomainId = getDestStorageDomainId(action); ImportVmParameters params = new ImportVmParameters(getEntity(), parent.getStorageDomainId(), destStorageDomainId, parent.getDataCenterId(destStorageDomainId), getClusterId(action)); params.setImageToDestinationDomainMap(getDiskToDestinationMap(action)); params.setForceOverride(action.isSetForce() ? action.isForce() : false); if (action.isSetVm() && action.getVm().isSetSnapshots() && action.getVm().getSnapshots().isSetCollapseSnapshots()) { params.setCopyCollapse(action.getVm().getSnapshots().isCollapseSnapshots()); } if (action.isSetClone()) { params.setImportAsNewEntity(action.isClone()); if(action.isSetVm() && action.getVm().isSetName()) { params.getVm().setvm_name(action.getVm().getName()); } } return doAction(VdcActionType.ImportVm, params, action); }

Target:
public Response doImport(Action action) { validateParameters(action, "cluster.id|name"); Guid destStorageDomainId = getDestStorageDomainId(action); ImportVmParameters params = new ImportVmParameters(getEntity(), parent.getStorageDomainId(), destStorageDomainId, parent.getDataCenterId(destStorageDomainId), getClusterId(action)); params.setImageToDestinationDomainMap(getDiskToDestinationMap(action)); params.setForceOverride(action.isSetExclusive() ? action.isExclusive() : false); if (action.isSetVm() && action.getVm().isSetSnapshots() && action.getVm().getSnapshots().isSetCollapseSnapshots()) { params.setCopyCollapse(action.getVm().getSnapshots().isCollapseSnapshots()); } if (action.isSetClone()) { params.setImportAsNewEntity(action.isClone()); if(action.isSetVm() && action.getVm().isSetName()) { params.getVm().setvm_name(action.getVm().getName()); } } return doAction(VdcActionType.ImportVm, params, action); }
Source:
public NoSuchFileException(String file, String other, String reason) { super(file + ", other " + other + ", reason " + reason); }

Target:
public NoSuchFileException(String file, String other, String reason) { super(MessageFormat.format(JGitText.get().noSuchFile, file, other, reason)); }
Source:
public String errorMessageWhile() { return "Server stilll has state " + currentState.getText(); }

Target:
public String errorMessageWhile() { return "Server still has state '" + currentState.getText() + "'"; }
Source:
public void write(int arg0) throws IOException { while(true) { if(lastWriteFuture.isDone() && !isClosed) { lastWriteFuture = c.write(ByteBuffer.wrap(new byte[]{(byte) arg0})); return; } else { try { lastWriteFuture.get(1000, TimeUnit.MILLISECONDS); } catch (Exception e) { ExceptionUtils.handleException(e); } } } }

Target:
public void write(int arg0) throws IOException { while(true) { if(lastWriteFuture.isDone() && !isClosed) { lastWriteFuture = c.write(ByteBuffer.wrap(new byte[]{(byte) arg0})); return; } else { blockWriteFuture(lastWriteFuture); } } }
Source:
private static void compensate() { List<KeyValue> commandSnapshots = DbFacade.getInstance().getBusinessEntitySnapshotDao().getAllCommands(); for (KeyValue commandSnapshot : commandSnapshots) { CommandBase<?> cmd = CommandsFactory.createCommand(commandSnapshot.getValue().toString(), (Guid) commandSnapshot.getKey()); if (cmd != null) { try { cmd.compensate(); } catch (RuntimeException e) { log.error( "Failed to run compensation on startup for Command '{}', Command Id '{}', due to: {}", commandSnapshot.getValue(), commandSnapshot.getKey(), ExceptionUtils.getMessage(e)); log.debug("Exception", e); } log.info("Running compensation on startup for Command '{}', Command Id '{}'", commandSnapshot.getValue(), commandSnapshot.getKey()); } else { log.error("Failed to run compensation on startup for Command '{}', Command Id '{}'", commandSnapshot.getValue(), commandSnapshot.getKey()); } } }

Target:
private static void compensate() { List<KeyValue> commandSnapshots = DbFacade.getInstance().getBusinessEntitySnapshotDao().getAllCommands(); for (KeyValue commandSnapshot : commandSnapshots) { CommandBase<?> cmd = CommandsFactory.createCommand(commandSnapshot.getValue().toString(), (Guid) commandSnapshot.getKey()); if (cmd != null) { try { cmd.compensate(); } catch (RuntimeException e) { log.error( "Failed to run compensation on startup for Command '{}', Command Id '{}': {}", commandSnapshot.getValue(), commandSnapshot.getKey(), ExceptionUtils.getMessage(e)); log.debug("Exception", e); } log.info("Running compensation on startup for Command '{}', Command Id '{}'", commandSnapshot.getValue(), commandSnapshot.getKey()); } else { log.error("Failed to run compensation on startup for Command '{}', Command Id '{}'", commandSnapshot.getValue(), commandSnapshot.getKey()); } } }
Source:
protected void populateDataTypes(String entity, Set<Field> metaFieldSet, ArrayList<String> headers, ArrayList<String> dataTypes) { try { final ClassLoader classLoader = getClass().getClassLoader(); final Class entityClass = classLoader.loadClass("com.bullhornsdk.data.model.entity.core.standard." + entity); for (Method method : Arrays.asList(entityClass.getMethods())){ if ("set".equalsIgnoreCase(method.getName().substring(0, 3))) { methodSet.add(method.getName().substring(3).toLowerCase()); } } } catch(ClassNotFoundException e) { throw new NullPointerException("Unknown entity passed as argument"); } for (Field field : metaFieldSet) { if ((methodSet.contains(field.getName().toLowerCase()) && !field.getName().contains("."))) { if (!isCompositeType(field)) { headers.add(field.getName()); if(field.getDataType() == null) { field.setDataType("Integer"); } dataTypes.add(field.getDataType()); } else if (isCompositeType(field)) { List<Method> compositeMethodList = getCompositeMethodList(entity, field); compositeMethodList.stream().forEach(n -> headers.add(getCompositeHeaderName(n, field))); compositeMethodList.stream().forEach(n -> dataTypes.add(n.getReturnType().getSimpleName())); } } } }

Target:
protected void populateDataTypes(String entity, Set<Field> metaFieldSet, ArrayList<String> headers, ArrayList<String> dataTypes) throws ClassNotFoundException { final HashSet<String> methodSet = getEntityFields(entity); for (Field field : metaFieldSet) { if ((methodSet.contains(field.getName().toLowerCase()) && !field.getName().contains("."))) { if (!isCompositeType(field)) { headers.add(field.getName()); if(field.getDataType() == null) { field.setDataType("Integer"); } dataTypes.add(field.getDataType()); } else if (isCompositeType(field)) { List<Method> compositeMethodList = getCompositeMethodList(entity, field); compositeMethodList.stream().forEach(n -> headers.add(getCompositeHeaderName(n, field))); compositeMethodList.stream().forEach(n -> dataTypes.add(n.getReturnType().getSimpleName())); } } } }
Source:
public void teardownTest() throws InterruptedException { Thread.sleep(10000); if (currentServer != null) { assertNodeAvailable(currentServer); deleteServer(currentServer.id()); } if (cloneServer != null) { assertNodeAvailable(cloneServer); deleteServer(cloneServer.id()); } }

Target:
public void teardownTest() throws InterruptedException { if (currentServer != null) { assertNodeAvailable(currentServer); deleteServer(currentServer.id()); } if (cloneServer != null) { assertNodeAvailable(cloneServer); deleteServer(cloneServer.id()); } }
Source:
public void updateAttachmentsList(Attachment attachment){ Attachment originalAttachment = attachments.get(attachment.uri); originalAttachment.updateResizeInfo(attachment.resizeFactor, attachment.overrideDefault); Log.d("ATTACH","Yes : " + attachments.size()); }

Target:
public void updateAttachmentsList(Attachment attachment){ Attachment originalAttachment = attachments.get(attachment.uri); originalAttachment.updateResizeInfo(attachment.resizeFactor, attachment.overrideDefault); }
Source:
private TraceFileSystemElement filterByTimerange(TraceFileSystemElement selectedFileSystemElements, IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor, 1); subMonitor.subTask(Messages.ImportTraceWizard_FilteringOperationTaskName); String tracePath = selectedFileSystemElements.getFileSystemObject().getAbsolutePath(); ITmfTrace trace = null; try { TraceTypeHelper traceTypeHelper = TmfTraceTypeUIUtils.selectTraceType(tracePath, null, null); if (traceTypeHelper == null) { return null; } trace = traceTypeHelper.getTrace(); IConfigurationElement ce = TmfTraceType.getTraceAttributes(traceTypeHelper.getTraceTypeId()); if (ce == null) { return null; } ITmfEvent event = (ITmfEvent) ce.createExecutableExtension(TmfTraceType.EVENT_TYPE_ATTR); trace.initTrace(null, tracePath, event.getClass()); if (isInTimerange(trace)) { return selectedFileSystemElements; } } catch (TmfTraceImportException | CoreException | TmfTraceException e) { String errorMessage = Messages.ImportTraceWizard_ImportProblem + ": " + tracePath; Activator.getDefault().logError(errorMessage, e); } finally { subMonitor.worked(1); if (trace != null) { trace.dispose(); } } return null; }

Target:
private TraceFileSystemElement filterByTimerange(TraceFileSystemElement selectedFileSystemElements, IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor, 1); subMonitor.subTask(Messages.ImportTraceWizard_FilteringOperationTaskName); String tracePath = selectedFileSystemElements.getFileSystemObject().getAbsolutePath(); ITmfTrace trace = null; try { TraceTypeHelper traceTypeHelper = TmfTraceTypeUIUtils.selectTraceType(tracePath, null, null); if (traceTypeHelper == null) { return null; } IConfigurationElement ce = TmfTraceType.getTraceAttributes(traceTypeHelper.getTraceTypeId()); if (ce == null) { return null; } trace = (ITmfTrace) ce.createExecutableExtension(TmfTraceType.TRACE_TYPE_ATTR); ITmfEvent event = (ITmfEvent) ce.createExecutableExtension(TmfTraceType.EVENT_TYPE_ATTR); trace.initTrace(null, tracePath, event.getClass()); if (isInTimerange(trace)) { return selectedFileSystemElements; } } catch (TmfTraceImportException | CoreException | TmfTraceException e) { String errorMessage = Messages.ImportTraceWizard_ImportProblem + ": " + tracePath; Activator.getDefault().logError(errorMessage, e); } finally { if (trace != null) { trace.dispose(); TmfTraceManager.deleteSupplementaryFolder(trace); } subMonitor.worked(1); } return null; }
Source:
private Map<String, Object> renderReadme(RevWalk walk, GitilesView view, Config cfg, RevObject head) throws IOException { RevTree rootTree; try { rootTree = walk.parseTree(head); } catch (MissingObjectException | IncorrectObjectTypeException notTreeish) { return null; } ReadmeHelper readme = new ReadmeHelper(walk.getObjectReader(), view, cfg, rootTree); readme.scanTree(rootTree); if (readme.isPresent()) { return ImmutableMap.<String, Object> of("readmeHtml", readme.render()); } return null; }

Target:
private Map<String, Object> renderReadme(RevWalk walk, GitilesView view, Config cfg, RevObject head) throws IOException { RevTree rootTree; try { rootTree = walk.parseTree(head); } catch (IncorrectObjectTypeException notTreeish) { return null; } ReadmeHelper readme = new ReadmeHelper(walk.getObjectReader(), view, cfg, rootTree); readme.scanTree(rootTree); if (readme.isPresent()) { return ImmutableMap.<String, Object> of("readmeHtml", readme.render()); } return null; }
Source:
public static List<List<String>> extractTests(File file) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(file)); List<List<String>> tests = new ArrayList<>(); List<String> test = new ArrayList<>(); String line = reader.readLine(); while (line != null) { switch (line) { case "!": tests.add(test); test = new ArrayList<>(); break; default: test.add(line); break; } line = reader.readLine(); } tests.add(test); tests = tests.subList(1, tests.size()); return tests; }

Target:
public static List<TckIndividualTest> extractTests(File file) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(file)); List<TckIndividualTest> tests = new ArrayList<>(); List<String> test = new ArrayList<>(); String line = reader.readLine(); String testFile = file.getName().replaceFirst(TckIndividualTest.clientPrefix, ""); while (line != null) { switch (line) { case "!": String name = ""; if (test.size() > 1) { name = test.get(0).split("%%")[1]; } TckIndividualTest tckTest = new TckIndividualTest(name, test, testFile); tests.add(tckTest); test = new ArrayList<>(); break; default: test.add(line); break; } line = reader.readLine(); } if (test.size() > 0) { String name = ""; name = test.get(0).split("%%")[1]; TckIndividualTest tckTest = new TckIndividualTest(name, test, testFile); tests.add(tckTest); tests = tests.subList(1, tests.size()); } return tests; }
Source:
public AbstractRuntimeManager(RuntimeEnvironment environment, String identifier) { this.environment = environment; this.identifier = identifier; if (registry.isRegistered(identifier)) { throw new IllegalStateException("RuntimeManager with id " + identifier + " is already active"); } ((SimpleRuntimeEnvironment)environment).getEnvironmentTemplate().set(EnvironmentName.DEPLOYMENT_ID, this.getIdentifier()); internalSetDeploymentDescriptor(); internalSetKieContainer(); ((InternalRegisterableItemsFactory)environment.getRegisterableItemsFactory()).setRuntimeManager(this); String eagerInit = (String)((SimpleRuntimeEnvironment)environment).getEnvironmentTemplate().get("RuntimeEngineEagerInit"); if (eagerInit != null) { engineInitEager = Boolean.parseBoolean(eagerInit); } ExecutionErrorStorage storage = (ExecutionErrorStorage) ((SimpleRuntimeEnvironment)environment).getEnvironmentTemplate().get("ExecutionErrorStorage"); if (storage == null) { storage = new DefaultExecutionErrorStorage(environment.getEnvironment()); } this.executionErrorManager = new ExecutionErrorManagerImpl(storage); ((SimpleRuntimeEnvironment)environment).getEnvironmentTemplate().set(EnvironmentName.EXEC_ERROR_MANAGER, executionErrorManager); if ((this instanceof SingletonRuntimeManager) && (environment instanceof SchedulerProvider)) { GlobalSchedulerService schedulerService = ((SchedulerProvider) environment).getSchedulerService(); Class<?> clazz; try { clazz = Class.forName("org.jbpm.services.ejb.timer.EjbSchedulerService"); if (schedulerService != null && schedulerService.getClass().equals(clazz)) { logger.warn("Singleton with EJB Timer Service is not recommended as it's not stable under load"); } } catch (ClassNotFoundException e) { } } logger.info("{} is created for {}", this.getClass().getSimpleName(), identifier); }

Target:
public AbstractRuntimeManager(RuntimeEnvironment environment, String identifier) { this.environment = environment; this.identifier = identifier; if (registry.isRegistered(identifier)) { throw new IllegalStateException("RuntimeManager with id " + identifier + " is already active"); } ((SimpleRuntimeEnvironment)environment).getEnvironmentTemplate().set(EnvironmentName.DEPLOYMENT_ID, this.getIdentifier()); internalSetDeploymentDescriptor(); internalSetKieContainer(); ((InternalRegisterableItemsFactory)environment.getRegisterableItemsFactory()).setRuntimeManager(this); String eagerInit = (String)((SimpleRuntimeEnvironment)environment).getEnvironmentTemplate().get("RuntimeEngineEagerInit"); if (eagerInit != null) { engineInitEager = Boolean.parseBoolean(eagerInit); } ExecutionErrorStorage storage = (ExecutionErrorStorage) ((SimpleRuntimeEnvironment)environment).getEnvironmentTemplate().get("ExecutionErrorStorage"); if (storage == null) { storage = new DefaultExecutionErrorStorage(environment.getEnvironment()); } this.executionErrorManager = new ExecutionErrorManagerImpl(storage); ((SimpleRuntimeEnvironment)environment).getEnvironmentTemplate().set(EnvironmentName.EXEC_ERROR_MANAGER, executionErrorManager); logger.info("{} is created for {}", this.getClass().getSimpleName(), identifier); }
Source:
private ByteBuffer ensure(ByteBuffer buffer, int size) { if (buffer == null) { buffer = allocator.allocate(size); } else if (buffer.capacity() >= size) { buffer.clear(); } else { allocator.release(buffer); release(buffer); buffer = allocator.allocate(size); } return buffer; }

Target:
private ByteBuffer ensure(ByteBuffer buffer, int size) { if (buffer == null) { buffer = allocator.allocate(size); } else if (buffer.capacity() >= size) { buffer.clear(); } else { release(buffer); buffer = allocator.allocate(size); } return buffer; }
Source:
public final void show() { Gdx.input.setInputProcessor(cStage); TextButtonStyle style = new TextButtonStyle(); style.font = cFont; cButtonSettings = new TextButton("Settings", style); cButtonStroll = new TextButton("Stroll", style); cWidth = Gdx.graphics.getWidth(); cHeight = Gdx.graphics.getHeight(); cButtonSettings.setPosition(cWidth / 2f - cButtonSettings.getWidth() / 2f, cHeight / 2f); cButtonStroll.setPosition(cWidth / 2f - cButtonStroll.getWidth() / 2f, cHeight / 2f + 20); cButtonSettings.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { ((Game) Gdx.app.getApplicationListener()).setScreen(new Settings()); Gdx.app.debug("Button", "Settings"); } }); cButtonStroll.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { Gdx.app.debug("Button", "Stroll"); } }); cStage.addActor(cButtonSettings); cStage.addActor(cButtonStroll); TimerTask timerTask = new TimerTask() { @Override public void onTick(int seconds) { cButtonStroll.setText("Stroll: " + seconds); } @Override public void onStart() { cButtonStroll.setText("Stroll: "); cButtonStroll.setDisabled(true); } @Override public void onStop() { cButtonStroll.setText("Stroll"); cButtonStroll.setDisabled(false); } }; TimeKeeper.getInstance().getTimer("INTERVAL").subscribe(timerTask); }

Target:
public void show() { cBatch = new SpriteBatch(); cBackground = new Texture(Gdx.files.internal("demobackground.jpg")); cStage = new Stage(); cFont = new BitmapFont(); Gdx.input.setInputProcessor(cStage); TextButtonStyle style = new TextButtonStyle(); style.font = cFont; cButtonSettings = new TextButton("Settings", style); cButtonStroll = new TextButton("Stroll", style); cWidth = Gdx.graphics.getWidth(); cHeight = Gdx.graphics.getHeight(); cButtonSettings.setPosition(cWidth / 2f - cButtonSettings.getWidth() / 2f, cHeight / 2f); cButtonStroll.setPosition(cWidth / 2f - cButtonStroll.getWidth() / 2f, cHeight / 2f + 20); cButtonSettings.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { ((Game) Gdx.app.getApplicationListener()).setScreen(new Settings()); Gdx.app.debug("Button", "Settings"); } }); cButtonStroll.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { Gdx.app.debug("Button", "Stroll"); } }); cStage.addActor(cButtonSettings); cStage.addActor(cButtonStroll); TimerTask timerTask = new TimerTask() { @Override public void onTick(int seconds) { cButtonStroll.setText("Stroll: " + seconds); } @Override public void onStart() { cButtonStroll.setText("Stroll: "); cButtonStroll.setDisabled(true); } @Override public void onStop() { cButtonStroll.setText("Stroll"); cButtonStroll.setDisabled(false); } }; TimeKeeper.getInstance().getTimer("INTERVAL").subscribe(timerTask); }