auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public RevTag call() throws NoMessageException, UnmergedPathException, ConcurrentRefUpdateException, JGitInternalException, WrongRepositoryStateException { checkCallable(); RepositoryState state = repo.getRepositoryState(); processOptions(state); try { Tag newTag = new Tag(repo); newTag.setTag(name); newTag.setMessage(message); newTag.setObjId(id); ObjectInserter inserter = repo.newObjectInserter(); try { ObjectLoader object = repo.open(newTag.getObjId()); newTag.setType(Constants.typeString(object.getType())); ObjectId tagId = inserter.insert(Constants.OBJ_TAG, inserter.format(newTag)); newTag.setTagId(tagId); inserter.flush(); RevWalk revWalk = new RevWalk(repo); try { RevTag revTag = revWalk.parseTag(newTag.getTagId()); String refName = Constants.R_TAGS + newTag.getTag(); RefUpdate tagRef = repo.updateRef(refName); tagRef.setNewObjectId(newTag.getTagId()); tagRef.setForceUpdate(forceUpdate); Result updateResult = tagRef.update(); switch (updateResult) { case NEW: case FORCED: { return revTag; } default: throw new JGitInternalException(MessageFormat .format(JGitText.get().updatingRefFailed, Constants.HEAD, newTag.toString(), updateResult)); } } finally { revWalk.release(); } } finally { inserter.release(); } } catch (IOException e) { throw new JGitInternalException( JGitText.get().exceptionCaughtDuringExecutionOfTagCommand, e); } }

Target:
public RevTag call() throws JGitInternalException, NoHeadException { checkCallable(); RepositoryState state = repo.getRepositoryState(); processOptions(state); try { Tag newTag = new Tag(repo); newTag.setTag(name); newTag.setMessage(message); newTag.setAuthor(author); Ref head = repo.getRef(Constants.HEAD); if (head == null) throw new NoHeadException( JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported); if (id == null) { id = repo.resolve(Constants.HEAD + "^{commit}"); } newTag.setObjId(id); ObjectInserter inserter = repo.newObjectInserter(); try { ObjectLoader object = repo.open(newTag.getObjId()); newTag.setType(Constants.typeString(object.getType())); ObjectId tagId = inserter.insert(Constants.OBJ_TAG, inserter.format(newTag)); newTag.setTagId(tagId); inserter.flush(); RevWalk revWalk = new RevWalk(repo); try { RevTag revTag = revWalk.parseTag(newTag.getTagId()); String refName = Constants.R_TAGS + newTag.getTag(); RefUpdate tagRef = repo.updateRef(refName); tagRef.setNewObjectId(tagId); tagRef.setForceUpdate(forceUpdate); Result updateResult = tagRef.update(); switch (updateResult) { case NEW: case FORCED: return revTag; default: throw new JGitInternalException(MessageFormat .format(JGitText.get().updatingRefFailed, Constants.HEAD, newTag.toString(), updateResult)); } } finally { revWalk.release(); } } finally { inserter.release(); } } catch (IOException e) { throw new JGitInternalException( JGitText.get().exceptionCaughtDuringExecutionOfTagCommand, e); } }
Source:
public ThingEventFactory() { super(Sets.newHashSet(ThingStatusInfoEvent.TYPE, ThingStatusInfoChangedEvent.TYPE, ThingAddedEvent.TYPE, ThingRemovedEvent.TYPE, ThingUpdatedEvent.TYPE, ThingTriggerEvent.TYPE)); }

Target:
public ThingEventFactory() { super(Sets.newHashSet(ThingStatusInfoEvent.TYPE, ThingStatusInfoChangedEvent.TYPE, ThingAddedEvent.TYPE, ThingRemovedEvent.TYPE, ThingUpdatedEvent.TYPE, ChannelTriggeredEvent.TYPE)); }
Source:
public int hashCode() { int result = super.hashCode(); result = 31 * result + mName.hashCode(); result = 31 * result + mFlavorDimension.hashCode(); result = 31 * result + (mMinSdkVersion != null ? mMinSdkVersion.hashCode() : 0); result = 31 * result + (mTargetSdkVersion != null ? mTargetSdkVersion.hashCode() : 0); result = 31 * result + (mMaxSdkVersion != null ? mMaxSdkVersion.hashCode() : 0); result = 31 * result + (mRenderscriptTargetApi != null ? mRenderscriptTargetApi.hashCode() : 0); result = 31 * result + (mRenderscriptSupportModeEnabled != null ? mRenderscriptSupportModeEnabled .hashCode() : 0); result = 31 * result + (mRenderscriptNdkModeEnabled != null ? mRenderscriptNdkModeEnabled.hashCode() : 0); result = 31 * result + (mVersionCode != null ? mVersionCode.hashCode() : 0); result = 31 * result + (mVersionName != null ? mVersionName.hashCode() : 0); result = 31 * result + (mApplicationId != null ? mApplicationId.hashCode() : 0); result = 31 * result + (mTestApplicationId != null ? mTestApplicationId.hashCode() : 0); result = 31 * result + (mTestInstrumentationRunner != null ? mTestInstrumentationRunner .hashCode() : 0); result = 31 * result + (mTestHandleProfiling != null ? mTestHandleProfiling.hashCode() : 0); result = 31 * result + (mTestFunctionalTest != null ? mTestFunctionalTest.hashCode() : 0); result = 31 * result + (mSigningConfig != null ? mSigningConfig.hashCode() : 0); result = 31 * result + (mResourceConfiguration != null ? mResourceConfiguration.hashCode() : 0); return result; }

Target:
public int hashCode() { int result = super.hashCode(); result = 31 * result + mName.hashCode(); result = 31 * result + (mFlavorDimension != null ? mFlavorDimension.hashCode() : 0); result = 31 * result + (mMinSdkVersion != null ? mMinSdkVersion.hashCode() : 0); result = 31 * result + (mTargetSdkVersion != null ? mTargetSdkVersion.hashCode() : 0); result = 31 * result + (mMaxSdkVersion != null ? mMaxSdkVersion.hashCode() : 0); result = 31 * result + (mRenderscriptTargetApi != null ? mRenderscriptTargetApi.hashCode() : 0); result = 31 * result + (mRenderscriptSupportModeEnabled != null ? mRenderscriptSupportModeEnabled .hashCode() : 0); result = 31 * result + (mRenderscriptNdkModeEnabled != null ? mRenderscriptNdkModeEnabled.hashCode() : 0); result = 31 * result + (mVersionCode != null ? mVersionCode.hashCode() : 0); result = 31 * result + (mVersionName != null ? mVersionName.hashCode() : 0); result = 31 * result + (mApplicationId != null ? mApplicationId.hashCode() : 0); result = 31 * result + (mTestApplicationId != null ? mTestApplicationId.hashCode() : 0); result = 31 * result + (mTestInstrumentationRunner != null ? mTestInstrumentationRunner .hashCode() : 0); result = 31 * result + (mTestHandleProfiling != null ? mTestHandleProfiling.hashCode() : 0); result = 31 * result + (mTestFunctionalTest != null ? mTestFunctionalTest.hashCode() : 0); result = 31 * result + (mSigningConfig != null ? mSigningConfig.hashCode() : 0); result = 31 * result + (mResourceConfiguration != null ? mResourceConfiguration.hashCode() : 0); return result; }
Source:
public Object stringToAttributeValue(String value, String type) throws InternalErrorException { if (type.equals(ArrayList.class.getName()) || type.equals(LinkedHashMap.class.getName()) || type.equals("java.util.LargeArrayList")) { if (value != null && !value.isEmpty() && !value.endsWith(String.valueOf(AttributesManagerImpl.LIST_DELIMITER))) { value = value.concat(String.valueOf(AttributesManagerImpl.LIST_DELIMITER)); } } return BeansUtils.stringToAttributeValue(value, type); }

Target:
public Object stringToAttributeValue(String value, String type) throws InternalErrorException { if (type.equals(ArrayList.class.getName()) || type.equals(LinkedHashMap.class.getName()) || type.equals(BeansUtils.largeArrayListClassName)) { if (value != null && !value.isEmpty() && !value.endsWith(String.valueOf(AttributesManagerImpl.LIST_DELIMITER))) { value = value.concat(String.valueOf(AttributesManagerImpl.LIST_DELIMITER)); } } return BeansUtils.stringToAttributeValue(value, type); }
Source:
public ExtendedInMemoryUserDetailsManager myUserDetailsService() { ExtendedInMemoryUserDetailsManager extendedInMemoryUserDetailsManager = new ExtendedInMemoryUserDetailsManager(); List<GrantedAuthority> userAuthorities = new ArrayList<>(); userAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_USER")); extendedInMemoryUserDetailsManager.createUser(new User("user", "password", userAuthorities)); List<GrantedAuthority> adminAuthorities = new ArrayList<>(); adminAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_ADMIN")); extendedInMemoryUserDetailsManager.createUser(new User("admin", "password", adminAuthorities)); return extendedInMemoryUserDetailsManager; }

Target:
public UserDetails myUserDetailsService() { ExtendedInMemoryUserDetailsManager extendedInMemoryUserDetailsManager = new ExtendedInMemoryUserDetailsManager(); List<GrantedAuthority> userAuthorities = new ArrayList<>(); userAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_USER")); extendedInMemoryUserDetailsManager.createUser(new User("user", "password", userAuthorities)); List<GrantedAuthority> adminAuthorities = new ArrayList<>(); adminAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_ADMIN")); extendedInMemoryUserDetailsManager.createUser(new User("admin", "password", adminAuthorities)); return (UserDetails) extendedInMemoryUserDetailsManager; }
Source:
protected String processStaleCheckBatchRow(StaleCheckBatchRow staleCheckRow) { LOG.info("processStaleCheckBatchRow: Starting processStaleCheckBatchRow for: " + staleCheckRow.getLogData()); CheckReconciliation checkReconciliation = checkReconciliationDao.findByCheckNumber(staleCheckRow.getCheckNumber()); String processingError = validateStaleCheckBatchRow(staleCheckRow, checkReconciliation); if (StringUtils.isNotBlank(processingError)) { return processingError; } checkReconciliation.setStatus(CRConstants.STALE); java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(System.currentTimeMillis()); checkReconciliation.setStatusChangeDate(java.sql.Date.valueOf(currentTimestamp.toLocalDateTime().toLocalDate())); businessObjectService.save(checkReconciliation); return processingError; }

Target:
protected String processStaleCheckBatchRow(StaleCheckBatchRow staleCheckRow) { LOG.info("processStaleCheckBatchRow: Starting processStaleCheckBatchRow for: " + staleCheckRow.getLogData()); CheckReconciliation checkReconciliation = checkReconciliationDao.findByCheckNumber(staleCheckRow.getCheckNumber()); String processingError = validateStaleCheckBatchRow(staleCheckRow, checkReconciliation); if (StringUtils.isNotBlank(processingError)) { return processingError; } checkReconciliation.setStatus(CRConstants.STALE); checkReconciliation.setStatusChangeDate(dateTimeService.getCurrentSqlDate()); businessObjectService.save(checkReconciliation); return processingError; }
Source:
public void thePushSetupSmsShouldBeSetOnTheDevice(final Map<String, String> settings) throws Throwable { final SetPushSetupSmsAsyncRequest asyncRequest = SetPushSetupSmsRequestFactory.fromScenarioContext(); final SetPushSetupSmsResponse response = this.smartMeteringConfigurationClient .getSetPushSetupSmsResponse(asyncRequest); assertNotNull("SetPushSetupsSmsResponse was null", response); assertNotNull("SetPushSetupsSmsResponse result was null", response.getResult()); assertEquals("SetPushSetupsSmsResponse should be OK", OsgpResultType.OK, response.getResult()); final GetSpecificAttributeValueResponse specificAttributeValues = this.getSpecificAttributeValues(settings); assertNotNull("GetSpecificAttributeValuesResponse was null", specificAttributeValues); assertNotNull("GetSpecificAttributeValuesResponse result was null", response.getResult()); assertEquals("GetSpecificAttributeValuesResponse should be OK", OsgpResultType.OK, response.getResult()); final String hostAndPort = (String) ScenarioContext.current().get(PlatformSmartmeteringKeys.HOSTNAME) + ":" + ScenarioContext.current().get(PlatformSmartmeteringKeys.PORT); final byte[] expectedBytes = (hostAndPort.getBytes(StandardCharsets.US_ASCII)); final String expected = Arrays.toString(expectedBytes); final String actual = new String(specificAttributeValues.getAttributeValueData().toString()); assertTrue("PushSetupSms was not set on device", actual.toString().contains(expected)); }

Target:
public void thePushSetupSmsShouldBeSetOnTheDevice(final Map<String, String> settings) throws Throwable { final SetPushSetupSmsAsyncRequest setPushSetupSmsAsyncRequest = SetPushSetupSmsRequestFactory .fromScenarioContext(); final SetPushSetupSmsResponse setPushSetupSmsResponse = this.smartMeteringConfigurationClient .getSetPushSetupSmsResponse(setPushSetupSmsAsyncRequest); assertNotNull("SetPushSetupSmsResponse was null", setPushSetupSmsResponse); assertNotNull("SetPushSetupSmsResponse result was null", setPushSetupSmsResponse.getResult()); assertEquals("SetPushSetupSmsResponse should be OK", OsgpResultType.OK, setPushSetupSmsResponse.getResult()); final GetSpecificAttributeValueResponse specificAttributeValues = this.getSpecificAttributeValues(settings); assertNotNull("GetSpecificAttributeValuesResponse was null", specificAttributeValues); assertNotNull("GetSpecificAttributeValuesResponse result was null", specificAttributeValues.getResult()); assertEquals("GetSpecificAttributeValuesResponse should be OK", OsgpResultType.OK, specificAttributeValues.getResult()); final String hostAndPort = (String) ScenarioContext.current().get(PlatformSmartmeteringKeys.HOSTNAME) + ":" + ScenarioContext.current().get(PlatformSmartmeteringKeys.PORT); final byte[] expectedBytes = (hostAndPort.getBytes(StandardCharsets.US_ASCII)); final String expected = Arrays.toString(expectedBytes); final String actual = new String(specificAttributeValues.getAttributeValueData().toString()); assertTrue("PushSetupSms was not set on device", actual.toString().contains(expected)); }
Source:
public void onMovePageToList(long sourceReadingListId, @NonNull HistoryEntry entry) { bottomSheetPresenter.show(getChildFragmentManager(), MoveToReadingListDialog.newInstance(sourceReadingListId, entry.getTitle(), MOST_READ_ACTIVITY)); }

Target:
public void onMovePageToList(long sourceReadingListId, @NonNull HistoryEntry entry) { bottomSheetPresenter.show(getChildFragmentManager(), MoveToReadingListDialog.newInstance(sourceReadingListId, entry.getTitle(), NEWS_ACTIVITY)); }
Source:
private void display() throws Failure { final PrintWriter stdout = toPrintWriter(out); hooks.addChangeListener(listener, currentUser); try { while (!stdout.checkError()) { final Object output = queue.take(); if (output != null) { stdout.println(gson.toJson(output)); stdout.flush(); } if (dropped) { stdout.println(droppedOutputEvent); stdout.flush(); dropped = false; } } } catch (InterruptedException e) { } finally { hooks.removeChangeListener(listener); } }

Target:
private void display() throws Failure { final PrintWriter stdout = toPrintWriter(out); hooks.addChangeListener(listener, currentUser); try { while (!stdout.checkError()) { stdout.println(gson.toJson(queue.take())); stdout.flush(); if (dropped) { stdout.println(droppedOutputEvent); stdout.flush(); dropped = false; } } } catch (InterruptedException e) { } finally { hooks.removeChangeListener(listener); } }
Source:
public void purgeBatchedVersionPaths() { String paths[]; synchronized(purgeOldVersionPaths) { if (purgeOldVersionPaths.isEmpty()) { return; } paths = purgeOldVersionPaths.toArray(new String[purgeOldVersionPaths.size()]); purgeOldVersionPaths.clear(); } for (String path: paths) { try { purgeOldVersions(path); } catch (Exception e) { synchronized(purgeOldVersionPaths) { purgeOldVersionPaths.add(path); } log.warn("Failed to purge old versions of {}. Ignoring error.", value("path", path)); } } }

Target:
public void purgeBatchedVersionPaths() { String[] paths; synchronized(purgeOldVersionPaths) { if (purgeOldVersionPaths.isEmpty()) { return; } paths = purgeOldVersionPaths.toArray(new String[purgeOldVersionPaths.size()]); purgeOldVersionPaths.clear(); } for (String path: paths) { try { purgeOldVersions(path); } catch (Exception e) { synchronized(purgeOldVersionPaths) { purgeOldVersionPaths.add(path); } log.warn("Failed to purge old versions of {}. Ignoring error.", value("path", path)); } } }
Source:
private Patient updatePatientIdentifiers(Config config, Patient patient) { Validate.notNull(patient, "Patient cannot be null"); Validate.notEmpty(patient.getUuid(), "Patient Id may not be empty"); List<Identifier> identifiersList = patientResource.getPatientIdentifierList(config, patient.getUuid()); Patient updatedPatient; try { updatePatientIdentifiers(config, patient, identifiersList); updatedPatient = getPatientByUuid(config, patient.getUuid()); eventRelay.sendEventMessage(new MotechEvent(EventKeys.UPDATED_PATIENT_SUBJECT, EventHelper.patientParameters(updatedPatient))); } catch (HttpClientErrorException e) { throw new OpenMRSException("Failed to update OpenMRS patient with id: " + patient.getUuid(), e); } return updatedPatient; }

Target:
private Patient updatePatientIdentifiers(Config config, Patient patient) { Validate.notNull(patient, "Patient cannot be null"); Validate.notEmpty(patient.getUuid(), "Patient Id cannot be empty"); List<Identifier> identifiersList = patientResource.getPatientIdentifierList(config, patient.getUuid()); Patient updatedPatient; try { updatePatientIdentifiers(config, patient, identifiersList); updatedPatient = getPatientByUuid(config, patient.getUuid()); eventRelay.sendEventMessage(new MotechEvent(EventKeys.UPDATED_PATIENT_IDENTIFIERS_SUBJECT, EventHelper.patientParameters(updatedPatient))); } catch (HttpClientErrorException e) { throw new OpenMRSException("Failed to update OpenMRS patient's identifiers for patient with id: " + patient.getUuid(), e); } return updatedPatient; }
Source:
private void triggerMatchingPipelines(T event) { try { List<Pipeline> allPipelines = pipelineCache.getPipelinesSync(); List<Pipeline> matchingPipelines = eventHandler.getMatchingPipelines(event, allPipelines); matchingPipelines.forEach(p -> { recordMatchingPipeline(p); pipelineInitiator.startPipeline(p); }); } catch (TimeoutException e) { log.error("Failed to get pipeline configs", e); } }

Target:
private void triggerMatchingPipelines(T event) { try { List<Pipeline> allPipelines = pipelineCache.getPipelinesSync(); List<Pipeline> matchingPipelines = eventHandler.getMatchingPipelines(event, allPipelines); matchingPipelines.stream() .map(pipelinePostProcessorHandler::process) .forEach(p -> { recordMatchingPipeline(p); pipelineInitiator.startPipeline(p); }); } catch (TimeoutException e) { log.error("Failed to get pipeline configs", e); } }
Source:
public void eject(final String name) throws IOException { assert Paths.get(this.friends.getAbsolutePath(), name).toFile() .delete(); }

Target:
public void eject(final String name) { assert Paths.get(this.friends.getAbsolutePath(), name).toFile() .delete(); }
Source:
public static void registerSerde(String type, ComplexMetricSerde serde) { if (complexSerializers.containsKey(type)) { if (!complexSerializers.get(type).getClass().getCanonicalName().equals(serde.getClass().getCanonicalName())) { throw new ISE( "Incompatible serializer for type[%s] already exists. Expected [%s], found [%s].", type, serde.getClass().getName(), complexSerializers.get(type).getClass().getName() ); } } else { complexSerializers.put(type, serde); } }

Target:
public static void registerSerde(String type, ComplexMetricSerde serde) { if (complexSerializers.containsKey(type)) { if (!complexSerializers.get(type).getClass().getName().equals(serde.getClass().getName())) { throw new ISE( "Incompatible serializer for type[%s] already exists. Expected [%s], found [%s].", type, serde.getClass().getName(), complexSerializers.get(type).getClass().getName() ); } } else { complexSerializers.put(type, serde); } }
Source:
protected void selectExternalProvider() { Network network = getNetwork(); if (network.isExternal()) { for (Provider provider : (Iterable<Provider>) getExternalProviders().getItems()) { if (provider.getId().equals(network.getProvidedBy().getProviderId())) { getExternalProviders().setSelectedItem(provider); return; } } } }

Target:
protected void selectExternalProvider() { final Network network = getNetwork(); if (network.isExternal()) { getExternalProviders().setSelectedItem(Linq.firstOrDefault((Iterable<Provider>) getExternalProviders().getItems(), new Linq.IPredicate<Provider>() { @Override public boolean match(Provider provider) { return provider.getId().equals(network.getProvidedBy().getProviderId()); } })); } }
Source:
public static Map<EClass, Integer> getEClassRootElements(EPackage ePackage) { List<EClass> concreteClasses = getConcreteClasses(ePackage); if (ePackage != null) { String nsURI = ePackage.getNsURI(); EPackageMetaData metaData = DslCommonPlugin.INSTANCE.getEPackageMetaData(nsURI); List<EClass> roots = new ArrayList<>(); if (metaData != null && !metaData.getSuggestedRoots().isEmpty()) { roots = concreteClasses.stream().filter(c -> metaData.getSuggestedRoots().contains(c.getName())).collect(Collectors.toList()); } if (!roots.isEmpty()) { Integer defaultScore = 0; return roots.stream().collect(Collectors.toMap(eClass -> eClass, eClass -> defaultScore)); } } Map<EClass, Integer> inferRootElementsCandidates = inferRootElementsCandidates(ePackage, concreteClasses); return inferRootElementsCandidates; }

Target:
public static List<EClass> getEClassRootElements(EPackage ePackage) { List<EClass> concreteClasses = getConcreteClasses(ePackage); if (ePackage != null) { String nsURI = ePackage.getNsURI(); EPackageMetaData metaData = DslCommonPlugin.INSTANCE.getEPackageMetaData(nsURI); List<EClass> roots = new ArrayList<>(); if (metaData != null && !metaData.getSuggestedRoots().isEmpty()) { roots = concreteClasses.stream().filter(c -> metaData.getSuggestedRoots().contains(c.getName())).collect(Collectors.toList()); } if (!roots.isEmpty()) { return roots; } } Map<EClass, Integer> inferredRootElementsCandidates = inferRootElementsCandidates(ePackage, concreteClasses); List<EClass> sortedResults = new ArrayList<EClass>(); sortedResults.addAll(inferredRootElementsCandidates.keySet()); Collections.sort(sortedResults, new Comparator<EClass>() { @Override public int compare(EClass eClass1, EClass eClass2) { return inferredRootElementsCandidates.get(eClass2).compareTo(inferredRootElementsCandidates.get(eClass1)); } }); return sortedResults; }
Source:
private void setUpMediaWikiBaseUri(final EditTextPreference pref) { pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, final Object newValue) { SiteInfoClient siteInfoClient = new SiteInfoClient((String) newValue, getActivity()); siteInfoClient.request(new SiteInfoClient.Callback() { public void onSuccess(SiteInfo info) { pref.setText(info.general().server()); } }); return true; } }); }

Target:
private void setUpMediaWikiBaseUri(final EditTextPreference pref) { pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, final Object newValue) { if (getActivity() == null) { return true; } final ProgressDialog dialog = ProgressDialog.show(getActivity(), "", getActivity().getString(R.string.dialog_loading_siteinfo_wait), true); SiteInfoClient siteInfoClient = new SiteInfoClient((String) newValue); siteInfoClient.request(new SiteInfoClient.Callback() { public void onSuccess(SiteInfo info) { String server = info.general().server(); if (server.startsWith(" server = "https:" + server; } pref.setText(server); resetMediaWikiSettings(); dialog.hide(); } public void onFailure(Throwable t) { dialog.hide(); if (getActivity() == null) { return; } String message = t.getMessage(); if (t instanceof HttpStatusException && message == null) { message = Integer.toString(((HttpStatusException) t).code()); } showAlert(getActivity().getString(R.string.dialog_loading_siteinfo_failed, message), t); } }); return true; } }); }
Source:
public static void premain(String agentArgument, Instrumentation instrumentation) throws Exception { String[] args = agentArgument.split(":"); if (args.length < 2 || args.length > 3) { System.err.println("Usage: -javaagent:/path/to/JavaAgent.jar=[host:]<port>:<yaml configuration file>"); System.exit(1); } String host; int port; String file; if (args.length == 3) { port = Integer.parseInt(args[1]); host = args[0]; file = args[2]; } else { port = Integer.parseInt(args[0]); host = "localhost"; file = args[1]; } new JmxCollector(new File(file)).register(); DefaultExports.initialize(); QueuedThreadPool pool = new QueuedThreadPool(); pool.setDaemon(true); pool.setMaxThreads(10); pool.setName("jmx_exporter"); server = new Server(pool); ServerConnector connector = new ServerConnector(server); connector.setReuseAddress(true); connector.setHost(host); connector.setPort(port); server.setConnectors(new Connector[]{connector}); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); context.addFilter(GzipFilter.class, "/*", null); server.setHandler(context); context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics"); server.setStopAtShutdown(true); server.start(); }

Target:
public static void premain(String agentArgument, Instrumentation instrumentation) throws Exception { String[] args = agentArgument.split(":"); if (args.length < 2 || args.length > 3) { System.err.println("Usage: -javaagent:/path/to/JavaAgent.jar=[host:]<port>:<yaml configuration file>"); System.exit(1); } String host; int port; String file; if (args.length == 3) { port = Integer.parseInt(args[1]); host = args[0]; file = args[2]; } else { port = Integer.parseInt(args[0]); host = "0.0.0.0"; file = args[1]; } new JmxCollector(new File(file)).register(); DefaultExports.initialize(); QueuedThreadPool pool = new QueuedThreadPool(); pool.setDaemon(true); pool.setMaxThreads(10); pool.setName("jmx_exporter"); server = new Server(pool); ServerConnector connector = new ServerConnector(server); connector.setReuseAddress(true); connector.setHost(host); connector.setPort(port); server.setConnectors(new Connector[]{connector}); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); context.addFilter(GzipFilter.class, "/*", null); server.setHandler(context); context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics"); server.start(); }
Source:
private List<Long> findPipelineIds(String pipelineName, FeedModifier modifier, long cursor, int pageSize) { List<Long> ids; Map<String, Object> params = arguments("pipelineName", pipelineName) .and("cursor", cursor) .and("limit", pageSize).asMap(); ids = getSqlMapClientTemplate().queryForList("getPipelineIds" + modifier.suffix(), params); return ids; }

Target:
private List<Long> findPipelineIds(String pipelineName, FeedModifier modifier, long cursor, int pageSize) { Map<String, Object> params = arguments("pipelineName", pipelineName) .and("cursor", cursor) .and("limit", pageSize).asMap(); return (List<Long>) getSqlMapClientTemplate().queryForList("getPipelineIds" + modifier.suffix(), params); }
Source:
public KeyClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; }

Target:
public KeyClientBuilder retryPolicy(RetryPolicy retryPolicy) { Objects.requireNonNull(retryPolicy, "The retry policy cannot be bull"); this.retryPolicy = retryPolicy; return this; }
Source:
public static Image getCamoImage(String category, String name) { if (category == null || name == null) { return ImageUtil.failStandardImage(); } initializeCamos(); if (camoDirectory == null) { return ImageUtil.failStandardImage(); } try { if (category.equals(IPlayer.NO_CAMO)) { return colorCamoImage(PlayerColors.getColor(name)); } if (IPlayer.ROOT_CAMO.equals(category)) { category = ""; } Image image = (Image) camoDirectory.getItem(category, name); if (image != null) { return image; } } catch (Exception e) { e.printStackTrace(); } LOG.error(CamoManager.class, "Could not create camo image! Category: " + category + "; Name: " + name); return ImageUtil.failStandardImage(); }

Target:
public static Image getCamoImage(String category, String name) { if ((category == null) || (name == null)) { return ImageUtil.failStandardImage(); } initializeCamos(); if (camoDirectory == null) { return ImageUtil.failStandardImage(); } try { if (category.equals(IPlayer.NO_CAMO)) { return colorCamoImage(PlayerColors.getColor(name)); } if (IPlayer.ROOT_CAMO.equals(category)) { category = ""; } Image image = (Image) camoDirectory.getItem(category, name); if (image != null) { return image; } } catch (Exception e) { e.printStackTrace(); } MegaMek.getLogger().error(CamoManager.class, "Could not create camo image! Category: " + category + "; Name: " + name); return ImageUtil.failStandardImage(); }
Source:
public void receiveNoPin() { mySignerId = JPAKE_SIGNERID_RECEIVER; theirSignerId = JPAKE_SIGNERID_SENDER; jParty = new JPakeParty(mySignerId); jpakeMaxTries = MAX_TRIES_FIRST_MSG; createSecret(); prepareStagesAndStartWithPin(false); }

Target:
public void receiveNoPin() { mySignerId = JPAKE_SIGNERID_RECEIVER; theirSignerId = JPAKE_SIGNERID_SENDER; jParty = new JPakeParty(mySignerId); jpakeMaxTries = MAX_TRIES_FIRST_MSG; createSecret(); prepareReceiverStages(); runNextStage(); }
Source:
public HiveTableInstance createMutable(HiveTableDefinition tableDefinition, State state, TableHandle tableHandle) { TableName tableName = createMutableTableName(tableHandle); LOGGER.debug("creating mutable table {}", tableName); if (state == PREPARED) { return new HiveTableInstance(tableName, tableDefinition); } createTable(tableDefinition, tableName, Optional.empty()); if (tableDefinition.isPartitioned()) { int partitionId = 0; for (HiveTableDefinition.PartitionDefinition partitionDefinition : tableDefinition.getPartitionDefinitons()) { String partitionDataPath = getMutableTableHdfsPath(tableName, Optional.of(partitionId)); if (state == LOADED) { uploadTableData(partitionDataPath, partitionDefinition.getDataSource()); } queryExecutor.executeQuery(partitionDefinition.getAddPartitionTableDDL(tableName, partitionDataPath)); partitionId++; } } else if (state == LOADED) { String tableDataPath = getMutableTableHdfsPath(tableName, Optional.empty()); uploadTableData(tableDataPath, tableDefinition.getDataSource()); } if (state == LOADED && analyzeMutableTables && tableDefinition.getDataSource().getStatistics().isPresent()) { checkState(!tableDefinition.isPartitioned(), "Statisitcs are not yet supported for parititioned tables"); hiveThriftClient.setStatistics(tableName, tableDefinition.getDataSource().getStatistics().get()); } return new HiveTableInstance(tableName, tableDefinition); }

Target:
public HiveTableInstance createMutable(HiveTableDefinition tableDefinition, State state, TableHandle tableHandle) { TableName tableName = createMutableTableName(tableHandle); LOGGER.debug("creating mutable table {}", tableName); if (state == PREPARED) { return new HiveTableInstance(tableName, tableDefinition); } createTable(tableDefinition, tableName, Optional.empty()); if (tableDefinition.isPartitioned()) { int partitionId = 0; for (HiveTableDefinition.PartitionDefinition partitionDefinition : tableDefinition.getPartitionDefinitons()) { String partitionDataPath = getMutableTableHdfsPath(tableName, Optional.of(partitionId)); if (state == LOADED) { uploadTableData(partitionDataPath, partitionDefinition.getDataSource()); } queryExecutor.executeQuery(partitionDefinition.getAddPartitionTableDDL(tableName, partitionDataPath)); partitionId++; } } else if (state == LOADED) { String tableDataPath = getMutableTableHdfsPath(tableName, Optional.empty()); uploadTableData(tableDataPath, tableDefinition.getDataSource()); } if (state == LOADED && analyzeMutableTables && tableDefinition.getDataSource().getStatistics().isPresent()) { checkState(!tableDefinition.isPartitioned(), "Statisitcs are not supported for parititioned tables"); hiveThriftClient.setStatistics(tableName, tableDefinition.getDataSource().getStatistics().get()); } return new HiveTableInstance(tableName, tableDefinition); }
Source:
public Optional<Repository> findRepository(Class<? extends Message> entityStateClass) { if (!guard.hasRepository(entityStateClass)) { return Optional.empty(); } Optional<Repository> repository = guard.repositoryFor(entityStateClass); return repository; }

Target:
public Optional<Repository> findRepository(Class<? extends Message> entityStateClass) { if (!guard.hasRepository(entityStateClass)) { throw newIllegalStateException("No repository found for the entity state class `%s`.", entityStateClass.getName()); } Optional<Repository> repository = guard.repositoryFor(entityStateClass); return repository; }
Source:
private MappingParameters(Field field) { index = field.index(); store = field.store(); fielddata = field.fielddata(); type = field.type(); dateFormat = field.format(); datePattern = field.pattern(); analyzer = field.analyzer(); searchAnalyzer = field.searchAnalyzer(); normalizer = field.normalizer(); copyTo = field.copyTo(); ignoreAbove = field.ignoreAbove() >= 0 ? field.ignoreAbove() : null; coerce = field.coerce(); docValues = field.docValues(); Assert.isTrue(!((type == FieldType.Text || type == FieldType.Nested) && !docValues), "docValues false is not allowed for field type text"); ignoreMalformed = field.ignoreMalformed(); indexOptions = field.indexOptions(); indexPhrases = field.indexPhrases(); if (field.indexPrefixes().length > 0) { indexPrefixes = field.indexPrefixes()[0]; } norms = field.norms(); nullValue = field.nullValue(); positionIncrementGap = field.positionIncrementGap(); similarity = field.similarity(); termVector = field.termVector(); scalingFactor = field.scalingFactor(); maxShingleSize = field.maxShingleSize(); Assert.isTrue(type != FieldType.Search_As_You_Type || (maxShingleSize >= 2 && maxShingleSize <= 4), "maxShingleSize must be in inclusive range from 2 to 4 for field type search_as_you_type"); }

Target:
private MappingParameters(Field field) { index = field.index(); store = field.store(); fielddata = field.fielddata(); type = field.type(); dateFormat = field.format(); datePattern = field.pattern(); analyzer = field.analyzer(); searchAnalyzer = field.searchAnalyzer(); normalizer = field.normalizer(); copyTo = field.copyTo(); ignoreAbove = field.ignoreAbove() >= 0 ? field.ignoreAbove() : null; coerce = field.coerce(); docValues = field.docValues(); Assert.isTrue(!((type == FieldType.Text || type == FieldType.Nested) && !docValues), "docValues false is not allowed for field type text"); ignoreMalformed = field.ignoreMalformed(); indexOptions = field.indexOptions(); indexPhrases = field.indexPhrases(); if (field.indexPrefixes().length > 0) { indexPrefixes = field.indexPrefixes()[0]; } norms = field.norms(); nullValue = field.nullValue(); positionIncrementGap = field.positionIncrementGap(); similarity = field.similarity(); termVector = field.termVector(); scalingFactor = field.scalingFactor(); maxShingleSize = field.maxShingleSize() >= 0 ? field.maxShingleSize() : null; Assert.isTrue(type != FieldType.Search_As_You_Type || maxShingleSize == null || (maxShingleSize >= 2 && maxShingleSize <= 4), "maxShingleSize must be in inclusive range from 2 to 4 for field type search_as_you_type"); }
Source:
public void setSpicePluginImplEnabled(boolean enabled, String reason) { spicePluginImplRadioButton.setVisible(enabled); spicePluginImplRadioButton.setEnabled(enabled); if (!enabled) { spicePluginImplRadioButtonTooltip.setText(reason); } }

Target:
public void setSpicePluginImplEnabled(boolean enabled, String reason) { spicePluginImplRadioButton.setEnabled(enabled); if (!enabled) { spicePluginImplRadioButtonTooltip.setText(reason); } }
Source:
public void checkAttributeValue(PerunSessionImpl perunSession, Resource resource, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException { Facility facility = perunSession.getPerunBl().getResourcesManagerBl().getFacility(perunSession, resource); List<Attribute> attributes = perunSession.getPerunBl().getAttributesManagerBl().getAttributes(perunSession, facility); Boolean found = false; for (Attribute attr: attributes) { if (attr.getFriendlyName().equals("homeMountPoints")) { if(attr.getValue().equals(attribute.getValue())){ found = true; break; } } } if(!found){ throw new WrongAttributeValueException(attribute, "ReplicaSourcePath has to be the same as one of the F:D:homeMountPoints"); } }

Target:
public void checkAttributeValue(PerunSessionImpl perunSession, Resource resource, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException { if(attribute.getValue() == null) { throw new WrongAttributeValueException(attribute, resource, "This attribute can't be empty"); } Facility facility = perunSession.getPerunBl().getResourcesManagerBl().getFacility(perunSession, resource); Attribute facilityAttr = null; try { facilityAttr = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, facility, AttributesManager.NS_FACILITY_ATTR_DEF + ":homeMountPoints"); } catch (AttributeNotExistsException ex) { throw new InternalErrorException(ex); } if(facilityAttr.getValue() != null) { if (!((List<String>) facilityAttr.getValue()).containsAll((List<String>) attribute.getValue())) { throw new WrongReferenceAttributeValueException(attribute, facilityAttr, resource, facility, "ReplicaSourcePath has to be the same as one of the F:D:homeMountPoints"); } } }
Source:
public BytesInput compress(BytesInput bytes) throws IOException { compressedOutBuffer.reset(); CompressionOutputStream cos = hadoopCodec.createOutputStream(compressedOutBuffer, compressor); bytes.writeAllTo(cos); cos.finish(); cos.close(); return BytesInput.from(compressedOutBuffer); }

Target:
public BytesInput compress(BytesInput bytes) throws IOException { compressedOutBuffer.reset(); try (CompressionOutputStream cos = hadoopCodec.createOutputStream(compressedOutBuffer, compressor)) { bytes.writeAllTo(cos); return BytesInput.from(compressedOutBuffer); } }
Source:
public static Method getMethod(String methodName, String obfName, Class clazz, Class<?>... params) { Method method = null; try { method = clazz.getDeclaredMethod(obfName, params); } catch (NoSuchMethodException e) { EsteemedInnovation.logger.warn("[EI] Unable to find method " + methodName + " with its obfuscated name. Trying to" + " find it by its name " + methodName); try { method = clazz.getDeclaredMethod(methodName, params); } catch (NoSuchMethodException e1) { e1.printStackTrace(); boolean builderHasAMethod = false; StringBuilder builder = new StringBuilder(); for (Method method1 : clazz.getDeclaredMethods()) { if (builderHasAMethod) { builder.append(", "); } builder.append(method1.getName()); builderHasAMethod = true; } EsteemedInnovation.logger.warn("[EI] Unable to find " + methodName + " method in " + clazz.getName() + ".class. Available methods are: " + builder + ". Things are not going to work right."); } } return method; }

Target:
public static Method getMethod(String methodName, String obfName, Class clazz, Class<?>... params) { Method method = null; try { method = clazz.getDeclaredMethod(obfName, params); } catch (NoSuchMethodException e) { EsteemedInnovation.logger.warn("Unable to find method " + methodName + " with its obfuscated name. Trying to" + " find it by its name " + methodName); try { method = clazz.getDeclaredMethod(methodName, params); } catch (NoSuchMethodException e1) { e1.printStackTrace(); boolean builderHasAMethod = false; StringBuilder builder = new StringBuilder(); for (Method method1 : clazz.getDeclaredMethods()) { if (builderHasAMethod) { builder.append(", "); } builder.append(method1.getName()); builderHasAMethod = true; } EsteemedInnovation.logger.warn("Unable to find " + methodName + " method in " + clazz.getName() + ".class. Available methods are: " + builder + ". Things are not going to work right."); } } return method; }
Source:
public void processAsSingleReferenceSlice(final Slice slice) { final ReferenceContext sliceContext = slice.getReferenceContext(); if (sliceContext.isMultiRef()) { throw new SAMException("Expecting a single reference or unmapped slice." ); } try { if (sliceContext.isMappedSingleRef()) { final int reference = sliceContext.getSequenceId(); if (reference != currentReference) { advanceToReference(reference); } if (reference != currentReference) { throw new SAMException("Unexpected reference " + reference + " when constructing index for " + currentReference + " for record " + slice); } } indexBuilder.recordSliceIndexMetadata(slice); if (sliceContext.isMappedSingleRef()) { indexBuilder.processSingleReferenceSlice(slice); } } catch (final Exception e) { throw new SAMException("Exception creating BAM index for slice " + slice, e); } }

Target:
public void processAsSingleReferenceSlice(final Slice slice) { final ReferenceContext sliceContext = slice.getReferenceContext(); if (sliceContext.isMultiRef()) { throw new SAMException("Expecting a single reference or unmapped slice."); } if (sliceContext.isMappedSingleRef()) { final int reference = sliceContext.getSequenceId(); if (reference != currentReference) { advanceToReference(reference); } if (reference != currentReference) { throw new SAMException("Unexpected reference " + reference + " when constructing index for " + currentReference + " for record " + slice); } } indexBuilder.recordSliceIndexMetadata(slice); if (sliceContext.isMappedSingleRef()) { indexBuilder.processSingleReferenceSlice(slice); } }
Source:
public List<ScanResult> scan() { String contextPath = servletContext.getContextPath(); List<ScanResult> results = new ArrayList<>(super.scan()); File webInfClasses = null; ScanResult webInfBeansXML = null; try { URL beansXmlUrl = null; for (String resource : RESOURCES) { URL resourceUrl; resourceUrl = servletContext.getResource(resource); if (resourceUrl != null) { if (beansXmlUrl != null) { WeldServletLogger.LOG.foundBothConfiguration(beansXmlUrl); } else { beansXmlUrl = resourceUrl; } } } if (beansXmlUrl != null) { BeansXml beansXml = parseBeansXml(beansXmlUrl); if (accept(beansXml)) { webInfClasses = Servlets.getRealFile(servletContext, WEB_INF_CLASSES); if (webInfClasses != null) { webInfBeansXML = new ScanResult(beansXml, webInfClasses.getPath()).extractBeanArchiveId(contextPath, WEB_INF); } else { webInfBeansXML = new ScanResult(beansXml, WEB_INF_CLASSES); } } } } catch (MalformedURLException e) { throw WeldServletLogger.LOG.errorLoadingResources(e); } for (Iterator<ScanResult> iterator = results.iterator(); iterator.hasNext();) { ScanResult result = iterator.next(); String path = result.getBeanArchiveRef().toString(); if (new File(path).equals(webInfClasses)) { iterator.remove(); } else { result.extractBeanArchiveId(contextPath, WEB_INF); } } if (webInfBeansXML != null) { results.add(webInfBeansXML); } return ImmutableList.copyOf(results); }

Target:
public List<ScanResult> scan() { String contextPath = servletContext.getContextPath(); List<ScanResult> results = new ArrayList<>(super.scan()); File webInfClasses = null; ScanResult webInfBeansXML = null; try { URL beansXmlUrl = null; for (String resource : RESOURCES) { URL resourceUrl; resourceUrl = servletContext.getResource(resource); if (resourceUrl != null) { if (beansXmlUrl != null) { WeldServletLogger.LOG.foundBothConfiguration(beansXmlUrl); } else { beansXmlUrl = resourceUrl; } } } if (beansXmlUrl != null) { BeansXml beansXml = parseBeansXml(beansXmlUrl); if (accept(beansXml)) { webInfClasses = Servlets.getRealFile(servletContext, WEB_INF_CLASSES); if (webInfClasses != null) { webInfBeansXML = new ScanResult(beansXml, webInfClasses.getPath()).extractBeanArchiveId(contextPath, WEB_INF); } else { webInfBeansXML = new ScanResult(beansXml, WEB_INF_CLASSES); } } } } catch (MalformedURLException e) { throw WeldServletLogger.LOG.errorLoadingResources(e); } for (Iterator<ScanResult> iterator = results.iterator(); iterator.hasNext();) { ScanResult result = iterator.next(); String path = result.getBeanArchiveRef().toString(); if (path.contains(WEB_INF_CLASSES_FILE_PATH) || path.contains(WEB_INF_CLASSES) || new File(path).equals(webInfClasses)) { iterator.remove(); } else { result.extractBeanArchiveId(contextPath, WEB_INF); } } if (webInfBeansXML != null) { results.add(webInfBeansXML); } return ImmutableList.copyOf(results); }
Source:
private int columnIndexForParameter(List<String> columnNames, String parameterName) { int result = -1; for (int i = 0; i < columnNames.size(); i++) { for (ColumnNameMappingStrategy strategy : nameMappingStrategies) { if (strategy.nameMatches(parameterName, columnNames.get(i))) { if (result >= 0) { throw new IllegalArgumentException(String.format( "Constructor '%s' parameter '%s' matches multiple " + "columns: '%s' (%d) and '%s' (%d)", constructor, parameterName, columnNames.get(result), result, columnNames.get(i), i)); } result = i; break; } } } if (result >= 0) { return result; } throw new IllegalArgumentException("Constructor '" + constructor + "' parameter '" + parameterName + "' has no column in the result set. Verify that the Java " + "compiler is confiured to emit parameter names, " + "that your result set has the columns expect, " + "or annotate the parameter names explicitly with @Bean"); }

Target:
private int columnIndexForParameter(List<String> columnNames, String parameterName) { int result = -1; for (int i = 0; i < columnNames.size(); i++) { for (ColumnNameMappingStrategy strategy : nameMappingStrategies) { if (strategy.nameMatches(parameterName, columnNames.get(i))) { if (result >= 0) { throw new IllegalArgumentException(String.format( "Constructor '%s' parameter '%s' matches multiple " + "columns: '%s' (%d) and '%s' (%d)", constructor, parameterName, columnNames.get(result), result, columnNames.get(i), i)); } result = i; break; } } } if (result >= 0) { return result; } throw new IllegalArgumentException("Constructor '" + constructor + "' parameter '" + parameterName + "' has no column in the result set. Verify that the Java " + "compiler is configured to emit parameter names, " + "that your result set has the columns expected, " + "or annotate the parameter names explicitly with @ColumnName"); }
Source:
public Iterable<Language> languages() { return new ArrayList<Language>(0); }

Target:
public Iterable<Language> languages() { final List<Language> languages = new ArrayList<Language>(0); final int java = 999; languages.add(new RtLanguage("Java", java)); final int php = 888; languages.add(new RtLanguage("PHP", php)); final int ruby = 777; languages.add(new RtLanguage("Ruby", ruby)); return languages; }
Source:
public Response remove() { get(); return performAction(VdcActionType.UnlabelNic, new LabelNicParameters(parent.getNicId(), id)); }

Target:
public Response remove() { get(); return performAction(VdcActionType.RemoveVfsConfigLabel, new VfsConfigLabelParameters(parent.getNicId(), id)); }