auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Optional<PublishResult> publishMessage(String message) { if (!isEnabled.get()) { log.warn("Publishing is disabled for topic {}, dropping message {}", topicARN, message); return Optional.empty(); } try { PublishRequest publishRequest = new PublishRequest(topicARN.getArn(), message); PublishResult publishResponse = amazonSNS.publish(publishRequest); log.debug( "Published message with id to topic {}", message, publishResponse.getMessageId(), topicARN); getSuccessCounter().increment(); return Optional.of(publishResponse); } catch (Exception e) { log.error("failed to publish message to topic {}", message, topicARN, e); getErrorCounter(e).increment(); return Optional.empty(); } }

Target:
public Optional<PublishResult> publishMessage(String message) { if (!isEnabled.get()) { log.warn("Publishing is disabled for topic {}, dropping message {}", topicARN, message); return Optional.empty(); } try { PublishRequest publishRequest = new PublishRequest(topicARN.getArn(), message); PublishResult publishResponse = retrySupport.retry( () -> amazonSNS.publish(publishRequest), 5, Duration.ofMillis(200), false); log.debug( "Published message with id to topic {}", message, publishResponse.getMessageId(), topicARN); getSuccessCounter().increment(); return Optional.of(publishResponse); } catch (Exception e) { log.error("failed to publish message to topic {}", message, topicARN, e); getErrorCounter(e).increment(); return Optional.empty(); } }
Source:
private TimeLockServices createNewClient(String namespace) { Preconditions.checkArgument(!namespace.equals(PaxosTimeLockConstants.LEADER_ELECTION_NAMESPACE), "The client name '%s' is reserved for the leader election service, and may not be " + "used.", PaxosTimeLockConstants.LEADER_ELECTION_NAMESPACE); if (getNumberOfActiveClients() >= maxNumberOfClients.get()) { log.error( "Unable to create timelock services for client {}, as it would exceed the maximum number of " + "allowed clients ({}). If this is intentional, the maximum number of clients can be " + "increased via the maximum-number-of-clients runtime config property.", SafeArg.of("client", namespace), SafeArg.of("maxNumberOfClients", maxNumberOfClients)); throw new IllegalStateException("Maximum number of clients exceeded"); } return clientServicesFactory.apply(namespace); }

Target:
private TimeLockServices createNewClient(String namespace) { Preconditions.checkArgument(!namespace.equals(PaxosTimeLockConstants.LEADER_ELECTION_NAMESPACE), "The client name '%s' is reserved for the leader election service, and may not be " + "used.", PaxosTimeLockConstants.LEADER_ELECTION_NAMESPACE); if (getNumberOfActiveClients() >= getMaxNumberOfClients()) { log.error( "Unable to create timelock services for client {}, as it would exceed the maximum number of " + "allowed clients ({}). If this is intentional, the maximum number of clients can be " + "increased via the maximum-number-of-clients runtime config property.", SafeArg.of("client", namespace), SafeArg.of("maxNumberOfClients", getMaxNumberOfClients())); throw new IllegalStateException("Maximum number of clients exceeded"); } return clientServicesFactory.apply(namespace); }
Source:
public void clearKey(String tabName, String key) { Map<String, Object> tab = getTab(tabName); tab.remove(key); }

Target:
void clearKey(String tabName, String key) { Map<String, Object> tab = getTab(tabName); tab.remove(key); }
Source:
public void handleGet(ActionParameters params) throws ActionException { final int layerId = params.getRequiredParamInt(PARAM_LAYER_ID); LOG.info("Checking layer usage in other layers for layerId: ", layerId); Map<String, Set<Integer>> layerUsages = new HashMap<>(); Set<Integer> timeseriesLayerIds = new HashSet<>(); for (OskariLayer layer : mapLayerService.findAll()) { JSONObject options = layer.getOptions(); try { if (options != null && options.has("timeseries")) { JSONObject timeseriesOptions = options.getJSONObject("timeseries"); Integer metadataLayerId = timeseriesOptions.getJSONObject("metadata").getInt("layer"); if (metadataLayerId == layerId) { timeseriesLayerIds.add(layer.getId()); } } } catch (JSONException e) { throw new ActionException("Cannot parse layer metadata options for layer: " + layer.getName() + ", id: " + layer.getId()); } } layerUsages.put("timeseries", timeseriesLayerIds); writeResponse(params, layerUsages); }

Target:
public void handleGet(ActionParameters params) throws ActionException { params.requireAdminUser(); final int layerId = params.getRequiredParamInt(PARAM_LAYER_ID); LOG.info("Checking layer usage in other layers for layerId: ", layerId); Map<String, Set<Integer>> layerUsages = new HashMap<>(); Set<Integer> timeseriesLayerIds = getTimeseriesLayerIds(layerId); layerUsages.put("timeseries", timeseriesLayerIds); ResponseHelper.writeResponse(params, new JSONObject(layerUsages)); }
Source:
public void updated(Dictionary<String, ?> properties) { if (properties == null || properties.isEmpty()) { return; } Map<String, Map<String, Object>> brokerConfigs = extractBrokerConfigurations(properties); for (Map<String, Object> brokerConfig : brokerConfigs.values()) { try { addBrokerConnection(brokerConfig).start(); } catch (ConfigurationException e) { logger.warn("MqttBroker connection configuration faulty: {}", e.getMessage()); } catch (MqttException e) { logger.warn("MqttBroker start failed: {}", e.getMessage(), e); } } }

Target:
public void updated(Dictionary<String, ?> properties) { if (properties == null || properties.isEmpty()) { return; } Iterator<Map.Entry<String, MqttBrokerConnection>> it = brokerConnections.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, MqttBrokerConnection> entry = it.next(); if (entry.getValue().isTextualConfiguredBroker()) { entry.getValue().close(); it.remove(); } } Map<String, Map<String, String>> brokerConfigs = extractBrokerConfigurations(properties); for (Map<String, String> brokerConfig : brokerConfigs.values()) { try { addBrokerConnection(brokerConfig).start(); } catch (ConfigurationException e) { logger.warn("MqttBroker connection configuration faulty: {}", e.getMessage()); } catch (MqttException e) { logger.warn("MqttBroker start failed: {}", e.getMessage(), e); } } }
Source:
public static XmlHighlighting highlight(SensorContext context, XmlFile xmlFile) { XmlHighlighting highlighting = new XmlHighlighting(xmlFile); highlighting.highlight(context); return highlighting; }

Target:
public static void highlight(SensorContext context, XmlFile xmlFile) { new XmlHighlighting(xmlFile).highlight(context); }
Source:
private <T> RMFailoverProxyProvider<T> createRMFailoverProxyProvider( Configuration conf, Class<T> protocol) { String defaultProviderClassName = YarnConfiguration.DEFAULT_CLIENT_FAILOVER_PROXY_PROVIDER; Class<? extends RMFailoverProxyProvider<T>> defaultProviderClass; try { defaultProviderClass = (Class<? extends RMFailoverProxyProvider<T>>) Class.forName(defaultProviderClassName); } catch (Exception e) { throw new YarnRuntimeException("Invalid default failover provider class" + defaultProviderClassName, e); } RMFailoverProxyProvider<T> provider = ReflectionUtils.newInstance( conf.getClass(YarnConfiguration.CLIENT_FAILOVER_PROXY_PROVIDER, defaultProviderClass, RMFailoverProxyProvider.class), conf); provider.init(conf, (RMProxy<T>) this, protocol); return provider; }

Target:
private <T> RMFailoverProxyProvider<T> createRMFailoverProxyProvider( Configuration conf, Class<T> protocol) { Class<? extends RMFailoverProxyProvider<T>> defaultProviderClass; try { defaultProviderClass = (Class<? extends RMFailoverProxyProvider<T>>) Class.forName( YarnConfiguration.DEFAULT_CLIENT_FAILOVER_PROXY_PROVIDER); } catch (Exception e) { throw new YarnRuntimeException("Invalid default failover provider class" + YarnConfiguration.DEFAULT_CLIENT_FAILOVER_PROXY_PROVIDER, e); } RMFailoverProxyProvider<T> provider = ReflectionUtils.newInstance( conf.getClass(YarnConfiguration.CLIENT_FAILOVER_PROXY_PROVIDER, defaultProviderClass, RMFailoverProxyProvider.class), conf); provider.init(conf, (RMProxy<T>) this, protocol); return provider; }
Source:
public String toString() { return "EntityHit(" + entity + " at " + intersection + " on " + normal + ")"; }

Target:
public String toString() { return "EntityHit(" + this.entity + " at " + this.intersection + " on " + this.normal + ")"; }
Source:
public URL create(final String key, final long value) { return create(key, ""+ value); }

Target:
public URL create(final String key, final long value) { return create(key, String.valueOf(value)); }
Source:
public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with " + "authorization code", null, t))).map(ar -> new MsalToken(ar, options)); }

Target:
public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); }
Source:
public boolean isEdgeWithObliqueRoutingStyle() { boolean isEdgeObliqueRoutingStyle = false; if (Routing.MANUAL_LITERAL.getLiteral().equals(getRoutingStyle())) { isEdgeObliqueRoutingStyle = true; } return isEdgeObliqueRoutingStyle; }

Target:
public boolean isEdgeWithObliqueRoutingStyle() { boolean isEdgeObliqueRoutingStyle = false; if (Routing.MANUAL_LITERAL.equals(getRoutingStyle())) { isEdgeObliqueRoutingStyle = true; } return isEdgeObliqueRoutingStyle; }
Source:
public void testCheckLengthVersion() throws Exception { System.setProperty("VERSION","1.0.0"); assertThatExceptionOfType(Exception.class).isThrownBy(() -> runontag.checkParams(runontag.getParams("@runOnEnv(VERSION>1.0)"))) .withMessage("Error while parsing params. The versions must have the same numbers of elements"); }

Target:
public void testCheckLengthVersion() throws Exception { System.setProperty("VERSION","1.0.0"); assertThatExceptionOfType(Exception.class).isThrownBy(() -> runontag.checkParams(runontag.getParams("@runOnEnv(VERSION>1.0)"))) .withMessage("Error while parsing params. The versions must have the same number of elements"); }
Source:
public RelNode copyWithLimitOffset(RelTraitSet traitSet, RexNode offset, RexNode limit) { VoltDBPTableSeqScan newScan = new VoltDBPTableSeqScan( getCluster(), traitSet, getTable(), getVoltTable(), getProgram(), offset, limit, getAggregateRelNode(), getPreAggregateRowType(), getPreAggregateProgram(), m_splitCount); return newScan; }

Target:
public AbstractVoltDBTableScan copyWithLimitOffset(RelTraitSet traitSet, RexNode offset, RexNode limit) { VoltDBPTableSeqScan newScan = new VoltDBPTableSeqScan( getCluster(), traitSet, getTable(), getVoltTable(), getProgram(), offset, limit, getAggregateRelNode(), getPreAggregateRowType(), getPreAggregateProgram(), m_splitCount); return newScan; }
Source:
private static void setVmTemplateStatus( Guid vmTemplateGuid, VmTemplateStatus status, CompensationContext compensationContext) { VmTemplate vmTemplate = DbFacade.getInstance().getVmTemplateDao().get(vmTemplateGuid); if (vmTemplate != null) { if (compensationContext != null) { compensationContext.snapshotEntityStatus(vmTemplate); } vmTemplate.setStatus(status); DbFacade.getInstance().getVmTemplateDao().update(vmTemplate); } else { log.warnFormat( "VmTemplateHandler::setVmTemplateStatus: vmTemplate is null, not setting status '{0}' to vmTemplate", status); } }

Target:
private static void setVmTemplateStatus( Guid vmTemplateGuid, VmTemplateStatus status, CompensationContext compensationContext) { VmTemplate vmTemplate = DbFacade.getInstance().getVmTemplateDao().get(vmTemplateGuid); if (vmTemplate != null) { if (compensationContext != null) { compensationContext.snapshotEntityStatus(vmTemplate); } vmTemplate.setStatus(status); DbFacade.getInstance().getVmTemplateDao().update(vmTemplate); } else { log.warnFormat( "setVmTemplateStatus: vmTemplate is null, not setting status '{0}' to vmTemplate", status); } }
Source:
public String ensureReadData(final String path, final long timeout) { Random rn = new Random(); int jitter; int retry = 1; int step = 50; int counter = 0; String content = super.readData(path, false); long totalWait = 0; while (content == null) { counter++; retry *= 2; jitter = rn.nextInt(100); long wait = retry * step + jitter; try { Thread.sleep(wait); } catch (InterruptedException e) { LOG.error("Failed to sleep at retry: " + counter + " " + e.getMessage()); } content = super.readData(path, false ); totalWait += wait; if (totalWait > timeout) { break; } } if (content == null) { LOG.warn("Failed to read znode data for path " + path + " within timeout " + timeout + " milliseconds"); } return content; }

Target:
public String ensureReadData(final String path, final long timeout) { Random rn = new Random(); int jitter; int retry = 1; int step = 50; int counter = 0; String content = super.readData(path, false); long totalWait = 0; long nextWait = 0; while (content == null && totalWait < timeout) { counter++; retry *= 2; jitter = rn.nextInt(100); nextWait = retry * step + jitter; if (totalWait + nextWait > timeout) { nextWait = timeout - totalWait; } try { Thread.sleep(nextWait); } catch (InterruptedException e) { LOG.error("Failed to sleep at retry: " + counter + " " + e.getMessage()); } totalWait += nextWait; content = super.readData(path, false ); } if (content == null) { LOG.warn("Failed to read znode data for path " + path + " within timeout " + timeout + " milliseconds"); } return content; }
Source:
private void addVertex(UnpackedBakedQuad.Builder quadBuilder, float x, float y, float u, float v) { vec.x = x; vec.y = y; vec.z = 0; vec.w = 1; matrix.transform(vec); for(int e = 0; e < format.getElementCount(); e++) { switch(format.getElement(e).getUsage()) { case POSITION: quadBuilder.put(e, vec.x, vec.y, vec.z, vec.w); break; case UV: if(format.getElement(e).getIndex() == 0) quadBuilder.put(e, sprite.getInterpolatedU(u * 16), sprite.getInterpolatedV(v * 16), 0, 1); break; case COLOR: quadBuilder.put(e, r, g, b, a); break; case NORMAL: quadBuilder.put(e, 0, 0, 1, 1); break; default: quadBuilder.put(e); break; } } }

Target:
private void addVertex(UnpackedBakedQuad.Builder quadBuilder, float x, float y, float u, float v) { for(int e = 0; e < format.getElementCount(); e++) { switch(format.getElement(e).getUsage()) { case POSITION: vec.set(x, y, 0f, 1f); transform.transformPosition(vec); quadBuilder.put(e, vec.x, vec.y, vec.z, vec.w); break; case COLOR: quadBuilder.put(e, r, g, b, a); break; case NORMAL: quadBuilder.put(e, 0, 0, 1, 1); break; case UV: if(format.getElement(e).getIndex() == 0) { quadBuilder.put(e, sprite.getInterpolatedU(u * 16), sprite.getInterpolatedV(v * 16), 0, 1); break; } default: quadBuilder.put(e); break; } } }
Source:
public Task getTask(int execServiceId, int facilityId, int engineID) { try { return this .getJdbcTemplate() .queryForObject( "select " + taskMappingSelectQuery + ", " + FacilitiesManagerImpl.facilityMappingSelectQuery + ", " + ExecServiceDaoJdbc.execServiceMappingSelectQuery + ", " + ServicesManagerImpl.serviceMappingSelectQuery + " from tasks left join exec_services on tasks.exec_service_id = exec_services.id " + "left join facilities on facilities.id = tasks.facility_id left join services on services.id = exec_services.service_id " + "where exec_services.id = ? and tasks.facility_id = ? and tasks.engine_id = ?", new Object[] { execServiceId, facilityId, engineID < 0 ? "null" : engineID}, TASK_ROWMAPPER); } catch (EmptyResultDataAccessException ex) { return null; } }

Target:
public Task getTask(int execServiceId, int facilityId, int engineID) { try { return this .getJdbcTemplate() .queryForObject( "select " + taskMappingSelectQuery + ", " + FacilitiesManagerImpl.facilityMappingSelectQuery + ", " + ExecServiceDaoJdbc.execServiceMappingSelectQuery + ", " + ServicesManagerImpl.serviceMappingSelectQuery + " from tasks left join exec_services on tasks.exec_service_id = exec_services.id " + "left join facilities on facilities.id = tasks.facility_id left join services on services.id = exec_services.service_id " + "where exec_services.id = ? and tasks.facility_id = ? and tasks.engine_id " + (engineID < 0 ? "is null" : "= ?"), engineID < 0 ? new Integer[] { execServiceId, facilityId } : new Integer[] { execServiceId, facilityId, engineID}, TASK_ROWMAPPER); } catch (EmptyResultDataAccessException ex) { return null; } }
Source:
public void verifyLoggingCustomEvents() { driver.logEvent("appium", "funEvent"); Object value = driver.getSessionDetail("events"); assertNotNull(((Map<String, Object>) value).get("appium:funEvent")); }

Target:
public void verifyLoggingCustomEvents() { CustomEvent evt = new CustomEvent(); evt.setEventName("funEvent"); evt.setVendor("appium"); driver.logEvent(evt); ServerEvents events = driver.getEvents(); boolean hasCustomEvent = events.events.stream().anyMatch((TimedEvent event) -> event.name.equals("appium:funEvent") && event.occurrences.get(0).intValue() > 0 ); boolean hasCommandName = events.commands.stream().anyMatch((CommandEvent event) -> event.name.equals("logCustomEvent") ); assertTrue(hasCustomEvent); assertTrue(hasCommandName); assertThat(events.jsonData, Matchers.containsString("\"appium:funEvent\"")); }
Source:
public void onEvent(Event event, Object source, Object data) { String name = ((ActionExecutionEvent) event).getActionName(); if (!SUPPORTED_EVENTS.contains(name)) { return; } if (event instanceof ActionExecutingEvent) { this.lockManager.lock(((XWikiDocument) source).getDocumentReference()); } else { this.lockManager.unlock(((XWikiDocument) source).getDocumentReference()); } }

Target:
public void onEvent(Event event, Object source, Object data) { if (event == null || source == null || !(event instanceof ActionExecutionEvent)) { return; } String name = ((ActionExecutionEvent) event).getActionName(); if (!SUPPORTED_EVENTS.contains(name)) { return; } if (event instanceof ActionExecutingEvent) { this.lockManager.lock(((XWikiDocument) source).getDocumentReference()); } else if (event instanceof ActionExecutedEvent) { this.lockManager.unlock(((XWikiDocument) source).getDocumentReference()); } }
Source:
public String getDefaultOutput() { return ""; }

Target:
public String getDefaultOutput() { return m_defaultOutput; }
Source:
public IVariable getVariable(int offset) throws DebugException { if (offset >= getLength()) { requestFailed(JDIDebugModelMessages.JDIArrayValue_6, new IndexOutOfBoundsException()); } return new JDIArrayEntryVariable(getJavaDebugTarget(), getArrayReference(), offset, fLogicalParent); }

Target:
public IVariable getVariable(int offset) throws DebugException { if (offset >= getLength()) { requestFailed(JDIDebugModelMessages.JDIArrayValue_6, new IndexOutOfBoundsException(Integer.toString(offset))); } return new JDIArrayEntryVariable(getJavaDebugTarget(), getArrayReference(), offset, fLogicalParent); }
Source:
Mono<Response<String>> renewLeaseWithResponse(BlobRenewLeaseOptions options, Context context) { StorageImplUtils.assertNotNull("options", options); BlobLeaseRequestConditions requestConditions = (options.getRequestConditions() == null) ? new BlobLeaseRequestConditions() : options.getRequestConditions(); context = context == null ? Context.NONE : context; if (this.isBlob) { return this.client.blobs().renewLeaseWithRestResponseAsync(null, null, this.leaseId, null, requestConditions.getIfModifiedSince(), requestConditions.getIfUnmodifiedSince(), requestConditions.getIfMatch(), requestConditions.getIfNoneMatch(), requestConditions.getIfTags(), null, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getLeaseId())); } else { return this.client.containers().renewLeaseWithRestResponseAsync(null, this.leaseId, null, requestConditions.getIfModifiedSince(), requestConditions.getIfUnmodifiedSince(), null, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getLeaseId())); } }

Target:
Mono<Response<String>> renewLeaseWithResponse(BlobRenewLeaseOptions options, Context context) { StorageImplUtils.assertNotNull("options", options); BlobLeaseRequestConditions requestConditions = (options.getRequestConditions() == null) ? new BlobLeaseRequestConditions() : options.getRequestConditions(); context = context == null ? Context.NONE : context; if (this.isBlob) { return this.client.blobs().renewLeaseWithRestResponseAsync(null, null, this.leaseId, null, requestConditions.getIfModifiedSince(), requestConditions.getIfUnmodifiedSince(), requestConditions.getIfMatch(), requestConditions.getIfNoneMatch(), requestConditions.getTagsConditions(), null, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getLeaseId())); } else { return this.client.containers().renewLeaseWithRestResponseAsync(null, this.leaseId, null, requestConditions.getIfModifiedSince(), requestConditions.getIfUnmodifiedSince(), null, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getLeaseId())); } }
Source:
public boolean isEmpty() { return getOutAverageLinkshare() == null && getOutAverageUpperlimit() == null && getOutAverageRealtime() == null; }

Target:
public boolean isEmpty() { return hostNetworkQosProperties.isEmpty(); }
Source:
protected Conditions createConditions(final CallbackProperties properties) { DateTime issueInstant = properties.getIssueInstant(); DateTime beginValidTime = properties.getSamlConditionsNotBefore(); DateTime endValidTime = properties.getSamlConditionsNotAfter(); if (issueInstant == null) { issueInstant = new DateTime(); } beginValidTime = setBeginValidTime(beginValidTime, issueInstant); endValidTime = setEndValidTime(endValidTime, issueInstant); return OpenSAML2ComponentBuilder.getInstance().createConditions(beginValidTime, endValidTime); }

Target:
protected Conditions createConditions(final CallbackProperties properties) { DateTime issueInstant = new DateTime(); DateTime beginValidTime = properties.getSamlConditionsNotBefore(); DateTime endValidTime = properties.getSamlConditionsNotAfter(); if (beginValidTime != null || endValidTime != null) { beginValidTime = setBeginValidTime(beginValidTime, issueInstant); endValidTime = setEndValidTime(endValidTime, issueInstant); return OpenSAML2ComponentBuilder.getInstance().createConditions(beginValidTime, endValidTime); } return null; }
Source:
public static Set<Path> getRequiredFields(EntityMetadata md, Projection p, QueryExpression q, Sort s) { Set<Path> fields=new HashSet<>(); FieldCursor cursor=md.getFieldCursor(); if(cursor.next()) { boolean done=false; do { Path field=cursor.getCurrentPath(); FieldTreeNode node=cursor.getCurrentNode(); LOGGER.debug("Checking if is included ({})",field,node); if(node instanceof ResolvedReferenceField|| node instanceof ReferenceField) { done=!cursor.nextSibling(); } else { if( (node instanceof ObjectField) || (node instanceof ArrayField && ((ArrayField)node).getElement() instanceof ObjectArrayElement) || (node instanceof ArrayElement)) { } else if( (p!=null && p.isFieldRequiredToEvaluateProjection(field)) || (q!=null && q.isRequired(field)) || (s!=null && s.isRequired(field)) ) { LOGGER.debug("{}: required",field); fields.add(field); } else { LOGGER.debug("{}: not required", field); } done=!cursor.next(); } } while(!done); } return fields; }

Target:
public static Set<Path> getRequiredFields(EntityMetadata md, Projection p, QueryExpression q, Sort s) { Set<Path> fields=new HashSet<>(); FieldCursor cursor=md.getFieldCursor(); Path skipPrefix=null; if(cursor.next()) { boolean done=false; do { Path field=cursor.getCurrentPath(); if(skipPrefix!=null) { if(!field.matchingDescendant(skipPrefix)) { skipPrefix=null; } } if(skipPrefix==null) { FieldTreeNode node=cursor.getCurrentNode(); LOGGER.debug("Checking if is included ({})",field,node); if(node instanceof ResolvedReferenceField|| node instanceof ReferenceField) { skipPrefix=field; } else { if( (node instanceof ObjectField) || (node instanceof ArrayField && ((ArrayField)node).getElement() instanceof ObjectArrayElement) || (node instanceof ArrayElement)) { } else if( (p!=null && p.isFieldRequiredToEvaluateProjection(field)) || (q!=null && q.isRequired(field)) || (s!=null && s.isRequired(field)) ) { LOGGER.debug("{}: required",field); fields.add(field); } else { LOGGER.debug("{}: not required", field); } done=!cursor.next(); } } else done=!cursor.next(); } while(!done); } return fields; }
Source:
private void insertText(String txt) { if (lastFocusedField!=null) { if (lastFocusedField instanceof IActionCodeEditor) { ((IActionCodeEditor)lastFocusedField).insertText(txt); } else if (lastFocusedField instanceof Text) { Text lastTextField = (Text) lastFocusedField; int begin = txt.indexOf('('); int end = txt.indexOf(')'); int offset = lastTextField.getSelection().x; lastTextField.insert(txt); if (begin>=0 && end>=0 && end>begin+1) lastTextField.setSelection(offset+begin+1, offset+end); lastTextField.setFocus(); } } }

Target:
private void insertText(String txt) { if (lastFocusedField != null) { if (actionEditorControlMap.containsKey(lastFocusedField)) { (actionEditorControlMap.get(lastFocusedField)).insertText(txt); } else if (lastFocusedField instanceof Text) { Text lastTextField = (Text) lastFocusedField; int begin = txt.indexOf('('); int end = txt.indexOf(')'); int offset = lastTextField.getSelection().x; lastTextField.insert(txt); if (begin >= 0 && end >= 0 && end > begin + 1) lastTextField .setSelection(offset + begin + 1, offset + end); lastTextField.setFocus(); } } }
Source:
public TopicNode getPaginatedTopicTree(String topicPath, int startIndex, int numberOfTopicsPerRound) throws EventBrokerException { try { UserRegistry userRegistry = this.registryService.getGovernanceSystemRegistry(EventBrokerHolder.getInstance().getTenantId()); if (!userRegistry.resourceExists(topicPath)) { userRegistry.put(topicPath, userRegistry.newCollection()); } log.info("Before calling userregistry.get method"); Collection collection = (Collection) userRegistry.get(topicPath); log.info("After calling userregistry.get method"); String[] paths = collection.getChildren(startIndex, numberOfTopicsPerRound); log.info("Children Paths length: " + paths.length); TopicNode rootTopic = new TopicNode("/", "/"); buildTopicTree(rootTopic, paths); log.info("After building topic Tree"); return rootTopic; } catch (RegistryException e) { throw new EventBrokerException(e.getMessage(), e); } }

Target:
public TopicNode getPaginatedTopicTree(String topicPath, int startIndex, int numberOfTopicsPerRound) throws EventBrokerException { try { UserRegistry userRegistry = this.registryService.getGovernanceSystemRegistry(EventBrokerHolder.getInstance().getTenantId()); if (!userRegistry.resourceExists(topicPath)) { userRegistry.put(topicPath, userRegistry.newCollection()); } Collection collection = (Collection) userRegistry.get(topicPath); String[] paths = collection.getChildren(startIndex, numberOfTopicsPerRound); TopicNode rootTopic = new TopicNode("/", "/"); buildTopicTree(rootTopic, paths); return rootTopic; } catch (RegistryException e) { throw new EventBrokerException(e.getMessage(), e); } }
Source:
public static boolean isValidGenericValue(String generic) { return isGeneric(generic) || Boolean.FALSE.toString().equals(generic); }

Target:
public static boolean isValidGenericValue(String generic) { return isGeneric(generic) || Boolean.FALSE.toString().equalsIgnoreCase(generic); }
Source:
private void setAllListModelsUnavailable() { for (ListModel m : getItems()) { if (!(m instanceof PluginModel)) { m.setIsAvailable(false); } } }

Target:
private void setAllListModelsUnavailable() { for (ListModel m : getItems()) { m.setIsAvailable(false); } }
Source:
protected String getTemplate(Artifact artifact, PresentationType presentationType) throws OseeCoreException { boolean useTemplateOnce = getBooleanOption(USE_TEMPLATE_ONCE); boolean firstTime = getBooleanOption("FirstTime"); boolean secondTime = getBooleanOption("SecondTime"); Object option = getOption(TEMPLATE_OPTION); if ((option instanceof Artifact) && (!useTemplateOnce || (useTemplateOnce && (firstTime || secondTime)))) { Artifact template = (Artifact) option; if (useTemplateOnce) { if (secondTime) { setOption("SecondTime", false); } if (firstTime) { setOption("FirstTime", false); setOption("SecondTime", true); } } return template.getSoleAttributeValue(CoreAttributeTypes.WholeWordContent); } else if ((option == null || option instanceof String) || (useTemplateOnce && !firstTime)) { if (useTemplateOnce && !firstTime && !secondTime) { option = null; } Artifact templateArtifact = TemplateManager.getTemplate(this, artifact, presentationType, (String) option); return templateArtifact.getSoleAttributeValue(CoreAttributeTypes.WholeWordContent); } return Strings.EMPTY_STRING; }

Target:
protected String getTemplate(Artifact artifact, PresentationType presentationType) throws OseeCoreException { boolean useTemplateOnce = getBooleanOption(USE_TEMPLATE_ONCE); boolean firstTime = getBooleanOption(FIRST_TIME); boolean secondTime = getBooleanOption(SECOND_TIME); Object option = getOption(TEMPLATE_OPTION); if ((option instanceof Artifact) && (!useTemplateOnce || (useTemplateOnce && (firstTime || secondTime)))) { Artifact template = (Artifact) option; if (useTemplateOnce) { if (secondTime) { setOption(SECOND_TIME, false); } if (firstTime) { setOption(FIRST_TIME, false); setOption(SECOND_TIME, true); } } return template.getSoleAttributeValue(CoreAttributeTypes.WholeWordContent); } else if ((option == null || option instanceof String) || (useTemplateOnce && !firstTime)) { if (useTemplateOnce && !firstTime && !secondTime) { option = null; } Artifact templateArtifact = TemplateManager.getTemplate(this, artifact, presentationType, (String) option); return templateArtifact.getSoleAttributeValue(CoreAttributeTypes.WholeWordContent); } return Strings.EMPTY_STRING; }
Source:
public Map<String, Fingerprint> identifyContaminant(final Path samFile, final double contamination) { final Map<FingerprintIdDetails, Fingerprint> fingerprintIdDetailsFingerprintMap = this.fingerprintSamFile(samFile, (h) -> new HaplotypeProbabilitiesFromContaminatorSequence(h, contamination)); final Map<FingerprintIdDetails, Fingerprint> fingerprintIdDetailsFingerprintbySample = Fingerprint.mergeFingerprintsBy(fingerprintIdDetailsFingerprintMap, Fingerprint.getFingerprintIdDetailsStringFunction(CrosscheckMetric.DataType.SAMPLE)); final Map<String,Fingerprint> fingerprintsBySample = fingerprintIdDetailsFingerprintbySample.entrySet().stream() .collect(Collectors.toMap(e -> e.getKey().sample, Map.Entry::getValue)); return fingerprintsBySample; }

Target:
public Map<String, Fingerprint> identifyContaminant(final Path samFile, final double contamination) { final Map<FingerprintIdDetails, Fingerprint> fpIdDetailsMap = this.fingerprintSamFile(samFile, h -> new HaplotypeProbabilitiesFromContaminatorSequence(h, contamination)); final Map<FingerprintIdDetails, Fingerprint> fpIdDetailsBySample = Fingerprint.mergeFingerprintsBy(fpIdDetailsMap, Fingerprint.getFingerprintIdDetailsStringFunction(CrosscheckMetric.DataType.SAMPLE)); return fpIdDetailsBySample.entrySet().stream() .collect(Collectors.toMap(e -> e.getKey().sample, Map.Entry::getValue)); }
Source:
public void post(Iterable<Event> events) { post(events, StreamObservers.<Event>noOpObserver()); }

Target:
public final void post(Iterable<Event> events) { post(events, StreamObservers.<IsSent>noOpObserver()); }
Source:
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { FUtil.bcastMsg(ChatColor.GRAY + "[" + ChatColor.YELLOW + "Imposter" + ChatColor.GRAY + "] " + ChatColor.WHITE + "< " + ChatColor.RESET + "" + sender.getName() + ChatColor.WHITE + "> " + ChatColor.YELLOW + "Has verified and is requesting to be added!" ); return true; }

Target:
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { for (Player player : server.getOnlinePlayers()) { if (isAdmin(player)) { FUtil.msg(ChatColor.GRAY + "[" + ChatColor.YELLOW + "Imposter" + ChatColor.GRAY + "] " + ChatColor.WHITE + "< " + ChatColor.RESET + "" + sender.getName() + ChatColor.WHITE + "> " + ChatColor.YELLOW + "Has verified and is requesting to be added!"); } return true; } }
Source:
public static boolean isStatusOk(Map<String, Object> response) { if (response.get("error") != null) { String errorCode = response.get("error_code") == null ? (String) response.get("error") : (String) response.get("error_code"); String errorDescription = response.get("error_description") == null ? (String) response.get("error") : (String) response.get("error_description"); throw new RuntimeException(String.format("%s: %s", errorCode, errorDescription)); } return true; }

Target:
public static boolean isStatusOk(Map<String, Object> response) { if (response.get("error") != null) { Object errorCode = response.get("error_code"); String msg; if (errorCode == null) { msg = String.format("%s: %s", response.get("error"), response.get("error_description")); } else { msg = String.format("%s: %s", errorCode, response.get("error")); } throw new RuntimeException(msg); } return true; }
Source:
public static String encodeTo(Node node) { String nodePath = node == Jenkins.getInstance() ? "(master)" : node.getNodeName(); return encodeTo("/computer/"+ nodePath, node.getDisplayName()); }

Target:
public static String encodeTo(Node node) { Computer c = node.toComputer(); if (c != null) { return encodeTo("/" + c.getUrl(), node.getDisplayName()); } String nodePath = node == Jenkins.getInstance() ? "(master)" : node.getNodeName(); return encodeTo("/computer/" + nodePath, node.getDisplayName()); }
Source:
ByteBuffer getBytes() { ByteBuffer value = ByteBuffer.allocate(indexValueSizeInBytes); if (version == PersistentIndex.VERSION_0) { value.putLong(size); value.putLong(offset.getOffset()); value.put(flags); value.putLong(expiresAtMs); value.putLong(originalMessageOffset); value.position(0); } else if (version == PersistentIndex.VERSION_1) { value.putLong(size); value.putLong(offset.getOffset()); value.put(flags); value.putInt( expiresAtMs != Utils.Infinite_Time ? Math.toIntExact(expiresAtMs / Time.MsPerSec) : (int) expiresAtMs); value.putLong(originalMessageOffset); value.putInt(operationTimeInSecs); value.putShort(serviceId); value.putShort(containerId); value.position(0); } return value; }

Target:
ByteBuffer getBytes() { ByteBuffer value; switch (version) { case PersistentIndex.VERSION_0: value = ByteBuffer.allocate(INDEX_VALUE_SIZE_IN_BYTES_V0); value.putLong(size); value.putLong(offset.getOffset()); value.put(flags); value.putLong(expiresAtMs); value.putLong(originalMessageOffset); value.position(0); break; case PersistentIndex.VERSION_1: value = ByteBuffer.allocate(INDEX_VALUE_SIZE_IN_BYTES_V1); value.putLong(size); value.putLong(offset.getOffset()); value.put(flags); value.putInt(expiresAtMs != Utils.Infinite_Time ? (int) (expiresAtMs / Time.MsPerSec) : (int) expiresAtMs); value.putLong(originalMessageOffset); value.putInt(operationTimeInMs != Utils.Infinite_Time ? (int) (operationTimeInMs / Time.MsPerSec) : (int) operationTimeInMs); value.putShort(serviceId); value.putShort(containerId); value.position(0); break; default: throw new IllegalArgumentException("Unsupported version " + version + " for IndexValue "); } return value; }
Source:
private void index(IFeatureModel childModel, IFeatureModel parentModel) { String childId = childModel.getFeature().getId(); Collection<IFeatureModel> parents = includingFeatures.get(childId); if (parents == null) { parents = new HashSet<>(); includingFeatures.put(childId, parents); } parents.add(parentModel); }

Target:
private void index(IFeatureModel childModel, IFeatureModel parentModel) { String childId = childModel.getFeature().getId(); Collection<IFeatureModel> parents = fIncludingFeatures.computeIfAbsent(childId, key -> new HashSet<>()); parents.add(parentModel); }
Source:
void load(final String type, final String value, final ConstraintType constraintType) { this.constraintValue = value; if (!Objects.isNull(value) && !value.isEmpty() && constraintType == null) { this.constraintType = inferComponentType(value); } else { this.constraintType = constraintType; } prepareView(type, value, constraintType); }

Target:
void load(final String type, final String value, final ConstraintType constraintType) { this.constraintValue = value; if (!StringUtils.isEmpty(value) && constraintType == null) { this.constraintType = inferComponentType(value); } else { this.constraintType = constraintType; } prepareView(type, value, constraintType); }
Source:
public CharSequence getContent() throws IllegalEditorStateException { if (!isAdded()) { throw new IllegalEditorStateException(); } if (mSourceView != null && mSourceView.getVisibility() == View.VISIBLE) { mContentHtml = mSourceViewContent.getText().toString(); return StringUtils.notNullStr(mContentHtml); } if (Looper.myLooper() == Looper.getMainLooper()) { AppLog.d(T.EDITOR, "getContent() called from UI thread"); } mGetContentCountDownLatch = new CountDownLatch(1); getActivity().runOnUiThread(new Runnable() { @Override public void run() { mWebView.execJavaScriptFromString("ZSSEditor.getField('zss_field_content').getHTMLForCallback();"); } }); try { mGetContentCountDownLatch.await(1, TimeUnit.SECONDS); } catch (InterruptedException e) { AppLog.e(T.EDITOR, e); Thread.currentThread().interrupt(); } mContentHtml = StringUtils.notNullStr(mContentHtml); if (mContentHtml.charAt(0) == '\u200B') { mContentHtml = mContentHtml.substring(1, mContentHtml.length()); } return mContentHtml; }

Target:
public CharSequence getContent() throws IllegalEditorStateException { if (!isAdded()) { throw new IllegalEditorStateException(); } if (mSourceView != null && mSourceView.getVisibility() == View.VISIBLE) { mContentHtml = mSourceViewContent.getText().toString(); return StringUtils.notNullStr(mContentHtml); } if (Looper.myLooper() == Looper.getMainLooper()) { AppLog.d(T.EDITOR, "getContent() called from UI thread"); } mGetContentCountDownLatch = new CountDownLatch(1); getActivity().runOnUiThread(new Runnable() { @Override public void run() { mWebView.execJavaScriptFromString("ZSSEditor.getField('zss_field_content').getHTMLForCallback();"); } }); try { mGetContentCountDownLatch.await(1, TimeUnit.SECONDS); } catch (InterruptedException e) { AppLog.e(T.EDITOR, e); Thread.currentThread().interrupt(); } return StringUtils.notNullStr(mContentHtml); }
Source:
public void update(InventoryScreen inventoryScreen, SolApplication solApplication) { Hero hero = solApplication.getGame().getHero(); SolItem selectedItem = inventoryScreen.getSelectedItem(); boolean itemPurchasable = (selectedItem != null && hero.getMoney() >= selectedItem.getPrice()); inventoryScreen.getInteractButton().setEnabled(itemPurchasable); inventoryScreen.setInteractText("Change"); }

Target:
public void update(InventoryScreen inventoryScreen, SolApplication solApplication) { Hero hero = solApplication.getGame().getHero(); SolItem selectedItem = inventoryScreen.getSelectedItem(); boolean itemPurchasable = (selectedItem != null && hero.getMoney() >= selectedItem.getPrice()); inventoryScreen.getInteractButton().setEnabled(itemPurchasable); }
Source:
public void add(long id) { if (id == 0) { throw new IllegalArgumentException(); } try { if (id > 0 && id <= 0x00000000FFFFFFFFL) { this.currentInts.get().add((int) id); } else { this.currentLongs.get().add(id); } } catch (IllegalArgumentException illegalArgumentException) { logger.warn( "There are too many entries within the disk-store, please execute an offline compaction.", illegalArgumentException); if (id > 0 && id <= 0x00000000FFFFFFFFL) { IntOpenHashSet overflownHashSet = new IntOpenHashSet((int) INVALID_ID); allInts.add(overflownHashSet); currentInts.set(overflownHashSet); currentInts.get().add((int) id); } else { LongOpenHashSet overflownHashSet = new LongOpenHashSet((int) INVALID_ID); allLongs.add(overflownHashSet); currentLongs.set(overflownHashSet); currentLongs.get().add(id); } } }

Target:
public void add(long id) { if (id == 0) { throw new IllegalArgumentException(); } try { if (id > 0 && id <= 0x00000000FFFFFFFFL) { this.currentInts.get().add((int) id); } else { this.currentLongs.get().add(id); } } catch (IllegalArgumentException illegalArgumentException) { logger.warn( "There is a large number of deleted entries within the disk-store, please execute an offline compaction."); if (id > 0 && id <= 0x00000000FFFFFFFFL) { IntOpenHashSet overflownHashSet = new IntOpenHashSet((int) INVALID_ID); allInts.add(overflownHashSet); currentInts.set(overflownHashSet); currentInts.get().add((int) id); } else { LongOpenHashSet overflownHashSet = new LongOpenHashSet((int) INVALID_ID); allLongs.add(overflownHashSet); currentLongs.set(overflownHashSet); currentLongs.get().add(id); } } }
Source:
public boolean isReadOnly() { DynaClass clazz = getDynaClass(); if(clazz instanceof WrapDynaClass){ return ((WrapDynaClass)clazz).getPropertyDescriptor(propertyName). getWriteMethod() == null; } return false; }

Target:
public boolean isReadOnly() { DynaClass clazz = getDynaClass(); if(clazz instanceof WrapDynaClass){ return ((WrapDynaClass)clazz).getPropertyDescriptor(propertyName). getWriteMethod() == null; } return readOnly; }
Source:
public void shouldSaveAllergyWithCodedAllergen() throws Exception { Allergy allergy = Context.getPatientService().getAllergyByUuid(getUuid()); Patient patient = allergy.getPatient(); String json = "{\"allergen\": {\"allergenType\":\"DRUG\", \"codedAllergen\": { \"uuid\": \"35d3346a-6769-4d52-823f-b4b234bac3e3\"} }}"; handle(newPostRequest(getURI(), json)); Allergies allergies = Context.getPatientService().getAllergies(patient); Assert.assertEquals(allergies.size(), 5); }

Target:
public void shouldSaveAllergyWithCodedAllergen() throws Exception { Allergy allergy = Context.getPatientService().getAllergyByUuid(getUuid()); Patient patient = allergy.getPatient(); Allergies allergies = Context.getPatientService().getAllergies(patient); Assert.assertEquals(allergies.size(), 4); String json = "{" + " \"comment\" : \"allergy comment\"," + " \"severity\" : { \"uuid\" : \"35d3346a-6769-4d52-823f-b4b234bac3e3\"}," + " \"allergen\" : " + " { \"allergenType\" : \"DRUG\", " + " \"codedAllergen\" : { \"uuid\" : \"35d3346a-6769-4d52-823f-b4b234bac3e3\"} " + " } " + "}"; SimpleObject savedAllergy = deserialize(handle(newPostRequest(getURI(), json))); Assert.assertEquals("allergy comment", Util.getByPath(savedAllergy, "comment")); Assert.assertEquals("35d3346a-6769-4d52-823f-b4b234bac3e3", Util.getByPath(savedAllergy, "severity/uuid")); Assert.assertEquals("35d3346a-6769-4d52-823f-b4b234bac3e3", Util.getByPath(savedAllergy, "allergen/codedAllergen/uuid")); Assert.assertEquals("DRUG", Util.getByPath(savedAllergy, "allergen/allergenType")); allergies = Context.getPatientService().getAllergies(patient); Assert.assertEquals(allergies.size(), 5); }
Source:
public List<KnowledgeMotionDataRow> translate(File file) throws IOException { Reader reader = new FileReader(file); Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(reader); List<KnowledgeMotionDataRow> result = new ArrayList<>(); for (CSVRecord record : records) { String source = record.get(KnowledgeMotionSpreadsheetColumn.SOURCE.getFieldName()); String id = record.get(KnowledgeMotionSpreadsheetColumn.ID.getFieldName()); String title = record.get(KnowledgeMotionSpreadsheetColumn.TITLE.getFieldName()); String description = record.get(KnowledgeMotionSpreadsheetColumn.DESCRIPTION.getFieldName()); String date = record.get(KnowledgeMotionSpreadsheetColumn.DATE.getFieldName()); String duration = record.get(KnowledgeMotionSpreadsheetColumn.DURATION.getFieldName()); String keywordsString = record.get(KnowledgeMotionSpreadsheetColumn.KEYWORDS.getFieldName()); String altId = record.get(KnowledgeMotionSpreadsheetColumn.ALT_ID.getFieldName()); List<String> keywords = new ArrayList<>(); Matcher keywordMatcher = KEYWORDS.matcher(keywordsString); while (keywordMatcher.find()) { keywords.add(keywordMatcher.group(1)); } result.add(new KnowledgeMotionDataRow(source, id, title, description, date, duration, keywords, altId)); } return result; }

Target:
public List<KnowledgeMotionDataRow> translate(File file) throws IOException { Reader reader = new FileReader(file); Iterator<CSVRecord> records = CSVFormat.RFC4180.withHeader(HEADER).parse(reader).iterator(); records.next(); ImmutableList.Builder<KnowledgeMotionDataRow> resultBuilder = ImmutableList.builder(); while (records.hasNext()) { CSVRecord record = records.next(); String source = record.get(KnowledgeMotionSpreadsheetColumn.SOURCE.getFieldName()); String id = record.get(KnowledgeMotionSpreadsheetColumn.ID.getFieldName()); String title = record.get(KnowledgeMotionSpreadsheetColumn.TITLE.getFieldName()); String description = record.get(KnowledgeMotionSpreadsheetColumn.DESCRIPTION.getFieldName()); String date = record.get(KnowledgeMotionSpreadsheetColumn.DATE.getFieldName()); String duration = record.get(KnowledgeMotionSpreadsheetColumn.DURATION.getFieldName()); String keywordsString = record.get(KnowledgeMotionSpreadsheetColumn.KEYWORDS.getFieldName()); String altId = record.get(KnowledgeMotionSpreadsheetColumn.ALT_ID.getFieldName()); List<String> keywords = new ArrayList<>(); Matcher keywordMatcher = KEYWORDS.matcher(keywordsString); while (keywordMatcher.find()) { keywords.add(keywordMatcher.group(1)); } resultBuilder.add(new KnowledgeMotionDataRow(source, id, title, description, date, duration, keywords, altId)); } return resultBuilder.build(); }