auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Instance getWorkingInstance(String zone, String name, String flavorId, int size) { InstanceApi instanceApi = api.getInstanceApiForZone(zone); for (int retries = 0; retries < 10; retries++) { Instance instance = null; try { instance = instanceApi.create(flavorId, size, name); } catch (Exception e) { try { Thread.sleep(50); } catch (InterruptedException ie) { } logger.error(e.getStackTrace().toString()); continue; } Instance updatedInstance = awaitAvailable(instance, instanceApi); if (updatedInstance == null) { instanceApi.delete(instance.getId()); InstancePredicates.awaitDeleted(instanceApi).apply(instance); continue; } return updatedInstance; } return null; }

Target:
public Instance getWorkingInstance(String zone, String name, String flavorId, int size) { InstanceApi instanceApi = api.getInstanceApiForZone(zone); for (int retries = 0; retries < 10; retries++) { Instance instance = null; try { instance = instanceApi.create(flavorId, size, name); } catch (Exception e) { Uninterruptibles.sleepUninterruptibly(15, TimeUnit.SECONDS); logger.error(e.getStackTrace().toString()); continue; } Instance updatedInstance = awaitAvailable(instance, instanceApi); if (updatedInstance != null) { return updatedInstance; } instanceApi.delete(instance.getId()); InstancePredicates.awaitDeleted(instanceApi).apply(instance); } return null; }
Source:
public List<BitmexMarginAccount> getBitmexMarginAccountsStatus() throws IOException { try { return bitmex.getMarginAccountsStatus(apiKey, exchange.getNonceFactory(), signatureCreator); } catch (BitmexException e) { throw new ExchangeException(e); } }

Target:
public List<BitmexMarginAccount> getBitmexMarginAccountsStatus() throws IOException { try { return bitmex.getMarginAccountsStatus(apiKey, exchange.getNonceFactory(), signatureCreator); } catch (BitmexException e) { throw handleError(e); } }
Source:
protected ProjectState( final ProjectCache projectCache, final AllProjectsName allProjectsName, final ProjectControl.AssistedFactory projectControlFactory, final PrologEnvironment.Factory envFactory, final GitRepositoryManager gitMgr, final RulesCache rulesCache, @Assisted final ProjectConfig config) { this.projectCache = projectCache; this.isAllProjects = config.getProject().getNameKey().equals(allProjectsName); this.allProjectsName = allProjectsName; this.projectControlFactory = projectControlFactory; this.envFactory = envFactory; this.gitMgr = gitMgr; this.rulesCache = rulesCache; this.config = config; this.capabilities = isAllProjects ? new CapabilityCollection(config.getProject().getNameKey(), config.getAccessSection(AccessSection.GLOBAL_CAPABILITIES)) : null; if (isAllProjects && !Permission.canBeOnAllProjects(AccessSection.ALL, Permission.OWNER)) { localOwners = Collections.emptySet(); } else { HashSet<AccountGroup.UUID> groups = new HashSet<AccountGroup.UUID>(); AccessSection all = config.getAccessSection(AccessSection.ALL); if (all != null) { Permission owner = all.getPermission(Permission.OWNER); if (owner != null) { for (PermissionRule rule : owner.getRules()) { GroupReference ref = rule.getGroup(); if (ref.getUUID() != null) { groups.add(ref.getUUID()); } } } } localOwners = Collections.unmodifiableSet(groups); } }

Target:
protected ProjectState( final ProjectCache projectCache, final AllProjectsName allProjectsName, final ProjectControl.AssistedFactory projectControlFactory, final PrologEnvironment.Factory envFactory, final GitRepositoryManager gitMgr, final RulesCache rulesCache, @Assisted final ProjectConfig config) { this.projectCache = projectCache; this.isAllProjects = config.getProject().getNameKey().equals(allProjectsName); this.allProjectsName = allProjectsName; this.projectControlFactory = projectControlFactory; this.envFactory = envFactory; this.gitMgr = gitMgr; this.rulesCache = rulesCache; this.config = config; this.capabilities = isAllProjects ? new CapabilityCollection(config.getAccessSection(AccessSection.GLOBAL_CAPABILITIES)) : null; if (isAllProjects && !Permission.canBeOnAllProjects(AccessSection.ALL, Permission.OWNER)) { localOwners = Collections.emptySet(); } else { HashSet<AccountGroup.UUID> groups = new HashSet<AccountGroup.UUID>(); AccessSection all = config.getAccessSection(AccessSection.ALL); if (all != null) { Permission owner = all.getPermission(Permission.OWNER); if (owner != null) { for (PermissionRule rule : owner.getRules()) { GroupReference ref = rule.getGroup(); if (ref.getUUID() != null) { groups.add(ref.getUUID()); } } } } localOwners = Collections.unmodifiableSet(groups); } }
Source:
public StormJaasCreator() { URL templateFileUrl = getClass().getClassLoader().getResource(STORM_JAAS_CONFIG_TEMPLATE); if (templateFileUrl == null) { throw new RuntimeException("Unable to read JAAS template file for Storm."); } try { stormJaasConfigTemplate = FileUtils.readFileToString(new File(templateFileUrl.toURI()), Charset.defaultCharset()); } catch (IOException | URISyntaxException e) { throw new RuntimeException("Unable to read JAAS template file for Storm."); } Configuration configuration = Configuration.getConfiguration(); AppConfigurationEntry[] streamlineConfigurations = configuration.getAppConfigurationEntry("StreamlineServer"); if (streamlineConfigurations == null || streamlineConfigurations.length == 0) { throw new RuntimeException("Streamline is not initialized with JAAS config. Unable to create JAAS for Storm."); } AppConfigurationEntry streamlineConf = streamlineConfigurations[0]; Map<String, ?> options = streamlineConf.getOptions(); keyTabPath = (String) options.get("keyTab"); streamlinePrincipal = (String) options.get("principal"); }

Target:
public StormJaasCreator() { URL templateFileUrl = getClass().getClassLoader().getResource(STORM_JAAS_CONFIG_TEMPLATE); if (templateFileUrl == null) { throw new RuntimeException("Unable to read JAAS template file for Storm."); } try { stormJaasConfigTemplate = FileUtils.readFileToString(new File(templateFileUrl.toURI()), Charset.defaultCharset()); } catch (IOException | URISyntaxException e) { throw new RuntimeException("Unable to read JAAS template file for Storm."); } Configuration configuration = Configuration.getConfiguration(); AppConfigurationEntry[] streamlineConfigurations = configuration.getAppConfigurationEntry(Constants.JAAS_STREAMLINE_APP_CONFIG_ENTRY_NAME); if (streamlineConfigurations == null || streamlineConfigurations.length == 0) { throw new RuntimeException("Streamline is not initialized with JAAS config. Unable to create JAAS for Storm."); } AppConfigurationEntry streamlineConf = streamlineConfigurations[0]; Map<String, ?> options = streamlineConf.getOptions(); keyTabPath = (String) options.get("keyTab"); streamlinePrincipal = (String) options.get("principal"); }
Source:
public Response doExport(Action action) { validateParameters(action, "storageDomain.id|name"); try { ExportRepoImageParameters exportParameters = DiskHelper.getExportRepoImageParameters(get(), getStorageDomainId(action)); return doAction(VdcActionType.ExportRepoImage, exportParameters, action); } catch (Exception e) { return handleError(e, action); } }

Target:
public Response doExport(Action action) { validateParameters(action, "storageDomain.id|name"); Disk disk = get(); Guid sourceStorageDomainId = new Guid(disk.getStorageDomains().getStorageDomains().get(0).getId()); Guid sourceStoragePoolId = StorageDomainHelper.getStoragePoolIdForDomain(this, sourceStorageDomainId); ExportRepoImageParameters exportParameters = new ExportRepoImageParameters(new Guid(disk.getImageId())); exportParameters.setStoragePoolId(sourceStoragePoolId); exportParameters.setStorageDomainId(sourceStorageDomainId); exportParameters.setImageGroupID(new Guid(disk.getId())); exportParameters.setDestinationDomainId(getStorageDomainId(action)); return doAction(VdcActionType.ExportRepoImage, exportParameters, action); }
Source:
protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { if (file.isScratchFile()) return; GoPackageClause packageClause = file.getPackage(); if (packageClause != null) { String packageName = file.getPackageName(); if (packageName == null || packageName.equals(GoConstants.DOCUMENTATION)) return; PsiDirectory dir = file.getContainingDirectory(); Collection<String> packages = GoUtil.getAllPackagesInDirectory(dir, true); packages.remove(GoConstants.DOCUMENTATION); if (packages.size() > 1) { Collection<LocalQuickFix> fixes = ContainerUtil.newArrayList(); if (problemsHolder.isOnTheFly()) { fixes.add(new GoMultiplePackagesQuickFix(packageClause, packageName, packages, true)); } else { for (String name : packages) { fixes.add(new GoMultiplePackagesQuickFix(packageClause, name, packages, false)); } } problemsHolder.registerProblem(packageClause, "Multiple packages in directory", fixes.toArray(new LocalQuickFix[fixes.size()])); } } }

Target:
protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { if (((ScratchFileType)ScratchFileType.INSTANCE).isMyFileType(file.getVirtualFile())) return; GoPackageClause packageClause = file.getPackage(); if (packageClause != null) { String packageName = file.getPackageName(); if (packageName == null || packageName.equals(GoConstants.DOCUMENTATION)) return; PsiDirectory dir = file.getContainingDirectory(); Collection<String> packages = GoUtil.getAllPackagesInDirectory(dir, true); packages.remove(GoConstants.DOCUMENTATION); if (packages.size() > 1) { Collection<LocalQuickFix> fixes = ContainerUtil.newArrayList(); if (problemsHolder.isOnTheFly()) { fixes.add(new GoMultiplePackagesQuickFix(packageClause, packageName, packages, true)); } else { for (String name : packages) { fixes.add(new GoMultiplePackagesQuickFix(packageClause, name, packages, false)); } } problemsHolder.registerProblem(packageClause, "Multiple packages in directory", fixes.toArray(new LocalQuickFix[fixes.size()])); } } }
Source:
private void removeIncompatibleSeries(IChartTypeDefinition type) { Iterator<ChartSeries> iterator = fSeries.iterator(); while (iterator.hasNext()) { ChartSeriesDialog series = (ChartSeriesDialog) checkNotNull(iterator.next()); if (!type.checkIfXDescriptorValid(series.getX(), null) || !type.checkIfYDescriptorValid(series.getY(), null)) { Button button = series.getButton(); if (button != null) { button.dispose(); } iterator.remove(); } } }

Target:
private void removeIncompatibleSeries(IChartTypeDefinition type) { Iterator<ChartSeries> iterator = fSelectedSeries.iterator(); while (iterator.hasNext()) { ChartSeriesDialog series = (ChartSeriesDialog) iterator.next(); if (!type.checkIfXDescriptorValid(series.getX(), null) || !type.checkIfYDescriptorValid(series.getY(), null)) { series.dispose(); iterator.remove(); } } }
Source:
protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec ) { measureChildren( widthMeasureSpec, heightMeasureSpec ); for( int i = 0; i < getChildCount(); i++ ) { View child = getChildAt( i ); if( child.getVisibility() != GONE ) { MarkerLayout.LayoutParams layoutParams = (MarkerLayout.LayoutParams) child.getLayoutParams(); int actualWidth = child.getMeasuredWidth(); int actualHeight = child.getMeasuredHeight(); float widthMultiplier = (layoutParams.anchorX == null) ? mAnchorX : layoutParams.anchorX; float heightMultiplier = (layoutParams.anchorY == null) ? mAnchorY : layoutParams.anchorY; float widthOffset = actualWidth * widthMultiplier; float heightOffset = actualHeight * heightMultiplier; switch (layoutParams.typeAnchorX) { case POS_ABSOLUTE_LEFT_TOP: widthOffset = widthMultiplier; break; case POS_ABSOLUTE_RIGHT_BOTTOM: widthOffset = widthMultiplier - actualWidth; break; } switch (layoutParams.typeAnchorY) { case POS_ABSOLUTE_LEFT_TOP: heightOffset = heightMultiplier; break; case POS_ABSOLUTE_RIGHT_BOTTOM: heightOffset = heightMultiplier - actualHeight; break; } int scaledX = FloatMathHelper.scale( layoutParams.x, mScale ); int scaledY = FloatMathHelper.scale( layoutParams.y, mScale ); layoutParams.mLeft = (int) (scaledX + widthOffset); layoutParams.mTop = (int) (scaledY + heightOffset); layoutParams.mRight = layoutParams.mLeft + actualWidth; layoutParams.mBottom = layoutParams.mTop + actualHeight; } } int availableWidth = MeasureSpec.getSize( widthMeasureSpec ); int availableHeight = MeasureSpec.getSize( heightMeasureSpec ); setMeasuredDimension( availableWidth, availableHeight ); }

Target:
protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec ) { measureChildren( widthMeasureSpec, heightMeasureSpec ); for( int i = 0; i < getChildCount(); i++ ) { View child = getChildAt( i ); if( child.getVisibility() != GONE ) { MarkerLayout.LayoutParams layoutParams = (MarkerLayout.LayoutParams) child.getLayoutParams(); int actualWidth = child.getMeasuredWidth(); int actualHeight = child.getMeasuredHeight(); float widthMultiplier = (layoutParams.anchorX == null) ? mAnchorX : layoutParams.anchorX; float heightMultiplier = (layoutParams.anchorY == null) ? mAnchorY : layoutParams.anchorY; float widthOffset = actualWidth * widthMultiplier + layoutParams.absoluteAnchorX; float heightOffset = actualHeight * heightMultiplier + layoutParams.absoluteAnchorY; int scaledX = FloatMathHelper.scale( layoutParams.x, mScale ); int scaledY = FloatMathHelper.scale( layoutParams.y, mScale ); layoutParams.mLeft = (int) (scaledX + widthOffset); layoutParams.mTop = (int) (scaledY + heightOffset); layoutParams.mRight = layoutParams.mLeft + actualWidth; layoutParams.mBottom = layoutParams.mTop + actualHeight; } } int availableWidth = MeasureSpec.getSize( widthMeasureSpec ); int availableHeight = MeasureSpec.getSize( heightMeasureSpec ); setMeasuredDimension( availableWidth, availableHeight ); }
Source:
public static void main(String[] args){ String networkAddress = NetworkController.LOCALHOST; if (args.length > 0){ networkAddress = args[0]; } new Spectator(networkAddress, new TextView()); }

Target:
public static void main(String[] args){ String networkAddress = NetworkController.LOCALHOST; if (args.length == 1){ networkAddress = args[0]; } else { System.out.println("Usage: [<server-ip-address>]"); return; } new Spectator(networkAddress, new TextView()); }
Source:
public PageControlSettingsUIBean() { try { String maxItemsPerPage = System.getProperty(MAX_ITEMS_PER_PAGE); if (maxItemsPerPage != null && Integer.parseInt(maxItemsPerPage) > 45) { pageSizes = new SelectItem[] { new SelectItem("15", "15"), new SelectItem("30", "30"), new SelectItem("45", "45"), new SelectItem(maxItemsPerPage, maxItemsPerPage) }; } } catch (NumberFormatException nfe) { } if (pageSizes == null) { pageSizes = new SelectItem[]{new SelectItem("15", "15"), new SelectItem("30", "30"), new SelectItem("45", "45")}; } }

Target:
public PageControlSettingsUIBean() { try { String maxItemsPerPage = System.getProperty(MAX_ITEMS_PER_PAGE); int maxItemsPerPageInt; if (maxItemsPerPage != null && (maxItemsPerPageInt = Integer.parseInt(maxItemsPerPage)) >= 45) { String tier0 = String.valueOf(Math.max(15, (int) (maxItemsPerPageInt * 0.25))); String tier1 = String.valueOf(Math.max(30, (int) (maxItemsPerPageInt * 0.50))); String tier2 = String.valueOf(Math.max(45, (int) (maxItemsPerPageInt * 0.75))); pageSizes = new SelectItem[] { new SelectItem(tier0, tier0), new SelectItem(tier1, tier1), new SelectItem(tier2, tier2), new SelectItem(maxItemsPerPage, maxItemsPerPage) }; } } catch (NumberFormatException nfe) { } if (pageSizes == null) { pageSizes = new SelectItem[]{new SelectItem("15", "15"), new SelectItem("30", "30"), new SelectItem("45", "45")}; } }
Source:
public AttributeAxisIterator(ElementNode startNodeInfo) { this.startNodeInfo = startNodeInfo; this.iterator = startNodeInfo.node instanceof net.sourceforge.pmd.lang.ast.xpath.AttributeNode ? ((net.sourceforge.pmd.lang.ast.xpath.AttributeNode) startNodeInfo.node).getAttributeIterator() : new net.sourceforge.pmd.lang.ast.xpath.AttributeAxisIterator(startNodeInfo.node); }

Target:
public AttributeAxisIterator(ElementNode startNodeInfo) { this.startNodeInfo = startNodeInfo; this.iterator = startNodeInfo.node.getXPathAttributesIterator(); }
Source:
private void isValidEmail(CharSequence email) { isValidEmail( email, "Expected a valid email for %1$s." ); }

Target:
private void isValidEmail(CharSequence email) { isValidEmail( email, "Expected %1$s to be a valid email." ); }
Source:
public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog alertDialog = (AlertDialog) super.onCreateDialog(savedInstanceState); RoboGuice.injectMembers(getContext(), this); et = new TextInputEditText(getContext()); til = new TextInputLayout(getContext()); til.addView(et); til.setHint(getContext().getString(R.string.email)); int paddingWidth = Math.round(getResources().getDimension(R.dimen.alert_dialog_padding_width)); int paddingHeight = Math.round(getResources().getDimension(R.dimen.alert_dialog_padding_height)); til.setPadding(paddingWidth, paddingHeight, paddingWidth, paddingHeight); alertDialog.setView(til); String email = getArguments().getString(EXTRA_LOGIN_EMAIL); if (email != null && !email.isEmpty()) { et.setText(email); } return alertDialog; }

Target:
public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog alertDialog = (AlertDialog) super.onCreateDialog(savedInstanceState); editText = new TextInputEditText(getContext()); textInputLayout = new TextInputLayout(getContext()); textInputLayout.addView(editText); textInputLayout.setHint(getContext().getString(R.string.email)); int paddingWidth = Math.round(getResources().getDimension(R.dimen.alert_dialog_padding_width)); int paddingHeight = Math.round(getResources().getDimension(R.dimen.alert_dialog_padding_height)); textInputLayout.setPadding(paddingWidth, paddingHeight, paddingWidth, paddingHeight); alertDialog.setView(textInputLayout); editText.setText(getArguments().getString(EXTRA_LOGIN_EMAIL)); return alertDialog; }
Source:
public Object transform(Object o) throws SQLException { if (o == null) { return null; } if (!(o instanceof java.math.BigDecimal)) { throw new UnsupportedOperationException(this.getClass().getSimpleName() + " cannot transform objects of type " + o.getClass().getName()); } java.math.BigDecimal bd = new java.math.BigDecimal(((java.math.BigDecimal) o).toString()); return bd; }

Target:
public Object transform(Object o) { if (o == null) { return null; } if (!(o instanceof java.math.BigDecimal)) { throw new UnsupportedOperationException(this.getClass().getSimpleName() + " cannot transform objects of type " + o.getClass().getName()); } return new java.math.BigDecimal(((java.math.BigDecimal) o).toString()); }
Source:
public BulkServiceImpl(BulkServiceDescriptor descriptor) { this.descriptor = descriptor; kvStore = Framework.getService(KeyValueService.class).getKeyValueStore(descriptor.kvStore); logManager = Framework.getService(StreamService.class).getLogManager(descriptor.logConfig); }

Target:
public BulkServiceImpl(BulkServiceDescriptor descriptor) { this.descriptor = descriptor; }
Source:
public I18nEmailMgtConfigServiceClient(String url, ConfigurationContext configContext) throws Exception { try { stub = new I18NEmailMgtConfigServiceStub(configContext, url + "I18nEmailMgtConfigService"); } catch (java.lang.Exception e) { handleException(e.getMessage(), e); } }

Target:
public I18nEmailMgtConfigServiceClient(String url, ConfigurationContext configContext) throws Exception { try { stub = new I18NEmailMgtConfigServiceStub(configContext, url + "I18nEmailMgtConfigService"); } catch (Exception e) { handleException(e.getMessage(), e); } }
Source:
private void endTurn(GameBean game) throws GameException { boolean shouldUpdateNextMove = true; if (game.getStage().equals(GameStage.PREPARATION)) { Integer previousPreparationCycle = game.getPreparationCycle(); preparationStageUtil.updateGameStageToMain(game); preparationStageUtil.updateCurrentCycleInitialBuildingNumber(game); preparationStageUtil.updatePreparationCycle(game); Integer newPreparationCycle = game.getPreparationCycle(); boolean preparationFinished = newPreparationCycle == null && !game.getCurrentMove().equals(1); shouldUpdateNextMove = (preparationFinished || previousPreparationCycle.equals(newPreparationCycle)); } else { game.setDiceThrown(false); } if (shouldUpdateNextMove) { playUtil.updateNextMove(game); } }

Target:
private void endTurn(GameBean game) throws GameException { switch (game.getStage()) { case PREPARATION: Integer previousPreparationCycle = game.getPreparationCycle(); preparationStageUtil.updateGameStageToMain(game); preparationStageUtil.updateCurrentCycleInitialBuildingNumber(game); preparationStageUtil.updatePreparationCycle(game); if (game.getPreparationCycle() == null || previousPreparationCycle.equals(game.getPreparationCycle())) { preparationStageUtil.updateNextMove(game); } break; case MAIN: mainStageUtil.resetDices(game); mainStageUtil.updateNextMove(game); break; } }
Source:
private static boolean isPresent() { try { Class.forName("com.chikli.hudson.plugin.naginator.NaginatorScheduleAction"); return true; } catch (Throwable ex) { return false; } }

Target:
private static boolean isPresent() { try { Class.forName("com.chikli.hudson.plugin.naginator.NaginatorScheduleAction"); return true; } catch (ClassNotFoundException ex) { log.log(Level.FINEST, "Naginator not available. ", ex); return false; } }
Source:
public boolean hasTier(String tier) { MinMaxPriorityQueue<ServerHolder> servers = historicals.get(tier); return (servers != null) && !servers.isEmpty(); }

Target:
public boolean hasTier(String tier) { NavigableSet<ServerHolder> servers = historicals.get(tier); return (servers != null) && !servers.isEmpty(); }
Source:
public boolean isLicenseCC() { if (!(TextUtils.isEmpty(license) && TextUtils.isEmpty(licenseShortName))) { if (license.startsWith("cc") || licenseShortName.toLowerCase().startsWith("cc")) { return true; } } return false; }

Target:
public boolean isLicenseCC() { return StringUtil.emptyIfNull(license).toLowerCase().startsWith(CREATIVE_COMMONS_PREFIX) || StringUtil.emptyIfNull(licenseShortName).toLowerCase().startsWith(CREATIVE_COMMONS_PREFIX); }
Source:
public boolean extractQuestionDetails( Map<String, String[]> requestParameters, FeedbackQuestionType questionType) { int numOfMsqChoices = 0; List<String> msqChoices = new LinkedList<String>(); boolean msqOtherEnabled = false; if (HttpRequestHelper.getValueFromParamMap(requestParameters, Const.ParamsNames.FEEDBACK_QUESTION_MSQOTHEROPTIONFLAG) != null && HttpRequestHelper.getValueFromParamMap(requestParameters, Const.ParamsNames.FEEDBACK_QUESTION_MSQOTHEROPTIONFLAG).equals("on")) { msqOtherEnabled = true; } String generatedMsqOptions = HttpRequestHelper.getValueFromParamMap(requestParameters, Const.ParamsNames.FEEDBACK_QUESTION_GENERATEDOPTIONS); if (generatedMsqOptions.equals(FeedbackParticipantType.NONE.toString())) { String numMsqChoicesCreatedString = HttpRequestHelper.getValueFromParamMap(requestParameters, Const.ParamsNames.FEEDBACK_QUESTION_NUMBEROFCHOICECREATED); Assumption.assertNotNull("Null number of choice for MSQ", numMsqChoicesCreatedString); int numMsqChoicesCreated = Integer.parseInt(numMsqChoicesCreatedString); for(int i = 0; i < numMsqChoicesCreated; i++) { String msqChoice = HttpRequestHelper.getValueFromParamMap(requestParameters, Const.ParamsNames.FEEDBACK_QUESTION_MSQCHOICE + "-" + i); if(msqChoice != null && !msqChoice.trim().isEmpty()) { msqChoices.add(msqChoice); numOfMsqChoices++; } } this.setMsqQuestionDetails(numOfMsqChoices, msqChoices, msqOtherEnabled); } else { this.setMsqQuestionDetails(FeedbackParticipantType.valueOf(generatedMsqOptions)); } return true; }

Target:
public boolean extractQuestionDetails( Map<String, String[]> requestParameters, FeedbackQuestionType questionType) { int numOfMsqChoices = 0; List<String> msqChoices = new LinkedList<String>(); boolean msqOtherEnabled = false; String otherOptionFlag = HttpRequestHelper.getValueFromParamMap(requestParameters, Const.ParamsNames.FEEDBACK_QUESTION_MSQOTHEROPTIONFLAG); if (otherOptionFlag != null && otherOptionFlag.equals("on")) { msqOtherEnabled = true; } String generatedMsqOptions = HttpRequestHelper.getValueFromParamMap(requestParameters, Const.ParamsNames.FEEDBACK_QUESTION_GENERATEDOPTIONS); if (generatedMsqOptions.equals(FeedbackParticipantType.NONE.toString())) { String numMsqChoicesCreatedString = HttpRequestHelper.getValueFromParamMap(requestParameters, Const.ParamsNames.FEEDBACK_QUESTION_NUMBEROFCHOICECREATED); Assumption.assertNotNull("Null number of choice for MSQ", numMsqChoicesCreatedString); int numMsqChoicesCreated = Integer.parseInt(numMsqChoicesCreatedString); for(int i = 0; i < numMsqChoicesCreated; i++) { String msqChoice = HttpRequestHelper.getValueFromParamMap(requestParameters, Const.ParamsNames.FEEDBACK_QUESTION_MSQCHOICE + "-" + i); if(msqChoice != null && !msqChoice.trim().isEmpty()) { msqChoices.add(msqChoice); numOfMsqChoices++; } } this.setMsqQuestionDetails(numOfMsqChoices, msqChoices, msqOtherEnabled); } else { this.setMsqQuestionDetails(FeedbackParticipantType.valueOf(generatedMsqOptions)); } return true; }
Source:
public V put(K key, V value) { V previousValue = super.put(key, logIfNull(value)); if (previousValue != null) { if (log.isWarnEnabled()) { log.warn("Detected duplicate map keys which are not allowed by Conjure", new IllegalArgumentException()); } assert false : "Duplicate values for the same key are not allowed by Conjure. Key '" + key + "' values ['" + value + "', '" + previousValue + "']"; } return previousValue; }

Target:
public V put(K key, V value) { V previousValue = super.put(key, logIfNull(value)); if (previousValue != null) { onDuplicateKey(key, previousValue, value); } return previousValue; }
Source:
private ValidationResult validateRangePart(String rangePart) { rangePart.toLowerCase(); boolean matches = MAC_ADDRESS_PATTERN.matcher(rangePart).matches(); if (!matches) { return new ValidationResult(false, "The range start/end is an invalid MAC address. " + rangePart + " should be in a format of AA:AA:AA:AA:AA:AA"); } else { return new ValidationResult(true); } }

Target:
private ValidationResult validateRangePart(String rangePart) { boolean matches = MAC_ADDRESS_PATTERN.matcher(rangePart).matches(); if (!matches) { return new ValidationResult(false, "The range start/end is an invalid MAC address. " + rangePart + " should be in a format of AA:AA:AA:AA:AA:AA"); } else { return new ValidationResult(true); } }
Source:
public static void setSecurityManager() { URL resourceURL = CarbonBaseUtilsTest.class.getClassLoader().getResource(""); if (resourceURL != null) { String resourcePath = resourceURL.getPath(); resourcePath = resourcePath + "policy-test.policy"; System.setProperty("java.security.policy", resourcePath); System.setSecurityManager(new SecurityManager()); } }

Target:
public void setSecurityManager() { URL resourceURL = CarbonBaseUtilsTest.class.getClassLoader().getResource(""); if (resourceURL != null) { String resourcePath = resourceURL.getPath(); resourcePath = resourcePath + "policy-test.policy"; System.setProperty("java.security.policy", resourcePath); System.setSecurityManager(new SecurityManager()); } }
Source:
public ArrayInterface setBoolean(int index, boolean value) { return setObject(index, value); }

Target:
public Array setBoolean(int index, boolean value) { return setObject(index, value); }
Source:
public void testPutAll() throws Exception { Store<Number, CharSequence> store = mock(Store.class); Ehcache<Number, CharSequence> ehcache = new Ehcache<Number, CharSequence>(cacheConfig, store); ehcache.init(); ehcache.put(100, "one hundred"); ehcache.put(101, "one hundred one"); ehcache.putAll(new HashMap<Number, CharSequence>() {{ put(1, "one"); put(2, "two"); put(3, "three"); }}.entrySet()); CacheStatistics stats = ehcache.getStatistics(); System.out.println(stats.getCachePuts()); verify(store).bulkCompute(argThat(hasItems(1, 2, 3)), any(Function.class)); }

Target:
public void testPutAll() throws Exception { Store<Number, CharSequence> store = mock(Store.class); Ehcache<Number, CharSequence> ehcache = new Ehcache<Number, CharSequence>(cacheConfig, store); ehcache.init(); ehcache.putAll(new HashMap<Number, CharSequence>() {{ put(1, "one"); put(2, "two"); put(3, "three"); }}.entrySet()); verify(store).bulkCompute(argThat(hasItems(1, 2, 3)), any(Function.class)); }
Source:
private JSONObject getTableExtendedProperties(final String tableName) throws FalconException { JSONObject table = tablesMap.get(tableName); if (table == null) { throw new FalconException("JSON object tables not found in ADF request."); } try { JSONObject tableProperties = table.getJSONObject(ADFJsonConstants.ADF_REQUEST_PROPERTIES); if (tableProperties == null) { throw new FalconException("JSON object " + ADFJsonConstants.ADF_REQUEST_PROPERTIES + " not found in ADF request."); } JSONObject tablesLocation = tableProperties.getJSONObject(ADFJsonConstants.ADF_REQUEST_LOCATION); if (tablesLocation == null) { throw new FalconException("JSON object " + ADFJsonConstants.ADF_REQUEST_LOCATION + " not found in ADF request."); } JSONObject tableExtendedProperties = tablesLocation.getJSONObject(ADFJsonConstants. ADF_REQUEST_EXTENDED_PROPERTIES); if (tableExtendedProperties == null) { throw new FalconException("JSON object " + ADFJsonConstants.ADF_REQUEST_EXTENDED_PROPERTIES + " not found in ADF request."); } return tableExtendedProperties; } catch (JSONException e) { throw new FalconException("Error when parsing ADF JSON message: " + table, e); } }

Target:
private JSONObject getTableExtendedProperties(final String tableName) throws FalconException { JSONObject table = tablesMap.get(tableName); if (table == null) { throw new FalconException("JSON object table " + tableName + " not found in ADF request."); } try { JSONObject tableProperties = table.getJSONObject(ADFJsonConstants.ADF_REQUEST_PROPERTIES); if (tableProperties == null) { throw new FalconException("JSON object " + ADFJsonConstants.ADF_REQUEST_PROPERTIES + " not found in ADF request."); } JSONObject tablesLocation = tableProperties.getJSONObject(ADFJsonConstants.ADF_REQUEST_LOCATION); if (tablesLocation == null) { throw new FalconException("JSON object " + ADFJsonConstants.ADF_REQUEST_LOCATION + " not found in ADF request."); } JSONObject tableExtendedProperties = tablesLocation.getJSONObject(ADFJsonConstants. ADF_REQUEST_EXTENDED_PROPERTIES); if (tableExtendedProperties == null) { throw new FalconException("JSON object " + ADFJsonConstants.ADF_REQUEST_EXTENDED_PROPERTIES + " not found in ADF request."); } return tableExtendedProperties; } catch (JSONException e) { throw new FalconException("Error while parsing ADF JSON message: " + table, e); } }
Source:
Master setMaster(int numOfWorkers) { ArrayTransposeMaster master = new ArrayTransposeMaster(numOfWorkers); return master; }

Target:
Master setMaster(int numOfWorkers) { return new ArrayTransposeMaster(numOfWorkers); }
Source:
private OutputStream addPreSteps(ProcessingStepHandler handler, IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor) { ArrayList<ProcessingStep> steps = new ArrayList<>(); if (IArtifactDescriptor.TYPE_ZIP.equals(descriptor.getProperty(IArtifactDescriptor.DOWNLOAD_CONTENTTYPE))) steps.add(new ZipVerifierStep()); Set<String> skipChecksums = DOWNLOAD_MD5_CHECKSUM_ENABLED ? Collections.<String> emptySet() : Collections.singleton(ChecksumUtilities.MD5); addChecksumVerifiers(descriptor, steps, skipChecksums, IArtifactDescriptor.DOWNLOAD_CHECKSUM); if (steps.isEmpty()) return destination; ProcessingStep[] stepArray = steps.toArray(new ProcessingStep[steps.size()]); return handler.link(stepArray, destination, monitor); }

Target:
private OutputStream addPreSteps(ProcessingStepHandler handler, IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor) { ArrayList<ProcessingStep> steps = new ArrayList<>(); if (IArtifactDescriptor.TYPE_ZIP.equals(descriptor.getProperty(IArtifactDescriptor.DOWNLOAD_CONTENTTYPE))) steps.add(new ZipVerifierStep()); Set<String> skipChecksums = DOWNLOAD_MD5_CHECKSUM_ENABLED ? Collections.emptySet() : Collections.singleton(ChecksumUtilities.MD5); addChecksumVerifiers(descriptor, steps, skipChecksums, IArtifactDescriptor.DOWNLOAD_CHECKSUM); if (steps.isEmpty()) return destination; ProcessingStep[] stepArray = steps.toArray(new ProcessingStep[steps.size()]); return handler.link(stepArray, destination, monitor); }
Source:
public WifiInfo get(final String senseId) { return getRemotely(senseId, Boolean.FALSE).get(); }

Target:
public Optional<WifiInfo> get(final String senseId) { final HashMap<String, AttributeValue> key = Maps.newHashMap(); key.put(SENSE_ATTRIBUTE_NAME, new AttributeValue().withS(senseId)); final GetItemRequest getItemRequest = new GetItemRequest() .withTableName(wifiTableName) .withKey(key); try { final GetItemResult getItemResult = dynamoDBClient.getItem(getItemRequest); final Map<String, AttributeValue> item = getItemResult.getItem(); return createWifiInfofromDynamoDBItem(item, senseId); } catch (AmazonServiceException ase) { LOGGER.error("Failed to get wifi info for {}", senseId); return Optional.absent(); } }
Source:
public final T createOrReplace(T... items) { T itemToCreateOrReplace = getItem(); if (items.length > 1) { throw new IllegalArgumentException("Too many items to create."); } else if (items.length == 1) { itemToCreateOrReplace = items[0]; } if (itemToCreateOrReplace == null) { throw new IllegalArgumentException("Nothing to create."); } if (Utils.isNullOrEmpty(name)) { return withName(itemToCreateOrReplace.getMetadata().getName()).createOrReplace(itemToCreateOrReplace); } final CompletableFuture<T> future = new CompletableFuture<>(); while (!future.isDone()) { try { KubernetesResourceUtil.setResourceVersion(itemToCreateOrReplace, null); future.complete(create(itemToCreateOrReplace)); } catch (KubernetesClientException exception) { final T itemFromServer; if (exception.getCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) { itemFromServer = fromServer().get(); if (itemFromServer == null) { try { Thread.sleep(200); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } continue; } } else if (exception.getCode() != HttpURLConnection.HTTP_CONFLICT) { throw exception; } else { itemFromServer = fromServer().get(); } KubernetesResourceUtil.setResourceVersion(itemToCreateOrReplace, KubernetesResourceUtil.getResourceVersion(itemFromServer)); future.complete(replace(itemToCreateOrReplace)); } } return future.join(); }

Target:
public final T createOrReplace(T... items) { T itemToCreateOrReplace = getItem(); if (items.length > 1) { throw new IllegalArgumentException("Too many items to create."); } else if (items.length == 1) { itemToCreateOrReplace = items[0]; } if (itemToCreateOrReplace == null) { throw new IllegalArgumentException("Nothing to create."); } if (Utils.isNullOrEmpty(name)) { return withName(itemToCreateOrReplace.getMetadata().getName()).createOrReplace(itemToCreateOrReplace); } T finalItemToCreateOrReplace = itemToCreateOrReplace; CreateOrReplaceHelper<T> createOrReplaceHelper = new CreateOrReplaceHelper<>( this::create, this::replace, m -> { try { return waitUntilCondition(Objects::nonNull, 1, TimeUnit.SECONDS); } catch (InterruptedException interruptedException) { interruptedException.printStackTrace(); } return null; }, m -> fromServer().get() ); return createOrReplaceHelper.createOrReplace(finalItemToCreateOrReplace); }
Source:
protected TimeEvent createTimeEvent(TimeGraphEntry entry, ITimeGraphState state) { if (state.getValue() == Integer.MIN_VALUE) { return new NullTimeEvent(entry, state.getStartTime(), state.getDuration()); } int value = ((int) state.getValue()); String label = state.getLabel(); if (label != null) { return new NamedTimeEvent(entry, state.getStartTime(), state.getDuration(), value, label); } return new TimeEvent(entry, state.getStartTime(), state.getDuration(), value); }

Target:
protected TimeEvent createTimeEvent(TimeGraphEntry entry, ITimeGraphState state) { if (state.getValue() == Integer.MIN_VALUE) { return new NullTimeEvent(entry, state.getStartTime(), state.getDuration()); } final int modulo = CallStackPresentationProvider.NUM_COLORS / 2; int value = ((int) state.getValue()) % modulo + modulo; String label = state.getLabel(); if (label != null) { return new NamedTimeEvent(entry, state.getStartTime(), state.getDuration(), value, label); } return new TimeEvent(entry, state.getStartTime(), state.getDuration(), value); }
Source:
private boolean isCurrentNetworkSufficient(WifiInfo wifiInfo, List<ScanDetail> scanDetails) { WifiConfiguration network = mWifiConfigManager.getConfiguredNetwork(wifiInfo.getNetworkId()); if (network == null) { localLog("No current connected network."); return false; } else { localLog("Current connected network: " + network.SSID + " , ID: " + network.networkId); } if (network.ephemeral) { localLog("Current network is an ephemeral one."); return false; } if (WifiConfigurationUtil.isConfigForOpenNetwork(network)) { localLog("Current network is a open one."); return false; } int currentRssi = wifiInfo.getRssi(); if (wifiInfo.is24GHz()) { if (is5GHzNetworkAvailable(scanDetails)) { localLog("Current network is 2.4GHz. 5GHz networks available."); return false; } if (currentRssi < mThresholdQualifiedRssi24) { localLog("Current network band=2.4GHz, RSSI[" + currentRssi + "]-acceptable but not qualified."); return false; } } else if (wifiInfo.is5GHz()) { if (currentRssi < mThresholdQualifiedRssi5) { localLog("Current network band=5GHz, RSSI[" + currentRssi + "]-acceptable but not qualified."); return false; } } else { Log.e(TAG, "We're on a wifi network that's neither 2.4 or 5GHz... aliens!"); } return true; }

Target:
private boolean isCurrentNetworkSufficient(WifiInfo wifiInfo, List<ScanDetail> scanDetails) { WifiConfiguration network = mWifiConfigManager.getConfiguredNetwork(wifiInfo.getNetworkId()); if (network == null) { localLog("No current connected network."); return false; } else { localLog("Current connected network: " + network.SSID + " , ID: " + network.networkId); } if (network.ephemeral) { localLog("Current network is an ephemeral one."); return false; } if (WifiConfigurationUtil.isConfigForOpenNetwork(network)) { localLog("Current network is a open one."); return false; } int currentRssi = wifiInfo.getRssi(); if (wifiInfo.is24GHz()) { if (is5GHzNetworkAvailable(scanDetails)) { localLog("Current network is 2.4GHz. 5GHz networks available."); return false; } if (currentRssi < mThresholdQualifiedRssi24) { localLog("Current network band=2.4GHz, RSSI[" + currentRssi + "]-acceptable but not qualified."); return false; } } else if (wifiInfo.is5GHz()) { if (currentRssi < mThresholdQualifiedRssi5) { localLog("Current network band=5GHz, RSSI[" + currentRssi + "]-acceptable but not qualified."); return false; } } else { Log.e(TAG, "We're on a wifi network that's neither 2.4 or 5GHz... aliens!"); return false; } return true; }
Source:
public List<Event> findEventsByCorrelationUid(final String organisationIdentification, final String correlationUid) throws OsgpException { LOGGER.info("findEventsByCorrelationUid called with organisation {}}", organisationIdentification); this.domainHelperService.findOrganisation(organisationIdentification); final List<ResponseData> meterResponseDataList = this.responseDataRepository .findByCorrelationUid(correlationUid); final List<Event> events = new ArrayList<>(); final List<ResponseData> meterResponseDataToDeleteList = new ArrayList<>(); for (final ResponseData meterResponseData : meterResponseDataList) { final Serializable messageData = meterResponseData.getMessageData(); if (messageData instanceof EventMessagesResponse) { events.addAll(((EventMessagesResponse) messageData).getEvents()); meterResponseDataToDeleteList.add(meterResponseData); } else { if (messageData instanceof String) { throw new TechnicalException(ComponentType.UNKNOWN, (String) messageData); } LOGGER.info( "findEventsByCorrelationUid also found other type of meter response data: for correlation UID: {}", messageData.getClass().getName(), correlationUid); } } LOGGER.info("deleting MeterResponseData rows", meterResponseDataToDeleteList.size()); this.responseDataRepository.delete(meterResponseDataToDeleteList); LOGGER.info("returning a list containing events", events.size()); return events; }

Target:
public List<Event> findEventsByCorrelationUid(final String organisationIdentification, final String correlationUid) throws OsgpException { LOGGER.info("findEventsByCorrelationUid called with organisation {}}", organisationIdentification); this.domainHelperService.findOrganisation(organisationIdentification); final ResponseData responseData = this.responseDataRepository.findByCorrelationUid(correlationUid); final List<Event> events = new ArrayList<>(); final Serializable messageData = responseData.getMessageData(); if (messageData instanceof EventMessagesResponse) { events.addAll(((EventMessagesResponse) messageData).getEvents()); LOGGER.info("deleting ResponseData for correlation uid {}.", correlationUid); this.responseDataRepository.delete(responseData); } else { if (messageData instanceof String) { throw new TechnicalException(ComponentType.UNKNOWN, (String) messageData); } LOGGER.info( "findEventsByCorrelationUid found other type of meter response data: for correlation UID: {}", messageData.getClass().getName(), correlationUid); } LOGGER.info("returning a list containing events", events.size()); return events; }
Source:
public static FileUtils.FileCopyResult copyToFileAndClose(InputStream is, File file) throws IOException { file.getParentFile().mkdirs(); try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { ByteStreams.copy(is, os); } finally { CloseQuietly.close(is); } return FileUtils.FileCopyResult.buildResult(file.toPath()); }

Target:
public static long copyToFileAndClose(InputStream is, File file) throws IOException { file.getParentFile().mkdirs(); try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { return ByteStreams.copy(is, os); } finally { CloseQuietly.close(is); } }
Source:
public void testMaxRowsPerSegment() throws Exception { expectPublishedSegments(2); final AppenderatorDriverRealtimeIndexTask task = makeRealtimeTask(null); final ListenableFuture<TaskStatus> statusFuture = runTask(task); while (task.getFirehose() == null) { Thread.sleep(50); } final TestFirehose firehose = (TestFirehose) task.getFirehose(); for (int i = 0; i < 2000; i++) { firehose.addRows( ImmutableList.of( ImmutableMap.of("t", now.getMillis(), "dim1", "foo-" + i, "met1", "1") ) ); } firehose.close(); Collection<DataSegment> publishedSegments = awaitSegments(); Assert.assertEquals(2000, task.getMetrics().processed()); Assert.assertEquals(0, task.getMetrics().thrownAway()); Assert.assertEquals(0, task.getMetrics().unparseable()); Assert.assertEquals(2000, sumMetric(task, null, "met1").longValue()); Assert.assertEquals(2000, sumMetric(task, null, "met1").longValue()); awaitHandoffs(); for (DataSegment publishedSegment : publishedSegments) { Pair<Executor, Runnable> executorRunnablePair = handOffCallbacks.get( new SegmentDescriptor( publishedSegment.getInterval(), publishedSegment.getVersion(), publishedSegment.getShardSpec().getPartitionNum() ) ); Assert.assertNotNull( publishedSegment + " missing from handoff callbacks: " + handOffCallbacks, executorRunnablePair ); executorRunnablePair.lhs.execute(executorRunnablePair.rhs); } handOffCallbacks.clear(); final TaskStatus taskStatus = statusFuture.get(); Assert.assertEquals(TaskState.SUCCESS, taskStatus.getStatusCode()); }

Target:
public void testMaxRowsPerSegment() throws Exception { expectPublishedSegments(2); final AppenderatorDriverRealtimeIndexTask task = makeRealtimeTask(null); final ListenableFuture<TaskStatus> statusFuture = runTask(task); while (task.getFirehose() == null) { Thread.sleep(50); } final TestFirehose firehose = (TestFirehose) task.getFirehose(); for (int i = 0; i < 2000; i++) { firehose.addRows( ImmutableList.of( ImmutableMap.of("t", now.getMillis(), "dim1", "foo-" + i, "met1", "1") ) ); } firehose.close(); Collection<DataSegment> publishedSegments = awaitSegments(); Assert.assertEquals(2000, task.getRowIngestionMeters().getProcessed()); Assert.assertEquals(0, task.getRowIngestionMeters().getThrownAway()); Assert.assertEquals(0, task.getRowIngestionMeters().getUnparseable()); Assert.assertEquals(2000, sumMetric(task, null, "rows").longValue()); Assert.assertEquals(2000, sumMetric(task, null, "met1").longValue()); awaitHandoffs(); for (DataSegment publishedSegment : publishedSegments) { Pair<Executor, Runnable> executorRunnablePair = handOffCallbacks.get( new SegmentDescriptor( publishedSegment.getInterval(), publishedSegment.getVersion(), publishedSegment.getShardSpec().getPartitionNum() ) ); Assert.assertNotNull( publishedSegment + " missing from handoff callbacks: " + handOffCallbacks, executorRunnablePair ); executorRunnablePair.lhs.execute(executorRunnablePair.rhs); } handOffCallbacks.clear(); final TaskStatus taskStatus = statusFuture.get(); Assert.assertEquals(TaskState.SUCCESS, taskStatus.getStatusCode()); }
Source:
public static Flowable<Long> rangeLong(long start, long count) { if (count < 0) { throw new IllegalArgumentException("count >= 0 required but it was " + count); } if (count == 0) { return empty(); } if (count == 1) { return just(start); } if (start + (count - 1) > Long.MAX_VALUE) { throw new IllegalArgumentException("Long overflow"); } return RxJavaPlugins.onAssembly(new FlowableRangeLong(start, count)); }

Target:
public static Flowable<Long> rangeLong(long start, long count) { if (count < 0) { throw new IllegalArgumentException("count >= 0 required but it was " + count); } if (count == 0) { return empty(); } if (count == 1) { return just(start); } long end = start + (count - 1); if (start > 0 && end < 0) { throw new IllegalArgumentException("Overflow! start + count is bigger than Long.MAX_VALUE"); } return RxJavaPlugins.onAssembly(new FlowableRangeLong(start, count)); }