auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static String getSDKLocation() throws CoreException { String sdkLocation = Platform.getPreferencesService().getString( THYM_UI_ID, WPConstants.WINDOWS_PHONE_SDK_LOCATION_PREF, null, null); if (sdkLocation == null) { File location = detectSDK(); if (location.exists()) { sdkLocation = location.getAbsolutePath(); IEclipsePreferences prefs = InstanceScope.INSTANCE .getNode(THYM_UI_ID); prefs.put(WPConstants.WINDOWS_PHONE_SDK_LOCATION_PREF, sdkLocation); } } return sdkLocation; }

Target:
public static String getSDKLocation() throws CoreException { String sdkLocation = Platform.getPreferencesService().getString( THYM_UI_ID, WPConstants.WINDOWS_PHONE_SDK_LOCATION_PREF, null, null); if (sdkLocation == null) { File location = detectSDK(); if (location != null && location.exists()) { sdkLocation = location.getAbsolutePath(); IEclipsePreferences prefs = InstanceScope.INSTANCE .getNode(THYM_UI_ID); prefs.put(WPConstants.WINDOWS_PHONE_SDK_LOCATION_PREF, sdkLocation); } } return sdkLocation; }
Source:
public boolean isAllowed(@NonNull String[] allowedGroups) { for (String allowedGroup: allowedGroups) { for (String group: groups) { if (allowedGroup.equals(group)) { return true; } } } return false; }

Target:
public boolean isAllowed(@NonNull String[] allowedGroups) { for (String allowedGroup: allowedGroups) { for (String group: groups) { if (allowedGroup != null && allowedGroup.equals(group)) { return true; } } } return false; }
Source:
public void initialize() { logger.debug("Initialize OpenWeatherMap API handler."); OpenWeatherMapAPIConfiguration config = getOpenWeatherMapAPIConfig(); boolean configValid = true; if (StringUtils.trimToNull(config.getApikey()) == null) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "@text/offline.conf-error-missing-apikey"); configValid = false; } if (config.getRefreshIntervall() != null && config.getRefreshIntervall() < 10) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "@text/offline.conf-error-not-supported-refreshIntervall"); configValid = false; } if (config.getLanguage() != null) { final String language = StringUtils.trimToEmpty(config.getLanguage()); if (!OpenWeatherMapAPIConfiguration.SUPPORTED_LANGUAGES.contains(language.toLowerCase())) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "@text/offline.conf-error-not-supported-language"); configValid = false; } } if (configValid) { connection = new OpenWeatherMapConnection(this, httpClient); if (refreshJob == null || refreshJob.isCancelled()) { logger.debug("Start refresh job at intervall min.", config.getRefreshIntervall()); refreshJob = scheduler.scheduleWithFixedDelay(this::updateThings, 1, config.getRefreshIntervall(), TimeUnit.MINUTES); } updateStatus(ThingStatus.UNKNOWN); } }

Target:
public void initialize() { logger.debug("Initialize OpenWeatherMap API handler."); config = getConfigAs(OpenWeatherMapAPIConfiguration.class); boolean configValid = true; if (StringUtils.trimToNull(config.getApikey()) == null) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "@text/offline.conf-error-missing-apikey"); configValid = false; } int refreshInterval = config.getRefreshInterval(); if (refreshInterval < 10) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "@text/offline.conf-error-not-supported-refreshInterval"); configValid = false; } String language = config.getLanguage(); if (language != null) { language = StringUtils.trimToEmpty(language); if (!OpenWeatherMapAPIConfiguration.SUPPORTED_LANGUAGES.contains(language.toLowerCase())) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "@text/offline.conf-error-not-supported-language"); configValid = false; } } else { language = localeProvider.getLocale().getLanguage(); if (OpenWeatherMapAPIConfiguration.SUPPORTED_LANGUAGES.contains(language)) { logger.debug("Language set to '{}'.", language); Configuration editConfig = editConfiguration(); editConfig.put(CONFIG_LANGUAGE, language); updateConfiguration(editConfig); } } if (configValid) { connection = new OpenWeatherMapConnection(this, httpClient); updateStatus(ThingStatus.UNKNOWN); if (refreshJob == null || refreshJob.isCancelled()) { logger.debug("Start refresh job at interval min.", refreshInterval); refreshJob = scheduler.scheduleWithFixedDelay(this::updateThings, INITIAL_DELAY_IN_SECONDS, TimeUnit.MINUTES.toSeconds(refreshInterval), TimeUnit.SECONDS); } } }
Source:
public CloudResource build(GcpContext context, AuthenticatedContext auth, Group group, Network network, Security security, CloudResource buildableResource) throws Exception { String projectId = context.getProjectId(); ComputeRequest<Operation> firewallRequest = StringUtils.isNotBlank(group.getSecurity().getCloudSecurityId()) && isExistingNetwork(network) ? updateExistingFirewallForNewTargets(context, auth, group) : createNewFirewallRule(context, auth, group, network, security, buildableResource, projectId); try { Operation operation = firewallRequest.execute(); if (operation.getHttpErrorStatusCode() != null) { throw new GcpResourceException(operation.getHttpErrorMessage(), resourceType(), buildableResource.getName()); } return createOperationAwareCloudResource(buildableResource, operation); } catch (GoogleJsonResponseException e) { throw new GcpResourceException(checkException(e), resourceType(), buildableResource.getName()); } }

Target:
public CloudResource build(GcpContext context, AuthenticatedContext auth, Group group, Network network, Security security, CloudResource buildableResource) throws Exception { String projectId = context.getProjectId(); ComputeRequest<Operation> firewallRequest = (group.getSecurity() != null && StringUtils.isNotBlank(group.getSecurity().getCloudSecurityId()) && isExistingNetwork(network)) ? updateExistingFirewallForNewTargets(context, auth, group) : createNewFirewallRule(context, auth, group, network, security, buildableResource, projectId); try { Operation operation = firewallRequest.execute(); if (operation.getHttpErrorStatusCode() != null) { throw new GcpResourceException(operation.getHttpErrorMessage(), resourceType(), buildableResource.getName()); } return createOperationAwareCloudResource(buildableResource, operation); } catch (GoogleJsonResponseException e) { throw new GcpResourceException(checkException(e), resourceType(), buildableResource.getName()); } }
Source:
public void add(Integer art_id, Integer branchId, Integer transactionId) { this.branchId = branchId; entries.add(new Entry(art_id, branchId, transactionId)); }

Target:
public void add(Integer art_id, Integer branchId, Integer transactionId) { entries.add(new Entry(art_id, branchId, transactionId)); }
Source:
public void start(ComponentContext context) { if (Framework.isBooleanPropertyTrue(CLUSTERING_ENABLED_PROP)) { String nodeId = Framework.getProperty(NODE_ID_PROP); if (StringUtils.isBlank(nodeId)) { nodeId = String.valueOf(RANDOM.nextLong()); log.warn("Missing cluster node id configuration, please define it explicitly " + "(usually through repository.clustering.id). Using random cluster node id instead: " + nodeId); } else { nodeId = nodeId.trim(); } invalidator = new CachePubSubInvalidator(); invalidator.initialize(CACHE_INVAL_PUBSUB_TOPIC, nodeId); log.info("Registered cache invalidator for node: " + nodeId); } else { log.info("No cache invalidator registered"); } registry.getCacheDescriptors().forEach(this::startCacheDescriptor); }

Target:
public void start(ComponentContext context) { if (Framework.isBooleanPropertyTrue(CLUSTERING_ENABLED_PROP)) { String nodeId = Framework.getProperty(NODE_ID_PROP); if (StringUtils.isBlank(nodeId)) { nodeId = String.valueOf(RANDOM.nextLong()); log.warn("Missing cluster node id configuration, please define it explicitly " + "(usually through repository.clustering.id). Using random cluster node id instead: " + nodeId); } else { nodeId = nodeId.trim(); } invalidator = new CachePubSubInvalidator(); invalidator.initialize(CACHE_INVAL_PUBSUB_TOPIC, nodeId); log.info("Registered cache invalidator for node: " + nodeId); } else { log.info("Not registering a cache invalidator because clustering is not enabled"); } registry.getCacheDescriptors().forEach(this::startCacheDescriptor); }
Source:
public void doDownload(DynamicForm form){ Task task = this.parentController.getSelectedTask(); if(task != null){ String taskId = task.getName(); form.getField("taskId").setValue(taskId); String jobId = Long.toString(task.getJobId()); form.getField("jobId").setValue(jobId); DownloadOption dlOption = this.model.getDownloadOption(); form.getField("media").setValue(dlOption.formDownload); form.submitForm(); } }

Target:
public void doDownload(DynamicForm form){ Task task = this.parentController.getSelectedTask(); if(task != null){ String taskId = task.getName(); form.getField(ResultView.taskIdFieldName).setValue(taskId); String jobId = Long.toString(task.getJobId()); form.getField(ResultView.jobIdFieldName).setValue(jobId); DownloadOption dlOption = this.model.getDownloadOption(); form.getField(ResultView.mediaFieldName).setValue(dlOption.formDownload); form.submitForm(); } }
Source:
public void set_cmd_status_to_error_if_got_exception_on_dispatching() { final Command cmd = Given.Command.createProject(); final CommandId commandId = getId(cmd); final Exception exception = new Exception(newUuid()); givenThrowingAggregate(exception, cmd); repositorySpy.dispatch(cmd); verify(commandStore).updateStatus(commandId, exception); }

Target:
public void set_cmd_status_to_error_if_got_exception_on_dispatching() { final Exception exception = new Exception(newUuid()); final CommandId id = dispatchCmdToAggregateThrowing(exception); verify(commandStore).updateStatus(id, exception); }
Source:
protected Map<Guid, Guid> addAllTemplateDisks() { CreateAllTemplateDisksParameters parameters = new CreateAllTemplateDisksParameters(getVm() != null ? getVmId() : Guid.Empty); parameters.setVmTemplateId(getVmTemplateId()); parameters.setVmTemplateName(getVmTemplateName()); parameters.setDiskInfoDestinationMap(diskInfoDestinationMap); parameters.setTargetDiskIds(targetDiskIds); parameters.setCopyVolumeType( !getParameters().isSealTemplate() ? CopyVolumeType.SharedVol : CopyVolumeType.LeafVol); parameters.setParentCommand(getActionType()); parameters.setParentParameters(getParameters()); parameters.setEndProcedure(EndProcedure.COMMAND_MANAGED); VdcReturnValueBase returnValue = runInternalAction( getAddAllTemplateDisksActionType(), parameters, ExecutionHandler.createDefaultContextForTasks(getContext())); if (!returnValue.getSucceeded()) { throw new EngineException(returnValue.getFault().getError(), returnValue.getFault().getMessage()); } return returnValue.getActionReturnValue(); }

Target:
protected Map<Guid, Guid> addAllTemplateDisks() { CreateAllTemplateDisksParameters parameters = new CreateAllTemplateDisksParameters(getVm() != null ? getVmId() : Guid.Empty); parameters.setVmTemplateId(getVmTemplateId()); parameters.setVmTemplateName(getVmTemplateName()); parameters.setDiskInfoDestinationMap(diskInfoDestinationMap); parameters.setTargetDiskIds(targetDiskIds); if (getParameters().isSealTemplate()) { parameters.setCopyVolumeType(CopyVolumeType.LeafVol); } parameters.setParentCommand(getActionType()); parameters.setParentParameters(getParameters()); parameters.setEndProcedure(EndProcedure.COMMAND_MANAGED); VdcReturnValueBase returnValue = runInternalAction( getAddAllTemplateDisksActionType(), parameters, ExecutionHandler.createDefaultContextForTasks(getContext())); if (!returnValue.getSucceeded()) { throw new EngineException(returnValue.getFault().getError(), returnValue.getFault().getMessage()); } return returnValue.getActionReturnValue(); }
Source:
private static int getIndexOfFileSeparator(String string) { int index = string.indexOf('/'); if (index == -1) { return string.indexOf('\\'); } return index; }

Target:
private static int getIndexOfFileSeparator(String string) { int index = string.indexOf('/'); return index == -1 ? string.indexOf('\\') : index; }
Source:
static String joinTags(Set<String> tags) { if (tags == null || tags.isEmpty()) { return ""; } StringBuilder sb = new StringBuilder(); boolean first = true; for (String tag : tags) { if (TextUtils.isEmpty(tag)) { continue; } if (first) { first = false; } else { sb.append(TAG_SEPARATOR); } sb.append(tag.trim().replaceAll(TAG_SEPARATOR, "_")); } return sb.toString(); }

Target:
static String joinTags(Set<String> tags) { for (String t : tags) { t.replaceAll(" ", "_"); } return TextUtils.join(" ", tags); }
Source:
private void registerMbean() { ObjectName objectName = null; MBeanServer mBeanServer = null; try { objectName = new ObjectName(Geocoding.class.getName() + ":service=geocoding"); mBeanServer = ManagementFactory.getPlatformMBeanServer(); } catch (MalformedObjectNameException e) { LOGGER.info("Unable to create Geocoding Configuration MBean.", e); } if (mBeanServer != null) { try { try { mBeanServer.registerMBean(this, objectName); LOGGER.debug( "Registered Geocoding Configuration MBean under object name: {}", objectName); } catch (InstanceAlreadyExistsException e) { mBeanServer.unregisterMBean(objectName); mBeanServer.registerMBean(this, objectName); LOGGER.debug("Re-registered Geocoding Configuration MBean"); } } catch (Exception e) { LOGGER.info("Could not register MBean [{}].", objectName, e); } } }

Target:
private void registerMbean() { ObjectName objectName = null; MBeanServer mBeanServer = null; try { objectName = new ObjectName(Geocoding.class.getName() + ":service=geocoding"); mBeanServer = ManagementFactory.getPlatformMBeanServer(); } catch (MalformedObjectNameException e) { LOGGER.info("Unable to create Geocoding Configuration MBean.", e); } if (mBeanServer != null) { try { try { mBeanServer.registerMBean(this, objectName); LOGGER.debug( "Registered Geocoding Configuration MBean under object name: {}", objectName); } catch (InstanceAlreadyExistsException e) { mBeanServer.unregisterMBean(objectName); mBeanServer.registerMBean(this, objectName); LOGGER.debug("Re-registered Geocoding Configuration MBean"); } } catch (Exception e) { LOGGER.info("Could not register MBean [{}].", objectName); } } }
Source:
public void visitMethodInvocation(MethodInvocationTree tree) { if (this.owner == tree.symbol().owner()) { return; } Arguments args = tree.arguments(); if (args.isEmpty()) { return; } args.stream().filter(arg -> is(arg, "this")).forEach(expr -> reportIssue(expr, REPORT)); }

Target:
public void visitMethodInvocation(MethodInvocationTree tree) { if (this.owner == tree.symbol().owner()) { return; } tree.arguments().stream().filter(this::isThis).forEach(this::report); super.visitMethodInvocation(tree); }
Source:
private boolean hasAnyFilter(int columnIndex) { return columnToScore.entrySet().contains(columnIndex) || filterFunctionInputs.contains(columnIndex); }

Target:
private boolean hasAnyFilter(int columnIndex) { return columnsWithFilterScores.containsKey(columnIndex) || filterFunctionInputs.contains(columnIndex); }
Source:
private static <T> List<T> getMapFields(List<Map<String, String>> results, Class classToUse) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchFieldException, ParseException { List<T> ret; Map<String, String> properties; ret = new ArrayList<>(); for (final Map<String, String> map : results) { Constructor<?> ctor = classToUse.getConstructor(); final T object = (T) ctor.newInstance(); properties = map.entrySet().stream().collect(Collectors .toMap(entry -> CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, entry.getKey()), entry ->map.get(entry.getKey()))); for (final String property: properties.keySet()){ if (properties.get(property) != null){ if (isFieldPresent(classToUse, String.class, property)){ PropertyUtils.setProperty(object, property, properties.get(property)); }else if (isFieldPresent(classToUse, Integer.TYPE, property)){ PropertyUtils.setProperty(object, property, Integer.parseInt(properties.get(property))); }else if (isFieldPresent(classToUse, Boolean.TYPE, property)){ PropertyUtils.setProperty(object, property, Boolean.parseBoolean(properties.get(property))); }else if (isFieldPresent(classToUse, Date.class, property)){ PropertyUtils.setProperty(object, property, df.parse(properties.get(property))); }else{ Logger.warn(classToUse, "Property " + property + "not set for " + classToUse.getName()); } } } ret.add(object); } return ret; }

Target:
private static <T> List<T> getMapFields(List<Map<String, String>> results, Class classToUse) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchFieldException, ParseException { List<T> ret; Map<String, String> properties; ret = new ArrayList<>(); for (final Map<String, String> map : results) { Constructor<?> ctor = classToUse.getConstructor(); final T object = (T) ctor.newInstance(); properties = map.entrySet().stream().collect(Collectors .toMap(entry -> CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, entry.getKey()), entry ->map.get(entry.getKey()))); for (final Entry entry: properties.entrySet()){ String property = (String) entry.getKey(); if (properties.get(property) != null){ if (isFieldPresent(classToUse, String.class, property)){ PropertyUtils.setProperty(object, property, properties.get(property)); }else if (isFieldPresent(classToUse, Integer.TYPE, property)){ PropertyUtils.setProperty(object, property, Integer.parseInt(properties.get(property))); }else if (isFieldPresent(classToUse, Boolean.TYPE, property)){ PropertyUtils.setProperty(object, property, Boolean.parseBoolean(properties.get(property))); }else if (isFieldPresent(classToUse, Date.class, property)){ PropertyUtils.setProperty(object, property, df.parse(properties.get(property))); }else{ Logger.warn(classToUse, "Property " + property + "not set for " + classToUse.getName()); } } } ret.add(object); } return ret; }
Source:
private void processFailure(Exception e) { if (client != null) { hostLocationProvider.reportFailedHost(client.getHostLocationHandle(), e); this.close(); } }

Target:
private void processFailure(Exception e) { if (client != null) { client.getHostLocationHandle().reportFailure(e); this.close(); } }
Source:
public IndexedFloats getFloatRow() { throw new UnsupportedOperationException("AAAAA"); }

Target:
public IndexedFloats getFloatRow() { return new IndexedFloats() { @Override public int size() { return 1; } @Override public float get(int index) { return 0.0f; } @Override public void fill(int index, float[] toFill) { throw new UnsupportedOperationException("NullDimensionSelector does not support fill"); } @Override public void close() throws IOException { } }; }
Source:
protected void applyDefaultRequestHeaders(Request request) { request.getHeaders().setAccept(java.util.Collections.singletonList(MediaType.APPLICATION_JSON)); List<String> stormpathAgents = request.getHeaders().get(STORMPATH_AGENT); if (stormpathAgents != null && stormpathAgents.size() > 0) { String stormpathAgent = Strings.arrayToDelimitedString(stormpathAgents.toArray(), " "); request.getHeaders().set("User-Agent", stormpathAgent + " " + USER_AGENT_STRING); } else { request.getHeaders().set("User-Agent", USER_AGENT_STRING); } if (request.getHeaders().getContentType() == null) { if (request.getBody() != null) { request.getHeaders().setContentType(MediaType.APPLICATION_JSON); } } }

Target:
protected void applyDefaultRequestHeaders(Request request) { request.getHeaders().setAccept(java.util.Collections.singletonList(MediaType.APPLICATION_JSON)); Map<String, List<String>> headerMap = HttpHeadersHolder.get(); String stormpathAgentHeaderName = STORMPATH_AGENT.toLowerCase(); if (headerMap != null && headerMap.get(stormpathAgentHeaderName) != null) { List<String> stormpathAgents = headerMap.get(stormpathAgentHeaderName); if (stormpathAgents != null && stormpathAgents.size() > 0) { String stormpathAgent = Strings.arrayToDelimitedString(stormpathAgents.toArray(), " "); request.getHeaders().set("User-Agent", stormpathAgent + " " + USER_AGENT_STRING); } } else { request.getHeaders().set("User-Agent", USER_AGENT_STRING); } if (request.getHeaders().getContentType() == null) { if (request.getBody() != null) { request.getHeaders().setContentType(MediaType.APPLICATION_JSON); } } }
Source:
public ClientReferrerFilter(final ReferringInformation referringInformation, @Nullable final String serviceName) { final ImmutableMap.Builder<String, List<Object>> builder = ImmutableMap.builder(); if (referringInformation.getReferrringHost() != null) { builder.put(OTHeaders.REFERRING_HOST, ImmutableList.of(referringInformation.getReferrringHost())); } if (referringInformation.getReferringEnvironment() != null) { builder.put(OTHeaders.REFERRING_ENV, ImmutableList.of(referringInformation.getReferringEnvironment())); } if (serviceName != null) { builder.put(OTHeaders.REFERRING_SERVICE, ImmutableList.of(serviceName)); } referrerHeaders = builder.build(); if (isActive()) { LOG.info("on outgoing jax-rs requests, will set headers: {}", referrerHeaders); } else { LOG.warn("no headers found for outgoing jax-rs requests"); } }

Target:
public ClientReferrerFilter(final ReferringInformation referringInformation, @Nullable final String serviceName) { final ImmutableMap.Builder<String, List<Object>> builder = ImmutableMap.builder(); if (referringInformation.getReferringHost() != null) { builder.put(OTHeaders.REFERRING_HOST, ImmutableList.of(referringInformation.getReferringHost())); } if (referringInformation.getReferringEnvironment() != null) { builder.put(OTHeaders.REFERRING_ENV, ImmutableList.of(referringInformation.getReferringEnvironment())); } if (serviceName != null) { builder.put(OTHeaders.REFERRING_SERVICE, ImmutableList.of(serviceName)); } referrerHeaders = builder.build(); if (isActive()) { LOG.info("on outgoing jax-rs requests, will set headers: {}", referrerHeaders); } else { LOG.warn("no headers found for outgoing jax-rs requests"); } }
Source:
public void testRecovery_ClosedStateTransition() { assertEquals("Delayed service is down", monitoringService.delayedServiceResponse()); assertEquals("OPEN", delayedServiceCircuitBreaker.getState()); try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } assertEquals("HALF_OPEN", delayedServiceCircuitBreaker.getState()); assertEquals("Delayed service is working", monitoringService.delayedServiceResponse()); assertEquals("CLOSED", delayedServiceCircuitBreaker.getState()); }

Target:
public void testRecovery_ClosedStateTransition() { assertEquals("Delayed service is down", monitoringService.delayedServiceResponse()); assertEquals("OPEN", delayedServiceCircuitBreaker.getState()); try { LOGGER.info("Waiting 4s for delayed service to become responsive"); Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } assertEquals("HALF_OPEN", delayedServiceCircuitBreaker.getState()); assertEquals("Delayed service is working", monitoringService.delayedServiceResponse()); assertEquals("CLOSED", delayedServiceCircuitBreaker.getState()); }
Source:
public void testOver9000() { testAssertOkLines(true, "package Vegeta", " native testSuccess()", " class Scouter", " static int size = 0", " construct()", " size++", "", " init", " for i = 0 to 20000", " new Scouter()", " if Scouter.size == 20001", " testSuccess()", "endpackage" ); }

Target:
public void testOver9000() { testAssertOkLines(true, "package Vegeta", " native testSuccess()", " class PowerLevel", " static int amount = 0", " construct()", " amount++", "", " init", " for i = 0 to 20000", " new PowerLevel()", " if PowerLevel.amount > 9000 and PowerLevel.amount == 20001", " testSuccess()", "endpackage" ); }
Source:
public BitmapIndexSeeker getBitmapIndexSeeker(String dimension) { final Column column = input.getColumn(dimension); if (column == null) { return new EmptyBitmapIndexSeeker(); } final BitmapIndex bitmaps = column.getBitmapIndex(); if (bitmaps == null) { return new EmptyBitmapIndexSeeker(); } final Indexed<String> dimSet = getDimValueLookup(dimension); return new BitmapIndexSeeker() { private int currIndex = 0; private String currVal = null; private String lastVal = null; @Override public IndexedInts seek(String value) { if (dimSet == null || dimSet.size() == 0) { return new EmptyIndexedInts(); } if (lastVal != null) { if (GenericIndexed.STRING_STRATEGY.compare(value, lastVal) <= 0) { throw new ISE("Value[%s] is less than the last value[%s] I have, cannot be.", value, lastVal); } return new EmptyIndexedInts(); } if (currVal == null) { if(currIndex == dimSet.size()) { return new EmptyIndexedInts(); } currVal = dimSet.get(currIndex); } int compareResult = GenericIndexed.STRING_STRATEGY.compare(currVal, value); if (compareResult == 0) { IndexedInts ret = new BitmapCompressedIndexedInts(bitmaps.getBitmap(currIndex)); ++currIndex; if (currIndex == dimSet.size()) { lastVal = value; } else { currVal = dimSet.get(currIndex); } return ret; } else if (compareResult < 0) { throw new ISE("Skipped currValue[%s], currIndex[%,d]; incoming value[%s]", currVal, currIndex, value); } else { return new EmptyIndexedInts(); } } }; }

Target:
public BitmapIndexSeeker getBitmapIndexSeeker(String dimension) { final Column column = input.getColumn(dimension); if (column == null) { return new EmptyBitmapIndexSeeker(); } final BitmapIndex bitmaps = column.getBitmapIndex(); if (bitmaps == null) { return new EmptyBitmapIndexSeeker(); } final Indexed<String> dimSet = getDimValueLookup(dimension); return new BitmapIndexSeeker() { private int currIndex = 0; private String currVal = null; private String lastVal = null; @Override public IndexedInts seek(String value) { if (dimSet == null || dimSet.size() == 0) { return new EmptyIndexedInts(); } if (lastVal != null) { if (GenericIndexed.STRING_STRATEGY.compare(value, lastVal) <= 0) { throw new ISE( "Value[%s] is less than the last value[%s] I have, cannot be.", value, lastVal ); } return new EmptyIndexedInts(); } if (currVal == null) { currVal = dimSet.get(currIndex); } int compareResult = GenericIndexed.STRING_STRATEGY.compare(currVal, value); if (compareResult == 0) { IndexedInts ret = new BitmapCompressedIndexedInts(bitmaps.getBitmap(currIndex)); ++currIndex; if (currIndex == dimSet.size()) { lastVal = value; } else { currVal = dimSet.get(currIndex); } return ret; } else if (compareResult < 0) { throw new ISE( "Skipped currValue[%s], currIndex[%,d]; incoming value[%s]", currVal, currIndex, value ); } else { return new EmptyIndexedInts(); } } }; }
Source:
public void testAUserCannotCreateAMeetingIfHasConflictsWithAnotherMeeting() { String organizer = meetingData.get(2).get("Organizer"); String subject = meetingData.get(2).get("Subject"); String startTime = meetingData.get(2).get("Start time"); String endTime = meetingData.get(2).get("End time"); String attendee = meetingData.get(2).get("Attendee"); String body = meetingData.get(2).get("Body"); String password = meetingData.get(2).get("Password"); HomeTabletPage home = new HomeTabletPage(); home .clickScheduleBtn() .setOrganizerTxtBox(organizer) .setSubjectTxtBox(subject) .setStartTimeDate(startTime) .setEndTimeDate(endTime) .setAttendeeTxtBoxPressingEnter(attendee) .setBodyTxtBox(body) .clickCreateBtn() .setPasswordTxtBox(password) .clickOkButton(); SchedulePage schedule = new SchedulePage(); schedule.clickCancelButton(); Assert.assertTrue(schedule.isMessageErrorCreationMeetingPopUpDisplayed()); }

Target:
public void testAUserCannotCreateAMeetingIfHasConflictsWithAnotherMeeting() { String organizer = meetingData.get(2).get("Organizer"); String subject = meetingData.get(2).get("Subject"); String startTime = meetingData.get(2).get("Start time"); String endTime = meetingData.get(2).get("End time"); String attendee = meetingData.get(2).get("Attendee"); String body = meetingData.get(2).get("Body"); String password = meetingData.get(2).get("Password"); HomeTabletPage homePage = new HomeTabletPage(); SchedulePage schedulePage = homePage .clickScheduleBtn() .createMeeting(organizer, subject, startTime, endTime, attendee, body, password) .clickCancelButton(); Assert.assertTrue(schedulePage.isMessageErrorCreationMeetingPopUpDisplayed()); }
Source:
private static io.fabric8.kubernetes.client.Config getKubeConfigFromPath(String path) { try{ final Path kubeConfigPath = Paths.get(path); final String kubeConfigContents = new String(Files.readAllBytes(kubeConfigPath), Charset.forName("UTF-8")); return io.fabric8.kubernetes.client.Config.fromKubeconfig(kubeConfigContents); }catch (java.io.IOException e) { throw new ConfigException("Could not read kubeConfig, check out kube_config_path."); } }

Target:
static io.fabric8.kubernetes.client.Config getKubeConfigFromPath(String path) { try { final Path kubeConfigPath = Paths.get(path); final String kubeConfigContents = new String(Files.readAllBytes(kubeConfigPath), Charset.forName("UTF-8")); return io.fabric8.kubernetes.client.Config.fromKubeconfig(kubeConfigContents); } catch (java.io.IOException e) { throw new ConfigException("Could not read kubeConfig, check kube_config_path."); } }
Source:
public void transform(StructuredRecord input, Emitter<StructuredRecord> emitter) { String fieldName; Node node; NodeList nodeList; try { InputSource source = new InputSource(new StringReader((String) input.get(config.inputField))); source.setEncoding(config.encoding); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(source); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); StructuredRecord.Builder builder = StructuredRecord.builder(outSchema); for (Schema.Field field : outSchema.getFields()) { fieldName = field.getName(); nodeList = (NodeList) xpath.compile(xPathMapping.get(fieldName)).evaluate(document, XPathConstants.NODESET); if (nodeList.getLength() > 1) { throw new IllegalArgumentException("Cannot specify XPath that are arrays"); } node = nodeList.item(0); builder.set(fieldName, parseValues(getValue(node, field.getSchema().getNonNullable().getType(), fieldName), field)); } emitter.emit(builder.build()); } catch (Exception e) { switch (mapErrorProcessing.get(config.processOnError)) { case 2: throw new IllegalStateException("Terminating process in error : " + e.getMessage()); case 3: emitter.emitError(new InvalidEntry<>(31, e.getStackTrace()[0].toString() + " : " + e.getMessage(), input)); break; default: break; } } }

Target:
public void transform(StructuredRecord input, Emitter<StructuredRecord> emitter) { try { InputSource source = new InputSource(new StringReader((String) input.get(config.inputField))); source.setEncoding(config.encoding); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(source); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); StructuredRecord.Builder builder = StructuredRecord.builder(outSchema); for (Schema.Field field : outSchema.getFields()) { String fieldName = field.getName(); NodeList nodeList = (NodeList) xpath.compile(xPathMapping.get(fieldName)).evaluate(document, XPathConstants.NODESET); if (nodeList.getLength() > 1) { throw new IllegalArgumentException("Cannot specify an XPath that is an array"); } Node node = nodeList.item(0); Schema.Type type = field.getSchema().getNonNullable().getType(); String value = getValue(node, type, fieldName); if (value == null) { builder.set(fieldName, null); } else { builder.set(fieldName, TypeConvertor.get(value, type)); } } emitter.emit(builder.build()); } catch (Exception e) { switch (config.processOnError) { case EXIT_ON_ERROR: throw new IllegalStateException("Terminating process on error: " + e.getMessage()); case WRITE_ERROR_DATASET: emitter.emitError(new InvalidEntry<>(31, e.getStackTrace()[0].toString() + " : " + e.getMessage(), input)); break; default: break; } } }
Source:
protected void processRequest() throws Exception { }

Target:
protected abstract void processRequest() throws Exception; @Override protected void mayProceed() throws InsufficientPermissionException { if (ub.isSysAdmin() || ub.isTechAdmin()) { return; } addPageMessage(respage.getString("no_have_correct_privilege_current_study") + respage.getString("change_study_contact_sysadmin")); throw new InsufficientPermissionException(Page.MENU_SERVLET, resexception.getString("not_allowed_access_extract_data_servlet"), "1"); }
Source:
public Context putAll(Context other) { if ( readonly ) throw new ARQException("Context is readonly") ; if ( other != null ) other.context.forEach(this::put); return this; }

Target:
public void putAll(Context other) { if ( readonly ) throw new ARQException("Context is readonly") ; if ( other != null ) other.context.forEach(this::put); }
Source:
public <O> Expression<O> createExecutableExpression(String expression, Class<?> returnType) { return createExecutableExpression(expression, returnType, false); }

Target:
public <O> Expression<O> createExecutableExpression(String expression, Class<?> returnType) { return createExecutableCode(expression, returnType, false); }
Source:
Worker(String applicationName, IRecordProcessorFactory recordProcessorFactory, KinesisClientLibConfiguration config, StreamConfig streamConfig, InitialPositionInStreamExtended initialPositionInStream, long parentShardPollIntervalMillis, long shardSyncIdleTimeMillis, boolean cleanupLeasesUponShardCompletion, ICheckpoint checkpoint, KinesisClientLibLeaseCoordinator leaseCoordinator, ExecutorService execService, IMetricsFactory metricsFactory, long taskBackoffTimeMillis, long failoverTimeMillis, boolean skipShardSyncAtWorkerInitializationIfLeasesExist, ShardPrioritization shardPrioritization) { this(applicationName, recordProcessorFactory, config, streamConfig, initialPositionInStream, parentShardPollIntervalMillis, shardSyncIdleTimeMillis, cleanupLeasesUponShardCompletion, checkpoint, leaseCoordinator, execService, metricsFactory, taskBackoffTimeMillis, failoverTimeMillis, skipShardSyncAtWorkerInitializationIfLeasesExist, shardPrioritization, Optional.empty(), Optional.empty(), DEFAULT_WORKER_STATE_CHANGE_LISTENER, new ShardSyncer(new KinesisLeaseCleanupValidator())); }

Target:
Worker(String applicationName, IRecordProcessorFactory recordProcessorFactory, KinesisClientLibConfiguration config, StreamConfig streamConfig, InitialPositionInStreamExtended initialPositionInStream, long parentShardPollIntervalMillis, long shardSyncIdleTimeMillis, boolean cleanupLeasesUponShardCompletion, ICheckpoint checkpoint, KinesisClientLibLeaseCoordinator leaseCoordinator, ExecutorService execService, IMetricsFactory metricsFactory, long taskBackoffTimeMillis, long failoverTimeMillis, boolean skipShardSyncAtWorkerInitializationIfLeasesExist, ShardPrioritization shardPrioritization) { this(applicationName, recordProcessorFactory, config, streamConfig, initialPositionInStream, parentShardPollIntervalMillis, shardSyncIdleTimeMillis, cleanupLeasesUponShardCompletion, checkpoint, leaseCoordinator, execService, metricsFactory, taskBackoffTimeMillis, failoverTimeMillis, skipShardSyncAtWorkerInitializationIfLeasesExist, shardPrioritization, Optional.empty(), Optional.empty(), DEFAULT_WORKER_STATE_CHANGE_LISTENER, DEFAULT_LEASE_CLEANUP_VALIDATOR ); }
Source:
public void setHeadersMap(Map<String, String> headers) { Assert.notNull(headers); HttpHeaders httpHeaders = new HttpHeaders(); for (String key : headers.keySet()) { String value = headers.get(key); String[] values = StringUtils.commaDelimitedListToStringArray(value); for (String v : values) { httpHeaders.add(key, v); } } setHeaders(httpHeaders); }

Target:
public void setHeadersMap(Map<String, String> headers) { Assert.notNull(headers); HttpHeaders httpHeaders = new HttpHeaders(); for (Map.Entry<String, String> entry : headers.entrySet()) { String[] values = StringUtils.commaDelimitedListToStringArray(entry.getValue()); for (String v : values) { httpHeaders.add(entry.getKey(), v); } } setHeaders(httpHeaders); }
Source:
public void validConnection() throws WaarpDatabaseNoConnectionException { try { dbModel.validConnection(getSession()); } catch (WaarpDatabaseNoConnectionException e) { getSession().setDisActive(true); setActive(false); throw e; } getSession().setDisActive(false); setActive(true); }

Target:
public void validConnection() throws WaarpDatabaseNoConnectionException { try { dbModel.validConnection(getSession()); } catch (WaarpDatabaseNoConnectionException e) { getSession().setDisActive(true); throw e; } getSession().setDisActive(false); }
Source:
public void validateJBIDE22704() { new NewOpenShift3ApplicationWizard().openWizardFromExplorer(); BuilderImageApplicationWizardHandlingTest.nextToBuildConfigurationWizardPage(); applicationName = new LabeledText("Name: ").getText(); assertNotNull(applicationName); assertTrue(applicationName.length() > 0); new WaitUntil(new WidgetIsEnabled(new NextButton())); new NextButton().click(); new WaitUntil(new WidgetIsEnabled(new BackButton())); int numberofEnvironmentVariables = new DefaultTable().rowCount(); assertTrue(numberofEnvironmentVariables > 0); new NextButton().click(); new WaitUntil(new WidgetIsEnabled(new BackButton())); int numberOfServicePorts = new DefaultTable().rowCount(); assertTrue(numberOfServicePorts > 0); new CancelButton().click(); }

Target:
private void validateJBIDE22704() { BuilderImageApplicationWizardHandlingTest.nextToBuildConfigurationWizardPage(); applicationName = new LabeledText("Name: ").getText(); assertNotNull(applicationName); assertTrue(applicationName.length() > 0); new WaitUntil(new WidgetIsEnabled(new NextButton())); new NextButton().click(); new WaitUntil(new WidgetIsEnabled(new BackButton())); int numberofEnvironmentVariables = new DefaultTable().rowCount(); assertTrue(numberofEnvironmentVariables > 0); new NextButton().click(); new WaitUntil(new WidgetIsEnabled(new BackButton())); int numberOfServicePorts = new DefaultTable().rowCount(); assertTrue(numberOfServicePorts > 0); new CancelButton().click(); new WaitWhile(new JobIsRunning(), TimePeriod.getCustom(120)); }
Source:
protected void writeAlignment(final SAMRecord alignment) { if (shouldFlushContainer(alignment)) { try { flushContainer(); } catch (final Exception e) { throw new RuntimeException(e); } } updateReferenceContext(alignment.getReferenceIndex()); samRecords.add(alignment); }

Target:
protected void writeAlignment(final SAMRecord alignment) { if (shouldFlushContainer(alignment)) { try { flushContainer(); } catch (IOException e) { throw new RuntimeIOException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } updateReferenceContext(alignment.getReferenceIndex()); samRecords.add(alignment); }
Source:
public static synchronized void forceShutdown() { if (instance != null) { try { instance.shutdownGracefully(100, 3000, TimeUnit.MILLISECONDS).await(); } catch (InterruptedException ignored) { } instance.channelFactoryCount.set(0); instance = null; } }

Target:
public static synchronized void forceShutdown() { if (instance != null) { instance.forEach(executor -> executor.shutdownGracefully(0, 0, TimeUnit.MILLISECONDS)); instance.channelFactoryCount.set(0); instance = null; } }
Source:
private Query createQuery(List<PriorityQueue<Object[]>> q) { int length = fieldsContext.size(); if ( length == 0 ) { throw new AssertionFailure( "Querying MoreLikeThis on 0 field." ); } else if ( length == 1 ) { return createQuery( q.get( 0 ), fieldsContext.getFirst() ); } else { BooleanQuery.Builder builder = new BooleanQuery.Builder(); Iterator<FieldContext> fieldsContextIterator = fieldsContext.iterator(); for ( PriorityQueue<Object[]> queue : q ) { try { builder.add( createQuery( queue, fieldsContextIterator.next() ), BooleanClause.Occur.SHOULD ); } catch (BooleanQuery.TooManyClauses ignore) { break; } } return builder.build(); } }

Target:
private Query createQuery(List<PriorityQueue<Object[]>> q) { int length = fieldsContext.size(); if ( length == 0 ) { throw new AssertionFailure( "Querying MoreLikeThis on 0 field." ); } else if ( length == 1 ) { return createQuery( q.get( 0 ), fieldsContext.getFirst() ); } else { BooleanQuery.Builder queryBuilder = new BooleanQuery.Builder(); Iterator<FieldContext> fieldsContextIterator = fieldsContext.iterator(); for ( PriorityQueue<Object[]> queue : q ) { try { queryBuilder.add( createQuery( queue, fieldsContextIterator.next() ), BooleanClause.Occur.SHOULD ); } catch (BooleanQuery.TooManyClauses ignore) { break; } } return queryBuilder.build(); } }
Source:
default IRetryAnalyzer getRetryAnalyzer(ITestResult result) { return null; }

Target:
default IRetryAnalyzer getRetryAnalyzer(ITestResult result) { return getRetryAnalyzer(); }
Source:
public void getYouViewVersionCridJson(HttpServletResponse response, @RequestParam(value = "pid", required = true) String pid) throws IOException { response.setContentType("application/json"); serializeJSON(response, outputForPid(pid)); }

Target:
public void getYouViewVersionCridJson(HttpServletResponse response, @RequestParam(value = "pid", required = true) String pid) throws IOException { response.setContentType(MimeType.APPLICATION_JSON.toString()); serializeJson(response, outputForPid(pid)); }
Source:
protected Span takeLocalSpanWithError(String errorTag) throws InterruptedException { Span result = takeSpanWithError(errorTag); assertLocalSpan(result); return result; }

Target:
protected Span takeLocalSpanWithError(String errorTag) throws InterruptedException { Span result = doTakeSpan(errorTag, false); assertLocalSpan(result); return result; }
Source:
public static ClockSkewMonitor create(Set<String> remoteServers, Optional<SSLSocketFactory> optionalSecurity) { Map<String, ClockService> monitors = Maps.toMap( remoteServers, (remoteServer) -> AtlasDbHttpClients.createProxy(optionalSecurity, remoteServer, ClockService.class)); return new ClockSkewMonitor( monitors, new ClockSkewEvents(AtlasDbMetrics.getMetricRegistry()), Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("clock-skew-monitor", true)), new ClockServiceImpl()); }

Target:
public static ClockSkewMonitor create(Set<String> remoteServers, Optional<SSLSocketFactory> optionalSecurity) { Map<String, ClockService> clocksByServer = Maps.toMap( remoteServers, (remoteServer) -> AtlasDbHttpClients.createProxy(optionalSecurity, remoteServer, ClockService.class)); return new ClockSkewMonitor( clocksByServer, new ClockSkewEvents(AtlasDbMetrics.getMetricRegistry()), Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("clock-skew-monitor", true)), new ClockServiceImpl()); }
Source:
public void testAbstractQueueDecoratorRemove() { if (!isRemoveSupported()) { return; } resetEmpty(); try { getCollection().remove(); fail("Queue.remove should throw NoSuchElementException"); } catch (final NoSuchElementException e) { } resetFull(); final int max = getFullElements().length; for (int i = 0; i < max; i++) { final E element = getCollection().remove(); final boolean success = getConfirmed().remove(element); assertTrue("remove should return correct element", success); verify(); } try { getCollection().element(); fail("Queue.remove should throw NoSuchElementException"); } catch (final NoSuchElementException e) { } }

Target:
public void testAbstractQueueDecoratorRemove() { if (!isRemoveSupported()) { return; } resetEmpty(); Exception exception = assertThrows(NoSuchElementException.class, () -> { getCollection().remove(); }); assertNull(exception.getMessage()); resetFull(); final int max = getFullElements().length; for (int i = 0; i < max; i++) { final E element = getCollection().remove(); final boolean success = getConfirmed().remove(element); assertTrue("remove should return correct element", success); verify(); } Exception noSuchElementException = assertThrows(NoSuchElementException.class, () -> { getCollection().element(); }); assertNull(noSuchElementException.getMessage()); }
Source:
public String generateForm(Schema<?> schema) { Map<String, Schema> properties = schema.getProperties(); if (properties != null) { String value = ""; for (Map.Entry<String, Schema> property : properties.entrySet()) { value += property.getKey(); value += FORMSYNTAX.get(Element.INNER_SEPARATOR); value += dataGenerator.generateValue(property.getKey(), property.getValue(), true); value += FORMSYNTAX.get(Element.OUTER_SEPARATOR); } return value.substring(0, value.length() - 1); } return ""; }

Target:
public String generateForm(Schema<?> schema) { Map<String, Schema> properties = schema.getProperties(); if (properties != null) { StringBuilder formData = new StringBuilder(); for (Map.Entry<String, Schema> property : properties.entrySet()) { formData.append(urlEncode(property.getKey())); formData.append(FORMSYNTAX.get(Element.INNER_SEPARATOR)); formData.append( urlEncode( dataGenerator.generateValue( property.getKey(), property.getValue(), true))); formData.append(FORMSYNTAX.get(Element.OUTER_SEPARATOR)); } return formData.substring(0, formData.length() - 1); } return ""; }
Source:
public ConfigDiff transaction(ConfigSource config, FileInputPlugin.Control control) { PluginTask task = config.loadConfig(PluginTask.class); Exec.getReporter(Reporters.Type.EVENT_LOG).report(Reporters.ReportLevel.INFO, ImmutableMap.<String, Object>of("foo", "bar")); List<String> files = listFiles(task); log.info("Loading files {}", files); task.setFiles(files); int taskCount = task.getFiles().size(); return resume(task.dump(), taskCount, control); }

Target:
public ConfigDiff transaction(ConfigSource config, FileInputPlugin.Control control) { PluginTask task = config.loadConfig(PluginTask.class); List<String> files = listFiles(task); log.info("Loading files {}", files); task.setFiles(files); int taskCount = task.getFiles().size(); return resume(task.dump(), taskCount, control); }
Source:
public void testPrepareStub() throws IOException { System.out.println("prepareStub"); File originProject = new File("src/test/resources/arith_funcs/"); File targetFolder = createTemporaryCopyOf(originProject); ExerciseBuilder instance = new ExerciseBuilder(); instance.prepareStub(targetFolder.toPath()); File expectedFolder = new File("src/test/resources/arith_funcs_stub/src"); File outputFolder = new File(targetFolder.getAbsolutePath() + "/src"); Map<String, File> expectedFiles = getFileMap(expectedFolder); Map<String, File> actualFiles = getFileMap(outputFolder); for(String fileName : expectedFiles.keySet()) { File expected = expectedFiles.get(fileName); File actual = actualFiles.get(fileName); List<String> expectedLines = FileUtils.readLines(expected); List<String> actualLines = FileUtils.readLines(actual); for (int i = 0 ; i < expectedLines.size() ; ++i) { String expectedLine = expectedLines.get(i); String actualLine = actualLines.get(i); assertEquals("Line in file " + fileName + " did not match ", expectedLine, actualLine); } } }

Target:
public void testPrepareStub() throws IOException { System.out.println("prepareStub"); File originProject = new File("src/test/resources/arith_funcs/"); File targetFolder = createTemporaryCopyOf(originProject); ExerciseBuilder instance = new ExerciseBuilder(); File expectedFolder = new File("src/test/resources/arith_funcs_stub/src"); File outputFolder = new File(targetFolder.getAbsolutePath() + "/src"); instance.prepareStub(targetFolder.toPath()); assertFileLines(expectedFolder, outputFolder); }
Source:
private int nextCorrelationId() { if (!isReserved(correlationId)) correlationId = MIN_RESERVED_CORRELATION_ID; return correlationId++; }

Target:
int nextCorrelationId() { if (!isReserved(correlationId)) correlationId = MIN_RESERVED_CORRELATION_ID; return correlationId++; }