auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public PythonFunctionRegistrar getPythonFunctionRegistrar() throws DbException { PythonFunctionRegistrar pyFuncRegistrar = null; try { if (execEnvVars.get(MyriaConstants.EXEC_ENV_VAR_TEST_MODE) == null) { if (getLocalSubQuery() instanceof WorkerSubQuery) { pyFuncRegistrar = ((WorkerSubQuery) getLocalSubQuery()).getWorker().getPythonFunctionRegistrar(); } } } catch (Exception e) { LOGGER.debug("exception getting pyFuncRegistrar"); pyFuncRegistrar = null; } return pyFuncRegistrar; }

Target:
public PythonFunctionRegistrar getPythonFunctionRegistrar() throws DbException { PythonFunctionRegistrar pyFuncRegistrar = null; if (!execEnvVars.containsKey(MyriaConstants.EXEC_ENV_VAR_TEST_MODE)) { if (getLocalSubQuery() instanceof WorkerSubQuery) { pyFuncRegistrar = ((WorkerSubQuery) getLocalSubQuery()).getWorker().getPythonFunctionRegistrar(); } } return pyFuncRegistrar; }
Source:
public static int getBatchSize(Type type) { int batchSize = 1000 * 10; if (type == Type.BLOB_TYPE) { batchSize = 1; } return batchSize; }

Target:
public static int getBatchSize(Type type) { int batchSize = 1000 * 10; if (type == Type.BLOB_TYPE) batchSize = 1; return batchSize; }
Source:
public DataFileWriter<D> appendTo(File file) throws IOException { SeekableInput input = new SeekableFileInput(file); OutputStream output = new SyncableFileOutputStream(file, true); try { return appendTo(input, output); } finally { input.close(); } }

Target:
public DataFileWriter<D> appendTo(File file) throws IOException { SeekableInput input = null; try { input = new SeekableFileInput(file); OutputStream output = new SyncableFileOutputStream(file, true); return appendTo(input, output); } finally { if (input != null) input.close(); // output does not need to be closed here. It will be closed by invoking close() of this writer. } }
Source:
public void tearDown() throws Exception { // delete temporary jks files File credDir = new File("."); File file = new File(credDir, JKS_FILE_NAME); file.delete(); file = new File(credDir, "." + JKS_FILE_NAME + ".crc"); file.delete(); }

Target:
public void tearDown() throws Exception { // delete temporary jks files File file = new File(credDir, JKS_FILE_NAME); file.delete(); file = new File(credDir, "." + JKS_FILE_NAME + ".crc"); file.delete(); }
Source:
public void setup() throws Exception { System.out.println("Executing setup"); StateStoreProperties.get().setProperty(FalconJPAService.URL, url); Configuration localConf = new Configuration(); fs.initialize(LocalFileSystem.getDefaultUri(localConf), localConf); fs.mkdirs(new Path(DB_BASE_DIR)); createDB(DB_SQL_FILE); falconJPAService.init(); this.dfsCluster = EmbeddedCluster.newCluster("testCluster"); this.conf = dfsCluster.getConf(); // registerServices(); }

Target:
public void setup() throws Exception{ StateStoreProperties.get().setProperty(FalconJPAService.URL, url); Configuration localConf = new Configuration(); fs.initialize(LocalFileSystem.getDefaultUri(localConf), localConf); fs.mkdirs(new Path(DB_BASE_DIR)); createDB(DB_SQL_FILE); falconJPAService.init(); this.dfsCluster = EmbeddedCluster.newCluster("testCluster"); this.conf = dfsCluster.getConf(); }
Source:
public BridgeAPI bridgeAPI() { logger.error( "bridgeAPI({}) called. Should NEVER occur as it seems to be a lack of protocol-specific implementation of this bridge API."); return null; }

Target:
public BridgeAPI bridgeAPI() { logger.debug( "bridgeAPI({}) called. Should NEVER occur as it seems to be a lack of protocol-specific implementation of this bridge API."); return null; }
Source:
public void run() { try { while (!Thread.interrupted()) { // synchronizes the software with the system status // Every x seconds do a full bus scan checkForBusScan(); Thread.sleep(1000); } } catch (InterruptedException p_i_ex) { logger.error("Openwebnet.run, InterruptedException : " + p_i_ex.getMessage()); } catch (Exception p_i_ex) { logger.error("Openwebnet.run, Exception : {}", p_i_ex.getMessage()); } finally { // interrupt handler on monitor thread will stop thread monitorSessionThread.interrupt(); logger.info("Stopped monitorSessionThread thread"); } logger.info("Stopped OpenWebNet thread"); }

Target:
public void run() { try { while (!Thread.interrupted()) { // synchronizes the software with the system status // Every x seconds do a full bus scan checkForBusScan(); Thread.sleep(1000); } } catch (InterruptedException p_i_ex) { logger.error("Openwebnet.run, InterruptedException : " + p_i_ex.getMessage()); } catch (Exception p_i_ex) { logger.warn("Openwebnet.run, Exception : {}", p_i_ex.getMessage()); } finally { // interrupt handler on monitor thread will stop thread monitorSessionThread.interrupt(); logger.info("Stopped monitorSessionThread thread"); } logger.info("Stopped OpenWebNet thread"); }
Source:
public void notifyEvent(ProtocolRead p_i_event) { for (IBticinoEventListener l_event_listener : m_event_listener_list) { try { l_event_listener.handleEvent(p_i_event); } catch (Exception p_ex) { logger.error("notifyEvent, Exception : {}", p_ex.getMessage()); } } }

Target:
public void notifyEvent(ProtocolRead p_i_event) { for (IBticinoEventListener l_event_listener : m_event_listener_list) { try { l_event_listener.handleEvent(p_i_event); } catch (Exception p_ex) { logger.warn("notifyEvent, Exception : {}", p_ex.getMessage()); } } }
Source:
public static String updateStatusVar(LcnDefs.Var var, int value) throws IllegalArgumentException { int id = LcnDefs.Var.toVarId(var); if (id != -1) { // define variable to set, offset 0x01000000 int x2cmd = id |= 0x40; int b1 = (value >> 8) & 0xff; int b2 = value & 0xff; return String.format("X2%03d%03d%03d", x2cmd, b1, b2); } // Setting variables and thresholds absolute not implemented in LCN firmware yet throw new IllegalArgumentException(); }

Target:
public static String updateStatusVar(LcnDefs.Var var, int value) throws IllegalArgumentException { int id = LcnDefs.Var.toVarId(var); if (id != -1) { // define variable to set, offset 0x01000000 int x2cmd = id | 0x40; int b1 = (value >> 8) & 0xff; int b2 = value & 0xff; return String.format("X2%03d%03d%03d", x2cmd, b1, b2); } // Setting variables and thresholds absolute not implemented in LCN firmware yet throw new IllegalArgumentException(); }
Source:
private void writeResponse() { String result = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/html\r\n" + "Content-Length: " + 0 + "\r\n" + "Connection: close\r\n\r\n"; try { os.write(result.getBytes()); os.flush(); } catch (IOException e) { logger.debug("ERROR: " + e.getMessage()); } }

Target:
private void writeResponse() { String result = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/html\r\n" + "Content-Length: " + 0 + "\r\n" + "Connection: close\r\n\r\n"; try { os.write(result.getBytes()); os.flush(); } catch (IOException e) { logger.error(e.getMessage()); } }
Source:
public void failValidationWithoutSchema() throws Exception { final Environment env = new Environment.Mock() .withFile( "src/main/resources/noschema.xml", // @checkstyle LineLength (1 line) "<Configuration><Appenders><Console name=\"CONSOLE\" target=\"SYSTEM_OUT\"><PatternLayout pattern=\"[%p] %t %c: %m%n\"/></Console></Appenders></Configuration>" ); final Validator validator = new XmlValidator(true); validator.validate(env); }

Target:
public void failValidationWithoutSchema() throws Exception { new XmlValidator(true).validate(new Environment.Mock() .withFile( "src/main/resources/noschema.xml", // @checkstyle LineLength (1 line) "<Configuration><Appenders><Console name=\"CONSOLE\" target=\"SYSTEM_OUT\"><PatternLayout pattern=\"[%p] %t %c: %m%n\"/></Console></Appenders></Configuration>" ) ); }
Source:
private static boolean hasFigCaption(TagNode node) { if (node.getChildren().stream().anyMatch(TableWithoutCaptionCheck::isFigCaption)) { return true; } else { return node.getChildren().stream().filter(child -> !isTable(child)).anyMatch(TableWithoutCaptionCheck::hasFigCaption); } }

Target:
private static boolean hasFigCaption(TagNode node) { // node has one child at least return isFigCaption(node.getChildren().get(0)) || isFigCaption(node.getChildren().get(node.getChildren().size() - 1)); }
Source:
public FirecannonBlast(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{1}{R}{R}"); // Firecannon Blast deals 3 damage to target creature. // Raid - Firecannon Blast deals 6 damage to that creature instead if you attacked with a creature this turn. this.getSpellAbility().addEffect(new ConditionalOneShotEffect( new DamageTargetEffect(6), new DamageTargetEffect(3), new InvertCondition(RaidCondition.instance), "{this} deals 3 damage to target creature.<br><i>Raid</i> &mdash; {this} deals 6 damage instead if you attacked with a creature this turn")); this.getSpellAbility().addTarget(new TargetCreaturePermanent()); this.getSpellAbility().addWatcher(new PlayerAttackedWatcher()); }

Target:
public FirecannonBlast(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{1}{R}{R}"); // Firecannon Blast deals 3 damage to target creature. // Raid - Firecannon Blast deals 6 damage to that creature instead if you attacked with a creature this turn. this.getSpellAbility().addEffect(new ConditionalOneShotEffect( new DamageTargetEffect(6), new DamageTargetEffect(3), RaidCondition.instance, "{this} deals 3 damage to target creature.<br><i>Raid</i> &mdash; {this} deals 6 damage instead if you attacked with a creature this turn")); this.getSpellAbility().addTarget(new TargetCreaturePermanent()); this.getSpellAbility().addWatcher(new PlayerAttackedWatcher()); }
Source:
public TreacherousUrge(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{4}{B}"); this.subtype.add(SubType.ARCANE); // Target opponent reveals his or her hand. You may put a creature card from it onto the battlefield under your control. That creature gains haste. Sacrifice it at the beginning of the next end step. this.getSpellAbility().addEffect(new TreacherousUrgeEffect()); this.getSpellAbility().addTarget(new TargetOpponent()); }

Target:
public TreacherousUrge(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{4}{B}"); // Target opponent reveals his or her hand. You may put a creature card from it onto the battlefield under your control. That creature gains haste. Sacrifice it at the beginning of the next end step. this.getSpellAbility().addEffect(new TreacherousUrgeEffect()); this.getSpellAbility().addTarget(new TargetOpponent()); }
Source:
public DeeprootWaters(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{2}{U}"); // Whenever you cast a Merfolk spell, create a 1/1 blue Merfolk creature token with hexproof. this.addAbility(new SpellCastControllerTriggeredAbility(new CreateTokenEffect(new MerfolkHexproofToken(), 1, true, false), filter, false)); }

Target:
public DeeprootWaters(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{2}{U}"); // Whenever you cast a Merfolk spell, create a 1/1 blue Merfolk creature token with hexproof. this.addAbility(new SpellCastControllerTriggeredAbility(new CreateTokenEffect(new MerfolkHexproofToken()), filter, false)); }
Source:
protected Toolbar createMainToolbar() { toolbar_ = new Toolbar("Tutorial Tab"); // TODO: managing history within an iframe is surprisingly challenging, // so we just leave these buttons unavailable for now and just allow // navigation to home // toolbar_.addLeftWidget(commands_.tutorialBack().createToolbarButton()); // toolbar_.addLeftWidget(commands_.tutorialForward().createToolbarButton()); toolbar_.addLeftWidget(homeButton_ = commands_.tutorialHome().createToolbarButton()); toolbar_.addLeftWidget(commands_.tutorialPopout().createToolbarButton()); toolbar_.addLeftWidget(commands_.tutorialStop().createToolbarButton()); toolbar_.addRightWidget(commands_.tutorialRefresh().createToolbarButton()); return toolbar_; }

Target:
protected Toolbar createMainToolbar() { toolbar_ = new Toolbar("Tutorial Tab"); // TODO: managing history within an iframe is surprisingly challenging, // so we just leave these buttons unavailable for now and just allow // navigation to home // toolbar_.addLeftWidget(commands_.tutorialBack().createToolbarButton()); // toolbar_.addLeftWidget(commands_.tutorialForward().createToolbarButton()); toolbar_.addLeftWidget(commands_.tutorialHome().createToolbarButton()); toolbar_.addLeftWidget(commands_.tutorialPopout().createToolbarButton()); toolbar_.addLeftWidget(commands_.tutorialStop().createToolbarButton()); toolbar_.addRightWidget(commands_.tutorialRefresh().createToolbarButton()); return toolbar_; }
Source:
public SourceAppCommand getSourceCommand(AppCommand command, SourceColumn column) { // check if we've already create a SourceAppCommand for this command for (SourceAppCommand cmd : sourceAppCommands_) { if (cmd.getCommand() == command && cmd.getColumn() == column.getName()) return cmd; } // if not found, create it SourceAppCommand sourceCommand = new SourceAppCommand(command, column.getName(), this); sourceAppCommands_.add(sourceCommand); return sourceCommand; }

Target:
public SourceAppCommand getSourceCommand(AppCommand command, SourceColumn column) { // check if we've already create a SourceAppCommand for this command String key = command.getId() + column.getName(); if (sourceAppCommands_.get(key) != null) return sourceAppCommands_.get(key); // if not found, create it SourceAppCommand sourceCommand = new SourceAppCommand(command, column.getName(), this); sourceAppCommands_.put(key, sourceCommand); return sourceCommand; }
Source:
public void setActive(String name) { if (StringUtil.isNullOrEmpty(name)) { Debug.logWarning("Active column should be set to the main source window instead of null."); if (activeColumn_ != null) { activeColumn_.setActiveEditor(""); activeColumn_ = null; } return; } // If we can't find the column, use the main column. This may happen on start up. SourceColumn column = getByName(name); if (column == null) column = getByName(MAIN_SOURCE_NAME); setActive(column); }

Target:
public void setActive(String name) { if (StringUtil.isNullOrEmpty(name)) { if (activeColumn_ != null) { activeColumn_.setActiveEditor(""); activeColumn_ = null; } return; } // If we can't find the column, use the main column. This may happen on start up. SourceColumn column = getByName(name); if (column == null) column = getByName(MAIN_SOURCE_NAME); setActive(column); }
Source:
private void runShinyApp() { source_.withSaveFilesBeforeCommand(() -> { events_.fireEvent(new LaunchShinyApplicationEvent(getPath(), prefs_.shinyBackgroundJobs().getValue() ? ShinyApplication.BACKGROUND_APP : ShinyApplication.FOREGROUND_APP, getExtendedFileType())); }, new Command() { public void execute() { } }, "Run Shiny Application"); }

Target:
private void runShinyApp() { source_.withSaveFilesBeforeCommand(() -> { events_.fireEvent(new LaunchShinyApplicationEvent(getPath(), prefs_.shinyBackgroundJobs().getValue() ? ShinyApplication.BACKGROUND_APP : ShinyApplication.FOREGROUND_APP, getExtendedFileType())); }, () -> {}, "Run Shiny Application"); }
Source:
public void executeCallback() { // This method must be called by a single HighlightPair, but because there can be multiple // pairs per query, we need to check if the callback has already executed before proceeding. if(!highlighter_.getCallbackProcessed(index_)) { highlighter_.setCallbackProcessed(index_, true); highlighter_.getServer().executeRCode(callback_, new ServerRequestCallback<String>(){ @Override public void onResponseReceived(String results) { // Remove listener from this element and all other elements with the same query highlighter_.clearEvents(); } @Override public void onError(ServerError error) { Debug.logError(error); } }); } }

Target:
public void executeCallback() { // This method must be called by a single HighlightPair, but because there can be multiple // pairs per query, we need to check if the callback has already executed before proceeding. if(!highlighter_.getCallbackProcessed(index_)) { highlighter_.setCallbackProcessed(index_, true); highlighter_.getServer().executeRCode(callback_, new ServerRequestCallback<String>(){ @Override public void onResponseReceived(String results) { // Remove listener from this element and all other elements with the same query highlighter_.clearEvents(); } @Override public void onError(ServerError error) { // Remove listener from this element and all other elements with the same query highlighter_.clearEvents(); Debug.logError(error); } }); } }
Source:
public void ensureInputVisible() { // NOTE: we don't scroll immediately as this is normally called // in response to mutations of the console input buffer, and so // we need to wait until Ace has finished rendering in response // to that change. scrollIntoViewPending_ = true; // In case there wasn't an Ace render in-flight, force a check // for pending scroll (which will then force the cursor into view) Scheduler.get().scheduleDeferred(() -> checkForPendingScroll()); }

Target:
public void ensureInputVisible() { // NOTE: we don't scroll immediately as this is normally called // in response to mutations of the console input buffer, and so // we need to wait until Ace has finished rendering in response // to that change. // // In case there wasn't an Ace render in-flight, we also force a check // for pending scroll (which will then force the cursor into view) if (!scrollIntoViewPending_) { scrollIntoViewPending_ = true; Scheduler.get().scheduleDeferred(() -> checkForPendingScroll()); } }
Source:
private void nudgeAutosave() { // Cancel any existing autosave timer if (autoSaveTimer_.isRunning()) autoSaveTimer_.cancel(); // Start new timer if enabled if (prefs_.autoSaveOnIdle().getValue() == UserPrefs.AUTO_SAVE_ON_IDLE_COMMIT) autoSaveTimer_.schedule(prefs_.autoSaveMs()); }

Target:
private void nudgeAutosave() { // Cancel any existing autosave timer autoSaveTimer_.cancel(); // Start new timer if enabled if (prefs_.autoSaveOnIdle().getValue() == UserPrefs.AUTO_SAVE_ON_IDLE_COMMIT) autoSaveTimer_.schedule(prefs_.autoSaveMs()); }
Source:
public DelegatingResourceDescription getCreatableProperties() throws ResourceDoesNotSupportOperationException { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addRequiredProperty("diagnosis"); description.addRequiredProperty("encounter"); description.addRequiredProperty("uuid"); description.addRequiredProperty("condition"); description.addRequiredProperty("certainty"); description.addRequiredProperty("patient"); description.addRequiredProperty("rank"); return description; }

Target:
public DelegatingResourceDescription getCreatableProperties() throws ResourceDoesNotSupportOperationException { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addRequiredProperty("diagnosis"); description.addRequiredProperty("encounter"); description.addRequiredProperty("condition"); description.addRequiredProperty("certainty"); description.addRequiredProperty("patient"); description.addRequiredProperty("rank"); return description; }
Source:
public void started() { log.info("Started the REST Web Service module"); // Cache Swagger Spec new SwaggerSpecificationCreator("host/openmrs/ws/rest").BuildJSON(); }

Target:
public void started() { log.info("Started the REST Web Service module"); }
Source:
public static XSLTTransformation using(String location) { // classLoader instance needed to see the file passed in the location contextClassLoader = Thread.currentThread().getContextClassLoader(); XSLTTransformation tansformation = new XSLTTransformation(); tansformation.location = location; return tansformation; }

Target:
public static XSLTTransformation using(String location) { XSLTTransformation tansformation = new XSLTTransformation(); // classLoader instance needed to see the file passed in the location tansformation.contextClassLoader = Thread.currentThread().getContextClassLoader(); tansformation.location = location; return tansformation; }
Source:
private Always(F0<A> supplier) { this.supplier = supplier; }

Target:
Always(F0<A> supplier) { this.supplier = supplier; }
Source:
private PureTrampolineEval(Eval<A> start) { this.start = start; }

Target:
PureTrampolineEval(Eval<A> start) { this.start = start; }
Source:
private BindTrampolineEval(F<A, Eval<B>> f, TrampolineEval<A> next) { this.next = next; this.f = f; }

Target:
BindTrampolineEval(F<A, Eval<B>> f, TrampolineEval<A> next) { this.next = next; this.f = f; }
Source:
public String toString() { //Don't call getCommand and getData since it causes //AuSetDeferredAttribute to evaluate the deferred value final StringBuffer sb = new StringBuffer(60).append("[cmd=").append(_cmd); if (_data != null && _data.length > 0) { sb.append(", {"); for (AuSetAttribute d : (AuSetAttribute[]) _data) { sb.append(d); } sb.append('}'); } return sb.append(']').toString(); }

Target:
public String toString() { final StringBuilder sb = new StringBuilder(60).append("[cmd=").append(_cmd); if (_data != null && _data.length > 0) { sb.append(", {"); for (AuSetAttribute d : (AuSetAttribute[]) _data) { sb.append(d); } sb.append('}'); } return sb.append(']').toString(); }
Source:
public void setConstraint(String constr) { if (!isValidConstraint(constr)) throw new WrongValueException("Invalid constraint: " + constr + " (the constraint should be formatted in yyyyMMdd)"); setConstraint(constr != null ? new SimpleDateConstraint(constr) : null); // Bug 2564298 }

Target:
public void setConstraint(String constr) { setConstraint(constr != null ? new SimpleDateConstraint(constr) : null); // Bug 2564298 }
Source:
public static List<String> addProperties(String key, List<String> values) { if (key == null) throw new NullPointerException(); if (key.length() == 0) throw new IllegalArgumentException(); List<String> old = _props.get(key); synchronized (_props) { if (old == null) old = new LinkedList<String>(); old.addAll(values); } return _props.put(key, old); }

Target:
public static List<String> addProperties(String key, List<String> values) { if (key == null) throw new NullPointerException(); if (key.length() == 0) throw new IllegalArgumentException(); synchronized (_props) { List<String> old = _props.get(key); if (old == null) old = new LinkedList<String>(); old.addAll(values); return _props.put(key, old); } }
Source:
private boolean isCheckmarkDeselectOther() { if (_ckDeselectOther == null) //ok to race _ckDeselectOther = Boolean .valueOf("true".equals(Library.getProperty("org.zkoss.zul.tree.checkmarkDeselectOthers"))); return Utils.testAttribute(this, "org.zkoss.zul.listbox.checkmarkDeselectOthers", _ckDeselectOther.booleanValue(), true); }

Target:
private boolean isCheckmarkDeselectOther() { if (_ckDeselectOther == null) //ok to race _ckDeselectOther = Boolean .valueOf("true".equals(Library.getProperty("org.zkoss.zul.tree.checkmarkDeselectOthers"))); return Utils.testAttribute(this, "org.zkoss.zul.tree.checkmarkDeselectOthers", _ckDeselectOther.booleanValue(), true); }
Source:
protected void renderProperties(org.zkoss.zk.ui.sys.ContentRenderer renderer) throws java.io.IOException { super.renderProperties(renderer); if (_columns > 0) renderer.render("columns", _columns); if (_columns > 0 && _start > 0) renderer.render("start", _start); //F85-ZK-3525: frozen support smooth mode (ee only) renderer.render("smooth", isSmooth()); }

Target:
protected void renderProperties(org.zkoss.zk.ui.sys.ContentRenderer renderer) throws java.io.IOException { super.renderProperties(renderer); if (_columns > 0) renderer.render("columns", _columns); if (_columns > 0 && _start > 0) renderer.render("start", _start); //F85-ZK-3525: frozen support smooth mode (ee only) if (!isSmooth()) renderer.render("smooth", false); }
Source:
public void onStart() { super.onStart(); EventBus.getDefault().register(this); autoDownload = prefs.getString(PREF_AUTO_DOWNLOAD,STRING_NO_FILTER); keepUpdated = prefs.getString(PREF_KEEP_UPDATED,STRING_NO_FILTER); autoDelete = prefs.getString(PREF_AUTO_DELETE,STRING_NO_FILTER); loadSubscriptions(); }

Target:
public void onStart() { super.onStart(); EventBus.getDefault().register(this); // autoDownload = SubscriptionFilterDialog.AutoDownload.valueOf(prefs.getString(PREF_AUTO_DOWNLOAD,STRING_NO_FILTER)); // keepUpdated = SubscriptionFilterDialog.KeepUpdated.valueOf(prefs.getString(PREF_KEEP_UPDATED,STRING_NO_FILTER)); // autoDelete =SubscriptionFilterDialog.AutoDelete.valueOf(prefs.getString(PREF_AUTO_DELETE,STRING_NO_FILTER)); loadSubscriptions(); }
Source:
public boolean onStartJob(JobParameters params) { Log.d(TAG, "Job started"); ClientConfig.initialize(getApplicationContext()); new Thread(() -> { FeedUpdateUtils.startAutoUpdate(getApplicationContext(), true); UserPreferences.restartUpdateAlarm(false); jobFinished(params, false); // needsReschedule = false }).start(); return true; }

Target:
public boolean onStartJob(JobParameters params) { Log.d(TAG, "Job started"); ClientConfig.initialize(getApplicationContext()); FeedUpdateUtils.startAutoUpdate(getApplicationContext(), () -> { UserPreferences.restartUpdateAlarm(false); jobFinished(params, false); // needsReschedule = false }); return true; }
Source:
private static String getWebsiteLinkWithFallback(Playable media) { String link = null; if (media != null) { link = media.getWebsiteLink(); if (link == null) { if (media instanceof FeedMedia) { link = FeedItemUtil.getLinkWithFallback(((FeedMedia)media).getItem()); } // else case not a FeedMedia, return null } } // else no media, return null return link; }

Target:
private static String getWebsiteLinkWithFallback(Playable media) { if (media == null) { return null; } else if (media.getWebsiteLink() != null) { return media.getWebsiteLink(); } else if (media instanceof FeedMedia) { return FeedItemUtil.getLinkWithFallback(((FeedMedia)media).getItem()); } return null; }
Source:
public static String getLinkWithFallback(FeedItem item) { String link = null; if (item != null) { link = item.getLink(); if (link == null) { Feed feed = item.getFeed(); if (feed != null) { link = feed.getLink(); } } } // else null item, can only return null return link; }

Target:
public static String getLinkWithFallback(FeedItem item) { if (item == null) { return null; } else if (item.getLink() != null) { return item.getLink(); } else if (item.getFeed() != null) { return item.getFeed().getLink(); } return null; }
Source:
public void testParseDateWithIncorrectWeekday() { GregorianCalendar exp1 = new GregorianCalendar(2014, 9, 8, 9, 00, 00); exp1.setTimeZone(TimeZone.getTimeZone("GMT")); Date expected = new Date(exp1.getTimeInMillis()); Date actual = DateUtils.parse("Thu, 8 Oct 2014 09:00:00 GMT"); // actually a Wednesday assertEquals(expected, actual); }

Target:
public void testParseDateWithIncorrectWeekday() { GregorianCalendar exp1 = new GregorianCalendar(2014, 9, 8, 9, 0, 0); exp1.setTimeZone(TimeZone.getTimeZone("GMT")); Date expected = new Date(exp1.getTimeInMillis()); Date actual = DateUtils.parse("Thu, 8 Oct 2014 09:00:00 GMT"); // actually a Wednesday assertEquals(expected, actual); }
Source:
private void updatePlaybackSpeedButton() { if(butPlaybackSpeed == null) { return; } // TODO this possibly needs to change if we introduce an alternative button if (controller == null || !(this instanceof AudioplayerActivity)) { butPlaybackSpeed.setVisibility(View.GONE); return; } updatePlaybackSpeedButtonText(); ViewCompat.setAlpha(butPlaybackSpeed, controller.canSetPlaybackSpeed() ? 1.0f : 0.5f); butPlaybackSpeed.setVisibility(View.VISIBLE); }

Target:
protected void updatePlaybackSpeedButton() { // Only meaningful on AudioplayerActivity, where it is overridden. }
Source:
public void setCharset(String charset) { if(charset == null) { throw new UnsupportedCharsetException("provided mediatype does not support setting charset"); } if(StringUtils.isNotEmpty(charset)) { this.charset = Charset.forName(charset); } }

Target:
public void setCharset(String charset) { if(this.charset == null) { throw new UnsupportedCharsetException("provided mediatype does not support setting charset"); } if(StringUtils.isNotEmpty(charset)) { this.charset = Charset.forName(charset); } }
Source:
private String determineDestination(ParameterValueList pvl) { if (StringUtils.isNotEmpty(getDestination())) { return getDestination(); } if (pvl!=null && pvl.containsKey(PARAMETER_DESTINATION)) { return pvl.getParameterValue(PARAMETER_DESTINATION).asStringValue(""); } return null; }

Target:
private String determineDestination(ParameterValueList pvl) { if (StringUtils.isNotEmpty(getDestination())) { return getDestination(); } if (pvl!=null && pvl.containsKey(PARAMETER_DESTINATION)) { return pvl.getParameterValue(PARAMETER_DESTINATION).asStringValue(null); } return null; }
Source:
public Message(Object request) { if (request instanceof Message) { this.request = ((Message)request).asObject(); } else { this.request = request; } }

Target:
private Message(Object request) { if (request instanceof Message) { // this code could be reached when this constructor was public and the actual type of the parameter was not known at compile time. // e.g. new Message(pipeRunResult.getResult()); this.request = ((Message)request).asObject(); } else { this.request = request; } }
Source:
private ArrayList<String> getSuperClasses(Class clazz) { ArrayList<String> superClasses = new ArrayList<String>(); int index = 0; while (clazz.getSuperclass() != null) { // Assign a string with a priority number attached to it and add it to the array of superclasses String str = Integer.toString(index); superClasses.add(clazz.getSimpleName() + str); clazz = clazz.getSuperclass(); index++; } return superClasses; }

Target:
private ArrayList<String> getSuperClasses(Class clazz) { ArrayList<String> superClasses = new ArrayList<String>(); while (clazz.getSuperclass() != null) { // Assign a string with a priority number attached to it and add it to the array of superclasses superClasses.add(clazz.getSuperclass().getSimpleName()); clazz = clazz.getSuperclass(); } return superClasses; }
Source:
public void add(String message, Throwable t) { String msgToLog = message; if(t.getMessage() != null) { msgToLog += ": "+t.getMessage(); } add(msgToLog); log.error(msgToLog, t); }

Target:
public void add(String message, Throwable t) { String msgToLog = message; if(t.getMessage() != null) { msgToLog += ": "+t.getMessage(); } add(msgToLog); log.warn(msgToLog, t); }
Source:
public String getLocalName() { String hostName = exchange.getDestinationAddress().getHostName(); if (hostName == null) { //return the IP as string return exchange.getDestinationAddress().getHostString(); } return hostName; }

Target:
public String getLocalName() { return exchange.getDestinationAddress().getHostName(); }
Source:
public void resolve_hasAnnotations_hasNoCookieParams() { // given HasAnnotations hasAnnotations = mock(HasAnnotations.class); // when String value = resolver.resolve(hasAnnotations); // then assertThat(value).isEqualTo(SOME_VALUE); }

Target:
public void resolve_hasAnnotations_hasNoCookieParams() { // given HasAnnotations hasAnnotations = mock(HasAnnotations.class); // when resolver.resolve(hasAnnotations); }
Source:
public TypedAction getAction() { return action; }

Target:
protected TypedAction getAction() { return action; }
Source:
protected <T> GinLinkedBindingBuilder<T> bindAnnotated(Class<T> clazz) { GinAnnotatedBindingBuilder<T> binding = bind(clazz); if (annotationClass != null) { return binding.annotatedWith(annotationClass); } return binding; }

Target:
private <T> GinLinkedBindingBuilder<T> bindAnnotated(Class<T> clazz) { GinAnnotatedBindingBuilder<T> binding = bind(clazz); if (annotationClass != null) { return binding.annotatedWith(annotationClass); } return binding; }
Source:
protected boolean connect() throws IOException { if (isConnected()) { return false; } if (super.connect()) { this.sslEngine = sslContext.createSSLEngine(); this.sslEngine.setUseClientMode(true); this.sslSession = sslEngine.getSession(); // Begin handshake sslEngine.beginHandshake(); doHandshake(channel(), sslEngine, ByteBuffer.allocate(sslSession.getPacketBufferSize()), ByteBuffer.allocate(sslSession.getPacketBufferSize())); } return false; }

Target:
protected boolean connect() throws IOException { if (super.connect()) { this.sslEngine = sslContext.createSSLEngine(); this.sslEngine.setUseClientMode(true); this.sslSession = sslEngine.getSession(); // Begin handshake sslEngine.beginHandshake(); doHandshake(channel(), sslEngine, ByteBuffer.allocate(sslSession.getPacketBufferSize()), ByteBuffer.allocate(sslSession.getPacketBufferSize())); } return false; }
Source:
private static boolean isEjbModule(IModule module) { IModuleType type = module.getModuleType(); return IWTPConstants.FACET_EJB.equals(type.getId()); //$NON-NLS-1$ }

Target:
private static boolean isEjbModule(IModule module) { IModuleType type = module.getModuleType(); if (type == null) { return false; } return IWTPConstants.FACET_EJB.equals(type.getId()); //$NON-NLS-1$ }
Source:
public void testKerberosAuthenticatorExceptionInExecute() throws Exception { String principal = flumePrincipal; String keytab = flumeKeytab.getAbsolutePath(); // Clear the previous statically stored logged in credentials FlumeAuthenticationUtil.clearCredentials(); FlumeAuthenticator authenticator = FlumeAuthenticationUtil.getAuthenticator(principal, keytab); assertTrue(authenticator instanceof KerberosAuthenticator); authenticator.execute(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { throw new IOException(); } }); }

Target:
public void testKerberosAuthenticatorExceptionInExecute() throws Exception { String principal = flumePrincipal; String keytab = flumeKeytab.getAbsolutePath(); FlumeAuthenticator authenticator = FlumeAuthenticationUtil.getAuthenticator(principal, keytab); assertTrue(authenticator instanceof KerberosAuthenticator); authenticator.execute(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { throw new IOException(); } }); }
Source:
public LatestLinkBuilder(File dir) throws IOException { System.out.println(String.format("Writing plugin symlinks and redirects to dir: %s", dir)); index = new IndexHtmlBuilder(dir,"Permalinks to latest files"); htaccess = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir,".htaccess")), "UTF-8")); htaccess.println("# GENERATED. DO NOT MODIFY."); // Redirect directive doesn't let us write redirect rules relative to the directory .htaccess exists, // so we are back to mod_rewrite htaccess.println("RewriteEngine on"); }

Target:
public LatestLinkBuilder(File dir) throws IOException { System.out.println(String.format("Writing plugin symlinks and redirects to dir: %s", dir)); index = new IndexHtmlBuilder(dir,"Permalinks to latest files"); htaccess = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir,".htaccess"), true), "UTF-8")); htaccess.println("# GENERATED. DO NOT MODIFY."); // Redirect directive doesn't let us write redirect rules relative to the directory .htaccess exists, // so we are back to mod_rewrite htaccess.println("RewriteEngine on"); }
Source:
public DynamicBooleanProperty(String propName, boolean defaultValue) { super(propName, Boolean.valueOf(defaultValue)); // Set the initial value of the cached primitive value. this.primitiveValue = chooseValue(); // Add a callback to update the cached primitive value when the property is changed. this.prop.addCallback(new Runnable() { @Override public void run() { primitiveValue = chooseValue(); } }); }

Target:
public DynamicBooleanProperty(String propName, boolean defaultValue) { super(propName, Boolean.valueOf(defaultValue)); }
Source:
protected void propertyChanged() { super.propertyChanged(); // derived.set(this.derive(this.get())); deriveAndSet(); }

Target:
protected void propertyChanged()
Source:
public void start() { // The DISCOVERY_INIT_TOPOLOGY should be the first event to be processed for both ACTIVE and STANDBY sites. this.eventQueue.add(new DiscoveryServiceEvent(DISCOVER_INIT_TOPOLOGY)); this.executorService.submit(this::run); startDiscovery(); }

Target:
public void start() { // The DISCOVERY_INIT_TOPOLOGY should be the first event to be processed for both ACTIVE and STANDBY sites. this.eventQueue.add(new DiscoveryServiceEvent(DISCOVER_INIT_TOPOLOGY)); this.executorService.submit(this::run); }
Source:
LogReplicationEntry generateMessageWithOpaqueEntryList(List<OpaqueEntry> opaqueEntryList, UUID logEntryRequestId) { // Set the last timestamp as the max timestamp currentMsgTs = opaqueEntryList.get(opaqueEntryList.size() - 1).getVersion(); LogReplicationEntry txMessage = new LogReplicationEntry(MSG_TYPE, topologyConfigId, logEntryRequestId, currentMsgTs, preMsgTs, globalBaseSnapshot, sequence, opaqueEntryList); preMsgTs = currentMsgTs; sequence++; log.trace("Generate a log entry message with transactions ", txMessage.getMetadata(), opaqueEntryList.size()); return txMessage; }

Target:
private LogReplicationEntry generateMessageWithOpaqueEntryList(List<OpaqueEntry> opaqueEntryList, UUID logEntryRequestId) { // Set the last timestamp as the max timestamp currentMsgTs = opaqueEntryList.get(opaqueEntryList.size() - 1).getVersion(); LogReplicationEntry txMessage = new LogReplicationEntry(MSG_TYPE, topologyConfigId, logEntryRequestId, currentMsgTs, preMsgTs, globalBaseSnapshot, sequence, opaqueEntryList); preMsgTs = currentMsgTs; sequence++; log.trace("Generate a log entry message with transactions ", txMessage.getMetadata(), opaqueEntryList.size()); return txMessage; }
Source:
boolean shouldProcess(OpaqueEntry entry) { Set<UUID> tmpUUIDs = entry.getEntries().keySet(); //If the entry's stream set is a subset of interested streams, it is the entry we should process if (streamUUIDs.containsAll(tmpUUIDs)) { return true; } //If the entry's stream set has no overlap with the interested streams, it should be skipped. tmpUUIDs.retainAll(streamUUIDs); if (tmpUUIDs.isEmpty()) { return false; } // If the entry's stream set contains both interested streams and other streams, it is not // the expected behavior log.error("There are noisy streams in the entry, expected streams set {}", entry.getEntries().keySet(), streamUUIDs); hasNoiseData = true; return false; }

Target:
private boolean shouldProcess(OpaqueEntry entry) { Set<UUID> tmpUUIDs = entry.getEntries().keySet(); //If the entry's stream set is a subset of interested streams, it is the entry we should process if (streamUUIDs.containsAll(tmpUUIDs)) { return true; } //If the entry's stream set has no overlap with the interested streams, it should be skipped. tmpUUIDs.retainAll(streamUUIDs); if (tmpUUIDs.isEmpty()) { return false; } // If the entry's stream set contains both interested streams and other streams, it is not // the expected behavior log.error("There are noisy streams in the entry, expected streams set {}", entry.getEntries().keySet(), streamUUIDs); hasNoiseData = true; return false; }
Source:
long getLastProcessed() { return logReplicationMetadataManager.getLastProcessedLogTimestamp(null); }

Target:
public long getLastProcessed() { return logReplicationMetadataManager.getLastProcessedLogTimestamp(null); }
Source:
TxBuilder getTxBuilder() { return corfuStore.tx(namespace); }

Target:
public TxBuilder getTxBuilder() { return corfuStore.tx(namespace); }
Source:
public CompletableFuture<LogReplicationEntry> sendWithBuffering(LogReplicationEntry message) { //todo need to be removed. message.getMetadata().setSnapshotSyncSeqNum(maxAckedMsgSeqNum++); pendingMessages.append(message); log.info("Send messsage {}", message.getMetadata()); CompletableFuture<LogReplicationEntry> cf = dataSender.send(message); addCFToAcked(message, cf); return cf; }

Target:
public CompletableFuture<LogReplicationEntry> sendWithBuffering(LogReplicationEntry message) { message.getMetadata().setSnapshotSyncSeqNum(maxAckedMsgSeqNum++); pendingMessages.append(message); log.trace("Send messsage {}", message.getMetadata()); CompletableFuture<LogReplicationEntry> cf = dataSender.send(message); addCFToAcked(message, cf); return cf; }
Source:
private void completeSnapshotApply(LogReplicationEntry inputEntry) { log.debug("Complete of a snapshot apply"); //check if the all the expected message has received rxState = RxState.LOG_ENTRY_SYNC; logReplicationMetadataManager.setSnapshotApplied(inputEntry); logEntrySinkBufferManager = new LogEntrySinkBufferManager(ackCycleTime, ackCycleCnt, bufferSize, logReplicationMetadataManager.getLastProcessedLogTimestamp(), this); log.info("Sink manager completed SNAPSHOT transfer for and has transit to state.", inputEntry, rxState); }

Target:
private void completeSnapshotApply(LogReplicationEntry inputEntry) { log.debug("Complete of a snapshot apply"); //check if the all the expected message has received rxState = RxState.LOG_ENTRY_SYNC; logReplicationMetadataManager.setSnapshotApplied(inputEntry); //logEntrySinkBufferManager = new LogEntrySinkBufferManager(ackCycleTime, ackCycleCnt, bufferSize, // logReplicationMetadataManager.getLastProcessedLogTimestamp(), this); log.info("Sink manager completed SNAPSHOT transfer for and has transit to state.", inputEntry, rxState); }
Source:
private CompletableFuture<CorfuInterClusterReplicationServerNode> startDiscoveryService(ServerContext serverContext) throws InterruptedException { log.info("Start Discovery Service."); CompletableFuture<CorfuInterClusterReplicationServerNode> discoveryServiceCallback = new CompletableFuture<>(); this.clusterManagerAdapter = buildClusterManagerAdapter(serverContext.getPluginConfigFilePath()); // Start LogReplicationDiscovery Service, responsible for // acquiring lock, retrieving Site Manager Info and processing this info // so this node is initialized as Source (sender) or Sink (receiver) replicationDiscoveryService = new CorfuReplicationDiscoveryService(serverContext, clusterManagerAdapter, discoveryServiceCallback); return discoveryServiceCallback; }

Target:
private CompletableFuture<CorfuInterClusterReplicationServerNode> startDiscoveryService(ServerContext serverContext) { log.info("Start Discovery Service."); CompletableFuture<CorfuInterClusterReplicationServerNode> discoveryServiceCallback = new CompletableFuture<>(); this.clusterManagerAdapter = buildClusterManagerAdapter(serverContext.getPluginConfigFilePath()); // Start LogReplicationDiscovery Service, responsible for // acquiring lock, retrieving Site Manager Info and processing this info // so this node is initialized as Source (sender) or Sink (receiver) replicationDiscoveryService = new CorfuReplicationDiscoveryService(serverContext, clusterManagerAdapter, discoveryServiceCallback); replicationDiscoveryService.start(); return discoveryServiceCallback; }
Source:
private void updatePointer(final ILogData data) { // Update the global pointer, if it is non-checkpoint data. if ((data.isData() && !data.hasCheckpointMetadata()) || (data.isHole() && (data.getBackpointerMap().isEmpty() || data.containsStream(getCurrentContext().id))) ) { // Note: here we only set the global pointer and do not validate its position with respect to the trim mark, // as the pointer is expected to be moving step by step (for instance when syncing a stream up to maxGlobal) // The validation is deferred to these methods which call it in advance based on the expected final position // of the pointer. getCurrentContext().setGlobalPointer(data.getGlobalAddress()); } }

Target:
private void updatePointer(final ILogData data) { // Update the global pointer, if it is non-checkpoint data. if ((data.isData() || data.isHole()) && !data.hasCheckpointMetadata()) { // Note: here we only set the global pointer and do not validate its position with respect to the trim mark, // as the pointer is expected to be moving step by step (for instance when syncing a stream up to maxGlobal) // The validation is deferred to these methods which call it in advance based on the expected final position // of the pointer. getCurrentContext().setGlobalPointer(data.getGlobalAddress()); } }
Source:
public Stream<Entry<K, V>> entryStream() { final ReadOptions readOptions = new ReadOptions(); // If ReadOptions.snapshot is given, the iterator will return data as of the snapshot. // If it is nullptr, the iterator will read from an implicit snapshot as of the time the // iterator is created. The implicit snapshot is preserved by pinning resource. readOptions.setSnapshot(null); final RocksDbEntryIterator entryIterator = new RocksDbEntryIterator(rocksDb.newIterator(readOptions), serializer); // It's necessary to use the RocksDbEntryIterator as try-with resource to ensure // the iterator is close, otherwise underlying RocksDB resources can leak Stream<Entry<K, V>> resStream = Streams.stream(entryIterator); resStream.onClose(entryIterator::close); return resStream; }

Target:
public Stream<Entry<K, V>> entryStream() { final RocksDbEntryIterator entryIterator = new RocksDbEntryIterator(rocksDb, serializer); Stream<Entry<K, V>> resStream = Streams.stream(entryIterator); resStream.onClose(entryIterator::close); return resStream; }
Source:
private long firstAddress() { if (cacheEntries.peek() == null) return Address.NOT_FOUND; return cacheEntries.peek().txVersion; }

Target:
public long firstAddress() { if (cacheEntries.isEmpty()) { return Address.NOT_FOUND; } return cacheEntries.peek().txVersion; }
Source:
public long firstAddress() { if (cacheEntries.isEmpty()) return Address.NOT_FOUND; return cacheEntries.peek().txVersion; }

Target:
public long firstAddress() { if (cacheEntries.isEmpty()) { return Address.NOT_FOUND; } return cacheEntries.peek().txVersion; }
Source:
public static Config parse(Map<String, Object> opts) { int cacheSize = (int)(opts.containsKey("--sequencer-cache-size") ? Long.parseLong((String)opts.get("--sequencer-cache-size")) : DEFAULT_CACHE_SIZE); return Config.builder() .cacheSize(cacheSize) .build(); }

Target:
public static Config parse(Map<String, Object> opts) { int cacheSize = (int)(opts.containsKey("--sequencer-cache-size") ? Integer.parseInt((String)opts.get("--sequencer-cache-size")) : DEFAULT_CACHE_SIZE); return Config.builder() .cacheSize(cacheSize) .build(); }
Source:
public boolean getBindToAllInterfaces() { if (getNetworkInterface() != null || getHostAddress() != null) { return false; } else { return true; } }

Target:
public boolean getBindToAllInterfaces() { // Bind to all interfaces only if a network interface or host address // hasn't been specified return !(getNetworkInterface() != null || getHostAddress() != null); }
Source:
public boolean contains(long address) { int retryCount = 0; while (true) { try { StreamLogSegment segment = segmentManager.getStreamLogSegment(address); return segment.contains(address); } catch (ClosedSegmentException e) { log.warn("Segment channel closed by compactor, retry for another time."); // Segment could be closed because of compaction, retry once. if (retryCount++ == CLOSE_SEGMENT_EXCEPTION_RETRY) { throw e; } } } }

Target:
public boolean contains(long address) { StreamLogSegment segment = segmentManager.getStreamLogSegment(address); return segment.contains(address); }
Source:
private void cleanUpForRetry() { runtime.getAddressSpaceView().invalidateClientCache(); runtime.getObjectsView().getObjectCache().clear(); runtime.getStreamsView().getStreamCache().clear(); // Re ask for the Head, if it changes while we were trying. findAndSetLogHead(); findAndSetLogTail(); nextRead = logHead; resetAddressProcessed(); log.info("retry fastobject loader head " + logHead + " tail " + logTail); }

Target:
private void cleanUpForRetry() { runtime.getAddressSpaceView().invalidateClientCache(); runtime.getObjectsView().getObjectCache().clear(); runtime.getStreamsView().getStreamCache().clear(); log.info("retry fastobject loader head " + logHead + " tail " + logTail); }
Source:
private boolean cacheReadRequest(ReadOptions options) { if (runtime.getParameters().isCacheDisabled() && options.isClientCacheable()) { // TODO(Maithem): We can remove this once we have multi-level caches if (runtime.getParameters().getPriorityLevel() != PriorityLevel.HIGH) { // Avoid log flooding for background tasks (eg. checkpointer) log.warn("read: Runtime cache is disabled, but read request is requesting to cache"); } } return !runtime.getParameters().isCacheDisabled() && options.isClientCacheable(); }

Target:
private boolean cacheReadRequest(ReadOptions options) { return !runtime.getParameters().isCacheDisabled() && options.isClientCacheable(); }