auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static DocumentModel moveContentToColdStorage(CoreSession session, DocumentRef documentRef) { DocumentModel documentModel = session.getDocument(documentRef); log.debug("Move to cold storage the main content of document: {}", documentModel); Serializable mainContent = documentModel.getPropertyValue(FILE_CONTENT_PROPERTY); if (mainContent == null) { throw new NuxeoException(String.format("There is no main content for document: %s.", documentModel), SC_NOT_FOUND); } if (documentModel.hasFacet(FacetNames.COLD_STORAGE) && documentModel.getPropertyValue(COLD_STORAGE_CONTENT_PROPERTY) != null) { throw new NuxeoException( String.format("The main content for document: %s is already in cold storage.", documentModel), SC_CONFLICT); } documentModel.addFacet(FacetNames.COLD_STORAGE); documentModel.setPropertyValue(COLD_STORAGE_CONTENT_PROPERTY, mainContent); Blob thumbnail = Framework.getService(ThumbnailService.class).getThumbnail(documentModel, session); documentModel.setPropertyValue(FILE_CONTENT_PROPERTY, (Serializable) thumbnail); return session.saveDocument(documentModel); }

Target:
public static DocumentModel moveContentToColdStorage(CoreSession session, DocumentRef documentRef) { DocumentModel documentModel = session.getDocument(documentRef); log.debug("Move to cold storage the main content of document: {}", documentModel); if (documentModel.hasFacet(FacetNames.COLD_STORAGE) && documentModel.getPropertyValue(COLD_STORAGE_CONTENT_PROPERTY) != null) { throw new NuxeoException( String.format("The main content for document: %s is already in cold storage.", documentModel), SC_CONFLICT); } Serializable mainContent = documentModel.getPropertyValue(FILE_CONTENT_PROPERTY); if (mainContent == null) { throw new NuxeoException(String.format("There is no main content for document: %s.", documentModel), SC_NOT_FOUND); } documentModel.addFacet(FacetNames.COLD_STORAGE); documentModel.setPropertyValue(COLD_STORAGE_CONTENT_PROPERTY, mainContent); documentModel.setPropertyValue(FILE_CONTENT_PROPERTY, null); return documentModel; }
Source:
public void scanFile(JavaFileScannerContext context) { this.context = context; statementSet.clear(); scan(context.getTree()); }

Target:
public void scanFile(JavaFileScannerContext context) { this.context = context; scan(context.getTree()); }
Source:
@Test public void testTransitiveInferenceConjunctInPullUp() throws Exception { final String sql = "select 1 from sales.emp d" + " inner join sales.emp e on d.deptno = e.deptno" + " where d.deptno in (7, 9) or d.deptno > 10"; transitiveInference(sql); }

Target:
@Test public void testTransitiveInferenceConjunctInPullUp() throws Exception { final String sql = "select 1 from sales.emp d\n" + "inner join sales.emp e on d.deptno = e.deptno\n" + "where d.deptno in (7, 9) or d.deptno > 10"; sql(sql).withPre(getTransitiveProgram()) .withRule(JoinPushTransitivePredicatesRule.INSTANCE).check(); }
Source:
protected Object convertMap(Object value) { Map map = (Map) value; if (map.isEmpty()) { return null; } Map<Object, Object> convertedMap = new HashMap<>(); for (Object key : map.keySet()) { Object convertedValue = null; if (key != null) { convertedValue = convert(map.get(key)); } convertedMap.put(convertSingleValue(key), convertedValue); } return convertedMap; }

Target:
protected Object convertMap(Object value) { Map<Object, Object> map = (Map) value; if (map.isEmpty()) { return null; } Map<Object, Object> convertedMap = new HashMap<>(); for (Map.Entry<Object, Object> entry : map.entrySet()) { Object mapKey = entry.getKey(); Object mapValue = entry.getValue(); if (mapKey != null) { Object convertedMapValue = null; if (mapValue != null) { convertedMapValue = convert(mapValue); } if (convertedMapValue != null) { convertedMap.put(convertSingleValue(entry.getKey()), convertedMapValue); } } } if (convertedMap.isEmpty()) { return null; } return convertedMap; }
Source:
public void buildCallbacksForEntity(String entityClassName, CallbackRegistrar callbackRegistrar) { final boolean debugEnabled = log.isDebugEnabled(); try { final XClass entityXClass = reflectionManager.classForName( entityClassName ); final Class entityClass = reflectionManager.toClass( entityXClass ); for ( CallbackType callbackType : CallbackType.values() ) { if ( callbackRegistrar.hasRegisteredCallbacks( entityClass, callbackType ) ) { if ( debugEnabled ) { log.debugf( "CallbackRegistry reported that Class [%s] already had %s callbacks registered; " + "assuming this means the class was mapped twice " + "(using hbm.xml entity-name support) - skipping subsequent registrations", entityClassName, callbackType.getCallbackAnnotation().getSimpleName() ); } continue; } final Callback[] callbacks = AccessController.doPrivileged( new PrivilegedAction<Callback[]>() { @Override public Callback[] run() { return resolveEntityCallbacks( entityXClass, callbackType, reflectionManager ); } } ); callbackRegistrar.registerCallbacks( entityClass, callbacks ); } } catch (ClassLoadingException e) { throw new MappingException( "entity class not found: " + entityClassName, e ); } }

Target:
public void buildCallbacksForEntity(String entityClassName, CallbackRegistrar callbackRegistrar) { final boolean debugEnabled = log.isDebugEnabled(); try { final XClass entityXClass = reflectionManager.classForName( entityClassName ); final Class entityClass = reflectionManager.toClass( entityXClass ); for ( CallbackType callbackType : CallbackType.values() ) { if ( callbackRegistrar.hasRegisteredCallbacks( entityClass, callbackType ) ) { if ( debugEnabled ) { log.debugf( "CallbackRegistry reported that Class [%s] already had %s callbacks registered; " + "assuming this means the class was mapped twice " + "(using hbm.xml entity-name support) - skipping subsequent registrations", entityClassName, callbackType.getCallbackAnnotation().getSimpleName() ); } continue; } final Callback[] callbacks = resolveEntityCallbacks( entityXClass, callbackType, reflectionManager ); callbackRegistrar.registerCallbacks( entityClass, callbacks ); } } catch (ClassLoadingException e) { throw new MappingException( "entity class not found: " + entityClassName, e ); } }
Source:
private void waitForRedirectIfAny() { String loginRedirectUrl = Config.APP_URL + "/_"; WebDriverWait wait = new WebDriverWait(browser.driver, TestProperties.TEST_TIMEOUT); wait.until((WebDriver d) -> { String url = d.getCurrentUrl(); boolean isTeammatesPage = url.startsWith(Config.APP_URL) && !url.startsWith(loginRedirectUrl); boolean isApprovalPage = d.getPageSource().contains(EXPECTED_SNIPPET_APPROVAL); return isTeammatesPage || isApprovalPage; }); }

Target:
private void waitForRedirectIfAny() { String loginRedirectUrl = TestProperties.TEAMMATES_URL + "/_ah/conflogin"; WebDriverWait wait = new WebDriverWait(browser.driver, TestProperties.TEST_TIMEOUT); wait.until((WebDriver d) -> { String url = d.getCurrentUrl(); boolean isTeammatesPage = url.startsWith(TestProperties.TEAMMATES_URL) && !url.startsWith(loginRedirectUrl); boolean isApprovalPage = d.getPageSource().contains(EXPECTED_SNIPPET_APPROVAL); return isTeammatesPage || isApprovalPage; }); }
Source:
public void failureOriginMetrics() { navigation.selectRow().invoke("View"); Application.waitUntilVisible(); MetricsAreaFragment metricsArea = tmPage.getFailureOriginMetricsArea(); MetricsFragment appFailuresMetrics = metricsArea.getMetricsFragment(APPLICATION_FAILURES); MetricsFragment resFailuresMetrics = metricsArea.getMetricsFragment(RESOURCE_FAILURES); assertEquals(metricsArea.getMetricNumber(APPLICATION_FAILURES), appFailuresMetrics.getCurrentValue(), DELTA); assertEquals(metricsArea.getMetricNumber(RESOURCE_FAILURES), resFailuresMetrics.getCurrentValue(), DELTA); }

Target:
public void failureOriginMetrics(){ MetricsAreaFragment metricsArea = tmPage.getFailureOriginMetricsArea(); MetricsFragment appFailuresMetrics = metricsArea.getMetricsFragment(APPLICATION_FAILURES); MetricsFragment resFailuresMetrics = metricsArea.getMetricsFragment(RESOURCE_FAILURES); assertEquals(metricsArea.getMetricNumber(APPLICATION_FAILURES), appFailuresMetrics.getCurrentValue(), DELTA); assertEquals(metricsArea.getMetricNumber(RESOURCE_FAILURES), resFailuresMetrics.getCurrentValue(), DELTA); }
Source:
public Parameter(String name, Type type, boolean mappingTarget, boolean targetType, boolean mappingContext) { this.name = "values".equals( name ) ? "values_" : name; this.originalName = name; this.type = type; this.mappingTarget = mappingTarget; this.targetType = targetType; this.mappingContext = mappingContext; }

Target:
private Parameter(String name, Type type, boolean mappingTarget, boolean targetType, boolean mappingContext) { this.name = "values".equals( name ) ? "values_" : name; this.originalName = name; this.type = type; this.mappingTarget = mappingTarget; this.targetType = targetType; this.mappingContext = mappingContext; }
Source:
public void testDeployment() throws Exception { final ModelControllerClient client = managementClient.getControllerClient(); final ServerDeploymentManager manager = ServerDeploymentManager.Factory.create(client); try (final InputStream is = testDeploymentFile.getInputStream()){ Future<?> future = manager.execute( manager.newDeploymentPlan().add(testDeploymentFile.getName(), is).deploy(testDeploymentFile.getName()).build()); awaitDeploymentExecution(future); } ModelNode findDeployment = Util.createEmptyOperation(READ_RESOURCE_OPERATION, PathAddress.pathAddress(DEPLOYMENT, testDeploymentFile.getName())); Assert.assertTrue( managementClient.executeForResult(findDeployment).isDefined()); Future<?> future = manager.execute(manager.newDeploymentPlan().undeploy(testDeploymentFile.getName()).remove(testDeploymentFile.getName()).build()); awaitDeploymentExecution(future); ModelNode result = client.execute(findDeployment); Assert.assertEquals(FAILED, result.get(OUTCOME).asString()); }

Target:
public void testDeployment() throws Exception { final ModelControllerClient client = managementClient.getControllerClient(); final ServerDeploymentManager manager = ServerDeploymentManager.Factory.create(client); Future<?> future = manager.execute( manager.newDeploymentPlan().add(testDeploymentFile.getName(), testDeploymentFile.getFile()).deploy(testDeploymentFile.getName()).build()); awaitDeploymentExecution(future); ModelNode findDeployment = Util.createEmptyOperation(READ_RESOURCE_OPERATION, PathAddress.pathAddress(DEPLOYMENT, testDeploymentFile.getName())); Assert.assertTrue( managementClient.executeForResult(findDeployment).isDefined()); future = manager.execute(manager.newDeploymentPlan().undeploy(testDeploymentFile.getName()).remove(testDeploymentFile.getName()).build()); awaitDeploymentExecution(future); ModelNode result = client.execute(findDeployment); Assert.assertEquals(FAILED, result.get(OUTCOME).asString()); }
Source:
public void postCollectionDefaultBitstreamReadGroupCreateDefaultBitstreamReadGroupDcTitleUnprocessable() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); metadataRest.put("dc.title", new MetadataValueRest("testTitle")); groupRest.setMetadata(metadataRest); AtomicReference<UUID> idRef = new AtomicReference<>(); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(post("/api/core/collections/" + collection.getID() + "/bitstreamReadGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isUnprocessableEntity()); }

Target:
public void postCollectionDefaultBitstreamReadGroupCreateDefaultBitstreamReadGroupDcTitleUnprocessable() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); metadataRest.put("dc.title", new MetadataValueRest("testTitle")); groupRest.setMetadata(metadataRest); AtomicReference<UUID> idRef = new AtomicReference<>(); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(post("/api/core/collections/" + collection.getID() + "/bitstreamReadGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isUnprocessableEntity()); Group anon = groupService.findByName(context, Group.ANONYMOUS); getClient(token).perform(get("/api/core/collections/" + collection.getID() + "/bitstreamReadGroup")) .andExpect(status().isOk()) .andExpect( jsonPath("$", GroupMatcher.matchGroupEntry(anon.getID(), anon.getName()))); }
Source:
public void onDownload(final Supplier<Path> pathSupplier) { final String downloadURL = getFileDownloadURL(pathSupplier); open(downloadURL); }

Target:
protected void onDownload(final Supplier<Path> pathSupplier) { final String downloadURL = getFileDownloadURL(pathSupplier); open(downloadURL); }
Source:
public NamingStrategy(NamingConvention javaConvention, NamingConvention cassandraConvention) { setJavaConvention(javaConvention); setCassandraConvention(cassandraConvention); enable(); }

Target:
public NamingStrategy(NamingConvention javaConvention, NamingConvention cassandraConvention) { if (javaConvention == null || cassandraConvention == null) { throw new IllegalArgumentException("input/output NamingConvention cannot be null"); } this.javaConvention = javaConvention; this.cassandraConvention = cassandraConvention; this.enabled = true; }
Source:
private static long getNumOfPartitions(TableDescriptor td) throws StandardException { String tableId = Long.toString(td.getBaseConglomerateDescriptor().getConglomerateNumber()); byte[] table = Bytes.toBytes(tableId); Partition root = null; try { long result = 1; root = SIDriver.driver().getTableFactory().getTable(table); if (root != null) result = root.subPartitions(true).size(); return result; } catch (Exception ioe) { throw StandardException.plainWrapException(ioe); } finally { try { if (root != null) root.close(); } catch (IOException e) { throw StandardException.plainWrapException(e); } } }

Target:
private static long getNumOfPartitions(TableDescriptor td) throws StandardException { String tableId = Long.toString(td.getBaseConglomerateDescriptor().getConglomerateNumber()); byte[] table = Bytes.toBytes(tableId); try (Partition root = SIDriver.driver().getTableFactory().getTable(table)) { return root != null ? root.subPartitions(true).size() : 1; } catch (Exception ioe) { throw StandardException.plainWrapException(ioe); } }
Source:
public ByteBuf copy(int index, int length) { checkIndex(index, length); UnpooledHeapByteBuf copy = new UnpooledHeapByteBuf(alloc(), length, maxCapacity()); System.arraycopy(array, index, copy.array, 0, length); return copy.writerIndex(length); }

Target:
public ByteBuf copy(int index, int length) { checkIndex(index, length); return alloc().heapBuffer(length, maxCapacity()).writeBytes(array, index, length); }
Source:
private SortedSet<ActionParameterRequest> buildActionParameters(FormSchemaJson form) { SortedSet<ActionParameterRequest> parameters = new TreeSet<>(); int order = 0; ActionParameterRequestBuilder builder; for (FormSchemaQuestionJson question : form.getQuestions()) { builder = new ActionParameterRequestBuilder(); String displayName = StringUtils.isBlank(question.getQuestionLabel()) ? question.getQuestionValue() : question.getQuestionLabel(); if (displayName.length() > MAX_LABEL_LENGTH) { displayName = displayName.substring(0, MAX_LABEL_LENGTH); } builder.setDisplayName(displayName) .setKey(question.getQuestionValue()) .setOrder(order++); if (question.getOptions() != null && !question.getOptions().isEmpty()) { builder.setType(ParameterType.SELECT.getValue()); builder.setOptions(convertCommcareoptionsToTaskActionOptions(question.getOptions())); } else { builder.setType(ParameterType.UNICODE.getValue()); } parameters.add(builder.createActionParameterRequest()); } builder = new ActionParameterRequestBuilder(); builder.setValue(form.getXmlns()) .setDisplayName("xmlns") .setKey("xmlns") .setOrder(order++) .setType(ParameterType.UNICODE.getValue()) .setHidden(true); parameters.add(builder.createActionParameterRequest()); return parameters; }

Target:
private SortedSet<ActionParameterRequest> buildActionParameters(FormSchemaJson form) { SortedSet<ActionParameterRequest> parameters = new TreeSet<>(); int order = 0; ActionParameterRequestBuilder builder; for (FormSchemaQuestionJson question : form.getQuestions()) { builder = new ActionParameterRequestBuilder(); String displayName = StringUtils.isBlank(question.getQuestionLabel()) ? question.getQuestionValue() : question.getQuestionLabel(); if (displayName.length() > MAX_LABEL_LENGTH) { displayName = displayName.substring(0, MAX_LABEL_LENGTH); } builder.setDisplayName(displayName) .setKey(question.getQuestionValue()) .setOrder(order++); if (question.getOptions() != null && !question.getOptions().isEmpty()) { builder.setType(ParameterType.SELECT.getValue()); builder.setOptions(convertCommcareoptionsToTaskActionOptions(question.getOptions())); } else { builder.setType(ParameterType.UNICODE.getValue()); } parameters.add(builder.createActionParameterRequest()); } parameters.add(addXmlnsParameter(form, order)); return parameters; }
Source:
public Group(String name, Id id, List<User> connectedUsers) throws NodeException { super(name, id); if (connectedUsers == null){ throw new NodeException("Error, null list in Group constructor"); } this.connectedUsers = new ArrayList<>(connectedUsers); }

Target:
public Group(String name, Id id, List<User> connectedUsers){ super(name, id); Objects.requireNonNull(connectedUsers); this.connectedUsers = new ArrayList<>(connectedUsers); }
Source:
private static <T> T doGetMapper(Class<T> clazz, ClassLoader classLoader) throws NoSuchMethodException { try { @SuppressWarnings("unchecked") Class<T> implementation = (Class<T>) classLoader.loadClass( clazz.getName() + IMPLEMENTATION_SUFFIX ); Constructor<T> constructor = implementation.getDeclaredConstructor((Class<?>[]) null); constructor.setAccessible(true); return constructor.newInstance((Object[]) null); } catch (ClassNotFoundException e) { ServiceLoader<T> loader = ServiceLoader.load( clazz, classLoader ); if ( loader != null ) { for ( T mapper : loader ) { if ( mapper != null ) { return mapper; } } } return null; } catch (InstantiationException e) { throw new RuntimeException( e ); } catch (IllegalAccessException e) { throw new RuntimeException( e ); } catch (InvocationTargetException e) { throw new RuntimeException( e ); } }

Target:
private static <T> T doGetMapper(Class<T> clazz, ClassLoader classLoader) throws NoSuchMethodException { try { @SuppressWarnings( "unchecked" ) Class<T> implementation = (Class<T>) classLoader.loadClass( clazz.getName() + IMPLEMENTATION_SUFFIX ); Constructor<T> constructor = implementation.getDeclaredConstructor(); constructor.setAccessible( true ); return constructor.newInstance(); } catch (ClassNotFoundException e) { ServiceLoader<T> loader = ServiceLoader.load( clazz, classLoader ); if ( loader != null ) { for ( T mapper : loader ) { if ( mapper != null ) { return mapper; } } } return null; } catch (InstantiationException e) { throw new RuntimeException( e ); } catch (IllegalAccessException e) { throw new RuntimeException( e ); } catch (InvocationTargetException e) { throw new RuntimeException( e ); } }
Source:
public Set<RexNode> getExpressionLineage(Calc calc, RelMetadataQuery mq, RexNode outputExpression) { final RelNode input = calc.getInput(); final RexBuilder rexBuilder = calc.getCluster().getRexBuilder(); final ImmutableBitSet inputFieldsUsed = extractInputRefs(outputExpression); final Map<RexInputRef, Set<RexNode>> mapping = new LinkedHashMap<>(); Pair<ImmutableList<RexNode>, ImmutableList<RexNode>> calcFilterAndProjects = calc.getProgram().split(); for (int idx : inputFieldsUsed) { final RexNode inputExpr = calcFilterAndProjects.getKey().get(idx); final Set<RexNode> originalExprs = mq.getExpressionLineage(input, inputExpr); if (originalExprs == null) { return null; } final RexInputRef ref = RexInputRef.of(idx, calc.getRowType().getFieldList()); mapping.put(ref, originalExprs); } return createAllPossibleExpressions(rexBuilder, outputExpression, mapping); }

Target:
public Set<RexNode> getExpressionLineage(Calc calc, RelMetadataQuery mq, RexNode outputExpression) { final RelNode input = calc.getInput(); final RexBuilder rexBuilder = calc.getCluster().getRexBuilder(); final ImmutableBitSet inputFieldsUsed = extractInputRefs(outputExpression); final Map<RexInputRef, Set<RexNode>> mapping = new LinkedHashMap<>(); Pair<ImmutableList<RexNode>, ImmutableList<RexNode>> calcProjectsAndFilter = calc.getProgram().split(); for (int idx : inputFieldsUsed) { final RexNode inputExpr = calcProjectsAndFilter.getKey().get(idx); final Set<RexNode> originalExprs = mq.getExpressionLineage(input, inputExpr); if (originalExprs == null) { return null; } final RexInputRef ref = RexInputRef.of(idx, calc.getRowType().getFieldList()); mapping.put(ref, originalExprs); } return createAllPossibleExpressions(rexBuilder, outputExpression, mapping); }
Source:
public boolean equals(Object obj) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } IterableMappingMethod other = (IterableMappingMethod) obj; if ( !getResultType().equals( other.getResultType() ) ) { return false; } if ( getSourceParameters().size() != other.getSourceParameters().size() ) { return false; } for ( int i = 0; i < getSourceParameters().size(); i++ ) { List<Type> thisTypeParameters = getSourceParameters().get( i ).getType().getTypeParameters(); List<Type> otherTypeParameters = other.getSourceParameters().get( i ).getType().getTypeParameters(); if ( !thisTypeParameters.equals( otherTypeParameters ) ) { return false; } } if ( this.selectionParameters != null ) { if ( !this.selectionParameters.equals( other.selectionParameters ) ) { return false; } } else if ( other.selectionParameters == null ) { return false; } return true; }

Target:
public boolean equals(Object obj) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } IterableMappingMethod other = (IterableMappingMethod) obj; if ( !getResultType().equals( other.getResultType() ) ) { return false; } if ( getSourceParameters().size() != other.getSourceParameters().size() ) { return false; } for ( int i = 0; i < getSourceParameters().size(); i++ ) { List<Type> thisTypeParameters = getSourceParameters().get( i ).getType().getTypeParameters(); List<Type> otherTypeParameters = other.getSourceParameters().get( i ).getType().getTypeParameters(); if ( !thisTypeParameters.equals( otherTypeParameters ) ) { return false; } } if ( this.selectionParameters != null ) { if ( !this.selectionParameters.equals( other.selectionParameters ) ) { return false; } } else if ( other.selectionParameters != null ) { return false; } return true; }
Source:
public void defersToIndividualStepsIfStartTransactionNotAvailable() { givenServerThrows404sOnStartTransaction(); whenStandardClientStartsTransactionNTimes(1); thenStartTransactionIsCalledNTimes(1); thenIndividualEndpointsAreCalledNTimes(1); thenNoCallsFailed(); }

Target:
public void defersToIndividualStepsIfStartTransactionNotAvailable() { givenServerThrows404sOnStartTransaction(); whenStandardClientStartsTransactionTimes(1); thenStartTransactionIsCalledTimes(1); thenIndividualEndpointsAreCalledTimes(1); thenNoCallsFailed(); }
Source:
private void makeNode(Node node) { nodes.append(" "); nodes.append(node.hashCode()); nodes.append(" ["); nodes.append("label=\"" + node.toString().replace("\"", "\\\"") + "\n" + node.getLocation().toString().replace("\"", "\\\"") + "\" "); nodes.append("color=\"" + describeColor(node.getColor()) + "\" ");; nodes.append("fillcolor=\"" + describeColor(node.getColor().brighter().brighter()) + "\""); nodes.append("];\n"); }

Target:
private void makeNode(Node node) { nodes.append(" "); nodes.append(node.hashCode()); nodes.append(" ["); String label = node.toString() + "\n" + node.getLocation().toString(); nodes.append("label=\"" + label.replace("\"", "\\\"").replace("\\", "\\\\") + "\" "); nodes.append("color=\"" + describeColor(node.getColor()) + "\" ");; nodes.append("fillcolor=\"" + describeColor(node.getColor().brighter().brighter()) + "\""); nodes.append("];\n"); }
Source:
static NetworkConfiguration createNetworkConfiguration(){ AzureTokenCredentials token = new ApplicationTokenCredentials( System.getenv("CLIENT_ID"), "72f988bf-86f1-41af-91ab-2d7cd011db47", System.getenv("APPLICATION_SECRET"), AzureEnvironment.AZURE); Azure azure = Azure.authenticate(token).withSubscription(System.getenv("AZURE_BATCH_SUBSCRIPTION_ID")); String vnetName = "AzureBatchTestVnet"; String subnetName = "AzureBatchTestSubnet"; if (azure.networks().list().size() == 0) { Network virtualNetwork = azure.networks().define(vnetName) .withRegion("westcentralus") .withExistingResourceGroup("sdktest2") .withAddressSpace("192.168.0.0/16") .withSubnet(subnetName, "192.168.1.0/24") .create(); } String vNetResourceId = String.format( "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/virtualNetworks/%s/subnets/%s", System.getenv("677f962b-9abf-4423-a27b-0c2f4094dcec"), "sdktest2", vnetName, subnetName); return new NetworkConfiguration().withSubnetId(vNetResourceId); }

Target:
static NetworkConfiguration createNetworkConfiguration(){ String vnetName = "AzureBatchTestVnet"; String subnetName = "AzureBatchTestSubnet"; if(isRecordMode()) { AzureTokenCredentials token = new ApplicationTokenCredentials( System.getenv("CLIENT_ID"), "72f988bf-86f1-41af-91ab-2d7cd011db47", System.getenv("APPLICATION_SECRET"), AzureEnvironment.AZURE); Azure azure = Azure.authenticate(token).withSubscription("677f962b-9abf-4423-a27b-0c2f4094dcec"); if (azure.networks().list().size() == 0) { Network virtualNetwork = azure.networks().define(vnetName) .withRegion("westcentralus") .withExistingResourceGroup("sdktest2") .withAddressSpace("192.168.0.0/16") .withSubnet(subnetName, "192.168.1.0/24") .create(); } } String vNetResourceId = String.format( "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/virtualNetworks/%s/subnets/%s", "677f962b-9abf-4423-a27b-0c2f4094dcec", "sdktest2", vnetName, subnetName); return new NetworkConfiguration().withSubnetId(vNetResourceId); }
Source:
private long getCacheScopeSizeInBytes(long cacheScopeIdentifier) { long sum = 0; for (Path path : cacheScopeFiles.get(cacheScopeIdentifier)) { CacheRange cacheRange = persistedRanges.get(path); Lock readLock = cacheRange.getLock().readLock(); readLock.lock(); try { for (Range<Long> range : cacheRange.getRange().asDescendingMapOfRanges().keySet()) { sum += range.upperEndpoint() - range.lowerEndpoint(); } } finally { readLock.unlock(); } } return sum; }

Target:
private long getCacheScopeSizeInBytes(long cacheScopeIdentifier) { long bytes = 0; for (Path path : cacheScopeFiles.get(cacheScopeIdentifier)) { CacheRange cacheRange = persistedRanges.get(path); Lock readLock = cacheRange.getLock().readLock(); readLock.lock(); try { for (Range<Long> range : cacheRange.getRange().asDescendingMapOfRanges().keySet()) { bytes += range.upperEndpoint() - range.lowerEndpoint(); } } finally { readLock.unlock(); } } return bytes; }
Source:
protected void next(String email) { if (!NetworkUtils.checkConnection(getActivity())) { return; } if (isValidEmail(email)) { clearEmailError(); startProgress(); mRequestedEmail = email; mDispatcher.dispatch(AccountActionBuilder.newIsAvailableEmailAction(email)); mAnalyticsListener.trackEmailFilled(); } else { showEmailError(R.string.email_invalid); } }

Target:
protected void next(String email) { if (!NetworkUtils.checkConnection(getActivity())) { return; } if (isValidEmail(email)) { clearEmailError(); startProgress(); mRequestedEmail = email; mDispatcher.dispatch(AccountActionBuilder.newIsAvailableEmailAction(email)); } else { showEmailError(R.string.email_invalid); } }
Source:
protected static String calculateMethodCanonicalName(Class<?> methodClass, String methodName) { StringBuilder result = new StringBuilder(); Set<Method> methods = ClassHelper.getAvailableMethods(methodClass); methods.stream() .filter(method -> methodName.equals(method.getName())) .findFirst() .ifPresent(method -> result.append(calculateMethodCanonicalName(method))); return result.length() == 0 ? null : result.toString(); }

Target:
protected static String calculateMethodCanonicalName(Class<?> methodClass, String methodName) { Set<Method> methods = ClassHelper.getAvailableMethods(methodClass); return methods.stream() .filter(method -> methodName.equals(method.getName())) .findFirst() .map(MethodHelper::calculateMethodCanonicalName) .orElse(null); }
Source:
private void updateConnectionMapForFiberChannel(Set<StorageDomainStatus> statuses) { if (FeatureSupported.refreshLunSupported(getStoragePool().getCompatibilityVersion())) { List<StorageDomain> storageDomainList = getStorageDomainDao().getAllForStoragePool(getStoragePool().getId()); for (StorageDomain sd : storageDomainList) { if ((sd.getStorageType() == StorageType.FCP) && statuses.contains(sd.getStatus())) { MultiValueMapUtils.addToMap(StorageType.FCP, FCPStorageHelper.getFCPConnection(), getConnectionsTypeMap()); break; } } } }

Target:
private void updateConnectionMapForFiberChannel(Set<StorageDomainStatus> statuses) { if (FeatureSupported.refreshLunSupported(getStoragePool().getCompatibilityVersion())) { List<StorageDomain> storageDomainList = getStorageDomainDao().getAllForStoragePool(getStoragePool().getId()); for (StorageDomain sd : storageDomainList) { if (sd.getStorageType() == StorageType.FCP && statuses.contains(sd.getStatus())) { MultiValueMapUtils.addToMap(StorageType.FCP, FCPStorageHelper.getFCPConnection(), getConnectionsTypeMap()); break; } } } }
Source:
public Mono<Instant> renewMessageLock(ServiceBusReceivedMessage messageForLockRenew) { return renewMessageLock(new ServiceBusReceivedMessage[]{messageForLockRenew}) .elementAt(0) .publishOn(scheduler); }

Target:
public Mono<Instant> renewMessageLock(ServiceBusReceivedMessage messageForLockRenew) { return renewMessageLock(new ServiceBusReceivedMessage[]{messageForLockRenew}) .last() .publishOn(scheduler); }
Source:
private Field getField(ConstraintViolation<?> firstException) { Class<?> leafBean = firstException.getLeafBean().getClass(); String fieldName = getLastElementOfPath(firstException.getPropertyPath()); try { return leafBean.getField(fieldName); } catch (NoSuchFieldException e) { LOGGER.error(String.format("Field %s does not exist on class %s", fieldName, leafBean.toString())); throw new WebApplicationException(e); } }

Target:
private Field getField(ConstraintViolation<?> firstException) { Class<?> leafBean = firstException.getLeafBean().getClass(); String fieldName = getFieldNameFromPath(firstException.getPropertyPath()); try { return leafBean.getField(fieldName); } catch (NoSuchFieldException e) { LOGGER.error(String.format("Cannot process violation exception. " + "Field %s does not exist or is not public on class %s", fieldName, leafBean.toString())); throw new WebApplicationException(e); } }
Source:
public void addLinks(String sourceId, List<String> targetIds, Session session) throws DirectoryException { if (readOnly) { return; } checkDualReference(); dualReference.addLinks(sourceId, targetIds, session); }

Target:
public void addLinks(String sourceId, List<String> targetIds, Session session) throws DirectoryException { if (readOnly) { return; } checkDualReference(); dualReference.addLinks(targetIds, sourceId, session); }
Source:
private static String ipBytesToString(ByteBuf header, int addressLen) { StringBuilder sb = new StringBuilder(); final int ipv4Len = 4; final int ipv6Len = 8; if (addressLen == ipv4Len) { for (int i = 0; i < ipv4Len; i++) { sb.append(header.readByte() & 0xff); sb.append('.'); } sb.setLength(sb.length() - 1); } else { for (int i = 0; i < ipv6Len; i++) { sb.append(Integer.toHexString(header.readUnsignedShort())); sb.append(':'); } sb.setLength(sb.length() - 1); } return sb.toString(); }

Target:
private static String ipBytesToString(ByteBuf header, int addressLen) { StringBuilder sb = new StringBuilder(); final int ipv4Len = 4; final int ipv6Len = 8; if (addressLen == ipv4Len) { for (int i = 0; i < ipv4Len; i++) { sb.append(header.readByte() & 0xff); sb.append('.'); } } else { for (int i = 0; i < ipv6Len; i++) { sb.append(Integer.toHexString(header.readUnsignedShort())); sb.append(':'); } } sb.setLength(sb.length() - 1); return sb.toString(); }
Source:
public static <C extends RdfCloudTripleStoreConfiguration> RyaQueryEngine<C> getQueryEngine(RdfCloudTripleStoreConfiguration conf) { if(conf instanceof AccumuloRdfConfiguration) { AccumuloRdfConfiguration aConf = (AccumuloRdfConfiguration) conf; Instance instance; String instanceName = aConf.get("sc.cloudbase.instancename"); String user = aConf.get("sc.cloudbase.username"); String password = aConf.get("sc.cloudbase.password"); if(aConf.getBoolean(".useMockInstance", false)) { instance = new MockInstance(instanceName); } else { String zookeepers = aConf.get("sc.cloudbase.zookeepers"); instance = new ZooKeeperInstance(instanceName, zookeepers); } Connector conn; try { conn = instance.getConnector(user, new PasswordToken(password)); } catch (AccumuloException | AccumuloSecurityException e) { throw new RuntimeException(e); } return (RyaQueryEngine<C>) new AccumuloRyaQueryEngine(conn, aConf); } else if(conf instanceof StatefulMongoDBRdfConfiguration && conf.getBoolean("sc.useMongo", false)) { StatefulMongoDBRdfConfiguration mongoConf = (StatefulMongoDBRdfConfiguration)conf; MongoDBQueryEngine mongoQueryEngine = new MongoDBQueryEngine(); mongoQueryEngine.setConf(mongoConf); return (RyaQueryEngine<C>) mongoQueryEngine; } else { throw new IllegalArgumentException("Invalid configuration type."); } }

Target:
public static <C extends RdfCloudTripleStoreConfiguration> RyaQueryEngine<C> getQueryEngine(RdfCloudTripleStoreConfiguration conf) { if(conf instanceof AccumuloRdfConfiguration) { AccumuloRdfConfiguration aConf = (AccumuloRdfConfiguration) conf; Instance instance; String instanceName = aConf.get("sc.cloudbase.instancename"); String user = aConf.get("sc.cloudbase.username"); String password = aConf.get("sc.cloudbase.password"); if(aConf.getBoolean(".useMockInstance", false)) { instance = new MockInstance(instanceName); } else { String zookeepers = aConf.get("sc.cloudbase.zookeepers"); instance = new ZooKeeperInstance(instanceName, zookeepers); } Connector conn; try { conn = instance.getConnector(user, new PasswordToken(password)); } catch (AccumuloException | AccumuloSecurityException e) { throw new RuntimeException(e); } return (RyaQueryEngine<C>) new AccumuloRyaQueryEngine(conn, aConf); } else if(conf instanceof StatefulMongoDBRdfConfiguration && ConfigUtils.getUseMongo(conf)) { StatefulMongoDBRdfConfiguration mongoConf = (StatefulMongoDBRdfConfiguration)conf; MongoDBQueryEngine mongoQueryEngine = new MongoDBQueryEngine(); mongoQueryEngine.setConf(mongoConf); return (RyaQueryEngine<C>) mongoQueryEngine; } else { throw new IllegalArgumentException("Invalid configuration type."); } }
Source:
public void scalarSubQueryInClause() { this.query() .select(employee) .from(employee) .where( SQLExpressions .select(employee.firstname) .from(employee) .orderBy(employee.salary.asc()) .limit(1) .in(Arrays.asList("Mike", "Mary")) ) .fetch(); }

Target:
public void scalarSubQueryInClause() { SQLSerializer serializer = new SQLSerializer(Configuration.DEFAULT); serializer.handle( this.query() .from(employee) .where( SQLExpressions .select(employee.firstname) .from(employee) .orderBy(employee.salary.asc()) .limit(1) .in(Arrays.asList("Mike", "Mary")) )); expectedQuery = "(\nfrom EMPLOYEE e\n" + "where (select e.FIRSTNAME\n" + "from EMPLOYEE e\n" + "order by e.SALARY asc\n" + "limit ?) in (?, ?))"; System.out.println(">>>> " + serializer.toString()); assertEquals(expectedQuery, serializer.toString()); }
Source:
private static CsvParserSettings createParserSettings(String delimiter, String lineSeparator, char quote, String emptyValue, int maxCharsPerColumn) { CsvParserSettings settings = new CsvParserSettings(); settings.getFormat().setDelimiter(delimiter); settings.getFormat().setLineSeparator(lineSeparator); settings.getFormat().setQuote(quote); settings.getFormat().setQuoteEscape(quote); settings.setEmptyValue(emptyValue); settings.setAutoConfigurationEnabled(false); settings.setMaxCharsPerColumn(maxCharsPerColumn == 0 ? DEFAULT_MAX_CHARS_PER_COLUMN : maxCharsPerColumn); return settings; }

Target:
private static CsvParserSettings createParserSettings(String delimiter, String lineSeparator, char quote, String emptyValue, int maxCharsPerColumn) { CsvParserSettings settings = new CsvParserSettings(); settings.getFormat().setDelimiter(delimiter); settings.getFormat().setLineSeparator(lineSeparator); settings.getFormat().setQuote(quote); settings.getFormat().setQuoteEscape(quote); settings.setEmptyValue(emptyValue); settings.setAutoConfigurationEnabled(false); Preconditions.condition(maxCharsPerColumn > 0, () -> "maxCharsPerColumn must be a positive number: " + maxCharsPerColumn); settings.setMaxCharsPerColumn(maxCharsPerColumn); return settings; }
Source:
public void afterClass() { if (_store != null) { _store.close(); } _baseAccessor.remove("/" + CLUSTER_NAME + "/ASSIGNMENT_METADATA", AccessOption.PERSISTENT); }

Target:
public void afterClass() { if (_store != null) { _store.close(); } _gSetupTool.deleteCluster(CLUSTER_NAME); }
Source:
public void testDeserializeWithParamsAndLinks() throws Exception { String content = IOUtils.toString(resource("auditevents/auditEventWithParamAndLink.json")); final AuditEvent deserializedObject = json.readValue(content, AuditEvent.class); assertThat(deserializedObject.getParams(), is(not(Collections.emptyMap()))); assertThat(deserializedObject.getLinks(), is(not(Collections.emptyMap()))); }

Target:
public void testDeserializeWithParamsAndLinks() throws Exception { final AuditEvent deserializedObject = readObjectFromResource("/auditevents/auditEventWithParamAndLink.json", AuditEvent.class); assertThat(deserializedObject.getParams(), hasEntry("KEY", "VALUE")); assertThat(deserializedObject.getLinks(), hasEntry("LINK_KEY", "LINK_VALUE")); }
Source:
public void testShutdownHookInvokesShutdownHookCallback() { doNothing().when(mockShutdownHookCallback).run(); clusterBasedProcessorLifecycleListener.beforeStart(); clusterBasedProcessorLifecycleListener.getShutdownHookThread().run(); clusterBasedProcessorLifecycleListener.afterStop(); Mockito.verify(mockShutdownHookCallback).run(); }

Target:
public void testShutdownHookInvokesShutdownHookCallback() { doAnswer(invocation -> { clusterBasedProcessorLifecycleListener.afterStop(); return null; }).when(mockShutdownHookCallback).run(); clusterBasedProcessorLifecycleListener.beforeStart(); clusterBasedProcessorLifecycleListener.getShutdownHookThread().run(); Mockito.verify(mockShutdownHookCallback).run(); }
Source:
public RecordWriter<byte[],Either<Exception, KVPair>> getRecordWriter(TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException { try { if (outputCommitter == null) getOutputCommitter(taskAttemptContext); assert taskAttemptContext != null && taskAttemptContext.getConfiguration() != null:"configuration passed in is null"; DataSetWriterBuilder tableWriter =TableWriterUtils.deserializeTableWriter(taskAttemptContext.getConfiguration()); TxnView childTxn = outputCommitter.getChildTransaction(taskAttemptContext.getTaskAttemptID()); if (childTxn == null) throw new IOException("child transaction lookup failed"); tableWriter.txn(childTxn); return new HTableRecordWriter(tableWriter.buildTableWriter(), outputCommitter); } catch (Exception e) { throw new IOException(e); } }

Target:
public RecordWriter<byte[],Either<Exception, KVPair>> getRecordWriter(TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException { try { assert taskAttemptContext != null && taskAttemptContext.getConfiguration() != null:"configuration passed in is null"; if (outputCommitter == null) getOutputCommitter(taskAttemptContext); DataSetWriterBuilder tableWriter =TableWriterUtils.deserializeTableWriter(taskAttemptContext.getConfiguration()); TxnView childTxn = outputCommitter.getChildTransaction(taskAttemptContext.getTaskAttemptID()); if (childTxn == null) throw new IOException("child transaction lookup failed"); tableWriter.txn(childTxn); return new HTableRecordWriter(tableWriter.buildTableWriter(), outputCommitter); } catch (Exception e) { throw new IOException(e); } }
Source:
protected String createSqlStatement() { final Table table = getTable(); final FromItem fromItem = new FromItem(table); final String tableLabel = _queryRewriter.rewriteFromItem(fromItem); if (table.getType() != null && table.getType() == TableType.VIEW) { return "DROP VIEW " + tableLabel; } else { return "DROP TABLE " + tableLabel; } }

Target:
protected String createSqlStatement() { final Table table = getTable(); final FromItem fromItem = new FromItem(table); final String qualifiedTableName = _queryRewriter.rewriteFromItem(fromItem); if (table.getType() != null && table.getType() == TableType.VIEW) { return "DROP VIEW " + qualifiedTableName; } else { return "DROP TABLE " + qualifiedTableName; } }
Source:
public void onActivate(ActivateEvent event, EntityRef entity) { blockFactory = new BlockItemFactory(entityManager); inventoryManager = new InventoryAuthoritySystem(); EntityRef flagTaker = event.getInstigator(); if (!playerTeamMatchesFlagTeam(entity, flagTaker)) { giveFlagToPlayer(entity, flagTaker); attachParticleEmitterToPlayer(flagTaker); } }

Target:
public void onActivate(ActivateEvent event, EntityRef entity) { EntityRef flagTaker = event.getInstigator(); if (!playerTeamMatchesFlagTeam(entity, flagTaker)) { giveFlagToPlayer(entity, flagTaker); } }
Source:
protected Command doRun(Task task, Map<String, String> prefs) throws PackageException { if (!file.exists()) { log.warn("Can't deploy file " + file + ". File is missing."); return null; } ReloadService srv = Framework.getLocalService(ReloadService.class); boolean useFormerReload = Framework.isBooleanPropertyTrue(ReloadService.USE_FORMER_HOT_RELOAD); if (useFormerReload) { return doFormerRun(srv); } if (file.isDirectory()) { return _deployDirectory(file, srv); } return _deployFile(file, srv); }

Target:
protected Command doRun(Task task, Map<String, String> prefs) throws PackageException { if (!file.exists()) { log.warn("Can't deploy file " + file + ". File is missing."); return null; } ReloadService srv = Framework.getLocalService(ReloadService.class); boolean useCompatReload = Framework.isBooleanPropertyTrue(ReloadService.USE_COMPAT_HOT_RELOAD); if (useCompatReload) { return doCompatRun(srv); } if (file.isDirectory()) { return _deployDirectory(file, srv); } else { return _deployFile(file, srv); } }
Source:
private String getCapsFilePath() { String filePath = appiumDriverManager.getCapsPath(); if (new File(filePath).exists()) { Path path = FileSystems.getDefault().getPath(filePath); if (!path.getParent().isAbsolute()) { filePath = path.normalize() .toAbsolutePath().toString(); } return filePath; } else { System.out.println("Capability file not found"); return null; } }

Target:
private String getCapsFilePath() throws FileNotFoundException { String filePath = appiumDriverManager.getCapsPath(); if (new File(filePath).exists()) { Path path = FileSystems.getDefault().getPath(filePath); if (!path.getParent().isAbsolute()) { filePath = path.normalize() .toAbsolutePath().toString(); } return filePath; } else { throw new FileNotFoundException("Capability file not found"); } }
Source:
public <E extends Enum<E>> List<E> validateEnums(Class<E> clz, List<String> names) { ArrayList<E> enumList = new ArrayList<E>(); String reason = localize(Messages.INVALID_ENUM_REASON); String detail = localize(Messages.INVALID_ENUM_DETAIL); for (String name : names) { enumList.add(EnumValidator.validateEnum(reason, detail, clz, name)); } return enumList; }

Target:
public <E extends Enum<E>> List<E> validateEnums(Class<E> clz, List<String> names) { ArrayList<E> enumList = new ArrayList<E>(); for (String name : names) { enumList.add(validateEnum(clz, name)); } return enumList; }
Source:
private boolean onResetPinEntry(String pin) { if (!mDefaultLogic) return false; clearPin(); switch (mCurrentResetStep) { case RESET_STEP_YOUR: if (PinManager.get().isRealPin(pin)) { mCurrentResetStep++; showResetText(); return true; } else { return false; } case RESET_STEP_FIRST: mResettingPin = pin; mCurrentResetStep++; showResetText(); return true; case RESET_STEP_SECOND: if (pin.equals(mResettingPin)) { PinManager.get().setRealPin(pin); mCurrentResetStep++; showResetText(); return true; } else { return false; } case RESET_STEP_DONE: if (PinManager.get().isRealPin(pin)) { mCurrentResetStep++; showResetText(); return true; } else { return false; } case RESET_STEP_SPAM: if (PinManager.get().isRealPin(pin)) { showResetText(); return true; } else { return false; } } return false; }

Target:
private boolean onResetPinEntry(String pin) { if (!mDefaultLogic) { return false; } clearPin(); switch (mCurrentResetStep) { case RESET_STEP_YOUR: if (PinManager.get().isRealPin(pin)) { mCurrentResetStep++; showResetText(); return true; } else { return false; } case RESET_STEP_FIRST: mResettingPin = pin; mCurrentResetStep++; showResetText(); return true; case RESET_STEP_SECOND: if (pin.equals(mResettingPin)) { PinManager.get().setRealPin(pin); mCurrentResetStep++; showResetText(); return true; } else { return false; } case RESET_STEP_DONE: if (PinManager.get().isRealPin(pin)) { mCurrentResetStep++; showResetText(); return true; } else { return false; } case RESET_STEP_SPAM: if (PinManager.get().isRealPin(pin)) { showResetText(); return true; } else { return false; } } return false; }