auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean shouldEnableWiktionaryDialog() { return Prefs.useRestBase() && isWiktionaryDialogEnabledForArticleLanguage(); }

Target:
private boolean shouldEnableWiktionaryDialog() { return Prefs.useRestBase() && WikipediaApp.getInstance().isPreProdRelease() && isWiktionaryDialogEnabledForArticleLanguage(); }
Source:
public void unauthorizedUserShouldReceiveExpectedUnauthorizedResponse() { mockMvc.contentType("application/json") .accept(ContentType.JSON) .when() .get("/api/configuration/strongbox") .peek() .then() .statusCode(HttpStatus.FORBIDDEN.value()) .contentType("application/json") .body("error", CoreMatchers.equalTo("forbidden")); }

Target:
public void unauthorizedUserShouldReceiveExpectedUnauthorizedResponse() { mockMvc.contentType("application/json") .accept(ContentType.JSON) .when() .get("/api/configuration/strongbox") .peek() .then() .statusCode(HttpStatus.FORBIDDEN.value()) .contentType("application/json") .body("error", equalTo("forbidden")); }
Source:
public AnalysisResult analyze(IRevision revision, RevisionResult previousResults) { AnalysisResult resultFromDiffAnalysis = previousResults.getResultFromClass(FineGrainDifftAnalyzer.class); DiffResult diffResut = (DiffResult) resultFromDiffAnalysis; String filename = diffResut.getDiffOfFiles().keySet().iterator().next().toString(); if (resultFromDiffAnalysis == null) { System.err.println("Error Diff must be executed before"); throw new IllegalArgumentException("Error: missing diff"); } String path = revision.getFolder(); Map<String, File> filePaths = processFilesPair(new File(path)); File src = filePaths.get("src"); File target = filePaths.get("target"); Option option = new Option(); option.featureOption = FeatureOption.ORIGINAL; Boolean cross = false; CodeDiffer codeDiffer = new CodeDiffer(false, option,cross); List<FeatureMatrix> featureMatrix = codeDiffer.runByGenerator(src, target); JsonObject jsonfile = null; if(cross) { jsonfile = genVectorsCSV(option,target,featureMatrix); } else { jsonfile = getNonCrossJSON(option,target,featureMatrix); } JsonArray filesArray = new JsonArray(); JsonObject file = new JsonObject(); JsonArray changesArray = new JsonArray(); changesArray.add(jsonfile); file.addProperty("file_name", filename); file.add("features", changesArray); filesArray.add(file); JsonObject root = new JsonObject(); root.addProperty("id", revision.getName()); root.add("files", filesArray); return (new FeaturesResult(revision, root)); }

Target:
public AnalysisResult analyze(IRevision revision, RevisionResult previousResults) { AnalysisResult resultFromDiffAnalysis = previousResults.getResultFromClass(FineGrainDifftAnalyzer.class); DiffResult diffResut = (DiffResult) resultFromDiffAnalysis; String filename = diffResut.getDiffOfFiles().keySet().iterator().next().toString(); if (resultFromDiffAnalysis == null) { System.err.println("Error Diff must be executed before"); throw new IllegalArgumentException("Error: missing diff"); } String path = revision.getFolder(); Map<String, File> filePaths = processFilesPair(new File(path)); File src = filePaths.get("src"); File target = filePaths.get("target"); Option option = new Option(); option.featureOption = FeatureOption.ORIGINAL; Boolean cross = ComingProperties.getPropertyBoolean("cross"); CodeDiffer codeDiffer = new CodeDiffer(false, option,cross); List<FeatureMatrix> featureMatrix = codeDiffer.runByGenerator(src, target); JsonObject jsonfile = null; if(cross) { jsonfile = genVectorsCSV(option,target,featureMatrix); } else { jsonfile = getSimleP4JJSON(option,target,featureMatrix); } JsonArray filesArray = new JsonArray(); JsonObject file = new JsonObject(); JsonArray changesArray = new JsonArray(); changesArray.add(jsonfile); file.addProperty("file_name", filename); file.add("features", changesArray); filesArray.add(file); JsonObject root = new JsonObject(); root.addProperty("id", revision.getName()); root.add("files", filesArray); return (new FeaturesResult(revision, root)); }
Source:
public KeyPairProducer(int numberOfworkers) { this.numberOfWorkers = new AtomicInteger(numberOfworkers); final ExecutorService executorService = Executors.newSingleThreadExecutor(); future = executorService.submit(new Runnable() { @Override public void run() { while (!Thread.interrupted()) { try { int numberOfKeysToAdd = numberOfWorkers.get() - keyPairs.size(); if (numberOfKeysToAdd > 0) { for (int i = 0; i < numberOfKeysToAdd; ++i) { keyPairs.put(generateAndAddKeyPairs()); } } synchronized (keyPairs) { keyPairs.wait(loopTimeout); } } catch (InterruptedException e) { LOGGER.error("Thread was interrupted.", e); Thread.currentThread().interrupt(); } catch (Throwable e) { LOGGER.error(e); } } } }); }

Target:
public KeyPairProducer(int numberOfworkers) { this.keyPairs = new LinkedBlockingQueue(numberOfworkers); final Thread thread = new Thread(new Runnable() { @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { keyPairs.put(generateAndAddKeyPairs()); } } catch (InterruptedException e) { LOGGER.error(e); Thread.currentThread().interrupt(); } catch (Exception e) { LOGGER.error(e); } } }); thread.setDaemon(true); thread.start(); }
Source:
public void execute(final Credentials credentials, final Callback callback) { mCallback = callback; insertedCredentials = credentials; mAuthenticationManager.hardcodedLogin(ServerAPIController.getServerUrl(), new IAuthenticationManager.Callback<UserAccount>() { @Override public void onSuccess(UserAccount userAccount) { mAsyncExecutor.run(new Runnable() { @Override public void run() { pullOrganisationCredentials(credentials, callback); } }); } @Override public void onError(Throwable throwable) { if (throwable instanceof MalformedURLException || throwable instanceof UnknownHostException) { notifyServerURLNotValid(); } else if (throwable instanceof InvalidCredentialsException) { notifyInvalidCredentials(); } else if (throwable instanceof NetworkException) { ICredentialsRepository credentialsLocalDataSource = new CredentialsLocalDataSource(); checkUserCredentialsWithOrgUnit( credentialsLocalDataSource.getOrganisationCredentials(), false); } } }); }

Target:
public void execute(final Credentials credentials, final Callback callback) { mCallback = callback; insertedCredentials = credentials; mAsyncExecutor.run(this); }
Source:
protected JobId createJob(final String name, final String version, final String image, final List<String> command, final Map<String, String> env, final Map<String, PortMapping> ports, final Map<ServiceEndpoint, ServicePorts> registration, final Map<String, String> volumes) throws Exception { return createJob(name, version, image, command, env, ports, registration, volumes, null); }

Target:
protected JobId createJob(final String name, final String version, final String image, final List<String> command, final Map<String, String> env, final Map<String, PortMapping> ports, final Map<ServiceEndpoint, ServicePorts> registration, final Map<String, String> volumes) throws Exception { return createJob(name, version, image, command, env, ports, registration, volumes, EMPTY_EXPIRES); }
Source:
public boolean load(Element shared, Element perNode) throws JmriConfigureXmlException { getInstance(); try { } catch (NullPointerException ex) { } try { } catch (NullPointerException ex) { } loadCommon(shared, perNode, portController); register(); if (!portController.getDisabled()) { portController.configure(); try { portController.connect(); } catch (IOException ex) { log.error("Unable to start service: {}", ex.getMessage()); } } return true; }

Target:
public boolean load(Element shared, Element perNode) throws JmriConfigureXmlException { getInstance(); try { short port = (short)shared.getAttribute("port").getIntValue(); portController.setPort(port); } catch (org.jdom2.DataConversionException ex) { log.warn("Could not parse port attribute: {}", shared.getAttribute("port")); } catch (NullPointerException ex) { log.error("No port attribute availableCould not parse port attribute", ex); } loadCommon(shared, perNode, portController); register(); if (!portController.getDisabled()) { portController.configure(); try { portController.connect(); } catch (IOException ex) { log.error("Unable to start service: {}", ex.getMessage()); } } return true; }
Source:
private void assignActivityChristmasInterestCoupon(String message){ InvestSuccessMessage investSuccessMessage = JsonConverter.readValue(message, InvestSuccessMessage.class); Date nowDate = DateTime.now().toDate(); if(investSuccessMessage == null){ logger.error("[MQ] parse InvestSuccessMessage is error {}.", message); return; } if(investSuccessMessage.getInvestInfo() == null){ logger.error("[MQ] query invest by investId is not exists {}.", investSuccessMessage.getInvestInfo().getInvestId()); return; } logger.info("[MQ] ready to consume activity message: assigning coupon."); if ((activityChristmasStartTime.before(nowDate) && activityChristmasEndTime.after(nowDate)) && investSuccessMessage.getLoanDetailInfo().isActivity() && investSuccessMessage.getLoanDetailInfo().getActivityDesc().equals(LOAN_ACTIVITY_DESCRIPTION) && (!investSuccessMessage.getInvestInfo().getTransferStatus().equals("SUCCESS") && investSuccessMessage.getInvestInfo().getStatus().equals("SUCCESS")) && investSuccessMessage.getInvestInfo().getAmount() >= INVEST_LIMIT) { mqClient.sendMessage(MessageQueue.CouponAssigning, investSuccessMessage.getInvestInfo().getLoginName() + ":" + INTEREST_COUPON_OF_ZERO_5_PERCENT_COUPON_ID); } }

Target:
private void assignActivityChristmasInterestCoupon(String message) { InvestSuccessMessage investSuccessMessage = null; try { investSuccessMessage = JsonConverter.readValue(message, InvestSuccessMessage.class); } catch (IOException e) { throw new RuntimeException(e); } Date nowDate = DateTime.now().toDate(); logger.info("[MQ] ready to consume activity message: assigning coupon."); if ((activityChristmasStartTime.before(nowDate) && activityChristmasEndTime.after(nowDate)) && investSuccessMessage.getLoanDetailInfo().isActivity() && investSuccessMessage.getLoanDetailInfo().getActivityDesc().equals(LOAN_ACTIVITY_DESCRIPTION) && (!investSuccessMessage.getInvestInfo().getTransferStatus().equals("SUCCESS") && investSuccessMessage.getInvestInfo().getStatus().equals("SUCCESS")) && investSuccessMessage.getInvestInfo().getAmount() >= INVEST_LIMIT) { mqClient.sendMessage(MessageQueue.CouponAssigning, investSuccessMessage.getInvestInfo().getLoginName() + ":" + INTEREST_COUPON_OF_ZERO_5_PERCENT_COUPON_ID); } }
Source:
ListPopup inflatePopupMenu(ArrayAdapter<ListPopup.Item> adapter, Context context) { ListPopup menu = new ListPopup(context); menu.setAdapter(adapter); String favApps = PreferenceManager.getDefaultSharedPreferences(context). getString("favorite-apps-list", ""); if (favApps.contains(this.pojo.id + ";")) { for (int i = 0; i < adapter.getCount(); i += 1) { ListPopup.Item item = adapter.getItem(i); assert item != null; if (item.stringId == R.string.menu_favorites_add) adapter.remove(item); } } else { for (int i = 0; i < adapter.getCount(); i += 1) { ListPopup.Item item = adapter.getItem(i); assert item != null; if (item.stringId == R.string.menu_favorites_remove) adapter.remove(item); } } if (BuildConfig.DEBUG) { int relevance = pojo.relevance - 1; adapter.add(new ListPopup.Item(context, "Relevance: " + relevance)); } return menu; }

Target:
ListPopup inflatePopupMenu(ArrayAdapter<ListPopup.Item> adapter, Context context) { ListPopup menu = new ListPopup(context); menu.setAdapter(adapter); String favApps = PreferenceManager.getDefaultSharedPreferences(context). getString("favorite-apps-list", ""); if (favApps.contains(this.pojo.id + ";")) { for (int i = 0; i < adapter.getCount(); i += 1) { ListPopup.Item item = adapter.getItem(i); assert item != null; if (item.stringId == R.string.menu_favorites_add) adapter.remove(item); } } else { for (int i = 0; i < adapter.getCount(); i += 1) { ListPopup.Item item = adapter.getItem(i); assert item != null; if (item.stringId == R.string.menu_favorites_remove) adapter.remove(item); } } if (BuildConfig.DEBUG) { adapter.add(new ListPopup.Item("Relevance: " + pojo.relevance)); } return menu; }
Source:
public void null_if_unknown_symbol() throws Exception { ExpressionTree tree = firstExpression("void foo() { unknown(e -> e.method()); }"); ExpressionTree expression = ((MethodInvocationTree) tree).arguments().get(0); MethodInvocationTree methodInvocationTree = (MethodInvocationTree)((LambdaExpressionTree)expression).body(); ExpressionTree defaultValue = JavaPropertiesHelper.retrievedPropertyDefaultValue(methodInvocationTree); assertThat(defaultValue).isNull(); }

Target:
public void null_if_unknown_symbol() throws Exception { ExpressionTree tree = firstExpression("void foo() { unknown(e -> e.method()); }"); ExpressionTree functionCallArgument = ((MethodInvocationTree) tree).arguments().get(0); MethodInvocationTree methodCallInsideLambda = (MethodInvocationTree)((LambdaExpressionTree)functionCallArgument).body(); ExpressionTree defaultValue = JavaPropertiesHelper.retrievedPropertyDefaultValue(methodCallInsideLambda); assertThat(defaultValue).isNull(); }
Source:
private void encodeUtf8Component(CharSequence s) { for (int i = 0, len = s.length(); i < len; i++) { char c = s.charAt(i); if (!dontNeedEncoding(c)) { if (i > 0) { uriBuilder.append(s, 0, i); } encodeUtf8ComponentSlow(s, i); return; } } uriBuilder.append(s); }

Target:
private void encodeUtf8Component(CharSequence s) { for (int i = 0, len = s.length(); i < len; i++) { char c = s.charAt(i); if (!dontNeedEncoding(c)) { encodeUtf8Component(s, i, len); return; } } uriBuilder.append(s); }
Source:
public void testParseCorrectlyHandlesFileWithNoHeaders() throws IOException, InvalidFormatException, DataParserException { InputStream file = getFile("/TestFile.xlsx"); Workbook workbook = WorkbookFactory.create(file); WorkbookParserSettings settings = WorkbookParserSettings.builder() .withHeader(ExcelHeader.NO_HEADER) .build(); WorkbookParser parser = new WorkbookParser(settings, getContext(), workbook, "Sheet1::0"); Record firstContentRow = parser.parse(); LinkedHashMap<String, Field> contentMap = new LinkedHashMap<>(); for (int i = 0; i <= 4; i++) { contentMap.put(String.valueOf(i), Field.create("column" + (i + 1))); } Field expected = Field.createListMap(contentMap); assertEquals(expected, firstContentRow.get()); }

Target:
public void testParseCorrectlyHandlesFileWithNoHeaders() throws IOException, InvalidFormatException, DataParserException { Workbook workbook = createWorkbook("/excel/TestExcel.xlsx"); WorkbookParser parser = new WorkbookParser(settingsNoHeader, getContext(), workbook, "Sheet1::0"); Record firstContentRow = parser.parse(); LinkedHashMap<String, Field> contentMap = new LinkedHashMap<>(); for (int i = 0; i <= 4; i++) { contentMap.put(String.valueOf(i), Field.create("column" + (i + 1))); } Field expected = Field.createListMap(contentMap); assertEquals(expected, firstContentRow.get()); }
Source:
public AsyncJobStatus queueJob(JobBuilder builder) { if (builder == null) { throw new IllegalArgumentException("job builder is null"); } AsyncJobStatus job = this.buildJobStatus(builder); job.setState(JobState.QUEUED); job = this.jobCurator.create(job); try { JobMessage message = new JobMessage(job.getId(), job.getJobKey()); this.dispatcher.sendJobMessage(message); } catch (Exception e) { log.warn("Error sending async job message.", e); this.jobCurator.delete(job); throw new RuntimeException("Error sending async job message.", e); } return job; }

Target:
public AsyncJobStatus queueJob(JobBuilder builder) { if (builder == null) { throw new IllegalArgumentException("job builder is null"); } AsyncJobStatus job = this.buildJobStatus(builder); job.setState(JobState.CREATED); try { job = this.jobCurator.create(job); JobMessage message = new JobMessage(job.getId(), job.getJobKey()); this.dispatcher.sendJobMessage(message); job = job.setState(JobState.QUEUED); this.jobCurator.merge(job); } catch (Exception e) { log.warn("Error sending async job message.", e); if (job != null && job.getId() != null) { this.jobCurator.delete(job); } throw new RuntimeException("Error sending async job message.", e); } return job; }
Source:
public String getSystem(String streamId) { return getOrDefault(String.format(SYSTEM_FOR_STREAM_ID, streamId), new JobConfig(this).getDefaultSystem().orElse(null)); }

Target:
public String getSystem(String streamId) { String system = get(String.format(SYSTEM_FOR_STREAM_ID, streamId)); return (system != null) ? system : new JobConfig(this).getDefaultSystem().orElse(null); }
Source:
private boolean shutdownDevice() { List<String> simctlArgs; simctlArgs = Arrays.asList("xcrun", "simctl", "shutdown", deviceUUID); Command simctlCmd = new Command(simctlArgs, true); int exitCode = simctlCmd.executeAndWait(true); if (exitCode == 146) { log.info("This device shuts down already: " + deviceUUID); return true; } else if (exitCode == 0) { log.info("Successfully shut down the device: " + deviceUUID); return true; } log.warning("Failed to shut down the device: " + deviceUUID + ". Command was used: " + simctlCmd.commandString()); return false; }

Target:
private boolean shutdownDevice() { List<String> simctlArgs = Arrays.asList("xcrun", "simctl", "shutdown", deviceUUID); Command simctlCmd = new Command(simctlArgs, true); int exitCode = simctlCmd.executeAndWait(true); if (exitCode == 146) { log.info("This device shuts down already: " + deviceUUID); return true; } else if (exitCode == 0) { log.info("Successfully shut down the device: " + deviceUUID); return true; } log.warning("Failed to shut down the device: " + deviceUUID + ". Command was used: " + simctlCmd.commandString()); return false; }
Source:
public void contextDestroyed(ServletContextEvent event) { if (config.getBoolean(ACTIVEMQ_ENABLED)) { activeMQContextListener.contextDestroyed(); injector.getInstance(ActiveMQStatusMonitor.class).stop(); ActiveMQClient.clearThreadPools(); } pinsetterListener.contextDestroyed(); loggerListener.contextDestroyed(); if (config.getBoolean(ConfigProperties.AMQP_INTEGRATION_ENABLED)) { Util.closeSafely(injector.getInstance(AMQPBusPublisher.class), "AMQPBusPublisher"); } injector.getInstance(PersistService.class).stop(); super.contextDestroyed(event); Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); try { DriverManager.deregisterDriver(driver); } catch (SQLException e) { log.info(String.format("Failed to de-registering driver %s", driver), e); } } InternalThreadLocalMap.destroy(); try { Thread.sleep(1000L); } catch (Exception e) { } }

Target:
public void contextDestroyed(ServletContextEvent event) { super.contextDestroyed(event); try { this.destroySubsystems(); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ProfilingUtils.split("WPLaunchActivity.onCreate"); mMigrationProgressDialog = new ProgressDialog(this); mMigrationProgressDialog.setMessage(this.getResources().getString(R.string.migration_message)); mMigrationProgressDialog.setCancelable(false); mMigrationProgressDialog.show(); WordPress.registerMigrationListener(new WordPress.MigrationListener() { @Override public void onCompletion() { launchWPMainActivity(); } }); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ProfilingUtils.split("WPLaunchActivity.onCreate"); if (WordPress.sIsMigrationInProgress) { final ProgressDialog migrationProgressDialog = new ProgressDialog(this); migrationProgressDialog.setMessage(this.getResources().getString(R.string.migration_message)); migrationProgressDialog.setCancelable(false); migrationProgressDialog.show(); WordPress.registerMigrationListener(new WordPress.MigrationListener() { @Override public void onCompletion() { migrationProgressDialog.dismiss(); launchWPMainActivity(); } }); } else { launchWPMainActivity(); } }
Source:
public String toString() { StringBuilder result = new StringBuilder(); if (this.names.size() > 0) { for (int i=0; i<this.names.size(); i++){ PersonName personName = this.names.get(i); if (i==0){ result.append(personName.toString()); }else{ result.append("|" + personName.toString()); } } } return result.toString(); }

Target:
public String toString() { final StringBuilder result = new StringBuilder(); if (names.size() > 0) { for (int i = 0; i < names.size(); i++) { final PersonName personName = names.get(i); if (i == 0) { result.append(personName.toString()); } else { result.append("|"); result.append(personName.toString()); } } } return result.toString(); }
Source:
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_SORT); onCreate(db); }

Target:
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { onCreate(db); }
Source:
public Paragraph<PS, SEG, S> trim(int length) { if(length >= length()) { return this; } else { Position pos = navigator.offsetToPosition(length, Backward); int segIdx = pos.getMajor(); List<SEG> segs = new ArrayList<>(segIdx + 1); segs.addAll(segments.subList(0, segIdx)); segmentOps.subSequence(segments.get(segIdx), 0, pos.getMinor()) .ifPresent(seg -> segs.add(seg)); return new Paragraph<>(paragraphStyle, segmentOps, segs); } }

Target:
public Paragraph<PS, SEG, S> trim(int length) { if(length >= length()) { return this; } else { Position pos = navigator.offsetToPosition(length, Backward); int segIdx = pos.getMajor(); List<SEG> segs = new ArrayList<>(segIdx + 1); segs.addAll(segments.subList(0, segIdx)); segs.add(segmentOps.subSequence(segments.get(segIdx), 0, pos.getMinor())); if (segs.isEmpty()) { segs.add(segmentOps.createEmpty()); } return new Paragraph<>(paragraphStyle, segmentOps, segs); } }
Source:
public void testDeleteMember() { assertNotNull(nonSelfMember); boolean successful = api().delete(nonSelfMember.id()); assertTrue(successful); }

Target:
public void testDeleteMember() { boolean successful = api().delete(nonSelfMember.id()); assertTrue(successful); }
Source:
public Mono<byte[]> getBodyAsByteArray() { return cachedBody.next().map(byteBuffer -> byteBuffer.array()); }

Target:
public Mono<byte[]> getBodyAsByteArray() { return cachedBody.next().map(ByteBuffer::array); }
Source:
public void playAttackSound() { String sound = getEntitySound() + "_attack"; if (!sound.equals("generic_attack") && AWNPCSounds.isValidSound(sound)) { playSound(AWNPCSounds.getSoundEventFromString(sound), 1.0F, 1.2F / (rand.nextFloat() * 0.2F + 0.9F)); } }

Target:
private void playAttackSound() { if (attackSound != SoundEvents.ENTITY_GENERIC_HURT) { playSound(attackSound, 1.0F, 1.2F / (rand.nextFloat() * 0.2F + 0.9F)); } }
Source:
void handleBody(InputStream payload) throws IOException, MessageFormatException { if (!successfullyDeserialized) { BlobData blobData = MessageFormatRecord.deserializeBlob(payload); chunkIndexToBuffer.put(chunkIndex, ByteBuffer.wrap(Utils.readBytesFromStream(blobData.getStream(), (int) blobData.getSize()))); numChunksRetrieved++; successfullyDeserialized = true; } else { } }

Target:
void handleBody(InputStream payload) throws IOException, MessageFormatException { if (!successfullyDeserialized) { BlobData blobData = MessageFormatRecord.deserializeBlob(payload); chunkIndexToBuffer.put(chunkIndex, blobData.getStream().getByteBuffer()); numChunksRetrieved++; successfullyDeserialized = true; } else { } }
Source:
void attemptScheduling(FSSchedulerNode node) { try { writeLock.lock(); if (rmContext.isWorkPreservingRecoveryEnabled() && !rmContext .isSchedulerReadyForAllocatingContainers()) { return; } final NodeId nodeID = node.getNodeID(); if (!nodeTracker.exists(nodeID)) { LOG.info( "Skipping scheduling as the node " + nodeID + " has been removed"); return; } for (FSAppAttempt app : node.getPreemptionList()) { if (!app.isStopped()) { app.assignContainer(node); } } boolean validReservation = false; FSAppAttempt reservedAppSchedulable = node.getReservedAppSchedulable(); if (reservedAppSchedulable != null) { validReservation = reservedAppSchedulable.assignReservedContainer(node); } if (!validReservation) { int assignedContainers = 0; Resource assignedResource = Resources.clone(Resources.none()); Resource maxResourcesToAssign = Resources.multiply( node.getUnallocatedResource(), 0.5f); while (node.getReservedContainer() == null) { boolean assignedContainer = false; Resource assignment = queueMgr.getRootQueue().assignContainer(node); if (!assignment.equals(Resources.none())) { assignedContainers++; assignedContainer = true; Resources.addTo(assignedResource, assignment); } if (!assignedContainer) { break; } if (!shouldContinueAssigning(assignedContainers, maxResourcesToAssign, assignedResource)) { break; } } } updateRootQueueMetrics(); } finally { writeLock.unlock(); } }

Target:
void attemptScheduling(FSSchedulerNode node) { try { writeLock.lock(); if (rmContext.isWorkPreservingRecoveryEnabled() && !rmContext .isSchedulerReadyForAllocatingContainers()) { return; } final NodeId nodeID = node.getNodeID(); if (!nodeTracker.exists(nodeID)) { LOG.info( "Skipping scheduling as the node " + nodeID + " has been removed"); return; } assignPreemptedContainers(node); FSAppAttempt reservedAppSchedulable = node.getReservedAppSchedulable(); boolean validReservation = false; if (reservedAppSchedulable != null) { validReservation = reservedAppSchedulable.assignReservedContainer(node); } if (!validReservation) { int assignedContainers = 0; Resource assignedResource = Resources.clone(Resources.none()); Resource maxResourcesToAssign = Resources.multiply( node.getUnallocatedResource(), 0.5f); while (node.getReservedContainer() == null) { boolean assignedContainer = false; Resource assignment = queueMgr.getRootQueue().assignContainer(node); if (!assignment.equals(Resources.none())) { assignedContainers++; assignedContainer = true; Resources.addTo(assignedResource, assignment); } if (!assignedContainer) { break; } if (!shouldContinueAssigning(assignedContainers, maxResourcesToAssign, assignedResource)) { break; } } } updateRootQueueMetrics(); } finally { writeLock.unlock(); } }
Source:
private void shutdown() { if (saveJob != null) { saveJob.cancel(); } if (idleListener == null) { return; } if (display != null && !display.isDisposed()) { try { display.asyncExec(new Runnable() { @Override public void run() { display.timerExec(-1, runnable); display.removeFilter(SWT.KeyUp, idleListener); display.removeFilter(SWT.MouseUp, idleListener); } }); } catch (SWTException ex) { } } }

Target:
private void shutdown() { if (saveJob != null) { saveJob.cancel(); } if (idleListener == null) { return; } Display display = getWorkbenchDisplay(); if (display != null && !display.isDisposed()) { try { display.asyncExec(new Runnable() { @Override public void run() { display.removeFilter(SWT.KeyUp, idleListener); display.removeFilter(SWT.MouseUp, idleListener); } }); } catch (SWTException ex) { } } }
Source:
public static Program findProgram(String extension) { Program program = Program.findProgram(extension); if (program == null && isMediaFile(extension)) { Program[] programs = Program.getPrograms(); for (Program prog : programs) { if (prog.getName().equals("PhotoViewer.FileAssoc.Tiff")) { program = prog; break; } } } return program; }

Target:
public static Program findProgram(String extension) { Program program = Program.findProgram(extension); if (program == null && isMediaFile(extension.toLowerCase())) { Program[] programs = Program.getPrograms(); for (Program prog : programs) { if (prog.getName().equals("PhotoViewer.FileAssoc.Tiff")) { program = prog; break; } } } return program; }
Source:
public void setAngle(float angle) { while (angle < 0) { angle += 360; } while (angle >= 360) { angle -= 360; } this.angle = angle; }

Target:
public void setAngle(float angle) { this.angle = SolMath.norm(angle); }
Source:
private ExpressionInterpreter(Expression expression, Metadata metadata, Session session, Map<NodeRef<Expression>, Type> expressionTypes, boolean optimize) { this.expression = requireNonNull(expression, "expression is null"); this.metadata = requireNonNull(metadata, "metadata is null"); this.literalInterpreter = new LiteralInterpreter(metadata.getBlockEncodingSerde()); this.session = requireNonNull(session, "session is null").toConnectorSession(); this.expressionTypes = ImmutableMap.copyOf(requireNonNull(expressionTypes, "expressionTypes is null")); verify((expressionTypes.containsKey(NodeRef.of(expression)))); this.optimize = optimize; this.functionInvoker = new FunctionInvoker(metadata.getFunctionRegistry()); this.visitor = new Visitor(); }

Target:
private ExpressionInterpreter(Expression expression, Metadata metadata, Session session, Map<NodeRef<Expression>, Type> expressionTypes, boolean optimize) { this.expression = requireNonNull(expression, "expression is null"); this.metadata = requireNonNull(metadata, "metadata is null"); this.literalEncoder = new LiteralEncoder(metadata.getBlockEncodingSerde()); this.session = requireNonNull(session, "session is null").toConnectorSession(); this.expressionTypes = ImmutableMap.copyOf(requireNonNull(expressionTypes, "expressionTypes is null")); verify((expressionTypes.containsKey(NodeRef.of(expression)))); this.optimize = optimize; this.functionInvoker = new FunctionInvoker(metadata.getFunctionRegistry()); this.legacyRowFieldOrdinalAccess = isLegacyRowFieldOrdinalAccessEnabled(session); this.visitor = new Visitor(); }
Source:
public Set<Integer> getPorts() { return Optional.of(ImmutableSet.of(ports.get(getNodeType()))) .orElse(ImmutableSet.of()); }

Target:
public Set<Integer> getPorts() { return ImmutableSet.of(PORTS.get(getNodeType())); }
Source:
public void testNestedScatterGatherSequenceTest() { PollableChannel replyChannel = new QueueChannel(); this.scatterGatherInSubFlowChannel.send( MessageBuilder.withPayload("sequencetest") .setReplyChannel(replyChannel) .build()); Message<?> receive = replyChannel.receive(10000); assertThat(receive).isNotNull(); assertThat(receive.getPayload()).isEqualTo("sequencetest"); }

Target:
public void testNestedScatterGatherSequenceTest() { PollableChannel replyChannel = new QueueChannel(); this.scatterGatherInSubFlowChannel.send( MessageBuilder.withPayload("sequencetest") .setReplyChannel(replyChannel) .build()); Message<?> wiretapMessage1 = scatterGatherWireTapChannel.receive(10000); assertThat(wiretapMessage1).isNotNull(); MessageHeaders headers1 = wiretapMessage1.getHeaders(); Message<?> wiretapMessage2 = scatterGatherWireTapChannel.receive(10000); assertThat(wiretapMessage2).isNotNull() .extracting(Message::getHeaders) .isEqualToComparingOnlyGivenFields(headers1, IntegrationMessageHeaderAccessor.CORRELATION_ID, "gatherResultChannel", IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, IntegrationMessageHeaderAccessor.SEQUENCE_SIZE); Message<?> receive = replyChannel.receive(10000); assertThat(receive).isNotNull(); assertThat(receive.getPayload()).isEqualTo("sequencetest"); }
Source:
public List<SshPairImpl> get(String owner, String service) throws ServerException { requireNonNull(owner); requireNonNull(service); try { EntityManager manager = managerProvider.get(); List<SshPairImpl> resultList = manager.createQuery("SELECT pair " + "FROM SshKeyPair pair " + "WHERE pair.owner = :owner " + " AND pair.service = :service", SshPairImpl.class) .setParameter("owner", owner) .setParameter("service", service) .getResultList(); return resultList; } catch (RuntimeException e) { throw new ServerException(e.getLocalizedMessage(), e); } }

Target:
public List<SshPairImpl> get(String owner, String service) throws ServerException { requireNonNull(owner); requireNonNull(service); try { return managerProvider.get() .createQuery("SELECT pair " + "FROM SshKeyPair pair " + "WHERE pair.owner = :owner " + " AND pair.service = :service", SshPairImpl.class) .setParameter("owner", owner) .setParameter("service", service) .getResultList(); } catch (RuntimeException e) { throw new ServerException(e.getLocalizedMessage(), e); } }
Source:
private TaskFlowJob createJobWithSpelJobModelVariablesUnauthorizedType() throws UserException { TaskFlowJob job = new TaskFlowJob(); job.setVariables(ImmutableMap.of("var1", new JobVariable("var1", "value1", SPEL_LEFT + "T(Runtime).exec('hostname').waitFor() instanceof T(Integer)" + SPEL_RIGHT))); return job; }

Target:
private TaskFlowJob createJobWithSpelJobModelVariablesUnauthorizedType() throws UserException { TaskFlowJob job = new TaskFlowJob(); job.setVariables(ImmutableMap.of("var1", new JobVariable("var1", "value1", SPEL_LEFT + "T(java.lang.Runtime).getRuntime().exec('hostname').waitFor() instanceof T(Integer)" + SPEL_RIGHT))); return job; }
Source:
private String updateNginxHttpConfigScript(final String host) { final String hosts = String.format("%s.hosts.conf", host); return Joiner.on(";").join( String.format( "if [[ $(grep '%1$s' %2$s) != *%1$s* ]]", hosts, this.config ), String.format( "then sed -i.bak -r 's/http \\{/http \\{\\n include %s;/' %s", hosts, this.config ), String.format("rm %s.bak", this.config), "fi" ); }

Target:
private String updateNginxHttpConfigScript(final String host) { final String hosts = String.format("%s.hosts.conf", host); return Joiner.on(";").join( String.format( "if ! grep -q '%s' %s", hosts, this.config ), String.format( "then sed -i.bak -r 's/http \\{/http \\{\\n include %s;/' %s", hosts, this.config ), String.format("rm %s.bak", this.config), "fi" ); }
Source:
public void testDisappearedCacheWasNotFoundMessage() { SqlQuery<String, Person> qry = new SqlQuery<String, Person>(Person.class, JoinSqlTestHelper.JOIN_SQL).setArgs("Organization #0"); qry.setDistributedJoins(true); try { personCache.query(qry).getAll(); fail("No CacheException emitted."); } catch (CacheException e) { boolean exp = e.getMessage().contains("Cache not found on local node"); if (!exp) throw e; } }

Target:
public void testDisappearedCacheWasNotFoundMessage() { SqlQuery<String, Person> qry = new SqlQuery<String, Person>(Person.class, JoinSqlTestHelper.JOIN_SQL).setArgs("Organization #0"); qry.setDistributedJoins(true); try { personCache.query(qry).getAll(); fail("No CacheException emitted."); } catch (CacheException e) { boolean exp = e.getMessage().contains("Cache not found on local node (was concurrently destroyed?)"); if (!exp) throw e; } }
Source:
public Rotation getRotation() { switch (rot) { case 0: return Rotation.NONE; case 1: return Rotation.NONE; case 2: return Rotation.CLOCKWISE; case 3: return Rotation.CLOCKWISE; case 4: return Rotation.FLIPPED; case 5: return Rotation.FLIPPED; case 6: return Rotation.COUNTER_CLOCKWISE; case 7: return Rotation.COUNTER_CLOCKWISE; } return Rotation.NONE; }

Target:
public Rotation getRotation() { switch (rot) { case 0: case 1: return Rotation.NONE; case 2: case 3: return Rotation.CLOCKWISE; case 4: case 5: return Rotation.FLIPPED; case 6: case 7: return Rotation.COUNTER_CLOCKWISE; } return Rotation.NONE; }
Source:
protected ColumnInfo copy(boolean immutable) { return this; }

Target:
protected ColumnInfo copy(boolean immutable) { throw new UnsupportedOperationException("DynamicColumnIndices cannot be copied"); }
Source:
public void patchMultipleOperationsWithSuccess() throws Exception { context.turnOffAuthorisationSystem(); EPerson ePerson = EPersonBuilder.createEPerson(context) .withNameInMetadata("John", "Doe") .withEmail("Johndoe@fake-email.com") .withNetId("testId") .build(); String token = getAuthToken(admin.getEmail(), password); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation1 = new ReplaceOperation("/canLogin", "true"); ops.add(replaceOperation1); ReplaceOperation replaceOperation2 = new ReplaceOperation("/netid", "multitestId"); ops.add(replaceOperation2); ReplaceOperation replaceOperation3 = new ReplaceOperation("/certificate", "true"); ops.add(replaceOperation3); String patchBody = getPatchContent(ops); getClient(token).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.canLogIn", Matchers.is(true))) .andExpect(jsonPath("$.netid", Matchers.is("multitestId"))) .andExpect(jsonPath("$.requireCertificate", Matchers.is(true))); }

Target:
public void patchMultipleOperationsWithSuccess() throws Exception { context.turnOffAuthorisationSystem(); EPerson ePerson = EPersonBuilder.createEPerson(context) .withNameInMetadata("John", "Doe") .withEmail("Johndoe@fake-email.com") .withNetId("testId") .build(); String token = getAuthToken(admin.getEmail(), password); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation1 = new ReplaceOperation("/canLogin", true); ops.add(replaceOperation1); ReplaceOperation replaceOperation2 = new ReplaceOperation("/netid", "multitestId"); ops.add(replaceOperation2); ReplaceOperation replaceOperation3 = new ReplaceOperation("/certificate", true); ops.add(replaceOperation3); String patchBody = getPatchContent(ops); getClient(token).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.canLogIn", Matchers.is(true))) .andExpect(jsonPath("$.netid", Matchers.is("multitestId"))) .andExpect(jsonPath("$.requireCertificate", Matchers.is(true))); }
Source:
public CassandraIsolatedClassLoader() { super( new Versions.Version(FBUtilities.getReleaseVersionString(), Versions.getClassPath()).classpath); }

Target:
public CassandraIsolatedClassLoader() { super(AbstractCluster.CURRENT_VERSION.classpath); }
Source:
runTaskTest(Callable<Task<?>> callable) { try { Task<?> task = callable.call(); task.waitForCompletion(); if (task.isFaulted()) { Exception error = task.getError(); if (error instanceof RuntimeException) { throw (RuntimeException) error; } throw new RuntimeException(error); } else if (task.isCancelled()) { throw new RuntimeException(new CancellationException()); } } catch (Exception e) { throw new RuntimeException(e); } }

Target:
private void runTaskTest(Callable<Task<?>> callable) { try { Task<?> task = callable.call(); task.waitForCompletion(); if (task.isFaulted()) { Exception error = task.getError(); if (error instanceof RuntimeException) { throw (RuntimeException) error; } throw new RuntimeException(error); } else if (task.isCancelled()) { throw new RuntimeException(new CancellationException()); } } catch (Exception e) { throw new RuntimeException(e); } }
Source:
public void build() { final List<BaseColumn> expandedColumns = dtable.getExpandedColumns(); for (; sourceColumnIndex < expandedColumns.size(); sourceColumnIndex++) { final BaseColumn baseColumn = expandedColumns.get(sourceColumnIndex); if (baseColumn instanceof AttributeCol52) { makeAttribute((AttributeCol52) baseColumn); } else if (baseColumn instanceof MetadataCol52) { makeMetadata((MetadataCol52) baseColumn); } else if (baseColumn instanceof ConditionCol52) { makeCondition((ConditionCol52) baseColumn); } else if (baseColumn instanceof ActionCol52) { makeAction(baseColumn); } else if (baseColumn instanceof RowNumberCol52) { continue; } else if (baseColumn instanceof DescriptionCol52) { } else { throw new IllegalArgumentException("TODO REMOTE THIS"); } columnIndex++; } }

Target:
public void build() { final List<BaseColumn> expandedColumns = dtable.getExpandedColumns(); for (int sourceColumnIndex = 0; sourceColumnIndex < expandedColumns.size(); sourceColumnIndex++) { final BaseColumn baseColumn = expandedColumns.get(sourceColumnIndex); if (baseColumn instanceof AttributeCol52) { makeAttribute((AttributeCol52) baseColumn); } else if (baseColumn instanceof MetadataCol52) { makeMetadata((MetadataCol52) baseColumn); } else if (baseColumn instanceof ConditionCol52) { makeCondition((ConditionCol52) baseColumn); } else if (baseColumn instanceof ActionCol52) { makeAction(sourceColumnIndex, baseColumn); } else if (baseColumn instanceof RowNumberCol52) { continue; } else if (baseColumn instanceof DescriptionCol52) { } else { throw new IllegalArgumentException("TODO REMOTE THIS"); } targetColumnIndex++; } }
Source:
public ResponseEntity<ContentTypeDto> create( @Valid @RequestBody ContentTypeDtoRequest contentType, BindingResult bindingResult) throws URISyntaxException { validator.validate(contentType, bindingResult); if(bindingResult.hasErrors()) { throw new ValidationGenericException(bindingResult); } ContentTypeDto result = service.create(contentType, bindingResult); return ResponseEntity.created( new URI("/plugins/contentTypes/" + result.getCode())) .body(result); }

Target:
public ResponseEntity<SimpleRestResponse<ContentTypeDto>> create( @Valid @RequestBody ContentTypeDtoRequest contentType, BindingResult bindingResult) throws URISyntaxException { logger.debug("REST request - create content type: {}", contentType); validateCreate(contentType, bindingResult); ContentTypeDto result = service.create(contentType, bindingResult); return ResponseEntity.created( new URI("/plugins/contentTypes/" + result.getCode())) .body(new SimpleRestResponse<>(result)); }
Source:
public BinarySourceBuilder fromAsFile(String asFile) { this.asFile = asFile; return this; }

Target:
public IBinarySourceBuilder fromAsFile(String asFile) { this.asFile = asFile; return this; }
Source:
public Object create(SimpleObject propertiesToCreate, RequestContext context) throws ResponseException { DelegatingResourceHandler<? extends T> handler; if (hasTypesDefined()) { String type = (String) propertiesToCreate.remove(RestConstants.PROPERTY_FOR_TYPE); if (type == null) throw new IllegalArgumentException( "When creating a resource that supports subclasses, you must indicate the particular subclass with a " + RestConstants.PROPERTY_FOR_TYPE + " property"); handler = getResourceHandler(type); } else { handler = this; } T delegate = handler.newDelegate(); setConvertedProperties(delegate, propertiesToCreate, handler.getCreatableProperties(), true); try { ValidateUtil.validate(delegate); } catch (ValidationException ex) { context.getResponse().setStatus(HttpStatus.BAD_REQUEST.value()); return getValidationErrors(ex); } delegate = save(delegate); SimpleObject ret = (SimpleObject) ConversionUtil.convertToRepresentation(delegate, Representation.DEFAULT); if (hasTypesDefined()) { ret.add(RestConstants.PROPERTY_FOR_TYPE, getTypeName(delegate)); } return ret; }

Target:
public Object create(SimpleObject propertiesToCreate, RequestContext context) throws ResponseException { DelegatingResourceHandler<? extends T> handler; if (hasTypesDefined()) { String type = (String) propertiesToCreate.remove(RestConstants.PROPERTY_FOR_TYPE); if (type == null) throw new IllegalArgumentException( "When creating a resource that supports subclasses, you must indicate the particular subclass with a " + RestConstants.PROPERTY_FOR_TYPE + " property"); handler = getResourceHandler(type); } else { handler = this; } T delegate = handler.newDelegate(propertiesToCreate); setConvertedProperties(delegate, propertiesToCreate, handler.getCreatableProperties(), true); ValidateUtil.validate(delegate); delegate = save(delegate); SimpleObject ret = (SimpleObject) ConversionUtil.convertToRepresentation(delegate, Representation.DEFAULT); if (hasTypesDefined()) { ret.add(RestConstants.PROPERTY_FOR_TYPE, getTypeName(delegate)); } return ret; }
Source:
public void beforeDestroy(BeforeDestroyEvent event, EntityRef player, CharacterComponent characterComponent, AliveCharacterComponent aliveCharacterComponent) { if (player.hasComponent(PlayerCharacterComponent.class)) { event.consume(); String team = player.getComponent(LASTeamComponent.class).team; Prefab staffPrefab = assetManager.getAsset(LASUtils.MAGIC_STAFF_URI, Prefab.class).orElse(null); Vector3f startPosition = new Vector3f(player.getComponent(LocationComponent.class).getLocalPosition()); Vector3f impulse = Vector3f.zero(); int inventorySize = inventoryManager.getNumSlots(player); for (int slotNumber = 0; slotNumber <= inventorySize; slotNumber++) { EntityRef slot = inventoryManager.getItemInSlot(player, slotNumber); Prefab currentPrefab = slot.getParentPrefab(); if (currentPrefab != null && !currentPrefab.equals(staffPrefab)) { int count = inventoryManager.getStackSize(slot); player.send(new DropItemRequest(slot, player, impulse, startPosition, count)); } } player.send(new DoHealEvent(100000, player)); player.send(new CharacterTeleportEvent(LASUtils.getTeleportDestination(team))); } }

Target:
public void beforeDestroy(BeforeDestroyEvent event, EntityRef player, CharacterComponent characterComponent, AliveCharacterComponent aliveCharacterComponent) { if (player.hasComponent(PlayerCharacterComponent.class)) { event.consume(); String team = player.getComponent(LASTeamComponent.class).team; dropItemsFromInventory(player); player.send(new DoHealEvent(100000, player)); player.send(new CharacterTeleportEvent(LASUtils.getTeleportDestination(team))); } }
Source:
public void testUpdateTrackersAfterRedimineUpdate() throws RedmineException { List<Tracker> availableTrackers=mgr.getIssueManager().getTrackers(); assertTrue("a minumum of 3 trackers should be configured in redmine", availableTrackers.size()>=3); Project projectToCreate = generateRandomProject(); String createdProjectKey = null; try { projectToCreate.clearTrackers(); Project createdProject = projectManager.createProject(projectToCreate); createdProjectKey = createdProject.getIdentifier(); assertEquals(0, createdProject.getTrackers().size()); Collection<Tracker> trackers=new HashSet<Tracker>(Arrays.asList(availableTrackers.get(0))); createdProject.addTrackers(trackers); projectManager.update(createdProject); createdProject=projectManager.getProjectByKey(createdProjectKey); assertEquals(1, createdProject.getTrackers().size()); trackers=new HashSet<Tracker>(Arrays.asList(availableTrackers.get(1), availableTrackers.get(2))); createdProject.addTrackers(trackers); projectManager.update(createdProject); createdProject=projectManager.getProjectByKey(createdProjectKey); assertEquals(3, createdProject.getTrackers().size()); createdProject.clearTrackers(); projectManager.update(createdProject); createdProject=projectManager.getProjectByKey(createdProjectKey); assertEquals(0, createdProject.getTrackers().size()); } finally { if (createdProjectKey != null) { projectManager.deleteProject(createdProjectKey); } } }

Target:
public void testUpdateTrackersAfterRedimineUpdate() throws RedmineException { List<Tracker> availableTrackers=mgr.getIssueManager().getTrackers(); assertTrue("a minumum of 3 trackers should be configured in redmine", availableTrackers.size()>=3); Project projectToCreate = generateRandomProject(); String createdProjectKey = null; try { Project createdProject = projectToCreate.clearTrackers().create(); createdProjectKey = createdProject.getIdentifier(); assertEquals(0, createdProject.getTrackers().size()); Collection<Tracker> trackersToSet=new HashSet<Tracker>(Arrays.asList(availableTrackers.get(0))); createdProject.addTrackers(trackersToSet).update(); createdProject=projectManager.getProjectByKey(createdProjectKey); assertEquals(1, createdProject.getTrackers().size()); Collection<Tracker> trackersToAdd=new HashSet<Tracker>(Arrays.asList(availableTrackers.get(1), availableTrackers.get(2))); createdProject.addTrackers(trackersToAdd).update(); createdProject=projectManager.getProjectByKey(createdProjectKey); assertEquals(3, createdProject.getTrackers().size()); createdProject.clearTrackers().update(); createdProject=projectManager.getProjectByKey(createdProjectKey); assertEquals(0, createdProject.getTrackers().size()); } finally { if (createdProjectKey != null) { projectManager.getProjectByKey(createdProjectKey).delete(); } } }
Source:
public void setEvent(final String name, final String value) { if (!TextUtils.isEmpty(name)) { mEventList.add(Pair.create(name, value)); } }

Target:
public void setEvent(final String name, final String value) { if (TextUtils.isEmpty(name)) { throw new IllegalArgumentException("Telemetry setEvent on null name"); } if (value == null) { return; } mEventList.add(Pair.create(name, value)); }
Source:
@NonNull public String dateTime() { if (dateTimeOriginal == null || dateTimeOriginal.value() == null) { return ""; } return dateTimeOriginal.value(); }

Target:
@NonNull public String dateTime() { return StringUtils.defaultString(dateTimeOriginal == null ? null : dateTimeOriginal.value()); }