auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public InputStream getStream() { final Delete delete = new Delete(); delete.setQuiet(quiet); final List<DeleteObject> deleteObjects = new ArrayList<>(); for ( Map.Entry< String, Set< UUID > > entry : objects.entrySet() ) { if ( null == entry.getValue() ) { deleteObjects.add( new DeleteObject( entry.getKey(), null ) ); } else { for ( UUID versionId : entry.getValue() ) { deleteObjects.add( new DeleteObject( entry.getKey(), versionId ) ); } } } delete.setDeleteObjectList(deleteObjects); final String xmlOutput = XmlOutput.toXml(delete); final byte[] stringBytes = xmlOutput.getBytes(Charset.forName("UTF-8")); this.size = stringBytes.length; return new ByteArrayInputStream(stringBytes); }

Target:
public InputStream getStream() { final Delete delete = new Delete(); delete.setQuiet(quiet); final List<DeleteObject> deleteObjects = new ArrayList<>(); for ( final Map.Entry< String, Set< UUID > > entry : objects.entrySet() ) { if ( null == entry.getValue() ) { deleteObjects.add( new DeleteObject( entry.getKey(), null ) ); } else { for ( final UUID versionId : entry.getValue() ) { deleteObjects.add( new DeleteObject( entry.getKey(), versionId ) ); } } } delete.setDeleteObjectList(deleteObjects); final String xmlOutput = XmlOutput.toXml(delete); final byte[] stringBytes = xmlOutput.getBytes(Charset.forName("UTF-8")); this.size = stringBytes.length; return new ByteArrayInputStream(stringBytes); }
Source:
public void testStartProcessFromDisplayer(){ kieWorkbenchFormsStartProcessDisplayer.initConfigs(processDisplayerConfig, onClose, onRefresh); kieWorkbenchFormsStartProcessDisplayer.startProcessFromDisplayer(); verify(service).call(any()); verify(kieWorkbenchFormsEntryPoint).startProcessFromRenderContext(any(), any(), any(), any(), any(), any()); }

Target:
public void testStartProcessFromDisplayer() { when(formRenderer.isValid()).thenReturn(true); when(formRenderingSettings.getTimestamp()).thenReturn(100000l); MapModelRenderingContext mapModelRenderingContext = mock(MapModelRenderingContext.class); when(formRenderingSettings.getRenderingContext()).thenReturn(mapModelRenderingContext); when(service.call(any())).thenReturn(kieWorkbenchFormsEntryPoint); ProcessDefinitionKey processDefinitionKey = new ProcessDefinitionKey( "test-serverTemplateId", "test-deploymentId", "test-processId", "test-processDefName"); ProcessDisplayerConfig processDisplayerConfig = new ProcessDisplayerConfig(processDefinitionKey, "test"); processDisplayerConfig.setRenderingSettings(formRenderingSettings); kieWorkbenchFormsStartProcessDisplayer.initConfigs(processDisplayerConfig, null, null); kieWorkbenchFormsStartProcessDisplayer.startProcessFromDisplayer(); verify(service).call(any()); verify(kieWorkbenchFormsEntryPoint).startProcessFromRenderContext(100000l, null, "test-serverTemplateId", "test-deploymentId", "test-processId", ""); }
Source:
public Object getCurrentTransactionId() { if (TransactionImple.getTransaction() == null) return null; return TransactionImple.getTransaction().get_uid(); }

Target:
public Object getCurrentTransactionId() { com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple transaction = TransactionImple.getTransaction(); if (transaction == null) return null; return transaction.get_uid(); }
Source:
private static Object getPayload(Object obj) { SpecificRecordBase record = (SpecificRecordBase) obj; Schema schema = record.getSchema(); for (String name : payloadStrs) { Object payload = schema.getField(name); if (payload != null) { return payload; } } return obj; }

Target:
private static Object getPayload(Object obj) { SpecificRecordBase record = (SpecificRecordBase) obj; Schema schema = record.getSchema(); for (String name : payloadStrs) { Schema.Field payload = schema.getField(name); if (payload != null) { return record.get(payload.pos()); } } return obj; }
Source:
public void queueBuildCompleted(BuildMemory.MemoryImprint memoryImprint, TaskListener listener) { String serverName = memoryImprint.getEvent().getProvider().getName(); BuildCompletedCommandJob job = new BuildCompletedCommandJob(getConfig(serverName), memoryImprint, listener); GerritSendCommandQueue.queue(job); }

Target:
public void queueBuildCompleted(BuildMemory.MemoryImprint memoryImprint, TaskListener listener) { String serverName = getServerName(memoryImprint); BuildCompletedCommandJob job = new BuildCompletedCommandJob(getConfig(serverName), memoryImprint, listener); GerritSendCommandQueue.queue(job); }
Source:
private boolean isOldestRequestPastDue() { if (unexpiredRequestSendTimes.size() == 0) { throw new IllegalStateException("There are no unexpired requests"); } Map.Entry<ReplicaId, Long> oldestEntry = unexpiredRequestSendTimes.entrySet().iterator().next(); Histogram latencyTracker = getTracker(oldestEntry.getKey()); return (latencyTracker.getCount() >= MIN_DATA_POINTS_REQUIRED) && (time.milliseconds() - oldestEntry.getValue() >= latencyTracker.getSnapshot().getValue(quantile)); }

Target:
private boolean isOldestRequestPastDue() { Map.Entry<ReplicaId, Long> oldestEntry = unexpiredRequestSendTimes.entrySet().iterator().next(); Histogram latencyTracker = getLatencyHistogram(oldestEntry.getKey()); return (latencyTracker.getCount() >= MIN_DATA_POINTS_REQUIRED) && (time.milliseconds() - oldestEntry.getValue() >= latencyTracker.getSnapshot().getValue(quantile)); }
Source:
public static float getDistance(double lat1, double long1, double lat2, double long2) { final double R = 6370e3; final double rad_per_deg = Math.PI/180; lat1 *= rad_per_deg; long1 *= rad_per_deg; lat2 *= rad_per_deg; long2 *= rad_per_deg; double dLat = lat2-lat1; double dLon = long2-long1; double A = square(Math.sin(0.5*dLat)) + Math.cos(lat1) * Math.cos(lat2) * square(Math.sin(0.5*dLon)); return (float)(2 * R * Math.asin(Math.sqrt(A))); }

Target:
public static float getDistance(double lat1, double long1, double lat2, double long2) { final double R = 6370e3; final double rad_per_deg = Math.PI/180; double dLat = lat2-lat1; double dLon = long2-long1; double A = square(Math.sin(0.5*dLat*rad_per_deg)) + Math.cos(lat1*rad_per_deg) * Math.cos(lat2*rad_per_deg) * square(Math.sin(0.5*dLon*rad_per_deg)); return (float)(2 * R * Math.asin(Math.sqrt(A))); }
Source:
public static synchronized void buildSystemConfig() throws ApplicationServerException, FileNotFoundException { classLoaderConfig = new ClassLoaderConfiguration(); String defaultEnvironmentConfigPath = System.getProperty("catalina.home") + File.separator + "conf" + File.separator + "wso2" + File.separator + LoaderConstants.ENVIRONMENT_CONFIG_FILE; File environmentConfigFile = new File(defaultEnvironmentConfigPath); if (!environmentConfigFile.exists()) { String errorMessage = "Failed to load environment configuration file: " + defaultEnvironmentConfigPath; throw new FileNotFoundException(errorMessage); } populateEnvironments(environmentConfigFile); String defaultClassloaderConfigPath = System.getProperty("catalina.home") + File.separator + "conf" + File.separator + "wso2" + File.separator + LoaderConstants.CLASSLOADER_CONFIG_FILE; File classLoaderConfigFile = new File(defaultClassloaderConfigPath); if (!classLoaderConfigFile.exists()) { String errorMessage = "Failed to load default classloader configuration file: " + defaultEnvironmentConfigPath; throw new FileNotFoundException(errorMessage); } loadClassLoaderPolicy(classLoaderConfigFile); isSuccessful = true; }

Target:
public static synchronized void buildSystemConfig() throws ApplicationServerException, FileNotFoundException { classLoaderConfig = new ClassLoaderConfiguration(); Path defaultEnvironmentConfigPath = Paths .get(System.getProperty("catalina.home"), "conf", "wso2", LoaderConstants.ENVIRONMENT_CONFIG_FILE); File environmentConfigFile = defaultEnvironmentConfigPath.toFile(); if (!environmentConfigFile.exists()) { String errorMessage = "Failed to load environment configuration file: " + defaultEnvironmentConfigPath; throw new FileNotFoundException(errorMessage); } populateEnvironments(environmentConfigFile); Path defaultClassloaderConfigPath = Paths .get(System.getProperty("catalina.home"), "conf", "wso2", LoaderConstants.CLASSLOADER_CONFIG_FILE); File classLoaderConfigFile = defaultClassloaderConfigPath.toFile(); if (!classLoaderConfigFile.exists()) { String errorMessage = "Failed to load default classloader configuration file: " + defaultEnvironmentConfigPath; throw new FileNotFoundException(errorMessage); } loadClassLoaderPolicy(classLoaderConfigFile); isSuccessful = true; }
Source:
protected void loadWithSdkInitialized(@NonNull final Activity activity, @NonNull final Map<String, Object> localExtras, @NonNull final Map<String, String> serverExtras) throws Exception { PersonalInfoManager personalInfoManager = MoPub.getPersonalInformationManager(); if ( personalInfoManager != null && personalInfoManager.gdprApplies() ) { boolean canCollectPersonalInfo = personalInfoManager.canCollectPersonalInformation(); AppLovinPrivacySettings.setHasUserConsent( canCollectPersonalInfo, activity.getApplicationContext() ); } parentActivity = activity; final String adMarkup = serverExtras.get( DataKeys.ADM_KEY ); final boolean hasAdMarkup = !TextUtils.isEmpty( adMarkup ); log( DEBUG, "Requesting AppLovin banner with serverExtras: " + serverExtras + ", localExtras: " + localExtras + " and has ad markup: " + hasAdMarkup ); final String zoneId; if ( hasAdMarkup ) { zoneId = DEFAULT_TOKEN_ZONE; } else { if ( AppLovinSdk.VERSION_CODE >= 750 && serverExtras != null && serverExtras.containsKey( "zone_id" ) ) { zoneId = serverExtras.get( "zone_id" ); } else { zoneId = DEFAULT_ZONE; } } incentivizedInterstitial = createIncentivizedInterstitialAd( zoneId, activity, sdk ); if ( hasAdMarkup ) { isTokenEvent = true; sdk.getAdService().loadNextAdForAdToken( adMarkup, this ); } else { incentivizedInterstitial.preload( this ); } }

Target:
protected void loadWithSdkInitialized(@NonNull final Activity activity, @NonNull final Map<String, Object> localExtras, @NonNull final Map<String, String> serverExtras) throws Exception { PersonalInfoManager personalInfoManager = MoPub.getPersonalInformationManager(); if ( personalInfoManager != null && personalInfoManager.gdprApplies() ) { boolean canCollectPersonalInfo = personalInfoManager.canCollectPersonalInformation(); AppLovinPrivacySettings.setHasUserConsent( canCollectPersonalInfo, activity.getApplicationContext() ); } parentActivity = activity; final String adMarkup = serverExtras.get( DataKeys.ADM_KEY ); final boolean hasAdMarkup = !TextUtils.isEmpty( adMarkup ); log( DEBUG, "Requesting AppLovin banner with serverExtras: " + serverExtras + ", localExtras: " + localExtras + " and has ad markup: " + hasAdMarkup ); final String zoneId; if ( hasAdMarkup ) { zoneId = DEFAULT_TOKEN_ZONE; } else { final String serverExtrasZoneId = serverExtras.get( ZONE_ID_SERVER_EXTRAS_KEY ); if ( !TextUtils.isEmpty( serverExtrasZoneId ) ) { zoneId = serverExtrasZoneId; } else { zoneId = DEFAULT_ZONE; } } incentivizedInterstitial = createIncentivizedInterstitialAd( zoneId, activity, sdk ); if ( hasAdMarkup ) { isTokenEvent = true; sdk.getAdService().loadNextAdForAdToken( adMarkup, this ); } else { incentivizedInterstitial.preload( this ); } }
Source:
protected abstract void readNext() throws IOException; @Override public final Iterator<T> iterator(){ return new Iterator<T>(){ @Override public T next() throws NoSuchElementException { if (nextRecordStatus == Status.ERROR || bufferedRecord == null && !hasNext()) { nextRecordStatus = Status.VOID; throw new NoSuchElementException("EOF has been reached. No more documents to read."); } T ret = bufferedRecord; bufferedRecord = null; return ret; } @Override public boolean hasNext() { if (nextRecordStatus == Status.ERROR) { return false; } if (bufferedRecord != null) { return true; } else if (atEOF) { return false; } try { readNext(); } catch (IOException | NoSuchElementException e1) { return false; } catch (RuntimeException e2) { nextRecordStatus = Status.VOID; skipped += 1; return hasNext(); } return bufferedRecord != null; } @Override public void remove() { throw new UnsupportedOperationException(); } }; }

Target:
protected abstract void readNext() throws IOException, ParseException, NoSuchElementException; @Override public final Iterator<T> iterator(){ return new Iterator<T>(){ @Override public T next() throws NoSuchElementException { if (error) { throw new NoSuchElementException("Encountered file read error, stopping iteration."); } if (bufferedRecord == null && !hasNext()) { throw new NoSuchElementException("EOF has been reached. No more documents to read."); } T ret = bufferedRecord; bufferedRecord = null; return ret; } @Override public boolean hasNext() { if (bufferedRecord != null) { return true; } else if (atEOF) { return false; } try { readNext(); } catch (IOException e1) { error = true; return false; } catch (NoSuchElementException e2){ return false; } catch (ParseException e3) { skipped += 1; return hasNext(); } return bufferedRecord != null; } @Override public void remove() { throw new UnsupportedOperationException(); } }; }
Source:
public static ImmutableMap<String, Ds3Type> removeUnusedTypes( final ImmutableMap<String, Ds3Type> types, final ImmutableList<Ds3Request> requests) { if (isEmpty(types) || isEmpty(requests)) { return ImmutableMap.of(); } final ImmutableSet.Builder<String> usedTypesBuilder = ImmutableSet.builder(); usedTypesBuilder.addAll(getUsedTypesFromRequests(requests)); usedTypesBuilder.addAll(getUsedTypesFromAllTypes(types, usedTypesBuilder.build())); final ImmutableMap.Builder<String, Ds3Type> builder = ImmutableMap.builder(); for (final Map.Entry<String, Ds3Type> entry : types.entrySet()) { if (usedTypesBuilder.build().contains(entry.getKey())) { builder.put(entry.getKey(), entry.getValue()); } } return builder.build(); }

Target:
public static ImmutableMap<String, Ds3Type> removeUnusedTypes( final ImmutableMap<String, Ds3Type> types, final ImmutableList<Ds3Request> requests) { if (isEmpty(types) || isEmpty(requests)) { return ImmutableMap.of(); } final ImmutableSet.Builder<String> usedTypesBuilder = ImmutableSet.builder(); usedTypesBuilder.addAll(getUsedTypesFromRequests(requests)); usedTypesBuilder.addAll(getUsedTypesFromAllTypes(types, usedTypesBuilder.build())); final ImmutableSet<String> usedTypes = usedTypesBuilder.build(); final ImmutableMap.Builder<String, Ds3Type> builder = ImmutableMap.builder(); for (final Map.Entry<String, Ds3Type> entry : types.entrySet()) { if (usedTypes.contains(entry.getKey())) { builder.put(entry.getKey(), entry.getValue()); } } return builder.build(); }
Source:
public ScenarioSimulationModel unmarshal(final String rawXml, boolean migrate) throws Exception { if (rawXml == null || rawXml.trim().equals("")) { throw new IllegalArgumentException("File content is empty!"); } String xml = migrate ? migrateIfNecessary(rawXml) : rawXml; return internalUnmarshal(xml); }

Target:
public ScenarioSimulationModel unmarshal(final String rawXml, boolean migrate) throws Exception { if (rawXml == null || rawXml.trim().equals("")) { throw new IllegalArgumentException("Malformed file, content is empty!"); } String xml = migrate ? migrateIfNecessary(rawXml) : rawXml; return internalUnmarshal(xml); }
Source:
public void testSDXWithDataLakeAndFreeIpaStorageCanBeCreatedSuccessfully(TestContext testContext) { String sdx = resourcePropertyProvider().getName(); String diagnostics = resourcePropertyProvider().getName(); DescribeFreeIpaResponse describeFreeIpaResponse = testContext.given(FreeIpaTestDto.class) .when(freeIpaTestClient.describe()) .getResponse(); testContext .given(sdx, SdxTestDto.class).withCloudStorage() .when(sdxTestClient.create(), key(sdx)) .awaitForFlow(key(sdx)) .await(SdxClusterStatusResponse.RUNNING) .awaitForInstance(getSdxInstancesHealthyState()) .given(diagnostics, SdxDiagnosticsTestDto.class) .when(sdxTestClient.collectDiagnostics(), key(diagnostics)) .awaitForFlow(key(diagnostics)) .given(sdx, SdxTestDto.class) .then((tc, testDto, client) -> { getCloudFunctionality(tc).cloudStorageListContainerDataLake(getBaseLocation(testDto), testDto.getResponse().getName(), testDto.getResponse().getStackCrn()); return testDto; }) .then((tc, testDto, client) -> { getCloudFunctionality(tc).cloudStorageListContainerFreeIpa(getBaseLocation(testDto), describeFreeIpaResponse.getName(), describeFreeIpaResponse.getCrn()); return testDto; }) .validate(); }

Target:
public void testSDXWithDataLakeAndFreeIpaStorageCanBeCreatedSuccessfully(TestContext testContext) { String sdx = resourcePropertyProvider().getName(); DescribeFreeIpaResponse describeFreeIpaResponse = testContext.given(FreeIpaTestDto.class) .when(freeIpaTestClient.describe()) .getResponse(); testContext .given(sdx, SdxTestDto.class).withCloudStorage() .when(sdxTestClient.create(), key(sdx)) .awaitForFlow(key(sdx)) .await(SdxClusterStatusResponse.RUNNING) .awaitForInstance(getSdxInstancesHealthyState()) .then((tc, testDto, client) -> { getCloudFunctionality(tc).cloudStorageListContainerDataLake(getBaseLocation(testDto), testDto.getResponse().getName(), testDto.getResponse().getStackCrn()); return testDto; }) .then((tc, testDto, client) -> { getCloudFunctionality(tc).cloudStorageListContainerFreeIpa(getBaseLocation(testDto), describeFreeIpaResponse.getName(), describeFreeIpaResponse.getCrn()); return testDto; }) .validate(); }
Source:
public List<String> saveRoleLayouts(final Role role, final Set<String> layoutIds, final LayoutAPI layoutAPI, final RoleAPI roleAPI, final SystemEventsAPI systemEventsAPI) throws DotDataException { final List<Layout> layouts = layoutAPI.loadLayoutsForRole(role); final List<String> layoutsAdded = new ArrayList<>(); final Map<String, Layout> currentLayoutMaps = layouts.stream().collect( Collectors.toMap(layout -> layout.getId(), layout -> layout)); layoutIds.forEach(layoutId -> currentLayoutMaps.remove(layoutId)); for(final Map.Entry<String, Layout> layoutToRemoveEntry : currentLayoutMaps.entrySet()) { roleAPI.removeLayoutFromRole(layoutToRemoveEntry.getValue(), role); } for(final String changedLayout : layoutIds) { final Layout layout = layoutAPI.findLayout(changedLayout); if (null != layout && UtilMethods.isSet(layout.getId())) { if (!roleAPI.hasLayoutToRole(layout, role)) { roleAPI.addLayoutToRole(layout, role); layoutsAdded.add(layout.getId()); } } } systemEventsAPI.pushAsync(SystemEventType.UPDATE_PORTLET_LAYOUTS, new Payload(layoutsAdded)); return layoutsAdded; }

Target:
public List<String> saveRoleLayouts(final Role role, final Set<String> layoutIds, final LayoutAPI layoutAPI, final RoleAPI roleAPI, final SystemEventsAPI systemEventsAPI) throws DotDataException { final List<Layout> layouts = layoutAPI.loadLayoutsForRole(role); final List<String> layoutsAdded = new ArrayList<>(); final Map<String, Layout> currentLayoutMaps = layouts.stream().collect( Collectors.toMap(layout -> layout.getId(), layout -> layout)); layoutIds.forEach(layoutId -> currentLayoutMaps.remove(layoutId)); for(final Map.Entry<String, Layout> layoutToRemoveEntry : currentLayoutMaps.entrySet()) { roleAPI.removeLayoutFromRole(layoutToRemoveEntry.getValue(), role); } for(final String changedLayout : layoutIds) { final Layout layout = layoutAPI.findLayout(changedLayout); if (null != layout && UtilMethods.isSet(layout.getId())) { if (!roleAPI.roleHasLayout(layout, role)) { roleAPI.addLayoutToRole(layout, role); layoutsAdded.add(layout.getId()); } } } systemEventsAPI.pushAsync(SystemEventType.UPDATE_PORTLET_LAYOUTS, new Payload(layoutsAdded)); return layoutsAdded; }
Source:
public Builder withStudentProfileAttributes(StudentProfileAttributes studentProfileAttributes) { accountAttributes.studentProfile = studentProfileAttributes; accountAttributes.studentProfile.sanitizeForSaving(); return this; }

Target:
public Builder withStudentProfileAttributes(StudentProfileAttributes studentProfileAttributes) { accountAttributes.studentProfile = studentProfileAttributes; return this; }
Source:
public RetryPolicyOptions() { setRetryOptions(new ExponentialBackoff(), null, null); }

Target:
public RetryPolicyOptions() { this(new ExponentialBackoff(), null, null); }
Source:
public void testGetVmDeviceByVmIdTypeAndDeviceFilteringSetToFlase() { List<VmDevice> devices = dao.getVmDeviceByVmIdTypeAndDevice(EXISTING_VM_ID, "disk", "disk", null, false); assertEquals("there should only be " + TOTAL_DEVICES + " disks", TOTAL_DEVICES, devices.size()); }

Target:
public void testGetVmDeviceByVmIdTypeAndDeviceFilteringSetToFlase() { List<VmDevice> devices = dao.getVmDeviceByVmIdTypeAndDevice(EXISTING_VM_ID, "disk", "disk", null, false); assertGetVMDeviceByIdTypeAndDeviceFullResult(devices); }
Source:
public void uploadMap(Path file, boolean isRanked, ByteCountListener listener) { MultiValueMap<String, Object> multipartContent = createFileMultipart(file, listener); multipartContent.add("metadata", "{\"isRanked\":\"" + isRanked + "\"}"); post("/maps/upload", multipartContent); }

Target:
public void uploadMap(Path file, boolean isRanked, ByteCountListener listener) { MultiValueMap<String, Object> multipartContent = createFileMultipart(file, listener); multipartContent.add("metadata", ImmutableMap.of("isRanked", isRanked)); post("/maps/upload", multipartContent); }
Source:
public Model getUPDATEModel(Representation representation) { return new ModelImpl() .property("condition", new StringProperty()) .property("patient", new StringProperty()) .property("clinicalStatus", new StringProperty()) .property("verificationStatus", new StringProperty()) .property("previousVersion", new StringProperty()) .property("onsetDate", new StringProperty()) .property("voided", new StringProperty()) .required("condition").required("onsetDate"); }

Target:
public Model getUPDATEModel(Representation representation) { return new ModelImpl() .property("condition", new StringProperty()) .property("clinicalStatus", new StringProperty()) .property("verificationStatus", new StringProperty()) .property("previousVersion", new StringProperty()) .property("onsetDate", new StringProperty()) .property("voided", new StringProperty()); }
Source:
private CliCommand getCommandExecutor() throws CommandException { final String commandName = this.args.getCommand(); String commandCamel = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, commandName.toString()); Iterator<CliCommand> implementations = getAllCommands(); while (implementations.hasNext()) { CliCommand implementation = implementations.next(); String className = implementation.getClass().getSimpleName(); if (className.equalsIgnoreCase(commandCamel)) { return implementation.withProvider(this.ds3Provider, this.fileUtils); } } throw new CommandException("No command class: " + commandName); }

Target:
private CliCommand getCommandExecutor() throws CommandException { final String commandName = this.args.getCommand(); final String commandCamel = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, commandName.toString()); final Iterator<CliCommand> implementations = getAllCommands(); while (implementations.hasNext()) { final CliCommand implementation = implementations.next(); final String className = implementation.getClass().getSimpleName(); if (className.equalsIgnoreCase(commandCamel)) { return implementation.withProvider(this.ds3Provider, this.fileUtils); } } throw new CommandException("No command class: " + commandName); }
Source:
public static JSITLiteralExpression dmnFromWB(final OutputClauseLiteralExpression wb) { if (Objects.isNull(wb)) { return null; } else if (StringUtils.isEmpty(wb.getText().getValue())) { return null; } return LiteralExpressionPropertyConverter.dmnFromWB(wb); }

Target:
public static JSITLiteralExpression dmnFromWB(final OutputClauseLiteralExpression wb) { if (Objects.isNull(wb)) { return null; } else if (Objects.isNull(wb.getText())) { return null; } else if (StringUtils.isEmpty(wb.getText().getValue())) { return null; } return LiteralExpressionPropertyConverter.dmnFromWB(wb); }
Source:
public synchronized void suspend() { synchronized (fSynchObject) { fIsPaused = true; } TmfCoreTracer.traceRequest(fRequest, "SUSPENDED"); }

Target:
public void suspend() { fIsPaused = true; TmfCoreTracer.traceRequest(fRequest, "SUSPENDED"); }
Source:
public StandaloneCommandBuilder setGitRepository(final String gitRepository, final String gitBranch, final String gitAuthentication) { if(gitRepository == null) { throw MESSAGES.nullParam("git-repo"); } Objects.requireNonNull(gitRepository); addServerArg("--git-repo", gitRepository); if (gitBranch != null) { addServerArg("--git-branch", gitBranch); } if (gitAuthentication != null) { addServerArg("--git-auth", gitAuthentication); } return this; }

Target:
public StandaloneCommandBuilder setGitRepository(final String gitRepository, final String gitBranch, final String gitAuthentication) { if(gitRepository == null) { throw MESSAGES.nullParam("git-repo"); } addServerArg("--git-repo", gitRepository); if (gitBranch != null) { addServerArg("--git-branch", gitBranch); } if (gitAuthentication != null) { addServerArg("--git-auth", gitAuthentication); } return this; }
Source:
public ResponseEntity<ExpenseDTO[]> createExpenses(@RequestBody @Valid Expense[] expenses) { try { if (expenses == null || expenses.length == 0) { throw new BadRequestException("No expenses found in request!"); } else { ExpenseDTO[] createdExpensesDTO = new ExpenseDTO[expenses.length]; int index = 0; for (Expense expense : expenses) { if (CurrencyUtil.getCurrency(expense.getCurrency()) == null) { throw new BadRequestException("Wrong currency code for index [" + index + "]!"); } String categoryName = expense.getCategory().getName(); AppUser user = userUtil.extractLoggedAppUserFromDatabase(); Category category = categoryDao.findByNameAndUsername(categoryName, user.getUsername()); if (category == null) { category = createAndSaveCategory(categoryName, user); } if (!user.getDefaultCurrency().getCurrencyCode().equals(expense.getCurrency())) { setDefaultCurrencyAmount(expense, user.getDefaultCurrency()); } expense.setCategory(category); expense.setUser(user); Expense savedExpense = expenseDao.saveAndFlush(expense); ExpenseDTO createdExpenseDto = expenseConverter.convertTo(savedExpense); createdExpensesDTO[index] = createdExpenseDto; index++; } return new ResponseEntity<>(createdExpensesDTO, HttpStatus.OK); } } catch (ConstraintViolationException e) { throw new BadRequestException(e.getMessage()); } }

Target:
public ResponseEntity<List<ExpenseDTO>> createExpenses(@RequestBody @Valid Expense[] expenses) { try { if (expenses == null || expenses.length == 0) { throw new BadRequestException("No expenses found in request!"); } else { List<ExpenseDTO> createdExpenseListDTO = new ArrayList<>(); int index = 0; for (Expense expense : expenses) { if (CurrencyUtil.getCurrency(expense.getCurrency()) == null) { throw new BadRequestException("Wrong currency code for index [" + index + "] and Currency code [" + expense.getCurrency() + "]!"); } AppUser user = userUtil.extractLoggedAppUserFromDatabase(); Category category = resolveCategory(user, expense.getCategory().getName()); if (!user.getDefaultCurrency().getCurrencyCode().equals(expense.getCurrency())) { setDefaultCurrencyAmount(expense, user.getDefaultCurrency()); } expense.setCategory(category); expense.setUser(user); ExpenseDTO createdExpenseDto = expenseConverter.convertTo(expenseDao.saveAndFlush(expense)); createdExpenseListDTO.add(createdExpenseDto); index++; } return new ResponseEntity<>(createdExpenseListDTO, HttpStatus.OK); } } catch (ConstraintViolationException e) { throw new BadRequestException(e.getMessage()); } }
Source:
private int getUserId(String username) { try (Connection conn = getConnection(); PreparedStatement insert = conn.prepareStatement("SELECT id FROM users WHERE name = ?;")) { insert.setString(1, username); ResultSet resultSet = insert.executeQuery(); resultSet.next(); return resultSet.getInt(1); } catch (SQLException sqe) { LOG.log(Level.WARNING, sqe.getMessage(), sqe); throw new RuntimeException(sqe); } }

Target:
private int getUserId(String username) { try (Connection conn = getConnection(); PreparedStatement userSelect = conn.prepareStatement("SELECT id FROM users WHERE name = ?;")) { userSelect.setString(1, username); ResultSet resultSet = userSelect.executeQuery(); resultSet.next(); return resultSet.getInt(1); } catch (SQLException sqe) { LOG.log(Level.WARNING, sqe.getMessage(), sqe); throw new RuntimeException(sqe); } }
Source:
private void clearTenantCaches(Tenant tenant) throws UserStoreException { if (tenant != null) { int tenantId = tenant.getId(); String tenantUniqueID = tenant.getTenantUniqueID(); tenantUniqueIdCache.clearCacheEntry(new TenantUniqueIDKey(tenantUniqueID)); tenantDomainCache.clearCacheEntry(new TenantIdKey(tenantId)); tenantIdCache.clearCacheEntry(new TenantDomainKey(tenant.getDomain())); tenantCacheManager.clearCacheEntry(new TenantIdKey(tenantId)); } }

Target:
private void clearTenantCaches(Tenant tenant) throws UserStoreException { int tenantId = tenant.getId(); String tenantUniqueID = tenant.getTenantUniqueID(); tenantUniqueIdCache.clearCacheEntry(new TenantUniqueIDKey(tenantUniqueID)); tenantDomainCache.clearCacheEntry(new TenantIdKey(tenantId)); tenantIdCache.clearCacheEntry(new TenantDomainKey(tenant.getDomain())); tenantCacheManager.clearCacheEntry(new TenantIdKey(tenantId)); }
Source:
private void testResizeOrMovePort(String representationName, boolean checkMoving) { editor = openAndGetEditor(representationName, representationName); PointList originalPoints = getBendpoints(DROP_PORT_NAME); final Rectangle originalPortBounds = getEditPartBounds(DROP_PORT_NAME); int relativeClickedY = checkMoving ? -originalPortBounds.height / 2 : -1; final Point pointToDrag = originalPortBounds.getBottom().getTranslated(0, relativeClickedY); editor.select(editor.getEditPart(DROP_PORT_NAME, AbstractDiagramBorderNodeEditPart.class)); final Point endpoint = pointToDrag.getTranslated(VERTICAL_TRANSLATION); editor.drag(pointToDrag.x, pointToDrag.y, endpoint.x, endpoint.y); final Rectangle newPortBounds = getEditPartBounds(DROP_PORT_NAME); if (checkMoving) { assertThat("Port is not at expected position (probably not moved but resized)", newPortBounds.getTopRight(), PointAround.around(originalPortBounds.getTopRight().getTranslated(VERTICAL_TRANSLATION), 5)); } else { assertThat("Port is not at expected position (probably not moved but resized)", newPortBounds.getTopRight(), PointAround.around(originalPortBounds.getTopRight(), 0)); } if (originalPoints != null && checkMoving) { checkEdgeStability(DROP_PORT_NAME, originalPoints); } }

Target:
private void testResizeOrMovePort(String representationName, boolean checkMoving) { editor = openAndGetEditor(representationName, representationName); PointList originalPoints = getBendpoints(DROP_PORT_NAME); final Rectangle originalPortBounds = getEditPartBounds(DROP_PORT_NAME); int relativeClickedY = checkMoving ? -originalPortBounds.height / 2 : -1; final Point pointToDrag = originalPortBounds.getBottom().getTranslated(0, relativeClickedY); editor.select(editor.getEditPart(DROP_PORT_NAME, AbstractDiagramBorderNodeEditPart.class)); final Point endpoint = pointToDrag.getTranslated(VERTICAL_TRANSLATION); editor.drag(pointToDrag.x, pointToDrag.y, endpoint.x, endpoint.y); final Rectangle newPortBounds = getEditPartBounds(DROP_PORT_NAME); if (checkMoving) { assertThat("Port is not at expected position (probably not moved but resized)", newPortBounds.getTopRight(), PointAround.around(originalPortBounds.getTopRight().getTranslated(VERTICAL_TRANSLATION), 5)); if (originalPoints != null) { checkEdgeStability(DROP_PORT_NAME, originalPoints); } } else { assertThat("Port is not at expected position (probably not moved but resized)", newPortBounds.getTopRight(), PointAround.around(originalPortBounds.getTopRight(), 0)); } }
Source:
public void testNoListenerUpdate() { observer.removeListener(); observer.checkAndNotify(); }

Target:
public void testNoListenerUpdate() throws Exception { initFiles(5, monitoredDirectory, "covert00"); observer.removeListener(); observer.checkAndNotify(); assertThat(observer.getRootFile().getChildren().isEmpty(), is(true)); }
Source:
public static void validateJsonAgainstSchema(String jsonSchema, String jsonData) { if (jsonSchema.contains("<LINK_0>") || jsonSchema.contains("<LINK_1>")) { LOGGER.info("JSON schema version draft-03/draft-04 was detected"); validateJsonAgainstSchemaV3V4(jsonSchema, jsonData); } else { LOGGER.info("JSON schema version higher than draft-03/draft-04 was detected"); validateJsonAgainstSchemaV6V7(jsonSchema, jsonData); } }

Target:
public static void validateJsonAgainstSchema(String jsonSchema, String jsonData) { Matcher m = Pattern.compile("\\d+", Pattern.MULTILINE).matcher(jsonSchema); if (m.find()) { int schemaVersion = Integer.valueOf(m.group()); if (schemaVersion <= 4) { LOGGER.info("JSON schema of version below or equal to draft-04 was detected"); validateJsonAgainstSchemaV3V4(jsonSchema, jsonData); } else { LOGGER.info("JSON schema of version higher than draft-04 was detected"); validateJsonAgainstSchemaV6V7(jsonSchema, jsonData); } } else { LOGGER.warn("JSON schema version can not be detected"); validateJsonAgainstSchemaV3V4(jsonSchema, jsonData); } }
Source:
private int getPriority(ExecutableFlow exflow) { ExecutionOptions options = exflow.getExecutionOptions(); int priority = ExecutionOptions.DEFAULT_FLOW_PRIORITY; if (options != null && options.getFlowParameters() != null && options.getFlowParameters() .containsKey(ExecutionOptions.FLOW_PRIORITY)) { try { priority = Integer.valueOf(options.getFlowParameters().get( ExecutionOptions.FLOW_PRIORITY)); } catch (NumberFormatException ex) { priority = ExecutionOptions.DEFAULT_FLOW_PRIORITY; logger.error("Failed to parse flow priority for exec_id = " + exflow.getExecutionId()); } } return priority; }

Target:
private int getPriority(ExecutableFlow exflow) { ExecutionOptions options = exflow.getExecutionOptions(); int priority = ExecutionOptions.DEFAULT_FLOW_PRIORITY; if (options != null && options.getFlowParameters() != null && options.getFlowParameters() .containsKey(ExecutionOptions.FLOW_PRIORITY)) { try { priority = Integer.valueOf(options.getFlowParameters().get( ExecutionOptions.FLOW_PRIORITY)); } catch (NumberFormatException ex) { priority = ExecutionOptions.DEFAULT_FLOW_PRIORITY; logger.error( "Failed to parse flow priority for exec_id = " + exflow.getExecutionId(), ex); } } return priority; }
Source:
private void generatePluginFiles(String pluginName) throws IOException { File pluginTargetFolder = new File(nodeModulesFolder, "@vaadin/" + pluginName); final String pluginFolder = "plugins/" + pluginName + "/"; final JsonObject json = getJsonFile(pluginFolder + PACKAGE_JSON); if (json == null) { log().error("Couldn't locate files for plugin '{}'", pluginName); return; } if (pluginTargetFolder.exists() && new File(pluginTargetFolder, PACKAGE_JSON).exists()) { String packageFile = FileUtils .readFileToString(new File(pluginTargetFolder, PACKAGE_JSON), StandardCharsets.UTF_8); final FrontendVersion packageVersion = new FrontendVersion( Json.parse(packageFile).getString("version")); FrontendVersion pluginVersion = new FrontendVersion( json.getString("version")); if (packageVersion.isEqualTo(pluginVersion)) { log().debug( "Skipping install of for version already installed", pluginName, pluginVersion.getFullVersion()); return; } } FileUtils.forceMkdir(pluginTargetFolder); final JsonArray files = json.getArray("files"); for (int i = 0; i < files.length(); i++) { final String file = files.getString(i); FileUtils.copyURLToFile(getUrlResource(pluginFolder + file), new File(pluginTargetFolder, file)); } FileUtils.copyURLToFile(getUrlResource(pluginFolder + PACKAGE_JSON), new File(pluginTargetFolder, PACKAGE_JSON)); }

Target:
private void generatePluginFiles(String pluginName) throws IOException { File pluginTargetFile = new File(nodeModulesFolder, "@vaadin/" + pluginName); final String pluginFolderName = "plugins/" + pluginName + "/"; final JsonObject packageJson = getJsonFile( pluginFolderName + PACKAGE_JSON); if (packageJson == null) { log().error( "Couldn't locate '{}' for plugin '{}'. Plugin will not be installed.", PACKAGE_JSON, pluginName); return; } if (pluginTargetFile.exists() && new File(pluginTargetFile, PACKAGE_JSON).exists()) { String packageFile = FileUtils .readFileToString(new File(pluginTargetFile, PACKAGE_JSON), StandardCharsets.UTF_8); final FrontendVersion packageVersion = new FrontendVersion( Json.parse(packageFile).getString("version")); FrontendVersion pluginVersion = new FrontendVersion( packageJson.getString("version")); if (packageVersion.isEqualTo(pluginVersion)) { log().debug( "Skipping install of for version already installed", pluginName, pluginVersion.getFullVersion()); return; } } FileUtils.forceMkdir(pluginTargetFile); final JsonArray files = packageJson.getArray("files"); for (int i = 0; i < files.length(); i++) { final String file = files.getString(i); FileUtils.copyURLToFile(getResourceUrl(pluginFolderName + file), new File(pluginTargetFile, file)); } FileUtils.copyURLToFile(getResourceUrl(pluginFolderName + PACKAGE_JSON), new File(pluginTargetFile, PACKAGE_JSON)); }
Source:
public Map<Integer, List<ObservationLevel>> getObservationLevelsMap(final List<Integer> studyIds) { try { final Map<Integer, List<ObservationLevel>> observationLevelsMap = new HashMap<>(); final String sqlString = "SELECT study_id AS studyId, dataset_type_id AS datasetTypeId, name AS studyName FROM project " + " where dataset_type_id != " + DatasetTypeEnum.SUMMARY_DATA.getId() + " AND study_id IN (:studyIds)"; final SQLQuery sqlQuery = this.getSession().createSQLQuery(sqlString); sqlQuery.addScalar("studyId", new IntegerType()); sqlQuery.addScalar("datasetTypeId", new IntegerType()); sqlQuery.addScalar("studyName", new StringType()); sqlQuery.setParameterList("studyIds", studyIds); sqlQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE); final List<Map<String, Object>> results = sqlQuery.list(); for (final Map<String, Object> result : results) { final ObservationLevel observationLevel = new ObservationLevel((Integer)result.get("datasetTypeId"), String.valueOf(result.get("studyName"))); final Integer studyId = (Integer) result.get("studyId"); if(observationLevelsMap.get(studyId) != null) { observationLevelsMap.get(studyId).add(observationLevel); } else { final List<ObservationLevel> observationLevels = new ArrayList<>(); observationLevels.add(observationLevel); observationLevelsMap.put(studyId, observationLevels); } } return observationLevelsMap; } catch (final HibernateException e) { throw new MiddlewareQueryException("Error getting getObservationLevelsMap for studyIds=" + studyIds + ":" + e.getMessage(), e); } }

Target:
public Map<Integer, List<ObservationLevel>> getObservationLevelsMap(final List<Integer> studyIds) { try { final Map<Integer, List<ObservationLevel>> observationLevelsMap = new HashMap<>(); final String sqlString = "SELECT study_id AS studyId, dataset_type_id AS datasetTypeId, name AS datasetName FROM project " + " where dataset_type_id != " + DatasetTypeEnum.SUMMARY_DATA.getId() + " AND study_id IN (:studyIds)"; final SQLQuery sqlQuery = this.getSession().createSQLQuery(sqlString); sqlQuery.addScalar("studyId", new IntegerType()); sqlQuery.addScalar("datasetTypeId", new IntegerType()); sqlQuery.addScalar("datasetName", new StringType()); sqlQuery.setParameterList("studyIds", studyIds); sqlQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE); final List<Map<String, Object>> results = sqlQuery.list(); for (final Map<String, Object> result : results) { final ObservationLevel observationLevel = new ObservationLevel((Integer)result.get("datasetTypeId"), String.valueOf(result.get("datasetName"))); final Integer studyId = (Integer) result.get("studyId"); observationLevelsMap.putIfAbsent(studyId, new ArrayList<>()); observationLevelsMap.get(studyId).add(observationLevel); } return observationLevelsMap; } catch (final HibernateException e) { throw new MiddlewareQueryException("Error getting getObservationLevelsMap for studyIds=" + studyIds + ":" + e.getMessage(), e); } }
Source:
public List<InterpreterCompletion> completion(String buffer, int cursor) { String lines[] = buffer.split(System.getProperty("line.separator")); if (lines.length > 0 && lines[0].startsWith("%") && cursor <= lines[0].trim().length()) { int idx = lines[0].indexOf(' '); if (idx < 0 || (idx > 0 && cursor <= idx)) { return getInterpreterCompletion(); } } String replName = getRequiredReplName(buffer); if (replName != null && cursor > replName.length()) { Matcher m = Pattern.compile(String.format("%%%s\\s*", replName)).matcher(buffer); if (m.find()) { cursor -= m.group().length(); } } String body = getScriptBody(buffer); Interpreter repl = getRepl(replName); if (repl == null) { return null; } InterpreterContext interpreterContext = getInterpreterContextWithoutRunner(null); List completion = repl.completion(body, cursor, interpreterContext); return completion; }

Target:
public List<InterpreterCompletion> completion(String buffer, int cursor) { String lines[] = buffer.split(System.getProperty("line.separator")); if (lines.length > 0 && lines[0].startsWith("%") && cursor <= lines[0].trim().length()) { int idx = lines[0].indexOf(' '); if (idx < 0 || (idx > 0 && cursor <= idx)) { return getInterpreterCompletion(); } } String trimmedBuffer = buffer != null ? buffer.trim() : null; cursor = calculateCursorPosition(buffer, trimmedBuffer, cursor); String replName = getRequiredReplName(trimmedBuffer); String body = getScriptBody(trimmedBuffer); Interpreter repl = getRepl(replName); if (repl == null) { return null; } InterpreterContext interpreterContext = getInterpreterContextWithoutRunner(null); List completion = repl.completion(body, cursor, interpreterContext); return completion; }
Source:
public void mouseHover(MouseEvent e) { if ((getChartViewer().getWindowDuration() != 0) && (e != null)) { IAxis xAxis = getChart().getAxisSet().getXAxis(0); IAxis yAxis = getChart().getAxisSet().getYAxis(0); ISeries[] series = getChart().getSeriesSet().getSeries(); double smallestDistance = Double.MAX_VALUE; Parameter param = null; for (int k = 0; k < series.length; k++) { ISeries serie = series[k]; double[] xS = serie.getXSeries(); double[] yS = serie.getYSeries(); if ((xS == null) || (yS == null)) { continue; } for (int i = 0; i < xS.length; i++) { int xs = xAxis.getPixelCoordinate(xS[i]) - e.x; int ys = yAxis.getPixelCoordinate(yS[i]) - e.y; double currentDistance = Math.sqrt(xs * xs + ys * ys); if ((currentDistance < smallestDistance) && (currentDistance < HIGHLIGHT_RADIUS)) { smallestDistance = currentDistance; fHighlightX = xs + e.x; fHighlightY = ys + e.y; if (param == null) { param = new Parameter(); } param.setSeriesIndex(k); param.setDataIndex(i); } } } String tooltip = null; if (param != null) { tooltip = createToolTipText(param); if (tooltip != null) { fIsHighlight = true; getChart().redraw(); } } getChart().getPlotArea().setToolTipText(tooltip); } }

Target:
public void mouseHover(MouseEvent e) { if ((getChartViewer().getWindowDuration() != 0) && (e != null)) { IAxis xAxis = getChart().getAxisSet().getXAxis(0); IAxis yAxis = getChart().getAxisSet().getYAxis(0); ISeries[] series = getChart().getSeriesSet().getSeries(); double smallestDistance = Double.MAX_VALUE; Parameter param = null; for (int k = 0; k < series.length; k++) { ISeries serie = series[k]; double[] xS = serie.getXSeries(); double[] yS = serie.getYSeries(); if ((xS == null) || (yS == null)) { continue; } for (int i = 0; i < xS.length; i++) { int xs = xAxis.getPixelCoordinate(xS[i]) - e.x; int ys = yAxis.getPixelCoordinate(yS[i]) - e.y; double currentDistance = xs * xs + ys * ys; if ((currentDistance < smallestDistance) && (currentDistance < (HIGHLIGHT_RADIUS * HIGHLIGHT_RADIUS))) { smallestDistance = currentDistance; fHighlightX = xs + e.x; fHighlightY = ys + e.y; if (param == null) { param = new Parameter(); } param.setSeriesIndex(k); param.setDataIndex(i); } } } String tooltip = null; if (param != null) { tooltip = createToolTipText(param); if (tooltip != null) { fIsHighlight = true; getChart().redraw(); } } getChart().getPlotArea().setToolTipText(tooltip); } }
Source:
public void fetch(@NonNull final Intent intent) { checkNotNull(intent); final int repositoryId = intent.getIntExtra("id", -1); if (repositoryId > -1) { fetchGitHubRepository(repositoryId); } else { Log.e(TAG, "No repositoryId provided in the intent extras"); } }

Target:
public void fetch(@NonNull final Intent intent) { checkNotNull(intent); final int repositoryId = intent.getIntExtra("id", -1); if (repositoryId >= 0) { fetchGitHubRepository(repositoryId); } else { Log.e(TAG, "No repositoryId provided in the intent extras"); } }
Source:
private Platform() { final String platformOs = System.getProperty("os.name").toLowerCase(); if (platformOs.equals("linux")) { this.os = "linux"; } else if (platformOs.startsWith("mac os")) { this.os = "mac"; } else if (platformOs.startsWith("windows")) { this.os = "windows"; } else { this.os = platformOs; } final String platformArch = System.getProperty("os.arch"); if (platformArch.equals("x86_64") || platformArch.equals("amd64")) { this.arch = "64"; } else if (platformArch.equals("x86")) { this.arch = "32"; } else { this.arch = platformArch; } }

Target:
private Platform() { final String platformOs = System.getProperty("os.name").toLowerCase(); if (platformOs.startsWith("linux")) { os = "linux"; } else if (platformOs.startsWith("mac os")) { os = "mac"; } else if (platformOs.startsWith("windows")) { os = "windows"; } else { os = platformOs; } final String platformArch = System.getProperty("os.arch"); if (platformArch.equals("x86_64") || platformArch.equals("amd64")) { arch = "64"; } else if (platformArch.equals("x86") || platformArch.equals("i386")) { arch = "32"; } else { arch = platformArch; } }